/* Good Time Espresso — Shop, Product, Story views (L'OR luxe) */

function ShopView({ onNav, addToCart }) {
  const [family, setFamily] = useState("Tout");
  const [sort, setSort] = useState("Pertinence");

  const families = ["Tout", "Capsules", "Dosettes", "Grains"];

  const filtered = useMemo(() => {
    let r = PRODUCTS.slice();
    if (family !== "Tout") r = r.filter(p => p.family === family);
    if (sort === "Prix ↑") r.sort((a, b) => a.price - b.price);
    if (sort === "Prix ↓") r.sort((a, b) => b.price - a.price);
    if (sort === "Note") r.sort((a, b) => b.rating - a.rating);
    return r;
  }, [family, sort]);

  const activeChip = { background: "var(--gold)", color: "var(--on-gold)", borderColor: "var(--gold)" };

  return (
    <div className="fade-up">
      {/* Header */}
      <section style={{ padding: "64px 0 40px", borderBottom: "1px solid var(--line)" }}>
        <div className="container">
          <div className="row gap-3" style={{ marginBottom: 24 }}>
            <span className="tracked" style={{ fontSize: 10, color: "var(--muted)" }}>Accueil</span>
            <span className="tracked" style={{ fontSize: 10, color: "var(--muted)" }}>/</span>
            <span className="tracked" style={{ fontSize: 10, color: "var(--gold)" }}>Boutique</span>
          </div>
          <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-end" }}>
            <h1 className="display" style={{ fontSize: "clamp(56px, 8vw, 120px)", margin: 0 }}>
              La <span className="display-italic" style={{ color: "var(--gold)" }}>collection</span>.
            </h1>
            <div className="col" style={{ alignItems: "flex-end", gap: 4 }}>
              <span className="tracked" style={{ fontSize: 10, color: "var(--muted)" }}>{filtered.length} références</span>
              <span style={{ fontSize: 13, color: "var(--text-dim)" }}>Morandini Caffè · 50% Arabica</span>
            </div>
          </div>
        </div>
      </section>

      {/* Filters bar */}
      <section style={{ position: "sticky", top: 164, zIndex: 20, background: "color-mix(in srgb, var(--bg) 92%, transparent)", backdropFilter: "blur(8px)", borderBottom: "1px solid var(--line)" }}>
        <div className="container row" style={{ justifyContent: "space-between", height: 64 }}>
          <div className="row gap-2">
            <span className="eyebrow" style={{ marginRight: 8 }}>Famille</span>
            {families.map(f => (
              <button key={f} onClick={() => setFamily(f)} className="chip" style={family === f ? activeChip : {}}>{f}</button>
            ))}
          </div>
          <div className="row gap-2">
            <span className="eyebrow" style={{ marginRight: 8 }}>Trier</span>
            <select value={sort} onChange={e => setSort(e.target.value)} className="chip" style={{ height: 28, paddingRight: 22, cursor: "pointer" }}>
              {["Pertinence", "Prix ↑", "Prix ↓", "Note"].map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
        </div>
      </section>

      {/* Grid */}
      <section style={{ padding: "48px 0 80px" }}>
        <div className="container" style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 48 }}>
          <aside className="col gap-6" style={{ paddingTop: 8 }}>
            <FilterGroup title="Format">
              {["Capsules", "Dosettes ESE", "Café en grains"].map(n => (
                <label key={n} className="row gap-2" style={{ cursor: "pointer", padding: "6px 0" }}>
                  <input type="checkbox" style={{ accentColor: "var(--gold)" }}/>
                  <span style={{ fontSize: 13, color: "var(--text-dim)" }}>{n}</span>
                </label>
              ))}
            </FilterGroup>
            <FilterGroup title="Profil aromatique">
              {["Cacao", "Fruits secs", "Noisette", "Crema dense", "Rond & doux"].map(n => (
                <label key={n} className="row gap-2" style={{ cursor: "pointer", padding: "6px 0" }}>
                  <input type="checkbox" style={{ accentColor: "var(--gold)" }}/>
                  <span style={{ fontSize: 13, color: "var(--text-dim)" }}>{n}</span>
                </label>
              ))}
            </FilterGroup>
            <FilterGroup title="Assemblage">
              {["50% Arabica", "Compostable", "Torréfié en Italie"].map(n => (
                <label key={n} className="row gap-2" style={{ cursor: "pointer", padding: "6px 0" }}>
                  <input type="checkbox" style={{ accentColor: "var(--gold)" }}/>
                  <span style={{ fontSize: 13, color: "var(--text-dim)" }}>{n}</span>
                </label>
              ))}
            </FilterGroup>
            <FilterGroup title="Compatibilité">
              {["Nespresso®*", "Machine à dosettes ESE", "Machine à grains"].map(n => (
                <label key={n} className="row gap-2" style={{ cursor: "pointer", padding: "6px 0" }}>
                  <input type="checkbox" style={{ accentColor: "var(--gold)" }}/>
                  <span style={{ fontSize: 13, color: "var(--text-dim)" }}>{n}</span>
                </label>
              ))}
            </FilterGroup>
          </aside>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
            {filtered.map(p => <ProductCard key={p.id} p={p} onNav={onNav} addToCart={addToCart}/>)}
          </div>
        </div>
      </section>
    </div>
  );
}

function FilterGroup({ title, children }) {
  return (
    <div>
      <div className="tracked" style={{ fontSize: 10, color: "var(--text)", marginBottom: 14, paddingBottom: 10, borderBottom: "1px solid var(--line-strong)" }}>{title}</div>
      <div>{children}</div>
    </div>
  );
}

/* ---------- Product detail ---------- */
function ProductView({ onNav, addToCart, productId }) {
  const p = PRODUCTS.find(x => x.id === productId) || PRODUCTS[0];
  const [format, setFormat] = useState("Espresso");
  const [qty, setQty] = useState(1);
  const [tab, setTab] = useState("Arômes");
  const gallery = [
    { cls: p.img, pack: true },
    ...(p.id === "p10" ? [{ cls: "img-dosetteopen", pack: true }] : []),
    { cls: p.family === "Grains" ? "img-arabica90" : "img-arabica", pack: true },
  ];
  const [active, setActive] = useState(0);

  return (
    <div className="fade-up">
      <section style={{ padding: "32px 0" }}>
        <div className="container">
          <div className="row gap-3" style={{ marginBottom: 32 }}>
            {[p.family, p.line, p.name].map((b, i, a) => (
              <React.Fragment key={b}>
                <span className="tracked" style={{ fontSize: 10, color: i === a.length - 1 ? "var(--gold)" : "var(--muted)" }}>{b}</span>
                {i < a.length - 1 && <span className="tracked" style={{ fontSize: 10, color: "var(--muted)" }}>/</span>}
              </React.Fragment>
            ))}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1.05fr 1fr", gap: 64, alignItems: "flex-start" }}>
            {/* Gallery */}
            <div className="col gap-3">
              <div className={`${gallery[active].pack ? "pack" : "photo"} ${gallery[active].cls}`} style={{ aspectRatio: "4/5", position: "relative" }}>
                <div style={{ position: "absolute", top: 18, left: 22, display: "flex", gap: 8, zIndex: 2 }}>
                  <span className="chip solid">{p.arabica}% Arabica</span>
                  {p.family === "Capsules" && <span className="chip" style={{ background: "rgba(11,11,12,0.7)", borderColor: "transparent", color: "var(--text)" }}>Compostable</span>}
                </div>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
                {gallery.map((g, i) => (
                  <button key={i} onClick={() => setActive(i)} className={`${g.pack ? "pack" : "photo"} ${g.cls}`}
                    style={{ aspectRatio: "1/1", padding: 0, outline: active === i ? "1px solid var(--gold)" : "1px solid var(--line)", outlineOffset: -1 }}/>
                ))}
              </div>
            </div>

            {/* Info */}
            <div style={{ position: "sticky", top: 200 }}>
              <div className="tracked" style={{ fontSize: 10, color: "var(--muted)", marginBottom: 14 }}>{p.origin}</div>
              <h1 className="display" style={{ fontSize: "clamp(48px, 6vw, 84px)", margin: "0 0 8px", lineHeight: 0.96 }}>
                {p.line}<br/>
                <span className="display-italic" style={{ color: "var(--gold)" }}>{p.family}</span>
              </h1>

              <div className="row gap-4" style={{ marginTop: 20, paddingBottom: 20, borderBottom: "1px solid var(--line)" }}>
                <div className="row gap-1" style={{ color: "var(--gold)" }}>
                  {[1,2,3,4,5].map(i => <Icon.Star key={i} style={{ opacity: i <= Math.round(p.rating) ? 1 : 0.25 }}/>)}
                </div>
                <span className="mono" style={{ fontSize: 12 }}>{p.rating}</span>
                <span className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>· 142 avis</span>
                <span style={{ flex: 1 }}/>
                <span className="chip">{p.arabica}% Arabica</span>
              </div>

              <p style={{ fontSize: 15, lineHeight: 1.7, color: "var(--text-dim)", margin: "24px 0", textWrap: "pretty" }}>
                La Miscela Crema de Morandini Caffè — un assemblage 50% Arabica
                / 50% Robusta torréfié en Italie. Espresso rond et gourmand,
                notes de cacao et de fruits secs, coiffé d'une crema dense et
                persistante.
              </p>

              {/* Tasting wheel */}
              <div className="card" style={{ padding: 20, marginBottom: 32 }}>
                <div className="tracked" style={{ fontSize: 9.5, color: "var(--gold)", marginBottom: 16 }}>Profil de tasse</div>
                {[["Corps", 4], ["Crema", 5], ["Amertume", 3], ["Acidité", 2]].map(([k, v]) => (
                  <div key={k} className="row" style={{ marginBottom: 12, gap: 16 }}>
                    <span style={{ fontSize: 13, width: 90, color: "var(--text-dim)" }}>{k}</span>
                    <div style={{ flex: 1, height: 3, background: "var(--line)", position: "relative" }}>
                      <div style={{ width: `${v * 20}%`, height: "100%", background: "var(--gold)" }}/>
                    </div>
                    <span className="mono" style={{ fontSize: 11, color: "var(--muted)", width: 24, textAlign: "right" }}>{v}/5</span>
                  </div>
                ))}
              </div>

              {/* Format selector */}
              <div className="tracked" style={{ fontSize: 9.5, color: "var(--text)", marginBottom: 12 }}>Préparation conseillée</div>
              <div className="row gap-2" style={{ marginBottom: 28, flexWrap: "wrap" }}>
                {["Ristretto", "Espresso", "Lungo"].map(g => (
                  <button key={g} onClick={() => setFormat(g)} className="chip"
                    style={format === g ? { background: "var(--gold)", color: "var(--on-gold)", borderColor: "var(--gold)" } : {}}>{g}</button>
                ))}
              </div>

              {/* Price + qty */}
              <div className="row" style={{ alignItems: "flex-end", justifyContent: "space-between", marginBottom: 20, paddingBottom: 24, borderBottom: "1px solid var(--line)" }}>
                <div>
                  <div className="tracked" style={{ fontSize: 9.5, color: "var(--muted)", marginBottom: 6 }}>{p.weight}</div>
                  <div className="display" style={{ fontSize: 44, lineHeight: 1, color: "var(--gold)" }}>{fmt(p.price)}</div>
                </div>
                <div className="row" style={{ border: "1px solid var(--line-strong)", height: 46 }}>
                  <button onClick={() => setQty(Math.max(1, qty - 1))} style={{ width: 42, height: "100%" }}><Icon.Minus/></button>
                  <div style={{ width: 42, textAlign: "center", fontFamily: "var(--font-mono)", fontSize: 14 }}>{qty}</div>
                  <button onClick={() => setQty(qty + 1)} style={{ width: 42, height: "100%" }}><Icon.Plus/></button>
                </div>
              </div>

              <div className="row gap-2" style={{ marginBottom: 20 }}>
                <button onClick={() => addToCart(p, qty)} className="btn btn-primary" style={{ flex: 1, height: 54 }}>
                  Ajouter · {fmt(p.price * qty)}
                </button>
                <button className="btn btn-ghost" style={{ width: 54, height: 54 }}><Icon.Heart/></button>
              </div>

              <div className="row gap-3" style={{ flexWrap: "wrap", fontSize: 12, color: "var(--muted)" }}>
                <span>100 % compostable</span><span>·</span>
                <span>Compatible Nespresso®*</span><span>·</span>
                <span>Livraison dès 30 €</span>
              </div>

              {/* Tabs */}
              <div style={{ marginTop: 40, borderTop: "1px solid var(--line)", paddingTop: 24 }}>
                <div className="row gap-5" style={{ marginBottom: 18 }}>
                  {["Arômes", "Composition", "Compatibilité"].map(t => (
                    <button key={t} onClick={() => setTab(t)} className="tracked"
                      style={{ fontSize: 10, paddingBottom: 8, color: tab === t ? "var(--gold)" : "var(--muted)", borderBottom: tab === t ? "1px solid var(--gold)" : "1px solid transparent" }}>{t}</button>
                  ))}
                </div>
                {tab === "Arômes" && (
                  <div className="row gap-2" style={{ flexWrap: "wrap" }}>
                    {["Cacao", "Fruits secs", "Noisette", "Rond", "Crema dense"].map(n => <span key={n} className="chip">{n}</span>)}
                  </div>
                )}
                {tab === "Composition" && (
                  <p style={{ fontSize: 14, lineHeight: 1.7, color: "var(--text-dim)", margin: 0 }}>
                    Assemblage 50% Arabica / 50% Robusta, torréfié en Italie.
                    {p.family === "Capsules" ? " Capsule 100 % compostable, environ 5,2 g de café moulu." : p.family === "Dosettes" ? " Dosette ESE 44mm en papier filtre, 7 g de café moulu." : " Café en grains torréfié, à moudre selon votre machine."}
                  </p>
                )}
                {tab === "Compatibilité" && (
                  <p style={{ fontSize: 14, lineHeight: 1.7, color: "var(--text-dim)", margin: 0 }}>
                    {p.family === "Capsules" ? "Compatible avec la plupart des machines Nespresso®* Original (hors modèles spécifiques)." : p.family === "Dosettes" ? "Compatible avec les machines à dosettes ESE 44mm." : "Pour machines à café en grains et moulins à café."}
                    <br/><span style={{ fontSize: 11, color: "var(--muted)" }}>*Nespresso® est une marque tierce, sans lien avec Morandini Caffè.</span>
                  </p>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Related */}
      <section style={{ padding: "100px 0 40px" }}>
        <div className="container">
          <h2 className="display" style={{ fontSize: "clamp(32px, 4vw, 56px)", marginBottom: 40 }}>
            Dans le même <span className="display-italic" style={{ color: "var(--gold)" }}>esprit</span>.
          </h2>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
            {PRODUCTS.slice(1, 5).map(p => <ProductCard key={p.id} p={p} onNav={onNav} addToCart={addToCart}/>)}
          </div>
        </div>
      </section>
    </div>
  );
}

/* ---------- Story view ---------- */
function StoryView() {
  return (
    <div className="fade-up">
      <section style={{ padding: "80px 0 40px" }}>
        <div className="container" style={{ maxWidth: 920 }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>— Notre histoire</div>
          <h1 className="display" style={{ fontSize: "clamp(56px, 8vw, 124px)", margin: 0, lineHeight: 0.95 }}>
            Morandini Caffè,<br/>
            <span className="display-italic" style={{ color: "var(--gold)" }}>l'Italie dans</span><br/>
            votre tasse.
          </h1>
        </div>
      </section>
      <section style={{ padding: "40px 0 80px" }}>
        <div className="container" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 64 }}>
          <div className="pack img-grain" style={{ aspectRatio: "4/5" }}/>
          <div style={{ paddingTop: 40 }}>
            <p style={{ fontSize: 18, lineHeight: 1.65, color: "var(--text-dim)", margin: "0 0 24px", textWrap: "pretty" }}>
              Coffee For You sélectionne pour vous la gamme Morandini Caffè,
              torréfaction italienne. Au cœur de la maison : la Miscela Crema,
              un assemblage 50% Arabica / 50% Robusta.
            </p>
            <p style={{ fontSize: 15, lineHeight: 1.75, color: "var(--text-dim)", textWrap: "pretty" }}>
              La douceur de l'Arabica, le corps du Robusta, une crema dense et
              persistante. Déclinée en capsules compostables, dosettes ESE et
              café en grains — le même caractère, trois façons de le savourer.
            </p>
            <div className="row gap-6" style={{ marginTop: 40, paddingTop: 28, borderTop: "1px solid var(--line)" }}>
              {[["50%", "Arabica"], ["3", "formats"], ["2018", "depuis"]].map(([k, v]) => (
                <div key={k}>
                  <div className="display" style={{ fontSize: 36, color: "var(--gold)" }}>{k}</div>
                  <div className="tracked" style={{ fontSize: 9.5, color: "var(--muted)", marginTop: 4 }}>{v}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { ShopView, ProductView, StoryView, FilterGroup });
