'use client';

import { useEffect, useState } from 'react';
import { useParams, useSearchParams, useRouter } from 'next/navigation';
import SportBadge from '@/components/vyndr/SportBadge';
import GradeBadge from '@/components/vyndr/GradeBadge';
import ArchetypeBadge from '@/components/vyndr/ArchetypeBadge';
import ArchetypeBlend from '@/components/vyndr/ArchetypeBlend';
import ModelRecord from '@/components/vyndr/ModelRecord';
import PlayerStreaks from '@/components/vyndr/PlayerStreaks';
import PitcherArsenal from '@/components/vyndr/PitcherArsenal';
import { archetypeInfo } from '@/lib/archetypes';
import { initials, sportLabel, dnaRows, blendReadout } from '@/lib/playerProfileAdapter';

interface IntelMetric { label: string; kind: string; value: string; score?: string; color: string }
interface ActiveProp { stat: string; line: number | string; side: string; grade: string; confidence?: string | null }
interface PlayerIntel {
  player: string;
  sport: string;
  team: string;
  found: boolean;
  archetype: { primary: { name: string } | null; secondary: { name: string } | null; blend: { archetype: string; weight: number }[] };
  propDNA: { reliable: string[]; volatile: string[] };
  education: string;
  season: { k: string; v: string; lg?: string }[];
  last10: { d?: string; opp?: string; res?: string; stat?: string }[];
  splits: { k: string; a: string; b: string }[];
  gradeHistory: { grade: string; prop: string; hit?: boolean; miss?: boolean }[];
  activeProps: ActiveProp[];
  intel: IntelMetric[];
  injury: { label: string; note: string; cascade: string } | null;
}

const SectionLabel = ({ children, color = '#7A7E8C', dot = '#00D4A0' }: { children: React.ReactNode; color?: string; dot?: string }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 14 }}>
    <span style={{ width: 6, height: 6, background: dot, borderRadius: 1 }} />
    <span className="mono" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.1em', color }}>{children}</span>
  </div>
);

export default function PlayerProfilePage() {
  const params = useParams();
  const search = useSearchParams();
  const router = useRouter();
  const rawName = decodeURIComponent(String(params?.name || ''));
  const sport = (search.get('sport') || 'nba').toLowerCase();

  const [data, setData] = useState<PlayerIntel | null>(null);
  const [state, setState] = useState<'loading' | 'ready' | 'error'>('loading');
  const [dnaOpen, setDnaOpen] = useState(false);

  useEffect(() => {
    let active = true;
    setState('loading');
    fetch(`/api/stats/player/${encodeURIComponent(rawName)}?sport=${encodeURIComponent(sport)}`)
      .then((r) => r.json())
      .then((d) => { if (active) { setData(d); setState('ready'); } })
      .catch(() => { if (active) setState('error'); });
    return () => { active = false; };
  }, [rawName, sport]);

  if (state === 'loading') {
    return (
      <section style={{ minHeight: '50vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <p className="mono" style={{ color: 'var(--text-2)' }}>Loading player intelligence…</p>
      </section>
    );
  }
  if (state === 'error' || !data) {
    return (
      <section style={{ maxWidth: 600, margin: '0 auto', padding: '40px 16px' }}>
        <p className="mono" style={{ color: 'var(--miss)' }}>Could not load this player. Try again in a moment.</p>
      </section>
    );
  }

  const p = data;
  const dna = dnaRows(p.propDNA);

  return (
    <section style={{ maxWidth: 920, margin: '0 auto', padding: '20px 16px 120px' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 20, flexWrap: 'wrap' }}>
        <div className="mono" style={{ fontSize: 11, color: 'var(--g-a)', letterSpacing: '0.12em' }}>PLAYER · /{p.sport.toUpperCase()}</div>
        <button onClick={() => router.back()} className="mono" style={{ cursor: 'pointer', background: 'transparent', border: '1px solid var(--border-hi)', borderRadius: 6, padding: '6px 12px', fontSize: 11, color: 'var(--text-1)' }}>← Back</button>
      </div>

      {/* A. HERO */}
      <div style={{ position: 'relative', overflow: 'hidden', background: 'linear-gradient(160deg,#15151f,#08080F)', border: '1px solid var(--border)', borderRadius: 16, padding: 26, marginBottom: 14 }}>
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: 'repeating-linear-gradient(0deg, rgba(0,212,160,0.045) 0px, rgba(0,212,160,0.045) 1px, transparent 1px, transparent 4px)' }} />
        <div style={{ position: 'relative', display: 'flex', gap: 20, alignItems: 'flex-start', flexWrap: 'wrap' }}>
          <div className="mono" style={{ flex: 'none', width: 72, height: 72, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'radial-gradient(circle at 30% 25%, #14241F, #0A100E)', border: '1.5px solid #00D4A066', color: 'var(--g-a)', fontWeight: 700, fontSize: 30, boxShadow: '0 0 24px #00D4A022' }}>{initials(p.player)}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <h1 className="player-hero-name" style={{ margin: 0, fontSize: 30, fontWeight: 800, letterSpacing: '-0.015em', lineHeight: 1.05, overflowWrap: 'anywhere' }}>{p.player}</h1>
            <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
              <SportBadge sport={p.sport} />
              {p.team && <span className="mono" style={{ fontSize: 12, color: 'var(--text-1)' }}>{p.team}</span>}
              <span className="mono" style={{ fontSize: 12, color: 'var(--text-2)' }}>{sportLabel(p.sport)}</span>
            </div>
            {/* Session 58 (work-order 1.4/§11) — VYNDR-on-player: the model's
                settled record on THIS player. Deferred-render; self-hides
                until the ledger has rows for them. */}
            <div style={{ marginTop: 10 }}>
              <ModelRecord player={p.player} sport={p.sport} align="left" />
            </div>
            {p.archetype?.blend?.length > 0 && (
              <div style={{ marginTop: 15 }}>
                <div className="mono" style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', color: 'var(--g-a)', marginBottom: 9 }}>ARCHETYPE DNA</div>
                <ArchetypeBlend blend={p.archetype.blend} size="md" showLegend caption={blendReadout(p.archetype)} />
                {/* Session 60 (5.1, spec amendment) — define the term on-page:
                    one line from the archetype library under the dual bar.
                    The "What does this mean?" expander keeps the long version. */}
                {p.archetype.primary && archetypeInfo(p.archetype.primary)?.d && (
                  <div className="mono" style={{ marginTop: 8, fontSize: 11.5, color: 'var(--text-1)', lineHeight: 1.5 }}>
                    <span style={{ fontWeight: 800, color: 'var(--text-0)' }}>{String(p.archetype.primary).toUpperCase()}</span>
                    <span style={{ color: 'var(--text-2)' }}> — </span>{archetypeInfo(p.archetype.primary).d}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
        {p.season?.length > 0 && (
          <>
            <div style={{ position: 'relative', height: 1, background: 'var(--border)', margin: '20px 0 16px' }} />
            <div className="mono" style={{ position: 'relative', display: 'flex', gap: 28, flexWrap: 'wrap' }}>
              {p.season.map((s, i) => (
                <div key={i}><span style={{ fontSize: 20, color: '#fff', fontWeight: 600 }}>{s.v}</span> <span style={{ fontSize: 11, color: 'var(--text-1)' }}>{s.k}</span></div>
              ))}
            </div>
          </>
        )}
      </div>

      {/* I. INJURY */}
      {p.injury && (
        <div style={{ display: 'flex', gap: 13, alignItems: 'flex-start', background: 'linear-gradient(135deg,#1A1305,#0E0B05)', border: '1px solid #FFB34740', borderRadius: 12, padding: '15px 17px', marginBottom: 14 }}>
          <span style={{ flex: 'none', fontSize: 16 }}>⚠️</span>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
              <span className="mono" style={{ fontWeight: 700, fontSize: 12, color: 'var(--amber)', letterSpacing: '0.06em' }}>{p.injury.label}</span>
              <span style={{ fontSize: 13, color: 'var(--text-0)' }}>{p.injury.note}</span>
            </div>
            <div className="mono" style={{ marginTop: 7, fontSize: 12, color: 'var(--text-1)' }}><span style={{ color: 'var(--amber)' }}>CASCADE</span> · {p.injury.cascade}</div>
          </div>
        </div>
      )}

      {/* Session 60 (night2/C) — active streaks join the dossier (FREE layer,
          through the lens). Self-hides when the player has none. */}
      <PlayerStreaks player={p.player} sport={p.sport} />

      {/* B. PROP DNA */}
      {dna.length > 0 && (
        <div className="intel-surface" style={{ borderRadius: 14, padding: 20, marginBottom: 14, border: '1px solid rgba(0,212,160,0.22)' }}>
          <SectionLabel color="var(--g-a)">PROP DNA</SectionLabel>
          <p style={{ margin: '0 0 16px', fontSize: 12, color: '#7E8A86', maxWidth: 520 }}>Which props this archetype makes reliable vs. volatile — unique to VYNDR.</p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10 }} className="terminal-grid">
            {dna.map((d, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'rgba(0,0,0,0.25)', border: '1px solid rgba(255,255,255,0.05)', borderRadius: 9, padding: '11px 13px' }}>
                <span style={{ flex: 'none', width: 9, height: 9, borderRadius: '50%', background: d.color, boxShadow: `0 0 8px ${d.color}` }} />
                <span style={{ fontWeight: 600, fontSize: 13, color: 'var(--text-0)' }}>{d.prop}</span>
                <span className="mono" style={{ marginLeft: 'auto', fontSize: 10, fontWeight: 600, letterSpacing: '0.06em', color: d.color }}>{d.state}</span>
              </div>
            ))}
          </div>
          {p.education && (
            <>
              <button onClick={() => setDnaOpen((o) => !o)} className="mono" style={{ marginTop: 14, cursor: 'pointer', background: 'transparent', border: 'none', padding: 0, fontSize: 11, fontWeight: 600, color: 'var(--g-a)', letterSpacing: '0.04em' }}>What does this mean? ⌄</button>
              {dnaOpen && <p style={{ margin: '12px 0 0', paddingTop: 13, borderTop: '1px solid rgba(0,212,160,0.16)', fontSize: 13, lineHeight: 1.65, color: '#A8B2AE', maxWidth: 640 }}>{p.education}</p>}
            </>
          )}
        </div>
      )}

      {/* C. VYNDR INTELLIGENCE */}
      {p.intel?.length > 0 && (
        <div className="intel-surface" style={{ borderRadius: 14, padding: 20, marginBottom: 14, border: '1px solid rgba(0,212,160,0.22)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 16 }}>
            <span style={{ width: 6, height: 6, background: 'var(--g-a)', borderRadius: 1 }} />
            <span className="mono" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.1em', color: 'var(--g-a)' }}>VYNDR INTELLIGENCE</span>
            <span style={{ flex: 1, height: 1, background: 'rgba(0,212,160,0.14)' }} />
            <span className="mono" style={{ fontSize: 10, color: 'var(--text-2)' }}>proprietary</span>
          </div>
          <div className="terminal-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 1, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.05)', borderRadius: 10, overflow: 'hidden' }}>
            {p.intel.map((m, i) => (
              <div key={i} style={{ background: '#080D0C', padding: '14px 15px', minHeight: 74, display: 'flex', flexDirection: 'column', gap: 7 }}>
                <span className="mono" style={{ fontSize: 9.5, color: 'var(--text-2)', letterSpacing: '0.06em' }}>{m.label}</span>
                {m.kind === 'grade' ? (
                  <GradeBadge grade={m.value} size="md" />
                ) : m.kind === 'form' ? (
                  <>
                    <div className="mono" style={{ fontSize: 22, fontWeight: 600, color: m.color }}>{m.value}</div>
                    <div style={{ height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.08)', overflow: 'hidden' }}><div style={{ height: '100%', width: m.score, background: m.color, boxShadow: `0 0 8px ${m.color}` }} /></div>
                  </>
                ) : (
                  <div className="mono" style={{ fontSize: 18, fontWeight: 600, color: m.color }}>{m.value}</div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* C2. PITCHER IDENTITY (Wave 5B) — Baseball Savant arsenal lens. MLB only;
          the component (heading included) SELF-HIDES for non-pitchers / when
          Savant has no arsenal. Context, not a graded market value. */}
      {p.sport === 'mlb' && (
        <PitcherArsenal name={p.player} sport={p.sport} heading pitcher={{ name: p.player, team: p.team }} />
      )}

      {/* D. ACTIVE PROPS */}
      {p.activeProps?.length > 0 && (
        <>
          <SectionLabel>ACTIVE PROPS · TONIGHT</SectionLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginBottom: 8 }}>
            {p.activeProps.map((pr, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap', background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 11, padding: '13px 16px' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, minWidth: 150 }}>
                  <span style={{ fontWeight: 700, fontSize: 14, color: '#fff' }}>{pr.stat}</span>
                  <span className="mono" style={{ fontSize: 12, color: 'var(--text-1)' }}>{pr.side} {pr.line}</span>
                </div>
                <GradeBadge grade={pr.grade} size="md" />
                {pr.confidence && <span className="mono" style={{ fontSize: 12, color: 'var(--text-1)' }}>conf <span style={{ color: '#B8BCC8' }}>{pr.confidence}</span></span>}
                <a href={`/scan?player=${encodeURIComponent(p.player)}&stat=${encodeURIComponent(pr.stat)}`} className="mono" style={{ marginLeft: 'auto', cursor: 'pointer', background: 'transparent', border: '1px solid var(--g-a)', borderRadius: 7, padding: '7px 13px', fontSize: 11, fontWeight: 600, letterSpacing: '0.04em', color: 'var(--g-a)', textDecoration: 'none' }}>GRADE PROP →</a>
              </div>
            ))}
          </div>
        </>
      )}

      {/* E/F. SEASON + LAST 10 */}
      {(p.season?.length > 0 || p.last10?.length > 0) && (
        <div className="terminal-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 24 }}>
          {p.season?.length > 0 && (
            <div style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12, padding: 18 }}>
              <SectionLabel>SEASON STATS</SectionLabel>
              <div className="mono" style={{ display: 'flex', flexDirection: 'column' }}>
                {p.season.map((r, i) => (
                  <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderTop: i ? '1px solid #14141E' : 'none', fontSize: 12 }}>
                    <span style={{ color: 'var(--text-1)' }}>{r.k}</span>
                    <span style={{ color: '#fff', fontWeight: 600 }}>{r.v}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
          {p.last10?.length > 0 && (
            <div style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12, padding: 18 }}>
              <SectionLabel>LAST 10</SectionLabel>
              <div className="mono" style={{ display: 'flex', flexDirection: 'column' }}>
                {p.last10.map((g, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderTop: i ? '1px solid #14141E' : 'none', fontSize: 11 }}>
                    <span style={{ color: 'var(--text-1)', width: 48 }}>{g.d}</span>
                    <span style={{ color: 'var(--text-1)', width: 58 }}>{g.opp}</span>
                    <span style={{ color: '#C8CCD6', flex: 1, textAlign: 'right' }}>{g.stat}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* G/H. SPLITS + GRADE HISTORY */}
      {(p.splits?.length > 0 || p.gradeHistory?.length > 0) && (
        <div className="terminal-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 14 }}>
          {p.splits?.length > 0 && (
            <div style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12, padding: 18 }}>
              <SectionLabel>SPLITS</SectionLabel>
              <div className="mono" style={{ display: 'flex', flexDirection: 'column', fontSize: 12 }}>
                {p.splits.map((r, i) => (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 12, padding: '7px 0', borderTop: i ? '1px solid #14141E' : 'none' }}>
                    <span style={{ color: 'var(--text-1)' }}>{r.k}</span>
                    <span style={{ color: '#fff', fontWeight: 600 }}>{r.a}</span>
                    <span style={{ color: '#C8CCD6' }}>{r.b}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
          {p.gradeHistory?.length > 0 && (
            <div style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12, padding: 18 }}>
              <SectionLabel>GRADE HISTORY</SectionLabel>
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                {p.gradeHistory.map((g, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderTop: i ? '1px solid #14141E' : 'none' }}>
                    <GradeBadge grade={g.grade} size="sm" />
                    <span className="mono" style={{ fontSize: 12, color: 'var(--text-1)' }}>{g.prop}</span>
                    {g.hit && <span className="mono" style={{ marginLeft: 'auto', fontSize: 10, fontWeight: 700, color: 'var(--hit)' }}>● HIT</span>}
                    {g.miss && <span className="mono" style={{ marginLeft: 'auto', fontSize: 10, fontWeight: 700, color: 'var(--miss)' }}>● MISS</span>}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Empty state when there is no graded prop yet */}
      {!p.found && (
        <div style={{ marginTop: 24, padding: 20, border: '1px dashed var(--border-hi)', borderRadius: 12, textAlign: 'center' }}>
          <p className="mono" style={{ color: 'var(--text-1)', fontSize: 13 }}>No graded props for {p.player} tonight.</p>
          <p style={{ color: 'var(--text-2)', fontSize: 12, marginTop: 6 }}>The archetype + prop DNA above still apply. Check back when tonight&apos;s slate posts.</p>
        </div>
      )}
    </section>
  );
}
