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

  const all = Array.isArray(scrims) ? scrims : [];
  const open = all.filter(s => s.kind === 'open' || s.status === 'Ouvert');
  const done = all.filter(s => s.kind === 'done' || s.status === 'Terminé');
  const openFiltered = divFilter === 'all' ? open : open.filter(s => s.division === divFilter);

  // Lookup captain Discord ID via teams roster
  const captainIdFor = (teamName) => {
    const t = (teams || []).find(t => t.team_name === teamName);
    if (!t || !t.roster) return null;
    const cap = t.roster.find(r => r.is_captain);
    return cap?.discord_id || null;
  };

  return (
    <div className="page-frame grain" data-screen-label="Scrims">
      <CZFHeader active="scrims" />
      <main style={{ padding: '2.5rem 2.5rem 3rem', position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: '1.75rem' }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: '.6rem' }}>Demandes ouvertes · {open.length}</div>
            <h1 className="display" style={{ fontSize: '3.2rem' }}>SCRIMS</h1>
            <div style={{ fontFamily: 'var(--fc)', fontSize: '.85rem', color: 'var(--cream-2)', maxWidth: 480, marginTop: '.45rem' }}>
              Trouve une opposition pour t'entraîner. Poste ta dispo via <code style={{ color: 'var(--gold)' }}>/scrim proposer</code> sur Discord.
            </div>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '.75rem', marginBottom: '2rem' }}>
          <StatBox n={open.length} l="Ouvertes" />
          <StatBox n={done.length} l="Terminées" />
          {['Yordle','Ixtal','Targon'].slice(0, 2).map(d => (
            <StatBox key={d} n={open.filter(s => s.division === d).length} l={d} />
          ))}
        </div>

        <div style={{ display: 'flex', gap: '.4rem', alignItems: 'center', marginBottom: '1rem' }}>
          <button className={`filter-btn ${divFilter === 'all' ? 'on' : ''}`} onClick={() => setDivFilter('all')}>Toutes</button>
          {['Yordle','Ixtal','Targon'].map(d => (
            <button key={d} className={`filter-btn ${divFilter === d ? 'on' : ''}`} onClick={() => setDivFilter(d)}>{d}</button>
          ))}
        </div>

        {loading
          ? <Loading />
          : openFiltered.length === 0
            ? <Empty title="AUCUN SCRIM OUVERT" sub="Aucune équipe ne cherche d'adversaire actuellement. Les capitaines peuvent en publier via /scrim proposer." />
            : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '.85rem', marginBottom: '2rem' }}>
                {openFiltered.map((s, i) => <ScrimCard key={s.scrim_id || i} s={s} captainId={captainIdFor(s.team_name)} />)}
              </div>
            )}

        {done.length > 0 && (
          <>
            <div className="section-head"><h2>Résultats récents</h2><span className="sub">{done.length}</span></div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '.6rem' }}>
              {done.slice(0, 6).map((s, i) => <ScrimResultRow key={i} s={s} />)}
            </div>
          </>
        )}
      </main>
    </div>
  );
};

const StatBox = ({ n, l }) => (
  <div style={{
    background: 'var(--char)', border: '1px solid var(--border)', borderRadius: 3,
    padding: '.85rem 1rem', position: 'relative',
  }}>
    <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 2, background: 'var(--gold)' }} />
    <div style={{ fontFamily: 'var(--fd)', fontSize: '2rem', color: 'var(--bone)', lineHeight: 1 }}>{n}</div>
    <div style={{ fontFamily: 'var(--fc)', fontSize: '.62rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--muted)', marginTop: 4 }}>{l}</div>
  </div>
);

const ScrimCard = ({ s, captainId }) => {
  const divKey = (s.division || 'Y')[0].toLowerCase();
  const divColor = DIV_COLOR[s.division] || 'var(--gold)';
  const discordUrl = captainId ? `https://discord.com/users/${captainId}` : null;
  return (
    <div style={{
      background: `linear-gradient(180deg, ${divColor}11, var(--char))`,
      border: '1px solid var(--border)', borderRadius: 4,
      padding: '1rem 1rem .85rem', position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 2, background: divColor, opacity: .8 }} />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '.75rem' }}>
        <span className={`chip chip-${divKey}-out`}>{s.division}</span>
        <span style={{
          fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.16em',
          color: 'var(--ok)', textTransform: 'uppercase',
          display: 'inline-flex', alignItems: 'center', gap: '.3rem',
        }}><span className="dot" style={{ background: 'var(--ok)' }} /> Ouverte</span>
      </div>
      <div style={{ fontFamily: 'var(--fd)', fontSize: '1.5rem', color: 'var(--bone)', letterSpacing: '.04em', lineHeight: 1 }}>
        {s.team_name?.toUpperCase()}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '.4rem .85rem', marginTop: '.85rem' }}>
        <Pair lbl="Quand" v={s.date_heure || 'Date flexible'} icon={<Icon.Calendar />} />
        {s.recherche && <Pair lbl="Message" v={s.recherche} />}
      </div>
      {discordUrl
        ? <a href={discordUrl} target="_blank" rel="noopener" className="btn btn-ghost" style={{ width: '100%', marginTop: '.85rem', justifyContent: 'center', padding: '.5rem', textDecoration: 'none' }}>
            <Icon.Discord style={{ color: '#5865F2' }} /> Répondre au capitaine
          </a>
        : <div style={{ marginTop: '.85rem', padding: '.5rem', textAlign: 'center', fontFamily: 'var(--fc)', fontSize: '.65rem', color: 'var(--muted)', letterSpacing: '.06em', border: '1px dashed var(--border)', borderRadius: 3 }}>
            Contact le capitaine via le serveur Discord
          </div>
      }
    </div>
  );
};

const Pair = ({ lbl, v, icon }) => (
  <div>
    <div style={{ fontFamily: 'var(--fc)', fontSize: '.55rem', fontWeight: 700, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--muted)' }}>{lbl}</div>
    <div style={{ display: 'flex', alignItems: 'center', gap: '.3rem', fontFamily: 'var(--fc)', fontSize: '.78rem', fontWeight: 600, color: 'var(--bone)', marginTop: 1 }}>
      {icon && <span style={{ color: 'var(--gold)' }}>{icon}</span>} {v}
    </div>
  </div>
);

const ScrimResultRow = ({ s }) => {
  const win = s.result_team === 'Victoire';
  return (
    <div style={{
      background: 'var(--char)', border: '1px solid var(--border)', borderRadius: 3,
      padding: '.6rem .85rem', display: 'flex', alignItems: 'center', gap: '.75rem',
    }}>
      <div style={{ minWidth: 60 }}>
        <div style={{ fontFamily: 'var(--fd)', fontSize: '1rem', color: 'var(--bone)', letterSpacing: '.04em' }}>{s.created_at || '—'}</div>
      </div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '.5rem', justifyContent: 'flex-end' }}>
        <div style={{ fontFamily: 'var(--fc)', fontSize: win ? '.92rem' : '.82rem', fontWeight: win ? 700 : 500, color: win ? 'var(--bone)' : 'var(--muted)' }}>{s.team_name}</div>
      </div>
      <div style={{ fontFamily: 'var(--fd)', fontSize: '1.1rem', color: 'var(--bone)', minWidth: 64, textAlign: 'center' }}>{s.score_result || '—'}</div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '.5rem' }}>
        <div style={{ fontFamily: 'var(--fc)', fontSize: !win ? '.92rem' : '.82rem', fontWeight: !win ? 700 : 500, color: !win ? 'var(--bone)' : 'var(--muted)' }}>{s.opponent || 'Inconnu'}</div>
      </div>
    </div>
  );
};

Object.assign(window, { ScrimsPage });
