document.addEventListener("alpine:init", () => {

    // Register the aesthetic picker component (custom aesthetic editor).
    Alpine.data('aestheticPicker', (initialAesthetic, isAestheticField, initialCss = '') => ({
        isCustom: initialAesthetic === 'custom',
        selected: initialAesthetic,
        baseTheme: '',
        cssContent: initialCss,
        themeCssCache: {},
        isAestheticField,

        init() {
            // Nothing auto-loads. The user must click "Load Base Theme" to import CSS.
        },

        async loadBaseTheme() {
            const slug = this.baseTheme;
            if (!slug) return;

            if (this.themeCssCache[slug]) {
                this.cssContent = this.cssContent
                    ? this.cssContent + '\n\n' + this.themeCssCache[slug]
                    : this.themeCssCache[slug];
                return;
            }

            try {
                const response = await fetch(FastFuzzySearch.ajax_url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'fast_fuzzy_search_get_theme_css',
                        theme: slug,
                        security: FastFuzzySearch._wpnonce,
                    }),
                });
                const result = await response.json();
                if (result.success) {
                    // Replace all theme-scoped selectors with .fast-fuzzy-search--custom
                    const transformed = result.data.css.replace(
                        new RegExp('\\.fast-fuzzy-search--' + slug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?=[\\s\\.\\,\\:\\>\\[\\]\\(\\)\\.\\{]|$)', 'g'),
                        '.fast-fuzzy-search--custom'
                    );
                    this.themeCssCache[slug] = transformed;
                    this.cssContent = transformed;
                }
            } catch (e) {
                console.error('Fast Fuzzy Search: failed to load theme CSS', e);
            }
        },

        onRadioChange(value) {
            this.selected = value;
            this.isCustom = value === 'custom';
            if (!this.isCustom) {
                this.cssContent = '';
            }
        },
    }));

    // Register the search-index stats Alpine component.
    Alpine.data("stats", () => ({
        query: '',
        resultsVisible: false,
        searchResults: [],
        activeResultIndex: 0,
        selected: null,
        items: [],
        data: [],
        haystack: [],
        size: 0,
        groupedData: {},
        state: 'loading',
        stateLabels: {
            idle: 'Idle',
            loading: 'Loading…',
            deleting: 'Deleting…',
            rebuilding: 'Rebuilding…',
        },
        async init() {
            this.state = 'loading';
            this.fetchData();
        },

        async fetchData() {
            try {
                const response = await fetch(FastFuzzySearch.ajax_url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: FastFuzzySearch.ajax_action,
                        security: FastFuzzySearch._wpnonce,
                    }),
                });

                if (response.ok) {
                    const json = await response.json();

                    const jsonString = JSON.stringify(json);
                    const sizeInBytes = new TextEncoder().encode(jsonString).length;

                    this.size = (sizeInBytes / (1024 * 1024)).toFixed(3);
                    this.haystack = json.haystack;
                    this.data = json.data;

                    this.groupedData = this.data.reduce((acc, item) => {
                        const key = item.type;
                        if (!acc[key]) {
                            acc[key] = [];
                        }
                        acc[key].push(item);
                        return acc;
                    }, {});
                }
            } catch (error) {
                console.error('Error:', error);
            } finally {
                this.state = 'idle';
            }
        },

        async refreshIndex() {
            this.state = 'deleting';

            try {
                await fetch(FastFuzzySearch.ajax_url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'fast_fuzzy_search_delete_posts_search_index',
                        security: FastFuzzySearch._wpnonce,
                    }),
                });
            } catch (error) {
                console.error('Error:', error);
            } finally {
                this.state = 'rebuilding';
                await this.fetchData();
                this.state = 'idle';
            }
        },
    }));

    // Tab navigation: switch panels when a tab is clicked.
    document.addEventListener('click', (event) => {
        const tab = event.target.closest('.ffs-tab[data-tab-target]');
        if (!tab) return;

        const target = tab.getAttribute('data-tab-target');
        const tabsContainer = tab.parentElement;

        tabsContainer.querySelectorAll('.ffs-tab').forEach((el) => {
            const isActive = el === tab;
            el.classList.toggle('is-active', isActive);
            el.setAttribute('aria-selected', isActive ? 'true' : 'false');
        });

        const panelSelector = `.ffs-tab-panel[data-tab-panel="${target}"]`;
        document.querySelectorAll('.ffs-tab-panel').forEach((panel) => {
            panel.classList.toggle('is-active', panel.matches(panelSelector));
        });
    });

    // Keyboard support for the page-level tabs AND the segmented controls.
    document.addEventListener('keydown', (event) => {
        const active = document.activeElement;
        if (!active) return;

        // Page-level tabs (.ffs-tab[data-tab-target])
        if (active.classList && active.classList.contains('ffs-tab')) {
            const tabsContainer = active.parentElement;
            if (!tabsContainer) return;
            const tabs = Array.from(tabsContainer.querySelectorAll('.ffs-tab[data-tab-target]'));
            const idx = tabs.indexOf(active);
            if (idx === -1) return;

            let next = null;
            if (event.key === 'ArrowRight') next = (idx + 1) % tabs.length;
            if (event.key === 'ArrowLeft')  next = (idx - 1 + tabs.length) % tabs.length;
            if (event.key === 'Home')       next = 0;
            if (event.key === 'End')        next = tabs.length - 1;

            if (next !== null) {
                event.preventDefault();
                tabs[next].focus();
                tabs[next].click();
            }
            return;
        }

        // Segmented control pills (.ffs-segmented__option)
        if (active.classList && active.classList.contains('ffs-segmented__option')) {
            const group = active.parentElement;
            if (!group || !group.classList || !group.classList.contains('ffs-segmented')) return;
            const options = Array.from(group.querySelectorAll('.ffs-segmented__option:not([disabled])'));
            const idx = options.indexOf(active);
            if (idx === -1) return;

            // Space / Enter: let the native label-to-radio activation run; just suppress page scroll on Space.
            if (event.key === ' ' || event.key === 'Spacebar') {
                event.preventDefault();
                active.click();
                return;
            }
            if (event.key === 'Enter') {
                event.preventDefault();
                active.click();
                return;
            }

            let next = null;
            if (event.key === 'ArrowRight') next = (idx + 1) % options.length;
            if (event.key === 'ArrowLeft')  next = (idx - 1 + options.length) % options.length;
            if (event.key === 'Home')       next = 0;
            if (event.key === 'End')        next = options.length - 1;

            if (next !== null) {
                event.preventDefault();
                options[next].focus();
                options[next].click();
            }
        }
    });
});
