import { useEffect, useState } from 'react'
import TitleBar from './components/TitleBar'
import Ribbon from './components/Ribbon'
import StatusBar from './components/StatusBar'
import Toast from './components/Toast'
import { PasswordModal } from './components/PasswordModal'
import EditView from './views/EditView'
import ConfigView from './views/ConfigView'
import { useStore } from './store'
import { resolvePageUrl } from './utils'
import { applyPublishDefaults } from './publishActions'
import type { LoadPayload } from './types'
import type { ConfigMenu } from './configMenus'

export default function App(): React.JSX.Element {
  const view = useStore((s) => s.view)
  const pages = useStore((s) => s.pages)
  const [configMenu, setConfigMenu] = useState<ConfigMenu>('info')

  // 监听屏幕状态变化
  useEffect(() => {
    const off = window.api.screens.onChanged((list) => {
      useStore.getState().setScreens(list)
    })
    void window.api.screens.list().then((list) => useStore.getState().setScreens(list))
    return off
  }, [])

  // 页面变化同步给主进程（供屏幕窗口键盘切页）
  useEffect(() => {
    window.api.syncProject(
      pages.map((p) => ({
        id: p.id,
        title: p.title,
        url: resolvePageUrl(p),
        screen: p.screen,
        ctrl: p.ctrl,
        display: p.display
      }))
    )
  }, [pages])

  // 启动：加载应用设置 + 消费/监听快捷方式打开的项目
  useEffect(() => {
    const st = useStore.getState
    void st().loadSettings()
    const handle = (p: unknown): void => {
      const lp = p as LoadPayload | null
      if (!lp?.json) return
      const mode = st().loadProject(lp)
      if (mode === 'publish') void applyPublishDefaults()
    }
    void window.api.app.consumeLoad().then(handle)
    const off = window.api.app.onLoadProject(handle)
    return off
  }, [])

  // 主窗口数字键切换页面
  useEffect(() => {
    const h = (e: KeyboardEvent): void => {
      if (e.ctrlKey || e.metaKey || e.altKey) return
      const t = e.target as HTMLElement | null
      if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
      const n = parseInt(e.key)
      if (n >= 1 && n <= 9) {
        const st = useStore.getState()
        const idx = st.pages.findIndex((p) => p.ctrl === n)
        if (idx >= 0) {
          st.selectPage(idx)
          st.setView('edit')
        }
      }
    }
    window.addEventListener('keydown', h)
    return () => window.removeEventListener('keydown', h)
  }, [])

  return (
    <div className="app">
      <TitleBar />
      <Ribbon configMenu={configMenu} onConfigMenu={setConfigMenu} />
      <div className="app-content">
        {view === 'edit' && <EditView />}
        {view === 'config' && <ConfigView menu={configMenu} />}
      </div>
      <StatusBar />
      <Toast />
      <PasswordModal />
    </div>
  )
}
