'use client';

// Plain progress bar — no waveform, no animation. Same playhead mechanics as
// the canvas modes (clip-path via --p, click/drag to seek). Use when you want
// a track scrubber without amplitude visualisation.

import { useEffect, useState } from 'react';
import { alpha, useThemeColor } from '@djangocfg/ui-core/styles/palette';
import { usePlayerAudio, usePlayerControls } from '../../context/selectors';
import { usePlayheadLoop } from '../../hooks/usePlayheadLoop';
import { attachHover, attachSeek } from './waveformInteraction';

type Props = { height?: number; seekStartsPlayback?: boolean };

export function ProgressBar({ height = 4, seekStartsPlayback }: Props) {
  const audio = usePlayerAudio();
  const controls = usePlayerControls();
  const [container, setContainer] = useState<HTMLDivElement | null>(null);
  const fgHex = useThemeColor('primary');
  const mutedHex = useThemeColor('muted-foreground');

  usePlayheadLoop(audio, container, true);

  useEffect(() => {
    if (!container) return;
    const detachSeek = attachSeek(container, audio, {
      startsPlayback: seekStartsPlayback,
      onPlayRequest: () => void controls.play(),
    });
    const detachHover = attachHover(container, audio);
    return () => {
      detachSeek();
      detachHover();
    };
  }, [audio, container, controls, seekStartsPlayback]);

  return (
    <div
      ref={setContainer}
      className="audioplayer-waveform relative w-full select-none cursor-pointer"
      style={{ ['--p' as string]: '0%' }}
      data-mode="progress"
    >
      <div
        className="rounded-full"
        style={{ height, backgroundColor: alpha(mutedHex, 0.25) }}
      />
      <div
        className="absolute inset-y-0 left-0 rounded-full"
        style={{
          width: 'var(--p)',
          backgroundColor: fgHex,
        }}
        aria-hidden="true"
      />
      <div
        className="audioplayer-hover pointer-events-none absolute -top-1 -bottom-1 w-px transition-opacity"
        style={{
          left: 'var(--hp, -10px)',
          opacity: 'var(--ho, 0)',
          backgroundColor: alpha(mutedHex, 0.5),
        }}
        aria-hidden="true"
      />
      <div
        data-audioplayer-time-tip
        className="audioplayer-tip pointer-events-none absolute -top-7 -translate-x-1/2 rounded bg-foreground px-1.5 py-0.5 text-[10px] tabular-nums text-background transition-opacity"
        style={{
          left: 'var(--hp, -100px)',
          opacity: 'var(--ht, 0)',
        }}
        aria-hidden="true"
      />
    </div>
  );
}
