import clsx from 'clsx';
import React, { useMemo } from 'react';

interface WaveformPreviewProps {
  length?: number;
  isPlaying: boolean;
  currentTime?: number;
  maxDuration?: number;
}

export const WaveformPreview: React.FC<WaveformPreviewProps> = ({
  length = 60,
  isPlaying,
  currentTime = 0,
  maxDuration = 30,
}) => {
  // Generate waveform heights once and memoize them (4.781px min, 24.438px max)
  // Memoized per length value to ensure consistent appearance
  const waveformHeights = useMemo(
    () => Array.from({ length }, () => 4.781 + Math.random() * 19.657),
    [length]
  );

  const timelineBars = 33;
  const currentBar = (currentTime / maxDuration) * timelineBars;

  return (
    <div className='flex h-[48px] w-full items-center gap-[2px] overflow-hidden px-0'>
      {waveformHeights.map((height, i) => {
        // Determine if this bar is in the timeline, played, or unplayed
        const isInTimeline = i < timelineBars;
        const isPlayed = i < currentBar;

        return (
          <div
            key={`waveform-bar-${i}`}
            className={clsx(
              'w-[2px] origin-center rounded-[53.125px] transition-colors duration-300 ease-linear',
              {
                'bg-foreground-primary': isPlayed, // Bright white for played bars
                'bg-foreground-primary/20': !isPlayed && isInTimeline, // Dim for unplayed timeline bars
                'bg-foreground-primary/10': !isPlayed && !isInTimeline, // Even dimmer for bars beyond timeline
                'animate-waveform-pulse': isPlaying,
              }
            )}
            style={{
              height: `${height}px`,
              animationDelay: isPlaying ? `${i * 0.05}s` : undefined,
            }}
          />
        );
      })}
    </div>
  );
};
