import {
  register,
  unregisterAll,
} from "@tauri-apps/plugin-global-shortcut";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { useAppStore } from "../store/useAppStore";
import type { GlobalHotkeys } from "../store/types";

/**
 * 注册三个全局快捷键：
 * - newTask: 显示窗口 + 打开任务面板 + 聚焦输入框
 * - togglePomodoro: 切换番茄钟开始/暂停（通过自定义事件分发）
 * - showHide: 显示/隐藏主窗口
 *
 * 返回 cleanup 函数。
 */
export function registerGlobalHotkeys(map: GlobalHotkeys): () => Promise<void> {
  const win = getCurrentWindow();

  (async () => {
    try {
      await unregisterAll();

      if (map.newTask) {
        await register(map.newTask, async (e) => {
          if (e.state !== "Pressed") return;
          await win.show();
          await win.setFocus();
          useAppStore.getState().setActivePanel("tasks");
          // 让任务输入框感知到聚焦请求
          window.dispatchEvent(new CustomEvent("deskfloat:focus-new-task"));
        });
      }
      if (map.togglePomodoro) {
        await register(map.togglePomodoro, (e) => {
          if (e.state !== "Pressed") return;
          window.dispatchEvent(new CustomEvent("deskfloat:toggle-pomodoro"));
        });
      }
      if (map.showHide) {
        await register(map.showHide, async (e) => {
          if (e.state !== "Pressed") return;
          const visible = await win.isVisible();
          if (visible) {
            await win.hide();
          } else {
            await win.show();
            await win.setFocus();
          }
        });
      }
    } catch (e) {
      console.error("[DeskFloat] hotkey register failed", e);
    }
  })();

  return async () => {
    try {
      await unregisterAll();
    } catch (e) {
      console.warn("[DeskFloat] hotkey unregister failed", e);
    }
  };
}
