// matchView.jsx - live HLTV-style match simulation
const { useState: useStX, useEffect: useEfX, useRef: useRfX, useMemo: useMmX } = React;

const SPEEDS = [
  { id:'Lento', label:'Lento', delay:1500 },
  { id:'Normal', label:'Normal', delay:900 },
  { id:'Rapido', label:'Rápido', delay:300 },
  { id:'Ultra', label:'Ultra', delay:80 },
];
const DEFAULT_SPEED = 'Normal';

function normalizeSpeed(speed) {
  return SPEEDS.some(s => s.id === speed) ? speed : DEFAULT_SPEED;
}

function speedDelay(speed) {
  return (SPEEDS.find(s => s.id === normalizeSpeed(speed)) || SPEEDS[1]).delay;
}

function speedStep(speed) {
  const normalized = normalizeSpeed(speed);
  if (normalized === 'Ultra') return 4;
  if (normalized === 'Rapido') return 2;
  return 1;
}

function MatchView({ matchContext, onMatchComplete, speedPreference = DEFAULT_SPEED, onSpeedChange }) {
  const isMobile = window.useIsMobileView?.(760) || false;
  const { teamA, teamB, map, seed, bo, mapIndex, seriesScore } = matchContext;
  const matchFormat = window.getMatchFormat(matchContext.matchFormat || 'MR16');
  const mapKey = `${matchContext.matchId}-${mapIndex || 0}-${map}`;

  const matchData = useMmX(() =>
    window.simulateMatch(teamA.players, teamB.players, map, seed + (mapIndex || 0) * 997, matchFormat.id),
    [teamA.id, teamB.id, map, seed, mapIndex, matchFormat.id]
  );

  const [revealed, setRevealed] = useStX(0);
  const [speed, setSpeedState] = useStX(normalizeSpeed(speedPreference));
  const [phase, setPhase] = useStX('playing');
  const intervalRef = useRfX(null);

  const totalRounds = matchData.rounds.length;
  const mySide = teamA.isMyTeam ? 'A' : 'B';

  useEfX(() => {
    clearInterval(intervalRef.current);
    setRevealed(0);
    setPhase('playing');
    setSpeedState(normalizeSpeed(speedPreference));
    return () => clearInterval(intervalRef.current);
  }, [mapKey]);

  function setSpeed(nextSpeed) {
    const normalized = normalizeSpeed(nextSpeed);
    setSpeedState(normalized);
    if (onSpeedChange) onSpeedChange(normalized);
  }

  const visStats = useMmX(() => {
    if (revealed === 0) return { A:initStats(teamA.players), B:initStats(teamB.players) };
    const rd = matchData.rounds[Math.min(revealed, totalRounds) - 1];
    return {
      A: rd?.snapA || initStats(teamA.players),
      B: rd?.snapB || initStats(teamB.players),
    };
  }, [revealed, matchData, teamA.players, teamB.players, totalRounds]);

  const curRound = matchData.rounds[Math.max(0, revealed - 1)];
  const scoreA = curRound ? curRound.scoreA : 0;
  const scoreB = curRound ? curRound.scoreB : 0;
  const myDisplayScore = mySide === 'A' ? scoreA : scoreB;
  const opponentDisplayScore = mySide === 'A' ? scoreB : scoreA;
  const myWonMap = (teamA.isMyTeam && matchData.winner === 'A') || (teamB.isMyTeam && matchData.winner === 'B');
  const mapMeta = window.MAPS.find(m => m.id === map) || { id:map, name:map, color:'var(--accent)' };

  useEfX(() => {
    if (phase !== 'playing') return;
    clearInterval(intervalRef.current);
    const step = speedStep(speed);
    intervalRef.current = setInterval(() => {
      setRevealed(r => {
        if (r >= totalRounds) {
          clearInterval(intervalRef.current);
          setPhase('done');
          return r;
        }
        const next = Math.min(totalRounds, r + step);
        if (next >= totalRounds) {
          clearInterval(intervalRef.current);
          setPhase('done');
        }
        return next;
      });
    }, speedDelay(speed));
    return () => clearInterval(intervalRef.current);
  }, [speed, phase, totalRounds, mapKey]);

  function skip() {
    clearInterval(intervalRef.current);
    setRevealed(totalRounds);
    setPhase('done');
  }

  function handleComplete() {
    onMatchComplete(matchData);
  }

  return (
    <main style={{ maxWidth:940, margin:'0 auto', padding:isMobile ? '14px 14px 42px' : '24px 20px 60px' }}>
      <MapContextPanel
        mapMeta={mapMeta}
        teamA={teamA}
        teamB={teamB}
        scoreA={scoreA}
        scoreB={scoreB}
        bo={bo}
        mapIndex={mapIndex}
        seriesScore={seriesScore}
        phase={phase}
        revealed={revealed}
        totalRounds={totalRounds}
        matchFormat={matchFormat}
        speed={speed}
        setSpeed={setSpeed}
        skip={skip}
        mySide={mySide}
      />

      {isMobile && phase === 'done' && (
        <div style={{ margin:'10px 0 12px', padding:'10px 12px',
          background: myWonMap ? 'rgba(244,165,35,0.07)' : 'rgba(144,48,48,0.07)',
          border:`1px solid ${myWonMap ? 'rgba(244,165,35,0.3)' : 'rgba(144,48,48,0.3)'}`,
          borderRadius:'var(--r-lg)', display:'flex', alignItems:'center',
          justifyContent:'space-between', gap:10 }}>
          <div style={{ minWidth:0 }}>
            <div style={{ fontFamily:'var(--font-cond)', fontWeight:800, fontSize:13,
              color: myWonMap ? 'var(--accent)' : '#f07070',
              letterSpacing:'0.04em', textTransform:'uppercase',
              whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
              {myWonMap ? 'Vitória' : 'Derrota'} - {myDisplayScore}:{opponentDisplayScore}
            </div>
            {matchData.isPerfect && (
              <span style={{ fontFamily:'var(--font-cond)', fontSize:9, fontWeight:800,
                color:'var(--accent)', letterSpacing:'0.1em' }}>PARTIDA PERFEITA</span>
            )}
          </div>
          <button onClick={handleComplete}
            style={{ flexShrink:0, padding:'9px 13px', minWidth:120,
              background: myWonMap ? 'var(--accent)' : 'var(--bg-4)',
              border: myWonMap ? 'none' : '1px solid var(--border-2)',
              borderRadius:'var(--r-md)', cursor:'pointer',
              fontFamily:'var(--font-cond)', fontSize:11, fontWeight:800,
              letterSpacing:'0.1em', textTransform:'uppercase',
              color: myWonMap ? '#111' : 'var(--text-2)' }}>
            CONTINUAR →
          </button>
        </div>
      )}

      <RoundTimeline rounds={matchData.rounds} revealed={revealed} mySide={mySide}
        matchFormat={matchFormat} />

      <div style={{ display:'flex', flexDirection:'column', gap:8, marginTop:16 }}>
        <ScoreboardTable team={teamA} stats={visStats.A} side="A" isMyTeam={teamA.isMyTeam} />
        <ScoreboardTable team={teamB} stats={visStats.B} side="B" isMyTeam={teamB.isMyTeam} />
      </div>

      {curRound?.highlight && phase === 'playing' && (
        <HighlightTicker key={revealed} name={curRound.highlight.name} k={curRound.highlight.k} />
      )}

      {!isMobile && phase === 'done' && (
        <div style={{ marginTop:20, padding:'14px 20px',
          background: myWonMap ? 'rgba(244,165,35,0.07)' : 'rgba(144,48,48,0.07)',
          border:`1px solid ${myWonMap ? 'rgba(244,165,35,0.3)' : 'rgba(144,48,48,0.3)'}`,
          borderRadius:'var(--r-lg)',
        display:'flex', flexDirection:isMobile ? 'column' : 'row',
        alignItems:isMobile ? 'stretch' : 'center', justifyContent:'space-between', gap:16 }}>
          <div>
            <div style={{ fontFamily:'var(--font-cond)', fontWeight:800, fontSize:15,
              color: myWonMap ? 'var(--accent)' : '#f07070',
              letterSpacing:'0.04em', textTransform:'uppercase', marginBottom:2 }}>
              {myWonMap ? 'Vitória' : 'Derrota'} - {myDisplayScore}:{opponentDisplayScore}
            </div>
            {matchData.isPerfect && (
              <span style={{ fontFamily:'var(--font-cond)', fontSize:10, fontWeight:800,
                color:'var(--accent)', letterSpacing:'0.1em' }}>PARTIDA PERFEITA</span>
            )}
          </div>
          <button onClick={handleComplete}
            style={{ flexShrink:0, padding:'9px 20px', width:isMobile ? '100%' : 'auto',
              background: myWonMap ? 'var(--accent)' : 'var(--bg-4)',
              border: myWonMap ? 'none' : '1px solid var(--border-2)',
              borderRadius:'var(--r-md)', cursor:'pointer',
              fontFamily:'var(--font-cond)', fontSize:11, fontWeight:800,
              letterSpacing:'0.1em', textTransform:'uppercase',
              color: myWonMap ? '#111' : 'var(--text-2)' }}>
            CONTINUAR →
          </button>
        </div>
      )}
    </main>
  );
}

function MapContextPanel({
  mapMeta,
  teamA,
  teamB,
  scoreA,
  scoreB,
  bo,
  mapIndex,
  seriesScore,
  phase,
  revealed,
  totalRounds,
  matchFormat,
  speed,
  setSpeed,
  skip,
  mySide,
}) {
  const isMobile = window.useIsMobileView?.(760) || false;
  const compactDone = isMobile && phase === 'done';
  const mine = mySide === 'A' ? scoreA : scoreB;
  const theirs = mySide === 'A' ? scoreB : scoreA;
  const myTeam = mySide === 'A' ? teamA : teamB;
  const opponentTeam = mySide === 'A' ? teamB : teamA;
  const myScore = mine;
  const opponentScore = theirs;
  const lead = mine - theirs;
  const stateText = phase === 'done'
    ? (lead > 0 ? 'VITÓRIA' : 'DERROTA')
    : (lead > 0 ? `VOCÊ +${lead}` : lead < 0 ? `ATRÁS ${Math.abs(lead)}` : 'EMPATE');
  const roundText = phase === 'done' ? 'Final' : `Round ${Math.min(revealed + 1, totalRounds)}/${totalRounds}`;
  const displaySeriesScore = bo > 1 && seriesScore
    ? (mySide === 'A' ? seriesScore : [seriesScore[1], seriesScore[0]])
    : null;
  const displaySeriesText = bo > 1 && seriesScore
    ? `${matchFormat.label} - Mapa ${(mapIndex || 0) + 1} de ${bo} - Série você ${displaySeriesScore[0]}:${displaySeriesScore[1]}`
    : `${matchFormat.label} - Mapa único`;

  return (
    <section style={{
      position:'relative',
      overflow:'hidden',
      border:'1px solid var(--border-2)',
      borderRadius:'var(--r-lg)',
      marginBottom:compactDone ? 0 : 16,
      background:'var(--bg-2)',
      minHeight:isMobile ? 0 : 178,
    }}>
      <div style={{
        position:'absolute',
        inset:0,
        backgroundImage:`linear-gradient(90deg, rgba(10,13,15,0.90) 0%, rgba(10,13,15,0.46) 45%, rgba(10,13,15,0.82) 100%), url(${mapMeta.image || ''})`,
        backgroundSize:'cover',
        backgroundPosition:'center',
        opacity:1,
      }} />
      <div style={{ position:'relative',
        padding:compactDone ? '10px 11px 11px' : isMobile ? '13px 13px 14px' : '16px 18px 18px',
        display:'flex', flexDirection:isMobile ? 'column' : 'row',
        flexWrap:isMobile ? 'nowrap' : 'wrap', alignItems:'stretch',
        gap:compactDone ? 8 : isMobile ? 14 : 18 }}>
        <div style={{ minWidth:0, flex:isMobile ? '1 1 auto' : '1 1 620px' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap',
            marginBottom:compactDone ? 8 : 18 }}>
            <window.MapBadge mapId={mapMeta.id} size="lg" />
            <span style={{ fontFamily:'var(--font-cond)', fontSize:10, fontWeight:800,
              color:'rgba(232,236,240,0.82)', letterSpacing:'0.12em', textTransform:'uppercase',
              textShadow:'0 1px 3px rgba(0,0,0,0.86)' }}>
              {displaySeriesText}
            </span>
            {phase === 'playing' && <window.LiveDot />}
          </div>

          <div style={{ display:'grid',
            gridTemplateColumns:compactDone ? 'minmax(0,1fr) auto minmax(0,1fr)' : isMobile ? '1fr' : 'minmax(0,1fr) auto minmax(0,1fr)',
            alignItems:'center', gap:compactDone ? 8 : isMobile ? 10 : 18 }}>
            <TeamPlate team={myTeam} align={compactDone ? 'right' : isMobile ? 'center' : 'right'}
              compact={compactDone} label="Meu time" />
            <div style={{ textAlign:'center', minWidth:isMobile ? 0 : 190 }}>
              <div style={{ display:'flex', alignItems:'center', justifyContent:'center',
                gap:10, marginBottom:compactDone ? 2 : 4 }}>
                <span style={{ fontFamily:'var(--font-cond)', fontSize:9, fontWeight:900,
                  color:'var(--accent)', letterSpacing:'0.14em', textTransform:'uppercase' }}>
                  Você
                </span>
                <span style={{ fontFamily:'var(--font-cond)', fontSize:9, fontWeight:800,
                  color:'rgba(232,236,240,0.58)', letterSpacing:'0.12em', textTransform:'uppercase',
                  textShadow:'0 1px 3px rgba(0,0,0,0.9)' }}>
                  vs
                </span>
                <span style={{ fontFamily:'var(--font-cond)', fontSize:9, fontWeight:800,
                  color:'rgba(232,236,240,0.82)', letterSpacing:'0.12em', textTransform:'uppercase',
                  textShadow:'0 1px 3px rgba(0,0,0,0.9)' }}>
                  Adversário
                </span>
              </div>
              <div style={{ display:'flex', alignItems:'baseline', justifyContent:'center', gap:12 }}>
                <span style={{ fontFamily:'var(--font-mono)', fontSize:compactDone ? 38 : isMobile ? 46 : 58, fontWeight:700, lineHeight:1,
                  color:'var(--accent)' }}>{myScore}</span>
                <span style={{ fontFamily:'var(--font-cond)', fontWeight:700, fontSize:compactDone ? 16 : 20,
                  color:'rgba(232,236,240,0.58)', letterSpacing:'0.1em',
                  textShadow:'0 1px 3px rgba(0,0,0,0.9)' }}>:</span>
                <span style={{ fontFamily:'var(--font-mono)', fontSize:compactDone ? 38 : isMobile ? 46 : 58, fontWeight:700, lineHeight:1,
                  color:'var(--text-1)' }}>{opponentScore}</span>
              </div>
              <div style={{ display:'flex', justifyContent:'center', alignItems:'center', gap:8,
                marginTop:compactDone ? 4 : 6 }}>
                <span style={{ fontFamily:'var(--font-cond)', fontSize:10, fontWeight:800,
                  letterSpacing:'0.12em', color: lead > 0 ? '#5aad5c' : lead < 0 ? '#d46a6a' : 'var(--text-3)',
                  padding:'3px 9px', whiteSpace:'nowrap',
                  background: lead > 0 ? 'rgba(90,173,92,0.13)' : lead < 0 ? 'rgba(212,106,106,0.13)' : 'rgba(255,255,255,0.06)',
                  border:`1px solid ${lead > 0 ? 'rgba(90,173,92,0.35)' : lead < 0 ? 'rgba(212,106,106,0.35)' : 'var(--border-2)'}`,
                  borderRadius:'var(--r-sm)' }}>{stateText}</span>
                <span style={{ fontFamily:'var(--font-cond)', fontSize:10, fontWeight:800,
                  color:'var(--text-2)', letterSpacing:'0.12em', textTransform:'uppercase',
                  padding:'3px 9px', background:'rgba(0,0,0,0.28)',
                  border:'1px solid rgba(255,255,255,0.08)', borderRadius:'var(--r-sm)' }}>
                  {roundText}
                </span>
              </div>
            </div>
            <TeamPlate team={opponentTeam} align={compactDone ? 'left' : isMobile ? 'center' : 'left'}
              compact={compactDone} label="Adversário" />
          </div>
        </div>

        <div style={{ display:compactDone ? 'none' : 'flex', flexDirection:isMobile ? 'row' : 'column',
          alignItems:isMobile ? 'center' : 'flex-end',
          justifyContent:'space-between', gap:12, flex:isMobile ? '1 1 auto' : '0 1 260px',
          marginLeft:isMobile ? 0 : 'auto' }}>
          <div style={{ textAlign:isMobile ? 'left' : 'right', minWidth:0, flex:1 }}>
            <div style={{ fontFamily:'var(--font-cond)', fontSize:9, fontWeight:800,
              color:'rgba(232,236,240,0.72)', letterSpacing:'0.14em', textTransform:'uppercase',
              textShadow:'0 1px 3px rgba(0,0,0,0.9)', marginBottom:6 }}>
              Velocidade
            </div>
            <div className={isMobile ? 'touch-scroll' : undefined}
              style={{ display:'flex', alignItems:'center', gap:4 }}>
              {SPEEDS.map(s => (
                <button key={s.id} data-sound="option"
                  onClick={() => { if (phase === 'playing') setSpeed(s.id); }}
                  style={{ padding:'4px 9px', border:'1px solid',
                    borderColor: speed === s.id ? 'var(--accent)' : 'rgba(255,255,255,0.16)',
                    borderRadius:'var(--r-sm)', background: speed === s.id ? 'rgba(244,165,35,0.14)' : 'rgba(0,0,0,0.24)',
                    cursor:'pointer', fontFamily:'var(--font-cond)', fontSize:9,
                    fontWeight:800, letterSpacing:'0.08em', color: speed === s.id ? 'var(--accent)' : 'var(--text-2)',
                    textTransform:'uppercase', transition:'all 100ms ease',
                    opacity: phase !== 'playing' ? 0.45 : 1 }}>
                  {s.label}
                </button>
              ))}
            </div>
          </div>

          {phase === 'playing' && (
            <button onClick={skip} style={{ padding:'7px 12px',
              border:'1px solid rgba(255,255,255,0.16)', borderRadius:'var(--r-sm)',
              background:'rgba(0,0,0,0.24)', cursor:'pointer', fontFamily:'var(--font-cond)',
              fontSize:10, fontWeight:800, letterSpacing:'0.1em',
              color:'var(--text-2)', textTransform:'uppercase' }}>
              PULAR MAPA
            </button>
          )}
        </div>
      </div>
    </section>
  );
}

function TeamPlate({ team, align, compact = false, label }) {
  const isMobile = window.useIsMobileView?.(760) || false;
  return (
    <div style={{ textAlign:align, minWidth:0 }}>
      {!compact && label && (
        <div style={{ fontFamily:'var(--font-cond)', fontSize:8, fontWeight:900,
          color:team.isMyTeam ? 'var(--accent)' : 'rgba(232,236,240,0.72)',
          letterSpacing:'0.14em', textTransform:'uppercase', marginBottom:3,
          textShadow:'0 1px 3px rgba(0,0,0,0.9)' }}>
          {label}
        </div>
      )}
      <div style={{ fontFamily:'var(--font-cond)', fontWeight:800, fontSize:compact ? 12 : isMobile ? 15 : 17,
        color: team.isMyTeam ? 'var(--accent)' : 'var(--text-1)',
        letterSpacing:'0.02em', textTransform:'uppercase', whiteSpace:'nowrap',
        overflow:'hidden', textOverflow:'ellipsis', textShadow:'0 1px 3px rgba(0,0,0,0.9)' }}>
        {team.name}
      </div>
      {!compact && <div style={{ fontFamily:'var(--font-cond)', fontSize:9,
        color:'rgba(232,236,240,0.70)', letterSpacing:'0.1em', textTransform:'uppercase',
        marginTop:4, textShadow:'0 1px 3px rgba(0,0,0,0.9)' }}>
        {team.isMyTeam ? `Seu elenco · OVR ${team.overall}` : `${team.year} · OVR ${team.overall}`}
      </div>}
    </div>
  );
}

function RoundTimeline({ rounds, revealed, mySide, matchFormat }) {
  const isMobile = window.useIsMobileView?.(760) || false;
  const visibleCount = Math.min(revealed, rounds.length);
  const current = visibleCount > 0 ? rounds[visibleCount - 1] : null;
  const myWins = current ? (mySide === 'A' ? current.scoreA : current.scoreB) : 0;
  const oppWins = current ? (mySide === 'A' ? current.scoreB : current.scoreA) : 0;
  return (
    <div style={{ background:'var(--bg-2)', border:'1px solid var(--border-1)',
      borderRadius:'var(--r-lg)', overflow:'hidden' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between',
        padding:'6px 12px', borderBottom:'1px solid var(--border-1)' }}>
        <div style={{ display:'flex', alignItems:'center', gap:6 }}>
          <span style={{ width:9, height:9, borderRadius:'50%', background:'var(--accent)',
            boxShadow:'0 0 5px rgba(244,165,35,0.5)' }} />
          <span style={{ fontFamily:'var(--font-cond)', fontSize:10, fontWeight:700,
            color:'var(--text-2)', letterSpacing:'0.08em', textTransform:'uppercase' }}>
            Seus rounds
          </span>
          <span style={{ fontFamily:'var(--font-mono)', fontSize:12, fontWeight:700,
            color:'var(--accent)' }}>{myWins}</span>
        </div>
        {!isMobile && <span style={{ fontFamily:'var(--font-cond)', fontSize:9, color:'var(--text-3)',
          letterSpacing:'0.1em', textTransform:'uppercase' }}>Timeline {matchFormat.label}</span>
        }
        <div style={{ display:'flex', alignItems:'center', gap:6 }}>
          <span style={{ fontFamily:'var(--font-mono)', fontSize:12, fontWeight:700,
            color:'#d46a6a' }}>{oppWins}</span>
          <span style={{ fontFamily:'var(--font-cond)', fontSize:10, fontWeight:700,
            color:'var(--text-2)', letterSpacing:'0.08em', textTransform:'uppercase' }}>
            Adversário
          </span>
          <span style={{ width:9, height:9, borderRadius:'50%', background:'#7a2e2e',
            border:'1px solid #a14545' }} />
        </div>
      </div>
      <div className={isMobile ? 'touch-scroll' : undefined}
        style={{ display:'flex', gap:3, flexWrap:isMobile ? 'nowrap' : 'wrap',
          padding:'10px 12px', minHeight:34 }}>
        {rounds.map((r, i) => {
          const show = i < visibleCount;
          const won = r.winner === mySide;
          if (r.num === matchFormat.halfSwitchRound) {
            return (
              <React.Fragment key={r.num}>
                <div style={{ width:8, borderLeft:'1px solid var(--border-2)', margin:'0 2px' }} />
                <RoundDot round={r} visible={show} won={won} />
              </React.Fragment>
            );
          }
          return <RoundDot key={r.num} round={r} visible={show} won={won} />;
        })}
      </div>
    </div>
  );
}

function RoundDot({ round, visible, won }) {
  if (!visible) return (
    <div style={{ width:13, height:13, borderRadius:'50%',
      background:'var(--bg-5)', border:'1px solid var(--border-1)', flexShrink:0 }} />
  );
  return (
    <div title={`Round ${round.num}: ${won ? 'ganho' : 'perdido'} - ${round.type}`}
      style={{ width:13, height:13, borderRadius:'50%', flexShrink:0,
        background: won ? 'var(--accent)' : '#7a2e2e',
        border: won ? 'none' : '1px solid #a14545',
        transition:'background 80ms ease',
        boxShadow: won ? '0 0 5px rgba(244,165,35,0.45)' : 'none' }}>
    </div>
  );
}

function ScoreboardTable({ team, stats, side, isMyTeam }) {
  const isMobile = window.useIsMobileView?.(760) || false;
  const sorted = React.useMemo(() => [...stats].sort((a, b) => b.rating - a.rating), [stats]);
  const statGrid = isMobile
    ? 'minmax(116px,1fr) 26px 26px 26px 34px 38px 42px'
    : '1fr 44px 44px 44px 56px 60px 64px';
  return (
    <div className="touch-scroll"
      style={{ background:'var(--bg-2)', border:`1px solid ${isMyTeam ? 'rgba(244,165,35,0.25)' : 'var(--border-2)'}`,
      borderRadius:'var(--r-lg)', overflowX:'auto', overflowY:'hidden' }}>
      <div style={{ padding:isMobile ? '7px 9px' : '7px 12px', background:'var(--bg-3)',
        borderBottom:'1px solid var(--border-1)',
        display:'flex', alignItems:'center', gap:8 }}>
        <span style={{ width:3, height:14, borderRadius:2, flexShrink:0,
          background: isMyTeam ? 'var(--accent)' : 'var(--border-3)' }} />
        <span style={{ fontFamily:'var(--font-cond)', fontSize:13, fontWeight:800,
          color: isMyTeam ? 'var(--accent)' : 'var(--text-1)',
          letterSpacing:'0.04em', textTransform:'uppercase', whiteSpace:'nowrap' }}>
          {team.name}{!isMyTeam && team.year ? ` ${team.year}` : ''}
        </span>
        <span style={{ marginLeft:'auto', fontFamily:'var(--font-cond)', fontSize:9,
          fontWeight:800, color:'var(--text-3)', letterSpacing:'0.12em',
          textTransform:'uppercase' }}>{side === 'A' ? 'Time A' : 'Time B'}</span>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:statGrid,
        minWidth:isMobile ? 0 : 560,
        padding:isMobile ? '5px 8px' : '5px 14px', borderBottom:'1px solid var(--border-1)' }}>
        {['JOGADOR','K','A','D','ADR','KAST','RATING'].map((h,i) => (
          <span key={i} style={{ fontFamily:'var(--font-cond)', fontSize:9, fontWeight:700,
            color:'var(--text-3)', letterSpacing:'0.12em',
            textAlign: i === 0 ? 'left' : 'center' }}>{h}</span>
        ))}
      </div>

      {sorted.map((p, i) => {
        const r = p.rating;
        const rColor = r >= 1.2 ? '#5aad5c' : r >= 0.95 ? 'var(--accent)' : r >= 0.7 ? 'var(--text-2)' : '#9a5050';
        return (
          <div key={p.id} style={{ display:'grid',
            gridTemplateColumns:statGrid,
            minWidth:isMobile ? 0 : 560,
            padding:isMobile ? '7px 8px' : '7px 14px', alignItems:'center',
            borderBottom: i < sorted.length-1 ? '1px solid var(--border-1)' : 'none',
            background: i % 2 === 0 ? 'transparent' : 'rgba(0,0,0,0.1)' }}>
            <div style={{ display:'flex', alignItems:'center', gap:7, minWidth:0 }}>
              <window.RoleBadge role={p.role} />
              {!isMobile && <window.Flag value={p.country} size={13} />}
              <span style={{ fontFamily:'var(--font-cond)', fontSize:13, fontWeight:700,
                color:'var(--text-1)', overflow:'hidden', textOverflow:'ellipsis',
                whiteSpace:'nowrap', letterSpacing:'0.01em', flex:1, minWidth:0 }}>{p.name}</span>
            </div>
            <span style={{ fontFamily:'var(--font-mono)', fontSize:12,
              color:'var(--text-1)', textAlign:'center' }}>{p.k}</span>
            <span style={{ fontFamily:'var(--font-mono)', fontSize:12,
              color:'var(--text-2)', textAlign:'center' }}>{p.a}</span>
            <span style={{ fontFamily:'var(--font-mono)', fontSize:12,
              color:'var(--text-2)', textAlign:'center' }}>{p.d}</span>
            <span style={{ fontFamily:'var(--font-mono)', fontSize:11,
              color:'var(--text-2)', textAlign:'center' }}>{p.adr}</span>
            <span style={{ fontFamily:'var(--font-mono)', fontSize:11,
              color:'var(--text-2)', textAlign:'center' }}>{p.kast}%</span>
            <span style={{ fontFamily:'var(--font-mono)', fontSize:12,
              color:rColor, textAlign:'center', fontWeight:700 }}>{p.rating.toFixed(2)}</span>
          </div>
        );
      })}
    </div>
  );
}

function HighlightTicker({ name, k }) {
  if (k < 3) return null;
  return (
    <div style={{ marginTop:8, padding:'5px 12px',
      background:'rgba(244,165,35,0.06)', border:'1px solid rgba(244,165,35,0.2)',
      borderRadius:'var(--r-md)', display:'inline-flex', alignItems:'center', gap:6,
      animation:'fadeSlide 300ms ease' }}>
      <span style={{ fontFamily:'var(--font-cond)', fontWeight:800, fontSize:10,
        color:'var(--accent)', letterSpacing:'0.08em', textTransform:'uppercase' }}>
        Multi-kill: {name} - {k} kills
      </span>
    </div>
  );
}

function initStats(players) {
  return players.map(p => ({
    ...p,
    k:0,
    a:0,
    d:0,
    adr:0,
    kast:0,
    rating:1.00,
    cs:{ k:0, a:0, d:0, adr:0, kast:0, rating:1.00 },
  }));
}

window.MatchView = MatchView;
