/**
 * ITSWEBER CMS – Terminal Theme JavaScript
 * Mobile navigation + Scroll-to-Top + Typing + Counter + Reveal
 */
document.addEventListener('DOMContentLoaded', function () {

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

        function onScroll() {
            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', onScroll, { 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.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 – v3.3.0
    // -------------------------------------------------------------------------
    (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 – v3.2.0
    // -------------------------------------------------------------------------
    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) – v3.2.0
    // -------------------------------------------------------------------------
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
        document.querySelectorAll('.reveal').forEach(function (el) {
            el.classList.add('vis');
        });
    } else if ('IntersectionObserver' in window) {
        var revealObserver = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting) {
                    entry.target.classList.add('vis');
                    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(.vis)').forEach(function (el) {
                var rect = el.getBoundingClientRect();
                if (rect.top < window.innerHeight) {
                    el.classList.add('vis');
                }
            });
        });
    } else {
        document.querySelectorAll('.reveal').forEach(function (el) {
            el.classList.add('vis');
        });
    }

    // -------------------------------------------------------------------------
    // Counter Animation (for stats values with data-target)
    // -------------------------------------------------------------------------
    var statElements = document.querySelectorAll('[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);
    }

    // -------------------------------------------------------------------------
    // Typing Effect for Hero
    // -------------------------------------------------------------------------
    var typedEl = document.getElementById('heroTyped');
    if (typedEl) {
        var fullText = typedEl.textContent;
        typedEl.textContent = '';
        typedEl.style.width = 'auto';
        typedEl.style.overflow = 'visible';
        typedEl.style.whiteSpace = 'normal';
        typedEl.style.animation = 'none';

        var charIndex = 0;
        var typeSpeed = 50;

        function typeChar() {
            if (charIndex < fullText.length) {
                typedEl.textContent += fullText.charAt(charIndex);
                charIndex++;
                setTimeout(typeChar, typeSpeed);
            }
        }
        setTimeout(typeChar, 600);
    }

    // -------------------------------------------------------------------------
    // Code Showcase Tab Switcher
    // -------------------------------------------------------------------------
    document.querySelectorAll('.terminal__tabs').forEach(function (tabContainer) {
        var tabs = tabContainer.querySelectorAll('.terminal__tab');
        var terminal = tabContainer.closest('.terminal');
        if (!terminal) return;
        var panels = terminal.querySelectorAll('.code-panel');

        tabs.forEach(function (tab, index) {
            tab.addEventListener('click', function () {
                tabs.forEach(function (t) { t.classList.remove('terminal__tab--active'); });
                tab.classList.add('terminal__tab--active');
                panels.forEach(function (p, i) {
                    p.style.display = (i === index) ? 'block' : 'none';
                });
            });
        });
    });

});

/* ── Sticky Header (v3.3.0) ─────────────────────────────────────────── */
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 (v3.3.0) ──────────────────────────────────────── */
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); });
    }
}
