import { useEffect } from 'react'
import { useSidebarStore } from '../stores/sidebarStore'

/**
 * AR-02: 自动展开到活动文件所在的目录
 */
export function useAutoExpandDir(activeFilePath: string | null) {
  const rootPath = useSidebarStore(s => s.rootPath)
  const expandDirs = useSidebarStore(s => s.expandDirs)

  useEffect(() => {
    if (!activeFilePath || !rootPath) return
    const norm = (p: string) => p.replace(/[/\\]+$/, '').replace(/\\/g, '/')
    const normalizedRoot = norm(rootPath) + '/'
    if (!norm(activeFilePath).startsWith(normalizedRoot)) return

    const dirsToExpand: string[] = []
    let dir = activeFilePath.replace(/[/\\][^/\\]+$/, '')
    let prev = ''
    while (dir && dir.length >= rootPath.length && dir !== rootPath && dir !== prev) {
      prev = dir
      dirsToExpand.push(dir)
      dir = dir.replace(/[/\\][^/\\]+$/, '')
    }
    if (dirsToExpand.length > 0) expandDirs(dirsToExpand)
  }, [activeFilePath, rootPath, expandDirs])
}
