import { useEffect, useCallback } from 'react'
import { useSidebarStore } from '../stores/sidebarStore'
import { useEditorStore } from '../stores/editorStore'

/**
 * AR-02: 从 Sidebar.tsx 提取的文件夹操作逻辑
 * UX-02: 添加目录加载 loading 状态
 */
export function useFolderOperations() {
  const rootPath = useSidebarStore(s => s.rootPath)
  const setRootPath = useSidebarStore(s => s.setRootPath)
  const setTree = useSidebarStore(s => s.setTree)
  const expandDirs = useSidebarStore(s => s.expandDirs)
  const setLoading = useEditorStore(s => s.setLoading)

  const handleOpenFolder = useCallback(async () => {
    if (!window.electronAPI) return
    const dirPath = await window.electronAPI.openFolderDialog()
    if (!dirPath) return
    setRootPath(dirPath)
    expandDirs([dirPath])
    setLoading('dir-load', true)
    try {
      const dirTree = await window.electronAPI.readDirTree(dirPath)
      if (dirTree.success && dirTree.tree) {
        setTree(dirTree.tree)
        window.electronAPI.watchDir(dirPath)
      }
    } finally {
      setLoading('dir-load', false)
    }
  }, [setRootPath, setTree, expandDirs, setLoading])

  const refreshTree = useCallback(async () => {
    if (!rootPath || !window.electronAPI) return
    setLoading('dir-load', true)
    try {
      const result = await window.electronAPI.readDirTree(rootPath)
      if (result.success && result.tree) setTree(result.tree)
    } finally {
      setLoading('dir-load', false)
    }
  }, [rootPath, setTree, setLoading])

  useEffect(() => {
    if (!window.electronAPI) return
    const unsubscribe = window.electronAPI.onDirChanged(() => refreshTree())
    return unsubscribe
  }, [refreshTree])

  return { handleOpenFolder }
}
