// products-page.jsx — tüm ürünleri listeleyen ayrı katalog sayfası (header'daki
// "Ürünler" linki artık anasayfadaki bölüme kaymak yerine buraya yönlendirir)
const { useState: useStateAllP, useEffect: useEffectAllP } = React;

function AllProductCard({ p, orient, lang }) {
  const imgUrl = p.imagePath ? productImageUrl(p.imagePath) : null;
  const soldOut = (p.stock || 0) <= 0;
  // Dikey fotoğraflar 3:4, yataylar 4:3 ortak kutuda gösterilir; gruplar
  // sıralamada bir arada tutulduğu için satırlar hizalı kalır.
  const aspect = orient === "portrait" ? "aspect-[3/4]" : "aspect-[4/3]";
  return (
    <a href={`/urun/${p.slug}`} className="group block">
      <div className={`relative overflow-hidden rounded-[18px] w-full ${aspect}`}>
        {imgUrl
          ? <img src={imgUrl} alt={p.label} loading="lazy" className={`absolute inset-0 w-full h-full object-cover transition-transform duration-[1100ms] ease-out group-hover:scale-[1.06] ${soldOut ? "blur-[3px] grayscale-[35%]" : ""}`} />
          : <Placeholder label={p.label} tone={p.tone} rounded="rounded-[18px]"
              className="absolute inset-0 transition-transform duration-[1100ms] ease-out group-hover:scale-[1.06]" />}
        {soldOut && (
          <span className="absolute inset-0 flex items-center justify-center" style={{ backgroundColor: "rgba(250,247,242,0.30)" }}>
            <span className="rounded-full px-5 py-2 text-cream" style={{ backgroundColor: "rgba(45,55,72,0.85)", fontSize: 13.5, fontWeight: 600, letterSpacing: "0.04em" }}>
              {lang === "en" ? "Sold out" : "Tükendi"}
            </span>
          </span>
        )}
      </div>
      <div className="flex items-end justify-between gap-3 pt-4">
        <div>
          <h3 className="font-serif text-ink" style={{ fontSize: 20, lineHeight: 1.15 }}>{p.name}</h3>
          <p className="text-ink/55 mt-1" style={{ fontSize: 13 }}>{p.price} · {p.meta}</p>
        </div>
        <span className="shrink-0 flex items-center justify-center rounded-full text-ink transition-all duration-400"
          style={{ width: 38, height: 38, border: "1px solid rgba(45,55,72,0.16)" }}>
          <Icon name="arrowUpRight" size={16} className="transition-transform duration-400 group-hover:rotate-45" />
        </span>
      </div>
    </a>
  );
}

function AllProductsPage({ lang, setLang }) {
  const c = window.CONTENT[lang];
  const [items, setItems] = useStateAllP(null); // null = yükleniyor
  const [search, setSearch] = useStateAllP("");
  const [catFilter, setCatFilter] = useStateAllP("all");
  const [orients, setOrients] = useStateAllP({}); // slug -> "portrait" | "landscape"

  useEffectAllP(() => {
    let cancelled = false;
    fetchCatalog(lang).then((list) => { if (!cancelled) setItems(list); });
    window.scrollTo(0, 0);
    return () => { cancelled = true; };
  }, [lang]);

  // Fotoğraf yönünü (dikey/yatay) ölçüp ürünleri gruplamak için önden yükle
  useEffectAllP(() => {
    if (!items) return;
    items.forEach((p) => {
      const url = p.imagePath ? productImageUrl(p.imagePath) : null;
      if (!url) return;
      const im = new Image();
      im.onload = () => setOrients((o) => (o[p.slug] ? o : { ...o, [p.slug]: im.naturalHeight >= im.naturalWidth ? "portrait" : "landscape" }));
      im.src = url;
    });
  }, [items]);

  const categories = Array.from(new Set((items || []).map((p) => p.cat).filter(Boolean)));
  const visible = (items || []).filter((p) => {
    const matchesSearch = !search.trim() || p.name.toLowerCase().includes(search.trim().toLowerCase());
    const matchesCat = catFilter === "all" || p.cat === catFilter;
    return matchesSearch && matchesCat;
  });
  // Dikey fotoğraflılar önce, yataylar sonra; grup içinde mevcut sıra korunur
  const orientRank = (p) => (orients[p.slug] === "portrait" ? 0 : orients[p.slug] === "landscape" ? 1 : 2);
  const grouped = [...visible].sort((a, b) => orientRank(a) - orientRank(b));

  return (
    <div style={{ backgroundColor: "#faf7f2" }}>
      <Nav c={c} lang={lang} setLang={setLang} />
      <main className="pt-[110px] lg:pt-[128px]">
        <section className="mx-auto max-w-[1240px] px-6 lg:px-10 pb-6">
          <nav className="flex items-center gap-2 text-ink/45" style={{ fontSize: 13 }}>
            <a href="/" className="hover:text-ink transition-colors">{c.pdp.home}</a>
            <span>/</span>
            <span className="text-ink/70">{c.pdp.productsCrumb}</span>
          </nav>
          <Eyebrow className="mt-8">{c.products.eyebrow}</Eyebrow>
          <h1 className="font-serif text-ink mt-5" style={{ fontSize: "clamp(30px,4vw,52px)", lineHeight: 1.08, letterSpacing: "-0.01em" }}>
            {c.products.title}
          </h1>
          <p className="text-ink/60 mt-4 max-w-xl" style={{ fontSize: 15, lineHeight: 1.7 }}>{c.products.sub}</p>
        </section>

        <section className="mx-auto max-w-[1240px] px-6 lg:px-10 pb-8">
          <div className="flex flex-wrap items-center gap-3">
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={lang === "tr" ? "Ürün ara…" : "Search products…"}
              className="rounded-full px-5 py-2.5 flex-1 min-w-[200px]"
              style={{ border: "1px solid rgba(45,55,72,0.16)", fontSize: 14 }}
            />
            {categories.length > 1 && (
              <select value={catFilter} onChange={(e) => setCatFilter(e.target.value)}
                className="rounded-full px-4 py-2.5" style={{ border: "1px solid rgba(45,55,72,0.16)", fontSize: 14 }}>
                <option value="all">{lang === "tr" ? "Tüm kategoriler" : "All categories"}</option>
                {categories.map((cat) => <option key={cat} value={cat}>{cat}</option>)}
              </select>
            )}
          </div>
        </section>

        <section className="mx-auto max-w-[1240px] px-6 lg:px-10 pb-28">
          {items === null && (
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-7">
              {["rose", "sage", "cream", "rose", "sage", "cream"].map((tone, i) => (
                <Placeholder key={i} label="" tone={tone} rounded="rounded-[18px]" className="aspect-[4/3] w-full" />
              ))}
            </div>
          )}
          {items && visible.length === 0 && (
            <p className="text-ink/50" style={{ fontSize: 15 }}>{lang === "tr" ? "Eşleşen ürün bulunamadı." : "No matching products."}</p>
          )}
          {items && visible.length > 0 && (
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-7">
              {grouped.map((p) => <AllProductCard key={p.slug} p={p} orient={orients[p.slug]} lang={lang} />)}
            </div>
          )}
        </section>
      </main>
      <Footer c={c} />
    </div>
  );
}

Object.assign(window, { AllProductsPage });
