// Tab switcher (KL-120 Alpine conversion). Reactive state lives in
// Alpine.store('tabs'). Tab choice persists to localStorage so a
// refresh keeps you where you were. Panels stay in DOM (toggled via
// the `hidden` attribute) so live meters in offscreen tabs keep their
// state warm — same behavior as the imperative version.

import {trackEvent} from '../js/utils.js';

const STORAGE_KEY = 'conductor.activeTab';

function storeDefinition() {
    return {
        active: 'show',
        init() {
            try {
                const saved = localStorage.getItem(STORAGE_KEY);
                if (saved && document.querySelector(`.tab-panel[data-tab-panel="${saved}"]`)) {
                    this.active = saved;
                }
            } catch (_) {}
        },
        activate(name, fire = true) {
            this.active = name;
            try { localStorage.setItem(STORAGE_KEY, name); } catch (_) {}
            if (fire) {
                const panel = document.querySelector(`.tab-panel[data-tab-panel="${name}"]`);
                const locked = !!(panel && panel.classList.contains('tab-locked'));
                trackEvent('nav.tab_switched', {tab: name, locked});
            }
        },
    };
}

function ensureStore() {
    if (!window.Alpine) return null;
    if (!window.Alpine.store('tabs')) {
        window.Alpine.store('tabs', storeDefinition());
    }
    return window.Alpine.store('tabs');
}

if (window.Alpine) {
    ensureStore();
} else {
    document.addEventListener('alpine:init', ensureStore);
}

// External callers expect this global (dmx_discover.js, govee.js,
// fixtures.js use it to jump the user to a specific tab without
// triggering analytics). Late-bind via the store so calls before
// Alpine init no-op gracefully instead of throwing.
window.conductorActivateTab = (name) => {
    const store = window.Alpine?.store('tabs');
    if (store) store.activate(name, false);
};

// initTabs() preserved as the entry main.js calls. The Alpine store's
// own init() (run automatically when Alpine registers the store)
// handles localStorage hydration; this function is just a stable hook.
export function initTabs() {
    ensureStore();
}
