import { defineStore } from 'pinia'
import { ref, watch, onMounted } from 'vue'

export interface CartItem {
  id: number | string
  name: string
  variation_id: number | string
  product_id: number | string
  price: number
  tp_rate: number
  quantity: number
  stock: number
  image?: string
  [key: string]: any
}

export const useCartStore = defineStore('cart', () => {
  const cartItems = ref<CartItem[]>([])
  const isClient = ref(false)
  const checkPriceLessThenTpPrice = [] as any
  const stockInvalidItems = ref<(number | string)[]>([])

  // ✅ Load from localStorage only on client
  onMounted(() => {
    isClient.value = true

    const storedCart = localStorage.getItem('cart')
    if (storedCart) {
      try {
        cartItems.value = JSON.parse(storedCart)
      } catch (e) {
        console.warn('Invalid cart data')
      }
    }
  })

  // ✅ Sync to localStorage only when cart is modified on client
  watch(
    cartItems,
    (newCart) => {
      if (isClient.value) {
        localStorage.setItem('cart', JSON.stringify(newCart))
      }
    },
    { deep: true }
  )

  function addToCart(product: CartItem) {
    const existing = cartItems.value.find(item =>
      item.id === product.id &&
      item.variation_id === product.variation_id &&
      item.product_id === product.product_id
    )
    if (existing) {
      //existing.quantity += 1
    } else {
      cartItems.value.push({ 
        ...product,
        quantity: product.quantity || 1
      })
    }
  }

  function removeFromCart(productId: number | string) {
    cartItems.value = cartItems.value.filter(item => item.id !== productId)
  }

  function updateQuantity(productId: number | string, quantity: number) {
    const item = cartItems.value.find(item => item.id === productId)
    if (item && quantity > 0) {
      item.quantity = quantity
    }
  }

  function clearCart() {
    cartItems.value = []
  }

  function totalItems(): number {
    return cartItems.value.reduce((sum, item) => sum + item.quantity, 0)
  }

  function totalPrice(): number {
    return cartItems.value.reduce(
      (sum, item) => sum + item.quantity * Number(item.price),
      0
    )
  }

  function updateItem(updatedItem: CartItem) {
    const item = cartItems.value.find(i =>
      i.id === updatedItem.id &&
      i.variation_id === updatedItem.variation_id &&
      i.product_id === updatedItem.product_id
    )
    if (item) {
      item.quantity = updatedItem.quantity
      item.price = updatedItem.price
    }
  }

  return {
    cartItems,
    addToCart,
    removeFromCart,
    updateQuantity,
    clearCart,
    totalItems,
    totalPrice,
    updateItem,
    checkPriceLessThenTpPrice,
    stockInvalidItems,
  }
})