/**
 * trust.js — Trust review pane.
 *
 * Editorial card layout showing: security posture, memory audit,
 * memory quarantine, active worktrees, detected clients.
 *
 * Cut 24 (Phase H): Trust review pane polish.
 */

import { api }       from '../api.js';
import { openDrawer } from '../widgets/drawer.js';

const $ = id => document.getElementById(id);
const esc = s => s == null ? '' : String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');

function fmtTs(ts) {
    if (!ts) return '—';
    return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}

function severityChip(sev) {
    const map = { critical: 'chip-bad', high: 'chip-bad', medium: 'chip-warn', low: 'chip-muted', info: 'chip-muted' };
    return `<span class="chip ${map[sev] || 'chip-muted'}">${esc(sev ?? 'info')}</span>`;
}

function pressureColor(level) {
    if (level === 'critical') return 'var(--bad)';
    if (level === 'high')     return 'var(--warn)';
    if (level === 'medium')   return 'var(--warn)';
    return 'var(--ok)';
}

/* ── Load ─────────────────────────────────────────────────────────────────── */

export async function load() {
    const container = $('trust-container');
    if (!container) return;
    container.innerHTML = `<div class="empty"><div class="empty-title">Loading trust data…</div></div>`;

    const data = await api('/api/dashboard/surface/trust', 15_000);
    render(data ?? {});
}

/* ── Render ───────────────────────────────────────────────────────────────── */

export function render(data) {
    const container = $('trust-container');
    if (!container) return;

    const pressure = data.machinePressure ?? 'unknown';
    const governor = data.governor ?? {};
    const audit    = Array.isArray(data.memoryAudit) ? data.memoryAudit : [];
    const quarantine = Array.isArray(data.memoryQuarantine) ? data.memoryQuarantine : [];
    const worktrees  = data.worktreeHealth ?? {};
    const clients    = Array.isArray(data.clients) ? data.clients : [];
    const primary    = data.primaryClient;
    const synapseHealth = Array.isArray(data.synapseHealth) ? data.synapseHealth : [];
    const approvals  = Array.isArray(data.synapseApprovals) ? data.synapseApprovals : [];
    const escalations = Array.isArray(data.architectsEscalations) ? data.architectsEscalations : [];

    container.innerHTML = `
        <div class="trust-grid">

            <!-- Security posture card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Security posture</span>
                    <span class="chip ${pressure === 'low' || pressure === 'normal' ? 'chip-ok' : pressure === 'critical' ? 'chip-bad' : 'chip-warn'}"
                          style="color:${pressureColor(pressure)}">${esc(pressure)}</span>
                </div>
                <div class="trust-posture-body">
                    ${_postureRows(governor)}
                </div>
            </div>

            <!-- Memory audit card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Memory audit</span>
                    <span class="trust-card-count">${audit.length} event${audit.length !== 1 ? 's' : ''}</span>
                </div>
                ${audit.length === 0
                    ? `<div class="empty-sub">No audit events recorded.</div>`
                    : `<div class="trust-event-list">
                        ${audit.slice(0, 30).map(e => _auditRow(e)).join('')}
                       </div>`
                }
            </div>

            <!-- Memory quarantine card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Quarantine</span>
                    <span class="trust-card-count">${quarantine.length} entr${quarantine.length !== 1 ? 'ies' : 'y'}</span>
                </div>
                ${quarantine.length === 0
                    ? `<div class="empty-sub">Quarantine is empty.</div>`
                    : `<div class="trust-event-list">
                        ${quarantine.slice(0, 20).map(q => _quarantineRow(q)).join('')}
                       </div>`
                }
            </div>

            <!-- Worktrees card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Active worktrees</span>
                </div>
                ${_worktreesSection(worktrees)}
            </div>

            <!-- Clients card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Detected clients</span>
                    <span class="trust-card-count">${clients.length}</span>
                </div>
                ${_clientsSection(clients, primary)}
            </div>

            <!-- Pending approvals card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Pending approvals</span>
                    <span class="trust-card-count">${approvals.length}</span>
                </div>
                ${approvals.length === 0
                    ? `<div class="empty-sub">No pending approvals.</div>`
                    : `<div class="trust-event-list">
                        ${approvals.slice(0, 10).map(a => _approvalRow(a)).join('')}
                       </div>`
                }
            </div>

            <!-- Escalations card -->
            ${escalations.length > 0 ? `
            <div class="card trust-card trust-card-wide">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Architects escalations</span>
                    <span class="chip chip-bad">${escalations.length}</span>
                </div>
                <div class="trust-event-list">
                    ${escalations.slice(0, 15).map(e => _escalationRow(e)).join('')}
                </div>
            </div>` : ''}

            <!-- Synapse health card -->
            ${synapseHealth.length > 0 ? `
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Operative health</span>
                    <span class="trust-card-count">${synapseHealth.length}</span>
                </div>
                <div class="trust-event-list">
                    ${synapseHealth.slice(0, 10).map(o => _operativeRow(o)).join('')}
                </div>
            </div>` : ''}

        </div>
    `;

    // Bind audit detail drawers.
    container.querySelectorAll('[data-audit-detail]').forEach(btn => {
        const idx = Number(btn.dataset.auditDetail);
        btn.addEventListener('click', () => {
            const e = audit[idx];
            if (!e) return;
            openDrawer({
                title: 'Audit event',
                body: `<pre style="font-family:var(--font-mono);font-size:var(--text-sm);white-space:pre-wrap;word-break:break-all;color:var(--text-muted)">${esc(JSON.stringify(e, null, 2))}</pre>`,
            });
        });
    });
}

/* ── Sub-renderers ────────────────────────────────────────────────────────── */

function _postureRows(gov) {
    const rows = [
        ['Pressure level',    gov.pressureLevel ?? '—'],
        ['Active worktrees',  gov.activeWorktrees ?? '—'],
        ['Sealed mode',       gov.sealedMode ? 'ON' : 'off'],
        ['Blocked actions',   (gov.blockedActions ?? []).length || '—'],
        ['Budget consumed',   gov.budgetConsumed != null ? `$${Number(gov.budgetConsumed).toFixed(4)}` : '—'],
    ];
    return rows.map(([k, v]) =>
        `<div class="trust-row"><span class="trust-row-k">${esc(k)}</span><span class="trust-row-v">${esc(String(v))}</span></div>`
    ).join('');
}

function _auditRow(e, idx) {
    return `
        <div class="trust-event-row">
            <div class="trust-event-main">
                ${severityChip(e.severity)}
                <span class="trust-event-type">${esc(e.type ?? e.action ?? 'event')}</span>
                ${e.target ? `<span style="font-family:var(--font-mono);font-size:var(--caption);color:var(--text-muted)">${esc(String(e.target).slice(0, 50))}</span>` : ''}
            </div>
            <div class="trust-event-meta">
                <span style="color:var(--text-dim);font-size:var(--caption)">${fmtTs(e.at ?? e.timestamp)}</span>
                ${idx != null ? `<button class="btn btn-sm" style="font-size:var(--caption);padding:0 6px;min-height:20px" data-audit-detail="${idx}">Detail</button>` : ''}
            </div>
        </div>`;
}

function _quarantineRow(q) {
    return `
        <div class="trust-event-row">
            <div class="trust-event-main">
                <span class="chip chip-bad">quarantined</span>
                <span class="trust-event-type">${esc(String(q.id ?? q.memoryId ?? '').slice(-12))}</span>
                ${q.reason ? `<span style="color:var(--text-muted);font-size:var(--text-sm)">${esc(q.reason.slice(0, 60))}</span>` : ''}
            </div>
            <div class="trust-event-meta">
                <span style="color:var(--text-dim);font-size:var(--caption)">${fmtTs(q.quarantinedAt)}</span>
            </div>
        </div>`;
}

function _worktreesSection(health) {
    const entries = Object.entries(health);
    if (!entries.length) return `<div class="empty-sub">No active worktrees.</div>`;
    return `<div class="trust-event-list">
        ${entries.slice(0, 10).map(([id, h]) => `
            <div class="trust-event-row">
                <div class="trust-event-main">
                    <span class="chip ${h?.status === 'active' ? 'chip-ok' : 'chip-warn'}">${esc(h?.status ?? 'unknown')}</span>
                    <span style="font-family:var(--font-mono);font-size:var(--text-sm)">${esc(id.slice(-20))}</span>
                </div>
                <div class="trust-event-meta">
                    ${h?.branch ? `<span class="chip chip-muted">${esc(h.branch)}</span>` : ''}
                </div>
            </div>
        `).join('')}
    </div>`;
}

function _clientsSection(clients, primary) {
    if (!clients.length) return `<div class="empty-sub">No clients detected.</div>`;
    return `<div class="trust-event-list">
        ${clients.slice(0, 10).map(c => {
            const id = c.clientId ?? c.id ?? c.name ?? '';
            const name = c.displayName ?? c.name ?? c.clientId ?? c.id ?? 'unknown';
            const primaryId = primary?.clientId ?? primary?.id ?? primary?.name ?? '';
            return `
            <div class="trust-event-row">
                <div class="trust-event-main">
                    ${id === primaryId ? `<span class="chip chip-ok">primary</span>` : `<span class="chip chip-muted">client</span>`}
                    <span class="trust-event-type">${esc(name)}</span>
                    ${c.version ? `<span style="font-family:var(--font-mono);font-size:var(--caption);color:var(--text-muted)">v${esc(c.version)}</span>` : ''}
                </div>
                <div class="trust-event-meta">
                    ${c.sessions != null ? `<span style="font-size:var(--caption);color:var(--text-muted)">${c.sessions} session${c.sessions !== 1 ? 's' : ''}</span>` : ''}
                </div>
            </div>
        `;}).join('')}
    </div>`;
}

function _approvalRow(a) {
    return `
        <div class="trust-event-row">
            <div class="trust-event-main">
                <span class="chip chip-warn">pending</span>
                <span class="trust-event-type">${esc(a.type ?? a.action ?? 'approval')}</span>
                ${a.description ? `<span style="color:var(--text-muted);font-size:var(--text-sm)">${esc(a.description.slice(0, 60))}</span>` : ''}
            </div>
            <div class="trust-event-meta">
                <span style="color:var(--text-dim);font-size:var(--caption)">${fmtTs(a.requestedAt)}</span>
            </div>
        </div>`;
}

function _escalationRow(e) {
    return `
        <div class="trust-event-row">
            <div class="trust-event-main">
                ${severityChip(e.severity ?? 'high')}
                <span class="trust-event-type">${esc(e.type ?? e.wardId ?? 'escalation')}</span>
                ${e.message ? `<span style="color:var(--text-muted);font-size:var(--text-sm)">${esc(e.message.slice(0, 80))}</span>` : ''}
            </div>
            <div class="trust-event-meta">
                <span style="color:var(--text-dim);font-size:var(--caption)">${fmtTs(e.escalatedAt ?? e.at)}</span>
            </div>
        </div>`;
}

function _operativeRow(o) {
    const alive = o.alive ?? o.status === 'active';
    return `
        <div class="trust-event-row">
            <div class="trust-event-main">
                <span class="chip ${alive ? 'chip-ok' : 'chip-muted'}">${alive ? 'active' : 'idle'}</span>
                <span class="trust-event-type">${esc(o.role ?? o.name ?? o.id ?? 'operative')}</span>
            </div>
            <div class="trust-event-meta">
                ${o.costUsd != null ? `<span style="font-family:var(--font-mono);font-size:var(--caption);color:var(--text-muted)">$${Number(o.costUsd).toFixed(4)}</span>` : ''}
            </div>
        </div>`;
}
