import { useEffect, useRef, useState } from 'react';
import { bindIframeDocumentHeightSync } from '../utils/iframeContentHeight';

export function PagePreviewFrame({
  src,
  title,
  reloadKey = 0,
  minHeight = 680,
  maxHeight = 12000,
  className = 'mindspace-page-preview-frame',
}: {
  src: string;
  title: string;
  reloadKey?: number;
  minHeight?: number;
  maxHeight?: number;
  className?: string;
}) {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [height, setHeight] = useState(minHeight);

  useEffect(() => {
    setHeight(minHeight);
  }, [src, reloadKey, minHeight]);

  useEffect(() => {
    const iframe = iframeRef.current;
    if (!iframe) return;
    return bindIframeDocumentHeightSync(iframe, {
      minHeight,
      maxHeight,
      onHeight: setHeight,
    });
  }, [maxHeight, minHeight, src, reloadKey]);

  return (
    <iframe
      ref={iframeRef}
      key={`${src}:${reloadKey}`}
      title={title}
      src={src}
      sandbox="allow-same-origin"
      className={className}
      style={{ height: `${height}px` }}
    />
  );
}
