// ═══════════════ CAST PAGE (LIVE) ═══════════════
const CastPage = () => {
  const [cfg, setCfg] = React.useState(window.__CZF_CONFIG__ || null);
  React.useEffect(() => {
    if (cfg) return;
    if (window.CZF && CZF.USE_LIVE_DATA) {
      fetch(`${CZF.API_BASE}/public/config`).then(r => r.json()).then(c => { setCfg(c); window.__CZF_CONFIG__ = c; }).catch(() => {});
    }
  }, []);

  const liveCast = cfg?.live_cast || { duo: [], match: '', description: '', twitch_url: '', yt_url: '' };
  const isLive = !!cfg?.live_cast?.is_live;
  const casters = Array.isArray(cfg?.casters) ? cfg.casters : [];
  const hasLiveDuo = liveCast.duo && liveCast.duo.length >= 1 && liveCast.duo[0];

  return (
    <div className="page-frame grain" data-screen-label="Cast">
      <CZFHeader active="cast" />
      <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' }}>L'équipe de diffusion</div>
            <h1 className="display" style={{ fontSize: '3.2rem' }}>
              CAST <span style={{ color: 'var(--muted-2)' }}>· {casters.length}</span>
            </h1>
          </div>
          {isLive && hasLiveDuo && (
            <div style={{ display: 'flex', alignItems: 'center', gap: '.6rem' }}>
              <span className="dot dot-live"></span>
              <span style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--red)' }}>
                {liveCast.duo.filter(Boolean).join(' & ')}{liveCast.match ? ' · ' + liveCast.match : ''}
              </span>
            </div>
          )}
        </div>

        {hasLiveDuo && (
          <div className="card-paper grain" style={{ display: 'flex', overflow: 'hidden', marginBottom: '1.5rem', position: 'relative' }}>
            <div style={{
              position: 'absolute', top: -40, left: '40%', width: 400, height: 400, 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=\'%23E63946\' stroke-width=\'24\' fill=\'none\' stroke-linecap=\'round\' opacity=\'.5\'/%3E%3C/svg%3E") center/contain no-repeat',
            }} />
            <div style={{ padding: '2rem 2.2rem', flex: 1, position: 'relative' }}>
              <div className="eyebrow" style={{ color: 'var(--red-2)', marginBottom: '.85rem' }}>
                {isLive ? 'Cast en cours · Live' : "Duo en tête d'affiche"}
              </div>
              <div style={{ fontFamily: 'var(--fd)', fontSize: '3.4rem', letterSpacing: '.04em', lineHeight: .95, color: 'var(--paper-ink)' }}>
                {(liveCast.duo[0] || '').toUpperCase()}{liveCast.duo[1] ? <> <span style={{ color: 'var(--paper-mut)', fontSize: '2rem' }}>&</span><br />{liveCast.duo[1].toUpperCase()}</> : null}
              </div>
              {liveCast.description && (
                <div style={{ fontFamily: 'var(--fc)', fontSize: '.95rem', color: 'var(--paper-mut)', letterSpacing: '.04em', marginTop: '.75rem', maxWidth: 380, lineHeight: 1.5 }}>
                  {liveCast.description}
                </div>
              )}
              <div style={{ display: 'flex', gap: '.5rem', marginTop: '1.25rem' }}>
                {liveCast.twitch_url && (
                  <a href={liveCast.twitch_url} target="_blank" rel="noopener" className="btn" style={{ background: '#9146FF', color: '#fff', textDecoration: 'none' }}>
                    <Icon.Twitch /> Voir le live
                  </a>
                )}
                {liveCast.yt_url && (
                  <a href={liveCast.yt_url} target="_blank" rel="noopener" className="btn btn-paper" style={{ textDecoration: 'none' }}>
                    <Icon.YouTube /> Chaîne YT
                  </a>
                )}
              </div>
            </div>
            <div style={{ width: 480, display: 'flex', gap: 4 }}>
              {liveCast.duo.filter(Boolean).map((n, i) => {
                const caster = casters.find(c => (c.name || c.discord_tag) === n) || {};
                const photoUrl = caster.photo_url || null;
                return (
                  <div key={n + i} style={{
                    flex: 1, position: 'relative', overflow: 'hidden', minHeight: 320,
                    background: photoUrl ? `url(${photoUrl}) center/cover` : `linear-gradient(135deg, ${i === 0 ? 'var(--red-deep)' : 'var(--gold-deep)'}, var(--paper-ink))`,
                  }}>
                    <div style={{
                      position: 'absolute', bottom: 0, left: 0, right: 0,
                      padding: '1rem', background: 'linear-gradient(0deg, rgba(0,0,0,.85), transparent)',
                    }}>
                      <div style={{ fontFamily: 'var(--fd)', fontSize: '1.4rem', color: 'var(--paper)', letterSpacing: '.04em' }}>{n.toUpperCase()}</div>
                    </div>
                    {!photoUrl && (
                      <div style={{
                        position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontFamily: 'var(--fd)', fontSize: '7rem', color: 'rgba(255,255,255,.12)', letterSpacing: '.04em',
                      }}>{n[0]}</div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        )}

        <div className="section-head">
          <h2>Tous les casters</h2>
          <span className="sub">{casters.length} caster{casters.length > 1 ? 's' : ''}</span>
        </div>
        {casters.length === 0
          ? <Empty title="AUCUN CASTER" sub="Les casters apparaîtront ici dès qu'ils auront utilisé la commande /caster-photo sur Discord." />
          : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '1rem' }}>
              {casters.map((c, i) => <CasterCard key={(c.name || c.discord_tag || i) + ''} c={c} />)}
            </div>
          )}
      </main>
    </div>
  );
};

const CasterCard = ({ c }) => {
  const name = c.name || c.discord_tag || '?';
  const photo = c.photo_url || null;
  return (
    <div style={{
      background: 'var(--char)', border: '1px solid var(--border)', borderRadius: 4,
      overflow: 'hidden', position: 'relative',
    }}>
      <div style={{
        height: 200, position: 'relative', overflow: 'hidden',
        borderBottom: '1px solid var(--border)',
        background: photo
          ? `url(${photo}) center/cover`
          : `repeating-linear-gradient(135deg, rgba(212,168,75,.05) 0px, rgba(212,168,75,.05) 14px, transparent 14px, transparent 28px), linear-gradient(180deg, var(--char-3), var(--char))`,
      }}>
        {!photo && (
          <div style={{
            position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--fd)', fontSize: '7rem', color: 'rgba(248,241,222,.08)', letterSpacing: '.04em',
          }}>{name[0]?.toUpperCase()}</div>
        )}
        {!photo && (
          <div style={{
            position: 'absolute', bottom: 8, right: 10,
            fontFamily: 'JetBrains Mono, monospace', fontSize: '.55rem',
            letterSpacing: '.15em', color: 'var(--muted-2)', textTransform: 'uppercase',
          }}>/caster-photo</div>
        )}
      </div>

      <div style={{ padding: '.95rem 1rem 1.1rem' }}>
        <div style={{ fontFamily: 'var(--fd)', fontSize: '1.5rem', letterSpacing: '.05em', color: 'var(--bone)', lineHeight: 1 }}>{name.toUpperCase()}</div>
        <div style={{ display: 'flex', gap: '.35rem', marginTop: '.9rem' }}>
          {c.twitch_url && <CasterBtn icon={<Icon.Twitch />} href={c.twitch_url} />}
          {c.yt_url && <CasterBtn icon={<Icon.YouTube />} href={c.yt_url} />}
          {c.discord_id && <CasterBtn icon={<Icon.Discord />} href={`https://discord.com/users/${c.discord_id}`} />}
          {!c.twitch_url && !c.yt_url && !c.discord_id && (
            <div style={{ fontFamily: 'var(--fc)', fontSize: '.62rem', color: 'var(--muted)', letterSpacing: '.06em' }}>Pas de liens renseignés</div>
          )}
        </div>
      </div>
    </div>
  );
};

const CasterBtn = ({ icon, href }) => (
  <a href={href || '#'} target={href ? '_blank' : undefined} rel="noopener" style={{
    flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: '.5rem', borderRadius: 3,
    background: '#0a0805', color: 'var(--bone)',
    border: '1px solid var(--border-2)',
    textDecoration: 'none', cursor: 'pointer',
  }}>{icon}</a>
);

Object.assign(window, { CastPage });
