// swissView.jsx - Pick'Em-style Swiss stage board

const SWISS_FLOW = [
  {
    title:'STAGE I',
    groups:[
      { label:'0X0', records:['0-0'], minSlots:10 },
    ],
  },
  {
    title:'STAGE II',
    groups:[
      { label:'1X0', records:['1-0'], minSlots:5 },
      { label:'0X1', records:['0-1'], minSlots:5 },
    ],
  },
  {
    title:'STAGE III',
    groups:[
      { label:'2X0', records:['2-0'], minSlots:3 },
      { label:'1X1', records:['1-1'], minSlots:5 },
      { label:'0X2', records:['0-2'], minSlots:3 },
    ],
  },
  {
    title:'DECISIONS',
    groups:[
      { label:'3X0 - CLASSIFICADAS', records:['3-0'], tone:'good', minSlots:2 },
      { label:'2X1', records:['2-1'], minSlots:3 },
      { label:'1X2', records:['1-2'], minSlots:3 },
      { label:'0X3 - ELIMINADAS', records:['0-3'], tone:'bad', minSlots:2 },
    ],
  },
  {
    title:'FINAL',
    groups:[
      { label:'3X1 E 3X2 - CLASSIFICADAS', records:['3-1','3-2'], tone:'good', minSlots:6 },
      { label:'2X2', records:['2-2'], minSlots:3 },
      { label:'1X3 E 2X3 - ELIMINADAS', records:['1-3','2-3'], tone:'bad', minSlots:4 },
    ],
  },
];

const TEAM_SHORT_NAMES = {
  my_team:'Meu Time',
  lum2016:'Luminosity',
  ast2018:'Astralis',
  navi2021:'NAVI',
  faze2022:'FaZe',
  fnc2015:'fnatic',
  spr2024:'Spirit',
  sk2017:'SK',
  vp2014:'Virtus.pro',
  c92018:'Cloud9',
  liq2019:'Liquid',
  heroic2023:'HEROIC',
  gambit2017:'Gambit',
  vit2023:'Vitality',
  g22023:'G2',
  nip2013:'NiP',
  envy2015:'EnVyUs',
  navi2010:'NAVI 1.6',
  mouz2024:'MOUZ',
  furia2022:'FURIA',
  outsiders2022:'Outsiders',
};

function SwissView({ swiss, myTeamId, onPlayMatch, onAdvance }) {
  const isMobile = window.useIsMobileView?.(820) || false;
  const myTeam = swiss.teams.find(t => t.id === myTeamId);
  const myRecord = recordOf(myTeam);
  const boardSnapshots = React.useMemo(() => buildSwissBoardSnapshots(swiss), [swiss]);
  const isQualified = (myTeam?.swiss?.wins || 0) >= 3;
  const isEliminated = (myTeam?.swiss?.losses || 0) >= 3;
  const activeCount = swiss.teams.filter(t => (t.swiss?.wins || 0) < 3 && (t.swiss?.losses || 0) < 3).length;
  const qualifiedCount = swiss.teams.filter(t => (t.swiss?.wins || 0) >= 3).length;
  const eliminatedCount = swiss.teams.filter(t => (t.swiss?.losses || 0) >= 3).length;

  if (isMobile) {
    return (
      <SwissMobileView
        swiss={swiss}
        myTeamId={myTeamId}
        myTeam={myTeam}
        myRecord={myRecord}
        boardSnapshots={boardSnapshots}
        isQualified={isQualified}
        isEliminated={isEliminated}
        activeCount={activeCount}
        qualifiedCount={qualifiedCount}
        eliminatedCount={eliminatedCount}
        onPlayMatch={onPlayMatch}
        onAdvance={onAdvance}
      />
    );
  }

  return (
    <main style={{ maxWidth:1380, margin:'0 auto', padding:'24px 30px 54px' }}>
      <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between',
        gap:16, marginBottom:18 }}>
        <div>
          <h2 style={{ fontFamily:'var(--font-cond)', fontWeight:800, fontSize:26,
            color:'var(--text-1)', letterSpacing:'0.055em', textTransform:'uppercase',
            marginBottom:2, lineHeight:1 }}>
            Fase suíça
          </h2>
          <p style={{ color:'var(--text-3)', fontSize:12 }}>
            16 times - 3 vitórias classificam - 3 derrotas eliminam - jogos decisivos em BO3
          </p>
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          {['STAGE I','STAGE II','STAGE III','PLAYOFFS'].map((label, i) => {
            const active = i === Math.min(Math.max((swiss.round || 1) - 1, 0), 2);
            return (
              <span key={label} style={{ padding:'5px 10px',
                background:active ? 'rgba(244,165,35,0.12)' : 'transparent',
                border:`1px solid ${active ? 'rgba(244,165,35,0.3)' : 'var(--border-2)'}`,
                borderRadius:'var(--r-sm)', fontFamily:'var(--font-cond)', fontSize:10,
                fontWeight:800, letterSpacing:'0.12em', color:active ? 'var(--accent)' : 'var(--text-3)' }}>
                {label}
              </span>
            );
          })}
        </div>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'300px minmax(0,1fr)', gap:16, alignItems:'stretch' }}>
        <aside style={{ display:'grid', gap:12, alignContent:'start' }}>
          <SwissProgressCard
            myTeam={myTeam}
            myRecord={myRecord}
            isQualified={isQualified}
            isEliminated={isEliminated}
            activeCount={activeCount}
            qualifiedCount={qualifiedCount}
            eliminatedCount={eliminatedCount}
            matchFormat={swiss.matchFormat}
          />

          {isQualified ? (
            <SwissStatusCard
              title="Classificado"
              body="Seu time chegou a 3 vitórias. Os demais jogos serão resolvidos para fechar o Top 8."
              tone="good"
              action="INICIAR PLAYOFFS →"
              onAction={onAdvance}
            />
          ) : isEliminated ? (
            <SwissStatusCard
              title="Eliminado"
              body="Seu time chegou a 3 derrotas na fase suíça."
              tone="bad"
            />
          ) : (
            <CurrentSwissMatch match={swiss.currentMatch} onPlayMatch={onPlayMatch} />
          )}

          <SwissHistory history={swiss.history} myTeamId={myTeamId} />
        </aside>

        <section style={{ overflowX:'auto', borderRadius:'var(--r-lg)',
          border:'1px solid rgba(54,122,83,0.34)',
          background:
            'radial-gradient(circle at 20% 18%, rgba(65,141,83,0.34), transparent 34%),' +
            'radial-gradient(circle at 78% 30%, rgba(27,96,66,0.30), transparent 34%),' +
            'linear-gradient(135deg, #12301f 0%, #0b2218 48%, #071912 100%)',
          boxShadow:'inset 0 0 90px rgba(0,0,0,0.20), 0 18px 44px rgba(0,0,0,0.25)' }}>
          <div style={{ minWidth:1180, padding:'18px 18px 20px' }}>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between',
              gap:14, marginBottom:14, color:'rgba(226,238,226,0.92)' }}>
              <div style={{ fontFamily:'var(--font-cond)', fontSize:18, fontWeight:800,
                letterSpacing:'0.08em', textTransform:'uppercase' }}>
                Pick'Em - Fase suíça
              </div>
              <div style={{ fontFamily:'var(--font-cond)', fontSize:11, fontWeight:800,
                letterSpacing:'0.12em', textTransform:'uppercase', color:'rgba(226,238,226,0.58)' }}>
                Rodada {swiss.round} - {myRecord}
              </div>
            </div>
            <SwissFlowBoard swiss={swiss} myTeamId={myTeamId} snapshots={boardSnapshots} />
          </div>
        </section>
      </div>
    </main>
  );
}

function SwissMobileView({ swiss, myTeamId, myTeam, myRecord, boardSnapshots,
  isQualified, isEliminated, activeCount, qualifiedCount, eliminatedCount,
  onPlayMatch, onAdvance }) {
  const activeIndex = Math.min(Math.max((swiss.round || 1) - 1, 0), SWISS_FLOW.length - 1);
  const [selectedIndex, setSelectedIndex] = React.useState(activeIndex);
  const [isFullMapOpen, setIsFullMapOpen] = React.useState(false);
  React.useEffect(() => setSelectedIndex(activeIndex), [activeIndex]);

  const selected = SWISS_FLOW[selectedIndex] || SWISS_FLOW[0];
  const currentIds = new Set([swiss.currentMatch?.teamA?.id, swiss.currentMatch?.teamB?.id].filter(Boolean));

  return (
    <main style={{ maxWidth:560, margin:'0 auto', padding:'14px 14px 42px' }}>
      <div className="mobile-rise" style={{ marginBottom:14 }}>
        <h2 style={{ fontFamily:'var(--font-cond)', fontWeight:800, fontSize:24,
          color:'var(--text-1)', letterSpacing:'0.055em', textTransform:'uppercase',
          marginBottom:4, lineHeight:1 }}>
          Fase suíça
        </h2>
        <p style={{ color:'var(--text-3)', fontSize:12, lineHeight:1.35 }}>
          3 vitórias classificam. 3 derrotas eliminam. Jogos decisivos em BO3.
        </p>
      </div>

      <div className="mobile-rise" style={{ display:'grid', gap:10, marginBottom:12 }}>
        <MobileSwissHero
          myTeam={myTeam}
          myRecord={myRecord}
          isQualified={isQualified}
          isEliminated={isEliminated}
          activeCount={activeCount}
          qualifiedCount={qualifiedCount}
          eliminatedCount={eliminatedCount}
          matchFormat={swiss.matchFormat}
        />

        {isQualified ? (
          <SwissStatusCard
            title="Classificado"
            body="Seu time chegou a 3 vitórias. Feche o restante da fase suíça para montar o Top 8."
            tone="good"
            action="INICIAR PLAYOFFS ->"
            onAction={onAdvance}
          />
        ) : isEliminated ? (
          <SwissStatusCard
            title="Eliminado"
            body="Seu time chegou a 3 derrotas na fase suíça."
            tone="bad"
          />
        ) : (
          <CurrentSwissMatch match={swiss.currentMatch} onPlayMatch={onPlayMatch} />
        )}
      </div>

      <MobileMyPath snapshots={boardSnapshots} myTeamId={myTeamId} activeIndex={activeIndex} />

      <div className="touch-scroll" style={{ display:'flex', gap:7, margin:'14px -14px 12px',
        padding:'0 14px' }}>
        {SWISS_FLOW.map((col, index) => {
          const active = selectedIndex === index;
          const done = index < activeIndex;
          return (
            <button key={col.title} data-sound="option" onClick={() => setSelectedIndex(index)}
              style={{ flex:'0 0 auto', padding:'8px 11px',
                background:active ? 'rgba(244,165,35,0.13)' : done ? 'rgba(25,197,108,0.08)' : 'var(--bg-2)',
                border:`1px solid ${active ? 'rgba(244,165,35,0.36)' : done ? 'rgba(25,197,108,0.22)' : 'var(--border-2)'}`,
                borderRadius:'var(--r-md)', color:active ? 'var(--accent)' : 'var(--text-2)',
                fontFamily:'var(--font-cond)', fontSize:11, fontWeight:800,
                letterSpacing:'0.11em', textTransform:'uppercase', cursor:'pointer',
                whiteSpace:'nowrap' }}>
              {mobileSwissTitle(col.title)}
            </button>
          );
        })}
      </div>

      <section className="mobile-slide" key={selected.title}
        style={{ display:'grid', gap:10, marginBottom:14 }}>
        <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between',
          gap:10 }}>
          <div style={{ fontFamily:'var(--font-cond)', fontSize:17, fontWeight:800,
            color:'var(--text-1)', letterSpacing:'0.08em', textTransform:'uppercase' }}>
            {mobileSwissTitle(selected.title)}
          </div>
          <div style={{ fontFamily:'var(--font-cond)', fontSize:10, fontWeight:800,
            color:'var(--text-3)', letterSpacing:'0.12em', textTransform:'uppercase' }}>
            rodada {swiss.round}
          </div>
        </div>

        {selected.groups.map(group => {
          const entries = entriesForGroup(swiss.teams, group, columnSnapshot(boardSnapshots, selectedIndex));
          const mine = entries.some(entry => entry.team.id === myTeamId);
          const active = entries.some(entry => currentIds.has(entry.team.id));
          return (
            <MobileSwissGroup key={group.label}
              group={group}
              entries={entries}
              mine={mine}
              active={active}
              myTeamId={myTeamId}
              currentIds={currentIds}
            />
          );
        })}
      </section>

      <details open={isFullMapOpen} onToggle={event => setIsFullMapOpen(event.currentTarget.open)}
        style={{ marginBottom:12, background:'var(--bg-2)',
        border:'1px solid var(--border-2)', borderRadius:'var(--r-lg)', overflow:'hidden' }}>
        <summary style={{ listStyle:'none', cursor:'pointer', padding:'12px 13px',
          fontFamily:'var(--font-cond)', fontSize:12, fontWeight:800,
          color:'var(--text-2)', letterSpacing:'0.1em', textTransform:'uppercase' }}>
          Mapa completo da fase
        </summary>
        {isFullMapOpen && (
          <div className="touch-scroll" style={{ borderTop:'1px solid var(--border-1)',
            background:
              'radial-gradient(circle at 18% 12%, rgba(65,141,83,0.30), transparent 34%),' +
              'linear-gradient(135deg, #12301f 0%, #071912 100%)' }}>
            <div style={{ minWidth:1180, padding:'16px' }}>
              <SwissFlowBoard swiss={swiss} myTeamId={myTeamId} snapshots={boardSnapshots} />
            </div>
          </div>
        )}
      </details>

      <SwissHistory history={swiss.history} myTeamId={myTeamId} />
    </main>
  );
}

function MobileSwissHero({ myTeam, myRecord, isQualified, isEliminated,
  activeCount, qualifiedCount, eliminatedCount, matchFormat }) {
  const recordColor = isQualified ? '#5aad5c' : isEliminated ? '#d46a6a' : 'var(--accent)';
  return (
    <section style={{ background:
        'linear-gradient(135deg, rgba(244,165,35,0.10), rgba(255,255,255,0.02) 42%, rgba(25,197,108,0.07))',
      border:'1px solid rgba(244,165,35,0.20)', borderRadius:'var(--r-lg)',
      padding:'14px', boxShadow:'0 12px 26px rgba(0,0,0,0.18)' }}>
      <div style={{ display:'flex', alignItems:'center', gap:11 }}>
        <TeamToken team={myTeam} mine size={46} />
        <div style={{ minWidth:0, flex:1 }}>
          <div style={{ fontFamily:'var(--font-cond)', fontSize:18, fontWeight:800,
            color:'var(--text-1)', whiteSpace:'nowrap', overflow:'hidden',
            textOverflow:'ellipsis' }}>
            {myTeam?.name || 'Meu Time'}
          </div>
          <div style={{ fontSize:10, color:'var(--text-3)' }}>
            {matchFormat || 'MR16'} - campanha suíça
          </div>
        </div>
        <div style={{ textAlign:'right' }}>
          <div style={{ fontFamily:'var(--font-mono)', fontSize:32, fontWeight:800,
            color:recordColor, lineHeight:1 }}>
            {myRecord}
          </div>
          <div style={{ marginTop:2, fontFamily:'var(--font-cond)', fontSize:9,
            fontWeight:800, color:'var(--text-3)', letterSpacing:'0.12em',
            textTransform:'uppercase' }}>
            record
          </div>
        </div>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:7, marginTop:13 }}>
        <MiniCount label="Ativos" value={activeCount} />
        <MiniCount label="Class." value={qualifiedCount} tone="good" />
        <MiniCount label="Elim." value={eliminatedCount} tone="bad" />
      </div>
    </section>
  );
}

function MobileMyPath({ snapshots, myTeamId, activeIndex }) {
  const path = SWISS_FLOW.map((col, index) => {
    const snap = columnSnapshot(snapshots, index);
    return { title:mobileSwissTitle(col.title), record:snap?.[myTeamId] || '-' };
  });
  return (
    <section className="mobile-rise" style={{ background:'var(--bg-2)',
      border:'1px solid var(--border-2)', borderRadius:'var(--r-lg)', padding:'12px 13px' }}>
      <div style={{ fontFamily:'var(--font-cond)', fontSize:11, fontWeight:800,
        color:'var(--text-3)', letterSpacing:'0.13em', textTransform:'uppercase', marginBottom:10 }}>
        Caminho do seu time
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(5,1fr)', gap:5 }}>
        {path.map((step, index) => {
          const active = index === activeIndex;
          const passed = index < activeIndex;
          return (
            <div key={step.title} style={{ minWidth:0, textAlign:'center',
              padding:'8px 4px', borderRadius:'var(--r-sm)',
              background:active ? 'rgba(244,165,35,0.12)' : passed ? 'rgba(25,197,108,0.08)' : 'var(--bg-3)',
              border:`1px solid ${active ? 'rgba(244,165,35,0.32)' : passed ? 'rgba(25,197,108,0.18)' : 'var(--border-2)'}` }}>
              <div style={{ fontFamily:'var(--font-mono)', fontSize:13, fontWeight:800,
                color:active ? 'var(--accent)' : passed ? '#5aad5c' : 'var(--text-3)' }}>
                {step.record.replace('-', ':')}
              </div>
              <div style={{ marginTop:3, fontFamily:'var(--font-cond)', fontSize:8,
                fontWeight:800, color:'var(--text-3)', letterSpacing:'0.08em',
                textTransform:'uppercase', whiteSpace:'nowrap', overflow:'hidden',
                textOverflow:'ellipsis' }}>
                {step.title}
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function MobileSwissGroup({ group, entries, mine, active, myTeamId, currentIds }) {
  const tone = group.tone || 'neutral';
  const good = tone === 'good';
  const bad = tone === 'bad';
  const emptySlots = Math.max((group.minSlots || 0) - entries.length, 0);
  const border = mine ? 'rgba(244,165,35,0.58)'
    : good ? 'rgba(28,190,111,0.34)'
    : bad ? 'rgba(206,75,83,0.34)'
    : active ? 'rgba(244,165,35,0.25)'
    : 'var(--border-2)';
  const bg = good ? 'rgba(25,197,108,0.08)'
    : bad ? 'rgba(212,84,92,0.08)'
    : 'var(--bg-2)';

  return (
    <div className={active ? 'mobile-pulse' : undefined}
      style={{ background:bg, border:`1px solid ${border}`,
        borderRadius:'var(--r-lg)', padding:'12px', overflow:'hidden' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between',
        gap:10, marginBottom:10 }}>
        <div style={{ minWidth:0 }}>
          <div style={{ fontFamily:'var(--font-cond)', fontSize:14, fontWeight:800,
            color:good ? '#86df9c' : bad ? '#e27a7f' : mine ? 'var(--accent)' : 'var(--text-1)',
            letterSpacing:'0.09em', textTransform:'uppercase', whiteSpace:'nowrap',
            overflow:'hidden', textOverflow:'ellipsis' }}>
            {group.label.replaceAll('X', '-')}
          </div>
          <div style={{ marginTop:2, fontSize:10, color:'var(--text-3)' }}>
            {entries.length} times nesta faixa
          </div>
        </div>
        {mine && (
          <span style={{ flexShrink:0, padding:'4px 7px',
            background:'rgba(244,165,35,0.12)', border:'1px solid rgba(244,165,35,0.28)',
            borderRadius:'var(--r-sm)', fontFamily:'var(--font-cond)', fontSize:9,
            fontWeight:800, color:'var(--accent)', letterSpacing:'0.1em',
            textTransform:'uppercase' }}>
            você
          </span>
        )}
      </div>
      <div style={{ display:'grid', gap:6 }}>
        {entries.map(entry => (
          <TeamPill key={`${entry.team.id}-${entry.record}`} team={entry.team}
            record={entry.record} mine={entry.team.id === myTeamId}
            current={currentIds.has(entry.team.id)} />
        ))}
        {Array.from({ length:Math.min(emptySlots, entries.length ? 2 : 4) }).map((_, i) => (
          <EmptyPill key={i} />
        ))}
      </div>
    </div>
  );
}

function mobileSwissTitle(title) {
  return title === 'STAGE I' ? 'Stage I'
    : title === 'STAGE II' ? 'Stage II'
    : title === 'STAGE III' ? 'Stage III'
    : title === 'DECISIONS' ? 'Decisao'
    : 'Final';
}

function SwissFlowBoard({ swiss, myTeamId, snapshots }) {
  return (
    <div style={{ display:'grid',
      gridTemplateColumns:'210px 38px 210px 38px 210px 38px 232px 38px 270px',
      alignItems:'stretch', gap:0 }}>
      {SWISS_FLOW.map((col, index) => (
        <React.Fragment key={col.title}>
          <div style={{ display:'grid', gap:10, alignContent:'stretch' }}>
            <div style={{ textAlign:'center', fontFamily:'var(--font-cond)', fontSize:11,
              fontWeight:800, letterSpacing:'0.13em', color:'rgba(226,238,226,0.66)',
              textTransform:'uppercase', minHeight:16 }}>
              {col.title}
            </div>
            {col.groups.map(group => (
              <SwissRecordGroup key={group.label}
                group={group}
                entries={entriesForGroup(swiss.teams, group, columnSnapshot(snapshots, index))}
                myTeamId={myTeamId}
                currentMatch={swiss.currentMatch}
              />
            ))}
          </div>
          {index < SWISS_FLOW.length - 1 && <FlowArrows index={index} />}
        </React.Fragment>
      ))}
    </div>
  );
}

function FlowArrows({ index }) {
  const arrows = index === 0 ? ['↗','↘']
    : index === 1 ? ['↗','→','↘']
    : ['↗','→','→','↘'];
  return (
    <div style={{ display:'flex', flexDirection:'column', justifyContent:'space-around',
      alignItems:'center', paddingTop:24, paddingBottom:8 }}>
      {arrows.map((arrow, i) => (
        <span key={`${arrow}-${i}`} style={{ fontFamily:'var(--font-mono)', fontSize:22,
          fontWeight:700, color: arrow === '↘' ? '#c34b49' : '#19c56c',
          textShadow:'0 0 10px rgba(25,197,108,0.22)' }}>
          {arrow}
        </span>
      ))}
    </div>
  );
}

function SwissRecordGroup({ group, entries, myTeamId, currentMatch }) {
  const tone = group.tone || 'neutral';
  const good = tone === 'good';
  const bad = tone === 'bad';
  const containsMine = entries.some(entry => entry.team.id === myTeamId);
  const currentIds = new Set([currentMatch?.teamA?.id, currentMatch?.teamB?.id].filter(Boolean));
  const active = entries.some(entry => currentIds.has(entry.team.id));
  const emptySlots = Math.max((group.minSlots || 0) - entries.length, 0);

  const bg = good ? 'rgba(15,105,76,0.84)'
    : bad ? 'rgba(104,28,47,0.84)'
    : active ? 'rgba(21,76,52,0.92)'
    : 'rgba(7,34,24,0.72)';
  const border = containsMine ? 'rgba(244,165,35,0.78)'
    : good ? 'rgba(28,190,111,0.38)'
    : bad ? 'rgba(206,75,83,0.38)'
    : 'rgba(94,151,111,0.20)';

  return (
    <div style={{ minHeight:78, padding:'8px 8px 9px',
      background:bg, border:`2px solid ${border}`, borderRadius:'var(--r-sm)',
      boxShadow: containsMine ? '0 0 0 2px rgba(244,165,35,0.16)' : 'inset 0 0 24px rgba(0,0,0,0.16)' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between',
        gap:8, marginBottom:8 }}>
        <span style={{ fontFamily:'var(--font-cond)', fontSize:11, fontWeight:800,
          color:good ? '#a8ffcd' : bad ? '#ffabb4' : 'rgba(226,238,226,0.72)',
          letterSpacing:'0.12em', textTransform:'uppercase' }}>
          {group.label}
        </span>
        <span style={{ fontFamily:'var(--font-mono)', fontSize:10, fontWeight:700,
          color:'rgba(226,238,226,0.42)' }}>
          {entries.length}
        </span>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr', gap:5 }}>
        {entries.map(entry => (
          <TeamPill key={`${entry.team.id}-${entry.record}`} team={entry.team}
            record={entry.record} mine={entry.team.id === myTeamId}
            current={currentIds.has(entry.team.id)} />
        ))}
        {Array.from({ length:emptySlots }).map((_, i) => (
          <EmptyPill key={i} />
        ))}
      </div>
    </div>
  );
}

function SwissProgressCard({ myTeam, myRecord, isQualified, isEliminated,
  activeCount, qualifiedCount, eliminatedCount, matchFormat }) {
  return (
    <div style={{ background:'var(--bg-2)', border:'1px solid var(--border-2)',
      borderRadius:'var(--r-lg)', padding:'16px' }}>
      <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:13 }}>
        <TeamToken team={myTeam} mine size={42} />
        <div style={{ minWidth:0, flex:1 }}>
          <div style={{ fontFamily:'var(--font-cond)', fontSize:16, fontWeight:800,
            color:'var(--text-1)', whiteSpace:'nowrap', overflow:'hidden',
            textOverflow:'ellipsis' }}>
            {myTeam?.name || 'Meu Time'}
          </div>
          <div style={{ fontSize:10, color:'var(--text-3)' }}>
            {matchFormat || 'MR16'} - campanha suíça
          </div>
        </div>
        <span style={{ fontFamily:'var(--font-mono)', fontSize:30, fontWeight:700,
          color:isQualified ? '#5aad5c' : isEliminated ? '#d46a6a' : 'var(--accent)',
          lineHeight:1 }}>
          {myRecord}
        </span>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:6 }}>
        <MiniCount label="Ativos" value={activeCount} />
        <MiniCount label="Class." value={qualifiedCount} tone="good" />
        <MiniCount label="Elim." value={eliminatedCount} tone="bad" />
      </div>
    </div>
  );
}

function MiniCount({ label, value, tone }) {
  const color = tone === 'good' ? '#5aad5c' : tone === 'bad' ? '#d46a6a' : 'var(--accent)';
  return (
    <div style={{ background:'var(--bg-3)', border:'1px solid var(--border-2)',
      borderRadius:'var(--r-sm)', padding:'8px 6px', textAlign:'center' }}>
      <div style={{ fontFamily:'var(--font-mono)', fontSize:18, fontWeight:700,
        color, lineHeight:1 }}>
        {value}
      </div>
      <div style={{ marginTop:3, fontFamily:'var(--font-cond)', fontSize:9, fontWeight:800,
        color:'var(--text-3)', letterSpacing:'0.1em', textTransform:'uppercase' }}>
        {label}
      </div>
    </div>
  );
}

function SwissStatusCard({ title, body, tone, action, onAction }) {
  const good = tone === 'good';
  return (
    <div style={{ background:good ? 'rgba(90,173,92,0.08)' : 'rgba(212,106,106,0.08)',
      border:`1px solid ${good ? 'rgba(90,173,92,0.28)' : 'rgba(212,106,106,0.28)'}`,
      borderRadius:'var(--r-lg)', padding:'16px' }}>
      <div style={{ fontFamily:'var(--font-cond)', fontSize:18, fontWeight:800,
        color:good ? '#5aad5c' : '#d46a6a', letterSpacing:'0.04em',
        textTransform:'uppercase', marginBottom:4 }}>{title}</div>
      <p style={{ color:'var(--text-2)', fontSize:12, lineHeight:1.45, marginBottom: action ? 14 : 0 }}>
        {body}
      </p>
      {action && (
        <button data-sound="major" onClick={onAction} style={{ width:'100%', padding:'11px 18px', background:'var(--accent)',
          border:'none', borderRadius:'var(--r-md)', cursor:'pointer',
          color:'#15110a', fontFamily:'var(--font-cond)', fontSize:12, fontWeight:800,
          letterSpacing:'0.1em', textTransform:'uppercase' }}>
          {action}
        </button>
      )}
    </div>
  );
}

function CurrentSwissMatch({ match, onPlayMatch }) {
  if (!match) return null;
  return (
    <div style={{ background:'var(--bg-2)', border:'1px solid rgba(244,165,35,0.28)',
      borderRadius:'var(--r-lg)', overflow:'hidden' }}>
      <div style={{ padding:'9px 12px', background:'rgba(244,165,35,0.08)',
        borderBottom:'1px solid rgba(244,165,35,0.18)', display:'flex',
        alignItems:'center', justifyContent:'space-between' }}>
        <span style={{ fontFamily:'var(--font-cond)', fontSize:12, fontWeight:800,
          color:'var(--accent)', letterSpacing:'0.1em', textTransform:'uppercase' }}>
          Próxima partida
        </span>
        <span style={{ fontFamily:'var(--font-cond)', fontSize:10, fontWeight:800,
          color:'var(--text-3)', letterSpacing:'0.1em' }}>
          {match.record} - BO{match.bo}
        </span>
      </div>
      <div style={{ padding:'14px 14px 12px' }}>
        <SwissTeamLine team={match.teamA} mine />
        <div style={{ height:1, background:'var(--border-1)', margin:'10px 0' }} />
        <SwissTeamLine team={match.teamB} />
        <button data-sound="match" onClick={() => onPlayMatch(match)}
          style={{ marginTop:14, width:'100%', padding:'11px 0', background:'var(--accent)',
            border:'none', borderRadius:'var(--r-md)', cursor:'pointer',
            color:'#15110a', fontFamily:'var(--font-cond)', fontSize:12, fontWeight:800,
            letterSpacing:'0.1em', textTransform:'uppercase' }}>
          JOGAR RODADA →
        </button>
      </div>
    </div>
  );
}

function SwissHistory({ history, myTeamId }) {
  return (
    <div style={{ background:'var(--bg-2)', border:'1px solid var(--border-2)',
      borderRadius:'var(--r-lg)', overflow:'hidden' }}>
      <div style={{ padding:'9px 12px', background:'var(--bg-3)',
        borderBottom:'1px solid var(--border-1)', fontFamily:'var(--font-cond)',
        fontSize:12, fontWeight:800, letterSpacing:'0.1em', textTransform:'uppercase' }}>
        Rodadas resolvidas
      </div>
      {history.length === 0 ? (
        <div style={{ padding:'14px 12px', color:'var(--text-3)', fontSize:12 }}>
          A primeira rodada começa agora.
        </div>
      ) : history.slice().reverse().map(round => (
        <div key={round.round} style={{ padding:'10px 12px', borderBottom:'1px solid var(--border-1)' }}>
          <div style={{ fontFamily:'var(--font-cond)', fontSize:10, fontWeight:800,
            color:'var(--accent)', letterSpacing:'0.1em', textTransform:'uppercase', marginBottom:6 }}>
            Rodada {round.round}
          </div>
          <div style={{ display:'grid', gap:4 }}>
            {round.matches.slice(0, 4).map(m => {
              const mine = m.teamAId === myTeamId || m.teamBId === myTeamId;
              return (
                <div key={m.id} style={{ display:'grid', gridTemplateColumns:'1fr 38px',
                  gap:8, color:mine ? 'var(--text-1)' : 'var(--text-3)', fontSize:11 }}>
                  <span style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                    {m.teamAName} vs {m.teamBName}{mine ? ' - você' : ''}
                  </span>
                  <span style={{ fontFamily:'var(--font-mono)', textAlign:'right' }}>{m.score}</span>
                </div>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

function SwissTeamLine({ team, mine }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
      <TeamToken team={team} mine={mine} size={38} />
      <div style={{ minWidth:0, flex:1 }}>
        <div style={{ fontFamily:'var(--font-cond)', fontSize:16, fontWeight:800,
          color:mine ? 'var(--accent)' : 'var(--text-1)', whiteSpace:'nowrap',
          overflow:'hidden', textOverflow:'ellipsis' }}>
          {team.name} {team.year || ''}
        </div>
        <div style={{ fontSize:10, color:'var(--text-3)', whiteSpace:'nowrap',
          overflow:'hidden', textOverflow:'ellipsis' }}>{team.achievement || team.era}</div>
      </div>
      <span style={{ fontFamily:'var(--font-mono)', fontSize:18, fontWeight:700,
        color:'var(--text-2)' }}>{recordOf(team)}</span>
    </div>
  );
}

function TeamPill({ team, record, mine = false, current = false }) {
  const displayRecord = record || recordOf(team);
  return (
    <div title={`${team?.name || 'Meu Time'} ${team?.year || ''} - ${displayRecord}`}
      style={{ display:'grid', gridTemplateColumns:'30px minmax(0,1fr) auto',
        alignItems:'center', gap:7, minHeight:32, padding:'4px 6px 4px 4px',
        borderRadius:'var(--r-sm)',
        background: mine ? 'rgba(244,165,35,0.13)' : current ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.20)',
        border:`1px solid ${mine ? 'rgba(244,165,35,0.42)' : current ? 'rgba(255,255,255,0.18)' : 'rgba(255,255,255,0.06)'}` }}>
      <TeamToken team={team} record={displayRecord} mine={mine} current={current} size={28} />
      <div style={{ minWidth:0 }}>
        <div style={{ fontFamily:'var(--font-cond)', fontSize:13, fontWeight:800,
          lineHeight:1, color:mine ? 'var(--accent)' : 'rgba(241,246,239,0.92)',
          whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
          {teamName(team)}
        </div>
        <div style={{ marginTop:2, fontFamily:'var(--font-mono)', fontSize:8,
          color:'rgba(226,238,226,0.42)', whiteSpace:'nowrap', overflow:'hidden',
          textOverflow:'ellipsis' }}>
          {team?.year || 'Mix'} · OVR {team?.overall || '-'}
        </div>
      </div>
      <span style={{ fontFamily:'var(--font-mono)', fontSize:10, fontWeight:700,
        color:'rgba(226,238,226,0.48)' }}>
        {displayRecord.replace('-', ':')}
      </span>
    </div>
  );
}

function TeamToken({ team, record, mine = false, current = false, size = 34 }) {
  const label = initials(team?.name || 'Meu Time');
  const color = team?.color || (mine ? 'var(--accent)' : '#8a9cb4');
  const textColor = tokenTextColor(color);
  return (
    <span title={`${team?.name || 'Meu Time'} ${team?.year || ''} - ${record || recordOf(team)}`}
      style={{ position:'relative', width:size, height:size, borderRadius:'50%',
        display:'inline-flex', alignItems:'center', justifyContent:'center',
        flexShrink:0, color:textColor,
        background:`radial-gradient(circle at 35% 28%, rgba(255,255,255,0.38), transparent 24%), ${color}`,
        border:`2px solid ${mine ? 'var(--accent)' : current ? '#d9f2d1' : 'rgba(255,255,255,0.22)'}`,
        boxShadow: mine || current ? '0 0 0 3px rgba(244,165,35,0.16)' : '0 2px 6px rgba(54,35,18,0.28)',
        fontFamily:'var(--font-cond)', fontWeight:800, fontSize:Math.max(10, Math.round(size * 0.34)),
        letterSpacing:'0.04em', textTransform:'uppercase' }}>
      {label}
      <span style={{ position:'absolute', right:-3, bottom:-3, width:Math.max(13, Math.round(size * 0.42)),
        height:Math.max(13, Math.round(size * 0.42)), borderRadius:'50%',
        background:'rgba(30,20,12,0.72)', display:'flex', alignItems:'center', justifyContent:'center',
        border:'1px solid rgba(255,239,191,0.4)' }}>
        <window.Flag value={team?.region?.split(' ')[0] || '🌍'} size={Math.max(10, Math.round(size * 0.32))} />
      </span>
    </span>
  );
}

function EmptyPill() {
  return (
    <div style={{ height:30, borderRadius:'var(--r-sm)', display:'flex',
      alignItems:'center', gap:7, padding:'0 8px',
      border:'1px dashed rgba(226,238,226,0.12)', color:'rgba(226,238,226,0.24)',
      background:'rgba(0,0,0,0.08)', fontFamily:'var(--font-cond)',
      fontSize:11, fontWeight:800, letterSpacing:'0.08em', textTransform:'uppercase' }}>
      <span style={{ width:20, height:20, borderRadius:'50%', border:'1px dashed rgba(226,238,226,0.18)',
        display:'inline-flex', alignItems:'center', justifyContent:'center',
        fontFamily:'var(--font-mono)', fontSize:10 }}>?</span>
      aguardando
    </div>
  );
}

function buildSwissBoardSnapshots(swiss) {
  const records = {};
  swiss.teams.forEach(team => { records[team.id] = '0-0'; });
  const snapshots = [{ ...records }];

  [...swiss.history].sort((a, b) => a.round - b.round).forEach(round => {
    round.matches.forEach(match => {
      const a = splitRecord(records[match.teamAId]);
      const b = splitRecord(records[match.teamBId]);
      if (match.winnerId === match.teamAId) {
        records[match.teamAId] = `${a.w + 1}-${a.l}`;
        records[match.teamBId] = `${b.w}-${b.l + 1}`;
      } else {
        records[match.teamAId] = `${a.w}-${a.l + 1}`;
        records[match.teamBId] = `${b.w + 1}-${b.l}`;
      }
    });
    snapshots.push({ ...records });
  });

  return snapshots;
}

function columnSnapshot(snapshots, columnIndex) {
  if (columnIndex < 4) return snapshots[columnIndex] || null;
  if (snapshots.length <= 4) return snapshots[4] || null;
  return snapshots[snapshots.length - 1] || null;
}

function entriesForGroup(teams, group, snapshot) {
  if (!snapshot) return [];
  const recordSet = new Set(group.records);
  return teams
    .map(team => ({ team, record:snapshot[team.id] }))
    .filter(entry => recordSet.has(entry.record))
    .sort((a, b) => sortSwissEntries(a, b));
}

function sortSwissEntries(a, b) {
  const ar = splitRecord(a.record);
  const br = splitRecord(b.record);
  if (br.w !== ar.w) return br.w - ar.w;
  if (ar.l !== br.l) return ar.l - br.l;
  return (a.team.swiss?.seedRank || 99) - (b.team.swiss?.seedRank || 99);
}

function sortSwissTeams(a, b) {
  const aw = a.swiss?.wins || 0;
  const bw = b.swiss?.wins || 0;
  const al = a.swiss?.losses || 0;
  const bl = b.swiss?.losses || 0;
  if (bw !== aw) return bw - aw;
  if (al !== bl) return al - bl;
  return (a.swiss?.seedRank || 99) - (b.swiss?.seedRank || 99);
}

function recordOf(team) {
  return `${team?.swiss?.wins || 0}-${team?.swiss?.losses || 0}`;
}

function splitRecord(record) {
  const [w, l] = String(record || '0-0').split('-').map(n => parseInt(n, 10) || 0);
  return { w, l };
}

function teamName(team) {
  if (!team) return 'Aguardando';
  if (team.id === 'my_team') return team.name || 'Meu Time';
  return TEAM_SHORT_NAMES[team.id] || team.name || 'Time';
}

function initials(name) {
  const clean = String(name || 'T').replace(/[^a-z0-9\s]/gi, ' ').trim();
  const parts = clean.split(/\s+/).filter(Boolean);
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
  return clean.slice(0, 2).toUpperCase() || 'T';
}

function tokenTextColor(color) {
  const hex = String(color || '').trim();
  if (!/^#[0-9a-f]{6}$/i.test(hex)) return '#f4ead8';
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  const luminance = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
  return luminance > 0.62 ? '#132019' : '#f4ead8';
}

window.SwissView = SwissView;
