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

export 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;
}

const initialState = {
  ufSource: "",
  isDirty: false,
  currentPage: null as PageMeta | null,
  compiledAscii: "",
  compiledMicron: "",
  compiledScript: "",
  isDynamic: false,
  compileWarnings: [] as string[],
  isCompiling: false,
  compileError: null as string | null,
  previewMode: "micron" as const,
};

function makeActions(set: (partial: Partial<EditorStore>) => void) {
  return {
    setSource: (s: string) => set({ ufSource: s, isDirty: true }),
    setCurrentPage: (p: PageMeta | null) => set({ currentPage: p }),
    setDirty: (v: boolean) => set({ isDirty: v }),
    setCompileResult: (ascii: string, micron: string, script: string, isDynamic: boolean, warnings: string[]) =>
      set({ compiledAscii: ascii, compiledMicron: micron, compiledScript: script, isDynamic, compileWarnings: warnings, isCompiling: false, compileError: null }),
    setCompiling: (v: boolean) => set({ isCompiling: v }),
    setCompileError: (e: string | null) => set({ compileError: e, isCompiling: false }),
    setPreviewMode: (mode: "micron" | "raw" | "script") => set({ previewMode: mode }),
    reset: () => set({ ...initialState }),
  };
}

export function createEditorStore() {
  return create<EditorStore>((set) => ({
    ...initialState,
    ...makeActions(set),
  }));
}

export const useEditorStore = createEditorStore();
