import { useEffect, useRef } from 'react'
import { useEditorStore } from '../stores/editorStore'
import { useSidebarStore } from '../stores/sidebarStore'
import { settingsRepository } from '../db/settingsRepository'
import { logError } from '../lib/errorHandler'

/**
 * AR-04: 统一设置加载 hook
 * 一次性从 IndexedDB 加载所有设置，分发到各 store
 * 替代 useTheme、useSettings、sidebarStore.loadFromDB 各自独立加载的模式
 */
export function useSettingsInit() {
  const setDarkMode = useEditorStore(s => s.setDarkMode)
  const setViewMode = useEditorStore(s => s.setViewMode)
  const isInitialized = useRef(false)

  useEffect(() => {
    if (isInitialized.current) return
    isInitialized.current = true

    settingsRepository.load()
      .then((settings) => {
        // 主题
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        const darkMode = settings.darkMode !== undefined ? settings.darkMode : prefersDark
        setDarkMode(darkMode)
        document.documentElement.classList.toggle('dark', darkMode)

        // 视图模式
        setViewMode(settings.viewMode ?? 'editor')

        // Sidebar 设置（直接分发，避免 sidebarStore 再次读取 IndexedDB）
        const sidebarStore = useSidebarStore.getState()
        if (!sidebarStore._loaded) {
          useSidebarStore.setState({
            isVisible: !settings.sidebarCollapsed,
            sidebarWidth: settings.sidebarWidth,
            _loaded: true
          })
        }
      })
      .catch((error: unknown) => {
        logError('加载设置失败', error)
      })
  }, [setDarkMode, setViewMode])

  return { isInitialized }
}
