'use client';

import { MediaPlaybackRateButton } from 'media-chrome/react';
import { cn } from '@djangocfg/ui-core/lib';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@djangocfg/ui-core/components';
import type { ComponentProps, ReactNode } from 'react';

export type PlaybackRateProps = Omit<
  ComponentProps<typeof MediaPlaybackRateButton>,
  'rates'
> & {
  /** Space-separated list, e.g. `'0.5 1 1.5 2'`, or an array of numbers. */
  readonly rates?: string | readonly number[];
  /** Tooltip copy. Defaults to `"Playback speed"`. Pass `false` to opt out. */
  readonly label?: ReactNode | false;
};

const DEFAULT_RATES: readonly number[] = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];

export function PlaybackRate({ className, rates, label, ...props }: PlaybackRateProps) {
  const value = rates ?? DEFAULT_RATES;
  const button = (
    <MediaPlaybackRateButton
      {...props}
      // media-chrome's setter accepts `string | ArrayLike<number>` — the
      // React typing pulls from the getter only, which is narrower.
      rates={value as unknown as ArrayLike<number>}
      className={cn(
        'video-player__control h-8 px-2 text-xs tabular-nums',
        className,
      )}
    />
  );

  if (label === false) return button;

  return (
    <Tooltip>
      <TooltipTrigger asChild>{button}</TooltipTrigger>
      <TooltipContent side="top">{label ?? 'Playback speed'}</TooltipContent>
    </Tooltip>
  );
}
