export class AccordionState {
    constructor(selector = "details.sidebar__accordion", storageKey = "accordion-state") {
        this.selector = selector;
        this.storageKey = storageKey;
        this.accordions = document.querySelectorAll(this.selector);
        this.init();
    }
    init() {
        this.restoreState();
        this.attachListeners();
    }
    getAccordionId(accordion, index) {
        const summary = accordion.querySelector("summary");
        const heading = summary?.querySelector("h2, h3");
        if (accordion.id) {
            return accordion.id;
        }
        if (heading?.textContent) {
            return heading.textContent
                .toLowerCase()
                .trim()
                .replace(/[^a-z0-9]+/g, "-")
                .replace(/^-|-$/g, "");
        }
        return `accordion-${index}`;
    }
    getState() {
        const state = {};
        this.accordions.forEach((accordion, index) => {
            const id = this.getAccordionId(accordion, index);
            state[id] = accordion.open;
        });
        return state;
    }
    saveState() {
        try {
            const state = this.getState();
            localStorage.setItem(this.storageKey, JSON.stringify(state));
        }
        catch (e) {
            console.warn("AccordionState: Could not save state", e);
        }
    }
    restoreState() {
        try {
            const savedState = localStorage.getItem(this.storageKey);
            if (!savedState) {
                return;
            }
            const state = JSON.parse(savedState);
            this.accordions.forEach((accordion, index) => {
                const id = this.getAccordionId(accordion, index);
                if (id in state) {
                    accordion.open = state[id];
                }
            });
        }
        catch (e) {
            console.warn("AccordionState: Could not restore state", e);
        }
    }
    attachListeners() {
        this.accordions.forEach((accordion) => {
            accordion.addEventListener("toggle", () => {
                this.saveState();
            });
        });
    }
    clearState() {
        try {
            localStorage.removeItem(this.storageKey);
        }
        catch (e) {
            console.warn("AccordionState: Could not clear state", e);
        }
    }
    expandAll() {
        this.accordions.forEach((accordion) => {
            accordion.open = true;
        });
        this.saveState();
    }
    collapseAll() {
        this.accordions.forEach((accordion) => {
            accordion.open = false;
        });
        this.saveState();
    }
}
export default AccordionState;
//# sourceMappingURL=AccordionState.js.map