// page_collection.jsx — collection index + filtering

function PageCollection() {
  const { params, go } = useRouter();
  const lang = useLang();
  const [activeCol, setActiveCol] = React.useState(params.id || "all");
  const [activeCat, setActiveCat] = React.useState("all");
  const [sort, setSort] = React.useState("featured");

  React.useEffect(() => {
    if (params.id && params.id !== activeCol) setActiveCol(params.id);
  }, [params.id]);

  const filtered = React.useMemo(() => {
    let arr = PRODUCTS.slice();
    if (activeCol !== "all") arr = arr.filter(p => p.collection === activeCol);
    if (activeCat !== "all") arr = arr.filter(p => p.categoryEn.toLowerCase().includes(activeCat));
    if (sort === "price-asc") arr.sort((a, b) => a.price - b.price);
    else if (sort === "price-desc") arr.sort((a, b) => b.price - a.price);
    else arr.sort((a, b) => (b.featured ? 1 : 0) - (a.featured ? 1 : 0));
    return arr;
  }, [activeCol, activeCat, sort]);

  const currentCol = COLLECTIONS.find(c => c.id === activeCol);

  return (
    <main style={{ background: "var(--off-white)", minHeight: "100vh" }}>
      {/* Hero header */}
      <section style={{
        padding: "100px 40px 80px",
        background: activeCol === "yoru" || activeCol === "kotodama" ? "var(--urushi)" : "var(--pearl-100)",
        color: (activeCol === "yoru" || activeCol === "kotodama") ? "#F8F5F0" : "#0C0C0C",
        transition: "background 600ms, color 600ms",
      }}>
        <div style={{ maxWidth: 1400, margin: "0 auto", textAlign: "center" }}>
          <div className="hoshi-eyebrow" style={{ color: "inherit", opacity: 0.7 }}>
            {lang === "ja" ? "コレクション" : "Collection"}
          </div>
          <h1 style={{
            fontFamily: "var(--serif-display)",
            fontSize: "clamp(56px, 7vw, 120px)",
            fontWeight: 400,
            lineHeight: 1.0,
            letterSpacing: "-0.01em",
            margin: "20px 0 0",
          }}>
            {currentCol
              ? (lang === "ja"
                  ? <><span style={{ fontFamily: "var(--serif-jp)", fontWeight: 300 }}>{currentCol.nameJa.split("—")[0].trim()}</span> <em style={{ fontStyle: "italic", opacity: 0.7 }}>— {currentCol.nameEn}</em></>
                  : <><em style={{ fontStyle: "italic" }}>{currentCol.nameEn}</em></>)
              : (lang === "ja" ? "すべての章" : "All Chapters")
            }
          </h1>
          {currentCol && (
            <p style={{
              marginTop: 36,
              fontFamily: "var(--serif-jp)",
              fontSize: 15,
              lineHeight: 2.0,
              maxWidth: 620,
              margin: "36px auto 0",
              opacity: 0.85,
              fontWeight: 300,
            }}>
              {lang === "ja" ? currentCol.descJa : currentCol.descEn}
            </p>
          )}
        </div>
      </section>

      {/* Filter bar */}
      <section style={{ padding: "40px 40px", borderBottom: "1px solid rgba(12,12,12,0.08)", position: "sticky", top: 108, background: "rgba(248,245,240,0.96)", backdropFilter: "blur(10px)", zIndex: 20 }}>
        <div style={{ maxWidth: 1400, margin: "0 auto", display: "flex", gap: 40, alignItems: "center", justifyContent: "space-between", flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 28, flexWrap: "wrap" }}>
            <FilterBtn active={activeCol === "all"} onClick={() => setActiveCol("all")}>
              {lang === "ja" ? "すべて" : "All"}
            </FilterBtn>
            {COLLECTIONS.map(c => (
              <FilterBtn key={c.id} active={activeCol === c.id} onClick={() => setActiveCol(c.id)}>
                {lang === "ja" ? c.nameJa.split("—")[0].trim() : c.nameEn}
              </FilterBtn>
            ))}
          </div>
          <div style={{ display: "flex", gap: 28, alignItems: "center" }}>
            {["all", "necklace", "ring", "earring", "bracelet"].map(cat => (
              <FilterBtn key={cat} active={activeCat === cat} onClick={() => setActiveCat(cat)} small>
                {cat === "all" ? (lang === "ja" ? "全種類" : "All") : cat.charAt(0).toUpperCase() + cat.slice(1)}
              </FilterBtn>
            ))}
            <select value={sort} onChange={e => setSort(e.target.value)} style={{
              fontFamily: "var(--sans)",
              fontSize: 10,
              letterSpacing: "0.28em",
              textTransform: "uppercase",
              background: "transparent",
              border: "1px solid rgba(12,12,12,0.15)",
              padding: "10px 16px",
              color: "#0C0C0C",
            }}>
              <option value="featured">{lang === "ja" ? "おすすめ順" : "Featured"}</option>
              <option value="price-asc">{lang === "ja" ? "価格: 低→高" : "Price ↑"}</option>
              <option value="price-desc">{lang === "ja" ? "価格: 高→低" : "Price ↓"}</option>
            </select>
          </div>
        </div>
      </section>

      {/* Grid */}
      <section style={{ padding: "80px 40px 160px" }}>
        <div style={{ maxWidth: 1400, margin: "0 auto" }}>
          <div style={{ fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.3em", textTransform: "uppercase", color: "#8A8378", marginBottom: 40 }}>
            {filtered.length} {lang === "ja" ? "点" : "pieces"}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 60, rowGap: 80 }}>
            {filtered.map(p => (
              <article key={p.id}>
                <ProductThumb product={p} onClick={() => go("pdp", p.id)} />
                <div style={{ marginTop: 24 }}>
                  <div className="hoshi-eyebrow">{lang === "ja" ? p.categoryJa : p.categoryEn} · {p.id}</div>
                  <h3 style={{ fontFamily: "var(--serif-jp)", fontWeight: 300, fontSize: 22, letterSpacing: "0.02em", margin: "10px 0 4px" }}>
                    {lang === "ja" ? p.nameJa : p.nameEn}
                  </h3>
                  <div style={{ fontFamily: "var(--serif-display)", fontStyle: "italic", fontSize: 16, color: "#5E5851" }}>
                    {formatPrice(p, lang)}
                  </div>
                </div>
              </article>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

function FilterBtn({ active, onClick, children, small }) {
  return (
    <button onClick={onClick} style={{
      fontFamily: "var(--sans)",
      fontSize: small ? 10 : 11,
      letterSpacing: "0.3em",
      textTransform: "uppercase",
      padding: "6px 0",
      borderBottom: active ? "1px solid #0C0C0C" : "1px solid transparent",
      color: active ? "#0C0C0C" : "rgba(12,12,12,0.55)",
      transition: "all 200ms",
    }}>{children}</button>
  );
}

window.PageCollection = PageCollection;
