"use client"

export interface CartItem {
  id: string
  name: string
  price: number
  size: string
  image: string
  quantity: number
}

const STORAGE_KEY = "valabel-cart"
const EVENT = "cart-updated"

let cachedRaw: string | null = null
let cachedItems: CartItem[] = []

function readCart(): CartItem[] {
  if (typeof window === "undefined") return []
  const raw = localStorage.getItem(STORAGE_KEY)
  if (raw === cachedRaw) return cachedItems
  cachedRaw = raw
  try {
    cachedItems = raw ? JSON.parse(raw) : []
  } catch {
    cachedItems = []
  }
  return cachedItems
}

function writeCart(items: CartItem[]) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
  window.dispatchEvent(new Event(EVENT))
}

export const cartStore = {
  getSnapshot: readCart,
  getServerSnapshot: (): CartItem[] => [],

  subscribe(callback: () => void) {
    window.addEventListener(EVENT, callback)
    window.addEventListener("storage", callback)
    return () => {
      window.removeEventListener(EVENT, callback)
      window.removeEventListener("storage", callback)
    }
  },

  add(item: Omit<CartItem, "quantity">) {
    const items = [...readCart()]
    const idx = items.findIndex((i) => i.id === item.id && i.size === item.size)
    if (idx >= 0) {
      items[idx] = { ...items[idx], quantity: items[idx].quantity + 1 }
    } else {
      items.push({ ...item, quantity: 1 })
    }
    writeCart(items)
  },

  remove(id: string, size: string) {
    writeCart(readCart().filter((i) => !(i.id === id && i.size === size)))
  },

  updateQty(id: string, size: string, quantity: number) {
    if (quantity < 1) return cartStore.remove(id, size)
    writeCart(
      readCart().map((i) =>
        i.id === id && i.size === size ? { ...i, quantity } : i
      )
    )
  },

  clear() {
    writeCart([])
  },
}
