/**
 * AudioVisualizer component
 *
 * Displays a simple audio level visualization using bars.
 * Uses the Web Audio API's AnalyserNode data (passed as audioLevel)
 * to show microphone input levels during recording.
 *
 * Design: Calm, non-aggressive colors following PDA-friendly guidelines.
 */

import { useMemo } from "react";

export interface AudioVisualizerProps {
  /** Current audio level (0-1) */
  audioLevel: number;
  /** Whether the visualizer is actively listening */
  isActive: boolean;
  /** Number of bars to display (default: 5) */
  barCount?: number;
  /** Additional CSS classes */
  className?: string;
}

/**
 * Generate bar heights based on audio level.
 * Creates a natural-looking wave pattern where center bars are taller.
 */
function generateBarHeights(level: number, count: number): number[] {
  const heights: number[] = [];
  const center = (count - 1) / 2;

  for (let i = 0; i < count; i++) {
    // Distance from center (0-1)
    const distFromCenter = Math.abs(i - center) / center;
    // Center bars are taller, edge bars shorter
    const multiplier = 1 - distFromCenter * 0.5;
    // Min height 4px, max height 24px when active
    const minHeight = 4;
    const maxHeight = 24;
    const height = minHeight + level * (maxHeight - minHeight) * multiplier;
    heights.push(Math.round(height));
  }

  return heights;
}

/**
 * Audio level visualizer with animated bars.
 * Shows microphone input levels during voice recording.
 */
export function AudioVisualizer({
  audioLevel,
  isActive,
  barCount = 5,
  className = "",
}: AudioVisualizerProps): React.JSX.Element {
  const barHeights = useMemo(() => {
    if (!isActive) {
      return Array.from({ length: barCount }, () => 4);
    }
    return generateBarHeights(audioLevel, barCount);
  }, [audioLevel, isActive, barCount]);

  return (
    <div
      data-testid="audio-visualizer"
      className={`flex items-center gap-0.5 ${className}`}
      role="img"
      aria-label={
        isActive
          ? `Audio level: ${String(Math.round(audioLevel * 100))}%`
          : "Audio visualizer inactive"
      }
    >
      {barHeights.map((height, index) => (
        <div
          key={index}
          data-testid="visualizer-bar"
          className={`w-1 rounded-full transition-all duration-150 ease-out ${
            isActive ? "bg-sky-400" : "bg-slate-300 dark:bg-slate-600"
          }`}
          style={{ height: `${height.toString()}px` }}
        />
      ))}
    </div>
  );
}
