/**
 * Settings > Memory — personal memory management
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

function fmtDate(d) {
    if (!d) return '\u2014';
    return new Date(d).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' });
}

function truncate(s, len) {
    if (!s) return '';
    return s.length > len ? s.substring(0, len) + '\u2026' : s;
}

export default function MemorySection() {
    const [memories, setMemories] = useState([]);
    const [loading, setLoading] = useState(true);
    const [count, setCount] = useState(0);
    const [editingId, setEditingId] = useState(null);
    const [editValue, setEditValue] = useState('');

    const load = useCallback(async () => {
        try {
            const [data, c] = await Promise.all([
                sw.api.memory.list(),
                sw.api.memory.count().catch(() => null),
            ]);
            setMemories(data || []);
            if (c != null) setCount(typeof c === 'number' ? c : c.count || 0);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, []);

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

    function startEdit(m) {
        setEditingId(m.id);
        setEditValue(m.value || m.content || '');
    }

    function cancelEdit() {
        setEditingId(null);
        setEditValue('');
    }

    async function saveEdit(id) {
        try {
            await sw.api.memory.update(id, { value: editValue, content: editValue });
            sw.toast('Memory updated', 'success');
            setEditingId(null);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function deleteMemory(id) {
        const ok = await sw.confirm('Delete this memory?', true);
        if (!ok) return;
        try {
            await sw.api.memory.del(id);
            sw.toast('Memory deleted', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    function statusBadge(status) {
        if (!status) return null;
        const cls = status === 'approved' ? 'badge-active'
            : status === 'rejected' ? 'badge-inactive'
            : 'badge';
        return html`<span class="badge ${cls}">${status}</span>`;
    }

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

    return html`
        <div>
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
                <span class="text-muted" style="font-size:12px;">${count || memories.length} memor${count === 1 ? 'y' : 'ies'}</span>
                <div style="flex:1"></div>
            </div>

            <div class="admin-list">
                ${memories.length === 0 && html`<div class="empty-hint">No memories stored.</div>`}
                ${memories.map(m => html`
                    <div class="admin-surface-row" key=${m.id} style="flex-direction:column;align-items:stretch;">
                        ${editingId === m.id ? html`
                            <div>
                                <textarea rows="3" style="width:100%;font-size:13px;margin-bottom:8px;"
                                          value=${editValue}
                                          onInput=${e => setEditValue(e.target.value)} />
                                <div style="display:flex;gap:6px;">
                                    <button class="btn-small btn-primary" onClick=${() => saveEdit(m.id)}>Save</button>
                                    <button class="btn-small" onClick=${cancelEdit}>Cancel</button>
                                </div>
                            </div>
                        ` : html`
                            <div style="display:flex;align-items:center;gap:8px;">
                                <div style="flex:1;min-width:0;">
                                    ${m.key && html`<strong style="margin-right:6px;">${m.key}</strong>`}
                                    <span style="font-size:13px;color:var(--text-2);">${truncate(m.value || m.content || '', 120)}</span>
                                </div>
                                ${statusBadge(m.status)}
                                <span class="text-muted" style="font-size:11px;white-space:nowrap;">${fmtDate(m.created_at)}</span>
                            </div>
                            <div style="display:flex;gap:6px;margin-top:6px;">
                                <button class="btn-small" onClick=${() => startEdit(m)}>Edit</button>
                                <button class="btn-small btn-danger" onClick=${() => deleteMemory(m.id)}>Delete</button>
                            </div>
                        `}
                    </div>
                `)}
            </div>
        </div>
    `;
}
