import { useEffect, useMemo, useRef } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { createPenpalHostBridge } from '@teres/iframe-bridge';
import { setChildPromise, clearChildPromise } from '@/iframe/bridgeManager';
import logger from '@/utils/logger';

export default function RagflowAgentPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const src = useMemo(() => `/ragflow/agent/${id ?? ''}`, [id]);

  logger.info('RagflowAgentPage', id, src);

  useEffect(() => {
    const el = iframeRef.current;
    if (!el) return;
    const { destroy, child } = createPenpalHostBridge({
      iframe: el,
      methods: {
        navigate: (to: string) => navigate(to),
        close: () => navigate('/agents'),
        agentReady: () => {
          // 可选：在需要时记录或触发后续逻辑
        },
      },
    });
    setChildPromise(child);
    return () => {
      clearChildPromise();
      destroy();
    };
  }, [navigate]);

  // 如需兼容旧的 postMessage 事件，可保留以下监听；为了纯 Penpal，此处移除

  return (
    <iframe
      ref={iframeRef}
      title="ragflow-agent"
      src={src}
      style={{ width: '100%', height: '100vh', border: 'none' }}
    />
  );
}