'use client';

/**
 * MarketBreadth (Wave 4A · Step 4) — the CONSENSUS-vs-MODEL strip that makes
 * the DeskShowcase "consensus vs model, live line moves" claim REAL.
 *
 * Fed pre-computed breadth rows (from `lib/marketBreadth.collectBreadth`): each
 * row carries the market CONSENSUS (median book line across ≥2 books) and the
 * model's position vs it, SIGNED by the graded side. Colored by the ONE color
 * contract (`edgeColor`): model-beats-market → signal-green, model-behind →
 * muted red, inline → neutral. Mono, tabular — it's data.
 *
 * SELF-HIDING: no rows (nothing has ≥2 books) → renders null. It never shows an
 * empty promise; the honest surface only appears when there's a real consensus.
 */

import SectionHead from './SectionHead';
import { edgeColor } from '@/lib/colorContract';
import { dedupeLeaders } from '@/lib/playerGrouping';

export interface BreadthRow {
  player?: string;
  stat?: string;
  line?: number | null;
  consensus: number | null;
  bookCount: number;
  model: number | null;
  delta: number | null;
  signedEdge: number | null;
  // Widened to string|null: collectBreadth is untyped JS, so its inferred
  // return widens these; the values are only ever 'above'|'below'|'inline'.
  position: string | null;
  side: string;
}

const STAT_LABEL: Record<string, string> = {
  total_bases: 'TB', home_runs: 'HR', hits: 'H', rbi: 'RBI', runs: 'R',
  strikeouts: 'K', hits_allowed: 'HA', earned_runs: 'ER', innings_pitched: 'IP',
  stolen_bases: 'SB', points: 'PTS', rebounds: 'REB', assists: 'AST', threes: '3PT',
};
function statLabel(stat?: string): string {
  if (!stat) return '';
  return STAT_LABEL[stat] || String(stat).replace(/_/g, ' ').toUpperCase();
}

function fmtSigned(n: number | null): string {
  if (n == null) return '';
  const s = n > 0 ? '+' : n < 0 ? '' : '±';
  return `${s}${n}`;
}

export default function MarketBreadth({
  items,
  title = 'CONSENSUS vs MODEL',
  max = 6,
}: {
  items?: BreadthRow[] | null;
  title?: string;
  max?: number;
}) {
  // P0-3 — group by player+market so a player's alt-line ladder shows as ONE
  // consensus row (the audit's Ben Williamson ×5). No per-market cap here — a
  // consensus table isn't a ranked board, it just shouldn't repeat a player.
  const rows = dedupeLeaders(Array.isArray(items) ? items : [], 0).slice(0, Math.max(0, max));
  if (rows.length === 0) return null; // self-hide — no honest consensus to show

  return (
    <section
      style={{
        background: 'var(--bg-1)',
        border: '1px solid var(--border)',
        borderRadius: 10,
        padding: 16,
        marginBottom: 16,
      }}
    >
      <SectionHead style={{ marginBottom: 12 }}>
        {title}
        <span className="mono" style={{ color: 'var(--text-2)', fontSize: 9, marginLeft: 8, letterSpacing: '0.14em' }}>
          MEDIAN BOOK LINE · MODEL EDGE
        </span>
      </SectionHead>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {rows.map((r, i) => {
          const col = edgeColor(r.signedEdge);
          const sideChar = r.side === 'under' ? 'u' : 'o';
          return (
            <div
              key={`${r.player}-${r.stat}-${i}`}
              className="mono breadth-row"
              style={{ display: 'flex', alignItems: 'baseline', gap: 10, fontSize: 12, flexWrap: 'wrap', fontVariantNumeric: 'tabular-nums', minWidth: 0 }}
            >
              {r.player && <span style={{ color: 'var(--text-0)', fontWeight: 700, minWidth: 96 }}>{r.player}</span>}
              <span style={{ color: 'var(--text-1)' }}>
                {statLabel(r.stat)} {sideChar}{r.line ?? r.consensus}
              </span>
              <span style={{ color: 'var(--text-2)' }}>
                CONSENSUS <span style={{ color: 'var(--text-0)' }}>{r.consensus}</span>
                <span style={{ color: 'var(--text-2)' }}> · {r.bookCount} BOOKS</span>
              </span>
              {r.model != null ? (
                <span style={{ color: 'var(--text-2)' }}>
                  MODEL <span style={{ color: 'var(--text-0)' }}>{r.model}</span>
                  {r.signedEdge != null && (
                    <span style={{ color: col, fontWeight: 800 }}> · {fmtSigned(r.signedEdge)}</span>
                  )}
                </span>
              ) : (
                <span style={{ color: 'var(--text-2)' }}>MODEL —</span>
              )}
            </div>
          );
        })}
      </div>
    </section>
  );
}
