/* global React */
const { useState: uS2, useMemo: uM2 } = React;

// ============================================================
// SHOP / COLLECTIONS / PRODUCT DETAIL
// ============================================================

function ShopPage({ setRoute, addToCart }) {
  const { products } = window.EVERLIT_DATA;
  const [filter, setFilter] = uS2("all");
  const [sort, setSort] = uS2("featured");

  const tabs = [
    { id: "all", label: "All seals" },
    { id: "Signature", label: "Signature" },
    { id: "Wedding", label: "Wedding" },
    { id: "Commissioned", label: "Commissioned" },
    { id: "Pattern", label: "Pattern" },
    { id: "Monogram", label: "Monogram" },
  ];

  let shown = filter === "all" ? products : products.filter(p => p.collection === filter);
  shown = [...shown].sort((a,b) => {
    if (sort === "price-asc") return a.price - b.price;
    if (sort === "price-desc") return b.price - a.price;
    return 0;
  });

  return (
    <div className="page-enter">
      <section style={{ paddingTop: 72, paddingBottom: 40 }}>
        <div className="container">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 60, alignItems: "end", borderBottom: "1px solid var(--rule)", paddingBottom: 48 }}>
            <div>
              <div className="eyebrow">The Shop · {shown.length} seals in currency</div>
              <h1 className="section-title" style={{ fontSize: "clamp(64px, 9vw, 140px)", marginTop: 18 }}>The <span className="italic-accent">Atelier</span><br/>Catalogue.</h1>
            </div>
            <p className="section-intro" style={{ maxWidth: "50ch", justifySelf: "end" }}>
              Every seal in our current season — from the standing signatures to the limited commissions. Filter by collection, or sort by price.
            </p>
          </div>
        </div>
      </section>

      <section style={{ padding: "0 0 80px" }}>
        <div className="container">
          <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 16, marginBottom: 48, paddingBottom: 20, borderBottom: "1px solid var(--rule)" }}>
            <div style={{ display: "flex", gap: 28, fontFamily: "var(--sans)", fontSize: 12, letterSpacing: "0.16em", textTransform: "uppercase", flexWrap: "wrap" }}>
              {tabs.map(t => (
                <button key={t.id} onClick={() => setFilter(t.id)} style={{ padding: "6px 0", borderBottom: filter === t.id ? "1px solid var(--ink)" : "1px solid transparent", color: filter === t.id ? "var(--ink)" : "var(--ink-muted)" }}>
                  {t.label}
                </button>
              ))}
            </div>
            <select value={sort} onChange={e => setSort(e.target.value)} style={{ border: "1px solid var(--rule)", padding: "6px 14px", fontFamily: "var(--sans)", fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", width: "auto" }}>
              <option value="featured">Sort: Featured</option>
              <option value="price-asc">Price, low → high</option>
              <option value="price-desc">Price, high → low</option>
            </select>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 48, rowGap: 64 }}>
            {shown.map((p, i) => (
              <ProductCard key={p.id} product={p} onClick={() => setRoute({ name: "product", id: p.id })} index={i+1} />
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

function CollectionsPage({ setRoute }) {
  const { collections } = window.EVERLIT_DATA;
  return (
    <div className="page-enter">
      <section style={{ paddingTop: 72, paddingBottom: 40 }}>
        <div className="container">
          <div style={{ textAlign: "center", paddingBottom: 48, borderBottom: "1px solid var(--rule)" }}>
            <div className="eyebrow">Four Collections</div>
            <h1 className="section-title" style={{ fontSize: "clamp(64px, 9vw, 140px)", marginTop: 18 }}>An archive, <span className="italic-accent">arranged.</span></h1>
            <p className="section-intro" style={{ margin: "28px auto 0" }}>Each collection is a small thesis — a way of looking at paper, ceremony, and the year of one's life.</p>
          </div>
        </div>
      </section>

      {collections.map((c, i) => (
        <section key={c.id} style={{ padding: "60px 0", background: i % 2 ? "var(--surface)" : "transparent" }}>
          <div className="container">
            <div style={{ display: "grid", gridTemplateColumns: i % 2 ? "1fr 1.2fr" : "1.2fr 1fr", gap: 80, alignItems: "center" }}>
              <div style={{ order: i % 2 ? 2 : 1 }}>
                <div style={{ aspectRatio: "4/5", overflow: "hidden" }}>
                  <img src={c.image} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </div>
              </div>
              <div style={{ order: i % 2 ? 1 : 2 }}>
                <div style={{ fontFamily: "var(--serif-display)", fontStyle: "italic", fontSize: 56, color: "var(--bronze)", lineHeight: 1 }}>№ {String(i+1).padStart(2,"0")}</div>
                <h2 className="section-title" style={{ fontSize: "clamp(40px, 5vw, 72px)", marginTop: 18 }}>{c.name}</h2>
                <p style={{ fontSize: 20, lineHeight: 1.55, maxWidth: "48ch", color: "var(--ink-soft)", fontStyle: "italic" }}>{c.description}</p>
                <div className="fig-caption" style={{ marginTop: 16 }}>{c.count} pieces · from ${[36, 65, 78, 42][i]}</div>
                <div style={{ marginTop: 32 }}>
                  <button className="btn" onClick={() => setRoute("shop")}>Shop the collection</button>
                </div>
              </div>
            </div>
          </div>
        </section>
      ))}
    </div>
  );
}

function ProductDetailPage({ productId, setRoute, addToCart }) {
  const { products, waxColors, shapes, reviews } = window.EVERLIT_DATA;
  const product = products.find(p => p.id === productId) || products[0];
  const [selectedWax, setSelectedWax] = uS2(waxColors[0]);
  const [selectedShape, setSelectedShape] = uS2(product.shape);
  const [qty, setQty] = uS2(1);
  const [added, setAdded] = uS2(false);
  const [mainIdx, setMainIdx] = uS2(0);

  // Reset gallery when product changes
  React.useEffect(() => { setMainIdx(0); }, [product.id]);

  const gallery = (product.gallery && product.gallery.length ? product.gallery : [product.image]);
  const mainImage = gallery[mainIdx] || product.image;

  const relProducts = products.filter(p => p.id !== product.id && p.price > 0).slice(0, 3);
  const productReviews = reviews.slice(0, 4);

  const handleAdd = () => {
    addToCart({ ...product, selectedWax, qty });
    setAdded(true);
    setTimeout(() => setAdded(false), 1800);
  };

  return (
    <div className="page-enter">
      <section style={{ paddingTop: 28, paddingBottom: 0 }}>
        <div className="container">
          <div className="fig-caption" style={{ marginBottom: 24 }}>
            <a onClick={() => setRoute("shop")} style={{ cursor: "pointer" }}>Shop</a> / <a onClick={() => setRoute("collections")} style={{ cursor: "pointer" }}>{product.collection}</a> / {product.name}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 72, alignItems: "start" }}>
            {/* Images */}
            <div>
              <div style={{ position: "sticky", top: 140 }}>
                <div style={{ aspectRatio: "1/1", background: "var(--ivory-deep)", overflow: "hidden" }}>
                  <img key={mainIdx} src={mainImage} style={{ width: "100%", height: "100%", objectFit: "cover", animation: "fadeIn .4s var(--ease)" }} />
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 8, marginTop: 8 }}>
                  {gallery.slice(0, 6).map((im, i) => (
                    <button key={i} onClick={() => setMainIdx(i)} style={{ aspectRatio: "1/1", overflow: "hidden", cursor: "pointer", background: "var(--ivory-deep)", border: i === mainIdx ? "1px solid var(--ink)" : "1px solid transparent", padding: 0 }}>
                      <img src={im} style={{ width: "100%", height: "100%", objectFit: "cover", opacity: i === mainIdx ? 1 : 0.7, transition: "opacity .2s" }} />
                    </button>
                  ))}
                </div>
                {gallery.length > 1 && (
                  <div className="fig-caption" style={{ marginTop: 14 }}>
                    Fig. {String.fromCharCode(65 + mainIdx)} · {gallery.length} photographs of this seal
                  </div>
                )}
              </div>
            </div>

            {/* Details */}
            <div style={{ paddingTop: 28 }}>
              <div className="eyebrow">{product.collection} · № {String(products.indexOf(product)+1).padStart(3, "0")}</div>
              <h1 className="section-title" style={{ fontSize: "clamp(48px, 6vw, 84px)", margin: "16px 0 4px" }}>{product.name}</h1>
              <div style={{ fontFamily: "var(--serif-display)", fontStyle: "italic", fontSize: 22, color: "var(--ink-muted)" }}>{product.subtitle}</div>

              <div style={{ marginTop: 28, display: "flex", alignItems: "center", gap: 16 }}>
                <Stars filled={Math.round(product.rating)} />
                <span className="fig-caption">{product.rating.toFixed(1)} · {product.reviews} reviews</span>
              </div>

              <div style={{ marginTop: 32, fontFamily: "var(--serif-display)", fontSize: 40 }}>
                {product.price > 0 ? `$${product.price}` : "Not for sale"}
                <span style={{ fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-muted)", marginLeft: 18 }}>Free courier</span>
              </div>

              <p style={{ marginTop: 32, fontSize: 18, lineHeight: 1.6, color: "var(--ink-soft)" }}>{product.description}</p>

              {product.price > 0 && (
                <>
                  {/* Wax color */}
                  <div style={{ marginTop: 40 }}>
                    <label>Paired wax · {selectedWax.name}</label>
                    <div style={{ display: "flex", gap: 10, marginTop: 12, flexWrap: "wrap" }}>
                      {waxColors.map(w => (
                        <button key={w.id} onClick={() => setSelectedWax(w)} title={w.name} style={{
                          width: 44, height: 44, borderRadius: "50%", background: w.hex,
                          border: selectedWax.id === w.id ? "2px solid var(--ink)" : "2px solid transparent",
                          outline: "1px solid var(--rule)", outlineOffset: 2, cursor: "pointer"
                        }} />
                      ))}
                    </div>
                  </div>

                  {/* Shape */}
                  <div style={{ marginTop: 32 }}>
                    <label>Form · {selectedShape}</label>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginTop: 12 }}>
                      {shapes.slice(0, 6).map(s => (
                        <button key={s.id} onClick={() => setSelectedShape(s.name)} style={{
                          padding: "14px 10px", border: selectedShape === s.name ? "1px solid var(--ink)" : "1px solid var(--rule)",
                          background: selectedShape === s.name ? "var(--ink)" : "transparent",
                          color: selectedShape === s.name ? "var(--ivory-paper)" : "var(--ink)",
                          fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", cursor: "pointer"
                        }}>
                          {s.name}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Qty + add */}
                  <div style={{ display: "flex", gap: 12, alignItems: "stretch", marginTop: 40 }}>
                    <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--ink)", padding: "0 8px" }}>
                      <button style={{ padding: "0 10px", fontSize: 18 }} onClick={() => setQty(Math.max(1, qty-1))}>−</button>
                      <span style={{ fontFamily: "var(--serif-display)", fontSize: 20, minWidth: 26, textAlign: "center" }}>{qty}</span>
                      <button style={{ padding: "0 10px", fontSize: 18 }} onClick={() => setQty(qty+1)}>+</button>
                    </div>
                    <button className="btn" style={{ flex: 1 }} onClick={handleAdd}>{added ? "✓ Sealed to your bag" : "Add to bag — $" + (product.price * qty)}</button>
                  </div>
                </>
              )}

              <div style={{ marginTop: 40, paddingTop: 32, borderTop: "1px solid var(--rule)" }}>
                <div className="eyebrow" style={{ marginBottom: 16 }}>Atelier notes</div>
                <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
                  {product.detail.map((d, i) => (
                    <li key={i} style={{ padding: "12px 0", borderTop: i === 0 ? "none" : "1px solid var(--rule-soft)", fontSize: 15, display: "flex", gap: 16 }}>
                      <span style={{ fontFamily: "var(--serif-display)", fontStyle: "italic", color: "var(--bronze)", minWidth: 30 }}>№ {String(i+1).padStart(2,"0")}</span>
                      <span>{d}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Reviews for product */}
      <section>
        <div className="container">
          <div className="eyebrow">Letters of praise</div>
          <h2 className="section-title" style={{ fontSize: "clamp(40px, 5vw, 72px)", marginTop: 16 }}>What is said <span className="italic-accent">about this seal.</span></h2>
          <div style={{ marginTop: 48, display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 48 }}>
            {productReviews.map((r, i) => (
              <figure key={i} style={{ margin: 0, padding: "24px 0", borderTop: "1px solid var(--rule)" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <Stars filled={r.rating} />
                  <span className="fig-caption">{r.date}</span>
                </div>
                <blockquote style={{ margin: "18px 0", fontFamily: "var(--serif-display)", fontSize: 22, lineHeight: 1.4, fontStyle: "italic" }}>
                  "{r.text}"
                </blockquote>
                <figcaption className="fig-caption">— {r.name}</figcaption>
              </figure>
            ))}
          </div>
        </div>
      </section>

      {/* Also loved */}
      <section style={{ background: "var(--surface)" }}>
        <div className="container">
          <div className="eyebrow">You may also love</div>
          <h2 className="section-title" style={{ fontSize: "clamp(40px, 5vw, 68px)", marginTop: 16, marginBottom: 48 }}>From <span className="italic-accent">the same atelier.</span></h2>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 40 }}>
            {relProducts.map((p, i) => (
              <ProductCard key={p.id} product={p} onClick={() => { setRoute({ name: "product", id: p.id }); window.scrollTo(0,0); }} index={i+1} />
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

window.ShopPage = ShopPage;
window.CollectionsPage = CollectionsPage;
window.ProductDetailPage = ProductDetailPage;
