// ═══════════════ EQUIPES PAGE (LIVE) ═══════════════
const EquipesPage = () => {
  const { data, loading } = useApi('/public/teams-full', []);
  const [divFilter, setDivFilter] = React.useState('all');

  const teams = Array.isArray(data) ? data : [];
  const filtered = divFilter === 'all' ? teams : teams.filter(t => t.division === divFilter);
  const top3 = filtered.slice(0, 3);
  const others = filtered.slice(3);

  return (
    <div className="page-frame grain" data-screen-label="Equipes">
      <CZFHeader active="equipes" />
      <main style={{ padding: '2.5rem 2.5rem 3rem', position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: '1.5rem' }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: '.6rem' }}>Phase de poules</div>
            <h1 className="display" style={{ fontSize: '3.2rem' }}>
              ÉQUIPES <span style={{ color: 'var(--muted-2)' }}>· {teams.length}</span>
            </h1>
          </div>
          <div style={{ display: 'flex', gap: '.4rem' }}>
            <button className={`filter-btn ${divFilter === 'all' ? 'on' : ''}`} onClick={() => setDivFilter('all')}>Toutes</button>
            {['Yordle','Ixtal','Targon'].map(d => (
              <button key={d} className="filter-btn" onClick={() => setDivFilter(d)}
                style={divFilter === d ? { background: DIV_COLOR[d], color: '#0E0A06', borderColor: DIV_COLOR[d] } : { color: DIV_COLOR[d], borderColor: DIV_COLOR[d] }}>{d}</button>
            ))}
          </div>
        </div>

        {loading
          ? <Loading />
          : filtered.length === 0
            ? <Empty title="AUCUNE ÉQUIPE" sub="Aucune équipe enregistrée pour le moment. Les capitaines créent leur équipe via la commande /roster sur Discord." />
            : (
              <>
                {top3.length > 0 && (
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '1.5rem', marginBottom: '2.25rem' }}>
                    {top3.map((t, i) => <LeaderCard key={t.team_name} team={t} rank={i + 1} />)}
                  </div>
                )}
                {others.length > 0 && (
                  <>
                    <div className="section-head">
                      <h2>Toutes les équipes</h2>
                      <span className="sub">{others.length} autre{others.length > 1 ? 's' : ''} · cliquez pour voir le détail</span>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '1.5rem' }}>
                      {others.map((t, i) => <TeamCard key={t.team_name} team={t} rank={i + 4} />)}
                    </div>
                  </>
                )}
              </>
            )}
      </main>
    </div>
  );
};

const teamMetrics = (t) => {
  const w = t.wins ?? 0, l = t.losses ?? 0;
  const wr = (w + l) > 0 ? Math.round((w/(w+l)) * 100) : 0;
  const tag = (t.team_name || '?').split(/\s+/).map(s => s[0]).join('').toUpperCase().slice(0,3);
  const divHex = { Yordle: '%23E8B53C', Ixtal: '%232FA77A', Targon: '%238B79E8' }[t.division] || '%23E8B53C';
  return { w, l, wr, tag, divHex };
};

const LeaderCard = ({ team, rank }) => {
  const divKey = (team.division || 'Y')[0].toLowerCase();
  const divColor = DIV_COLOR[team.division] || 'var(--gold)';
  const { w, l, wr, tag, divHex } = teamMetrics(team);
  return (
    <a href="#equipe" className="card-paper grain" style={{ padding: '1.1rem 1.2rem 1.1rem', position: 'relative', overflow: 'hidden', display: 'block', textDecoration: 'none', color: 'inherit' }}>
      <div style={{
        position: 'absolute', top: -10, right: -25, width: 95, height: 95, pointerEvents: 'none',
        background: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 200'%3E%3Cpath d='M40 30 Q100 50 80 100 T140 180' stroke='${divHex}' stroke-width='28' fill='none' stroke-linecap='round' opacity='.4'/%3E%3C/svg%3E") center/contain no-repeat`,
      }} />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span className={`chip chip-${divKey}`}>{team.division}</span>
        <div style={{ fontFamily: 'var(--fd)', fontSize: '2.2rem', lineHeight: .8,
          color: rank === 1 ? 'var(--red-2)' : 'var(--paper-mut)', opacity: rank === 1 ? 1 : .7 }}>#{rank}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: '.85rem', marginTop: '.85rem' }}>
        <div style={{ width: 52, height: 52, borderRadius: 4, flexShrink: 0,
          background: 'var(--paper-ink)', color: divColor,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--fd)', fontSize: '1.5rem', letterSpacing: '.06em' }}>{tag}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--fd)', fontSize: '1.6rem', letterSpacing: '.04em', color: 'var(--paper-ink)', lineHeight: 1 }}>{team.team_name.toUpperCase()}</div>
          <div style={{ fontFamily: 'var(--fc)', fontSize: '.65rem', letterSpacing: '.08em', color: 'var(--paper-mut)', marginTop: '.2rem' }}>Leader de division</div>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginTop: '1rem', paddingTop: '.85rem', borderTop: '1px solid rgba(0,0,0,.08)' }}>
        <PStatLocal lbl="W" v={w} c="var(--paper-ink)" />
        <PStatLocal lbl="L" v={l} c="var(--paper-mut)" />
        <PStatLocal lbl="WR" v={`${wr}%`} c="var(--red-2)" />
        <MultiGG roster={team.roster} />
      </div>
    </a>
  );
};

const TeamCard = ({ team, rank }) => {
  const divKey = (team.division || 'Y')[0].toLowerCase();
  const divColor = DIV_COLOR[team.division] || 'var(--gold)';
  const { w, l, wr, tag, divHex } = teamMetrics(team);
  const roster = (team.roster || []).slice(0, 5);
  while (roster.length < 5) roster.push({ position: '?', player_tag: '—' });

  return (
    <a href="#equipe" className="card-paper grain" style={{ padding: '1.1rem 1.2rem', position: 'relative', overflow: 'hidden', display: 'block', textDecoration: 'none', color: 'inherit' }}>
      <div style={{
        position: 'absolute', top: -10, right: -25, width: 95, height: 95, pointerEvents: 'none',
        background: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 200'%3E%3Cpath d='M40 30 Q100 50 80 100 T140 180' stroke='${divHex}' stroke-width='28' fill='none' stroke-linecap='round' opacity='.4'/%3E%3C/svg%3E") center/contain no-repeat`,
      }} />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span className={`chip chip-${divKey}`}>{team.division}</span>
        <div style={{ fontFamily: 'var(--fd)', fontSize: '1.4rem', color: 'var(--paper-mut)', opacity: .65 }}>#{rank}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: '.85rem', marginTop: '.85rem' }}>
        <div style={{ width: 48, height: 48, borderRadius: 4, flexShrink: 0,
          background: 'var(--paper-ink)', color: divColor,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--fd)', fontSize: '1.3rem', letterSpacing: '.06em' }}>{tag}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--fd)', fontSize: '1.45rem', letterSpacing: '.04em', color: 'var(--paper-ink)', lineHeight: 1 }}>{team.team_name.toUpperCase()}</div>
          <div style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', letterSpacing: '.06em', color: 'var(--paper-mut)', marginTop: '.3rem' }}>
            {w}W · {l}L · <strong style={{ color: 'var(--paper-ink)' }}>{wr}%</strong>
          </div>
        </div>
        <MultiGG roster={team.roster} />
      </div>
      <div style={{ marginTop: '1rem', paddingTop: '.85rem', borderTop: '1px dashed rgba(0,0,0,.15)' }}>
        <div style={{ fontFamily: 'var(--fc)', fontSize: '.58rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--paper-mut)', marginBottom: '.6rem' }}>Roster</div>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {roster.map((p, i) => (
            <React.Fragment key={i}>
              <RosterMini p={p} divColor={divColor} />
              {i < 4 && <div style={{ width: 1, height: 30, background: 'rgba(0,0,0,.12)', margin: '0 .35rem', alignSelf: 'center' }} />}
            </React.Fragment>
          ))}
        </div>
      </div>
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: '.3rem', marginTop: '.85rem',
        fontFamily: 'var(--fc)', fontSize: '.62rem', fontWeight: 700,
        letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--red-2)',
      }}>Voir l'équipe →</span>
    </a>
  );
};

const RosterMini = ({ p, divColor }) => {
  const isEmpty = !p.player_tag || p.player_tag === '—';
  const name = isEmpty ? '?' : (p.player_tag.split('#')[0] || '?');
  const icon = p.profile_icon_id
    ? `https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/profile-icons/${p.profile_icon_id}.jpg`
    : null;
  const role = ({ TOP:'TOP', JUNGLE:'JGL', MIDDLE:'MID', BOTTOM:'ADC', UTILITY:'SUP' }[p.position] || p.position || '?');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, flex: 1, minWidth: 0 }}>
      <div style={{
        width: 32, height: 32, borderRadius: '50%',
        background: isEmpty ? 'rgba(0,0,0,.08)' : (icon ? `url(${icon}) center/cover` : 'linear-gradient(135deg, var(--paper-ink), #3a2a18)'),
        border: isEmpty ? '1px dashed rgba(0,0,0,.25)' : `1.5px solid ${divColor}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'var(--fd)', fontSize: '.85rem',
        color: isEmpty ? 'var(--paper-mut)' : 'var(--paper)', letterSpacing: '.02em',
      }}>{!icon && name[0]?.toUpperCase()}</div>
      <div style={{ fontFamily: 'var(--fc)', fontSize: '.55rem', fontWeight: 700, letterSpacing: '.1em', color: 'var(--paper-mut)' }}>{role}</div>
    </div>
  );
};

const PStatLocal = ({ lbl, v, c }) => (
  <div>
    <div style={{ fontFamily: 'var(--fc)', fontSize: '.55rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--paper-mut)' }}>{lbl}</div>
    <div style={{ fontFamily: 'var(--fd)', fontSize: '1.4rem', color: c, lineHeight: 1 }}>{v}</div>
  </div>
);

const MultiGG = ({ roster }) => {
  const ids = (roster || []).map(r => r.riot_id).filter(Boolean);
  if (ids.length === 0) return null;
  const url = `https://www.op.gg/multisearch/euw?summoners=${ids.map(id => id.replace(/ /g, '+').replace('#', '%23')).join(',')}`;
  return (
    <a href={url} target="_blank" rel="noopener" onClick={e => e.stopPropagation()} style={{
      marginLeft: 'auto',
      display: 'inline-flex', alignItems: 'center', gap: '.35rem',
      fontFamily: 'var(--fc)', fontSize: '.62rem', fontWeight: 800, letterSpacing: '.1em', textTransform: 'uppercase',
      padding: '.4rem .7rem', borderRadius: 3,
      background: 'var(--paper-ink)', color: 'var(--paper)',
      textDecoration: 'none', flexShrink: 0,
    }}><Icon.Opgg style={{ width: 12, height: 12 }} /> Multi OP.GG</a>
  );
};

Object.assign(window, { EquipesPage });
