import { useEffect } from "react";
import { Toolbar } from "./components/Toolbar/Toolbar";
import { PinnedTasksOverlay } from "./modules/tasks/PinnedTasksOverlay";
import { useAppStore } from "./store/useAppStore";
import { registerGlobalHotkeys } from "./hooks/useHotkeys";
import { setAlwaysOnTop } from "./api/tauri";

/**
 * 应用根组件：
 * 1. 启动时 hydrate 持久化数据
 * 2. 同步系统级设置（置顶 / 全局热键 / 透明度）
 * 3. 渲染浮动工具栏
 */
export function App() {
  const ready = useAppStore((s) => s.ready);
  const hydrate = useAppStore((s) => s.hydrate);
  const settings = useAppStore((s) => s.settings);
  const taskPinMode = useAppStore((s) => s.taskPinMode);

  // 启动加载
  useEffect(() => {
    void hydrate();
  }, [hydrate]);

  // 透明度变化时同步到 CSS 变量（钉子模式使用专用更低透明度）
  useEffect(() => {
    if (taskPinMode) return;
    document.documentElement.style.setProperty(
      "--bg-opacity",
      String(settings.opacity)
    );
  }, [settings.opacity, taskPinMode]);

  // 置顶状态同步到窗口
  useEffect(() => {
    if (!ready) return;
    void setAlwaysOnTop(settings.alwaysOnTop);
  }, [ready, settings.alwaysOnTop]);

  // 全局快捷键
  useEffect(() => {
    if (!ready) return;
    const unregister = registerGlobalHotkeys(settings.globalHotkeys);
    return () => {
      void unregister();
    };
  }, [ready, settings.globalHotkeys]);

  if (!ready) return null;
  if (taskPinMode) return <PinnedTasksOverlay />;
  return <Toolbar />;
}
