import { useEffect } from 'react'
import { useTabStore } from '../stores/tabStore'
import { useEditorStore } from '../stores/editorStore'

/**
 * AR-03: 文件外部修改检测
 * 使用 Zustand store 状态替代 DOM CustomEvent
 */
export function useFileWatch() {
  const getActiveTab = useTabStore(s => s.getActiveTab)
  const setExternallyModified = useEditorStore(s => s.setExternallyModified)

  useEffect(() => {
    if (!window.electronAPI) return

    const unsubscribe = window.electronAPI.onExternalModification((filePath: string) => {
      const tab = getActiveTab()
      if (tab && tab.filePath === filePath) {
        // AR-03: 直接更新 store 状态，不再派发 CustomEvent
        setExternallyModified({ filePath })
      }
    })

    return unsubscribe
  }, [getActiveTab, setExternallyModified])
}
