import { useEffect, useRef, useState } from "preact/hooks";
import { createAudioMeter } from "../audioMeter";

/** Polls the audio level from a MediaStream at rAF rate. Returns a 0–1 level. */
export function useAudioMeter(stream: MediaStream | null): number {
  const meterRef = useRef(createAudioMeter());
  const [level, setLevel] = useState(0);

  useEffect(() => {
    const meter = meterRef.current;
    if (stream) meter.connect(stream);
    let rafId: number;
    const tick = () => {
      setLevel(meter.getLevel());
      rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafId);
  }, [stream]);

  return level;
}
