/**
 * ITSWEBER CMS – Arcade Theme JavaScript
 * Retro Gaming: Starfield, Score Counters, Navigation, Reveal, Dark Mode
 */
(function () {
    'use strict';

    // -------------------------------------------------------------------------
    // Starfield Generator – 80 stars with twinkle
    // -------------------------------------------------------------------------
    var starfield = document.getElementById('starfield');
    if (starfield) {
        for (var i = 0; i < 80; i++) {
            var star = document.createElement('div');
            star.className = 'star';
            star.style.left   = (Math.random() * 100) + '%';
            star.style.top    = (Math.random() * 100) + '%';
            var size = Math.random() < 0.3 ? 3 : (Math.random() < 0.6 ? 2 : 1);
            star.style.width  = size + 'px';
            star.style.height = size + 'px';
            star.style.setProperty('--dur',   (2 + Math.random() * 4) + 's');
            star.style.setProperty('--delay', (Math.random() * 3) + 's');
            star.style.opacity = (0.3 + Math.random() * 0.7).toString();
            starfield.appendChild(star);
        }
    }

    document.addEventListener('DOMContentLoaded', function () {

        // ---------------------------------------------------------------------
        // Scroll-to-Top Button
        // ---------------------------------------------------------------------
        var scrollBtn = document.getElementById('scrollToTop');
        if (scrollBtn) {
            var scrollThreshold = 300;
            var ticking = false;

            function handleScrollBtn() {
                if (!ticking) {
                    window.requestAnimationFrame(function () {
                        scrollBtn.classList.toggle('is-visible', window.scrollY > scrollThreshold);
                        ticking = false;
                    });
                    ticking = true;
                }
            }

            window.addEventListener('scroll', handleScrollBtn, { passive: true });

            scrollBtn.addEventListener('click', function () {
                window.scrollTo({ top: 0, behavior: 'smooth' });
            });
        }

        // ---------------------------------------------------------------------
        // Sticky Header – .is-scrolled after 10px scroll
        // ---------------------------------------------------------------------
        var siteHeader = document.querySelector('.site-header');
        if (siteHeader) {
            var headerTicking = false;

            function handleHeaderScroll() {
                if (!headerTicking) {
                    window.requestAnimationFrame(function () {
                        siteHeader.classList.toggle('is-scrolled', window.scrollY > 10);
                        headerTicking = false;
                    });
                    headerTicking = true;
                }
            }

            window.addEventListener('scroll', handleHeaderScroll, { passive: true });
            handleHeaderScroll(); // set initial state
        }

        // ---------------------------------------------------------------------
        // Mobile Navigation Toggle
        // ---------------------------------------------------------------------
        var navToggle = document.getElementById('navToggle');
        var navList   = document.getElementById('navList');

        if (navToggle && navList) {
            navToggle.addEventListener('click', function () {
                var isOpen = navList.classList.toggle('open');
                navToggle.classList.toggle('is-active', isOpen);
                navToggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
                if (!isOpen) {
                    navList.querySelectorAll('.nav-item.has-children.is-open').forEach(function (item) {
                        item.classList.remove('is-open');
                        var sub = item.querySelector(':scope > .sub-menu');
                        if (sub) sub.style.maxHeight = '';
                    });
                }
            });
        }

        // ---------------------------------------------------------------------
        // Sub-Menu / Dropdown Navigation
        // ---------------------------------------------------------------------
        (function () {
            var isMobile = function () { return window.innerWidth <= 768; };
            var closeDelay = 150;
            var timers = new Map();

            document.querySelectorAll('.nav-list > .nav-item.has-children').forEach(function (item) {
                item.addEventListener('mouseenter', function () {
                    if (isMobile()) return;
                    if (timers.has(item)) { clearTimeout(timers.get(item)); timers.delete(item); }
                    item.parentNode.querySelectorAll(':scope > .nav-item.has-children.is-open').forEach(function (s) {
                        if (s !== item) closeDropdown(s);
                    });
                    openDropdown(item);
                });
                item.addEventListener('mouseleave', function () {
                    if (isMobile()) return;
                    timers.set(item, setTimeout(function () { closeDropdown(item); timers.delete(item); }, closeDelay));
                });
            });

            document.querySelectorAll('.sub-menu > .nav-item.has-children').forEach(function (item) {
                item.addEventListener('mouseenter', function () {
                    if (isMobile()) return;
                    item.classList.add('is-open');
                });
                item.addEventListener('mouseleave', function () {
                    if (isMobile()) return;
                    item.classList.remove('is-open');
                });
            });

            document.addEventListener('click', function (e) {
                var clickedChevron = e.target.closest('.nav-chevron') || e.target.closest('.nav-flyout-chevron');
                if (!clickedChevron) return;
                var link = e.target.closest('.nav-item.has-children > a');
                if (!link) return;
                e.preventDefault();
                e.stopPropagation();
                var navItem = link.closest('.nav-item.has-children');
                if (navItem.classList.contains('is-open')) {
                    closeDropdown(navItem);
                } else {
                    openDropdown(navItem);
                }
            });

            document.addEventListener('click', function (e) {
                if (isMobile()) return;
                if (!e.target.closest('.nav-item.has-children')) {
                    document.querySelectorAll('.nav-item.has-children.is-open').forEach(closeDropdown);
                }
            });

            document.addEventListener('keydown', function (e) {
                if (e.key === 'Escape') {
                    document.querySelectorAll('.nav-item.has-children.is-open').forEach(function (item) {
                        closeDropdown(item);
                        var link = item.querySelector(':scope > a');
                        if (link) link.focus();
                    });
                }
            });

            function openDropdown(item) {
                item.classList.add('is-open');
                var link = item.querySelector(':scope > a[aria-expanded]');
                if (link) link.setAttribute('aria-expanded', 'true');
            }

            function closeDropdown(item) {
                item.classList.remove('is-open');
                var link = item.querySelector(':scope > a[aria-expanded]');
                if (link) link.setAttribute('aria-expanded', 'false');
                item.querySelectorAll('.nav-item.has-children.is-open').forEach(function (child) {
                    child.classList.remove('is-open');
                    var cLink = child.querySelector(':scope > a[aria-expanded]');
                    if (cLink) cLink.setAttribute('aria-expanded', 'false');
                });
            }
        })();

        // ---------------------------------------------------------------------
        // Active Nav Highlight on Scroll
        // ---------------------------------------------------------------------
        var sections  = document.querySelectorAll('section[id]');
        var navLinks  = document.querySelectorAll('.nav-link[href^="#"]');

        function updateActiveNav() {
            var scrollY = window.scrollY + 120;
            sections.forEach(function (section) {
                var top    = section.offsetTop;
                var height = section.offsetHeight;
                var id     = section.getAttribute('id');
                if (scrollY >= top && scrollY < top + height) {
                    navLinks.forEach(function (link) {
                        link.classList.remove('active');
                        if (link.getAttribute('href') === '#' + id) {
                            link.classList.add('active');
                        }
                    });
                }
            });
        }

        window.addEventListener('scroll', updateActiveNav, { passive: true });

        // ---------------------------------------------------------------------
        // Header Search Toggle
        // ---------------------------------------------------------------------
        var searchToggle = document.getElementById('searchToggle');
        var searchDropdown = document.getElementById('searchDropdown');

        if (searchToggle && searchDropdown) {
            searchToggle.addEventListener('click', function (e) {
                e.stopPropagation();
                var isOpen = searchDropdown.classList.toggle('is-open');
                searchToggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
                if (isOpen) {
                    var input = searchDropdown.querySelector('input[type="search"], input[type="text"]');
                    if (input) input.focus();
                }
            });

            document.addEventListener('click', function (e) {
                if (!searchDropdown.contains(e.target) && e.target !== searchToggle) {
                    searchDropdown.classList.remove('is-open');
                    searchToggle.setAttribute('aria-expanded', 'false');
                }
            });

            document.addEventListener('keydown', function (e) {
                if (e.key === 'Escape' && searchDropdown.classList.contains('is-open')) {
                    searchDropdown.classList.remove('is-open');
                    searchToggle.setAttribute('aria-expanded', 'false');
                    searchToggle.focus();
                }
            });
        }

        // ---------------------------------------------------------------------
        // Dark Mode Toggle
        // ---------------------------------------------------------------------
        var themeToggle = document.getElementById('themeToggle');
        if (themeToggle) {
            themeToggle.addEventListener('click', function () {
                var html    = document.documentElement;
                var current = html.getAttribute('data-theme');
                var isDark  = current === 'dark' ||
                    (current !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches);
                var next = isDark ? 'light' : 'dark';
                html.setAttribute('data-theme', next);
                try { localStorage.setItem('iw-theme', next); } catch (e) {}
            });
        }

        // ---------------------------------------------------------------------
        // IntersectionObserver Scroll Reveal (.reveal → .visible)
        // ---------------------------------------------------------------------
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            document.querySelectorAll('.reveal').forEach(function (el) {
                el.classList.add('visible');
            });
        } else if ('IntersectionObserver' in window) {
            var revealObserver = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('visible');
                        revealObserver.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.15,
                rootMargin: '0px 0px -40px 0px'
            });

            document.querySelectorAll('.reveal').forEach(function (el) {
                revealObserver.observe(el);
            });

            window.addEventListener('load', function () {
                document.querySelectorAll('.reveal:not(.visible)').forEach(function (el) {
                    var rect = el.getBoundingClientRect();
                    if (rect.top < window.innerHeight) {
                        el.classList.add('visible');
                    }
                });
            });
        } else {
            document.querySelectorAll('.reveal').forEach(function (el) {
                el.classList.add('visible');
            });
        }

        // ---------------------------------------------------------------------
        // Animated Score Counter – .score-value in #highscore section
        // ---------------------------------------------------------------------
        var scoreValues  = document.querySelectorAll('.score-value');
        var scoreCounted = false;

        function animateScores() {
            if (scoreCounted) return;
            var highscoreSection = document.getElementById('highscore');
            if (!highscoreSection) return;

            var rect = highscoreSection.getBoundingClientRect();
            if (rect.top < window.innerHeight * 0.85) {
                scoreCounted = true;

                scoreValues.forEach(function (el) {
                    var text   = el.textContent.trim();
                    var target = parseInt(text.replace(/[\.,]/g, ''), 10);
                    if (isNaN(target)) return;

                    var duration  = 1500;
                    var startTime = null;

                    function step(timestamp) {
                        if (!startTime) startTime = timestamp;
                        var progress = Math.min((timestamp - startTime) / duration, 1);
                        // Ease out cubic
                        var eased   = 1 - Math.pow(1 - progress, 3);
                        var current = Math.floor(eased * target);
                        el.textContent = current.toLocaleString('de-DE');
                        if (progress < 1) {
                            requestAnimationFrame(step);
                        }
                    }

                    requestAnimationFrame(step);
                });
            }
        }

        window.addEventListener('scroll', animateScores, { passive: true });
        animateScores(); // check on page load

        // ---------------------------------------------------------------------
        // Stat Counter – .stat-number[data-target] (stats section)
        // ---------------------------------------------------------------------
        var statElements = document.querySelectorAll('.stat-number[data-target]');
        if ('IntersectionObserver' in window && statElements.length > 0) {
            var counterObserver = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (entry.isIntersecting) {
                        animateCounter(entry.target);
                        counterObserver.unobserve(entry.target);
                    }
                });
            }, { threshold: 0.5 });

            statElements.forEach(function (el) {
                counterObserver.observe(el);
            });
        }

        function animateCounter(el) {
            var target   = parseInt(el.getAttribute('data-target'), 10);
            var suffix   = el.getAttribute('data-suffix') || '';
            var duration = 1800;
            var start    = performance.now();

            function update(now) {
                var progress = Math.min((now - start) / duration, 1);
                var eased    = 1 - Math.pow(1 - progress, 3);
                var current  = Math.round(target * eased);
                el.textContent = current.toLocaleString('de-DE') + suffix;
                if (progress < 1) {
                    requestAnimationFrame(update);
                }
            }
            requestAnimationFrame(update);
        }

        // ---------------------------------------------------------------------
        // Smooth Scroll for anchor links
        // ---------------------------------------------------------------------
        document.querySelectorAll('a[href^="#"]').forEach(function (link) {
            link.addEventListener('click', function (e) {
                var targetId = this.getAttribute('href');
                if (targetId === '#' || targetId === '#main-content') return;

                var targetEl = document.querySelector(targetId);
                if (!targetEl) return;

                e.preventDefault();

                var headerHeight    = siteHeader ? siteHeader.offsetHeight : 80;
                var targetPosition  = targetEl.getBoundingClientRect().top + window.scrollY - headerHeight - 20;

                window.scrollTo({ top: targetPosition, behavior: 'smooth' });

                if (history.pushState) {
                    history.pushState(null, null, targetId);
                }
            });
        });

        // ---------------------------------------------------------------------
        // Cookie Consent
        // ---------------------------------------------------------------------
        var consentBanner = document.getElementById('cookieConsent');
        if (consentBanner) {
            var consentKey = 'iw-cookie-consent';

            // Hide if already consented
            if (localStorage.getItem(consentKey)) {
                consentBanner.style.display = 'none';
            }

            var acceptBtn = consentBanner.querySelector('[data-consent-accept]');
            var rejectBtn = consentBanner.querySelector('[data-consent-reject]');

            if (acceptBtn) {
                acceptBtn.addEventListener('click', function () {
                    try { localStorage.setItem(consentKey, 'accepted'); } catch (e) {}
                    consentBanner.classList.add('is-hidden');
                    setTimeout(function () { consentBanner.style.display = 'none'; }, 400);
                });
            }

            if (rejectBtn) {
                rejectBtn.addEventListener('click', function () {
                    try { localStorage.setItem(consentKey, 'rejected'); } catch (e) {}
                    consentBanner.classList.add('is-hidden');
                    setTimeout(function () { consentBanner.style.display = 'none'; }, 400);
                });
            }

            // Reopen consent
            var reopenLinks = document.querySelectorAll('[data-consent-reopen]');
            reopenLinks.forEach(function (link) {
                link.addEventListener('click', function (e) {
                    e.preventDefault();
                    try { localStorage.removeItem(consentKey); } catch (err) {}
                    consentBanner.style.display = '';
                    consentBanner.classList.remove('is-hidden');
                });
            });
        }

    }); // end DOMContentLoaded

    // -------------------------------------------------------------------------
    // Sticky Header via data attribute (compatible with CMS setting)
    // -------------------------------------------------------------------------
    if (document.documentElement.hasAttribute('data-sticky-header')) {
        var stickyHeader = document.querySelector('.site-header');
        if (stickyHeader) {
            window.addEventListener('scroll', function () {
                stickyHeader.classList.toggle('is-scrolled', window.scrollY > 10);
            }, { passive: true });
        }
    }

    // -------------------------------------------------------------------------
    // Scroll Animations via data attribute (compatible with CMS setting)
    // -------------------------------------------------------------------------
    if (document.documentElement.hasAttribute('data-scroll-animations')) {
        var animEls = document.querySelectorAll('.animate-on-scroll');
        if (animEls.length && 'IntersectionObserver' in window) {
            var animObs = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('is-visible');
                        animObs.unobserve(entry.target);
                    }
                });
            }, { threshold: 0.15 });
            animEls.forEach(function (el) { animObs.observe(el); });
        }
    }

})();
