import { create } from "zustand";
import type { PageMeta } from "@/api/client";

interface EditorStore {
  // Source
  ufSource: string;
  isDirty: boolean;
  currentPage: PageMeta | null;

  // Compiled output
  compiledAscii: string;
  compiledMicron: string;
  compiledScript: string;
  isDynamic: boolean;
  compileWarnings: string[];
  isCompiling: boolean;
  compileError: string | null;

  // Preview
  previewMode: "micron" | "raw" | "script";

  // Actions
  setSource: (s: string) => void;
  setCurrentPage: (p: PageMeta | null) => void;
  setDirty: (v: boolean) => void;
  setCompileResult: (ascii: string, micron: string, script: string, isDynamic: boolean, warnings: string[]) => void;
  setCompiling: (v: boolean) => void;
  setCompileError: (e: string | null) => void;
  setPreviewMode: (mode: "micron" | "raw" | "script") => void;
  reset: () => void;
}

export const useEditorStore = create<EditorStore>((set) => ({
  ufSource: "",
  isDirty: false,
  currentPage: null,

  compiledAscii: "",
  compiledMicron: "",
  compiledScript: "",
  isDynamic: false,
  compileWarnings: [],
  isCompiling: false,
  compileError: null,

  previewMode: "micron",

  setSource: (s) => set({ ufSource: s, isDirty: true }),
  setCurrentPage: (p) => set({ currentPage: p }),
  setDirty: (v) => set({ isDirty: v }),
  setCompileResult: (ascii, micron, script, isDynamic, warnings) =>
    set({
      compiledAscii: ascii,
      compiledMicron: micron,
      compiledScript: script,
      isDynamic,
      compileWarnings: warnings,
      isCompiling: false,
      compileError: null,
    }),
  setCompiling: (v) => set({ isCompiling: v }),
  setCompileError: (e) => set({ compileError: e, isCompiling: false }),
  setPreviewMode: (mode) => set({ previewMode: mode }),
  reset: () =>
    set({
      ufSource: "",
      isDirty: false,
      currentPage: null,
      compiledAscii: "",
      compiledMicron: "",
      compiledScript: "",
      isDynamic: false,
      compileWarnings: [],
      isCompiling: false,
      compileError: null,
      previewMode: "micron",
    }),
}));
