export type StoredCartItem = { productId: string; quantity: number };

export const CART_STORAGE_KEY = "elit_cart";
export const CART_UPDATE_EVENT = "cart:update";

function normalizeQuantity(quantity: unknown) {
  return Math.max(1, Math.floor(Number(quantity) || 1));
}

export function normalizeCartItems(value: unknown): StoredCartItem[] {
  if (!Array.isArray(value)) return [];

  const byProduct = new Map<string, number>();
  for (const item of value) {
    if (!item || typeof item !== "object") continue;
    const productId = "productId" in item ? item.productId : undefined;
    if (typeof productId !== "string" || !productId.trim()) continue;
    byProduct.set(productId, (byProduct.get(productId) || 0) + normalizeQuantity("quantity" in item ? item.quantity : 1));
  }

  return Array.from(byProduct, ([productId, quantity]) => ({ productId, quantity }));
}

export function readCartItems() {
  const raw = window.localStorage.getItem(CART_STORAGE_KEY);
  if (!raw) return [];

  try {
    const parsed = JSON.parse(raw);
    const items = normalizeCartItems(parsed);
    if (!items.length) {
      window.localStorage.removeItem(CART_STORAGE_KEY);
      return [];
    }

    if (JSON.stringify(parsed) !== JSON.stringify(items)) {
      window.localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(items));
    }
    return items;
  } catch {
    window.localStorage.removeItem(CART_STORAGE_KEY);
    return [];
  }
}

export function writeCartItems(items: StoredCartItem[]) {
  const normalized = normalizeCartItems(items);
  if (normalized.length) {
    window.localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(normalized));
  } else {
    window.localStorage.removeItem(CART_STORAGE_KEY);
  }
  window.dispatchEvent(new Event(CART_UPDATE_EVENT));
  return normalized;
}
