// hifi-sections.jsx — sections of the hi-fi La Foire page.

// ────── HERO (3 variants : cubes / monster / classic) ──────
function Hero({ variant = 'cubes' }) {
  return (
    <section className={`hero hero--${variant}`}>
      <Starburst color="#F4BF33" />
      <KraftOverlay />

      <div className="hero__inner container">
        {/* Bulb garland at the top */}
        <div className="hero__garland"><BulbGarland count={13} /></div>

        {/* CONTENT — switches on variant */}
        {variant === 'cubes' && <HeroCubes />}
        {variant === 'monster' && <HeroMonster />}
        {variant === 'classic' && <HeroClassic />}

        {/* Sub & CTAs (shared across variants) */}
        <div className="hero__sub">
          <strong>{CONTENT.hero.subBold}</strong>{CONTENT.hero.subRest}
        </div>
        <div className="hero__cta-row">
          <a href="#final" className="btn btn--losange btn--lg btn--yellow hero__cta">
            {CONTENT.hero.cta} <span className="btn__arrow" />
          </a>
        </div>

        <div className="hero__pun">{CONTENT.hero.pun}</div>
      </div>
    </section>);

}

// Variant 1 — Lettres-cubes (default, brand signature)
function HeroCubes() {
  return (
    <div className="hero__title-wrap">
      <div className="hero__title">
        {'LAFOIRE'.split('').map((c, i) => (
          <span key={i} className="hero__cube">{c}</span>
        ))}
      </div>
    </div>);

}

// Variant 2 — Typo monstre
function HeroMonster() {
  return (
    <div className="hero__title-wrap" style={{ position: 'relative' }}>
      <div className="hero__title-monster">LA<br />FOIRE</div>
      <span className="hero__script" style={{ position: 'absolute', right: '4%', top: '38%' }}>les stands !</span>
    </div>);

}

// Variant 3 — Classic
function HeroClassic() {
  return (
    <div className="hero__title-wrap">
      <div className="hero__title-classic">La Foire</div>
      <span className="hero__script">les stands.</span>
    </div>);

}

// ────── PITCH section ──────────────────────────────────────
const PLATE_VARIANTS = ['', 'yellow', ''];
const PLATE_ROTATES  = [-2.5, 1.5, -1.5];

function PitchSection() {
  const { eyebrow, titleLine1, titleWord, titleLine2, lead, note, plates } = CONTENT.pitch;
  const noteLines = note.split('\n');
  return (
    <section id="pitch" className="section section--lait pitch">
      <span className="pitch__note" aria-hidden="true">
        {noteLines.map((l, i) => <React.Fragment key={i}>{l}{i < noteLines.length - 1 && <br />}</React.Fragment>)}
      </span>
      <div className="container">
        <Reveal className="pitch__intro">
          <Eyebrow>{eyebrow}</Eyebrow>
          <h2 className="section__title">
            {titleLine1}<br />la <em className="pitch__kermesse">{titleWord}</em> {titleLine2}
          </h2>
          <p className="pitch__lead">{lead}</p>
        </Reveal>

        <div className="pitch__plates">
          {plates.map((p, i) => (
            <Reveal key={i} className="plate-wrap" delay={i * 120}>
              <div
                className={`plate ${PLATE_VARIANTS[i] ? 'plate--' + PLATE_VARIANTS[i] : ''}`}
                style={{ transform: `rotate(${PLATE_ROTATES[i]}deg)` }}
              >
                <span className="plate__rivet plate__rivet--tl" />
                <span className="plate__rivet plate__rivet--tr" />
                <span className="plate__rivet plate__rivet--bl" />
                <span className="plate__rivet plate__rivet--br" />
                <div className="plate__num">
                  {p.num}{p.unit && <small>{p.unit}</small>}
                </div>
                <div className="plate__lbl">{p.label}</div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>);
}

// ────── HOW IT WORKS ───────────────────────────────────────
function HowSection() {
  const steps = [
  { n: '1', t: 'Tu badges', d: "Récupère ton bracelet RFID à l'accueil." },
  { n: '2', t: 'Tu joues', d: '7 stands en libre-accès, 1h30, 2 manches automatiques.' },
  { n: '3', t: 'Tu marques', d: 'Chaque action te rapporte des points, en temps réel.' },
  { n: '4', t: 'Tu triomphes', d: "Leaderboard live affiché en salle pour l'équipe." }];

  return (
    <section className="section section--paper">
      <div className="container">
        <Reveal className="section-head">
          <Eyebrow>Comment ça marche</Eyebrow>
          <h2 className="section__title">Quatre temps,<br />zéro friction.</h2>
        </Reveal>

        <div className="steps">
          {steps.map((s, i) =>
          <Reveal key={i} className="step" delay={i * 100}>
              <NumDiamond size="lg" rotate={i % 2 ? 3 : -3}>{s.n}</NumDiamond>
              <div className="step__title">{s.t}</div>
              <div className="step__desc">{s.d}</div>
            </Reveal>
          )}
        </div>

        <Reveal className="steps__pun">
          Pas d'opérateur. Pas de monnaie. Pas de queue.<br />
          <span className="steps__pun--cool">Que de la compète entre potes.</span>
        </Reveal>
      </div>
    </section>);

}

// ────── STANDS ─────────────────────────────────────────────
function StandsSection() {
  const { eyebrow, titleLine1, titleLine2 } = CONTENT.stands;
  return (
    <section id="stands" className="section section--lait">
      <div className="container">
        <Reveal className="stands__head">
          <Eyebrow>{eyebrow}</Eyebrow>
          <h2 className="section__title">
            {titleLine1}<br />
            <span style={{ color: 'var(--c-bavette)' }}>{titleLine2}</span>
          </h2>
        </Reveal>

        <div className="stands__grid">
          {STANDS_DATA.map((s, i) =>
          <Reveal key={s.n} className="stand" delay={i % 3 * 80}>
              <div className="stand__head">
                <NumDiamond variant={s.yellow ? 'yellow' : ''} rotate={i % 2 ? 3 : -3}>{s.n}</NumDiamond>
              </div>
              <div
                className={`stand__photo ${s.yellow ? 'stand__photo--yellow' : ''}`}
                style={{ '--stand-color': s.color || '#1B223F' }}>
                {s.photo
                  ? <img src={s.photo} alt={s.name} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                  : <span className="stand__photo-label">Photo à fournir</span>
                }
              </div>
              <h3 className="stand__name">{s.name}</h3>
              <p className="stand__desc">{s.desc}</p>
            </Reveal>
          )}
        </div>
      </div>
    </section>);

}

// ────── LEADERBOARD ────────────────────────────────────────
const ROW_H = 46; // px — must match padding + content height in CSS

function LeaderboardSection() {
  const [players, setPlayers] = React.useState(CONTENT.leaderboard.players);

  // { id → { delta, key } } — one popup per player at a time
  const [popups, setPopups] = React.useState({});
  const [clock, setClock] = React.useState('21:47');

  // Clock ticks forward 1 min every 8 s
  React.useEffect(() => {
    let total = 21 * 60 + 47;
    const id = setInterval(() => {
      total++;
      const h = Math.floor(total / 60) % 24;
      const m = total % 60;
      setClock(`${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}`);
    }, 8000);
    return () => clearInterval(id);
  }, []);

  // Score engine — each tick, 1-2 random players score
  React.useEffect(() => {
    // Different base intervals per player (ms) — "Toi" is the hungriest
    const speeds = { 1: 3200, 2: 2600, 3: 3800, 4: 2900, 5: 2100 };

    const timers = Object.entries(speeds).map(([idStr, interval]) => {
      const pid = Number(idStr);
      const tick = () => {
        // 25% chance of missing this tick
        if (Math.random() < 0.25) return;
        const delta = Math.floor(Math.random() * 170) + 40;
        const popKey = Date.now();

        setPlayers(prev =>
          prev.map(p => p.id === pid ? { ...p, score: p.score + delta } : p)
        );
        setPopups(prev => ({ ...prev, [pid]: { delta, key: popKey } }));
        setTimeout(() =>
          setPopups(prev => {
            if (prev[pid]?.key !== popKey) return prev;
            const next = { ...prev };
            delete next[pid];
            return next;
          }), 1100);
      };
      // Stagger startup so all players don't fire at once
      const jitter = Math.random() * interval;
      let timer;
      const startup = setTimeout(() => { tick(); timer = setInterval(tick, interval); }, jitter);
      return { startup, get timer() { return timer; } };
    });

    return () => timers.forEach(t => { clearTimeout(t.startup); clearInterval(t.timer); });
  }, []);

  const sorted = [...players]
    .sort((a, b) => b.score - a.score)
    .map((p, i) => ({ ...p, rank: i + 1 }));

  return (
    <>
      <section id="leaderboard" className="section section--encre">
        <div className="container">
          <div className="lb">
            <Reveal className="lb__copy">
              <Eyebrow>{CONTENT.leaderboard.eyebrow}</Eyebrow>
              <h2 className="section__title">{CONTENT.leaderboard.title}<br />
                <span style={{ color: 'var(--c-pissenlit)' }}>{CONTENT.leaderboard.titleHighlight}</span>
              </h2>
              <p>{CONTENT.leaderboard.copy}</p>
            </Reveal>

            <Reveal className="lb__screen" delay={120}>
              <div className="lb__head">
                <span className="lb__live">Live · {CONTENT.leaderboard.teamName}</span>
                <span className="lb__clock">{clock}</span>
              </div>
              <div className="lb__list" style={{ height: ROW_H * sorted.length }}>
                {sorted.map((p, idx) => {
                  const popup = popups[p.id];
                  return (
                    <div
                      key={p.id}
                      className={`lb__row ${p.me ? 'lb__row--me' : ''}`}
                      style={{ top: idx * ROW_H }}
                    >
                      <div className={`lb__rank ${p.rank === 1 ? 'lb__rank--first' : ''}`}>
                        {p.rank}
                      </div>
                      <div className="lb__name">{p.name}</div>
                      <div className="lb__score" style={{ position: 'relative' }}>
                        <span className={popup ? 'lb__score--flash' : ''} key={popup?.key}>
                          {p.score.toLocaleString('fr-FR')}
                        </span>
                        {popup && (
                          <span className="lb__delta" key={'d' + popup.key}>
                            +{popup.delta}
                          </span>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </Reveal>
          </div>
        </div>
      </section>
      <Damier variant="encre" />
    </>
  );
}

// ────── F&B (variant B · Cartes polaroid) ─────────────────
const FB_ROTATES = [-2.5, 2.5];
const FB_KINDS   = ['food', 'bar'];

function FBSection() {
  const { eyebrow, title, intro, blocks: rawBlocks } = CONTENT.fb;
  const blocks = rawBlocks.map((b, i) => ({
    ...b,
    kind: FB_KINDS[i],
    cap: b.caption,
    ctaLabel: b.cta,
    rotate: FB_ROTATES[i],
  }));

  return (
    <section id="fb" className="section section--paper">
      <div className="container">
        <Reveal className="fb__head">
          <Eyebrow>{eyebrow}</Eyebrow>
          <h2 className="section__title">
            {title}<br />
            pour <em style={{ fontStyle: 'normal', color: 'var(--c-bavette)' }}>trinquer</em> &amp; <em style={{ fontStyle: 'normal', color: 'var(--c-bavette)' }}>manger</em>.
          </h2>
          <p>{intro}</p>
        </Reveal>

        <div className="fb__split">
          {blocks.map((b, i) => (
            <Reveal key={b.kind} className="fb__stack" delay={i * 120}>
              <div className="fb__polaroid" style={{ transform: `rotate(${b.rotate}deg)` }}>
                <span className="fb__tape" aria-hidden="true" />
                <div className="fb__polaroid-photo" style={{ background: '#111' }}>
                  {b.photo
                    ? <img src={b.photo} alt={b.name} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                    : <span className="fb__polaroid-photo-label">Photo à fournir</span>
                  }
                </div>
                <div className="fb__polaroid-cap">{b.cap}</div>
              </div>
              <div className="fb__card">
                <div className="fb__card-eyebrow">{b.eyebrow}</div>
                <h3 className="fb__card-name">{b.name}</h3>
                <p className="fb__card-copy">{b.copy}</p>
                <div className="fb__card-foot">
                  <span className="fb__card-note">{b.note}</span>
                  <a href="#" className="btn btn--losange btn--md btn--ink fb__card-cta">
                    {b.ctaLabel} <span className="btn__arrow" />
                  </a>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>);

}

// ────── FINAL CTA ──────────────────────────────────────────
function FinalCTASection() {
  const { titleLine1, titleLine2, sub, cta1, cta2 } = CONTENT.final;
  return (
    <section id="final" className="section section--bavette final">
      <KraftOverlay />
      <Starburst color="#1B223F" />
      <div className="container" style={{ position: 'relative', zIndex: 2 }}>
        <div className="hero__garland" style={{ justifyContent: 'center', marginBottom: 32 }}>
          <BulbGarland count={7} />
        </div>
        <Reveal>
          <h2 className="final__title">{titleLine1}<br />{titleLine2}</h2>
        </Reveal>
        <Reveal delay={120}>
          <span className="final__sub">{sub}</span>
        </Reveal>
        <Reveal className="final__cta-row" delay={240}>
          <a href="#" className="btn btn--losange btn--lg btn--yellow">{cta1} <span className="btn__arrow" /></a>
          <a href="#" className="btn btn--losange btn--lg btn--cream">{cta2}</a>
        </Reveal>
      </div>
    </section>);

}

// ────── FOOTER ─────────────────────────────────────────────
function Footer() {
  return (
    <footer className="footer">
      <div className="footer__inner">
        <img src="assets/logo-red-diamond.png" alt="Au Taquet" />
        <Tagline size={13} style={{ color: 'var(--c-lait)' }} />
        <div className="footer__links">
          {CONTENT.footer.links.map(l => <a key={l.label} href={l.href}>{l.label}</a>)}
        </div>
      </div>
    </footer>);

}

Object.assign(window, {
  Hero, PitchSection, HowSection, StandsSection,
  LeaderboardSection, FBSection, FinalCTASection, Footer
});