import { r as h, m as Zt, x as _, aH as Q, v as ut, aB as Jt, y as Kt, j as v, c as I, aI as Qt, aJ as te, aK as ee, ap as ie, l as re, as as Rt, aL as se, aM as ne, aN as oe, L as ae, aO as le, aP as de, aQ as ce, ai as he, aR as ue, E as Y, _ as Z } from "./index-6wLGsgHc.js";
import { y as pe, X as St } from "./Toolbar-Ba82LOXi-BP4R8EQ5.js";
import { d as me, m as fe } from "./FormClearHelper-Dgu5Halt-DyRdP6JG.js";
import { a as ge } from "./createDownloadLinkElement-CbRjLJ8e-BjJEUuqX.js";
import { o as ve } from "./Hooks-BLb3umpI-DYKqkUO8.js";
import { i as be, o as ye } from "./FileDownload.esm-BP6Yw6Mo-B_twH90j.js";
var Tt = /* @__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"
  }));
});
Tt.displayName = "Mic";
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 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"
  }));
});
It.displayName = "Pause";
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("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"
  }));
});
At.displayName = "PlayArrow";
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("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"
  }));
});
Lt.displayName = "Refresh";
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("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"
  }));
});
Ot.displayName = "StopCircle";
function T(r, t, e, i) {
  return new (e || (e = Promise))(function(s, n) {
    function d(a) {
      try {
        c(i.next(a));
      } catch (o) {
        n(o);
      }
    }
    function l(a) {
      try {
        c(i.throw(a));
      } catch (o) {
        n(o);
      }
    }
    function c(a) {
      var o;
      a.done ? s(a.value) : (o = a.value, o instanceof e ? o : new e(function(m) {
        m(o);
      })).then(d, l);
    }
    c((i = i.apply(r, t || [])).next());
  });
}
let J = class {
  constructor() {
    this.listeners = {};
  }
  on(r, t, e) {
    if (this.listeners[r] || (this.listeners[r] = /* @__PURE__ */ new Set()), e?.once) {
      const i = (...s) => {
        this.un(r, i), t(...s);
      };
      return this.listeners[r].add(i), () => this.un(r, i);
    }
    return this.listeners[r].add(t), () => this.un(r, t);
  }
  un(r, t) {
    var e;
    (e = this.listeners[r]) === null || e === void 0 || e.delete(t);
  }
  once(r, t) {
    return this.on(r, t, {
      once: !0
    });
  }
  unAll() {
    this.listeners = {};
  }
  emit(r, ...t) {
    this.listeners[r] && this.listeners[r].forEach((e) => e(...t));
  }
};
const tt = {
  decode: function(r, t) {
    return T(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 s = i[0];
      if (s.some((n) => n > 1 || n < -1)) {
        const n = s.length;
        let d = 0;
        for (let l = 0; l < n; l++) {
          const c = Math.abs(s[l]);
          c > d && (d = c);
        }
        for (const l of i) for (let c = 0; c < n; c++) l[c] /= d;
      }
    })(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 s = e[i];
        if (!s) throw new Error(`Channel ${i} not found`);
        return s;
      },
      copyFromChannel: AudioBuffer.prototype.copyFromChannel,
      copyToChannel: AudioBuffer.prototype.copyToChannel
    };
  }
};
function jt(r, t) {
  const e = t.xmlns ? document.createElementNS(t.xmlns, r) : document.createElement(r);
  for (const [i, s] of Object.entries(t)) if (i === "children" && s) for (const [n, d] of Object.entries(s)) d instanceof Node ? e.appendChild(d) : typeof d == "string" ? e.appendChild(document.createTextNode(d)) : e.appendChild(jt(n, d));
  else i === "style" ? Object.assign(e.style, s) : i === "textContent" ? e.textContent = s : e.setAttribute(i, s.toString());
  return e;
}
function Et(r, t, e) {
  const i = jt(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 T(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(s, n) {
        T(this, void 0, void 0, function* () {
          if (!s.body || !s.headers) return;
          const d = s.body.getReader(), l = Number(s.headers.get("Content-Length")) || 0;
          let c = 0;
          const a = (o) => {
            c += o?.length || 0;
            const m = Math.round(c / l * 100);
            n(m);
          };
          try {
            for (; ; ) {
              const o = yield d.read();
              if (o.done) break;
              a(o.value);
            }
          } catch (o) {
            console.warn("Progress tracking error:", o);
          }
        });
      })(i.clone(), t), i.blob();
    });
  }
};
class xe extends J {
  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 s = e instanceof Blob && (this.canPlayType(e.type) || !t) ? URL.createObjectURL(e) : t;
    if (i && this.media.removeAttribute("src"), s || t) try {
      this.media.src = s;
    } 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 T(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 s = Math.round(r * e * i);
  return {
    topHeight: s,
    totalHeight: s + Math.round(t * e * i) || 1
  };
}
function Se({
  barAlign: r,
  halfHeight: t,
  topHeight: e,
  totalHeight: i,
  canvasHeight: s
}) {
  return r === "top" ? 0 : r === "bottom" ? s - i : t - e;
}
function Pt(r, t, e) {
  const i = t - r.left, s = e - r.top;
  return [i / r.width, s / r.height];
}
function Ut(r) {
  return !!(r.barWidth || r.barGap || r.barAlign);
}
function Wt(r, t) {
  if (!Ut(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 kt({
  scrollLeft: r,
  totalWidth: t,
  numCanvases: e
}) {
  if (t === 0) return [0];
  const i = r / t, s = Math.floor(i * e);
  return [s - 1, s, s + 1];
}
function Dt({
  scrollLeft: r,
  clientWidth: t,
  scrollWidth: e
}) {
  return e === 0 ? {
    startX: 0,
    endX: 0
  } : {
    startX: r / e,
    endX: (r + t) / e
  };
}
class Ee extends J {
  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 [s, n] = this.initHtml();
    i.appendChild(s), this.container = s, this.scrollContainer = n.querySelector(".scroll"), this.wrapper = n.querySelector(".wrapper"), this.canvasWrapper = n.querySelector(".canvases"), this.progressWrapper = n.querySelector(".progress"), this.cursor = n.querySelector(".cursor"), e && n.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, s] = Pt(e, t.clientX, t.clientY);
      this.emit("click", i, s);
    }), this.wrapper.addEventListener("dblclick", (t) => {
      const e = this.wrapper.getBoundingClientRect(), [i, s] = Pt(e, t.clientX, t.clientY);
      this.emit("dblclick", i, s);
    }), 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: s,
        endX: n
      } = Dt({
        scrollLeft: t,
        scrollWidth: e,
        clientWidth: i
      });
      this.emit("scroll", s, n, 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, s, n = 3, d = 0, l = 100) {
      if (!t) return () => {
      };
      const c = /* @__PURE__ */ new Map(), a = matchMedia("(pointer: coarse)").matches;
      let o = () => {
      };
      const m = (f) => {
        if (f.button !== d || (c.set(f.pointerId, f), c.size > 1)) return;
        let u = f.clientX, p = f.clientY, b = !1;
        const g = Date.now(), D = (y) => {
          if (y.defaultPrevented || c.size > 1 || a && Date.now() - g < l) return;
          const C = y.clientX, E = y.clientY, A = C - u, j = E - p;
          if (b || Math.abs(A) > n || Math.abs(j) > n) {
            y.preventDefault(), y.stopPropagation();
            const F = t.getBoundingClientRect(), {
              left: L,
              top: N
            } = F;
            b || (i?.(u - L, p - N), b = !0), e(A, j, C - L, E - N), u = C, p = E;
          }
        }, W = (y) => {
          if (c.delete(y.pointerId), b) {
            const C = y.clientX, E = y.clientY, A = t.getBoundingClientRect(), {
              left: j,
              top: F
            } = A;
            s?.(C - j, E - F);
          }
          o();
        }, k = (y) => {
          c.delete(y.pointerId), y.relatedTarget && y.relatedTarget !== document.documentElement || W(y);
        }, R = (y) => {
          b && (y.stopPropagation(), y.preventDefault());
        }, S = (y) => {
          y.defaultPrevented || c.size > 1 || b && y.preventDefault();
        };
        document.addEventListener("pointermove", D), document.addEventListener("pointerup", W), document.addEventListener("pointerout", k), document.addEventListener("pointercancel", k), document.addEventListener("touchmove", S, {
          passive: !1
        }), document.addEventListener("click", R, {
          capture: !0
        }), o = () => {
          document.removeEventListener("pointermove", D), document.removeEventListener("pointerup", W), document.removeEventListener("pointerout", k), document.removeEventListener("pointercancel", k), document.removeEventListener("touchmove", S), setTimeout(() => {
            document.removeEventListener("click", R, {
              capture: !0
            });
          }, 10);
        };
      };
      return t.addEventListener("pointerdown", m), () => {
        o(), t.removeEventListener("pointerdown", m), c.clear();
      };
    })(this.wrapper, (t, e, i) => {
      const s = this.wrapper.getBoundingClientRect().width;
      this.emit("drag", ot(i / s));
    }, (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 s = () => {
      e && (clearTimeout(e), e = void 0), i && (i(), i = void 0);
    };
    return this.timeouts.push(s), () => new Promise((n, d) => {
      s(), i = d, e = setTimeout(() => {
        e = void 0, i = void 0, n();
      }, t);
    });
  }
  getHeight(t, e) {
    var i;
    const s = ((i = this.audioData) === null || i === void 0 ? void 0 : i.numberOfChannels) || 1;
    return (function({
      optionsHeight: n,
      optionsSplitChannels: d,
      parentHeight: l,
      numberOfChannels: c,
      defaultHeight: a = 128
    }) {
      if (n == null) return a;
      const o = Number(n);
      if (!isNaN(o)) return o;
      if (n === "auto") {
        const m = l || a;
        return d?.every((f) => !f.overlay) ? m / c : m;
      }
      return a;
    })({
      optionsHeight: t,
      optionsSplitChannels: e,
      parentHeight: this.parent.clientHeight,
      numberOfChannels: s,
      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 s = document.createElement("canvas"), n = s.getContext("2d"), d = s.height * i, l = n.createLinearGradient(0, 0, 0, d || i), c = 1 / (e.length - 1);
      return e.forEach((a, o) => {
        l.addColorStop(o * c, a);
      }), l;
    })(t, this.getPixelRatio());
  }
  getPixelRatio() {
    return t = window.devicePixelRatio, Math.max(1, t || 1);
    var t;
  }
  renderBarWaveform(t, e, i, s) {
    const {
      width: n,
      height: d
    } = i.canvas, {
      halfHeight: l,
      barWidth: c,
      barRadius: a,
      barIndexScale: o,
      barSpacing: m
    } = (function({
      width: u,
      height: p,
      length: b,
      options: g,
      pixelRatio: D
    }) {
      const W = p / 2, k = g.barWidth ? g.barWidth * D : 1, R = g.barGap ? g.barGap * D : g.barWidth ? k / 2 : 0, S = k + R || 1;
      return {
        halfHeight: W,
        barWidth: k,
        barGap: R,
        barRadius: g.barRadius || 0,
        barIndexScale: b > 0 ? u / S / b : 0,
        barSpacing: S
      };
    })({
      width: n,
      height: d,
      length: (t[0] || []).length,
      options: e,
      pixelRatio: this.getPixelRatio()
    }), f = (function({
      channelData: u,
      barIndexScale: p,
      barSpacing: b,
      barWidth: g,
      halfHeight: D,
      vScale: W,
      canvasHeight: k,
      barAlign: R
    }) {
      const S = u[0] || [], y = u[1] || S, C = S.length, E = [];
      let A = 0, j = 0, F = 0;
      for (let L = 0; L <= C; L++) {
        const N = Math.round(L * p);
        if (N > A) {
          const {
            topHeight: U,
            totalHeight: z
          } = Re({
            maxTop: j,
            maxBottom: F,
            halfHeight: D,
            vScale: W
          }), B = Se({
            barAlign: R,
            halfHeight: D,
            topHeight: U,
            totalHeight: z,
            canvasHeight: k
          });
          E.push({
            x: A * b,
            y: B,
            width: g,
            height: z
          }), A = N, j = 0, F = 0;
        }
        const O = Math.abs(S[L] || 0), G = Math.abs(y[L] || 0);
        O > j && (j = O), G > F && (F = G);
      }
      return E;
    })({
      channelData: t,
      barIndexScale: o,
      barSpacing: m,
      barWidth: c,
      halfHeight: l,
      vScale: s,
      canvasHeight: d,
      barAlign: e.barAlign
    });
    i.beginPath();
    for (const u of f) a && "roundRect" in i ? i.roundRect(u.x, u.y, u.width, u.height, a) : i.rect(u.x, u.y, u.width, u.height);
    i.fill(), i.closePath();
  }
  renderLineWaveform(t, e, i, s) {
    const {
      width: n,
      height: d
    } = i.canvas, l = (function({
      channelData: c,
      width: a,
      height: o,
      vScale: m
    }) {
      const f = o / 2, u = c[0] || [];
      return [u, c[1] || u].map((p, b) => {
        const g = p.length, D = g ? a / g : 0, W = f, k = b === 0 ? -1 : 1, R = [{
          x: 0,
          y: W
        }];
        let S = 0, y = 0;
        for (let C = 0; C <= g; C++) {
          const E = Math.round(C * D);
          if (E > S) {
            const j = W + (Math.round(y * f * m) || 1) * k;
            R.push({
              x: S,
              y: j
            }), S = E, y = 0;
          }
          const A = Math.abs(p[C] || 0);
          A > y && (y = A);
        }
        return R.push({
          x: S,
          y: W
        }), R;
      });
    })({
      channelData: t,
      width: n,
      height: d,
      vScale: s
    });
    i.beginPath();
    for (const c of l) if (c.length) {
      i.moveTo(c[0].x, c[0].y);
      for (let a = 1; a < c.length; a++) {
        const o = c[a];
        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 s = (function({
      channelData: n,
      barHeight: d,
      normalize: l
    }) {
      var c;
      const a = d || 1;
      if (!l) return a;
      const o = n[0];
      if (!o || o.length === 0) return a;
      let m = 0;
      for (let f = 0; f < o.length; f++) {
        const u = (c = o[f]) !== null && c !== void 0 ? c : 0, p = Math.abs(u);
        p > m && (m = p);
      }
      return m ? a / m : a;
    })({
      channelData: t,
      barHeight: e.barHeight,
      normalize: e.normalize
    });
    Ut(e) ? this.renderBarWaveform(t, e, i, s) : this.renderLineWaveform(t, e, i, s);
  }
  renderSingleCanvas(t, e, i, s, n, d, l) {
    const c = this.getPixelRatio(), a = document.createElement("canvas");
    a.width = Math.round(i * c), a.height = Math.round(s * c), a.style.width = `${i}px`, a.style.height = `${s}px`, a.style.left = `${Math.round(n)}px`, d.appendChild(a);
    const o = a.getContext("2d");
    if (e.renderFunction ? (o.fillStyle = this.convertColorValues(e.waveColor), e.renderFunction(t, o)) : this.renderWaveform(t, e, o), a.width > 0 && a.height > 0) {
      const m = a.cloneNode(), f = m.getContext("2d");
      f.drawImage(a, 0, 0), f.globalCompositeOperation = "source-in", f.fillStyle = this.convertColorValues(e.progressColor), f.fillRect(0, 0, a.width, a.height), l.appendChild(m);
    }
  }
  renderMultiCanvas(t, e, i, s, n, d) {
    const l = this.getPixelRatio(), {
      clientWidth: c
    } = this.scrollContainer, a = i / l, o = (function({
      clientWidth: p,
      totalWidth: b,
      options: g
    }) {
      return Wt(Math.min(8e3, p, b), g);
    })({
      clientWidth: c,
      totalWidth: a,
      options: e
    });
    let m = {};
    if (o === 0) return;
    const f = (p) => {
      if (p < 0 || p >= u || m[p]) return;
      m[p] = !0;
      const b = p * o;
      let g = Math.min(a - b, o);
      if (g = Wt(g, e), g <= 0) return;
      const D = (function({
        channelData: W,
        offset: k,
        clampedWidth: R,
        totalWidth: S
      }) {
        return W.map((y) => {
          const C = Math.floor(k / S * y.length), E = Math.floor((k + R) / S * y.length);
          return y.slice(C, E);
        });
      })({
        channelData: t,
        offset: b,
        clampedWidth: g,
        totalWidth: a
      });
      this.renderSingleCanvas(D, e, g, s, b, n, d);
    }, u = Math.ceil(a / o);
    if (!this.isScrollable) {
      for (let p = 0; p < u; p++) f(p);
      return;
    }
    if (kt({
      scrollLeft: this.scrollContainer.scrollLeft,
      totalWidth: a,
      numCanvases: u
    }).forEach((p) => f(p)), u > 1) {
      const p = this.on("scroll", () => {
        const {
          scrollLeft: b
        } = this.scrollContainer;
        Object.keys(m).length > 10 && (n.innerHTML = "", d.innerHTML = "", m = {}), kt({
          scrollLeft: b,
          totalWidth: a,
          numCanvases: u
        }).forEach((g) => f(g));
      });
      this.unsubscribeOnScroll.push(p);
    }
  }
  renderChannel(t, e, i, s) {
    var {
      overlay: n
    } = e, d = (function(o, m) {
      var f = {};
      for (var u in o) Object.prototype.hasOwnProperty.call(o, u) && m.indexOf(u) < 0 && (f[u] = o[u]);
      if (o != null && typeof Object.getOwnPropertySymbols == "function") {
        var p = 0;
        for (u = Object.getOwnPropertySymbols(o); p < u.length; p++) m.indexOf(u[p]) < 0 && Object.prototype.propertyIsEnumerable.call(o, u[p]) && (f[u[p]] = o[u[p]]);
      }
      return f;
    })(e, ["overlay"]);
    const l = document.createElement("div"), c = this.getHeight(d.height, d.splitChannels);
    l.style.height = `${c}px`, n && s > 0 && (l.style.marginTop = `-${c}px`), this.canvasWrapper.style.minHeight = `${c}px`, this.canvasWrapper.appendChild(l);
    const a = l.cloneNode();
    this.progressWrapper.appendChild(a), this.renderMultiCanvas(t, d, i, c, l, a);
  }
  render(t) {
    return T(this, void 0, void 0, function* () {
      var e;
      this.timeouts.forEach((a) => a()), 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(), s = this.scrollContainer.clientWidth, {
        scrollWidth: n,
        isScrollable: d,
        useParentWidth: l,
        width: c
      } = (function({
        duration: a,
        minPxPerSec: o = 0,
        parentWidth: m,
        fillParent: f,
        pixelRatio: u
      }) {
        const p = Math.ceil(a * o), b = p > m, g = !!(f && !b);
        return {
          scrollWidth: p,
          isScrollable: b,
          useParentWidth: g,
          width: (g ? m : p) * u
        };
      })({
        duration: t.duration,
        minPxPerSec: this.options.minPxPerSec || 0,
        parentWidth: s,
        fillParent: this.options.fillParent,
        pixelRatio: i
      });
      if (this.isScrollable = d, this.wrapper.style.width = l ? "100%" : `${n}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 a = 0; a < t.numberOfChannels; a++) {
        const o = Object.assign(Object.assign({}, this.options), (e = this.options.splitChannels) === null || e === void 0 ? void 0 : e[a]);
        this.renderChannel([t.getChannelData(a)], o, c, a);
      }
      else {
        const a = [t.getChannelData(0)];
        t.numberOfChannels > 1 && a.push(t.getChannelData(1)), this.renderChannel(a, this.options, c, 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(), s = (function(n) {
        const d = 2 * n;
        return (d < 0 ? Math.floor(d) : Math.ceil(d)) / 2;
      })(i - e);
      this.scrollContainer.scrollLeft += s;
    }
  }
  zoom(t) {
    this.options.minPxPerSec = t, this.reRender();
  }
  scrollIntoView(t, e = !1) {
    const {
      scrollLeft: i,
      scrollWidth: s,
      clientWidth: n
    } = this.scrollContainer, d = t * s, l = i, c = i + n, a = n / 2;
    if (this.isDragging) d + 30 > c ? this.scrollContainer.scrollLeft += 30 : d - 30 < l && (this.scrollContainer.scrollLeft -= 30);
    else {
      (d < l || d > c) && (this.scrollContainer.scrollLeft = d - (this.options.autoCenter ? a : 0));
      const o = d - i - a;
      e && this.options.autoCenter && o > 0 && (this.scrollContainer.scrollLeft += o);
    }
    {
      const o = this.scrollContainer.scrollLeft, {
        startX: m,
        endX: f
      } = Dt({
        scrollLeft: o,
        scrollWidth: s,
        clientWidth: n
      });
      this.emit("scroll", m, f, o, o + n);
    }
  }
  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 T(this, void 0, void 0, function* () {
      const s = this.canvasWrapper.querySelectorAll("canvas");
      if (!s.length) throw new Error("No waveform data");
      if (i === "dataURL") {
        const n = Array.from(s).map((d) => d.toDataURL(t, e));
        return Promise.resolve(n);
      }
      return Promise.all(Array.from(s).map((n) => new Promise((d, l) => {
        n.toBlob((c) => {
          c ? d(c) : l(new Error("Could not export image"));
        }, t, e);
      })));
    });
  }
}
class Pe extends J {
  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 J {
  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 T(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 T(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 T(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 X extends xe {
  static create(t) {
    return new X(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 s = this.options.url || this.getSrc() || "";
    Promise.resolve().then(() => {
      this.emit("init");
      const {
        peaks: n,
        duration: d
      } = this.options;
      (s || n && d) && this.load(s, n, d).catch((l) => {
        this.emit("error", l instanceof Error ? l : new Error(String(l)));
      });
    });
  }
  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, s) => {
      const n = this.getDuration();
      this.emit("scroll", t * n, e * n, i, s);
    }), 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 s;
        if (!this.options.interact) return;
        this.renderer.renderProgress(i), clearTimeout(t);
        let n = 0;
        const d = this.options.dragToSeek;
        this.isPlaying() ? n = 0 : d === !0 ? n = 200 : d && typeof d == "object" && (n = (s = d.debounceTime) !== null && s !== void 0 ? s : 200), t = setTimeout(() => {
          this.seekTo(i);
        }, n), 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, s) {
    return T(this, void 0, void 0, function* () {
      var n;
      if (this.emit("load", t), !this.options.media && this.isPlaying() && this.pause(), this.decodedData = null, this.stopAtPosition = null, (n = this.abortController) === null || n === void 0 || n.abort(), this.abortController = null, !e && !i) {
        const l = this.options.fetchParams || {};
        window.AbortController && !l.signal && (this.abortController = new AbortController(), l.signal = this.abortController.signal);
        const c = (o) => this.emit("loading", o);
        e = yield Ce.fetchBlob(t, c, l);
        const a = this.options.blobMimeType;
        a && (e = new Blob([e], {
          type: a
        }));
      }
      this.setSrc(t, e);
      const d = yield new Promise((l) => {
        const c = s || this.getDuration();
        c ? l(c) : this.mediaSubscriptions.push(this.onMediaEvent("loadedmetadata", () => l(this.getDuration()), {
          once: !0
        }));
      });
      if (!t && !e) {
        const l = this.getMediaElement();
        l instanceof at && (l.duration = d);
      }
      if (i) this.decodedData = tt.createBuffer(i, d || 0);
      else if (e) {
        const l = yield e.arrayBuffer();
        this.decodedData = yield tt.decode(l, 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 T(this, void 0, void 0, function* () {
      try {
        return yield this.loadAudio(t, void 0, e, i);
      } catch (s) {
        throw this.emit("error", s), s;
      }
    });
  }
  loadBlob(t, e, i) {
    return T(this, void 0, void 0, function* () {
      try {
        return yield this.loadAudio("", t, e, i);
      } catch (s) {
        throw this.emit("error", s), s;
      }
    });
  }
  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 s = Math.min(t, this.decodedData.numberOfChannels), n = [];
    for (let d = 0; d < s; d++) {
      const l = this.decodedData.getChannelData(d), c = [], a = l.length / e;
      for (let o = 0; o < e; o++) {
        const m = l.slice(Math.floor(o * a), Math.ceil((o + 1) * a));
        let f = 0;
        for (let u = 0; u < m.length; u++) {
          const p = m[u];
          Math.abs(p) > Math.abs(f) && (f = p);
        }
        c.push(Math.round(f * i) / i);
      }
      n.push(c);
    }
    return n;
  }
  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 T(this, void 0, void 0, function* () {
      t != null && this.setTime(t);
      const s = yield i.play.call(this);
      return e != null && (this.media instanceof at ? this.media.stopAt(e) : this.stopAtPosition = e), s;
    });
  }
  playPause() {
    return T(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 T(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();
  }
}
X.BasePlugin = class extends J {
  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;
  }
}, X.dom = we;
function lt(r, t, e, i) {
  return new (e || (e = Promise))(function(s, n) {
    function d(a) {
      try {
        c(i.next(a));
      } catch (o) {
        n(o);
      }
    }
    function l(a) {
      try {
        c(i.throw(a));
      } catch (o) {
        n(o);
      }
    }
    function c(a) {
      var o;
      a.done ? s(a.value) : (o = a.value, o instanceof e ? o : new e(function(m) {
        m(o);
      })).then(d, l);
    }
    c((i = i.apply(r, [])).next());
  });
}
class Bt {
  constructor() {
    this.listeners = {};
  }
  on(t, e, i) {
    if (this.listeners[t] || (this.listeners[t] = /* @__PURE__ */ new Set()), i?.once) {
      const s = (...n) => {
        this.un(t, s), e(...n);
      };
      return this.listeners[t].add(s), () => this.un(t, s);
    }
    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 ke extends Bt {
  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 De extends Bt {
  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 Me = ["audio/webm", "audio/wav", "audio/mpeg", "audio/mp4", "audio/mp3"];
class pt extends ke {
  constructor(t) {
    var e, i, s, n, d, l;
    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: (s = t.scrollingWaveformWindow) !== null && s !== void 0 ? s : 5,
      continuousWaveform: (n = t.continuousWaveform) !== null && n !== void 0 && n,
      renderRecordedAudio: (d = t.renderRecordedAudio) === null || d === void 0 || d,
      mediaRecorderTimeslice: (l = t.mediaRecorderTimeslice) !== null && l !== void 0 ? l : 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 De(), this.subscriptions.push(this.timer.on("tick", () => {
      const c = performance.now() - this.lastStartTime;
      this.duration = this.isPaused() ? this.duration : this.lastDuration + c, this.emit("record-progress", this.duration);
    }));
  }
  static create(t) {
    return new pt(t || {});
  }
  renderMicStream(t) {
    var e;
    const i = new AudioContext(), s = i.createMediaStreamSource(t), n = i.createAnalyser();
    s.connect(n), this.options.continuousWaveform && (n.fftSize = 32);
    const d = n.frequencyBinCount, l = new Float32Array(d);
    let c = 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 a = setInterval(() => {
      var o, m, f, u;
      if (!this.isWaveformPaused) {
        if (n.getFloatTimeDomainData(l), this.options.scrollingWaveform) {
          const p = Math.floor((this.options.scrollingWaveformWindow || 0) * i.sampleRate), b = Math.min(p, this.dataWindow ? this.dataWindow.length + d : d), g = new Float32Array(p);
          if (this.dataWindow) {
            const D = Math.max(0, p - this.dataWindow.length);
            g.set(this.dataWindow.slice(-b + d), D);
          }
          g.set(l, p - d), this.dataWindow = g;
        } else if (this.options.continuousWaveform) {
          if (!this.dataWindow) {
            const b = this.options.continuousWaveformDuration ? Math.round(100 * this.options.continuousWaveformDuration) : ((m = (o = this.wavesurfer) === null || o === void 0 ? void 0 : o.getWidth()) !== null && m !== void 0 ? m : 0) * window.devicePixelRatio;
            this.dataWindow = new Float32Array(b);
          }
          let p = 0;
          for (let b = 0; b < d; b++) {
            const g = Math.abs(l[b]);
            g > p && (p = g);
          }
          if (c + 1 > this.dataWindow.length) {
            const b = new Float32Array(2 * this.dataWindow.length);
            b.set(this.dataWindow, 0), this.dataWindow = b;
          }
          this.dataWindow[c] = p, c++;
        } else this.dataWindow = l;
        if (this.wavesurfer) {
          const p = ((u = (f = this.dataWindow) === null || f === void 0 ? void 0 : f.length) !== null && u !== void 0 ? u : 0) / 100;
          this.wavesurfer.load("", [this.dataWindow], this.options.scrollingWaveform ? this.options.scrollingWaveformWindow : p).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(a), s?.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 (s) {
        throw new Error("Error accessing the microphone: " + s.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((s) => s.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 || Me.find((d) => MediaRecorder.isTypeSupported(d)),
        audioBitsPerSecond: this.options.audioBitsPerSecond
      });
      this.mediaRecorder = i, this.stopRecording();
      const s = [];
      i.ondataavailable = (d) => {
        d.data.size > 0 && s.push(d.data), this.emit("record-data-available", d.data);
      };
      const n = (d) => {
        var l;
        const c = new Blob(s, {
          type: i.mimeType
        });
        this.emit(d, c), this.options.renderRecordedAudio && (this.applyOriginalOptionsIfNeeded(), this.recordedBlobUrl && URL.revokeObjectURL(this.recordedBlobUrl), this.recordedBlobUrl = URL.createObjectURL(c), (l = this.wavesurfer) === null || l === void 0 || l.load(this.recordedBlobUrl));
      };
      i.onpause = () => n("record-pause"), i.onstop = () => n("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 Te = (r, t) => {
  const {
    libConfig: {
      enforceDownloadInNewTab: e = !1
      // Default to false, if no libConfig, e.g. for tests
    }
  } = h.useContext(ae);
  return h.useCallback(() => {
    if (!r) return;
    const i = ge({
      enforceDownloadInNewTab: e,
      url: r,
      filename: t
    });
    i.style.display = "none", document.body.appendChild(i), i.click(), document.body.removeChild(i);
  }, [r, e, t]);
}, dt = ({
  widgetMgr: r,
  id: t,
  formId: e,
  key: i,
  defaultValue: s
}) => {
  h.useEffect(() => {
    const o = r.getElementState(t, i);
    ut(o) && _(s) && r.setElementState(t, i, s);
  }, [r, t, i, s]);
  const [n, d] = h.useState(r.getElementState(t, i) ?? s), l = h.useCallback((o) => {
    r.setElementState(t, i, o), d(o);
  }, [r, t, i]), c = h.useMemo(() => ({
    formId: e || ""
  }), [e]), a = h.useCallback(() => l(s), [s, l]);
  return fe({
    element: c,
    widgetMgr: r,
    onFormCleared: a
  }), [n, l];
}, Ie = async ({
  files: r,
  uploadClient: t,
  widgetMgr: e,
  widgetInfo: i,
  fragmentId: s
}) => {
  let n = [];
  try {
    n = await t.fetchFileURLs(r);
  } catch (a) {
    return {
      successfulUploads: [],
      failedUploads: r.map((o) => ({
        file: o,
        error: Rt(a)
      }))
    };
  }
  const d = se(r, n), l = [], c = [];
  return await Promise.all(d.map(async ([a, o]) => {
    if (!a || !o?.uploadUrl || !o.fileId) return {
      file: a,
      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,
        a
      ), l.push({
        fileUrl: o,
        file: a
      });
    } catch (m) {
      const f = Rt(m);
      c.push({
        file: a,
        error: f
      });
    }
  })), e.setFileUploaderStateValue(i, new ne({
    uploadedFileInfo: l.map(({
      file: a,
      fileUrl: o
    }) => new oe({
      fileId: o.fileId,
      fileUrls: o,
      name: a.webkitRelativePath || a.name,
      size: a.size
    }))
  }), {
    fromUi: !0
  }, s), {
    successfulUploads: l,
    failedUploads: c
  };
}, Ae = /* @__PURE__ */ I("div", {
  target: "e12wn80j14"
})(""), Mt = /* @__PURE__ */ I("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"
}), ""), Le = /* @__PURE__ */ I("div", {
  target: "e12wn80j12"
})({
  name: "82a6rk",
  styles: "flex:1"
}), Oe = /* @__PURE__ */ I("div", {
  target: "e12wn80j11"
})(({
  show: r
}) => ({
  display: r ? "block" : "none"
}), ""), je = /* @__PURE__ */ I("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__ */ I("div", {
  target: "e12wn80j9"
})({
  name: "1kyw74z",
  styles: "width:100%;text-align:center;overflow:hidden"
}), Nt = /* @__PURE__ */ I("span", {
  target: "e12wn80j8"
})(({
  theme: r
}) => ({
  color: r.colors.bodyText
}), ""), Ue = /* @__PURE__ */ I("a", {
  target: "e12wn80j7"
})(({
  theme: r
}) => ({
  color: r.colors.link,
  textDecoration: r.linkUnderline ? "underline" : "none"
}), ""), Be = /* @__PURE__ */ I("div", {
  target: "e12wn80j6"
})(({
  theme: r
}) => ({
  height: r.sizes.largestElementHeight,
  display: "flex",
  justifyContent: "center",
  alignItems: "center"
}), ""), Fe = /* @__PURE__ */ I("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__ */ I("span", {
  target: "e12wn80j4"
})(({
  theme: r
}) => ({
  "& > button": {
    color: r.colors.primary,
    padding: r.spacing.threeXS
  },
  "& > button:hover, & > button:focus": {
    color: r.colors.redColor
  }
}), ""), ze = /* @__PURE__ */ I("span", {
  target: "e12wn80j3"
})(({
  theme: r
}) => ({
  "& > button": {
    padding: r.spacing.threeXS,
    color: r.colors.fadedText60
  },
  "& > button:hover, & > button:focus": {
    color: r.colors.bodyText
  }
}), ""), zt = /* @__PURE__ */ I("span", {
  target: "e12wn80j2"
})(({
  theme: r
}) => ({
  "& > button": {
    padding: r.spacing.threeXS,
    color: r.colors.fadedText60
  },
  "& > button:hover, & > button:focus": {
    color: r.colors.bodyText
  }
}), ""), ct = /* @__PURE__ */ I("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
}), ""), He = /* @__PURE__ */ I("div", {
  target: "e12wn80j0"
})(({
  theme: r
}) => ({
  marginLeft: r.spacing.sm
}), ""), q = ({
  onClick: r,
  disabled: t,
  ariaLabel: e,
  iconContent: i
}) => /* @__PURE__ */ v.jsx(ce, {
  kind: he.BORDERLESS_ICON,
  onClick: r,
  disabled: t,
  "aria-label": e,
  containerWidth: !0,
  "data-testid": "stAudioInputActionButton",
  children: /* @__PURE__ */ v.jsx(ue, {
    content: i,
    size: "lg",
    color: "inherit"
  })
}), Ve = ({
  disabled: r,
  stopRecording: t
}) => /* @__PURE__ */ v.jsx(Ne, {
  children: /* @__PURE__ */ v.jsx(q, {
    onClick: t,
    disabled: r,
    ariaLabel: "Stop recording",
    iconContent: Ot
  })
}), _e = ({
  disabled: r,
  isPlaying: t,
  onClickPlayPause: e
}) => /* @__PURE__ */ v.jsx(zt, {
  children: t ? /* @__PURE__ */ v.jsx(q, {
    onClick: e,
    disabled: r,
    ariaLabel: "Pause",
    iconContent: It
  }) : /* @__PURE__ */ v.jsx(q, {
    onClick: e,
    disabled: r,
    ariaLabel: "Play",
    iconContent: At
  })
}), $e = ({
  disabled: r,
  startRecording: t
}) => /* @__PURE__ */ v.jsx(ze, {
  children: /* @__PURE__ */ v.jsx(q, {
    onClick: t,
    disabled: r,
    ariaLabel: "Record",
    iconContent: Tt
  })
}), Ge = ({
  onClick: r
}) => /* @__PURE__ */ v.jsx(zt, {
  children: /* @__PURE__ */ v.jsx(q, {
    disabled: !1,
    onClick: r,
    ariaLabel: "Reset",
    iconContent: Lt
  })
}), Xe = ({
  disabled: r,
  isRecording: t,
  isPlaying: e,
  isUploading: i,
  isError: s,
  recordingUrlExists: n,
  startRecording: d,
  stopRecording: l,
  onClickPlayPause: c,
  onClear: a
}) => s ? /* @__PURE__ */ v.jsx(ct, {
  children: /* @__PURE__ */ v.jsx(Ge, {
    onClick: a
  })
}) : i ? /* @__PURE__ */ v.jsx(ct, {
  children: /* @__PURE__ */ v.jsx(le, {
    "aria-label": "Uploading",
    size: "base",
    margin: "0",
    padding: "0"
  })
}) : /* @__PURE__ */ v.jsxs(ct, {
  children: [t ? /* @__PURE__ */ v.jsx(Ve, {
    disabled: r,
    stopRecording: l
  }) : /* @__PURE__ */ v.jsx($e, {
    disabled: r,
    startRecording: d
  }), n && /* @__PURE__ */ v.jsx(_e, {
    disabled: r,
    isPlaying: e,
    onClickPlayPause: c
  })]
}), qe = h.memo(Xe), Ye = () => /* @__PURE__ */ v.jsx(Ft, {
  children: /* @__PURE__ */ v.jsx(Nt, {
    children: "An error has occurred, please try again."
  })
}), Ze = h.memo(Ye), Je = 4, Ke = 4, Qe = 4, ti = 8, ei = 0, et = "00:00", V = re.getLogger("convertAudioToWav");
async function ii(r, t) {
  if (!r || r.size === 0) {
    V.error("Invalid or empty blob provided");
    return;
  }
  if (!window.AudioContext) {
    V.error("AudioContext not supported in this browser");
    return;
  }
  const e = new AudioContext();
  let i;
  try {
    i = await r.arrayBuffer();
  } catch (m) {
    V.error("Failed to read blob as ArrayBuffer", m), e.close();
    return;
  }
  let s;
  try {
    s = await e.decodeAudioData(i);
  } catch (m) {
    V.error("Failed to decode audio data", m), e.close();
    return;
  } finally {
    e.close();
  }
  const n = t || s.sampleRate;
  if (n === s.sampleRate) return V.debug(`No resampling needed, sample rate is already ${n}Hz`), it(s, n);
  V.debug(`Resampling from ${s.sampleRate}Hz to ${n}Hz`);
  const {
    duration: d,
    numberOfChannels: l
  } = s, c = Math.ceil(d * n);
  if (!window.OfflineAudioContext) return V.error("OfflineAudioContext not supported, falling back to no resampling"), it(s, s.sampleRate);
  const a = new OfflineAudioContext(l, c, n), o = a.createBufferSource();
  o.buffer = s, o.connect(a.destination), o.start(0);
  try {
    const m = await a.startRendering();
    return it(m, n);
  } catch (m) {
    return V.error("Failed to resample audio using OfflineAudioContext", m), it(s, s.sampleRate);
  }
}
function it(r, t) {
  const e = r.numberOfChannels, i = r.length * e * 2 + 44, s = new ArrayBuffer(i), n = new DataView(s), d = (c, a) => {
    for (let o = 0; o < a.length; o++) n.setUint8(c + o, a.charCodeAt(o));
  };
  d(0, "RIFF"), n.setUint32(4, i - 8, !0), d(8, "WAVE"), d(12, "fmt "), n.setUint32(16, 16, !0), n.setUint16(20, 1, !0), n.setUint16(22, e, !0), n.setUint32(24, t, !0), n.setUint32(28, t * e * 2, !0), n.setUint16(32, e * 2, !0), n.setUint16(34, 16, !0), d(36, "data"), n.setUint32(40, i - 44, !0);
  let l = 44;
  for (let c = 0; c < r.length; c++) for (let a = 0; a < e; a++) {
    const o = Math.max(-1, Math.min(1, r.getChannelData(a)[c]));
    n.setInt16(l, o * 32767, !0), l += 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), s = t % 60, n = e % 60, d = s.toString().padStart(2, "0"), l = n.toString().padStart(2, "0"), c = i.toString().padStart(2, "0");
  return e < 60 ? `${l}:${d}` : `${c}:${l}:${d}`;
}, ri = () => /* @__PURE__ */ v.jsxs(Ft, {
  children: [/* @__PURE__ */ v.jsx(Nt, {
    children: "This app would like to use your microphone."
  }), " ", /* @__PURE__ */ v.jsx(Ue, {
    href: de,
    rel: "noopener noreferrer",
    target: "_blank",
    children: "Learn how to allow access."
  })]
}), si = h.memo(ri), ni = () => /* @__PURE__ */ v.jsx(Be, {
  children: /* @__PURE__ */ v.jsx(Fe, {})
}), oi = h.memo(ni), ai = ({
  element: r,
  uploadClient: t,
  widgetMgr: e,
  fragmentId: i,
  disabled: s
}) => {
  const n = Zt(), d = ve(n), [l, c] = h.useState(null), a = h.useRef(null), o = h.useRef(null), [m, f] = dt({
    widgetMgr: e,
    id: r.id,
    key: "deleteFileUrl",
    defaultValue: null
  }), [u, p] = dt({
    widgetMgr: e,
    id: r.id,
    key: "recordingUrl",
    defaultValue: null
  }), [, b] = h.useState(0), g = h.useCallback(() => {
    b((w) => w + 1);
  }, []), [D, W] = h.useState(et), [k, R] = dt({
    widgetMgr: e,
    id: r.id,
    formId: r.formId,
    key: "recordingTime",
    defaultValue: et
  }), [S, y] = h.useState(!1), [C, E] = h.useState(!1), [A, j] = h.useState(!1), [F, L] = h.useState(!1), [N, O] = h.useState(!1), G = r.id, U = r.formId, z = r.sampleRate || null, B = h.useRef(null), rt = h.useRef({}), mt = h.useCallback(async (w) => {
    try {
      L(!0), _(U) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set([U]));
      let x;
      if (w.type === "audio/wav" ? x = w : x = await ii(w, z || void 0), !x) {
        O(!0), L(!1), _(U) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set());
        return;
      }
      let M;
      try {
        M = URL.createObjectURL(x), o.current && o.current !== M && URL.revokeObjectURL(o.current), o.current = M;
      } catch {
        O(!0), L(!1), _(U) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set());
        return;
      }
      p(M), l && (l.load(M), l.setOptions({
        interact: !0,
        waveColor: Q(n.colors.fadedText40, n.colors.secondaryBg),
        progressColor: n.colors.bodyText
      }));
      const $ = (/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/:/g, "-"), P = new File([x], `${$}_audio.wav`, {
        type: x.type
      });
      try {
        const {
          successfulUploads: K,
          failedUploads: nt
        } = await Ie({
          files: [P],
          uploadClient: t,
          widgetMgr: e,
          widgetInfo: {
            id: G,
            formId: U
          },
          fragmentId: i
        });
        if (nt.length > 0) {
          O(!0);
          return;
        }
        O(!1);
        const xt = K[0];
        xt?.fileUrl?.deleteUrl && f(xt.fileUrl.deleteUrl);
      } catch {
        O(!0);
      } finally {
        _(U) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set()), L(!1);
      }
    } catch {
      O(!0), L(!1), _(U) && e.setFormsWithUploadsInProgress(/* @__PURE__ */ new Set());
    }
  }, [t, e, l, G, U, i, f, z, p, n.colors.fadedText40, n.colors.secondaryBg, n.colors.bodyText]), H = h.useCallback(async ({
    updateWidgetManager: w,
    deleteFile: x
  }) => {
    if (ut(l)) return;
    const M = u;
    if (M && o.current === M && (URL.revokeObjectURL(M), o.current = null), p(null), f(null), W(et), R(et), y(!1), l.empty(), w && e.setFileUploaderStateValue(r, {}, {
      fromUi: !0
    }, i), x && m) try {
      await t.deleteFile(m);
    } catch {
    }
    _(M) && URL.revokeObjectURL(M);
  }, [m, u, t, l, r, e, i, R, f, p]);
  h.useEffect(() => {
    if (ut(U)) return;
    const w = new me();
    return w.manageFormClearListener(e, U, () => {
      H({
        updateWidgetManager: !0,
        deleteFile: !1
      });
    }), () => w.disconnect();
  }, [U, H, e]);
  const ft = h.useCallback(() => {
    if (a.current === null) return;
    const w = X.create({
      container: a.current,
      waveColor: u ? Q(n.colors.fadedText40, n.colors.secondaryBg) : n.colors.primary,
      progressColor: n.colors.bodyText,
      height: Jt(n.sizes.largestElementHeight) - 2 * Je,
      barWidth: Ke,
      barGap: Qe,
      barRadius: ti,
      cursorWidth: ei,
      interact: !0
    }), x = (P) => {
      W(ht(P * 1e3));
    }, M = () => {
      g();
    };
    w.on("timeupdate", x), w.on("pause", M), c(w), u && (w.load(u), w.setOptions({
      interact: !0
    }));
    const $ = {
      renderRecordedAudio: !1,
      scrollingWaveform: !1,
      mimeType: "audio/webm"
    };
    try {
      const P = w.registerPlugin(pt.create($));
      B.current = P;
      const K = (nt) => {
        R(ht(nt));
      };
      P.on("record-progress", K), rt.current = {
        handleRecordProgress: K
      };
    } catch (P) {
      P instanceof Error && (P.name === "NotAllowedError" || P.name === "PermissionDeniedError") && E(!0);
    }
    return () => {
      if (B.current) {
        B.current.isRecording() && B.current.stopRecording();
        const P = rt.current;
        P.handleRecordProgress && B.current.un("record-progress", P.handleRecordProgress), B.current.destroy(), B.current = null, rt.current = {};
      }
      w && (w.un("timeupdate", x), w.un("pause", M), w.destroy());
    };
  }, [n, W, g, u, R, E]);
  h.useEffect(() => ft(), [ft]), h.useEffect(() => {
    Kt(d, n) || l?.setOptions({
      waveColor: u ? Q(n.colors.fadedText40, n.colors.secondaryBg) : n.colors.primary,
      progressColor: n.colors.bodyText,
      interact: !0
    });
  }, [n, d, u, l]);
  const Ht = h.useCallback(() => {
    l && (async () => {
      try {
        await l.playPause();
      } catch {
        O(!0);
      }
      y(!0), g();
    })();
  }, [l, g]), gt = h.useCallback(async () => {
    if (!A) {
      j(!0);
      let w = null;
      try {
        w = await navigator.mediaDevices.getUserMedia({
          audio: !0
        });
      } catch {
        E(!0);
        return;
      } finally {
        w && w.getTracks().forEach((x) => x.stop());
      }
    }
    if (u && await H({
      updateWidgetManager: !1,
      deleteFile: !0
    }), B.current && l) {
      l.setOptions({
        waveColor: n.colors.primary
      });
      const w = z ? {
        sampleRate: {
          ideal: z
        }
      } : {};
      try {
        await B.current.startRecording(w), R(ht(0)), g();
      } catch (x) {
        x instanceof Error && (x.name === "NotAllowedError" || x.name === "PermissionDeniedError") ? E(!0) : O(!0);
      }
    } else C || O(!0);
  }, [A, R, C, z, l, n.colors.primary, g, u, H]), vt = h.useCallback((w) => new Promise((x, M) => {
    const $ = (P) => {
      w.un("record-end", $), P && P instanceof Blob && P.size > 0 ? x(P) : M(new Error("Invalid or empty recording blob"));
    };
    w.on("record-end", $), w.stopRecording();
  }), []), bt = h.useCallback(async () => {
    const w = B.current;
    if (w?.isRecording()) try {
      const x = await vt(w);
      await mt(x), l && l.setOptions({
        waveColor: Q(n.colors.fadedText40, n.colors.secondaryBg),
        progressColor: n.colors.bodyText
      });
    } catch {
      O(!0);
    }
  }, [mt, l, n, vt]), yt = Te(u, "recording.wav"), st = B.current?.isRecording() || !1, wt = !!l?.isPlaying(), Vt = st || wt, Ct = !st && !u && !C, _t = C || Ct || N, $t = h.useCallback(() => {
    gt();
  }, [gt]), Gt = h.useCallback(() => {
    bt();
  }, [bt]), Xt = h.useCallback(() => {
    H({
      updateWidgetManager: !1,
      deleteFile: !0
    }), O(!1);
  }, [H]), qt = h.useCallback(() => {
    yt();
  }, [yt]), Yt = h.useCallback(() => {
    H({
      updateWidgetManager: !0,
      deleteFile: !0
    });
  }, [H]);
  return /* @__PURE__ */ v.jsxs(Ae, {
    className: "stAudioInput",
    "data-testid": "stAudioInput",
    children: [/* @__PURE__ */ v.jsx(Qt, {
      label: r.label,
      disabled: s,
      labelVisibility: te(r.labelVisibility?.value),
      children: r.help && /* @__PURE__ */ v.jsx(He, {
        children: /* @__PURE__ */ v.jsx(ee, {
          content: r.help,
          placement: ie.TOP
        })
      })
    }), /* @__PURE__ */ v.jsxs(Mt, {
      disabled: s,
      children: [/* @__PURE__ */ v.jsxs(pe, {
        isFullScreen: !1,
        disableFullscreenMode: !0,
        target: Mt,
        children: [u && /* @__PURE__ */ v.jsx(St, {
          label: "Download as WAV",
          icon: be,
          onClick: qt
        }), m && /* @__PURE__ */ v.jsx(St, {
          label: "Clear recording",
          icon: ye,
          onClick: Yt
        })]
      }), /* @__PURE__ */ v.jsx(qe, {
        isRecording: st,
        isPlaying: wt,
        isUploading: F,
        isError: N,
        recordingUrlExists: !!u,
        startRecording: $t,
        stopRecording: Gt,
        onClickPlayPause: Ht,
        onClear: Xt,
        disabled: s || C
      }), /* @__PURE__ */ v.jsxs(Le, {
        children: [N && /* @__PURE__ */ v.jsx(Ze, {}), Ct && /* @__PURE__ */ v.jsx(oi, {}), C && /* @__PURE__ */ v.jsx(si, {}), /* @__PURE__ */ v.jsx(Oe, {
          "data-testid": "stAudioInputWaveSurfer",
          ref: a,
          show: !_t
        })]
      }), /* @__PURE__ */ v.jsx(je, {
        isPlayingOrRecording: Vt,
        disabled: s,
        "data-testid": "stAudioInputWaveformTimeCode",
        children: S ? D : k
      })]
    })]
  });
}, mi = h.memo(ai);
export {
  mi as default
};
//# sourceMappingURL=index-CAzavyuT-CC7elPti.js.map
