import { useEffect, useRef } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { createPenpalHostBridge, toChildPath } from '@teres/iframe-bridge';

export default function RagflowIframePage() {
  const location = useLocation();
  const navigate = useNavigate();
  // 将宿主的 "/route-ragflow/**" 路径转换为子应用的 "/ragflow/**" 路径
  const childPath = toChildPath(location.pathname);
  const src = `/ragflow${childPath}${location.search}${location.hash}`;
  const iframeRef = useRef<HTMLIFrameElement>(null);

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

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