import { defineComponent as He, inject as re, computed as r, unref as l, toRefs as Ge, ref as g, watch as ce, createElementBlock as i, openBlock as n, normalizeClass as G, createCommentVNode as f, createElementVNode as o, createVNode as Y, withCtx as V, createTextVNode as h, toDisplayString as d, createBlock as $, Fragment as x, withDirectives as Z, vShow as de, vModelText as Ye, Transition as me, nextTick as Ze } from "vue";
import { useMessageActions as qe } from "../../../hooks/messages/useMessageActions.js";
import "../../../node_modules/linkifyjs/dist/linkify.js";
import "../../../node_modules/linkify-string/dist/linkify-string.js";
import "../../../functions/parseMarkdown.js";
import { useSubtextTooltip as ze } from "../../../hooks/messages/useSubtextTooltip.js";
import Je from "../../1_atoms/ContextMenu/ContextMenu.vue.js";
import ve from "../../1_atoms/Tooltip/Tooltip.vue.js";
import Ke from "./icons/IncomingCallIcon.vue.js";
import Qe from "./icons/OutgoingCallIcon.vue.js";
const Xe = ["messageId"], We = ["src"], et = {
  key: 1,
  class: "call-message__subtext"
}, tt = { class: "call-message__content" }, at = { class: "call-message__header-container" }, st = { class: "call-message__title-wrapper" }, lt = {
  key: 0,
  class: "call-message__title"
}, nt = {
  key: 1,
  class: "call-message__title call-message__title--missed"
}, ot = {
  key: 0,
  class: "call-message__title"
}, ut = {
  key: 1,
  class: "call-message__title call-message__title--missed"
}, it = {
  key: 0,
  class: "call-message__missed-info"
}, rt = {
  key: 1,
  class: "call-message__audio-wrapper"
}, ct = ["src"], dt = { class: "call-message__audio-progress" }, mt = { class: "call-message__audio-progress-bar" }, vt = ["max"], pt = { class: "call-message__audio-time" }, _t = { class: "call-message__info-container" }, ft = { class: "call-message__actions" }, gt = { class: "call-message__time" }, yt = {
  key: 0,
  class: "call-message__expand-panel"
}, Ct = { class: "call-message__expand-inner" }, ht = {
  key: 0,
  class: "call-message__expand-placeholder"
}, xt = ["innerHTML"], bt = {
  key: 1,
  class: "call-message__expand-plain"
}, wt = {
  key: 0,
  class: "call-message__expand-placeholder"
}, kt = ["innerHTML"], Tt = { class: "call-message__expand-close-wrap" }, Mt = "RECOGNITION_READY", Nt = "SUMMARY_READY", $t = /* @__PURE__ */ He({
  __name: "CallMessage",
  props: {
    message: {
      type: Object,
      required: !0
    },
    /**
     * Позволяет переопределить действие кнопки "Перезвонить" снаружи (например, из feed).
     * Если не задано, компонент эмитит событие `call`.
     */
    onCall: {
      type: Function,
      required: !1,
      default: void 0
    },
    applyStyle: {
      type: Function,
      default: () => null
    },
    subtextTooltipData: {
      type: Object,
      required: !1,
      default: () => ({})
    }
  },
  emits: ["action", "reply", "call"],
  setup(pe, { emit: _e }) {
    const q = re("channels", void 0), z = re("selectedChat", void 0), fe = r(() => {
      if (q)
        return l(q);
    }), ge = r(() => {
      if (z)
        return l(z);
    }), M = _e, b = pe, { message: a, applyStyle: ye } = Ge(b), N = r(() => {
      const e = a.value;
      return e.url ? e.url : typeof e.recordUrl == "string" ? e.recordUrl : void 0;
    }), {
      isOpenMenu: P,
      buttonMenuVisible: Ce,
      showMenu: J,
      hideMenu: j,
      clickAction: he
    } = qe(b.message, M), p = g(null), I = r(() => {
      var t;
      const e = (t = a.value) == null ? void 0 : t.transcript;
      return !e || typeof e != "object" ? null : e;
    }), R = r(() => {
      var t;
      const e = (t = a.value) == null ? void 0 : t.summary;
      return !e || typeof e != "object" ? null : e;
    }), K = r(() => {
      var t;
      const e = (t = I.value) == null ? void 0 : t.html;
      return typeof e != "string" ? "" : e.trim();
    }), Q = r(() => {
      var t;
      const e = (t = R.value) == null ? void 0 : t.html;
      return typeof e != "string" ? "" : e.trim();
    }), X = r(() => {
      var e;
      return ((e = I.value) == null ? void 0 : e.status) === Mt && K.value.length > 0;
    }), W = r(() => {
      var e;
      return ((e = R.value) == null ? void 0 : e.status) === Nt && Q.value.length > 0;
    }), E = g({
      text: !1,
      summary: !1
    }), S = r(() => {
      var e, t;
      return !!((e = I.value) != null && e.status) && !((t = a.value) != null && t.isMissedCall);
    }), F = r(() => {
      var e, t;
      return !!((e = R.value) != null && e.status) && !((t = a.value) != null && t.isMissedCall);
    }), xe = r(() => p.value === "text" ? S.value : p.value === "summary" ? F.value : !1), be = r(() => {
      var e;
      switch ((e = I.value) == null ? void 0 : e.status) {
        case "RECOGNITION_PLANNED":
          return "Распознаем звонок, пожалуйста подождите...";
        case "RECOGNITION_ERROR":
          return "Не удалось распознать звонок";
        case "RECOGNITION_NOT_CONFIGURED":
          return "Опция распознавания не включена";
        default:
          return "Текст звонка недоступен";
      }
    }), we = r(() => {
      var e;
      switch ((e = R.value) == null ? void 0 : e.status) {
        case "SUMMARY_PLANNED":
          return "Формируем резюме, пожалуйста подождите...";
        case "SUMMARY_ERROR":
          return "Не удалось сформировать резюме";
        case "SUMMARY_NOT_CONFIGURED":
          return "Опция формирования резюме не включена";
        default:
          return "Резюме недоступно";
      }
    }), s = g(null), w = g(void 0), m = g(!1), y = g(0), v = g(0), C = g(!1), O = g(0), B = [
      {
        text: "1.0x",
        speed: 1
      },
      {
        text: "1.25x",
        speed: 1.25
      },
      {
        text: "1.5x",
        speed: 1.5
      },
      {
        text: "2.0x",
        speed: 2
      }
    ], H = r(() => B[O.value] ?? B[0]), ke = (e) => {
      if (!e) return;
      const u = e.trim().match(/^(\d+):([0-5]\d)$/);
      if (!u) return;
      const _ = Number(u[1]), c = Number(u[2]);
      if (!(Number.isNaN(_) || Number.isNaN(c)))
        return _ * 60 + c;
    }, ee = () => {
      var e;
      m.value = !1, v.value = 0, y.value = ke((e = a.value) == null ? void 0 : e.callDuration) ?? 0, C.value = !1, O.value = 0;
    };
    ee(), ce(
      N,
      (e, t) => {
        e !== t && (ee(), w.value = void 0, s.value && (s.value.pause(), s.value.currentTime = 0, s.value.removeAttribute("src"), s.value.load()));
      }
    );
    const te = (e) => {
      const t = Math.floor(e / 60), u = Math.floor(e % 60);
      return `${t.toString().padStart(2, "0")}:${u.toString().padStart(2, "0")}`;
    }, Te = r(() => te(v.value)), Me = r(() => te(y.value)), ae = async () => {
      const e = N.value;
      if (!(!s.value || !e))
        if (m.value)
          s.value.pause(), m.value = !1;
        else
          try {
            w.value || (w.value = e, await Ze(), s.value.load()), await s.value.play(), m.value = !0;
          } catch (t) {
            console.error("Не удалось воспроизвести запись звонка", t), m.value = !1;
          }
    }, Ne = () => {
      O.value = (O.value + 1) % B.length, s.value && (s.value.playbackRate = H.value.speed);
    };
    ce(
      () => v.value,
      () => {
        s.value && C.value && (s.value.duration !== 1 / 0 && !Number.isNaN(s.value.duration) && (s.value.currentTime = v.value), Math.abs(v.value - y.value) < 0.1 && (m.value = !1));
      }
    );
    const se = () => {
      s.value && C.value && s.value.duration !== 1 / 0 && !Number.isNaN(s.value.duration) && (s.value.currentTime = v.value), C.value = !1;
    }, Ie = () => {
      if (!s.value) return;
      const e = s.value;
      if (y.value = 0, v.value = e.currentTime || 0, e.duration === 1 / 0 || Number.isNaN(e.duration)) {
        e.currentTime = 1e101;
        const t = () => {
          s.value && (y.value = s.value.duration || 0, v.value = 0, s.value.currentTime = 0);
        };
        e.addEventListener("timeupdate", t, { once: !0 });
      } else
        y.value = e.duration || 0;
      e.playbackRate = H.value.speed;
    }, Re = () => {
      s.value && (C.value || (v.value = s.value.currentTime), s.value.ended && m.value && (m.value = !1));
    }, Ee = () => {
      m.value = !1;
    }, Se = () => {
      console.error("Не удалось загрузить запись звонка"), m.value = !1, w.value = void 0, s.value && (s.value.pause(), s.value.currentTime = 0, s.value.removeAttribute("src"), s.value.load());
    }, A = r(() => {
      var e;
      switch ((e = a.value) == null ? void 0 : e.direction) {
        case "incoming":
          return "Входящий";
        case "outgoing":
          return "Исходящий";
        default:
          return "Звонок";
      }
    }), le = r(() => {
      var t, u;
      const e = (t = a.value) == null ? void 0 : t.isMissedCall;
      switch ((u = a.value) == null ? void 0 : u.direction) {
        case "incoming":
          return e ? "#F84932" : "#00AC47";
        case "outgoing":
          return e ? "#5F5F5F" : "#118ABF";
        default:
          return e ? "#5F5F5F" : "#00AC47";
      }
    }), Fe = r(() => {
      var e;
      return ((e = a.value) == null ? void 0 : e.direction) === "outgoing" ? "Без ответа" : "Пропущенный";
    }), ne = r(() => {
      var D;
      const e = a.value, t = fe.value, u = ge.value;
      if (!(e != null && e.dialogId) || !t || !u)
        return null;
      const _ = (D = u.dialogs) == null ? void 0 : D.find((k) => k.dialogId === e.dialogId);
      if (!(_ != null && _.channelId))
        return null;
      const c = t.find((k) => k.channelId === _.channelId);
      return (c == null ? void 0 : c.title) || null;
    }), Oe = ze(() => b.message, () => b.subtextTooltipData), Ae = {
      message: "message"
    };
    function De(e, t) {
      const u = e.position;
      switch (t) {
        case "message":
          return u === "left" ? "call-message__left" : "call-message__right";
        default:
          return "";
      }
    }
    const Le = () => {
      if (typeof b.onCall == "function") {
        b.onCall(a.value);
        return;
      }
      M("call", { message: a.value });
    }, Ue = () => {
      if (!S.value) return;
      const e = p.value === "text" ? null : "text";
      p.value = e, e === "text" && !X.value && !E.value.text && (E.value.text = !0, M("action", { action: "fetchTranscript", messageId: a.value.messageId }));
    }, Ve = () => {
      if (!F.value) return;
      const e = p.value === "summary" ? null : "summary";
      p.value = e, e === "summary" && !W.value && !E.value.summary && (E.value.summary = !0, M("action", { action: "fetchCallSummary", messageId: a.value.messageId }));
    }, $e = async () => {
      var t, u, _;
      const e = N.value;
      if (e)
        try {
          const c = await fetch(e, {
            headers: {
              Accept: "audio/*"
            }
          });
          if (!c.ok)
            throw new Error(`HTTP error! status: ${c.status}`);
          const D = c.headers.get("content-type") || "", k = await c.blob(), L = ((u = (t = e.split(".").pop()) == null ? void 0 : t.split("?")[0]) == null ? void 0 : u.toLowerCase()) || "", je = {
            "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": L || "mp3"
          }, oe = L && ["mp3", "wav", "ogg", "webm", "aac", "flac", "m4a"].includes(L) ? L : je[D] || "mp3", ue = e.split("/"), U = decodeURIComponent(((_ = ue[ue.length - 1]) == null ? void 0 : _.split("?")[0]) || ""), Be = U ? U.includes(".") ? U : `${U}.${oe}` : `call-${a.value.messageId}.${oe}`, ie = window.URL.createObjectURL(k), T = document.createElement("a");
          T.href = ie, T.download = Be, document.body.appendChild(T), T.click(), document.body.removeChild(T), window.URL.revokeObjectURL(ie);
        } catch (c) {
          console.error("Ошибка при скачивании аудио звонка:", c), e && window.open(e, "_blank");
        }
    }, Pe = (e) => {
      e.action === "download" ? ($e(), j()) : he(e);
    };
    return (e, t) => (n(), i("div", {
      class: G([
        De(l(a), Ae.message),
        l(ye)(l(a))
      ]),
      messageId: l(a).messageId,
      onMouseenter: t[5] || (t[5] = //@ts-ignore
      (...u) => l(J) && l(J)(...u)),
      onMouseleave: t[6] || (t[6] = //@ts-ignore
      (...u) => l(j) && l(j)(...u))
    }, [
      l(a).avatar ? (n(), i("img", {
        key: 0,
        class: "call-message__avatar",
        src: l(a).avatar,
        height: "32",
        width: "32"
      }, null, 8, We)) : f("", !0),
      l(a).subText ? (n(), i("p", et, [
        Y(ve, {
          text: l(Oe),
          position: l(a).position === "left" ? "right" : "left",
          offset: 8
        }, {
          default: V(() => [
            h(d(l(a).subText), 1)
          ]),
          _: 1
        }, 8, ["text", "position"])
      ])) : f("", !0),
      o("div", tt, [
        o("div", at, [
          o("div", st, [
            l(a).direction === "incoming" || !l(a).direction ? (n(), $(Ke, {
              key: 0,
              class: "call-message__direction-icon",
              color: le.value
            }, null, 8, ["color"])) : (n(), $(Qe, {
              key: 1,
              class: "call-message__direction-icon",
              color: le.value
            }, null, 8, ["color"])),
            ne.value ? (n(), $(ve, {
              key: 2,
              text: ne.value,
              position: "top",
              offset: 8
            }, {
              default: V(() => [
                l(a).isMissedCall ? (n(), i("span", nt, [
                  h(d(A.value) + " ", 1),
                  l(a).direction !== "incoming" ? (n(), i(x, { key: 0 }, [
                    h(" звонок ")
                  ], 64)) : (n(), i(x, { key: 1 }, [
                    h(" звонок ")
                  ], 64))
                ])) : (n(), i("span", lt, d(A.value) + " звонок ", 1))
              ]),
              _: 1
            }, 8, ["text"])) : (n(), i(x, { key: 3 }, [
              l(a).isMissedCall ? (n(), i("span", ut, [
                h(d(A.value) + " ", 1),
                l(a).direction !== "incoming" ? (n(), i(x, { key: 0 }, [
                  h(" звонок ")
                ], 64)) : (n(), i(x, { key: 1 }, [
                  h(" звонок ")
                ], 64))
              ])) : (n(), i("span", ot, d(A.value) + " звонок ", 1))
            ], 64))
          ]),
          l(a).isMissedCall ? (n(), i("p", it, d(Fe.value) + ": " + d(l(a).callAttemptDuration), 1)) : f("", !0),
          N.value && !l(a).isMissedCall ? (n(), i("div", rt, [
            o("audio", {
              ref_key: "player",
              ref: s,
              src: w.value,
              type: "audio/webm",
              onLoadedmetadata: Ie,
              onTimeupdate: Re,
              onEnded: Ee,
              onError: Se
            }, null, 40, ct),
            Z(o("button", {
              class: "call-message__audio-play",
              type: "button",
              onClick: ae
            }, [...t[7] || (t[7] = [
              o("div", { class: "call-message__audio-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), [
              [de, !m.value]
            ]),
            Z(o("button", {
              class: "call-message__audio-pause",
              type: "button",
              onClick: ae
            }, [...t[8] || (t[8] = [
              o("div", { class: "call-message__audio-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 0 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), [
              [de, m.value]
            ]),
            o("div", dt, [
              o("div", mt, [
                Z(o("input", {
                  "onUpdate:modelValue": t[0] || (t[0] = (u) => v.value = u),
                  class: "call-message__audio-slider",
                  type: "range",
                  min: 0,
                  max: y.value,
                  step: "0.1",
                  onMousedown: t[1] || (t[1] = (u) => C.value = !0),
                  onMouseup: se,
                  onTouchstartPassive: t[2] || (t[2] = (u) => C.value = !0),
                  onTouchendPassive: se
                }, null, 40, vt), [
                  [Ye, v.value]
                ]),
                o("button", {
                  type: "button",
                  class: "call-message__audio-speed-btn",
                  onClick: Ne
                }, d(H.value.text), 1)
              ]),
              o("div", pt, [
                o("span", null, d(Te.value), 1),
                o("span", null, d(Me.value), 1)
              ])
            ])
          ])) : f("", !0)
        ]),
        o("div", _t, [
          o("div", ft, [
            !l(a).isMissedCall && (S.value || F.value) ? (n(), i(x, { key: 0 }, [
              S.value ? (n(), i("button", {
                key: 0,
                class: G([
                  "call-message__call-button",
                  { "call-message__call-button--active": p.value === "text" }
                ]),
                type: "button",
                onClick: Ue
              }, " Текст ", 2)) : f("", !0),
              F.value ? (n(), i("button", {
                key: 1,
                class: G([
                  "call-message__call-button",
                  { "call-message__call-button--active": p.value === "summary" }
                ]),
                type: "button",
                onClick: Ve
              }, " Резюме ", 2)) : f("", !0)
            ], 64)) : f("", !0),
            o("button", {
              class: "call-message__call-button",
              type: "button",
              onClick: Le
            }, " Перезвонить ")
          ]),
          o("span", gt, d(l(a).time), 1)
        ]),
        Y(me, { name: "call-message-expand" }, {
          default: V(() => [
            xe.value ? (n(), i("div", yt, [
              o("div", Ct, [
                p.value === "text" ? (n(), i(x, { key: 0 }, [
                  X.value ? (n(), i("p", {
                    key: 1,
                    class: "call-message__expand-plain",
                    innerHTML: K.value
                  }, null, 8, xt)) : (n(), i("p", ht, d(be.value), 1))
                ], 64)) : (n(), i("p", bt, [
                  W.value ? (n(), i("span", {
                    key: 1,
                    innerHTML: Q.value
                  }, null, 8, kt)) : (n(), i("span", wt, d(we.value), 1))
                ]))
              ]),
              o("div", Tt, [
                o("button", {
                  type: "button",
                  class: "call-message__expand-close",
                  onClick: t[3] || (t[3] = (u) => p.value = null)
                }, " Закрыть ")
              ])
            ])) : f("", !0)
          ]),
          _: 1
        }),
        l(Ce) && l(a).actions ? (n(), i("button", {
          key: 0,
          class: "call-message__menu-button",
          onClick: t[4] || (t[4] = (u) => P.value = !l(P))
        }, [...t[9] || (t[9] = [
          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)
        ])])) : f("", !0),
        Y(me, null, {
          default: V(() => [
            l(P) && l(a).actions ? (n(), $(Je, {
              key: 0,
              class: "call-message__context-menu",
              actions: l(a).actions,
              onClick: Pe
            }, null, 8, ["actions"])) : f("", !0)
          ]),
          _: 1
        })
      ])
    ], 42, Xe));
  }
});
export {
  $t as default
};
