import { u as j } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a524.js";
import { r as Z } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a523.js";
import {
  i as Q,
  b as X,
  P as T,
  c as Y,
  U as x,
  g as ee,
  u as k,
  d as te,
  e as D,
  V as C,
} from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a54.js";
import {
  i as ae,
  u as w,
  S as U,
  a as M,
  b as S,
  m as G,
  C as oe,
  c as se,
  d as A,
  e as R,
  f as re,
  g as ie,
  h as ne,
  j as ce,
  k as de,
  l as ue,
  n as le,
  o as pe,
  p as me,
  q as F,
  r as fe,
  A as ge,
  t as he,
  s as be,
  v as _e,
  w as we,
} from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a525.js";
import {
  u as q,
  i as Se,
} from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a526.js";
import {
  i as ve,
  a as ye,
} from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a527.js";
import { g as Ce } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a528.js";
import {
  l as Ae,
  g as Ee,
} from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a529.js";
import { i as Te } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a530.js";
import { i as Le } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a531.js";
import { i as ke } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a532.js";
import { i as De } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a533.js";
import {
  u as _,
  V as h,
  z as b,
  O as E,
} from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a55.js";
import { i as Ue } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a534.js";
import { j as g } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a53.js";
import {
  N as Me,
  t as v,
} from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a58.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a52.js";
import { u as Re } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a535.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a536.js";
import { s as Fe } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a537.js";
import { a as I } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a56.js";
import {
  d as Ie,
  S as y,
} from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a538.js";
import { u as ze } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a539.js";
import { n as $e } from "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a540.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a541.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a5.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a57.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a59.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a510.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a520.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a542.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a543.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a544.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a545.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a546.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a547.js";
import "./v_7_4_3_73_d3c9bac7-c74e-47f6-ac42-499f067843a548.js";
const Pe = () => {
    const t = document.createElement("script");
    ((t.src = chrome.runtime.getURL("whatsapp/wpp/index.js")),
      (document.head || document.documentElement).appendChild(t),
      (t.onload = function () {
        t.remove();
      }));
    const e = document.createElement("script");
    ((e.src = chrome.runtime.getURL("whatsapp/wpp_module/index.js")),
      (document.head || document.documentElement).appendChild(e),
      (e.onload = function () {
        (e.remove(),
          window.postMessage(
            {
              origem: "content",
              action: "chrome_store_data",
              payload: { extension_id: chrome.runtime.id },
            },
            "*",
          ));
      }));
    const a = document.createElement("link");
    ((a.rel = "stylesheet"),
      (a.href = chrome.runtime.getURL("whatsapp/style/index.css")),
      (document.head || document.documentElement).appendChild(a));
  },
  je = (t, e, a = 8e3) => {
    const s = Date.now(),
      o = () => {
        document.querySelector(t)
          ? e()
          : Date.now() - s >= a
            ? (console.error(
                `Erro: O seletor "${t}" não foi encontrado dentro do tempo limite.`,
              ),
              e())
            : setTimeout(o, 300);
      };
    o();
  };
je("#app .app-wrapper-web", () => {
  Pe();
});
const z = async (t) => {
    t.action === "module-error" &&
      (j.setState({ active: !0 }),
      Z.navigate({ to: "/error", search: { error: t.dados.code } }));
  },
  W = (t) => {
    z(t.data);
  };
window.addEventListener("message", W);
chrome.runtime.onMessage.addListener(z);
window.addEventListener("beforeunload", () => {
  (chrome.runtime.onMessage.removeListener(z),
    window.removeEventListener("message", W));
});
Q();
X();
ae();
function xe(t) {
  if (t.id.fromMe) return;
  const { FollowUp: e, removeChatFromFollowUp: a } = w.getState();
  for (let s of e)
    if (s?.regras?.cancelAfterChat?.propriedades?.active) {
      for (let o of s.funil.abas) a(s.id, o.id, t.id.remote._serialized, "tab");
      for (let o of s.funil.etiquetas)
        a(s.id, o.id, t.id.default_remote._serialized, "label");
    }
}
const Ge = (t) => {
  const e = t.data,
    { type: a, chat: s, labels: o } = e;
  if (!s || !s.id) return;
  const r = { ...s, id: T(s.id._serialized) },
    i = w.getState().FollowUp.filter((d) => d.active);
  if (i.length !== 0) {
    if (a === "add") {
      We(r, o, i);
      const d = i.filter((n) => n.acionamento.type === "timing");
      o.forEach((n) => {
        Ke(r, n.id, d);
      });
    } else if (a === "remove") {
      qe(r, o, i);
      const d = i.filter((n) => n.acionamento.type === "timing");
      o.forEach((n) => {
        Ne(r, n.id, d);
      });
    }
  }
};
function qe(t, e, a) {
  e.forEach((s) => {
    a.filter((r) => {
      const i = r.funil.etiquetas.some((c) => c.id === s.id),
        d = t.id.endsWith("@g.us"),
        n = r.regras?.responderGrupos?.propriedades?.active !== !1;
      return i && r.acionamento.type === "dispararAoSair" && (!d || n);
    }).forEach((r) => {
      try {
        U(t.id, r);
      } catch (i) {
        console.error(
          `❌ Erro ao disparar follow-up: ${r.id} para o chat: ${t.id}`,
          i,
        );
      }
    });
  });
}
function We(t, e, a) {
  e.forEach((s) => {
    a.filter((r) => {
      const i = r.funil.etiquetas.some((c) => c.id === s.id),
        d = t.id.endsWith("@g.us"),
        n = r.regras?.responderGrupos?.propriedades?.active !== !1;
      return i && r.acionamento.type === "dispararAoEntrar" && (!d || n);
    }).forEach((r) => {
      try {
        U(t.id, r);
      } catch (i) {
        console.error(
          `❌ Erro ao disparar follow-up: ${r.id} para o chat: ${t.id}`,
          i,
        );
      }
    });
  });
}
function Ke(t, e, a) {
  a.filter((o) => {
    const r = o.funil.etiquetas.some((n) => n.id === e),
      i = t.id.endsWith("@g.us"),
      d = o.regras?.responderGrupos?.propriedades?.active !== !1;
    return r && (!i || d);
  }).forEach((o) => {
    w.getState().addChatToFollowUp(o.id, e, t, "label");
  });
}
function Ne(t, e, a) {
  a.filter((o) => {
    const r = o.funil.etiquetas.some((n) => n.id === e),
      i = t.id.endsWith("@g.us"),
      d = o.regras?.responderGrupos?.propriedades?.active !== !1;
    return r && (!i || d);
  }).forEach((o) => {
    w.getState().removeChatFromFollowUp(o.id, e, t.id, "label");
  });
}
function Be(t, e) {
  const a = [],
    s = [],
    o = new Set(e.flatMap((n) => n.chats.map((c) => `${c.id}|${n.id}`))),
    r = new Set(t.flatMap((n) => n.chats.map((c) => `${c.id}|${n.id}`))),
    i = new Map(
      e.flatMap((n) =>
        n.chats.map((c) => [`${c.id}|${n.id}`, { chat: c, tabId: n.id }]),
      ),
    ),
    d = new Map(
      t.flatMap((n) =>
        n.chats.map((c) => [`${c.id}|${n.id}`, { chat: c, tabId: n.id }]),
      ),
    );
  for (const n of r)
    if (!o.has(n)) {
      const c = d.get(n);
      c && a.push({ ...c, chat: { ...c.chat, id: T(c.chat.id) } });
    }
  for (const n of o)
    if (!r.has(n)) {
      const c = i.get(n);
      c && s.push({ ...c, chat: { ...c.chat, id: T(c.chat.id) } });
    }
  return { chatsAdded: a, chatsRemoved: s };
}
async function $(t, e, a) {
  for (const { chat: s, tabId: o } of t) {
    const r = e.filter((i) => {
      const d = i.funil.abas.some((m) => m.id === o),
        n = s.id.endsWith("@g.us"),
        c = i.regras?.responderGrupos?.propriedades?.active !== !1;
      return d && i.acionamento.type === a && (!n || c);
    });
    for (const i of r)
      try {
        await U(s.id, i);
      } catch (d) {
        console.error(
          `❌ Erro ao disparar follow-up: ${i.id} para chat: ${s.id}`,
          d,
        );
      }
  }
}
function Oe(t, e) {
  t.forEach(({ chat: a, tabId: s }) => {
    e.filter((r) => {
      const i = r.funil.abas.some((c) => c.id === s),
        d = a.id.endsWith("@g.us"),
        n = r.regras?.responderGrupos?.propriedades?.active !== !1;
      return i && r.acionamento.type === "timing" && (!d || n);
    }).forEach((r) => {
      w.getState().addChatToFollowUp(r.id, s, a, "tab");
    });
  });
}
function Ve(t, e) {
  t.forEach(({ chat: a, tabId: s }) => {
    e.filter((r) => {
      const i = r.funil.abas.some((c) => c.id === s),
        d = a.id.endsWith("@g.us"),
        n = r.regras?.responderGrupos?.propriedades?.active !== !1;
      return i && r.acionamento.type === "timing" && (!d || n);
    }).forEach((r) => {
      w.getState().removeChatFromFollowUp(r.id, s, a.id, "tab");
    });
  });
}
function He() {
  return M.subscribe(async (e, a) => {
    if (!e.userTabs || !w.getState().initSubscribeUserTabs) return;
    const s = e.userTabs || [],
      o = a.userTabs || [],
      r = w.getState().FollowUp.filter((l) => l.active);
    if (r.length === 0) return;
    const i = o.filter((l) => !s.some((u) => u.id === l.id)),
      { chatsAdded: d, chatsRemoved: n } = Be(s, o),
      c = i.flatMap((l) => l.chats.map((u) => ({ chat: u, tabId: l.id }))),
      m = n.filter((l) => !c.some((u) => u.chat.id === l.chat.id));
    if (d.length > 0) {
      const l = r.filter((p) => p.acionamento.type === "dispararAoEntrar"),
        u = r.filter((p) => p.acionamento.type === "timing");
      (l.length > 0 && (await $(d, l, "dispararAoEntrar")),
        u.length > 0 && Oe(d, u));
    }
    if (m.length > 0) {
      const l = r.filter((f) => f.acionamento.type === "dispararAoSair"),
        u = m.filter((f) => !i.some((J) => J.id === f.tabId));
      l.length > 0 && u.length > 0 && (await $(u, l, "dispararAoSair"));
      const p = r.filter((f) => f.acionamento.type === "timing");
      p.length > 0 && Ve(m, p);
    }
  });
}
const Je = () =>
    new Promise((t) => {
      const e = S.subscribe((a) => {
        a.is_load && (e(), t(a.assinatura));
      });
    }),
  Ze = () =>
    new Promise((t) => {
      const e = _.subscribe((a) => {
        a.is_load &&
          (!a.whatsappID ||
            !String(a.whatsappID).trim() ||
            (e(), t(a.whatsappID)));
      });
    }),
  Qe = () =>
    new Promise((t) => {
      const e = h.subscribe((a) => {
        a.session.is_load &&
          a.session.is_auth &&
          (!a.user?.bearer_token ||
            !String(a.user.bearer_token).trim() ||
            (e(), t()));
      });
    });
async function L() {
  if (!S.getState().is_load) return;
  const { assinatura: t } = S.getState();
  if (!t.multiAtendimento) return;
  const { is_load: e, whatsappID: a } = _.getState();
  if (!e) return;
  const s = String(a ?? "").trim();
  if (!s) return;
  const { user: o, session: r } = h.getState();
  if (
    !r.is_load ||
    !r.is_auth ||
    !String(o?.bearer_token ?? "").trim() ||
    !String(o?.user_id ?? "").trim()
  )
    return;
  const { active: i, socket: d, connect: n } = G.getState();
  (i && d?.connected) || (await n(s));
}
async function Xe() {
  (await Promise.all([Je(), Ze()]), await Qe(), await L());
}
function Ye() {
  let t = {
    multi: S.getState().assinatura.multiAtendimento,
    customizeKey: "",
    loginKey: "",
  };
  const e = () => {
      const o = _.getState();
      return `${o.is_load}:${o.whatsappID}`;
    },
    a = () => {
      const o = h.getState();
      return `${o.session.is_load}:${o.session.is_auth}:${o.user?.bearer_token ?? ""}`;
    },
    s = () => {
      if (!S.getState().is_load) return;
      const o = S.getState().assinatura.multiAtendimento,
        r = e(),
        i = a();
      (o === t.multi && r === t.customizeKey && i === t.loginKey) ||
        ((t = { multi: o, customizeKey: r, loginKey: i }), L());
    };
  (S.subscribe(s), _.subscribe(s), h.subscribe(s), L());
}
Ye();
const K = [
  "chat",
  "image",
  "document",
  "video",
  "ptt",
  "vcard",
  "sticker",
  "poll_creation",
  "location",
  "list_response",
  "call_log",
];
function et(t) {
  if (!t.type || t.id.fromMe || !K.includes(t.type) || tt(t.t ?? 0)) return;
  const { autoAtendimento: e } = q.getState();
  e.forEach((a) => {
    a.active && at(t, a);
  });
}
const tt = (t) => {
    const e = t.toString().length === 10 ? t * 1e3 : t,
      s = Date.now() - e,
      o = 300 * 1e3;
    return s > o;
  },
  at = async (t, e) => {
    const { getUserAbasTam: a, userTabs: s } = M.getState(),
      o = Y.getState().crm,
      { isBusiness: r } = _.getState();
    if (!e.regras.responderGrupos.propriedades.active && t.author) return;
    const i = await b.Chat("getActiveChat", "@");
    if (
      (e.regras.responderChatAtivo.propriedades.active &&
        i === t.id.default_remote._serialized) ||
      (e?.regras?.responderChatArquivado?.propriedades?.active === !0 &&
        (await b.Chat("get", t.id.default_remote._serialized))?.archive)
    )
      return;
    const d = new Date().getDay(),
      n = [
        "domingo",
        "segunda",
        "terca",
        "quarta",
        "quinta",
        "sexta",
        "sabado",
      ];
    if (
      "domingo" in e.regras.responderDias.propriedades &&
      e.regras.responderDias.propriedades.active
    ) {
      const m = n[d],
        {
          horaInicio: l,
          horaFim: u,
          periodoAtivacao: p,
          active: f,
        } = e.regras.responderDias.propriedades[m] || {};
      if (!l || !u || !f || (p && !x.isValidInterval(l, u))) return;
    }
    const { labels: c } = await b.Chat("get", t.id.default_remote._serialized);
    if (
      !(
        r &&
        e.regras?.notResponderChatEtiquetado?.propriedades?.active === !0 &&
        c.length > 0
      ) &&
      !(
        r &&
        e.regras?.notResponderEtiqueta?.propriedades?.active === !0 &&
        e.regras.notResponderEtiqueta.propriedades.labelID.some((u) =>
          c.includes(u),
        )
      ) &&
      !(
        r &&
        e?.regras?.responderEtiqueta?.propriedades?.active === !0 &&
        !e.regras.responderEtiqueta.propriedades.labelID.some((u) =>
          c.includes(u),
        )
      ) &&
      !(
        e?.regras?.notResponderChatCRM?.propriedades?.active === !0 &&
        a(t.id.remote.user) + ee(t.id.remote.user) !== 0
      )
    ) {
      if (e?.regras?.notResponderCRM?.propriedades?.active === !0) {
        const m = e.regras.notResponderCRM.propriedades.crm;
        let l = !0;
        for (const u of m)
          if (u.crmID === "abas")
            s.find((p) => p.id === u.abaID)?.chats.forEach((p) => {
              p.id === t.id.remote.user && (l = !1);
            });
          else
            for (const p of o)
              p.id === u.crmID &&
                p.list
                  .find((f) => f.id === u.abaID)
                  ?.chats.forEach((f) => {
                    f.id === t.id.remote.user && (l = !1);
                  });
        if (!l) return;
      }
      if (e?.regras?.responderCRM?.propriedades?.active === !0) {
        const m = e.regras.responderCRM.propriedades.crm;
        let l = !1;
        for (const u of m)
          if (u.crmID === "abas")
            s.find((p) => p.id === u.abaID)?.chats.forEach((p) => {
              p.id === t.id.remote.user && (l = !0);
            });
          else
            for (const p of o)
              p.id === u.crmID &&
                p.list
                  .find((f) => f.id === u.abaID)
                  ?.chats.forEach((f) => {
                    f.id === t.id.remote.user && (l = !0);
                  });
        if (!l) return;
      }
      ot(t, e);
    }
  },
  ot = async (t, e) => {
    const a = k.getState().language,
      s = te(),
      { updateUsedLenght: o } = q.getState(),
      r = async () => {
        if ((await oe("autoatendimento", !0)) === !0) {
          Me("autoAtendimento", a.btnPremium, s);
          return;
        }
        const i = e.regras.assinatura.propriedades;
        (se(
          t.id.remote._serialized,
          e.acao,
          {
            desativar: i.active ? i.desativarAss : !1,
            personalizar: i.active ? i.persAss.active : !1,
            nome: i.persAss.nameAss,
          },
          "useAcaoAutoAtendimento",
        ),
          o(e.id),
          A.getState().dispartWebhook(t.id.remote.user, "autoAtendimento", {
            id: e.id,
            name: e.nome,
            usedLenght: e.usedLenght + 1,
          }));
      };
    for (const i of e.acionamento) {
      if (
        i.type === "message_Received" &&
        (i.text == t.body || i.text == t.caption)
      ) {
        r();
        break;
      }
      if (i.type === "keyword") {
        let d = !1;
        if (
          (i.chaves.forEach((n) => {
            (t.type === "chat" || t.type === "list_response") &&
              t.body.toLowerCase().includes(n.toLowerCase()) &&
              (d = !0);
          }),
          d)
        ) {
          r();
          break;
        }
      }
      if (i.type === "day_Message") {
        const d = (
          await b.Chat("getMessages", {
            id: t.id.default_remote._serialized,
            quant: 5,
          })
        ).reverse();
        d.shift();
        const n = d.find((c) => c.id.fromMe === !1 && K.includes(c.type));
        if (n) {
          const c = parseInt(n.t.toString() + "000");
          if (!x.isDataDeHoje(c)) {
            r();
            break;
          }
        }
      }
      if (
        i.type === "customer_Message" &&
        (
          await b.Chat("getMessages", {
            id: t.id.default_remote._serialized,
            quant: 5,
          })
        ).filter(
          (c) =>
            c.type !== "e2e_notification" && c.type !== "notification_template",
        ).length === 1
      ) {
        r();
        break;
      }
    }
  },
  st = E.on("chat.new_message", (t) => {
    if (
      !R.getState().domSelector.disabled_wait_sync &&
      !_.getState().isSynchronized
    )
      return;
    const e = t.data;
    if (
      (t.author && (e.author = t.author),
      t.msgID && (e.id = t.msgID),
      et(e),
      Ae({ msg: e, manualActivation: null }),
      xe(e),
      A.getState().dispartWebhook(e.id.remote.user, "messages", e),
      e.ctwaContext)
    ) {
      const a = e.from.toString();
      A.getState().dispartWebhook(a.replace(/@c\.us/g, ""), "metaAds");
    }
    (e.id.fromMe &&
      e.type === "chat" &&
      !e.author &&
      G.getState().filterAtendimento(e),
      M.getState().activeTab.type === "custom" &&
        setTimeout(() => {
          re();
        }, 1e3));
  });
window.addEventListener("beforeunload", () => {
  st();
});
const rt = E.on("chat.update_label", (t) => {
  if (
    !R.getState().domSelector.disabled_wait_sync &&
    !_.getState().isSynchronized
  )
    return;
  const e = t.data;
  !e.chat ||
    !e.chat.id ||
    ((e.chat.id = {
      server: "@" + e.chat.id.split("@")[1],
      user: e.chat.id.split("@")[0],
      _serialized: e.chat.id,
    }),
    A.getState().dispartWebhook(e.chat.id._serialized, "labels", {
      labels: e.labels,
      type: e.type,
    }),
    Re.getState().orderLabels(t.all_labels),
    Ge(t));
});
window.addEventListener("beforeunload", () => {
  rt();
});
ie();
Se();
ve();
ye();
Ce();
Ee();
Te();
ne();
Le();
ke();
ce();
de();
ue();
De();
le();
He();
pe();
me();
Ue();
Xe();
Fe({ useModal: F, useModalOptions: fe });
const it = () => {
    const { openModal: t } = F.getState(),
      { session: e, user: a } = h.getState();
    if (!e.is_auth) return null;
    switch (e.user_status) {
      case "test_finished":
        t({
          type: "not_structure",
          modal: g.jsx(y, { status: e.user_status }),
        });
        break;
      case "canceled":
        t({
          type: "not_structure",
          modal: g.jsx(y, { status: e.user_status }),
        });
        break;
      case "overdue":
        t({
          type: "not_structure",
          modal: g.jsx(y, { status: e.user_status }),
        });
        break;
      case "suspended":
        t({
          type: "not_structure",
          modal: g.jsx(y, { status: e.user_status }),
        });
        break;
      case "active":
        const s = Ie(a.user_premium.data_liberacao);
        s <= 15 &&
          t({
            type: "not_structure",
            modal: g.jsx(y, { status: e.user_status, days: s }),
          });
        break;
    }
  },
  nt = async () => {
    const { user: t } = await b.Conn("getMyDeviceId"),
      e = { dataUltimoLogin: new Date().toISOString(), whatsapp_plugin: t };
    await ze(e);
  },
  ct = async () => {
    await ge(10);
    const { user: t, session: e, auth_google: a } = h.getState(),
      { user: s } = await b.Conn("getMyDeviceId");
    return {
      user_id: t.user_id,
      name: t.name,
      email: t.email,
      email_auth: a.email_auth,
      whatsapp_plugin: s,
      user_premium: !!t.user_premium,
      user_status: e.user_status,
      navigator: navigator.userAgent,
      time: he(),
      dataCadastro: t.dataCadastro,
      whatsapp_registro: t.whatsapp_registro,
      path: t.path,
      afiliado: t.afiliado,
      campanhaID: t.campanhaID,
      cookies: t?.cookies,
    };
  },
  dt = async () => {
    const { getWebhooks: t } = D.getState(),
      e = t("login_plugin"),
      a = new Date().getTime(),
      s = localStorage.getItem("8fd5ad24df1e1b800d670e563b1b83591980060a=="),
      o = 24;
    if (s) {
      const r = new Date(s).getTime();
      if ((a - r) / (1e3 * 60 * 60) < o) return;
    }
    if (
      (localStorage.setItem(
        "8fd5ad24df1e1b800d670e563b1b83591980060a==",
        new Date().toISOString(),
      ),
      e.active)
    ) {
      const r = await ct();
      I.post(e.link, r, { headers: { "Content-Type": "application/json" } });
    }
    (it(), nt());
  },
  N = async (t = !1) => {
    const { language: e } = k.getState(),
      { config: a } = D.getState(),
      { login: s, logout: o, session: r, user: i } = h.getState(),
      { openRendertype: d } = F.getState();
    if (!r.is_auth) return null;
    try {
      const n = { email: i.email, access_token_plugin: i.access_token_plugin },
        c = (
          await I.post(
            // NOTA ET esta linea deslogea l usuario cada 5 minutos
            //`${C.backend_plugin}api/auth/validation/${a.chromeStoreID}`,
            `https://wabacrm.360digitals.com/api/auth/validation/${a.chromeStoreID}`,
            n,
            {
              headers: {
                "Content-Type": "application/json",
                accept: "application/json",
                "access-token": C.cript_key,
              },
            },
          )
        ).data;
      return c.success
        ? (s(c.user, c.auth_google, c.user_status), c.user)
        : c.msg_id === "invalid_token_in_validation"
          ? (d("access_duplicate"), v.error(e[c.msg_id]), o(), null)
          : c.msg_id === "login_other_white_label"
            ? (v.error(
                g.jsxs(g.Fragment, {
                  children: [
                    e.login_other_white_label,
                    g.jsxs("strong", { children: [c.origin_name, " "] }),
                    e.login_other_white_label_prt2,
                  ],
                }),
              ),
              o(),
              null)
            : (v.error(e[c.msg_id]), o(), null);
    } catch (n) {
      return (
        console.error("Error ao tentar validar o login do usuário", n),
        i
      );
    } finally {
      !t && dt();
    }
  },
  B = h.subscribe((t) => {
    t.session.is_load && (B(), t.session.is_auth && N());
  });
function O(t) {
  t.target.closest("section") && j.getState().setActive(!0);
}
function V() {
  document.addEventListener("click", O);
}
function ut() {
  document.removeEventListener("click", O);
}
const lt = h.getState();
lt.session?.is_auth || V();
const pt = h.subscribe((t, e) => {
    const a = e?.session?.is_auth,
      s = t.session?.is_auth;
    a !== s && (s ? ut() : V());
  }),
  H = async (t) => {
    t.action === "license_update" && N();
  };
chrome.runtime.onMessage.addListener(H);
window.addEventListener("beforeunload", () => {
  (B(), pt(), chrome.runtime.onMessage.removeListener(H));
});
(() => {
  const e = new URLSearchParams(window.location.search).get("color");
  if (!e) return;
  const a = decodeURIComponent(atob(e)),
    { light: s, dark: o } = JSON.parse(a);
  if (typeof s == "object" || typeof o == "object") {
    const r = `
            :root {
                --primaria: ${s.primaria} !important;
                --secundaria: ${s.secundaria} !important;
                --terciaria: ${s.terciaria} !important;
            }

            .dark {
                --primaria: ${o.primaria} !important;
                --secundaria: ${o.secundaria} !important;
                --terciaria: ${o.terciaria} !important;
            }
        `,
      i = "preview-theme",
      d = document.getElementById(i);
    d && d.remove();
    const n = document.createElement("style");
    ((n.id = i), (n.textContent = r), document.head.appendChild(n));
  }
})();
let P = !1;
const mt = E.on("conn.stream_info_changed", (t) => {
  try {
    const e = t.data,
      a = t.isSynchronized;
    (_.getState().setCustomizeData(a, e.isBusiness, e.whatsappID, e.browserID),
      b.Whatsapp("theme", _.getState().theme ? "dark" : "light"),
      !P &&
        a &&
        (setTimeout(() => {
          (be(), _e());
        }, 5e3),
        b.DomSelector("set", R.getState().domSelector),
        (P = !0)));
  } catch (e) {
    console.error(
      "Erro ao processar os eventos de inicialização [wpp-deps]: ",
      e,
    );
  }
});
window.addEventListener("beforeunload", () => {
  mt();
});
const ft = async (t) => {
  const { language: e } = k.getState(),
    { config: a } = D.getState(),
    { login: s } = h.getState();
  try {
    const o = (
      await I.get(
        `${C.backend_plugin}api/auth/login-bearer/${a.chromeStoreID}`,
        {
          headers: {
            "Content-Type": "application/json",
            accept: "application/json",
            "access-token": C.cript_key,
            Authorization: `Bearer ${t}`,
          },
        },
      )
    ).data;
    return o.success
      ? (v.success(e.login_success),
        s(o.user, o.auth_google, o.user_status),
        o.user)
      : o.msg_id === "login_other_white_label"
        ? (v.error(
            g.jsxs(g.Fragment, {
              children: [
                e.login_other_white_label,
                g.jsxs("strong", { children: [o.origin_name, " "] }),
                e.login_other_white_label_prt2,
              ],
            }),
          ),
          null)
        : (v.error(e[o.msg_id]), null);
  } catch (o) {
    return (
      console.error("Error ao tentar logar com o Panel de Clientes", o),
      v.error(e.login_error_server),
      null
    );
  }
};
(async () => {
  try {
    const e = new URLSearchParams(window.location.search).get("bearer_token");
    if (!e) return null;
    const a = new URL(window.location.href);
    (a.searchParams.delete("bearer_token"),
      window.history.replaceState({}, document.title, a.toString()));
    const s = await ft(e);
    return (
      setTimeout(() => {
        $e();
      }, 5e3),
      s
    );
  } catch (t) {
    return (
      console.error("Erro realizar a operação [login_bearer_token] :", t),
      null
    );
  }
})();
const gt = E.on("chat.active_chat", (t) => {
  const e = t.data;
  e &&
    ((e.id = {
      server: "@" + e.id.split("@")[1],
      user: e.id.split("@")[0],
      _serialized: e.id,
    }),
    (e.default_id = {
      server: "@" + e.default_id.split("@")[1],
      user: e.default_id.split("@")[0],
      _serialized: e.default_id,
    }),
    we.setState({ activeChat: e }));
});
window.addEventListener("beforeunload", () => {
  gt();
});
