'use client';

import { useEffect, useRef } from 'react';

interface ResponsiveIframeProps {
  src: string;
  className?: string;
  allow?: string;
  style?: React.CSSProperties;
  token?: string;
}

export function ResponsiveIframe({ src, className = '', allow, style, token }: ResponsiveIframeProps) {
  const iframeRef = useRef<HTMLIFrameElement>(null);

  const fullSrc = token ? 
    `${src}${src.includes('?') ? '&' : '?'}token=${encodeURIComponent(token)}` : 
    src;

  useEffect(() => {
    const iframe = iframeRef.current;
    if (!iframe) return;

    const calculateHeight = () => {
      const pageY = (elem: HTMLElement): number => {
        return elem.offsetParent ? 
          (elem.offsetTop + pageY(elem.offsetParent as HTMLElement)) : 
          elem.offsetTop;
      };

      const height = document.documentElement.clientHeight;
      const iframeY = pageY(iframe);
      const newHeight = Math.max(0, height - iframeY);
      iframe.style.height = `${newHeight}px`;
    };

    const handleHashChange = () => {
      if (window.location.hash && window.location.hash.length) {
        const iframeURL = new URL(iframe.src);
        iframeURL.hash = window.location.hash;
        iframe.src = iframeURL.toString();
      }
    };
    
    // Handle authentication messages from iframe
    const handleMessage = (event: MessageEvent) => {
      // Only accept messages from our iframe
      if (iframe.contentWindow !== event.source) return;
      
      const { type, data } = event.data || {};
      
      // Handle auth related messages
      if (type === 'AUTH_ERROR' || type === 'SESSION_EXPIRED') {
        console.log('Auth error in iframe:', data);
        // Optionally redirect to login page
        // window.location.href = '/signin';
      }
    };

    // Initial setup
    calculateHeight();
    handleHashChange();

    // Event listeners
    window.addEventListener('resize', calculateHeight);
    window.addEventListener('hashchange', handleHashChange);
    window.addEventListener('message', handleMessage);
    iframe.addEventListener('load', calculateHeight);

    // Cleanup
    return () => {
      window.removeEventListener('resize', calculateHeight);
      window.removeEventListener('hashchange', handleHashChange);
      window.removeEventListener('message', handleMessage);
      iframe.removeEventListener('load', calculateHeight);
    };
  }, []);

  return (
    <iframe
      ref={iframeRef}
      id="myFrame"
      src={fullSrc}
      className={`w-full border-none ${className}`}
      style={{
        display: 'block',
        width: '100%',
        height: '100%',
        ...style
      }}
      allow={allow}
      allowFullScreen
    />
  );
} 