'use client';

import { useEffect, useState } from 'react';

/**
 * ModelRecord (Session 58, work-order 1.4) — the public model record as a
 * deferred-render strip/chip. Reads the /api/ledger/model 30d aggregate:
 *
 *   n ≥ min_sample → "MODEL 30D: H-M · X% HIT [· Y% BEAT CLOSE]" (green)
 *   settles building → "RECORD BUILDING · N reads pending settlement" (amber)
 *   nothing at all / fetch failed → renders NOTHING.
 *
 * Never a percentage on a small sample; never an invented number. Ship the
 * wiring now — the numbers appear on their own as settles accumulate.
 * Optional `sport` / `player` scope the record (VYNDR-on-player, §11).
 */

interface Aggregate {
  settled: number;
  hits: number;
  misses: number;
  hit_pct: number | null;
  beat_close_pct: number | null;
  pending: number;
}

export default function ModelRecord({
  sport,
  player,
  team,
  align = 'center',
}: {
  sport?: string;
  player?: string;
  /** VYNDR-on-team (5.2) — exact team name as the feed writes it. */
  team?: string;
  align?: 'center' | 'left';
}) {
  const [agg, setAgg] = useState<Aggregate | null>(null);
  const [minSample, setMinSample] = useState(20);

  useEffect(() => {
    let active = true;
    const params = new URLSearchParams({ limit: '1' });
    if (sport) params.set('sport', sport.toLowerCase());
    if (player) params.set('player', player);
    if (team) params.set('team', team);
    fetch(`/api/ledger/model?${params}`)
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (!active || !data?.aggregate) return;
        setAgg(data.aggregate);
        if (Number(data.min_sample) > 0) setMinSample(Number(data.min_sample));
      })
      .catch(() => { /* self-hide */ });
    return () => { active = false; };
  }, [sport, player, team]);

  if (!agg) return null;
  const ready = agg.settled >= minSample && agg.hit_pct != null;
  if (!ready && agg.pending === 0 && agg.settled === 0) return null; // nothing to claim yet

  return (
    <div
      className="mono"
      style={{
        display: 'flex',
        justifyContent: align === 'center' ? 'center' : 'flex-start',
        alignItems: 'baseline',
        gap: 12,
        flexWrap: 'wrap',
        fontSize: 11.5,
        letterSpacing: '0.06em',
      }}
    >
      {ready ? (
        <>
          <span style={{ color: 'var(--text-2, #6A6A7A)', fontWeight: 700 }}>MODEL 30D</span>
          <span style={{ color: 'var(--g-a, #00D4A0)', fontWeight: 800 }}>
            {agg.hits}-{agg.misses} · {agg.hit_pct}% HIT
          </span>
          {agg.beat_close_pct != null && (
            <span style={{ color: 'var(--text-0, #EDEDF2)', fontWeight: 700 }}>
              {agg.beat_close_pct}% BEAT CLOSE
            </span>
          )}
        </>
      ) : (
        <span style={{ color: 'var(--amber, #FFB347)', fontWeight: 700 }}>
          RECORD BUILDING · {agg.pending} read{agg.pending === 1 ? '' : 's'} pending settlement
        </span>
      )}
    </div>
  );
}
