// GRAPPES — pages thématiques regroupant les plantes par affinité d'usage.
// (Nommées « grappes » côté interface ; le slug interne reste « pole ».)
// Source : window.POLES (components/poles.js). Réutilise CatCard pour le détail.
//
// Deux états : liste des grappes (cartes) → détail d'une grappe (description + grille).

// Petit glyphe de grappe (grains + vrille), en écho au nom de la section.
function GrapeGlyph({ size = 30, color = "var(--moss-deep)" }) {
  const grains = [
    [12, 9.2], [9.1, 11.3], [14.9, 11.3],
    [12, 13.4], [10.4, 15.5], [13.6, 15.5], [12, 17.6],
  ];
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true" style={{ display: "block" }}>
      {/* vrille + pédoncule */}
      <path d="M12 9V4.6M12 5.4c1.7-1.3 3.7-1.2 4.6.3" stroke={color} strokeWidth="1.3" strokeLinecap="round" />
      {grains.map(([cx, cy], i) => (
        <circle key={i} cx={cx} cy={cy} r="2.05" fill={color} stroke="var(--paper)" strokeWidth="0.6" />
      ))}
    </svg>
  );
}

function Poles({ setRoute, setPlantId, poleSlug, setPoleSlug }) {
  const isMobile = useMobile();
  // État de sélection levé dans App (poleSlug) : permet d'ouvrir une grappe
  // précise depuis une fiche. null = vue liste ; sinon vue détail.
  const slug = poleSlug || null;
  const setSlug = setPoleSlug;
  const poles = window.POLES || [];

  const goFiche = (id) => { setPlantId(id); setRoute("fiche"); };
  const pad = isMobile ? "0 20px" : "0 40px";

  // Résout les ids d'un pôle en objets plante (ignore les ids inconnus).
  const plantsOf = (pole) =>
    (pole.plantes || []).map((id) => (window.PLANTS || []).find((p) => p.id === id)).filter(Boolean);

  const current = slug ? poles.find((p) => p.slug === slug) : null;

  // ── Vue détail d'un pôle ──
  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 grappes</button>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
              <GrapeGlyph size={26} />
              <span className="kicker">Grappe · {plants.length} plantes</span>
            </div>
            <h1 className="h-display" style={{ fontSize: isMobile ? "clamp(34px, 8vw, 52px)" : "clamp(48px, 6vw, 80px)", lineHeight: 1.0, margin: "0 0 24px", letterSpacing: "-0.02em" }}>
              {current.titre}
            </h1>
            {current.description && (
              <p style={{ fontFamily: "var(--serif)", fontSize: isMobile ? 18 : 22, lineHeight: 1.55, color: "var(--ink-soft)", maxWidth: 720, margin: 0 }}>
                {current.description}
              </p>
            )}
          </div>
        </section>
        <section style={{ padding: isMobile ? "24px 0 64px" : "32px 0 100px" }}>
          <div style={{ maxWidth: 1400, margin: "0 auto", padding: pad }}>
            <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>
          </div>
        </section>
      </main>
    );
  }

  // ── Vue liste des pôles ──
  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 style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
            <GrapeGlyph size={28} />
            <span className="kicker">Grappes · {poles.length} affinités d'usage</span>
          </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" }}>
            Plantes <span className="h-italic">apparentées</span>.
          </h1>
          {!isMobile && (
            <p style={{ fontFamily: "var(--serif)", fontSize: 22, lineHeight: 1.5, color: "var(--ink-soft)", maxWidth: 720, margin: 0 }}>
              Au-delà des familles botaniques, les plantes se rassemblent ici par affinité d'usage, en grappes — comme la vigne porte ses grains. Une même plante peut mûrir dans plusieurs d'entre elles.
            </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 }}>
            {poles.map((pole) => {
              const plants = plantsOf(pole);
              return <PoleCard key={pole.slug} pole={pole} plants={plants} onClick={() => setSlug(pole.slug)} isMobile={isMobile} />;
            })}
          </div>
        </div>
      </section>
    </main>
  );
}

// Carte d'un pôle dans la liste : bandeau de mini-vignettes + titre + description.
function PoleCard({ pole, plants, onClick, isMobile }) {
  const [hover, setHover] = React.useState(false);
  const previews = plants.slice(0, 4);
  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 : mini-vignettes des plantes du pôle */}
        <div style={{ display: "flex", height: isMobile ? 120 : 150, background: "var(--paper)", borderBottom: "1px solid var(--line-soft)" }}>
          {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 }}>{plants.length} plantes</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)" }}>
            {pole.titre}
          </h3>
          {pole.description && (
            <p style={{ fontFamily: "var(--serif)", fontSize: isMobile ? 15 : 16, lineHeight: 1.5, color: "var(--ink-mute)", margin: 0 }}>
              {pole.description}
            </p>
          )}
        </div>
      </article>
    </Reveal>
  );
}

window.Poles = Poles;
