"use client";

import React, { useEffect, useRef } from "react";
import { IframeEmbedProps, bgColorMap } from "./types";

/**
 * IframeEmbed — A generic, responsive iframe component for embedding third-party content
 * such as Brand Featured badges, widgets, or any external HTML page.
 *
 * Features:
 * - **Auto-resize:** Listens for `postMessage` events with an `{ iframeHeight: number }` payload
 *   from the embedded page and adjusts the iframe height dynamically.
 * - **Background color:** Supports predefined background colors (`gray90`, `green`, `white`)
 *   behind the iframe, defaulting to transparent.
 * - **Lazy loading:** The iframe uses `loading="lazy"` for performance.
 * - **Anchor support:** An optional `anchorId` is applied to the wrapping `<section>` for
 *   deep-linking or scroll-to navigation.
 *
 * @example
 * ```tsx
 * <IframeEmbed
 *   iframeUrl="https://api.brandfeatured.com/badges/badge-news_dark.html?id=123"
 *   backgroundColor="green"
 *   anchorId="brand-badge"
 * />
 * ```
 */
export const IframeEmbed: React.FC<IframeEmbedProps> = ({
  iframeUrl,
  anchorId,
  backgroundColor,
  height,
}) => {
  const iframeRef = useRef<HTMLIFrameElement>(null);

  useEffect(() => {
    if (!iframeUrl) return;

    const handleMessage = (event: MessageEvent) => {
      const height = event.data?.iframeHeight;
      if (
        typeof height === "number" &&
        Number.isFinite(height) &&
        height > 0 &&
        height <= 10000 &&
        iframeRef.current
      ) {
        iframeRef.current.style.height = `${height}px`;
      }
    };

    window.addEventListener("message", handleMessage);
    return () => window.removeEventListener("message", handleMessage);
  }, [iframeUrl]);

  if (!iframeUrl) return null;

  return (
    <section id={anchorId} className="w-full">
      <iframe
        ref={iframeRef}
        src={iframeUrl}
        width="100%"
        frameBorder="0"
        scrolling="no"
        style={{
          background: backgroundColor
            ? bgColorMap[backgroundColor]
            : "transparent",
          ...(height ? { height: `${height}px` } : {}),
        }}
        title="Iframe Embed"
        loading="lazy"
      />
    </section>
  );
};

export default IframeEmbed;
