import { createContext, useContext, useState, useCallback } from "react";

const WatchlistContext = createContext();

const STORAGE_KEY = "wfm-watchlist";

function loadWatchlist() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    return raw ? JSON.parse(raw) : [];
  } catch {
    return [];
  }
}

export function WatchlistProvider({ children }) {
  const [watchlist, setWatchlist] = useState(loadWatchlist);

  const save = useCallback((list) => {
    setWatchlist(list);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(list));
  }, []);

  const toggleItem = useCallback(
    (itemSlug) => {
      setWatchlist((prev) => {
        const next = prev.includes(itemSlug)
          ? prev.filter((s) => s !== itemSlug)
          : [...prev, itemSlug];
        localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
        return next;
      });
    },
    []
  );

  const isWatched = useCallback(
    (itemSlug) => watchlist.includes(itemSlug),
    [watchlist]
  );

  return (
    <WatchlistContext.Provider value={{ watchlist, toggleItem, isWatched }}>
      {children}
    </WatchlistContext.Provider>
  );
}

export function useWatchlist() {
  return useContext(WatchlistContext);
}
