/* global React */
const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP } = React;

/* ---------- Shop / Collection page ---------- */
function ShopPage({ navigate, onAdd, favs, toggleFav, filterCollection }) {
  const D = window.PEARLA_DATA;
  const collection = filterCollection ? D.collections.find(c => c.id === filterCollection) : null;
  const [cat, setCat] = useStateP("All");
  const [sort, setSort] = useStateP("Featured");

  const cats = ["All", "Abayas", "Dresses", "Sets", "Scarves"];

  let list = D.products.slice();
  if (collection) list = list.filter(p => p.collection === collection.title);
  if (cat !== "All") list = list.filter(p => p.category === cat);
  if (sort === "Price ↑") list.sort((a, b) => a.price - b.price);
  if (sort === "Price ↓") list.sort((a, b) => b.price - a.price);
  if (sort === "Name") list.sort((a, b) => a.name.localeCompare(b.name));

  return (
    <>
      <header className="page-head">
        <div>
          <span className="eyebrow">{collection ? collection.tag : "Boutique"}</span>
          <h1 className="h-display" style={{ marginTop: 6, fontSize: "clamp(56px, 8vw, 120px)" }}>
            {collection ? collection.title : "Shop the House"}
          </h1>
        </div>
        <div className="page-head__meta">
          {collection ? (
            <p style={{ marginTop: 0 }}>{collection.kicker}</p>
          ) : (
            <p style={{ marginTop: 0 }}>The full Pearla wardrobe — abayas, dresses, sets and scarves cut in our Dubai atelier. Real AED prices. Worldwide shipping in 2–7 days.</p>
          )}
          <p className="label" style={{ marginTop: 14 }}>{list.length} pieces · {collection ? collection.subtitle : "Updated weekly"}</p>
        </div>
      </header>

      {collection && (
        <div className="wrap section" style={{ paddingBlock: 40 }}>
          <div className="lookbook">
            <div><img src={collection.hero} alt="" /></div>
            <div>
              <span className="eyebrow">The lookbook</span>
              <h2 className="h-2">{collection.subtitle}</h2>
              <p className="lede">{collection.kicker}</p>
              <p className="body-l muted">
                Each piece is named, numbered and made in a limited run from the d3 atelier. We re‑cut bestsellers once per season — pieces marked sold out rarely return.
              </p>
              <div style={{ display: "flex", gap: 12, marginTop: 14 }}>
                <a className="btn btn--ghost" href="https://wa.me/971528009555" target="_blank">Personal styling</a>
                <button className="btn btn--ghost" onClick={() => navigate("/about")}>Book the atelier</button>
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="wrap" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingBlock: 24, borderBottom: "1px solid var(--line)" }}>
        <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
          {cats.map(c => (
            <button key={c}
              onClick={() => setCat(c)}
              className="btn btn--ghost btn--sm"
              style={{
                background: cat === c ? "var(--ink)" : "transparent",
                color: cat === c ? "var(--ivory)" : "var(--ink)",
                border: "1px solid " + (cat === c ? "var(--ink)" : "var(--line)")
              }}>{c}</button>
          ))}
        </div>
        <label className="label" style={{ display: "flex", gap: 10, alignItems: "center" }}>
          Sort
          <select value={sort} onChange={(e) => setSort(e.target.value)}
            style={{
              border: "1px solid var(--line)", background: "transparent",
              padding: "8px 12px", fontFamily: "var(--sans)",
              fontSize: 12, letterSpacing: "0.16em", textTransform: "uppercase"
            }}>
            <option>Featured</option>
            <option>Price ↑</option>
            <option>Price ↓</option>
            <option>Name</option>
          </select>
        </label>
      </div>

      <section className="section wrap">
        <div className="prod-grid">
          {list.map(p => (
            <ProductCard key={p.id} p={p}
              onOpen={(id) => navigate("/product/" + id)}
              onAdd={onAdd} fav={favs.has(p.id)} toggleFav={toggleFav} />
          ))}
        </div>
        {list.length === 0 && (
          <div style={{ padding: 80, textAlign: "center", color: "var(--muted)" }}>
            <p className="h-3">No pieces match your filters.</p>
            <p className="body-l">Try a different category, or <a className="link-arrow" onClick={() => setCat("All")}>see everything <Icon.ArrowR /></a></p>
          </div>
        )}
      </section>
    </>
  );
}

/* ---------- Collections index ---------- */
function CollectionsIndex({ navigate }) {
  const D = window.PEARLA_DATA;
  return (
    <>
      <header className="page-head">
        <div>
          <span className="eyebrow">The Chapters</span>
          <h1 className="h-display" style={{ fontSize: "clamp(56px, 8vw, 120px)", marginTop: 6 }}>Collections.</h1>
        </div>
        <div className="page-head__meta">
          <p>Each Pearla collection is a chapter — named, numbered and tied to a season. Wearable everyday on one side, theatrical statement on the other.</p>
        </div>
      </header>
      <section className="section wrap">
        <div className="coll-grid">
          {D.collections.map((c, i) => (
            <article className={"coll-card" + (i === 0 ? " tall" : "")} key={c.id} onClick={() => navigate("/collections/" + c.id)}>
              <div className="coll-card__media">
                <img src={c.hero} alt="" />
                <span className="coll-card__count">{c.count} pieces</span>
                <span className="coll-card__season">{c.subtitle}</span>
              </div>
              <div className="coll-card__body">
                <span className="label">{c.tag}</span>
                <h3 className="h-3">{c.title}</h3>
                <p className="muted body-m">{c.kicker}</p>
              </div>
            </article>
          ))}
        </div>
      </section>
    </>
  );
}

/* ---------- Product detail ---------- */
function ProductDetail({ id, navigate, onAdd, favs, toggleFav }) {
  const p = window.PEARLA_DATA.products.find(x => x.id === id);
  if (!p) {
    return (
      <section className="section wrap" style={{ minHeight: 400, textAlign: "center" }}>
        <h1 className="h-2">We couldn't find that piece.</h1>
        <button className="btn btn--ghost" style={{ marginTop: 20 }} onClick={() => navigate("/shop")}>Back to the boutique <Icon.ArrowR /></button>
      </section>
    );
  }
  const gallery = [p.image, p.alt, p.image].filter(Boolean);
  const [activeImg, setActiveImg] = useStateP(0);
  const [size, setSize] = useStateP("M");
  const [open, setOpen] = useStateP("story");

  const related = window.PEARLA_DATA.products.filter(x => x.id !== p.id && x.category === p.category).slice(0, 4);

  return (
    <>
      <div className="wrap pd">
        <div className="pd__gallery">
          <div className="pd__thumbs">
            {gallery.map((src, i) => (
              <button key={i} className={"pd__thumb" + (activeImg === i ? " active" : "")} onClick={() => setActiveImg(i)}>
                <img src={src} alt="" />
              </button>
            ))}
          </div>
          <div className="pd__main">
            <img src={gallery[activeImg]} alt={p.name} />
          </div>
        </div>
        <aside className="pd__info">
          <div className="pd__crumbs">
            <a onClick={() => navigate("/")}>Home</a> / <a onClick={() => navigate("/shop")}>{p.category}</a> / <span>{p.name}</span>
          </div>
          <h1 className="pd__name">{p.name}</h1>
          <div className="pd__price">AED {p.price.toLocaleString()}</div>
          <p className="pd__story">{p.story}</p>

          <div className="pd__group">
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <span className="label">Size</span>
              <a className="label" onClick={() => navigate("/contact")} style={{ borderBottom: "1px solid var(--muted)", cursor: "pointer" }}>Size guide</a>
            </div>
            <div className="pd__sizes">
              {["XS", "S", "M", "L", "XL"].map(s => (
                <button key={s} className={"pd__size" + (size === s ? " active" : "") + (s === "XS" ? " oos" : "")}
                  onClick={() => s !== "XS" && setSize(s)}>{s}</button>
              ))}
            </div>
          </div>

          <div className="pd__cta-row">
            <button className="btn" onClick={() => onAdd(p, size)}>Add to Bag · AED {p.price.toLocaleString()}</button>
            <button className={"btn btn--ghost"} onClick={() => toggleFav(p.id)} style={{ flex: "0 0 auto" }} aria-label="Save">
              {favs.has(p.id) ? <Icon.HeartFill /> : <Icon.Heart />}
            </button>
          </div>
          <a className="btn btn--ghost" href={"https://wa.me/971528009555?text=Enquiry%20about%20" + encodeURIComponent(p.name)} target="_blank" style={{ width: "100%", justifyContent: "center" }}>
            <Icon.Wa /> Enquire on WhatsApp
          </a>

          <div className="pd__accordion" style={{ marginTop: 18 }}>
            {[
              { id: "story", title: "The Story", body: p.story + " Each piece is named in the order it was cut — yours is one of a small, numbered run." },
              { id: "fabric", title: "Fabric & Make", body: <ul className="pd__list">
                <li><b>Fabric</b><span>{p.fabric || "Crepe / satin · See label"}</span></li>
                <li><b>Composition</b><span>{p.composition || "100% polyester · Lining 100% viscose"}</span></li>
                <li><b>Care</b><span>{p.care || "Dry clean only"}</span></li>
                <li><b>Made in</b><span>Dubai, UAE — Pearla atelier</span></li>
              </ul> },
              { id: "ship", title: "Shipping & Returns", body: "Worldwide via Premium Express, 2–7 working days. Pre‑order pieces 7–10 days. 10‑day exchange‑only window from delivery; refunds issued as store credit. Sale & customised items final. Customer covers return shipping; garment tags must remain attached." },
              { id: "service", title: "Atelier Services", body: "Book a fitting at our d3 atelier, request a personal stylist over WhatsApp, or add complimentary gift wrap with a handwritten note (AED 30) at checkout." }
            ].map(item => (
              <div className="pd__acc-item" key={item.id}>
                <button className="pd__acc-head" onClick={() => setOpen(open === item.id ? null : item.id)}>
                  <span>{item.title}</span>
                  <span>{open === item.id ? <Icon.Minus /> : <Icon.Plus />}</span>
                </button>
                {open === item.id && <div className="pd__acc-body">{item.body}</div>}
              </div>
            ))}
          </div>
        </aside>
      </div>

      <section className="section wrap" style={{ paddingTop: 40 }}>
        <div className="sec-head">
          <div className="sec-head__title">
            <span className="eyebrow">In the same chapter</span>
            <h2 className="h-2">You may also love.</h2>
          </div>
        </div>
        <div className="prod-grid">
          {related.map(rp => (
            <ProductCard key={rp.id} p={rp}
              onOpen={(id) => { navigate("/product/" + id); window.scrollTo({ top: 0, behavior: "smooth" }); }}
              onAdd={onAdd} fav={favs.has(rp.id)} toggleFav={toggleFav} />
          ))}
        </div>
      </section>
    </>
  );
}

/* ---------- Fragrance page ---------- */
function FragrancePage({ navigate, onAdd }) {
  const bottle = { id: "selever-50ml", name: "S'élever Eau de Parfum — 50 ml", price: 200, image: "media/fragrance-selever-bottle.webp", category: "Fragrance", collection: "S'élever" };
  return (
    <>
      <FragranceBlock navigate={navigate} />
      <section className="section wrap">
        <div className="founder">
          <div>
            <span className="eyebrow">The brief</span>
            <h2 className="h-1" style={{ marginTop: 8 }}>To rise — softly.</h2>
            <p className="lede" style={{ marginTop: 14 }}>
              S'élever is French for "to rise". We worked with a Grasse perfumer for sixteen months to find a scent that wears the way our abayas do — quietly, then memorably.
            </p>
            <p className="body-l muted" style={{ marginTop: 14, maxWidth: "52ch" }}>
              The top opens with bergamot and crisp pear, settles into a long white‑tea heart, then dries down to oud, cashmere musk and a thread of silk. It is not a loud scent. It is, however, one that strangers will ask about.
            </p>
            <div style={{ display: "flex", gap: 12, marginTop: 28, flexWrap: "wrap" }}>
              <button className="btn" onClick={() => onAdd(bottle, "50 ML")}>Add 50 ml — AED 200</button>
              <button className="btn btn--ghost" onClick={() => onAdd({ ...bottle, id: "selever-30ml", name: "S'élever — 30 ml", price: 100 }, "30 ML")}>Add 30 ml — AED 100</button>
            </div>
            <p className="label" style={{ marginTop: 14 }}>Order a 2 ml sample with any garment · AED 30</p>
          </div>
          <div className="founder__media" style={{ background: "var(--noir)" }}>
            <img src="media/fragrance-selever-bottle.webp" alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "contain", padding: 40 }} />
          </div>
        </div>
      </section>
    </>
  );
}

/* ---------- Gifting page ---------- */
function GiftingPage({ navigate, onAdd, favs, toggleFav }) {
  const D = window.PEARLA_DATA;
  const occasions = [
    { title: "Ramadan & Eid", note: "Iftar grace, Eid mornings, the long evenings between.", img: "media/product-13-sage-bloom-lace.webp", id: "ramadan-eid" },
    { title: "Wedding Season", note: "For the guest list — statement caftans and ceremony‑ready dresses.", img: "media/onmodel-01-midnight-muse-lace.webp", id: "princess-and-the-pearl" },
    { title: "Hostess & Thank You", note: "Scarves, the scent, a handwritten card — under AED 500.", img: "media/fragrance-selever-bottle.webp", id: "by-the-sea" },
    { title: "Travel Capsule", note: "Pieces that survive a long flight and a longer holiday.", img: "media/product-14-azure-elegance.webp", id: "by-the-sea" }
  ];
  return (
    <>
      <header className="page-head">
        <div>
          <span className="eyebrow">Gifting Atelier</span>
          <h1 className="h-display" style={{ fontSize: "clamp(56px, 8vw, 120px)", marginTop: 6 }}>For her, with story.</h1>
        </div>
        <div className="page-head__meta">
          <p>Hand‑finished tissue, ribbon and a wax‑sealed note — for AED 30. Or hand the brief to our team and we'll choose the piece with you over WhatsApp.</p>
        </div>
      </header>

      <section className="section wrap">
        <div className="sec-head">
          <div className="sec-head__title">
            <span className="eyebrow">Guides by occasion</span>
            <h2 className="h-1">What is it for.</h2>
          </div>
        </div>
        <div className="coll-grid">
          {occasions.map((o, i) => (
            <article className={"coll-card" + (i === 0 ? " tall" : "")} key={o.title} onClick={() => navigate("/collections/" + o.id)}>
              <div className="coll-card__media">
                <img src={o.img} alt="" />
              </div>
              <div className="coll-card__body">
                <span className="label">Edit</span>
                <h3 className="h-3">{o.title}</h3>
                <p className="muted body-m">{o.note}</p>
              </div>
            </article>
          ))}
        </div>
      </section>

      <GiftingBlock navigate={navigate} />

      <ProductsBlock
        navigate={navigate} onAdd={onAdd} favs={favs} toggleFav={toggleFav}
        products={D.products.slice(0, 4)} />
    </>
  );
}

/* ---------- About ---------- */
function AboutPage({ navigate }) {
  return (
    <>
      <header className="page-head">
        <div>
          <span className="eyebrow">An Emirati house</span>
          <h1 className="h-display" style={{ fontSize: "clamp(56px, 8vw, 120px)", marginTop: 6 }}>The atelier.</h1>
        </div>
        <div className="page-head__meta">
          <p>Pearla is an independent modest‑fashion house founded by sisters Hessa and Fatma Ali Aljoker, designed and made in the Dubai Design District.</p>
        </div>
      </header>

      <section className="section wrap">
        <div className="founder">
          <div className="founder__media">
            <div className="placeholder">
              <span className="mono">[ founder portrait — to supply ]</span>
              <h3>Hessa &amp; Fatma</h3>
              <span className="mono">d3 · Dubai</span>
            </div>
          </div>
          <div>
            <span className="eyebrow">The founders</span>
            <h2 className="h-1" style={{ marginTop: 8 }}>Two sisters,<br/>one fairytale.</h2>
            <p className="lede" style={{ marginTop: 16 }}>
              We started Pearla to introduce abstract, contemporary pieces that merge art, storytelling and a wide imagination with fashion.
            </p>
            <p className="body-l" style={{ marginTop: 14, maxWidth: "52ch" }}>
              Each garment is a small chapter — named the way books are named, in the order it was cut. Pearla travels between two registers: the wearable everyday in fine fabric, and the theatrical statement for the nights you'll remember.
            </p>
            <p className="body-l muted" style={{ marginTop: 14, maxWidth: "52ch" }}>
              In 2023 we presented our ready‑to‑wear at Women's Arab Fashion Week, FW 22 / 23 — the room was small, the response was not. Today the house ships globally from d3.
            </p>
          </div>
        </div>
      </section>

      <section className="wrap section" style={{ paddingTop: 0 }}>
        <div className="about-stats">
          <div><b>61</b><span>Pieces in the live collection</span></div>
          <div><b>2</b><span>Sisters · creative directors</span></div>
          <div><b>FW 22/23</b><span>Arab Fashion Week, RTW</span></div>
        </div>
      </section>

      <section className="section wrap">
        <div className="sec-head">
          <div className="sec-head__title">
            <span className="eyebrow">The house philosophy</span>
            <h2 className="h-1">Two registers.<br/>One voice.</h2>
          </div>
        </div>
        <div className="about-grid">
          <div>
            <h3 className="h-2">Wearable everyday</h3>
            <p className="body-l muted" style={{ marginTop: 10, maxWidth: "44ch" }}>
              Fine crepe, soft cotton, considered cuts. Pieces designed to be folded into a suitcase and re‑pressed at the other end. The wardrobe you reach for on a Tuesday.
            </p>
            <div className="prod-grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 24 }}>
              <img src="media/product-09-slate-wave-abaya.webp" alt="" style={{ aspectRatio: "3/4", objectFit: "cover" }} />
              <img src="media/product-06-desert-bloom-set.webp" alt="" style={{ aspectRatio: "3/4", objectFit: "cover" }} />
            </div>
          </div>
          <div>
            <h3 className="h-2">Theatrical statement</h3>
            <p className="body-l muted" style={{ marginTop: 10, maxWidth: "44ch" }}>
              Beadwork, lace, embroidered constellations and gilt thread. The Pearla pieces that get photographed, asked after and inherited — written in lace, finished by hand.
            </p>
            <div className="prod-grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 24 }}>
              <img src="media/product-04-celestial-bloom-abaya.webp" alt="" style={{ aspectRatio: "3/4", objectFit: "cover" }} />
              <img src="media/product-11-golden-vine-dress.webp" alt="" style={{ aspectRatio: "3/4", objectFit: "cover" }} />
            </div>
          </div>
        </div>
      </section>

      <section className="section wrap" style={{ paddingTop: 0 }}>
        <div className="sec-head">
          <div className="sec-head__title">
            <span className="eyebrow">Visit</span>
            <h2 className="h-1">By appointment, in Dubai.</h2>
          </div>
          <button className="btn" onClick={() => navigate("/contact")}>Book the atelier <Icon.ArrowR /></button>
        </div>
        <div className="contact-info" style={{ gridColumn: "1 / -1" }}>
          <div>
            <b>The Pearla Atelier</b>
            <p>Office 303B, Building 5 · Dubai Design District · Dubai, UAE</p>
            <p className="label" style={{ marginTop: 8 }}>By appointment · Sunday – Friday · Hours to confirm with the team</p>
          </div>
        </div>
      </section>
    </>
  );
}

/* ---------- Contact ---------- */
function ContactPage() {
  const [sent, setSent] = useStateP(false);
  return (
    <>
      <header className="page-head">
        <div>
          <span className="eyebrow">Atelier &amp; care</span>
          <h1 className="h-display" style={{ fontSize: "clamp(56px, 8vw, 120px)", marginTop: 6 }}>Get in touch.</h1>
        </div>
        <div className="page-head__meta">
          <p>For personal styling, atelier appointments, custom orders or aftercare — we read everything that comes in. WhatsApp is the fastest line.</p>
        </div>
      </header>

      <section className="section wrap">
        <div className="contact-grid">
          <div className="contact-info">
            <div style={{ borderTop: 0, paddingTop: 0 }}>
              <span className="label">Atelier</span>
              <b>Office 303B, Building 5</b>
              <p>Dubai Design District (d3), Dubai, UAE<br/>P.O. Box 20213</p>
              <p className="label" style={{ marginTop: 8 }}>By appointment · Sunday – Friday</p>
            </div>
            <div>
              <span className="label">Direct lines</span>
              <p style={{ marginTop: 8 }}>
                <b style={{ display: "inline" }}>info@pearla.ae</b>
                <span className="label" style={{ display: "inline", marginLeft: 10 }}>email</span>
              </p>
              <p>
                <b style={{ display: "inline" }}>+971 4 277 2012</b>
                <span className="label" style={{ display: "inline", marginLeft: 10 }}>landline</span>
              </p>
              <p>
                <b style={{ display: "inline" }}>+971 52 800 9555</b>
                <span className="label" style={{ display: "inline", marginLeft: 10 }}>WhatsApp · fastest</span>
              </p>
            </div>
            <div>
              <span className="label">Service</span>
              <ul style={{ paddingLeft: 18, margin: "10px 0 0", color: "var(--ink)", fontSize: 14, lineHeight: 1.7 }}>
                <li>Worldwide shipping via Premium Express, 2–7 days</li>
                <li>10‑day exchange window from delivery</li>
                <li>Refunds issued as store credit</li>
                <li>Complimentary gift wrap, AED 30</li>
              </ul>
            </div>
            <div>
              <span className="label">Follow</span>
              <div style={{ display: "flex", gap: 10, marginTop: 12 }}>
                <a className="btn btn--ghost btn--sm" href="https://instagram.com/pearladubai" target="_blank"><Icon.Ig /> @pearladubai</a>
                <a className="btn btn--ghost btn--sm" href="https://tiktok.com/@pearladubai" target="_blank"><Icon.Tt /> @pearladubai</a>
              </div>
            </div>
          </div>

          <form className="contact-form" onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
            <span className="eyebrow">Send a note</span>
            <h2 className="h-2" style={{ margin: "4px 0 12px" }}>What can we help with?</h2>
            <label>
              <span>Full name</span>
              <input required placeholder="Aisha Al Falasi" />
            </label>
            <label>
              <span>Email</span>
              <input type="email" required placeholder="you@example.com" />
            </label>
            <label>
              <span>Phone / WhatsApp</span>
              <input placeholder="+971 50 000 0000" />
            </label>
            <label>
              <span>Subject</span>
              <select>
                <option>Personal styling</option>
                <option>Atelier appointment</option>
                <option>Custom order</option>
                <option>Press &amp; collaborations</option>
                <option>Aftercare</option>
              </select>
            </label>
            <label>
              <span>Message</span>
              <textarea required placeholder="Tell us what you're after — occasion, dates, sizes if you know them." />
            </label>
            {!sent ? (
              <div style={{ display: "flex", gap: 10, marginTop: 8 }}>
                <button className="btn" type="submit">Send the note <Icon.ArrowR /></button>
                <a className="btn btn--ghost" href="https://wa.me/971528009555" target="_blank"><Icon.Wa /> WhatsApp instead</a>
              </div>
            ) : (
              <div className="label" style={{ marginTop: 8, padding: "14px 0", borderTop: "1px solid var(--ink)" }}>Thank you — we'll write back within one business day.</div>
            )}
          </form>
        </div>
      </section>
    </>
  );
}

/* expose */
Object.assign(window, { ShopPage, CollectionsIndex, ProductDetail, FragrancePage, GiftingPage, AboutPage, ContactPage });
