// ==================== AUTH STATE ====================
let isLoggedIn = localStorage.getItem('authink_logged_in') === 'true';
let currentPage = 'home';
let docsScrollSpyInstance = null;

function handleLogin() {
    isLoggedIn = true;
    localStorage.setItem('authink_logged_in', 'true');
    showToast('Logged in successfully!', 'success');
    setTimeout(() => navigate('dashboard'), 600);
}

function handleLogout() {
    isLoggedIn = false;
    localStorage.setItem('authink_logged_in', 'false');
    showToast('Logged out successfully', 'info');
    setTimeout(() => navigate('home'), 400);
}

function updateAuthUI() {
    const authButtons = document.getElementById('auth-buttons');
    const mobileAuthItems = document.getElementById('mobile-auth-items');

    if (isLoggedIn) {
        authButtons.innerHTML = `
            <span class="text-sm text-gray-400 hidden sm:inline">demo@authink.app</span>
            <button onclick="handleLogout()" class="btn-outline !py-2 !px-4 !text-sm cursor-pointer">Log out</button>
        `;
        mobileAuthItems.innerHTML = `
            <div class="mobile-menu-item"><a onclick="navigate('dashboard');toggleMobileMenu()" class="block px-4 py-3.5 text-lg font-medium rounded-xl hover:bg-white/5 transition-all cursor-pointer text-violet-300">Dashboard</a></div>
            <div class="mobile-menu-item"><a onclick="handleLogout();toggleMobileMenu()" class="block px-4 py-3.5 text-lg font-medium rounded-xl hover:bg-white/5 transition-all cursor-pointer text-red-400">Log out</a></div>
        `;
    } else {
        authButtons.innerHTML = `
            <button onclick="navigate('login')" class="text-sm font-medium text-gray-400 hover:text-white transition-colors px-3 py-2 cursor-pointer">Log in</button>
            <button onclick="navigate('register')" class="btn-primary text-sm !py-2 !px-5 cursor-pointer">Start Free</button>
        `;
        mobileAuthItems.innerHTML = `
            <div class="mobile-menu-item"><a onclick="navigate('login');toggleMobileMenu()" class="block px-4 py-3.5 text-lg font-medium rounded-xl hover:bg-white/5 transition-all cursor-pointer text-gray-300">Log in</a></div>
            <div class="mobile-menu-item"><a onclick="navigate('register');toggleMobileMenu()" class="block px-4 py-3.5 text-lg font-medium rounded-xl bg-white text-black text-center cursor-pointer mt-2">Start Free</a></div>
        `;
    }
    
    // Update nav links
    const navLinks = document.getElementById('nav-links');
    if (navLinks) {
        navLinks.innerHTML = `
            <a onclick="navigate('home')" class="nav-link px-3.5 py-2 text-sm ${currentPage === 'home' ? 'text-white font-semibold' : 'text-gray-400'} hover:text-white rounded-lg hover:bg-white/5 transition-all cursor-pointer" data-nav="home">Home</a>
            <a onclick="navigate('pricing')" class="nav-link px-3.5 py-2 text-sm ${currentPage === 'pricing' ? 'text-white font-semibold' : 'text-gray-400'} hover:text-white rounded-lg hover:bg-white/5 transition-all cursor-pointer" data-nav="pricing">Pricing</a>
            <a onclick="navigate('docs')" class="nav-link px-3.5 py-2 text-sm ${currentPage === 'docs' ? 'text-white font-semibold' : 'text-gray-400'} hover:text-white rounded-lg hover:bg-white/5 transition-all cursor-pointer" data-nav="docs">Docs</a>
            <a onclick="navigate('status')" class="nav-link px-3.5 py-2 text-sm ${currentPage === 'status' ? 'text-white font-semibold' : 'text-gray-400'} hover:text-white rounded-lg hover:bg-white/5 transition-all cursor-pointer" data-nav="status">Status</a>
        `;
        
        // Add dashboard link if logged in
        if (isLoggedIn) {
            navLinks.insertAdjacentHTML('afterbegin', `
                <a onclick="navigate('dashboard')" class="nav-link px-3.5 py-2 text-sm ${currentPage === 'dashboard' ? 'text-white font-semibold' : 'text-gray-400'} hover:text-white rounded-lg hover:bg-white/5 transition-all cursor-pointer" data-nav="dashboard">Dashboard</a>
            `);
        }
    }
}

// ==================== ROUTER & PAGE LOADER ====================
async function navigate(page) {
    if (page === 'dashboard' && !isLoggedIn) {
        navigate('login');
        return;
    }

    if (currentPage === 'docs' && page !== 'docs' && docsScrollSpyInstance) {
        docsScrollSpyInstance.disconnect();
        docsScrollSpyInstance = null;
    }

    // Show loading state or hide current
    const app = document.getElementById('app');
    app.style.opacity = '0';
    app.style.transform = 'translateY(10px)';
    
    try {
        let htmlContent;
        
        if (page === currentPage && document.getElementById(`page-${page}`)) {
            // Page already loaded, just show it
            htmlContent = null;
        } else {
            // Fetch page content
            const response = await fetch(`./pages/${page}.html`);
            if (!response.ok) throw new Error('Page not found');
            htmlContent = await response.text();
        }
        
        // Update DOM
        if (htmlContent) {
            app.innerHTML = htmlContent;
        }
        
        // Show page
        setTimeout(() => {
            const target = document.getElementById(`page-${page}`);
            if (target) {
                target.classList.add('active');
                target.style.animation = 'pageIn 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards';
            }
            
            app.style.opacity = '1';
            app.style.transform = 'translateY(0)';
            app.style.transition = 'all 0.3s ease';
            
            // Handle footer and blobs visibility
            const footer = document.getElementById('footer');
            const blobs = document.querySelectorAll('.blob');
            if (['dashboard', 'login', 'register'].includes(page)) {
                footer.style.display = 'none';
                blobs.forEach(b => b.style.opacity = page === 'dashboard' ? '0.15' : '0.3');
            } else {
                footer.style.display = 'block';
                blobs.forEach(b => b.style.opacity = '0.5');
            }
            
            window.scrollTo({ top: 0, behavior: 'smooth' });
            updateAuthUI();
            initScrollReveal();
            
            if (page === 'docs') {
                setTimeout(initDocsScrollSpy, 600);
            }
            
            currentPage = page;
            window.location.hash = '/' + (page === 'home' ? '' : page);
        }, 100);
        
    } catch (error) {
        console.error('Failed to load page:', error);
        app.innerHTML = '<div class="pt-32 text-center"><h1 class="text-4xl font-bold text-white mb-4">Page Not Found</h1><p class="text-gray-400">The page you\'re looking for doesn\'t exist.</p><button onclick="navigate(\'home\')" class="btn-primary mt-6 cursor-pointer">Go Home</button></div>';
        app.style.opacity = '1';
        app.style.transform = 'translateY(0)';
    }
}

window.addEventListener('hashchange', () => {
    const hash = window.location.hash.replace('#/', '') || 'home';
    if (hash !== currentPage) navigate(hash);
});

window.addEventListener('DOMContentLoaded', () => {
    const hash = window.location.hash.replace('#/', '') || 'home';
    if (isLoggedIn && (hash === 'home' || hash === '')) {
        navigate('dashboard');
    } else {
        navigate(hash);
    }
});

// ==================== MOBILE MENU ====================
let mobileMenuOpen = false;

function toggleMobileMenu() {
    const menu = document.getElementById('mobileMenu');
    const overlay = document.getElementById('mobileOverlay');
    mobileMenuOpen = !mobileMenuOpen;

    if (mobileMenuOpen) {
        menu.classList.add('open');
        menu.style.pointerEvents = 'auto';
        overlay.style.opacity = '1';
        overlay.style.pointerEvents = 'auto';
        document.body.style.overflow = 'hidden';
    } else {
        menu.classList.remove('open');
        overlay.style.opacity = '0';
        overlay.style.pointerEvents = 'none';
        document.body.style.overflow = '';
        setTimeout(() => { menu.style.pointerEvents = 'none'; }, 500);
    }
}

// ==================== DOCS SIDEBAR TOGGLE (MOBILE) ====================
function toggleDocsSidebar() {
    const sidebar = document.getElementById('docsSidebarContainer');
    const overlay = document.getElementById('docsSidebarOverlay');
    
    if (sidebar && overlay) {
        sidebar.classList.toggle('show');
        overlay.classList.toggle('show');
        
        if (sidebar.classList.contains('show')) {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = '';
        }
    }
}

// ==================== TAB SWITCHING ====================
function switchTab(btn, tabId) {
    const parent = btn.parentElement;
    parent.querySelectorAll('.docs-tab').forEach(t => t.classList.remove('active'));
    btn.classList.add('active');
    
    const container = parent.parentElement;
    container.querySelectorAll('.docs-code-block').forEach(block => {
        block.style.display = 'none';
    });
    
    const targetBlock = document.getElementById(tabId);
    if (targetBlock) {
        targetBlock.style.display = 'block';
    }
}

// ==================== DOCS COPY CODE ====================
function copyDocsCode(btn) {
    const codeBlock = btn.closest('.docs-code-block');
    const codeEl = codeBlock.querySelector('.docs-code-body code');
    const code = codeEl.textContent;
    
    navigator.clipboard.writeText(code).then(() => {
        btn.textContent = 'Copied!';
        btn.classList.add('copied');
        
        setTimeout(() => {
            btn.textContent = 'Copy';
            btn.classList.remove('copied');
        }, 2000);
    }).catch(err => {
        showToast('Failed to copy code', 'error');
    });
}

// ==================== DOCS SCROLL SPY ====================
function initDocsScrollSpy() {
    const sections = document.querySelectorAll('.scroll-spy-section');
    const navLinks = document.querySelectorAll('.docs-nav-link');
    const tocLinks = document.querySelectorAll('.docs-toc-link');
    const progressBar = document.getElementById('sidebarProgress');
    const sidebarContainer = document.getElementById('docsSidebarContainer');
    
    if (!sections.length || !navLinks.length || !progressBar) return;

    if (docsScrollSpyInstance) {
        docsScrollSpyInstance.disconnect();
    }

    const config = {
        root: null,
        rootMargin: '-10% 0px -70% 0px',
        threshold: [0, 0.1, 0.5, 1]
    };

    let currentActiveId = null;
    let ticking = false;

    const handleIntersect = (entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const id = entry.target.getAttribute('id');
                if (id !== currentActiveId) {
                    currentActiveId = id;
                    updateActiveLink(id);
                }
            }
        });
        updateProgressBar();
    };

    docsScrollSpyInstance = new IntersectionObserver(handleIntersect, config);

    sections.forEach(section => {
        docsScrollSpyInstance.observe(section);
    });

    let scrollTimeout;
    window.addEventListener('scroll', () => {
        if (!ticking) {
            requestAnimationFrame(() => {
                updateProgressBar();
                
                let found = false;
                sections.forEach(section => {
                    const rect = section.getBoundingClientRect();
                    if (rect.top <= 150 && rect.bottom > 200) {
                        const id = section.getAttribute('id');
                        if (id !== currentActiveId) {
                            currentActiveId = id;
                            updateActiveLink(id);
                        }
                        found = true;
                    }
                });
                
                ticking = false;
            });
            ticking = true;
        }
        
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(() => {
            ticking = false;
        }, 100);
    }, { passive: true });

    function updateActiveLink(sectionId) {
        navLinks.forEach(link => link.classList.remove('active'));
        tocLinks.forEach(link => link.classList.remove('active'));

        const activeLink = document.querySelector(`.docs-nav-link[data-section="${sectionId}"]`);
        const activeTocLink = document.querySelector(`.docs-toc-link[href="#${sectionId}"]`);
        
        if (activeLink) {
            activeLink.classList.add('active');
            
            const linkRect = activeLink.getBoundingClientRect();
            const sidebarRect = sidebarContainer.getBoundingClientRect();
            
            const offsetTop = linkRect.top - sidebarRect.top;
            const offsetBottom = linkRect.bottom - sidebarRect.bottom;
            
            if (offsetTop < 20) {
                sidebarContainer.scrollBy({ top: offsetTop - 40, behavior: 'smooth' });
            } else if (offsetBottom > 0) {
                sidebarContainer.scrollBy({ top: offsetBottom + 40, behavior: 'smooth' });
            }
        }
        
        if (activeTocLink) {
            activeTocLink.classList.add('active');
        }
    }

    function updateProgressBar() {
        const contentArea = document.getElementById('docsContentArea');
        if (!contentArea || !sidebarContainer) return;

        const contentRect = contentArea.getBoundingClientRect();
        const viewportHeight = window.innerHeight;
        
        let scrolled = -contentRect.top;
        const contentHeight = contentRect.height;
        const totalScrollable = contentHeight - viewportHeight;
        
        let progressPercent = Math.min(100, Math.max(0, (scrolled / totalScrollable) * 100));
        
        progressBar.style.top = `${progressPercent}%`;
        progressBar.style.height = '20px';
        
        if (progressPercent >= 98) {
            progressBar.style.top = '100%';
            progressBar.style.height = '2px';
        }
    }

    setTimeout(() => {
        updateProgressBar();
        
        const hash = window.location.hash.replace('#', '');
        if (hash && document.querySelector(`[id="${hash}"]`)) {
            updateActiveLink(hash);
        } else {
            const firstSection = sections[0];
            if (firstSection) {
                updateActiveLink(firstSection.getAttribute('id'));
            }
        }
    }, 100);
}

// ==================== SCROLL REVEAL ====================
function initScrollReveal() {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('revealed');
            }
        });
    }, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });

    document.querySelectorAll('.scroll-reveal').forEach(el => {
        if (!el.classList.contains('revealed')) observer.observe(el);
    });
}

// ==================== BUTTON RIPPLE ====================
document.addEventListener('click', (e) => {
    const btn = e.target.closest('.btn-primary');
    if (!btn) return;
    const ripple = document.createElement('span');
    ripple.classList.add('ripple');
    const rect = btn.getBoundingClientRect();
    const size = Math.max(rect.width, rect.height);
    ripple.style.width = ripple.style.height = size + 'px';
    ripple.style.left = (e.clientX - rect.left - size / 2) + 'px';
    ripple.style.top = (e.clientY - rect.top - size / 2) + 'px';
    btn.appendChild(ripple);
    setTimeout(() => ripple.remove(), 600);
});

// ==================== TOAST ====================
function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    let borderColor = '#10b981';
    if (type === 'info') borderColor = '#3b82f6';
    else if (type === 'error') borderColor = '#ef4444';
    toast.style.borderLeft = `3px solid ${borderColor}`;
    toast.classList.add('show');
    setTimeout(() => toast.classList.remove('show'), 3000);
}

// ==================== NAVBAR SCROLL EFFECT ====================
window.addEventListener('scroll', () => {
    const navbar = document.getElementById('navbar');
    if (navbar) {
        if (window.scrollY > 100) {
            navbar.style.boxShadow = '0 1px 20px rgba(0,0,0,0.5)';
            navbar.style.borderBottomColor = 'rgba(255,255,255,0.1)';
        } else {
            navbar.style.boxShadow = 'none';
            navbar.style.borderBottomColor = 'rgba(255,255,255,0.06)';
        }
    }
});

// ==================== DOCS SCROLL WITH ACTIVE STATE UPDATE ====================
function scrollToDoc(id) {
    const el = document.getElementById(id);
    if (el) {
        el.scrollIntoView({ behavior: 'smooth', block: 'start' });
        
        document.querySelectorAll('.docs-nav-link').forEach(l => l.classList.remove('active'));
        document.querySelectorAll('.docs-toc-link').forEach(l => l.classList.remove('active'));
        
        const clickedLink = document.querySelector(`.docs-nav-link[data-section="${id}"]`);
        const clickedTocLink = document.querySelector(`.docs-toc-link[href="#${id}"]`);
        
        if (clickedLink) clickedLink.classList.add('active');
        if (clickedTocLink) clickedTocLink.classList.add('active');
        
        const sidebar = document.getElementById('docsSidebarContainer');
        if (sidebar && sidebar.classList.contains('show')) {
            toggleDocsSidebar();
        }
    }
}

// ==================== INIT ====================
updateAuthUI();
