/**
 * KotoTv Global Core Script
 * Handles Authentication, Search Dropdown, Navigation, Mobile Drawer & Watchlist
 */

// Auth token auto-sync from meta tags
(function() {
    const metaToken = document.querySelector('meta[name="auth-token"]')?.getAttribute('content');
    const metaUser = document.querySelector('meta[name="auth-user"]')?.getAttribute('content');
    if (metaToken && metaUser) {
        try {
            localStorage.setItem('kototv_token', metaToken);
            localStorage.setItem('kototv_user', metaUser);
        } catch(e) {}
    }
})();

// Check User Token in LocalStorage
function checkUserAuth() {
    const token = localStorage.getItem('kototv_token') || localStorage.getItem('hiasian_token');
    const user = localStorage.getItem('kototv_user') || localStorage.getItem('hiasian_user');
    const loggedInView = document.getElementById('user-logged-in-view');
    const btnOpenLogin = document.getElementById('btn-open-login');
    const nameEl = document.getElementById('user-display-name');

    if (token && user) {
        try {
            const parsed = JSON.parse(user);
            if (nameEl) nameEl.textContent = parsed.display_name || ('User #' + parsed.id);
            if (loggedInView) loggedInView.style.display = 'flex';
            if (btnOpenLogin) btnOpenLogin.style.display = 'none';
        } catch(e) {}
    } else {
        if (loggedInView) loggedInView.style.display = 'none';
        if (btnOpenLogin) btnOpenLogin.style.display = 'flex';
    }
}

        // Live Search Dropdown
        const searchInput = document.getElementById('header-search-input');
        const searchDropdown = document.getElementById('search-dropdown');
        let searchTimeout = null;

        if (searchInput) {
            searchInput.addEventListener('input', function() {
                const q = this.value.trim();
                clearTimeout(searchTimeout);
                if (q.length < 2) {
                    searchDropdown.style.display = 'none';
                    searchDropdown.innerHTML = '';
                    return;
                }

                searchTimeout = setTimeout(() => {
                    fetch('/api/ajax/search?q=' + encodeURIComponent(q))
                        .then(r => r.json())
                        .then(data => {
                            if (!data.results || data.results.length === 0) {
                                searchDropdown.innerHTML = '<div style="padding:14px;color:var(--muted);font-size:13px;text-align:center">No anime found</div>';
                                searchDropdown.style.display = 'block';
                                return;
                            }

                            let html = '';
                            data.results.forEach(item => {
                                html += `
                                    <a href="${item.url}" class="search-item">
                                        <img src="${item.poster || 'https://placehold.co/42x56/121722/35d5bf?text=Anime'}" class="search-poster" alt="${item.title}" referrerpolicy="no-referrer">
                                        <div class="search-meta">
                                            <h4>${item.title}</h4>
                                            <div class="search-sub-info">
                                                <span>${item.format}</span>
                                                ${item.episodes ? `<span>• ${item.episodes} EPS</span>` : ''}
                                                ${item.score ? `<span style="color:#eab308">• ⭐ ${item.score}</span>` : ''}
                                            </div>
                                        </div>
                                    </a>
                                `;
                            });
                            searchDropdown.innerHTML = html;
                            searchDropdown.style.display = 'block';
                        })
                        .catch(() => {});
                }, 200);
            });

            document.addEventListener('click', function(e) {
                if (!searchInput.contains(e.target) && !searchDropdown.contains(e.target)) {
                    searchDropdown.style.display = 'none';
                }
            });
        }

        // Auth Modal Controls
        function openAuthModal(tab = 'login') {
            const modal = document.getElementById('authModal');
            if (modal) modal.style.display = 'flex';
            switchAuthTab(tab);
        }

        function closeAuthModal() {
            const modal = document.getElementById('authModal');
            if (modal) modal.style.display = 'none';
        }

        function switchAuthTab(tab) {
            const tabLogin = document.getElementById('tab-login');
            const tabReg = document.getElementById('tab-register');
            const formLogin = document.getElementById('form-login');
            const formReg = document.getElementById('form-register');

            if (tab === 'login') {
                if (tabLogin) tabLogin.classList.add('active');
                if (tabReg) tabReg.classList.remove('active');
                if (formLogin) formLogin.style.display = 'block';
                if (formReg) formReg.style.display = 'none';
            } else {
                if (tabReg) tabReg.classList.add('active');
                if (tabLogin) tabLogin.classList.remove('active');
                if (formLogin) formLogin.style.display = 'none';
                if (formReg) formReg.style.display = 'block';
            }
        }

        function submitLogin(e) {
            e.preventDefault();
            const identifier = document.getElementById('login-identifier').value.trim();
            const password = document.getElementById('login-password').value;
            const errBox = document.getElementById('login-error');
            errBox.style.display = 'none';

            fetch('/api/v1/auth/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                body: JSON.stringify({ login: identifier, password: password })
            })
            .then(async res => {
                const data = await res.json();
                if (!res.ok) throw new Error(data.message || 'Login failed');
                localStorage.setItem('kototv_token', data.token);
                localStorage.setItem('kototv_user', JSON.stringify(data.user));
                closeAuthModal();
                checkUserAuth();
                window.location.reload();
            })
            .catch(err => {
                errBox.textContent = err.message;
                errBox.style.display = 'block';
            });
        }

        function submitRegister(e) {
            e.preventDefault();
            const name = document.getElementById('reg-name').value.trim();
            const email = document.getElementById('reg-email').value.trim();
            const password = document.getElementById('reg-password').value;
            const errBox = document.getElementById('reg-error');
            errBox.style.display = 'none';

            fetch('/api/v1/auth/register', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                body: JSON.stringify({ display_name: name, email: email || null, password: password })
            })
            .then(async res => {
                const data = await res.json();
                if (!res.ok) throw new Error(data.message || 'Registration failed');
                localStorage.setItem('kototv_token', data.token);
                localStorage.setItem('kototv_user', JSON.stringify(data.user));
                closeAuthModal();
                checkUserAuth();
                window.location.reload();
            })
            .catch(err => {
                errBox.textContent = err.message;
                errBox.style.display = 'block';
            });
        }

        function handleLogout() {
            const token = localStorage.getItem('kototv_token') || localStorage.getItem('hiasian_token');
            if (token) {
                fetch('/api/v1/auth/logout', {
                    method: 'POST',
                    headers: { 'Authorization': 'Bearer ' + token, 'Accept': 'application/json' }
                }).catch(() => {});
            }
            localStorage.removeItem('kototv_token');
            localStorage.removeItem('kototv_user');
            localStorage.removeItem('hiasian_token');
            localStorage.removeItem('hiasian_user');
            checkUserAuth();
            window.location.reload();
        }

        // Mobile Drawer & Search Toggle
        const mobileMenuToggle = document.getElementById('mobileMenuToggle');
        const mobileMenuClose = document.getElementById('mobileMenuClose');
        const mobileNavBackdrop = document.getElementById('mobileNavBackdrop');
        const mobileNavDrawer = document.getElementById('mobileNavDrawer');
        const mobileSearchToggle = document.getElementById('mobileSearchToggle');
        const mobileSearchBar = document.getElementById('mobileSearchBar');

        if (mobileMenuToggle && mobileNavDrawer && mobileNavBackdrop) {
            function openDrawer() {
                mobileNavDrawer.classList.add('active');
                mobileNavBackdrop.classList.add('active');
                document.body.style.overflow = 'hidden';
            }
            function closeDrawer() {
                mobileNavDrawer.classList.remove('active');
                mobileNavBackdrop.classList.remove('active');
                document.body.style.overflow = '';
            }
            mobileMenuToggle.addEventListener('click', openDrawer);
            if (mobileMenuClose) mobileMenuClose.addEventListener('click', closeDrawer);
            mobileNavBackdrop.addEventListener('click', closeDrawer);
        }

        if (mobileSearchToggle && mobileSearchBar) {
            mobileSearchToggle.addEventListener('click', function(e) {
                e.stopPropagation();
                mobileSearchBar.classList.toggle('active');
                if (mobileSearchBar.classList.contains('active')) {
                    const input = document.getElementById('mobile-search-input');
                    if (input) input.focus();
                }
            });
            document.addEventListener('click', function(e) {
                if (!mobileSearchBar.contains(e.target) && !mobileSearchToggle.contains(e.target)) {
                    mobileSearchBar.classList.remove('active');
                }
            });
        }

        document.addEventListener('DOMContentLoaded', checkUserAuth);

// Global Watchlist Removal with Confirmation Dialog
let pendingRemoveAnimeId = null;
        let pendingRemoveAnimeTitle = '';
        let pendingRemoveCallback = null;

        function promptRemoveWatchlist(animeId, animeTitle, callback) {
            pendingRemoveAnimeId = animeId;
            pendingRemoveAnimeTitle = animeTitle || 'this anime';
            pendingRemoveCallback = (typeof callback === 'function') ? callback : null;

            const titleEl = document.getElementById('confirmAnimeTitle');
            if (titleEl) {
                titleEl.textContent = `"${pendingRemoveAnimeTitle}"`;
            }
            const modal = document.getElementById('confirmRemoveModal');
            if (modal) {
                modal.style.display = 'flex';
            }
        }

        function closeConfirmModal() {
            const modal = document.getElementById('confirmRemoveModal');
            if (modal) {
                modal.style.display = 'none';
            }
            pendingRemoveAnimeId = null;
            pendingRemoveCallback = null;
        }

        function executeRemoveFromWatchlist() {
            if (!pendingRemoveAnimeId) return;

            const btnConfirm = document.getElementById('btnConfirmRemove');
            const originalBtnHtml = btnConfirm ? btnConfirm.innerHTML : '';
            if (btnConfirm) {
                btnConfirm.disabled = true;
                btnConfirm.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Removing...';
            }

            const token = localStorage.getItem('kototv_token') || localStorage.getItem('hiasian_token');
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
            const headers = {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            };
            if (token) headers['Authorization'] = 'Bearer ' + token;
            if (csrfToken) headers['X-CSRF-TOKEN'] = csrfToken;

            const animeIdToRemove = pendingRemoveAnimeId;
            const removeCb = pendingRemoveCallback;

            fetch('/api/v1/watchlist/' + animeIdToRemove, {
                method: 'DELETE',
                headers: headers
            })
            .then(res => res.json())
            .then(data => {
                closeConfirmModal();
                showToast('Removed from watchlist successfully', 'success');

                // 1. If card exists on page (e.g. profile page), animate and remove it
                const cardEl = document.getElementById('anime-card-' + animeIdToRemove);
                if (cardEl) {
                    cardEl.style.transition = 'opacity 0.25s ease, transform 0.25s ease';
                    cardEl.style.opacity = '0';
                    cardEl.style.transform = 'scale(0.85)';
                    setTimeout(() => {
                        cardEl.remove();
                        updateWatchlistPillCounters();
                    }, 250);
                }

                // 2. If callback is provided (e.g. from anime details page), execute it
                if (removeCb) {
                    removeCb(data);
                }

                window.dispatchEvent(new CustomEvent('watchlist-removed', { detail: { animeId: animeIdToRemove } }));
            })
            .catch(err => {
                console.error('Error removing from watchlist:', err);
                showToast('Failed to remove from watchlist', 'error');
            })
            .finally(() => {
                if (btnConfirm) {
                    btnConfirm.disabled = false;
                    btnConfirm.innerHTML = originalBtnHtml;
                }
            });
        }

        function updateWatchlistPillCounters() {
            const activePill = document.querySelector('.filter-pill.active');
            if (activePill) {
                const m = activePill.textContent.match(/\((\d+)\)/);
                if (m) {
                    const current = parseInt(m[1], 10);
                    const nextVal = Math.max(0, current - 1);
                    activePill.textContent = activePill.textContent.replace(/\(\d+\)/, `(${nextVal})`);
                }
            }
        }

        function showToast(message, type = 'success') {
            let container = document.getElementById('global-toast-container');
            if (!container) {
                container = document.createElement('div');
                container.id = 'global-toast-container';
                container.style.cssText = 'position:fixed;bottom:24px;right:24px;z-index:999999;display:flex;flex-direction:column;gap:10px;pointer-events:none;';
                document.body.appendChild(container);
            }
            const toast = document.createElement('div');
            toast.style.cssText = 'background:#121722;color:#fff;border:1px solid ' + (type === 'error' ? '#ef4444' : '#26a3d6') + ';border-radius:10px;padding:12px 18px;font-size:14px;font-weight:600;box-shadow:0 10px 30px rgba(0,0,0,0.6);display:flex;align-items:center;gap:10px;animation:fadeInToast 0.2s ease;pointer-events:auto;';
            toast.innerHTML = (type === 'error' ? '<i class="bi bi-x-circle-fill text-danger"></i>' : '<i class="bi bi-check-circle-fill" style="color:#26a3d6"></i>') + '<span>' + message + '</span>';
            container.appendChild(toast);
            setTimeout(() => {
                toast.style.transition = 'opacity 0.3s, transform 0.3s';
                toast.style.opacity = '0';
                toast.style.transform = 'translateY(10px)';
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        }

        // Global exports
        window.checkUserAuth = checkUserAuth;
        window.openAuthModal = openAuthModal;
        window.closeAuthModal = closeAuthModal;
        window.switchAuthTab = switchAuthTab;
        window.submitLogin = submitLogin;
        window.submitRegister = submitRegister;
        window.handleLogout = handleLogout;
        window.promptRemoveWatchlist = promptRemoveWatchlist;
        window.closeConfirmModal = closeConfirmModal;
        window.executeRemoveFromWatchlist = executeRemoveFromWatchlist;
        window.showToast = showToast;

