import { defineComponent as fe, ref as k, computed as i, inject as w, unref as s, watch as ge, nextTick as K, onMounted as ye, createElementBlock as c, openBlock as l, createVNode as g, createBlock as f, createCommentVNode as u, normalizeStyle as O, renderSlot as j, withDirectives as pe, createElementVNode as h, vShow as be, Transition as v, withCtx as S, Fragment as ke, renderList as he, resolveDynamicComponent as ve, mergeProps as Se, toDisplayString as Re, Teleport as Me } from "vue";
import Be from "../../2_feed_elements/DateMessageSticky/DateMessageSticky.vue.js";
import Ie from "../../2_feed_elements/BaseReplyMessage/BaseReplyMessage.vue.js";
import Te from "../../2_feed_elements/MessageKeyboard/MessageKeyboard.vue.js";
import Ae from "../../2_feed_elements/FeedKeyboard/FeedKeyboard.vue.js";
import Ce from "../../2_feed_elements/TypingMessage/TypingMessage.vue.js";
import Fe from "../../1_atoms/LoadingIndicator/LoadingIndicator.vue.js";
import { useFeedButton as De } from "./composables/useFeedButton.js";
import { useFeedComponents as we } from "./composables/useFeedComponents.js";
import { useFeedGrouping as Ke } from "./composables/useFeedGrouping.js";
import { useFeedKeyboard as Oe } from "./composables/useFeedKeyboard.js";
import { useFeedLoadMore as je } from "./composables/useFeedLoadMore.js";
import { useFeedMessageVisibility as xe } from "./composables/useFeedMessageVisibility.js";
import { useFeedReply as Le } from "./composables/useFeedReply.js";
import { useFeedScroll as Ve } from "./composables/useFeedScroll.js";
import { useFeedScrollTo as $e } from "./composables/useFeedScrollTo.js";
import { useStickyDate as qe } from "./composables/useStickyDate.js";
import { throttle as Pe } from "./functions/throttle.js";
import ze from "./assets/chat-background.svg.js";
const Ee = { class: "message-feed-wrapper" }, We = ["id"], Ne = { class: "message-feed__loading" }, Ge = ["id", "data-timestamp", "onDblclick"], Ue = { style: { margin: "auto" } }, He = {
  key: 0,
  class: "message-feed__unread-amount"
}, ft = /* @__PURE__ */ fe({
  __name: "Feed",
  props: {
    objects: {
      type: Array,
      required: !0
    },
    buttonParams: {
      type: Object,
      required: !1,
      default: void 0
    },
    // принудительный скролл вниз по событию извне (сообщение, смена чата)
    scrollToBottom: {
      type: Boolean,
      default: !1
    },
    typing: {
      type: [Object, Boolean],
      default: !1
    },
    enableDoubleClickReply: {
      type: Boolean,
      default: !1
    },
    scrollTo: {
      type: String,
      default: null
    },
    applyStyle: {
      type: Function,
      default: () => null
    },
    keyboardAlign: {
      type: String,
      default: "right",
      validator: (e) => ["left", "center", "right"].includes(e)
    },
    feedKeyboards: {
      type: Array,
      required: !1,
      default: void 0
    },
    feedKeyboardAlign: {
      type: String,
      default: "right",
      validator: (e) => ["left", "center", "right"].includes(e)
    },
    chatBackground: {
      type: String,
      default: void 0
    },
    isLoadingMore: {
      type: Boolean,
      default: !1
    },
    reactionsEnabled: {
      type: Boolean,
      default: !0
    },
    subtextTooltipData: {
      type: Object,
      required: !1,
      default: () => ({})
    },
    /**
     * Позволяет переопределить действие "Перезвонить" для `message.call`.
     * Будет передано внутрь `CallMessage` как проп `onCall`.
     */
    callMessageOnCallback: {
      type: Function,
      required: !1,
      default: void 0
    }
  },
  emits: [
    "messageAction",
    "loadMore",
    "loadMoreDown",
    "messageVisible",
    "clickRepliedMessage",
    "forceScrollToBottom",
    "keyboardAction",
    "feedAction",
    "smsInvite",
    "delimiterRead"
  ],
  setup(e, { emit: x }) {
    const a = e, b = k(), r = k(), R = k(), {
      isShowButton: L,
      isKeyboardPlace: V,
      checkButtonVisibility: $
    } = De({
      feedRef: r,
      keyboardRef: R
    }), { componentsMap: q } = we(), P = i(() => a.reactionsEnabled), { groupedObjects: z } = Ke({
      objects: i(() => a.objects)
    }), y = w("chatAppId"), M = w("selectedChat", void 0), B = i(() => {
      if (M)
        return s(M);
    });
    function E(o) {
      return o.timestamp;
    }
    function W(o) {
      var m;
      const n = o;
      if (!n.dialogId || !((m = B.value) != null && m.dialogs))
        return;
      const t = B.value.dialogs.find((p) => p.dialogId === n.dialogId);
      return t == null ? void 0 : t.channelId;
    }
    function N(o) {
      return o.type === "message.call" && typeof a.callMessageOnCallback == "function" ? { onCall: a.callMessageOnCallback } : {};
    }
    const d = x, {
      checkScrollPosition: G,
      startScrollWatch: I,
      stopScrollWatch: T,
      resetAllowFlags: U
    } = je({
      feedRef: r,
      emit: d,
      isLoadingMoreRef: i(() => a.isLoadingMore)
    }), {
      getMessage: A,
      messageAction: H,
      handleClickReplied: J,
      feedObjectDoubleClick: Q,
      handleResetReply: X
    } = Le({
      enableDoubleClickReply: a.enableDoubleClickReply,
      emit: d
    });
    function Y(o) {
      d("smsInvite", o);
    }
    function Z(o) {
      d("delimiterRead", o);
    }
    const {
      showKeyboard: _,
      keyboardAction: ee,
      feedKeyboardAction: te
    } = Oe({
      isKeyboardPlace: V,
      objects: i(() => a.objects),
      emit: d
    }), {
      showStickyDate: oe,
      stickyDateText: se,
      show: ae
    } = qe({
      feedRef: r,
      trackingObjects: b
    }), {
      isInitialized: ne,
      performScrollToBottom: le,
      ensureScrollToBottom: C,
      initializeScroll: ie,
      smoothScrollToBottom: re
    } = Ve({
      feedRef: r,
      objectsRef: i(() => a.objects),
      scrollToBottomRef: i(() => a.scrollToBottom)
    }), F = i(() => a.chatBackground ?? `data:image/svg+xml;charset=utf-8,${encodeURIComponent(ze)}`);
    function D(o = !0) {
      $(), G(o), ae();
    }
    const de = Pe(() => D(), 250);
    function ce() {
      d("forceScrollToBottom"), re();
    }
    function ue(o) {
      const n = a.objects;
      if (o.startsWith("mid-")) {
        const t = parseInt(o.slice(4), 10);
        return n[t];
      }
      return n.find((t) => t.messageId === o);
    }
    const { restartObserving: me } = xe({
      trackingObjects: b,
      chatAppId: y,
      getMessageById: ue,
      onMessageVisible: (o) => d("messageVisible", o)
    });
    return ge(
      () => a.objects,
      () => {
        K(() => {
          requestAnimationFrame(() => {
            U(), D(!1), b.value = document.querySelectorAll(".tracking-message"), me();
          });
        });
      },
      { immediate: !0 }
    ), $e({
      targetIdRef: i(() => a.scrollTo),
      feedContainerId: `feed-container-${y}`
    }), ye(() => {
      K(() => {
        a.objects.length > 0 && !ne.value && ie();
        const o = new ResizeObserver(() => {
          a.scrollToBottom && (le(), setTimeout(() => {
            C();
          }, 200), setTimeout(() => {
            C();
          }, 800));
        });
        r.value && o.observe(r.value);
      });
    }), (o, n) => (l(), c("div", Ee, [
      e.objects.length > 0 || e.typing ? (l(), c("div", {
        key: 0,
        id: "feed-container-" + s(y),
        ref_key: "refFeed",
        ref: r,
        class: "message-feed",
        style: O({ backgroundImage: `url(${F.value})` }),
        onScroll: n[0] || (n[0] = (t) => s(de)()),
        onMousedown: n[1] || (n[1] = //@ts-ignore
        (...t) => s(I) && s(I)(...t)),
        onMouseup: n[2] || (n[2] = //@ts-ignore
        (...t) => s(T) && s(T)(...t))
      }, [
        j(o.$slots, "prepend", {}, void 0, !0),
        pe(h("div", Ne, [
          g(Fe, {
            "is-loading": e.isLoadingMore,
            size: "small",
            position: "top"
          }, null, 8, ["is-loading"])
        ], 512), [
          [be, e.isLoadingMore]
        ]),
        g(v, null, {
          default: S(() => [
            s(oe) && !e.isLoadingMore ? (l(), f(Be, {
              key: 0,
              class: "message-feed__sticky-date",
              text: s(se)
            }, null, 8, ["text"])) : u("", !0)
          ]),
          _: 1
        }),
        (l(!0), c(ke, null, he(s(z), (t, m) => (l(), c("div", {
          id: "msg-" + (t.messageId ?? "mid-" + m),
          key: t.messageId ?? "mid-" + m,
          "data-timestamp": E(t),
          class: "tracking-message",
          onDblclick: (p) => s(Q)(p, t)
        }, [
          (l(), f(ve(s(q)(t.type)), Se({
            key: t.messageId ?? "mid-" + m,
            class: "message-feed__message",
            message: t,
            "apply-style": e.applyStyle,
            "is-first-in-series": t.isFirstInSeries,
            "reactions-enabled": P.value,
            "subtext-tooltip-data": e.subtextTooltipData,
            channel: W(t)
          }, { ref_for: !0 }, N(t), {
            onAction: s(H),
            onReply: s(J),
            onSmsInvite: (p) => Y(t),
            onRead: Z
          }), null, 16, ["message", "apply-style", "is-first-in-series", "reactions-enabled", "subtext-tooltip-data", "channel", "onAction", "onReply", "onSmsInvite"]))
        ], 40, Ge))), 128)),
        e.typing ? (l(), f(Ce, {
          key: 0,
          message: {
            subText: e.typing.title,
            avatar: e.typing.avatar
          }
        }, null, 8, ["message"])) : u("", !0),
        g(v, null, {
          default: S(() => [
            s(_) ? (l(), f(Te, {
              key: 0,
              ref_key: "keyboardRef",
              ref: R,
              class: "message-feed__keyboard",
              keyboard: e.objects[e.objects.length - 1].keyboard,
              align: e.keyboardAlign,
              onAction: s(ee)
            }, null, 8, ["keyboard", "align", "onAction"])) : u("", !0)
          ]),
          _: 1
        }),
        e.feedKeyboards && e.feedKeyboards.length > 0 ? (l(), f(Ae, {
          key: 1,
          buttons: e.feedKeyboards,
          align: e.feedKeyboardAlign,
          onAction: s(te)
        }, null, 8, ["buttons", "align", "onAction"])) : u("", !0)
      ], 44, We)) : (l(), c("div", {
        key: 1,
        ref_key: "refFeed",
        ref: r,
        class: "message-feed",
        style: O({ backgroundImage: `url(${F.value})` })
      }, [
        h("div", Ue, [
          j(o.$slots, "empty-feed", {}, void 0, !0)
        ])
      ], 4)),
      g(v, null, {
        default: S(() => [
          s(L) ? (l(), c("button", {
            key: 0,
            class: "message-feed__button-down",
            onClick: ce
          }, [
            e.buttonParams ? (l(), c("div", He, Re(e.buttonParams.unreadAmount), 1)) : u("", !0),
            n[3] || (n[3] = h("span", { class: "pi pi-angle-down message-feed__icon-down" }, null, -1))
          ])) : u("", !0)
        ]),
        _: 1
      }),
      s(A)().reply ? (l(), f(Me, {
        key: 2,
        to: "#chat-input-reply-line-" + s(y)
      }, [
        g(Ie, {
          class: "chat-input-reply",
          message: s(A)().reply,
          onReset: s(X)
        }, null, 8, ["message", "onReset"])
      ], 8, ["to"])) : u("", !0)
    ]));
  }
});
export {
  ft as default
};
