// First-launch Govee onboarding nudge. If the user has no devices
// configured yet, run a silent LAN scan and — if anything replies —
// offer a single-click "Add them all and turn Govee on" toast.
//
// Lifecycle rules, same as starter_cta: session-scoped dismiss (once
// you click Not now, it stays quiet until the tab closes). Runs only
// when the devices list is empty; once the user has configured lights
// the toast never fires again even if they delete them later this
// session.

import {pushToast, dismissToast, registerToastAction} from './toasts.js';

const DISMISS_KEY = 'conductor.govee_cta.dismissed';
const TOAST_KEY = 'govee-first-launch-cta';

function markDismissed() {
    try { sessionStorage.setItem(DISMISS_KEY, '1'); } catch (_) {}
}

function dismissed() {
    try { return sessionStorage.getItem(DISMISS_KEY) === '1'; } catch (_) { return false; }
}

async function fetchConfig() {
    try {
        const r = await fetch('/api/govee');
        if (!r.ok) return null;
        return await r.json();
    } catch (_) {
        return null;
    }
}

async function silentScan() {
    try {
        const r = await fetch('/api/govee/scan', {method: 'POST'});
        if (!r.ok) return [];
        const data = await r.json();
        return data.found || [];
    } catch (_) {
        return [];
    }
}

async function autopopulate() {
    try {
        const r = await fetch('/api/govee/autopopulate', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({enable: true}),
        });
        return r.ok ? await r.json() : null;
    } catch (_) {
        return null;
    }
}

export function initGoveeCta() {
    if (dismissed()) return;

    // Delay past initial paint so the Starter toast (if any) lands
    // first and the connection/Mac-audio toasts don't pile up at once.
    setTimeout(async () => {
        if (dismissed()) return;
        const cfg = await fetchConfig();
        if (!cfg) return;
        // Only nudge users who haven't configured anything yet. If they
        // already have devices, they've been here before — no toast.
        if ((cfg.devices || []).length > 0) return;

        const found = await silentScan();
        if (!found.length) return;

        const count = found.length;
        const label = count === 1 ? 'light' : 'lights';

        registerToastAction('govee-cta-add', async () => {
            markDismissed();
            dismissToast(TOAST_KEY);
            const result = await autopopulate();
            if (result && result.added) {
                pushToast({
                    key: 'govee-cta-added',
                    level: 'info',
                    title: `Added ${result.added} Govee ${result.added === 1 ? 'light' : 'lights'}`,
                    detail: 'Restart Conductør to start driving them.',
                });
            } else if (result) {
                pushToast({
                    key: 'govee-cta-added',
                    level: 'warn',
                    title: 'Nothing added',
                    detail: 'The scan came up empty that time — try again from the Govee tab.',
                });
            }
        });
        registerToastAction('govee-cta-later', () => {
            markDismissed();
            dismissToast(TOAST_KEY);
        });

        pushToast({
            key: TOAST_KEY,
            level: 'info',
            title: `Found ${count} Govee ${label} on your network`,
            detail: 'Add them all and turn Govee on?',
            actions: [
                {id: 'govee-cta-add', label: `Add ${count === 1 ? 'it' : 'all'} & turn on`},
                {id: 'govee-cta-later', label: 'Not now'},
            ],
            dismissible: false,
        });
    }, 4000);
}
