'use client';

import { useEffect, useState } from 'react';

/**
 * PriorReads (Session 60, night2/E — work-order 4.3, spec §7).
 * "PRIOR READS: [chips]" under a scan result — the model's own public
 * history on this player from ledger_entries. Deferred-render: nothing
 * shows until real rows exist; settled rows carry their outcome, pending
 * rows say pending. Never invented.
 */

interface PriorRow {
  id: string;
  stat: string;
  line: number;
  side: string;
  grade: string;
  game_date: string;
  outcome?: 'hit' | 'miss' | 'push' | null;
  actual_value?: number | null;
}

export default function PriorReads({ player, stat }: { player: string; stat?: string }) {
  const [rows, setRows] = useState<PriorRow[] | null>(null);

  useEffect(() => {
    let active = true;
    const params = new URLSearchParams({ player, limit: '8' });
    fetch(`/api/ledger/model?${params}`)
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => { if (active && data) setRows(Array.isArray(data.entries) ? data.entries : []); })
      .catch(() => { /* self-hide */ });
    return () => { active = false; };
  }, [player]);

  if (!rows || rows.length === 0) return null;
  // Same-stat reads first — the most relevant history for this scan.
  const sorted = stat
    ? [...rows].sort((a, b) => Number(b.stat === stat.toLowerCase()) - Number(a.stat === stat.toLowerCase()))
    : rows;

  return (
    <div style={{ padding: '4px 4px 0' }}>
      <div className="mono" style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', color: 'var(--text-2)', marginBottom: 8 }}>
        PRIOR READS · {rows.length}
      </div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {sorted.slice(0, 6).map((r) => {
          const color = r.outcome === 'hit' ? 'var(--g-a, #00D4A0)'
            : r.outcome === 'miss' ? 'var(--miss, #FF5252)'
            : r.outcome === 'push' ? 'var(--text-1)' : 'var(--text-2)';
          const mark = r.outcome === 'hit' ? '✓' : r.outcome === 'miss' ? '✕' : r.outcome === 'push' ? '–' : '…';
          return (
            <span
              key={r.id}
              className="mono"
              title={`${r.game_date} · graded ${r.grade}${r.actual_value != null ? ` · actual ${r.actual_value}` : ''}`}
              style={{ fontSize: 10.5, fontWeight: 700, padding: '3px 8px', borderRadius: 5, border: `1px solid ${color}`, color, letterSpacing: '0.03em' }}
            >
              {mark} {String(r.side).toUpperCase() === 'UNDER' ? 'U' : 'O'}{r.line} {r.stat.replace(/_/g, ' ')} · {r.grade}
            </span>
          );
        })}
      </div>
    </div>
  );
}
