// Marmar Halim — Shop, Product detail, Collections
const { useState: useStateC, useMemo: useMemoC, useEffect: useEffectC } = React;

/* ---------- Shop ---------- */
function Shop({ go, openProduct }) {
  const { PRODUCTS, fmtAED } = window.MMH_DATA;
  const [line, setLine] = useStateC("All");
  const [sort, setSort] = useStateC("featured");
  const lines = ["All", "Eveningwear", "Couture", "Bridal", "Modest"];

  const filtered = useMemoC(() => {
    let arr = PRODUCTS.filter((p) => line === "All" ? true : p.line === line);
    if (sort === "low") arr = [...arr].sort((a, b) => a.aed - b.aed);
    else if (sort === "high") arr = [...arr].sort((a, b) => b.aed - a.aed);
    return arr;
  }, [line, sort]);

  return (
    <div className="page-enter" data-screen-label="Shop">
      <section className="page-head container">
        <div className="crumbs"><button onClick={() => go("home")}>Home</button> / Shop</div>
        <h1>Eveningwear <em>· SS25.</em></h1>
        <p className="lede">Sixteen ready-to-order silhouettes from the current book. Each piece is made for you in our Dubai atelier over four to six weeks. Customisation is welcome.</p>
      </section>

      <section className="container">
        <div className="shop-toolbar">
          <div className="filter-group" role="tablist" aria-label="Filter by line">
            {lines.map((l) => (
              <button key={l} className="filter-chip" aria-pressed={line === l} onClick={() => setLine(l)}>{l}</button>
            ))}
          </div>
          <div className="flex" style={{ gap: 16, alignItems: "center" }}>
            <span className="shop-meta">{filtered.length} pieces</span>
            <select className="filter-chip" value={sort} onChange={(e) => setSort(e.target.value)} style={{ padding: "8px 14px", appearance: "none" }}>
              <option value="featured">Sort · Featured</option>
              <option value="low">Sort · Price Low</option>
              <option value="high">Sort · Price High</option>
            </select>
          </div>
        </div>

        <div className="products-grid">
          {filtered.map((p) => <ProductCard key={p.id} p={p} onOpen={openProduct} />)}
        </div>

        <div className="spacer-lg"></div>
        <div className="center" style={{ paddingBottom: 80 }}>
          <div className="eyebrow gold" style={{ marginBottom: 18 }}>Made to your size</div>
          <p style={{ maxWidth: 56 + "ch", margin: "0 auto 24px", color: "var(--ink-2)" }}>
            Looking for a piece in another colourway, length or fabric? The atelier accepts customisation on most styles.
          </p>
          <a className="btn btn--ghost" href="https://wa.me/971564973497" target="_blank" rel="noreferrer">Speak to the Atelier <span className="arrow"></span></a>
        </div>
      </section>
    </div>
  );
}

/* ---------- Product Detail ---------- */
function ProductDetail({ p, go, openProduct, toast }) {
  const { PRODUCTS, fmtAED } = window.MMH_DATA;
  const [size, setSize] = useStateC("38");
  const [color, setColor] = useStateC(0);
  const [view, setView] = useStateC(0);

  const more = useMemoC(() => PRODUCTS.filter((x) => x.id !== p.id).slice(0, 4), [p]);
  const sizes = ["34", "36", "38", "40", "42", "44"];
  const gallery = [p.img, p.img, p.img, p.img]; // single asset; gallery placeholders

  return (
    <div className="page-enter" data-screen-label={"Product: " + p.name}>
      <section className="container" style={{ padding: "40px 0 80px" }}>
        <div className="pdp-info" style={{ position: "static", marginBottom: 20 }}>
          <div className="breadcrumbs">
            <button onClick={() => go("home")} style={{ background: "none", border: 0, padding: 0, font: "inherit", color: "inherit" }}>Home</button>
            {" / "}
            <button onClick={() => go("shop")} style={{ background: "none", border: 0, padding: 0, font: "inherit", color: "inherit" }}>Shop</button>
            {" / "}{p.line} / <span style={{ color: "var(--ink)" }}>{p.name}</span>
          </div>
        </div>
        <div className="pdp">
          <div className="pdp-gallery">
            <div className="main"><img src={gallery[view]} alt={p.name} /></div>
            <div className="thumbs">
              {gallery.map((src, i) => (
                <button key={i} className={"t " + (i === view ? "active" : "")} onClick={() => setView(i)} aria-label={"View " + (i + 1)}>
                  <img src={src} alt="" />
                </button>
              ))}
            </div>
          </div>

          <div className="pdp-info">
            <div className="breadcrumbs">SS25 · MY GIRL · {p.line.toUpperCase()}</div>
            <h1>{p.name}</h1>
            <div className="price">{fmtAED(p.aed)}</div>
            <div className="mto">— Made to order · 4–6 weeks</div>

            <p className="desc">{p.craft}</p>

            <div className="opt-row">
              <div className="label"><span>Colour · {p.colors[color]}</span></div>
              <div className="swatches">
                {p.colors.map((c, i) => (
                  <button
                    key={c}
                    className="swatch"
                    aria-pressed={color === i}
                    aria-label={c}
                    onClick={() => setColor(i)}
                    style={{ background: swatchOf(c) }}
                  />
                ))}
                <button className="swatch" aria-label="Custom colour" style={{ background: "linear-gradient(135deg, var(--ivory) 0%, var(--bone) 50%, var(--accent) 100%)" }} title="Custom colour on enquiry" />
              </div>
            </div>

            <div className="opt-row">
              <div className="label"><span>Size (EU)</span><a href="#" onClick={(e) => e.preventDefault()}>Size guide</a></div>
              <div className="sizes">
                {sizes.map((s) => (
                  <button key={s} className="size-chip" aria-pressed={size === s} onClick={() => setSize(s)}>{s}</button>
                ))}
              </div>
            </div>

            <div className="pdp-ctas">
              <button className="btn btn--lg" onClick={() => toast("Added · " + p.name + " · " + size + " · " + p.colors[color])}>Add to bag · {fmtAED(p.aed)}</button>
              <a className="btn btn--ghost btn--lg" href={`https://wa.me/971564973497?text=Hi%2C%20I%27d%20like%20to%20enquire%20about%20%22${encodeURIComponent(p.name)}%22%20(${size},%20${p.colors[color]}).`} target="_blank" rel="noreferrer">Enquire on WhatsApp <span className="arrow"></span></a>
            </div>

            <div className="pdp-meta">
              <details open>
                <summary>Fabric &amp; Craft</summary>
                <p>{p.fabric}. {p.craft} All hand-pleating and draping is finished in the Dubai atelier.</p>
              </details>
              <details>
                <summary>Made to Order</summary>
                <p>Every piece is produced in our Dubai atelier once you place your order. Standard lead time is 4–6 weeks for ready-to-order; couture commissions are 6–10 weeks plus fittings.</p>
              </details>
              <details>
                <summary>Customisation</summary>
                <p>Most styles accept colour, length, neckline and sleeve adjustments. Speak to the atelier on WhatsApp before placing your order.</p>
              </details>
              <details>
                <summary>Shipping &amp; Returns</summary>
                <p>Fully tracked worldwide shipping from Dubai. Five-day inspection window from delivery on ready-to-order pieces. Couture is final sale once production begins.</p>
              </details>
            </div>
          </div>
        </div>
      </section>

      {/* You may also love */}
      <section className="section--tight container">
        <SectionHead eyebrow="Also in the atelier" title={<span>You may also <em>love.</em></span>} meta={null} />
        <div className="products-grid">
          {more.map((p) => <ProductCard key={p.id} p={p} onOpen={openProduct} />)}
        </div>
      </section>
    </div>
  );
}

function swatchOf(name) {
  const n = name.toLowerCase();
  if (n.includes("indigo") || n.includes("blue")) return "#3a2dc3";
  if (n.includes("ivory") || n.includes("pearl")) return "#F4ECDD";
  if (n.includes("champagne")) return "#E8DCC1";
  if (n.includes("sand")) return "#D9C9A8";
  if (n.includes("butter")) return "#E9D795";
  if (n.includes("gold") && n.includes("antique")) return "#C9A04A";
  if (n.includes("gold")) return "#CFAE5F";
  if (n.includes("bronze")) return "#7E5B36";
  if (n.includes("olive")) return "#7C7A4A";
  if (n.includes("sienna")) return "#B45A2A";
  if (n.includes("terracotta")) return "#B5563B";
  if (n.includes("dove")) return "#8C8A95";
  return "#cdbfae";
}

/* ---------- Collections index ---------- */
function Collections({ go }) {
  const { COLLECTIONS } = window.MMH_DATA;
  return (
    <div className="page-enter" data-screen-label="Collections">
      <section className="page-head container">
        <div className="crumbs"><button onClick={() => go("home")}>Home</button> / Collections</div>
        <h1>The seasons, <em>by hand.</em></h1>
        <p className="lede">SS25 → FW26. Each book is shot in Dubai and shaped from the same atelier — pleated, draped, and finished by hand.</p>
      </section>

      <section className="container" style={{ paddingBottom: 120 }}>
        {COLLECTIONS.map((c, i) => (
          <article key={c.id} style={{ display: "grid", gridTemplateColumns: i % 2 === 0 ? "1.3fr 1fr" : "1fr 1.3fr", gap: "clamp(40px, 5vw, 96px)", alignItems: "center", margin: "0 0 clamp(60px, 8vw, 140px)" }} className="collection-row">
            <div style={{ order: i % 2 === 0 ? 0 : 1, background: "var(--bone)" }}>
              <img src={c.img} alt={c.title} style={{ width: "100%", aspectRatio: "4/5", objectFit: "cover" }} />
            </div>
            <div>
              <div className="eyebrow gold" style={{ marginBottom: 18 }}>{c.season} · {c.looks} looks</div>
              <h2 style={{ fontFamily: "var(--serif)", fontWeight: 300, fontSize: "clamp(40px, 5vw, 72px)", lineHeight: 1.02, letterSpacing: "-0.01em", marginBottom: 24 }}>{c.title}</h2>
              <p style={{ fontSize: 17, color: "var(--ink-2)", maxWidth: "44ch", marginBottom: 28 }}>{c.note}</p>
              <div className="flex" style={{ gap: 12, flexWrap: "wrap" }}>
                <button className="btn btn--ghost" onClick={() => go(c.id === "bridal-25" ? "bridal" : c.id === "couture-25" ? "couture" : "shop")}>
                  View the collection <span className="arrow"></span>
                </button>
                <button className="link-under" onClick={() => go("appointments")} style={{ alignSelf: "center" }}>Book a Fitting →</button>
              </div>
            </div>
          </article>
        ))}
      </section>
    </div>
  );
}

Object.assign(window, { Shop, ProductDetail, Collections });
