/* Relay — Catalog screen */
function CatalogScreen() {
  const { CATALOG } = window.RelayData;
  const [items, setItems] = React.useState(() => CATALOG.map((c) => ({ ...c })));
  const [type, setType] = React.useState("food");
  const [cat, setCat] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const [view, setView] = React.useState("grid");

  const categories = React.useMemo(() => {
    const set = new Set(items.filter((i) => i.type === type).map((i) => i.category));
    return ["all", ...[...set].sort()];
  }, [items, type]);

  React.useEffect(() => { setCat("all"); }, [type]);

  const shown = items.filter((i) => i.type === type && (cat === "all" || i.category === cat) &&
    (!search.trim() || (i.name + " " + i.sku).toLowerCase().includes(search.trim().toLowerCase())));

  const toggleAvail = (id) => setItems((prev) => prev.map((i) => i.id === id ? { ...i, available: !i.available } : i));
  const available = items.filter((i) => i.type === type && i.available).length;
  const total = items.filter((i) => i.type === type).length;

  return (
    <Scroller>
      <PageHeader title="Katalog" icon={<I.catalog size={18} />} subtitle="Tüm kanallarda ve POS'ta satışı yapılabilir ürünler.">
        <Btn kind="primary"><I.plus size={15} />Ürün ekle</Btn>
      </PageHeader>

      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
        <Segmented options={[{ id: "food", label: "Yemek menüsü" }, { id: "retail", label: "Perakende ürünler" }]} value={type} onChange={setType} />
        <div style={{ position: "relative" }}>
          <span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", color: "var(--text-3)" }}><I.search size={15} /></span>
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Katalogda ara…" style={{ padding: "8px 12px 8px 34px", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)", background: "var(--surface)", fontSize: 13, width: 200, outline: "none" }} />
        </div>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12.5, color: "var(--text-3)" }}><b style={{ color: "var(--ready)" }}>{available}</b> / {total} kullanılabilir</span>
        <Segmented size="sm" options={[{ id: "grid", label: "Izgara", icon: <I.grid size={13} /> }, { id: "list", label: "Liste", icon: <I.list size={13} /> }]} value={view} onChange={setView} />
      </div>

      {/* category chips */}
      <div style={{ display: "flex", gap: 7, marginBottom: 18, flexWrap: "wrap" }}>
        {categories.map((c) => (
          <button key={c} onClick={() => setCat(c)} style={{
            padding: "6px 13px", fontSize: 12.5, fontWeight: 600, borderRadius: 999,
            border: "1px solid " + (cat === c ? "var(--graphite)" : "var(--border)"),
            background: cat === c ? "var(--graphite)" : "var(--surface)", color: cat === c ? "#fff" : "var(--text-2)",
            textTransform: c === "all" ? "none" : "none", whiteSpace: "nowrap",
          }}>{c === "all" ? "Tüm kategoriler" : c}</button>
        ))}
      </div>

      {view === "grid" ? (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(230px, 1fr))", gap: 14 }}>
          {shown.map((it) => (
            <div key={it.id} style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)", padding: 15, boxShadow: "var(--shadow-sm)", opacity: it.available ? 1 : 0.62, display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
                <span style={{ fontSize: 10.5, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".04em", background: "var(--surface-3)", padding: "3px 8px", borderRadius: 5 }}>{it.category}</span>
                <TypeIcon type={it.type} size={15} />
              </div>
              <div style={{ fontWeight: 600, fontSize: 14.5, lineHeight: 1.25, minHeight: 36 }}>{it.name}</div>
              <div className="mono" style={{ fontSize: 11.5, color: "var(--text-3)" }}>{it.sku}{it.type === "retail" && it.stock != null ? ` · ${it.stock} stokta` : ""}</div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 2 }}>
                <span className="mono" style={{ fontSize: 17, fontWeight: 600 }}>AED {it.price}</span>
                <AvailToggle on={it.available} onClick={() => toggleAvail(it.id)} />
              </div>
            </div>
          ))}
          {shown.length === 0 && <div style={{ gridColumn: "1/-1", textAlign: "center", color: "var(--text-3)", padding: "40px", fontSize: 13.5 }}>Ürün bulunamadı.</div>}
        </div>
      ) : (
        <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)", overflow: "hidden", boxShadow: "var(--shadow-sm)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 150px 120px 110px 100px", gap: 12, padding: "11px 18px", borderBottom: "1px solid var(--border)", background: "var(--surface-2)", fontSize: 10.5, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".05em" }}>
            <span>Ürün</span><span>Kategori</span><span>SKU</span><span style={{ textAlign: "right" }}>Fiyat</span><span style={{ textAlign: "right" }}>Kullanılabilirlik</span>
          </div>
          {shown.map((it) => (
            <div key={it.id} style={{ display: "grid", gridTemplateColumns: "1fr 150px 120px 110px 100px", gap: 12, padding: "11px 18px", borderBottom: "1px solid var(--border)", alignItems: "center", opacity: it.available ? 1 : 0.6 }}>
              <span style={{ fontWeight: 600, fontSize: 13.5, display: "flex", alignItems: "center", gap: 8 }}><TypeIcon type={it.type} size={13} />{it.name}</span>
              <span style={{ fontSize: 12.5, color: "var(--text-2)" }}>{it.category}</span>
              <span className="mono" style={{ fontSize: 12, color: "var(--text-3)" }}>{it.sku}</span>
              <span className="mono" style={{ textAlign: "right", fontSize: 14, fontWeight: 600 }}>AED {it.price}</span>
              <span style={{ display: "flex", justifyContent: "flex-end" }}><AvailToggle on={it.available} onClick={() => toggleAvail(it.id)} /></span>
            </div>
          ))}
          {shown.length === 0 && <div style={{ textAlign: "center", color: "var(--text-3)", padding: "40px", fontSize: 13.5 }}>Ürün bulunamadı.</div>}
        </div>
      )}
    </Scroller>
  );
}

function AvailToggle({ on, onClick }) {
  return (
    <button onClick={onClick} title={on ? "Kullanılabilir" : "Gizli"} style={{
      width: 40, height: 23, borderRadius: 999, border: "none", padding: 2,
      background: on ? "var(--ready)" : "var(--border-strong)", display: "flex",
      justifyContent: on ? "flex-end" : "flex-start", transition: "all .15s", cursor: "pointer",
    }}>
      <span style={{ width: 19, height: 19, borderRadius: 999, background: "#fff", boxShadow: "0 1px 2px rgba(0,0,0,.2)" }} />
    </button>
  );
}

Object.assign(window, { CatalogScreen });
