/**
 * ITSWEBER CMS – Business Theme JavaScript
 * Mobile navigation + Scroll-to-Top (v3.0.6)
 * Gallery lightbox is now handled by /assets/js/gallery-lightbox.js
 */
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');
            // Close all submenus when closing mobile nav
            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();

        // Desktop: hover open/close with delay
        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); }
                // Close siblings
                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));
            });
        });

        // Level 3 flyout: hover on sub-items
        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');
            });
        });

        // Chevron click toggles submenu (mobile + desktop)
        // Link text click navigates normally on both mobile and desktop
        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);
            }
        });

        // Click outside closes all dropdowns (desktop)
        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);
            }
        });

        // Escape key
        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');
            // Also close nested flyouts
            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
    // Respects prefers-reduced-motion for accessibility
    // -------------------------------------------------------------------------
    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.12,
            rootMargin: '0px 0px -40px 0px'
        });

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

        // Fallback: reveal above-the-fold elements that observer may miss
        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');
        });
    }


});

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