"use client";

import {
  createContext,
  useContext,
  useEffect,
  useState,
  type ReactNode,
} from "react";
import type { Product } from "@/data/types";
import { useToast } from "./toast-context";

type WishlistContextValue = {
  ids: string[];
  toggle: (product: Product) => void;
  has: (productId: string) => boolean;
};

const WishlistContext = createContext<WishlistContextValue | null>(null);
const STORAGE_KEY = "fliemart-wishlist";

export function WishlistProvider({ children }: { children: ReactNode }) {
  const [ids, setIds] = useState<string[]>([]);
  const [hydrated, setHydrated] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (raw) setIds(JSON.parse(raw) as string[]);
    } catch {
      // ignore
    }
    setHydrated(true);
  }, []);

  useEffect(() => {
    if (!hydrated) return;
    localStorage.setItem(STORAGE_KEY, JSON.stringify(ids));
  }, [ids, hydrated]);

  const has = (productId: string) => ids.includes(productId);

  const toggle = (product: Product) => {
    // Toast outside setState — updaters can run twice in React Strict Mode.
    const removing = ids.includes(product.id);
    setIds((current) =>
      removing
        ? current.filter((id) => id !== product.id)
        : current.includes(product.id)
          ? current
          : [...current, product.id],
    );
    toast(
      removing
        ? `Removed ${product.name} from wishlist`
        : `Saved ${product.name} to wishlist`,
      removing ? "info" : "success",
    );
  };

  return (
    <WishlistContext.Provider value={{ ids, toggle, has }}>
      {children}
    </WishlistContext.Provider>
  );
}

export function useWishlist() {
  const context = useContext(WishlistContext);
  if (!context) {
    throw new Error("useWishlist must be used within WishlistProvider");
  }
  return context;
}
