"use client";

import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import type { Product } from "@/lib/headless/types";

interface WishlistState {
  products: Product[];
  isOpen: boolean;
  hasHydrated: boolean;
  openWishlist: () => void;
  closeWishlist: () => void;
  setHasHydrated: (value: boolean) => void;
  toggleProduct: (product: Product) => void;
  removeProduct: (productId: string) => void;
  contains: (productId: string) => boolean;
}

export const useWishlistStore = create<WishlistState>()(
  persist(
    (set, get) => ({
      products: [],
      isOpen: false,
      hasHydrated: false,
      openWishlist: () => set({ isOpen: true }),
      closeWishlist: () => set({ isOpen: false }),
      setHasHydrated: (value) => set({ hasHydrated: value }),
      toggleProduct: (product) => set((state) => ({
        products: state.products.some((item) => item.id === product.id)
          ? state.products.filter((item) => item.id !== product.id)
          : [...state.products, product],
      })),
      removeProduct: (productId) => set((state) => ({
        products: state.products.filter((item) => item.id !== productId),
      })),
      contains: (productId) => get().products.some((item) => item.id === productId),
    }),
    {
      name: "ari-shopping-wishlist-v4-1",
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({ products: state.products }),
      onRehydrateStorage: () => (state) => state?.setHasHydrated(true),
    },
  ),
);
