/**
 * ITSWEBER CMS – Nexus Theme JavaScript
 * Cyberpunk/Neon Gaming: Navigation, Scroll, Counters, Glitch, Reveal
 */
(function () {
    'use strict';

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

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

            function handleScroll() {
                if (!ticking) {
                    window.requestAnimationFrame(function () {
                        if (window.scrollY > scrollThreshold) {
                            scrollBtn.classList.add('is-visible');
                        } else {
                            scrollBtn.classList.remove('is-visible');
                        }
                        ticking = false;
                    });
                    ticking = true;
                }
            }

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

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

        // ---------------------------------------------------------------------
        // 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 = '';
                    });
                }
            });
        }

        // ---------------------------------------------------------------------
        // 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');
                });
            }
        })();

        // ---------------------------------------------------------------------
        // 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) {}
            });
        }

        // ---------------------------------------------------------------------
        // Scroll Reveal (IntersectionObserver)
        // ---------------------------------------------------------------------
        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.1,
                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');
            });
        }

        // ---------------------------------------------------------------------
        // Counter Animation (stat-number elements with data-target)
        // ---------------------------------------------------------------------
        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);
        }

        // ---------------------------------------------------------------------
        // Glitch Effect on .neon-word hover
        // ---------------------------------------------------------------------
        document.querySelectorAll('.neon-word').forEach(function (el) {
            el.addEventListener('mouseenter', function () {
                el.style.animation = 'none';
                // Force reflow to restart animation
                void el.offsetWidth;
                el.style.animation = '';
            });
        });

        // ---------------------------------------------------------------------
        // Sticky Header – add .scrolled class at 50px
        // ---------------------------------------------------------------------
        var siteHeader = document.querySelector('.site-header');
        if (siteHeader) {
            var headerTicking = false;

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

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

        // ---------------------------------------------------------------------
        // 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 : 0;
                var targetPosition = targetEl.getBoundingClientRect().top + window.scrollY - headerHeight - 20;

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

                // Update URL without jump
                if (history.pushState) {
                    history.pushState(null, null, targetId);
                }
            });
        });

    });

    // -------------------------------------------------------------------------
    // Scroll Animations (data-scroll-animations attribute)
    // -------------------------------------------------------------------------
    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); });
        }
    }

})();
