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

export type GenStatus = "idle" | "ready" | "generating" | "done" | "failed";

export interface UseGenerationStatusReturn {
  status: GenStatus;
  error: string | null;
  abortRef: { current: boolean };
  start: () => void;
  succeed: () => void;
  fail: (msg: string) => void;
  reset: () => void;
  cancel: () => void;
  isGenerating: boolean;
  isFailed: boolean;
  isIdle: boolean;
}

export function useGenerationStatus(): UseGenerationStatusReturn {
  const [status, setStatus] = useState<GenStatus>("idle");
  const [error, setError] = useState<string | null>(null);
  const abortRef = useRef(false);

  const start = useCallback(() => {
    setStatus("generating");
    setError(null);
    abortRef.current = false;
  }, []);

  const succeed = useCallback(() => setStatus("done"), []);
  const fail = useCallback((msg: string) => { setStatus("failed"); setError(msg); }, []);
  const reset = useCallback(() => { setStatus("idle"); setError(null); }, []);
  const cancel = useCallback(() => { abortRef.current = true; }, []);

  return {
    status, error, abortRef, start, succeed, fail, reset, cancel,
    isGenerating: status === "generating",
    isFailed: status === "failed",
    isIdle: status === "idle",
  };
}
