/**
 * Blog Over Menu JavaScript
 *
 * Handles:
 * - Dropdown toggle (hover + click for touch)
 * - Sticky header behavior
 * - Mobile menu toggle
 * - Keyboard navigation (Enter, Space, Arrow keys, Escape)
 * - ARIA state management
 * 
 * UPDATED: Removed focus-based auto-expand. Submenus now only open via:
 * - Enter/Space on toggle button
 * - Arrow keys
 * - Mouse hover (desktop)
 * - Touch (mobile)
 */
(function () {
    'use strict';

    // Settings from WordPress (injected via wp_head)
    const settings = window.novaMenuSettings || {
        stickyEnable: false,
        stickyOffset: 100,
        mobileBreakpoint: 992
    };

    // DOM Elements
    const header = document.querySelector('.blog-over-header');
    const mobileToggle = document.querySelector('.blog-over-mobile-toggle');
    const mobileMenu = document.querySelector('.blog-over-mobile-menu');
    const mobileClose = document.querySelector('.blog-over-mobile-close');
    const dropdownToggles = document.querySelectorAll('.blog-over-dropdown-toggle');
    const hasDropdownItems = document.querySelectorAll('.blog-over-has-dropdown, .menu-item-has-children');

    // =========================================
    // Sticky Header
    // =========================================
    function initStickyHeader() {
        if (!settings.stickyEnable || !header) return;

        const headerHeight = header.offsetHeight;
        let placeholder = document.querySelector('.blog-over-header-placeholder');

        if (!placeholder) {
            placeholder = document.createElement('div');
            placeholder.className = 'blog-over-header-placeholder';
            placeholder.style.height = headerHeight + 'px';
            header.parentNode.insertBefore(placeholder, header.nextSibling);
        }

        function handleScroll() {
            const scrollY = window.scrollY || window.pageYOffset;

            if (scrollY > settings.stickyOffset) {
                header.classList.add('is-sticky');
                placeholder.classList.add('active');

                // Dynamically calculate top offset for admin bar and announcement bar
                let topOffset = 0;

                const adminBar = document.getElementById('wpadminbar');
                if (adminBar) {
                    topOffset += adminBar.offsetHeight;
                }

                const announcementBar = document.querySelector('.blog-over-announcement-sticky');
                if (announcementBar) {
                    topOffset += announcementBar.offsetHeight;
                }

                header.style.top = topOffset + 'px';

            } else {
                header.classList.remove('is-sticky');
                placeholder.classList.remove('active');
                header.style.top = '';
            }
        }

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

    // =========================================
    // Mobile Menu Toggle
    // =========================================
    function initMobileMenu() {
        if (!mobileToggle || !mobileMenu) return;

        mobileToggle.addEventListener('click', function () {
            const isExpanded = this.getAttribute('aria-expanded') === 'true';

            this.setAttribute('aria-expanded', !isExpanded);
            this.classList.toggle('active');
            mobileMenu.classList.toggle('active');
            document.body.classList.toggle('blog-over-menu-open');

            if (!isExpanded) {
                // Menu is opening - focus close button or first item
                setTimeout(function () {
                    if (mobileClose) {
                        mobileClose.focus();
                    } else {
                        const firstLink = mobileMenu.querySelector('.blog-over-menu-link');
                        if (firstLink) firstLink.focus();
                    }
                }, 50);

                // Enable focus trap
                enableFocusTrap();
            } else {
                // Menu is closing - return focus to toggle
                disableFocusTrap();
            }
        });

        if (mobileClose) {
            mobileClose.addEventListener('click', closeMobileMenu);
        }

        // Close on Escape key
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && mobileMenu.classList.contains('active')) {
                closeMobileMenu();
            }
        });

        // Close when clicking overlay (if body has menu-open class)
        mobileMenu.addEventListener('click', function (e) {
            if (e.target === mobileMenu) {
                closeMobileMenu();
            }
        });
    }

    function closeMobileMenu() {
        if (mobileToggle) {
            mobileToggle.setAttribute('aria-expanded', 'false');
            mobileToggle.classList.remove('active');
        }
        if (mobileMenu) {
            mobileMenu.classList.remove('active');
            // Close all open submenus when closing menu
            closeAllDropdowns();
        }
        document.body.classList.remove('blog-over-menu-open');
        disableFocusTrap();
        // Return focus to toggle button per WordPress guidelines
        if (mobileToggle) {
            setTimeout(function () {
                mobileToggle.focus();
            }, 10);
        }
    }

    // =========================================
    // Focus Trap for Mobile Menu (WordPress Accessibility)
    // =========================================
    let focusTrapHandler = null;

    function enableFocusTrap() {
        if (!mobileMenu) return;

        focusTrapHandler = function (e) {
            if (e.key !== 'Tab') return;
            if (!mobileMenu.classList.contains('active')) return;

            // Get all currently focusable elements in mobile menu
            const focusableSelector =
                'a[href]:not([tabindex="-1"]), ' +
                'button:not([disabled]):not([tabindex="-1"]), ' +
                'input:not([disabled]):not([tabindex="-1"]), ' +
                '[tabindex="0"], ' +
                '.blog-over-menu-link, ' +
                '.blog-over-dropdown-toggle:not([tabindex="-1"]), ' +
                '.blog-over-mobile-close';

            const allFocusable = Array.from(mobileMenu.querySelectorAll(focusableSelector))
                .filter(el => el.offsetParent !== null); // Only visible elements

            if (allFocusable.length === 0) return;

            const firstFocusable = allFocusable[0];
            const lastFocusable = allFocusable[allFocusable.length - 1];
            const activeEl = document.activeElement;

            // Shift+Tab on first element -> go to last
            if (e.shiftKey) {
                if (activeEl === firstFocusable || !mobileMenu.contains(activeEl)) {
                    e.preventDefault();
                    lastFocusable.focus();
                }
            }
            // Tab on last element -> go to first
            else {
                if (activeEl === lastFocusable || !mobileMenu.contains(activeEl)) {
                    e.preventDefault();
                    firstFocusable.focus();
                }
            }
        };

        // Use capture phase to intercept Tab before it moves focus
        document.addEventListener('keydown', focusTrapHandler, true);
    }

    function disableFocusTrap() {
        if (focusTrapHandler) {
            document.removeEventListener('keydown', focusTrapHandler, true);
            focusTrapHandler = null;
        }
    }

    // =========================================
    // Dropdown Toggles (Click for touch, plus buttons)
    // =========================================
    function initDropdownToggles() {
        dropdownToggles.forEach(function (toggle) {
            toggle.addEventListener('click', function (e) {
                e.preventDefault();
                e.stopPropagation();

                const parentItem = this.closest('.blog-over-has-dropdown, .menu-item-has-children');
                toggleDropdown(parentItem, this);
            });

            // Keyboard: Enter/Space on toggle button
            toggle.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    e.stopPropagation();

                    const parentItem = this.closest('.blog-over-has-dropdown, .menu-item-has-children');
                    const wasOpen = parentItem.classList.contains('submenu-open');

                    toggleDropdown(parentItem, this);

                    // If we just opened, focus first submenu link
                    if (!wasOpen && parentItem.classList.contains('submenu-open')) {
                        const submenu = parentItem.querySelector('.blog-over-sub-menu, .sub-menu');
                        if (submenu) {
                            const firstLink = submenu.querySelector('a');
                            if (firstLink) {
                                setTimeout(function () {
                                    firstLink.focus();
                                }, 50);
                            }
                        }
                    }
                }

                // Arrow Down: Open submenu and focus first item
                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    const parentItem = this.closest('.blog-over-has-dropdown, .menu-item-has-children');

                    if (!parentItem.classList.contains('submenu-open')) {
                        openDropdown(parentItem, this);
                    }

                    const submenu = parentItem.querySelector('.blog-over-sub-menu, .sub-menu');
                    if (submenu) {
                        const firstLink = submenu.querySelector('a');
                        if (firstLink) firstLink.focus();
                    }
                }

                // Escape: Close submenu and focus toggle
                if (e.key === 'Escape') {
                    e.preventDefault();
                    const parentItem = this.closest('.blog-over-has-dropdown, .menu-item-has-children');
                    closeDropdown(parentItem, this);
                    this.focus();
                }
            });
        });

        // Close dropdowns when clicking outside
        document.addEventListener('click', function (e) {
            if (!e.target.closest('.blog-over-has-dropdown, .menu-item-has-children')) {
                closeAllDropdowns();
            }
        });
    }

    function toggleDropdown(parentItem, toggle) {
        if (parentItem.classList.contains('submenu-open')) {
            closeDropdown(parentItem, toggle);
        } else {
            // Close sibling open dropdowns first
            closeSiblingDropdowns(parentItem);
            openDropdown(parentItem, toggle);
        }
    }

    function openDropdown(parentItem, toggle) {
        const submenu = parentItem.querySelector('.blog-over-sub-menu, .sub-menu');

        parentItem.classList.add('submenu-open');
        if (toggle) toggle.setAttribute('aria-expanded', 'true');
        if (submenu) {
            submenu.setAttribute('aria-hidden', 'false');
            // Make submenu links focusable
            setSubmenuTabIndex(submenu, 0);
        }
    }

    function closeDropdown(parentItem, toggle) {
        const submenu = parentItem.querySelector('.blog-over-sub-menu, .sub-menu');

        parentItem.classList.remove('submenu-open');
        parentItem.classList.remove('blog-over-focus');
        if (toggle) toggle.setAttribute('aria-expanded', 'false');
        if (submenu) {
            submenu.setAttribute('aria-hidden', 'true');
            // Make submenu links not focusable via Tab
            setSubmenuTabIndex(submenu, -1);
        }
    }

    function closeSiblingDropdowns(currentItem) {
        const parent = currentItem.parentNode;
        if (!parent) return;

        const siblings = parent.querySelectorAll(':scope > .submenu-open');
        siblings.forEach(function (sibling) {
            if (sibling !== currentItem) {
                const toggle = sibling.querySelector(':scope > .blog-over-dropdown-toggle');
                closeDropdown(sibling, toggle);
            }
        });
    }

    function closeAllDropdowns() {
        hasDropdownItems.forEach(function (item) {
            const toggle = item.querySelector(':scope > .blog-over-dropdown-toggle');
            closeDropdown(item, toggle);
        });
    }

    function setSubmenuTabIndex(submenu, tabIndex) {
        const links = submenu.querySelectorAll('a');
        links.forEach(function (link) {
            link.setAttribute('tabindex', tabIndex);
        });

        const toggles = submenu.querySelectorAll('.blog-over-dropdown-toggle');
        toggles.forEach(function (toggle) {
            toggle.setAttribute('tabindex', tabIndex);
        });
    }

    // =========================================
    // Keyboard Navigation for Submenu Items
    // =========================================
    function initKeyboardNav() {
        // Global Escape key closes all dropdowns
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') {
                closeAllDropdowns();
            }
        });

        // Add keyboard handlers to parent menu links
        hasDropdownItems.forEach(function (item) {
            const link = item.querySelector(':scope > .blog-over-menu-link, :scope > a');
            const toggle = item.querySelector(':scope > .blog-over-dropdown-toggle');
            const submenu = item.querySelector(':scope > .blog-over-sub-menu, :scope > .sub-menu');

            if (link) {
                link.addEventListener('keydown', function (e) {
                    // Arrow Right: Open submenu
                    if (e.key === 'ArrowRight' && submenu) {
                        e.preventDefault();
                        openDropdown(item, toggle);
                        const firstLink = submenu.querySelector('a');
                        if (firstLink) firstLink.focus();
                    }

                    // Arrow Down: Move to toggle button or first submenu item
                    if (e.key === 'ArrowDown') {
                        e.preventDefault();
                        if (toggle) {
                            toggle.focus();
                        } else if (submenu) {
                            openDropdown(item, toggle);
                            const firstLink = submenu.querySelector('a');
                            if (firstLink) firstLink.focus();
                        }
                    }
                });

                // REMOVED: Focus-based auto-expand
                // Submenus now only open via Enter/Space on toggle, Arrow keys, or hover
            }

            // Add keyboard handlers to submenu links
            if (submenu) {
                const submenuLinks = submenu.querySelectorAll(':scope > li > a');
                submenuLinks.forEach(function (subLink, index) {
                    subLink.addEventListener('keydown', function (e) {
                        const allLinks = Array.from(submenu.querySelectorAll(':scope > li > a'));
                        const currentIndex = allLinks.indexOf(subLink);

                        // Arrow Down: Next submenu item
                        if (e.key === 'ArrowDown') {
                            e.preventDefault();
                            if (currentIndex < allLinks.length - 1) {
                                allLinks[currentIndex + 1].focus();
                            }
                        }

                        // Arrow Up: Previous item or back to toggle/parent
                        if (e.key === 'ArrowUp') {
                            e.preventDefault();
                            if (currentIndex > 0) {
                                allLinks[currentIndex - 1].focus();
                            } else {
                                // First item - go back to toggle or link
                                if (toggle) {
                                    toggle.focus();
                                } else if (link) {
                                    link.focus();
                                }
                            }
                        }

                        // Arrow Left or Escape: Close submenu, return to parent
                        if (e.key === 'ArrowLeft' || e.key === 'Escape') {
                            e.preventDefault();
                            closeDropdown(item, toggle);
                            if (toggle) {
                                toggle.focus();
                            } else if (link) {
                                link.focus();
                            }
                        }
                    });
                });
            }
        });
    }

    // =========================================
    // Initialize Submenu Tab Indices
    // =========================================
    function initSubmenuTabIndices() {
        // Initially make all submenu links non-focusable via Tab
        hasDropdownItems.forEach(function (item) {
            const submenu = item.querySelector('.blog-over-sub-menu, .sub-menu');
            if (submenu) {
                setSubmenuTabIndex(submenu, -1);
            }
        });
    }

    // =========================================
    // Hover Intent (Desktop only)
    // =========================================
    function initHoverIntent() {
        if (window.innerWidth < settings.mobileBreakpoint) return;

        hasDropdownItems.forEach(function (item) {
            // Do not bind hover intent to items inside the mobile menu
            if (item.closest('.blog-over-mobile-menu')) return;

            let timeout;
            const toggle = item.querySelector(':scope > .blog-over-dropdown-toggle');

            item.addEventListener('mouseenter', function () {
                clearTimeout(timeout);
                openDropdown(item, toggle);
            });

            item.addEventListener('mouseleave', function () {
                timeout = setTimeout(function () {
                    closeDropdown(item, toggle);
                }, 150); // Small delay for better UX
            });
        });
    }

    // =========================================
    // Initialize
    // =========================================
    function init() {
        initStickyHeader();
        initMobileMenu();
        initSubmenuTabIndices();
        initDropdownToggles();
        initKeyboardNav();
        initHoverIntent();
    }

    // Run on DOMContentLoaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    // Re-init hover on resize
    let resizeTimer;
    window.addEventListener('resize', function () {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () {
            initHoverIntent();
        }, 250);
    });

})();
