"use client";

import dynamic from "next/dynamic";
import { useEffect } from "react";
import { useSearchPaletteStore } from "@/store/search-palette";

type SearchPaletteProps = {
  workspaceId: string | null;
};

const SearchPaletteRuntime = dynamic<SearchPaletteProps>(
  () => import("./search-palette.runtime").then((mod) => mod.SearchPalette),
  {
    ssr: false,
    loading: () => null,
  },
);

// 轻量 host：负责首开前热键与懒加载，重型搜索面板首次打开后再进入运行态。
export function SearchPaletteHost({ workspaceId }: SearchPaletteProps) {
  const openSearch = useSearchPaletteStore((state) => state.openSearch);
  const openReference = useSearchPaletteStore((state) => state.openReference);
  const activated = useSearchPaletteStore((state) => state.activated);

  useEffect(() => {
    if (activated) {
      return undefined;
    }

    const handleGlobalHotkey = (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && !event.shiftKey && event.key.toLowerCase() === "p") {
        event.preventDefault();
        openSearch();
      }
      if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === "r") {
        event.preventDefault();
        openReference();
      }
    };

    window.addEventListener("keydown", handleGlobalHotkey);
    return () => window.removeEventListener("keydown", handleGlobalHotkey);
  }, [activated, openReference, openSearch]);

  if (!activated) {
    return null;
  }

  return <SearchPaletteRuntime workspaceId={workspaceId} />;
}
