/**
 * @file 购物车管理（轻量，无 Vuex）
 * @description 提供添加、更新、删除、清空、查询购物车的函数。使用 localStorage 持久化。
 */

const STORAGE_KEY = 'power_leasing_cart_v1';

/**
 * @typedef {Object} CartItem
 * @property {string} id - 商品ID
 * @property {string} title - 商品标题
 * @property {number} price - 单价
 * @property {number} quantity - 数量
 * @property {string} image - 图片URL
 */

/**
 * 读取本地购物车
 * @returns {CartItem[]}
 */
export const readCart = () => {
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    return parsed.filter(Boolean);
  } catch (error) {
    console.error('[cartManager] readCart error:', error);
    return [];
  }
}

/**
 * 持久化购物车
 * @param {CartItem[]} cart
 */
const writeCart = (cart) => {
  try {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(cart));
    // 同步派发购物车更新事件（总数量），用于头部徽标等全局更新
    try {
      const count = cart.reduce((s, c) => s + Number(c.quantity || 0), 0)
      window.dispatchEvent(new CustomEvent('cart-updated', { detail: { count } }))
    } catch (e) { /* noop */ }
  } catch (error) {
    console.error('[cartManager] writeCart error:', error);
  }
}

/**
 * 添加到购物车（若已存在则数量累加）
 * @param {CartItem} item
 * @returns {CartItem[]}
 */
export const addToCart = (item) => {
  if (!item || !item.id) return readCart();
  const cart = readCart();
  const index = cart.findIndex((c) => c.id === item.id);
  if (index >= 0) {
    const next = [...cart];
    next[index] = {
      ...next[index],
      quantity: Math.max(1, Number(next[index].quantity || 0) + Number(item.quantity || 1))
    };
    writeCart(next);
    return next;
  }
  const next = [...cart, { ...item, quantity: Math.max(1, Number(item.quantity || 1)) }];
  writeCart(next);
  return next;
}

/**
 * 更新数量
 * @param {string} productId
 * @param {number} quantity
 * @returns {CartItem[]}
 */
export const updateQuantity = (productId, quantity) => {
  const cart = readCart();
  const next = cart
    .map((c) => (c.id === productId ? { ...c, quantity: Math.max(1, Number(quantity) || 1) } : c));
  writeCart(next);
  return next;
}

/**
 * 移除商品
 * @param {string} productId
 * @returns {CartItem[]}
 */
export const removeFromCart = (productId) => {
  const cart = readCart();
  const next = cart.filter((c) => c.id !== productId);
  writeCart(next);
  return next;
}

/**
 * 清空购物车
 * @returns {CartItem[]}
 */
export const clearCart = () => {
  writeCart([]);
  return [];
}

/**
 * 计算总价
 * @returns {{ totalQuantity: number, totalPrice: number }}
 */
export const computeSummary = () => {
  const cart = readCart();
  const totalQuantity = cart.reduce((sum, cur) => sum + Number(cur.quantity || 0), 0);
  const totalPrice = cart.reduce((sum, cur) => sum + Number(cur.quantity || 0) * Number(cur.price || 0), 0);
  return { totalQuantity, totalPrice };
}

export default {
  readCart,
  addToCart,
  updateQuantity,
  removeFromCart,
  clearCart,
  computeSummary
}

