(() => {
    document.addEventListener('DOMContentLoaded', () => {
        initMobileNav();
        initCopyPassword();
        initCatalog();
        initRevealOnScroll();
        initReviewsSlider();
        initFAQAccordion();
        initCookieBar();
    });

    function initMobileNav() {
        const burger = document.getElementById('burger');
        const mobileMenu = document.getElementById('mobileMenu');
        if (!burger || !mobileMenu) return;
        burger.addEventListener('click', () => {
            const open = mobileMenu.style.display === 'block';
            mobileMenu.style.display = open ? 'none' : 'block';
            burger.setAttribute('aria-label', open ? 'Open menu' : 'Close menu');
        });
    }

    function initCopyPassword() {
        const pw = document.getElementById('pw');
        const copyBtn = document.getElementById('copyBtn');
        const copyNote = document.getElementById('copyNote');
        if (!pw || !copyBtn) return;

        copyBtn.addEventListener('click', async () => {
            const text = pw.textContent.trim();
            try {
                await navigator.clipboard.writeText(text);
                setCopiedUI(true);
            } catch {
                const range = document.createRange();
                range.selectNodeContents(pw);
                const sel = window.getSelection();
                sel.removeAllRanges(); sel.addRange(range);
                try { document.execCommand('copy'); } catch { }
                setTimeout(() => sel.removeAllRanges(), 1200);
                setCopiedUI(true);
            }
        });

        function setCopiedUI(ok) {
            if (!ok) return;
            copyBtn.textContent = 'Copied ✓';
            if (copyNote) copyNote.style.display = 'block';
            setTimeout(() => {
                copyBtn.textContent = 'Copy password';
                if (copyNote) copyNote.style.display = 'none';
            }, 1600);
        }
    }

    function initCatalog() {
        const grid = document.getElementById('grid');
        const input = document.getElementById('search');
        const empty = document.getElementById('empty');
        if (!grid) return;

        const DATA_URL = '/cheats.json';
        let cheats = [];
        let q = '';

        function debounce(fn, ms) {
            let t;
            return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); };
        }

        function render(list) {
            if (!Array.isArray(list)) return;
            grid.innerHTML = list.map(item => {
                const name = escapeHtml(item.name || '');
                const desc = escapeHtml(item.description || '');
                const img = escapeAttr(item.image || '');
                const alt = escapeAttr(item.name || '');
                return `
<article class="cheat-card">
  <img class="cheat-cover" src="${img}" alt="${alt}" />
  <div class="cheat-body">
    <h3 class="cheat-title">${name}</h3>
    <p class="cheat-desc">${desc}</p>
  </div>
  <div class="cheat-actions">
    <a class="btn btn-primary download-btn" href="/download">Download</a>
  </div>
</article>`;
            }).join('');
        }

        function applyFilter() {
            const query = q.trim().toLowerCase();
            const filtered = !query
                ? cheats
                : cheats.filter(c => {
                    const name = (c.name || '').toLowerCase();
                    const desc = (c.description || '').toLowerCase();
                    return name.includes(query) || desc.includes(query);
                });

            render(filtered);
            if (empty) empty.style.display = filtered.length ? 'none' : 'block';
        }

        (async () => {
            try {
                grid.innerHTML = '<div style="grid-column:1/-1;color:var(--muted);padding:8px 0">Loading…</div>';
                const res = await fetch(DATA_URL, { cache: 'no-store' });
                if (!res.ok) throw new Error('Failed to load cheats.json');
                cheats = await res.json();
                applyFilter();
            } catch (err) {
                grid.innerHTML = '<div style="grid-column:1/-1;color:var(--muted);padding:8px 0">Failed to load catalog.</div>';
                if (window.console) console.error(err);
            }
        })();

        if (input) {
            input.addEventListener('input', debounce((e) => {
                q = e.target.value || '';
                applyFilter();
            }, 150));
        }

        function escapeHtml(s) {
            return String(s)
                .replaceAll('&', '&amp;')
                .replaceAll('<', '&lt;')
                .replaceAll('>', '&gt;')
                .replaceAll('"', '&quot;')
                .replaceAll("'", '&#39;');
        }
        function escapeAttr(s) {
            return escapeHtml(s).replaceAll('`', '&#96;');
        }
    }

    function initRevealOnScroll() {
        const elements = [...document.querySelectorAll('.reveal')];
        if (!elements.length) return;

        if (!('IntersectionObserver' in window)) {
            elements.forEach(el => el.classList.add('visible'));
            return;
        }
        const io = new IntersectionObserver((entries) => {
            entries.forEach(e => {
                if (e.isIntersecting) {
                    e.target.classList.add('visible');
                    io.unobserve(e.target);
                }
            });
        }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });

        function revealCheck() {
            elements.forEach(el => {
                if (el.classList.contains('visible')) return;
                const r = el.getBoundingClientRect();
                if (r.top < window.innerHeight * 0.88 && r.bottom > 0) {
                    el.classList.add('visible'); io.unobserve(el);
                } else {
                    io.observe(el);
                }
            });
        }
        window.addEventListener('resize', revealCheck, { passive: true });
        window.addEventListener('load', revealCheck);
        revealCheck();
    }

    function initReviewsSlider() {
        const track = document.getElementById('reviewsTrack');
        const prev = document.getElementById('prev');
        const next = document.getElementById('next');
        if (!track || !prev || !next) return;

        let index = 0;
        let visible = calcVisible();

        function calcVisible() {
            const w = window.innerWidth;
            return w <= 900 ? 1 : (w <= 1200 ? 2 : 3);
        }
        function maxIndex() {
            return Math.max(0, track.children.length - visible);
        }
        function update() {
            visible = calcVisible();
            index = Math.min(index, maxIndex());
            const step = 100 / visible;
            track.style.transform = `translateX(-${index * step}%)`;
        }

        next.addEventListener('click', () => { index = (index >= maxIndex()) ? 0 : index + 1; update(); });
        prev.addEventListener('click', () => { index = (index <= 0) ? maxIndex() : index - 1; update(); });
        window.addEventListener('resize', update, { passive: true });
        update();
    }

    function initFAQAccordion() {
        const buttons = document.querySelectorAll('.qa button');
        if (!buttons.length) return;

        buttons.forEach(btn => {
            btn.addEventListener('click', () => {
                const qa = btn.closest('.qa');
                const isOpen = qa.classList.contains('open');
                document.querySelectorAll('.qa.open').forEach(q => {
                    q.classList.remove('open');
                    q.querySelector('button')?.setAttribute('aria-expanded', 'false');
                });
                if (!isOpen) {
                    qa.classList.add('open');
                    btn.setAttribute('aria-expanded', 'true');
                }
            });
        });
    }

    function initCookieBar() {
        const cookieBar = document.getElementById('cookieBar');
        const accept = document.getElementById('cookieAccept');
        const decline = document.getElementById('cookieDecline');
        if (!cookieBar || !accept || !decline) return;

        const KEY = 'skillora_cookies';
        const choice = localStorage.getItem(KEY);

        if (!choice) {
            cookieBar.style.display = 'block';
            requestAnimationFrame(() => cookieBar.classList.add('show'));
        }

        accept.addEventListener('click', () => { localStorage.setItem(KEY, 'accepted'); hideBar(); });
        decline.addEventListener('click', () => { localStorage.setItem(KEY, 'declined'); hideBar(); });

        function hideBar() {
            cookieBar.classList.remove('show');
            setTimeout(() => { cookieBar.style.display = 'none'; }, 250);
        }
    }
})();
