document.addEventListener('DOMContentLoaded', function() {
    const dropdown = document.getElementById('services-dropdown');
    const button = document.getElementById('services-menu-button');
    const menu = dropdown.querySelector('div[role="menu"]');
    let menuTimeout;
    let isMouseOverMenu = false;
    let isMouseOverButton = false;

    // Show menu on hover
    dropdown.addEventListener('mouseenter', function() {
        isMouseOverButton = true;
        clearTimeout(menuTimeout);
        menu.classList.remove('hidden');
        button.setAttribute('aria-expanded', 'true');
    });

    dropdown.addEventListener('mouseleave', function() {
        isMouseOverButton = false;
        closeMenuWithDelay();
    });

    // Menu hover events
    menu.addEventListener('mouseenter', function() {
        isMouseOverMenu = true;
        clearTimeout(menuTimeout);
        menu.classList.remove('hidden');
    });

    menu.addEventListener('mouseleave', function() {
        isMouseOverMenu = false;
        closeMenuWithDelay();
    });

    // Click events for better mobile support
    button.addEventListener('click', function(e) {
        e.stopPropagation();
        if (menu.classList.contains('hidden')) {
            menu.classList.remove('hidden');
            button.setAttribute('aria-expanded', 'true');
        } else {
            menu.classList.add('hidden');
            button.setAttribute('aria-expanded', 'false');
        }
    });

    // Close menu when clicking outside
    document.addEventListener('click', function(event) {
        if (!dropdown.contains(event.target)) {
            menu.classList.add('hidden');
            button.setAttribute('aria-expanded', 'false');
        }
    });

    // Close menu with delay if mouse is not over menu or button
    function closeMenuWithDelay() {
        clearTimeout(menuTimeout);
        menuTimeout = setTimeout(function() {
            if (!isMouseOverMenu && !isMouseOverButton) {
                menu.classList.add('hidden');
                button.setAttribute('aria-expanded', 'false');
            }
        }, 800); // 800ms delay before closing
    }

    // Close menu when clicking on a menu item (optional)
    const menuItems = menu.querySelectorAll('a');
    menuItems.forEach(item => {
        item.addEventListener('click', function() {
            menu.classList.add('hidden');
            button.setAttribute('aria-expanded', 'false');
        });
    });
});
