// MediaFrame.jsx — embeds a standalone HTML asset (self-contained page with its
// own <head>, styles, and scripts) via a sandboxed iframe. The iframe renders
// at a fixed base size (default 1920×1080, 16:9) and is CSS-scaled to fit the
// parent container, so embedded content lays out at a predictable viewport
// instead of stretching/clipping to whatever the slot happens to be.
// Mirrors MediaImg's "Missing · {src}" fallback.

const { useState: useMF, useEffect: useMFE, useRef: useMFR } = React;

function MediaFrame({ src, title = "", baseWidth = 1920, baseHeight = 1080, style = {} }) {
  const [failed, setFailed] = useMF(false);
  const [scale, setScale] = useMF(1);
  const wrapRef = useMFR(null);

  useMFE(() => {
    const el = wrapRef.current;
    if (!el) return;
    const update = () => {
      const r = el.getBoundingClientRect();
      if (!r.width || !r.height) return;
      setScale(Math.min(r.width / baseWidth, r.height / baseHeight));
    };
    update();
    const ro = new ResizeObserver(update);
    ro.observe(el);
    return () => ro.disconnect();
  }, [baseWidth, baseHeight]);

  if (failed) {
    return (
      <div style={{
        width: "100%", height: "100%",
        background:
          "repeating-linear-gradient(45deg, #0c0c0c 0 10px, #141414 10px 20px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        color: "var(--mute)",
        fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: ".14em",
        textTransform: "uppercase", textAlign: "center", padding: 24,
        ...style,
      }}>
        Missing · {src}
      </div>
    );
  }

  return (
    <div
      ref={wrapRef}
      style={{
        width: "100%",
        height: "100%",
        position: "relative",
        overflow: "hidden",
        ...style,
      }}
    >
      <iframe
        src={src}
        title={title}
        loading="lazy"
        sandbox="allow-scripts allow-same-origin"
        onError={() => setFailed(true)}
        style={{
          width: baseWidth,
          height: baseHeight,
          border: 0,
          display: "block",
          position: "absolute",
          top: 0,
          left: 0,
          transformOrigin: "top left",
          transform: `scale(${scale})`,
        }}
      />
    </div>
  );
}

window.MediaFrame = MediaFrame;
