import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { notifyHost, runtimeConfig } from '@/lib/runtime-config';

export default function ShireIntegrationBridge() {
  const navigate = useNavigate();

  useEffect(() => {
    if (!runtimeConfig.embedded) return undefined;

    const onMessage = (event) => {
      if (runtimeConfig.hostOrigin !== '*' && event.origin !== runtimeConfig.hostOrigin) return;
      const message = event.data;
      if (!message || message.source !== 'shire-host') return;

      if (message.type === 'NAVIGATE' && typeof message.payload?.path === 'string') {
        navigate(message.payload.path);
      }
      if (message.type === 'PING') {
        notifyHost('PONG', { at: new Date().toISOString() });
      }
    };

    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, [navigate]);

  return null;
}
