import { defineComponent as Ue, ref as p, computed as l, watch as j, createElementBlock as m, openBlock as i, unref as r, normalizeStyle as ue, normalizeClass as C, createCommentVNode as c, createElementVNode as o, createVNode as k, withCtx as G, createTextVNode as Ve, toDisplayString as h, createBlock as O, withDirectives as Y, vShow as le, vModelText as Be, Transition as re, Fragment as He, nextTick as je } from "vue";
import Ge from "../../1_atoms/ContextMenu/ContextMenu.vue.js";
import Ye from "../../1_atoms/LinkPreview/LinkPreview.vue.js";
import Ze from "../../1_atoms/EmbedPreview/EmbedPreview.vue.js";
import qe from "../BaseReplyMessage/BaseReplyMessage.vue.js";
import ze from "../MessageReactions/MessageReactions.vue.js";
import We from "../MessageStatusIndicator/MessageStatusIndicator.vue.js";
import Je from "../MessageSmsInvite/MessageSmsInvite.vue.js";
import Ke from "../../1_atoms/Tooltip/Tooltip.vue.js";
import { useMessageActions as Qe } from "../../../hooks/messages/useMessageActions.js";
import { useMessageLinks as Xe } from "../../../hooks/messages/useMessageLinks.js";
import { useChannelAccentColor as et } from "../../../hooks/messages/useChannelAccentColor.js";
import { useSubtextTooltip as tt } from "../../../hooks/messages/useSubtextTooltip.js";
import { getStatus as st, getStatusTitle as at } from "../../../functions/getStatusMessage.js";
import { getMessageClass as nt } from "../../../functions/getMessageClass.js";
import { createReactionHandlers as ot } from "../../../functions/createReactionHandlers.js";
import "../../../functions/parseMarkdown.js";
const it = ["messageId"], ut = ["src"], lt = {
  key: 1,
  class: "audio-message__subtext"
}, rt = { class: "audio-message__audio-container" }, mt = ["src"], ct = { class: "audio-message__progress-wrapper" }, dt = ["max"], vt = { class: "audio-message__speed-btn-container" }, gt = { class: "audio-message__player-controls" }, ft = { class: "audio-message__current-time" }, pt = { class: "audio-message__duration" }, yt = {
  key: 1,
  class: "audio-message__text-container"
}, ht = ["innerHTML"], bt = { class: "audio-message__info-container" }, Ct = {
  key: 0,
  class: "audio-message__actions"
}, wt = { class: "audio-message__time" }, xt = {
  key: 0,
  class: "audio-message__expand-panel"
}, kt = { class: "audio-message__expand-inner" }, Tt = {
  key: 0,
  class: "audio-message__expand-placeholder"
}, Rt = ["innerHTML"], Mt = {
  key: 1,
  class: "audio-message__expand-plain"
}, St = {
  key: 0,
  class: "audio-message__expand-placeholder"
}, Nt = ["innerHTML"], _t = { class: "audio-message__expand-close-wrap" }, It = "RECOGNITION_READY", Et = "SUMMARY_READY", Jt = /* @__PURE__ */ Ue({
  __name: "AudioMessage",
  props: {
    message: {
      type: Object,
      required: !0
    },
    applyStyle: {
      type: Function,
      default: () => null
    },
    isFirstInSeries: {
      type: Boolean,
      default: !0
    },
    reactionsEnabled: {
      type: Boolean,
      default: !0
    },
    subtextTooltipData: {
      type: Object,
      required: !1,
      default: () => ({})
    },
    channel: {
      type: String,
      required: !1,
      default: void 0
    }
  },
  emits: ["action", "reply", "sms-invite"],
  setup(s, { emit: me }) {
    const u = s, F = p([
      {
        text: "1.0x",
        speed: 1
      },
      {
        text: "1.25x",
        speed: 1.25
      },
      {
        text: "1.5x",
        speed: 1.5
      },
      {
        text: "2.0x",
        speed: 2
      }
    ]), L = p(0), D = l(() => F.value[L.value] ?? F.value[0]), ce = () => {
      L.value = (L.value + 1) % F.value.length, a.value && (a.value.playbackRate = D.value.speed);
    }, T = me, a = p(null), w = p(void 0), d = p(!1), y = p(0), g = p(0), b = p(!1), P = l(() => {
      var t, n;
      const e = u.message;
      return e.url || (typeof ((t = e.meta) == null ? void 0 : t.url) == "string" ? e.meta.url : void 0) || ((n = e.data) == null ? void 0 : n.url);
    }), $ = (e) => {
      if (e == null) return;
      if (typeof e == "number")
        return !Number.isFinite(e) || e < 0 ? void 0 : Math.floor(e);
      const t = String(e).trim();
      if (!t) return;
      if (/^\d+$/.test(t)) {
        const v = Number(t);
        return Number.isFinite(v) && v >= 0 ? Math.floor(v) : void 0;
      }
      const n = t.match(/^(\d+):([0-5]\d):([0-5]\d)$/);
      if (n) {
        const v = Number(n[1]), B = Number(n[2]), H = Number(n[3]);
        return v * 3600 + B * 60 + H;
      }
      const x = t.match(/^(\d+):([0-5]\d)$/);
      if (x) return Number(x[1]) * 60 + Number(x[2]);
    }, Z = () => {
      d.value = !1, g.value = 0, y.value = $(u.message.duration) ?? 0, b.value = !1;
    };
    Z(), j(
      () => P.value,
      (e, t) => {
        e !== t && (Z(), w.value = void 0, a.value && (a.value.pause(), a.value.currentTime = 0, a.value.removeAttribute("src"), a.value.load()));
      }
    ), j(
      () => u.message.duration,
      () => {
        w.value === void 0 && (y.value = $(u.message.duration) ?? 0);
      }
    );
    const {
      isOpenMenu: U,
      buttonMenuVisible: de,
      showMenu: q,
      hideMenu: V,
      clickAction: ve,
      viewsAction: z,
      handleClickReplied: ge
    } = Qe(u.message, T), f = p(null), M = p({ text: !1, summary: !1 }), S = l(() => {
      var n;
      const e = u.message, t = e.transcript ?? ((n = e.meta) == null ? void 0 : n.transcript);
      return !t || typeof t != "object" ? null : t;
    }), N = l(() => {
      var n;
      const e = u.message, t = e.summary ?? ((n = e.meta) == null ? void 0 : n.summary);
      return !t || typeof t != "object" ? null : t;
    }), W = l(() => {
      var t;
      const e = (t = S.value) == null ? void 0 : t.html;
      return typeof e != "string" ? "" : e.trim();
    }), J = l(() => {
      var e;
      return ((e = S.value) == null ? void 0 : e.status) === It && W.value.length > 0;
    }), K = l(() => {
      var t;
      const e = (t = N.value) == null ? void 0 : t.html;
      return typeof e != "string" ? "" : e.trim();
    }), Q = l(() => {
      var e;
      return ((e = N.value) == null ? void 0 : e.status) === Et && K.value.length > 0;
    }), _ = l(() => {
      var e;
      return !!((e = S.value) != null && e.status);
    }), I = l(() => {
      var e;
      return !!((e = N.value) != null && e.status);
    }), fe = l(() => f.value === "text" ? _.value : f.value === "summary" ? I.value : !1), pe = l(() => {
      var e;
      switch ((e = S.value) == null ? void 0 : e.status) {
        case "RECOGNITION_PLANNED":
          return "Распознаем сообщение, пожалуйста подождите...";
        case "RECOGNITION_ERROR":
          return "Не удалось распознать сообщение";
        case "RECOGNITION_NOT_CONFIGURED":
          return "Опция распознавания не включена";
        default:
          return "Текст сообщения недоступен";
      }
    }), ye = l(() => {
      var e;
      switch ((e = N.value) == null ? void 0 : e.status) {
        case "SUMMARY_PLANNED":
          return "Формируем резюме, пожалуйста подождите...";
        case "SUMMARY_ERROR":
          return "Не удалось сформировать резюме";
        case "SUMMARY_NOT_CONFIGURED":
          return "Опция формирования резюме не включена";
        default:
          return "Резюме недоступно";
      }
    }), he = async () => {
      var t, n, x;
      const e = P.value;
      if (e)
        try {
          const v = await fetch(e, {
            headers: {
              Accept: "audio/*"
            }
          });
          if (!v.ok)
            throw new Error(`HTTP error! status: ${v.status}`);
          const B = v.headers.get("content-type") || "", H = await v.blob(), E = ((n = (t = e.split(".").pop()) == null ? void 0 : t.split("?")[0]) == null ? void 0 : n.toLowerCase()) || "", Pe = {
            "audio/mpeg": "mp3",
            "audio/mp3": "mp3",
            "audio/wav": "wav",
            "audio/x-wav": "wav",
            "audio/ogg": "ogg",
            "audio/webm": "webm",
            "audio/aac": "aac",
            "audio/flac": "flac",
            "audio/m4a": "m4a",
            "audio/x-m4a": "m4a",
            "application/octet-stream": E || "mp3"
          }, ne = E && ["mp3", "wav", "ogg", "webm", "aac", "flac", "m4a"].includes(E) ? E : Pe[B] || "mp3", oe = e.split("/"), A = decodeURIComponent(((x = oe[oe.length - 1]) == null ? void 0 : x.split("?")[0]) || ""), $e = A ? A.includes(".") ? A : `${A}.${ne}` : `audio-${u.message.messageId}.${ne}`, ie = window.URL.createObjectURL(H), R = document.createElement("a");
          R.href = ie, R.download = $e, document.body.appendChild(R), R.click(), document.body.removeChild(R), window.URL.revokeObjectURL(ie);
        } catch (v) {
          console.error("Ошибка при скачивании аудио:", v), e && window.open(e, "_blank");
        }
    }, be = (e) => {
      e.action === "download" ? (he(), V()) : ve(e);
    }, { linkedHtml: Ce, inNewWindow: X } = Xe(() => u.message.text), we = l(() => st(u.message.status)), xe = l(() => at(u.message.status, u.message.statusMsg)), { bubbleStyle: ke } = et(
      l(() => u.message),
      { cssVariable: "--chotto-audiomessage-right-background-color", position: "right" }
    ), ee = async () => {
      const e = P.value;
      if (!(!a.value || !e))
        if (d.value)
          a.value.pause(), d.value = !1;
        else
          try {
            w.value || (w.value = e, await je(), a.value.load()), await a.value.play(), d.value = !0;
          } catch (t) {
            console.error("Не удалось воспроизвести аудио", t), d.value = !1;
          }
    }, te = (e) => {
      const t = Math.floor(e / 60), n = Math.floor(e % 60);
      return `${t.toString().padStart(2, "0")}:${n.toString().padStart(2, "0")}`;
    }, Te = l(() => te(g.value));
    j(
      () => g.value,
      () => {
        a.value && b.value && (a.value.duration != 1 / 0 && !Number.isNaN(a.value.duration) && (a.value.currentTime = g.value), Math.abs(g.value - y.value) < 0.1 && (d.value = !1));
      }
    );
    const se = () => {
      a.value && b.value && a.value.duration != 1 / 0 && !Number.isNaN(a.value.duration) && (a.value.currentTime = g.value), b.value = !1;
    }, Re = l(() => te(y.value)), Me = () => {
      if (!a.value) return;
      const e = a.value;
      if (g.value = e.currentTime || 0, e.duration === 1 / 0 || Number.isNaN(e.duration)) {
        e.currentTime = 1e101;
        const t = () => {
          a.value && (y.value = a.value.duration || 0, g.value = 0, a.value.currentTime = 0);
        };
        e.addEventListener("timeupdate", t, { once: !0 });
      } else
        y.value = e.duration || 0;
      e.playbackRate = D.value.speed;
    }, Se = () => {
      a.value && (b.value || (g.value = a.value.currentTime), a.value.ended && d.value && (d.value = !1));
    }, Ne = () => {
      d.value = !1;
    }, _e = () => {
      console.error("Не удалось загрузить аудио"), d.value = !1, w.value = void 0, a.value && (a.value.pause(), a.value.currentTime = 0, a.value.removeAttribute("src"), a.value.load()), y.value = $(u.message.duration) ?? 0;
    };
    function ae(e) {
      return nt(e.position, "audio-message");
    }
    const { onToggleReaction: Ie, onAddReaction: Ee, onRemoveReaction: Ae } = ot(T), Oe = tt(() => u.message, () => u.subtextTooltipData);
    function Fe() {
      T("sms-invite", u.message);
    }
    const Le = () => {
      if (!_.value) return;
      const e = f.value === "text" ? null : "text";
      f.value = e, e === "text" && !J.value && !M.value.text && (M.value.text = !0, T("action", { action: "fetchTranscript", messageId: u.message.messageId }));
    }, De = () => {
      if (!I.value) return;
      const e = f.value === "summary" ? null : "summary";
      f.value = e, e === "summary" && !Q.value && !M.value.summary && (M.value.summary = !0, T("action", { action: "fetchSummary", messageId: u.message.messageId }));
    };
    return (e, t) => (i(), m("div", {
      class: C(["audio-message", [
        ae(s.message),
        s.applyStyle(s.message)
      ]]),
      messageId: s.message.messageId,
      style: ue(r(ke)),
      onMouseleave: t[8] || (t[8] = //@ts-ignore
      (...n) => r(V) && r(V)(...n))
    }, [
      s.message.avatar && s.isFirstInSeries ? (i(), m("img", {
        key: 0,
        class: "audio-message__avatar",
        src: s.message.avatar,
        height: "32",
        width: "32",
        style: ue({ gridRow: s.message.subText ? "2" : "1" })
      }, null, 12, ut)) : c("", !0),
      s.message.subText && s.isFirstInSeries ? (i(), m("p", lt, [
        k(Ke, {
          text: r(Oe),
          position: s.message.position === "left" ? "right" : "left",
          offset: 8
        }, {
          default: G(() => [
            Ve(h(s.message.subText), 1)
          ]),
          _: 1
        }, 8, ["text", "position"])
      ])) : c("", !0),
      o("div", {
        class: C(["audio-message__content", { "is-first": s.isFirstInSeries, "with-avatar-indent": !s.isFirstInSeries && s.message.avatar }]),
        onMouseenter: t[7] || (t[7] = //@ts-ignore
        (...n) => r(q) && r(q)(...n))
      }, [
        s.message.reply ? (i(), O(qe, {
          key: 0,
          style: { "grid-column": "1/3" },
          message: s.message.reply,
          class: C(s.message.position),
          onReply: r(ge)
        }, null, 8, ["message", "class", "onReply"])) : c("", !0),
        o("div", rt, [
          o("audio", {
            ref_key: "player",
            ref: a,
            src: w.value,
            type: "audio/webm",
            onLoadedmetadata: Me,
            onTimeupdate: Se,
            onEnded: Ne,
            onError: _e
          }, null, 40, mt),
          Y(o("button", {
            class: "audio-message__play",
            onClick: ee
          }, [...t[9] || (t[9] = [
            o("div", { class: "audio-message__play-icon" }, [
              o("svg", {
                width: "20",
                height: "23",
                viewBox: "0 0 20 23",
                fill: "none",
                xmlns: "http://www.w3.org/2000/svg"
              }, [
                o("path", {
                  d: "M18.99 12.9934L3.0825 22.2234C1.7325 23.0059 0 22.0584 0 20.4809V2.02087C0 0.44587 1.73 -0.50413 3.0825 0.28087L18.99 9.51087C19.2971 9.68618 19.5524 9.93959 19.7299 10.2454C19.9075 10.5512 20.001 10.8985 20.001 11.2521C20.001 11.6057 19.9075 11.953 19.7299 12.2589C19.5524 12.5647 19.2971 12.8181 18.99 12.9934Z",
                  fill: "#5F5F5F"
                })
              ])
            ], -1)
          ])], 512), [
            [le, !d.value]
          ]),
          Y(o("button", {
            class: "audio-message__pause",
            onClick: ee
          }, [...t[10] || (t[10] = [
            o("div", { class: "audio-message__pause-icon" }, [
              o("svg", {
                width: "20",
                height: "23",
                viewBox: "0 0 20 23",
                fill: "none",
                xmlns: "http://www.w3.org/2000/svg"
              }, [
                o("path", {
                  d: "M3.75 0C4.74456 0 5.69839 0.395088 6.40165 1.09835C7.10491 1.80161 7.5 2.75544 7.5 3.75V18.75C7.5 19.7446 7.10491 20.6984 6.40165 21.4017C5.69839 22.1049 4.74456 22.5 3.75 22.5C2.75544 22.5 1.80161 22.1049 1.09835 21.4017C0.395088 20.6984 2.09588e-08 19.7446 0 18.75V3.75C0 2.75544 0.395088 1.80161 1.09835 1.09835C1.80161 0.395088 2.75544 0 3.75 0ZM16.25 0C17.2446 0 18.1984 0.395088 18.9017 1.09835C19.6049 1.80161 20 2.75544 20 3.75V18.75C20 19.7446 19.6049 20.6984 18.9017 21.4017C18.1984 22.1049 17.2446 22.5 16.25 22.5C15.2554 22.5 14.3016 22.1049 13.5983 21.4017C12.8951 20.6984 12.5 19.7446 12.5 18.75V3.75C12.5 2.75544 12.8951 1.80161 13.5983 1.09835C14.3016 0.395088 15.2554 0 16.25 0Z",
                  fill: "#5F5F5F"
                })
              ])
            ], -1)
          ])], 512), [
            [le, d.value]
          ]),
          o("div", ct, [
            Y(o("input", {
              "onUpdate:modelValue": t[0] || (t[0] = (n) => g.value = n),
              class: "audio-message__progress-bar-container",
              type: "range",
              min: 0,
              max: y.value,
              step: "0.1",
              onMousedown: t[1] || (t[1] = (n) => b.value = !0),
              onMouseup: se,
              onTouchstartPassive: t[2] || (t[2] = (n) => b.value = !0),
              onTouchendPassive: se
            }, null, 40, dt), [
              [Be, g.value]
            ]),
            o("div", vt, [
              o("button", {
                type: "button",
                class: "audio-message__speed-btn",
                onClick: ce
              }, h(D.value.text), 1)
            ])
          ]),
          o("div", gt, [
            o("p", ft, h(Te.value), 1),
            o("p", pt, h(Re.value), 1)
          ])
        ]),
        s.message.text ? (i(), m("div", yt, [
          o("p", {
            onClick: t[3] || (t[3] = //@ts-ignore
            (...n) => r(X) && r(X)(...n)),
            innerHTML: r(Ce)
          }, null, 8, ht)
        ])) : c("", !0),
        s.message.linkPreview ? (i(), O(Ye, {
          key: 2,
          class: C(["audio-message__link-preview", s.message.position]),
          "link-preview": s.message.linkPreview
        }, null, 8, ["class", "link-preview"])) : c("", !0),
        s.message.embed ? (i(), O(Ze, {
          key: 3,
          class: C(s.message.position),
          embed: s.message.embed
        }, null, 8, ["class", "embed"])) : c("", !0),
        k(ze, {
          reactions: s.message.reactions,
          "message-id": s.message.messageId,
          enabled: s.reactionsEnabled,
          onToggleReaction: r(Ie),
          onAddReaction: r(Ee),
          onRemoveReaction: r(Ae)
        }, null, 8, ["reactions", "message-id", "enabled", "onToggleReaction", "onAddReaction", "onRemoveReaction"]),
        o("div", bt, [
          _.value || I.value ? (i(), m("div", Ct, [
            _.value ? (i(), m("button", {
              key: 0,
              class: C([
                "audio-message__action-button",
                { "audio-message__action-button--active": f.value === "text" }
              ]),
              type: "button",
              onClick: Le
            }, " Текст ", 2)) : c("", !0),
            I.value ? (i(), m("button", {
              key: 1,
              class: C([
                "audio-message__action-button",
                { "audio-message__action-button--active": f.value === "summary" }
              ]),
              type: "button",
              onClick: De
            }, " Резюме ", 2)) : c("", !0)
          ])) : c("", !0),
          s.message.views ? (i(), m("div", {
            key: 1,
            class: "audio-message__views",
            onClick: t[4] || (t[4] = //@ts-ignore
            (...n) => r(z) && r(z)(...n))
          }, [
            t[11] || (t[11] = o("span", { class: "pi pi-eye" }, null, -1)),
            o("p", null, h(s.message.views), 1)
          ])) : c("", !0),
          o("span", wt, h(s.message.time), 1),
          k(We, {
            "base-class": "audio-message",
            "message-class": ae(s.message),
            "message-status": s.message.status,
            "status-class": we.value,
            "status-title": xe.value
          }, null, 8, ["message-class", "message-status", "status-class", "status-title"])
        ]),
        k(re, { name: "audio-message-expand" }, {
          default: G(() => [
            fe.value ? (i(), m("div", xt, [
              o("div", kt, [
                f.value === "text" ? (i(), m(He, { key: 0 }, [
                  J.value ? (i(), m("p", {
                    key: 1,
                    class: "audio-message__expand-plain",
                    innerHTML: W.value
                  }, null, 8, Rt)) : (i(), m("p", Tt, h(pe.value), 1))
                ], 64)) : (i(), m("p", Mt, [
                  Q.value ? (i(), m("span", {
                    key: 1,
                    innerHTML: K.value
                  }, null, 8, Nt)) : (i(), m("span", St, h(ye.value), 1))
                ]))
              ]),
              o("div", _t, [
                o("button", {
                  type: "button",
                  class: "audio-message__expand-close",
                  onClick: t[5] || (t[5] = (n) => f.value = null)
                }, " Закрыть ")
              ])
            ])) : c("", !0)
          ]),
          _: 1
        }),
        k(Je, {
          status: s.message.status,
          "has-messenger-account": s.message.hasMessengerAccount,
          channel: s.channel,
          onSmsInvite: Fe
        }, null, 8, ["status", "has-messenger-account", "channel"]),
        r(de) && s.message.actions ? (i(), m("button", {
          key: 4,
          class: "audio-message__menu-button",
          onClick: t[6] || (t[6] = (n) => U.value = !r(U))
        }, [...t[12] || (t[12] = [
          o("svg", {
            width: "4",
            height: "17",
            viewBox: "0 0 4 17",
            fill: "none",
            xmlns: "http://www.w3.org/2000/svg"
          }, [
            o("path", {
              d: "M3.75 14.375C3.75 14.8723 3.55246 15.3492 3.20083 15.7008C2.84919 16.0525 2.37228 16.25 1.875 16.25C1.37772 16.25 0.900805 16.0525 0.549175 15.7008C0.197544 15.3492 0 14.8723 0 14.375C0 13.8777 0.197544 13.4008 0.549175 13.0492C0.900805 12.6975 1.37772 12.5 1.875 12.5C2.37228 12.5 2.84919 12.6975 3.20083 13.0492C3.55246 13.4008 3.75 13.8777 3.75 14.375ZM3.75 8.125C3.75 8.62228 3.55246 9.09919 3.20083 9.45083C2.84919 9.80246 2.37228 10 1.875 10C1.37772 10 0.900805 9.80246 0.549175 9.45083C0.197544 9.09919 0 8.62228 0 8.125C0 7.62772 0.197544 7.15081 0.549175 6.79917C0.900805 6.44754 1.37772 6.25 1.875 6.25C2.37228 6.25 2.84919 6.44754 3.20083 6.79917C3.55246 7.15081 3.75 7.62772 3.75 8.125ZM3.75 1.875C3.75 2.37228 3.55246 2.84919 3.20083 3.20083C2.84919 3.55246 2.37228 3.75 1.875 3.75C1.37772 3.75 0.900805 3.55246 0.549175 3.20083C0.197544 2.84919 0 2.37228 0 1.875C0 1.37772 0.197544 0.900806 0.549175 0.549175C0.900805 0.197544 1.37772 0 1.875 0C2.37228 0 2.84919 0.197544 3.20083 0.549175C3.55246 0.900806 3.75 1.37772 3.75 1.875Z",
              fill: "#5F5F5F"
            })
          ], -1)
        ])])) : c("", !0),
        k(re, null, {
          default: G(() => [
            r(U) && s.message.actions ? (i(), O(Ge, {
              key: 0,
              class: "audio-message__context-menu",
              actions: s.message.actions,
              onClick: be
            }, null, 8, ["actions"])) : c("", !0)
          ]),
          _: 1
        })
      ], 34)
    ], 46, it));
  }
});
export {
  Jt as default
};
