/* History of past evaluations */
(() => {
const { useEffect: useEffectH, useState: useStateH } = React;

function History({ onOpen }) {
  const [data, setData] = useStateH(null);
  const [err, setErr] = useStateH('');

  useEffectH(() => {
    api.listEvaluations(50, 0).then(setData).catch(e => setErr(e.message));
  }, []);

  if (err) return <div className="text-red-700 bg-red-50 border border-red-200 rounded p-4 text-sm">⚠ {err}</div>;
  if (!data) return <div className="text-ink-4 text-sm">Loading…</div>;
  if (!data.items.length) return <div className="text-ink-4 text-sm bg-white rounded-2xl border border-gray-200 p-8 text-center">No evaluations yet.</div>;

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
      <div className="text-xs font-bold text-ink-4 uppercase tracking-wider px-5 pt-5">
        History · {data.total} evaluation{data.total === 1 ? '' : 's'}
      </div>
      <div className="divide-y divide-gray-100 mt-3">
        {data.items.map(ev => (
          <button
            key={ev.public_key}
            onClick={() => onOpen(ev.public_key)}
            className="w-full text-left px-5 py-3 hover:bg-gray-50 transition flex items-center gap-4"
          >
            <div className="font-mono text-xs text-ink-4 w-20">{ev.public_key}</div>
            <div className="flex-1 min-w-0">
              <div className="text-sm font-medium text-ink truncate">{ev.defendant_name || '(no defendant)'}</div>
              <div className="text-xs text-ink-4">
                {ev.client_name || '—'} · {ev.client_state || '—'} · {new Date(ev.created_at).toLocaleDateString()}
              </div>
            </div>
            <div className="text-right">
              {ev.score != null ? (
                <div className="text-lg font-bold text-ink">{ev.score.toFixed(1)}</div>
              ) : (
                <div className="text-xs text-ink-4">{ev.status}</div>
              )}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

window.History = History;
})();
