'use client';

import { useEffect, useState } from 'react';
import SectionHead from '@/components/vyndr/SectionHead';

/**
 * DeskShowcase (DS5 · DESIGN-SPEC Part 6, #8) — the Desk-as-hero story above the
 * pricing grid. The pitch (left) is copy; the feature visuals (right) are now
 * REAL data (Truth-Everywhere Part 2, item 6), fetched from /api/desk-showcase:
 *  - ALT LINE LADDER: a real graded prop's ladder (line + grade; edge only when
 *    it's a plausible market value).
 *  - PARLAY φ: the model's real same-team correlation, computed for two REAL
 *    same-team legs (named).
 * The old hardcoded ladder / QUARTER-KELLY 2.4% / φ 0.34 mocks are gone. When
 * the board has no real ladder, the visuals HIDE (real-or-hidden) — the Kelly
 * tile is dropped entirely (the snapshot has no odds to size from honestly).
 */

interface Rung { line: number; grade: string; edge: number | null; base?: boolean }
interface Showcase {
  available: boolean;
  ladder?: { player: string | null; stat_type: string | null; sport?: string; rungs: Rung[] } | null;
  parlay?: { value: number; legs: string[]; team?: string } | null;
}

const STAT_LABEL: Record<string, string> = {
  total_bases: 'TB', home_runs: 'HR', hits: 'H', rbi: 'RBI', runs: 'R', doubles: '2B',
  strikeouts: 'K', points: 'PTS', rebounds: 'REB', assists: 'AST', threes: '3PT',
};
const statLabel = (s?: string | null) => (s ? (STAT_LABEL[s] || s.replace(/_/g, ' ').toUpperCase()) : '');

function RungCell({ line, grade, edge, base }: Rung) {
  const gradeCol = grade.startsWith('A') ? 'var(--g-a)' : grade.startsWith('B') ? 'var(--text-0)' : grade.startsWith('C') ? 'var(--text-1)' : 'var(--miss)';
  const edgeCol = edge == null ? 'var(--text-2)' : edge >= 0 ? 'var(--g-a)' : 'var(--miss)';
  return (
    <div style={{ flex: '1 1 0', minWidth: 58, textAlign: 'center', padding: '9px 6px', background: 'var(--bg-2)', border: `1px solid ${base ? 'var(--border-hi)' : 'var(--border)'}`, borderRadius: 6 }}>
      <div className="mono" style={{ fontSize: 11, color: base ? 'var(--text-0)' : 'var(--text-1)', marginBottom: 5 }}>{line}{base ? ' •' : ''}</div>
      <div className="mono" style={{ fontSize: 17, fontWeight: 800, color: gradeCol }}>{grade}</div>
      <div className="mono" style={{ fontSize: 10, color: edgeCol, marginTop: 3 }}>
        {edge == null ? '—' : `${edge >= 0 ? '+' : ''}${edge}%`}
      </div>
    </div>
  );
}

export default function DeskShowcase() {
  const [data, setData] = useState<Showcase | null>(null);

  useEffect(() => {
    let alive = true;
    fetch('/api/desk-showcase', { cache: 'no-store' })
      .then((r) => r.json())
      .then((d) => { if (alive) setData(d); })
      .catch(() => { if (alive) setData({ available: false }); });
    return () => { alive = false; };
  }, []);

  const ladder = data?.available ? data.ladder : null;
  const parlay = data?.available ? data.parlay : null;
  const showVisuals = !!ladder && ladder.rungs.length > 0;

  return (
    <section style={{ padding: '72px 24px 8px', borderTop: '1px solid var(--border)' }}>
      <div className="desk-showcase" style={{ maxWidth: 1100, margin: '0 auto', display: 'grid', gap: 40, alignItems: 'center' }}>
        {/* LEFT — the pitch */}
        <div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', color: 'var(--g-a)', marginBottom: 14 }}>
            THE DESK · FLAGSHIP
          </div>
          <h2 className="text-balance" style={{ fontSize: 'clamp(30px, 4.4vw, 50px)', fontWeight: 800, letterSpacing: '-0.03em', lineHeight: 1.02, margin: 0 }}>
            Every grade, every alt line, live.{' '}
            <span className="mono" style={{ color: 'var(--g-a)' }}>$44.99</span>
            <span style={{ color: 'var(--text-tertiary)' }}>/mo.</span>
          </h2>
          <p style={{ fontSize: 17, color: 'var(--text-secondary)', margin: '18px 0 0', maxWidth: 460, lineHeight: 1.55 }}>
            Every alt line graded, quarter-Kelly sizing on your bankroll, parlay
            correlation, and the model&rsquo;s real-time feed. The desk a trading
            floor pays five figures for — priced for one bettor.
          </p>

          <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 28, flexWrap: 'wrap' }}>
            <a href="#pricing" className="btn-primary" style={{ padding: '13px 24px', fontSize: 15, textDecoration: 'none' }}>
              Claim a Founder Desk →
            </a>
            <span className="mono" style={{ fontSize: 12.5, color: 'var(--text-tertiary)' }}>
              <span style={{ color: 'var(--g-a)', fontWeight: 700 }}>$34.99</span> locked for the first 100 · then $44.99
            </span>
          </div>
        </div>

        {/* RIGHT — REAL feature visuals (hidden when the board has none) */}
        {showVisuals && (
          <div style={{ display: 'grid', gap: 14 }}>
            <div style={{ background: 'var(--bg-1)', border: '1px solid var(--border-hi)', borderRadius: 12, padding: 18 }}>
              <SectionHead style={{ marginBottom: 4 }}>
                ALT LINE LADDER <span style={{ color: 'var(--amber)', fontSize: 9, border: '1px solid rgba(255,179,71,.4)', borderRadius: 3, padding: '1px 5px', marginLeft: 4 }}>DESK</span>
              </SectionHead>
              <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-2)', marginBottom: 10, letterSpacing: '0.04em' }}>
                {ladder!.player} · {statLabel(ladder!.stat_type)}
              </div>
              <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap' }}>
                {ladder!.rungs.map((r) => <RungCell key={r.line} {...r} />)}
              </div>
            </div>

            {/* PARLAY φ — real, only when two real same-team legs exist */}
            {parlay && (
              <div style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12, padding: 16 }}>
                <SectionHead style={{ marginBottom: 10 }}>PARLAY φ</SectionHead>
                <div className="mono" style={{ fontSize: 26, fontWeight: 800, color: 'var(--text-0)', fontVariantNumeric: 'tabular-nums' }}>{parlay.value}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 4 }}>
                  correlation · {parlay.legs[0]} + {parlay.legs[1]}
                </div>
              </div>
            )}

            {/* Real-time feed — backed by the live MarketBreadth (consensus vs model). */}
            <div style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12, padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
              <span className="live-dot" style={{ background: 'var(--g-a)' }} aria-hidden />
              <span className="mono" style={{ fontSize: 11.5, color: 'var(--text-1)', letterSpacing: '0.04em' }}>
                REAL-TIME FEED · <span style={{ color: 'var(--g-a)', fontWeight: 700 }}>consensus vs model</span>, live line moves
              </span>
            </div>
          </div>
        )}
      </div>
    </section>
  );
}
