import type { StateCreator } from "zustand";
import type { LessonPlanDocument } from "../types";
import type { EditorState } from "./use-lesson-plan-editor";

export interface VersionSlice {
  isDirty: boolean;
  isSaving: boolean;
  lastSavedAt: number | null;
  /** V5-1：自动保存失败标记，供 UI 显示兜底提示与重试按钮 */
  saveError: boolean;
  /** V5-1：网络在线状态，供 UI 显示断网提示 */
  isOnline: boolean;
  hydrate: (planId: string, title: string, doc: LessonPlanDocument) => void;
  markSaved: () => void;
  setSaving: (saving: boolean) => void;
  replaceDoc: (doc: LessonPlanDocument) => void;
  /** V5-1：标记保存失败/成功 */
  setSaveError: (hasError: boolean) => void;
  /** V5-1：更新在线状态（监听 window online/offline 事件） */
  setOnline: (online: boolean) => void;
}

export const createVersionSlice: StateCreator<
  EditorState,
  [],
  [],
  VersionSlice
> = (set) => ({
  isDirty: false,
  isSaving: false,
  lastSavedAt: null,
  saveError: false,
  isOnline: true,

  hydrate: (planId, title, doc) =>
    set({
      planId,
      title,
      doc,
      isDirty: false,
      lastSavedAt: Date.now(),
      selectedNodeId: null,
      saveError: false,
      past: [],
      future: [], // V5-2：hydrate 时清空历史，避免跨课案污染
    }),

  markSaved: () => set({ isDirty: false, lastSavedAt: Date.now(), saveError: false }),
  setSaving: (saving) => set({ isSaving: saving }),
  replaceDoc: (doc) => set({ doc, isDirty: false, saveError: false, past: [], future: [] }),
  setSaveError: (hasError) => set({ saveError: hasError }),
  setOnline: (online) => set({ isOnline: online }),
});
