// data.jsx — runtime data loader for the storefront.
// Replaces the prototype's hardcoded constants with fetches against the backend.
// Static taxonomies (categories, fabrics) stay here because they're shared
// vocabulary, not editable per-season.

const CATEGORIES = ["OUTERWEAR", "TAILORING", "KNIT", "SHIRT", "TROUSER", "DRESS", "BAG", "FOOTWEAR"];
const FABRICS = ["WASHED WOOL", "RAW LINEN", "CASHMERE", "ORGANIC COTTON", "JAPANESE DENIM", "VEG-TAN LEATHER", "BOILED WOOL", "RAMIE", "RECYCLED NYLON", "SILK CDC"];

async function apiGet(path) {
  const res = await fetch(path, { credentials: "same-origin" });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: res.statusText }));
    throw Object.assign(new Error(err.error || `request failed: ${path}`), { status: res.status });
  }
  return res.json();
}

async function apiPost(path, body) {
  const res = await fetch(path, {
    method: "POST",
    credentials: "same-origin",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body || {}),
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw Object.assign(new Error(data.error || `request failed: ${path}`), { status: res.status });
  return data;
}

window.CATEGORIES = CATEGORIES;
window.FABRICS = FABRICS;
window.api = { get: apiGet, post: apiPost };

// ── Resized image URLs ──────────────────────────────────────────────────────
// Campaign masters are 3000px+; the server resizes on demand at /img/<w>/<file>
// (widths must match IMG_WIDTHS in server.js). sbImg picks one width, sbSrcSet
// emits the whole ladder for srcset + sizes. The ?v=mtime suffix rides along so
// replaced media still busts caches. Non-/uploads URLs pass through untouched.
const IMG_WIDTHS = [480, 800, 1200, 1600, 2000];
function sbImg(url, w) {
  if (!url || typeof url !== "string" || !url.startsWith("/uploads/")) return url;
  const q = url.indexOf("?");
  const rel = (q === -1 ? url : url.slice(0, q)).slice("/uploads/".length);
  return "/img/" + w + "/" + rel + (q === -1 ? "" : url.slice(q));
}
function sbSrcSet(url) {
  if (!url || typeof url !== "string" || !url.startsWith("/uploads/")) return undefined;
  return IMG_WIDTHS.map((w) => sbImg(url, w) + " " + w + "w").join(", ");
}
window.sbImg = sbImg;
window.sbSrcSet = sbSrcSet;

// Grid / Line layout toggle, shared by the collection grid and line sheet.
function ViewToggle({ layout, setLayout }) {
  return (
    <div className="view-toggle">
      <button className={"view-toggle-btn" + (layout === "grid" ? " is-active" : "")}
        onClick={() => setLayout("grid")}>GRID</button>
      <span className="view-toggle-sep">/</span>
      <button className={"view-toggle-btn" + (layout === "line" ? " is-active" : "")}
        onClick={() => setLayout("line")}>ROWS</button>
    </div>
  );
}
window.ViewToggle = ViewToggle;
