'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-video-element` already defaults the embed to `controls=0`,
 * `rel=0`, `iv_load_policy=3`, `modestbranding=1`. We extend that via
 * the `config` prop (serialized into `data-config`, merged into the
 * IFrame `playerVars`) to also suppress YouTube's keyboard handling
 * (`disablekb=1` — our controls own keyboard) and the in-player
 * close-captions toggle the element turns on by default.
 *
 * NOTE: YouTube's ToS forbids fully hiding its branding — a small logo
 * and the pause-screen overlay remain by design. `modestbranding=1` is
 * the maximum allowed suppression.
 */

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 = {
  // We render our own media-chrome control bar — hide YouTube's.
  controls: 0,
  // Our keyboard shortcuts own the player; disable YouTube's.
  disablekb: 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} />}
    </>
  );
}
