// src/showmasterpiece/logic/shared/storage.ts
var hasWxStorage = () => typeof wx !== "undefined" && typeof wx.getStorageSync === "function";
var hasLocalStorage = () => typeof localStorage !== "undefined" && typeof localStorage.getItem === "function";
var getStorageSync = (key) => {
  try {
    if (hasWxStorage()) {
      return wx.getStorageSync(key);
    }
    if (hasLocalStorage()) {
      const value = localStorage.getItem(key);
      return value ? JSON.parse(value) : null;
    }
  } catch {
    return null;
  }
  return null;
};
var setStorageSync = (key, value) => {
  try {
    if (hasWxStorage()) {
      wx.setStorageSync(key, value);
      return;
    }
    if (hasLocalStorage()) {
      localStorage.setItem(key, JSON.stringify(value));
    }
  } catch {
  }
};

// src/showmasterpiece/logic/shared/cart.ts
var CART_STORAGE_KEY = "showmasterpiece_cart";
var normalizeCart = (cart) => {
  const safeCart = cart ?? { items: [], totalPrice: 0, totalQuantity: 0 };
  const totals = safeCart.items.reduce(
    (acc, item) => {
      acc.totalQuantity += item.quantity;
      acc.totalPrice += (item.collection.price || 0) * item.quantity;
      return acc;
    },
    { totalQuantity: 0, totalPrice: 0 }
  );
  return {
    ...safeCart,
    totalQuantity: totals.totalQuantity,
    totalPrice: totals.totalPrice
  };
};
var getCart = () => {
  const stored = getStorageSync(CART_STORAGE_KEY);
  if (stored && stored.items) {
    return normalizeCart(stored);
  }
  return normalizeCart();
};
var saveCart = (cart) => {
  setStorageSync(CART_STORAGE_KEY, cart);
};
var addToCart = (collection, quantity = 1) => {
  const cart = getCart();
  const existing = cart.items.find((item) => item.collectionId === collection.id);
  if (existing) {
    existing.quantity += quantity;
  } else {
    cart.items.push({
      collectionId: collection.id,
      collection,
      quantity,
      addedAt: /* @__PURE__ */ new Date()
    });
  }
  const next = normalizeCart(cart);
  saveCart(next);
  return next;
};
var updateCartItem = (collectionId, quantity) => {
  const cart = getCart();
  const target = cart.items.find((item) => item.collectionId === collectionId);
  if (!target) return cart;
  if (quantity <= 0) {
    cart.items = cart.items.filter((item) => item.collectionId !== collectionId);
  } else {
    target.quantity = quantity;
  }
  const next = normalizeCart(cart);
  saveCart(next);
  return next;
};
var removeCartItem = (collectionId) => {
  const cart = getCart();
  cart.items = cart.items.filter((item) => item.collectionId !== collectionId);
  const next = normalizeCart(cart);
  saveCart(next);
  return next;
};
var clearCart = () => {
  const empty = normalizeCart({ items: [], totalPrice: 0, totalQuantity: 0 });
  saveCart(empty);
  return empty;
};

export { addToCart, clearCart, getCart, removeCartItem, updateCartItem };
//# sourceMappingURL=chunk-DWJLOHAE.mjs.map
//# sourceMappingURL=chunk-DWJLOHAE.mjs.map