/**
 * ALGA ARENA — Core Application JS
 * Pure Vanilla JavaScript, no frameworks
 */

'use strict';

// ============================================================
// CORE MODULE: Navigation
// ============================================================
const Navigation = (() => {
    let sidebar = null;
    let sidebarToggle = null;
    let shell = null;
    let isCollapsed = false;

    const init = () => {
        sidebar = document.getElementById('arenaSidebar');
        sidebarToggle = document.getElementById('sidebarToggle');
        shell = document.getElementById('arenaShell');

        if (sidebarToggle) {
            sidebarToggle.addEventListener('click', toggleSidebar);
        }

        // Restore state
        try {
            isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
        } catch (e) {
            isCollapsed = false;
        }
        if (isCollapsed && shell) {
            shell.classList.add('sidebar-collapsed');
        }

        // Active nav item
        highlightActive();

        // Mobile offcanvas
        initOffcanvas();
    };

    const toggleSidebar = () => {
        const isMobile = window.innerWidth <= 768;
        if (isMobile) {
            const offcanvas = document.getElementById('mobileOffcanvas');
            const overlay = document.getElementById('offcanvasOverlay');
            if (offcanvas) {
                const isOpen = offcanvas.classList.contains('open');
                if (isOpen) {
                    offcanvas.classList.remove('open');
                    if (overlay) overlay.classList.remove('active');
                    document.body.style.overflow = '';
                } else {
                    offcanvas.classList.add('open');
                    if (overlay) overlay.classList.add('active');
                    document.body.style.overflow = 'hidden';
                }
            }
            return;
        }

        isCollapsed = !isCollapsed;
        if (shell) shell.classList.toggle('sidebar-collapsed', isCollapsed);
        try {
            localStorage.setItem('sidebarCollapsed', isCollapsed);
        } catch (e) {
            console.warn("Could not save sidebarCollapsed:", e);
        }
    };

    const highlightActive = () => {
        const path = window.location.pathname;
        document.querySelectorAll('.sidebar-item, .public-nav-links a, .mobile-nav-item').forEach(link => {
            const href = link.getAttribute('href');
            if (href && path === href) {
                link.classList.add('active');
            } else if (href && href !== '/' && path.startsWith(href)) {
                link.classList.add('active');
            }
        });
    };

    const initOffcanvas = () => {
        const trigger = document.getElementById('mobileMenuToggle');
        const offcanvas = document.getElementById('mobileOffcanvas');
        const overlay = document.getElementById('offcanvasOverlay');
        const closeBtn = document.getElementById('offcanvasClose');

        if (!trigger || !offcanvas) return;

        const open = () => {
            offcanvas.classList.add('open');
            if (overlay) overlay.classList.add('active');
            document.body.style.overflow = 'hidden';
            closeBtn?.focus();
        };

        const close = () => {
            offcanvas.classList.remove('open');
            if (overlay) overlay.classList.remove('active');
            document.body.style.overflow = '';
            trigger.focus();
        };

        trigger.addEventListener('click', open);
        if (closeBtn) closeBtn.addEventListener('click', close);
        if (overlay) overlay.addEventListener('click', close);

        // Esc key
        document.addEventListener('keydown', e => {
            if (e.key === 'Escape' && offcanvas.classList.contains('open')) close();
        });
    };

    return { init };
})();

// ============================================================
// CORE MODULE: Dropdowns
// ============================================================
const Dropdowns = (() => {
    const init = () => {
        document.querySelectorAll('[data-dropdown]').forEach(trigger => {
            const targetId = trigger.dataset.dropdown;
            const target = document.getElementById(targetId);
            if (!target) return;

            trigger.addEventListener('click', e => {
                e.stopPropagation();
                const isOpen = target.classList.contains('open');
                closeAll();
                if (!isOpen) {
                    target.classList.add('open');
                    trigger.setAttribute('aria-expanded', 'true');
                    positionDropdown(trigger, target);
                }
            });

            trigger.addEventListener('keydown', e => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    trigger.click();
                }
            });
        });

        document.addEventListener('click', closeAll);
        document.addEventListener('keydown', e => {
            if (e.key === 'Escape') closeAll();
        });
    };

    const closeAll = () => {
        document.querySelectorAll('.dropdown-arena.open').forEach(d => {
            d.classList.remove('open');
            const triggerId = d.dataset.triggeredBy;
            if (triggerId) {
                document.getElementById(triggerId)?.setAttribute('aria-expanded', 'false');
            }
        });
    };

    const positionDropdown = (trigger, target) => {
        const rect = trigger.getBoundingClientRect();
        const isRTL = document.documentElement.dir === 'rtl';
        if (isRTL) {
            target.style.right = `${window.innerWidth - rect.right}px`;
            target.style.left = 'auto';
        } else {
            target.style.left = `${rect.left}px`;
            target.style.right = 'auto';
        }
    };

    return { init };
})();

// ============================================================
// CORE MODULE: Modals
// ============================================================
const Modals = (() => {
    let activeModal = null;
    let previousFocus = null;

    const init = () => {
        // Open triggers
        document.querySelectorAll('[data-modal-open]').forEach(btn => {
            btn.addEventListener('click', () => {
                const id = btn.dataset.modalOpen;
                open(id);
            });
        });

        // Close triggers
        document.querySelectorAll('[data-modal-close]').forEach(btn => {
            btn.addEventListener('click', () => close());
        });

        // Close on overlay click
        document.querySelectorAll('.arena-overlay').forEach(overlay => {
            overlay.addEventListener('click', () => close());
        });

        // Esc key
        document.addEventListener('keydown', e => {
            if (e.key === 'Escape' && activeModal) close();
        });
    };

    const open = (id) => {
        const modal = document.getElementById(id);
        const overlay = document.getElementById(id + 'Overlay') || document.querySelector('.arena-overlay');
        if (!modal) return;

        previousFocus = document.activeElement;
        activeModal = modal;

        if (overlay) overlay.classList.add('active');
        modal.classList.add('active');
        modal.removeAttribute('aria-hidden');
        document.body.style.overflow = 'hidden';

        // Focus first focusable element
        const focusable = modal.querySelector('button, input, select, textarea, a[href], [tabindex="0"]');
        if (focusable) setTimeout(() => focusable.focus(), 100);

        // Trap focus
        modal.addEventListener('keydown', trapFocus);
    };

    const close = () => {
        if (!activeModal) return;
        const overlay = document.querySelector('.arena-overlay.active');

        activeModal.classList.remove('active');
        activeModal.setAttribute('aria-hidden', 'true');
        activeModal.removeEventListener('keydown', trapFocus);

        if (overlay) overlay.classList.remove('active');
        document.body.style.overflow = '';

        if (previousFocus) previousFocus.focus();
        activeModal = null;
    };

    const trapFocus = (e) => {
        if (e.key !== 'Tab' || !activeModal) return;
        const focusable = activeModal.querySelectorAll(
            'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], [tabindex="0"]'
        );
        const first = focusable[0];
        const last = focusable[focusable.length - 1];

        if (e.shiftKey) {
            if (document.activeElement === first) { e.preventDefault(); last.focus(); }
        } else {
            if (document.activeElement === last) { e.preventDefault(); first.focus(); }
        }
    };

    return { init, open, close };
})();

// ============================================================
// CORE MODULE: Tabs
// ============================================================
const Tabs = (() => {
    const init = () => {
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const tabGroup = btn.closest('[data-tabs]')?.dataset.tabs
                    || btn.dataset.tabGroup;
                const targetId = btn.dataset.tab;

                // Deactivate all in group
                const context = btn.closest('[data-tabs]') || document;
                context.querySelectorAll('.tab-btn').forEach(b => {
                    b.classList.remove('active');
                    b.setAttribute('aria-selected', 'false');
                });

                context.querySelectorAll('.tab-pane').forEach(p => {
                    p.classList.remove('active');
                });

                // Activate
                btn.classList.add('active');
                btn.setAttribute('aria-selected', 'true');
                const pane = document.getElementById(targetId);
                if (pane) pane.classList.add('active');
            });

            // Keyboard arrow navigation
            btn.addEventListener('keydown', e => {
                const tabs = [...btn.closest('.tabs-arena').querySelectorAll('.tab-btn')];
                const idx = tabs.indexOf(btn);
                if (e.key === 'ArrowRight' || (document.dir === 'rtl' && e.key === 'ArrowLeft')) {
                    tabs[(idx + 1) % tabs.length]?.click();
                    tabs[(idx + 1) % tabs.length]?.focus();
                } else if (e.key === 'ArrowLeft' || (document.dir === 'rtl' && e.key === 'ArrowRight')) {
                    tabs[(idx - 1 + tabs.length) % tabs.length]?.click();
                    tabs[(idx - 1 + tabs.length) % tabs.length]?.focus();
                }
            });
        });
    };

    return { init };
})();

// ============================================================
// CORE MODULE: Direction (RTL/LTR)
// ============================================================
const Direction = (() => {
    const init = () => {
        document.querySelectorAll('.lang-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const lang = btn.dataset.lang;
                switchLanguage(lang);
            });
        });

        // Restore saved language
        let saved = 'en';
        try {
            saved = localStorage.getItem('arenaLang') || 'en';
        } catch (e) {
            saved = 'en';
        }
        applyLanguage(saved, false);
    };

    const switchLanguage = (lang) => {
        try {
            localStorage.setItem('arenaLang', lang);
        } catch (e) {
            console.warn("Could not save language selection:", e);
        }
        applyLanguage(lang, true);
    };

    const applyLanguage = (lang, animate) => {
        const isAr = lang === 'ar';
        document.documentElement.dir = isAr ? 'rtl' : 'ltr';
        document.documentElement.lang = lang;

        // Update button states
        document.querySelectorAll('.lang-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.lang === lang);
        });

        if (animate) {
            document.documentElement.style.transition = 'none';
            setTimeout(() => document.documentElement.style.transition = '', 50);
        }
    };

    return { init };
})();

// ============================================================
// CORE MODULE: Toggle switches
// ============================================================
const Toggles = (() => {
    const init = () => {
        document.querySelectorAll('.toggle-arena').forEach(toggle => {
            toggle.setAttribute('role', 'switch');
            toggle.setAttribute('tabindex', '0');

            const update = () => {
                const checked = toggle.classList.contains('checked');
                toggle.setAttribute('aria-checked', checked ? 'true' : 'false');
                const input = toggle.previousElementSibling;
                if (input?.type === 'checkbox') input.checked = checked;
            };

            toggle.addEventListener('click', () => {
                toggle.classList.toggle('checked');
                update();
            });

            toggle.addEventListener('keydown', e => {
                if (e.key === ' ' || e.key === 'Enter') {
                    e.preventDefault();
                    toggle.click();
                }
            });

            update();
        });
    };

    return { init };
})();

// ============================================================
// CORE MODULE: Notification panel
// ============================================================
const NotificationPanel = (() => {
    let panel = null;

    const init = () => {
        const trigger = document.getElementById('notificationTrigger');
        panel = document.getElementById('notificationPanel');

        if (!trigger || !panel) return;

        trigger.addEventListener('click', e => {
            e.stopPropagation();
            const isOpen = panel.classList.contains('dropdown-arena') && panel.classList.contains('open');
            document.querySelectorAll('.dropdown-arena.open').forEach(d => d.classList.remove('open'));
            if (!isOpen) {
                panel.classList.add('open');
                markAsRead();
            }
        });

        document.addEventListener('click', e => {
            if (!panel.contains(e.target) && e.target !== trigger) {
                panel.classList.remove('open');
            }
        });
    };

    const markAsRead = () => {
        const dot = document.querySelector('#notificationTrigger .badge-dot');
        if (dot) setTimeout(() => dot.remove(), 2000);
    };

    return { init };
})();

// ============================================================
// CORE MODULE: Search command palette
// ============================================================
const CommandPalette = (() => {
    let palette = null;
    let input = null;

    const init = () => {
        palette = document.getElementById('commandPalette');
        input = document.getElementById('commandInput');

        if (!palette) return;

        // Keyboard shortcut Ctrl+K / Cmd+K
        document.addEventListener('keydown', e => {
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                toggle();
            }
            if (e.key === 'Escape' && palette.classList.contains('open')) close();
        });

        // Click header search area
        document.getElementById('headerSearch')?.addEventListener('click', open);

        // Backdrop close
        const backdrop = document.getElementById('paletteBackdrop');
        if (backdrop) backdrop.addEventListener('click', close);

        // Input events
        if (input) {
            input.addEventListener('input', debounce(handleSearch, 200));
            input.addEventListener('keydown', handleKeyNav);
        }
    };

    const open = () => {
        if (!palette) return;
        palette.classList.add('open');
        const backdrop = document.getElementById('paletteBackdrop');
        if (backdrop) backdrop.classList.add('active');
        document.body.style.overflow = 'hidden';
        setTimeout(() => input?.focus(), 50);
    };

    const close = () => {
        palette?.classList.remove('open');
        const backdrop = document.getElementById('paletteBackdrop');
        if (backdrop) backdrop.classList.remove('active');
        document.body.style.overflow = '';
        if (input) input.value = '';
    };

    const toggle = () => {
        palette?.classList.contains('open') ? close() : open();
    };

    const handleSearch = () => {
        // Frontend-only mock search — will be replaced with real API
        const q = input.value.toLowerCase().trim();
        const results = document.getElementById('commandResults');
        if (!results) return;

        if (!q) {
            results.innerHTML = getDefaultResults();
            return;
        }

        const mockItems = [
            { type: 'player', name: 'NightFalcon', icon: '👤', href: '/preview/players/nightfalcon' },
            { type: 'team', name: 'Team Nexus', icon: '🛡️', href: '/preview/teams/nexus' },
            { type: 'tournament', name: 'ALGA Arena Cup', icon: '🏆', href: '/preview/tournaments/arena-cup' },
            { type: 'page', name: 'Rankings', icon: '📊', href: '/preview/rankings' },
            { type: 'page', name: 'Recruitment', icon: '🎯', href: '/preview/recruitment' },
        ].filter(item => item.name.toLowerCase().includes(q));

        if (!mockItems.length) {
            results.innerHTML = `<div class="empty-state p-6 text-center fs-sm text-muted">No results for "${escapeHtml(q)}"</div>`;
            return;
        }

        results.innerHTML = mockItems.map(item => `
            <a class="command-result-item" href="${item.href}">
                <div class="command-result-icon">${item.icon}</div>
                <div>
                    <div class="fw-600">${escapeHtml(item.name)}</div>
                    <div class="fs-xs text-muted text-capitalize">${item.type}</div>
                </div>
            </a>
        `).join('');
    };

    const getDefaultResults = () => `
        <div class="command-group-label">Quick Actions</div>
        <a class="command-result-item" href="/preview/players"><div class="command-result-icon">👥</div><span>Browse Players</span></a>
        <a class="command-result-item" href="/preview/teams"><div class="command-result-icon">🛡️</div><span>Browse Teams</span></a>
        <a class="command-result-item" href="/preview/tournaments"><div class="command-result-icon">🏆</div><span>Tournaments</span></a>
        <a class="command-result-item" href="/preview/recruitment"><div class="command-result-icon">🎯</div><span>Recruitment</span></a>
        <div class="command-group-label">Recent</div>
        <a class="command-result-item" href="/preview/players/nightfalcon"><div class="command-result-icon">👤</div><div><div class="fw-600">NightFalcon</div><div class="fs-xs text-muted">Player</div></div></a>
    `;

    const handleKeyNav = (e) => {
        const items = palette.querySelectorAll('.command-result-item');
        const selected = palette.querySelector('.command-result-item.selected');
        let idx = selected ? [...items].indexOf(selected) : -1;

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            selected?.classList.remove('selected');
            items[Math.min(idx + 1, items.length - 1)]?.classList.add('selected');
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            selected?.classList.remove('selected');
            items[Math.max(idx - 1, 0)]?.classList.add('selected');
        } else if (e.key === 'Enter') {
            if (selected) { selected.click(); close(); }
        }
    };

    return { init, open, close };
})();

// ============================================================
// UTILITY: Debounce
// ============================================================
function debounce(fn, delay) {
    let timer;
    return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => fn(...args), delay);
    };
}

// ============================================================
// UTILITY: Escape HTML
// ============================================================
function escapeHtml(str) {
    const d = document.createElement('div');
    d.textContent = str;
    return d.innerHTML;
}

// ============================================================
// UTILITY: Format numbers
// ============================================================
function formatNumber(n) {
    if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
    if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
    return n.toString();
}

// ============================================================
// UTILITY: Relative time
// ============================================================
function relativeTime(date) {
    const diff = Date.now() - new Date(date).getTime();
    const mins = Math.floor(diff / 60000);
    if (mins < 1) return 'just now';
    if (mins < 60) return `${mins}m ago`;
    const hrs = Math.floor(mins / 60);
    if (hrs < 24) return `${hrs}h ago`;
    const days = Math.floor(hrs / 24);
    return `${days}d ago`;
}

// ============================================================
// CHAT MODULE (Mock interaction)
// ============================================================
const Chat = (() => {
    const init = () => {
        const input = document.getElementById('chatMessageInput');
        const sendBtn = document.getElementById('chatSendBtn');
        const messages = document.getElementById('chatMessages');

        if (!input || !messages) return;

        const send = () => {
            const text = input.value.trim();
            if (!text) return;

            const msg = document.createElement('div');
            msg.className = 'message own';
            msg.innerHTML = `
                <div class="message-bubble">${escapeHtml(text)}</div>
            `;
            messages.appendChild(msg);
            input.value = '';
            messages.scrollTop = messages.scrollHeight;

            // Mock reply
            setTimeout(() => {
                const reply = document.createElement('div');
                reply.className = 'message';
                reply.innerHTML = `
                    <img src="/assets/images/generated/players/player-2.webp" class="msg-avatar" alt="User" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2228%22 height=%2228%22><rect width=%2228%22 height=%2228%22 fill=%22%231D2030%22/></svg>'">
                    <div class="message-bubble">Got it! 👍</div>
                `;
                messages.appendChild(reply);
                messages.scrollTop = messages.scrollHeight;
            }, 1200);
        };

        sendBtn?.addEventListener('click', send);
        input.addEventListener('keydown', e => {
            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
        });

        // Auto-resize textarea
        input.addEventListener('input', () => {
            input.style.height = 'auto';
            input.style.height = Math.min(input.scrollHeight, 120) + 'px';
        });
    };

    return { init };
})();

// ============================================================
// COUNTERS (Stat count-up — GSAP-free fallback)
// ============================================================
const Counters = (() => {
    const init = () => {
        const counters = document.querySelectorAll('[data-counter]');
        if (!counters.length) return;

        const observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                if (!entry.isIntersecting) return;
                animateCounter(entry.target);
                observer.unobserve(entry.target);
            });
        }, { threshold: 0.3 });

        counters.forEach(el => observer.observe(el));
    };

    const animateCounter = (el) => {
        const target = parseFloat(el.dataset.counter);
        const duration = 1600;
        const suffix = el.dataset.suffix || '';
        const prefix = el.dataset.prefix || '';
        const start = performance.now();
        const isDecimal = String(target).includes('.');

        const update = (time) => {
            const progress = Math.min((time - start) / duration, 1);
            const eased = 1 - Math.pow(1 - progress, 4);
            const current = target * eased;
            el.textContent = prefix + (isDecimal ? current.toFixed(1) : Math.floor(current).toLocaleString()) + suffix;
            if (progress < 1) requestAnimationFrame(update);
        };

        // Respect reduced motion
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            el.textContent = prefix + (isDecimal ? target.toFixed(1) : target.toLocaleString()) + suffix;
            return;
        }

        requestAnimationFrame(update);
    };

    return { init };
})();

// ============================================================
// SCROLL REVEALS (IntersectionObserver-based, GSAP-free fallback)
// ============================================================
const ScrollReveals = (() => {
    const init = () => {
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

        const els = document.querySelectorAll('[data-reveal]');
        if (!els.length) return;

        const style = document.createElement('style');
        style.textContent = `
            [data-reveal] { opacity: 0; transform: translateY(24px); transition: opacity 0.6s var(--ease-out-expo), transform 0.6s var(--ease-out-expo); }
            [data-reveal="left"] { transform: translateX(-24px); }
            [data-reveal="right"] { transform: translateX(24px); }
            [data-reveal="scale"] { transform: scale(0.96); }
            [data-reveal].revealed { opacity: 1; transform: none; }
        `;
        document.head.appendChild(style);

        const observer = new IntersectionObserver(entries => {
            entries.forEach((entry, i) => {
                if (!entry.isIntersecting) return;
                const delay = entry.target.dataset.delay || 0;
                setTimeout(() => entry.target.classList.add('revealed'), Number(delay));
                observer.unobserve(entry.target);
            });
        }, { threshold: 0.15, rootMargin: '0px 0px -40px 0px' });

        els.forEach(el => observer.observe(el));
    };

    return { init };
})();

// ============================================================
// GSAP HERO ANIMATIONS (loaded after GSAP CDN)
// ============================================================
const HeroMotion = (() => {
    const init = () => {
        if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') return;
        if (!document.querySelector('.landing-hero')) return;
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

        gsap.registerPlugin(ScrollTrigger);

        // Hero text entrance
        const tl = gsap.timeline({ delay: 0.2 });

        tl.from('.hero-tag', { opacity: 0, y: 20, duration: 0.6, ease: 'power3.out' })
          .from('.hero-headline', { opacity: 0, y: 40, duration: 0.8, ease: 'power3.out' }, '-=0.3')
          .from('.hero-desc', { opacity: 0, y: 24, duration: 0.7, ease: 'power3.out' }, '-=0.5')
          .from('.hero-actions .btn-arena', { opacity: 0, y: 20, duration: 0.5, stagger: 0.1, ease: 'power3.out' }, '-=0.4')
          .from('.hero-stat', { opacity: 0, y: 16, duration: 0.5, stagger: 0.08, ease: 'power3.out' }, '-=0.3');

        // Hero bg parallax
        ScrollTrigger.create({
            trigger: '.landing-hero',
            start: 'top top',
            end: 'bottom top',
            scrub: 1,
            onUpdate: self => {
                const y = self.progress * 120;
                gsap.set('.hero-bg img', { y: y });
            }
        });

        // Section reveals via ScrollTrigger
        document.querySelectorAll('[data-gsap-reveal]').forEach(el => {
            gsap.from(el, {
                scrollTrigger: {
                    trigger: el,
                    start: 'top 85%',
                    toggleActions: 'play none none none',
                },
                opacity: 0,
                y: 40,
                duration: 0.8,
                ease: 'power3.out',
                delay: Number(el.dataset.gsapDelay || 0),
            });
        });

        // Stat count-up with GSAP
        document.querySelectorAll('[data-counter]').forEach(el => {
            const target = parseFloat(el.dataset.counter);
            const suffix = el.dataset.suffix || '';
            const prefix = el.dataset.prefix || '';

            ScrollTrigger.create({
                trigger: el,
                start: 'top 85%',
                onEnter: () => {
                    gsap.fromTo({ val: 0 }, { val: target }, {
                        duration: 1.8,
                        ease: 'power2.out',
                        onUpdate() {
                            const v = this.targets()[0].val;
                            el.textContent = prefix + (String(target).includes('.')
                                ? v.toFixed(1)
                                : Math.round(v).toLocaleString()
                            ) + suffix;
                        }
                    });
                },
                once: true,
            });
        });
    };

    return { init };
})();

// ============================================================
// RANK PROGRESS BARS
// ============================================================
const RankProgress = (() => {
    const init = () => {
        const bars = document.querySelectorAll('.progress-bar-arena[data-progress]');
        if (!bars.length) return;

        const observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                if (!entry.isIntersecting) return;
                const bar = entry.target;
                const target = bar.dataset.progress + '%';

                if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
                    bar.style.width = target;
                } else {
                    requestAnimationFrame(() => { bar.style.width = target; });
                }
                observer.unobserve(bar);
            });
        }, { threshold: 0.3 });

        bars.forEach(bar => {
            bar.style.width = '0%';
            observer.observe(bar);
        });
    };

    return { init };
})();

// ============================================================
// PRICING TOGGLE (Monthly / Yearly)
// ============================================================
const PricingToggle = (() => {
    const init = () => {
        const toggle = document.getElementById('pricingPeriodToggle');
        if (!toggle) return;

        toggle.addEventListener('click', () => {
            toggle.classList.toggle('checked');
            const isYearly = toggle.classList.contains('checked');
            document.querySelectorAll('[data-price-monthly]').forEach(el => {
                const monthly = el.dataset.priceMonthly;
                const yearly  = el.dataset.priceYearly;
                el.textContent = isYearly ? yearly : monthly;
            });
            const label = document.getElementById('pricingLabel');
            if (label) label.textContent = isYearly ? 'per year' : 'per month';
        });
    };

    return { init };
})();

// ============================================================
// MOCK CHAT INTERACTION
// ============================================================
const ChatList = (() => {
    const init = () => {
        document.querySelectorAll('.chat-item').forEach(item => {
            item.addEventListener('click', () => {
                document.querySelectorAll('.chat-item').forEach(i => i.classList.remove('active'));
                item.classList.add('active');
                // Remove unread badge
                item.querySelector('.chat-unread')?.remove();
            });
        });
    };

    return { init };
})();

// ============================================================
// INIT
// ============================================================
document.addEventListener('DOMContentLoaded', () => {
    Navigation.init();
    Dropdowns.init();
    Modals.init();
    Tabs.init();
    Direction.init();
    Toggles.init();
    NotificationPanel.init();
    CommandPalette.init();
    Counters.init();
    ScrollReveals.init();
    RankProgress.init();
    PricingToggle.init();
    ChatList.init();
    Chat.init();

    // Init GSAP hero after a tick (GSAP loads async from CDN)
    setTimeout(HeroMotion.init, 100);
});
