'use client';

import { useEffect, useRef, type RefObject } from 'react';

const BAR_COUNT = 28;
const MIN_H = 3;
const MAX_H = 34;

/**
 * 波形 — 读真实麦克风电平(AnalyserNode + requestAnimationFrame),有声才起伏,静音趋平。
 * 直接改 DOM 的 style.height,不触发 React re-render。
 */
export function AudioVisualizer({
  analyserRef,
  active,
}: {
  analyserRef: RefObject<AnalyserNode | null>;
  active: boolean;
}) {
  const barsRef = useRef<(HTMLSpanElement | null)[]>([]);

  useEffect(() => {
    if (!active) return;
    let raf = 0;
    const buf = new Uint8Array(128);
    const tick = () => {
      const an = analyserRef.current;
      const bars = barsRef.current;
      if (an) {
        an.getByteFrequencyData(buf);
        // 取低频段(人声主要能量),映射到 BAR_COUNT 根柱子,中间高两边低更像声纹
        for (let i = 0; i < BAR_COUNT; i++) {
          const bin = Math.floor((i / BAR_COUNT) * 48) + 1; // 用前 ~48 个频段
          const v = (buf[bin] ?? 0) / 255; // 0..1
          const center = 1 - Math.abs(i - (BAR_COUNT - 1) / 2) / (BAR_COUNT / 2);
          const h = MIN_H + v * (MAX_H - MIN_H) * (0.5 + 0.5 * center);
          const el = bars[i];
          if (el) el.style.height = `${h}px`;
        }
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [active, analyserRef]);

  return (
    <div className="h-9 flex items-center justify-center gap-[3px]">
      {Array.from({ length: BAR_COUNT }).map((_, i) => (
        <span
          key={i}
          ref={(el) => {
            barsRef.current[i] = el;
          }}
          className="w-[3px] rounded-full bg-brand-500/90 transition-[height] duration-75 ease-out"
          style={{ height: `${MIN_H}px` }}
        />
      ))}
    </div>
  );
}
