'use client';

/**
 * `<youtube-video slot="media">` — registers the custom element via
 * `youtube-video-element` side-effect import. The element wraps the
 * YouTube IFrame API and exposes an `HTMLVideoElement`-shaped surface
 * that media-chrome's `<MediaController>` drives.
 *
 * YouTube embeds render their OWN native control set inside the iframe,
 * and YouTube's ToS chrome (title bar, branding tray, share/clock icons)
 * cannot be hidden via player params. Trying to drive the embed with our
 * own media-chrome controls layered on top produced a duplicate, jittery
 * UI (two play buttons, two bottom bars) — see VideoPlayer.tsx. So for
 * YouTube we let the native player own playback entirely: `controls=1`
 * gives YouTube's standard hover-to-reveal controls with seek bar, time,
 * volume and fullscreen — one coherent, familiar control set.
 *
 * We still pass `rel=0`, `modestbranding=1`, `iv_load_policy=3` to trim
 * end-screen suggestions, annotations and branding to the maximum the
 * ToS allows.
 */

import 'youtube-video-element';
import './jsx-augmentation';
import { MediaPosterImage } from 'media-chrome/react';
import type { YouTubeSource, VideoPlayerSettings } from '../types';

export interface YouTubeCanvasProps extends VideoPlayerSettings {
  readonly source: YouTubeSource;
}

/**
 * Extra YouTube IFrame `playerVars` merged on top of the element
 * defaults. Keep keys YouTube-documented:
 * https://developers.google.com/youtube/player_parameters
 */
const YT_PLAYER_VARS = {
  // YouTube's native controls own playback (no duplicate media-chrome bar).
  controls: 1,
  // Minimise the YouTube logo chrome (max suppression allowed by ToS).
  modestbranding: 1,
  // Do not surface "More videos" / related-channel end-screen suggestions.
  rel: 0,
  // Hide video annotations.
  iv_load_policy: 3,
  // Keep playback inline on iOS instead of forcing native fullscreen.
  playsinline: 1,
  // Don't auto-load closed captions.
  cc_load_policy: 0,
} as const;

export function YouTubeCanvas({
  source,
  autoPlay,
  muted,
  loop,
}: YouTubeCanvasProps) {
  const params = new URLSearchParams();
  params.set('v', source.videoId);
  if (source.startTime) params.set('t', `${source.startTime}s`);
  if (source.playlistId) params.set('list', source.playlistId);
  const src = `https://www.youtube.com/watch?${params.toString()}`;

  return (
    <>
      <youtube-video
        slot="media"
        src={src}
        config={YT_PLAYER_VARS}
        {...(muted && { muted: true })}
        {...(autoPlay && { autoplay: true })}
        {...(loop && { loop: true })}
        playsInline
      />
      {source.poster && <MediaPosterImage slot="poster" src={source.poster} />}
    </>
  );
}
