"use client";

import dynamic from "next/dynamic";
import { useEffect } from "react";
import type { PageBodyPersistedMeta } from "@/lib/documents/page-body-command";
import type { PageOptionsState } from "@/types/page-options";
import type { PageSubtreeProjection } from "@/lib/documents/page-subtree";
import type { Json } from "@/types/supabase";
import { useAiAgentUiStore } from "@/store/ai-agent-ui";

export type PageAggregateAiSnapshot = {
  blocks: Json | null;
  pageSubtree: PageSubtreeProjection | null;
  persistedMeta: {
    workspaceId: string | null;
    revision: number | null;
    conflictDetectionKey: string | null;
  };
  pageOptions: PageOptionsState;
};

type DocumentAiAgentPanelProps = {
  documentId: string;
  getLatestPageAggregateSnapshot: () => PageAggregateAiSnapshot;
  onPersistedMetaChange?: (meta: PageBodyPersistedMeta) => void;
  onPageHeadTitleChange?: (title: string) => void;
};

const DocumentAiAgentPanelRuntime = dynamic<DocumentAiAgentPanelProps>(
  () => import("./DocumentAiAgentPanel.runtime").then((mod) => mod.DocumentAiAgentPanelRuntime),
  {
    ssr: false,
    loading: () => null,
  },
);

// 轻量 host：页面挂载时只维护可用态，真正的 AI runtime 首次打开后再加载。
export function DocumentAiAgentPanel(props: DocumentAiAgentPanelProps) {
  const activated = useAiAgentUiStore((state) => state.documentAgentActivated);
  const setOpen = useAiAgentUiStore((state) => state.setDocumentAgentOpen);
  const setAvailable = useAiAgentUiStore((state) => state.setDocumentAgentAvailable);

  useEffect(() => {
    setAvailable(true);
    return () => {
      setAvailable(false);
      setOpen(false);
    };
  }, [setAvailable, setOpen]);

  if (!activated) {
    return null;
  }

  return <DocumentAiAgentPanelRuntime {...props} />;
}
