// Success Page JavaScript for Downloads Domain
// This file handles security, URL parameters, and user data display

// Configuration - UPDATE THIS WITH YOUR ACTUAL MAIN DOMAIN
const MAIN_DOMAIN = "https://myaxisinsurance.online"; // Change to your main domain (e.g., 'https://yoursite.com')
const VERIFICATION_TIMEOUT = 5 * 60 * 1000; // 5 minutes

document.addEventListener("DOMContentLoaded", function () {
    // Security Check - Verify user came from proper verification
    checkVerificationStatus();
    
    // Load customer data from URL parameters
    loadCustomerData();
    
    // Setup navigation links to main domain
    setupCrossDomainLinks();
    
    // Mobile menu toggle
    const menuToggle = document.querySelector(".menu-toggle");
    const navLinks = document.querySelector(".nav-links");

    if (menuToggle && navLinks) {
        menuToggle.addEventListener("click", function () {
            navLinks.classList.toggle("active");
            const icon = menuToggle.querySelector("i");
            if (navLinks.classList.contains("active")) {
                icon.classList.remove("fa-bars");
                icon.classList.add("fa-times");
            } else {
                icon.classList.remove("fa-times");
                icon.classList.add("fa-bars");
            }
        });
    }

    // Close mobile menu when clicking on a link
    const navLinksItems = document.querySelectorAll(".nav-links a");
    navLinksItems.forEach(link => {
        link.addEventListener("click", () => {
            if (navLinks && navLinks.classList.contains("active")) {
                navLinks.classList.remove("active");
                const icon = menuToggle.querySelector("i");
                icon.classList.remove("fa-times");
                icon.classList.add("fa-bars");
            }
        });
    });

    // Back to top button functionality
    const backToTopButton = document.getElementById("back-to-top");
    
    if (backToTopButton) {
        window.addEventListener("scroll", () => {
            if (window.pageYOffset > 300) {
                backToTopButton.classList.add("show");
            } else {
                backToTopButton.classList.remove("show");
            }
        });

        backToTopButton.addEventListener("click", () => {
            window.scrollTo({
                top: 0,
                behavior: "smooth"
            });
        });
    }

    // Download button analytics (optional)
    const downloadLinks = document.querySelectorAll('a[download]');
    downloadLinks.forEach(link => {
        link.addEventListener('click', function() {
            console.log('APK download initiated');
            // You can add analytics tracking here if needed
        });
    });
});

/**
 * Security Check - Ensure user came through proper verification
 */
function checkVerificationStatus() {
    const urlParams = new URLSearchParams(window.location.search);
    const verified = urlParams.get('verified');
    const mobile = urlParams.get('mobile');
    const timestamp = urlParams.get('timestamp');
    
    // Check if all required parameters are present
    if (!verified || verified !== 'true' || !mobile) {
        console.warn('Access denied: Invalid or missing verification parameters');
        redirectToMainSite();
        return;
    }
    
    // Check timestamp if provided (optional security layer)
    if (timestamp) {
        const currentTime = Date.now();
        const verificationTime = parseInt(timestamp);
        
        if (isNaN(verificationTime) || (currentTime - verificationTime) > VERIFICATION_TIMEOUT) {
            console.warn('Access denied: Verification expired');
            alert('Your verification session has expired. Please verify again.');
            redirectToMainSite();
            return;
        }
    }
    
    // Log successful verification
    console.log('Verification check passed for mobile:', mobile);
}

/**
 * Load and display customer data from URL parameters
 */
function loadCustomerData() {
    const urlParams = new URLSearchParams(window.location.search);
    const mobile = urlParams.get('mobile') || '';
    const name = urlParams.get('name') || 'Valued Customer';
    
    // Update customer name in welcome message
    const customerNameElement = document.getElementById('customer-name');
    if (customerNameElement) {
        customerNameElement.textContent = name;
    }
    
    // Store mobile for potential future use
    if (mobile) {
        sessionStorage.setItem('customerMobile', mobile);
    }
    
    // Log customer info (remove in production if needed)
    console.log('Customer loaded:', { name, mobile });
}

/**
 * Setup cross-domain navigation links to main site
 */
function setupCrossDomainLinks() {
    // Get main site links
    const homeLinks = document.querySelectorAll('#homeLink, #returnHome, .main-site-link');
    
    homeLinks.forEach(link => {
        link.href = MAIN_DOMAIN;
    });
    
    // Setup contact link
    const contactLink = document.getElementById('contactLink');
    if (contactLink) {
        contactLink.href = MAIN_DOMAIN + '#contact';
    }
}

/**
 * Redirect user back to main site
 */
function redirectToMainSite() {
    // Add a small delay to show any alert messages
    setTimeout(() => {
        window.location.href = MAIN_DOMAIN;
    }, 1000);
}

/**
 * Show notification message (utility function)
 */
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    // Add styles if not already added
    if (!document.querySelector('#notification-styles')) {
        const styles = document.createElement('style');
        styles.id = 'notification-styles';
        styles.textContent = `
            .notification {
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 16px 20px;
                border-radius: 8px;
                color: white;
                font-weight: 500;
                z-index: 10000;
                min-width: 300px;
                animation: slideInRight 0.3s ease;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            }
            .notification-success { background: #10B981; }
            .notification-error { background: #EF4444; }
            .notification-info { background: #3B82F6; }
            .notification-content {
                display: flex;
                align-items: center;
                gap: 10px;
            }
            @keyframes slideInRight {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
        `;
        document.head.appendChild(styles);
    }
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideInRight 0.3s ease reverse';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 4000);
}
