import { useState as g, useRef as d, useCallback as f } from "react";
import { webmFixDuration as E } from "../utils/BlobFix.es.js";
function I() {
  const u = [
    "audio/webm",
    "audio/mp4",
    "audio/ogg",
    "audio/wav",
    "audio/aac"
  ];
  for (let n = 0; n < u.length; n++)
    if (MediaRecorder.isTypeSupported(u[n]))
      return u[n];
}
function P() {
  const [u, n] = g(!1), [T, m] = g(0), [y, h] = g(!1), r = d(null), o = d(null), l = d([]), a = d(null), p = d(0), b = f(async () => {
    try {
      r.current || (r.current = await navigator.mediaDevices.getUserMedia({
        audio: !0
      }));
      const e = I(), t = new MediaRecorder(r.current, {
        mimeType: e
      });
      o.current = t, l.current = [], p.current = Date.now(), t.addEventListener("dataavailable", (s) => {
        s.data.size > 0 && l.current.push(s.data);
      }), t.start(), n(!0), a.current = window.setInterval(() => {
        m(Math.floor((Date.now() - p.current) / 1e3));
      }, 1e3);
    } catch (e) {
      console.error("Error accessing microphone:", e), alert("Unable to access microphone. Please check your permissions.");
    }
  }, []), v = f(() => new Promise((e) => {
    if (o.current && o.current.state === "recording") {
      const t = o.current.mimeType, s = Date.now() - p.current;
      o.current.addEventListener("stop", async () => {
        let c = new Blob(l.current, { type: t });
        t === "audio/webm" && (c = await E(c, s, c.type)), e(c);
      }), o.current.stop(), n(!1), m(0), a.current && (window.clearInterval(a.current), a.current = null), r.current && (r.current.getTracks().forEach((c) => c.stop()), r.current = null);
    } else
      e(null);
  }), []), D = f(async (e, t, s, c) => {
    h(!0);
    try {
      const i = new FormData();
      i.append("file", e, "audio.webm"), i.append("model", c), i.append("response_format", "json");
      const R = {};
      t && (R.Authorization = `Bearer ${t}`);
      const w = await fetch(s, {
        method: "POST",
        headers: R,
        body: i
      });
      if (!w.ok)
        throw new Error(`Transcription failed: ${w.statusText}`);
      return (await w.json()).text || "";
    } catch (i) {
      throw console.error("Transcription error:", i), i;
    } finally {
      h(!1);
    }
  }, []), k = f(() => {
    o.current && o.current.stop(), r.current && (r.current.getTracks().forEach((e) => e.stop()), r.current = null), a.current && (window.clearInterval(a.current), a.current = null), l.current = [], n(!1), m(0);
  }, []);
  return {
    isRecording: u,
    recordingTime: T,
    isTranscribing: y,
    startRecording: b,
    stopRecording: v,
    transcribeAudio: D,
    cancelRecording: k
  };
}
export {
  P as useAudioRecorder
};
//# sourceMappingURL=useAudioRecorder.es.js.map
