import { ref as d, computed as i, watch as H, onMounted as Ue, onUnmounted as Ge, createElementBlock as a, openBlock as s, createCommentVNode as f, unref as n, Fragment as A, renderList as W, normalizeClass as v, createBlock as y, createVNode as B, createElementVNode as c, withCtx as U, resolveDynamicComponent as I, toDisplayString as P, normalizeStyle as Je, nextTick as ve } from "vue";
import G from "../../1_atoms/Tooltip/Tooltip.vue.js";
import { useCommunicationChannels as Ke } from "./composables/useCommunicationChannels.js";
import { useCommunicationMenu as Qe } from "./composables/useCommunicationMenu.js";
import { useCommunicationAttributes as Xe, isAttributeBlocked as Ye, getAttributeStatusClass as ye, isAttributeConfirming as Ce } from "./composables/useCommunicationAttributes.js";
import { useCommunicationActions as Ze } from "./composables/useCommunicationActions.js";
import { useCommunicationSubMenu as et } from "./composables/useCommunicationSubMenu.js";
import { useCommunicationDialogSync as tt } from "./composables/useCommunicationDialogSync.js";
import { useCommunicationPlaceholder as nt } from "./composables/useCommunicationPlaceholder.js";
import be from "./CommunicationPanelAttributeIndicator.vue.js";
import ot from "./icons/CommunicationPanelCheckIcon.vue.js";
/* empty css                                           */
import st from "../../../_virtual/_plugin-vue_export-helper.js";
/* empty css                        */
const lt = ["onClick", "onMouseenter"], at = { class: "channel-icon" }, it = { class: "channel-icon" }, ut = {
  key: 1,
  class: "attributes-menu"
}, rt = {
  key: 0,
  class: "empty-channels-placeholder"
}, ct = ["data-attribute-status", "onMouseenter", "onClick"], dt = { class: "attribute-info" }, ft = { class: "attribute-value" }, mt = { class: "menu-icon" }, pt = {
  key: 0,
  class: "menu-icon-arrow"
}, ht = ["data-attribute-status", "onMouseenter", "onClick"], vt = { class: "attribute-info" }, yt = { class: "attribute-value" }, Ct = { class: "menu-icon" }, bt = {
  key: 0,
  class: "menu-icon-arrow"
}, gt = ["onClick"], kt = {
  key: 0,
  class: "selected-indicator"
}, At = { class: "sub-menu-title" }, It = {
  __name: "CommunicationPanel",
  props: {
    contactAttributes: {
      type: Array,
      required: !0,
      default: () => []
    },
    channels: {
      type: Array,
      required: !0,
      default: () => []
    },
    selectedDialog: {
      type: Object,
      required: !1,
      default: null
    },
    channelTooltips: {
      type: Object,
      required: !1,
      default: () => ({})
    },
    attributeTooltips: {
      type: Object,
      required: !1,
      default: () => ({})
    },
    /** Подсказки для галочки / спиннера: selected, confirmed, confirming, blocked */
    attributeIndicatorTooltips: {
      type: Object,
      required: !1,
      default: () => ({})
    },
    messages: {
      type: Array,
      required: !1,
      default: () => []
    },
    selectedChat: {
      type: Object,
      required: !1,
      default: null
    },
    isNewDialog: {
      type: Boolean,
      required: !1,
      default: !1
    },
    showChannelIcons: {
      type: Boolean,
      required: !1,
      default: !1
    },
    emptyChannelsPlaceholder: {
      type: Object,
      required: !1,
      default: () => ({})
    },
    /** Id атрибута в процессе подтверждения (спиннер вместо галочки). Задаёт родитель на время запроса. */
    confirmingAttributeId: {
      type: String,
      required: !1,
      default: null
    },
    /** Id атрибутов, заблокированных после неудачного подтверждения */
    blockedAttributeIds: {
      type: Array,
      required: !1,
      default: () => []
    },
    /**
     * Порядок кнопок каналов в панели.
     * По умолчанию: max → telegram → whatsapp → sms → phone.
     */
    channelOrder: {
      type: Array,
      required: !1,
      default: void 0
    },
    /**
     * Типы каналов для отображения (обычно с бэка — доступные пользователю).
     * Если не задан — показываются все поддерживаемые типы.
     */
    visibleChannelTypes: {
      type: Array,
      required: !1,
      default: void 0
    }
  },
  emits: [
    "select-attribute-channel",
    "confirm-attribute",
    "phone-call",
    "reset-blocked-attributes"
  ],
  setup(T, { emit: ge }) {
    const l = T, J = ge, E = d(null), ke = d(null), N = d(null), z = d(null), _ = d(null), $ = d({}), C = d(!1), M = d(null), m = d(null), S = d(null), b = i(
      () => l.confirmingAttributeId ?? S.value
    ), j = i(() => l.blockedAttributeIds ?? []), g = (t) => Ye(t, j.value), F = i(() => l.channels ?? []), Ae = i(() => l.channelOrder), Ie = i(() => l.visibleChannelTypes), Te = i(() => l.channelTooltips ?? {}), _e = i(() => l.attributeTooltips ?? {}), K = i(() => l.attributeIndicatorTooltips ?? {}), Q = i(() => l.messages ?? []), Me = i(() => l.selectedChat ?? null), X = i(() => l.isNewDialog ?? !1), Se = i(() => {
      var t;
      return ((t = l.selectedDialog) == null ? void 0 : t.channelId) ?? null;
    }), Y = (t) => Se.value === t, we = i(() => {
      var t;
      return ((t = l.selectedDialog) == null ? void 0 : t.attributeId) ?? null;
    }), w = (t) => {
      const o = we.value;
      if (!o || !t)
        return !1;
      const e = t.id ?? t.attributeId;
      return o === e;
    }, Z = (t) => {
      const o = _e.value, e = (t == null ? void 0 : t.attributeId) ?? (t == null ? void 0 : t.id);
      if (e != null) {
        const u = o[String(e)];
        if (u)
          return u;
      }
      return t != null && t.value ? o[String(t.value)] ?? "" : "";
    }, Re = (t) => !!Z(t), {
      panelChannelTypes: De,
      channelsTypes: ee,
      getTooltipText: qe,
      getChannelTypeFromId: xe,
      hasMultipleChannels: k,
      isChannelActive: R,
      getSingleChannelForType: Oe,
      getMenuChannelIconComponentForChannelId: Be,
      getSingleMenuChannelIconComponent: te,
      getAvailableChannels: ne
    } = Ke({
      channels: F,
      channelTooltips: Te,
      channelOrder: Ae,
      visibleChannelTypes: Ie,
      selectedChannelType: _
    }), {
      activeChannelType: r,
      hoveredChannel: D,
      showMenu: q,
      showSubMenu: L,
      handleChannelClick: Pe,
      closeMenu: oe,
      handleClickOutside: se
    } = Qe({
      panelRef: E,
      selectedChannelType: _,
      frozenAttribute: z
    }), V = i(() => l.contactAttributes ?? []), le = (t) => {
      var p;
      if (!t || !Q.value) return !0;
      const o = (p = Me.value) == null ? void 0 : p.chatId;
      return o ? !Q.value.filter(
        (h) => {
          var he;
          return h.chatId === o && h.dialogId === ((he = l.selectedDialog) == null ? void 0 : he.dialogId);
        }
      ).some(
        (h) => h.type !== "message.system" && h.type !== "message.delimiter" && h.type !== "system" && h.type !== "system_message" && h.type !== "notification"
      ) : !0;
    }, ae = () => {
      x(), C.value = !0, ve(() => {
        const t = Array.isArray(m.value) ? m.value[0] : m.value;
        t && typeof t.startAutoShow == "function" ? t.startAutoShow() : console.log("startAutoShow method not found on tooltipRef");
      }), M.value = setTimeout(() => {
        C.value = !1;
      }, 5e3);
    }, x = () => {
      if (M.value && (clearTimeout(M.value), M.value = null), m.value) {
        const t = Array.isArray(m.value) ? m.value[0] : m.value;
        t && typeof t.clearAutoTimer == "function" && t.clearAutoTimer();
      }
      C.value = !1;
    }, {
      organizedContactAttributes: ie,
      organizeContactAttributes: Ee,
      isAttributeFrozen: ue
    } = Xe({
      contactAttributes: V,
      panelChannelTypes: De,
      frozenAttribute: z
    }), {
      handleAttributeClick: Ne,
      selectChannel: ze,
      availableChannels: $e
    } = Ze({
      activeChannelType: r,
      channels: F,
      selectedChannel: $,
      selectedChannelType: _,
      hoveredAttribute: N,
      confirmingAttributeId: S,
      isAttributeBlocked: g,
      closeMenu: oe,
      hasMultipleChannels: k,
      getSingleChannelForType: Oe,
      getAvailableChannels: ne,
      isChannelEmpty: le,
      isNewDialog: X,
      showDefaultChannelTooltipWithTimer: ae,
      clearDefaultChannelTooltip: x,
      emit: J
    }), {
      subMenuTop: je,
      handleAttributeMouseEnter: Fe,
      handleAttributeMouseLeave: O,
      keepSubMenuOpen: re,
      closeSubMenu: ce,
      alignSubMenuWithTarget: Le
    } = et({
      activeChannelType: r,
      showSubMenu: L,
      frozenAttribute: z,
      hoveredAttribute: N,
      hasMultipleChannels: k,
      isAttributeBlocked: g
    }), Ve = (t) => {
      q.value && r.value === t || J("reset-blocked-attributes"), Pe(t);
    }, de = (t) => {
      g(t) || Ne(t);
    };
    tt({
      selectedChannelType: _,
      selectedChannel: $,
      channels: F,
      selectedDialog: i(() => l.selectedDialog ?? null),
      isChannelEmpty: le,
      isNewDialog: X,
      showDefaultChannelTooltipWithTimer: ae,
      clearDefaultChannelTooltip: x
    });
    const {
      emptyChannelsPlaceholderText: He,
      shouldShowEmptyChannelsPlaceholder: fe
    } = nt({
      showMenu: q,
      activeChannelType: r,
      emptyChannelsPlaceholder: i(() => l.emptyChannelsPlaceholder ?? {}),
      getAvailableChannels: ne,
      organizedContactAttributes: ie
    }), me = i(
      () => $e()
    ), We = i(
      () => L.value && N.value && me.value.length > 0 && r.value !== "phone" && k(r.value)
    ), pe = async (t, o) => {
      const e = Fe(t, o.currentTarget);
      await ve(), e instanceof HTMLElement && Le(E, e);
    };
    return H(() => l.confirmingAttributeId, (t) => {
      t || (S.value = null);
    }), H(V, () => {
      const t = b.value;
      if (!t)
        return;
      const o = V.value.find((e) => e.id === t);
      (o == null ? void 0 : o.status) === "confirmed" && (S.value = null, oe());
    }, { deep: !0 }), H(() => l.selectedDialog, () => {
    }, { deep: !0 }), Ue(() => {
      document.addEventListener("click", se), Ee();
    }), Ge(() => {
      document.removeEventListener("click", se), x();
    }), (t, o) => (s(), a("div", {
      ref_key: "panelRef",
      ref: E,
      class: "communication-panel"
    }, [
      n(ee).length ? (s(), a("div", {
        key: 0,
        ref_key: "channelsPanelRef",
        ref: ke,
        class: "channels-panel"
      }, [
        (s(!0), a(A, null, W(n(ee), (e) => {
          var u;
          return s(), a("button", {
            key: e.type,
            class: v(["channel-btn", {
              active: n(R)(e.type),
              hover: n(D) === e.type && !n(R)(e.type) || n(D) === e.type && n(R)(e.type),
              menuOpen: n(q) && n(r) === e.type
            }]),
            onClick: (p) => Ve(e.type),
            onMouseenter: (p) => D.value = e.type,
            onMouseleave: o[0] || (o[0] = (p) => D.value = null)
          }, [
            n(R)(e.type) ? (s(), a(A, { key: 0 }, [
              B(G, {
                ref_for: !0,
                ref: (p) => {
                  p && (m.value = p);
                },
                text: C.value ? "Выбран канал по умолчанию, можно изменить в настройках профиля" : (u = $.value) == null ? void 0 : u.title,
                position: "bottom-left",
                offset: 8,
                trigger: C.value ? "auto" : "hover",
                "auto-show-duration": C.value ? 5e3 : 0
              }, {
                default: U(() => [
                  c("span", at, [
                    (s(), y(I(e.component)))
                  ])
                ]),
                _: 2
              }, 1032, ["text", "trigger", "auto-show-duration"]),
              o[5] || (o[5] = c("span", { class: "active-indicator" }, null, -1))
            ], 64)) : (s(), y(G, {
              key: 1,
              text: n(qe)(e.type),
              position: "bottom-left",
              offset: 8
            }, {
              default: U(() => [
                c("span", it, [
                  (s(), y(I(e.component)))
                ])
              ]),
              _: 2
            }, 1032, ["text"]))
          ], 42, lt);
        }), 128))
      ], 512)) : f("", !0),
      n(q) && n(r) ? (s(), a("div", ut, [
        n(fe) ? (s(), a("div", rt, P(n(He)), 1)) : f("", !0),
        n(fe) ? f("", !0) : (s(!0), a(A, { key: 1 }, W(n(ie)[n(r)], (e) => (s(), a(A, {
          key: e.attributeId
        }, [
          Re(e) ? (s(), y(G, {
            key: 0,
            text: Z(e),
            position: "bottom-left",
            offset: 8
          }, {
            default: U(() => [
              c("div", {
                class: v(["attribute-item", n(ye)(e), {
                  "frozen-hover": n(ue)(e),
                  selected: w(e),
                  confirming: n(Ce)(e, b.value),
                  blocked: g(e)
                }]),
                "data-attribute-status": e.status,
                onMouseenter: (u) => pe(e, u),
                onMouseleave: o[1] || (o[1] = (...u) => n(O) && n(O)(...u)),
                onClick: (u) => de(e)
              }, [
                c("div", dt, [
                  B(be, {
                    attribute: e,
                    "is-selected": w(e),
                    "confirming-attribute-id": b.value,
                    "blocked-attribute-ids": j.value,
                    "indicator-tooltips": K.value
                  }, null, 8, ["attribute", "is-selected", "confirming-attribute-id", "blocked-attribute-ids", "indicator-tooltips"]),
                  c("span", ft, P(e.value), 1)
                ]),
                c("span", mt, [
                  n(k)(n(r)) ? (s(), a("span", pt)) : T.showChannelIcons ? (s(), a("span", {
                    key: 1,
                    class: v(["channel-icon-small", { "menu-icon-grey": n(r) !== "sms" }])
                  }, [
                    (s(), y(I(n(te)(n(r)))))
                  ], 2)) : f("", !0)
                ])
              ], 42, ct)
            ]),
            _: 2
          }, 1032, ["text"])) : (s(), a("div", {
            key: 1,
            class: v(["attribute-item", n(ye)(e), {
              "frozen-hover": n(ue)(e),
              selected: w(e),
              confirming: n(Ce)(e, b.value),
              blocked: g(e)
            }]),
            "data-attribute-status": e.status,
            onMouseenter: (u) => pe(e, u),
            onMouseleave: o[2] || (o[2] = (...u) => n(O) && n(O)(...u)),
            onClick: (u) => de(e)
          }, [
            c("div", vt, [
              B(be, {
                attribute: e,
                "is-selected": w(e),
                "confirming-attribute-id": b.value,
                "blocked-attribute-ids": j.value,
                "indicator-tooltips": K.value
              }, null, 8, ["attribute", "is-selected", "confirming-attribute-id", "blocked-attribute-ids", "indicator-tooltips"]),
              c("span", yt, P(e.value), 1)
            ]),
            c("span", Ct, [
              n(k)(n(r)) ? (s(), a("span", bt)) : T.showChannelIcons ? (s(), a("span", {
                key: 1,
                class: v(["channel-icon-small", { "menu-icon-grey": n(r) !== "sms" }])
              }, [
                (s(), y(I(n(te)(n(r)))))
              ], 2)) : f("", !0)
            ])
          ], 42, ht))
        ], 64))), 128)),
        n(L) && We.value ? (s(), a("div", {
          key: 2,
          class: "sub-menu left",
          style: Je({ top: n(je) + "px" }),
          onMouseenter: o[3] || (o[3] = (...e) => n(re) && n(re)(...e)),
          onMouseleave: o[4] || (o[4] = (...e) => n(ce) && n(ce)(...e))
        }, [
          o[6] || (o[6] = c("div", { class: "sub-menu-header" }, " Канал связи ", -1)),
          (s(!0), a(A, null, W(me.value, (e) => (s(), a("div", {
            key: e.channelId,
            class: v(["sub-menu-item", { selected: Y(e.channelId) }]),
            onClick: (u) => n(ze)(e.channelId)
          }, [
            Y(e.channelId) ? (s(), a("span", kt, [
              B(n(ot))
            ])) : f("", !0),
            c("span", At, P(e.title || e.channelId), 1),
            T.showChannelIcons ? (s(), a("span", {
              key: 1,
              class: v(["sub-menu-icon", { "menu-icon-grey": n(xe)(e.channelId) !== "sms" }])
            }, [
              (s(), y(I(n(Be)(e.channelId))))
            ], 2)) : f("", !0)
          ], 10, gt))), 128))
        ], 36)) : f("", !0)
      ])) : f("", !0)
    ], 512));
  }
}, zt = /* @__PURE__ */ st(It, [["__scopeId", "data-v-cae081e6"]]);
export {
  zt as default
};
