/*!
 * Copyright (c) 2018, 2023 Eclipse Foundation, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * Contributors:
 *   Christopher Guindon <chris.guindon@eclipse-foundation.org>
 *   Olivier Goulet <olivier.goulet@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

const handleCollapse = (element) => {
    const iconElement = element.querySelector('.main-sidebar-item-icon');

    if (element.getAttribute('aria-expanded') === 'true') {
        iconElement?.classList.remove('fa-chevron-down');
        iconElement?.classList.add('fa-chevron-up');
    } else {
        iconElement?.classList.remove('fa-chevron-up');
        iconElement?.classList.add('fa-chevron-down');
    }
}

const setupObserver = (mutationList) => {
    for (const mutation of mutationList) {
        handleCollapse(mutation.target);
    }
}

const eclipseFdnSidebar = {
    run: () => {
        const menuItemCollapseToggleElement = Array.from(
            document.querySelectorAll('.main-sidebar-item a')
        );
        if (menuItemCollapseToggleElement.length === 0) return;
        
        // Listen for aria-expanded changes on each menu item
        const observer = new MutationObserver(setupObserver);
        menuItemCollapseToggleElement.forEach(menuItem => {
            observer.observe(menuItem, { 
                attributes: true, 
                attributeFilter: ['aria-expanded']
            });
        });
    }
}

export default eclipseFdnSidebar;