'use client';

import { useEffect, useState } from 'react';
import { GradePill } from './GradeCard';
import PriceTriplet from './vyndr/PriceTriplet';

/**
 * Daily hero prop card (Truth-Everywhere Part 2, item 5).
 *
 * A live RULE, not a hand-picked example: the graded prop where VYNDR disagrees
 * MOST with the market — largest |model - consensus| gap, A/B grades only —
 * fetched from /api/hero-prop (which reads the pre-graded snapshot). The card
 * shows the disagreement explicitly (the book's number vs ours) with the real
 * grade timestamp. Empty slate → the most recent real graded read. Nothing
 * cached → the card hides. There is NO static fallback — the old Jokic
 * "Example" card is gone.
 */

type Hero = {
  available: boolean;
  is_recent?: boolean;
  sport?: string;
  player?: string | null;
  stat_type?: string | null;
  line?: number | null;
  direction?: 'over' | 'under';
  projection?: number | null;
  grade?: string | null;
  book?: string | null;
  graded_at?: string | null;
  reasoning?: string | null;
  // Session 66 — the PRICE LAYER. /api/hero-prop (heroPropService.toHero) has
  // emitted these all along; the card just never declared or read them. All
  // nullable: a missing leg renders absent, never a sample number.
  book_odds?: number | null;
  fair_odds?: number | null;
  model_odds?: number | null;
  ev_pct?: number | null;
  value?: boolean | null;
  takeable?: boolean | null;
  quarantine_reason?: string | null;
  /** Free/anonymous: model leg stripped server-side (utils/snapshotGating). */
  model_price_locked?: boolean;
};

const SPORT_LABEL: Record<string, string> = { nba: 'NBA', wnba: 'WNBA', mlb: 'MLB', soccer: 'Soccer' };
const SPORT_COLOR: Record<string, string> = { nba: '#E94B3C', wnba: '#FFB347', mlb: '#1E90FF', soccer: '#00D4A0' };
const BOOK_LABEL: Record<string, string> = {
  draftkings: 'DK', fanduel: 'FD', betmgm: 'MGM', caesars: 'CZR', pointsbet: 'PB', betrivers: 'BR',
};

function fmtTime(iso?: string | null, withDate = false): string {
  if (!iso) return '';
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return '';
  const t = d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
  if (!withDate) return t;
  return `${d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} · ${t}`;
}

export default function LiveHeroProp() {
  const [data, setData] = useState<Hero | null>(null);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    let alive = true;
    fetch('/api/hero-prop', { cache: 'no-store' })
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => { if (alive) { setData(json); setLoaded(true); } })
      .catch(() => { if (alive) setLoaded(true); });
    return () => { alive = false; };
  }, []);

  // No fabrication: hide until a REAL read is available.
  if (!loaded || !data || !data.available || !data.player) return null;

  const sport = data.sport || 'mlb';
  const sportLabel = SPORT_LABEL[sport] || sport.toUpperCase();
  const sportColor = SPORT_COLOR[sport] || 'var(--grade-a)';
  const statLabel = (data.stat_type || '').replace(/_/g, ' ');
  const dir = (data.direction || 'over');
  const dirCap = dir.charAt(0).toUpperCase() + dir.slice(1);
  const bookLabel = data.book ? (BOOK_LABEL[data.book] || data.book.toUpperCase()) : 'BOOK';
  const grade = data.grade || 'B';
  const line = typeof data.line === 'number' ? data.line : null;
  const projection = typeof data.projection === 'number' ? data.projection : null;
  const isRecent = !!data.is_recent;

  return (
    <div
      style={{
        position: 'relative', transform: 'rotate(-1deg)', padding: 24,
        background: 'var(--bg-elevated)', border: '1px solid var(--border-focus)',
        borderRadius: 20, boxShadow: '0 24px 64px rgba(0,0,0,0.6), 0 0 0 1px var(--accent-glow)',
        maxWidth: 380, marginInline: 'auto',
      }}
    >
      {/* Status — LIVE for a current read; LATEST for the empty-slate fallback.
          Never "Example": this is a real graded read either way. */}
      <div
        className="mono"
        aria-label={isRecent ? 'Most recent read' : 'Live'}
        style={{
          position: 'absolute', top: 12, right: 12, display: 'inline-flex', alignItems: 'center', gap: 4,
          fontSize: 9, color: isRecent ? 'var(--text-tertiary)' : 'var(--grade-a)', fontWeight: 800, letterSpacing: '0.1em',
        }}
      >
        {!isRecent && (
          <span aria-hidden style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--grade-a)', boxShadow: '0 0 8px var(--grade-a)' }} />
        )}
        {isRecent ? 'LATEST READ' : 'LIVE'}
      </div>

      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14, marginTop: 8 }}>
        <div>
          <span className="mono" style={{ fontSize: 11, padding: '2px 8px', borderRadius: 999, background: `${sportColor}26`, color: sportColor, fontWeight: 700 }}>
            {sportLabel}
          </span>
          <h3 style={{ fontSize: 16, fontWeight: 600, marginTop: 8 }}>{data.player}</h3>
          <p className="mono" style={{ fontSize: 12, color: 'var(--text-secondary)' }}>
            {dirCap} {line ?? ''} {statLabel}
          </p>
        </div>
        <GradePill grade={grade} />
      </div>

      {/* THE DISAGREEMENT — the book's number vs ours, side by side. This is the
          whole point: the read where VYNDR disagrees most with the market. */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 10 }}>
        <div style={{ flex: 1, padding: '8px 12px', background: 'var(--bg-surface)', borderRadius: 10, textAlign: 'center' }}>
          <div style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>{bookLabel} LINE</div>
          <div className="mono" style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>
            {line ?? '—'}
          </div>
        </div>
        <div style={{ flex: 1, padding: '8px 12px', background: 'var(--bg-surface)', borderRadius: 10, textAlign: 'center', border: '1px solid var(--accent-glow)' }}>
          <div style={{ fontSize: 10, color: 'var(--grade-a)' }}>VYNDR MODEL</div>
          <div className="mono" style={{ fontSize: 14, fontWeight: 700, color: 'var(--grade-a)' }}>
            {projection != null ? projection.toFixed(projection < 10 ? 1 : 0) : '—'}
          </div>
        </div>
      </div>

      {/* ② PRICE · IS IT FAIR (Session 66 — the price triplet).
          The block above answers "will it clear" in STAT space; this answers
          "is it fair" in PRICE space. Additive — the projection comparison is
          untouched and the triplet sits beside it, per the design's two-question
          hierarchy. Self-hides when the feed carries no real prices. */}
      {(data.book_odds != null || data.fair_odds != null) && (
        <div style={{ marginBottom: 12 }}>
          <div
            className="mono"
            style={{ fontSize: 9, letterSpacing: '0.14em', color: 'var(--text-3)', fontWeight: 700, marginBottom: 6 }}
          >
            PRICE · IS IT FAIR
          </div>
          <PriceTriplet
            compact
            showBody={false}
            data={{
              book_odds: data.book_odds,
              fair_odds: data.fair_odds,
              model_odds: data.model_odds,
              ev_pct: data.ev_pct,
              quarantine_reason: data.quarantine_reason,
              // Session 67 — MUST be forwarded. Without it a GATED model leg
              // falls through to the withheld/quarantine branch and the card
              // says "we suppressed our price" when the truth is "you don't
              // have this tier". A paywall must never wear poison's copy.
              model_price_locked: data.model_price_locked,
            }}
          />
        </div>
      )}

      {/* Real timestamp — proves this was graded, and when. */}
      {data.graded_at && (
        <p className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)', margin: '0 0 12px', letterSpacing: '0.04em' }}>
          Graded {fmtTime(data.graded_at, isRecent)}
        </p>
      )}

      {/* Reasoning — BLURRED, the paywall (only when the model supplied one). */}
      {data.reasoning && (
        <div
          className="hero-grade-reasoning"
          aria-label="Full analysis available after sign up"
          style={{ position: 'relative', padding: 12, background: 'var(--bg-surface)', borderRadius: 10, marginBottom: 12, overflow: 'hidden' }}
        >
          <div style={{ filter: 'blur(4px)', userSelect: 'none', pointerEvents: 'none', fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.4 }} aria-hidden>
            {data.reasoning}
          </div>
          <div aria-hidden style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(18,18,26,0) 30%, rgba(18,18,26,0.85) 100%)', pointerEvents: 'none' }} />
          <div className="mono" style={{ position: 'absolute', bottom: 6, left: 0, right: 0, textAlign: 'center', fontSize: 10, color: 'var(--text-tertiary)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            Classified · Sign up to unlock
          </div>
        </div>
      )}

      <a href="/signup" className="btn-primary" style={{ display: 'block', textAlign: 'center', padding: '10px 16px', fontSize: 13, fontWeight: 700, textDecoration: 'none' }}>
        Sign up to read the full analysis →
      </a>
    </div>
  );
}
