import { useCallback } from 'react';
import { useSetAtom } from 'jotai';
import { Icons } from 'folds';
import FileSaver from 'file-saver';
import { createDownloadToast, toastQueueAtom } from '../state/toast';

/**
 * Save a blob/URL to disk AND surface a "Downloaded <filename>" toast.
 *
 * The desktop (Tauri) app has no native download UI, so `FileSaver.saveAs` saved
 * files silently — users re-clicked because nothing confirmed success. This gives
 * uniform, visible feedback across web + desktop for every download call site.
 */
export const useSaveFile = () => {
  const setToast = useSetAtom(toastQueueAtom);

  return useCallback(
    (data: Blob | string, filename: string) => {
      FileSaver.saveAs(data, filename);
      setToast(createDownloadToast(filename, Icons.Check));
    },
    [setToast],
  );
};
