import { r as h, E as Y, _ as Z, L as Zt, k as ut, n as $, b3 as Rt, bp as Kt, bj as Jt, bi as Qt, s as M, j as v, ah as te, c as ee, B as ie, an as re, x as ne, bv as se, u as oe, bw as Q, aE as ae, aV as le, W as ce, l as de, T as he, P as ue } from "./index-B5oQV-ql.js";
import { T as pe, a as xt } from "./Toolbar-C_GX-d4y.js";
import { u as fe, F as me } from "./FormClearHelper-KUqXSigL.js";
import { c as ge } from "./createDownloadLinkElement-CbRjLJ8e.js";
import { u as ve } from "./Hooks-CGOh8RID.js";
import { F as be, D as ye } from "./FileDownload.esm-CwbnEkJ8.js";
var At = /* @__PURE__ */ h.forwardRef(function(r, t) {
  var e = {
    fill: "currentColor",
    xmlns: "http://www.w3.org/2000/svg"
  };
  return /* @__PURE__ */ h.createElement(Y, Z({
    iconAttrs: e,
    iconVerticalAlign: "middle",
    iconViewBox: "0 0 24 24"
  }, r, {
    ref: t
  }), /* @__PURE__ */ h.createElement("g", {
    fill: "none"
  }, /* @__PURE__ */ h.createElement("rect", {
    width: 24,
    height: 24
  }), /* @__PURE__ */ h.createElement("rect", {
    width: 24,
    height: 24
  }), /* @__PURE__ */ h.createElement("rect", {
    width: 24,
    height: 24
  })), /* @__PURE__ */ h.createElement("path", {
    d: "M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"
  }), /* @__PURE__ */ h.createElement("path", {
    d: "M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"
  }));
});
At.displayName = "Mic";
var Mt = /* @__PURE__ */ h.forwardRef(function(r, t) {
  var e = {
    fill: "currentColor",
    xmlns: "http://www.w3.org/2000/svg"
  };
  return /* @__PURE__ */ h.createElement(Y, Z({
    iconAttrs: e,
    iconVerticalAlign: "middle",
    iconViewBox: "0 0 24 24"
  }, r, {
    ref: t
  }), /* @__PURE__ */ h.createElement("rect", {
    width: 24,
    height: 24,
    fill: "none"
  }), /* @__PURE__ */ h.createElement("path", {
    d: "M8 19c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2s-2 .9-2 2v10c0 1.1.9 2 2 2zm6-12v10c0 1.1.9 2 2 2s2-.9 2-2V7c0-1.1-.9-2-2-2s-2 .9-2 2z"
  }));
});
Mt.displayName = "Pause";
var It = /* @__PURE__ */ h.forwardRef(function(r, t) {
  var e = {
    fill: "currentColor",
    xmlns: "http://www.w3.org/2000/svg"
  };
  return /* @__PURE__ */ h.createElement(Y, Z({
    iconAttrs: e,
    iconVerticalAlign: "middle",
    iconViewBox: "0 0 24 24"
  }, r, {
    ref: t
  }), /* @__PURE__ */ h.createElement("rect", {
    width: 24,
    height: 24,
    fill: "none"
  }), /* @__PURE__ */ h.createElement("path", {
    d: "M8 6.82v10.36c0 .79.87 1.27 1.54.84l8.14-5.18a1 1 0 000-1.69L9.54 5.98A.998.998 0 008 6.82z"
  }));
});
It.displayName = "PlayArrow";
var Ot = /* @__PURE__ */ h.forwardRef(function(r, t) {
  var e = {
    fill: "currentColor",
    xmlns: "http://www.w3.org/2000/svg"
  };
  return /* @__PURE__ */ h.createElement(Y, Z({
    iconAttrs: e,
    iconVerticalAlign: "middle",
    iconViewBox: "0 0 24 24"
  }, r, {
    ref: t
  }), /* @__PURE__ */ h.createElement("path", {
    fill: "none",
    d: "M0 0h24v24H0V0z"
  }), /* @__PURE__ */ h.createElement("path", {
    d: "M17.65 6.35a7.95 7.95 0 00-6.48-2.31c-3.67.37-6.69 3.35-7.1 7.02C3.52 15.91 7.27 20 12 20a7.98 7.98 0 007.21-4.56c.32-.67-.16-1.44-.9-1.44-.37 0-.72.2-.88.53a5.994 5.994 0 01-6.8 3.31c-2.22-.49-4.01-2.3-4.48-4.52A6.002 6.002 0 0112 6c1.66 0 3.14.69 4.22 1.78l-1.51 1.51c-.63.63-.19 1.71.7 1.71H19c.55 0 1-.45 1-1V6.41c0-.89-1.08-1.34-1.71-.71l-.64.65z"
  }));
});
Ot.displayName = "Refresh";
var Lt = /* @__PURE__ */ h.forwardRef(function(r, t) {
  var e = {
    fill: "currentColor",
    xmlns: "http://www.w3.org/2000/svg"
  };
  return /* @__PURE__ */ h.createElement(Y, Z({
    iconAttrs: e,
    iconVerticalAlign: "middle",
    iconViewBox: "0 0 24 24"
  }, r, {
    ref: t
  }), /* @__PURE__ */ h.createElement("g", {
    fill: "none"
  }, /* @__PURE__ */ h.createElement("rect", {
    width: 24,
    height: 24
  }), /* @__PURE__ */ h.createElement("rect", {
    width: 24,
    height: 24
  })), /* @__PURE__ */ h.createElement("path", {
    fillRule: "evenodd",
    d: "M9 16h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1H9c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1zm3-14C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z"
  }));
});
Lt.displayName = "StopCircle";
function A(r, t, e, i) {
  return new (e || (e = Promise))((function(n, s) {
    function a(l) {
      try {
        d(i.next(l));
      } catch (o) {
        s(o);
      }
    }
    function c(l) {
      try {
        d(i.throw(l));
      } catch (o) {
        s(o);
      }
    }
    function d(l) {
      var o;
      l.done ? n(l.value) : (o = l.value, o instanceof e ? o : new e((function(u) {
        u(o);
      }))).then(a, c);
    }
    d((i = i.apply(r, t || [])).next());
  }));
}
let K = class {
  constructor() {
    this.listeners = {};
  }
  on(t, e, i) {
    if (this.listeners[t] || (this.listeners[t] = /* @__PURE__ */ new Set()), i?.once) {
      const n = (...s) => {
        this.un(t, n), e(...s);
      };
      return this.listeners[t].add(n), () => this.un(t, n);
    }
    return this.listeners[t].add(e), () => this.un(t, e);
  }
  un(t, e) {
    var i;
    (i = this.listeners[t]) === null || i === void 0 || i.delete(e);
  }
  once(t, e) {
    return this.on(t, e, { once: !0 });
  }
  unAll() {
    this.listeners = {};
  }
  emit(t, ...e) {
    this.listeners[t] && this.listeners[t].forEach(((i) => i(...e)));
  }
};
const tt = { decode: function(r, t) {
  return A(this, void 0, void 0, (function* () {
    const e = new AudioContext({ sampleRate: t });
    try {
      return yield e.decodeAudioData(r);
    } finally {
      e.close();
    }
  }));
}, createBuffer: function(r, t) {
  if (!r || r.length === 0) throw new Error("channelData must be a non-empty array");
  if (t <= 0) throw new Error("duration must be greater than 0");
  if (typeof r[0] == "number" && (r = [r]), !r[0] || r[0].length === 0) throw new Error("channelData must contain non-empty channel arrays");
  (function(i) {
    const n = i[0];
    if (n.some(((s) => s > 1 || s < -1))) {
      const s = n.length;
      let a = 0;
      for (let c = 0; c < s; c++) {
        const d = Math.abs(n[c]);
        d > a && (a = d);
      }
      for (const c of i) for (let d = 0; d < s; d++) c[d] /= a;
    }
  })(r);
  const e = r.map(((i) => i instanceof Float32Array ? i : Float32Array.from(i)));
  return { duration: t, length: e[0].length, sampleRate: e[0].length / t, numberOfChannels: e.length, getChannelData: (i) => {
    const n = e[i];
    if (!n) throw new Error(`Channel ${i} not found`);
    return n;
  }, copyFromChannel: AudioBuffer.prototype.copyFromChannel, copyToChannel: AudioBuffer.prototype.copyToChannel };
} };
function Ut(r, t) {
  const e = t.xmlns ? document.createElementNS(t.xmlns, r) : document.createElement(r);
  for (const [i, n] of Object.entries(t)) if (i === "children" && n) for (const [s, a] of Object.entries(n)) a instanceof Node ? e.appendChild(a) : typeof a == "string" ? e.appendChild(document.createTextNode(a)) : e.appendChild(Ut(s, a));
  else i === "style" ? Object.assign(e.style, n) : i === "textContent" ? e.textContent = n : e.setAttribute(i, n.toString());
  return e;
}
function Et(r, t, e) {
  const i = Ut(r, t || {});
  return e?.appendChild(i), i;
}
var we = Object.freeze({ __proto__: null, createElement: Et, default: Et });
const Ce = { fetchBlob: function(r, t, e) {
  return A(this, void 0, void 0, (function* () {
    const i = yield fetch(r, e);
    if (i.status >= 400) throw new Error(`Failed to fetch ${r}: ${i.status} (${i.statusText})`);
    return (function(n, s) {
      A(this, void 0, void 0, (function* () {
        if (!n.body || !n.headers) return;
        const a = n.body.getReader(), c = Number(n.headers.get("Content-Length")) || 0;
        let d = 0;
        const l = (o) => {
          d += o?.length || 0;
          const u = Math.round(d / c * 100);
          s(u);
        };
        try {
          for (; ; ) {
            const o = yield a.read();
            if (o.done) break;
            l(o.value);
          }
        } catch (o) {
          console.warn("Progress tracking error:", o);
        }
      }));
    })(i.clone(), t), i.blob();
  }));
} };
class Se extends K {
  constructor(t) {
    super(), this.isExternalMedia = !1, t.media ? (this.media = t.media, this.isExternalMedia = !0) : this.media = document.createElement("audio"), t.mediaControls && (this.media.controls = !0), t.autoplay && (this.media.autoplay = !0), t.playbackRate != null && this.onMediaEvent("canplay", (() => {
      t.playbackRate != null && (this.media.playbackRate = t.playbackRate);
    }), { once: !0 });
  }
  onMediaEvent(t, e, i) {
    return this.media.addEventListener(t, e, i), () => this.media.removeEventListener(t, e, i);
  }
  getSrc() {
    return this.media.currentSrc || this.media.src || "";
  }
  revokeSrc() {
    const t = this.getSrc();
    t.startsWith("blob:") && URL.revokeObjectURL(t);
  }
  canPlayType(t) {
    return this.media.canPlayType(t) !== "";
  }
  setSrc(t, e) {
    const i = this.getSrc();
    if (t && i === t) return;
    this.revokeSrc();
    const n = e instanceof Blob && (this.canPlayType(e.type) || !t) ? URL.createObjectURL(e) : t;
    if (i && this.media.removeAttribute("src"), n || t) try {
      this.media.src = n;
    } catch {
      this.media.src = t;
    }
  }
  destroy() {
    this.isExternalMedia || (this.media.pause(), this.revokeSrc(), this.media.removeAttribute("src"), this.media.load(), this.media.remove());
  }
  setMediaElement(t) {
    this.media = t;
  }
  play() {
    return A(this, void 0, void 0, (function* () {
      try {
        return yield this.media.play();
      } catch (t) {
        if (t instanceof DOMException && t.name === "AbortError") return;
        throw t;
      }
    }));
  }
  pause() {
    this.media.pause();
  }
  isPlaying() {
    return !this.media.paused && !this.media.ended;
  }
  setTime(t) {
    this.media.currentTime = Math.max(0, Math.min(t, this.getDuration()));
  }
  getDuration() {
    return this.media.duration;
  }
  getCurrentTime() {
    return this.media.currentTime;
  }
  getVolume() {
    return this.media.volume;
  }
  setVolume(t) {
    this.media.volume = t;
  }
  getMuted() {
    return this.media.muted;
  }
  setMuted(t) {
    this.media.muted = t;
  }
  getPlaybackRate() {
    return this.media.playbackRate;
  }
  isSeeking() {
    return this.media.seeking;
  }
  setPlaybackRate(t, e) {
    e != null && (this.media.preservesPitch = e), this.media.playbackRate = t;
  }
  getMediaElement() {
    return this.media;
  }
  setSinkId(t) {
    return this.media.setSinkId(t);
  }
}
function ot(r) {
  return r < 0 ? 0 : r > 1 ? 1 : r;
}
function Re({ maxTop: r, maxBottom: t, halfHeight: e, vScale: i }) {
  const n = Math.round(r * e * i);
  return { topHeight: n, totalHeight: n + Math.round(t * e * i) || 1 };
}
function xe({ barAlign: r, halfHeight: t, topHeight: e, totalHeight: i, canvasHeight: n }) {
  return r === "top" ? 0 : r === "bottom" ? n - i : t - e;
}
function Pt(r, t, e) {
  const i = t - r.left, n = e - r.top;
  return [i / r.width, n / r.height];
}
function Bt(r) {
  return !!(r.barWidth || r.barGap || r.barAlign);
}
function Wt(r, t) {
  if (!Bt(t)) return r;
  const e = t.barWidth || 0.5, i = e + (t.barGap || e / 2);
  return i === 0 ? r : Math.floor(r / i) * i;
}
function Dt({ scrollLeft: r, totalWidth: t, numCanvases: e }) {
  if (t === 0) return [0];
  const i = r / t, n = Math.floor(i * e);
  return [n - 1, n, n + 1];
}
function Tt({ scrollLeft: r, clientWidth: t, scrollWidth: e }) {
  return e === 0 ? { startX: 0, endX: 0 } : { startX: r / e, endX: (r + t) / e };
}
class Ee extends K {
  constructor(t, e) {
    super(), this.timeouts = [], this.isScrollable = !1, this.audioData = null, this.resizeObserver = null, this.lastContainerWidth = 0, this.isDragging = !1, this.subscriptions = [], this.unsubscribeOnScroll = [], this.dragUnsubscribe = null, this.subscriptions = [], this.options = t;
    const i = this.parentFromOptionsContainer(t.container);
    this.parent = i;
    const [n, s] = this.initHtml();
    i.appendChild(n), this.container = n, this.scrollContainer = s.querySelector(".scroll"), this.wrapper = s.querySelector(".wrapper"), this.canvasWrapper = s.querySelector(".canvases"), this.progressWrapper = s.querySelector(".progress"), this.cursor = s.querySelector(".cursor"), e && s.appendChild(e), this.initEvents();
  }
  parentFromOptionsContainer(t) {
    let e;
    if (typeof t == "string" ? e = document.querySelector(t) : t instanceof HTMLElement && (e = t), !e) throw new Error("Container not found");
    return e;
  }
  initEvents() {
    if (this.wrapper.addEventListener("click", ((t) => {
      const e = this.wrapper.getBoundingClientRect(), [i, n] = Pt(e, t.clientX, t.clientY);
      this.emit("click", i, n);
    })), this.wrapper.addEventListener("dblclick", ((t) => {
      const e = this.wrapper.getBoundingClientRect(), [i, n] = Pt(e, t.clientX, t.clientY);
      this.emit("dblclick", i, n);
    })), this.options.dragToSeek !== !0 && typeof this.options.dragToSeek != "object" || this.initDrag(), this.scrollContainer.addEventListener("scroll", (() => {
      const { scrollLeft: t, scrollWidth: e, clientWidth: i } = this.scrollContainer, { startX: n, endX: s } = Tt({ scrollLeft: t, scrollWidth: e, clientWidth: i });
      this.emit("scroll", n, s, t, t + i);
    })), typeof ResizeObserver == "function") {
      const t = this.createDelay(100);
      this.resizeObserver = new ResizeObserver((() => {
        t().then((() => this.onContainerResize())).catch((() => {
        }));
      })), this.resizeObserver.observe(this.scrollContainer);
    }
  }
  onContainerResize() {
    const t = this.parent.clientWidth;
    t === this.lastContainerWidth && this.options.height !== "auto" || (this.lastContainerWidth = t, this.reRender(), this.emit("resize"));
  }
  initDrag() {
    this.dragUnsubscribe || (this.dragUnsubscribe = (function(t, e, i, n, s = 3, a = 0, c = 100) {
      if (!t) return () => {
      };
      const d = /* @__PURE__ */ new Map(), l = matchMedia("(pointer: coarse)").matches;
      let o = () => {
      };
      const u = (m) => {
        if (m.button !== a || (d.set(m.pointerId, m), d.size > 1)) return;
        let p = m.clientX, f = m.clientY, b = !1;
        const g = Date.now(), T = (w) => {
          if (w.defaultPrevented || d.size > 1 || l && Date.now() - g < c) return;
          const C = w.clientX, E = w.clientY, I = C - p, U = E - f;
          if (b || Math.abs(I) > s || Math.abs(U) > s) {
            w.preventDefault(), w.stopPropagation();
            const F = t.getBoundingClientRect(), { left: O, top: N } = F;
            b || (i?.(p - O, f - N), b = !0), e(I, U, C - O, E - N), p = C, f = E;
          }
        }, W = (w) => {
          if (d.delete(w.pointerId), b) {
            const C = w.clientX, E = w.clientY, I = t.getBoundingClientRect(), { left: U, top: F } = I;
            n?.(C - U, E - F);
          }
          o();
        }, D = (w) => {
          d.delete(w.pointerId), w.relatedTarget && w.relatedTarget !== document.documentElement || W(w);
        }, R = (w) => {
          b && (w.stopPropagation(), w.preventDefault());
        }, x = (w) => {
          w.defaultPrevented || d.size > 1 || b && w.preventDefault();
        };
        document.addEventListener("pointermove", T), document.addEventListener("pointerup", W), document.addEventListener("pointerout", D), document.addEventListener("pointercancel", D), document.addEventListener("touchmove", x, { passive: !1 }), document.addEventListener("click", R, { capture: !0 }), o = () => {
          document.removeEventListener("pointermove", T), document.removeEventListener("pointerup", W), document.removeEventListener("pointerout", D), document.removeEventListener("pointercancel", D), document.removeEventListener("touchmove", x), setTimeout((() => {
            document.removeEventListener("click", R, { capture: !0 });
          }), 10);
        };
      };
      return t.addEventListener("pointerdown", u), () => {
        o(), t.removeEventListener("pointerdown", u), d.clear();
      };
    })(this.wrapper, ((t, e, i) => {
      const n = this.wrapper.getBoundingClientRect().width;
      this.emit("drag", ot(i / n));
    }), ((t) => {
      this.isDragging = !0;
      const e = this.wrapper.getBoundingClientRect().width;
      this.emit("dragstart", ot(t / e));
    }), ((t) => {
      this.isDragging = !1;
      const e = this.wrapper.getBoundingClientRect().width;
      this.emit("dragend", ot(t / e));
    })), this.subscriptions.push(this.dragUnsubscribe));
  }
  initHtml() {
    const t = document.createElement("div"), e = t.attachShadow({ mode: "open" }), i = this.options.cspNonce && typeof this.options.cspNonce == "string" ? this.options.cspNonce.replace(/"/g, "") : "";
    return e.innerHTML = `
      <style${i ? ` nonce="${i}"` : ""}>
        :host {
          user-select: none;
          min-width: 1px;
        }
        :host audio {
          display: block;
          width: 100%;
        }
        :host .scroll {
          overflow-x: auto;
          overflow-y: hidden;
          width: 100%;
          position: relative;
        }
        :host .noScrollbar {
          scrollbar-color: transparent;
          scrollbar-width: none;
        }
        :host .noScrollbar::-webkit-scrollbar {
          display: none;
          -webkit-appearance: none;
        }
        :host .wrapper {
          position: relative;
          overflow: visible;
          z-index: 2;
        }
        :host .canvases {
          min-height: ${this.getHeight(this.options.height, this.options.splitChannels)}px;
          pointer-events: none;
        }
        :host .canvases > div {
          position: relative;
        }
        :host canvas {
          display: block;
          position: absolute;
          top: 0;
          image-rendering: pixelated;
        }
        :host .progress {
          pointer-events: none;
          position: absolute;
          z-index: 2;
          top: 0;
          left: 0;
          width: 0;
          height: 100%;
          overflow: hidden;
        }
        :host .progress > div {
          position: relative;
        }
        :host .cursor {
          pointer-events: none;
          position: absolute;
          z-index: 5;
          top: 0;
          left: 0;
          height: 100%;
          border-radius: 2px;
        }
      </style>

      <div class="scroll" part="scroll">
        <div class="wrapper" part="wrapper">
          <div class="canvases" part="canvases"></div>
          <div class="progress" part="progress"></div>
          <div class="cursor" part="cursor"></div>
        </div>
      </div>
    `, [t, e];
  }
  setOptions(t) {
    if (this.options.container !== t.container) {
      const e = this.parentFromOptionsContainer(t.container);
      e.appendChild(this.container), this.parent = e;
    }
    t.dragToSeek !== !0 && typeof this.options.dragToSeek != "object" || this.initDrag(), this.options = t, this.reRender();
  }
  getWrapper() {
    return this.wrapper;
  }
  getWidth() {
    return this.scrollContainer.clientWidth;
  }
  getScroll() {
    return this.scrollContainer.scrollLeft;
  }
  setScroll(t) {
    this.scrollContainer.scrollLeft = t;
  }
  setScrollPercentage(t) {
    const { scrollWidth: e } = this.scrollContainer, i = e * t;
    this.setScroll(i);
  }
  destroy() {
    var t;
    this.subscriptions.forEach(((e) => e())), this.container.remove(), this.resizeObserver && (this.resizeObserver.disconnect(), this.resizeObserver = null), (t = this.unsubscribeOnScroll) === null || t === void 0 || t.forEach(((e) => e())), this.unsubscribeOnScroll = [];
  }
  createDelay(t = 10) {
    let e, i;
    const n = () => {
      e && (clearTimeout(e), e = void 0), i && (i(), i = void 0);
    };
    return this.timeouts.push(n), () => new Promise(((s, a) => {
      n(), i = a, e = setTimeout((() => {
        e = void 0, i = void 0, s();
      }), t);
    }));
  }
  getHeight(t, e) {
    var i;
    const n = ((i = this.audioData) === null || i === void 0 ? void 0 : i.numberOfChannels) || 1;
    return (function({ optionsHeight: s, optionsSplitChannels: a, parentHeight: c, numberOfChannels: d, defaultHeight: l = 128 }) {
      if (s == null) return l;
      const o = Number(s);
      if (!isNaN(o)) return o;
      if (s === "auto") {
        const u = c || l;
        return a?.every(((m) => !m.overlay)) ? u / d : u;
      }
      return l;
    })({ optionsHeight: t, optionsSplitChannels: e, parentHeight: this.parent.clientHeight, numberOfChannels: n, defaultHeight: 128 });
  }
  convertColorValues(t) {
    return (function(e, i) {
      if (!Array.isArray(e)) return e || "";
      if (e.length === 0) return "#999";
      if (e.length < 2) return e[0] || "";
      const n = document.createElement("canvas"), s = n.getContext("2d"), a = n.height * i, c = s.createLinearGradient(0, 0, 0, a || i), d = 1 / (e.length - 1);
      return e.forEach(((l, o) => {
        c.addColorStop(o * d, l);
      })), c;
    })(t, this.getPixelRatio());
  }
  getPixelRatio() {
    return t = window.devicePixelRatio, Math.max(1, t || 1);
    var t;
  }
  renderBarWaveform(t, e, i, n) {
    const { width: s, height: a } = i.canvas, { halfHeight: c, barWidth: d, barRadius: l, barIndexScale: o, barSpacing: u } = (function({ width: p, height: f, length: b, options: g, pixelRatio: T }) {
      const W = f / 2, D = g.barWidth ? g.barWidth * T : 1, R = g.barGap ? g.barGap * T : g.barWidth ? D / 2 : 0, x = D + R || 1;
      return { halfHeight: W, barWidth: D, barGap: R, barRadius: g.barRadius || 0, barIndexScale: b > 0 ? p / x / b : 0, barSpacing: x };
    })({ width: s, height: a, length: (t[0] || []).length, options: e, pixelRatio: this.getPixelRatio() }), m = (function({ channelData: p, barIndexScale: f, barSpacing: b, barWidth: g, halfHeight: T, vScale: W, canvasHeight: D, barAlign: R }) {
      const x = p[0] || [], w = p[1] || x, C = x.length, E = [];
      let I = 0, U = 0, F = 0;
      for (let O = 0; O <= C; O++) {
        const N = Math.round(O * f);
        if (N > I) {
          const { topHeight: B, totalHeight: H } = Re({ maxTop: U, maxBottom: F, halfHeight: T, vScale: W }), j = xe({ barAlign: R, halfHeight: T, topHeight: B, totalHeight: H, canvasHeight: D });
          E.push({ x: I * b, y: j, width: g, height: H }), I = N, U = 0, F = 0;
        }
        const L = Math.abs(x[O] || 0), X = Math.abs(w[O] || 0);
        L > U && (U = L), X > F && (F = X);
      }
      return E;
    })({ channelData: t, barIndexScale: o, barSpacing: u, barWidth: d, halfHeight: c, vScale: n, canvasHeight: a, barAlign: e.barAlign });
    i.beginPath();
    for (const p of m) l && "roundRect" in i ? i.roundRect(p.x, p.y, p.width, p.height, l) : i.rect(p.x, p.y, p.width, p.height);
    i.fill(), i.closePath();
  }
  renderLineWaveform(t, e, i, n) {
    const { width: s, height: a } = i.canvas, c = (function({ channelData: d, width: l, height: o, vScale: u }) {
      const m = o / 2, p = d[0] || [];
      return [p, d[1] || p].map(((f, b) => {
        const g = f.length, T = g ? l / g : 0, W = m, D = b === 0 ? -1 : 1, R = [{ x: 0, y: W }];
        let x = 0, w = 0;
        for (let C = 0; C <= g; C++) {
          const E = Math.round(C * T);
          if (E > x) {
            const U = W + (Math.round(w * m * u) || 1) * D;
            R.push({ x, y: U }), x = E, w = 0;
          }
          const I = Math.abs(f[C] || 0);
          I > w && (w = I);
        }
        return R.push({ x, y: W }), R;
      }));
    })({ channelData: t, width: s, height: a, vScale: n });
    i.beginPath();
    for (const d of c) if (d.length) {
      i.moveTo(d[0].x, d[0].y);
      for (let l = 1; l < d.length; l++) {
        const o = d[l];
        i.lineTo(o.x, o.y);
      }
    }
    i.fill(), i.closePath();
  }
  renderWaveform(t, e, i) {
    if (i.fillStyle = this.convertColorValues(e.waveColor), e.renderFunction) return void e.renderFunction(t, i);
    const n = (function({ channelData: s, barHeight: a, normalize: c }) {
      var d;
      const l = a || 1;
      if (!c) return l;
      const o = s[0];
      if (!o || o.length === 0) return l;
      let u = 0;
      for (let m = 0; m < o.length; m++) {
        const p = (d = o[m]) !== null && d !== void 0 ? d : 0, f = Math.abs(p);
        f > u && (u = f);
      }
      return u ? l / u : l;
    })({ channelData: t, barHeight: e.barHeight, normalize: e.normalize });
    Bt(e) ? this.renderBarWaveform(t, e, i, n) : this.renderLineWaveform(t, e, i, n);
  }
  renderSingleCanvas(t, e, i, n, s, a, c) {
    const d = this.getPixelRatio(), l = document.createElement("canvas");
    l.width = Math.round(i * d), l.height = Math.round(n * d), l.style.width = `${i}px`, l.style.height = `${n}px`, l.style.left = `${Math.round(s)}px`, a.appendChild(l);
    const o = l.getContext("2d");
    if (e.renderFunction ? (o.fillStyle = this.convertColorValues(e.waveColor), e.renderFunction(t, o)) : this.renderWaveform(t, e, o), l.width > 0 && l.height > 0) {
      const u = l.cloneNode(), m = u.getContext("2d");
      m.drawImage(l, 0, 0), m.globalCompositeOperation = "source-in", m.fillStyle = this.convertColorValues(e.progressColor), m.fillRect(0, 0, l.width, l.height), c.appendChild(u);
    }
  }
  renderMultiCanvas(t, e, i, n, s, a) {
    const c = this.getPixelRatio(), { clientWidth: d } = this.scrollContainer, l = i / c, o = (function({ clientWidth: f, totalWidth: b, options: g }) {
      return Wt(Math.min(8e3, f, b), g);
    })({ clientWidth: d, totalWidth: l, options: e });
    let u = {};
    if (o === 0) return;
    const m = (f) => {
      if (f < 0 || f >= p || u[f]) return;
      u[f] = !0;
      const b = f * o;
      let g = Math.min(l - b, o);
      if (g = Wt(g, e), g <= 0) return;
      const T = (function({ channelData: W, offset: D, clampedWidth: R, totalWidth: x }) {
        return W.map(((w) => {
          const C = Math.floor(D / x * w.length), E = Math.floor((D + R) / x * w.length);
          return w.slice(C, E);
        }));
      })({ channelData: t, offset: b, clampedWidth: g, totalWidth: l });
      this.renderSingleCanvas(T, e, g, n, b, s, a);
    }, p = Math.ceil(l / o);
    if (!this.isScrollable) {
      for (let f = 0; f < p; f++) m(f);
      return;
    }
    if (Dt({ scrollLeft: this.scrollContainer.scrollLeft, totalWidth: l, numCanvases: p }).forEach(((f) => m(f))), p > 1) {
      const f = this.on("scroll", (() => {
        const { scrollLeft: b } = this.scrollContainer;
        Object.keys(u).length > 10 && (s.innerHTML = "", a.innerHTML = "", u = {}), Dt({ scrollLeft: b, totalWidth: l, numCanvases: p }).forEach(((g) => m(g)));
      }));
      this.unsubscribeOnScroll.push(f);
    }
  }
  renderChannel(t, e, i, n) {
    var { overlay: s } = e, a = (function(o, u) {
      var m = {};
      for (var p in o) Object.prototype.hasOwnProperty.call(o, p) && u.indexOf(p) < 0 && (m[p] = o[p]);
      if (o != null && typeof Object.getOwnPropertySymbols == "function") {
        var f = 0;
        for (p = Object.getOwnPropertySymbols(o); f < p.length; f++) u.indexOf(p[f]) < 0 && Object.prototype.propertyIsEnumerable.call(o, p[f]) && (m[p[f]] = o[p[f]]);
      }
      return m;
    })(e, ["overlay"]);
    const c = document.createElement("div"), d = this.getHeight(a.height, a.splitChannels);
    c.style.height = `${d}px`, s && n > 0 && (c.style.marginTop = `-${d}px`), this.canvasWrapper.style.minHeight = `${d}px`, this.canvasWrapper.appendChild(c);
    const l = c.cloneNode();
    this.progressWrapper.appendChild(l), this.renderMultiCanvas(t, a, i, d, c, l);
  }
  render(t) {
    return A(this, void 0, void 0, (function* () {
      var e;
      this.timeouts.forEach(((l) => l())), this.timeouts = [], this.canvasWrapper.innerHTML = "", this.progressWrapper.innerHTML = "", this.options.width != null && (this.scrollContainer.style.width = typeof this.options.width == "number" ? `${this.options.width}px` : this.options.width);
      const i = this.getPixelRatio(), n = this.scrollContainer.clientWidth, { scrollWidth: s, isScrollable: a, useParentWidth: c, width: d } = (function({ duration: l, minPxPerSec: o = 0, parentWidth: u, fillParent: m, pixelRatio: p }) {
        const f = Math.ceil(l * o), b = f > u, g = !!(m && !b);
        return { scrollWidth: f, isScrollable: b, useParentWidth: g, width: (g ? u : f) * p };
      })({ duration: t.duration, minPxPerSec: this.options.minPxPerSec || 0, parentWidth: n, fillParent: this.options.fillParent, pixelRatio: i });
      if (this.isScrollable = a, this.wrapper.style.width = c ? "100%" : `${s}px`, this.scrollContainer.style.overflowX = this.isScrollable ? "auto" : "hidden", this.scrollContainer.classList.toggle("noScrollbar", !!this.options.hideScrollbar), this.cursor.style.backgroundColor = `${this.options.cursorColor || this.options.progressColor}`, this.cursor.style.width = `${this.options.cursorWidth}px`, this.audioData = t, this.emit("render"), this.options.splitChannels) for (let l = 0; l < t.numberOfChannels; l++) {
        const o = Object.assign(Object.assign({}, this.options), (e = this.options.splitChannels) === null || e === void 0 ? void 0 : e[l]);
        this.renderChannel([t.getChannelData(l)], o, d, l);
      }
      else {
        const l = [t.getChannelData(0)];
        t.numberOfChannels > 1 && l.push(t.getChannelData(1)), this.renderChannel(l, this.options, d, 0);
      }
      Promise.resolve().then((() => this.emit("rendered")));
    }));
  }
  reRender() {
    if (this.unsubscribeOnScroll.forEach(((i) => i())), this.unsubscribeOnScroll = [], !this.audioData) return;
    const { scrollWidth: t } = this.scrollContainer, { right: e } = this.progressWrapper.getBoundingClientRect();
    if (this.render(this.audioData), this.isScrollable && t !== this.scrollContainer.scrollWidth) {
      const { right: i } = this.progressWrapper.getBoundingClientRect(), n = (function(s) {
        const a = 2 * s;
        return (a < 0 ? Math.floor(a) : Math.ceil(a)) / 2;
      })(i - e);
      this.scrollContainer.scrollLeft += n;
    }
  }
  zoom(t) {
    this.options.minPxPerSec = t, this.reRender();
  }
  scrollIntoView(t, e = !1) {
    const { scrollLeft: i, scrollWidth: n, clientWidth: s } = this.scrollContainer, a = t * n, c = i, d = i + s, l = s / 2;
    if (this.isDragging)
      a + 30 > d ? this.scrollContainer.scrollLeft += 30 : a - 30 < c && (this.scrollContainer.scrollLeft -= 30);
    else {
      (a < c || a > d) && (this.scrollContainer.scrollLeft = a - (this.options.autoCenter ? l : 0));
      const o = a - i - l;
      e && this.options.autoCenter && o > 0 && (this.scrollContainer.scrollLeft += o);
    }
    {
      const o = this.scrollContainer.scrollLeft, { startX: u, endX: m } = Tt({ scrollLeft: o, scrollWidth: n, clientWidth: s });
      this.emit("scroll", u, m, o, o + s);
    }
  }
  renderProgress(t, e) {
    if (isNaN(t)) return;
    const i = 100 * t;
    this.canvasWrapper.style.clipPath = `polygon(${i}% 0%, 100% 0%, 100% 100%, ${i}% 100%)`, this.progressWrapper.style.width = `${i}%`, this.cursor.style.left = `${i}%`, this.cursor.style.transform = this.options.cursorWidth ? `translateX(-${t * this.options.cursorWidth}px)` : "", this.isScrollable && this.options.autoScroll && this.scrollIntoView(t, e);
  }
  exportImage(t, e, i) {
    return A(this, void 0, void 0, (function* () {
      const n = this.canvasWrapper.querySelectorAll("canvas");
      if (!n.length) throw new Error("No waveform data");
      if (i === "dataURL") {
        const s = Array.from(n).map(((a) => a.toDataURL(t, e)));
        return Promise.resolve(s);
      }
      return Promise.all(Array.from(n).map(((s) => new Promise(((a, c) => {
        s.toBlob(((d) => {
          d ? a(d) : c(new Error("Could not export image"));
        }), t, e);
      })))));
    }));
  }
}
class Pe extends K {
  constructor() {
    super(...arguments), this.animationFrameId = null, this.isRunning = !1;
  }
  start() {
    if (this.isRunning) return;
    this.isRunning = !0;
    const t = () => {
      this.isRunning && (this.emit("tick"), this.animationFrameId = requestAnimationFrame(t));
    };
    t();
  }
  stop() {
    this.isRunning = !1, this.animationFrameId !== null && (cancelAnimationFrame(this.animationFrameId), this.animationFrameId = null);
  }
  destroy() {
    this.stop();
  }
}
class at extends K {
  constructor(t = new AudioContext()) {
    super(), this.bufferNode = null, this.playStartTime = 0, this.playedDuration = 0, this._muted = !1, this._playbackRate = 1, this._duration = void 0, this.buffer = null, this.currentSrc = "", this.paused = !0, this.crossOrigin = null, this.seeking = !1, this.autoplay = !1, this.addEventListener = this.on, this.removeEventListener = this.un, this.audioContext = t, this.gainNode = this.audioContext.createGain(), this.gainNode.connect(this.audioContext.destination);
  }
  load() {
    return A(this, void 0, void 0, (function* () {
    }));
  }
  get src() {
    return this.currentSrc;
  }
  set src(t) {
    if (this.currentSrc = t, this._duration = void 0, !t) return this.buffer = null, void this.emit("emptied");
    fetch(t).then(((e) => {
      if (e.status >= 400) throw new Error(`Failed to fetch ${t}: ${e.status} (${e.statusText})`);
      return e.arrayBuffer();
    })).then(((e) => this.currentSrc !== t ? null : this.audioContext.decodeAudioData(e))).then(((e) => {
      this.currentSrc === t && (this.buffer = e, this.emit("loadedmetadata"), this.emit("canplay"), this.autoplay && this.play());
    })).catch(((e) => {
      console.error("WebAudioPlayer load error:", e);
    }));
  }
  _play() {
    if (!this.paused) return;
    this.paused = !1, this.bufferNode && (this.bufferNode.onended = null, this.bufferNode.disconnect()), this.bufferNode = this.audioContext.createBufferSource(), this.buffer && (this.bufferNode.buffer = this.buffer), this.bufferNode.playbackRate.value = this._playbackRate, this.bufferNode.connect(this.gainNode);
    let t = this.playedDuration * this._playbackRate;
    (t >= this.duration || t < 0) && (t = 0, this.playedDuration = 0), this.bufferNode.start(this.audioContext.currentTime, t), this.playStartTime = this.audioContext.currentTime, this.bufferNode.onended = () => {
      this.currentTime >= this.duration && (this.pause(), this.emit("ended"));
    };
  }
  _pause() {
    var t;
    this.paused = !0, (t = this.bufferNode) === null || t === void 0 || t.stop(), this.playedDuration += this.audioContext.currentTime - this.playStartTime;
  }
  play() {
    return A(this, void 0, void 0, (function* () {
      this.paused && (this._play(), this.emit("play"));
    }));
  }
  pause() {
    this.paused || (this._pause(), this.emit("pause"));
  }
  stopAt(t) {
    const e = t - this.currentTime, i = this.bufferNode;
    i?.stop(this.audioContext.currentTime + e), i?.addEventListener("ended", (() => {
      i === this.bufferNode && (this.bufferNode = null, this.pause());
    }), { once: !0 });
  }
  setSinkId(t) {
    return A(this, void 0, void 0, (function* () {
      return this.audioContext.setSinkId(t);
    }));
  }
  get playbackRate() {
    return this._playbackRate;
  }
  set playbackRate(t) {
    this._playbackRate = t, this.bufferNode && (this.bufferNode.playbackRate.value = t);
  }
  get currentTime() {
    return (this.paused ? this.playedDuration : this.playedDuration + (this.audioContext.currentTime - this.playStartTime)) * this._playbackRate;
  }
  set currentTime(t) {
    const e = !this.paused;
    e && this._pause(), this.playedDuration = t / this._playbackRate, e && this._play(), this.emit("seeking"), this.emit("timeupdate");
  }
  get duration() {
    var t, e;
    return (t = this._duration) !== null && t !== void 0 ? t : ((e = this.buffer) === null || e === void 0 ? void 0 : e.duration) || 0;
  }
  set duration(t) {
    this._duration = t;
  }
  get volume() {
    return this.gainNode.gain.value;
  }
  set volume(t) {
    this.gainNode.gain.value = t, this.emit("volumechange");
  }
  get muted() {
    return this._muted;
  }
  set muted(t) {
    this._muted !== t && (this._muted = t, this._muted ? this.gainNode.disconnect() : this.gainNode.connect(this.audioContext.destination));
  }
  canPlayType(t) {
    return /^(audio|video)\//.test(t);
  }
  getGainNode() {
    return this.gainNode;
  }
  getChannelData() {
    const t = [];
    if (!this.buffer) return t;
    const e = this.buffer.numberOfChannels;
    for (let i = 0; i < e; i++) t.push(this.buffer.getChannelData(i));
    return t;
  }
  removeAttribute(t) {
    switch (t) {
      case "src":
        this.src = "";
        break;
      case "playbackRate":
        this.playbackRate = 0;
        break;
      case "currentTime":
        this.currentTime = 0;
        break;
      case "duration":
        this.duration = 0;
        break;
      case "volume":
        this.volume = 0;
        break;
      case "muted":
        this.muted = !1;
    }
  }
}
const We = { waveColor: "#999", progressColor: "#555", cursorWidth: 1, minPxPerSec: 0, fillParent: !0, interact: !0, dragToSeek: !1, autoScroll: !0, autoCenter: !0, sampleRate: 8e3 };
class G extends Se {
  static create(t) {
    return new G(t);
  }
  constructor(t) {
    const e = t.media || (t.backend === "WebAudio" ? new at() : void 0);
    super({ media: e, mediaControls: t.mediaControls, autoplay: t.autoplay, playbackRate: t.audioRate }), this.plugins = [], this.decodedData = null, this.stopAtPosition = null, this.subscriptions = [], this.mediaSubscriptions = [], this.abortController = null, this.options = Object.assign({}, We, t), this.timer = new Pe();
    const i = e ? void 0 : this.getMediaElement();
    this.renderer = new Ee(this.options, i), this.initPlayerEvents(), this.initRendererEvents(), this.initTimerEvents(), this.initPlugins();
    const n = this.options.url || this.getSrc() || "";
    Promise.resolve().then((() => {
      this.emit("init");
      const { peaks: s, duration: a } = this.options;
      (n || s && a) && this.load(n, s, a).catch(((c) => {
        this.emit("error", c instanceof Error ? c : new Error(String(c)));
      }));
    }));
  }
  updateProgress(t = this.getCurrentTime()) {
    return this.renderer.renderProgress(t / this.getDuration(), this.isPlaying()), t;
  }
  initTimerEvents() {
    this.subscriptions.push(this.timer.on("tick", (() => {
      if (!this.isSeeking()) {
        const t = this.updateProgress();
        this.emit("timeupdate", t), this.emit("audioprocess", t), this.stopAtPosition != null && this.isPlaying() && t >= this.stopAtPosition && this.pause();
      }
    })));
  }
  initPlayerEvents() {
    this.isPlaying() && (this.emit("play"), this.timer.start()), this.mediaSubscriptions.push(this.onMediaEvent("timeupdate", (() => {
      const t = this.updateProgress();
      this.emit("timeupdate", t);
    })), this.onMediaEvent("play", (() => {
      this.emit("play"), this.timer.start();
    })), this.onMediaEvent("pause", (() => {
      this.emit("pause"), this.timer.stop(), this.stopAtPosition = null;
    })), this.onMediaEvent("emptied", (() => {
      this.timer.stop(), this.stopAtPosition = null;
    })), this.onMediaEvent("ended", (() => {
      this.emit("timeupdate", this.getDuration()), this.emit("finish"), this.stopAtPosition = null;
    })), this.onMediaEvent("seeking", (() => {
      this.emit("seeking", this.getCurrentTime());
    })), this.onMediaEvent("error", (() => {
      var t;
      this.emit("error", (t = this.getMediaElement().error) !== null && t !== void 0 ? t : new Error("Media error")), this.stopAtPosition = null;
    })));
  }
  initRendererEvents() {
    this.subscriptions.push(this.renderer.on("click", ((t, e) => {
      this.options.interact && (this.seekTo(t), this.emit("interaction", t * this.getDuration()), this.emit("click", t, e));
    })), this.renderer.on("dblclick", ((t, e) => {
      this.emit("dblclick", t, e);
    })), this.renderer.on("scroll", ((t, e, i, n) => {
      const s = this.getDuration();
      this.emit("scroll", t * s, e * s, i, n);
    })), this.renderer.on("render", (() => {
      this.emit("redraw");
    })), this.renderer.on("rendered", (() => {
      this.emit("redrawcomplete");
    })), this.renderer.on("dragstart", ((t) => {
      this.emit("dragstart", t);
    })), this.renderer.on("dragend", ((t) => {
      this.emit("dragend", t);
    })), this.renderer.on("resize", (() => {
      this.emit("resize");
    })));
    {
      let t;
      const e = this.renderer.on("drag", ((i) => {
        var n;
        if (!this.options.interact) return;
        this.renderer.renderProgress(i), clearTimeout(t);
        let s = 0;
        const a = this.options.dragToSeek;
        this.isPlaying() ? s = 0 : a === !0 ? s = 200 : a && typeof a == "object" && (s = (n = a.debounceTime) !== null && n !== void 0 ? n : 200), t = setTimeout((() => {
          this.seekTo(i);
        }), s), this.emit("interaction", i * this.getDuration()), this.emit("drag", i);
      }));
      this.subscriptions.push((() => {
        clearTimeout(t), e();
      }));
    }
  }
  initPlugins() {
    var t;
    !((t = this.options.plugins) === null || t === void 0) && t.length && this.options.plugins.forEach(((e) => {
      this.registerPlugin(e);
    }));
  }
  unsubscribePlayerEvents() {
    this.mediaSubscriptions.forEach(((t) => t())), this.mediaSubscriptions = [];
  }
  setOptions(t) {
    this.options = Object.assign({}, this.options, t), t.duration && !t.peaks && (this.decodedData = tt.createBuffer(this.exportPeaks(), t.duration)), t.peaks && t.duration && (this.decodedData = tt.createBuffer(t.peaks, t.duration)), this.renderer.setOptions(this.options), t.audioRate && this.setPlaybackRate(t.audioRate), t.mediaControls != null && (this.getMediaElement().controls = t.mediaControls);
  }
  registerPlugin(t) {
    if (this.plugins.includes(t)) return t;
    t._init(this), this.plugins.push(t);
    const e = t.once("destroy", (() => {
      this.plugins = this.plugins.filter(((i) => i !== t)), this.subscriptions = this.subscriptions.filter(((i) => i !== e));
    }));
    return this.subscriptions.push(e), t;
  }
  unregisterPlugin(t) {
    this.plugins = this.plugins.filter(((e) => e !== t)), t.destroy();
  }
  getWrapper() {
    return this.renderer.getWrapper();
  }
  getWidth() {
    return this.renderer.getWidth();
  }
  getScroll() {
    return this.renderer.getScroll();
  }
  setScroll(t) {
    return this.renderer.setScroll(t);
  }
  setScrollTime(t) {
    const e = t / this.getDuration();
    this.renderer.setScrollPercentage(e);
  }
  getActivePlugins() {
    return this.plugins;
  }
  loadAudio(t, e, i, n) {
    return A(this, void 0, void 0, (function* () {
      var s;
      if (this.emit("load", t), !this.options.media && this.isPlaying() && this.pause(), this.decodedData = null, this.stopAtPosition = null, (s = this.abortController) === null || s === void 0 || s.abort(), this.abortController = null, !e && !i) {
        const c = this.options.fetchParams || {};
        window.AbortController && !c.signal && (this.abortController = new AbortController(), c.signal = this.abortController.signal);
        const d = (o) => this.emit("loading", o);
        e = yield Ce.fetchBlob(t, d, c);
        const l = this.options.blobMimeType;
        l && (e = new Blob([e], { type: l }));
      }
      this.setSrc(t, e);
      const a = yield new Promise(((c) => {
        const d = n || this.getDuration();
        d ? c(d) : this.mediaSubscriptions.push(this.onMediaEvent("loadedmetadata", (() => c(this.getDuration())), { once: !0 }));
      }));
      if (!t && !e) {
        const c = this.getMediaElement();
        c instanceof at && (c.duration = a);
      }
      if (i) this.decodedData = tt.createBuffer(i, a || 0);
      else if (e) {
        const c = yield e.arrayBuffer();
        this.decodedData = yield tt.decode(c, this.options.sampleRate);
      }
      this.decodedData && (this.emit("decode", this.getDuration()), this.renderer.render(this.decodedData)), this.emit("ready", this.getDuration());
    }));
  }
  load(t, e, i) {
    return A(this, void 0, void 0, (function* () {
      try {
        return yield this.loadAudio(t, void 0, e, i);
      } catch (n) {
        throw this.emit("error", n), n;
      }
    }));
  }
  loadBlob(t, e, i) {
    return A(this, void 0, void 0, (function* () {
      try {
        return yield this.loadAudio("", t, e, i);
      } catch (n) {
        throw this.emit("error", n), n;
      }
    }));
  }
  zoom(t) {
    if (!this.decodedData) throw new Error("No audio loaded");
    this.renderer.zoom(t), this.emit("zoom", t);
  }
  getDecodedData() {
    return this.decodedData;
  }
  exportPeaks({ channels: t = 2, maxLength: e = 8e3, precision: i = 1e4 } = {}) {
    if (!this.decodedData) throw new Error("The audio has not been decoded yet");
    const n = Math.min(t, this.decodedData.numberOfChannels), s = [];
    for (let a = 0; a < n; a++) {
      const c = this.decodedData.getChannelData(a), d = [], l = c.length / e;
      for (let o = 0; o < e; o++) {
        const u = c.slice(Math.floor(o * l), Math.ceil((o + 1) * l));
        let m = 0;
        for (let p = 0; p < u.length; p++) {
          const f = u[p];
          Math.abs(f) > Math.abs(m) && (m = f);
        }
        d.push(Math.round(m * i) / i);
      }
      s.push(d);
    }
    return s;
  }
  getDuration() {
    let t = super.getDuration() || 0;
    return t !== 0 && t !== 1 / 0 || !this.decodedData || (t = this.decodedData.duration), t;
  }
  toggleInteraction(t) {
    this.options.interact = t;
  }
  setTime(t) {
    this.stopAtPosition = null, super.setTime(t), this.updateProgress(t), this.emit("timeupdate", t);
  }
  seekTo(t) {
    const e = this.getDuration() * t;
    this.setTime(e);
  }
  play(t, e) {
    const i = Object.create(null, { play: { get: () => super.play } });
    return A(this, void 0, void 0, (function* () {
      t != null && this.setTime(t);
      const n = yield i.play.call(this);
      return e != null && (this.media instanceof at ? this.media.stopAt(e) : this.stopAtPosition = e), n;
    }));
  }
  playPause() {
    return A(this, void 0, void 0, (function* () {
      return this.isPlaying() ? this.pause() : this.play();
    }));
  }
  stop() {
    this.pause(), this.setTime(0);
  }
  skip(t) {
    this.setTime(this.getCurrentTime() + t);
  }
  empty() {
    this.load("", [[0]], 1e-3);
  }
  setMediaElement(t) {
    this.unsubscribePlayerEvents(), super.setMediaElement(t), this.initPlayerEvents();
  }
  exportImage() {
    return A(this, arguments, void 0, (function* (t = "image/png", e = 1, i = "dataURL") {
      return this.renderer.exportImage(t, e, i);
    }));
  }
  destroy() {
    var t;
    this.emit("destroy"), (t = this.abortController) === null || t === void 0 || t.abort(), this.plugins.forEach(((e) => e.destroy())), this.subscriptions.forEach(((e) => e())), this.unsubscribePlayerEvents(), this.timer.destroy(), this.renderer.destroy(), super.destroy();
  }
}
G.BasePlugin = class extends K {
  constructor(r) {
    super(), this.subscriptions = [], this.isDestroyed = !1, this.options = r;
  }
  onInit() {
  }
  _init(r) {
    this.isDestroyed && (this.subscriptions = [], this.isDestroyed = !1), this.wavesurfer = r, this.onInit();
  }
  destroy() {
    this.emit("destroy"), this.subscriptions.forEach(((r) => r())), this.subscriptions = [], this.isDestroyed = !0, this.wavesurfer = void 0;
  }
}, G.dom = we;
function lt(r, t, e, i) {
  return new (e || (e = Promise))((function(n, s) {
    function a(l) {
      try {
        d(i.next(l));
      } catch (o) {
        s(o);
      }
    }
    function c(l) {
      try {
        d(i.throw(l));
      } catch (o) {
        s(o);
      }
    }
    function d(l) {
      var o;
      l.done ? n(l.value) : (o = l.value, o instanceof e ? o : new e((function(u) {
        u(o);
      }))).then(a, c);
    }
    d((i = i.apply(r, [])).next());
  }));
}
class jt {
  constructor() {
    this.listeners = {};
  }
  on(t, e, i) {
    if (this.listeners[t] || (this.listeners[t] = /* @__PURE__ */ new Set()), i?.once) {
      const n = (...s) => {
        this.un(t, n), e(...s);
      };
      return this.listeners[t].add(n), () => this.un(t, n);
    }
    return this.listeners[t].add(e), () => this.un(t, e);
  }
  un(t, e) {
    var i;
    (i = this.listeners[t]) === null || i === void 0 || i.delete(e);
  }
  once(t, e) {
    return this.on(t, e, { once: !0 });
  }
  unAll() {
    this.listeners = {};
  }
  emit(t, ...e) {
    this.listeners[t] && this.listeners[t].forEach(((i) => i(...e)));
  }
}
class De extends jt {
  constructor(t) {
    super(), this.subscriptions = [], this.isDestroyed = !1, this.options = t;
  }
  onInit() {
  }
  _init(t) {
    this.isDestroyed && (this.subscriptions = [], this.isDestroyed = !1), this.wavesurfer = t, this.onInit();
  }
  destroy() {
    this.emit("destroy"), this.subscriptions.forEach(((t) => t())), this.subscriptions = [], this.isDestroyed = !0, this.wavesurfer = void 0;
  }
}
class Te extends jt {
  constructor() {
    super(...arguments), this.animationFrameId = null, this.isRunning = !1;
  }
  start() {
    if (this.isRunning) return;
    this.isRunning = !0;
    const t = () => {
      this.isRunning && (this.emit("tick"), this.animationFrameId = requestAnimationFrame(t));
    };
    t();
  }
  stop() {
    this.isRunning = !1, this.animationFrameId !== null && (cancelAnimationFrame(this.animationFrameId), this.animationFrameId = null);
  }
  destroy() {
    this.stop();
  }
}
const ke = ["audio/webm", "audio/wav", "audio/mpeg", "audio/mp4", "audio/mp3"];
class pt extends De {
  constructor(t) {
    var e, i, n, s, a, c;
    super(Object.assign(Object.assign({}, t), { audioBitsPerSecond: (e = t.audioBitsPerSecond) !== null && e !== void 0 ? e : 128e3, scrollingWaveform: (i = t.scrollingWaveform) !== null && i !== void 0 && i, scrollingWaveformWindow: (n = t.scrollingWaveformWindow) !== null && n !== void 0 ? n : 5, continuousWaveform: (s = t.continuousWaveform) !== null && s !== void 0 && s, renderRecordedAudio: (a = t.renderRecordedAudio) === null || a === void 0 || a, mediaRecorderTimeslice: (c = t.mediaRecorderTimeslice) !== null && c !== void 0 ? c : void 0 })), this.stream = null, this.mediaRecorder = null, this.dataWindow = null, this.isWaveformPaused = !1, this.lastStartTime = 0, this.lastDuration = 0, this.duration = 0, this.micStream = null, this.recordedBlobUrl = null, this.timer = new Te(), this.subscriptions.push(this.timer.on("tick", (() => {
      const d = performance.now() - this.lastStartTime;
      this.duration = this.isPaused() ? this.duration : this.lastDuration + d, this.emit("record-progress", this.duration);
    })));
  }
  static create(t) {
    return new pt(t || {});
  }
  renderMicStream(t) {
    var e;
    const i = new AudioContext(), n = i.createMediaStreamSource(t), s = i.createAnalyser();
    n.connect(s), this.options.continuousWaveform && (s.fftSize = 32);
    const a = s.frequencyBinCount, c = new Float32Array(a);
    let d = 0;
    this.wavesurfer && ((e = this.originalOptions) !== null && e !== void 0 || (this.originalOptions = Object.assign({}, this.wavesurfer.options)), this.wavesurfer.options.interact = !1, this.options.scrollingWaveform && (this.wavesurfer.options.cursorWidth = 0));
    const l = setInterval((() => {
      var o, u, m, p;
      if (!this.isWaveformPaused) {
        if (s.getFloatTimeDomainData(c), this.options.scrollingWaveform) {
          const f = Math.floor((this.options.scrollingWaveformWindow || 0) * i.sampleRate), b = Math.min(f, this.dataWindow ? this.dataWindow.length + a : a), g = new Float32Array(f);
          if (this.dataWindow) {
            const T = Math.max(0, f - this.dataWindow.length);
            g.set(this.dataWindow.slice(-b + a), T);
          }
          g.set(c, f - a), this.dataWindow = g;
        } else if (this.options.continuousWaveform) {
          if (!this.dataWindow) {
            const b = this.options.continuousWaveformDuration ? Math.round(100 * this.options.continuousWaveformDuration) : ((u = (o = this.wavesurfer) === null || o === void 0 ? void 0 : o.getWidth()) !== null && u !== void 0 ? u : 0) * window.devicePixelRatio;
            this.dataWindow = new Float32Array(b);
          }
          let f = 0;
          for (let b = 0; b < a; b++) {
            const g = Math.abs(c[b]);
            g > f && (f = g);
          }
          if (d + 1 > this.dataWindow.length) {
            const b = new Float32Array(2 * this.dataWindow.length);
            b.set(this.dataWindow, 0), this.dataWindow = b;
          }
          this.dataWindow[d] = f, d++;
        } else this.dataWindow = c;
        if (this.wavesurfer) {
          const f = ((p = (m = this.dataWindow) === null || m === void 0 ? void 0 : m.length) !== null && p !== void 0 ? p : 0) / 100;
          this.wavesurfer.load("", [this.dataWindow], this.options.scrollingWaveform ? this.options.scrollingWaveformWindow : f).then((() => {
            this.wavesurfer && this.options.continuousWaveform && (this.wavesurfer.setTime(this.getDuration() / 1e3), this.wavesurfer.options.minPxPerSec || this.wavesurfer.setOptions({ minPxPerSec: this.wavesurfer.getWidth() / this.wavesurfer.getDuration() }));
          })).catch(((b) => {
            console.error("Error rendering real-time recording data:", b);
          }));
        }
      }
    }), 10);
    return { onDestroy: () => {
      clearInterval(l), n?.disconnect(), i?.close();
    }, onEnd: () => {
      this.isWaveformPaused = !0, this.stopMic();
    } };
  }
  startMic(t) {
    return lt(this, void 0, void 0, (function* () {
      let e;
      this.micStream && this.stopMic();
      try {
        e = yield navigator.mediaDevices.getUserMedia({ audio: t == null || t });
      } catch (n) {
        throw new Error("Error accessing the microphone: " + n.message);
      }
      const i = this.renderMicStream(e);
      return this.micStream = i, this.unsubscribeDestroy = this.once("destroy", i.onDestroy), this.unsubscribeRecordEnd = this.once("record-end", i.onEnd), this.stream = e, e;
    }));
  }
  stopMic() {
    var t, e, i;
    (t = this.micStream) === null || t === void 0 || t.onDestroy(), (e = this.unsubscribeDestroy) === null || e === void 0 || e.call(this), (i = this.unsubscribeRecordEnd) === null || i === void 0 || i.call(this), this.micStream = null, this.unsubscribeDestroy = void 0, this.unsubscribeRecordEnd = void 0, this.stream && (this.stream.getTracks().forEach(((n) => n.stop())), this.stream = null, this.mediaRecorder = null);
  }
  startRecording(t) {
    return lt(this, void 0, void 0, (function* () {
      const e = this.stream || (yield this.startMic(t));
      this.dataWindow = null;
      const i = this.mediaRecorder || new MediaRecorder(e, { mimeType: this.options.mimeType || ke.find(((a) => MediaRecorder.isTypeSupported(a))), audioBitsPerSecond: this.options.audioBitsPerSecond });
      this.mediaRecorder = i, this.stopRecording();
      const n = [];
      i.ondataavailable = (a) => {
        a.data.size > 0 && n.push(a.data), this.emit("record-data-available", a.data);
      };
      const s = (a) => {
        var c;
        const d = new Blob(n, { type: i.mimeType });
        this.emit(a, d), this.options.renderRecordedAudio && (this.applyOriginalOptionsIfNeeded(), this.recordedBlobUrl && URL.revokeObjectURL(this.recordedBlobUrl), this.recordedBlobUrl = URL.createObjectURL(d), (c = this.wavesurfer) === null || c === void 0 || c.load(this.recordedBlobUrl));
      };
      i.onpause = () => s("record-pause"), i.onstop = () => s("record-end"), i.start(this.options.mediaRecorderTimeslice), this.lastStartTime = performance.now(), this.lastDuration = 0, this.duration = 0, this.isWaveformPaused = !1, this.timer.start(), this.emit("record-start");
    }));
  }
  getDuration() {
    return this.duration;
  }
  isRecording() {
    var t;
    return ((t = this.mediaRecorder) === null || t === void 0 ? void 0 : t.state) === "recording";
  }
  isPaused() {
    var t;
    return ((t = this.mediaRecorder) === null || t === void 0 ? void 0 : t.state) === "paused";
  }
  isActive() {
    var t;
    return ((t = this.mediaRecorder) === null || t === void 0 ? void 0 : t.state) !== "inactive";
  }
  stopRecording() {
    var t;
    this.isActive() && ((t = this.mediaRecorder) === null || t === void 0 || t.stop(), this.timer.stop());
  }
  pauseRecording() {
    var t, e;
    this.isRecording() && (this.isWaveformPaused = !0, (t = this.mediaRecorder) === null || t === void 0 || t.requestData(), (e = this.mediaRecorder) === null || e === void 0 || e.pause(), this.timer.stop(), this.lastDuration = this.duration);
  }
  resumeRecording() {
    var t;
    this.isPaused() && (this.isWaveformPaused = !1, (t = this.mediaRecorder) === null || t === void 0 || t.resume(), this.timer.start(), this.lastStartTime = performance.now(), this.emit("record-resume"));
  }
  static getAvailableAudioDevices() {
    return lt(this, void 0, void 0, (function* () {
      return navigator.mediaDevices.enumerateDevices().then(((t) => t.filter(((e) => e.kind === "audioinput"))));
    }));
  }
  destroy() {
    this.applyOriginalOptionsIfNeeded(), super.destroy(), this.stopRecording(), this.stopMic(), this.recordedBlobUrl && (URL.revokeObjectURL(this.recordedBlobUrl), this.recordedBlobUrl = null);
  }
  applyOriginalOptionsIfNeeded() {
    this.wavesurfer && this.originalOptions && (this.wavesurfer.setOptions(this.originalOptions), delete this.originalOptions);
  }
}
const Ae = (r, t) => {
  const {
    libConfig: {
      enforceDownloadInNewTab: e = !1
      // Default to false, if no libConfig, e.g. for tests
    }
  } = h.useContext(Zt);
  return h.useCallback(() => {
    if (!r) return;
    const n = ge({
      enforceDownloadInNewTab: e,
      url: r,
      filename: t
    });
    n.style.display = "none", document.body.appendChild(n), n.click(), document.body.removeChild(n);
  }, [r, e, t]);
}, ct = ({
  widgetMgr: r,
  id: t,
  formId: e,
  key: i,
  defaultValue: n
}) => {
  h.useEffect(() => {
    const o = r.getElementState(t, i);
    ut(o) && $(n) && r.setElementState(t, i, n);
  }, [r, t, i, n]);
  const [s, a] = h.useState(r.getElementState(t, i) ?? n), c = h.useCallback((o) => {
    r.setElementState(t, i, o), a(o);
  }, [r, t, i]), d = h.useMemo(() => ({
    formId: e || ""
  }), [e]), l = h.useCallback(() => c(n), [n, c]);
  return fe({
    element: d,
    widgetMgr: r,
    onFormCleared: l
  }), [s, c];
}, Me = async ({
  files: r,
  uploadClient: t,
  widgetMgr: e,
  widgetInfo: i,
  fragmentId: n
}) => {
  let s = [];
  try {
    s = await t.fetchFileURLs(r);
  } catch (l) {
    return {
      successfulUploads: [],
      failedUploads: r.map((o) => ({
        file: o,
        error: Rt(l)
      }))
    };
  }
  const a = Kt(r, s), c = [], d = [];
  return await Promise.all(a.map(async ([l, o]) => {
    if (!l || !o?.uploadUrl || !o.fileId)
      return {
        file: l,
        fileUrl: o,
        error: new Error("No upload URL found")
      };
    try {
      await t.uploadFile(
        {
          id: o.fileId,
          formId: i.formId || ""
        },
        // TODO SEE IF DOWNSTREAM LOGIC CAN BE SIMPLIFIED
        o.uploadUrl,
        l
      ), c.push({
        fileUrl: o,
        file: l
      });
    } catch (u) {
      const m = Rt(u);
      d.push({
        file: l,
        error: m
      });
    }
  })), e.setFileUploaderStateValue(i, new Jt({
    uploadedFileInfo: c.map(({
      file: l,
      fileUrl: o
    }) => new Qt({
      fileId: o.fileId,
      fileUrls: o,
      name: l.webkitRelativePath || l.name,
      size: l.size
    }))
  }), {
    fromUi: !0
  }, n), {
    successfulUploads: c,
    failedUploads: d
  };
}, Ie = /* @__PURE__ */ M("div", {
  target: "e12wn80j14"
})(""), kt = /* @__PURE__ */ M("div", {
  target: "e12wn80j13"
})(({
  theme: r,
  disabled: t
}) => ({
  height: r.sizes.largestElementHeight,
  width: "100%",
  background: r.colors.secondaryBg,
  borderRadius: r.radii.default,
  marginBottom: r.spacing.twoXS,
  display: "flex",
  alignItems: "center",
  position: "relative",
  paddingLeft: r.spacing.xs,
  paddingRight: r.spacing.sm,
  border: r.colors.widgetBorderColor ? `${r.sizes.borderWidth} solid ${r.colors.widgetBorderColor}` : void 0,
  cursor: t ? "not-allowed" : "auto"
}), ""), Oe = /* @__PURE__ */ M("div", {
  target: "e12wn80j12"
})({
  name: "82a6rk",
  styles: "flex:1"
}), Le = /* @__PURE__ */ M("div", {
  target: "e12wn80j11"
})(({
  show: r
}) => ({
  display: r ? "block" : "none"
}), ""), Ue = /* @__PURE__ */ M("span", {
  target: "e12wn80j10"
})(({
  theme: r,
  isPlayingOrRecording: t,
  disabled: e
}) => ({
  margin: r.spacing.sm,
  fontFamily: r.fonts.monospace,
  color: e ? r.colors.fadedText40 : t ? r.colors.bodyText : r.colors.fadedText60,
  backgroundColor: r.colors.secondaryBg,
  fontSize: r.fontSizes.sm
}), ""), Ft = /* @__PURE__ */ M("div", {
  target: "e12wn80j9"
})({
  name: "1kyw74z",
  styles: "width:100%;text-align:center;overflow:hidden"
}), Nt = /* @__PURE__ */ M("span", {
  target: "e12wn80j8"
})(({
  theme: r
}) => ({
  color: r.colors.bodyText
}), ""), Be = /* @__PURE__ */ M("a", {
  target: "e12wn80j7"
})(({
  theme: r
}) => ({
  color: r.colors.link,
  textDecoration: r.linkUnderline ? "underline" : "none"
}), ""), je = /* @__PURE__ */ M("div", {
  target: "e12wn80j6"
})(({
  theme: r
}) => ({
  height: r.sizes.largestElementHeight,
  display: "flex",
  justifyContent: "center",
  alignItems: "center"
}), ""), Fe = /* @__PURE__ */ M("div", {
  target: "e12wn80j5"
})(({
  theme: r
}) => {
  const t = "0.625em";
  return {
    opacity: 0.2,
    width: "100%",
    height: t,
    backgroundSize: t,
    backgroundImage: `radial-gradient(${r.colors.fadedText10} 40%, transparent 40%)`,
    backgroundRepeat: "repeat"
  };
}, ""), Ne = /* @__PURE__ */ M("span", {
  target: "e12wn80j4"
})(({
  theme: r
}) => ({
  "& > button": {
    color: r.colors.primary,
    padding: r.spacing.threeXS
  },
  "& > button:hover, & > button:focus": {
    color: r.colors.redColor
  }
}), ""), He = /* @__PURE__ */ M("span", {
  target: "e12wn80j3"
})(({
  theme: r
}) => ({
  "& > button": {
    padding: r.spacing.threeXS,
    color: r.colors.fadedText60
  },
  "& > button:hover, & > button:focus": {
    color: r.colors.bodyText
  }
}), ""), Ht = /* @__PURE__ */ M("span", {
  target: "e12wn80j2"
})(({
  theme: r
}) => ({
  "& > button": {
    padding: r.spacing.threeXS,
    color: r.colors.fadedText60
  },
  "& > button:hover, & > button:focus": {
    color: r.colors.bodyText
  }
}), ""), dt = /* @__PURE__ */ M("div", {
  target: "e12wn80j1"
})(({
  theme: r
}) => ({
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  flexGrow: 0,
  flexShrink: 1,
  padding: r.spacing.xs,
  gap: r.spacing.twoXS,
  marginRight: r.spacing.twoXS
}), ""), ze = /* @__PURE__ */ M("div", {
  target: "e12wn80j0"
})(({
  theme: r
}) => ({
  marginLeft: r.spacing.sm
}), ""), q = ({
  onClick: r,
  disabled: t,
  ariaLabel: e,
  iconContent: i
}) => /* @__PURE__ */ v.jsx(ee, { kind: ie.BORDERLESS_ICON, onClick: r, disabled: t, "aria-label": e, containerWidth: !0, "data-testid": "stAudioInputActionButton", children: /* @__PURE__ */ v.jsx(re, { content: i, size: "lg", color: "inherit" }) }), _e = ({
  disabled: r,
  stopRecording: t
}) => /* @__PURE__ */ v.jsx(Ne, { children: /* @__PURE__ */ v.jsx(q, { onClick: t, disabled: r, ariaLabel: "Stop recording", iconContent: Lt }) }), $e = ({
  disabled: r,
  isPlaying: t,
  onClickPlayPause: e
}) => /* @__PURE__ */ v.jsx(Ht, { children: t ? /* @__PURE__ */ v.jsx(q, { onClick: e, disabled: r, ariaLabel: "Pause", iconContent: Mt }) : /* @__PURE__ */ v.jsx(q, { onClick: e, disabled: r, ariaLabel: "Play", iconContent: It }) }), Ve = ({
  disabled: r,
  startRecording: t
}) => /* @__PURE__ */ v.jsx(He, { children: /* @__PURE__ */ v.jsx(q, { onClick: t, disabled: r, ariaLabel: "Record", iconContent: At }) }), Xe = ({
  onClick: r
}) => /* @__PURE__ */ v.jsx(Ht, { children: /* @__PURE__ */ v.jsx(q, { disabled: !1, onClick: r, ariaLabel: "Reset", iconContent: Ot }) }), Ge = ({
  disabled: r,
  isRecording: t,
  isPlaying: e,
  isUploading: i,
  isError: n,
  recordingUrlExists: s,
  startRecording: a,
  stopRecording: c,
  onClickPlayPause: d,
  onClear: l
}) => n ? /* @__PURE__ */ v.jsx(dt, { children: /* @__PURE__ */ v.jsx(Xe, { onClick: l }) }) : i ? /* @__PURE__ */ v.jsx(dt, { children: /* @__PURE__ */ v.jsx(te, { "aria-label": "Uploading", size: "base", margin: "0", padding: "0" }) }) : /* @__PURE__ */ v.jsxs(dt, { children: [
  t ? /* @__PURE__ */ v.jsx(_e, { disabled: r, stopRecording: c }) : /* @__PURE__ */ v.jsx(Ve, { disabled: r, startRecording: a }),
  s && /* @__PURE__ */ v.jsx($e, { disabled: r, isPlaying: e, onClickPlayPause: d })
] }), qe = h.memo(Ge), Ye = () => /* @__PURE__ */ v.jsx(Ft, { children: /* @__PURE__ */ v.jsx(Nt, { children: "An error has occurred, please try again." }) }), Ze = h.memo(Ye), Ke = 4, Je = 4, Qe = 4, ti = 8, ei = 0, et = "00:00", _ = ne.getLogger("convertAudioToWav");
async function ii(r, t) {
  if (!r || r.size === 0) {
    _.error("Invalid or empty blob provided");
    return;
  }
  if (!window.AudioContext) {
    _.error("AudioContext not supported in this browser");
    return;
  }
  const e = new AudioContext();
  let i;
  try {
    i = await r.arrayBuffer();
  } catch (u) {
    _.error("Failed to read blob as ArrayBuffer", u), e.close();
    return;
  }
  let n;
  try {
    n = await e.decodeAudioData(i);
  } catch (u) {
    _.error("Failed to decode audio data", u), e.close();
    return;
  } finally {
    e.close();
  }
  const s = t || n.sampleRate;
  if (s === n.sampleRate)
    return _.debug(`No resampling needed, sample rate is already ${s}Hz`), it(n, s);
  _.debug(`Resampling from ${n.sampleRate}Hz to ${s}Hz`);
  const {
    duration: a,
    numberOfChannels: c
  } = n, d = Math.ceil(a * s);
  if (!window.OfflineAudioContext)
    return _.error("OfflineAudioContext not supported, falling back to no resampling"), it(n, n.sampleRate);
  const l = new OfflineAudioContext(c, d, s), o = l.createBufferSource();
  o.buffer = n, o.connect(l.destination), o.start(0);
  try {
    const u = await l.startRendering();
    return it(u, s);
  } catch (u) {
    return _.error("Failed to resample audio using OfflineAudioContext", u), it(n, n.sampleRate);
  }
}
function it(r, t) {
  const i = r.numberOfChannels, n = r.length * i * 2 + 44, s = new ArrayBuffer(n), a = new DataView(s), c = (l, o) => {
    for (let u = 0; u < o.length; u++)
      a.setUint8(l + u, o.charCodeAt(u));
  };
  c(0, "RIFF"), a.setUint32(4, n - 8, !0), c(8, "WAVE"), c(12, "fmt "), a.setUint32(16, 16, !0), a.setUint16(20, 1, !0), a.setUint16(22, i, !0), a.setUint32(24, t, !0), a.setUint32(28, t * i * 2, !0), a.setUint16(32, i * 2, !0), a.setUint16(34, 16, !0), c(36, "data"), a.setUint32(40, n - 44, !0);
  let d = 44;
  for (let l = 0; l < r.length; l++)
    for (let o = 0; o < i; o++) {
      const u = Math.max(-1, Math.min(1, r.getChannelData(o)[l]));
      a.setInt16(d, u * 32767, !0), d += 2;
    }
  return new Blob([s], {
    type: "audio/wav"
  });
}
const ht = (r) => {
  const t = Math.floor(r / 1e3), e = Math.floor(t / 60), i = Math.floor(e / 60), n = t % 60, s = e % 60, a = n.toString().padStart(2, "0"), c = s.toString().padStart(2, "0"), d = i.toString().padStart(2, "0");
  return e < 60 ? `${c}:${a}` : `${d}:${c}:${a}`;
}, ri = () => /* @__PURE__ */ v.jsxs(Ft, { children: [
  /* @__PURE__ */ v.jsx(Nt, { children: "This app would like to use your microphone." }),
  " ",
  /* @__PURE__ */ v.jsx(Be, { href: se, rel: "noopener noreferrer", target: "_blank", children: "Learn how to allow access." })
] }), ni = h.memo(ri), si = () => /* @__PURE__ */ v.jsx(je, { children: /* @__PURE__ */ v.jsx(Fe, {}) }), oi = h.memo(si), ai = ({
  element: r,
  uploadClient: t,
  widgetMgr: e,
  fragmentId: i,
  disabled: n
}) => {
  const s = oe(), a = ve(s), [c, d] = h.useState(null), l = h.useRef(null), o = h.useRef(null), [u, m] = ct({
    widgetMgr: e,
    id: r.id,
    key: "deleteFileUrl",
    defaultValue: null
  }), [p, f] = ct({
    widgetMgr: e,
    id: r.id,
    key: "recordingUrl",
    defaultValue: null
  }), [, b] = h.useState(0), g = h.useCallback(() => {
    b((y) => y + 1);
  }, []), [T, W] = h.useState(et), [D, R] = ct({
    widgetMgr: e,
    id: r.id,
    formId: r.formId,
    key: "recordingTime",
    defaultValue: et
  }), [x, w] = h.useState(!1), [C, E] = h.useState(!1), [I, U] = h.useState(!1), [F, O] = h.useState(!1), [N, L] = h.useState(!1), X = r.id, B = r.formId, H = r.sampleRate || null, j = h.useRef(null), rt = h.useRef({}), ft = h.useCallback(async (y) => {
    try {
      O(!0), $(B) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set([B]));
      let S;
      if (y.type === "audio/wav" ? S = y : S = await ii(y, H || void 0), !S) {
        L(!0), O(!1), $(B) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set());
        return;
      }
      let k;
      try {
        k = URL.createObjectURL(S), o.current && o.current !== k && URL.revokeObjectURL(o.current), o.current = k;
      } catch {
        L(!0), O(!1), $(B) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set());
        return;
      }
      f(k), c && (c.load(k), c.setOptions({
        interact: !0,
        waveColor: Q(s.colors.fadedText40, s.colors.secondaryBg),
        progressColor: s.colors.bodyText
      }));
      const V = (/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/:/g, "-"), P = new File([S], `${V}_audio.wav`, {
        type: S.type
      });
      try {
        const {
          successfulUploads: J,
          failedUploads: st
        } = await Me({
          files: [P],
          uploadClient: t,
          widgetMgr: e,
          widgetInfo: {
            id: X,
            formId: B
          },
          fragmentId: i
        });
        if (st.length > 0) {
          L(!0);
          return;
        }
        L(!1);
        const St = J[0];
        St?.fileUrl?.deleteUrl && m(St.fileUrl.deleteUrl);
      } catch {
        L(!0);
      } finally {
        $(B) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set()), O(!1);
      }
    } catch {
      L(!0), O(!1), $(B) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set());
    }
  }, [t, e, c, X, B, i, m, H, f, s.colors.fadedText40, s.colors.secondaryBg, s.colors.bodyText]), z = h.useCallback(async ({
    updateWidgetManager: y,
    deleteFile: S
  }) => {
    if (ut(c))
      return;
    const k = p;
    if (k && o.current === k && (URL.revokeObjectURL(k), o.current = null), f(null), m(null), W(et), R(et), w(!1), c.empty(), y && e.setFileUploaderStateValue(r, {}, {
      fromUi: !0
    }, i), S && u)
      try {
        await t.deleteFile(u);
      } catch {
      }
    $(k) && URL.revokeObjectURL(k);
  }, [u, p, t, c, r, e, i, R, m, f]);
  h.useEffect(() => {
    if (ut(B)) return;
    const y = new me();
    return y.manageFormClearListener(e, B, () => {
      z({
        updateWidgetManager: !0,
        deleteFile: !1
      });
    }), () => y.disconnect();
  }, [B, z, e]);
  const mt = h.useCallback(() => {
    if (l.current === null) return;
    const y = G.create({
      container: l.current,
      waveColor: p ? Q(s.colors.fadedText40, s.colors.secondaryBg) : s.colors.primary,
      progressColor: s.colors.bodyText,
      height: ae(s.sizes.largestElementHeight) - 2 * Ke,
      barWidth: Je,
      barGap: Qe,
      barRadius: ti,
      cursorWidth: ei,
      interact: !0
    }), S = (P) => {
      W(ht(P * 1e3));
    }, k = () => {
      g();
    };
    y.on("timeupdate", S), y.on("pause", k), d(y), p && (y.load(p), y.setOptions({
      interact: !0
    }));
    const V = {
      renderRecordedAudio: !1,
      scrollingWaveform: !1,
      mimeType: "audio/webm"
    };
    try {
      const P = y.registerPlugin(pt.create(V));
      j.current = P;
      const J = (st) => {
        R(ht(st));
      };
      P.on("record-progress", J), rt.current = {
        handleRecordProgress: J
      };
    } catch (P) {
      P instanceof Error && (P.name === "NotAllowedError" || P.name === "PermissionDeniedError") && E(!0);
    }
    return () => {
      if (j.current) {
        j.current.isRecording() && j.current.stopRecording();
        const P = rt.current;
        P.handleRecordProgress && j.current.un("record-progress", P.handleRecordProgress), j.current.destroy(), j.current = null, rt.current = {};
      }
      y && (y.un("timeupdate", S), y.un("pause", k), y.destroy());
    };
  }, [s, W, g, p, R, E]);
  h.useEffect(() => mt(), [mt]), h.useEffect(() => {
    le(a, s) || c?.setOptions({
      waveColor: p ? Q(s.colors.fadedText40, s.colors.secondaryBg) : s.colors.primary,
      progressColor: s.colors.bodyText,
      interact: !0
    });
  }, [s, a, p, c]);
  const zt = h.useCallback(() => {
    if (!c) return;
    (async () => {
      try {
        await c.playPause();
      } catch {
        L(!0);
      }
      w(!0), g();
    })();
  }, [c, g]), gt = h.useCallback(async () => {
    if (!I) {
      U(!0);
      let y = null;
      try {
        y = await navigator.mediaDevices.getUserMedia({
          audio: !0
        });
      } catch {
        E(!0);
        return;
      } finally {
        y && y.getTracks().forEach((S) => S.stop());
      }
    }
    if (p && await z({
      updateWidgetManager: !1,
      deleteFile: !0
    }), j.current && c) {
      c.setOptions({
        waveColor: s.colors.primary
      });
      const y = H ? {
        sampleRate: {
          ideal: H
        }
      } : {};
      try {
        await j.current.startRecording(y), R(ht(0)), g();
      } catch (S) {
        S instanceof Error && (S.name === "NotAllowedError" || S.name === "PermissionDeniedError") ? E(!0) : L(!0);
      }
    } else C || L(!0);
  }, [I, R, C, H, c, s.colors.primary, g, p, z]), vt = h.useCallback((y) => new Promise((S, k) => {
    const V = (P) => {
      y.un("record-end", V), P && P instanceof Blob && P.size > 0 ? S(P) : k(new Error("Invalid or empty recording blob"));
    };
    y.on("record-end", V), y.stopRecording();
  }), []), bt = h.useCallback(async () => {
    const y = j.current;
    if (y?.isRecording())
      try {
        const S = await vt(y);
        await ft(S), c && c.setOptions({
          waveColor: Q(s.colors.fadedText40, s.colors.secondaryBg),
          progressColor: s.colors.bodyText
        });
      } catch {
        L(!0);
      }
  }, [ft, c, s, vt]), yt = Ae(p, "recording.wav"), nt = j.current?.isRecording() || !1, wt = !!c?.isPlaying(), _t = nt || wt, Ct = !nt && !p && !C, $t = C || Ct || N, Vt = h.useCallback(() => {
    gt();
  }, [gt]), Xt = h.useCallback(() => {
    bt();
  }, [bt]), Gt = h.useCallback(() => {
    z({
      updateWidgetManager: !1,
      deleteFile: !0
    }), L(!1);
  }, [z]), qt = h.useCallback(() => {
    yt();
  }, [yt]), Yt = h.useCallback(() => {
    z({
      updateWidgetManager: !0,
      deleteFile: !0
    });
  }, [z]);
  return /* @__PURE__ */ v.jsxs(Ie, { className: "stAudioInput", "data-testid": "stAudioInput", children: [
    /* @__PURE__ */ v.jsx(ce, { label: r.label, disabled: n, labelVisibility: de(r.labelVisibility?.value), children: r.help && /* @__PURE__ */ v.jsx(ze, { children: /* @__PURE__ */ v.jsx(he, { content: r.help, placement: ue.TOP }) }) }),
    /* @__PURE__ */ v.jsxs(kt, { disabled: n, children: [
      /* @__PURE__ */ v.jsxs(pe, { isFullScreen: !1, disableFullscreenMode: !0, target: kt, children: [
        p && /* @__PURE__ */ v.jsx(xt, { label: "Download as WAV", icon: be, onClick: qt }),
        u && /* @__PURE__ */ v.jsx(xt, { label: "Clear recording", icon: ye, onClick: Yt })
      ] }),
      /* @__PURE__ */ v.jsx(qe, { isRecording: nt, isPlaying: wt, isUploading: F, isError: N, recordingUrlExists: !!p, startRecording: Vt, stopRecording: Xt, onClickPlayPause: zt, onClear: Gt, disabled: n || C }),
      /* @__PURE__ */ v.jsxs(Oe, { children: [
        N && /* @__PURE__ */ v.jsx(Ze, {}),
        Ct && /* @__PURE__ */ v.jsx(oi, {}),
        C && /* @__PURE__ */ v.jsx(ni, {}),
        /* @__PURE__ */ v.jsx(Le, { "data-testid": "stAudioInputWaveSurfer", ref: l, show: !$t })
      ] }),
      /* @__PURE__ */ v.jsx(Ue, { isPlayingOrRecording: _t, disabled: n, "data-testid": "stAudioInputWaveformTimeCode", children: x ? T : D })
    ] })
  ] });
}, mi = h.memo(ai);
export {
  mi as default
};
//# sourceMappingURL=index-Co6MYdT7.js.map
