// Page: Products — grid + filter chips + detail modal with image carousel
const { useState: useStateProducts, useEffect: useEffectProducts, useMemo } = React;

function ProductsPage({ products, addToCart, navigate, openProductId, clearOpen }) {
  const [activeCat, setActiveCat] = useStateProducts("All");
  const [openId, setOpenId] = useStateProducts(openProductId || null);
  const [search, setSearch] = useStateProducts("");

  useEffectProducts(() => {
    if (openProductId) setOpenId(openProductId);
  }, [openProductId]);

  const filtered = useMemo(() => {
    return products.filter((p) =>
      (activeCat === "All" || p.category === activeCat) &&
      (search.trim() === "" || (p.name + " " + p.description).toLowerCase().includes(search.toLowerCase()))
    );
  }, [products, activeCat, search]);

  const opened = products.find((p) => p.id === openId);

  return (
    <main id="main">
      <PageHeader
        eyebrow="Handmade in Kirkcaldy"
        title="Studio shop"
        sub="Each piece is sewn here in our High Street studio. Quantities are limited and one-of-a-kind — when it's gone, it's gone."
      />

      <section className="section" style={{ paddingTop: 32 }}>
        <div className="container">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap", marginBottom: 24 }}>
            <div className="chips" role="tablist" aria-label="Categories">
              {CATEGORIES.map((c) => (
                <button
                  key={c}
                  role="tab"
                  aria-selected={activeCat === c}
                  className={"chip" + (activeCat === c ? " active" : "")}
                  onClick={() => setActiveCat(c)}
                >
                  {c}
                </button>
              ))}
            </div>
            <input
              className="input"
              type="search"
              placeholder="Search products…"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              aria-label="Search products"
              style={{ maxWidth: 280 }}
            />
          </div>

          {filtered.length === 0 ? (
            <div className="empty">
              <h3>Nothing here yet</h3>
              <p>Try a different category, or check back soon — Heather is always making more.</p>
            </div>
          ) : (
            <div className="grid-products">
              {filtered.map((p) => (
                <ProductCard
                  key={p.id}
                  product={p}
                  onAdd={() => addToCart(p)}
                  onOpen={() => setOpenId(p.id)}
                />
              ))}
            </div>
          )}
        </div>
      </section>

      <Modal open={!!opened} onClose={() => { setOpenId(null); clearOpen && clearOpen(); }}>
        {opened && (
          <React.Fragment>
            <ProductGallery product={opened} />
            <div className="modal-body">
              <span className="tag">{opened.category}</span>
              <h2 style={{ fontFamily: "var(--font-serif)" }}>{opened.name}</h2>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: "1.5rem", color: "var(--accent)" }}>£{Number(opened.price).toFixed(0)}</div>
              <p style={{ color: "var(--ink-2)" }}>{opened.description}</p>
              <hr className="stitch-divider" style={{ margin: "8px 0" }} />
              <dl className="kv">
                <dt>Made by</dt><dd>Heather, in Kirkcaldy</dd>
                <dt>Materials</dt><dd>100% cotton, hand-pieced</dd>
                <dt>Care</dt><dd>Cold machine wash, low iron</dd>
                <dt>Lead time</dt><dd>In stock — ready to collect</dd>
              </dl>
              <div style={{ display: "flex", gap: 10, marginTop: 12, flexWrap: "wrap" }}>
                <button className="btn btn-primary" onClick={() => { addToCart(opened); }}>
                  <Icon.Plus /> Add to cart
                </button>
                <button className="btn btn-secondary" onClick={() => { setOpenId(null); navigate("cart"); }}>
                  View cart
                </button>
              </div>
              <p style={{ fontSize: 13, color: "var(--muted)", marginTop: 8 }}>
                Add the pieces you'd like, then check out securely via Stripe. UK shipping at checkout.
              </p>
            </div>
          </React.Fragment>
        )}
      </Modal>
    </main>
  );
}

function ProductGallery({ product }) {
  const images = (Array.isArray(product.images) && product.images.length)
    ? product.images
    : (product.image ? [product.image] : []);
  const [idx, setIdx] = React.useState(0);

  // Reset to first image when the opened product changes
  React.useEffect(() => { setIdx(0); }, [product.id]);

  if (images.length === 0) return <div className="modal-img" style={{ background: "var(--bg-2)" }} />;

  const prev = () => setIdx((i) => (i - 1 + images.length) % images.length);
  const next = () => setIdx((i) => (i + 1) % images.length);

  return (
    <div className="modal-img" style={{ position: "relative" }}>
      <img src={images[idx]} alt={`${product.name} — image ${idx + 1} of ${images.length}`} />
      {images.length > 1 && (
        <React.Fragment>
          <button
            onClick={prev}
            aria-label="Previous image"
            style={galleryNavStyle("left")}
          >‹</button>
          <button
            onClick={next}
            aria-label="Next image"
            style={galleryNavStyle("right")}
          >›</button>
          <div style={{
            position: "absolute", left: 0, right: 0, bottom: 12,
            display: "flex", justifyContent: "center", gap: 6, padding: "0 16px",
          }}>
            {images.map((src, i) => (
              <button
                key={i}
                onClick={() => setIdx(i)}
                aria-label={`Show image ${i + 1}`}
                style={{
                  width: 10, height: 10, padding: 0, borderRadius: "50%",
                  border: "1px solid rgba(255,255,255,.8)",
                  background: i === idx ? "var(--accent, #c98a5b)" : "rgba(255,255,255,.4)",
                  cursor: "pointer",
                }}
              />
            ))}
          </div>
          <div style={{
            position: "absolute", right: 12, top: 12,
            background: "rgba(0,0,0,.55)", color: "#fff",
            fontSize: 12, padding: "3px 8px", borderRadius: 999,
          }}>{idx + 1} / {images.length}</div>
        </React.Fragment>
      )}
    </div>
  );
}

function galleryNavStyle(side) {
  return {
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
    [side]: 8,
    width: 36, height: 36,
    border: "0",
    borderRadius: "50%",
    background: "rgba(0,0,0,.55)",
    color: "#fff",
    fontSize: 22,
    lineHeight: 1,
    cursor: "pointer",
    display: "grid",
    placeItems: "center",
  };
}

Object.assign(window, { ProductsPage, ProductGallery });
