// ============================================================
// screens/Match.jsx — Match playback with animated pitch
// ============================================================
const { useState: useState_M, useEffect: useEffect_M, useRef: useRef_M, useMemo: useMemo_M } = React;

function MatchScreen({ playerSquad, opponent, onFinish, simStyle }) {
  const match = useMemo_M(() => {
    const oppSquad = { cards: opponent.cards, name: opponent.name, teamKey: opponent.teamKey };
    const mySquad = { cards: playerSquad, name: 'Your XI', teamKey: 'player' };
    return window.simulateMatch(mySquad, oppSquad, { seed: Math.floor(Math.random()*1e9) });
  }, [playerSquad, opponent]);

  const [idx, setIdx] = useState_M(0);
  const [playing, setPlaying] = useState_M(true);
  const [speed, setSpeed] = useState_M(1);
  const [finished, setFinished] = useState_M(false);

  // auto-advance
  useEffect_M(() => {
    if (!playing || finished) return;
    const ev = match.events[idx];
    const dur = ev.kind === 'goal' ? 2400 : ev.kind === 'save' ? 1800 : ev.kind === 'miss' ? 1500 : ev.kind === 'buildup' ? 1400 : ev.kind === 'kickoff' ? 2000 : ev.kind === 'fulltime' ? 3000 : 1000;
    const t = setTimeout(() => {
      if (idx >= match.events.length - 1) {
        setFinished(true);
      } else {
        setIdx(i => i + 1);
      }
    }, dur / speed);
    return () => clearTimeout(t);
  }, [idx, playing, speed, match.events.length, finished]);

  const cur = match.events[idx];
  const scoreA = cur?.scoreA ?? 0;
  const scoreB = cur?.scoreB ?? 0;

  return (
    <div style={{ padding: '20px 32px', maxWidth: 1400, margin: '0 auto' }}>
      {/* Scoreboard */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 20,
        padding: '16px 24px',
        background: 'linear-gradient(180deg, #0e1114, #0a0d0e)',
        border: '1px solid #1a1f26', borderRadius: 12, marginBottom: 20,
      }}>
        <TeamBadge name="Your XI" color="#ffc43d" align="right" />
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '0 20px' }}>
          <ScoreDigit value={scoreA} flash={cur?.kind === 'goal' && cur?.team === 'A'} />
          <div style={{ color: '#5a6169', fontFamily: 'var(--font-mono)', fontSize: 13 }}>
            {cur?.kind === 'kickoff' ? "00'" : cur?.kind === 'fulltime' ? '90\'' : `${Math.round((cur?.t || 0) / match.events.length * 90)}'`}
          </div>
          <ScoreDigit value={scoreB} flash={cur?.kind === 'goal' && cur?.team === 'B'} />
        </div>
        <TeamBadge name={opponent.name} color={window.getOpponentDisplayColor(opponent.teamKey, '#8a9099')} align="left" />
        <div style={{ flex: 1 }} />
        <div style={{ fontSize: 10, color: '#5a6169', fontFamily: 'var(--font-mono)', letterSpacing: '0.1em' }}>
          SEED {match.seed.toString().padStart(9, '0')}
        </div>
      </div>

      {finished ? (
        <PostMatch match={match} opponent={opponent} onFinish={onFinish} />
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: simStyle === 'feed' ? '1fr' : simStyle === 'commentary' ? '1fr 1fr' : '1.3fr 1fr', gap: 20 }}>
          {simStyle !== 'feed' && (
            <PitchView match={match} curEvent={cur} squad={playerSquad} opponent={opponent} />
          )}
          {simStyle !== 'pitch_only' && (
            <Timeline events={match.events} idx={idx} onJump={setIdx} curEvent={cur} simStyle={simStyle} />
          )}
        </div>
      )}

      {/* Controls */}
      {!finished && (
        <div style={{
          marginTop: 16, display: 'flex', alignItems: 'center', gap: 12,
          padding: '12px 18px', background: '#0e1114', border: '1px solid #1a1f26', borderRadius: 8,
        }}>
          <button onClick={() => setPlaying(p=>!p)} style={btnStyle}>
            {playing ? '❚❚ Pause' : '▸ Play'}
          </button>
          <button onClick={() => setIdx(i => Math.max(0, i-1))} style={btnStyle}>◂ Prev</button>
          <button onClick={() => setIdx(i => Math.min(match.events.length-1, i+1))} style={btnStyle}>Next ▸</button>
          <button onClick={() => { setIdx(match.events.length-1); setTimeout(()=>setFinished(true), 100); }} style={btnStyle}>Skip to end ⏭</button>
          <div style={{ flex: 1 }} />
          <div style={{ fontSize: 10, color: '#5a6169', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Speed</div>
          {[0.5, 1, 2, 4].map(s => (
            <button key={s} onClick={()=>setSpeed(s)} style={{
              ...btnStyle,
              background: speed === s ? '#1e2329' : 'transparent',
              color: speed === s ? '#ffc43d' : '#8a9099',
            }}>{s}×</button>
          ))}
        </div>
      )}
    </div>
  );
}

const btnStyle = {
  background: 'transparent', border: '1px solid #1e2329',
  color: '#e6e8eb', padding: '6px 12px', fontSize: 11,
  borderRadius: 5, cursor: 'pointer', fontFamily: 'inherit',
  fontWeight: 600, letterSpacing: '0.04em',
};

function TeamBadge({ name, color, align }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 1, justifyContent: align === 'right' ? 'flex-end' : 'flex-start' }}>
      {align === 'left' && <div style={{ width: 8, height: 24, background: color, borderRadius: 2, boxShadow: `0 0 12px ${color}66` }} />}
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: '#fff', fontWeight: 600 }}>{name}</div>
      {align === 'right' && <div style={{ width: 8, height: 24, background: color, borderRadius: 2, boxShadow: `0 0 12px ${color}66` }} />}
    </div>
  );
}

function ScoreDigit({ value, flash }) {
  return (
    <div style={{
      fontFamily: 'var(--font-display)', fontSize: 44, fontWeight: 700,
      color: flash ? '#ffc43d' : '#fff',
      lineHeight: 1, minWidth: 32, textAlign: 'center',
      textShadow: flash ? '0 0 30px rgba(255,196,61,0.9)' : 'none',
      transition: 'all 0.2s',
      transform: flash ? 'scale(1.2)' : 'scale(1)',
    }}>{value}</div>
  );
}

// ---------- Pitch view ----------
function PitchView({ match, curEvent, squad, opponent }) {
  const ballX = curEvent?.ball?.x ?? 50;
  const ballY = curEvent?.ball?.y ?? 50;

  // Player dots: plan positions based on formation slots of the squad length
  const formation = window.FORMATIONS[squad.length] || window.FORMATIONS[5];
  const oppFormation = window.FORMATIONS[opponent.cards.length] || window.FORMATIONS[5];

  // Convert to pitch coords (0-100 both dims); player side uses same formation but mirrored
  const myDots = formation.slots.map((s, i) => {
    const card = window.CARDS.find(c => c.id === squad[i]);
    // Home side at bottom (y=50..100)
    return { x: s.x, y: 50 + (s.y/100)*50, card, side: 'A' };
  });
  const oppDots = oppFormation.slots.map((s, i) => {
    const card = window.CARDS.find(c => c.id === opponent.cards[i]);
    return { x: s.x, y: 50 - (s.y/100)*50, card, side: 'B' };
  });

  // Event flash: pulse player who scored/saved
  const flashId = (curEvent?.kind === 'goal' || curEvent?.kind === 'save' || curEvent?.kind === 'buildup' || curEvent?.kind === 'miss') ? curEvent.card : null;

  return (
    <div style={{
      position: 'relative',
      aspectRatio: '0.7',
      background: `
        repeating-linear-gradient(0deg, #0f1e15 0 36px, #0d1b13 36px 72px),
        linear-gradient(180deg, #0f1e15 0%, #0a140e 100%)
      `,
      borderRadius: 12,
      border: '1.5px solid #1a2820',
      overflow: 'hidden',
      boxShadow: 'inset 0 0 60px rgba(0,0,0,0.5)',
    }}>
      {/* Lines */}
      <svg viewBox="0 0 100 140" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <g fill="none" stroke="rgba(255,255,255,0.15)" strokeWidth="0.3">
          <rect x="2" y="2" width="96" height="136" />
          <line x1="2" y1="70" x2="98" y2="70" />
          <circle cx="50" cy="70" r="10" />
          <circle cx="50" cy="70" r="0.8" fill="rgba(255,255,255,0.3)" />
          <rect x="28" y="2" width="44" height="14" />
          <rect x="38" y="2" width="24" height="6" />
          <rect x="28" y="124" width="44" height="14" />
          <rect x="38" y="132" width="24" height="6" />
        </g>
      </svg>

      {/* Dots */}
      {[...oppDots, ...myDots].map((dot, i) => {
        if (!dot.card) return null;
        const isFlash = dot.card.id === flashId;
        const color = dot.side === 'A' ? '#ffc43d' : window.getOpponentDisplayColor(opponent.teamKey, '#3ea9ff');
        return (
          <div key={`${dot.side}-${i}`} style={{
            position: 'absolute',
            left: `${dot.x}%`, top: `${(dot.y/140)*100}%`,
            transform: 'translate(-50%,-50%)',
            transition: 'all 0.8s cubic-bezier(0.4, 0, 0.2, 1)',
          }}>
            <div style={{
              width: isFlash ? 20 : 14, height: isFlash ? 20 : 14, borderRadius: '50%',
              background: color,
              boxShadow: `0 0 ${isFlash ? 24 : 8}px ${color}`,
              border: '2px solid rgba(0,0,0,0.4)',
              transition: 'all 0.3s',
            }} />
            <div style={{
              position: 'absolute', top: '100%', left: '50%', transform: 'translateX(-50%)',
              fontSize: 8, color: '#fff', marginTop: 2, whiteSpace: 'nowrap',
              textShadow: '0 1px 2px rgba(0,0,0,0.9)', fontWeight: 600,
              opacity: isFlash ? 1 : 0.65,
            }}>{dot.card.name.split(' ').slice(-1)[0]}</div>
          </div>
        );
      })}

      {/* Ball */}
      <div key={`ball-${curEvent?.t}-${curEvent?.kind}`} style={{
        position: 'absolute',
        left: `${ballX}%`, top: `${(ballY/140)*100}%`,
        transform: 'translate(-50%,-50%)',
        transition: 'all 0.9s cubic-bezier(0.34, 1.26, 0.64, 1)',
        zIndex: 10,
      }}>
        <div style={{
          width: 10, height: 10, borderRadius: '50%',
          background: '#fff',
          boxShadow: '0 0 12px #fff, 0 2px 4px rgba(0,0,0,0.6)',
          border: '1px solid #0a0d0e',
        }} />
      </div>

      {/* Event overlay */}
      {curEvent?.kind === 'goal' && (
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(circle, rgba(255,196,61,0.2) 0%, transparent 70%)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          pointerEvents: 'none',
          animation: 'goalFlash 0.6s ease',
        }}>
          <div style={{
            fontFamily: 'var(--font-display)', fontSize: 80, fontWeight: 800,
            color: '#ffc43d', letterSpacing: '0.1em',
            textShadow: '0 0 40px rgba(255,196,61,0.9)',
            transform: 'skewY(-4deg)',
          }}>GOAL!</div>
        </div>
      )}

      {/* Caption strip */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 18px',
        background: 'linear-gradient(180deg, transparent, rgba(0,0,0,0.85))',
        color: '#fff', fontSize: 13, fontFamily: 'var(--font-sans)',
        fontWeight: 500, letterSpacing: '0.01em',
      }}>
        <span style={{
          display: 'inline-block', fontSize: 9, padding: '2px 6px', borderRadius: 3,
          background: eventColor(curEvent?.kind), color: '#0a0d0e', fontWeight: 700,
          letterSpacing: '0.08em', textTransform: 'uppercase', marginRight: 8,
        }}>{curEvent?.kind}</span>
        {curEvent?.text}
      </div>
    </div>
  );
}

function eventColor(kind) {
  return ({
    goal: '#ffc43d', save: '#3ea9ff', miss: '#ff5a3c',
    buildup: '#c69bff', midfield: '#8a9099', kickoff: '#58d07a',
    fulltime: '#ffc43d', ability: '#c69bff',
  })[kind] || '#8a9099';
}

// ---------- Timeline ----------
function Timeline({ events, idx, onJump, curEvent, simStyle }) {
  const ref = useRef_M(null);
  useEffect_M(() => {
    const el = ref.current?.querySelector(`[data-ev="${idx}"]`);
    if (el) el.scrollIntoView({ block: 'center', behavior: 'smooth' });
  }, [idx]);

  const visible = events.filter((_, i) => i <= idx);

  return (
    <div ref={ref} style={{
      background: '#0a0d0e', border: '1px solid #1a1f26', borderRadius: 12,
      padding: 16, maxHeight: 620, overflowY: 'auto',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12,
        paddingBottom: 10, borderBottom: '1px solid #1a1f26',
      }}>
        <span style={{
          fontSize: 10, color: '#ffc43d', letterSpacing: '0.12em',
          textTransform: 'uppercase', fontWeight: 700,
        }}>◉ LIVE</span>
        <div style={{ color: '#fff', fontSize: 12, fontFamily: 'var(--font-display)' }}>Match timeline</div>
      </div>
      {visible.map((e, i) => (
        <div key={i} data-ev={i} onClick={() => onJump(i)} style={{
          padding: '10px 4px 10px 12px',
          borderLeft: `2px solid ${eventColor(e.kind)}`,
          marginBottom: 6, cursor: 'pointer',
          background: i === idx ? 'rgba(255,196,61,0.06)' : 'transparent',
          borderRadius: '0 6px 6px 0',
          transition: 'background 0.2s',
        }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 3 }}>
            <span style={{
              fontSize: 9, color: eventColor(e.kind),
              textTransform: 'uppercase', letterSpacing: '0.12em', fontWeight: 700,
            }}>{e.kind}</span>
            <span style={{ fontSize: 10, color: '#5a6169', fontFamily: 'var(--font-mono)' }}>
              {e.kind === 'kickoff' ? '0\'' : e.kind === 'fulltime' ? '90\'' : `${Math.round((e.t || 0) / events.length * 90)}'`}
            </span>
            {(e.kind === 'goal' || e.scoreA !== undefined) && e.kind !== 'kickoff' && (
              <span style={{ fontSize: 10, color: '#8a9099', fontFamily: 'var(--font-mono)', marginLeft: 'auto' }}>
                {e.scoreA}–{e.scoreB}
              </span>
            )}
          </div>
          <div style={{
            color: e.kind === 'goal' ? '#ffc43d' : '#c4ccd4',
            fontSize: 13, lineHeight: 1.4,
            fontWeight: e.kind === 'goal' ? 600 : 400,
          }}>{e.text}</div>
        </div>
      ))}
    </div>
  );
}

// ---------- Post-match ----------
function PostMatch({ match, opponent, onFinish }) {
  const result = match.scoreA > match.scoreB ? 'VICTORY' : match.scoreA < match.scoreB ? 'DEFEAT' : 'DRAW';
  const resultCode = result === 'VICTORY' ? 'W' : result === 'DEFEAT' ? 'L' : 'D';
  const color = result === 'VICTORY' ? '#ffc43d' : result === 'DEFEAT' ? '#ff5a3c' : '#8a9099';
  const coins = result === 'VICTORY' ? 50 : result === 'DRAW' ? 25 : 10;
  const goals = match.events.filter(e => e.kind === 'goal');

  return (
    <div style={{
      background: 'linear-gradient(180deg, #0e1114, #0a0d0e)',
      border: `1px solid ${color}44`, borderRadius: 14, padding: 40,
      textAlign: 'center',
      boxShadow: `0 0 60px ${color}22`,
    }}>
      <div style={{
        fontSize: 11, color: color, letterSpacing: '0.25em',
        textTransform: 'uppercase', fontWeight: 700, marginBottom: 10,
      }}>◆ Full Time ◆</div>
      <div style={{
        fontFamily: 'var(--font-display)', fontSize: 80, fontWeight: 700,
        color, lineHeight: 1, marginBottom: 10,
        textShadow: `0 0 40px ${color}66`, letterSpacing: '0.04em',
      }}>{result}</div>
      <div style={{
        fontFamily: 'var(--font-display)', fontSize: 44, color: '#fff', fontWeight: 600, marginBottom: 24,
      }}>{match.scoreA} — {match.scoreB}</div>

      <div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginBottom: 30 }}>
        <Stat label="Coins" value={`+${coins}`} color="#ffc43d" />
        <Stat label="XP per card" value={`+${result === 'VICTORY' ? 20 : result === 'DRAW' ? 10 : 5}`} color="#3ea9ff" />
        <Stat label="Possession" value={`${Math.round(match.teamA.possession / (match.teamA.possession + match.teamB.possession) * 100)}%`} color="#58d07a" />
      </div>

      {goals.length > 0 && (
        <div style={{ textAlign: 'left', maxWidth: 460, margin: '0 auto 30px' }}>
          <div style={{
            fontSize: 10, color: '#5a6169', letterSpacing: '0.14em',
            textTransform: 'uppercase', fontWeight: 700, marginBottom: 10,
          }}>◆ Goalscorers</div>
          {goals.map((g, i) => {
            const card = window.CARDS.find(c => c.id === g.card);
            return (
              <div key={i} style={{
                padding: '8px 12px', background: '#0a0d0e', borderRadius: 6,
                marginBottom: 6, display: 'flex', justifyContent: 'space-between',
                border: '1px solid #1a1f26',
              }}>
                <span style={{ color: g.team === 'A' ? '#ffc43d' : '#c4ccd4' }}>
                  {card?.name || 'Unknown'}
                </span>
                <span style={{ color: '#5a6169', fontFamily: 'var(--font-mono)', fontSize: 11 }}>
                  {Math.round((g.t || 0) / match.events.length * 90)}'
                </span>
              </div>
            );
          })}
        </div>
      )}

      <button onClick={() => onFinish(resultCode)} style={{
        background: 'linear-gradient(135deg, #ffc43d, #ff9500)',
        color: '#0a0d0e', border: 'none', padding: '14px 32px',
        borderRadius: 8, fontFamily: 'var(--font-display)', fontSize: 17,
        fontWeight: 700, cursor: 'pointer', letterSpacing: '0.04em',
        boxShadow: '0 0 24px rgba(255,196,61,0.4)',
      }}>Continue ▸</button>
    </div>
  );
}

function Stat({ label, value, color }) {
  return (
    <div>
      <div style={{
        fontSize: 10, color: '#5a6169', letterSpacing: '0.12em',
        textTransform: 'uppercase', fontWeight: 700, marginBottom: 4,
      }}>{label}</div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, color, fontWeight: 700 }}>{value}</div>
    </div>
  );
}

window.MatchScreen = MatchScreen;
