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

export interface SavedScript {
  id: string;
  name: string;
  content: string;
  savedAt: number;
}

export function useSavedScripts(storageKey: string) {
  const lsKey = `vigent_${storageKey}_savedScripts`;
  const lsKeyRef = useRef(lsKey);
  lsKeyRef.current = lsKey;

  const [savedScripts, setSavedScripts] = useState<SavedScript[]>([]);

  // Re-read from localStorage whenever lsKey changes (e.g. guest → userId)
  useEffect(() => {
    try {
      const raw = localStorage.getItem(lsKey);
      setSavedScripts(raw ? JSON.parse(raw) : []);
    } catch {
      setSavedScripts([]);
    }
  }, [lsKey]);

  const saveScript = (content: string) => {
    const name = content.slice(0, 15).replace(/\n/g, " ") || "未命名";
    const entry: SavedScript = {
      id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
      name,
      content,
      savedAt: Date.now(),
    };
    setSavedScripts((prev) => {
      const next = [entry, ...prev];
      localStorage.setItem(lsKeyRef.current, JSON.stringify(next));
      return next;
    });
  };

  const deleteScript = (id: string) => {
    setSavedScripts((prev) => {
      const next = prev.filter((s) => s.id !== id);
      localStorage.setItem(lsKeyRef.current, JSON.stringify(next));
      return next;
    });
  };

  return { savedScripts, saveScript, deleteScript };
}
