// Sunehra — Collections / Listing page

const { useState, useEffect, useMemo } = React;

// =============== Catalogue data ===============

const CAT_LABEL = {
  bridal: "The Bridal Edit",
  necklaces: "Necklaces & Haar",
  earrings: "Earrings & Jhumka",
  rings: "Rings & Solitaires",
  bangles: "Bangles & Kangan",
  mangalsutra: "Mangalsutra",
  nosepins: "Nose Pins · Nath",
  anklets: "Anklets · Payal",
  diamond: "Diamonds",
};
const CAT_SUB = {
  bridal: "Aabhushan · Vivaha",
  necklaces: "Aabhushan · Haar",
  earrings: "Aabhushan · Karna",
  rings: "Aabhushan · Anguthi",
  bangles: "Aabhushan · Kangan",
  mangalsutra: "Aabhushan · Mangal",
  nosepins: "Aabhushan · Nath",
  anklets: "Aabhushan · Payal",
  diamond: "Dhatu · Heera",
};
const CAT_BLURB = {
  bridal: "Twenty-three pieces composed for the seven pheras — rani-haars, jadau chokers, nath, and bangles that travel through generations.",
  necklaces: "From single-line solitaire chains to weighted rani-haars in polki and meenakari. Wear daily, or wear the day.",
  earrings: "Chandbalis, jhumkas, ear-cuffs, and studs — for the temple, the office, and the wedding.",
  rings: "Solitaire engagement bands, anniversary rings, and the everyday gold cocktail.",
  bangles: "Stacked kangans, single jadau bangles, and meenakari cuffs from Bikaner.",
  mangalsutra: "Sacred and modern — black bead, gold pendant, with an optional diamond accent.",
  diamond: "GIA-certified solitaires, halos, and pavé settings from .25 to 3 carats.",
};

// Catalogue lives in shared.jsx (window.CATALOG) so the wishlist page can
// resolve saved ids too. This page just reuses it.
const PRODUCTS = CATALOG;

// =============== Filter UI ===============

const FILTERS = {
  metal: ["22K Gold", "18K Gold", "Platinum", "22K + Kundan", "22K + Pearl"],
  occasion: ["Bridal", "Engagement", "Festive", "Sangeet", "Everyday"],
  weight: ["Under 20g", "20–50g", "50g+"],
  craft: ["Polki", "Jadau", "Meenakari", "Temple", "Solitaire"],
};

function FilterChip({ label, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      appearance: "none", border: `1px solid ${active ? "var(--brand)" : "var(--line)"}`,
      background: active ? "var(--brand)" : "transparent",
      color: active ? "var(--ivory)" : "var(--fg)",
      padding: "8px 14px", borderRadius: 999,
      fontFamily: "var(--font-body)", fontSize: 10.5,
      letterSpacing: ".16em", textTransform: "uppercase", cursor: "pointer",
      transition: "all .2s ease", whiteSpace: "nowrap",
    }}>{label}</button>
  );
}

function FilterGroup({ title, options, value, onToggle }) {
  return (
    <div style={{ paddingBottom: 24, borderBottom: "1px solid var(--line)", marginBottom: 24 }}>
      <div className="mono" style={{ fontSize: 9.5, color: "var(--brand)", marginBottom: 14, letterSpacing: ".18em" }}>
        ◇ {title}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {options.map(o => {
          const checked = value.includes(o);
          return (
            <label key={o} style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", fontSize: 13, color: checked ? "var(--brand)" : "var(--fg)" }}>
              <span style={{
                width: 14, height: 14, border: `1.5px solid ${checked ? "var(--brand)" : "var(--line)"}`,
                background: checked ? "var(--brand)" : "transparent",
                position: "relative", display: "inline-block",
              }}>
                {checked && <span style={{ position: "absolute", inset: 1, color: "var(--ivory)", fontSize: 10, lineHeight: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>✓</span>}
              </span>
              {o}
            </label>
          );
        })}
      </div>
    </div>
  );
}

// =============== Product card ===============

function ProductCard({ p, onWish, wished }) {
  const [hover, setHover] = useState(false);
  return (
    <a href={`product.html?id=${p.id}`}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ display: "flex", flexDirection: "column", gap: 14, position: "relative" }}>
      <Ph variant={p.v} src={p.img} tag={p.id} style={{ aspectRatio: "4/5" }}>
        {/* badges */}
        <div style={{ position: "absolute", left: 14, top: 14, display: "flex", gap: 6, zIndex: 2 }}>
          {p.isNew && <span style={{
            background: "var(--ivory)", color: "var(--brand)",
            padding: "5px 9px", fontSize: 9, letterSpacing: ".2em",
            textTransform: "uppercase", fontWeight: 600, borderRadius: 1, whiteSpace: "nowrap",
          }}>New</span>}
          {p.best && <span style={{
            background: "var(--metal)", color: "var(--ink)",
            padding: "5px 9px", fontSize: 9, letterSpacing: ".2em",
            textTransform: "uppercase", fontWeight: 600, borderRadius: 1, whiteSpace: "nowrap",
          }}>Best Seller</span>}
        </div>
        {/* wishlist */}
        <button onClick={(e) => { e.preventDefault(); onWish(p.id); }}
          style={{
            position: "absolute", top: 14, right: 14, zIndex: 2,
            width: 36, height: 36, borderRadius: "50%",
            background: "rgba(248, 241, 229, .92)",
            border: "none", color: wished ? "var(--brand)" : "var(--ink)",
            cursor: "pointer", fontSize: 16, display: "flex", alignItems: "center", justifyContent: "center",
            transition: "transform .2s ease",
            transform: hover ? "scale(1.06)" : "scale(1)",
          }}>{wished ? "♥" : "♡"}</button>
        {/* hover overlay */}
        <div style={{
          position: "absolute", left: 14, right: 14, bottom: 14, zIndex: 2,
          opacity: hover ? 1 : 0, transform: hover ? "translateY(0)" : "translateY(8px)",
          transition: "all .3s ease",
          background: "rgba(248, 241, 229, .96)",
          padding: "10px 14px",
          display: "flex", justifyContent: "space-between", alignItems: "center",
        }}>
          <span className="mono" style={{ fontSize: 9.5, color: "var(--brand)" }}>QUICK VIEW</span>
          <span style={{ fontSize: 14, color: "var(--brand)" }}>→</span>
        </div>
      </Ph>
      <div>
        <div className="mono" style={{ fontSize: 9, color: "var(--fg-soft)", marginBottom: 4 }}>
          {p.metal.toUpperCase()} · {p.weight}G
        </div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 19, lineHeight: 1.15, color: "var(--fg)" }}>
          {p.name}
        </div>
        <div style={{ fontSize: 11, color: "var(--fg-soft)", marginTop: 4 }}>
          {p.type}
        </div>
      </div>
    </a>
  );
}

// =============== Page hero ===============

function CatHero({ cat, count }) {
  const label = CAT_LABEL[cat] || "All Collections";
  const sub = CAT_SUB[cat] || "Aabhushan · Catalogue";
  const blurb = CAT_BLURB[cat] || "Every piece in the Sunehra atelier, indexed for browsing.";
  return (
    <section style={{
      padding: "80px 0 60px",
      borderBottom: "1px solid var(--line)",
      position: "relative",
    }}>
      <div className="wrap">
        <div className="mono" style={{ fontSize: 10, color: "var(--fg-soft)", letterSpacing: ".2em", marginBottom: 10 }}>
          <a href="index.html" style={{ color: "var(--fg-soft)" }}>HOME</a> &nbsp;/&nbsp; <a href="collections.html" style={{ color: "var(--fg-soft)" }}>COLLECTIONS</a> &nbsp;/&nbsp; <span style={{ color: "var(--brand)" }}>{label.toUpperCase()}</span>
        </div>
        <div className="grid-cat-hero">
          <div>
            <span className="eyebrow" style={{ color: "var(--brand)" }}>◈ &nbsp; {sub}</span>
            <h1 className="display" style={{ fontSize: "clamp(56px, 7vw, 96px)", margin: "16px 0 0", color: "var(--fg)", lineHeight: 1.02 }}>
              {label.split(" ").slice(0, -1).join(" ")} <span style={{ fontStyle: "italic", color: "var(--accent)" }}>{label.split(" ").slice(-1)}</span>
            </h1>
          </div>
          <div>
            <p style={{ fontSize: 14.5, lineHeight: 1.75, color: "var(--fg-soft)", maxWidth: 460 }}>
              {blurb}
            </p>
            <div style={{ marginTop: 18, display: "flex", gap: 24, fontSize: 11, letterSpacing: ".22em", textTransform: "uppercase" }}>
              <span><span style={{ color: "var(--brand)", fontWeight: 600 }}>{count}</span> pieces</span>
              <span><span style={{ color: "var(--metal)" }}>BIS</span> Hallmarked</span>
              <span>GIA Certified</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// =============== Toolbar (sort + view) ===============

function Toolbar({ active, onChange, sort, setSort, view, setView, total }) {
  const quick = ["new", "bestsellers", "polki", "diamond", "under-50g", "bridal"];
  return (
    <div style={{ padding: "28px 0", borderBottom: "1px solid var(--line)", position: "sticky", top: 142, background: "var(--bg)", zIndex: 10 }}>
      <div className="wrap" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          {quick.map(q => (
            <FilterChip key={q} label={q.replace(/-/g, " ")}
              active={active === q}
              onClick={() => onChange(active === q ? null : q)}/>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 24 }}>
          <span className="mono" style={{ fontSize: 10, color: "var(--fg-soft)" }}>{total} pieces</span>
          <div style={{ display: "flex", gap: 4, border: "1px solid var(--line)", borderRadius: 2 }}>
            <button onClick={() => setView(3)} style={{
              all: "unset", padding: "6px 10px", cursor: "pointer",
              background: view === 3 ? "var(--brand)" : "transparent",
              color: view === 3 ? "var(--ivory)" : "var(--fg)",
              fontSize: 11, letterSpacing: ".2em", fontWeight: 500,
            }}>III</button>
            <button onClick={() => setView(4)} style={{
              all: "unset", padding: "6px 10px", cursor: "pointer",
              background: view === 4 ? "var(--brand)" : "transparent",
              color: view === 4 ? "var(--ivory)" : "var(--fg)",
              fontSize: 11, letterSpacing: ".2em", fontWeight: 500,
            }}>IIII</button>
          </div>
          <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11, letterSpacing: ".2em", textTransform: "uppercase", color: "var(--fg-soft)" }}>
            Sort
            <select value={sort} onChange={e => setSort(e.target.value)} style={{
              appearance: "none", border: "1px solid var(--line)", background: "transparent",
              padding: "6px 26px 6px 10px", fontFamily: "var(--font-body)", fontSize: 11,
              letterSpacing: ".18em", textTransform: "uppercase", color: "var(--fg)", cursor: "pointer",
              borderRadius: 2,
            }}>
              <option value="featured">Featured</option>
              <option value="new">Newest</option>
              <option value="weight-asc">Weight: low → high</option>
              <option value="weight-desc">Weight: high → low</option>
            </select>
          </label>
        </div>
      </div>
    </div>
  );
}

// =============== Editorial inline block ===============

function EditorialBlock() {
  return (
    <div className="editorial-cell" style={{ gridColumn: "span 2" }}>
      <Ph variant="emerald" src={IMG.editorial} cap="editorial · vivaha 2026" tag="vol / xii"
          style={{ aspectRatio: "8/5", borderRadius: 0 }}>
        <div style={{
          position: "absolute", inset: 0,
          display: "flex", alignItems: "center", padding: "0 60px",
          background: "linear-gradient(90deg, rgba(7,51,31,.85) 0%, rgba(7,51,31,.45) 60%, transparent 100%)",
        }}>
          <div style={{ maxWidth: 380, color: "var(--ivory)" }}>
            <span className="mono" style={{ fontSize: 9.5, color: "var(--metal-soft)" }}>◇ EDITOR'S NOTE</span>
            <h3 style={{
              fontFamily: "var(--font-display)", fontSize: 32, lineHeight: 1.15, margin: "14px 0 18px",
              fontStyle: "italic", color: "var(--ivory)", fontWeight: 400,
            }}>The polki revival.</h3>
            <p style={{ fontSize: 13.5, lineHeight: 1.7, color: "rgba(248,241,229,.78)" }}>
              Why uncut diamonds are leaving the Mughal court and finding their way back to modern brides — read our editor's note.
            </p>
            <a href="#" style={{
              marginTop: 18, display: "inline-block",
              fontSize: 10.5, letterSpacing: ".24em", textTransform: "uppercase",
              color: "var(--metal-soft)", borderBottom: "1px solid var(--metal-soft)", paddingBottom: 3,
            }}>Read the journal →</a>
          </div>
        </div>
      </Ph>
    </div>
  );
}

// =============== Main app ===============

function App() {
  const params = new URLSearchParams(window.location.search);
  const cat = params.get("cat") || "bridal";

  const wishlist = useWishlist();
  const [filters, setFilters] = useState({ metal: [], occasion: [], weight: [], craft: [] });
  const [quickFilter, setQuickFilter] = useState(null);
  const [sort, setSort] = useState("featured");
  const [view, setView] = useState(3);
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);

  // Lock body scroll while the filter drawer is open on mobile.
  useEffect(() => {
    const prev = document.body.style.overflow;
    if (mobileFiltersOpen) document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, [mobileFiltersOpen]);

  const toggleWish = (id) => wishlist.toggle(id);
  const toggleFilter = (group, val) => setFilters(f => {
    const arr = f[group];
    return { ...f, [group]: arr.includes(val) ? arr.filter(x => x !== val) : [...arr, val] };
  });

  const filtered = useMemo(() => {
    let list = PRODUCTS.filter(p => {
      if (cat && cat !== "all" && !p.cat.includes(cat)) return false;
      if (filters.metal.length && !filters.metal.some(m => p.metal.includes(m.split(" ")[0]))) return false;
      if (filters.occasion.length && !filters.occasion.includes(p.occasion)) return false;
      if (filters.craft.length && !filters.craft.some(c => p.type.includes(c))) return false;
      if (filters.weight.length) {
        const w = p.weight;
        const ok = filters.weight.some(b => (b === "Under 20g" ? w < 20 : b === "20–50g" ? w >= 20 && w <= 50 : w > 50));
        if (!ok) return false;
      }
      if (quickFilter === "new" && !p.isNew) return false;
      if (quickFilter === "bestsellers" && !p.best) return false;
      if (quickFilter === "polki" && !p.type.includes("Polki") && !p.metal.includes("Kundan")) return false;
      if (quickFilter === "diamond" && !p.cat.includes("diamond")) return false;
      if (quickFilter === "under-50g" && p.weight >= 50) return false;
      if (quickFilter === "bridal" && !p.cat.includes("bridal")) return false;
      return true;
    });
    if (sort === "new") list = [...list].sort((a, b) => (b.isNew ? 1 : 0) - (a.isNew ? 1 : 0));
    if (sort === "weight-asc") list = [...list].sort((a, b) => a.weight - b.weight);
    if (sort === "weight-desc") list = [...list].sort((a, b) => b.weight - a.weight);
    return list;
  }, [cat, filters, quickFilter, sort]);

  return (
    <div data-screen-label="Collections">
      <AnnouncementBar/>
      <Header active={cat}/>
      <main>
        <CatHero cat={cat} count={filtered.length}/>
        <Toolbar
          active={quickFilter} onChange={setQuickFilter}
          sort={sort} setSort={setSort}
          view={view} setView={setView}
          total={filtered.length}/>

        <section style={{ padding: "48px 0 120px" }}>
          <div className="wrap grid-collections">
            {/* Mobile filter toggle */}
            <button onClick={() => setMobileFiltersOpen(true)} className="show-mobile-block" style={{
              cursor: "pointer", padding: "12px 18px",
              border: "1px solid var(--brand)", background: "transparent", color: "var(--brand)",
              fontSize: 11, letterSpacing: ".22em", textTransform: "uppercase",
              textAlign: "center", marginBottom: 8,
              fontFamily: "var(--font-body)",
              order: -1,
            }}>⚯ Filter & Refine</button>
            {/* Sidebar */}
            <aside className={mobileFiltersOpen ? "filters-open" : "filters-closed"}>
              {/* Mobile close button */}
              <button onClick={() => setMobileFiltersOpen(false)} className="show-mobile-flex filter-close" style={{
                all: "unset", cursor: "pointer",
                position: "absolute", right: 16, top: 16,
                width: 36, height: 36, fontSize: 20,
                alignItems: "center", justifyContent: "center",
                color: "var(--fg)", zIndex: 2,
              }}>×</button>
              <div style={{ position: "sticky", top: 230 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24 }}>
                  <span className="display" style={{ fontSize: 22 }}>Refine</span>
                  <button onClick={() => setFilters({ metal: [], occasion: [], weight: [], craft: [] })} style={{
                    all: "unset", fontSize: 10, color: "var(--brand)", letterSpacing: ".2em", textTransform: "uppercase", cursor: "pointer",
                  }}>Clear</button>
                </div>
                <FilterGroup title="METAL" options={FILTERS.metal} value={filters.metal} onToggle={v => toggleFilter("metal", v)}/>
                <FilterGroup title="OCCASION" options={FILTERS.occasion} value={filters.occasion} onToggle={v => toggleFilter("occasion", v)}/>
                <FilterGroup title="WEIGHT" options={FILTERS.weight} value={filters.weight} onToggle={v => toggleFilter("weight", v)}/>
                <FilterGroup title="CRAFT" options={FILTERS.craft} value={filters.craft} onToggle={v => toggleFilter("craft", v)}/>

                <div style={{
                  marginTop: 16, padding: 20,
                  background: "var(--bg-alt)", borderRadius: 2,
                }}>
                  <div className="mono" style={{ fontSize: 9, color: "var(--brand)", marginBottom: 10 }}>◇ NEED HELP DECIDING?</div>
                  <p style={{ fontSize: 12.5, lineHeight: 1.6, color: "var(--fg-soft)", margin: 0 }}>
                    Book a private viewing — our stylists will pull pieces tailored to you.
                  </p>
                  <a href="index.html#appointment" style={{
                    marginTop: 12, display: "inline-block",
                    fontSize: 10, color: "var(--brand)",
                    letterSpacing: ".2em", textTransform: "uppercase",
                    borderBottom: "1px solid var(--brand)", paddingBottom: 2,
                    whiteSpace: "nowrap",
                  }}>Book a viewing →</a>
                </div>
              </div>
            </aside>

            {/* Grid */}
            <div>
              {/* Active filter pills */}
              {(Object.values(filters).flat().length > 0 || quickFilter) && (
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 28 }}>
                  <span className="mono" style={{ fontSize: 10, color: "var(--fg-soft)", alignSelf: "center" }}>FILTERED BY:</span>
                  {quickFilter && (
                    <button onClick={() => setQuickFilter(null)} style={{
                      all: "unset", padding: "4px 10px", background: "var(--brand)", color: "var(--ivory)",
                      fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase", borderRadius: 999, cursor: "pointer",
                    }}>{quickFilter} ✕</button>
                  )}
                  {Object.entries(filters).flatMap(([g, vals]) =>
                    vals.map(v => (
                      <button key={g + v} onClick={() => toggleFilter(g, v)} style={{
                        all: "unset", padding: "4px 10px", background: "var(--ink)", color: "var(--ivory)",
                        fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase", borderRadius: 999, cursor: "pointer",
                      }}>{v} ✕</button>
                    ))
                  )}
                </div>
              )}

              {filtered.length === 0 ? (
                <div style={{ padding: "80px 0", textAlign: "center" }}>
                  <div className="display" style={{ fontSize: 28, fontStyle: "italic", marginBottom: 10 }}>Nothing in this combination, yet.</div>
                  <div style={{ fontSize: 13, color: "var(--fg-soft)" }}>Try removing a filter, or commission a custom piece.</div>
                </div>
              ) : (
                <div className="grid-products" style={{ "--cols": view }}>
                  {filtered.slice(0, 6).map(p => (
                    <ProductCard key={p.id} p={p} onWish={toggleWish} wished={wishlist.has(p.id)}/>
                  ))}
                  {filtered.length > 6 && <EditorialBlock/>}
                  {filtered.slice(6).map(p => (
                    <ProductCard key={p.id} p={p} onWish={toggleWish} wished={wishlist.has(p.id)}/>
                  ))}
                </div>
              )}
            </div>
          </div>
        </section>

        {/* Related categories */}
        <section style={{ padding: "60px 0 120px", borderTop: "1px solid var(--line)", background: "var(--bg-alt)" }}>
          <div className="wrap">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 36 }}>
              <h3 className="display" style={{ fontSize: 36, margin: 0 }}>
                Continue browsing <span style={{ fontStyle: "italic", color: "var(--accent)" }}>by craft</span>.
              </h3>
            </div>
            <div className="grid-related">
              {[
                { name: "Polki",     desc: "Uncut diamonds",  v: "gold",    img: IMG.featRaniHaar },
                { name: "Jadau",     desc: "Setting craft",   v: "emerald", img: IMG.craftHand },
                { name: "Meenakari", desc: "Enamel work",     v: "",        img: IMG.featKangan },
                { name: "Temple",    desc: "South heritage",  v: "ink",     img: IMG.matTemple },
              ].map((c, i) => (
                <a key={i} href={`collections.html?craft=${c.name.toLowerCase()}`}>
                  <Ph variant={c.v} src={c.img} style={{ aspectRatio: "1/1" }} tag={`c / ${i+1}`}>
                    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", justifyContent: "flex-end", padding: 18, background: "linear-gradient(180deg, transparent 50%, rgba(0,0,0,.6) 100%)" }}>
                      <div className="display" style={{ fontSize: 24, color: "var(--ivory)", fontStyle: "italic" }}>{c.name}</div>
                      <div className="mono" style={{ fontSize: 9.5, color: "var(--metal-soft)", marginTop: 4 }}>{c.desc}</div>
                    </div>
                  </Ph>
                </a>
              ))}
            </div>
          </div>
        </section>
      </main>
      <Footer/>
      <SunehraTweaks/>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
