// PAGE « ZONE » — portrait d'un secteur du jardin d'Opio. Index (#/zone) : les
// zones peuplées ; détail (#/zone/<slug>) : ce qui pousse ici et ce qui s'y
// passe ce mois-ci. Cible des QR posés à l'entrée des secteurs.
// Logique pure : components/zone.js. Cartes réutilisées : CatCard, DANGER_META
// (Catalogue.jsx). Patron de page : Sol.jsx.
(function () {
  function Zone({ zoneSlug, setRoute, setPlantId, visite }) {
    const isMobile = useMobile();
    const pad = isMobile ? "0 20px" : "0 40px";
    const plantsRev = window.PLANTS_REV;
    const plants = window.PLANTS || [];
    const moisIdx = new Date().getMonth();
    const moisNom = window.MOIS_FR[moisIdx];
    const zoneNom = React.useMemo(() => window.zoneDepuisSlug(window.ZONES, zoneSlug), [zoneSlug]);
    const index = React.useMemo(() => window.indexZones(plants, window.ZONES), [plantsRev]);
    const portrait = React.useMemo(() => (zoneNom ? window.portraitZone(plants, zoneNom, moisIdx) : null), [zoneNom, moisIdx, plantsRev]);

    const goFiche = (id) => { setPlantId(id); setRoute("fiche"); };
    const goZone = (slug) => { location.hash = window.buildHash("zone", slug ? { zone: slug } : {}); };
    const goCatalogue = () => { location.hash = window.buildHash("catalogue", { jardin: zoneNom }); };

    // — DÉTAIL : portrait d'une zone —
    if (zoneSlug) {
      const rienCeMois = portrait && !portrait.enFleur.length && !portrait.aRecolter.length && !portrait.taille.length && !portrait.plantation.length;
      return (
        <main className="page-enter">
          <section style={{ padding: isMobile ? "44px 0 20px" : "80px 0 32px" }}>
            <div style={{ maxWidth: 1400, margin: "0 auto", padding: pad }}>
              {/* En mode visite, les sorties vers le reste de l'herbier (index des
                  zones, panier du mois, catalogue) sont masquées : elles ne
                  mèneraient qu'à l'écran « réservé aux membres ». */}
              {!visite && (
              <button onClick={() => goZone("")} style={{ background: "none", border: "none", cursor: "pointer", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--ink-mute)", padding: 0, marginBottom: 18 }}>
                ← Toutes les zones
              </button>
              )}
              <div className="kicker" style={{ marginBottom: 16 }}>Le jardin d'Opio · zone</div>
              {zoneNom ? (
                <React.Fragment>
                  <h1 className="h-display" style={{ fontSize: isMobile ? "clamp(34px,8vw,58px)" : "clamp(52px,7vw,88px)", lineHeight: 0.98, margin: isMobile ? "0 0 14px" : "0 0 18px", letterSpacing: "-0.02em" }}>
                    {zoneNom}<span className="h-italic">.</span>
                  </h1>
                  <div style={{ fontFamily: "var(--mono)", fontSize: 12, letterSpacing: ".16em", textTransform: "uppercase", color: "var(--moss-deep)" }}>
                    {portrait.especes.length} espèce{portrait.especes.length > 1 ? "s" : ""}
                    {portrait.arbres > 0 && <> · dont {portrait.arbres} arbre{portrait.arbres > 1 ? "s" : ""}</>}
                  </div>
                </React.Fragment>
              ) : (
                <h1 className="h-display" style={{ fontSize: isMobile ? 34 : 52, lineHeight: 1, margin: 0 }}>
                  Zone <span className="h-italic">inconnue</span>.
                </h1>
              )}
            </div>
          </section>

          {zoneNom && (
            <section style={{ maxWidth: 1400, margin: "8px auto 0", padding: pad }}>
              {/* En ce moment — la raison d'être de la page pour qui est sur place. */}
              <div style={{ border: "1px solid var(--line)", background: "var(--tint)", padding: isMobile ? "16px 18px" : "22px 28px", display: "flex", flexDirection: "column", gap: 8 }}>
                <div className="kicker">En ce moment · {moisNom}</div>
                {rienCeMois ? (
                  <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 16, color: "var(--ink-mute)", margin: 0 }}>
                    Rien de documenté ce mois-ci dans cette zone.
                  </p>
                ) : (
                  <React.Fragment>
                    <ZoneLigne label="En fleur" plants={portrait.enFleur} color="var(--moss-deep)" onOpen={goFiche} />
                    <ZoneLigne label="À récolter" plants={portrait.aRecolter} color="var(--rust)" onOpen={goFiche} />
                    <ZoneLigne label="À tailler" plants={portrait.taille} color="#5b7fb0" onOpen={goFiche} />
                    <ZoneLigne label="À planter" plants={portrait.plantation} color="#8a6f3e" onOpen={goFiche} />
                  </React.Fragment>
                )}
                {!visite && portrait.aRecolter.length > 0 && (
                  <button onClick={() => { location.hash = window.buildHash("cueillette"); }}
                    style={{ alignSelf: "flex-start", background: "none", border: "none", padding: 0, marginTop: 2, cursor: "pointer", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: ".16em", textTransform: "uppercase", color: "var(--rust)" }}>
                    Ouvrir le panier du mois →
                  </button>
                )}
              </div>

              {/* Avant de cueillir — les sosies dangereux présents dans la zone. */}
              {portrait.dangers.length > 0 && (
                <div style={{ marginTop: 28, border: "1px solid rgba(139,74,43,0.35)", padding: isMobile ? "16px 18px" : "20px 28px" }}>
                  <div className="kicker" style={{ color: "var(--rust)", marginBottom: 10 }}>Avant de cueillir</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {portrait.dangers.map((p) => {
                      const meta = DANGER_META[p.danger];
                      return (
                        <button key={p.id} onClick={() => goFiche(p.id)}
                          style={{ display: "flex", alignItems: "center", gap: 12, background: "none", border: "none", padding: 0, cursor: "pointer", textAlign: "left" }}>
                          <span style={{ fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: ".12em", textTransform: "uppercase", padding: "4px 9px", borderRadius: 100, background: meta.bg, color: meta.fg, border: meta.border, flexShrink: 0 }}>
                            ⚠ {meta.label}
                          </span>
                          <span style={{ fontFamily: "var(--serif)", fontSize: 16, color: "var(--ink)" }}>{p.nom}</span>
                          {!isMobile && <span className="h-italic" style={{ fontSize: 14, color: "var(--moss-deep)" }}>{p.latin}</span>}
                        </button>
                      );
                    })}
                  </div>
                  <p style={{ fontFamily: "var(--serif)", fontSize: 14, color: "var(--ink-soft)", margin: "12px 0 0" }}>
                    Chaque fiche détaille le sosie et comment l'en distinguer.
                  </p>
                </div>
              )}

              {!visite && (
              <div style={{ display: "flex", gap: 22, flexWrap: "wrap", marginTop: 28 }}>
                <button onClick={goCatalogue} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--moss-deep)" }}>
                  Voir au catalogue avec les filtres →
                </button>
              </div>
              )}
            </section>
          )}

          <section style={{ maxWidth: 1400, margin: "36px auto 0", padding: pad, paddingBottom: isMobile ? 64 : 100 }}>
            {zoneNom ? (
              <React.Fragment>
                <div className="kicker" style={{ marginBottom: 16 }}>Toutes les espèces de la zone</div>
                <div style={{ display: "grid", gridTemplateColumns: isMobile ? "repeat(2, 1fr)" : "repeat(4, 1fr)", gap: isMobile ? 12 : 20 }}>
                  {portrait.especes.map((p, i) => (
                    <CatCard key={p.id} p={p} idx={i + 1} onClick={() => goFiche(p.id)} isMobile={isMobile} />
                  ))}
                </div>
              </React.Fragment>
            ) : (
              <p style={{ fontFamily: "var(--serif)", fontSize: 18, fontStyle: "italic", color: "var(--ink-mute)" }}>
                Cette zone n'existe pas dans le jardin — ou son lien a expiré.
              </p>
            )}
          </section>
        </main>
      );
    }

    // — INDEX : les zones du jardin —
    return (
      <main className="page-enter">
        <section style={{ padding: isMobile ? "44px 0 8px" : "80px 0 24px" }}>
          <div style={{ maxWidth: 1400, margin: "0 auto", padding: pad }}>
            <div className="kicker" style={{ marginBottom: 18 }}>Le jardin d'Opio · zones</div>
            <h1 className="h-display" style={{ fontSize: isMobile ? "clamp(38px,9vw,60px)" : "clamp(56px,7vw,92px)", lineHeight: 0.98, margin: isMobile ? "0 0 16px" : "0 0 20px", letterSpacing: "-0.02em" }}>
              Où <span className="h-italic">êtes-vous</span> ?
            </h1>
            <p style={{ fontFamily: "var(--serif)", fontSize: isMobile ? 17 : 20, lineHeight: 1.5, color: "var(--ink-soft)", maxWidth: 640 }}>
              Chaque secteur du jardin a son portrait : les espèces qui y poussent, ce qui
              fleurit et se récolte ce mois-ci, les arbres à tailler ou à planter, et les
              sosies à connaître avant de cueillir.
            </p>
          </div>
        </section>
        <section style={{ maxWidth: 900, margin: "8px auto 0", padding: pad, paddingBottom: isMobile ? 64 : 100 }}>
          <div style={{ borderTop: "1px solid var(--line)" }}>
            {index.map((z) => (
              <button key={z.slug} onClick={() => goZone(z.slug)}
                style={{ display: "flex", width: "100%", textAlign: "left", alignItems: "baseline", gap: 16, padding: isMobile ? "18px 4px" : "22px 6px", background: "none", border: "none", borderBottom: "1px solid var(--line)", cursor: "pointer" }}>
                <span className="h-display" style={{ fontSize: isMobile ? 22 : 28, flex: 1 }}>{z.nom}</span>
                {z.arbres > 0 && !isMobile && (
                  <span style={{ fontFamily: "var(--serif)", fontSize: 15, color: "var(--ink-soft)" }}>{z.arbres} arbre{z.arbres > 1 ? "s" : ""}</span>
                )}
                <span style={{ fontFamily: "var(--mono)", fontSize: 12, letterSpacing: ".14em", color: "var(--moss-deep)", flexShrink: 0 }}>{z.count} →</span>
              </button>
            ))}
          </div>
        </section>
      </main>
    );
  }

  // Une ligne « EN FLEUR — Lavande, Sauge… et N autres » (patron SeasonLine du
  // catalogue, non exporté). Plafond de 8 noms ; le reste en compteur.
  function ZoneLigne({ label, plants, color, onOpen }) {
    if (!plants.length) return null;
    const shown = plants.slice(0, 8);
    const rest = plants.length - shown.length;
    return (
      <div style={{ fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.7, color: "var(--ink-soft)" }}>
        <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: ".14em", textTransform: "uppercase", color }}>{label}</span>
        {" — "}
        {shown.map((p, i) => (
          <React.Fragment key={p.id}>
            {i > 0 && ", "}
            <button onClick={() => onOpen(p.id)} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", font: "inherit", color: "var(--ink)" }}>{p.nom}</button>
          </React.Fragment>
        ))}
        {rest > 0 && <span> et {rest} autre{rest > 1 ? "s" : ""}</span>}
      </div>
    );
  }

  window.Zone = Zone;
})();
