/**
 * PlayerControls — Minimal playback UI for BradlyPlayer.
 *
 * Provides play/pause, scrub bar, and time display.
 * Rendered at the bottom of the player when `controls` prop is true.
 */
import React, { useRef, useCallback } from 'react';

interface PlayerControlsProps {
  frame: number;
  durationInFrames: number;
  fps: number;
  playing: boolean;
  onPlay: () => void;
  onPause: () => void;
  onSeek: (frame: number) => void;
}

function formatTime(frames: number, fps: number): string {
  const totalSeconds = Math.floor(frames / fps);
  const mins = Math.floor(totalSeconds / 60);
  const secs = totalSeconds % 60;
  return `${mins}:${String(secs).padStart(2, '0')}`;
}

export const PlayerControls: React.FC<PlayerControlsProps> = ({
  frame,
  durationInFrames,
  fps,
  playing,
  onPlay,
  onPause,
  onSeek,
}) => {
  const scrubRef = useRef<HTMLDivElement>(null);
  const isDragging = useRef(false);

  const progress = durationInFrames > 0 ? (frame / (durationInFrames - 1)) * 100 : 0;

  const scrubToPosition = useCallback(
    (clientX: number) => {
      if (!scrubRef.current) return;
      const rect = scrubRef.current.getBoundingClientRect();
      const pct = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
      onSeek(Math.round(pct * (durationInFrames - 1)));
    },
    [onSeek, durationInFrames]
  );

  const handlePointerDown = useCallback(
    (e: React.PointerEvent) => {
      e.preventDefault();
      (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
      isDragging.current = true;
      scrubToPosition(e.clientX);
    },
    [scrubToPosition]
  );

  const handlePointerMove = useCallback(
    (e: React.PointerEvent) => {
      if (!isDragging.current) return;
      scrubToPosition(e.clientX);
    },
    [scrubToPosition]
  );

  const handlePointerUp = useCallback(() => {
    isDragging.current = false;
  }, []);

  return (
    <div
      style={{
        height: 32,
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        padding: '0 8px',
        backgroundColor: 'rgba(0, 0, 0, 0.85)',
        borderTop: '1px solid rgba(255, 255, 255, 0.08)',
        userSelect: 'none',
      }}
    >
      {/* Play/Pause */}
      <button
        onClick={playing ? onPause : onPlay}
        title={playing ? 'Pause' : 'Play'}
        style={{
          width: 24,
          height: 24,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: 'none',
          border: 'none',
          color: '#fff',
          cursor: 'pointer',
          padding: 0,
          flexShrink: 0,
        }}
      >
        {playing ? (
          <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
            <rect x="6" y="4" width="4" height="16" />
            <rect x="14" y="4" width="4" height="16" />
          </svg>
        ) : (
          <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
            <polygon points="5,3 19,12 5,21" />
          </svg>
        )}
      </button>

      {/* Scrub Bar */}
      <div
        ref={scrubRef}
        style={{
          flex: 1,
          height: 6,
          backgroundColor: 'rgba(255, 255, 255, 0.15)',
          borderRadius: 3,
          cursor: 'pointer',
          position: 'relative',
        }}
        onPointerDown={handlePointerDown}
        onPointerMove={handlePointerMove}
        onPointerUp={handlePointerUp}
        onPointerCancel={handlePointerUp}
      >
        {/* Progress fill */}
        <div
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            height: '100%',
            width: `${progress}%`,
            backgroundColor: '#8b5cf6',
            borderRadius: 3,
            transition: isDragging.current ? 'none' : 'width 50ms linear',
          }}
        />
        {/* Thumb */}
        <div
          style={{
            position: 'absolute',
            top: '50%',
            left: `${progress}%`,
            width: 10,
            height: 10,
            borderRadius: '50%',
            backgroundColor: '#fff',
            transform: 'translate(-50%, -50%)',
            boxShadow: '0 1px 4px rgba(0,0,0,0.5)',
          }}
        />
      </div>

      {/* Time display */}
      <span
        style={{
          fontSize: 10,
          fontFamily: 'monospace',
          color: 'rgba(255, 255, 255, 0.6)',
          flexShrink: 0,
          minWidth: 60,
          textAlign: 'right',
        }}
      >
        {formatTime(frame, fps)} / {formatTime(durationInFrames, fps)}
      </span>
    </div>
  );
};
