// Accueil SAISON 02 — reprend la maquette « ttc saison 02 » (maillots option A),
// avec les vraies données du site : sorties hebdo, agenda (Sheet), adhésion, partenaires.
// Affiché par index.html quand la saison 02 est active (saison.js, ?saison=02).
// Styles : theme-s02.css (préfixe .s2h-). Dépend de agenda.jsx (useAgenda, useVisuels…).

// Les sorties hebdo : le lundi en trois groupes de niveau, le jeudi à l'aventure (version Happy).
const S2H_LUNDI = [
  { name: "Happy Trail", km: "8 km" },
  { name: "Flow Trail", km: "10 km" },
  { name: "Tonic Trail", km: "12 km" },
];

const S2H_DIRS = [
  { v: "S'entraîner", ex: "Sortie hebdo, séances piste, cohortes par niveau. La meute pousse." },
  { v: "Partager", ex: "Récits, retours matos, échange de plans nutrition. Carnet collectif." },
  { v: "Progresser", ex: "Pas de coach, pas de programme. Courir ensemble, souvent, et avancer sans y penser." },
  { v: "Défendre", ex: "Refuges, sentiers, montagne. Ce qu'on traverse, on en prend soin." },
];

const s2hSaison = () => document.documentElement.getAttribute("data-saison") || "01";
const s2hTag = () => (s2hSaison() === "02" ? "Saison 02 · Nice" : "Social trail run · Nice");

const s2hDate = (e) => {
  const d = e.date, f = e.fin && e.fin > e.date ? e.fin : null;
  if (f) return AG_JOURS[d.getDay()].replace(".", "") + " " + d.getDate() + " → " + AG_JOURS[f.getDay()].replace(".", "") + " " + f.getDate() + " " + AG_MOIS_COURT[f.getMonth()];
  return AG_JOURS[d.getDay()].replace(".", "") + " " + d.getDate() + " " + AG_MOIS_COURT[d.getMonth()] + (e.heure ? " · " + e.heure.replace(/h00$/, " h") : "");
};

// Saison 02 : la date en panneau de stand (le panneau que l'équipe tend au pilote).
const S2hPit = ({ e, live }) => {
  const d = e.date, f = e.fin && e.fin > e.date ? e.fin : null;
  const j = (x) => AG_JOURS[x.getDay()].replace(".", "");
  const p2 = (n) => String(n).padStart(2, "0");
  return (
    <span className="s2h-pit s2-only" aria-hidden="true">
      <span className="l">{live && <span className="s2h-blink"></span>}{j(d)}{f ? " → " + j(f) : ""}</span>
      <span className="n">{p2(d.getDate())}{f ? "-" + p2(f.getDate()) : ""}</span>
      <span className="l m">{AG_MOIS_COURT[(f || d).getMonth()]}{!f && e.heure ? " · " + e.heure.replace(/h00$/, " h") : ""}</span>
    </span>
  );
};

// Bandeau qui défile (atoms.jsx, dans le header) : sur l'accueil, on y ajoute le prochain rendez-vous.
const s2hTickerExtra = (next) => (next ? { g: AG_GLYPH[agIcoKey(next.e, next.v)] || AG_GLYPH.event, c: agLivree(next.e, next.v), t: "Prochain rendez-vous · " + agTitre(next.e, next.v) + " · " + s2hDate(next.e) } : null);

const S2hHero = () => (
  <section className="s2h-hero s2h-intro">
    <div className="s2h-wrap s2h-hero-grid">
      <div className="s2h-hero-copy">
        <h1 className="s2h-title">
          {/* Saison 02 : le damier du sticker « From beginner » devant le titre (masqué en saison 01) */}
          <span className="s2h-flag" aria-hidden="true"></span>
          <span className="l1">From beginner</span> <span className="l2">to <span className="marker">ultra</span> trailer</span>
        </h1>
        <p className="s2h-lede"><strong>Premier social run 100 % trail à Nice.</strong> Des sorties chaque semaine dans l'arrière-pays niçois, gratuites et ouvertes à tous, un moment convivial à l'arrivée.</p>
        <div className="s2h-cta">
          <a className="btn btn-primary" href="#sorties">Voir les sorties →</a>
          <a className="btn" href="agenda.html">L'agenda</a>
        </div>
        <div className="s2-only s2h-hero-marks"><span className="s2-nice" aria-label="06 Nice, Côte d'Azur"><b>06</b><i></i><span><em>Nice</em><small>Côte d'Azur</small></span></span></div>
      </div>
      <div className="s2h-hero-photo">
        <div className="s2h-frame"><img src="img/mercantour-sunset.jpg" alt="Deux coureurs sur un sommet au-dessus de la mer au coucher du soleil, Mercantour" /></div>
        <span className="s2h-stamp">Full push</span>
      </div>
    </div>
    <div className="s2h-checker"></div>
  </section>
);

const S2hSorties = () => (
  <section className="s2h-band s2h-alt" id="sorties">
    <div className="s2h-wrap">
      <div className="s2h-head">
        <div>
          <h2 className="s2h-section-title">Nos sorties hebdo</h2>
        </div>
        <p className="s2h-lede s2h-lede-sm">Ouvertes à tous et gratuites, au départ de Nice. Pas de chrono, pas de classement : on court ensemble et personne ne reste derrière.</p>
      </div>
      <div className="s2h-runs">
        <a className="s2h-run s2h-reveal" href="agenda.html#lundi">
          <span className="s2h-run-top"><span className="s2h-run-day"><span className="s2h-los" style={{ "--c": "var(--ink)" }}><AgPlq e={{ type: "run" }} v={null} /></span>Lundi · 19 h</span><span className="s2h-chip">3 groupes</span></span>
          <span className="s2h-run-t">Lundi trail</span>
          <span className="s2h-run-x">Trois groupes de niveau, même départ, même moment convivial à l'arrivée. Chacun choisit sa distance.</span>
          <span className="s2h-groups">
            {S2H_LUNDI.map((g, i) => <span key={g.name} className="s2h-group"><b><i className={"ag-nv-l n" + (i + 1)} aria-hidden="true"></i>{g.name}</b><em>{g.km}</em></span>)}
          </span>
          <span className="s2h-run-foot"><span>Tous niveaux</span><span className="go">J'y vais →</span></span>
        </a>
        <a className="s2h-run s2h-reveal" href="agenda.html#jeudi">
          <span className="s2h-run-top"><span className="s2h-run-day"><span className="s2h-los" style={{ "--c": "var(--ink)" }}><AgPlq e={{ type: "run" }} v={null} /></span>Jeudi · 19 h</span><span className="s2h-chip s1-only">Happy → Tonic</span></span>
          <span className="s2h-montee"><AgMontee /></span>
          <span className="s2h-run-t">Jeudi trail</span>
          <span className="s2h-run-x">Le parcours change chaque semaine : exploration, surprise, terrain nouveau. Selon le nombre de coureurs, ça va du Happy au Tonic, mais c'est toujours à l'aventure.</span>
          <span className="s2h-run-foot"><span>Surprise hebdo</span><span className="go">J'y vais →</span></span>
        </a>
        <div className="s2h-run s2h-share s2h-reveal">
          <span className="s2h-run-top"><span className="s2h-run-day">Les autres jours</span><span className="s2h-chip">Commu WhatsApp</span></span>
          <span className="s2h-run-t">Partage ta sortie</span>
          <span className="s2h-run-x">Tu cherches des gens avec qui courir ? Propose ta sortie ou rejoins celle d'un autre sur la commu WhatsApp. C'est l'ADN du club : gratuit et ouvert à tous.</span>
          <span className="s2h-run-foot"><span>Gratuit · ouvert à tous</span><span>Via la commu WhatsApp</span></span>
        </div>
      </div>
    </div>
  </section>
);

// Talon de date (jour de la semaine, chiffre, mois), comme les billets de la vue Liste.
const AgTalon = ({ e, live }) => {
  const d = e.date, f = e.fin && e.fin > e.date ? e.fin : null;
  const j = (x) => AG_JOURS[x.getDay()].replace(".", "");
  return (
    <React.Fragment>
      <small>{live && <span className="s2h-blink" aria-hidden="true"></span>}{f ? j(d) + " → " + j(f) : j(d)}</small>
      <b>{f ? d.getDate() + "-" + f.getDate() : String(d.getDate()).padStart(2, "0")}</b>
      <small>{AG_MOIS_COURT[(f || d).getMonth()]}</small>
    </React.Fragment>
  );
};

// Les prochains rendez-vous, lus dans le même Sheet que l'agenda : trois cartes identiques.
const S2hRounds = ({ next, title = "Nos prochains rendez-vous", cta = "Tout l'agenda →", ctaHref = "agenda.html" }) => {
  // un clic ouvre la fiche par-dessus la page (même bulle que l'agenda), sans quitter la page
  const visuels = useVisuels();
  const [ouvert, setOuvert] = React.useState(null);
  const fermer = React.useCallback(() => setOuvert(null), []);
  if (!next.length) return null;
  return (
    <div className="s2h-vert">
      <section className="s2h-band">
        <div className="s2h-wrap">
          <div className="s2h-head">
            <h2 className="s2h-section-title">{title}</h2>
            {cta && <a className="btn btn-primary" href={ctaHref}>{cta}</a>}
          </div>
          <div className="s2h-rdvs">
            {next.map((o, i) => {
              const photo = o.v.photo || o.e.photo || (AG_DEFAUTS[o.e.type] || {}).photo;
              const twitch = o.e.type === "twitch";
              return (
                <a key={o.e.id} className={"s2h-rdv s2h-reveal tk2 u-" + (agRose(o.v) ? "caritatif" : ["twitch", "pause", "team", "run"].includes(o.e.type) ? o.e.type : "event") + (twitch ? " twitch" : "") + (o.v && o.v.mode === "affiche" ? " affiche" : "") + (o.passe ? " passe" : "")} href={o.href || "agenda.html#" + o.e.id} style={{ "--c": agLivree(o.e, o.v), ...(o.v && o.v.ticket ? { "--tb": o.v.ticket, "--tc": o.v.ticketTexte || "#F5F0DF", "--tl": o.v.ticketLabel || o.v.accent, "--tp": o.v.ticketFilet || "rgba(245,240,223,.3)", "--acc": o.v.accent, "--at": o.v.accentTexte || "#003F2D" } : {}) }}
                  onClick={o.href ? undefined : (ev) => { if (ev.metaKey || ev.ctrlKey || ev.shiftKey) return; ev.preventDefault(); setOuvert(o.e); }}>
                  <span className="ph">
                    {twitch
                      // Live Twitch : notre bannière gamer, en entier
                      ? <img className="tw-ban" src="img/agenda/twitch-banniere.jpg" alt="Live Twitch · tout terrain club" loading="lazy" />
                      : o.v && o.v.mode === "affiche" && photo
                        // affiche officielle : en entier, sur un fond flouté tiré de l'affiche
                        ? <React.Fragment><img className="aff-blur" src={photo} alt="" aria-hidden="true" loading="lazy" /><img className="aff" src={photo} alt={"Affiche · " + o.e.titre} loading="lazy" /></React.Fragment>
                        : photo ? <img src={photo} alt="" loading="lazy" style={(o.photoPos || (o.v && o.v.photoPos)) ? { objectPosition: o.photoPos || o.v.photoPos } : undefined} /> : null}
                    {/* le prochain rendez-vous : un point qui clignote */}
                    <span className="s2h-rdv-date">{i === 0 && <span className="s2h-blink" aria-hidden="true"></span>}{s2hDate(o.e)}</span>
                    {o.v.complet && <span className="ag-soldout">Sold out</span>}
                    {/* team course sans photo : le sticker Team ttc sert de visuel (jamais par-dessus une vraie photo) */}
                    {o.e.type === "team" && !photo && <img className="ag-team s2h-rdv-team s2-only" src="img/s02/team-ttc.webp" alt="Team ttc" />}
                  </span>
                  <span className="body">
                    {/* saison 02 : la date en talon de billet, comme la vue Liste de l'agenda */}
                    <span className="s2h-tal" style={{ "--c": agLivree(o.e, o.v) }} data-dark={agSombre(o.e, o.v) ? "1" : undefined}><AgTalon e={o.e} live={i === 0 && o.live !== false} /></span>
                    <span className="s2h-rdv-type"><span className="s2h-los" style={{ "--c": agLivree(o.e, o.v) }}><AgPlq e={o.e} v={o.v} /><AgAdh e={o.e} /></span><span className="s2-only">{agTheme(o.e, o.v)}{o.e.acces === "Réservé membres" ? " · Adhérents" : o.e.acces === "Priorité membres" ? " · Priorité adhérents" : ""}</span><span className="s1-only">{o.e.typeLabel}{o.e.acces === "Réservé membres" ? " · Adhérents" : ""}</span></span>
                    <span className="s2h-rdv-t">{agTitre(o.e, o.v)}</span>
                    {o.e.lieu && <span className="s2h-rdv-lieu">{o.e.lieu}</span>}
                    <span className="go"><b>{(() => { const l = o.go || (o.v.complet ? "Je regarde →" : "J'y vais →"); return l.length > 12 ? (o.passe ? "Revivre →" : o.v.complet ? "Je regarde →" : "J'y vais →") : l; })()}</b></span>
                  </span>
                </a>
              );
            })}
          </div>
        </div>
        <div className="s2h-checker orange"></div>
      </section>
      {ouvert && <AgDayModal k={agIso(ouvert.date)} items={[{ e: ouvert }]} visuels={visuels} onClose={fermer} />}
    </div>
  );
};

// Crossfader façon table de mixage : une barre verticale coupe la photo, Trail (montagne) à gauche,
// Techno (DJ set) à droite. La barre va et vient toute seule ; on la prend en main avec la manette
// ou en glissant sur la photo, et elle repart seule après quelques secondes.
const S2hCrossfader = () => {
  const [v, setV] = React.useState(50); // 0 = tout Trail, 100 = tout Techno
  const zone = React.useRef(null);
  const drag = React.useRef(false);
  const touched = React.useRef(0);
  const hold = () => { touched.current = Date.now(); };
  React.useEffect(() => {
    if (window.matchMedia && matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let raf, t0 = performance.now(), base = 50;
    const tick = (t) => {
      if (Date.now() - touched.current > 4000 && !drag.current) {
        // aller-retour doux de 15 % à 85 % (une boucle ≈ 7 s)
        setV(Math.round(50 + 35 * Math.sin((t - t0) / 1100)));
      } else { t0 = t - Math.asin(Math.max(-1, Math.min(1, (base - 50) / 35))) * 1100; }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);
  const fromX = (x) => {
    const r = zone.current.getBoundingClientRect();
    // position de la barre = x ; à droite de la barre, Techno
    setV(Math.max(0, Math.min(100, Math.round(100 - ((x - r.left) / r.width) * 100)))); hold();
  };
  const bar = 100 - v; // position de la barre en % depuis la gauche
  return (
    <div className="s2h-xf">
      <div className="s2h-xf-stage" ref={zone} role="slider" tabIndex={0} aria-label="Crossfader : de Trail (montagne) à Techno (DJ set)"
        aria-valuemin={0} aria-valuemax={100} aria-valuenow={v}
        onKeyDown={(e) => { if (e.key === "ArrowRight") { setV(Math.min(100, v + 10)); hold(); } if (e.key === "ArrowLeft") { setV(Math.max(0, v - 10)); hold(); } }}
        onPointerDown={(e) => { drag.current = true; e.currentTarget.setPointerCapture(e.pointerId); fromX(e.clientX); }}
        onPointerMove={(e) => { if (drag.current) fromX(e.clientX); }}
        onPointerUp={() => { drag.current = false; hold(); }} onPointerCancel={() => { drag.current = false; }}>
        <img className="jour" src="img/mc-ridge-run.jpg" alt="Coureurs sur une crête de montagne" draggable="false" />
        <img className="nuit" src="img/dj.jpg" alt="Julien aux platines pendant le DJ set au refuge" draggable="false" style={{ clipPath: "inset(0 0 0 " + bar + "%)" }} />
        <span className="s2h-xf-bar" style={{ left: bar + "%" }} aria-hidden="true"><i></i></span>
        <span className="s2h-xf-lab jour">Trail</span>
        <span className="s2h-xf-lab nuit">Techno</span>
      </div>
    </div>
  );
};

const S2hT2T = () => (
  <section className="s2h-band">
    <div className="s2h-wrap s2h-t2t">
      <div className="s2h-t2t-copy">
        <span className="s2h-eyebrow">Un concept signé <span className="ttc">tout terrain club™</span></span>
        <h2 className="s2h-t2t-title">Trail <span className="to">to</span> <span className="tech">Techno</span></h2>
        <p className="s2h-lede">Un sommet à gravir le jour, un refuge de montagne pour camp de base, et une nuit qui dure jusqu'à ce que le soleil repasse la crête.</p>
        <div className="s2h-daynight">
          <div className="dn day s2h-reveal"><span className="eb">Le jour</span><span className="big">On grimpe</span><span className="sm">De la simple rando à une vraie expédition.</span></div>
          <div className="dn night s2h-reveal"><span className="eb">La nuit</span><span className="big">On partage</span><span className="sm">Repas de refuge et DJ set jusqu'au bout de la nuit.</span></div>
        </div>
        <div className="s2h-cta"><a className="btn btn-primary" href="trail-to-techno.html">Découvrir le concept →</a></div>
      </div>
      <S2hCrossfader />
    </div>
  </section>
);

const S2hDirections = () => (
  <section className="s2h-band s2h-alt">
    <div className="s2h-wrap">
      <div className="s2h-head">
        <div>
          <h2 className="s2h-section-title">L'esprit du club</h2>
        </div>
        <div className="s2h-head-stickers">
          <img className="s2h-head-sticker sticker-str" src="img/s02/social-trail-run.webp?v=2" alt="Social trail run, born in Nice" />
          <img className="s2h-head-sticker" src="img/s02/dplus.webp?v=2" alt="D+" />
        </div>
      </div>
      <div className="s2h-dirs">
        {S2H_DIRS.map((d) => <div key={d.v} className="s2h-dir s2h-reveal"><span className="verb">{d.v}</span><p>{d.ex}</p></div>)}
      </div>
    </div>
  </section>
);

const S2hJoin = () => {
  const A = window.ADHESION || {};
  const prix = A.prix || { membership: 40, athlete: 80 };
  const now = new Date();
  const ouverte = A.ouverture && A.fermeture && now >= new Date(A.ouverture) && now <= new Date(A.fermeture);
  return (
    <div className="s2h-vert">
      <section className="s2h-band s2h-join-band">
        <div className="s2h-wrap s2h-join">
          <div className="s2h-join-copy">
            <div className="s2h-join-head">
              <h2 className="s2h-title s2h-join-t">Rejoins la meute</h2>
              <img className="s2h-join-sticker" src="img/s02/sanglier-racing.webp?v=2" alt="Sanglier Racing" />
            </div>
            <p className="s2h-lede">Les sorties sont gratuites et ouvertes à tous, postées chaque semaine sur Strava. L'adhésion ajoute les à-côtés : infos en priorité, réductions sur les events, ressources pour progresser et soirées.</p>
            <div className="s2h-join-photo"><img src="img/s02/tu-viens.jpg" alt="Une trentaine de membres bras levés sur le port de Nice, de nuit" loading="lazy" /></div>
          </div>
          <div className="s2h-adh s2h-reveal">
            <div className="body">
              <div className="s2-only s2h-adh-marks"><img src="img/s02/team-ttc.webp" alt="Team ttc" /><img src="img/s02/pit-crew.webp" alt="Pit crew" /></div>
              <div className="tier">Adhésion saison 2027 · Athlète</div>
              <div className="price">{prix.athlete} €<span className="per"> / saison</span></div>
              <p className="alt">Ou {prix.membership} € en formule Membre, sans le t-shirt.</p>
              <ul>
                <li><span className="ck">✓</span>Le t-shirt trail saison 02 inclus</li>
                <li><span className="ck">✓</span>−{A.remiseAthlete || 20} % sur le reste du merch</li>
                <li><span className="ck">✓</span>Infos et inscriptions en priorité</li>
                <li><span className="ck">✓</span>Réductions sur les events et les soirées</li>
              </ul>
              <div className="s2h-adh-cta">
                <a className="btn" href="adhesion-2027.html">{ouverte ? "J'adhère →" : "Adhésions fermées · en savoir plus"}</a>
                <a className="btn btn-ghost-light" href="https://www.strava.com/clubs/toutterrainclub" target="_blank" rel="noopener">Nos sorties sur Strava ↗</a>
              </div>
            </div>
            
          </div>
        </div>
      </section>
    </div>
  );
};

// Apparitions au défilement + compteurs (coupés si l'appareil demande moins d'animations).
function useS2hMotion() {
  React.useEffect(() => {
    const reduce = window.matchMedia && matchMedia("(prefers-reduced-motion: reduce)").matches;
    const header = document.querySelector(".header");
    const onScroll = () => { if (header) header.classList.toggle("s2h-scrolled", (window.scrollY || 0) > 12); };
    addEventListener("scroll", onScroll, { passive: true }); onScroll();
    if (reduce || !("IntersectionObserver" in window)) return () => removeEventListener("scroll", onScroll);
    const io = new IntersectionObserver((entries) => entries.forEach((en) => {
      if (!en.isIntersecting) return;
      const el = en.target; io.unobserve(el);
      if (el.dataset.count) {
        const target = +el.dataset.count, small = el.querySelector("small"), suffix = small ? small.outerHTML : "";
        const t0 = performance.now(), dur = 1100, fmt = (n) => n >= 1000 ? Math.round(n).toLocaleString("fr-FR").replace(/ | /g, " ") : String(Math.round(n));
        const step = (t) => { const k = Math.min(1, (t - t0) / dur); el.innerHTML = fmt(target * (1 - Math.pow(1 - k, 3))) + suffix; if (k < 1) requestAnimationFrame(step); };
        requestAnimationFrame(step); return;
      }
      const i = el.parentElement ? Array.prototype.indexOf.call(el.parentElement.children, el) : 0;
      el.animate([{ opacity: 0, transform: "translateY(28px)" }, { opacity: 1, transform: "none" }], { duration: 650, delay: Math.min(i, 5) * 80, easing: "cubic-bezier(.2,.8,.2,1)", fill: "backwards" });
    }), { rootMargin: "0px 0px -8% 0px" });
    const watch = () => document.querySelectorAll(".s2h-reveal, .s2h-stat .num[data-count]").forEach((el) => {
      if (el.dataset.s2hSeen) return; el.dataset.s2hSeen = "1";
      if (el.dataset.count || el.getBoundingClientRect().top > innerHeight) io.observe(el);
    });
    watch(); const t = setTimeout(watch, 1500);
    return () => { io.disconnect(); clearTimeout(t); removeEventListener("scroll", onScroll); };
  }, []);
}

const HomeS02 = () => {
  const { events } = useAgenda();
  const visuels = useVisuels();
  const today = agToday();
  const next = (events || []).filter((e) => !e.rec && (e.fin || e.date) >= today).sort((a, b) => a.date - b.date).slice(0, 3)
    .map((e) => ({ e, v: agVisuel(e, visuels) || {} }));
  useS2hMotion();
  return (
    <div className="page s2h">
      <HeaderPublic active="Accueil" tickerExtra={s2hTickerExtra(next[0])} />
      <S2hHero />
      <S2hSorties />
      <S2hRounds next={next} />
      <S2hT2T />
      <S2hDirections />
      <S2hJoin />
      <PartnersBand />
      <FooterPublic />
    </div>
  );
};

window.HomeS02 = HomeS02;
window.S2hRounds = S2hRounds;
