import { create } from 'zustand'
import type { FileNode } from '../types/file'
import { settingsRepository } from '../db/settingsRepository'

interface SidebarState {
  isVisible: boolean
  rootPath: string | null
  tree: FileNode[]
  expandedDirs: string[]
  sidebarWidth: number
  _loaded: boolean

  setVisible: (visible: boolean) => void
  setRootPath: (path: string | null) => void
  setTree: (tree: FileNode[]) => void
  toggleDir: (path: string) => void
  expandDirs: (paths: string[]) => void
  setSidebarWidth: (width: number) => void
}

export const useSidebarStore = create<SidebarState>((set) => ({
  isVisible: true,
  rootPath: null,
  tree: [],
  expandedDirs: [],
  sidebarWidth: 240,
  _loaded: false,

  setVisible: (visible: boolean) => {
    set({ isVisible: visible })
    settingsRepository.save({ sidebarCollapsed: !visible })
  },
  setRootPath: (path: string | null) => set({ rootPath: path }),
  setTree: (tree: FileNode[]) => set({ tree }),
  toggleDir: (path: string) =>
    set(state => ({
      expandedDirs: state.expandedDirs.includes(path)
        ? state.expandedDirs.filter(p => p !== path)
        : [...state.expandedDirs, path]
    })),
  expandDirs: (paths: string[]) =>
    set(state => {
      const newDirs = paths.filter(p => !state.expandedDirs.includes(p))
      return newDirs.length > 0
        ? { expandedDirs: [...state.expandedDirs, ...newDirs] }
        : state
    }),
  setSidebarWidth: (width: number) => {
    set({ sidebarWidth: width })
    settingsRepository.save({ sidebarWidth: width })
  }
}))
