// duel-result.jsx — GTO Duel match result screen (portrait + landscape split).
// Exports (to window): DuelResult({ onPlayAgain, onViewProfile, landscape })

function HPChart({ w = 330, h = 150 }) {
  const padL = 30, padB = 18, padT = 8, padR = 8;
  const innerW = w - padL - padR, innerH = h - padT - padB;
  const maxX = 5, maxHP = 1000;
  const X = (x) => padL + (x / maxX) * innerW;
  const Y = (v) => padT + (1 - v / maxHP) * innerH;
  const hero = [[0, 1000], [3.6, 1000], [4.0, 940], [4.4, 760], [4.7, 470], [4.9, 180], [5, 0]];
  const opp = [[0, 1000], [5, 1000]];
  const toPath = (pts) => pts.map((p, i) => `${i ? 'L' : 'M'}${X(p[0]).toFixed(1)} ${Y(p[1]).toFixed(1)}`).join(' ');
  const grid = [0, 250, 500, 750, 1000];
  return (
    <svg width="100%" viewBox={`0 0 ${w} ${h}`} style={{ display: 'block' }}>
      {grid.map((g) => (
        <g key={g}>
          <line x1={padL} y1={Y(g)} x2={w - padR} y2={Y(g)} stroke="rgba(255,255,255,0.08)" strokeWidth="1" strokeDasharray={g === 0 ? '0' : '3 4'} />
          <text x={padL - 6} y={Y(g) + 3} textAnchor="end" fontSize="8" fontFamily="var(--op-font-ui)" fill="rgba(255,255,255,0.4)">{g}</text>
        </g>
      ))}
      <text x={w - padR} y={padT + 8} textAnchor="end" fontSize="9" fontFamily="var(--op-font-ui)" fontWeight="700" fill="rgba(255,255,255,0.4)">1&#215;</text>
      {[0, 5].map((x) => <text key={x} x={X(x)} y={h - 4} textAnchor="middle" fontSize="8" fontFamily="var(--op-font-ui)" fill="rgba(255,255,255,0.4)">{x}</text>)}
      <path d={toPath(opp)} fill="none" stroke="#FB81CA" strokeWidth="2.5" strokeLinecap="round" />
      <path d={toPath(hero)} fill="none" stroke="#6C5CE7" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function CompareRow({ label, you, ai, youWin, aiWin }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr auto auto', alignItems: 'center', gap: 12, padding: '11px 2px', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
      <span style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 400, fontSize: 13, color: 'rgba(255,255,255,0.7)' }}>{label}</span>
      <span style={{ width: 64, textAlign: 'right', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 14, color: '#fff' }}>{you}{youWin && ' \uD83C\uDFC6'}</span>
      <span style={{ width: 76, textAlign: 'right', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 14, color: '#fff' }}>{ai}{aiWin && ' \uD83C\uDFC6'}</span>
    </div>
  );
}

function GradePill({ text, tone }) {
  const tones = {
    blunder: { bg: 'rgba(231,76,60,0.16)', fg: '#EC7265' },
    aggressive: { bg: 'rgba(233,154,40,0.16)', fg: '#E9B663' },
    tight: { bg: 'rgba(80,181,255,0.16)', fg: '#50B5FF' },
  };
  const t = tones[tone] || tones.blunder;
  return <span style={{ background: t.bg, color: t.fg, borderRadius: 6, padding: '3px 8px', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 10.5, letterSpacing: '0.04em', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>{text}</span>;
}

function RKV({ k, v, vColor = '#fff' }) {
  return (
    <div>
      <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 600, fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.4)', marginBottom: 2 }}>{k}</div>
      <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 13, color: vColor }}>{v}</div>
    </div>
  );
}

function MistakeCard({ row }) {
  return (
    <DarkCard pad={13} style={{ marginBottom: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 12, color: 'rgba(255,255,255,0.4)' }}>#{row.n}</span>
          <CardRow codes={row.hand} w={26} />
          <span style={{ color: 'rgba(255,255,255,0.25)', fontSize: 12 }}>on</span>
          <CardRow codes={row.board} w={24} />
        </span>
        <GradePill text={row.grade} tone={row.tone} />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px 14px' }}>
        <RKV k="Facing" v={row.facing} />
        <RKV k="Direction" v={row.direction} vColor="#E9B663" />
        <RKV k="Correct" v={row.correct} vColor="var(--op-green-30)" />
        <RKV k="Picked" v={row.picked} vColor="var(--op-red-40)" />
        <RKV k="Size" v={row.size} />
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'flex-end' }}>
          <button className="op-tap" style={{ display: 'flex', alignItems: 'center', gap: 5, background: 'rgba(108,92,231,0.16)', border: '1px solid rgba(108,92,231,0.35)', borderRadius: 8, padding: '5px 10px', cursor: 'pointer', color: 'var(--op-exodus-50)', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 11 }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" /></svg>
            Study
          </button>
        </div>
      </div>
    </DarkCard>
  );
}

function Legend({ color, label }) {
  return (
    <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <span style={{ width: 14, height: 3, borderRadius: 2, background: color }}></span>
      <span style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 600, fontSize: 11, color: 'rgba(255,255,255,0.6)' }}>{label}</span>
    </span>
  );
}

function SummaryStat({ label, value, sub, color = '#fff', border }) {
  return (
    <DarkCard pad={14} style={{ textAlign: 'center', borderColor: border || 'rgba(255,255,255,0.07)' }}>
      <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 10.5, letterSpacing: '0.08em', color: 'rgba(255,255,255,0.45)' }}>{label}</div>
      <div style={{ fontFamily: 'var(--op-font-display)', fontWeight: 700, fontSize: 28, color, marginTop: 4 }}>{value}</div>
      <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 600, fontSize: 10.5, color: 'rgba(255,255,255,0.4)' }}>{sub}</div>
    </DarkCard>
  );
}

const MISTAKES = [
  { n: 5, hand: ['7h', 'Qc'], board: ['2c', '3d', 'Kd'], facing: 'No action', correct: 'Check', picked: 'Bet 57.58', direction: 'Too aggressive', grade: 'Blunder', tone: 'blunder', size: '14.4% pot' },
];

function DuelResult({ onPlayAgain, onViewProfile, landscape }) {
  const win = false; // demo: opponent wins

  const outcomeTitle = (
    <div style={{
      fontFamily: 'var(--op-font-display)', fontWeight: 700, fontSize: 30, lineHeight: 1.05,
      background: win ? 'linear-gradient(180deg, #4DDB8A, #27BF69)' : 'linear-gradient(180deg, #ABA2F1, #6C5CE7)',
      WebkitBackgroundClip: 'text', backgroundClip: 'text', WebkitTextFillColor: 'transparent',
    }}>{win ? 'You win' : 'Opponent wins'}</div>
  );
  const endReason = <div style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 400, fontSize: 12.5, color: 'rgba(255,255,255,0.45)', marginTop: 4 }}>End reason: ko</div>;

  const playAgainBtn = (
    <button onClick={onPlayAgain} className="op-tap" style={{
      flex: 1, cursor: 'pointer', border: 'none', borderRadius: 12, background: 'linear-gradient(180deg, #7C6BF0, #6C5CE7)', color: '#fff',
      padding: '15px 0', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 14, letterSpacing: '0.04em', boxShadow: '0 10px 28px rgba(108,92,231,0.5)',
    }}>Play Again</button>
  );
  const viewProfileBtn = (
    <button onClick={onViewProfile} className="op-tap" style={{
      flex: 1, cursor: 'pointer', background: 'none', border: '1px solid rgba(255,255,255,0.2)', borderRadius: 12, color: '#fff',
      padding: '15px 0', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 14, letterSpacing: '0.04em',
    }}>View Profile</button>
  );

  const youStat = <SummaryStat label="YOU" value="0" sub="final HP" color={win ? 'var(--op-green-30)' : '#fff'} border={win ? 'rgba(77,219,138,0.4)' : null} />;
  const aiStat = <SummaryStat label={win ? 'AI (ADVANCED)' : 'AI (ADVANCED) \uD83C\uDFC6'} value="1000" sub="final HP" color={!win ? 'var(--op-gold-50)' : '#fff'} border={!win ? 'rgba(233,182,99,0.4)' : null} />;
  const accStat = <SummaryStat label="ACCURACY" value="66.7%" sub="2 / 3" />;
  const blunderStat = <SummaryStat label="BLUNDERS" value="1" sub="this match" color="var(--op-red-40)" />;

  const chartBlock = (
    <div>
      <Eyebrow style={{ marginBottom: 10 }}>HP over time</Eyebrow>
      <DarkCard pad={12} style={{ marginBottom: 20 }}>
        <HPChart />
        <div style={{ display: 'flex', gap: 18, justifyContent: 'center', marginTop: 8 }}>
          <Legend color="#6C5CE7" label="You" />
          <Legend color="#FB81CA" label="AI (Advanced)" />
        </div>
      </DarkCard>
    </div>
  );

  const compareBlock = (
    <div>
      <Eyebrow style={{ marginBottom: 10 }}>Match comparison</Eyebrow>
      <DarkCard pad={15} style={{ marginBottom: 20 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 12, paddingBottom: 8, borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
          <span style={{ fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.4)' }}>Stat</span>
          <span style={{ width: 64, textAlign: 'right', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.4)' }}>You</span>
          <span style={{ width: 76, textAlign: 'right', fontFamily: 'var(--op-font-ui)', fontWeight: 700, fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.4)' }}>AI</span>
        </div>
        <CompareRow label="Final HP" you="0" ai="1000" aiWin />
        <CompareRow label="Decisions faced" you="3" ai="2" />
        <CompareRow label="Perfect decisions" you="2" ai="2" />
        <CompareRow label="RNG mistakes" you="0" ai="0" />
        <CompareRow label="EV mistakes" you="0" ai="0" />
        <CompareRow label="Blunders" you="1" ai="0" aiWin />
        <CompareRow label="Max streak" you="2" ai="2" />
        <CompareRow label="Power-ups (T1/T2)" you="0 / 0" ai="0 / 0" />
      </DarkCard>
    </div>
  );

  const mistakeBlock = (
    <React.Fragment>
      <Eyebrow style={{ marginBottom: 10 }}>Mistake Log</Eyebrow>
      {MISTAKES.map((m) => <MistakeCard key={m.n} row={m} />)}
    </React.Fragment>
  );

  // ---------- Landscape: split rail (outcome + summary + actions) | scrolling detail ----------
  if (landscape) {
    const sidebar = (
      <React.Fragment>
        <div>{outcomeTitle}{endReason}</div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {youStat}{aiStat}{accStat}{blunderStat}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 12 }}>{playAgainBtn}{viewProfileBtn}</div>
      </React.Fragment>
    );
    return (
      <ScreenShell landscape sidebar={sidebar}>
        {chartBlock}
        {compareBlock}
        {mistakeBlock}
      </ScreenShell>
    );
  }

  // ---------- Portrait ----------
  const header = (
    <div style={{ padding: '52px 16px 16px', textAlign: 'center', borderBottom: '1px solid rgba(255,255,255,0.06)', background: 'rgba(11,12,19,0.6)', backdropFilter: 'blur(8px)' }}>
      {outcomeTitle}{endReason}
    </div>
  );
  const footer = (
    <div style={{ display: 'flex', gap: 12, padding: '14px 16px 22px', borderTop: '1px solid rgba(255,255,255,0.06)', background: 'rgba(11,12,19,0.6)', backdropFilter: 'blur(8px)' }}>
      {playAgainBtn}{viewProfileBtn}
    </div>
  );
  return (
    <ScreenShell header={header} footer={footer} padBody={16}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 18 }}>
        {youStat}{aiStat}
      </div>
      {chartBlock}
      {compareBlock}
      {mistakeBlock}
    </ScreenShell>
  );
}

Object.assign(window, { DuelResult });
