// resultView.jsx — Champion / Eliminated screen
const { useState: useStateR } = React;

function ResultView({ type, myTeam, opponent, matchResult, isPerfect, seriesSummary, campaignSummary, onPlayAgain, onHome }) {
  const isChamp = type === 'champion';
  const [showShare, setShowShare] = useStateR(false);
  const isMobile = window.useIsMobileView?.(760) || false;

  const mySide = matchResult?.mySide || 'A';
  const finalStats = mySide === 'A'
    ? (matchResult?.teamAStats || [])
    : (matchResult?.teamBStats || []);
  const myScore = mySide === 'A' ? matchResult?.scoreA : matchResult?.scoreB;
  const oppScore = mySide === 'A' ? matchResult?.scoreB : matchResult?.scoreA;
  const displayScore = seriesSummary?.score || (matchResult ? [myScore ?? 0, oppScore ?? 0] : null);
  const myWon = matchResult ? matchResult.winner === mySide : false;
  const matchFormat = window.getMatchFormat(matchResult?.matchFormat || myTeam?.matchFormat || 'MR16');
  const sharePlayers = myTeam?.players?.length ? myTeam.players : finalStats;
  const shareOverall = myTeam?.overall || (sharePlayers.length ? window.calcTeamOverall(sharePlayers) : 0);
  const opponentLabel = opponent
    ? `${opponent.name}${opponent.year ? ` ${opponent.year}` : ''}`
    : undefined;
  const myTeamLabel = myTeam?.name || 'Meu Time';
  const shareData = {
    type,
    players: sharePlayers,
    overall: shareOverall,
    score: displayScore,
    teamName: myTeamLabel,
    opponentName: opponentLabel,
    isPerfect,
    matchFormat:matchFormat.id,
    perfectScore:matchFormat.perfectScore,
    seriesSummary,
    campaignSummary,
    campaignSeed: myTeam?.campaignSeed || campaignSummary?.seed,
  };
  const resultStatGrid = isMobile
    ? 'minmax(116px,1fr) 26px 26px 26px 34px 38px 42px'
    : '1fr 40px 40px 40px 50px 52px 54px';

  return (
    <>
    <main style={{ maxWidth:700, margin:'0 auto',
      padding:isMobile ? '34px 14px 50px' : '60px 20px 80px', textAlign:'center' }}>

      {/* Trophy / Eliminated */}
      <div style={{ fontSize: isChamp ? 80 : 48, lineHeight:1, marginBottom:20 }}>
        {isChamp ? '🏆' : '💀'}
      </div>

      <div style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-3)',
        letterSpacing:'0.2em', textTransform:'uppercase', marginBottom:10 }}>
        {isChamp ? 'Major Finalizado' : 'Eliminado por'}
      </div>

      <h1 style={{ fontFamily:'var(--font-cond)', fontWeight:800, lineHeight:1.02,
        fontSize: isChamp ? 'clamp(34px,6vw,54px)' : 'clamp(28px,5vw,46px)',
        color: isChamp ? 'var(--accent)' : 'var(--text-1)',
        letterSpacing:'0.02em', textTransform:'uppercase', marginBottom:8,
        textWrap:'balance' }}>
        {isChamp ? 'CAMPEÃO DO MAJOR' : opponent?.name || 'OPONENTE'}
      </h1>

      {!isChamp && opponent && (
        <p style={{ color:'var(--text-2)', fontSize:13, marginBottom:4 }}>
          {opponent.year} · {opponent.era}
        </p>
      )}

      {isPerfect && isChamp && (
        <div style={{ display:'inline-flex', alignItems:'center', gap:8,
          padding:'6px 16px', marginTop:12, marginBottom:0,
          background:'rgba(244,165,35,0.1)', border:'1px solid rgba(244,165,35,0.35)',
          borderRadius:'var(--r-md)' }}>
          <span style={{ fontFamily:'var(--font-cond)', fontWeight:800, fontSize:12,
            color:'var(--accent)', letterSpacing:'0.12em' }}>
            ★ {matchFormat.perfectScore} PERFEITO
          </span>
        </div>
      )}

      {/* Score if available */}
      {displayScore && (
        <div style={{ margin:'24px auto 0', display:'inline-flex', alignItems:'center', gap:16,
          width:isMobile ? '100%' : 'auto', justifyContent:'center',
          padding:'14px 28px', background:'var(--bg-2)',
          border:'1px solid var(--border-2)', borderRadius:'var(--r-lg)' }}>
          <div style={{ textAlign:'center' }}>
            <div style={{ fontFamily:'var(--font-cond)', fontSize:9, color:'var(--text-3)',
              letterSpacing:'0.1em', marginBottom:4, maxWidth:isMobile ? 118 : 150,
              overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
              {myTeamLabel.toUpperCase()}
            </div>
            <div style={{ fontFamily:'var(--font-mono)', fontSize:36, fontWeight:700,
              color: myWon ? 'var(--accent)' : 'var(--text-1)', lineHeight:1 }}>
              {displayScore[0]}
            </div>
          </div>
          <div style={{ fontFamily:'var(--font-cond)', fontWeight:700, fontSize:14,
            color:'var(--text-3)', letterSpacing:'0.1em' }}>–</div>
          <div style={{ textAlign:'center' }}>
            <div style={{ fontFamily:'var(--font-cond)', fontSize:9, color:'var(--text-3)',
              letterSpacing:'0.1em', marginBottom:4 }}>
              {opponent?.name?.toUpperCase() || 'OPONENTE'}
            </div>
            <div style={{ fontFamily:'var(--font-mono)', fontSize:36, fontWeight:700,
              color: !myWon ? 'var(--accent)' : 'var(--text-1)', lineHeight:1 }}>
              {displayScore[1]}
            </div>
          </div>
        </div>
      )}

      {seriesSummary && (
        <div style={{ margin:'18px auto 0', maxWidth:620, textAlign:'left',
          background:'var(--bg-2)', border:'1px solid var(--border-2)',
          borderRadius:'var(--r-lg)', overflow:'hidden' }}>
          <div style={{ padding:'11px 14px', background:'var(--bg-3)',
            display:'flex', alignItems:'center', justifyContent:'space-between', gap:10 }}>
            <span style={{ fontFamily:'var(--font-cond)', fontWeight:800, fontSize:13,
              color:'var(--text-1)', letterSpacing:'0.06em', textTransform:'uppercase' }}>
              {seriesSummary.stageLabel} - BO{seriesSummary.bo}
            </span>
            {campaignSummary?.totalRecord && (
              <span style={{ fontFamily:'var(--font-mono)', fontSize:11,
                color:'var(--accent)', fontWeight:800 }}>
                Campanha {campaignSummary.totalRecord}
              </span>
            )}
          </div>
          <div style={{ padding:'12px 14px', display:'grid',
            gridTemplateColumns:isMobile ? '1fr' : '1fr auto', gap:12, alignItems:'center' }}>
            <div style={{ display:'flex', flexWrap:'wrap', gap:7 }}>
              {(seriesSummary.maps || []).map((map, index) => (
                <span key={`${map.mapId}-${index}`} style={{
                  display:'inline-flex', alignItems:'center', gap:7,
                  padding:'6px 9px', borderRadius:'var(--r-sm)',
                  background:map.won ? 'rgba(244,165,35,0.12)' : 'rgba(160,80,80,0.12)',
                  border:`1px solid ${map.won ? 'rgba(244,165,35,0.28)' : 'rgba(160,80,80,0.28)'}`,
                  fontFamily:'var(--font-cond)', fontWeight:800, fontSize:11,
                  color:map.won ? 'var(--accent)' : '#d46a6a', letterSpacing:'0.04em',
                  textTransform:'uppercase' }}>
                  M{index + 1} {map.name} {map.score?.[0]}:{map.score?.[1]}{map.overtime ? ' OT' : ''}
                </span>
              ))}
            </div>
            {campaignSummary?.path?.length > 0 && (
              <div style={{ display:'flex', flexWrap:'wrap', gap:5,
                justifyContent:isMobile ? 'flex-start' : 'flex-end' }}>
                {campaignSummary.path.map(item => (
                  <span key={`${item.label}-${item.value}`} style={{ padding:'4px 7px',
                    background:'rgba(255,255,255,0.04)', border:'1px solid var(--border-1)',
                    borderRadius:'var(--r-sm)', fontFamily:'var(--font-cond)',
                    fontSize:10, fontWeight:800, color:'var(--text-2)',
                    letterSpacing:'0.04em', textTransform:'uppercase' }}>
                    {item.label} {item.value}
                  </span>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Final scoreboard */}
      {finalStats.length > 0 && (
        <div style={{ marginTop:28, textAlign:'left' }}>
          <window.SectionLabel label="Seu time — estatísticas finais" />
          <div className="touch-scroll"
            style={{ background:'var(--bg-2)', border:'1px solid var(--border-2)',
            borderRadius:'var(--r-lg)', overflowX:'auto', overflowY:'hidden' }}>
            <div style={{ display:'grid', gridTemplateColumns:resultStatGrid,
              minWidth:isMobile ? 0 : 540, padding:isMobile ? '6px 8px' : '6px 12px', background:'var(--bg-3)',
              borderBottom:'1px solid var(--border-1)' }}>
              {['JOGADOR','K','A','D','ADR','KAST','RATING'].map(h => (
                <span key={h} style={{ fontFamily:'var(--font-cond)', fontSize:9, fontWeight:700,
                  color:'var(--text-3)', letterSpacing:'0.1em',
                  textAlign: h === 'JOGADOR' ? 'left' : 'center' }}>{h}</span>
              ))}
            </div>
            {finalStats.map((p, i) => {
              const r = parseFloat(p.cs?.rating || 0);
              const rColor = r >= 1.2 ? '#5aad5c' : r >= 0.9 ? 'var(--accent)' : '#9a5050';
              return (
                <div key={p.id} style={{ display:'grid',
                  gridTemplateColumns:resultStatGrid,
                  minWidth:isMobile ? 0 : 540, padding:isMobile ? '7px 8px' : '7px 12px', alignItems:'center',
                  borderBottom: i < finalStats.length - 1 ? '1px solid var(--border-1)' : 'none',
                  background: i % 2 === 0 ? 'transparent' : 'rgba(0,0,0,0.12)' }}>
                  <div style={{ display:'flex', alignItems:'center', gap:7, minWidth:0 }}>
                    <window.RoleBadge role={p.role} />
                    {!isMobile && <window.Flag value={p.country} size={12} />}
                    <span style={{ fontFamily:'var(--font-cond)', fontSize:13, fontWeight:700,
                      color:'var(--text-1)', overflow:'hidden', textOverflow:'ellipsis',
                      whiteSpace:'nowrap', flex:1, minWidth:0 }}>
                      {p.name}
                    </span>
                  </div>
                  {[p.cs?.k, p.cs?.a, p.cs?.d].map((v, j) => (
                    <span key={j} style={{ fontFamily:'var(--font-mono)', fontSize:12,
                      color:'var(--text-1)', textAlign:'center' }}>{v ?? '—'}</span>
                  ))}
                  <span style={{ fontFamily:'var(--font-mono)', fontSize:11,
                    color:'var(--text-2)', textAlign:'center' }}>{p.cs?.adr ?? '—'}</span>
                  <span style={{ fontFamily:'var(--font-mono)', fontSize:11,
                    color:'var(--text-2)', textAlign:'center' }}>{p.cs?.kast ?? '—'}%</span>
                  <span style={{ fontFamily:'var(--font-mono)', fontSize:12,
                    color:rColor, textAlign:'center', fontWeight:700 }}>{p.cs?.rating ?? '—'}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* CTAs */}
      <div style={{ marginTop:32, display:'flex', flexDirection:isMobile ? 'column' : 'row',
        gap:8, justifyContent:'center', flexWrap:'wrap' }}>
        <button onClick={() => {
          if (window.openShareRoute) window.openShareRoute(shareData);
          else setShowShare(true);
        }} style={{ padding:'11px 26px', whiteSpace:'nowrap',
          width:isMobile ? '100%' : 'auto', justifyContent:'center',
          background:'var(--accent)', border:'none', borderRadius:'var(--r-md)',
          color:'#15110a', fontFamily:'var(--font-cond)', fontSize:12,
          fontWeight:800, letterSpacing:'0.1em', textTransform:'uppercase', cursor:'pointer',
          display:'inline-flex', alignItems:'center', gap:8 }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
            strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="18" cy="5" r="3" />
            <circle cx="6" cy="12" r="3" />
            <circle cx="18" cy="19" r="3" />
            <path d="M8.6 10.8l6.8-4.6M8.6 13.2l6.8 4.6" />
          </svg>
          COMPARTILHAR
        </button>
        <button data-sound="draft" onClick={onPlayAgain} style={{ padding:'11px 26px', whiteSpace:'nowrap',
          width:isMobile ? '100%' : 'auto',
          background:'var(--bg-3)', border:'1px solid var(--border-2)',
          borderRadius:'var(--r-md)', color:'var(--text-1)',
          fontFamily:'var(--font-cond)', fontSize:12,
          fontWeight:800, letterSpacing:'0.1em', textTransform:'uppercase', cursor:'pointer' }}>
          {isChamp ? 'NOVO DRAFT' : 'TENTAR DE NOVO'}
        </button>
        <button onClick={onHome} style={{ padding:'11px 26px', whiteSpace:'nowrap',
          width:isMobile ? '100%' : 'auto',
          background:'var(--bg-3)', border:'1px solid var(--border-2)',
          borderRadius:'var(--r-md)', color:'var(--text-2)',
          fontFamily:'var(--font-cond)', fontSize:12,
          fontWeight:700, letterSpacing:'0.1em', textTransform:'uppercase', cursor:'pointer' }}>
          INÍCIO
        </button>
      </div>
    </main>
    {showShare && window.ShareOverlay && (
      <window.ShareOverlay data={shareData} onClose={() => setShowShare(false)} />
    )}
    </>
  );
}

window.ResultView = ResultView;
