'use client';

/**
 * VideoPlayer — composable shell over `media-chrome` web components.
 *
 * The shell is just a `<MediaController>` wrapper + a `<CanvasDispatcher>`
 * that mounts the right media element (`<video>`, `<youtube-video>`,
 * `<vimeo-video>`, `<hls-video>`, `<iframe>`) into the `media` slot.
 *
 * Custom layouts: pass `children` to replace the default control bar.
 * `controls={false}` opts out of any control surface (useful for
 * iframe sources where the embed renders its own UI).
 */

import { useMemo, type CSSProperties } from 'react';
import { MediaController } from 'media-chrome/react';
import { cn } from '@djangocfg/ui-core/lib';
import './styles/video-player.css';

import type { VideoPlayerProps, AspectRatioValue } from './types';
import { parseEmbedUrl } from './utils/parse-embed-url';
import { CanvasDispatcher } from './canvas/canvas-dispatcher';
import {
  ControlsBar,
  PlayButton,
  SeekBar,
  Volume,
  PlaybackRate,
  Pip,
  Fullscreen,
} from './parts';

function aspectRatioStyle(ar: AspectRatioValue): CSSProperties | undefined {
  if (ar === 'fill') return { height: '100%' };
  if (ar === 'auto') return undefined;
  return { aspectRatio: String(ar) };
}

export function VideoPlayer({
  source,
  controls = true,
  aspectRatio = 16 / 9,
  className,
  children,
  ...settings
}: VideoPlayerProps) {
  const normalized = useMemo(
    () => (typeof source === 'string' ? parseEmbedUrl(source) : source),
    [source],
  );

  const isIframe = normalized.type === 'iframe';
  // For iframe embeds media-chrome cannot drive the inner player — hide the
  // control bar to avoid a non-functional UI.
  const showControls = controls && !isIframe;

  return (
    <MediaController
      // Fade controls + scrim after 2.5s of inactivity while playing;
      // they reappear on mousemove / pause / focus (media-chrome built-in).
      autohide="2.5"
      className={cn(
        'video-player relative block w-full overflow-hidden rounded-lg bg-black',
        className,
      )}
      style={aspectRatioStyle(aspectRatio)}
    >
      <CanvasDispatcher source={normalized} {...settings} />
      {children ??
        (showControls && (
          <ControlsBar>
            <PlayButton />
            <SeekBar />
            <Volume iconOnly />
            <PlaybackRate />
            <Pip />
            <Fullscreen />
          </ControlsBar>
        ))}
    </MediaController>
  );
}
