import { getSidebarCustomize } from "../sidebar/getSidebarCustomize.js";

/**
 * In your preview website you can listen if a panel or section got opened or is closed.
 * For example you can show a container or hide if the given container should be customized.
 *
 * This event handler is dirty, that means, `onChange` is also fired for the first state!
 */
function listenPanelExpanded(id: string, onChange: (state: boolean) => void, includeSections = false) {
    const customize = getSidebarCustomize();
    const panel = customize.panel(id) || customize.section(id);

    if (!panel) {
        return false;
    }

    let state = panel.expanded(); // save state ourself because events are also thrown in sub-panels
    const changeState = (should: boolean, e: any) => {
        if (!includeSections && state === should) {
            return;
        }

        if ([`accordion-panel-${id}`, `accordion-section-${id}`].indexOf(e.currentTarget?.id) > -1) {
            onChange(should);
            state = should;
        }
    };

    onChange(state);
    panel.container
        .bind("expanded", (e: any) => {
            changeState(true, e);
        })
        .bind("collapsed", (e: any) => {
            changeState(false, e);
        });

    return true;
}

export { listenPanelExpanded };
