"use client";

import { useState, useEffect, useCallback } from "react";
import {
  getSavedDownloads,
  removeDownload as removeDownloadUtil,
  clearDownloads as clearDownloadsUtil,
  type DownloadEntry,
} from "@/utils/downloads";

export function useDownloadManager() {
  const [downloads, setDownloads] = useState<DownloadEntry[]>([]);

  const refresh = useCallback(() => {
    setDownloads(getSavedDownloads());
  }, []);

  useEffect(() => {
    refresh();

    // Listen for storage changes (e.g. from another tab)
    const onStorage = (e: StorageEvent) => {
      if (e.key === "doliplay_downloads") {
        refresh();
      }
    };

    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, [refresh]);

  const removeDownload = useCallback(
    (id: string) => {
      removeDownloadUtil(id);
      refresh();
    },
    [refresh],
  );

  const clearAll = useCallback(() => {
    clearDownloadsUtil();
    refresh();
  }, [refresh]);

  return { downloads, removeDownload, clearAll, refresh };
}
