// FAMILLES — pages pédagogiques de reconnaissance des familles botaniques.
// Source du contenu : window.FAMILLES_INFO (components/familles.js).
// Rattachement des plantes : AUTOMATIQUE via le champ `famille` des fiches.
// Réutilise CatCard (Catalogue) et Reveal (shared).
//
// Deux états : liste des familles (cartes) → détail (signature + grille plantes).

function Familles({ setRoute, setPlantId }) {
  const isMobile = useMobile();
  const [slug, setSlug] = React.useState(null);
  const familles = window.FAMILLES_INFO || [];

  const goFiche = (id) => { setPlantId(id); setRoute("fiche"); };
  const pad = isMobile ? "0 20px" : "0 40px";

  // Plantes du recueil appartenant à une famille (match exact sur `famille`).
  const plantsOf = (fam) =>
    (window.PLANTS || []).filter((p) => p.famille === fam.nom);

  const current = slug ? familles.find((f) => f.slug === slug) : null;

  // ── Vue détail d'une famille ──
  if (current) {
    const plants = plantsOf(current);
    return (
      <main className="page-enter">
        <section style={{ padding: isMobile ? "36px 0 24px" : "70px 0 32px" }}>
          <div style={{ maxWidth: 1100, margin: "0 auto", padding: pad }}>
            <button onClick={() => setSlug(null)} style={{
              fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".12em", textTransform: "uppercase",
              color: "var(--ink-mute)", background: "none", border: "none", cursor: "pointer", padding: 0, marginBottom: 24,
            }}>← Toutes les familles</button>
            <div className="kicker" style={{ marginBottom: 16 }}>
              Famille botanique{current.sousTitre ? " · " + current.sousTitre : ""}
            </div>
            <h1 className="h-display" style={{ fontSize: isMobile ? "clamp(34px, 8vw, 52px)" : "clamp(48px, 6vw, 80px)", lineHeight: 1.0, margin: "0 0 28px", letterSpacing: "-0.02em" }}>
              {current.nom}
            </h1>

            {/* Blocs signature */}
            <div style={{ display: "grid", gap: isMobile ? 16 : 20, maxWidth: 760 }}>
              <SignatureBlock label="L'attribut clé" color="var(--moss-deep)" text={current.attribut} />
              <SignatureBlock label="La propriété" color="var(--olive)" text={current.propriete} />
              <SignatureBlock label="Le signe de reconnaissance" color="var(--terra)" text={current.signe} />
              {current.cuisine && (
                <SignatureBlock label="En cuisine" color="var(--olive)" text={current.cuisine} />
              )}
            </div>
          </div>
        </section>

        {/* Plantes du recueil dans cette famille */}
        <section style={{ padding: isMobile ? "20px 0 64px" : "32px 0 100px" }}>
          <div style={{ maxWidth: 1400, margin: "0 auto", padding: pad }}>
            <div className="kicker" style={{ marginBottom: 18 }}>
              {plants.length > 0
                ? `${plants.length} plante${plants.length > 1 ? "s" : ""} du recueil`
                : "Aucune fiche pour l'instant"}
            </div>
            {plants.length > 0 ? (
              <div style={{ display: "grid", gridTemplateColumns: isMobile ? "repeat(2, 1fr)" : "repeat(4, 1fr)", gap: isMobile ? 12 : 20 }}>
                {plants.map((p, i) => (
                  <CatCard key={p.id} p={p} idx={i + 1} onClick={() => goFiche(p.id)} isMobile={isMobile} />
                ))}
              </div>
            ) : (
              <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 17, lineHeight: 1.6, color: "var(--ink-mute)", maxWidth: 620 }}>
                Cette famille n'a pas encore de représentante dans le recueil —
                mais ça ne saurait tarder. En attendant, sa signature ci-dessus
                vous aidera déjà à la reconnaître sur le terrain.
              </p>
            )}
          </div>
        </section>
      </main>
    );
  }

  // ── Vue liste des familles ──
  return (
    <main className="page-enter">
      <section style={{ padding: isMobile ? "44px 0 24px" : "80px 0 36px" }}>
        <div style={{ maxWidth: 1400, margin: "0 auto", padding: pad }}>
          <div className="kicker" style={{ marginBottom: 18 }}>Familles botaniques · reconnaître & comprendre</div>
          <h1 className="h-display" style={{ fontSize: isMobile ? "clamp(40px, 9vw, 64px)" : "clamp(60px, 8vw, 100px)", lineHeight: 0.95, margin: isMobile ? "0 0 16px" : "0 0 24px", letterSpacing: "-0.02em" }}>
            L'air <span className="h-italic">de famille</span>.
          </h1>
          {!isMobile && (
            <p style={{ fontFamily: "var(--serif)", fontSize: 22, lineHeight: 1.5, color: "var(--ink-soft)", maxWidth: 760, margin: 0 }}>
              Apprendre à reconnaître les grandes familles, c'est lire la plante avant
              même de connaître son nom : un signe botanique, une molécule
              caractéristique, et déjà l'on devine ses usages. De grappe en grappe,
              il faut se souvenir, voici les clés d'un savoir presque inné.
            </p>
          )}
        </div>
      </section>

      <section style={{ padding: isMobile ? "20px 0 64px" : "32px 0 100px" }}>
        <div style={{ maxWidth: 1400, margin: "0 auto", padding: pad }}>
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(2, 1fr)", gap: isMobile ? 16 : 24 }}>
            {familles.map((fam) => {
              const plants = plantsOf(fam);
              return <FamilleCard key={fam.slug} famille={fam} plants={plants} onClick={() => setSlug(fam.slug)} isMobile={isMobile} />;
            })}
          </div>
        </div>
      </section>
    </main>
  );
}

// Bloc de signature (attribut / propriété / signe) dans la vue détail.
function SignatureBlock({ label, color, text }) {
  return (
    <div style={{ borderLeft: `3px solid ${color}`, paddingLeft: 18 }}>
      <div className="kicker" style={{ marginBottom: 8, color }}>{label}</div>
      <p style={{ fontFamily: "var(--serif)", fontSize: 17, lineHeight: 1.6, color: "var(--ink-soft)", margin: 0 }}>
        {text}
      </p>
    </div>
  );
}

// Carte d'une famille dans la liste : bandeau de vignettes (ou état « à venir »)
// + nom + sous-titre + signe de reconnaissance en accroche.
function FamilleCard({ famille, plants, onClick, isMobile }) {
  const [hover, setHover] = React.useState(false);
  const previews = plants.slice(0, 4);
  const empty = plants.length === 0;
  return (
    <Reveal>
      <article
        onClick={onClick}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{ cursor: "pointer", background: "var(--cream)", border: "1px solid var(--line-soft)", display: "flex", flexDirection: "column", overflow: "hidden" }}
      >
        {/* Bandeau d'aperçu */}
        <div style={{ display: "flex", height: isMobile ? 120 : 150, background: "var(--paper)", borderBottom: "1px solid var(--line-soft)" }}>
          {empty ? (
            <div style={{
              flex: 1, display: "grid", placeItems: "center",
              fontFamily: "var(--mono)", fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase",
              color: "var(--ink-mute)",
              backgroundImage: "repeating-linear-gradient(45deg, transparent 0 9px, rgba(45,67,41,0.05) 9px 10px)",
            }}>
              Famille à venir
            </div>
          ) : (
            previews.map((p, i) => (
              <div key={p.id} style={{ flex: 1, overflow: "hidden", borderRight: i < previews.length - 1 ? "1px solid var(--line-soft)" : "none", position: "relative" }}>
                {p.thumb && (
                  <img src={p.thumb} alt={p.nom} style={{
                    width: "100%", height: "100%", objectFit: "contain", display: "block",
                    transition: "transform 900ms var(--ease)", transform: hover ? "scale(1.05)" : "scale(1)",
                  }} />
                )}
              </div>
            ))
          )}
        </div>
        <div style={{ padding: isMobile ? "16px 18px" : "22px 26px" }}>
          <div className="kicker" style={{ marginBottom: 8 }}>
            {empty ? "À venir" : `${plants.length} plante${plants.length > 1 ? "s" : ""}`}
            {famille.sousTitre ? " · " + famille.sousTitre : ""}
          </div>
          <h3 className="h-display" style={{ fontSize: isMobile ? 23 : 30, lineHeight: 1.05, margin: "0 0 10px", color: hover ? "var(--moss-deep)" : "var(--ink)", transition: "color 300ms var(--ease)" }}>
            {famille.nom}
          </h3>
          <p style={{ fontFamily: "var(--serif)", fontSize: isMobile ? 15 : 16, lineHeight: 1.5, color: "var(--ink-mute)", margin: 0 }}>
            {famille.signe}
          </p>
        </div>
      </article>
    </Reveal>
  );
}

window.Familles = Familles;
