import { useMemo } from 'react';

export interface AudioWaveformProps {
	audioData: Uint8Array | null;
	width?: number;
	height?: number;
	barCount?: number;
	color?: string;
}

export function AudioWaveform({
	audioData,
	width = 200,
	height = 40,
	barCount = 20,
	color = '#9ca3af',
}: AudioWaveformProps) {
	const bars = useMemo(() => {
		if (!audioData || audioData.length === 0) {
			// Return default bars (silence)
			return Array.from({ length: barCount }, () => 2);
		}

		// Sample the audio data to get barCount bars
		const samples: number[] = [];
		const step = Math.floor(audioData.length / barCount);

		for (let i = 0; i < barCount; i++) {
			const index = i * step;
			const value = audioData[index] || 0;
			// Normalize to height (0-100%)
			const normalized = (value / 255) * 100;
			// Minimum height of 2px for visibility
			samples.push(Math.max(normalized, 2));
		}

		return samples;
	}, [audioData, barCount]);

	const barWidth = width / barCount - 2;

	return (
		<div className='flex items-center gap-1' style={{ width, height }}>
			{bars.map((height, index) => (
				<div
					key={index}
					className='rounded-full transition-all duration-75'
					style={{
						width: `${barWidth}px`,
						height: `${height}%`,
						backgroundColor: color,
						minHeight: '2px',
					}}
				/>
			))}
		</div>
	);
}
