
document.addEventListener('DOMContentLoaded', () => {
    // Theme Switcher - Single Source of Truth
    window.toggleTheme = () => {
        const current = document.documentElement.getAttribute('data-theme') || localStorage.getItem('theme') || 'light';
        const next = current === 'light' ? 'dark' : 'light';
        document.documentElement.setAttribute('data-theme', next);
        localStorage.setItem('theme', next);
        
        // Update icons if any
        const icon = document.querySelector('#theme-toggle i');
        if (icon) {
            icon.className = next === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
        }
        
        // Update system color scheme
        document.documentElement.style.colorScheme = next;
    };

    window.setLang = (lang) => {
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
        console.log('Setting language to:', lang);
        
        fetch('/set-lang', {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: 'lang=' + encodeURIComponent(lang) + '&_csrf_token=' + encodeURIComponent(csrfToken || '')
        })
        .then(response => {
            if (response.ok) {
                console.log('Language set successfully, reloading...');
                location.reload();
            } else {
                console.error('Failed to set language, status:', response.status);
                // Fallback: try GET if POST fails (though POST is preferred)
                window.location.href = '/language?lang=' + lang;
            }
        })
        .catch(err => {
            console.error('Network error during language switch:', err);
            window.location.href = '/language?lang=' + lang;
        });
    };

    window.toggleMobileMenu = () => {
        const btn = document.getElementById('mobile-menu-btn');
        const drawer = document.getElementById('mobile-nav-drawer');
        if (btn && drawer) {
            btn.classList.toggle('open');
            drawer.classList.toggle('open');
            document.body.style.overflow = drawer.classList.contains('open') ? 'hidden' : '';
        }
    };

    window.closeMobileMenu = () => {
        document.getElementById('mobile-menu-btn')?.classList.remove('open');
        document.getElementById('mobile-nav-drawer')?.classList.remove('open');
        document.body.style.overflow = '';
    };

    // Close drawer on outside click
    document.addEventListener('click', (e) => {
        const drawer = document.getElementById('mobile-nav-drawer');
        const btn = document.getElementById('mobile-menu-btn');
        if (drawer?.classList.contains('open') && !drawer.contains(e.target) && !btn.contains(e.target)) {
            closeMobileMenu();
        }
    });

    // AJAX Voting
    document.querySelectorAll('.vote-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const postId = btn.dataset.post;
            const commentId = btn.dataset.comment;
            const type = btn.dataset.type;
            const csrf = document.querySelector('meta[name="csrf-token"]').content;

            try {
                const response = await fetch('/post/vote', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: `post_id=${postId || ''}&comment_id=${commentId || ''}&type=${type}&_csrf_token=${csrf}`
                });

                const data = await response.json();
                if (data.score !== undefined) {
                    const scoreEl = btn.parentElement.querySelector('.score-count');
                    scoreEl.textContent = data.score;
                    
                    btn.parentElement.querySelectorAll('.vote-btn').forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                }
            } catch (error) {
                console.error('Vote failed', error);
            }
        });
    });

    // Global Keyboard Shortcuts (PC Only)
    let combo = [];
    document.addEventListener('keydown', (e) => {
        const active = document.activeElement;
        // Don't trigger shortcuts when typing in an input
        if (['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName) || active.isContentEditable) {
            if (e.key === 'Escape') active.blur();
            return;
        }

        const key = e.key.toLowerCase();
        
        // Single Keys
        if (key === '/') {
            const searchInput = document.querySelector('input[name="q"]');
            if (searchInput) {
                e.preventDefault();
                searchInput.focus();
                searchInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }

        if (key === 'c') window.location.href = '/post/create';
        if (key === 'n') window.location.href = '/notifications';
        if (key === 'm') window.location.href = '/messages';
        if (key === 'p') window.location.href = '/u/current';
        
        // Combos (G + Key)
        if (key === 'g') {
            combo.push('g');
            setTimeout(() => combo = [], 1000); // Clear combo after 1s
        } else if (combo.includes('g')) {
            if (key === 'h') window.location.href = '/';
            combo = [];
        } else {
            combo = [];
        }
    });

    // Premium User Hover Cards (PC Only)
    const hoverCard = document.getElementById('user-hover-card');
    let hoverTimeout;

    if (hoverCard) {
        document.addEventListener('mouseover', async (e) => {
            const link = e.target.closest('a[href^="/u/"]');
            if (!link || window.innerWidth < 1024) return;

            const url = link.getAttribute('href');
            const username = url.split('/u/')[1];
            if (!username || username === 'current') return;

            clearTimeout(hoverTimeout);
            hoverTimeout = setTimeout(async () => {
                try {
                    const res = await fetch(`/api/users/${username}`);
                    const user = await res.json();
                    if (user.error) return;

                    document.getElementById('hover-card-username').textContent = user.username;
                    document.getElementById('hover-card-avatar').src = user.avatar_url;
                    document.getElementById('hover-card-reputation').textContent = user.reputation || 0;
                    document.getElementById('hover-card-joined').textContent = user.joined_date || 'N/A';
                    document.getElementById('hover-card-bio').textContent = user.bio || 'Community member...';
                    
                    const cover = document.getElementById('hover-card-cover');
                    if (user.cover_url) {
                        cover.style.backgroundImage = `url(${user.cover_url})`;
                    } else {
                        cover.style.background = 'var(--primary)';
                        cover.style.backgroundImage = 'none';
                    }

                    const rect = link.getBoundingClientRect();
                    hoverCard.style.top = `${window.scrollY + rect.top - 240}px`; // Better positioning
                    hoverCard.style.left = `${window.scrollX + rect.left}px`;
                    hoverCard.style.display = 'block';
                    setTimeout(() => { hoverCard.style.opacity = '1'; }, 10);
                    hoverCard.style.pointerEvents = 'auto';
                } catch (err) {}
            }, 500);
        });

        document.addEventListener('mouseout', (e) => {
            if (!e.target.closest('a[href^="/u/"]') && !e.target.closest('#user-hover-card')) {
                clearTimeout(hoverTimeout);
                hoverCard.style.opacity = '0';
                setTimeout(() => {
                    if (hoverCard.style.opacity === '0') hoverCard.style.display = 'none';
                }, 200);
            }
        });
    }

    const scrollBtn = document.getElementById('scroll-top');
    if (scrollBtn) {
        window.addEventListener('scroll', () => {
            if (window.scrollY > 500) {
                scrollBtn.style.display = 'block';
            } else {
                scrollBtn.style.display = 'none';
            }
        });
        scrollBtn.addEventListener('click', () => {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
    }

    // Scroll Progress
    const progress = document.getElementById('scroll-progress');
    if (progress) {
        window.addEventListener('scroll', () => {
            const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
            const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
            const scrolled = (winScroll / height) * 100;
            progress.style.width = scrolled + "%";
        });
    }

});
