// VideoEmbed - one click-to-play video frame, shared by the hero and the pillars.
//
// Why a facade and not a plain iframe: a single Loom embed pulls ~250 requests
// from cdn.loom.com. Eight of them on one page is ~2000 requests competing for
// the same host, which made the page crawl and left some players never
// finishing. So nothing third-party loads until the viewer asks for it. Until
// then this is a static poster (one lazy image) over the accent gradient; the
// real iframe is mounted on click, with autoplay so it stays a single click.
//
// States: poster (has a video, not started) -> iframe (started).
// No video at all, or a poster that fails to load, falls back to `placeholder`.

function VideoEmbed({
  url,
  aspect,
  poster,
  seconds,
  label,
  accent,
  accentDark,
  className = '',
  placeholder = null,
  eagerPoster = false,
}) {
  const [started, setStarted] = React.useState(false);
  const [posterFailed, setPosterFailed] = React.useState(false);

  const video = window.videoEmbed(url);
  const wrapStyle = aspect ? {['--aspect']: `${aspect}%`} : undefined;
  const duration = window.fmtDuration(seconds);

  // Nothing wired up yet - whatever the caller wants to show instead.
  if (!video) return placeholder;

  if (started) {
    return (
      <div className={`video-wrap ${className}`} style={wrapStyle}>
        <iframe
          src={`${video.src}?autoplay=1`}
          title={label}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
        />
      </div>
    );
  }

  const showPoster = poster && !posterFailed;
  return (
    <button
      type="button"
      className={`video-wrap video-facade ${showPoster ? '' : 'no-poster'} ${className}`}
      style={{
        ...wrapStyle,
        ...(accent ? {['--accent']: accent, ['--accent-dark']: accentDark || accent} : {}),
      }}
      onClick={() => setStarted(true)}
      aria-label={`Play ${label}${duration ? `, ${duration}` : ''}`}
    >
      {showPoster && (
        <img
          src={poster}
          alt=""
          loading={eagerPoster ? 'eager' : 'lazy'}
          fetchPriority={eagerPoster ? 'high' : 'auto'}
          decoding="async"
          onError={() => setPosterFailed(true)}
        />
      )}
      <span className="video-facade-scrim" aria-hidden="true"></span>
      <span className="video-facade-play" aria-hidden="true">
        <i className="fas fa-play"></i>
      </span>
      {duration && <span className="video-facade-time" aria-hidden="true">{duration}</span>}
    </button>
  );
}

window.VideoEmbed = VideoEmbed;
