import { useEffect, useRef } from "react";
import { invoke } from "@tauri-apps/api/core";
import { useStore, actions } from "@/lib/store";

export function useAutoSave() {
  const { settings, tabs } = useStore();
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const prevContentRef = useRef<string>("");

  useEffect(() => {
    if (!settings.autoSave) {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
      return;
    }

    const contentKey = tabs.map((t) => t.path + ":" + t.content.length).join("|");
    if (contentKey === prevContentRef.current) return;
    prevContentRef.current = contentKey;

    if (timerRef.current) clearTimeout(timerRef.current);

    timerRef.current = setTimeout(async () => {
      const currentState = actions.getState();
      for (const tab of currentState.tabs) {
        if (tab.content !== tab.savedContent) {
          try {
            await invoke("write_file", { path: tab.path, contents: tab.content });
            actions.markSaved(tab.path);
          } catch (err) {
            console.error("Auto-save failed for", tab.name, err);
          }
        }
      }
    }, 1500);

    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, [settings.autoSave, tabs]);
}
