// ═══════════════ HOME PAGE v2 ═══════════════
// Itération sur retours utilisateur :
// - Fond brush massif (style graff/arène effacée) partant du logo
// - Header text plus crème
// - Widget live + pills + inscrits collés au bord droit
// - Pills sociales transparentes avec signature brush
// - Derniers inscrits refondus en style éditorial (pas "code")
// - CTA "S'inscrire" rouge unique (Discord = via pill)
// - Feature cards : scrims=crème, tierlist=blanc, prochain=rouge

// Brush stroke component — paint stroke style
const Brush = ({ d, color, width, opacity = 1, ...p }) => (
  <path d={d} stroke={color} strokeWidth={width} fill="none"
        strokeLinecap="round" strokeLinejoin="round" opacity={opacity} {...p} />
);

// Mountain Colosseum — graphic ink illustration, tertiary visual element
const MountainColosseum = () => (
  <svg viewBox="0 0 700 700" preserveAspectRatio="xMidYMid meet"
       style={{
         position: 'absolute',
         left: '46%', top: '8%',
         width: 540, height: 540,
         pointerEvents: 'none',
         opacity: .55,
       }}>
    <defs>
      <filter id="ink-rough">
        <feTurbulence type="fractalNoise" baseFrequency="0.06" numOctaves="2" seed="4" />
        <feDisplacementMap in="SourceGraphic" scale="3" />
      </filter>
      <filter id="ink-rough2">
        <feTurbulence type="fractalNoise" baseFrequency="0.12" numOctaves="3" seed="9" />
        <feDisplacementMap in="SourceGraphic" scale="1.8" />
      </filter>
      <radialGradient id="halo" cx="50%" cy="45%" r="55%">
        <stop offset="0" stopColor="#E63946" stopOpacity=".35" />
        <stop offset=".5" stopColor="#7A1820" stopOpacity=".18" />
        <stop offset="1" stopColor="#0a0805" stopOpacity="0" />
      </radialGradient>
    </defs>

    {/* Red halo behind — like a blood moon */}
    <circle cx="350" cy="310" r="260" fill="url(#halo)" />

    {/* Far peak (background) */}
    <g filter="url(#ink-rough)">
      <path d="M 50 540 L 180 320 L 250 400 L 340 280 L 410 380 L 510 240 L 600 380 L 680 540 Z"
            fill="#1a0e08" stroke="#3a1f10" strokeWidth="2" />
      {/* Snow caps with hatching */}
      <path d="M 320 305 L 340 280 L 370 320 Z" fill="#5a3018" opacity=".6" />
      <path d="M 490 265 L 510 240 L 540 275 Z" fill="#5a3018" opacity=".6" />
    </g>

    {/* Mid peak — the main mountain holding colosseum */}
    <g filter="url(#ink-rough)">
      <path d="M 100 600 L 220 380 L 290 440 L 350 320 L 420 440 L 510 380 L 620 600 Z"
            fill="#0e0805" stroke="#4a2516" strokeWidth="2.5" />
      {/* Mountain hatching — brush strokes for texture */}
      <g stroke="#3a1f10" strokeWidth="1.5" fill="none" opacity=".65" strokeLinecap="round">
        <path d="M 220 400 L 240 460 M 250 420 L 270 490 M 290 460 L 310 530" />
        <path d="M 380 460 L 360 520 M 410 450 L 390 510 M 440 470 L 420 540" />
        <path d="M 480 410 L 510 480 M 530 430 L 560 510 M 580 460 L 600 540" />
        <path d="M 170 480 L 150 560 M 200 460 L 180 540" />
      </g>
      {/* Highlighted edge */}
      <path d="M 220 380 L 290 440 L 350 320 L 420 440"
            stroke="#D4A84B" strokeWidth="1.5" fill="none" opacity=".45" strokeLinecap="round" />
    </g>

    {/* COLOSSEUM on top — ruined arena perched on the peak */}
    <g transform="translate(350, 320)" filter="url(#ink-rough2)">
      {/* Base plinth */}
      <ellipse cx="0" cy="38" rx="160" ry="22" fill="#1a0e08" stroke="#5a3018" strokeWidth="1.5" />
      <ellipse cx="0" cy="30" rx="160" ry="22" fill="#080503" />

      {/* Lower ring of arches (8 columns visible) */}
      <g>
        {Array.from({ length: 11 }).map((_, i) => {
          const x = -150 + i * 30;
          const t = (i - 5) / 5;
          const skew = Math.abs(t) * 4;
          const h = 28 - Math.abs(t) * 4;
          return (
            <g key={i}>
              <rect x={x - 6} y={-h} width="12" height={h + 8} fill="#0e0805" stroke="#3a1f10" strokeWidth="1" />
              <path d={`M ${x - 4} ${-h + 12} Q ${x} ${-h + 4} ${x + 4} ${-h + 12}`}
                    fill="none" stroke="#5a3018" strokeWidth="1" />
            </g>
          );
        })}
        {/* Lower rim */}
        <ellipse cx="0" cy="6" rx="148" ry="14" fill="none" stroke="#5a3018" strokeWidth="1.5" />
        {/* Top rim of lower ring */}
        <ellipse cx="0" cy="-30" rx="148" ry="14" fill="#1a0e08" stroke="#5a3018" strokeWidth="1.5" />
      </g>

      {/* Upper ring — broken/ruined, irregular tops */}
      <g transform="translate(0, -38)">
        {[-130, -100, -68, -40, 0, 40, 78, 116].map((x, i) => {
          const heights = [22, 38, 30, 42, 36, 28, 40, 18];
          const h = heights[i];
          return (
            <g key={i}>
              <rect x={x - 5} y={-h} width="10" height={h} fill="#0a0503" stroke="#3a1f10" strokeWidth="1" />
              {/* broken top */}
              <path d={`M ${x - 5} ${-h} L ${x - 2} ${-h - 3} L ${x + 1} ${-h - 1} L ${x + 5} ${-h + 1}`}
                    fill="none" stroke="#5a3018" strokeWidth="1" />
            </g>
          );
        })}
      </g>

      {/* Central tallest column with banner */}
      <g transform="translate(0, -80)">
        <rect x="-4" y="0" width="8" height="50" fill="#0a0503" stroke="#5a3018" strokeWidth="1" />
        {/* Banner */}
        <path d="M 4 4 L 36 6 L 32 22 L 36 38 L 4 36 Z" fill="#E63946" stroke="#7A1820" strokeWidth="1" opacity=".9" />
        <path d="M 16 12 L 24 12 M 18 18 L 22 18 M 16 24 L 24 24" stroke="#1a0e08" strokeWidth="1.2" opacity=".5" />
      </g>

      {/* Smoke from inside */}
      <g opacity=".5">
        <path d="M -20 -36 Q -16 -56 -24 -76 Q -16 -86 -10 -98"
              fill="none" stroke="#5a3018" strokeWidth="1.5" strokeLinecap="round" />
        <path d="M 10 -32 Q 18 -52 12 -72 Q 22 -82 18 -94"
              fill="none" stroke="#5a3018" strokeWidth="1.2" strokeLinecap="round" />
      </g>
    </g>

    {/* Birds */}
    <g stroke="#5a3018" strokeWidth="1.2" fill="none" strokeLinecap="round" opacity=".7">
      <path d="M 480 180 q 4 -4 8 0 q 4 -4 8 0" />
      <path d="M 530 220 q 3 -3 6 0 q 3 -3 6 0" />
      <path d="M 190 250 q 3 -3 6 0 q 3 -3 6 0" />
      <path d="M 230 200 q 4 -4 8 0 q 4 -4 8 0" />
    </g>

    {/* Foreground brush stroke ground line — anchors it visually */}
    <g opacity=".4">
      <path d="M 60 605 Q 250 615 380 600 T 660 612"
            stroke="#D4A84B" strokeWidth="3" fill="none" strokeLinecap="round" />
    </g>
  </svg>
);

// Subtle haze / gold spotlight overlay (no arches now)
const HazeBackdrop = () => (
  <svg viewBox="0 0 1440 900" preserveAspectRatio="xMidYMax slice"
       style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }}>
    <defs>
      <radialGradient id="haze-2" cx="60%" cy="40%" r="55%">
        <stop offset="0" stopColor="#3a1810" stopOpacity=".4" />
        <stop offset=".55" stopColor="#1a0f08" stopOpacity=".18" />
        <stop offset="1" stopColor="#0a0805" stopOpacity="0" />
      </radialGradient>
      <radialGradient id="spot-2" cx="60%" cy="0%" r="55%">
        <stop offset="0" stopColor="#D4A84B" stopOpacity=".12" />
        <stop offset="1" stopColor="#D4A84B" stopOpacity="0" />
      </radialGradient>
      <linearGradient id="floor-2" x1="0" y1="0" x2="0" y2="1">
        <stop offset=".55" stopColor="#0a0805" stopOpacity="0" />
        <stop offset="1" stopColor="#0a0805" stopOpacity=".75" />
      </linearGradient>
    </defs>
    <rect width="1440" height="900" fill="url(#haze-2)" />
    <rect width="1440" height="900" fill="url(#spot-2)" />
    <rect width="1440" height="900" fill="url(#floor-2)" />
    {/* Dust */}
    <g opacity=".4">
      {Array.from({ length: 35 }).map((_, i) => {
        const cx = (i * 137) % 1440;
        const cy = ((i * 91) % 760) + 60;
        const r = .8 + (i % 3) * .4;
        return <circle key={i} cx={cx} cy={cy} r={r} fill="#D4A84B" opacity={.35 + (i % 5) * .1} />;
      })}
    </g>
  </svg>
);

// Massive logo backdrop — the actual brush logo, faded, placed in the empty
// middle gap between title and right rail. Tagline cropped out.
const LogoBackdrop = () => (
  <>
    {/* Logo image — cropped to hide tagline, fills middle space */}
    <div style={{
      position: 'absolute',
      left: '36%', top: '4%',
      width: 720, height: 540,
      pointerEvents: 'none',
      overflow: 'hidden',
    }}>
      <div style={{
        width: 720, height: 720,
        backgroundImage: 'url("assets/logo-czf.webp")',
        backgroundSize: 'contain',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'center top',
        mixBlendMode: 'lighten',
        opacity: .22,
        filter: 'contrast(.9) saturate(.7)',
      }} />
    </div>
    {/* Soft left fade so title block stays clean */}
    <div style={{
      position: 'absolute', left: 0, top: 0, bottom: 0, width: '52%',
      pointerEvents: 'none',
      background: 'linear-gradient(90deg, rgba(10,8,5,1) 0%, rgba(10,8,5,.9) 50%, rgba(10,8,5,.4) 85%, transparent 100%)',
    }} />
    {/* Right fade so the right rail content stays clean */}
    <div style={{
      position: 'absolute', right: 0, top: 0, bottom: 0, width: '24%',
      pointerEvents: 'none',
      background: 'linear-gradient(270deg, rgba(10,8,5,1) 0%, rgba(10,8,5,.7) 50%, transparent 100%)',
    }} />
  </>
);

// Massive painted CZF backdrop — fills right side, fades into bg
const HeroBackdrop = () => (
  <svg viewBox="0 0 1200 900" preserveAspectRatio="xMidYMid slice"
       style={{ position: 'absolute', top: 0, right: 0, width: '70%', height: '100%', pointerEvents: 'none' }}>
    <defs>
      {/* Rough brush filter for hand-painted feel */}
      <filter id="rough">
        <feTurbulence type="fractalNoise" baseFrequency="0.025" numOctaves="2" seed="3" />
        <feDisplacementMap in="SourceGraphic" scale="10" />
      </filter>
      <filter id="rough2">
        <feTurbulence type="fractalNoise" baseFrequency="0.04" numOctaves="3" seed="7" />
        <feDisplacementMap in="SourceGraphic" scale="6" />
      </filter>
      {/* Soft edge mask for fade-in from left */}
      <linearGradient id="fade-left" x1="0" x2="1">
        <stop offset="0" stopColor="#000" stopOpacity="0" />
        <stop offset=".18" stopColor="#000" stopOpacity=".4" />
        <stop offset=".4" stopColor="#000" stopOpacity=".85" />
        <stop offset="1" stopColor="#000" stopOpacity="1" />
      </linearGradient>
      <mask id="m-fade">
        <rect width="1200" height="900" fill="url(#fade-left)" />
      </mask>
    </defs>

    <g mask="url(#m-fade)" filter="url(#rough)">
      {/* Big white "C" brushstroke */}
      <Brush d="M 400 250 Q 280 320 290 480 Q 300 640 440 700" color="#E8DEC2" width="110" opacity=".22" />
      {/* Big red "Z" diagonal */}
      <Brush d="M 580 220 L 820 230" color="#E63946" width="80" opacity=".48" />
      <Brush d="M 800 240 L 600 660" color="#E63946" width="95" opacity=".58" />
      <Brush d="M 590 650 L 830 670" color="#E63946" width="80" opacity=".5" />
      {/* Big "F" right */}
      <Brush d="M 900 240 L 1100 250" color="#E8DEC2" width="60" opacity=".18" />
      <Brush d="M 920 250 L 940 700" color="#E8DEC2" width="100" opacity=".22" />
      <Brush d="M 920 450 L 1040 450" color="#E8DEC2" width="55" opacity=".19" />
      {/* Gold underline */}
      <Brush d="M 380 760 Q 600 750 820 770 T 1100 760" color="#D4A84B" width="14" opacity=".55" />
    </g>

    {/* Extra splashes for texture */}
    <g filter="url(#rough2)" mask="url(#m-fade)">
      <Brush d="M 200 380 Q 300 360 400 400" color="#E8DEC2" width="20" opacity=".08" />
      <Brush d="M 950 100 L 1000 200" color="#E63946" width="14" opacity=".35" />
      <Brush d="M 1080 600 L 1140 680" color="#D4A84B" width="10" opacity=".45" />
      <Brush d="M 850 800 Q 870 820 860 850" color="#E63946" width="12" opacity=".3" />
    </g>

    {/* Drip drops */}
    <g opacity=".55">
      <circle cx="610" cy="700" r="3" fill="#E63946" />
      <circle cx="850" cy="690" r="2" fill="#E63946" />
      <circle cx="940" cy="790" r="2.5" fill="#E8DEC2" />
    </g>
  </svg>
);

// Brush underline used as graphic signature beneath social pills
const BrushUnderline = ({ color = '#E8DEC2', opacity = .7 }) => (
  <svg viewBox="0 0 200 12" preserveAspectRatio="none"
       style={{ position: 'absolute', left: 8, right: 8, bottom: 4, width: 'calc(100% - 16px)', height: 6, pointerEvents: 'none' }}>
    <path d="M 5 6 Q 40 2 100 5 T 195 6" stroke={color} strokeWidth="2" fill="none" strokeLinecap="round" opacity={opacity} />
  </svg>
);

const HomePage = () => {
  // Fetch live data from worker (falls back to defaults if API down)
  const [cfg, setCfg] = React.useState(window.__CZF_CONFIG__ || null);
  const [summary, setSummary] = React.useState(null);
  const [recentPlayers, setRecentPlayers] = React.useState(null);
  const [showInscrModal, setShowInscrModal] = React.useState(false);

  React.useEffect(() => {
    if (!window.CZF || !CZF.USE_LIVE_DATA) return;
    const base = CZF.API_BASE;
    // Config
    fetch(`${base}/public/config`).then(r => r.json()).then(c => { setCfg(c); window.__CZF_CONFIG__ = c; }).catch(() => {});
    // Summary stats
    fetch(`${base}/public/summary`).then(r => r.json()).then(setSummary).catch(() => {});
    // Recent players (last 4 created)
    fetch(`${base}/public/players-full`).then(r => r.json()).then(arr => {
      const sorted = (arr || []).slice().sort((a, b) => (b.created_at || '').localeCompare(a.created_at || ''));
      setRecentPlayers(sorted.slice(0, 4));
    }).catch(() => {});
  }, []);

  const inscriptions = cfg?.inscriptions || { open: true, deadline: '12 juin' };
  const season = cfg?.season || { number: 4, state: 'EN COURS' };
  const socials = cfg?.socials || {};
  const lc = cfg?.live_cast || null;

  const stats = summary || { players: 0, teams: 0, matches: 0, scrims: 0 };

  return (
    <div className="page-frame" data-screen-label="Home" style={{ position: 'relative' }}>
      <CZFHeader active="home" headerStyle="bone" />

      {/* Atmospheric haze — deepest layer */}
      <HazeBackdrop />

      {/* Massive logo backdrop — the real brush, fadi, off-center */}
      <LogoBackdrop />

      {/* Subtle grain over everything */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none', opacity: .25, mixBlendMode: 'overlay',
        backgroundImage: "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 0.95 0 0 0 0 0.85 0 0 0 0 0.65 0 0 0 .35 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")",
      }} />

      <main style={{ position: 'relative', padding: '3.5rem 0 2rem 2.75rem', minHeight: 760 }}>
        {/* LEFT BLOCK */}
        <div style={{ maxWidth: 640, position: 'relative', zIndex: 2 }}>
          <div className="eyebrow" style={{ marginBottom: '1.25rem', color: 'var(--gold)' }}>
            Saison {season.number} · MYG Community
          </div>

          <h1 className="display" style={{ fontSize: '7.5rem', position: 'relative', marginBottom: '1rem' }}>
            CLASH<br />
            DES <span style={{ color: 'var(--red)', position: 'relative' }}>
              ZÉROS
              <svg viewBox="0 0 300 24" style={{ position: 'absolute', left: '-4%', right: '-4%', bottom: '-14px', width: '108%', height: 20 }}>
                <path d="M5 14 Q60 6 150 10 T295 12" stroke="var(--gold)" strokeWidth="5" fill="none" strokeLinecap="round" opacity=".9" />
                <path d="M20 20 Q120 18 220 21 T290 19" stroke="var(--gold)" strokeWidth="2" fill="none" strokeLinecap="round" opacity=".55" />
              </svg>
            </span><br />
            DE LA<br />
            FAILLE
          </h1>

          <p style={{ fontSize: '1.05rem', color: 'var(--cream)', lineHeight: 1.7, maxWidth: 480, marginBottom: '2rem' }}>
            Le tournoi amateur de la communauté <strong style={{ color: 'var(--gold)', fontWeight: 600 }}>MYG</strong>. Trois divisions, de Bronze à Master. Plus de 100 joueurs, scrims ouverts, et un cast complet sur Twitch.
          </p>

          {/* Single red CTA */}
          <div style={{ display: 'flex', gap: '.75rem', marginBottom: '3rem', alignItems: 'center' }}>
            <a className="btn btn-red" style={{ padding: '.85rem 1.5rem', fontSize: '.85rem', cursor: 'pointer' }} onClick={() => setShowInscrModal(true)}>
              S'inscrire <Icon.ChevronR />
            </a>
            <span style={{ fontFamily: 'var(--fc)', fontSize: '.72rem', color: 'var(--cream-2)', letterSpacing: '.1em' }}>
              {inscriptions.open
                ? `Inscriptions ouvertes${inscriptions.deadline ? ` · clôture le ${inscriptions.deadline}` : ''}`
                : 'Inscriptions fermées'}
            </span>
          </div>

          {/* Stats — 4 columns */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '.85rem', maxWidth: 620 }}>
            {[
              { n: stats.players ?? 0, l: 'Joueurs',        sub: stats.new_this_week ? `+${stats.new_this_week} cette semaine` : '' },
              { n: stats.teams   ?? 0, l: 'Équipes',        sub: '3 divisions' },
              { n: stats.matches ?? 0, l: 'Matchs joués',   sub: `Saison ${season.number}` },
              { n: stats.scrims  ?? 0, l: 'Scrims ouverts', sub: 'En attente' },
            ].map((s, i) => (
              <div key={i} style={{
                background: 'rgba(20,16,10,.7)', backdropFilter: 'blur(4px)',
                border: '1px solid var(--border)', borderRadius: 3,
                padding: '.85rem .9rem 1rem', position: 'relative', overflow: 'hidden',
              }}>
                <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 2, background: 'var(--gold)' }} />
                <span className="stat-n" style={{ fontSize: '2.2rem' }}>{s.n}</span>
                <div className="stat-l" style={{ marginTop: '.25rem' }}>{s.l}</div>
                <div style={{ fontFamily: 'var(--fc)', fontSize: '.62rem', color: 'var(--muted)', marginTop: '.15rem' }}>{s.sub}</div>
              </div>
            ))}
          </div>
        </div>

        {/* RIGHT RAIL — flush to edge */}
        <aside style={{
          position: 'absolute', top: '2.25rem', right: '1.25rem',
          width: 280, zIndex: 3,
          display: 'flex', flexDirection: 'column', gap: '1rem',
        }}>
          {/* LIVE NOW card — affiché seulement si un cast est en cours */}
          {lc?.is_live && lc?.duo?.length >= 1 && (
          <div className="card-paper grain" style={{ padding: '1rem 1.1rem 1rem', position: 'relative', overflow: 'hidden' }}>
            <svg viewBox="0 0 200 200" style={{ position: 'absolute', top: -30, right: -50, width: 180, height: 180, opacity: .14, pointerEvents: 'none' }}>
              <Brush d="M 40 30 Q 100 80 80 140 T 140 200" color="#E63946" width="36" />
            </svg>
            <div style={{ display: 'flex', alignItems: 'center', gap: '.5rem', marginBottom: '.65rem', position: 'relative' }}>
              <span className="dot dot-live"></span>
              <span style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 800, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--red-2)' }}>
                Live · Cast en cours
              </span>
            </div>
            <div style={{ fontFamily: 'var(--fd)', fontSize: '1.2rem', letterSpacing: '.04em', color: 'var(--paper-ink)', lineHeight: 1.1, position: 'relative' }}>
              {(lc.match || '').toUpperCase()}
            </div>
            <div style={{ fontFamily: 'var(--fc)', fontSize: '.65rem', letterSpacing: '.12em', color: 'var(--paper-mut)', textTransform: 'uppercase', marginTop: '.35rem' }}>
              Casté par {lc.duo.join(' & ')}
            </div>
            {lc.twitch_url && (
              <a href={lc.twitch_url} target="_blank" rel="noopener" className="btn" style={{
                marginTop: '.85rem', background: '#9146FF', color: '#fff',
                width: '100%', justifyContent: 'center', padding: '.55rem', fontSize: '.7rem', textDecoration: 'none',
              }}>
                <Icon.Twitch /> Regarder le live
              </a>
            )}
          </div>
          )}

          {/* Social pills — minimal, transparent, brush signature */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: '.15rem' }}>
            <CleanPill type="discord" name="Discord MYG" sub="2 480 membres" />
            <CleanPill type="twitch" name="mygcommunity" sub="Live · Cast CZF" live />
            <CleanPill type="youtube" name="@mygcommunity" sub="VODs & highlights" />
          </div>

          {/* Derniers inscrits — editorial, no code-y chips */}
          <InscritsBlock />
        </aside>
      </main>

      {/* Bottom strip — featured */}
      <section style={{ padding: '1.25rem 2.75rem 2.5rem', position: 'relative', zIndex: 2 }}>
        <div className="brush-divider" />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '1rem' }}>
          <FeatureCard label="Prochain match" title="Frost Vow vs Iron Howl" sub="Lundi 26 Mai · 21:00 · Poules J6" cta="Pronostiquer" tint="red" />
          <FeatureCard label="Scrims ouverts" title="3 demandes en attente" sub="Yordle, Ixtal, Targon — cette semaine" cta="Voir scrims" tint="cream" />
          <FeatureCard label="Tierlist communauté" title="Nouveau top 1" sub="Volt Riders dépasse Iron Howl" cta="Voter" tint="white" />
        </div>
      </section>

      {showInscrModal && <InscriptionModal onClose={() => setShowInscrModal(false)} />}
    </div>
  );
};

// ── Clean social pill — transparent, brush signature ──
const CleanPill = ({ type, name, sub, live, href }) => {
  const themes = {
    discord: { color: '#A8B0F4', accent: '#5865F2', icon: <Icon.Discord /> },
    twitch:  { color: '#BFA3FF', accent: '#9146FF', icon: <Icon.Twitch /> },
    youtube: { color: '#FF9999', accent: '#FF4646', icon: <Icon.YouTube /> },
  }[type];
  return (
    <a href={href || '#'} target={href ? '_blank' : undefined} rel="noopener" style={{
      display: 'flex', alignItems: 'center', gap: '.75rem',
      padding: '.7rem .9rem .85rem',
      background: 'transparent', borderRadius: 0,
      color: 'var(--bone)', textDecoration: 'none',
      position: 'relative',
      borderBottom: '1px solid transparent',
    }}>
      <span style={{ color: themes.accent, display: 'inline-flex' }}>{themes.icon}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: 'var(--fc)', fontSize: '.92rem', fontWeight: 700,
          letterSpacing: '.05em', color: 'var(--bone)', lineHeight: 1.1,
        }}>{name}</div>
        <div style={{
          fontFamily: 'var(--fc)', fontSize: '.65rem', color: 'var(--cream-2)',
          letterSpacing: '.04em', marginTop: 2,
          display: 'inline-flex', alignItems: 'center', gap: '.35rem',
        }}>
          {live && <span className="dot dot-live" style={{ width: 5, height: 5 }} />}
          {sub}
        </div>
      </div>
      <Icon.ChevronR style={{ color: 'var(--muted)', opacity: .6 }} />
      {/* brush signature underline */}
      <BrushUnderline color={themes.accent} opacity={.55} />
    </a>
  );
};

// ── Inscrits block — editorial, brush signature ──
const InscritsBlock = ({ players }) => {
  const items = (players && players.length > 0)
    ? players.map(p => ({
        name: p.discord_nick || p.discord_tag?.split('#')[0] || '?',
        rank: p.rank_calcule || p.tier || '—',
        when: timeAgo(p.created_at),
      }))
    : (window.MOCK?.inscrits || []);
  return (
  <div style={{ position: 'relative', paddingTop: '1.25rem', marginTop: '.5rem' }}>
    {/* Brush separator on top */}
    <svg viewBox="0 0 280 8" preserveAspectRatio="none" style={{ position: 'absolute', top: 0, left: 0, right: 0, width: '100%', height: 6 }}>
      <path d="M 5 4 Q 60 1 140 3 T 275 4" stroke="var(--gold)" strokeWidth="1.5" fill="none" strokeLinecap="round" opacity=".5" />
    </svg>

    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: '.85rem' }}>
      <div style={{
        fontFamily: 'var(--fd)', fontSize: '1.05rem', color: 'var(--bone)',
        letterSpacing: '.06em',
      }}>NOUVEAUX VENUS</div>
      <span style={{ fontFamily: 'var(--fc)', fontSize: '.62rem', letterSpacing: '.14em', color: 'var(--gold)', textTransform: 'uppercase' }}>+8 cette semaine</span>
    </div>

    <div style={{ display: 'flex', flexDirection: 'column' }}>
      {items.map((p, i) => (
        <div key={i} style={{
          display: 'flex', alignItems: 'center', gap: '.7rem',
          padding: '.55rem 0',
          borderBottom: i < items.length - 1 ? '1px solid rgba(80,70,55,.18)' : 'none',
        }}>
          {/* Avatar — neutral, no division color */}
          <div style={{
            width: 30, height: 30, borderRadius: '50%', flexShrink: 0,
            background: 'linear-gradient(135deg, var(--char-3), var(--char))',
            border: '1px solid var(--border-2)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--fd)', fontSize: '.85rem', color: 'var(--cream)',
            letterSpacing: '.04em',
          }}>{p.name[0]}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: 'var(--fd)', fontSize: '.95rem', color: 'var(--bone)',
              letterSpacing: '.04em', lineHeight: 1,
            }}>{p.name.toUpperCase()}</div>
            <div style={{
              fontFamily: 'var(--fc)', fontSize: '.62rem', color: 'var(--muted)',
              letterSpacing: '.05em', marginTop: 3,
            }}>{p.rank} · {p.when}</div>
          </div>
        </div>
      ))}
    </div>

    <a href="#joueurs" style={{
      display: 'inline-flex', alignItems: 'center', gap: '.3rem', marginTop: '.65rem',
      fontFamily: 'var(--fc)', fontSize: '.65rem', fontWeight: 700, letterSpacing: '.16em',
      textTransform: 'uppercase', color: 'var(--cream-2)', textDecoration: 'none',
    }}>
      Voir tous les joueurs <Icon.ChevronR />
    </a>
  </div>
  );
};

function timeAgo(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 60) return 'il y a un instant';
  if (diff < 3600) return `il y a ${Math.round(diff/60)} min`;
  if (diff < 86400) return `il y a ${Math.round(diff/3600)}h`;
  if (diff < 7*86400) return `il y a ${Math.round(diff/86400)}j`;
  return d.toLocaleDateString('fr-FR');
}

// ── Feature card ──
const FeatureCard = ({ label, title, sub, cta, tint }) => {
  const tints = {
    red:   { accent: 'var(--red)',  bg: 'linear-gradient(135deg, rgba(230,57,70,.10), transparent 70%)' },
    cream: { accent: 'var(--paper-2)', bg: 'linear-gradient(135deg, rgba(244,236,216,.08), transparent 70%)' },
    white: { accent: '#FFFFFF',     bg: 'linear-gradient(135deg, rgba(255,255,255,.07), transparent 70%)' },
  }[tint];
  return (
    <div style={{
      background: `${tints.bg}, var(--char)`,
      border: '1px solid var(--border)', borderRadius: 4,
      padding: '1.1rem 1.25rem 1.2rem', position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 2, background: tints.accent, opacity: .85 }} />
      <div className="eyebrow" style={{ color: tints.accent, marginBottom: '.55rem' }}>{label}</div>
      <div style={{ fontFamily: 'var(--fd)', fontSize: '1.35rem', color: 'var(--bone)', letterSpacing: '.04em', lineHeight: 1 }}>{title}</div>
      <div style={{ fontFamily: 'var(--fc)', fontSize: '.75rem', color: 'var(--muted)', marginTop: '.4rem', letterSpacing: '.04em' }}>{sub}</div>
      <a style={{
        display: 'inline-flex', alignItems: 'center', gap: '.3rem', marginTop: '.85rem',
        fontFamily: 'var(--fc)', fontSize: '.7rem', fontWeight: 700, letterSpacing: '.16em',
        textTransform: 'uppercase', color: tints.accent, textDecoration: 'none',
      }}>
        {cta} <Icon.ChevronR />
      </a>
    </div>
  );
};

Object.assign(window, { HomePage });

// ── Inscription modal ──
const InscriptionModal = ({ onClose }) => (
  <div onClick={onClose} style={{
    position: 'fixed', inset: 0, zIndex: 600,
    background: 'rgba(0,0,0,.75)', backdropFilter: 'blur(4px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1.5rem',
  }}>
    <div onClick={e => e.stopPropagation()} className="card-paper grain" style={{
      width: '100%', maxWidth: 560, padding: '1.75rem 2rem', position: 'relative', overflow: 'hidden',
      boxShadow: '0 24px 60px rgba(0,0,0,.8)',
    }}>
      <svg viewBox="0 0 200 200" style={{ position: 'absolute', top: -20, right: -30, width: 160, height: 160, opacity: .22, pointerEvents: 'none' }}>
        <path d="M 40 30 Q 100 80 80 140 T 140 200" stroke="#E63946" strokeWidth="36" fill="none" strokeLinecap="round" />
      </svg>
      <button onClick={onClose} style={{
        position: 'absolute', top: 12, right: 12, zIndex: 3,
        width: 28, height: 28, borderRadius: 2,
        background: 'transparent', border: '1px solid rgba(0,0,0,.15)',
        color: 'var(--paper-mut)', fontFamily: 'var(--fc)', fontSize: '1rem', cursor: 'pointer',
      }}>×</button>

      <div className="eyebrow" style={{ color: 'var(--red-2)', marginBottom: '.65rem' }}>Comment s'inscrire</div>
      <div style={{ fontFamily: 'var(--fd)', fontSize: '2.2rem', color: 'var(--paper-ink)', letterSpacing: '.04em', lineHeight: 1 }}>REJOINS LE CZF</div>
      <div style={{ fontFamily: 'var(--fc)', fontSize: '.9rem', color: 'var(--paper-mut)', marginTop: '.5rem', lineHeight: 1.55, position: 'relative' }}>
        L'inscription se fait sur Discord avec une commande slash.
      </div>

      <div style={{ marginTop: '1.25rem', padding: '1rem', background: 'rgba(0,0,0,.06)', borderRadius: 4, border: '1px dashed rgba(0,0,0,.15)' }}>
        <div style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--paper-mut)', marginBottom: '.5rem' }}>Étape 1 · tape sur Discord</div>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: '.85rem',
          padding: '.55rem .75rem', background: '#36393f', color: '#dcddde', borderRadius: 4,
          display: 'inline-flex', alignItems: 'center', gap: '.5rem',
        }}>
          <span style={{ color: '#7289da' }}>/inscrire</span>
          <span style={{ background: 'rgba(114,137,218,.15)', padding: '.15rem .45rem', borderRadius: 3, color: '#a8b0f4', fontSize: '.78rem' }}>riotid</span>
          <span style={{ color: '#72767d', fontSize: '.78rem' }}>MonPseudo#EUW</span>
        </div>
        <div style={{ fontFamily: 'var(--fc)', fontSize: '.75rem', color: 'var(--paper-mut)', marginTop: '.65rem', lineHeight: 1.5 }}>
          Remplace <strong>MonPseudo#EUW</strong> par ton Riot ID (visible en jeu).
        </div>
      </div>

      <div style={{ marginTop: '.85rem', padding: '1rem', background: 'rgba(0,0,0,.06)', borderRadius: 4, border: '1px dashed rgba(0,0,0,.15)' }}>
        <div style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--paper-mut)', marginBottom: '.5rem' }}>Étape 2 · confirmation</div>
        <div style={{ fontFamily: 'var(--fc)', fontSize: '.78rem', color: 'var(--paper-ink)', lineHeight: 1.5 }}>
          Le bot analyse tes 40 dernières parties ranked, te place dans la bonne division (Yordle / Ixtal / Targon) et te donne le rôle Discord correspondant.
        </div>
      </div>

      <a href="https://discord.com/channels/1500055832409145455/1504119719786057830" target="_blank" rel="noopener"
         className="btn" style={{
           width: '100%', justifyContent: 'center', marginTop: '1.25rem', padding: '.75rem',
           background: '#5865F2', color: '#fff', textDecoration: 'none',
         }}>
        <Icon.Discord /> Ouvrir le salon #inscription
      </a>
      <div style={{ fontFamily: 'var(--fc)', fontSize: '.65rem', color: 'var(--paper-mut)', textAlign: 'center', marginTop: '.6rem', letterSpacing: '.04em' }}>
        Déjà inscrit ? Utilise <code style={{ color: 'var(--red-2)' }}>/refresh</code> pour mettre à jour tes stats.
      </div>
    </div>
  </div>
);
