"use client";

import dynamic from "next/dynamic";
import { useEffect, useState } from "react";
import { Bot } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useOnlyOfficeAiBridgeStore } from "@/store/onlyoffice-ai-bridge";

type OnlyOfficeAiAgentPanelProps = {
  openFile: { id: string; title: string; fileUrl: string; mimeType?: string | null };
};

const CHANNEL = "mnote_onlyoffice_agent_tools_v1";

const OnlyOfficeAiAgentPanelRuntime = dynamic<OnlyOfficeAiAgentPanelProps & { initialOpen?: boolean }>(
  () => import("./OnlyOfficeAiAgentPanel.runtime").then((mod) => mod.OnlyOfficeAiAgentPanelRuntime),
  {
    ssr: false,
    loading: () => null,
  },
);

// 轻量 host：常驻接住插件 ready 握手，真正的面板 runtime 在首次点击后再挂载。
export function OnlyOfficeAiAgentPanel(props: OnlyOfficeAiAgentPanelProps) {
  const captureReady = useOnlyOfficeAiBridgeStore((state) => state.captureReady);
  const reset = useOnlyOfficeAiBridgeStore((state) => state.reset);
  const [activated, setActivated] = useState(false);

  useEffect(() => {
    const onMessage = (ev: MessageEvent) => {
      const data = ev.data as unknown;
      if (!data || typeof data !== "object") return;

      const channel = "channel" in (data as Record<string, unknown>) ? String((data as Record<string, unknown>).channel ?? "") : "";
      const type = "type" in (data as Record<string, unknown>) ? String((data as Record<string, unknown>).type ?? "") : "";
      if (channel !== CHANNEL || type !== "ready") return;

      const targetWindow =
        ev.source && typeof (ev.source as Window).postMessage === "function" ? (ev.source as Window) : null;
      captureReady({
        targetOrigin: String(ev.origin || "*"),
        targetWindow,
      });
    };

    window.addEventListener("message", onMessage);
    return () => {
      window.removeEventListener("message", onMessage);
      reset();
    };
  }, [captureReady, reset]);

  if (!activated) {
    return (
      <div className="fixed bottom-4 right-4 z-[60]">
        <Button
          className="shadow"
          onClick={() => {
            setActivated(true);
          }}
        >
          <Bot className="mr-2 h-4 w-4" />
          AI
        </Button>
      </div>
    );
  }

  return <OnlyOfficeAiAgentPanelRuntime {...props} initialOpen />;
}
