/*!
 * @file download_button.js
 * @brief Download dropdown button behavior for Shibuya theme header bar (A9OD-607)
 * @details Manages the expand/collapse of the Download dropdown panel in the header.
 *          Implements the WAI-ARIA menu button pattern:
 *          - Click or ArrowDown/Enter/Space opens the panel and focuses the first item.
 *          - Escape closes the panel and returns focus to the trigger.
 *          - ArrowDown/ArrowUp moves focus between menu items (wrapping).
 *          - Tab closes the panel and lets focus continue naturally.
 *          - Outside click closes the panel without returning focus.
 * @author STMicroelectronics
 * @copyright Copyright (c) 2026 STMicroelectronics.
 *            All rights reserved.
 *            This software is licensed under SLA0044 terms that can be found at:
 *            https://www.st.com/SLA0044
 *            or in the LICENSE.md file in the root directory of this software component.
 */
(function () {
    'use strict';

    const initDownloadButton = () => {
        const trigger = document.getElementById('sy-download-trigger');
        if (!trigger) return;

        const panel = document.getElementById('sy-download-panel');
        if (!panel) return;

        console.debug('[download_button] initializing');

        const getMenuItems = () => Array.from(panel.querySelectorAll('[role="menuitem"]'));

        const isOpen = () => !panel.hasAttribute('hidden');

        const openPanel = () => {
            panel.removeAttribute('hidden');
            trigger.setAttribute('aria-expanded', 'true');
            console.debug('[download_button] panel opened');
            const items = getMenuItems();
            if (items.length > 0) {
                items[0].focus();
            }
        };

        const closePanel = (returnFocus) => {
            panel.setAttribute('hidden', '');
            trigger.setAttribute('aria-expanded', 'false');
            console.debug('[download_button] panel closed');
            if (returnFocus) {
                trigger.focus();
            }
        };

        // --- Trigger: click toggles the panel ---
        trigger.addEventListener('click', (ev) => {
            ev.stopPropagation();
            if (isOpen()) {
                closePanel(false);
            } else {
                openPanel();
            }
        });

        // --- Trigger: keyboard opens panel (ArrowDown also opens + focuses first item) ---
        trigger.addEventListener('keydown', (ev) => {
            if (ev.key === 'ArrowDown') {
                ev.preventDefault();
                if (!isOpen()) {
                    openPanel();
                } else {
                    const items = getMenuItems();
                    if (items.length > 0) {
                        items[0].focus();
                    }
                }
            } else if (ev.key === 'Escape' && isOpen()) {
                ev.preventDefault();
                closePanel(true);
            }
        });

        // --- Panel: arrow-key navigation and Escape/Tab handling ---
        panel.addEventListener('keydown', (ev) => {
            const items = getMenuItems();
            const idx = items.indexOf(document.activeElement);

            switch (ev.key) {
                case 'ArrowDown':
                    ev.preventDefault();
                    items[(idx < items.length - 1) ? idx + 1 : 0].focus();
                    break;
                case 'ArrowUp':
                    ev.preventDefault();
                    items[(idx > 0) ? idx - 1 : items.length - 1].focus();
                    break;
                case 'Escape':
                    ev.preventDefault();
                    closePanel(true);
                    break;
                case 'Tab':
                    // Let Tab move focus naturally; close panel without stealing focus.
                    closePanel(false);
                    break;
                default:
                    break;
            }
        });

        // --- Document: click outside closes the panel ---
        document.addEventListener('click', (ev) => {
            if (isOpen() && !trigger.contains(ev.target) && !panel.contains(ev.target)) {
                closePanel(false);
            }
        });
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initDownloadButton);
    } else {
        initDownloadButton();
    }
})();

