'use client';

import { useEffect, useState } from 'react';
import GradeResultCard, { type GradeResultData } from '@/components/vyndr/GradeResultCard';

/** Minimal pulsing synapse mark (the full NeuralBrain lands with the living
 *  layer in Session 38). Uses brain-node / brain-link keyframes from globals. */
function MiniBrain({ size = 56 }: { size?: number }) {
  const nodes = [
    [12, 14], [30, 8], [46, 16], [20, 30], [40, 34], [28, 46], [50, 44], [10, 40],
  ];
  const links: [number, number][] = [[0, 1], [1, 2], [0, 3], [3, 4], [4, 6], [3, 5], [5, 6], [7, 3], [2, 4]];
  return (
    <svg width={size} height={size} viewBox="0 0 60 56" aria-hidden style={{ flexShrink: 0 }}>
      {links.map(([a, b], i) => (
        <line key={i} className="brain-link" x1={nodes[a][0]} y1={nodes[a][1]} x2={nodes[b][0]} y2={nodes[b][1]} stroke="var(--g-ap)" strokeWidth="1" opacity="0.5" />
      ))}
      {nodes.map(([x, y], i) => (
        <circle key={i} className="brain-node" cx={x} cy={y} r="2.6" fill="var(--g-ap)" style={{ animationDelay: `${(i % 5) * 0.2}s` }} />
      ))}
    </svg>
  );
}

interface ProcessingGradeProps {
  data: GradeResultData;
  replayKey?: number;
  onShare?: (d: GradeResultData) => void;
  onAddToParlay?: (d: GradeResultData) => void;
  onReadAnother?: () => void;
}

/**
 * The "brain weighing factors" moment before a grade resolves (§D.1.3). Factors
 * ignite sequentially (factor-ignite), a proc-scan bar sweeps, the % rail fills,
 * then the GradeResultCard reveals. Pure chrome — the underlying grade is fixed.
 */
export default function ProcessingGrade({ data, replayKey = 0, onShare, onAddToParlay, onReadAnother }: ProcessingGradeProps) {
  // Session 60 (night2/E, spec §7) — full reveal choreography:
  // analyzing steps → DECLASSIFIED stamp → card with 90ms-staggered panels.
  // Reduced-motion users skip straight to the card (chrome, never data).
  const [phase, setPhase] = useState<'proc' | 'stamp' | 'card'>('proc');
  const [lit, setLit] = useState(0);

  const factors = (data.signals || []).slice(0, 5);
  const total = factors.length || 1;

  useEffect(() => {
    if (typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      setPhase('card');
      return;
    }
    setPhase('proc');
    setLit(0);
    const stepMs = 190;
    const timers: ReturnType<typeof setTimeout>[] = [];
    for (let i = 1; i <= total; i++) timers.push(setTimeout(() => setLit(i), stepMs * i));
    timers.push(setTimeout(() => setPhase('stamp'), stepMs * total + 360));
    timers.push(setTimeout(() => setPhase('card'), stepMs * total + 360 + 700));
    return () => timers.forEach(clearTimeout);
  }, [replayKey, total]);

  if (phase === 'card') {
    return (
      <div className="grade-reveal">
        <GradeResultCard
          data={data}
          replayKey={replayKey}
          onShare={onShare}
          onAddToParlay={onAddToParlay}
          onReadAnother={onReadAnother}
        />
      </div>
    );
  }

  const pct = Math.round((lit / total) * 100);
  return (
    <div
      className="intel-surface"
      style={{ width: '100%', maxWidth: 640, margin: '0 auto', borderRadius: 12, overflow: 'hidden', border: '1px solid rgba(0,255,184,.25)', minHeight: 360, position: 'relative', boxShadow: '0 0 0 1px rgba(0,212,160,.18), 0 24px 70px -28px rgba(0,212,160,.35)' }}
      aria-label="Processing grade"
    >
      {/* §7 — the DECLASSIFIED stamp lands between analysis and the card. */}
      {phase === 'stamp' && (
        <div style={{ position: 'absolute', inset: 0, zIndex: 5, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(4,20,15,.55)' }}>
          <span
            className="mono stamp-in"
            style={{ fontSize: 30, fontWeight: 900, letterSpacing: '0.22em', color: 'var(--g-ap)', border: '3px solid var(--g-ap)', borderRadius: 6, padding: '10px 26px', transform: 'rotate(-7deg)', textShadow: '0 0 18px rgba(0,255,184,.7)', boxShadow: '0 0 30px rgba(0,255,184,.35), inset 0 0 22px rgba(0,255,184,.12)' }}
          >
            DECLASSIFIED
          </span>
        </div>
      )}
      <div className="proc-scan" style={{ position: 'absolute', left: 0, right: 0, top: 0, height: '30%', background: 'linear-gradient(180deg, transparent, rgba(0,255,184,.12) 50%, transparent)', zIndex: 1 }} />
      <div style={{ position: 'relative', zIndex: 2, padding: '26px 24px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 22 }}>
          <MiniBrain size={56} />
          <div>
            <div className="mono amber-glow" style={{ fontSize: 13, fontWeight: 700, letterSpacing: '0.12em', color: 'var(--g-ap)', textShadow: '0 0 10px rgba(0,255,184,.6)' }}>
              PROCESSING<span className="phosphor-cursor" style={{ height: 11, marginLeft: 3 }} />
            </div>
            <div className="mono" style={{ fontSize: 12, color: 'rgba(232,255,244,.65)', marginTop: 4 }}>
              {data.player} · {data.side} {data.line} {data.stat}
            </div>
          </div>
          <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
            <div className="mono" style={{ fontSize: 30, fontWeight: 800, color: 'var(--g-ap)', textShadow: '0 0 16px rgba(0,255,184,.5)' }}>{pct}%</div>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.12em', color: 'rgba(232,255,244,.5)' }}>WEIGHING THE FACTORS</div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {factors.map((f, i) => {
            const on = i < lit;
            return (
              <div key={i} className={on ? 'factor-ignite' : ''} style={{ display: 'flex', alignItems: 'center', gap: 12, opacity: on ? 1 : 0.18, transition: 'opacity .2s' }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', flexShrink: 0, background: on ? 'var(--g-ap)' : 'rgba(232,255,244,.3)', boxShadow: on ? '0 0 10px rgba(0,255,184,.8)' : 'none' }} />
                <span className="mono" style={{ fontSize: 13, color: on ? '#e8fff4' : 'rgba(232,255,244,.4)' }}>{f}</span>
                {on && <span className="mono" style={{ marginLeft: 'auto', fontSize: 10.5, color: 'var(--g-ap)', letterSpacing: '0.08em' }}>✓ WEIGHED</span>}
              </div>
            );
          })}
        </div>

        <div style={{ marginTop: 24, height: 4, background: 'rgba(0,0,0,.35)', borderRadius: 3, overflow: 'hidden' }}>
          <div style={{ width: `${pct}%`, height: '100%', background: 'linear-gradient(90deg, var(--acc-1), var(--g-ap))', borderRadius: 3, transition: 'width .18s ease-out', boxShadow: '0 0 10px rgba(0,255,184,.6)' }} />
        </div>
      </div>
    </div>
  );
}
