/* ============================================================
   LINGEA — Collection (shop) + Product detail
   (useState/useEffect come from the shared global declared in components.jsx)
   ============================================================ */

/* ---------------- Collection ---------------- */
function CollectionPage({ nav, route }) {
  const P = window.LINGEA.products;
  const cats = ["All", "Bracelets", "Rings", "Brooches"];
  const [filter, setFilter] = useState(route.filter || "All");
  useEffect(() => { if (route.filter) setFilter(route.filter); }, [route.filter]);
  useReveal("coll-" + filter);

  const shown = filter === "All" ? P : P.filter((p) => p.category === filter);

  return (
    <main className="coll-page">
      <div className="coll-hero wrap">
        <span className="eyebrow accent fade-up in">Edition 01 — The Foundational Collection</span>
        <h1 className="display coll-title fade-up in" style={{ animationDelay: "70ms" }}>The Collection</h1>
        <p className="body coll-intro fade-up in" style={{ animationDelay: "140ms" }}>
          Seven pieces, made to order in solid 18k gold. Filter by form below — or
          take them in the order they were designed.
        </p>
        <div className="coll-filter fade-up in" style={{ animationDelay: "200ms" }}>
          {cats.map((c) => (
            <button
              key={c}
              className={"filter-pill" + (filter === c ? " active" : "")}
              onClick={() => setFilter(c)}
            >
              {c}
              <span className="filter-count">
                {c === "All" ? P.length : P.filter((p) => p.category === c).length}
              </span>
            </button>
          ))}
        </div>
      </div>

      <div className="wrap">
        <div className="grid-3 coll-grid">
          {shown.map((p, i) => <ProductCard product={p} nav={nav} index={i} key={p.id} />)}
        </div>
      </div>
    </main>
  );
}

/* ---------------- Accordion ---------------- */
function Accordion({ title, children, open, onToggle }) {
  return (
    <div className={"acc" + (open ? " open" : "")}>
      <button className="acc-head" onClick={onToggle}>
        <span>{title}</span>
        <span className="acc-sign"><Icon name={open ? "minus" : "plus"} size={16} /></span>
      </button>
      <div className="acc-body"><div className="acc-inner body">{children}</div></div>
    </div>
  );
}

/* ---------------- Product detail ---------------- */
function ProductPage({ nav, route, addToBag }) {
  const P = window.LINGEA.products;
  const product = P.find((p) => p.id === route.id) || P[0];
  const isRing = product.category === "Rings";
  const [size, setSize] = useState("");
  const [acc, setAcc] = useState("ship");
  const [added, setAdded] = useState(false);
  useReveal("prod-" + product.id);
  useEffect(() => { setSize(""); setAdded(false); window.scrollTo(0, 0); }, [product.id]);

  const sizes = ["4", "4.5", "5", "5.5", "6", "6.5", "7", "7.5", "8", "8.5", "9"];

  const handleAdd = () => {
    if (isRing && !size) { setAcc("size-hint"); return; }
    addToBag(product, isRing ? size : null);
    setAdded(true);
    setTimeout(() => setAdded(false), 2200);
  };

  const related = P.filter((p) => p.id !== product.id)
    .sort((a, b) => (a.category === product.category ? -1 : 1))
    .slice(0, 3);

  const specs = [
    ["Metal", product.metal],
    ["Centre stone", product.stone],
    ["Detail", product.detail],
    ["Weight", product.grams],
    ["Dimensions", product.dims],
    ["Certification", product.cert],
  ].filter((s) => s[1]);

  return (
    <main className="prod-page">
      <div className="wrap prod-crumb">
        <button onClick={() => nav({ page: "collection" })}>Collection</button>
        <span>/</span>
        <button onClick={() => nav({ page: "collection", filter: product.category })}>{product.category}</button>
        <span>/</span>
        <span className="crumb-here">{product.name}{product.variant ? " · " + product.variant : ""}</span>
      </div>

      <div className="wrap prod-main">
        <div className="prod-gallery">
          <div className="prod-img-main">
            <ProductImage product={product} />
            {product.edition ? <span className="prod-edition-tag">{product.edition} of {window.LINGEA.collection.total}</span> : null}
          </div>
        </div>

        <div className="prod-info">
          <span className="eyebrow accent">{product.type}</span>
          <h1 className="display prod-name">
            {product.name}{product.variant ? <em> {product.variant}</em> : null}
          </h1>
          <p className="prod-short">{product.shortDesc}</p>
          <div className="prod-price">{fmt(product.price)}</div>

          {isRing && (
            <div className="prod-size">
              <div className="prod-size-label">
                <span className="eyebrow">Ring size — US</span>
                <button className="size-guide" onClick={() => setAcc(acc === "size" ? "" : "size")}>Size guide</button>
              </div>
              <div className="size-grid">
                {sizes.map((s) => (
                  <button key={s} className={"size-chip" + (size === s ? " active" : "")} onClick={() => setSize(s)}>{s}</button>
                ))}
              </div>
              {acc === "size-hint" && !size ? <p className="size-warn">Please select a ring size to continue.</p> : null}
            </div>
          )}

          <div className="prod-actions">
            <button className={"btn block add-btn" + (added ? " done" : "")} onClick={handleAdd}>
              {added ? "Added to bag ✓" : "Add to bag — made to order"}
            </button>
            <p className="prod-made">Each piece is made by hand to order · 3–4 weeks · {product.metal.includes("Rose") ? "rose" : product.metal.includes("White") ? "white" : "yellow"} gold</p>
          </div>

          <div className="prod-story body">{product.story}</div>

          <dl className="spec">
            {specs.map(([k, v]) => (
              <div className="spec-row" key={k}><dt>{k}</dt><dd>{v}</dd></div>
            ))}
          </dl>

          <div className="prod-accs">
            <Accordion title="Shipping" open={acc === "ship"} onToggle={() => setAcc(acc === "ship" ? "" : "ship")}>
              Complimentary FedEx Priority Overnight, fully insured and signature-required, on every order within the US.
              You receive tracking the moment your piece leaves the atelier. International shipping is arranged privately —
              contact the studio.
            </Accordion>
            <Accordion title="Returns &amp; exchanges" open={acc === "ret"} onToggle={() => setAcc(acc === "ret" ? "" : "ret")}>
              30 days from delivery. Pieces must be unworn with the tamper-evident security tag intact. Return shipping is
              prepaid and insured by us. Made-to-order rings can be re-sized once, complimentary, within the first year.
            </Accordion>
            <Accordion title="Certification &amp; care" open={acc === "cert"} onToggle={() => setAcc(acc === "cert" ? "" : "cert")}>
              Arrives with an independent coloured-stone report and a stamped statement of metal purity and gram weight.
              Lifetime complimentary cleaning, re-polishing and prong-checks at the studio.
            </Accordion>
          </div>
        </div>
      </div>

      <section className="prod-related wrap">
        <div className="section-head fade-up">
          <h2 className="display section-title small">Also in Edition 01</h2>
          <button className="ulink" onClick={() => nav({ page: "collection" })}>
            View all <span className="arr"><Icon name="arrow" size={16} /></span>
          </button>
        </div>
        <div className="grid-3">
          {related.map((p, i) => <ProductCard product={p} nav={nav} index={i} key={p.id} />)}
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { CollectionPage, ProductPage, Accordion });
