/* global React, useRoute, useCart, useToast, Placeholder, UntitledEmbed, I, CATALOG, CATEGORIES, PRICE_BANDS */
const { useState, useMemo, useEffect } = React;

function Store() {
  const { route, goto } = useRoute();
  const initialCat = route.params?.cat || "all";
  const [cat, setCat] = useState(initialCat);
  const [band, setBand] = useState("any");
  const [sort, setSort] = useState("featured");
  const [view, setView] = useState("grid"); // grid | gallery

  useEffect(() => { if (route.params?.cat) setCat(route.params.cat); }, [route.params?.cat]);

  const items = useMemo(() => {
    let list = CATALOG.filter((p) => cat === "all" || p.cat === cat);
    const pb = PRICE_BANDS.find((b) => b.key === band);
    if (pb?.test) list = list.filter((p) => pb.test(p.price));
    if (sort === "low") list = [...list].sort((a, b) => a.price - b.price);
    if (sort === "high") list = [...list].sort((a, b) => b.price - a.price);
    if (sort === "name") list = [...list].sort((a, b) => a.name.localeCompare(b.name));
    return list;
  }, [cat, band, sort]);

  return (
    <main className="fade">
      {/* Header band */}
      <section style={{ padding: "72px 0 36px", borderBottom: "1px solid var(--border-1)" }}>
        <div className="container">
          <span className="eyebrow eyebrow-gold">§ Store · Vol. III</span>
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 56, alignItems: "end", marginTop: 14 }}>
            <h1 className="serif balance" style={{ fontSize: "clamp(48px, 6.4vw, 96px)", lineHeight: 0.98, margin: 0 }}>
              <em style={{ fontStyle: "italic", color: "var(--gold-soft)" }}>Editions</em>, in small batches.
            </h1>
            <p className="pretty" style={{ color: "var(--text-1)", fontSize: 15.5, maxWidth: 460, justifySelf: "end" }}>
              Apparel, objects, and music made by the studio, produced in numbered runs, restocked rarely.
              Everything ships from the studio within five days.
            </p>
          </div>
        </div>
      </section>

      {/* Filters */}
      <section style={{ position: "sticky", top: "var(--hdr)", zIndex: 20, background: "rgba(10,10,10,0.92)", backdropFilter: "blur(10px)", borderBottom: "1px solid var(--border-1)" }}>
        <div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 32px", gap: 18, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {CATEGORIES.map((c) => (
              <button key={c.key} className="chip" data-active={cat === c.key} onClick={() => setCat(c.key)}>
                {c.label}
              </button>
            ))}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <I name="filter" size={14} stroke="var(--text-3)" />
              <select value={band} onChange={(e) => setBand(e.target.value)}
                style={{ background: "transparent", border: 0, color: "var(--text-1)", font: "500 12px var(--mono)", letterSpacing: "0.06em", textTransform: "uppercase", cursor: "pointer", outline: "none" }}>
                {PRICE_BANDS.map((b) => <option key={b.key} value={b.key} style={{ background: "#111" }}>{b.label}</option>)}
              </select>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <I name="sliders" size={14} stroke="var(--text-3)" />
              <select value={sort} onChange={(e) => setSort(e.target.value)}
                style={{ background: "transparent", border: 0, color: "var(--text-1)", font: "500 12px var(--mono)", letterSpacing: "0.06em", textTransform: "uppercase", cursor: "pointer", outline: "none" }}>
                <option value="featured" style={{ background: "#111" }}>Featured</option>
                <option value="low" style={{ background: "#111" }}>Price · low</option>
                <option value="high" style={{ background: "#111" }}>Price · high</option>
                <option value="name" style={{ background: "#111" }}>A → Z</option>
              </select>
            </div>
            <div style={{ width: 1, height: 18, background: "var(--border)" }} />
            <div style={{ display: "flex", border: "1px solid var(--border)", borderRadius: 999, padding: 2 }}>
              <button onClick={() => setView("grid")} className="icon-btn" style={{ width: 32, height: 28, color: view === "grid" ? "var(--gold)" : "var(--text-2)" }} aria-label="Grid">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><rect x="1" y="1" width="6" height="6" /><rect x="9" y="1" width="6" height="6" /><rect x="1" y="9" width="6" height="6" /><rect x="9" y="9" width="6" height="6" /></svg>
              </button>
              <button onClick={() => setView("gallery")} className="icon-btn" style={{ width: 32, height: 28, color: view === "gallery" ? "var(--gold)" : "var(--text-2)" }} aria-label="Gallery">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><rect x="1" y="1" width="14" height="6" /><rect x="1" y="9" width="6" height="6" /><rect x="9" y="9" width="6" height="6" /></svg>
              </button>
            </div>
          </div>
        </div>
      </section>

      {/* Grid */}
      <section style={{ padding: "48px 0 96px" }}>
        <div className="container">
          <p className="mono" style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-3)", marginBottom: 28 }}>
            {items.length} {items.length === 1 ? "piece" : "pieces"} {cat !== "all" && `· ${cat}`}
          </p>
          {items.length === 0 ? (
            <div style={{ padding: "120px 0", textAlign: "center", color: "var(--text-2)" }}>
              <p className="serif" style={{ fontSize: 24 }}>Nothing matches that filter, yet.</p>
              <button className="btn btn-line" style={{ marginTop: 18 }} onClick={() => { setCat("all"); setBand("any"); }}>Reset filters</button>
            </div>
          ) : (
            <div style={{
              display: "grid",
              gridTemplateColumns: view === "grid" ? "repeat(4, 1fr)" : "1fr 1fr",
              gap: view === "grid" ? 28 : 40,
              rowGap: view === "grid" ? 56 : 64,
            }}>
              {items.map((p, i) => (
                <div key={p.id} className="product" onClick={() => goto("pdp", { id: p.id })} style={{ cursor: "pointer" }}>
                  <div className={`product-art${p.kind === "music" ? " product-art--music" : ""}`} style={p.kind === "music" ? undefined : { aspectRatio: view === "gallery" ? "5/4" : "4/5" }}>
                    {p.cover ? (
                      <Placeholder label={p.name.toLowerCase()} variant={p.imgVariant} code={p.code} src={p.cover} focal={p.focal} fit="cover" />
                    ) : p.video ? (
                      <Placeholder label={p.name.toLowerCase()} variant={p.imgVariant} code={p.code} video={p.video} poster={p.poster} focal={p.focal} />
                    ) : (
                      <Placeholder label={p.name.toLowerCase()} variant={p.imgVariant} code={p.code} />
                    )}
                    <div style={{ position: "absolute", top: 12, left: 12 }}>
                      <span className="num" style={{ background: "rgba(0,0,0,0.55)", padding: "4px 6px", borderRadius: 3 }}>No. {String(i + 1).padStart(2, "0")}</span>
                    </div>
                    {p.badge && (
                      <div style={{ position: "absolute", top: 12, right: 12 }}>
                        <span className="num" style={{ background: "var(--gold)", color: "#000", padding: "4px 8px", borderRadius: 3, fontWeight: 600 }}>{p.badge}</span>
                      </div>
                    )}
                  </div>
                  <div>
                    <div className="product-cat">{p.cat} · {p.subtitle}</div>
                    <div className="product-meta">
                      <span className="product-name">{p.name}</span>
                      <span className="product-price">${p.price}</span>
                    </div>
                    {p.kind === "music" && p.untitledId && (
                      <a
                        href={`https://untitled.stream/embed/${p.untitledId}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={(e) => e.stopPropagation()}
                        className="lk"
                        style={{ fontSize: 12, marginTop: 8, display: "inline-flex", alignItems: "center", gap: 6 }}
                      >
                        Open on Untitled <I name="ext" size={11} />
                      </a>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    </main>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Product detail page
   ───────────────────────────────────────────────────────────────── */
function PDP() {
  const { route, goto } = useRoute();
  const { add, setOpen } = useCart();
  const toast = useToast();
  const id = route.params?.id;
  const product = CATALOG.find((p) => p.id === id) || CATALOG[0];

  const [variant, setVariant] = useState(product.variants[0]);
  const [qty, setQty] = useState(1);
  const [activeImg, setActiveImg] = useState(0);
  useEffect(() => { setVariant(product.variants[0]); setQty(1); setActiveImg(0); }, [product.id]);

  const related = CATALOG.filter((p) => p.id !== product.id && p.cat === product.cat).slice(0, 3);
  const imgs = [
    { code: product.code, label: product.name.toLowerCase(), v: product.imgVariant },
    { code: product.code + "-A", label: "detail · weave", v: "deep" },
    { code: product.code + "-B", label: "on figure", v: "warm" },
    { code: product.code + "-C", label: "back · lay-flat", v: "cool" },
  ];

  return (
    <main className="fade">
      {/* Breadcrumb */}
      <div style={{ borderBottom: "1px solid var(--border-1)" }}>
        <div className="container" style={{ padding: "16px 32px", display: "flex", gap: 8, fontSize: 12, color: "var(--text-3)" }}>
          <a className="lk" onClick={() => goto("home")} style={{ cursor: "pointer", fontSize: 12 }}>Home</a>
          <span>/</span>
          <a className="lk" onClick={() => goto("store")} style={{ cursor: "pointer", fontSize: 12 }}>Store</a>
          <span>/</span>
          <a className="lk" onClick={() => goto("store", { cat: product.cat })} style={{ cursor: "pointer", fontSize: 12, textTransform: "capitalize" }}>{product.cat}</a>
          <span>/</span>
          <span style={{ color: "var(--text-1)" }}>{product.name}</span>
        </div>
      </div>

      <section style={{ padding: "48px 0 80px" }}>
        <div className="container">
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 64, alignItems: "start" }}>
            {/* PRIMARY MEDIA, cover/video on top, Untitled embed below if music */}
            <div>
              {product.kind === "music" && product.cover ? (
                <>
                  <Placeholder label={product.name.toLowerCase()} variant={product.imgVariant} code={product.code} src={product.cover}
                    style={{ aspectRatio: "1/1", width: "100%" }} />
                  {product.untitledId && (
                    <div style={{ marginTop: 16 }}>
                      <UntitledEmbed id={product.untitledId} height={344} radius={12} />
                      <a className="lk" href={`https://untitled.stream/embed/${product.untitledId}`} target="_blank" rel="noopener noreferrer"
                         style={{ fontSize: 12, marginTop: 12, display: "inline-flex", alignItems: "center", gap: 6 }}>
                        Open on Untitled <I name="ext" size={11} />
                      </a>
                    </div>
                  )}
                </>
              ) : product.video ? (
                <Placeholder label={product.name.toLowerCase()} variant={product.imgVariant} code={product.code}
                  video={product.video} poster={product.poster} style={{ aspectRatio: "4/5", width: "100%" }} />
              ) : (
                <>
                  <Placeholder label={imgs[activeImg].label} variant={imgs[activeImg].v} code={imgs[activeImg].code}
                    style={{ aspectRatio: "4/5", width: "100%" }} />
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginTop: 12 }}>
                    {imgs.map((img, i) => (
                      <button key={i} onClick={() => setActiveImg(i)}
                        style={{ aspectRatio: "1/1", padding: 0, border: 0, background: "transparent", cursor: "pointer", outline: i === activeImg ? "1px solid var(--gold)" : "1px solid transparent", outlineOffset: 2 }}>
                        <Placeholder label="" variant={img.v} style={{ width: "100%", height: "100%" }} />
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>

            {/* INFO */}
            <div style={{ position: "sticky", top: "calc(var(--hdr) + 24px)" }}>
              <span className="eyebrow eyebrow-gold">{product.cat} · {product.code}</span>
              <h1 className="serif balance" style={{ fontSize: "clamp(36px, 4vw, 52px)", lineHeight: 1.02, margin: "12px 0 6px" }}>
                {product.name}
              </h1>
              <p style={{ color: "var(--text-2)", margin: "0 0 24px", fontSize: 14 }}>{product.subtitle}</p>
              <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 28 }}>
                <span className="serif" style={{ fontSize: 32 }}>${product.price}</span>
                <span className="mono" style={{ fontSize: 11, color: "var(--text-3)", letterSpacing: "0.1em" }}>USD · ships within US</span>
              </div>

              <div style={{ marginBottom: 24 }}>
                <div className="label">Variant</div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {product.variants.map((v) => (
                    <button key={v} onClick={() => setVariant(v)}
                      className="chip"
                      data-active={v === variant}
                      style={{ height: 38, padding: "0 16px", fontSize: 12 }}>
                      {v}
                    </button>
                  ))}
                </div>
              </div>

              <div style={{ marginBottom: 28 }}>
                <div className="label">Quantity</div>
                <div style={{ display: "flex", alignItems: "center", gap: 0, border: "1px solid var(--border)", borderRadius: 999, width: "fit-content" }}>
                  <button className="icon-btn" onClick={() => setQty(Math.max(1, qty - 1))}><I name="minus" size={14} /></button>
                  <span className="mono" style={{ minWidth: 36, textAlign: "center", fontSize: 13 }}>{qty}</span>
                  <button className="icon-btn" onClick={() => setQty(qty + 1)}><I name="plus" size={14} /></button>
                </div>
              </div>

              <div style={{ display: "flex", gap: 10, marginBottom: 32 }}>
                <button className="btn btn-gold btn-lg" style={{ flex: 1 }}
                  onClick={() => {
                    add({ id: product.id, name: product.name, variant, price: product.price, qty, kind: product.kind });
                    toast(`Added ${product.name} · ${variant}`);
                    setOpen(true);
                  }}>
                  Add to bag · ${(product.price * qty).toFixed(0)}
                </button>
                <button className="icon-btn" style={{ width: 52, height: 52, border: "1px solid var(--border)" }} aria-label="Save">
                  <I name="heart" size={18} />
                </button>
              </div>

              <div style={{ borderTop: "1px solid var(--border-1)", paddingTop: 24 }}>
                <p className="pretty" style={{ color: "var(--text-1)", fontSize: 14.5, lineHeight: 1.7, margin: 0 }}>
                  {product.desc}
                </p>
              </div>

              {/* Specs accordion */}
              <div style={{ marginTop: 32, borderTop: "1px solid var(--border-1)" }}>
                {[
                  ["Materials", product.kind === "music" ? "Lossless WAV (24-bit / 96kHz) · MP3 320kbps · stem package on request." : "Cotton, canvas, or wool sourced from Tuscany and Yamagata. Hardware in solid brass and bronze."],
                  ["Care", product.kind === "music" ? "DRM-free download. Stream from your library forever." : "Wash cold, hang to dry. Steam, do not iron. Garment will wear in over time, that's the point."],
                  ["Shipping", "Ships from the studio within 3–5 business days. Free on orders over $200."],
                ].map(([k, v], i) => (
                  <details key={k} style={{ borderBottom: "1px solid var(--border-1)" }}>
                    <summary style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "18px 0", cursor: "pointer", listStyle: "none" }}>
                      <span className="mono" style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-2)" }}>{String(i + 1).padStart(2, "0")} · {k}</span>
                      <I name="plus" size={14} stroke="var(--text-3)" />
                    </summary>
                    <p className="pretty" style={{ color: "var(--text-2)", fontSize: 13.5, lineHeight: 1.7, padding: "0 0 18px" }}>{v}</p>
                  </details>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Related */}
      <section style={{ padding: "60px 0 100px", background: "#080808", borderTop: "1px solid var(--border-1)" }}>
        <div className="container">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", marginBottom: 32 }}>
            <h3 className="serif" style={{ fontSize: 32, margin: 0 }}>You might also keep</h3>
            <button className="btn btn-line btn-sm" onClick={() => goto("store", { cat: product.cat })}>All {product.cat} <I name="arrow" size={12} /></button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 28 }}>
            {related.map((p, i) => (
              <div key={p.id} className="product" onClick={() => goto("pdp", { id: p.id })}>
                <div className="product-art">
                  <Placeholder label={p.name.toLowerCase()} variant={p.imgVariant} code={p.code} />
                </div>
                <div>
                  <div className="product-cat">{p.cat}</div>
                  <div className="product-meta">
                    <span className="product-name">{p.name}</span>
                    <span className="product-price">${p.price}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

window.Store = Store;
window.PDP = PDP;
