/* Shared merch cart — used by desktop (src/) and mobile (mobile/) */
const MERCH_SIZES = ["YS", "YM", "YL", "S", "M", "L", "XL", "2XL"];
const MERCH_COLOR_NAMES = { "#0a0a0a": "Black", "#f4f1ea": "White", "var(--c-red)": "Red" };
const MERCH_CART_KEY = "ll_merch_cart";
const merchNeedsSize = (p) => p.key !== "bottle";
const merchColorChoices = (p) => (p.key === "pinnie" ? [] : p.colors);
const merchMoney = (n) => "$" + (Number.isInteger(n) ? n : n.toFixed(2));

function merchReadCart() {
  try { const c = JSON.parse(localStorage.getItem(MERCH_CART_KEY)); return Array.isArray(c) ? c : []; } catch (e) { return []; }
}

function useMerchCart(products) {
  const [cart, setCart] = React.useState(merchReadCart);
  React.useEffect(() => {
    const h = () => setCart(merchReadCart());
    window.addEventListener("ll-cart", h); window.addEventListener("storage", h);
    return () => { window.removeEventListener("ll-cart", h); window.removeEventListener("storage", h); };
  }, []);
  const save = (next) => {
    try { localStorage.setItem(MERCH_CART_KEY, JSON.stringify(next)); } catch (e) {}
    setCart(next); window.dispatchEvent(new Event("ll-cart"));
  };
  const add = ({ key, size, color, qty = 1 }) => {
    const cur = merchReadCart();
    const id = [key, size || "", color || ""].join("|");
    const hit = cur.find((l) => l.id === id);
    save(hit ? cur.map((l) => l.id === id ? { ...l, qty: l.qty + qty } : l) : [...cur, { id, key, size, color, qty }]);
  };
  const setQty = (id, qty) => save(qty <= 0 ? merchReadCart().filter((l) => l.id !== id) : merchReadCart().map((l) => l.id === id ? { ...l, qty } : l));
  const clear = () => save([]);
  const lines = cart.map((l) => ({ ...l, product: products.find((p) => p.key === l.key) })).filter((l) => l.product);
  const count = lines.reduce((s, l) => s + l.qty, 0);
  const total = lines.reduce((s, l) => s + l.qty * l.product.price, 0);
  return { lines, count, total, add, setQty, clear };
}

function merchLineLabel(l) {
  return [l.size, l.color ? MERCH_COLOR_NAMES[l.color] || l.color : null].filter(Boolean).join(" · ");
}

async function submitMerchOrder(d, lines, total, source) {
  const items = lines.map((l) => `${l.qty} × ${l.product.name}${merchLineLabel(l) ? " (" + merchLineLabel(l) + ")" : ""} — ${merchMoney(l.qty * l.product.price)}`).join("\n");
  const res = await fetch("https://api.web3forms.com/submit", {
    method: "POST",
    headers: { "Content-Type": "application/json", Accept: "application/json" },
    body: JSON.stringify({
      access_key: "b8d90ff4-9ffd-422f-a59d-c0c2d5e120c6",
      subject: `[Merch Order] ${d.name} — ${lines.reduce((s, l) => s + l.qty, 0)} item(s) · ${merchMoney(total)}`,
      from_name: `London LOGIC Basketball — Merch Order (${source})`,
      replyto: d.email,
      "Name": d.name,
      "Email": d.email,
      "Phone": d.phone || "—",
      "Items": items,
      "Order Total": merchMoney(total) + " (invoice to be sent)",
      "Fulfillment": d.fulfillment === "delivery" ? "Free delivery (within London)" : "Pick up",
      "Delivery Address": d.fulfillment === "delivery" ? [d.street, d.city, d.postal].filter(Boolean).join(", ") : "N/A (pick up)",
      "Notes": d.notes || "—",
    }),
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok || !json.success) throw new Error(json.message || `Submission failed (${res.status})`);
}

Object.assign(window, { MERCH_SIZES, MERCH_COLOR_NAMES, merchNeedsSize, merchColorChoices, merchMoney, useMerchCart, merchLineLabel, submitMerchOrder });
