"use client";
import {
  createContext,
  useContext,
  useEffect,
  useCallback,
  useMemo,
} from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchWishlist,
  toggleWishlist,
  optimisticToggle,
} from "@/store/slices/marketplaceWishlistSlice";

interface WishlistCtx {
  ids: Set<string>;
  toggle: (id: string) => void;
  has: (id: string) => boolean;
  count: number;
}

const WishlistContext = createContext<WishlistCtx>({
  ids: new Set(),
  toggle: () => {},
  has: () => false,
  count: 0,
});

export function WishlistProvider({ children }: { children: React.ReactNode }) {
  const dispatch = useAppDispatch();
  const { ids: rawIds } = useAppSelector((s) => s.marketplaceWishlist);

  /* Fetch server wishlist once on mount */
  useEffect(() => {
    dispatch(fetchWishlist(false));
  }, [dispatch]);

  const ids = useMemo(() => new Set(rawIds), [rawIds]);

  const toggle = useCallback(
    (id: string) => {
      /* Optimistic flip so heart animates instantly */
      dispatch(optimisticToggle(id));
      /* Fire API — slice handles toast + revert on failure */
      dispatch(toggleWishlist(id));
    },
    [dispatch]
  );

  const has = useCallback((id: string) => ids.has(id), [ids]);

  const value = useMemo(
    () => ({ ids, toggle, has, count: ids.size }),
    [ids, toggle, has]
  );

  return (
    <WishlistContext.Provider value={value}>{children}</WishlistContext.Provider>
  );
}

export const useWishlist = () => useContext(WishlistContext);
