"use client";

export type CartItem = {
  listingId: string;
  variantId: string;
  quantity: number;
};

const CART_KEY = "shop_local_cart";
const FAVORITES_KEY = "shop_local_favorites";

function readJson<T>(key: string, fallback: T): T {
  if (typeof window === "undefined") return fallback;
  try {
    const raw = localStorage.getItem(key);
    return raw ? (JSON.parse(raw) as T) : fallback;
  } catch {
    return fallback;
  }
}

function writeJson<T>(key: string, value: T): void {
  if (typeof window === "undefined") return;
  localStorage.setItem(key, JSON.stringify(value));
}

export function getCart(): CartItem[] {
  return readJson<CartItem[]>(CART_KEY, []);
}

export function addToCart(listingId: string, variantId: string, quantity = 1): void {
  const cart = getCart();
  const existing = cart.find(
    (item) => item.listingId === listingId && item.variantId === variantId
  );
  if (existing) {
    existing.quantity += quantity;
  } else {
    cart.push({ listingId, variantId, quantity });
  }
  writeJson(CART_KEY, cart);
}

export function getFavorites(): string[] {
  return readJson<string[]>(FAVORITES_KEY, []);
}

export function isFavorite(listingId: string): boolean {
  return getFavorites().includes(listingId);
}

export function toggleFavorite(listingId: string): boolean {
  const favorites = getFavorites();
  const idx = favorites.indexOf(listingId);
  if (idx >= 0) {
    favorites.splice(idx, 1);
    writeJson(FAVORITES_KEY, favorites);
    return false;
  }
  favorites.push(listingId);
  writeJson(FAVORITES_KEY, favorites);
  return true;
}
