/* global React */
/* ============================================================
   RANCHO LA VEGA — carrito de compras (estado en localStorage)
   ============================================================ */
const { useState: useStateCart, useEffect: useEffectCart } = React;

const CART_KEY = "rlv_cart_v1";
const ALERTS_KEY = "rlv_alerts_v1";
const ORDERS_KEY = "rlv_orders_v1";

function readJSON(key, fallback) {
  try { const v = JSON.parse(localStorage.getItem(key)); return v || fallback; }
  catch (e) { return fallback; }
}
function writeJSON(key, val) {
  localStorage.setItem(key, JSON.stringify(val));
  window.dispatchEvent(new CustomEvent("rlv-store", { detail: { key } }));
}

/* ---------- Carrito ---------- */
function cartGet() { return readJSON(CART_KEY, []); }
function cartCount() { return cartGet().reduce((n, i) => n + (i.qty || 1), 0); }
function cartAdd(spec) {
  const cart = cartGet();
  const found = cart.find((i) => i.id === spec.id);
  if (found) { found.qty = (found.qty || 1) + 1; }
  else {
    cart.push({ id: spec.id, code: spec.code, line: spec.line, cat: spec.cat, price: spec.price, qty: 1 });
  }
  writeJSON(CART_KEY, cart);
}
function cartRemove(id) { writeJSON(CART_KEY, cartGet().filter((i) => i.id !== id)); }
function cartSetQty(id, qty) {
  const cart = cartGet();
  const it = cart.find((i) => i.id === id);
  if (it) { it.qty = Math.max(1, qty); writeJSON(CART_KEY, cart); }
}
function cartClear() { writeJSON(CART_KEY, []); }

/* ---------- Alertas de disponibilidad ("Notificarme") ---------- */
function alertsGet() { return readJSON(ALERTS_KEY, []); }
function alertToggle(spec) {
  const a = alertsGet();
  const i = a.indexOf(spec.id);
  if (i >= 0) a.splice(i, 1); else a.push(spec.id);
  writeJSON(ALERTS_KEY, a);
}
function hasAlert(id) { return alertsGet().includes(id); }

/* ---------- Pedidos generados ---------- */
function ordersGet() { return readJSON(ORDERS_KEY, []); }
function orderCreate(order) {
  const all = ordersGet();
  all.unshift(order);
  writeJSON(ORDERS_KEY, all);
}
function newFolio() {
  const n = Math.floor(1000 + Math.random() * 9000);
  const d = new Date();
  const ymd = "" + d.getFullYear() + String(d.getMonth() + 1).padStart(2, "0") + String(d.getDate()).padStart(2, "0");
  return "RLV-" + ymd + "-" + n;
}

/* Convierte "$10,000" → 10000 */
function priceNum(p) { return parseInt(String(p).replace(/[^0-9]/g, ""), 10) || 0; }
function money(n) { return "$" + n.toLocaleString("es-MX"); }

/* Hook que re-renderiza cuando cambia el store (carrito/alertas) */
function useStore() {
  const [, setTick] = useStateCart(0);
  useEffectCart(() => {
    const on = () => setTick((t) => t + 1);
    window.addEventListener("rlv-store", on);
    window.addEventListener("storage", on);
    return () => { window.removeEventListener("rlv-store", on); window.removeEventListener("storage", on); };
  }, []);
}

Object.assign(window, {
  cartGet, cartCount, cartAdd, cartRemove, cartSetQty, cartClear,
  alertsGet, alertToggle, hasAlert,
  ordersGet, orderCreate, newFolio,
  priceNum, money, useStore,
});
