import { useCallback, useState } from "react";
import type { ChatMessage, JobExtract, ResumePlan } from "../shared/types";
import { Home } from "./screens/Home";
import { PdfScreen } from "./screens/Pdf";
import { Workspace } from "./screens/Workspace";

export interface GeneratedResume {
  plan: ResumePlan;
  source: "ai" | "fallback";
  note?: string;
  latex: string;
  pdfUrl: string;
}

type Stage =
  | { name: "home" }
  | { name: "workspace"; jd: JobExtract }
  | { name: "pdf"; jd: JobExtract; result: GeneratedResume };

export function App() {
  const [stage, setStage] = useState<Stage>({ name: "home" });
  const [chat, setChat] = useState<ChatMessage[]>([]);

  const openWorkspace = useCallback((jd: JobExtract) => {
    setChat([]);
    setStage({ name: "workspace", jd });
  }, []);

  if (stage.name === "home") return <Home onExtracted={openWorkspace} />;

  if (stage.name === "workspace") {
    return (
      <Workspace
        jd={stage.jd}
        messages={chat}
        onMessagesChange={setChat}
        onBack={() => setStage({ name: "home" })}
        onGenerated={(result) => setStage({ name: "pdf", jd: stage.jd, result })}
      />
    );
  }

  return (
    <PdfScreen
      result={stage.result}
      onBack={() => setStage({ name: "workspace", jd: stage.jd })}
      onRecompiled={(result) => setStage({ name: "pdf", jd: stage.jd, result })}
    />
  );
}
