// screen-debrief.jsx
// Final results / leaderboard screen.

const { useState: useSt4, useEffect: useEf4 } = React;

function DebriefScreen({ run, scores, onRestart, onResources }) {
  const total = (scores.datastream || 0) + (scores.heist || 0) + (scores.policy || 0);
  const passed = total >= 1500;

  const [reveal, setReveal] = useSt4(0);
  useEf4(() => {
    const t = setInterval(() => {
      setReveal((r) => {
        if (r >= 5) { clearInterval(t); return r; }
        return r + 1;
      });
    }, 320);
    return () => clearInterval(t);
  }, []);

  const grade = total >= 2500 ? 'S' : total >= 2000 ? 'A' : total >= 1500 ? 'B' : total >= 1000 ? 'C' : 'F';
  const gradeColor = {
    S: 'var(--neon-yellow)', A: 'var(--neon-lime)', B: 'var(--neon-cyan)',
    C: 'var(--neon-magenta)', F: 'var(--neon-red)'
  }[grade];

  const fakeBoard = [
    { rank: 1, squad: 'BLACK_KERNEL', score: 3120, role: 'cryptographer' },
    { rank: 2, squad: 'NEON_VECTOR', score: 2840, role: 'netrunner' },
    { rank: 3, squad: 'DROP_TABLE', score: 2330, role: 'archivist' },
    { rank: null, squad: run.squadName, score: total, role: run.role.id, you: true },
    { rank: 4, squad: 'PHANTOM_BIT', score: 1680, role: 'fixer' },
    { rank: 5, squad: 'VOID_LOOP', score: 1420, role: 'netrunner' },
  ].sort((a, b) => b.score - a.score).map((row, i) => ({ ...row, rank: i + 1 }));

  return (
    <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1.2fr 1fr', minHeight: 0 }}>
      {/* LEFT — Run results */}
      <div style={{ padding: '40px 56px', display: 'flex', flexDirection: 'column', gap: 24, minHeight: 0, overflow: 'auto' }}>
        <div>
          <div className="chip" style={{ marginBottom: 12, background: passed ? 'rgba(170,255,0,.1)' : 'rgba(255,51,85,.1)', color: passed ? 'var(--neon-lime)' : 'var(--neon-red)', borderColor: passed ? 'rgba(170,255,0,.4)' : 'rgba(255,51,85,.4)' }}>
            {passed ? '◉ MISSION SUCCESS' : '◉ MISSION INCOMPLETE'}
          </div>
          <h2 className="t-display flicker" style={{ fontSize: 64, letterSpacing: '0.04em', color: passed ? 'var(--neon-lime)' : 'var(--neon-red)', textShadow: `0 0 24px ${passed ? 'rgba(170,255,0,.5)' : 'rgba(255,51,85,.5)'}` }}>
            {passed ? 'OVERRIDE COMPLETE' : 'FIREWALL HOLDS'}
          </h2>
          <div style={{ fontSize: 13, color: 'var(--ink-60)', marginTop: 8, letterSpacing: '0.04em', maxWidth: 500 }}>
            {passed
              ? 'Squad extracted full term intel. Mainframe access granted. Knowledge persists across reboots.'
              : 'Insufficient datastream coverage. Some policies remain encrypted. Recommend re-run.'}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 200px', gap: 24, alignItems: 'flex-start' }}>
          {/* Score breakdown */}
          <div className="panel" style={{ padding: 20 }}>
            <div className="chip" style={{ marginBottom: 16 }}>◇ XP BREAKDOWN</div>
            <ScoreRow label="01 / DATASTREAM" value={scores.datastream || 0} reveal={reveal >= 1} accent="var(--neon-cyan)" />
            <ScoreRow label="02 / HEIST" value={scores.heist || 0} reveal={reveal >= 2} accent="var(--neon-magenta)" />
            <ScoreRow label="03 / FIREWALL" value={scores.policy || 0} reveal={reveal >= 3} accent="var(--neon-yellow)" />
            <div style={{ borderTop: '1px solid rgba(0,234,255,.2)', marginTop: 12, paddingTop: 12 }}>
              <ScoreRow label="TOTAL XP" value={total} reveal={reveal >= 4} accent="var(--ink-100)" big />
            </div>
          </div>

          {/* Grade card */}
          <div className="panel panel-magenta" style={{ padding: 24, textAlign: 'center', minHeight: 200, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
            <div className="chip chip-magenta" style={{ alignSelf: 'center' }}>◇ FINAL GRADE</div>
            <div className="t-display flicker" style={{
              fontSize: 120, color: gradeColor, lineHeight: 1, letterSpacing: '0.02em',
              textShadow: `0 0 32px ${gradeColor}`,
              opacity: reveal >= 5 ? 1 : 0, transition: 'opacity .4s',
            }}>
              {grade}
            </div>
            <div style={{ fontSize: 10, color: 'var(--ink-60)', letterSpacing: '0.18em' }}>
              {grade === 'S' && 'TRANSCENDENT'}
              {grade === 'A' && 'EXEMPLARY'}
              {grade === 'B' && 'COMPETENT'}
              {grade === 'C' && 'BAREFOOT'}
              {grade === 'F' && 'COMPROMISED'}
            </div>
          </div>
        </div>

        {/* Achievement */}
        <div className="panel" style={{ padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{
            width: 48, height: 48, background: 'rgba(170,255,0,.1)', border: '1px solid var(--neon-lime)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'Orbitron', fontWeight: 800, fontSize: 22, color: 'var(--neon-lime)',
            textShadow: '0 0 8px rgba(170,255,0,.6)',
          }}>◈</div>
          <div style={{ flex: 1 }}>
            <div className="t-display" style={{ fontSize: 13, color: 'var(--neon-lime)', letterSpacing: '0.1em' }}>BADGE UNLOCKED</div>
            <div style={{ fontSize: 11, color: 'var(--ink-80)', marginTop: 4, lineHeight: 1.5 }}>
              {passed
                ? '◇ SYLLABUS_DECODER — You read the policies. Your squad will thank you.'
                : '◇ FIRST_RUN — Every run teaches the system. Try again.'}
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 16, marginTop: 'auto', flexWrap: 'wrap' }}>
          <button className="btn btn-primary" onClick={onRestart}>► RUN AGAIN</button>
          <button className="btn btn-ghost" onClick={() => window.location.reload()}>◇ NEW SQUAD</button>
          {onResources && (
            <button onClick={onResources} className="t-mono"
              style={{
                background: 'transparent',
                border: '1px solid rgba(255,45,149,.4)', color: 'var(--neon-magenta)',
                padding: '10px 18px', fontSize: 11, letterSpacing: '0.16em',
                cursor: 'pointer', textTransform: 'uppercase', marginLeft: 'auto',
              }}>
              ◢ SUPPORT_NET
            </button>
          )}
        </div>
      </div>

      {/* RIGHT — Leaderboard */}
      <div style={{ padding: '40px 56px 40px 0', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div className="panel" style={{ padding: 24, flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 16 }}>
            <div className="chip">◇ NETWORK LEADERBOARD</div>
            <div style={{ fontSize: 9, color: 'var(--ink-60)', letterSpacing: '0.18em' }}>SECTION-04 · LIVE</div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '32px 1fr 80px', gap: 8, fontSize: 9, color: 'var(--ink-60)', letterSpacing: '0.16em', textTransform: 'uppercase', paddingBottom: 8, borderBottom: '1px solid rgba(0,234,255,.15)', marginBottom: 8 }}>
            <div>RNK</div>
            <div>SQUAD</div>
            <div style={{ textAlign: 'right' }}>XP</div>
          </div>

          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4, overflowY: 'auto' }}>
            {fakeBoard.map((row) => {
              const role = SQUAD_ROLES.find(r => r.id === row.role);
              return (
                <div key={row.squad}
                  style={{
                    display: 'grid', gridTemplateColumns: '32px 1fr 80px', gap: 8,
                    padding: '12px 10px', alignItems: 'center',
                    background: row.you ? `linear-gradient(90deg, ${role.accent}22, transparent)` : 'transparent',
                    border: row.you ? `1px solid ${role.accent}88` : '1px solid transparent',
                    borderLeft: `3px solid ${row.rank === 1 ? 'var(--neon-yellow)' : row.you ? role.accent : 'transparent'}`,
                  }}
                >
                  <div className="t-display" style={{
                    fontSize: 14, color: row.rank === 1 ? 'var(--neon-yellow)' : row.you ? role.accent : 'var(--ink-60)',
                    letterSpacing: '0.04em',
                  }}>{String(row.rank).padStart(2, '0')}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                    <div style={{
                      width: 22, height: 22, background: `${role.accent}22`, border: `1px solid ${role.accent}aa`,
                      color: role.accent, display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: 'Orbitron', fontWeight: 800, fontSize: 11,
                    }}>{role.glyph}</div>
                    <div style={{ minWidth: 0 }}>
                      <div className="t-display" style={{ fontSize: 12, color: 'var(--ink-100)', letterSpacing: '0.06em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {row.squad}{row.you && <span style={{ color: role.accent, marginLeft: 6 }}>◆</span>}
                      </div>
                    </div>
                  </div>
                  <div className="t-display" style={{ fontSize: 13, textAlign: 'right', color: row.you ? role.accent : 'var(--ink-100)', letterSpacing: '0.04em', fontVariantNumeric: 'tabular-nums' }}>
                    {row.score.toLocaleString()}
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid rgba(0,234,255,.15)', fontSize: 10, color: 'var(--ink-60)', lineHeight: 1.6 }}>
            ◇ Top squad of the week earns extra-credit cycles. Decryption never sleeps.
          </div>
        </div>
      </div>
    </div>
  );
}

function ScoreRow({ label, value, reveal, accent, big }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '8px 0' }}>
      <div className="t-display" style={{ fontSize: big ? 13 : 11, color: 'var(--ink-60)', letterSpacing: '0.12em' }}>
        {label}
      </div>
      <div className="t-display" style={{
        fontSize: big ? 26 : 18, color: accent, letterSpacing: '0.04em', fontVariantNumeric: 'tabular-nums',
        opacity: reveal ? 1 : 0, transform: reveal ? 'translateX(0)' : 'translateX(8px)',
        transition: 'all .3s', textShadow: big ? `0 0 12px ${accent}66` : 'none',
      }}>
        {reveal ? `+${value.toLocaleString()}` : '----'}
      </div>
    </div>
  );
}

window.DebriefScreen = DebriefScreen;
