import { create } from 'zustand'
import type { EditorView } from '@milkdown/prose/view'
import type { ViewMode } from '../types/settings'

// Module-level getter/setter for the ProseMirror EditorView
// Used by OutlinePanel for heading navigation
let _getView: (() => EditorView | null) | null = null

export function setEditorViewGetter(fn: () => EditorView | null) {
  _getView = fn
}

export function getEditorView(): EditorView | null {
  return _getView ? _getView() : null
}

interface EditorState {
  viewMode: ViewMode
  darkMode: boolean
  // AR-03: 外部修改检测状态，替代 DOM CustomEvent
  externallyModified: { filePath: string } | null
  // UX-02: 全局加载状态
  loadingStates: Record<string, boolean>

  setViewMode: (mode: ViewMode) => void
  setDarkMode: (dark: boolean) => void
  toggleDarkMode: () => void
  setExternallyModified: (info: { filePath: string } | null) => void
  // UX-02: 加载状态管理
  setLoading: (key: string, loading: boolean) => void
  isLoading: (key: string) => boolean
}

export const useEditorStore = create<EditorState>((set, get) => ({
  viewMode: 'editor',
  darkMode: false,
  externallyModified: null,
  loadingStates: {},

  setViewMode: (mode: ViewMode) => set({ viewMode: mode }),
  setDarkMode: (dark: boolean) => set({ darkMode: dark }),
  toggleDarkMode: () => set(state => ({ darkMode: !state.darkMode })),
  setExternallyModified: (info: { filePath: string } | null) => set({ externallyModified: info }),
  setLoading: (key: string, loading: boolean) => set(state => ({
    loadingStates: { ...state.loadingStates, [key]: loading }
  })),
  isLoading: (key: string) => get().loadingStates[key] ?? false
}))
