/**
 * Settings > Notifications — notification preferences
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

export default function NotificationsSection() {
    const [prefs, setPrefs] = useState(null);
    const [saving, setSaving] = useState({});

    const load = useCallback(async () => {
        try {
            const data = await sw.api.notifications.prefs();
            // Normalize: could be an array of { type, enabled, ... } or an object keyed by type
            if (Array.isArray(data)) {
                const obj = {};
                data.forEach(p => { obj[p.type] = p; });
                setPrefs(obj);
            } else {
                setPrefs(data || {});
            }
        } catch (e) { sw.toast(e.message, 'error'); setPrefs({}); }
    }, []);

    useEffect(() => { load(); }, []);

    async function togglePref(type, currentEnabled) {
        setSaving(prev => ({ ...prev, [type]: true }));
        try {
            await sw.api.notifications.setPref(type, { enabled: !currentEnabled });
            setPrefs(prev => ({
                ...prev,
                [type]: { ...prev[type], enabled: !currentEnabled },
            }));
            sw.toast('Preference updated', 'success');
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setSaving(prev => ({ ...prev, [type]: false })); }
    }

    async function resetPref(type) {
        setSaving(prev => ({ ...prev, [type]: true }));
        try {
            await sw.api.notifications.delPref(type);
            sw.toast('Reset to default', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setSaving(prev => ({ ...prev, [type]: false })); }
    }

    if (prefs === null) return html`<div class="settings-placeholder">Loading\u2026</div>`;

    const types = Object.keys(prefs);

    function friendlyName(type) {
        return type
            .replace(/_/g, ' ')
            .replace(/\b\w/g, c => c.toUpperCase());
    }

    return html`
        <div>
            ${types.length === 0 && html`<div class="empty-hint">No notification preferences available.</div>`}

            <div class="admin-list">
                ${types.map(type => {
                    const pref = prefs[type];
                    const enabled = pref.enabled !== false;
                    const isSaving = saving[type];
                    return html`
                        <div class="admin-surface-row" key=${type}>
                            <div style="flex:1;min-width:0;">
                                <strong>${friendlyName(type)}</strong>
                                ${pref.description && html`
                                    <div class="text-muted" style="font-size:12px;margin-top:2px;">${pref.description}</div>
                                `}
                            </div>
                            <label class="toggle-label" style="margin:0;">
                                <input type="checkbox"
                                       checked=${enabled}
                                       disabled=${isSaving}
                                       onChange=${() => togglePref(type, enabled)} />
                                <span class="toggle-track"></span>
                            </label>
                            <button class="btn-small btn-ghost"
                                    disabled=${isSaving}
                                    onClick=${() => resetPref(type)}
                                    title="Reset to default">
                                Reset
                            </button>
                        </div>
                    `;
                })}
            </div>
        </div>
    `;
}
