import { useRef } from 'react';

export function useSeekBar(mediaRef: React.RefObject<HTMLMediaElement | null>, duration: number) {
  const barRef = useRef<HTMLDivElement>(null);

  const seekTo = (clientX: number) => {
    const el = mediaRef.current;
    const bar = barRef.current;
    if (!el || !bar || !duration) return;
    const rect = bar.getBoundingClientRect();
    const pct = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
    el.currentTime = pct * duration;
  };

  const onSeekDown = (e: React.MouseEvent<HTMLDivElement>) => {
    e.preventDefault();
    seekTo(e.clientX);
    const onMove = (ev: MouseEvent) => seekTo(ev.clientX);
    const onUp = () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  };

  return { barRef, onSeekDown };
}

type SeekBarProps = {
  barRef: React.RefObject<HTMLDivElement | null>;
  onSeekDown: (e: React.MouseEvent<HTMLDivElement>) => void;
  pct: number;
  trackClass?: string;
  fillClass?: string;
  thumbClass?: string;
};

export const SeekBar = ({
  barRef,
  onSeekDown,
  pct,
  trackClass = 'bg-duck-dark/10',
  fillClass = 'bg-duck-teal',
  thumbClass = 'bg-duck-teal border-white',
}: SeekBarProps) => (
  <div ref={barRef} onMouseDown={onSeekDown} className="relative h-4 flex items-center cursor-pointer group">
    <div className={`absolute left-0 right-0 h-1.5 rounded-full ${trackClass} pointer-events-none`}>
      <div className={`absolute inset-y-0 left-0 rounded-full ${fillClass}`} style={{ width: `${pct}%` }} />
    </div>
    <div
      className={`absolute top-1/2 -translate-y-1/2 w-3.5 h-3.5 rounded-full shadow-md border-2 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none ${thumbClass} ${fillClass}`}
      style={{ left: `calc(${pct}% - 7px)` }}
    />
  </div>
);
