// Shopping cart — module-level store + React hook, persisted to localStorage.
// Pattern mirrors the rest of the app: everything attaches to window, no build step.

const CART_KEY = "onethird_cart_v1";

const cartStore = (() => {
  let items = [];
  try { items = JSON.parse(localStorage.getItem(CART_KEY) || "[]"); } catch { items = []; }
  const listeners = new Set();

  const persist = () => {
    try { localStorage.setItem(CART_KEY, JSON.stringify(items)); } catch {}
    listeners.forEach((l) => l());
  };

  return {
    subscribe(l) { listeners.add(l); return () => listeners.delete(l); },
    get() { return items; },
    add(product, qty = 1) {
      const ex = items.find((i) => i.id === product.id);
      if (ex) {
        items = items.map((i) => i.id === product.id ? { ...i, qty: i.qty + qty } : i);
      } else {
        items = [...items, {
          id: product.id, name: product.name, num: product.num,
          price: product.price, volume: product.volume, image: product.image || null, qty,
        }];
      }
      persist();
    },
    setQty(id, qty) {
      items = qty <= 0 ? items.filter((i) => i.id !== id) : items.map((i) => i.id === id ? { ...i, qty } : i);
      persist();
    },
    remove(id) { items = items.filter((i) => i.id !== id); persist(); },
    clear() { items = []; persist(); },
  };
})();

window.cartStore = cartStore;

// Hook — re-renders any component subscribed to the cart.
// Always resolves prices from current window.PRODUCTS + auth state so stale
// localStorage prices (or price changes) are automatically corrected.
function useCart() {
  const raw = React.useSyncExternalStore(cartStore.subscribe, cartStore.get, cartStore.get);
  const { user } = useAuth();

  const items = raw.map((it) => {
    const product = (window.PRODUCTS || []).find((p) => p.id === it.id);
    if (!product) return it;
    const price = user && product.memberPrice ? product.memberPrice : product.price;
    return { ...it, price };
  });

  const count = items.reduce((s, i) => s + i.qty, 0);
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  return {
    items, count, subtotal,
    add: cartStore.add, setQty: cartStore.setQty, remove: cartStore.remove, clear: cartStore.clear,
  };
}
window.useCart = useCart;

// Drawer open/close lives in its own tiny store so Nav + drawer share it.
const drawerStore = (() => {
  let open = false;
  const listeners = new Set();
  return {
    subscribe(l) { listeners.add(l); return () => listeners.delete(l); },
    get() { return open; },
    set(v) { open = v; document.body.style.overflow = v ? "hidden" : ""; listeners.forEach((l) => l()); },
  };
})();
function useCartDrawer() {
  const open = React.useSyncExternalStore(drawerStore.subscribe, drawerStore.get, drawerStore.get);
  return [open, drawerStore.set];
}
window.useCartDrawer = useCartDrawer;

// ── Cart button for the nav ──────────────────────────────────
const CartButton = ({ inverse = false }) => {
  const { count } = useCart();
  const [, setOpen] = useCartDrawer();
  return (
    <button
      onClick={() => setOpen(true)}
      className="mono"
      aria-label="Cart"
      style={{
        display: "inline-flex", alignItems: "center", gap: 8,
        fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase",
        color: "inherit", background: "transparent", border: 0, cursor: "pointer", padding: "4px 0",
      }}
    >
      Cart
      <span style={{
        minWidth: 18, height: 18, padding: "0 5px", borderRadius: 9,
        background: inverse ? "var(--cream)" : "var(--ink)",
        color: inverse ? "var(--ink)" : "var(--cream)",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        fontSize: 10, lineHeight: 1,
      }}>{count}</span>
    </button>
  );
};
window.CartButton = CartButton;

// ── Slide-over cart drawer ───────────────────────────────────
const CartDrawer = ({ navigate }) => {
  const { items, subtotal, setQty, remove } = useCart();
  const [open, setOpen] = useCartDrawer();

  const goCheckout = () => { setOpen(false); navigate("/checkout"); };

  return (
    <React.Fragment>
      {/* scrim */}
      <div
        onClick={() => setOpen(false)}
        style={{
          position: "fixed", inset: 0, zIndex: 60, background: "rgba(15,14,12,0.4)",
          opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity .3s ease",
        }}
      />
      <aside style={{
        position: "fixed", top: 0, right: 0, bottom: 0, width: "min(440px, 92vw)", zIndex: 61,
        background: "var(--cream)", borderLeft: "1px solid var(--hair-strong)",
        transform: open ? "translateX(0)" : "translateX(100%)", transition: "transform .35s cubic-bezier(.2,.6,.2,1)",
        display: "flex", flexDirection: "column",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "24px var(--pad-x)", borderBottom: "1px solid var(--hair)" }}>
          <span className="mono" style={{ fontSize: 11, letterSpacing: ".18em", textTransform: "uppercase" }}>Your cart</span>
          <button onClick={() => setOpen(false)} className="mono" style={{ fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", opacity: 0.6 }}>Close ✕</button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: "8px var(--pad-x)" }}>
          {items.length === 0 ? (
            <div style={{ padding: "60px 0", textAlign: "center" }}>
              <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 28, margin: 0 }}>Nothing here yet.</p>
              <button className="lnk" style={{ marginTop: 20 }} onClick={() => { setOpen(false); navigate("/products"); }}>Browse the six →</button>
            </div>
          ) : items.map((it) => (
            <div key={it.id} style={{ display: "flex", gap: 16, padding: "20px 0", borderBottom: "1px solid var(--hair)" }}>
              <div style={{ width: 64, flex: "0 0 64px" }}>
                {it.image
                  ? <img src={it.image} alt={it.name} style={{ width: 64, height: 80, objectFit: "cover" }} />
                  : <div className="ph" data-label="" style={{ width: 64, height: 80 }} />}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
                  <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 20, lineHeight: 1 }}>{it.name}</span>
                  <button onClick={() => remove(it.id)} className="mono" style={{ fontSize: 10, letterSpacing: ".12em", textTransform: "uppercase", opacity: 0.5 }}>Remove</button>
                </div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--ink-mute)", marginTop: 6 }}>{it.volume}</div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12 }}>
                  <div style={{ display: "inline-flex", alignItems: "center", border: "1px solid var(--hair-strong)" }}>
                    <button onClick={() => setQty(it.id, it.qty - 1)} style={{ padding: "4px 12px", fontFamily: "var(--mono)" }}>−</button>
                    <span className="mono" style={{ fontSize: 12, minWidth: 24, textAlign: "center" }}>{it.qty}</span>
                    <button onClick={() => setQty(it.id, it.qty + 1)} style={{ padding: "4px 12px", fontFamily: "var(--mono)" }}>+</button>
                  </div>
                  <span className="mono" style={{ fontSize: 12 }}>{formatIDR(it.price * it.qty)}</span>
                </div>
              </div>
            </div>
          ))}
        </div>

        {items.length > 0 && (
          <div style={{ padding: "24px var(--pad-x)", borderTop: "1px solid var(--hair-strong)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18 }}>
              <span className="mono" style={{ fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", opacity: 0.6 }}>Subtotal</span>
              <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 28 }}>{formatIDR(subtotal)}</span>
            </div>
            <p className="mono" style={{ fontSize: 10, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-mute)", margin: "0 0 16px" }}>Shipping calculated at checkout.</p>
            <button className="btn solid" style={{ width: "100%", justifyContent: "center" }} onClick={goCheckout}>
              Checkout <span className="arr">→</span>
            </button>
          </div>
        )}
      </aside>
    </React.Fragment>
  );
};
window.CartDrawer = CartDrawer;
