'use client';

import { useState, useEffect } from 'react';
import { logger } from '~/lib/logger';
import { sanitizeIframelyHtml } from '~/lib/iframely-utils';

// SRI hash pins the exact embed.js build we audited. Update with: make -C infra update-iframely-sri
const EMBED_JS_SRC = 'https://cdn.iframe.ly/embed.js';
const EMBED_JS_INTEGRITY = 'sha256-3GwLJcK+mlckENNer3dPxN7pSjeNqIRkurShyMXvtsw=';

function ensureEmbedJs() {
  const existing = document.querySelector<HTMLScriptElement>(
    `script[src="${EMBED_JS_SRC}"]`,
  );
  if (existing) {
    // Already injected — ask embed.js to re-scan new embeds in the DOM.
    (window as { iframely?: { load(): void } }).iframely?.load();
    return;
  }
  const script = document.createElement('script');
  script.src = EMBED_JS_SRC;
  script.integrity = EMBED_JS_INTEGRITY;
  script.crossOrigin = 'anonymous';
  script.async = true;
  document.head.appendChild(script);
}

interface IframelyEmbedProps {
  url: string;
  width?: number;
  height?: number;
}

export default function IframelyEmbed({ url, width = 444, height = 250 }: IframelyEmbedProps) {
  const [html, setHtml] = useState<string | null>(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    const apiUrl = `${import.meta.env.VITE_API_URL}/iframely?url=${encodeURIComponent(url)}`;
    logger.debug('fetching iframely embed: ' + apiUrl);

    fetch(apiUrl)
      .then(res => {
        if (!res.ok) throw new Error(`iframely API returned ${res.status}`);
        return res.json() as Promise<{ html?: string }>;
      })
      .then(data => {
        if (data.html) {
          setHtml(sanitizeIframelyHtml(data.html));
        } else {
          setError(true);
        }
      })
      .catch(err => {
        logger.error({ err }, 'iframely embed fetch failed');
        setError(true);
      });
  }, [url]);

  useEffect(() => {
    if (!html) return;
    ensureEmbedJs();
  }, [html]);

  if (error) {
    return (
      <figure className="embed-container">
        <a href={url} target="_blank" rel="noopener noreferrer">{url}</a>
      </figure>
    );
  }

  if (!html) {
    return (
      <figure className="embed-container" style={{ width, minHeight: height }}>
        <p className="text-gray-500 text-sm">Loading embed...</p>
      </figure>
    );
  }

  return (
    <figure
      className="embed-container"
      dangerouslySetInnerHTML={{ __html: html }}
    />
  );
}
