'use client';

import { useEffect, useRef, useState } from 'react';

export function PostEmbed({ src, title }: { src: string; title: string }) {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [height, setHeight] = useState(480);

  useEffect(() => {
    const onMessage = (event: MessageEvent) => {
      if (event.source !== iframeRef.current?.contentWindow) return;
      const data = event.data;
      if (data && typeof data === 'object' && data.type === 'plaza:embed-height') {
        const next = Number(data.height);
        if (Number.isFinite(next) && next > 0) setHeight(Math.min(next, 4000));
      }
    };
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, []);

  return (
    <iframe
      ref={iframeRef}
      src={src}
      title={title}
      sandbox="allow-scripts allow-same-origin"
      className="w-full rounded-2xl border border-[#d6d0c3] bg-white"
      style={{ height }}
      loading="lazy"
    />
  );
}
