/**
 * SET 58 — always-on observability strip. The page itself reports the health
 * of every extension channel and the last captured failure, so a broken
 * install describes itself without DevTools.
 */
import { useSyncExternalStore } from 'react';
import { getSnapshot, subscribe, type Diag } from './store';

function lastPerChannel(diags: Diag[]): Diag[] {
  const seen = new Map<string, Diag>();
  for (const d of diags) seen.set(d.channel, d);
  return [...seen.values()].sort((a, b) => a.channel.localeCompare(b.channel));
}

export function Diagnostics() {
  const s = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
  const rows = lastPerChannel(s.diags);
  const failures = s.diags.filter(d => !d.ok);
  return (
    <details className="sh-diag" data-rha-shell="diagnostics">
      <summary>
        Diagnostics — {rows.filter(r => r.ok).length}/{rows.length || 0} channels ok
        {s.lastError ? <span className="bad"> · last failure: {s.lastError}</span> : null}
      </summary>
      <div className="sh-diag-body">
        {rows.map(d => (
          <div key={d.channel} className={`sh-diag-row ${d.ok ? 'ok' : 'bad'}`}>
            <span className="sh-diag-ch">{d.channel}</span>
            <span>{d.ok ? 'ok' : d.note}</span>
            <span className="dim">{new Date(d.ts).toLocaleTimeString()}</span>
          </div>
        ))}
        {failures.length > 0 && (
          <details style={{ marginTop: 6 }}>
            <summary className="dim">failure history ({failures.length})</summary>
            {failures.slice(-20).map((d, i) => (
              <div key={i} className="sh-diag-row bad">
                <span className="sh-diag-ch">{d.channel}</span>
                <span>{d.note}</span>
                <span className="dim">{new Date(d.ts).toLocaleTimeString()}</span>
              </div>
            ))}
          </details>
        )}
      </div>
    </details>
  );
}
