
import React, { useRef, forwardRef, useImperativeHandle } from 'react';

export interface IframeManagerRef {
  loadUrl: (url: string) => void;
  refresh: () => void;
  injectScript: (script: string) => void;
  requestSummary: () => void;
}

interface IframeManagerProps {
  onTitleChange: (title: string) => void;
}

const IframeManager = forwardRef<IframeManagerRef, IframeManagerProps>(
  ({ onTitleChange }, ref) => {
    const iframeRef = useRef<HTMLIFrameElement>(null);

    const loadUrl = async (url: string) => {
      try {
        console.log('Loading into iframe:', url);
        
        const proxiedUrl = url.startsWith('http') 
          ? `https://embed-proxy-prod.gamma-app.workers.dev/?alt_url=${encodeURIComponent(url)}`
          : url;

        if (iframeRef.current) {
          iframeRef.current.src = proxiedUrl;
        }
      } catch (error) {
        console.error('Error loading page:', error);
        alert(`Failed to load page: ${error}`);
      }
    };

    const refresh = () => {
      if (iframeRef.current && iframeRef.current.src) {
        const currentSrc = iframeRef.current.src;
        iframeRef.current.src = '';
        setTimeout(() => {
          if (iframeRef.current) {
            iframeRef.current.src = currentSrc;
          }
        }, 100);
      }
    };

    const injectScript = (script: string) => {
      if (iframeRef.current?.contentWindow) {
        iframeRef.current.contentWindow.postMessage({
          type: 'user-script',
          script
        }, '*');
      }
    };

    const requestSummary = () => {
      if (iframeRef.current?.contentWindow) {
        iframeRef.current.contentWindow.postMessage('extract-summary', '*');
      }
    };

    useImperativeHandle(ref, () => ({
      loadUrl,
      refresh,
      injectScript,
      requestSummary
    }));

    return (
      <iframe
        ref={iframeRef}
        className="w-full h-full border-none"
        sandbox="allow-scripts allow-same-origin allow-popups allow-forms"
        title="Embedded Browser"
      />
    );
  }
);

IframeManager.displayName = 'IframeManager';

export default IframeManager;
