// Settings → Autoplay toggle (Alpine carve-out KL-133). Tiny module:
// one toggle, one status line, one POST. Carved out of settings.js.

function storeDefinition() {
    return {
        enabled: false,
        statusText: 'Loading…',

        get statusClass() {
            return this.enabled ? 'set-env' : 'unset';
        },

        applyState(enabled) {
            this.enabled = !!enabled;
            this.statusText = this.enabled
                ? 'On — engine runs at launch'
                : 'Off — starts stopped';
        },

        async refresh() {
            try {
                const resp = await fetch('/api/settings/autoplay');
                const data = await resp.json();
                this.applyState(data.enabled);
            } catch (_) { /* non-critical */ }
        },

        async save(enabled) {
            try {
                const resp = await fetch('/api/settings/autoplay', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({enabled}),
                });
                const data = await resp.json();
                this.applyState(data.enabled);
            } catch (_) { /* non-critical */ }
        },
    };
}

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

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

export function initAutoplay() {
    let store = ensureStore();
    if (!store) {
        document.addEventListener('alpine:init', () => {
            ensureStore()?.refresh();
        }, {once: true});
        return;
    }
    store.refresh();
}
