export const MADE_DREAMS_CART_STORAGE_KEY = 'madeDreamsCart';
export const MADE_DREAMS_CART_EVENT = 'made-dreams-cart-updated';

export type MadeDreamsProduct = {
  id: string;
  name: string;
  category: string;
  price: number;
  badge: string;
  palette: string[];
  imageClass: string;
  description: string;
  reviews: number;
  inventory: number;
};

export type MadeDreamsCartItem = {
  id: string;
  productId: string;
  type: 'product' | 'custom';
  name: string;
  category: string;
  price: number;
  quantity: number;
  badge: string;
  palette: string[];
  imageClass: string;
  description: string;
  maxInventory?: number;
  options?: {
    size?: string;
    difficulty?: string;
    uploadedFileName?: string;
  };
};

export type MadeDreamsCartSummary = {
  itemCount: number;
  subtotal: number;
  shipping: number;
  total: number;
};

export const madeDreamsProducts: MadeDreamsProduct[] = [
  {
    id: 'golden-hour-atelier-kit',
    name: 'Golden Hour Atelier Kit',
    category: 'Best seller',
    price: 68,
    badge: 'Ships in 3 days',
    palette: ['#1f2937', '#b45309', '#f59e0b', '#fde68a', '#fff7ed'],
    imageClass: 'from-[#19130f] via-[#9a5b22] to-[#f6d287]',
    description: 'A warm architectural canvas with 28 rich acrylic colors and three fine-detail brushes.',
    reviews: 184,
    inventory: 18,
  },
  {
    id: 'moonlit-anime-portrait',
    name: 'Moonlit Anime Portrait',
    category: 'New arrival',
    price: 74,
    badge: 'Limited drop',
    palette: ['#111827', '#4c1d95', '#7c3aed', '#c4b5fd', '#f5f3ff'],
    imageClass: 'from-[#111827] via-[#6d28d9] to-[#ddd6fe]',
    description: 'A dramatic anime-inspired design with crisp numbered shapes and luminous violet hues.',
    reviews: 92,
    inventory: 12,
  },
  {
    id: 'forever-family-custom-kit',
    name: 'Forever Family Custom Kit',
    category: 'Personalized',
    price: 89,
    badge: 'Upload-ready',
    palette: ['#292524', '#7f1d1d', '#fb7185', '#fed7aa', '#fff7ed'],
    imageClass: 'from-[#292524] via-[#be123c] to-[#fed7aa]',
    description: 'Our premium custom kit for treasured photos, hand-balanced for a painterly finish.',
    reviews: 267,
    inventory: 25,
  },
];

export const formatCurrency = (amount: number) =>
  new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
  }).format(amount);

const isBrowser = () => typeof window !== 'undefined';

const clampQuantity = (quantity: number, maxInventory = 99) => {
  const nextQuantity = Number.isFinite(quantity) ? Math.floor(quantity) : 1;
  return Math.max(1, Math.min(nextQuantity, maxInventory));
};

const isCartItem = (item: MadeDreamsCartItem) =>
  Boolean(item?.id && item?.name && item?.price >= 0 && item?.quantity > 0);

export const readMadeDreamsCart = (): MadeDreamsCartItem[] => {
  if (!isBrowser()) return [];

  const rawCart = window.localStorage.getItem(MADE_DREAMS_CART_STORAGE_KEY);
  if (!rawCart) return [];

  try {
    const parsedCart = JSON.parse(rawCart);
    if (!Array.isArray(parsedCart)) return [];

    return parsedCart.filter(isCartItem).map((item) => ({
      ...item,
      quantity: clampQuantity(item.quantity, item.maxInventory),
    }));
  } catch (error) {
    console.error('Failed to read Made Dreams cart from localStorage:', error);
    return [];
  }
};

const emitCartUpdated = () => {
  if (!isBrowser()) return;
  window.dispatchEvent(new Event(MADE_DREAMS_CART_EVENT));
};

export const writeMadeDreamsCart = (items: MadeDreamsCartItem[]) => {
  if (!isBrowser()) return items;

  window.localStorage.setItem(MADE_DREAMS_CART_STORAGE_KEY, JSON.stringify(items));
  emitCartUpdated();
  return items;
};

export const getMadeDreamsCartSummary = (items: MadeDreamsCartItem[]): MadeDreamsCartSummary => {
  const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
  const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
  const shipping = subtotal === 0 || subtotal >= 100 ? 0 : 9;

  return {
    itemCount,
    subtotal,
    shipping,
    total: subtotal + shipping,
  };
};

export const addMadeDreamsProductToCart = (product: MadeDreamsProduct, quantity = 1) => {
  const items = readMadeDreamsCart();
  const existingItem = items.find((item) => item.productId === product.id && item.type === 'product');

  if (existingItem) {
    const updatedItems = items.map((item) =>
      item.id === existingItem.id
        ? {
            ...item,
            quantity: clampQuantity(item.quantity + quantity, product.inventory),
          }
        : item,
    );

    return writeMadeDreamsCart(updatedItems);
  }

  return writeMadeDreamsCart([
    ...items,
    {
      id: product.id,
      productId: product.id,
      type: 'product',
      name: product.name,
      category: product.category,
      price: product.price,
      quantity: clampQuantity(quantity, product.inventory),
      badge: product.badge,
      palette: product.palette,
      imageClass: product.imageClass,
      description: product.description,
      maxInventory: product.inventory,
    },
  ]);
};

export const addMadeDreamsCustomKitToCart = ({
  uploadedFileName,
  size,
  difficulty,
  price,
}: {
  uploadedFileName: string;
  size: string;
  difficulty: string;
  price: number;
}) => {
  const items = readMadeDreamsCart();
  const cartLineId = `custom-kit-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;

  return writeMadeDreamsCart([
    ...items,
    {
      id: cartLineId,
      productId: 'custom-paint-by-numbers-kit',
      type: 'custom',
      name: 'Custom Paint By Numbers Kit',
      category: 'Custom generator',
      price,
      quantity: 1,
      badge: 'Personalized',
      palette: ['#201713', '#a0672a', '#d7a25d', '#f0dfca', '#fff8ef'],
      imageClass: 'from-[#201713] via-[#a0672a] to-[#f5d29a]',
      description: 'Photo-to-canvas custom kit with numbered pattern, curated paints, and premium brushes.',
      options: {
        uploadedFileName,
        size,
        difficulty,
      },
    },
  ]);
};

export const updateMadeDreamsCartQuantity = (itemId: string, quantity: number) => {
  const items = readMadeDreamsCart();

  if (quantity < 1) {
    return writeMadeDreamsCart(items.filter((item) => item.id !== itemId));
  }

  return writeMadeDreamsCart(
    items.map((item) =>
      item.id === itemId
        ? {
            ...item,
            quantity: clampQuantity(quantity, item.maxInventory),
          }
        : item,
    ),
  );
};

export const removeMadeDreamsCartItem = (itemId: string) =>
  writeMadeDreamsCart(readMadeDreamsCart().filter((item) => item.id !== itemId));

export const clearMadeDreamsCart = () => writeMadeDreamsCart([]);
