const pages = ['home','problem','why','how','roi','pricing','who','trust','roadmap','faq','signin','apply','forgot'];


function openPage(pageId) {
    if (!pages.includes(pageId)) {
        console.warn(`Attempted to navigate to a non-existent page: ${pageId}`);
        return; // Do not proceed if the page is not in the allowed list
    }

    // Hide all pages
    document.querySelectorAll('.page').forEach(p => {
        p.classList.add('hidden');
    });

    // Show the active page
    const activePage = document.getElementById('page-' + pageId);
    if (activePage) {
        activePage.classList.remove('hidden');
    } else {
        // If no specific page content, default to home
        document.getElementById('page-home').classList.remove('hidden');
    }

    // Update active link styling
    document.querySelectorAll('.navlink').forEach(link => {
        if (link.dataset.page === pageId) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });

    // Smooth scroll to top
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

document.addEventListener('DOMContentLoaded', () => {
    const navLinksContainer = document.getElementById('nav-links');
    const mobileMenuContainer = document.getElementById('mobile-menu');
    const footerLinksContainer = document.getElementById('footer-links');
    const menuButton = document.getElementById('menu-button');

    // Generate navigation links
    let navHTML = '';
    pages.forEach(page => {
        let link = `#${page}`;
        if (page === 'faq' || page === 'trust') {
            link = `#${page}`;
        }
        navHTML += `<a href="${link}" class="navlink px-3 py-2 rounded-full hover:bg-gray-100" data-page="${page}">${page.charAt(0).toUpperCase() + page.slice(1)}</a>`;
    });
    navLinksContainer.innerHTML = navHTML;
    mobileMenuContainer.innerHTML = navHTML.replace(/class="/g, 'class="block w-full text-left ');

    // Generate footer links
    if (footerLinksContainer) {
        let footerHTML = '';
        const footerPages = ['apply', 'signin', 'trust', 'faq'];
        footerPages.forEach((page, index) => {
            let link = `#${page}`;
            if (page === 'faq' || page === 'trust') {
                link = `#${page}`;
            }
            footerHTML += `<a href="${link}" class="underline navlink" data-page="${page}">${page.charAt(0).toUpperCase() + page.slice(1)}</a>`;
            if (index < footerPages.length - 1) {
                footerHTML += `<span class="opacity-50">·</span>`;
            }
        });
        footerLinksContainer.innerHTML = footerHTML;
    }

    // Toggle mobile menu
    menuButton.addEventListener('click', () => {
        mobileMenuContainer.classList.toggle('hidden');
    });

    if (document.getElementById('page-home')) {
        // Handle navigation clicks for SPA
        document.querySelectorAll('.navlink').forEach(link => {
            link.addEventListener('click', (e) => {
                const page = link.dataset.page;
                e.preventDefault();
                openPage(link.dataset.page);
            });
        });

        // Open page based on hash or default to 'home'
        const initialPage = window.location.hash.substring(1) || 'home';
        openPage(initialPage);

        // Tab functionality for 'Why FinMox' page
        const whyTabs = document.querySelectorAll('.why-tab');
        const whyContents = document.querySelectorAll('.why-content');

        whyTabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabId = tab.dataset.tab;

                // Update tab styles
                whyTabs.forEach(t => {
                    if (t.dataset.tab === tabId) {
                        t.classList.add('bg-white', 'text-gray-900');
                        t.classList.remove('bg-gray-200', 'text-gray-500');
                    } else {
                        t.classList.remove('bg-white', 'text-gray-900');
                        t.classList.add('bg-gray-200', 'text-gray-500');
                    }
                });

                // Update content visibility
                whyContents.forEach(c => {
                    if (c.dataset.content === tabId) {
                        c.classList.remove('hidden');
                    } else {
                        c.classList.add('hidden');
                    }
                });
            });
        });
    }

    const applyNowBtn = document.getElementById('applyNowBtn');
    if (applyNowBtn) {
        applyNowBtn.addEventListener('click', applyForBeta);
    }
});

function signIn(event) {
    event.preventDefault();
    const emailEl = document.getElementById('signinEmail');
    const passwordEl = document.getElementById('signinPassword');
    const msgEl = document.getElementById('signinMsg');

    if (!emailEl || !passwordEl || !msgEl) {
        return;
    }

    const email = emailEl.value.trim();
    const password = passwordEl.value.trim();

    msgEl.classList.add('hidden');
    msgEl.textContent = '';

    if (!email || !password) {
        msgEl.textContent = 'Please enter both email and password.';
        msgEl.classList.remove('hidden');
        return;
    }

    fetch('login.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'same-origin',
        body: JSON.stringify({ email, password }),
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = 'dashboard.php';
        } else {
            msgEl.textContent = data.message || 'An unknown error occurred.';
            msgEl.classList.remove('hidden');
        }
    })
    .catch(error => {
        msgEl.textContent = 'A network error occurred. Please try again.';
        msgEl.classList.remove('hidden');
    });
}

function applyForBeta(event) {
    event.preventDefault();

    const form = document.getElementById('applyForm');
    const msgEl = document.getElementById('applyMsg');

    if (!form || !msgEl) {
        return;
    }

    const data = {
        companyName: document.getElementById('companyName').value,
        yourName: document.getElementById('yourName').value,
        workEmail: document.getElementById('workEmail').value,
        role: document.getElementById('role').value,
        employees: document.getElementById('employees').value,
        rolesPerMonth: document.getElementById('rolesPerMonth').value,
        candidatesPerRole: document.getElementById('candidatesPerRole').value,
        ats: document.getElementById('ats').value,
        scheduling: document.getElementById('scheduling').value,
        painPoints: document.getElementById('painPoints').value,
        successMetrics: document.getElementById('successMetrics').value,
        hiringFocus: document.getElementById('hiringFocus').value,
    };

    msgEl.classList.add('hidden');
    msgEl.textContent = '';

    // Basic validation
    if (!data.workEmail || !data.companyName || !data.yourName) {
        msgEl.textContent = 'Please fill out all required fields.';
        msgEl.classList.remove('hidden');
        return;
    }

    fetch('apply.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'same-origin',
        body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            msgEl.textContent = 'Thank you for your application! We will be in touch shortly.';
            msgEl.classList.remove('hidden');
            msgEl.classList.remove('text-red-600');
            msgEl.classList.add('text-green-600');
            form.reset();
        } else {
            msgEl.textContent = result.message || 'An unknown error occurred.';
            msgEl.classList.remove('hidden');
        }
    })
    .catch(error => {
        msgEl.textContent = 'A network error occurred. Please try again.';
        msgEl.classList.remove('hidden');
    });
}