(() => {
    if (typeof window === 'undefined') {
        return;
    }

    if (window.__tenantpilotSidebarStoreFallbackApplied) {
        return;
    }

    window.__tenantpilotSidebarStoreFallbackApplied = true;

    const ensureSidebarStore = () => {
        const Alpine = window.Alpine;

        if (!Alpine || typeof Alpine.store !== 'function') {
            return false;
        }

        try {
            const existing = Alpine.store('sidebar');

            if (existing && typeof existing === 'object') {
                return true;
            }
        } catch {
            // Alpine.store('sidebar') can throw if stores aren't ready yet.
        }

        const storeFactory = () => {
            return {
                isOpen: true,
                isOpenDesktop: true,
                collapsedGroups: [],

                resizeObserver: null,

                init() {
                    this.setUpResizeObserver();

                    document.addEventListener('livewire:navigated', () => {
                        this.setUpResizeObserver();
                    });
                },

                setUpResizeObserver() {
                    if (typeof ResizeObserver === 'undefined') {
                        return;
                    }

                    if (this.resizeObserver) {
                        this.resizeObserver.disconnect();
                    }

                    let previousWidth = window.innerWidth;

                    this.resizeObserver = new ResizeObserver(() => {
                        const currentWidth = window.innerWidth;

                        const wasDesktop = previousWidth >= 1024;
                        const isNowMobile = currentWidth < 1024;
                        const isNowDesktop = currentWidth >= 1024;

                        if (wasDesktop && isNowMobile) {
                            this.isOpenDesktop = this.isOpen;

                            if (this.isOpen) {
                                this.close();
                            }
                        } else if (!wasDesktop && isNowDesktop) {
                            this.isOpen = this.isOpenDesktop;
                        }

                        previousWidth = currentWidth;
                    });

                    this.resizeObserver.observe(document.body);

                    if (window.innerWidth < 1024) {
                        if (this.isOpen) {
                            this.isOpenDesktop = true;
                            this.close();
                        }
                    } else {
                        this.isOpenDesktop = this.isOpen;
                    }
                },

                groupIsCollapsed(label) {
                    if (!Array.isArray(this.collapsedGroups)) {
                        this.collapsedGroups = [];
                    }

                    return this.collapsedGroups.includes(label);
                },

                collapseGroup(label) {
                    if (!this.groupIsCollapsed(label)) {
                        this.collapsedGroups = this.collapsedGroups.concat(label);
                    }
                },

                toggleCollapsedGroup(label) {
                    if (this.groupIsCollapsed(label)) {
                        this.collapsedGroups = this.collapsedGroups.filter((item) => item !== label);
                    } else {
                        this.collapsedGroups = this.collapsedGroups.concat(label);
                    }
                },

                close() {
                    this.isOpen = false;

                    if (window.innerWidth >= 1024) {
                        this.isOpenDesktop = false;
                    }
                },

                open() {
                    this.isOpen = true;

                    if (window.innerWidth >= 1024) {
                        this.isOpenDesktop = true;
                    }
                },
            };
        };

        try {
            Alpine.store('sidebar', storeFactory());

            return true;
        } catch {
            return false;
        }
    };

    const tryEnsure = () => {
        ensureSidebarStore();
    };

    window.addEventListener('alpine:init', tryEnsure);
    window.addEventListener('alpine:initialized', tryEnsure);
    document.addEventListener('alpine:init', tryEnsure);
    document.addEventListener('alpine:initialized', tryEnsure);
    document.addEventListener('livewire:navigated', tryEnsure);

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', tryEnsure, { once: true });
    } else {
        tryEnsure();
    }

    let tries = 0;
    const maxTries = 50;

    const timer = setInterval(() => {
        tries += 1;

        if (ensureSidebarStore() || tries >= maxTries) {
            clearInterval(timer);
        }
    }, 100);
})();
