'use client';

import { useRef } from 'react';
import { usePlayerMeta } from '../../context/selectors';
import { usePeaks } from '../../hooks/usePeaks';
import type { WaveformConfig } from '../../types';
import { BarsWaveform } from './BarsWaveform';
import { LiveWaveform } from './LiveWaveform';
import { PeaksWaveform } from './PeaksWaveform';
import { ProgressBar } from './ProgressBar';
import { WaveformSkeleton } from './WaveformSkeleton';

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

export function Waveform({ config, height, seekStartsPlayback }: Props) {
  const meta = usePlayerMeta();
  const triggerRef = useRef<HTMLDivElement | null>(null);

  const mode = config?.mode ?? 'peaks';
  const barWidth = config?.barWidth ?? 2;
  const barGap = config?.barGap ?? 1;

  const peaksEnabled = mode === 'peaks';
  const { peaks, loading, error } = usePeaks({
    src: meta.src,
    enabled: peaksEnabled,
    triggerRef,
    decodeOnMount: config?.decodeOnMount,
  });

  if (mode === 'none') return null;
  if (mode === 'progress')
    return <ProgressBar height={Math.min(height, 6)} seekStartsPlayback={seekStartsPlayback} />;
  if (mode === 'bars') return <BarsWaveform height={height} barWidth={barWidth} barGap={barGap} />;
  if (mode === 'live')
    return (
      <LiveWaveform
        height={height}
        barWidth={barWidth}
        barGap={barGap}
        seekStartsPlayback={seekStartsPlayback}
      />
    );

  // peaks mode
  if (loading || (!peaks && !error)) {
    return (
      <div ref={triggerRef}>
        <WaveformSkeleton height={height} />
      </div>
    );
  }
  if (!peaks) {
    // Decode failed — degrade to a plain scrubber. Playback works; user can
    // still seek; we just can't show amplitude. Per ADR-002 we never surface
    // decode failure as a hard error.
    return <ProgressBar height={Math.min(height, 6)} seekStartsPlayback={seekStartsPlayback} />;
  }
  return (
    <div ref={triggerRef}>
      <PeaksWaveform
        peaks={peaks}
        height={height}
        barWidth={barWidth}
        barGap={barGap}
        seekStartsPlayback={seekStartsPlayback}
      />
    </div>
  );
}
