import { useEffect } from "react";

export default function useAutosave({
  settings,
  settingsAutosaveReady,
  taskAutosaveReady,
  taskAutosaveTimer,
  taskForm,
  competitorText,
  taskAccountRoles,
  selectedAccountIds,
  canSaveTask,
  saveTask,
  setSettings,
  showNotification
}) {
  useEffect(() => {
    if (!settingsAutosaveReady.current) {
      settingsAutosaveReady.current = true;
      return;
    }
    if (!window.api) return;
    const timer = setTimeout(async () => {
      try {
        const updated = await window.api.saveSettings(settings);
        setSettings(updated);
      } catch (error) {
        showNotification(error.message || String(error), "error");
      }
    }, 600);
    return () => clearTimeout(timer);
  }, [settings]);

  useEffect(() => {
    if (!taskAutosaveReady.current) return;
    if (!canSaveTask) return;
    if (taskAutosaveTimer.current) {
      clearTimeout(taskAutosaveTimer.current);
    }
    taskAutosaveTimer.current = setTimeout(() => {
      saveTask("autosave", { silent: true });
    }, 800);
    return () => clearTimeout(taskAutosaveTimer.current);
  }, [taskForm, competitorText, taskAccountRoles, selectedAccountIds, canSaveTask]);
}
