/**
 * Admin > System > Channels (Archived + Retention)
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

export default function ChannelsSection() {
    const [channels, setChannels] = useState([]);
    const [total, setTotal] = useState(0);
    const [retentionTTL, setRetentionTTL] = useState(0);
    const [ttlDraft, setTTLDraft] = useState('');
    const [loading, setLoading] = useState(true);

    const load = useCallback(async () => {
        try {
            const data = await sw.api.admin.channels.archived();
            setChannels(data.data || []);
            setTotal(data.total || 0);
            const ttl = data.retention_ttl_days || 0;
            setRetentionTTL(ttl);
            setTTLDraft(String(ttl));
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, []);

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

    async function saveTTL() {
        const val = parseInt(ttlDraft, 10);
        if (isNaN(val) || val < 0) { sw.toast('TTL must be 0 or more', 'error'); return; }
        try {
            await sw.api.admin.settings.update('retention_ttl_days', { value: { value: val } });
            setRetentionTTL(val);
            sw.toast('Retention TTL saved', 'success');
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function purge(id, title) {
        const ok = await sw.confirm(`Permanently delete "${title || id}"? This cannot be undone.`, true);
        if (!ok) return;
        try {
            await sw.api.admin.channels.purge(id);
            sw.toast('Channel purged', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

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

    return html`
        <div>
            <div class="stat-cards-grid" style="margin-bottom:16px;">
                <div class="stat-card"><div class="stat-value">${total}</div><div class="stat-label">Archived</div></div>
                <div class="stat-card"><div class="stat-value">${retentionTTL || 'Off'}</div><div class="stat-label">Retention TTL (days)</div></div>
            </div>

            <div class="admin-section" style="margin-bottom:20px;">
                <h4 style="margin:0 0 8px;">Retention Policy</h4>
                <p class="text-muted" style="font-size:12px;margin:0 0 8px;">
                    Channels are archived on delete and purged after this many days.
                    Only Personal (BYOK) provider channels are exempt. Set to 0 to disable retention.
                </p>
                <div style="display:flex;gap:8px;align-items:center;">
                    <input type="number" min="0" value=${ttlDraft}
                        onInput=${e => setTTLDraft(e.target.value)}
                        style="width:80px;padding:6px 8px;background:var(--bg-2);color:var(--text);border:1px solid var(--border);border-radius:4px;"
                        placeholder="0" />
                    <span class="text-muted" style="font-size:12px;">days</span>
                    <button class="btn-small" onClick=${saveTTL}
                        disabled=${String(retentionTTL) === ttlDraft}>Save</button>
                </div>
            </div>

            <h4 style="margin:0 0 8px;">Archived Channels</h4>
            <div class="admin-list">
                ${channels.length === 0 && html`<div class="empty-hint">No archived channels</div>`}
                ${channels.map(c => html`
                    <div class="admin-surface-row" key=${c.id}>
                        <strong style="flex:1;">${c.title || c.id}</strong>
                        <span class="text-muted" style="font-size:11px;">${c.archived_at ? new Date(c.archived_at).toLocaleDateString() : ''}</span>
                        <button class="btn-small btn-danger" onClick=${() => purge(c.id, c.title)}>Purge</button>
                    </div>
                `)}
            </div>
        </div>
    `;
}
