# Cart (storefront)

Cart UI, session identity, and mutations. See `docs/cart-ui-implementation-plan.md` and `docs/add-to-cart-implementation-plan.md`.

## Session and identity

- **`useCartSessionId()`** — Returns the guest session id (cookie) or `undefined` for authenticated users. Use this as the single source of identity for cart.
- Use the same `sessionId` with `useCart()` and `useCartMutations(sessionId)` so guest and auth stay consistent.

## Mutations: `useCartMutations(sessionId)`

Returns `{ addItem, updateItem, removeItem, clear }`.

### addItem (Add-to-Cart API)

- **Signature:** `addItem(variantId: Id<"productVariants"> | string, quantity: number): Promise<unknown>`
- **Usage:** `const { addItem } = useCartMutations(useCartSessionId()); addItem(variantId, quantity)`
- **Validation:** Quantity is validated client-side (≥ 1) before calling the backend; backend enforces stock and variant availability.
- **Loading and error (Phase 0.2):** `addItem` returns a **Promise**. Callers (e.g. PDP, product grid) should:
  - Use the promise to drive loading state (e.g. set loading true before the call, false in `.then()`/`.catch()`).
  - Use `.catch()` to show errors (e.g. "Insufficient stock", "Variant not found").
- No dedicated `useAddToCart` hook; the promise-based API keeps one mutation hook and lets each entry point manage its own loading/error state.

## PDP add-to-cart (Phase 1)

- **Entry point:** `ProductDetailHeroSection` — "Add to cart" calls `addItem(selectedVariant._id, quantity)` with loading and error state; on success calls `openCart()` from `useCartUI()` so the cart drawer (lg+) or bottom sheet (&lt; lg) opens. Choice: **always open cart after add**; can be made configurable (e.g. per product or A/B) later.

## Analytics (Phase 4)

- **`trackAddToCart({ variantId, quantity, source })`** in `lib/cart/analytics.ts` — Placeholder for "add_to_cart" events. No-op by default.
- **Where to fire:** After a successful `addItem()`:
  - **PDP:** In `ProductDetailHeroSection`, inside the `addItem(...).then()` callback, call `trackAddToCart({ variantId: selectedVariant._id, quantity, source: "pdp" })`.
  - **Grid:** In `ProductCard` / `ProductListTile`, inside the `addItem(...).then()` callback (when grid add-to-cart is implemented), call `trackAddToCart({ variantId, quantity: 1, source: "grid" })`.
