"use client";
import { useState as o, useRef as v, useEffect as R } from "react";
import { recordAudio as f } from "../lib/audio-utils.js";
function w({
  transcribeAudio: t,
  onTranscriptionComplete: d
}) {
  const [l, c] = o(!1), [p, h] = o(!!t), [S, i] = o(!1), [m, u] = o(!1), [r, n] = o(null), a = v(null);
  R(() => {
    (async () => {
      const s = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
      h(s && !!t);
    })();
  }, [t]);
  const g = async () => {
    i(!1), u(!0);
    try {
      f.stop();
      const e = await a.current;
      if (t && e) {
        const s = await t(e);
        d?.(s);
      }
    } catch (e) {
      console.error("Error transcribing audio:", e);
    } finally {
      u(!1), c(!1), r && (r.getTracks().forEach((e) => e.stop()), n(null)), a.current = null;
    }
  };
  return {
    isListening: l,
    isSpeechSupported: p,
    isRecording: S,
    isTranscribing: m,
    audioStream: r,
    toggleListening: async () => {
      if (l)
        await g();
      else
        try {
          c(!0), i(!0);
          const e = await navigator.mediaDevices.getUserMedia({
            audio: !0
          });
          n(e), a.current = f(e);
        } catch (e) {
          console.error("Error recording audio:", e), c(!1), i(!1), r && (r.getTracks().forEach((s) => s.stop()), n(null));
        }
    },
    stopRecording: g
  };
}
export {
  w as useAudioRecording
};
