"use client";

import { useCallback, useEffect, useState } from "react";

/**
 * The person's watchlist, stored with their account rather than in the
 * browser — a watchlist that disappears on another device isn't much use.
 */
export function useWatchlist() {
  const [ids, setIds] = useState<string[]>([]);

  const load = useCallback(() => {
    fetch("/api/marketplace?saved=1")
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => setIds(Array.isArray(d) ? d.map((l: { id: string }) => l.id) : []))
      .catch(() => {});
  }, []);

  useEffect(load, [load]);

  const toggle = useCallback(async (id: string) => {
    // Moved straight away so the heart responds, then confirmed.
    setIds((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
    );

    const res = await fetch(`/api/marketplace/${id}/save`, { method: "POST" }).catch(
      () => null
    );

    // Put it back if the server disagreed.
    if (!res || !res.ok) load();
  }, [load]);

  return {
    ids,
    count: ids.length,
    has: (id: string) => ids.includes(id),
    toggle,
    reload: load,
  };
}
