import {
    S as O,
    C as te,
    U as me,
    W as z,
    G as Q,
    R as G,
    g as f,
    r as E,
    _ as ue,
    j as g,
    I as N,
    E as J,
    O as ca,
    h as da,
    P as M,
    f as Ve,
    N as Ye,
    i as wt,
    k as la,
    w as ua
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f10.js";
import {
    a as ve,
    A as pa
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f6.js";
import {
    a as k
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f4.js";
import {
    X as zt,
    G as L
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f8.js";
import {
    c as b
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f7.js";
import {
    V as ye,
    W as m
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f18.js";
import {
    b as y,
    u as _
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f19.js";
import {
    g as ma,
    r as fa
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f.js";
import {
    d as Dt,
    l as ga,
    u as ha,
    b as va,
    f as Aa,
    s as ba,
    c as Sa,
    o as wa
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f9.js";
import {
    G as ya
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f2.js";
import {
    O as xa
} from "./v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f3.js";
const le = b()((a, t) => ({
    label: {
        chromeStoreID: "",
        descricao: "",
        language: "pt",
        name: "",
        nameID: "",
        sigeID: "",
        checkout: "",
        tutorial: "",
        cor_primaria: !1,
        banner: null,
        install: "",
        uninstall: "",
        rewards: "",
        webhook_login_clients: "",
        ia_wascript: "",
        meetAovivo: null,
        suporte_clientes: {
            premium: "",
            free: ""
        },
        videos_tutoriais: {
            resposta_rapida: "",
            mensagens_agendadas: "",
            envio_em_massa: "",
            status: "",
            auto_atendimento: "",
            fluxo: "",
            follow_up: "",
            api: "",
            webhook: ""
        },
        btn_black: ""
    },
    setLabel: e => {
        a({
            label: e
        });
        const s = document.querySelector("main");
        s && s.setAttribute("plugin-ico-color", String(t().label.cor_primaria))
    }
}));
async function di() {
    try {
        const t = await (await fetch(chrome.runtime.getURL("/label/config/utils.json"))).json();
        try {
            const s = (await ve.get(`${ye.backend}api/whiteLabel/get?wl_id=${t.chromeStoreID}`, {
                headers: {
                    "Content-Type": "application/json",
                    accept: "application/json"
                }
            })).data.wl;
            s.cor_primaria = s.cor_primaria === 0;
            const o = {
                ...t,
                ...s
            };
            le.getState().setLabel(o)
        } catch (e) {
            const s = {
                ...t,
                checkout: "",
                tutorial: "",
                cor_primaria: !1,
                banner: null,
                install: "",
                uninstall: "",
                rewards: "",
                webhook_login_clients: "",
                ia_wascript: "",
                meetAovivo: null,
                suporte_clientes: {
                    premium: "",
                    free: ""
                },
                videos_tutoriais: {
                    resposta_rapida: "",
                    mensagens_agendadas: "",
                    envio_em_massa: "",
                    status: "",
                    auto_atendimento: "",
                    fluxo: "",
                    follow_up: "",
                    api: "",
                    webhook: ""
                },
                btn_black: ""
            };
            le.getState().setLabel(s), console.error("erro ao carregar a WL remota", e)
        }
    } catch (a) {
        console.error("Erro ao carregar o arquivo da Label Local:", a)
    }
}
const Ne = {
        date: {
            tag: "date",
            quant: 0,
            max: 0,
            old: Date.now()
        },
        init_conversa: {
            tag: "init_conversa",
            quant: 0,
            max: 5
        },
        create_link: {
            tag: "create_link",
            quant: 0,
            max: 3
        },
        close_service: {
            tag: "close_service",
            quant: 0,
            max: 3
        },
        lembretes: {
            tag: "lembretes",
            quant: 0,
            max: 1
        },
        assinatura: {
            tag: "assinatura",
            quant: 0,
            max: 5
        },
        googleCalendario: {
            tag: "googleCalendario",
            quant: 0,
            max: 1
        },
        contatos: {
            tag: "contatos",
            quant: 0,
            max: 1
        },
        respostasRapidas: {
            tag: "respostasRapidas",
            quant: 0,
            max: 3
        },
        agendamentos: {
            tag: "agendamentos",
            quant: 0,
            max: 1
        },
        perfilDoContato: {
            tag: "perfilDoContato",
            quant: 0,
            max: 10
        },
        encomendas: {
            tag: "encomendas",
            quant: 0,
            max: 1
        },
        autoatendimento: {
            tag: "autoatendimento",
            quant: 0,
            max: 3
        },
        fluxo: {
            tag: "fluxo",
            quant: 0,
            max: 15
        },
        followUp: {
            tag: "followUp",
            quant: 0,
            max: 3
        },
        webhook: {
            tag: "webhook",
            quant: 0,
            max: 3
        },
        clear_message: {
            tag: "clear_message",
            quant: 0,
            max: 1
        },
        useTradutor: {
            tag: "useTradutor",
            quant: 0,
            max: 1
        },
        status: {
            tag: "status",
            quant: 0,
            max: 1
        },
        assistente_chat: {
            tag: "assistente_chat",
            quant: 0,
            max: 3
        },
        API: {
            tag: "API",
            quant: 0,
            max: 3
        },
        trascrever_audio: {
            tag: "trascrever_audio",
            quant: 0,
            max: 1
        }
    },
    Fe = b()(a => ({
        userFreeLimity: Ne,
        setUserFreeLimity: t => {
            O("wpp-functions", "functions", [te.encryptData(t)]), a(e => ({
                ...e,
                userFreeLimity: t
            }))
        },
        setUserFreeLimityPluginPage: () => a(t => ({
            ...t,
            plugin_page: !0
        }))
    })),
    jt = a => {
        var s;
        if (C.getState().user.estado) return !1;
        const t = Fe.getState().userFreeLimity;
        if (me.subtrData(t.date.old) > 1) {
            const o = {
                ...Ne
            };
            for (const r in o)
                if (Object.prototype.hasOwnProperty.call(o, r)) {
                    const i = o[r];
                    i.quant = 0, i.tag === "date" && (i.old = Date.now()), i.tag === a && (i.quant = 1)
                } return Fe.getState().setUserFreeLimity(o), !1
        }
        if (t[a] || (t[a] = Ne[a]), t[a].quant === ((s = t[a]) == null ? void 0 : s.max)) return !0;
        const e = {
            ...t
        };
        return e[a].quant++, Fe.getState().setUserFreeLimity(t), !1
    },
    ae = async (a, t = !1) => {
        let e = !1;
        return y.getState().plugin_page ? C.getState().user.estado ? e = !1 : e = await z("exe-CheckUserFreeLock", a) : e = jt(a), e && !t && X.getState().openRendertype("user_free"), e
    }, li = async () => {
        let a = Ne;
        const t = await Q("wpp-functions", "functions");
        t[0] && t[0][0] && (a = te.decryptData(t[0][0])), Fe.getState().setUserFreeLimity(a)
    };
chrome.runtime.onMessage.addListener(async a => {
    a.action === "exe-CheckUserFreeLock" && !y.getState().plugin_page && chrome.runtime.sendMessage({
        action: a.action,
        response: JSON.stringify(jt(a.dados)),
        id: a.id
    })
});
chrome.runtime.onMessage.addListener(a => {
    switch (a.action) {
        case "updateActivePerfil":
            const {
                activePerfil: t, perfil: e
            } = $.getState(), {
                updatePerfil: s
            } = a.dados, o = e.filter(i => i.userID !== s.userID), r = [s, ...o];
            t.userID === s.userID ? $.setState({
                activePerfil: s,
                perfil: r
            }) : $.setState({
                perfil: r
            });
            break;
        case "BackupPerfil":
            (async () => {
                const i = await G("perfil");
                $.setState({
                    perfil: i
                })
            })();
            break
    }
});
const yt = {
    cargo: "",
    cidade: "",
    estado: "",
    dataNascimento: "",
    email: "",
    empresa: "",
    entrada: "",
    observacoes: "",
    origemLead: "",
    produtos: [],
    saida: "",
    sexo: "",
    valNegocio: [],
    idioma: "",
    userID: ""
};
let $e = null;
const $ = b()((a, t) => ({
        perfil: [],
        activePerfil: yt,
        activeUser: {
            picture: "",
            labels: []
        },
        setActiveUser: async ({
            id: e,
            labels: s
        }) => {
            const o = await m.Contact("getProfilePictureUrl", e._serialized),
                i = (await m.Labels("getAllLabels")).filter(n => s.includes(n.id));
            a({
                activeUser: {
                    picture: o,
                    labels: i
                }
            })
        },
        setActivePerfil: e => a(s => {
            e = e.replace("@c.us", "").replace("@g.us", "");
            const o = s.perfil.find(r => r.userID === e);
            return o ? {
                activePerfil: o
            } : {
                activePerfil: {
                    ...yt,
                    userID: e
                }
            }
        }),
        updateActivePerfil: (e, s) => {
            const {
                activePerfil: o
            } = $.getState(), r = {
                ...o,
                [e]: s
            };
            a({
                activePerfil: r
            }), $e && clearTimeout($e), $e = setTimeout(async () => {
                if (await ae("perfilDoContato") === !0) return;
                const {
                    perfil: i
                } = $.getState(), n = {
                    ...o,
                    [e]: s
                }, c = i.filter(d => d.userID !== o.userID), l = [n, ...c];
                f("perfil", l), y.getState().plugin_page ? z("updateActivePerfil", {
                    updatePerfil: n
                }, !1) : chrome.runtime.sendMessage({
                    action: "updateActivePerfil",
                    dados: {
                        updatePerfil: n
                    }
                }), a({
                    perfil: l
                })
            }, 1e3)
        },
        getValorNegocio: () => {
            const {
                activePerfil: e
            } = $.getState(), {
                idioma: s
            } = _();
            let o = 0;
            if (e.valNegocio)
                for (let c of e.valNegocio) o += parseFloat(c.valor);
            const r = {
                    pt: {
                        locale: "pt-BR",
                        currency: "BRL"
                    },
                    en: {
                        locale: "en-US",
                        currency: "USD"
                    },
                    es: {
                        locale: "es-ES",
                        currency: "EUR"
                    }
                },
                {
                    locale: i,
                    currency: n
                } = r[s] || r.pt;
            return o.toLocaleString(i, {
                style: "currency",
                currency: n
            })
        },
        getPerfilContato: e => {
            const {
                perfil: s
            } = t();
            e = e.replace("@g.us", "").replace("@c.us", "");
            const o = s.find(i => i.userID === e);
            if (!o) return null;
            let r = 0;
            if (o.valNegocio)
                for (let i of o.valNegocio) r += parseFloat(i.valor);
            return {
                ...o,
                valorNegocioTotal: r.toLocaleString("pt-BR", {
                    style: "currency",
                    currency: "BRL"
                })
            }
        }
    })),
    Ca = async a => {
        $.setState({
            perfil: a
        }), await f("perfil", a), chrome.runtime.sendMessage({
            action: "BackupPerfil"
        })
    }, ui = a => {
        const t = [...$.getState().perfil],
            s = ((o, r) => o.concat(r).reduce((c, l) => (c.find(u => u.userID === l.userID) || c.push(l), c), []))(t, a);
        Ca(s)
    };
(async () => {
    const a = await G("perfil");
    $.setState({
        perfil: a
    })
})();
chrome.runtime.onMessage.addListener(a => {
    switch (a.action) {
        case "serviceCompleted":
            W.getState().dispartWebhook(a.dados, "serviceCompleted");
            break;
        case "dispartWebhook":
            const t = a.dados;
            W.getState().dispartWebhook(t.userID, t.webhookID, t.eventDetails, t.sendID);
            break
    }
});
const Ot = [{
        id: "eventDetails",
        active: !0,
        disabled: !0
    }, {
        id: "number",
        active: !0,
        disabled: !0
    }, {
        id: "name",
        active: !0,
        disabled: !0
    }, {
        id: "picture",
        active: !1
    }, {
        id: "labels",
        active: !1
    }, {
        id: "perfilContato",
        active: !1
    }, {
        id: "user",
        active: !1
    }],
    Xe = {
        id: "metaAds",
        active: !1,
        url: "",
        param: Ot,
        sent: []
    },
    pi = ["metaAds", "serviceCompleted", "respostaRapida", "autoAtendimento", "followUp", "agendamento", "crm", "labels", "messages"],
    W = b()(a => ({
        webhook: [],
        activeHook: Xe,
        timeout: null,
        setActiveHook: t => a(e => {
            const s = e.webhook.find(o => o.id === t);
            return s ? {
                activeHook: s
            } : {
                activeHook: {
                    id: t,
                    active: !1,
                    url: "",
                    param: Ot,
                    sent: []
                }
            }
        }),
        setDadosWebHook: (t, e, s) => a(o => {
            let r = null,
                i = [];
            return o.webhook.find(c => c.id === t) ? i = o.webhook.map(c => c.id === t ? (r = {
                ...c,
                [e]: s
            }, r) : c) : (r = {
                ...o.activeHook,
                [e]: s
            }, i = [r, ...o.webhook]), f("webhook", i), {
                activeHook: r,
                webhook: i
            }
        }),
        setDadosParam: (t, e) => a(s => {
            const o = s.activeHook.param.map(c => c.id === e ? {
                id: c.id,
                active: !c.active
            } : c);
            let r = {
                    ...s.activeHook,
                    param: o
                },
                i = [];
            return s.webhook.find(c => c.id === t) ? i = s.webhook.map(c => c.id === t ? r : c) : i = [r, ...s.webhook], f("webhook", i), {
                activeHook: r,
                webhook: i
            }
        }),
        dispartWebhook: async (t, e, s, o) => {
            const {
                timeout: r
            } = W.getState(), {
                getPerfilContato: i
            } = $.getState(), n = C.getState().user.login;
            if (y.getState().plugin_page) {
                Ma(t, e, s, o);
                return
            }
            const c = W.getState().webhook.find(S => S.id === e);
            if (!c || !c.active) return;
            if (r && clearTimeout(r), await ae("webhook", !0) === !0) {
                a({
                    timeout: setTimeout(() => {}, 5e3)
                });
                return
            }
            const l = await m.Utils("get-card", t);
            l.number = l.id, delete l.id, l.eventID = c.id, s && (l.eventDetails = s), l.perfilContato = i(t), l.user = n, c.param.forEach(S => {
                S.active || delete l[S.id]
            });
            let d = 500;
            const u = {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify(l)
                },
                p = await fetch(c.url, u).then(S => {
                    d = S.status
                }).then(() => !0).catch(S => (console.error("error", S), !1)),
                A = me.dayDate(),
                v = me.timeDate(),
                h = {
                    id: o || E(),
                    status: !!p,
                    code: d,
                    userID: t,
                    date: `${A.day}/${A.month}/${A.year} as ${v.hours}:${v.minutes}:${v.seconds}`
                };
            s && (h.eventDetails = s), a(o ? S => {
                const U = S.webhook.map(w => {
                    if (w.id === e) {
                        const F = w.sent.map(oe => oe.id === o ? h : oe);
                        return {
                            ...w,
                            sent: F
                        }
                    }
                    return w
                });
                return f("webhook", U), {
                    activeHook: U.find(w => w.id === e),
                    webhook: U
                }
            } : S => {
                const U = S.webhook.map(w => {
                    if (w.id === e) {
                        const F = w.sent;
                        return F.length >= 30 && F.pop(), {
                            ...w,
                            sent: [h, ...F]
                        }
                    }
                    return w
                });
                return f("webhook", U), {
                    activeHook: U.find(w => w.id === e),
                    webhook: U
                }
            })
        }
    })),
    mi = async () => {
        let t = (await G("webhook") || []).map(s => s.param.find(r => r.id === "user") ? s : {
            ...s,
            param: [...s.param, {
                id: "user",
                active: !1
            }]
        });
        const e = t.find(s => s.id === "metaAds") || Xe;
        W.setState({
            activeHook: e,
            webhook: t
        })
    }, fi = a => {
        f("webhook", a);
        const t = a.find(e => e.id === "metaAds") || Xe;
        W.setState({
            activeHook: t,
            webhook: a
        })
    }, Ma = (a, t, e, s) => {
        z("dispartWebhook", {
            userID: a,
            webhookID: t,
            eventDetails: e,
            sendID: s
        })
    }, xt = () => {
        var a = new KeyboardEvent("keydown", {
            code: "Escape",
            which: 27,
            bubbles: !0,
            composed: !0,
            keyCode: 27,
            cancelable: !0,
            key: "Escape"
        });
        document.dispatchEvent(a)
    }, Ta = {
        trasferirAtendimento: {
            text: "",
            active: !1
        },
        finalizarAtendimento: {
            text: "",
            active: !1,
            arquivar: !1
        }
    }, Ae = b()(a => ({
        atendimento: Ta,
        activeTrasferencia: null,
        trasferencias: [],
        renderTrasferencia: t => a(e => {
            const {
                modal: s
            } = X.getState();
            return s ? {
                trasferencias: [...e.trasferencias, t]
            } : {
                activeTrasferencia: t
            }
        }),
        alterRenderTrasferencia: () => a(t => ({
            activeTrasferencia: t.trasferencias[0],
            trasferencias: t.trasferencias.slice(1)
        })),
        setFinalizarAtendimento: (t, e) => a(s => {
            const o = {
                ...s.atendimento,
                finalizarAtendimento: {
                    ...s.atendimento.finalizarAtendimento,
                    [t]: e
                }
            };
            return f("atendimento", o), {
                atendimento: o
            }
        }),
        setTransferirAtendimento: (t, e) => a(s => {
            const o = {
                ...s.atendimento,
                trasferirAtendimento: {
                    ...s.atendimento.trasferirAtendimento,
                    [t]: e
                }
            };
            return f("atendimento", o), {
                atendimento: o
            }
        }),
        finalizarAtendimento: t => {
            const {
                atendimento: e
            } = Ae.getState(), {
                plugin_page: s
            } = y.getState();
            if (xt(), s ? z("serviceCompleted", t) : W.getState().dispartWebhook(t, "serviceCompleted", {
                    type: "Finalizado"
                }), e.finalizarAtendimento.active) {
                const o = `*_Atendimento Finalizado_* 
 ` + e.finalizarAtendimento.text;
                m.Chat("sendTxt", {
                    id: t,
                    msg: o
                })
            }
            e.finalizarAtendimento.arquivar && m.Chat("arquivar", t)
        },
        trasferirAtendimento: (t, e) => {
            const {
                atendimento: s
            } = Ae.getState(), {
                plugin_page: o
            } = y.getState();
            if (xt(), o ? z("serviceCompleted", t) : W.getState().dispartWebhook(t, "serviceCompleted", {
                    type: "Trasferido"
                }), s.trasferirAtendimento.active) {
                const r = `*_Atendimento Transferido para ${e}_*: 
 ${s.trasferirAtendimento.text}`;
                m.Chat("sendTxt", {
                    id: t,
                    msg: r
                })
            }
        }
    }));
(async () => {
    const a = await G("atendimento") || void 0;
    a && Ae.setState({
        atendimento: a
    })
})();
Ae.subscribe(a => {
    a.activeTrasferencia && X.getState().openRendertype("receive_atendimento", !1)
});
const gi = a => {
        Ae.setState({
            atendimento: a
        }), f("atendimento", a)
    },
    ka = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f46.js")), []));

function _a() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(ka, {})
    })
}
const Ra = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f47.js")), []));

function La() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Ra, {})
    })
}
const Ua = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f48.js")), []));

function Ea() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Ua, {})
    })
}
const Fa = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f49.js")), []));

function Na() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Fa, {})
    })
}
const Ia = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f50.js")), []));

function qa() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Ia, {})
    })
}
const Pa = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f51.js")), []));

function za() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Pa, {})
    })
}
const Da = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f52.js")), []));

function ja() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Da, {})
    })
}
const Oa = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f53.js")), []));

function Wa() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Oa, {})
    })
}
const X = b()(a => ({
    modal: null,
    disableClose: !1,
    btnClose: !0,
    auxFunc: {
        mounted: null,
        desmouted: null
    },
    open: (t, e = !0, s = {
        mounted: null,
        desmouted: null
    }, o = !1) => a(() => (s.mounted && s.mounted(), {
        modal: t,
        btnClose: e,
        disableClose: o,
        auxFunc: s
    })),
    close: () => a(t => (t.auxFunc.desmouted && t.auxFunc.desmouted(), {
        modal: null
    })),
    openRendertype: (t, e = !0, s = {
        mounted: null,
        desmouted: null
    }, o = !1) => {
        let r;
        switch (t) {
            case "Active_IA":
                r = g.jsx(La, {});
                break;
            case "user_free":
                r = g.jsx(Na, {});
                break;
            case "access_duplicate":
                r = g.jsx(Ea, {});
                break;
            case "receive_atendimento":
                r = g.jsx(ja, {});
                break;
            case "Modelo_Selecao":
                r = g.jsx(za, {});
                break;
            case "ModalLeads":
                r = g.jsx(Wa, {});
                break;
            case "assinatura":
                r = g.jsx(_a, {});
                break;
            case "login":
                r = g.jsx(qa, {});
                break
        }
        X.getState().open(r, e, s, o)
    }
}));

function hi() {
    const {
        modal: a,
        btnClose: t,
        close: e,
        disableClose: s
    } = X(), o = k.useRef(null), r = k.useRef(null);
    return k.useEffect(() => {
        const i = n => {
            const c = document.querySelector(".iziToast-wrapper"),
                l = document.querySelector('section[data-id="Modal Options"]'),
                d = document.querySelector('section[data-id="Modal Emoji"]'),
                u = document.querySelector('section[data-id="Modal Externo"]');
            t && o.current && !r.current.contains(n.target) && (!c || !c.contains(n.target)) && !l && !d && !u && e()
        };
        return a && document.addEventListener("mousedown", i), () => {
            document.removeEventListener("mousedown", i)
        }
    }, [a]), a && g.jsx("section", {
        "data-id": "Modal",
        children: g.jsx("dialog", {
            id: "my_modal_5",
            ref: o,
            className: "animate__animated animate__zoomIn modal modal-bottom sm:modal-middle !absolute overflow-hidden !opacity-100 !pointer-events-auto !visible",
            children: g.jsxs("div", {
                ref: r,
                className: "modal-box relative overflow-hidden !max-w-none !max-h-none !w-fit !h-fit",
                children: [!s && g.jsx("span", {
                    className: "absolute w-5 h-5 top-3 right-3 pulse !cursor-pointer",
                    onClick: e,
                    children: g.jsx(zt, {
                        className: "w-full h-full text-[var(--primary-strong)]"
                    })
                }), g.jsx("div", {
                    className: "w-full h-full",
                    children: a
                })]
            })
        })
    })
}
X.subscribe(a => {
    const {
        trasferencias: t,
        alterRenderTrasferencia: e
    } = Ae.getState();
    t.length !== 0 && !a.modal && e()
});
async function Ba(a) {
    try {
        return (await ve.post(`${ye.backend}api/auth/validacao`, {
            ...a
        }, {
            headers: {
                "Content-Type": "application/json",
                accept: "application/json"
            }
        })).data
    } catch {
        return {
            success: !0,
            message: "Validação realizada com sucesso",
            msg_id: "validacao_successo"
        }
    }
}
const Va = () => {
        const a = new Date,
            t = a.toLocaleString(),
            e = a.getTimezoneOffset(),
            s = (() => {
                const r = -e,
                    i = String(Math.floor(Math.abs(r) / 60)).padStart(2, "0"),
                    n = String(Math.abs(r) % 60).padStart(2, "0");
                return `${r>=0?"+":"-"}${i}:${n}`
            })(),
            o = Intl.DateTimeFormat().resolvedOptions().timeZone;
        return {
            localDateTime: t,
            timezoneOffset: s,
            timezoneName: o
        }
    },
    $a = async a => {
        let t = "GRATUITO";
        a.estado && (t = "ASSINANTE");
        const {
            user: e
        } = await m.Conn("getMyDeviceId"), s = await G("modalLead");
        return {
            state_user: t,
            user: a,
            cadastro_lead: s,
            phone: e,
            navegador: navigator.userAgent,
            horario: Va()
        }
    }, Wt = async a => {
        const t = le.getState().label;
        if (t.webhook_login_clients && t.webhook_login_clients.length !== 0) {
            const e = new Date().getTime(),
                s = localStorage.getItem("8fd5ad24df1e1b800d670e563b1b83591980060a=="),
                o = 24;
            if (s) {
                const i = new Date(s).getTime();
                if ((e - i) / (1e3 * 60 * 60) < o) return
            }
            const r = await $a(a);
            ve.post(t.webhook_login_clients, r, {
                headers: {
                    "Content-Type": "application/json"
                }
            }), localStorage.setItem("8fd5ad24df1e1b800d670e563b1b83591980060a==", new Date().toISOString())
        }
    }, Ie = {
        realizou_login: !1,
        estado: !1,
        login: "",
        senha: "",
        token: ""
    }, C = b()(a => ({
        user: Ie,
        setUser: t => {
            const e = te.encryptData(t);
            O("wpp-client", "client", [e]), chrome.runtime.sendMessage({
                action: "post-user",
                user: t
            }), a({
                user: t
            })
        },
        setRemoveUser: () => {
            const t = {
                ...Ie,
                realizou_login: !0
            };
            O("wpp-client", "client", [te.encryptData(t)]), chrome.runtime.sendMessage({
                action: "post-user",
                user: t
            }), a(e => ({
                ...e,
                user: t
            }))
        },
        setUserPluginPage: t => a({
            user: t
        })
    })), Bt = async a => {
        const {
            language: t
        } = _.getState(), {
            label: e
        } = le.getState(), {
            setUser: s
        } = C.getState(), {
            openRendertype: o
        } = X.getState();
        if (!a.estado) {
            a.realizou_login && o("login");
            return
        }
        const r = await Ba({
            email: a.login,
            token: a.token,
            chromeStoreID: e.chromeStoreID
        });
        r.success ? s(a) : (s(Ie), r.msg_id === "login_duplicado" ? o("access_duplicate") : r.plugin_origem ? (N({
            type: "Error",
            message: t[r.msg_id] + r.plugin_origem,
            position: "top-right"
        }), o("login")) : (N({
            type: "Error",
            message: t[r.msg_id],
            position: "top-right"
        }), o("login")))
    }, vi = async () => {
        let a = Ie;
        const t = await Q("wpp-client", "client");
        t[0] && t[0][0] && (a = te.decryptData(t[0][0])), Bt(a), Wt(a)
    };
chrome.runtime.onMessage.addListener(async a => {
    a.action === "get-user" && chrome.runtime.sendMessage({
        action: a.action,
        response: JSON.stringify(C.getState().user),
        id: a.id
    }), a.action === "post-user" && y.getState().plugin_page && C.getState().setUserPluginPage(a.user), a.action === "license_update" && (Wt(C.getState().user), C.getState().user.estado && Bt(C.getState().user))
});
const Ha = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_15_728248e3-b235-44ed-9cd5-d3199fba8c4f54.js")), []));

function Ct({
    notificacao: a
}) {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Ha, {
            notificacao: a
        })
    })
}
const ce = b()((a, t) => ({
    notificacoes_modal: [],
    notificacoes_box: [],
    notificacoes_inbox: [],
    modal: null,
    active_inbox_notify: null,
    notificacoes_modalIDVisible: [],
    notificacoes_boxIDVisible: [],
    notificacoes_inboxIDVisible: [],
    getNotificaoes: async () => {
        try {
            const {
                label: e
            } = le.getState();
            if (e.chromeStoreID.length === 0) return;
            const o = (await ve.get(`${ye.backend}api/notificacao/get?wl_id=${e.chromeStoreID}`, {
                headers: {
                    "Content-Type": "application/json",
                    accept: "application/json"
                }
            })).data.notificacoes;
            a({
                notificacoes_modal: o.filter(r => r.viewer === "MODAL"),
                notificacoes_box: o.filter(r => r.viewer === "NOTIFY"),
                notificacoes_inbox: o.filter(r => r.viewer === "INBOX")
            }), t().renderNotificacoes_modal(), t().renderNotificacoes_inbox()
        } catch (e) {
            console.error("Error ao capturar as notificações", e)
        }
    },
    renderNotificacoes_modal: () => a(e => {
        const {
            user: s
        } = C.getState(), r = e.notificacoes_modal.filter(i => i.client === "PREMIUM" && s.estado || i.client === "FREE" && s.estado === !1 || i.client === "ALL").filter(i => !e.notificacoes_modalIDVisible.includes(i.id));
        return {
            notificacoes_modal: r,
            modal: r.length !== 0 ? g.jsx(Ct, {
                notificacao: r[0]
            }) : null
        }
    }),
    closeNotificacoes_modal: () => {
        a({
            modal: null
        });
        const {
            notificacoes_modal: e
        } = t(), s = [...e];
        s.shift(), ce.getState().setNotificacoes_ModalVisible(e[0].id), setTimeout(() => {
            a({
                notificacoes_modal: s,
                modal: s.length !== 0 ? g.jsx(Ct, {
                    notificacao: s[0]
                }) : null
            })
        }, 2e3)
    },
    setNotificacoes_ModalVisible: e => a(s => {
        const o = [e, ...s.notificacoes_modalIDVisible];
        return localStorage.setItem("notificacoes_modal", JSON.stringify(o)), {
            notificacoes_modalIDVisible: o
        }
    }),
    renderNotificacoes_box: () => {
        const {
            user: e
        } = C.getState();
        return ce.getState().notificacoes_box.filter(r => r.client === "PREMIUM" && e.estado || r.client === "FREE" && e.estado === !1 || r.client === "ALL")
    },
    setNotificacoes_boxVisible: e => a(s => {
        if (s.notificacoes_boxIDVisible.includes(e)) return {};
        const o = [e, ...s.notificacoes_boxIDVisible];
        return localStorage.setItem("notificacoes_box", JSON.stringify(o)), {
            notificacoes_boxIDVisible: o
        }
    }),
    isBoxVisible: e => ce.getState().notificacoes_boxIDVisible.includes(e),
    renderNotificacoes_inbox: () => a(e => {
        const {
            user: s
        } = C.getState(), r = e.notificacoes_inbox.filter(i => i.client === "PREMIUM" && s.estado || i.client === "FREE" && s.estado === !1 || i.client === "ALL").filter(i => !e.notificacoes_inboxIDVisible.includes(i.id));
        return {
            notificacoes_inbox: r,
            active_inbox_notify: r.length !== 0 ? r[0] : null
        }
    }),
    closeNotificacoes_inbox: () => {
        a({
            active_inbox_notify: null
        });
        const {
            notificacoes_inbox: e,
            setNotificacoes_inboxVisible: s
        } = t(), o = [...e];
        o.shift(), s(e[0].id), setTimeout(() => {
            a({
                notificacoes_inbox: o,
                active_inbox_notify: o.length !== 0 ? o[0] : null
            })
        }, 2e3)
    },
    setNotificacoes_inboxVisible: e => a(s => {
        const o = [e, ...s.notificacoes_inboxIDVisible];
        return localStorage.setItem("notificacoes_inbox", JSON.stringify(o)), {
            notificacoes_inboxIDVisible: o
        }
    })
}));

function Ai() {
    const {
        modal: a
    } = ce();
    return a && g.jsx("section", {
        "data-id": "Notificacao-Modal",
        children: g.jsx("dialog", {
            id: "Notificacao-Modal",
            className: "z-[99999999999999] animate__animated animate__zoomIn modal modal-bottom sm:modal-middle !absolute overflow-hidden !opacity-100 !pointer-events-auto !visible",
            children: g.jsxs("div", {
                className: "modal-box relative overflow-hidden !max-w-none !max-h-none !w-fit !h-fit",
                children: [g.jsx("span", {
                    className: "absolute w-5 h-5 top-3 right-3 pulse !cursor-pointer",
                    onClick: () => ce.getState().closeNotificacoes_modal(),
                    children: g.jsx(zt, {
                        className: "w-full h-full text-[var(--primary-strong)]"
                    })
                }), g.jsx("div", {
                    className: "w-full h-full",
                    children: a
                })]
            })
        })
    })
}
chrome.runtime.onMessage.addListener(a => {
    a.action === "Remote-Notificacao" && ce.getState().getNotificaoes()
});
(() => {
    const a = JSON.parse(localStorage.getItem("notificacoes_modal")),
        t = JSON.parse(localStorage.getItem("notificacoes_box")),
        e = JSON.parse(localStorage.getItem("notificacoes_inbox"));
    a && a.length !== 0 && ce.setState({
        notificacoes_modalIDVisible: a
    }), t && t.length !== 0 && ce.setState({
        notificacoes_boxIDVisible: t
    }), e && e.length !== 0 && ce.setState({
        notificacoes_inboxIDVisible: e
    })
})();
const Ga = async (a, t, e, s, o = !1) => {
    const i = x.getState().crm.map(n => n.id === a ? {
        ...n,
        name: t,
        desc: e,
        hexColor: s
    } : n);
    J({
        stopPropag: o,
        action: "editCrm",
        waitForResponse: !1,
        data: {
            crmID: a,
            name: t,
            desc: e,
            hexColor: s
        }
    }), !o && f("crm", i), x.setState({
        crm: i
    })
}, Ja = async (a, t = !1) => {
    const s = x.getState().crm.filter(o => o.id !== a);
    J({
        stopPropag: t,
        action: "removeCrm",
        waitForResponse: !1,
        data: a
    }), !t && f("crm", s), x.setState({
        crm: s
    })
}, Ka = async ({
    id: a = E(),
    ativeCRM: t,
    name: e,
    hexColor: s
}, o = !1) => {
    const i = x.getState().crm.map(n => {
        if (n.id === t) {
            const c = {
                id: a,
                name: e,
                hexColor: s,
                chats: []
            };
            return {
                ...n,
                list: [...n.list, c]
            }
        }
        return n
    });
    J({
        stopPropag: o,
        action: "addNewTabCRM",
        waitForResponse: !1,
        data: {
            id: a,
            ativeCRM: t,
            name: e,
            hexColor: s
        }
    }), !o && f("crm", i), x.setState({
        crm: i
    })
}, Za = async (a, t = !1) => {
    const s = [...x.getState().crm, ...a].reduce((o, r) => o.find(n => n.id === r.id) ? o : o.concat([r]), []);
    J({
        stopPropag: t,
        action: "setCrm",
        waitForResponse: !1,
        data: a
    }), !t && f("crm", s), x.setState({
        crm: s
    })
}, Qa = async (a, t, e, s = !1) => {
    const r = x.getState().crm.map(i => i.id === a ? {
        ...i,
        list: i.list.map(n => n.id === t ? {
            ...n,
            name: e
        } : n)
    } : i);
    J({
        stopPropag: s,
        action: "editTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            abaID: t,
            name: e
        }
    }), !s && f("crm", r), x.setState({
        crm: r
    })
}, Ya = async (a, t, e, s = !1) => {
    const r = x.getState().crm.map(i => i.id === a ? {
        ...i,
        list: i.list.map(n => n.id === t ? {
            ...n,
            chats: n.chats.filter(c => c.id !== e)
        } : n)
    } : i);
    J({
        stopPropag: s,
        action: "removeChatTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            abaID: t,
            chatID: e
        }
    }), !s && f("crm", r), x.setState({
        crm: r
    })
}, Xa = async (a, t, e, s = !1) => {
    const r = x.getState().crm.map(i => i.id === a ? {
        ...i,
        list: i.list.map(n => n.id === t ? {
            ...n,
            hexColor: e
        } : n)
    } : i);
    J({
        stopPropag: s,
        action: "changeColorTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            abaID: t,
            hexColor: e
        }
    }), !s && f("crm", r), x.setState({
        crm: r
    })
}, Vt = async (a, t, e, s, o = !1) => {
    const r = x.getState().crm;
    a = a.replace("@c.us", "").replace("@g.us", "");
    let i;
    t ? i = r.map(n => ({
        ...n,
        list: n.list.map(c => ({
            ...c,
            chats: c.chats.filter(l => l.id !== a)
        }))
    })) : i = r.map(n => n.id === e ? {
        ...n,
        list: n.list.map(c => c.id === s ? {
            ...c,
            chats: c.chats.filter(l => l.id !== a)
        } : c)
    } : n), J({
        stopPropag: o,
        action: "setRemoveUserCRM",
        waitForResponse: !1,
        data: {
            userID: a,
            isAll: t,
            crmID: e,
            abaID: s
        }
    }), !o && f("crm", i), x.setState({
        crm: i
    })
}, $t = a => {
    const t = x.getState().crm;
    let e = 0;
    return t.map(s => {
        s.list.map(o => {
            o.chats.map(r => {
                r.id === a && e++
            })
        })
    }), e
}, Ht = async (a, t, e, s, o = !1) => {
    const r = x.getState().crm;
    a = a.replace("@c.us", "").replace("@g.us", "");
    let i = r.map(n => n.id === t ? {
        ...n,
        list: n.list.map(c => {
            if (c.id === e && !c.chats.some(d => d.id === a)) {
                let d = [...c.chats];
                return d.splice(s, 0, {
                    id: a
                }), {
                    ...c,
                    chats: d
                }
            }
            return c
        })
    } : n);
    J({
        stopPropag: o,
        action: "setNewUserCRM",
        waitForResponse: !1,
        data: {
            userID: a,
            crmID: t,
            abaID: e,
            insertPosition: s
        }
    }), !o && f("crm", i), x.setState({
        crm: i
    })
}, es = (a, t, e, s, o, r = !1) => {
    const n = x.getState().crm.map(c => ({
        ...c,
        list: c.list.map(l => {
            if (l.id === t && !o) {
                const d = l.chats.filter(u => u.id !== a.id);
                return {
                    ...l,
                    chats: d
                }
            } else if (l.id === e) {
                const d = [...l.chats];
                return d.some(p => p.id === a.id) || d.splice(s, 0, a), {
                    ...l,
                    chats: d
                }
            }
            return l
        })
    }));
    J({
        stopPropag: r,
        action: "moveUserTabCRM",
        waitForResponse: !1,
        data: {
            chat: a,
            source: t,
            destination: e,
            insertPosition: s,
            duplicate: o
        }
    }), !r && f("crm", n), x.setState({
        crm: n
    })
}, ts = (a, t, e, s, o = !1) => {
    const i = x.getState().crm.map(n => n.id === a ? {
        ...n,
        list: n.list.map(c => {
            if (c.id === t) {
                const l = [...c.chats],
                    [d] = l.splice(e, 1);
                return l.splice(s, 0, d), {
                    ...c,
                    chats: l
                }
            }
            return c
        })
    } : n);
    J({
        stopPropag: o,
        action: "orderUserInTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            columnID: t,
            indexHome: e,
            indexDestination: s
        }
    }), !o && f("crm", i), x.setState({
        crm: i
    })
}, as = (a, t, e, s = !1) => {
    const r = x.getState().crm.map(i => {
        if (i.id === a) {
            const n = [...i.list],
                [c] = n.splice(t, 1);
            return n.splice(e, 0, c), {
                ...i,
                list: n
            }
        }
        return i
    });
    J({
        stopPropag: s,
        action: "sortUserTabsCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            indexHome: t,
            indexDestination: e
        }
    }), !s && f("crm", r), x.setState({
        crm: r
    })
}, ss = (a, t, e = !1) => {
    const o = x.getState().crm.map(r => r.id === a ? {
        ...r,
        list: r.list.filter(i => i.id !== t)
    } : r);
    J({
        stopPropag: e,
        action: "deleteTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            abaID: t
        }
    }), !e && f("crm", o), x.setState({
        crm: o
    })
}, os = ca({
    setCrm: a => {
        Za(a.data, !0)
    },
    editCrm: a => {
        const {
            crmID: t,
            name: e,
            desc: s,
            hexColor: o
        } = a.data;
        Ga(t, e, s, o, !0)
    },
    removeCrm: a => {
        Ja(a.data, !0)
    },
    addNewTabCRM: a => {
        Ka(a.data, !0)
    },
    editTabCRM: a => {
        const {
            crmID: t,
            abaID: e,
            name: s
        } = a.data;
        Qa(t, e, s, !0)
    },
    removeChatTabCRM: a => {
        const {
            crmID: t,
            abaID: e,
            chatID: s
        } = a.data;
        Ya(t, e, s, !0)
    },
    changeColorTabCRM: a => {
        const {
            crmID: t,
            abaID: e,
            hexColor: s
        } = a.data;
        Xa(t, e, s, !0)
    },
    setRemoveUserCRM: a => {
        const {
            userID: t,
            isAll: e,
            crmID: s,
            abaID: o
        } = a.data;
        Vt(t, e, s, o, !0)
    },
    setNewUserCRM: a => {
        const {
            userID: t,
            crmID: e,
            abaID: s,
            insertPosition: o
        } = a.data;
        Ht(t, e, s, o, !0)
    },
    moveUserTabCRM: a => {
        const {
            chat: t,
            source: e,
            destination: s,
            insertPosition: o,
            duplicate: r
        } = a.data;
        es(t, e, s, o, r, !0)
    },
    orderUserInTabCRM: a => {
        const {
            crmID: t,
            columnID: e,
            indexHome: s,
            indexDestination: o
        } = a.data;
        ts(t, e, s, o, !0)
    },
    sortUserTabsCRM: a => {
        const {
            crmID: t,
            indexHome: e,
            indexDestination: s
        } = a.data;
        as(t, e, s, !0)
    },
    deleteTabCRM: a => {
        const {
            crmID: t,
            abaID: e
        } = a.data;
        ss(t, e, !0)
    }
});
chrome.runtime.onMessage.addListener(os);
const x = b()(() => ({
        crm: []
    })),
    rs = "1.8",
    is = "",
    ns = "true",
    cs = "true",
    ds = {
        timer: "60000",
        enable_two_send: !1
    },
    ls = {
        model: "taghtml",
        parm: "body.color-refresh"
    },
    us = {
        model: "querySelector",
        selector: ["#app"]
    },
    ps = {
        model: "querySelector",
        selector: ["body > div"]
    },
    ms = {
        model: "Element",
        selector: "#pane-side"
    },
    fs = {
        model: "querySelector",
        selector: ["#app > div > div ._aigs"]
    },
    gs = {
        model: "Element",
        selector: "two"
    },
    hs = {
        model: "querySelector",
        selector: [".two._aigs > div:nth-child(6)"]
    },
    vs = {
        model: "Element",
        selector: "x10l6tqk"
    },
    As = {
        model: "querySelector",
        selector: [".lexical-rich-text-input > div"]
    },
    bs = {
        model: "querySelector",
        selector: ["[data-icon='search']"]
    },
    Ss = {
        model: "querySelector",
        selector: ["header > div > div > div > div > span > div > div:nth-child(1)", "header > div._ak0w"]
    },
    ws = {
        model: "querySelector",
        selector: ["header > header > div > span > div"]
    },
    ys = {
        model: "querySelector",
        selector: ["#side > div._ak9t > div"]
    },
    xs = {
        model: "querySelector",
        selector: ["#main > header > div.xeuugli > div > div"]
    },
    Cs = {
        model: "querySelector",
        selector: ["#main ._amm9", "#main .x1n2onr6.x1vjfegm.x1cqoux5.x14yy4lh"]
    },
    Ms = {
        model: "querySelector",
        selector: ["#main > header :nth-child(3) div"]
    },
    Ts = {
        model: "querySelector",
        selector: ["footer ._ak1m"]
    },
    ks = {
        model: "querySelector",
        selector: ["footer > div"]
    },
    _s = {
        model: "querySelector",
        selector: ["footer div[contenteditable=true]"]
    },
    Rs = {
        model: "querySelector",
        selector: ["footer > div.copyable-area > div"]
    },
    Ls = {
        model: "querySelector",
        selector: ["#main > div.x1n2onr6.x1vjfegm.x1cqoux5.x14yy4lh"]
    },
    Us = {
        model: "querySelector",
        selector: ["._1VZX7 ._3Uu1_, ._ak1r > div"]
    },
    Es = {
        model: "querySelector",
        selector: ["#main > footer > div > div > span > div > div._ak1r > div > div.x9f619.x78zum5.x6s0dn4", "#main > footer > div.copyable-area > div > span > div > div._ak1r > div.x123j3cw"]
    },
    Fs = {
        model: "querySelector",
        selector: ["#main > footer > div.copyable-area > div > span > div > div._ak1m > div > button[tabindex='-1']"]
    },
    Ns = {
        model: "querySelector",
        selector: ["#main > footer > div:nth-child(3) > div > div:nth-child(4) > div > div > div > button", "#main > footer > div:nth-child(3) > div > div > span > div > div > div.x9f619 > button"]
    },
    Is = {
        model: "querySelector",
        selector: ["#main > div.x1n2onr6.x1vjfegm.x1cqoux5.x14yy4lh > div > div.x10l6tqk.x13vifvy"]
    },
    qs = {
        model: "querySelectorAll",
        selector: ["#main div > div[data-id]"]
    },
    Ps = {
        model: "querySelector",
        selector: ["#main > footer"]
    },
    zs = {
        model: "querySelector",
        selector: ["#side div[tabindex='-1']"]
    },
    Ds = {
        model: "querySelector",
        selector: ["#side > div:nth-child(2)"]
    },
    js = {
        model: "querySelector",
        selector: ["#main > footer > div:nth-child(3) > div > div:nth-child(4) > div > div > div", "#main > footer > div:nth-child(3) > div > div > span > div > div"]
    },
    Os = {
        model: "querySelector",
        selector: ["#pane-side > div > div > div"]
    },
    Ws = {
        model: "querySelectorAll",
        selector: ["#pane-side > div > div > div > div  div[aria-selected]", "#pane-side > div > div > div div[role='button'] > div"]
    },
    Bs = {
        model: "Element",
        selector: "div._ak8l > div._ak8j > div._ak8i"
    },
    Vs = {
        model: "Element",
        selector: "x10l6tqk xh8yej3 x1g42fcv"
    },
    $s = {
        model: "Element",
        selector: "__reactFiber"
    },
    Hs = {
        model: "querySelector",
        selector: ["#side div._ai04 > button"]
    },
    Gs = {
        model: "listElement",
        list: {
            main_audio_1: "div._amk6._amlo",
            main_audio_2: "div._ak49._ak48",
            camp_text_1: "row-translate",
            camp_text_2: "span.selectable-text",
            add_btn_tradutor: "div.x1c4vz4f.x1q0g3np.x6s0dn4._amj_",
            camp_audio_1: 'div[role="slider"] > canvas',
            camp_audio_2: 'div[role="slider"] div._ahwf'
        }
    },
    Js = {
        model: "querySelector",
        selector: ["div.two._aigs > div._aigw"]
    },
    Ks = {
        model: "querySelector",
        selector: ["#main > span:nth-child(8)", "#main > :last-child"]
    },
    Zs = {
        model: "querySelector",
        selector: ["#main > span:nth-child(7)", "#main > span:nth-child(8)", "#main > span:nth-child(9)"]
    },
    Qs = {
        model: "querySelector",
        selector: ["#app > div > div > span:nth-child(4)", "#app > div > span:nth-child(4)"]
    },
    Ys = {
        model: "querySelector",
        selector: ["#app > div > div.x78zum5.xdt5ytf.x5yr21d > div > header > div > div:nth-child(2) > div", "header > div > div:nth-child(2) > div"]
    },
    Xs = {
        model: "querySelector",
        selector: ["#main header"]
    },
    eo = {
        model: "querySelector",
        selector: ["#main > footer > div > div > span > div > div._ak1r > div"]
    },
    to = {
        model: "querySelector",
        selector: ["#side"]
    },
    ao = {
        model: "listElement",
        list: {
            div_filters: "_akap _akan _arj9"
        }
    },
    so = {
        model: "querySelectorAll",
        selector: ["#side > div:nth-of-type(2) div[role=tab]", "#side > div:nth-of-type(2) button"]
    },
    oo = {
        model: "querySelector",
        selector: [".os-win"]
    },
    ro = {
        version: rs,
        update_path: is,
        update_path_active: ns,
        disabeldOldMenu: cs,
        wpp_mensagens: ds,
        newModel: ls,
        app: us,
        afiliadoMain: ps,
        paneSide: ms,
        waPage: fs,
        two: gs,
        menuLateral: hs,
        closeChat: vs,
        chatListInput: As,
        searchInput: bs,
        downAba: Ss,
        chatListHeader: ws,
        searchCamp: ys,
        chatName: xs,
        menuVertical: Cs,
        menuHorizontal: Ms,
        menuFooter: Ts,
        respostaRapida: ks,
        footerTextArea: _s,
        mainAudio: Rs,
        assChat: Ls,
        assInput: Us,
        assBtn: Es,
        assEmoji: Fs,
        assCitacao: Ns,
        listMensages: Is,
        allMensages: qs,
        assistenteChat: Ps,
        trasferidos: zs,
        notification: Ds,
        quotedMsg: js,
        listChats: Os,
        listChatsUsers: Ws,
        listChatAtendimento: Bs,
        insertAtendente: Vs,
        reactFiber: $s,
        updateChatList: Hs,
        useTradutor: Gs,
        chatList: Js,
        observerFooter: Ks,
        observerFooterNewModel: Zs,
        whatsModal: Qs,
        menu_whats: Ys,
        actionMonitor: Xs,
        footerIconsLeft: eo,
        side: to,
        chatFiltersContainer: ao,
        chatFilters: so,
        selector_theme: oo
    },
    D = b()((a, t) => ({
        domSelector: ro,
        getDomSelector: e => {
            const {
                domSelector: s
            } = t();
            return s[e]
        },
        getSeletor: (e, s = o => null) => {
            const {
                getDomSelector: o
            } = t(), r = o(e);
            let i = null;
            if (!r) return null;
            for (let n of r.selector) {
                let c = null;
                if (r.model === "querySelector") {
                    if (c = document.querySelector(n), c) {
                        i = c, s(c);
                        break
                    }
                } else if (r.model === "querySelectorAll" && (c = document.querySelectorAll(n), c && c.length > 0)) {
                    i = c, s(c);
                    break
                }
            }
            return i || console.warn("Tag error: ", r.selector.toString()), i
        },
        getElement: e => {
            const {
                getDomSelector: s
            } = t();
            return s(e).selector
        },
        getListElement: (e, s) => {
            const {
                getDomSelector: o
            } = t();
            return o(e).list[s]
        }
    }));
chrome.runtime.onMessage.addListener(a => {
    if (a.action === "Update_DomSelector") {
        const {
            domSelector: t
        } = D.getState();
        t.version !== a.dados.version && window.location.reload()
    }
});
const io = {
        crm: !0,
        quick_replies: !1,
        env_massa: !0,
        ia: !0,
        calendar: !0,
        flow: !0,
        funnil_crm: !0,
        att_atendimento: !0,
        follow_up: !0,
        status: !0,
        api: !0,
        webhook: !0,
        links: !0,
        start_chat: !0,
        afiliate_link: !0,
        google_funcs: !0
    },
    no = {
        crm: !0,
        quick_replies: !0,
        env_massa: !0,
        ia: !1,
        calendar: !0,
        flow: !1,
        funnil_crm: !0,
        att_atendimento: !0,
        follow_up: !1,
        status: !0,
        api: !1,
        webhook: !1,
        links: !1,
        start_chat: !0,
        afiliate_link: !0,
        google_funcs: !1
    },
    Gt = () => {
        const {
            label: a
        } = le.getState();
        return a.chromeStoreID == "gjlfpggiddcminhebiejofeglfjmleli" ? no : io
    },
    Jt = b()(a => ({
        activeView: !0,
        setActiveView: t => a(() => {
            localStorage.setItem("active-view-menu", String(t));
            const e = document.querySelector("main");
            return e && e.setAttribute("active-view-menu", String(t)), {
                activeView: t
            }
        }),
        activeHeader: !0,
        setActiveHeader: t => a({
            activeHeader: t
        }),
        activeMenu: Gt(),
        setActiveMenu: t => a(e => {
            const s = {
                ...e.activeMenu,
                [t]: !e.activeMenu[t]
            };
            return O("usePluginMenu", "pluginMenu", [s]), {
                activeMenu: s
            }
        }),
        tema: "default",
        setTema: t => a(() => {
            O("ThemeMenu", "activeTheme", [t]);
            const e = document.querySelector("main");
            return e && e.setAttribute("theme-active", String(t)), {
                tema: t
            }
        }),
        chatsIA: !1,
        setChatsIA: t => a(() => (O("chatsIA", "state", [t]), {
            chatsIA: t
        }))
    })),
    bi = async () => {
        let a = !0;
        const t = localStorage.getItem("active-view-menu");
        t && t == "false" && (a = !1);
        let e = Gt();
        const s = await Q("usePluginMenu", "pluginMenu");
        s && s[0] && s[0][0] && (e = s[0][0]);
        let o = "default";
        const r = await Q("ThemeMenu", "activeTheme");
        r && r[0] && r[0][0] && (o = r[0][0]);
        let i = !0;
        const n = await Q("chatsIA", "state");
        n && n[0] && typeof n[0][0] == "boolean" && (i = n[0][0]), Jt.setState({
            activeView: a,
            activeMenu: e,
            tema: o,
            chatsIA: i
        })
    }, Si = () => {
        const {
            setActiveView: a,
            setActiveHeader: t
        } = Jt.getState();
        D.getState().getSeletor("whatsModal", e => {
            new MutationObserver(o => {
                for (const r of o) r.type === "childList" && (r.addedNodes.length > 0 && (a(!1), t(!1)), r.removedNodes.length > 0 && (a(!0), t(!0)))
            }).observe(e, {
                childList: !0
            })
        })
    }, Mt = {
        assinatura: {
            type: "assinatura",
            propriedades: {
                active: !1,
                desativarAss: !1,
                persAss: {
                    active: !1,
                    nameAss: ""
                }
            }
        },
        responderGrupos: {
            type: "responderGrupos",
            propriedades: {
                active: !1
            }
        },
        responderDias: {
            type: "responderDias",
            propriedades: {
                active: !1,
                segunda: {
                    active: !1,
                    periodoAtivacao: !1,
                    horaInicio: "00:00",
                    horaFim: "23:59"
                },
                terca: {
                    active: !1,
                    periodoAtivacao: !1,
                    horaInicio: "00:00",
                    horaFim: "23:59"
                },
                quarta: {
                    active: !1,
                    periodoAtivacao: !1,
                    horaInicio: "00:00",
                    horaFim: "23:59"
                },
                quinta: {
                    active: !1,
                    periodoAtivacao: !1,
                    horaInicio: "00:00",
                    horaFim: "23:59"
                },
                sexta: {
                    active: !0,
                    periodoAtivacao: !1,
                    horaInicio: "00:00",
                    horaFim: "23:59"
                },
                sabado: {
                    active: !0,
                    periodoAtivacao: !1,
                    horaInicio: "00:00",
                    horaFim: "23:59"
                },
                domingo: {
                    active: !0,
                    periodoAtivacao: !1,
                    horaInicio: "00:00",
                    horaFim: "23:59"
                }
            }
        },
        responderChatAtivo: {
            type: "responderChatAtivo",
            propriedades: {
                active: !1
            }
        },
        responderChatArquivado: {
            type: "responderChatArquivado",
            propriedades: {
                active: !1
            }
        },
        notResponderChatCRM: {
            type: "notResponderChatCRM",
            propriedades: {
                active: !1
            }
        },
        notResponderCRM: {
            type: "notResponderCRM",
            propriedades: {
                active: !1,
                crm: []
            }
        },
        responderCRM: {
            type: "responderCRM",
            propriedades: {
                active: !1,
                crm: []
            }
        },
        notResponderChatEtiquetado: {
            type: "notResponderChatEtiquetado",
            propriedades: {
                active: !1
            }
        },
        notResponderEtiqueta: {
            type: "notResponderEtiqueta",
            propriedades: {
                active: !1,
                labelID: []
            }
        },
        responderEtiqueta: {
            type: "responderEtiqueta",
            propriedades: {
                active: !1,
                labelID: []
            }
        }
    }, ge = b()(a => ({
        model: "Create",
        activeColapse: "acionamento",
        setActiveColapse: t => a(() => ({
            activeColapse: t
        })),
        activeAutoAtt: {
            id: E(),
            nome: "",
            active: !0,
            acionamento: [],
            acao: [],
            regras: Mt,
            usedLenght: 0
        },
        setActiveAutoAtt: (t, e) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                [t]: e
            }
        })),
        setResetDefaultAutoAtt: () => a(t => ({
            model: "Create",
            activeAutoAtt: {
                id: E(),
                nome: "",
                active: !0,
                acionamento: [],
                acao: [],
                regras: Mt,
                usedLenght: 0
            },
            activeColapse: "acionamento"
        })),
        setEditAutoAtt: t => a(() => (t.regras.notResponderChatCRM || (t.regras = {
            ...t.regras,
            notResponderChatCRM: {
                type: "notResponderChatCRM",
                propriedades: {
                    active: !1
                }
            },
            notResponderCRM: {
                type: "notResponderCRM",
                propriedades: {
                    active: !1,
                    crm: []
                }
            },
            responderCRM: {
                type: "responderCRM",
                propriedades: {
                    active: !1,
                    crm: []
                }
            },
            notResponderChatEtiquetado: {
                type: "notResponderChatEtiquetado",
                propriedades: {
                    active: !1
                }
            },
            responderEtiqueta: {
                type: "responderEtiqueta",
                propriedades: {
                    active: !1,
                    labelID: []
                }
            },
            notResponderEtiqueta: {
                type: "notResponderEtiqueta",
                propriedades: {
                    active: !1,
                    labelID: []
                }
            }
        }), t.regras.assinatura || (t.regras.assinatura = {
            type: "assinatura",
            propriedades: {
                active: !1,
                desativarAss: !1,
                persAss: {
                    active: !1,
                    nameAss: ""
                }
            }
        }), t.regras.responderChatArquivado || (t.regras.responderChatArquivado = {
            type: "responderChatArquivado",
            propriedades: {
                active: !1
            }
        }), {
            model: "Edit",
            activeAutoAtt: t,
            activeColapse: "acionamento"
        })),
        setCreateAcionamento: t => a(e => ({
            activeAutoAtt: {
                ...e.activeAutoAtt,
                acionamento: [...e.activeAutoAtt.acionamento, {
                    id: E(),
                    type: t
                }]
            }
        })),
        setRemoveAcionamento: t => a(e => ({
            activeAutoAtt: {
                ...e.activeAutoAtt,
                acionamento: e.activeAutoAtt.acionamento.filter(s => s.id !== t)
            }
        })),
        setAcionamentoText: (t, e) => a(s => {
            const o = s.activeAutoAtt.acionamento.map(r => r.id === t ? {
                ...r,
                text: e
            } : r);
            return {
                activeAutoAtt: {
                    ...s.activeAutoAtt,
                    acionamento: o
                }
            }
        }),
        setAcionamentoChave: (t, e) => a(s => {
            const o = s.activeAutoAtt.acionamento.map(r => r.id === t ? {
                ...r,
                chaves: r.chaves ? [e, ...r.chaves] : [e]
            } : r);
            return {
                activeAutoAtt: {
                    ...s.activeAutoAtt,
                    acionamento: o
                }
            }
        }),
        setAcionamentoRemoveChave: (t, e) => a(s => {
            const o = s.activeAutoAtt.acionamento.map(r => r.id === t ? {
                ...r,
                chaves: r.chaves.filter(i => i !== e)
            } : r);
            return {
                activeAutoAtt: {
                    ...s.activeAutoAtt,
                    acionamento: o
                }
            }
        }),
        setAcionamentoanuncioID: (t, e) => a(s => {
            const o = s.activeAutoAtt.acionamento.map(r => r.id === t ? {
                ...r,
                anuncioID: e
            } : r);
            return {
                activeAutoAtt: {
                    ...s.activeAutoAtt,
                    acionamento: o
                }
            }
        }),
        setCreateAcao: (t, e = {}) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                acao: [...s.activeAutoAtt.acao, {
                    id: E(),
                    type: t,
                    propriedades: e
                }]
            }
        })),
        setRemoveAcao: t => a(e => ({
            activeAutoAtt: {
                ...e.activeAutoAtt,
                acao: e.activeAutoAtt.acao.filter(s => s.id !== t)
            }
        })),
        setAcaoPropriedades: (t, e) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                acao: s.activeAutoAtt.acao.map(o => o.id === t ? {
                    ...o,
                    propriedades: {
                        ...o.propriedades,
                        ...e
                    }
                } : o)
            }
        })),
        sortAcoes: t => a(e => {
            const s = [...e.activeAutoAtt.acao],
                o = Array.from(s),
                [r] = o.splice(t.source.index, 1);
            return o.splice(t.destination.index, 0, r), {
                activeAutoAtt: {
                    ...e.activeAutoAtt,
                    acao: o
                }
            }
        }),
        setRegraUpdate: t => a(e => ({
            activeAutoAtt: {
                ...e.activeAutoAtt,
                regras: {
                    ...e.activeAutoAtt.regras,
                    [t]: {
                        ...e.activeAutoAtt.regras[t],
                        propriedades: {
                            ...e.activeAutoAtt.regras[t].propriedades,
                            active: !e.activeAutoAtt.regras[t].propriedades.active
                        }
                    }
                }
            }
        })),
        setRegraUpdateEtiqueta: t => a(e => ({
            activeAutoAtt: {
                ...e.activeAutoAtt,
                regras: {
                    ...e.activeAutoAtt.regras,
                    notResponderChatEtiquetado: {
                        ...e.activeAutoAtt.regras.notResponderChatEtiquetado,
                        propriedades: {
                            ...e.activeAutoAtt.regras.notResponderChatEtiquetado.propriedades,
                            active: t === "notResponderChatEtiquetado" ? !e.activeAutoAtt.regras[t].propriedades.active : !1
                        }
                    },
                    notResponderEtiqueta: {
                        ...e.activeAutoAtt.regras.notResponderEtiqueta,
                        propriedades: {
                            ...e.activeAutoAtt.regras.notResponderEtiqueta.propriedades,
                            active: t === "notResponderEtiqueta" ? !e.activeAutoAtt.regras[t].propriedades.active : !1
                        }
                    },
                    responderEtiqueta: {
                        ...e.activeAutoAtt.regras.responderEtiqueta,
                        propriedades: {
                            ...e.activeAutoAtt.regras.responderEtiqueta.propriedades,
                            active: t === "responderEtiqueta" ? !e.activeAutoAtt.regras[t].propriedades.active : !1
                        }
                    }
                }
            }
        })),
        setRegraUpdateCRM: t => a(e => ({
            activeAutoAtt: {
                ...e.activeAutoAtt,
                regras: {
                    ...e.activeAutoAtt.regras,
                    notResponderChatCRM: {
                        ...e.activeAutoAtt.regras.notResponderChatCRM,
                        propriedades: {
                            ...e.activeAutoAtt.regras.notResponderChatCRM.propriedades,
                            active: t === "notResponderChatCRM" ? !e.activeAutoAtt.regras[t].propriedades.active : !1
                        }
                    },
                    notResponderCRM: {
                        ...e.activeAutoAtt.regras.notResponderCRM,
                        propriedades: {
                            ...e.activeAutoAtt.regras.notResponderCRM.propriedades,
                            active: t === "notResponderCRM" ? !e.activeAutoAtt.regras[t].propriedades.active : !1
                        }
                    },
                    responderCRM: {
                        ...e.activeAutoAtt.regras.responderCRM,
                        propriedades: {
                            ...e.activeAutoAtt.regras.responderCRM.propriedades,
                            active: t === "responderCRM" ? !e.activeAutoAtt.regras[t].propriedades.active : !1
                        }
                    }
                }
            }
        })),
        setRegrasUpdateDias: t => {
            a(e => {
                const s = e.activeAutoAtt.regras.responderDias.propriedades[t].active;
                return {
                    activeAutoAtt: {
                        ...e.activeAutoAtt,
                        regras: {
                            ...e.activeAutoAtt.regras,
                            responderDias: {
                                ...e.activeAutoAtt.regras.responderDias,
                                propriedades: {
                                    ...e.activeAutoAtt.regras.responderDias.propriedades,
                                    [t]: {
                                        ...e.activeAutoAtt.regras.responderDias.propriedades[t],
                                        active: !s
                                    }
                                }
                            }
                        }
                    }
                }
            })
        },
        setRegrasUpdateHorario: (t, e, s) => {
            a(o => ({
                activeAutoAtt: {
                    ...o.activeAutoAtt,
                    regras: {
                        ...o.activeAutoAtt.regras,
                        responderDias: {
                            ...o.activeAutoAtt.regras.responderDias,
                            propriedades: {
                                ...o.activeAutoAtt.regras.responderDias.propriedades,
                                [t]: {
                                    ...o.activeAutoAtt.regras.responderDias.propriedades[t],
                                    horaInicio: e,
                                    horaFim: s
                                }
                            }
                        }
                    }
                }
            }))
        },
        setRegrasUpdateAssinatura: t => {
            a(e => {
                const s = e.activeAutoAtt.regras.assinatura.propriedades,
                    o = {
                        ...s
                    };
                return t === "persAss" ? (o.persAss = {
                    ...s.persAss,
                    active: !s.persAss.active
                }, o.persAss.active && (o.desativarAss = !1)) : t === "desativarAss" && (o.persAss = {
                    ...s.persAss,
                    active: !1
                }, o.desativarAss = !s.desativarAss), {
                    activeAutoAtt: {
                        ...e.activeAutoAtt,
                        regras: {
                            ...e.activeAutoAtt.regras,
                            assinatura: {
                                ...e.activeAutoAtt.regras.assinatura,
                                propriedades: o
                            }
                        }
                    }
                }
            })
        },
        setAssinaturaName: t => {
            a(e => {
                const s = e.activeAutoAtt.regras.assinatura.propriedades;
                return {
                    activeAutoAtt: {
                        ...e.activeAutoAtt,
                        regras: {
                            ...e.activeAutoAtt.regras,
                            assinatura: {
                                ...e.activeAutoAtt.regras.assinatura,
                                propriedades: {
                                    ...s,
                                    persAss: {
                                        ...s.persAss,
                                        nameAss: t
                                    }
                                }
                            }
                        }
                    }
                }
            })
        },
        setPeriodoAtivacao: t => {
            a(e => {
                const s = e.activeAutoAtt.regras.responderDias.propriedades[t];
                return {
                    activeAutoAtt: {
                        ...e.activeAutoAtt,
                        regras: {
                            ...e.activeAutoAtt.regras,
                            responderDias: {
                                ...e.activeAutoAtt.regras.responderDias,
                                propriedades: {
                                    ...e.activeAutoAtt.regras.responderDias.propriedades,
                                    [t]: {
                                        ...s,
                                        periodoAtivacao: !s.periodoAtivacao
                                    }
                                }
                            }
                        }
                    }
                }
            })
        },
        validateAutoAtt: () => {
            const {
                acao: t
            } = qe.getState(), {
                activeAutoAtt: e
            } = ge.getState(), s = e.regras.assinatura.propriedades || null, o = e.regras.responderDias.propriedades;
            return e.nome.length < 3 ? {
                success: !1,
                message: "O nome deve ter mais de 3 caracteres"
            } : e.acionamento.length === 0 ? (ge.getState().setActiveColapse("acionamento"), {
                success: !1,
                message: "O auto atendimento deve ter ao menos um acionamento"
            }) : t.length === 0 ? (ge.getState().setActiveColapse("script"), {
                success: !1,
                message: "O auto atendimento deve ter ao menos uma ação"
            }) : s != null && s.active && s.persAss.active && !s.persAss.nameAss ? (ge.getState().setActiveColapse("regras"), {
                success: !1,
                message: "O nome da assinatura deve ser preenchido"
            }) : s != null && s.active && !(s.desativarAss || s.persAss.active) ? (ge.getState().setActiveColapse("regras"), {
                success: !1,
                message: "A assinatura deve ter ao menos uma opção ativa"
            }) : o.active && !["segunda", "terca", "quarta", "quinta", "sexta", "sabado", "domingo"].some(n => o[n].active) ? (ge.getState().setActiveColapse("regras"), {
                success: !1,
                message: "Deve ter ao menos um dia ativo"
            }) : {
                success: !0
            }
        },
        addEtiqueta: (t, e) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                regras: {
                    ...s.activeAutoAtt.regras,
                    [t]: {
                        ...s.activeAutoAtt.regras[t],
                        propriedades: {
                            ...s.activeAutoAtt.regras[t].propriedades,
                            labelID: [...s.activeAutoAtt.regras[t].propriedades.labelID, e]
                        }
                    }
                }
            }
        })),
        removeEtiqueta: (t, e) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                regras: {
                    ...s.activeAutoAtt.regras,
                    [t]: {
                        ...s.activeAutoAtt.regras[t],
                        propriedades: {
                            ...s.activeAutoAtt.regras[t].propriedades,
                            labelID: s.activeAutoAtt.regras[t].propriedades.labelID.filter(o => o !== e)
                        }
                    }
                }
            }
        })),
        addCRM: (t, e) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                regras: {
                    ...s.activeAutoAtt.regras,
                    [t]: {
                        ...s.activeAutoAtt.regras[t],
                        propriedades: {
                            ...s.activeAutoAtt.regras[t].propriedades,
                            crm: [...s.activeAutoAtt.regras[t].propriedades.crm, e]
                        }
                    }
                }
            }
        })),
        removeCRM: (t, e) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                regras: {
                    ...s.activeAutoAtt.regras,
                    [t]: {
                        ...s.activeAutoAtt.regras[t],
                        propriedades: {
                            ...s.activeAutoAtt.regras[t].propriedades,
                            crm: s.activeAutoAtt.regras[t].propriedades.crm.filter(o => o !== e)
                        }
                    }
                }
            }
        }))
    })), He = {
        cancelAfterChat: {
            type: "cancelAfterChat",
            propriedades: {
                active: !1
            }
        },
        responderGrupos: {
            type: "responderGrupos",
            propriedades: {
                active: !1
            }
        },
        assinatura: {
            type: "assinatura",
            propriedades: {
                active: !1,
                desativarAss: !1,
                persAss: {
                    active: !1,
                    nameAss: ""
                }
            }
        }
    }, he = b()((a, t) => ({
        model: "Create",
        activeColapse: "funil",
        addAbaInFunil: e => a(s => {
            try {
                const o = {
                    ...s.activeFollowUp.funil
                };
                return o.abas.some(i => i.id === e.id) || o.abas.push(e), {
                    activeFollowUp: {
                        ...s.activeFollowUp,
                        funil: o
                    }
                }
            } catch (o) {
                console.error("Error in addAbaInFunil", o)
            }
        }),
        removeAbaInFunil: e => a(s => {
            try {
                const o = {
                    ...s.activeFollowUp.funil
                };
                return o.abas = o.abas.filter(r => r.id !== e), {
                    activeFollowUp: {
                        ...s.activeFollowUp,
                        funil: o
                    }
                }
            } catch (o) {
                console.error("Error in removeAbaInFunil", o)
            }
        }),
        addLabelInFunil: e => a(s => {
            try {
                const o = {
                    ...s.activeFollowUp.funil
                };
                return o.etiquetas.some(i => i.id === e.id) || o.etiquetas.push(e), {
                    activeFollowUp: {
                        ...s.activeFollowUp,
                        funil: o
                    }
                }
            } catch (o) {
                console.error("Error in addLabelInFunil", o)
            }
        }),
        LabelOrTabIsExist: e => {
            const o = t().activeFollowUp.funil,
                r = o.abas.some(n => n.id === e),
                i = o.etiquetas.some(n => n.id === e);
            return r || i
        },
        removeLabelInFunil: e => a(s => {
            try {
                const o = {
                    ...s.activeFollowUp.funil
                };
                return o.etiquetas = o.etiquetas.filter(r => r.id !== e), {
                    activeFollowUp: {
                        ...s.activeFollowUp,
                        funil: o
                    }
                }
            } catch (o) {
                console.error("Error in removeLabelInFunil", o)
            }
        }),
        activeTabOrLabel: y.getState().isBusiness ? "labels" : "userTabs",
        setActiveTabOrLabel: e => a(() => ({
            activeTabOrLabel: e
        })),
        setActiveColapse: e => a(() => ({
            activeColapse: e
        })),
        activeFollowUp: {
            id: E(),
            nome: "",
            active: !0,
            funil: {
                id: E(),
                abas: [],
                etiquetas: []
            },
            acionamento: {
                type: "dispararAoEntrar",
                timing: {
                    days: 0,
                    hours: 0,
                    minutes: 0
                }
            },
            acao: [],
            regras: He
        },
        setActiveFollowUp: (e, s) => a(o => ({
            activeFollowUp: {
                ...o.activeFollowUp,
                [e]: s
            }
        })),
        setResetDefaultFollowUp: () => a(e => ({
            model: "Create",
            activeFollowUp: {
                id: E(),
                nome: "",
                active: !0,
                funil: {
                    id: E(),
                    abas: [],
                    etiquetas: []
                },
                acionamento: {
                    type: "dispararAoEntrar",
                    timing: {
                        days: 0,
                        hours: 0,
                        minutes: 0
                    }
                },
                acao: [],
                regras: He
            },
            activeColapse: "funil"
        })),
        setEditFollowUp: e => a(() => (e.regras || (e.regras = He), e.regras.cancelAfterChat || (e.regras.cancelAfterChat = {
            type: "cancelAfterChat",
            propriedades: {
                active: !1
            }
        }), e.regras.responderGrupos || (e.regras.responderGrupos = {
            type: "responderGrupos",
            propriedades: {
                active: !1
            }
        }), e.regras.assinatura || (e.regras.assinatura = {
            type: "assinatura",
            propriedades: {
                active: !1,
                desativarAss: !1,
                persAss: {
                    active: !1,
                    nameAss: ""
                }
            }
        }), e.funil || (e.funil = {
            id: E(),
            abas: [],
            etiquetas: []
        }), {
            model: "Edit",
            activeFollowUp: e,
            activeColapse: "funil"
        })),
        setTimingAcionamento: e => a(s => ({
            activeFollowUp: {
                ...s.activeFollowUp,
                acionamento: {
                    ...s.activeFollowUp.acionamento,
                    timing: e
                }
            }
        })),
        setDispararAcionamento: e => a(s => ({
            activeFollowUp: {
                ...s.activeFollowUp,
                acionamento: {
                    ...s.activeFollowUp.acionamento,
                    type: e
                }
            }
        })),
        setCreateAcao: (e, s = {}) => a(o => ({
            activeFollowUp: {
                ...o.activeFollowUp,
                acao: [...o.activeFollowUp.acao, {
                    id: E(),
                    type: e,
                    propriedades: s
                }]
            }
        })),
        setRemoveAcao: e => a(s => ({
            activeFollowUp: {
                ...s.activeFollowUp,
                acao: s.activeFollowUp.acao.filter(o => o.id !== e)
            }
        })),
        setAcaoPropriedades: (e, s) => a(o => ({
            activeFollowUp: {
                ...o.activeFollowUp,
                acao: o.activeFollowUp.acao.map(r => r.id === e ? {
                    ...r,
                    propriedades: {
                        ...r.propriedades,
                        ...s
                    }
                } : r)
            }
        })),
        sortAcoes: e => a(s => {
            const o = [...s.activeFollowUp.acao],
                r = Array.from(o),
                [i] = r.splice(e.source.index, 1);
            return r.splice(e.destination.index, 0, i), {
                activeFollowUp: {
                    ...s.activeFollowUp,
                    acao: r
                }
            }
        }),
        setRegraUpdate: e => a(s => ({
            activeFollowUp: {
                ...s.activeFollowUp,
                regras: {
                    ...s.activeFollowUp.regras,
                    [e]: {
                        ...s.activeFollowUp.regras[e],
                        propriedades: {
                            ...s.activeFollowUp.regras[e].propriedades,
                            active: !s.activeFollowUp.regras[e].propriedades.active
                        }
                    }
                }
            }
        })),
        setRegrasUpdateAssinatura: e => {
            a(s => {
                const o = s.activeFollowUp.regras.assinatura.propriedades,
                    r = {
                        ...o
                    };
                return e === "persAss" ? (r.persAss = {
                    ...o.persAss,
                    active: !o.persAss.active
                }, r.persAss.active && (r.desativarAss = !1)) : e === "desativarAss" && (r.persAss = {
                    ...o.persAss,
                    active: !1
                }, r.desativarAss = !o.desativarAss), {
                    activeFollowUp: {
                        ...s.activeFollowUp,
                        regras: {
                            ...s.activeFollowUp.regras,
                            assinatura: {
                                ...s.activeFollowUp.regras.assinatura,
                                propriedades: r
                            }
                        }
                    }
                }
            })
        },
        setAssinaturaName: e => {
            a(s => {
                const o = s.activeFollowUp.regras.assinatura.propriedades;
                return {
                    activeFollowUp: {
                        ...s.activeFollowUp,
                        regras: {
                            ...s.activeFollowUp.regras,
                            assinatura: {
                                ...s.activeFollowUp.regras.assinatura,
                                propriedades: {
                                    ...o,
                                    persAss: {
                                        ...o.persAss,
                                        nameAss: e
                                    }
                                }
                            }
                        }
                    }
                }
            })
        },
        validateFollowUp: () => {
            const {
                acao: e
            } = Pe.getState(), {
                activeFollowUp: s
            } = he.getState(), o = s.regras.assinatura.propriedades || null, r = s.acionamento.type || null, {
                days: i,
                hours: n,
                minutes: c
            } = s.acionamento.timing || null;
            return s.nome.length < 3 ? {
                success: !1,
                message: "O nome deve ter mais de 3 caracteres"
            } : s.funil.abas.length === 0 && s.funil.etiquetas.length === 0 ? (he.getState().setActiveColapse("funil"), {
                success: !1,
                message: "O funil deve ter ao menos uma aba ou etiqueta adicionada"
            }) : !r && !i && !n && !c ? (he.getState().setActiveColapse("acionamento"), {
                success: !1,
                message: "O acionamento deve ter ao menos um tempo configurado"
            }) : e.length === 0 ? (he.getState().setActiveColapse("script"), {
                success: !1,
                message: "O follow up deve ter ao menos uma ação"
            }) : o != null && o.active && o.persAss.active && !o.persAss.nameAss ? (he.getState().setActiveColapse("regras"), {
                success: !1,
                message: "O nome da assinatura deve ser preenchido"
            }) : o != null && o.active && !(o.desativarAss || o.persAss.active) ? (he.getState().setActiveColapse("regras"), {
                success: !1,
                message: "A assinatura deve ter ao menos uma opção ativa"
            }) : {
                success: !0
            }
        }
    })), Me = {
        useAcaoRespostaRapida: {
            size: "medium",
            arrow: !1,
            overflow: !1
        },
        useAcaoAutoAtendimento: {
            size: "large",
            inputName: "my-accordion-2",
            OnOpen: () => ge.getState().setActiveColapse("script"),
            arrow: !0,
            overflow: !0
        },
        useAcaoFollowUp: {
            size: "large",
            inputName: "my-accordion-2",
            OnOpen: () => he.getState().setActiveColapse("script"),
            arrow: !0,
            overflow: !0
        },
        useAcaoEditAndSendRes: {
            size: "large",
            arrow: !1,
            overflow: !0
        },
        useAcaoEnvioEmMassa: {
            size: "medium",
            arrow: !1,
            overflow: !0,
            style: {
                primaria: "var(--conversation-panel-background)",
                secundaria: "var(--outgoing-background)",
                hover: "var(--incoming-background)"
            }
        },
        useAcaoEnvioEmMassaNew: {
            size: "medium",
            arrow: !1,
            overflow: !0
        }
    }, Te = a => b()((t, e) => ({
        model: a,
        setModel: s => t({
            model: s
        }),
        acao: [],
        setAcao: s => t({
            acao: s
        }),
        setCreateAcao: (s, o = {}) => t(r => ({
            acao: [...r.acao, {
                id: E(),
                type: s,
                propriedades: o
            }]
        })),
        setRemoveAcao: s => t(o => ({
            acao: o.acao.filter(r => r.id !== s)
        })),
        setAcaoPropriedades: (s, o) => t(r => ({
            acao: r.acao.map(i => i.id === s ? {
                ...i,
                propriedades: {
                    ...i.propriedades,
                    ...o
                }
            } : i)
        })),
        clearAcao: () => t({
            acao: []
        }),
        sortAcoes: s => t(o => {
            const r = [...o.acao],
                i = Array.from(r),
                [n] = i.splice(s.oldIndex, 1);
            return i.splice(s.newIndex, 0, n), {
                acao: i
            }
        }),
        updateAcaoRowField: (s, o, r, i, n) => t(c => ({
            acao: c.acao.map(l => l.id !== s ? l : {
                ...l,
                propriedades: {
                    ...l.propriedades,
                    sections: l.propriedades.sections.map(d => d.sectionId !== o ? d : {
                        ...d,
                        rows: d.rows.map(u => u.rowId === r ? {
                            ...u,
                            [i]: n
                        } : u)
                    })
                }
            })
        }))
    })), Kt = Te(Me.useAcaoRespostaRapida), qe = Te(Me.useAcaoAutoAtendimento), Pe = Te(Me.useAcaoFollowUp), co = Te(Me.useAcaoEditAndSendRes), lo = Te(Me.useAcaoEnvioEmMassa), uo = Te(Me.useAcaoEnvioEmMassaNew), wi = {
        useAcaoRespostaRapida: Kt,
        useAcaoAutoAtendimento: qe,
        useAcaoFollowUp: Pe,
        useAcaoEditAndSendRes: co,
        useAcaoEnvioEmMassa: lo,
        useAcaoEnvioEmMassaNew: uo
    }, ke = b()(a => ({
        autoAtendimento: [],
        createAutoAtendimento: t => a(e => {
            const {
                acao: s
            } = qe.getState(), r = [{
                ...t,
                acao: s
            }, ...e.autoAtendimento];
            return f("autoatendimento", r), {
                autoAtendimento: r
            }
        }),
        editAutoAtendimento: t => a(e => {
            const {
                acao: s
            } = qe.getState(), o = {
                ...t,
                acao: s
            }, r = e.autoAtendimento.map(i => i.id === o.id ? o : i);
            return f("autoatendimento", r), {
                autoAtendimento: r
            }
        }),
        deleteAutoAtendimento: t => a(e => {
            const s = e.autoAtendimento.filter(o => o.id !== t);
            return f("autoatendimento", s), {
                autoAtendimento: s
            }
        }),
        duplicateAutoAtendimento: t => a(e => {
            const s = e.getAutoAtendimento(t),
                o = s.nome.includes("(Cópia") ? s.nome.split(" (Cópia")[0] : s.nome,
                r = e.autoAtendimento.filter(c => c.nome.startsWith(o + " (Cópia")).length,
                n = [{
                    ...s,
                    id: E(),
                    nome: `${o} (Cópia${r>0?` ${r+1}`:""})`,
                    usedLenght: 0
                }, ...e.autoAtendimento];
            return f("autoatendimento", n), {
                autoAtendimento: n
            }
        }),
        getAutoAtendimento: t => ke.getState().autoAtendimento.find(s => s.id === t),
        switchActive: t => a(e => {
            const s = e.autoAtendimento.map(o => o.id === t ? {
                ...o,
                active: !o.active
            } : o);
            return f("autoatendimento", s), {
                autoAtendimento: s
            }
        }),
        updateUsedLenght: t => a(e => {
            const s = e.autoAtendimento.map(o => o.id === t ? {
                ...o,
                usedLenght: o.usedLenght + 1
            } : o);
            return f("autoatendimento", s), {
                autoAtendimento: s
            }
        })
    })), po = a => {
        ke.setState({
            autoAtendimento: a
        }), f("autoatendimento", a)
    }, yi = a => {
        const t = ke.getState().autoAtendimento,
            e = new Set(t.map(s => s.id));
        a.forEach(s => {
            e.has(s.id) || (t.push(s), e.add(s.id))
        }), po(t)
    }, xi = async () => {
        const a = await G("autoatendimento") || [];
        ke.setState({
            autoAtendimento: a
        })
    }, mo = b()((a, t) => ({
        quickReplies: [],
        addQuickReply: e => a(s => {
            const o = [...s.quickReplies, e];
            return f("respostasRapidas", o), {
                quickReplies: o
            }
        }),
        editQuickReply: e => a(s => {
            const o = s.quickReplies.map(r => r.id === e.id ? e : r);
            return f("respostasRapidas", o), {
                quickReplies: o
            }
        }),
        getQuickReply: (e, s) => {
            const {
                quickReplies: o
            } = t(), r = o.find(n => n.id === e);
            return (r == null ? void 0 : r[s]) || r
        },
        deleteQuickReply: e => a(s => {
            const o = s.quickReplies.filter(r => r.id !== e);
            return f("respostasRapidas", o), {
                quickReplies: o
            }
        }),
        sortQuickReply: e => a(() => (f("respostasRapidas", e), {
            quickReplies: e
        }))
    })), H = b()(() => ({
        activeChat: null
    }));
var fo = fa();
const Ge = ma(fo),
    _e = b(a => ({
        contatos: [],
        setContatos: async t => (await f("contatos", t), y.getState().plugin_page ? z("setContatos", {
            contatos: t
        }, !1) : chrome.runtime.sendMessage({
            action: "setContatos",
            dados: {
                contatos: t
            }
        }), a(() => ({
            contatos: t
        })), {
            contatos: t
        })
    })),
    go = async a => {
        _e.setState({
            contatos: a
        }), m.Utils("contatoInit", a), await f("contatos", a), chrome.runtime.sendMessage({
            action: "contatos-backup-update"
        })
    }, Ci = a => {
        const t = [..._e.getState().contatos];
        a.forEach(e => {
            const s = t.findIndex(o => o.id === e.id);
            s === -1 ? t.push(e) : t[s] = e
        }), go(t)
    }, ho = async () => {
        const a = await G("contatos") || [];
        m.Utils("contatoInit", a), _e.setState({
            contatos: a
        })
    }, {
        setContatos: vo
    } = _e.getState();
chrome.runtime.onMessage.addListener(a => {
    switch (a.action) {
        case "setContatos":
            chrome.storage.local.get("contatos", t => {
                JSON.stringify(t.contatos) !== JSON.stringify(_e.getState().contatos) && (vo(t.contatos), m.Utils("contatoInit", t.contatos))
            });
            break;
        case "contatos-backup-update":
            ho();
            break
    }
});
const et = b()(a => ({
    chatName: {
        name: "",
        number: "",
        autoSave: !1
    },
    setAutoSaveChatName: t => a(e => (O("autoSaveChat", "autoSave", [t]), {
        chatName: {
            ...e.chatName,
            autoSave: t
        }
    })),
    getActiveChat: async t => {
        const {
            contatos: e,
            setContatos: s
        } = _e.getState(), {
            chatName: o,
            setAutoSaveChatName: r
        } = et.getState(), i = await m.Utils("getContato", t), n = e.find(c => c.id === t);
        if (a(n ? {
                chatName: {
                    ...o,
                    name: n.name,
                    number: t
                }
            } : {
                chatName: {
                    ...o,
                    name: i.name,
                    number: t
                }
            }), o.autoSave && await ae("contatos") === !0) {
            r(!1);
            return
        }
        if (o.autoSave && !n && i.name !== i.number) {
            const c = {
                id: t,
                name: i.name
            };
            m.Utils("contatoSave", c);
            const l = [...e, c];
            s(l)
        }
    }
}));
(async () => {
    const a = await Q("autoSaveChat", "autoSave");
    a && a[0] && a[0][0] && et.getState().setAutoSaveChatName(a[0][0])
})();
const I = b()(a => ({
        assinatura: {
            multiAtendimento: !1,
            active: !1,
            name: ""
        },
        timeout: null,
        setAssinatura: (t, e) => a(s => {
            const o = {
                ...s.assinatura,
                [t]: e
            };
            return O("useAssinatura", "assinatura", [o]), s.dispartAssMultiAtendimento(), {
                assinatura: o
            }
        }),
        setMultiATendimento: () => a(t => {
            const {
                connect: e,
                disconnect: s
            } = Z.getState(), {
                whatsappID: o
            } = y.getState(), {
                language: r
            } = _.getState(), i = {
                ...t.assinatura
            };
            return t.assinatura.multiAtendimento ? (i.multiAtendimento = !1, s()) : i.name.length < 2 ? N({
                type: "Error",
                message: r.insiraUmNomeCom3Caracteres,
                position: "top-right"
            }) : (i.multiAtendimento = !0, e(o)), O("useAssinatura", "assinatura", [i]), {
                assinatura: i
            }
        }),
        sendTextChat: async () => {
            var l, d;
            const t = Z.getState().addLocalAtendente,
                {
                    assinatura: e
                } = I.getState(),
                s = (d = (l = H.getState().activeChat) == null ? void 0 : l.id) == null ? void 0 : d._serialized,
                {
                    getSeletor: o
                } = D.getState(),
                {
                    language: r
                } = _.getState(),
                i = o("footerTextArea"),
                n = [...(i == null ? void 0 : i.childNodes) ?? []].map(u => u.innerText !== `
` ? u.innerText : "").join(`
`);
            if (!i || !n.trim()) return;
            let c;
            await ae("assinatura") === !0 ? (c = n, I.getState().setAssinatura("active", !1), N({
                type: "Info",
                message: r.assinaturaDesativada,
                position: "top-right"
            })) : c = e.active ? `*_${e.name}:_* 
${n}` : n, o("assEmoji", u => {
                u == null || u.click()
            }), o("assCitacao", u => {
                u == null || u.click()
            }), m.Functions("sendTextChat", {
                chatID: s,
                formattedMessage: c
            }), t(s, "Ativo")
        },
        configAssinatura: () => {
            const {
                getSeletor: t
            } = D.getState(), {
                activeChat: e
            } = H.getState();
            if (!e) return;
            const s = l => {
                    l.key === "Enter" && I.getState().assinatura.active && (l.stopPropagation(), I.getState().sendTextChat())
                },
                o = Ge(t("assChat"));
            o.off("keypress"), o.on("keypress", s);
            const r = l => {
                l.key === "Enter" && !l.shiftKey && !l.altKey && I.getState().assinatura.active && (l.preventDefault(), l.stopPropagation(), I.getState().sendTextChat())
            };
            t("assInput", l => {
                var u;
                const d = Ge(l);
                d.off("keydown"), d[0] && !d.data("keydownEventAdded") && ((u = d[0]) == null || u.addEventListener("keydown", r, !0), d == null || d.data("keydownEventAdded", !0))
            });
            const i = l => {
                I.getState().assinatura.active && (l.preventDefault(), l.stopPropagation(), I.getState().sendTextChat())
            };
            t("assBtn", l => {
                var u;
                const d = Ge(l);
                d == null || d.off("click"), d[0] && !d.data("ClickEventAdded") && ((u = d[0]) == null || u.addEventListener("click", i, !0), d == null || d.data("ClickEventAdded", !0))
            });
            const n = t("mainAudio"),
                c = new MutationObserver(l => {
                    l[0].removedNodes.length !== 0 && (o.off("keypress"), c.disconnect(), I.getState().configAssinatura())
                });
            n && c.observe(n, {
                childList: !0
            })
        },
        insertName: () => {
            var i, n;
            const {
                chatName: t
            } = et.getState(), e = (n = (i = H.getState().activeChat) == null ? void 0 : i.id) == null ? void 0 : n._serialized, {
                getSeletor: s
            } = D.getState(), o = s("footerTextArea"), r = [...(o == null ? void 0 : o.childNodes) ?? []].map(c => c.innerText !== `
` ? c.innerText : "").join(`
`);
            m.Chat("setInputText", {
                txt: r.trim() ? r + " " + t.name : t.name,
                id: e
            })
        },
        dispartAssMultiAtendimento: () => {
            var s, o;
            const {
                timeout: t
            } = I.getState(), e = (o = (s = H.getState().activeChat) == null ? void 0 : s.id) == null ? void 0 : o._serialized;
            t && clearTimeout(t), a({
                timeout: setTimeout(() => {
                    Z.getState().update(e)
                }, 2500)
            })
        }
    })),
    Mi = async () => {
        const a = await Q("useAssinatura", "assinatura");
        a && a[0] && a[0][0] && I.setState({
            assinatura: a[0][0]
        })
    };

function Ao(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M12 9v4"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M10.363 3.591l-8.106 13.534a1.914 1.914 0 0 0 1.636 2.871h16.214a1.914 1.914 0 0 0 1.636 -2.87l-8.106 -13.536a1.914 1.914 0 0 0 -3.274 0z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M12 16h.01"
            },
            child: []
        }]
    })(a)
}

function Ti(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M18 9l3 3l-3 3"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M15 12h6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M6 9l-3 3l3 3"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M3 12h6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M9 18l3 3l3 -3"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M12 15v6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M15 6l-3 -3l-3 3"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M12 3v6"
            },
            child: []
        }]
    })(a)
}

function ki(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M16.5 10c3.038 0 5.5 2.015 5.5 4.5c0 1.397 -.778 2.645 -2 3.47l0 2.03l-1.964 -1.178a6.649 6.649 0 0 1 -1.536 .178c-3.038 0 -5.5 -2.015 -5.5 -4.5s2.462 -4.5 5.5 -4.5z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M11.197 15.698c-.69 .196 -1.43 .302 -2.197 .302a8.008 8.008 0 0 1 -2.612 -.432l-2.388 1.432v-2.801c-1.237 -1.082 -2 -2.564 -2 -4.199c0 -3.314 3.134 -6 7 -6c3.782 0 6.863 2.57 7 5.785l0 .233"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M10 8h.01"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M7 8h.01"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M15 14h.01"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M18 14h.01"
            },
            child: []
        }]
    })(a)
}

function _i(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M14 4h6v6h-6z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M4 14h6v6h-6z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M17 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M7 7m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"
            },
            child: []
        }]
    })(a)
}

function Ri(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1"
            },
            child: []
        }]
    })(a)
}

function Li(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M11.192 17.966c-3.242 -.28 -5.972 -2.269 -8.192 -5.966c2.4 -4 5.4 -6 9 -6c3.326 0 6.14 1.707 8.442 5.122"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M18.42 15.61a2.1 2.1 0 0 1 2.97 2.97l-3.39 3.42h-3v-3l3.42 -3.39z"
            },
            child: []
        }]
    })(a)
}

function Ui(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M12 20l-3 1v-8.5l-4.48 -4.928a2 2 0 0 1 -.52 -1.345v-2.227h16v2.172a2 2 0 0 1 -.586 1.414l-4.414 4.414v1.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19.001 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19.001 15.5v1.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19.001 21v1.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M22.032 17.25l-1.299 .75"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M17.27 20l-1.3 .75"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M15.97 17.25l1.3 .75"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M20.733 20l1.3 .75"
            },
            child: []
        }]
    })(a)
}

function Ei(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M12 19h-7a2 2 0 0 1 -2 -2v-11a2 2 0 0 1 2 -2h4l3 3h7a2 2 0 0 1 2 2v3.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19 16v6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M22 19l-3 3l-3 -3"
            },
            child: []
        }]
    })(a)
}

function Fi(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M4 14v-3a8 8 0 1 1 16 0v3"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M18 19c0 1.657 -2.686 3 -6 3"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M4 14a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v3a2 2 0 0 1 -2 2h-1a2 2 0 0 1 -2 -2v-3z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M15 14a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v3a2 2 0 0 1 -2 2h-1a2 2 0 0 1 -2 -2v-3z"
            },
            child: []
        }]
    })(a)
}

function Ni(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M8 9h8"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M8 13h6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M12 21l-3 -3h-3a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19 19m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M17 21l4 -4"
            },
            child: []
        }]
    })(a)
}

function Ii(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M8 9h8"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M8 13h6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M12 21l-1 -1l-2 -2h-3a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M20 21l2 -2l-2 -2"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M17 17l-2 2l2 2"
            },
            child: []
        }]
    })(a)
}

function qi(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M8 9h8"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M8 13h6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M12 21l-3 -3h-3a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M16 22l5 -5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M21 21.5v-4.5h-4.5"
            },
            child: []
        }]
    })(a)
}

function Pi(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M12.007 19.98a9.869 9.869 0 0 1 -4.307 -.98l-4.7 1l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c1.992 1.7 2.93 4.04 2.747 6.34"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M16 19h6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19 16v6"
            },
            child: []
        }]
    })(a)
}

function zi(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M8 9h8"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M8 13h4.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M10.325 19.605l-2.325 1.395v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v4.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M17.8 20.817l-2.172 1.138a.392 .392 0 0 1 -.568 -.41l.415 -2.411l-1.757 -1.707a.389 .389 0 0 1 .217 -.665l2.428 -.352l1.086 -2.193a.392 .392 0 0 1 .702 0l1.086 2.193l2.428 .352a.39 .39 0 0 1 .217 .665l-1.757 1.707l.414 2.41a.39 .39 0 0 1 -.567 .411l-2.172 -1.138z"
            },
            child: []
        }]
    })(a)
}

function Di(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M8 9h8"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M8 13h6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M11.99 18.606l-3.99 2.394v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v5.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19 22v-6"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M22 19l-3 -3l-3 3"
            },
            child: []
        }]
    })(a)
}

function ji(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M7 12l5 5l-1.5 1.5a3.536 3.536 0 1 1 -5 -5l1.5 -1.5z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M17 12l-5 -5l1.5 -1.5a3.536 3.536 0 1 1 5 5l-1.5 1.5z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M3 21l2.5 -2.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M18.5 5.5l2.5 -2.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M10 11l-2 2"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M13 14l-2 2"
            },
            child: []
        }]
    })(a)
}

function Oi(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M9 3m0 2a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M9 17v-5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M12 17v-1"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M15 17v-3"
            },
            child: []
        }]
    })(a)
}

function Wi(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M12.003 21c-.732 .001 -1.465 -.438 -1.678 -1.317a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c.886 .215 1.325 .957 1.318 1.694"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19.001 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19.001 15.5v1.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M19.001 21v1.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M22.032 17.25l-1.299 .75"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M17.27 20l-1.3 .75"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M15.97 17.25l1.3 .75"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M20.733 20l1.3 .75"
            },
            child: []
        }]
    })(a)
}

function Bi(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M9 10a3 3 0 1 0 6 0a3 3 0 0 0 -6 0"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M6 21v-1a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v1"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M3 5a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-14z"
            },
            child: []
        }]
    })(a)
}

function Vi(a) {
    return L({
        attr: {
            viewBox: "0 0 24 24",
            fill: "none",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
        },
        child: [{
            tag: "path",
            attr: {
                d: "M3 19c3.333 -2 5 -4 5 -6c0 -3 -1 -3 -2 -3s-2.032 1.085 -2 3c.034 2.048 1.658 2.877 2.5 4c1.5 2 2.5 2.5 3.5 1c.667 -1 1.167 -1.833 1.5 -2.5c1 2.333 2.333 3.5 4 3.5h2.5"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M20 17v-12c0 -1.121 -.879 -2 -2 -2s-2 .879 -2 2v12l2 2l2 -2z"
            },
            child: []
        }, {
            tag: "path",
            attr: {
                d: "M16 7h4"
            },
            child: []
        }]
    })(a)
}
const Y = b()((a, t) => ({
        initSubscribeUserTabs: !1,
        FollowUp: [],
        createFollowUp: e => a(s => {
            const {
                acao: o
            } = Pe.getState(), i = [{
                ...e,
                acao: o
            }, ...s.FollowUp];
            return f("FollowUp", i), {
                FollowUp: i
            }
        }),
        editFollowUp: e => a(s => {
            const {
                acao: o
            } = Pe.getState(), r = {
                ...e,
                acao: o
            }, i = s.FollowUp.map(n => n.id === r.id ? r : n);
            return f("FollowUp", i), {
                FollowUp: i
            }
        }),
        deleteFollowUp: e => {
            const s = _.getState().language;
            da({
                icon: g.jsx(Ao, {
                    className: "text-[var(--primaria)]",
                    size: 22
                }),
                content: g.jsxs(g.Fragment, {
                    children: [s.removeFollowUp, g.jsxs("strong", {
                        children: [" ", e.nome]
                    }), "?"]
                }),
                confirmText: s.confirm,
                submit: () => o()
            });
            const o = () => {
                a(r => {
                    const i = r.FollowUp.filter(n => n.id !== e.id);
                    return f("FollowUp", i), {
                        FollowUp: i
                    }
                }), N({
                    type: "Success",
                    message: s.followUpRemovedSuccess,
                    position: "top-right"
                })
            }
        },
        duplicateFollowUp: e => a(s => {
            const o = _.getState().language,
                r = s.getFollowById(e),
                i = r.nome.includes(`(${o.copy}`) ? r.nome.split(` (${o.copy}`)[0] : r.nome,
                n = s.FollowUp.filter(d => d.nome.startsWith(i + ` (${o.copy}`)).length,
                l = [{
                    ...r,
                    id: E(),
                    nome: `${i} (${o.copy}${n>0?` ${n+1}`:""})`
                }, ...s.FollowUp];
            return f("FollowUp", l), {
                FollowUp: l
            }
        }),
        getFollowById: e => t().FollowUp.find(s => s.id === e),
        switchActive: e => a(s => {
            const o = _.getState().language,
                r = s.getFollowById(e);
            if (r.funil.abas.length === 0 && r.funil.etiquetas.length === 0) return N({
                type: "Error",
                message: o.followUpNotAllowedToActive,
                position: "top-right"
            }), s;
            const n = s.FollowUp.map(c => c.id === e ? {
                ...c,
                active: !c.active
            } : c);
            return f("FollowUp", n), {
                FollowUp: n
            }
        }),
        disableFollowUp: e => a(s => {
            const o = s.FollowUp.map(r => r.id === e ? {
                ...r,
                active: !1
            } : r);
            return f("FollowUp", o), {
                FollowUp: o
            }
        }),
        addChatToFollowUp: (e, s, o, r) => a(i => {
            try {
                const n = i.FollowUp.map(c => {
                    if (c.id === e) {
                        const l = {
                            ...o,
                            date: c.acionamento.type === "timing" ? Date.now() : null
                        };
                        if (r === "tab") return {
                            ...c,
                            funil: {
                                ...c.funil,
                                abas: c.funil.abas.map(d => {
                                    if (d.id === s) {
                                        const u = d.chats.filter(p => p.id !== o.id);
                                        return {
                                            ...d,
                                            chats: [...u, l]
                                        }
                                    }
                                    return d
                                })
                            }
                        };
                        if (r === "label") return {
                            ...c,
                            funil: {
                                ...c.funil,
                                etiquetas: c.funil.etiquetas.map(d => {
                                    if (d.id === s) {
                                        const u = d.chats.filter(p => p.id !== o.id);
                                        return {
                                            ...d,
                                            chats: [...u, l]
                                        }
                                    }
                                    return d
                                })
                            }
                        }
                    }
                    return c
                });
                return f("FollowUp", n), {
                    FollowUp: n
                }
            } catch (n) {
                return console.error("❌ Erro ao adicionar chat ao follow-up:", n), i
            }
        }),
        removeChatFromFollowUp: (e, s, o, r) => a(i => {
            try {
                const n = i.FollowUp.map(c => {
                    if (c.id === e) {
                        if (r === "tab") return {
                            ...c,
                            funil: {
                                ...c.funil,
                                abas: c.funil.abas.map(l => l.id === s ? {
                                    ...l,
                                    chats: l.chats.filter(d => d.id !== o)
                                } : l)
                            }
                        };
                        if (r === "label") return {
                            ...c,
                            funil: {
                                ...c.funil,
                                etiquetas: c.funil.etiquetas.map(l => l.id === s ? {
                                    ...l,
                                    chats: l.chats.filter(d => d.id !== o)
                                } : l)
                            }
                        }
                    }
                    return c
                });
                return f("FollowUp", n), {
                    FollowUp: n
                }
            } catch (n) {
                return console.error("Erro ao remover chat do follow-up:", n), i
            }
        }),
        removeTabFromFunnels: e => a(s => {
            const o = s.FollowUp.map(r => {
                const i = r.funil.abas.filter(n => !e.some(c => c.id === n.id));
                return i.length !== r.funil.abas.length ? {
                    ...r,
                    funil: {
                        ...r.funil,
                        abas: i
                    }
                } : r
            });
            return f("FollowUp", o), {
                FollowUp: o
            }
        })
    })),
    bo = a => {
        Y.setState({
            FollowUp: a
        }), f("FollowUp", a)
    },
    $i = a => {
        const t = Y.getState().FollowUp,
            e = new Set(t.map(s => s.id));
        a.forEach(s => {
            e.has(s.id) || (t.push(s), e.add(s.id))
        }), bo(t)
    },
    Hi = async () => {
        try {
            const a = await G("FollowUp") || [];
            Y.setState({
                FollowUp: a
            })
        } catch (a) {
            console.error("Failed to initialize FollowUp:", a)
        }
    };

function So(a) {
    var s, o, r;
    if (a.id.fromMe) return;
    const {
        FollowUp: t,
        removeChatFromFollowUp: e
    } = Y.getState();
    for (let i of t)
        if ((r = (o = (s = i == null ? void 0 : i.regras) == null ? void 0 : s.cancelAfterChat) == null ? void 0 : o.propriedades) != null && r.active) {
            for (let n of i.funil.abas) e(i.id, n.id, a.id.remote, "tab");
            for (let n of i.funil.etiquetas) e(i.id, n.id, a.id.remote, "label")
        }
}
const wo = b()(a => ({
    monitors: [],
    addMonitor: t => a(e => ({
        monitors: [...e.monitors, t]
    })),
    stopSendAction: t => a(e => ({
        monitors: e.monitors.map(s => s.id === t ? {
            ...s,
            sendAction: "Canceled"
        } : s)
    })),
    deleteMonitor: t => a(e => ({
        monitors: e.monitors.filter(s => s.id !== t)
    })),
    updateMonitor: (t, e, s) => {
        let o = !0;
        return a(r => ({
            monitors: r.monitors.map(i => i.id === t ? (i.sendAction === "Canceled" && (o = !1), {
                ...i,
                actionIndice: e + 1,
                activeAction: s
            }) : i)
        })), o
    }
}));
async function Re(a) {
    if (!(a == null || a == 0)) return new Promise(t => {
        setTimeout(() => {
            t()
        }, a * 1e3)
    })
}
async function be(a, t, e) {
    t == null || t == 0 || (m.Chat(e === "txt" ? "markIsComposing" : "markIsRecording", {
        id: a,
        timer: t * 1e3
    }), await Re(t))
}

function tt(a, t) {
    const {
        assinatura: e
    } = I.getState();
    return t.desativar ? a : t.personalizar ? `*_${t.nome}:_*
${a}` : e.active ? `*_${e.name}:_*
${a}` : a
}
const yo = async (a, t) => {
    let e = "";
    return (t.includes("#nome") || t.includes("#primeiroNome")) && (e = (await m.Utils("getContato", a)).name), e
}, xo = () => {
    const {
        idioma: a
    } = _.getState(), t = {
        pt: ["Olá, tudo bem?", "Olá, tudo bom?", "Oi, tudo bem?", "Oi, tudo bom?", "E ai, tudo bem?", "E ai, tudo bom?"],
        en: ["Hello, how are you?", "Hello, how's it going?", "Hi, how are you?", "Hi, how's it going?", "Hey, how are you?", "Hey, how's it going?"],
        es: ["Hola, ¿cómo estás?", "Hola, ¿qué tal?", "Hola, ¿cómo estás?", "Hola, ¿qué tal?", "¿Qué onda, cómo estás?", "¿Qué onda, qué tal?"]
    }, e = Math.floor(Math.random() * t[a].length);
    return t[a][e]
}, Co = () => {
    const {
        idioma: a
    } = _.getState(), e = new Date().getHours(), s = {
        pt: {
            manha: "Bom dia",
            tarde: "Boa tarde",
            noite: "Boa noite"
        },
        en: {
            manha: "Good morning",
            tarde: "Good afternoon",
            noite: "Good evening"
        },
        es: {
            manha: "Buenos días",
            tarde: "Buenas tardes",
            noite: "Buenas noches"
        }
    };
    return e >= 6 && e < 12 ? s[a].manha : e >= 12 && e < 18 ? s[a].tarde : s[a].noite
};
async function ze(a, t) {
    const e = await yo(a, t);
    try {
        t = t.replaceAll("#saudação", xo), t = t.replaceAll("#periodo-dia", Co), t = t.replaceAll("#primeiroNome", e.split(" ")[0]), t = t.replaceAll("#nome", e), t = t.replaceAll("#numero", a.replace("@g.us", "").replace("@c.us", ""))
    } catch (s) {
        console.error("Erro ao validar existência de uma variável", s)
    }
    return t
}
const Mo = a => {
    let t = 0;
    if (a)
        for (let e of a) t += parseFloat(e.valor);
    return t.toLocaleString("pt-BR", {
        style: "currency",
        currency: "BRL"
    })
};

function De(a, t) {
    const {
        getPerfilContato: e
    } = $.getState();
    try {
        const s = e(a);
        if (!s) return t;
        t = t.replaceAll("#sexo", s.sexo), t = t.replaceAll("#data_nascimento", s.dataNascimento), t = t.replaceAll("#idioma", s.idioma), t = t.replaceAll("#email", s.email), t = t.replaceAll("#cidade", s.cidade), t = t.replaceAll("#estado", s.estado), t = t.replaceAll("#origem", s.origemLead), t = t.replaceAll("#data_entrada", s.entrada), t = t.replaceAll("#data_saida", s.saida), t = t.replaceAll("#valor_negocio", Mo(s.valNegocio || [])), t = t.replaceAll("#empresa", s.empresa), t = t.replaceAll("#cargo", s.cargo), t = t.replaceAll("#produtos_de_interesse", s.produtos.toString()), t = t.replaceAll("#observações", s.observacoes)
    } catch (s) {
        console.error(`Erro ao tentar capturar o perfil do contato de ${a}`, s)
    } finally {
        return t
    }
}
async function at(a, t) {
    if (t.includes("#mencionar-todos") && a.includes("@g.us")) {
        const s = (await m.Group("getParticipants", a)).map(r => r.id.toString()),
            o = s.map(r => " @" + r.replaceAll("@c.us", ""));
        return t = t.replaceAll("#mencionar-todos", o.toString()), {
            mentionedList: s,
            msg: t
        }
    } else return t = t.replaceAll("#mencionar-todos", ""), {
        mentionedList: [],
        msg: t
    }
}

function To(a, t) {
    let e;
    try {
        e = a()
    } catch {
        return
    }
    return {
        getItem: o => {
            var r;
            const i = c => c === null ? null : JSON.parse(c, t == null ? void 0 : t.reviver),
                n = (r = e.getItem(o)) != null ? r : null;
            return n instanceof Promise ? n.then(i) : i(n)
        },
        setItem: (o, r) => e.setItem(o, JSON.stringify(r, t == null ? void 0 : t.replacer)),
        removeItem: o => e.removeItem(o)
    }
}
const Ke = a => t => {
        try {
            const e = a(t);
            return e instanceof Promise ? e : {
                then(s) {
                    return Ke(s)(e)
                },
                catch (s) {
                    return this
                }
            }
        } catch (e) {
            return {
                then(s) {
                    return this
                },
                catch (s) {
                    return Ke(s)(e)
                }
            }
        }
    },
    ko = (a, t) => (e, s, o) => {
        let r = {
                storage: To(() => localStorage),
                partialize: h => h,
                version: 0,
                merge: (h, S) => ({
                    ...S,
                    ...h
                }),
                ...t
            },
            i = !1;
        const n = new Set,
            c = new Set;
        let l = r.storage;
        if (!l) return a((...h) => {
            console.warn(`[zustand persist middleware] Unable to update item '${r.name}', the given storage is currently unavailable.`), e(...h)
        }, s, o);
        const d = () => {
                const h = r.partialize({
                    ...s()
                });
                return l.setItem(r.name, {
                    state: h,
                    version: r.version
                })
            },
            u = o.setState;
        o.setState = (h, S) => (u(h, S), d());
        const p = a((...h) => (e(...h), d()), s, o);
        o.getInitialState = () => p;
        let A;
        const v = () => {
            var h, S;
            if (!l) return;
            i = !1, n.forEach(w => {
                var F;
                return w((F = s()) != null ? F : p)
            });
            const U = ((S = r.onRehydrateStorage) == null ? void 0 : S.call(r, (h = s()) != null ? h : p)) || void 0;
            return Ke(l.getItem.bind(l))(r.name).then(w => {
                if (w)
                    if (typeof w.version == "number" && w.version !== r.version) {
                        if (r.migrate) {
                            const F = r.migrate(w.state, w.version);
                            return F instanceof Promise ? F.then(oe => [!0, oe]) : [!0, F]
                        }
                        console.error("State loaded from storage couldn't be migrated since no migrate function was provided")
                    } else return [!1, w.state];
                return [!1, void 0]
            }).then(w => {
                var F;
                const [oe, Ee] = w;
                if (A = r.merge(Ee, (F = s()) != null ? F : p), e(A, !0), oe) return d()
            }).then(() => {
                U == null || U(A, void 0), A = s(), i = !0, c.forEach(w => w(A))
            }).catch(w => {
                U == null || U(void 0, w)
            })
        };
        return o.persist = {
            setOptions: h => {
                r = {
                    ...r,
                    ...h
                }, h.storage && (l = h.storage)
            },
            clearStorage: () => {
                l == null || l.removeItem(r.name)
            },
            getOptions: () => r,
            rehydrate: () => v(),
            hasHydrated: () => i,
            onHydrate: h => (n.add(h), () => {
                n.delete(h)
            }),
            onFinishHydration: h => (c.add(h), () => {
                c.delete(h)
            })
        }, r.skipHydration || v(), A || p
    },
    Zt = ko;

function Gi(a) {
    var t;
    return (t = a.id) == null ? void 0 : t.startsWith("1313555")
}
async function Ji(a) {
    if (a.name) return a.name;
    try {
        const t = await m.Contact("get", M(a.id));
        return (t == null ? void 0 : t.name) || (t == null ? void 0 : t.pushname) || a.id
    } catch (t) {
        return console.warn(`Erro ao buscar contato ${a.id}:`, t), a.id
    }
}

function _o(a) {
    var s;
    const t = [a["First Name"], a["Middle Name"], a["Last Name"]].map(o => o == null ? void 0 : o.trim()).filter(Boolean).join(" ");
    if (t) return t;
    const e = ["Nickname", "Organization Name"].map(o => {
        var r;
        return (r = a[o]) == null ? void 0 : r.trim()
    }).find(Boolean);
    return e || ((s = a.name) != null && s.trim() ? a.name.trim() : "")
}
const Ro = a => a.map(e => ({
        ...e,
        id: e.id || e["Phone 1 - Value"],
        name: _o(e)
    })),
    Lo = b()(Zt(a => ({
        importedContacts: [],
        setImportedContacts: t => {
            const e = Ro(t);
            a({
                importedContacts: e
            })
        }
    }), {
        name: "useImportedContactsStore-store",
        version: 1,
        partialize: a => ({
            importedContacts: a.importedContacts
        })
    })),
    je = (a, t) => {
        if (!t || t.trim() === "") return a;
        const {
            importedContacts: e
        } = Lo.getState(), s = t.split("@")[0], o = e.find(i => i.id === s);
        if (!o) return a;
        let r = a;
        return Object.keys(o).forEach(i => {
            const n = `#${i}`,
                c = o[i];
            c && typeof c == "string" && (r = r.replaceAll(n, c))
        }), r
    };
async function Uo(a, t, e) {
    await be(a, t.composing, "txt");
    let {
        mentionedList: s,
        msg: o
    } = await at(a, t.mensagem);
    o = je(o, a), o = await ze(a, o), o = De(a, o), o = tt(o, e);
    const r = await m.Chat("sendTxt", {
        id: a,
        msg: o,
        mentionedList: s
    });
    return await Re(t.aguarde), r
}
async function Eo(a, t, e) {
    await be(a, t.composing, "txt");
    let {
        mentionedList: s,
        msg: o
    } = await at(a, t.mensagem);
    o = je(o, a), o = await ze(a, o), o = De(a, o), o = tt(o, e);
    const r = await m.Chat("sendImage", {
        id: a,
        msg: o,
        mentionedList: s,
        base64: t.base64,
        isViewOnce: t.isViewOnce
    });
    return await Re(t.aguarde), r
}
async function Fo(a, t, e) {
    await be(a, t.composing, "txt");
    let {
        mentionedList: s,
        msg: o
    } = await at(a, t.mensagem);
    o = je(o, a), o = await ze(a, o), o = De(a, o), o = tt(o, e);
    const r = await m.Chat("sendVideo", {
        id: a,
        msg: o,
        mentionedList: s,
        base64: t.base64,
        microVideo: t.microVideo,
        isViewOnce: t.isViewOnce
    });
    return await Re(t.aguarde), r
}
async function No(a, t) {
    return await be(a, t.composing, "audio"), await m.Chat("sendAudio", {
        id: a,
        base64: t.base64
    })
}
async function Io(a, t) {
    return await m.Chat("sendDoc", {
        id: a,
        base64: t.base64,
        name: t.base64Name
    })
}
async function qo(a, t) {
    return await m.Chat("sendPixKeyMessage", {
        id: a,
        keyType: t.keyType,
        name: t.name,
        key: t.key
    })
}
async function Po(a, t) {
    return await m.Chat("sendGroupInviteMessage", {
        id: a,
        groupID: t.groupID
    })
}
async function zo(a, t) {
    return await m.Chat("sendContact", {
        id: a,
        phone: t.userID,
        name: t.userName
    })
}
async function Do(a, t) {
    return await m.Chat("linkPreview", {
        id: a,
        link: t.link,
        title: t.title,
        description: t.description
    })
}
async function jo(a, t) {
    return await m.Chat("sticker", {
        id: a,
        base64: t.base64
    })
}
async function Oo(a, t, e) {
    const {
        setNewUser: s
    } = q.getState();
    t === "abas" ? s(a, e) : Ht(a, t, e, 0)
}
async function Tt(a, t, e, s) {
    const {
        setRemoveUser: o
    } = q.getState();
    (e === "abas" || t === !0) && o(a, t, s), e !== "abas" && Vt(a, t, e, s)
}
async function kt(a, t, e) {
    const s = [{
        labelId: t,
        type: e
    }];
    await m.Labels("addOrRemoveLabels", {
        id: a,
        label: s
    })
}
async function Wo(a) {
    const {
        labels: t
    } = await m.Chat("get", a);
    if (!t) {
        console.error(`Etiquetas do contato ${a} não encotrada`);
        return
    }
    let e = [];
    for (const s of t) e.push({
        labelId: s,
        type: "remove"
    });
    await m.Labels("addOrRemoveLabels", {
        id: a,
        label: e
    })
}
async function _t(a, t = !1) {
    t ? await m.Chat("desarquivar", a) : await m.Chat("arquivar", a)
}
const B = b()(a => ({
        pin: [],
        pinChat: () => {
            const t = H.getState().activeChat.id._serialized,
                s = B.getState().pin.find(o => o.chatID === t);
            s ? B.getState().setUnpinChat(s) : B.getState().setPinChat(t)
        },
        pinOrUnpinChat: t => {
            const s = B.getState().pin.find(o => o.chatID === t);
            s ? B.getState().setUnpinChat(s) : B.getState().setPinChat(t)
        },
        setPinChat: t => a(e => {
            if (!C.getState().user.estado && e.pin.length > 0) return X.getState().openRendertype("user_free"), {};
            const s = {
                    chatID: t,
                    pin: Date.now()
                },
                o = [s, ...e.pin];
            return m.Functions("FixChats", {
                action: "pin",
                pin: s
            }), f("pinChat", o), {
                pin: o
            }
        }),
        setUnpinChat: t => a(e => {
            const s = e.pin.filter(o => o.chatID !== t.chatID);
            return m.Functions("FixChats", {
                action: "unpin",
                pin: t
            }), f("pinChat", s), {
                pin: s
            }
        }),
        isPin: () => {
            var s, o;
            const t = (o = (s = H.getState().activeChat) == null ? void 0 : s.id) == null ? void 0 : o._serialized;
            return t ? !!B.getState().pin.find(r => r.chatID === t) : !1
        },
        usedPin: (t, e) => {
            const o = B.getState().pin.find(r => r.chatID === t);
            o && B.getState().setUnpinChat(o), e === "pin" && B.getState().setPinChat(t)
        }
    })),
    Bo = async a => {
        B.setState({
            pin: a
        }), m.Functions("FixChats", {
            action: "pinStorage",
            pin: a
        }), f("pinChat", a)
    }, Ki = a => {
        const t = [...B.getState().pin],
            s = ((o, r) => o.concat(r).reduce((c, l) => (c.find(u => u.chatID === l.chatID) || c.push(l), c), []))(t, a);
        Bo(s)
    };
async function Zi() {
    const a = await G("pinChat");
    m.Functions("FixChats", {
        action: "pinStorage",
        pin: a
    }), B.setState({
        pin: a
    })
}
async function Rt(a, t) {
    const {
        usedPin: e
    } = B.getState();
    e(a, t)
}
async function Vo(a) {
    await m.Chat("markIsUnread", {
        id: a
    })
}
async function $o(a, t) {
    const {
        socket: e,
        multi_atendente: s,
        atendente: o
    } = Z.getState(), {
        whatsappID: r
    } = y.getState(), i = s.find(c => c.email === t.email) || {
        id: "NaN",
        whatsappID: r,
        activeChat: "closeChat",
        userLogado: !0,
        email: t.email,
        assinaturaActive: !1,
        assinatura: t.email,
        deviceID: NaN
    }, n = {
        chatID: a,
        whatsappID: r,
        atendente: i,
        status: "Transferido",
        dataUltimaInteracao: Date.now()
    };
    e.emit("transferir_atendimento", {
        attID: i.id,
        remetenteID: o.id,
        chatID: a.replace(/@c\.us/g, ""),
        text: t.mensagem,
        urgencia: t.urgencia
    }, n)
}
async function Ho(a) {
    await m.BlockList("blockContact", a)
}
async function Go(a, t, e) {
    try {
        const {
            sendAction: s
        } = oa.getState(), {
            getQuickReply: o
        } = mo.getState(), r = o(t);
        await s(r, a, e)
    } catch (s) {
        console.error("Error ao tentar enviar a resposta rapida pelo SendAction", s)
    }
}
const Se = async (a, t) => {
    let e = await ze(a, t);
    return e = je(e, a), e = De(a, e), e
};
async function Jo(a, t) {
    await be(a, t.composing, "txt");
    let e = {
        ...t,
        title: await Se(a, t.title),
        description: await Se(a, t.description),
        footer: await Se(a, t.footer),
        buttonText: await Se(a, t.buttonText),
        sections: await Promise.all(t.sections.map(async o => ({
            ...o,
            rows: await Promise.all(o.rows.map(async r => ({
                ...r,
                title: await Se(a, r.title),
                description: await Se(a, r.description)
            })))
        })))
    };
    const s = await m.Chat("sendListMessage", {
        id: a,
        options: e
    });
    return await Re(t.aguarde), s
}
async function st(a, t, e, s) {
    const {
        addMonitor: o,
        deleteMonitor: r,
        updateMonitor: i
    } = wo.getState(), n = [], c = E();
    o({
        id: c,
        userID: a,
        sendAction: "Actived",
        remetente: s,
        actionsTam: t.length,
        actionIndice: 0,
        activeAction: t[0]
    });
    for (const [l, d] of t.entries()) {
        if (!i(c, l, d)) {
            n.push(!1);
            break
        }
        switch (d.type) {
            case "txt":
                n.push(await Uo(M(a), d.propriedades, e));
                break;
            case "image":
                n.push(await Eo(M(a), d.propriedades, e));
                break;
            case "video":
                n.push(await Fo(M(a), d.propriedades, e));
                break;
            case "audio":
                n.push(await No(M(a), d.propriedades));
                break;
            case "doc":
                n.push(await Io(M(a), d.propriedades));
                break;
            case "pix":
                n.push(await qo(M(a), d.propriedades));
                break;
            case "groupInvite":
                n.push(await Po(M(a), d.propriedades));
                break;
            case "contact":
                n.push(await zo(M(a), d.propriedades));
                break;
            case "linkPreview":
                n.push(await Do(M(a), d.propriedades));
                break;
            case "sticker":
                n.push(await jo(M(a), d.propriedades));
                break;
            case "addCRM":
                await Oo(Ve(a), d.propriedades.crmID, d.propriedades.abaID);
                break;
            case "removeCRM":
                await Tt(Ve(a), !1, d.propriedades.crmID, d.propriedades.abaID);
                break;
            case "removeAllCRM":
                await Tt(Ve(a), !0);
                break;
            case "addLabel":
                await kt(M(a), d.propriedades.labelID, "add");
                break;
            case "removeLabel":
                await kt(M(a), d.propriedades.labelID, "remove");
                break;
            case "removeAllLabel":
                await Wo(M(a));
                break;
            case "timer":
                await Re(d.propriedades.segundos);
                break;
            case "composing":
                await be(M(a), d.propriedades.segundos, "txt");
                break;
            case "recording":
                await be(M(a), d.propriedades.segundos, "audio");
                break;
            case "arquivar":
                await _t(M(a));
                break;
            case "desarquivar":
                await _t(M(a), !0);
                break;
            case "fixarChat":
                await Rt(M(a), "pin");
                break;
            case "desfixarChat":
                await Rt(M(a), "unpin");
                break;
            case "marcarNaoLido":
                await Vo(M(a));
                break;
            case "transferir":
                await $o(M(a), d.propriedades);
                break;
            case "bloquear":
                await Ho(M(a));
                break;
            case "respostaRapida":
                await Go(M(a), d.propriedades.respostaRapidaID, e);
                break;
            case "list":
                await Jo(M(a), d.propriedades);
                break;
            default:
                console.warn(`No handler found for action type: ${d.type}`);
                break
        }
    }
    return r(c), n.length === 0 || n.every(l => l && l.id)
}
async function ot(a, t) {
    const {
        language: e
    } = _.getState(), {
        label: s
    } = le.getState();
    if (await ae("followUp", !0) === !0) {
        Ye("followUp", e.btnPremium, s.checkout);
        return
    }
    const o = t.regras.assinatura.propriedades;
    await st(a, t.acao, {
        desativar: o.active ? o.desativarAss : !1,
        personalizar: o.active ? o.persAss.active : !1,
        nome: o.persAss.nameAss
    }, "useAcaoFollowUp"), W.getState().dispartWebhook(a.replace(/@c\.us/g, ""), "followUp", {
        id: t.id,
        name: t.nome
    })
}(function() {
    window.addEventListener("message", t => {
        if (t.data.type === "Ev" && t.data.action === "chat.update_label") {
            const e = JSON.parse(t.data.model),
                {
                    type: s,
                    chat: o,
                    labels: r
                } = e;
            if (!o || !o.id) return;
            const i = {
                    ...o,
                    id: M(o.id)
                },
                n = Y.getState().FollowUp.filter(c => c.active);
            if (n.length === 0) return;
            if (s === "add") {
                Zo(i, r, n);
                const c = n.filter(l => l.acionamento.type === "timing");
                r.forEach(l => {
                    Qo(i, l.id, c)
                })
            } else if (s === "remove") {
                Ko(i, r, n);
                const c = n.filter(l => l.acionamento.type === "timing");
                r.forEach(l => {
                    Yo(i, l.id, c)
                })
            }
        }
    })
})();

function Ko(a, t, e) {
    t.forEach(s => {
        e.filter(r => {
            var l, d, u;
            const i = r.funil.etiquetas.some(p => p.id === s.id),
                n = a.id.endsWith("@g.us"),
                c = ((u = (d = (l = r.regras) == null ? void 0 : l.responderGrupos) == null ? void 0 : d.propriedades) == null ? void 0 : u.active) !== !1;
            return i && r.acionamento.type === "dispararAoSair" && (!n || c)
        }).forEach(r => {
            try {
                ot(a.id, r)
            } catch (i) {
                console.error(`❌ Erro ao disparar follow-up: ${r.id} para o chat: ${a.id}`, i)
            }
        })
    })
}

function Zo(a, t, e) {
    t.forEach(s => {
        e.filter(r => {
            var l, d, u;
            const i = r.funil.etiquetas.some(p => p.id === s.id),
                n = a.id.endsWith("@g.us"),
                c = ((u = (d = (l = r.regras) == null ? void 0 : l.responderGrupos) == null ? void 0 : d.propriedades) == null ? void 0 : u.active) !== !1;
            return i && r.acionamento.type === "dispararAoEntrar" && (!n || c)
        }).forEach(r => {
            try {
                ot(a.id, r)
            } catch (i) {
                console.error(`❌ Erro ao disparar follow-up: ${r.id} para o chat: ${a.id}`, i)
            }
        })
    })
}

function Qo(a, t, e) {
    e.filter(o => {
        var c, l, d;
        const r = o.funil.etiquetas.some(u => u.id === t),
            i = a.id.endsWith("@g.us"),
            n = ((d = (l = (c = o.regras) == null ? void 0 : c.responderGrupos) == null ? void 0 : l.propriedades) == null ? void 0 : d.active) !== !1;
        return r && (!i || n)
    }).forEach(o => {
        Y.getState().addChatToFollowUp(o.id, t, a, "label")
    })
}

function Yo(a, t, e) {
    e.filter(o => {
        var c, l, d;
        const r = o.funil.etiquetas.some(u => u.id === t),
            i = a.id.endsWith("@g.us"),
            n = ((d = (l = (c = o.regras) == null ? void 0 : c.responderGrupos) == null ? void 0 : l.propriedades) == null ? void 0 : d.active) !== !1;
        return r && (!i || n)
    }).forEach(o => {
        Y.getState().removeChatFromFollowUp(o.id, t, a.id, "label")
    })
}

function Xo() {
    const a = Y.getState().FollowUp.filter(s => s.active && s.acionamento.type === "timing");
    if (a.length === 0) return;
    const t = Date.now();
    let e = [];
    a.forEach(s => {
        s.funil.abas.forEach(o => {
            o.chats.forEach(r => {
                if (!r.date) return;
                const i = me.convertTimingToMilliseconds(s.acionamento.timing);
                t >= r.date + i && e.push({
                    chat: r,
                    abaId: o.id,
                    followUp: s
                })
            })
        }), s.funil.etiquetas.forEach(o => {
            o.chats.forEach(r => {
                if (!r.date) return;
                const i = me.convertTimingToMilliseconds(s.acionamento.timing);
                t >= r.date + i && e.push({
                    chat: r,
                    etiquetaId: o.id,
                    followUp: s
                })
            })
        })
    }), e.forEach(({
        chat: s,
        abaId: o,
        etiquetaId: r,
        followUp: i
    }) => {
        ot(s.id, i), o ? Y.getState().removeChatFromFollowUp(i.id, o, s.id, "tab") : r && Y.getState().removeChatFromFollowUp(i.id, r, s.id, "label")
    })
}
chrome.runtime.onMessage.addListener(async a => {
    switch (a.action) {
        case "dispatch_timing_follow":
            Xo();
            break
    }
});

function er() {
    return q.subscribe((t, e) => {
        if (!t.userTabs || !Y.getState().initSubscribeUserTabs) return;
        const s = t.userTabs || [],
            r = (e.userTabs || []).filter(i => !s.some(n => n.id === i.id));
        r.length !== 0 && Y.getState().removeTabFromFunnels(r)
    })
}
const tr = [{
        id: 1,
        name: "tab_all",
        visibility: !0
    }, {
        id: 2,
        name: "tab_groups",
        visibility: !0
    }, {
        id: 3,
        name: "tab_unread",
        visibility: !0
    }, {
        id: 4,
        name: "tab_1_1",
        visibility: !0
    }, {
        id: 5,
        name: "tab_atendentes",
        visibility: !0
    }],
    q = b()(a => ({
        userTabs: [],
        systemTabs: tr,
        activeTab: {
            type: "tab",
            id: 1
        },
        sortUserTabs: (t, e) => a(s => {
            const o = [...s.userTabs],
                [r] = o.splice(t, 1),
                i = [...o.slice(0, e), r, ...o.slice(e)];
            return f("userTabs", i), y.getState().plugin_page ? z("userTabs-sortUserTabs", {
                home: t,
                destination: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-sortUserTabs",
                dados: {
                    home: t,
                    destination: e
                }
            }), {
                userTabs: i
            }
        }),
        setNewUser: async (t, e) => {
            var n;
            const s = t.replace("@c.us", "").replace("@g.us", "");
            if ((n = q.getState().userTabs.find(c => c.id === e)) == null ? void 0 : n.chats.find(c => c.id === t || c.id === s)) return;
            const {
                name: r
            } = await m.Utils("getContato", t), i = q.getState().userTabs.map(c => {
                if (c.id === e) {
                    if (!C.getState().user.estado && c.chats.length >= 5) return X.getState().openRendertype("user_free"), c;
                    {
                        const l = {
                            ...c,
                            chats: [...c.chats, {
                                id: t,
                                name: r
                            }]
                        };
                        return W.getState().dispartWebhook(t, "crm", {
                            id: e,
                            type: "NewUser",
                            name: l.tag
                        }), l
                    }
                } else return c
            });
            f("userTabs", i), y.getState().plugin_page ? z("userTabs-setNewUser", {
                userID: t,
                id: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setNewUser",
                dados: {
                    userID: t,
                    id: e
                }
            }), a(c => ({
                ...c,
                userTabs: i
            }))
        },
        setChatsTab: async (t, e, s = !0) => {
            const o = q.getState().userTabs.map(r => r.id === e ? {
                ...r,
                chats: t
            } : r);
            q.setState({
                userTabs: o
            }), s && (f("userTabs", o), y.getState().plugin_page ? z("userTabs-setChatsTab", {
                chats: t,
                id: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setChatsTab",
                dados: {
                    chats: t,
                    id: e
                }
            }))
        },
        setCopyChats: (t, e) => a(s => {
            const o = s.userTabs.map(r => {
                if (r.id === e) {
                    const i = t.filter(n => !r.chats.some(c => c.id === n.id));
                    return {
                        ...r,
                        chats: [...r.chats, ...i]
                    }
                }
                return r
            });
            return f("userTabs", o), y.getState().plugin_page ? z("userTabs-setCopyChats", {
                chats: t,
                id: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setCopyChats",
                dados: {
                    chats: t,
                    id: e
                }
            }), {
                userTabs: o
            }
        }),
        setMoveChats: (t, e, s) => a(o => {
            const r = o.userTabs.map(i => {
                if (i.id === e) {
                    const n = i.chats.filter(c => !t.some(l => l.id === c.id));
                    return {
                        ...i,
                        chats: n
                    }
                }
                if (i.id === s) {
                    const n = [...i.chats, ...t.filter(c => !i.chats.some(l => l.id === c.id))];
                    return {
                        ...i,
                        chats: n
                    }
                }
                return i
            });
            return f("userTabs", r), y.getState().plugin_page ? z("userTabs-setMoveChats", {
                chats: t,
                source: e,
                destination: s
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setMoveChats",
                dados: {
                    chats: t,
                    source: e,
                    destination: s
                }
            }), {
                userTabs: r
            }
        }),
        setRemoveUser: (t, e, s) => a(o => {
            const r = t.replace("@c.us", "").replace("@g.us", ""),
                i = o.userTabs.map(n => e ? {
                    ...n,
                    chats: n.chats.filter(c => c.id !== r && c.id !== t)
                } : n.id === s ? {
                    ...n,
                    chats: n.chats.filter(c => c.id !== r && c.id !== t)
                } : {
                    ...n
                });
            if (e) W.getState().dispartWebhook(r, "crm", {
                id: s,
                type: "RemoveUser-All"
            });
            else {
                const n = o.userTabs.find(c => c.id === s);
                n && W.getState().dispartWebhook(r, "crm", {
                    id: s,
                    type: "RemoveUser",
                    name: n.tag
                })
            }
            return f("userTabs", i), y.getState().plugin_page ? z("userTabs-setRemoveUser", {
                userID: r,
                isAll: e,
                id: s
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setRemoveUser",
                dados: {
                    userID: r,
                    isAll: e,
                    id: s
                }
            }), {
                userTabs: i
            }
        }),
        setEditUserTabName: (t, e) => a(s => {
            const o = s.userTabs.map(r => r.id === t ? {
                ...r,
                tag: e
            } : r);
            return f("userTabs", o), y.getState().plugin_page ? z("userTabs-setEditUserTabName", {
                id: t,
                tabName: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setEditUserTabName",
                dados: {
                    id: t,
                    tabName: e
                }
            }), {
                userTabs: o
            }
        }),
        setRemoveTab: t => a(e => {
            const s = e.userTabs.filter(o => o.id !== t);
            return f("userTabs", s), y.getState().plugin_page ? z("userTabs-setRemoveTab", {
                id: t
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setRemoveTab",
                dados: {
                    id: t
                }
            }), {
                userTabs: s
            }
        }),
        setCreateUserTab: t => a(e => {
            const s = {
                    id: E(),
                    chats: [],
                    tag: t,
                    type: "user",
                    hide: !1
                },
                o = [s, ...e.userTabs];
            return f("userTabs", o), y.getState().plugin_page ? z("userTabs-setCreateUserTab", {
                newUserTab: s
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setCreateUserTab",
                dados: {
                    newUserTab: s
                }
            }), {
                userTabs: o
            }
        }),
        setVisibilityUserTab: t => a(e => {
            const s = e.userTabs.map(o => o.id === t ? {
                ...o,
                hide: !o.hide
            } : o);
            return f("userTabs", s), y.getState().plugin_page ? z("userTabs-setVisibilityUserTab", {
                id: t
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setVisibilityUserTab",
                dados: {
                    id: t
                }
            }), {
                userTabs: s
            }
        }),
        getUserAbasTam: t => q.getState().userTabs.filter(s => s.chats.filter(o => o.id === t).length > 0).length,
        getTabByID: t => q.getState().userTabs.find(s => s.id === t),
        setVisibilitySystemTab: t => a(e => {
            const s = e.systemTabs.map(o => o.id === t ? {
                ...o,
                visibility: !o.visibility
            } : o);
            return O("SystemTabsDB", "SystemTabs", [te.encryptData(s)]), {
                systemTabs: s
            }
        }),
        setActiveTab: t => a(e => ({
            ...e,
            activeTab: t
        }))
    }));
q.subscribe(() => {
    Be.getState().chatListTabs(), er()
});
const Qt = b()((a, t) => ({
    active: "default",
    setActive: e => a({
        active: e
    }),
    selecionados: [],
    getSelecionado: e => !!t().selecionados.find(s => s.id === e),
    onChangeSelecionado: (e, s, o) => a(r => r.selecionados.find(i => i.id === e) ? {
        selecionados: r.selecionados.filter(n => {
            if (n.id !== e) return n
        })
    } : {
        selecionados: [...r.selecionados, {
            id: e,
            type: s,
            ...o && {
                chats: o
            }
        }]
    }),
    renderFiltroPersonalizado: () => {
        q.getState().setActiveTab({
            id: "custom",
            type: "custom"
        }), m.ListChat("custom", t().selecionados)
    }
}));
Qt.subscribe(async a => {
    a.selecionados.length === 1 && a.selecionados[0].id === "tab_unread" ? (q.getState().setActiveTab({
        id: 0,
        type: "default-filter"
    }), m.ListChat("nao-lido")) : (q.getState().setActiveTab({
        id: "custom",
        type: "custom"
    }), m.ListChat("custom", {
        selecionados: a.selecionados,
        user: C.getState().user
    }))
});
const Yt = ["chat", "image", "document", "video", "ptt", "vcard", "sticker", "poll_creation", "location", "list_response", "call_log"];

function ar(a) {
    if (a.id.fromMe || !Yt.includes(a.type)) return;
    const {
        autoAtendimento: t
    } = ke.getState();
    t.forEach(e => {
        e.active && sr(a, e)
    })
}
const sr = async (a, t) => {
    var u, p, A, v, h, S, U, w, F, oe, Ee, nt, ct, dt, lt, ut, pt, mt, ft, gt, ht, vt, At, bt, St;
    const {
        getUserAbasTam: e,
        userTabs: s
    } = q.getState(), o = x.getState().crm, {
        isBusiness: r
    } = y.getState(), i = a.id.remote.toString().replace(/@(.*)/, "");
    if (!t.regras.responderGrupos.propriedades.active && a.author) return;
    const n = await m.Chat("getActiveChat", "@");
    if (t.regras.responderChatAtivo.propriedades.active && n === a.id.remote || ((A = (p = (u = t == null ? void 0 : t.regras) == null ? void 0 : u.responderChatArquivado) == null ? void 0 : p.propriedades) == null ? void 0 : A.active) === !0 && (await m.Chat("get", i)).archive) return;
    const c = new Date().getDay(),
        l = ["domingo", "segunda", "terca", "quarta", "quinta", "sexta", "sabado"];
    if ("domingo" in t.regras.responderDias.propriedades && t.regras.responderDias.propriedades.active) {
        const re = l[c],
            {
                horaInicio: K,
                horaFim: P,
                periodoAtivacao: j,
                active: ie
            } = t.regras.responderDias.propriedades[re] || {};
        if (!K || !P || !ie || j && !me.isValidInterval(K, P)) return
    }
    const {
        labels: d
    } = await m.Chat("get", a.id.remote);
    if (!(r && ((S = (h = (v = t.regras) == null ? void 0 : v.notResponderChatEtiquetado) == null ? void 0 : h.propriedades) == null ? void 0 : S.active) === !0 && d.length > 0) && !(r && ((F = (w = (U = t.regras) == null ? void 0 : U.notResponderEtiqueta) == null ? void 0 : w.propriedades) == null ? void 0 : F.active) === !0 && t.regras.notResponderEtiqueta.propriedades.labelID.some(P => d.includes(P))) && !(r && ((nt = (Ee = (oe = t == null ? void 0 : t.regras) == null ? void 0 : oe.responderEtiqueta) == null ? void 0 : Ee.propriedades) == null ? void 0 : nt.active) === !0 && !t.regras.responderEtiqueta.propriedades.labelID.some(P => d.includes(P))) && !(((lt = (dt = (ct = t == null ? void 0 : t.regras) == null ? void 0 : ct.notResponderChatCRM) == null ? void 0 : dt.propriedades) == null ? void 0 : lt.active) === !0 && e(i) + $t(i) !== 0)) {
        if (((mt = (pt = (ut = t == null ? void 0 : t.regras) == null ? void 0 : ut.notResponderCRM) == null ? void 0 : pt.propriedades) == null ? void 0 : mt.active) === !0) {
            const re = t.regras.notResponderCRM.propriedades.crm;
            let K = !0;
            for (const P of re)
                if (P.crmID === "abas")(ft = s.find(j => j.id === P.abaID)) == null || ft.chats.forEach(j => {
                    j.id === i && (K = !1)
                });
                else
                    for (const j of o) j.id === P.crmID && ((gt = j.list.find(ie => ie.id === P.abaID)) == null || gt.chats.forEach(ie => {
                        ie.id === i && (K = !1)
                    }));
            if (!K) return
        }
        if (((At = (vt = (ht = t == null ? void 0 : t.regras) == null ? void 0 : ht.responderCRM) == null ? void 0 : vt.propriedades) == null ? void 0 : At.active) === !0) {
            const re = t.regras.responderCRM.propriedades.crm;
            let K = !1;
            for (const P of re)
                if (P.crmID === "abas")(bt = s.find(j => j.id === P.abaID)) == null || bt.chats.forEach(j => {
                    j.id === i && (K = !0)
                });
                else
                    for (const j of o) j.id === P.crmID && ((St = j.list.find(ie => ie.id === P.abaID)) == null || St.chats.forEach(ie => {
                        ie.id === i && (K = !0)
                    }));
            if (!K) return
        }
        or(a, t)
    }
}, or = async (a, t) => {
    const e = _.getState().language,
        {
            label: s
        } = le.getState(),
        {
            updateUsedLenght: o
        } = ke.getState(),
        r = async () => {
            if (await ae("autoatendimento", !0) === !0) {
                Ye("autoAtendimento", e.btnPremium, s.checkout);
                return
            }
            const i = t.regras.assinatura.propriedades;
            st(a.id.remote.toString(), t.acao, {
                desativar: i.active ? i.desativarAss : !1,
                personalizar: i.active ? i.persAss.active : !1,
                nome: i.persAss.nameAss
            }, "useAcaoAutoAtendimento"), o(t.id), W.getState().dispartWebhook(a.id.remote.toString().replace(/@c\.us/g, ""), "autoAtendimento", {
                id: t.id,
                name: t.nome,
                usedLenght: t.usedLenght + 1
            })
        };
    for (const i of t.acionamento) {
        if (i.type === "message_Received" && (i.text == a.body || i.text == a.caption)) {
            r();
            break
        }
        if (i.type === "keyword") {
            let n = !1;
            if (i.chaves.forEach(c => {
                    (a.type === "chat" || a.type === "list_response") && a.body.toLowerCase().includes(c.toLowerCase()) && (n = !0)
                }), n) {
                r();
                break
            }
        }
        if (i.type === "day_Message") {
            const n = (await m.Chat("getMessages", {
                id: a.id.remote,
                quant: 5
            })).reverse();
            n.shift();
            const c = n.find(l => l.id.fromMe === !1 && Yt.includes(l.type));
            if (c) {
                const l = parseInt(c.t.toString() + "000");
                if (!me.isDataDeHoje(l)) {
                    r();
                    break
                }
            }
        }
        if (i.type === "customer_Message" && (await m.Chat("getMessages", {
                id: a.id.remote,
                quant: 5
            })).filter(l => l.type !== "e2e_notification" && l.type !== "notification_template").length === 1) {
            r();
            break
        }
    }
}, T = b((a, t) => ({
    workflows: [],
    currentWorkflow: null,
    saveToStorage: e => {
        f("fluxo", e)
    },
    getSourceNode: (e, s) => {
        const o = t().workflows.find(n => n.id === s);
        if (!o) return null;
        const r = o.edges.find(n => n.target === e);
        if (!r) return null;
        const i = o.nodes.find(n => n.id === r.source);
        return i || null
    },
    getTargetNode: (e, s) => {
        const o = t().workflows.find(n => n.id === s);
        if (!o) return null;
        const r = o.edges.find(n => n.source === e);
        if (!r) return null;
        const i = o.nodes.find(n => n.id === r.target);
        return i || null
    },
    getAllTargetNodes: (e, s) => {
        const o = t().workflows.find(n => n.id === s);
        if (!o) return [];
        const r = o.edges.filter(n => n.source === e);
        return r.length ? r.map(n => o.nodes.find(c => c.id === n.target)).filter(Boolean) : []
    },
    getTargetNodeByBestMatch: (e, s, o) => {
        const r = t().workflows.find(d => d.id === s);
        if (!r) return null;
        const i = r.nodes.find(d => d.id === e);
        if (!i || i.type !== "send-answers") return null;
        const n = r.edges.filter(d => d.source === e);
        if (!n.length) return null;
        const c = n.find(d => {
            var p, A;
            return parseInt(((A = (p = d.sourceHandle) == null ? void 0 : p.split("-")) == null ? void 0 : A.pop()) || "", 10) === o
        });
        if (!c) return null;
        const l = r.nodes.find(d => d.id === c.target);
        return l || null
    },
    getTargetNodeByRowId: (e, s, o) => {
        const r = t().workflows.find(u => u.id === s);
        if (!r) return null;
        const i = r.nodes.find(u => u.id === e);
        if (!i || i.type !== "send-list") return null;
        const n = i == null ? void 0 : i.data;
        if (!n || !(n != null && n.sections)) return null;
        const c = n.sections.flatMap(u => u.rows).find(u => u.rowId === o);
        if (!c) return null;
        const l = r.edges.find(u => u.source === e && u.sourceHandle === `on-response-${c.rowId}`);
        if (!l) return null;
        const d = r.nodes.find(u => u.id === l.target);
        return d || null
    },
    getRetryQuestion: e => {
        const {
            noMatch: s
        } = e;
        return s.sendPersonalizedMessage.active && s.sendPersonalizedMessage.personalizedMessage || s.endPersonalizedMessage.active && s.endPersonalizedMessage.personalizedMessage ? s.sendPersonalizedMessage.active ? s.sendPersonalizedMessage.personalizedMessage : s.endPersonalizedMessage.personalizedMessage : e.question
    },
    initNodeIsConnected: e => {
        const s = e.nodes.find(r => r.type === "init");
        return s ? e.edges.some(r => r.source === s.id) : !1
    },
    getVariableByNodeId: (e, s) => {
        const o = t().workflows.find(i => i.id === s);
        if (!o) return;
        const r = o.variaveis.find(i => i.nodeId === e);
        if (r) return r
    },
    updateVariableAsync: async (e, s, o, r) => new Promise(i => {
        a(n => {
            const c = n.workflows.map(d => {
                    if (d.id !== o) return d;
                    const u = d.variaveis.map(p => {
                        if (p.nodeId !== s) return p;
                        const v = p.clients.some(h => h.userId === e) ? p.clients.map(h => h.userId === e ? {
                            ...h,
                            value: r
                        } : h) : [...p.clients, {
                            userId: e,
                            value: r
                        }];
                        return {
                            ...p,
                            clients: v
                        }
                    });
                    return {
                        ...d,
                        variaveis: u
                    }
                }),
                l = n.currentWorkflow && n.currentWorkflow.id === o && c.find(d => d.id === o) || n.currentWorkflow;
            return t().saveToStorage({
                workflows: c,
                currentWorkflow: l
            }), setTimeout(() => i(), 0), {
                workflows: c,
                currentWorkflow: l
            }
        })
    }),
    delay: e => new Promise(s => setTimeout(s, e))
}));
async function Qi() {
    const t = ((await G("fluxo") || {}).workflows || []).map(e => {
        var s;
        return (s = e.globalSettings) != null && s.blockTransitionDelay ? e : {
            ...e,
            globalSettings: {
                ...e.globalSettings,
                blockTransitionDelay: {
                    value: 2,
                    unit: "segundos"
                }
            }
        }
    });
    T.setState({
        workflows: t,
        currentWorkflow: null
    })
}

function Yi(a) {
    var l;
    const {
        workflows: t,
        currentWorkflow: e
    } = a, s = T.getState(), o = new Set(s.workflows.map(d => d.name)), r = d => {
        let u = d,
            p = 1;
        for (; o.has(u);) u = `${d} (${p})`, p++;
        return u
    }, i = t.map(d => {
        s.workflows.find(v => v.id === d.id) && (d.id = E());
        const p = s.workflows.find(v => v.id === d.id);
        if (p) {
            const v = {
                ...p,
                ...d
            };
            return v.name !== p.name && (v.name = r(v.name)), v
        }
        const A = r(d.name);
        return {
            ...d,
            name: A
        }
    }), n = e ? ((l = s.currentWorkflow) == null ? void 0 : l.id) === e.id ? {
        ...s.currentWorkflow,
        ...e
    } : e : s.currentWorkflow, c = {
        workflows: i,
        currentWorkflow: n
    };
    T.setState(c), T.getState().saveToStorage(c)
}

function Xi(a) {
    const {
        workflows: t,
        currentWorkflow: e
    } = a, s = {
        workflows: t || [],
        currentWorkflow: e || null
    };
    T.setState(s), T.getState().saveToStorage(s)
}
chrome.storage.onChanged.addListener((a, t) => {
    var e;
    if ((e = a.fluxo) != null && e.newValue) {
        const s = a.fluxo.newValue;
        T.setState({
            workflows: s.workflows || [],
            currentWorkflow: s.currentWorkflow || null
        })
    }
});
const V = b((a, t) => ({
        progresses: {},
        resetUserProgress: e => {
            a(s => {
                const {
                    [e]: o, ...r
                } = s.progresses;
                return {
                    progresses: r
                }
            })
        },
        updateUserProgress: (e, s, o) => {
            a(r => ({
                progresses: {
                    ...r.progresses,
                    [e]: {
                        currentNodeId: o,
                        workflowId: s
                    }
                }
            }))
        },
        getUserProgress: e => t().progresses[e]
    })),
    Lt = b((a, t) => ({
        processingUsers: new Set,
        addProcessingUser: e => {
            const s = new Set(t().processingUsers);
            s.add(e), a({
                processingUsers: s
            })
        },
        removeProcessingUser: e => {
            const s = new Set(t().processingUsers);
            s.delete(e), a({
                processingUsers: s
            })
        },
        isProcessing: e => t().processingUsers.has(e)
    })),
    Xt = b()(Zt((a, t) => ({
        sessions: {},
        startSession: (e, s) => {
            const o = {
                userID: e,
                workflowId: s,
                lastInteraction: new Date().toISOString()
            };
            a(r => ({
                sessions: {
                    ...r.sessions,
                    [e]: o
                }
            }))
        },
        endSession: e => {
            a(s => {
                const {
                    [e]: o, ...r
                } = s.sessions;
                return {
                    sessions: r
                }
            })
        },
        updateLastInteraction: e => {
            a(s => {
                const o = s.sessions[e];
                return o ? {
                    sessions: {
                        ...s.sessions,
                        [e]: {
                            ...o,
                            lastInteraction: new Date().toISOString()
                        }
                    }
                } : s
            })
        },
        getSession: e => t().sessions[e],
        getLastInteractionDate: e => {
            const s = t().sessions[e];
            return s ? new Date(s.lastInteraction) : void 0
        }
    }), {
        name: "user-flow-session-store"
    })),
    Ze = ["chat", "image", "document", "video", "list", "list_response", "ptt", "vcard", "sticker", "poll_creation", "location"];
async function rr(a, t) {
    const e = (t.acionamentos ?? []).filter(o => {
            var r;
            return !!((r = o == null ? void 0 : o.data) != null && r.active)
        }),
        s = a.id.remote.toString();
    for (const o of e) switch (o.type) {
        case "aoReceberMensagem":
            return !0;
        case "porPalavraChave": {
            const r = o.data;
            if ((a.type === "chat" || a.type === "list_response") && r.chaves.some(i => a.body.toLowerCase().includes(i.toLowerCase()))) return !0;
            break
        }
        case "primeiraMensagemDoClienteNoDia": {
            if (wt(s)) break;
            const r = a.t * 1e3,
                i = new Date(r),
                n = new Date;
            if (i.getDate() !== n.getDate() || i.getMonth() !== n.getMonth() || i.getFullYear() !== n.getFullYear()) break;
            const l = (await m.Chat("getMessages", {
                id: s,
                quant: 20
            })).filter(d => {
                if (d.id.fromMe !== !1 || !Ze.includes(d.type)) return !1;
                const u = d.t * 1e3,
                    p = new Date(u);
                return p.getDate() === n.getDate() && p.getMonth() === n.getMonth() && p.getFullYear() === n.getFullYear()
            });
            if (l.sort((d, u) => d.t - u.t), l.length > 0 && l[0].t === a.t) return !0;
            break
        }
        case "primeiraMensagemDoCliente": {
            if (wt(s)) break;
            if ((await m.Chat("getMessages", {
                    id: s,
                    quant: 50
                })).filter(n => n.id.fromMe === !1 && Ze.includes(n.type)).length === 1) return !0;
            break
        }
        default:
            continue
    }
    return !1
}
async function ea(a, t) {
    var o, r;
    const e = (o = t.regras) == null ? void 0 : o.find(i => i.type === "responderChatAtivo");
    return !e || !((r = e.propriedades) != null && r.active) ? !0 : await m.Chat("getActiveChat", "@") !== a.id.remote.toString()
}
async function ir(a, t) {
    const {
        getUserAbasTam: e,
        userTabs: s
    } = q.getState(), o = x.getState().crm, {
        isBusiness: r
    } = y.getState(), i = a.id.remote.toString().replace(/@(.*)/, ""), {
        labels: n
    } = await m.Chat("get", a.id.remote.toString()), c = t.regras.find(d => d.type === "responderGrupos");
    if (a.author && !c.propriedades.active) return;
    const l = (t.regras ?? []).filter(d => {
        var u;
        return !!((u = d == null ? void 0 : d.propriedades) != null && u.active)
    });
    for (const d of l) switch (d.type) {
        case "responderChatAtivo": {
            if (!await ea(a, t)) return !1;
            break
        }
        case "responderDias": {
            const u = new Date().getDay(),
                A = ["domingo", "segunda", "terca", "quarta", "quinta", "sexta", "sabado"][u],
                v = d.propriedades[A];
            if (!v || !v.active) return !1;
            if (!v.periodoAtivacao) break;
            const {
                horaInicio: h,
                horaFim: S
            } = v;
            if (!me.isValidInterval(h, S)) return !1;
            break
        }
        case "notResponderChatEtiquetado": {
            if (r && n.length > 0) return !1;
            break
        }
        case "notResponderEtiqueta": {
            if (r) {
                const {
                    labelID: u
                } = d.propriedades;
                if (n.some(p => u.includes(p))) return !1
            }
            break
        }
        case "responderEtiqueta": {
            if (r) {
                const {
                    labelID: u
                } = d.propriedades;
                if (!n.some(p => u.includes(p))) return !1
            }
            break
        }
        case "notResponderChatCRM": {
            if (e(i) + $t(i) !== 0) return !1;
            break
        }
        case "notResponderCRM": {
            const {
                crm: u
            } = d.propriedades;
            let p = !0;
            for (const A of u)
                if (A.crmID === "abas") {
                    if (s.some(v => v.id === A.abaID && v.chats.some(h => h.id === i))) {
                        p = !1;
                        break
                    }
                } else
                    for (const v of o)
                        if (v.id === A.crmID && v.list.some(h => h.id === A.abaID && h.chats.some(S => S.id === i))) {
                            p = !1;
                            break
                        } if (!p) return !1;
            break
        }
        case "responderCRM": {
            const {
                crm: u
            } = d.propriedades;
            let p = !1;
            for (const A of u)
                if (A.crmID === "abas") {
                    if (s.some(v => v.id === A.abaID && v.chats.some(h => h.id === i))) {
                        p = !0;
                        break
                    }
                } else
                    for (const v of o)
                        if (v.id === A.crmID && v.list.some(h => h.id === A.abaID && h.chats.some(S => S.id === i))) {
                            p = !0;
                            break
                        } if (!p) return !1;
            break
        }
    }
    return !0
}
const rt = b((a, t) => ({
        lastMessages: {},
        updatedVariables: {},
        setLastMessage: (e, s) => {
            a(o => ({
                lastMessages: {
                    ...o.lastMessages,
                    [e]: s
                }
            }))
        },
        getLastMessage: e => t().lastMessages[e],
        clearLastMessage: e => a(s => {
            const o = {
                ...s.lastMessages
            };
            return delete o[e], {
                lastMessages: o
            }
        }),
        markVariableAsUpdated: (e, s) => {
            const o = `${e}:${s}`;
            a(r => ({
                updatedVariables: {
                    ...r.updatedVariables,
                    [o]: !0
                }
            }))
        },
        isVariableUpdated: (e, s) => {
            const o = `${e}:${s}`;
            return t().updatedVariables[o] === !0
        },
        resetUpdatedVariables: e => {
            a(s => {
                const o = {
                    ...s.updatedVariables
                };
                return Object.keys(o).forEach(r => {
                    r.startsWith(`${e}:`) && delete o[r]
                }), {
                    updatedVariables: o
                }
            })
        }
    })),
    se = a => {
        const {
            unit: t,
            value: e
        } = a;
        switch (t) {
            case "minutos":
                return e * 60 * 1e3;
            case "segundos":
                return e * 1e3;
            case "horas":
                return e * 60 * 60 * 1e3;
            default:
                return 0
        }
    },
    nr = (a, t) => {
        const {
            getSession: e,
            getLastInteractionDate: s
        } = Xt.getState();
        if (!e(a)) return !0;
        const r = t.cooldown;
        if (!r || r.value <= 0) return !0;
        const i = se(r),
            n = s(a).getTime();
        return Date.now() - n >= i
    },
    cr = a => {
        const t = a.nodes.find(s => s.type === "init");
        return t ? a.edges.some(s => s.source === t.id) : !1
    },
    dr = (a, t, e) => ({
        id: `virtual-${Date.now()}`,
        type: a,
        data: t,
        index: -1,
        position: {
            x: 0,
            y: 0
        },
        send: {
            type: "timeout",
            data: t
        }
    }),
    lr = async (a, t) => {
        let e = "";
        return (t.includes("#nome") || t.includes("#primeiroNome")) && (e = (await m.Utils("getContato", a)).name), e
    }, ur = () => {
        const a = ["Olá, tudo bem?", "Olá, tudo bom?", "Oi, tudo bem?", "Oi, tudo bom?", "E ai, tudo bem?", "E ai, tudo bom?"],
            t = Math.floor(Math.random() * a.length);
        return a[t]
    }, pr = () => {
        const t = new Date().getHours();
        return t >= 6 && t < 12 ? "Bom dia" : t >= 12 && t < 18 ? "Boa tarde" : "Boa noite"
    }, Ue = async (a, t) => {
        const e = await lr(a, t);
        try {
            t = t.replaceAll("#saudação", ur()), t = t.replaceAll("#periodo-dia", pr()), t = t.replaceAll("#primeiroNome", e.split(" ")[0]), t = t.replaceAll("#nome", e), t = t.replaceAll("#numero", a.replace("@g.us", "").replace("@c.us", ""))
        } catch (s) {
            console.error("Erro ao validar existência de uma variável", s)
        }
        return t
    }, mr = (a, t) => {
        var r;
        const {
            assinatura: e
        } = I.getState(), s = (r = t == null ? void 0 : t.regras) == null ? void 0 : r.find(i => i.type === "assinatura"), o = s == null ? void 0 : s.propriedades;
        return o && o.active && o.persAss.active && !o.desativarAss && o.persAss.nameAss.length !== 0 && a.length !== 0 ? a = `*_${o.persAss.nameAss}:_*
${a}` : o && o.active && o.desativarAss && a.length !== 0 || e.active && e.name.length !== 0 && a.length !== 0 && (a = `*_${e.name}:_*
${a}`), a
    };
async function Oe(a, t, e) {
    const s = await Ue(a, t);
    return mr(s, e)
}
const pe = (a, t, e) => t.replace(/{{(.*?)}}/g, (o, r) => {
    const i = r.trim(),
        c = T.getState().workflows.find(d => d.id === e.id).variaveis.find(d => d.name.trim() === i);
    if (!c) return "";
    const l = c.clients.find(d => d.userId === a);
    return (l == null ? void 0 : l.value) ?? ""
});
async function fr(a, t, e, s) {
    var o, r;
    try {
        if (!(a != null && a.message)) return;
        const i = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(u => u.type === "simulateWriting"),
            n = (i == null ? void 0 : i.propriedades) ?? {
                active: !1
            },
            c = se((r = e.globalSettings) == null ? void 0 : r.blockTransitionDelay),
            l = typeof c == "number" && c > 0 ? c : 0;
        (n.active || l > 0) && await m.Chat("markIsComposing", {
            id: t,
            timer: l
        });
        let d = a.message;
        d = await Oe(t, d, e), d = pe(t, d, e), await m.Chat("sendTxt", {
            id: t,
            msg: d
        })
    } catch (i) {
        throw console.error(`Erro ao enviar mensagem para ${t}:`, i), i
    }
}
const Le = b(() => ({
    files: []
}));
async function en() {
    const a = await G("fluxoFiles") || [];
    Le.setState({
        files: a
    })
}
chrome.storage.onChanged.addListener((a, t) => {
    var e;
    if ((e = a.fluxoFiles) != null && e.newValue) {
        const s = a.fluxoFiles.newValue;
        Le.setState({
            files: s
        })
    }
});
async function gr(a, t, e, s) {
    var o, r;
    try {
        const i = Le.getState().files.find(p => p.nodeRefId === s);
        if (!(i != null && i.base64)) return;
        const n = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(p => p.type === "simulateWriting"),
            c = (n == null ? void 0 : n.propriedades) ?? {
                active: !1
            },
            l = se((r = e.globalSettings) == null ? void 0 : r.blockTransitionDelay),
            d = typeof l == "number" && l > 0 ? l : 0;
        (c.active || d > 0) && await m.Chat("markIsComposing", {
            id: t,
            timer: d
        });
        let u = a.caption;
        u = await Oe(t, u, e), u = pe(t, u, e), await m.Chat("sendImage", {
            id: t,
            base64: i.base64.toString(),
            msg: u
        })
    } catch (i) {
        throw console.error(`Erro ao enviar imagem para ${t}:`, i), i
    }
}
async function hr(a, t, e, s) {
    var o, r;
    try {
        const i = Le.getState().files.find(p => p.nodeRefId === s);
        if (!(i != null && i.base64)) return;
        const n = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(p => p.type === "simulateWriting"),
            c = (n == null ? void 0 : n.propriedades) ?? {
                active: !1
            },
            l = se((r = e.globalSettings) == null ? void 0 : r.blockTransitionDelay),
            d = typeof l == "number" && l > 0 ? l : 0;
        (c.active || d > 0) && await m.Chat("markIsComposing", {
            id: t,
            timer: d
        });
        let u = a.caption;
        u = await Oe(t, u, e), u = pe(t, u, e), await m.Chat("sendVideo", {
            id: t,
            base64: i.base64.toString(),
            msg: u
        })
    } catch (i) {
        throw console.error(`Erro ao enviar video para ${t}:`, i), i
    }
}
async function vr(a, t, e, s) {
    var o, r;
    try {
        const i = Le.getState().files.find(u => u.nodeRefId === s);
        if (!(i != null && i.base64)) return;
        const n = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(u => u.type === "simulateWriting"),
            c = (n == null ? void 0 : n.propriedades) ?? {
                active: !1
            },
            l = se((r = e.globalSettings) == null ? void 0 : r.blockTransitionDelay),
            d = typeof l == "number" && l > 0 ? l : 0;
        (c.active || d > 0) && await m.Chat("markIsComposing", {
            id: t,
            timer: d
        }), await m.Chat("sendAudio", {
            id: t,
            base64: i.base64.toString()
        })
    } catch (i) {
        throw console.error(`Erro ao enviar áudio para ${t}:`, i), i
    }
}
async function Ar(a, t, e, s) {
    var o, r;
    try {
        const i = Le.getState().files.find(u => u.nodeRefId === s);
        if (!(i != null && i.base64)) return;
        const n = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(u => u.type === "simulateWriting"),
            c = (n == null ? void 0 : n.propriedades) ?? {
                active: !1
            },
            l = se((r = e.globalSettings) == null ? void 0 : r.blockTransitionDelay),
            d = typeof l == "number" && l > 0 ? l : 0;
        (c.active || d > 0) && await m.Chat("markIsComposing", {
            id: t,
            timer: d
        }), await m.Chat("sendDoc", {
            id: t,
            base64: i.base64.toString(),
            name: i.name
        })
    } catch (i) {
        throw console.error(`Erro ao enviar documento para ${t}:`, i), i
    }
}
async function br(a, t, e, s) {
    var o, r;
    try {
        if (!(a != null && a.question)) return;
        const i = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(u => u.type === "simulateWriting"),
            n = (i == null ? void 0 : i.propriedades) ?? {
                active: !1
            },
            c = se((r = e.globalSettings) == null ? void 0 : r.blockTransitionDelay),
            l = typeof c == "number" && c > 0 ? c : 0;
        (n.active || l > 0) && await m.Chat("markIsComposing", {
            id: t,
            timer: l
        });
        let d = a.question;
        d = await Oe(t, d, e), d = pe(t, d, e), await m.Chat("sendTxt", {
            id: t,
            msg: d
        })
    } catch (i) {
        throw console.error(`Erro ao enviar mensagem para ${t}:`, i), i
    }
}
async function Sr(a, t, e, s) {
    var o, r;
    try {
        if (!(a != null && a.sections)) return;
        const {
            language: i
        } = _.getState(), n = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(S => S.type === "simulateWriting"), c = (n == null ? void 0 : n.propriedades) ?? {
            active: !1
        }, l = se((r = e.globalSettings) == null ? void 0 : r.blockTransitionDelay), d = typeof l == "number" && l > 0 ? l : 0;
        (c.active || d > 0) && await m.Chat("markIsComposing", {
            id: t,
            timer: d
        });
        let u = a.title || "",
            p = a.description || "",
            A = a.footer || "",
            v = a.buttonText || `${i.escolhaUmaOpcao}`;
        u = await Ue(t, u), p = await Ue(t, p), A = await Ue(t, A), v = await Ue(t, v), u = pe(t, u, e), p = pe(t, p, e), A = pe(t, A, e), v = pe(t, v, e);
        const h = {
            buttonText: v,
            description: p,
            title: u,
            footer: A,
            sections: a.sections.map(S => ({
                title: S.title,
                rows: S.rows.map(U => ({
                    rowId: U.rowId,
                    title: U.title,
                    description: U.description || ""
                }))
            }))
        };
        await m.Chat("sendListMessage", {
            id: t,
            options: h
        })
    } catch (i) {
        throw console.error(`Erro ao enviar lista para ${t}:`, i), i
    }
}
const wr = {
    "send-text": (a, t, e, s) => fr(a, t, e),
    "send-image": (a, t, e, s) => gr(a, t, e, s),
    "send-video": (a, t, e, s) => hr(a, t, e, s),
    "send-audio": (a, t, e, s) => vr(a, t, e, s),
    "send-document": (a, t, e, s) => Ar(a, t, e, s),
    "send-answers": (a, t, e, s) => br(a, t, e),
    "send-list": (a, t, e, s) => Sr(a, t, e)
};
let Ut = 0;
const yr = 1e4;
async function de(a, t, e) {
    const {
        language: s
    } = _.getState(), {
        label: o
    } = le.getState(), {
        getSourceNode: r,
        updateVariableAsync: i
    } = T.getState(), {
        getLastMessage: n,
        isVariableUpdated: c,
        markVariableAsUpdated: l
    } = rt.getState();
    if (a.type === "init") return;
    if (await ae("fluxo", !0)) {
        const h = Date.now();
        h - Ut >= yr && (Ut = h, Ye("fluxo", s.btnPremium, o.checkout));
        return
    }
    const d = a.type,
        u = wr[d];
    if (!u) throw new Error(`Tipo de nó não tratado: ${d}`);
    if (a.data.type !== d) throw new Error("Tipo de dados incompatível");
    const p = a.data,
        A = n(t),
        v = r(a.id, e.id);
    A && v && !c(t, v.id) && (await i(t, v.id, e.id, A), l(t, v.id)), await u(p, t, e, a.id)
}
const xr = .7,
    Cr = 2,
    we = a => a.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9\s]/g, "").replace(/\s+/g, " ").trim(),
    Mr = (a, t) => {
        const e = Math.max(a.length, t.length);
        return e === 0 ? 1 : (e - Dt(a, t)) / e
    },
    ta = (a, t) => {
        const {
            options: e,
            typeDetection: s,
            allowNumberDetection: o
        } = t, r = we(a);
        let i = null;
        if (o) {
            const c = parseInt(r, 10);
            if (!isNaN(c)) {
                const l = e.find(d => d.index === c);
                if (l) return l
            }
        }
        if (s.active) switch (s.type) {
            case "equals":
                return e.find(l => we(l.text) === r) || null;
            case "contains":
                let c = 0;
                if (e.forEach(l => {
                        const d = we(l.text);
                        if (r.includes(d)) {
                            i = l;
                            return
                        }
                        const u = Mr(r, d);
                        u > c && u >= xr && (c = u, i = l)
                    }), i) return i;
                break;
            case "startsWith":
                return e.find(l => r.startsWith(we(l.text))) || null;
            case "endsWith":
                return e.find(l => r.endsWith(we(l.text))) || null
        }
        let n = 1 / 0;
        return e.forEach(c => {
            const l = Dt(r, we(c.text));
            l < n && l <= Cr && (n = l, i = c)
        }), i
    },
    Tr = (a, t) => a.send.data.waitTime ? se(a.send.data.waitTime) : null,
    kr = (a, t) => {
        const {
            getAllTargetNodes: e
        } = T.getState(), s = e(a.id, t.id).find(o => o.send.type === "timeout");
        return s || null
    },
    _r = async (a, t, e) => new Promise(s => {
        const o = async r => {
            if (r.data.type === "Ev" && r.data.action === "chat.new_message") {
                const i = JSON.parse(r.data.model);
                i.id.remote.toString() === a && !i.id.fromMe && (i.body && !la(i.body) && rt.getState().setLastMessage(a, i.body), window.removeEventListener("message", o), s(i))
            }
        };
        window.addEventListener("message", o)
    }), Et = async (a, t) => new Promise(e => {
        let s = !1,
            o, r;
        const i = n => {
            s || (s = !0, r && window.removeEventListener("message", r), clearTimeout(o), e(n))
        };
        o = setTimeout(() => i("timeout"), t), r = n => {
            if (n.data.type === "Ev" && n.data.action === "chat.new_message") {
                const c = JSON.parse(n.data.model);
                c.id.remote.toString() === a && !c.id.fromMe && (clearTimeout(o), o = setTimeout(() => i("timeout"), t))
            }
        }, window.addEventListener("message", r)
    }), Rr = a => {
        var e, s;
        const t = ((s = (e = a.globalSettings) == null ? void 0 : e.absenceMessage) == null ? void 0 : s.waitTime) ?? null;
        return t ? se(t) : null
    }, We = async (a, t, e) => {
        var u, p;
        const s = Tr(a),
            o = kr(a, e),
            r = (u = e.globalSettings) == null ? void 0 : u.absenceMessage,
            i = r && ((p = r.message) == null ? void 0 : p.trim()),
            n = i ? Rr(e) : null,
            c = _r(t, a.id, e.id);
        if (!s && !n) return await c;
        const l = [c];
        if (s) {
            const A = Et(t, s).then(() => "node-timeout");
            l.push(A)
        }
        if (n) {
            const A = Et(t, n).then(() => "global-timeout");
            l.push(A)
        }
        const d = await Promise.race(l);
        if (d === "node-timeout") return o ? await Ft(o, t, e) : V.getState().resetUserProgress(t), null;
        if (d === "global-timeout") {
            if (i) {
                const A = {
                        message: r.message,
                        type: "send-text",
                        waitTime: r.waitTime
                    },
                    v = dr("send-text", A);
                await Ft(v, t, e)
            } else V.getState().resetUserProgress(t);
            return null
        }
        return d
    }, Lr = async (a, t, e) => {
        const s = T.getState().getTargetNode(a.id, e.id);
        return s && V.getState().updateUserProgress(t, e.id, s.id), s
    }, Ft = async (a, t, e) => (await de(a, t, e), V.getState().resetUserProgress(t), null), aa = async (a, t, e) => {
        const s = a.data,
            {
                noMatch: o
            } = s,
            {
                sendPersonalizedMessage: r,
                endPersonalizedMessage: i,
                repeatBlock: n
            } = o || {};
        if (!(r != null && r.active) && !(i != null && i.active) && !n) return V.getState().resetUserProgress(t), null;
        if (i != null && i.active) {
            const l = {
                ...a,
                data: {
                    ...s,
                    question: i.personalizedMessage || ""
                }
            };
            return await de(l, t, e), V.getState().resetUserProgress(t), null
        }
        const c = {
            ...a,
            data: {
                ...s,
                question: T.getState().getRetryQuestion(s)
            }
        };
        V.getState().updateUserProgress(t, e.id, c.id), await de(c, t, e);
        try {
            const l = await We(a, t, e);
            if (l === null) return null;
            const d = l.body,
                u = ta(d, s);
            if (u) {
                const p = T.getState().getTargetNodeByBestMatch(a.id, e.id, u.index);
                if (p) return V.getState().updateUserProgress(t, e.id, p.id), await de(p, t, e), p
            }
            return !u && (n || r != null && r.active) ? await aa(a, t, e) : (V.getState().resetUserProgress(t), null)
        } catch (l) {
            return console.error("Erro inesperado em handleNoMatchNode:", l), V.getState().resetUserProgress(t), null
        }
    }, Ur = async (a, t, e) => {
        const s = T.getState().getSourceNode(a.id, e.id);
        return await We(s, t, e) === null ? null : (await de(a, t, e), T.getState().getTargetNode(a.id, e.id))
    }, Er = async (a, t, e) => {
        const s = T.getState().getSourceNode(a.id, e.id);
        if (!s || s.type !== "send-answers") return null;
        const o = await We(s, t, e);
        if (o === null) return null;
        const r = o.body,
            i = s.data,
            n = ta(r, i);
        if (!n) {
            const l = await aa(s, t, e);
            return l ? T.getState().getTargetNode(l.id, e.id) : null
        }
        const c = T.getState().getTargetNodeByBestMatch(s.id, e.id, n.index);
        return c ? (await de(c, t, e), T.getState().getTargetNode(c.id, e.id)) : null
    }, sa = async (a, t, e) => {
        var l, d;
        const s = T.getState().getSourceNode(a.id, e.id);
        if (!s || s.type !== "send-list") return null;
        const o = await We(s, t, e);
        if (o === null) return null;
        const r = s.data,
            i = r.sections.flatMap(u => u.rows.map(p => p.rowId)),
            n = (d = (l = o.listResponse) == null ? void 0 : l.singleSelectReply) == null ? void 0 : d.selectedRowId;
        if (!n || !i.includes(n)) {
            const {
                noMatch: u
            } = r, {
                repeatBlock: p
            } = u || {};
            if (p) return await de(s, t, e), await sa(a, t, e)
        }
        const c = T.getState().getTargetNodeByRowId(s.id, e.id, n);
        return c ? (V.getState().updateUserProgress(t, e.id, c.id), await de(c, t, e), T.getState().getTargetNode(c.id, e.id)) : null
    }, Fr = async (a, t, e) => (await de(a, t, e), T.getState().getTargetNode(a.id, e.id));
async function Nr({
    msg: a,
    manualActivation: t
}) {
    if (a.id.fromMe || !Ze.includes(a.type)) return;
    const e = a.id.remote.toString(),
        s = Xt.getState();
    if (Lt.getState().isProcessing(e)) return;
    const o = t ? [t.workflow] : T.getState().workflows.filter(r => r.active);
    if (o.length) {
        for (const r of o) {
            if (!cr(r) || !t && !nr(e, r) || !t && (!await rr(a, r) || !await ir(a, r))) continue;
            rt.getState().resetUpdatedVariables(e);
            const i = V.getState(),
                n = Lt.getState(),
                c = r.nodes.find(d => d.type === "init");
            if (!c) continue;
            s.startSession(e, r.id);
            let l = i.getUserProgress(e);
            if ((!l || l.workflowId !== r.id) && (i.resetUserProgress(e), i.updateUserProgress(e, r.id, c.id), l = {
                    currentNodeId: c.id,
                    workflowId: r.id
                }), !n.isProcessing(e)) {
                n.addProcessingUser(e);
                try {
                    let d = r.nodes.find(u => u.id === l.currentNodeId);
                    if (!d) {
                        i.resetUserProgress(e), s.endSession(e);
                        continue
                    }
                    for (; d;) {
                        if (s.updateLastInteraction(e), d.type !== "init" && !t && !await ea(a, r)) {
                            i.resetUserProgress(e), s.endSession(e), d = null;
                            break
                        }
                        switch (!0) {
                            case d.type === "init":
                                d = await Lr(d, e, r);
                                break;
                            case d.send.type === "timeout":
                                i.resetUserProgress(e), d = null;
                                break;
                            case d.send.type === "on-response":
                                d = await Ur(d, e, r);
                                break;
                            case d.send.type === "next-block":
                                d = await Fr(d, e, r);
                                break;
                            case /^on-response-\d+$/.test(d.send.type):
                                d = await Er(d, e, r);
                                break;
                            case /^on-response-[a-zA-Z0-9-]+$/.test(d.send.type):
                                d = await sa(d, e, r);
                                break;
                            default:
                                d = null
                        }
                        if (d) i.updateUserProgress(e, r.id, d.id);
                        else {
                            i.resetUserProgress(e), s.updateLastInteraction(e);
                            break
                        }
                    }
                    i.resetUserProgress(e), s.updateLastInteraction(e)
                } catch {
                    i.resetUserProgress(e), s.endSession(e)
                } finally {
                    n.removeProcessingUser(e)
                }
            }
        }
        V.getState().resetUserProgress(e)
    }
}
const Nt = W.getState().dispartWebhook;
let It = null,
    fe = null,
    Je = !1;
const Be = b()(() => ({
    chatListTabs: async () => {
        const {
            activeTab: a,
            userTabs: t
        } = q.getState(), {
            selecionados: e
        } = Qt.getState();
        let s;
        if ((a == null ? void 0 : a.type) !== "default-filter") {
            if ((a == null ? void 0 : a.type) === "tab") switch (a.id) {
                case 1:
                    s = "tab-1-tudo";
                    break;
                case 2:
                    s = "tab-2-grupos";
                    break;
                case 3:
                    s = "tab-3-nao-lido";
                    break;
                case 4:
                    s = "tab-4-1:1";
                    break;
                case 5:
                    s = `tab-5-atendimento-${C.getState().user}`;
                    break;
                case 6:
                    s = `tab-6-trasferencias-${C.getState().user}`;
                    break;
                default:
                    s = `tab-${a.id}-UserTabs`;
                    break
            } else a.type === "custom" ? s = `custom-${JSON.stringify(e)}-${C.getState().user}` : s = `label-${a.id}`;
            if (It !== s)
                if (It = s, (a == null ? void 0 : a.type) === "tab") switch (a.id) {
                    case 1:
                        await m.ListChat("tudo");
                        break;
                    case 2:
                        await m.ListChat("grupos");
                        break;
                    case 3:
                        await m.ListChat("nao-lido");
                        break;
                    case 4:
                        await m.ListChat("1:1");
                        break;
                    case 5:
                        await m.ListChat("atendimento", C.getState().user);
                        break;
                    case 6:
                        await m.ListChat("trasferencias", C.getState().user);
                        break;
                    default:
                        await m.ListChat("UserTabs", t.find(o => o.id === a.id).chats);
                        break
                } else a.type === "custom" ? m.ListChat("custom", {
                    selecionados: e,
                    user: C.getState().user
                }) : await m.ListChat("UserLabels", a.id)
        }
    },
    setupListeners: () => {
        if (Je) return console.warn("[new_message] Listener já está ativo, ignorando chamada duplicada"), () => {};
        fe && fe.abort(), fe = new AbortController, Je = !0;
        const a = t => {
            if (t.data.type === "Ev" && t.data.action === "chat.new_message") {
                const e = JSON.parse(t.data.model);
                if (t.data.author && (e.author = t.data.author), ar(e), Nr({
                        msg: e,
                        manualActivation: null
                    }), So(e), Nt(e.from.toString().replace(/@.*/g, ""), "messages", e), e.ctwaContext) {
                    const s = e.from.toString();
                    Nt(s.replace(/@c\.us/g, ""), "metaAds")
                }
                e.id.fromMe && e.type === "chat" && !e.author && Z.getState().filterAtendimento(e), q.getState().activeTab.type === "custom" && setTimeout(() => {
                    Be.getState().chatListTabs()
                }, 1e3)
            }
        };
        return window.addEventListener("message", a, {
            signal: fe.signal
        }), () => {
            fe && (fe.abort(), fe = null), Je = !1
        }
    }
}));
Be.getState().setupListeners();
async function Ir() {
    const {
        user: a
    } = C.getState(), t = await G("initDate");
    return t ? a.estado ? !1 : (Date.now() - t) / (1440 * 60 * 1e3) >= 3 : (f("initDate", Date.now()), !1)
}
const Z = b()((a, t) => ({
        active: !1,
        unsubscribeUserLogin: null,
        socket: null,
        atendente: null,
        multi_atendente: [],
        chatActive_atentendes: [],
        atendimentos: [],
        connect: async e => {
            var v, h;
            const {
                update: s,
                ouvintes: o
            } = t(), {
                user: r
            } = C.getState(), {
                assinatura: i,
                setMultiATendimento: n
            } = I.getState(), c = (h = (v = H.getState().activeChat) == null ? void 0 : v.id) == null ? void 0 : h._serialized, {
                openRendertype: l
            } = X.getState(), d = y.getState().browserID;
            if (await Ir()) {
                l("user_free"), n();
                return
            }
            const p = ga(ye.webSocket["multi-atendimento"], {
                path: "/ws/socket.io",
                transports: ["websocket"]
            });
            p.open(), p.on("connection", null);
            const A = {
                id: "",
                user_id: d,
                whatsappID: e,
                userLogado: r.estado,
                email: r.login,
                assinaturaActive: i.active,
                assinatura: i.name,
                activeChat: c
            };
            p.emit("connect-atendente", A), m.MultiAtendimento("start"), s(c), o(p), a({
                socket: p,
                active: !0,
                unsubscribeUserLogin: C.subscribe(() => {
                    s(c)
                })
            })
        },
        disconnect: () => a(() => {
            const {
                socket: e,
                unsubscribeUserLogin: s
            } = t();
            return e == null || e.close(), e == null || e.disconnect(), m.MultiAtendimento("stop"), s && s(), {
                active: !1,
                atendente: null,
                unsubscribeUserLogin: null
            }
        }),
        update: e => {
            const {
                socket: s,
                atendente: o,
                active: r
            } = t(), {
                user: i
            } = C.getState(), {
                assinatura: n
            } = I.getState(), {
                whatsappID: c,
                browserID: l
            } = y.getState();
            if (r && o) {
                const d = {
                    ...o,
                    whatsappID: c,
                    userLogado: i.estado,
                    activeChat: e,
                    email: i.login,
                    assinaturaActive: n.active,
                    assinatura: n.name
                };
                s.emit("update-atendente", d), a({
                    atendente: d
                })
            }
        },
        active_atendentes: e => a(() => {
            var r, i;
            const s = (i = (r = H.getState().activeChat) == null ? void 0 : r.id) == null ? void 0 : i._serialized,
                {
                    whatsappID: o
                } = y.getState();
            return {
                multi_atendente: e,
                chatActive_atentendes: e.filter(n => n.whatsappID === o && n.activeChat === s)
            }
        }),
        send_atendimento: (e, s) => {
            const {
                whatsappID: o
            } = y.getState(), {
                socket: r,
                atendente: i,
                active: n
            } = t(), c = {
                chatID: e,
                whatsappID: o,
                atendente: i,
                status: s,
                dataUltimaInteracao: Date.now()
            };
            n && i && r.emit("update-atendimento", c)
        },
        trasferir_atendimento: (e, s, o) => {
            var u;
            const {
                socket: r,
                atendente: i
            } = t(), {
                user: n,
                _serialized: c
            } = (u = H.getState().activeChat) == null ? void 0 : u.id, {
                whatsappID: l
            } = y.getState(), d = {
                chatID: c,
                whatsappID: l,
                atendente: e,
                status: "Transferido",
                dataUltimaInteracao: Date.now()
            };
            r.emit("transferir_atendimento", {
                attID: e.id,
                remetenteID: i.id,
                chatID: n,
                text: s,
                urgencia: o
            }, d)
        },
        getMyAtendimento: () => {
            const {
                atendimentos: e
            } = Z.getState(), {
                browserID: s
            } = y.getState();
            return e.filter(o => {
                var r;
                return ((r = o.atendente) == null ? void 0 : r.user_id) === s
            }).filter(o => o.status !== "Finalizado").map(o => o.chatID)
        },
        getAtendimentoByDeviceID: e => {
            const {
                atendimentos: s
            } = t();
            return s.filter(o => o.atendente.user_id === e).filter(o => o.status !== "Finalizado").length
        },
        filterAtendimento: e => {
            const {
                send_atendimento: s
            } = t();
            e.body.includes("*_Atendimento Finalizado_*") || e.body.includes("*_Atendimento Trasferido para") || s(e.id.remote.toString(), "Ativo")
        },
        ouvintes: e => {
            const {
                update: s
            } = t(), {
                renderTrasferencia: o
            } = Ae.getState();
            e.on("connected-atentende", ({
                atendente: r,
                atendimentos: i
            }) => {
                var c, l;
                Z.setState({
                    atendente: r
                }), m.MultiAtendimento("setAtendimento", {
                    atendimentos: i,
                    user: C.getState().user
                }), Z.setState({
                    atendimentos: i
                });
                const n = (l = (c = H.getState().activeChat) == null ? void 0 : c.id) == null ? void 0 : l._serialized;
                s(n)
            }), e.on("active-atendentes", r => {
                Z.getState().active_atendentes(r)
            }), e.on("active-atendimento", r => {
                m.MultiAtendimento("setAtendimento", {
                    atendimentos: r,
                    user: C.getState().user
                }), Be.getState().chatListTabs(), Z.setState({
                    atendimentos: r
                })
            }), e.on("transferir_atendimento", r => {
                o(r)
            })
        },
        addLocalAtendente: (e, s) => a(o => {
            const {
                whatsappID: r
            } = y.getState(), {
                atendente: i
            } = t(), n = {
                chatID: e,
                whatsappID: r,
                atendente: i,
                status: s,
                dataUltimaInteracao: Date.now()
            }, c = o.atendimentos.filter(l => l.chatID !== e);
            return {
                atendimentos: [n, ...c]
            }
        })
    })),
    tn = async () => {
        const {
            connect: a
        } = Z.getState(), {
            assinatura: t
        } = I.getState();
        if (t.multiAtendimento) {
            const {
                user: e
            } = await m.Conn("getMyDeviceId");
            a(e)
        }
    }, qr = (a, t) => {
        a.forEach(e => {
            e.addedNodes.forEach(s => {
                t(e)
            })
        })
    }, Pr = a => {
        const {
            update: t
        } = Z.getState(), {
            getElement: e
        } = D.getState(), {
            setIsOpen: s
        } = xe.getState();
        qr(a, o => {
            var i;
            const r = o.addedNodes[0];
            (r == null ? void 0 : r.id) === "main" ? s(!0): (i = r == null ? void 0 : r.classList) != null && i.contains(e("closeChat")) && (t("closeChat"), s(!1))
        })
    }, zr = a => {
        const {
            setIsThree: t
        } = xe.getState(), {
            getElement: e
        } = D.getState();
        a[0].target.classList.contains(e("two")) ? t(!1) : t(!0)
    }, Qe = (a, t, e) => {
        new MutationObserver(t).observe(a, e)
    }, Dr = () => {
        const {
            getSeletor: a
        } = D.getState();
        a("menuLateral", t => {
            Qe(t, Pr, {
                childList: !0
            })
        }), a("waPage", t => {
            Qe(t, zr, {
                attributes: !0
            })
        })
    };
ua(D.getState().getElement("paneSide"), () => {
    Dr(), D.getState().getSeletor("whatsModal", a => {
        Qe(a, t => {
            const {
                setIsOpen: e
            } = xe.getState();
            t[0].addedNodes.length > 0 ? e(!1) : e(!0)
        }, {
            childList: !0
        })
    })
});
const xe = b()((a, t) => ({
    isOpen: !1,
    setIsOpen: e => a(s => ({
        isOpen: e
    })),
    isThree: !1,
    setIsThree: e => a(s => ({
        isThree: e
    })),
    menuContent: {
        children: "close",
        width: "320",
        desactiveMonitorEnv: !1
    },
    setMenuContent: (e, s) => a(o => {
        const r = {
            ...o.menuContent,
            [e]: s
        };
        return O("MenuContentDB", "MenuContent", [r]), {
            menuContent: r
        }
    }),
    assinatura: {
        desativar: !1,
        personalizar: !1,
        nome: ""
    },
    setAssinatura: (e, s) => a(o => {
        let r = o.assinatura;
        return e === "desativar" && s ? r = {
            ...o.assinatura,
            desativar: !0,
            personalizar: !1
        } : e === "personalizar" && s ? r = {
            ...o.assinatura,
            personalizar: !0,
            desativar: !1
        } : r = {
            ...o.assinatura,
            [e]: s
        }, O("menulatera-assinatura", "assinatura", [r]), {
            assinatura: r
        }
    })
}));
(async () => {
    const a = await Q("MenuContentDB", "MenuContent");
    a && a[0] && a[0][0] && xe.setState({
        menuContent: a[0][0]
    });
    const t = await Q("menulatera-assinatura", "assinatura");
    t && t[0] && t[0][0] && xe.setState({
        assinatura: t[0][0]
    })
})();
const oa = b()((a, t) => ({
    actions: [],
    addActions: e => a(s => {
        const o = [...s.actions, e];
        return f("respostasRapidasAcao", o), {
            actions: o
        }
    }),
    editActions: e => a(s => {
        const o = s.actions.map(r => r.id === e.id ? e : r);
        return f("respostasRapidasAcao", o), {
            actions: o
        }
    }),
    deleteActions: e => a(s => {
        const o = s.actions.filter(r => r.id !== e);
        return f("respostasRapidasAcao", o), {
            actions: o
        }
    }),
    edit: e => {
        const {
            actions: s
        } = t(), o = s.find(r => r.id === e);
        o && Kt.setState({
            acao: o.acao
        })
    },
    getAction: e => {
        const {
            actions: s
        } = t();
        return s.find(r => r.id === e).acao || []
    },
    sendAction: async (e, s, o) => {
        var u;
        const {
            actions: r
        } = t(), {
            activeChat: i
        } = H.getState(), {
            assinatura: n
        } = xe.getState(), {
            language: c
        } = _.getState(), {
            dispartWebhook: l
        } = W.getState();
        let d = [];
        if (e.type === "script")
            for (const [p, {
                    id: A,
                    timer: v
                }] of e.script.entries()) {
                const h = r.find(S => S.id === A);
                h && h.acao && (p > 0 && d.push({
                    id: E(),
                    propriedades: {
                        segundos: v
                    },
                    type: "timer"
                }), d.push(...h.acao))
            } else d = (u = r.find(p => p.id === e.id)) == null ? void 0 : u.acao;
        if (d && d.length > 0) {
            const p = s || i.id._serialized;
            await st(p, d, o || n, "useAcaoRespostaRapida"), l(p.replace(/@(?:g|c)\.us/g, ""), "respostaRapida", {
                id: e.id,
                type: e.type,
                name: e.titulo,
                categoria: e.categoria
            })
        } else N({
            type: "Error",
            message: c.createResNotAction,
            position: "top-right"
        })
    }
}));
chrome.runtime.onMessage.addListener(a => {
    switch (a.action) {
        case "sendAction-Res":
            oa.getState().sendAction(a.dados.res, a.dados.userID);
            break
    }
});
const R = b()(a => ({
        viewIA: "Gemini",
        setViewIA: t => a({
            viewIA: t
        }),
        IA: {
            activeIA: null,
            keyGemini: "",
            agenteIA: "Random",
            keyGPT: "",
            instanceGemini: null,
            instanceGPT: null
        },
        setIA: (t, e) => a(s => {
            const o = {
                ...s.IA,
                [t]: e
            };
            return f("IA", o), {
                IA: o
            }
        }),
        validateGeminiKey: async (t = !0) => {
            const {
                language: e
            } = _.getState(), s = R.getState().IA.keyGemini, o = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${s}`;
            try {
                await ve.post(o, {
                    contents: [{
                        parts: [{
                            text: "hello"
                        }]
                    }]
                });
                const i = new ya(s).getGenerativeModel({
                    model: "gemini-2.0-flash"
                });
                t && N({
                    type: "Success",
                    message: e.useIAchaveAPI,
                    position: "top-right"
                });
                const n = {
                    ...R.getState().IA,
                    activeIA: "Gemini",
                    instanceGemini: i
                };
                R.setState({
                    IA: n
                }), f("IA", n)
            } catch (r) {
                R.setState({
                    IA: {
                        ...R.getState().IA,
                        activeIA: null,
                        instanceGemini: null
                    }
                }), r instanceof pa && r.status === 429 ? (console.error("Erro ao validar a chave Gemini:", r.status), N({
                    type: "Error",
                    message: e.useIAFreeTeste,
                    position: "top-right"
                })) : t && N({
                    type: "Error",
                    message: e.useIAchaveAPI,
                    position: "top-right"
                })
            }
        },
        validateGPTKey: (t = !0) => {
            const {
                language: e
            } = _.getState(), s = () => {
                const o = {
                    ...R.getState().IA,
                    activeIA: null,
                    instanceGPT: null
                };
                R.setState({
                    IA: o
                }), t && N({
                    type: "Error",
                    message: e.ChaveDaApiGPTInvalida,
                    position: "top-right"
                })
            };
            ve.get("https://api.openai.com/v1/engines", {
                headers: {
                    Authorization: `Bearer ${R.getState().IA.keyGPT}`
                }
            }).then(() => {
                try {
                    const o = new xa({
                        apiKey: R.getState().IA.keyGPT || "",
                        dangerouslyAllowBrowser: !0
                    });
                    t && N({
                        type: "Success",
                        message: e.chaveGPTProntaParaUso,
                        position: "top-right"
                    });
                    const r = {
                        ...R.getState().IA,
                        activeIA: "GPT",
                        instanceGPT: o
                    };
                    R.setState({
                        IA: r
                    }), f("IA", r)
                } catch {
                    s()
                }
            }).catch(o => {
                s(), console.error("Erro ao realizar a ativação da key do gemini: " + o)
            })
        }
    })),
    an = async a => {
        switch (R.setState({
                IA: a
            }), a.activeIA) {
            case "Gemini":
                R.getState().validateGeminiKey(!1);
                break;
            case "GPT":
                R.getState().validateGPTKey(!1);
                break
        }
    }, sn = async () => {
        const a = await G("IA") || [];
        switch (R.setState({
                IA: a
            }), a.activeIA) {
            case "Gemini":
                R.getState().validateGeminiKey(!1);
                break;
            case "GPT":
                R.getState().validateGPTKey(!1);
                break
        }
    }, ee = b()(a => ({
        assistente: {
            active: !1,
            model: "tradutor"
        },
        textAssistente: "",
        setAssistente: (t, e) => a(s => {
            const o = {
                ...s.assistente,
                [t]: e
            };
            O("useAssistente", "assistente", [o]), t === "active" && !s.assistente.active && ee.getState().manipulatedInputText(), t === "model" && setTimeout(() => {
                ee.getState().reloadText()
            }, 2500);
            const r = document.querySelector("main");
            return r && r.setAttribute("active-assistente-chat", String(o.active)), {
                assistente: {
                    ...s.assistente,
                    [t]: e
                }
            }
        }),
        formatTextAssistente: async t => {
            const e = await ra(t);
            e.success && a({
                textAssistente: e.response
            })
        },
        manipulatedInputText: () => {
            const {
                getSeletor: t
            } = D.getState(), {
                activeChat: e
            } = H.getState();
            if (!e || !e.canSend) return;
            const s = t("footerTextArea");
            if (!s) return;
            let o = null;
            const r = () => {
                o && clearTimeout(o), o = setTimeout(() => {
                    const n = [...(s == null ? void 0 : s.childNodes) ?? []].map(c => c.innerText !== `
` ? c.innerText : "").join(`
`);
                    ee.getState().formatTextAssistente(n)
                }, 3e3)
            };
            new MutationObserver(r).observe(s, {
                subtree: !0,
                childList: !0,
                attributes: !0
            }), s.addEventListener("copy", r), s.addEventListener("paste", r), s.addEventListener("cut", r), t("assChat", n => {
                const c = l => {
                    l.key === "Enter" && l.altKey && (l.stopPropagation(), ee.getState().sendAssistenteMenssage())
                };
                n.addEventListener("keydown", c), setTimeout(() => {
                    n.scrollTop = n.scrollHeight
                }, 500)
            }), t("assInput", n => {
                n == null || n.addEventListener("keydown", c => {
                    c.key === "Enter" && c.altKey && (c.preventDefault(), c.stopPropagation(), ee.getState().sendAssistenteMenssage())
                }, !0)
            })
        },
        reloadText: () => {
            const {
                getSeletor: t
            } = D.getState(), e = t("footerTextArea"), s = [...(e == null ? void 0 : e.childNodes) ?? []].map(o => o.innerText !== `
` ? o.innerText : "").join(`
`);
            ee.getState().formatTextAssistente(s)
        },
        sendAssistenteMenssage: async () => {
            var i, n;
            const {
                assinatura: t
            } = I.getState(), e = (n = (i = H.getState().activeChat) == null ? void 0 : i.id) == null ? void 0 : n._serialized, {
                textAssistente: s
            } = ee.getState(), {
                getSeletor: o
            } = D.getState();
            if (s.length === 0 || await ae("assistente_chat")) return;
            let r = s;
            t.active && (r = `*_${t.name}:_* 
${r}`), a({
                textAssistente: ""
            }), m.Functions("sendTextChat", {
                chatID: e,
                formattedMessage: r
            }), o("assEmoji", c => {
                c == null || c.click()
            }), o("assCitacao", c => {
                c == null || c.click()
            })
        }
    }));
(async () => {
    const a = await Q("useAssistente", "assistente");
    a && a[0] && a[0][0] && ee.setState({
        assistente: a[0][0]
    })
})();
const jr = async a => {
    const {
        instanceGPT: t
    } = R.getState().IA, {
        language: e
    } = _.getState();
    try {
        const s = await t.chat.completions.create({
            messages: [{
                role: "user",
                content: a
            }],
            model: "gpt-3.5-turbo-0125",
            temperature: .5
        });
        return {
            success: !!s.choices[0].message.content,
            response: s.choices[0].message.content
        }
    } catch (s) {
        return s.code === "insufficient_quota" && N({
            type: "Error",
            message: e.limiteDeUsoAtingidoOpenAI,
            position: "top-right"
        }), console.error(s), {
            success: !1,
            response: null
        }
    }
}, Or = async a => {
    const {
        instanceGemini: t
    } = R.getState().IA, s = (await t.generateContent(a)).response;
    return {
        success: !!(s && s.text()),
        response: s.text()
    }
};
async function it(a) {
    const {
        IA: t
    } = R.getState(), {
        openRendertype: e
    } = X.getState(), {
        setAssistente: s
    } = ee.getState(), {
        language: o
    } = _.getState();
    let r;
    switch (t.activeIA) {
        case "Gemini":
            r = await Or(a);
            break;
        case "GPT":
            r = await jr(a);
            break;
        default:
            e("Active_IA"), N({
                type: "Info",
                message: o.keyAPI_IA,
                position: "top-right"
            }), s("active", !1), r = {
                success: !1,
                response: ""
            };
            break
    }
    return r
}
async function Wr(a) {
    const t = `Correct the spelling of this text while maintaining the default language: [${a}] , (take the received text calmly and correct its spelling, avoiding word substitutions as much as possible, keep all emojis, keep all characters, keep all links ) 
    After finishing, return the text between [ and ].`,
        e = await it(t);
    return {
        success: e.success,
        response: e.success ? (() => {
            const s = /\[([^\]]*?)\]/g;
            return e.response.match(s)[0].slice(1, -1)
        })() : ""
    }
}
async function Br(a) {
    const t = `improve this text by making it slightly more persuasive: [${a}] , (capture the text calmly and improve it, keep the language, keep all the emojis, keep all the characters, keep all the links, don't generate a link if it does not exist in the text) 
    After finishing, return the text between [ and ].`,
        e = await it(t);
    return {
        success: e.success,
        response: e.success ? (() => {
            const s = /\[([^\]]*?)\]/g;
            return e.response.match(s)[0].slice(1, -1)
        })() : ""
    }
}
async function Vr(a, t) {
    const e = `Traduza o seguinte texto para ${a}, mantendo seu significado original:  

- Preserve todos os emojis, caracteres e links existentes.  
- Mantenha a formatação original do texto sempre que possível.  
- Não altere a estrutura das frases sem necessidade.  
- Mantenha a moeda do idioma original enfatizando que ela pertence a ele.
- Retorne o texto traduzido entre [ e ].  

Texto a ser traduzido: [${t}]`,
        s = await it(e);
    return {
        success: s.success,
        response: s.success ? (() => {
            const o = /\[([^\]]*?)\]/g;
            return s.response.match(o)[0].slice(1, -1)
        })() : ""
    }
}
const $r = async (a, t, e) => {
    const s = ["Traduza o texto para o idioma " + e];
    return await m.IA("text", {
        agente: a,
        question: t,
        context: s
    })
}, Hr = async (a, t) => {
    const e = ["Gramatica: Valide o texto por completo e corrija gramaticalmente conformo o idioma do texto."];
    return await m.IA("text", {
        agente: a,
        question: t,
        context: e
    })
}, Gr = async (a, t) => {
    const e = ["Objetivo: gerar uma resposta de vendas curta, clara e convincente que faça o lead avançar de etapa.", "Preserve exatamente: nome do produto, preço/valores, condições/prazos e links. Não invente dados.", "Ética: nada de promessas irreais, falsas garantias ou escassez fictícia. Seja honesto e transparente.", "Estrutura sugerida (modo vendas): (1) Gancho orientado a benefício → (2) 1-3 benefícios/diferenciais claros → (3) Prova/resultado rápido (se houver) → (4) Oferta com preço/condição → (5) Redução de risco (garantia, suporte, teste) → (6) CTA única.", "Tom: consultivo, confiante e cordial. Evite jargões; priorize clareza e valor prático.", "Persuasão: use gatilhos éticos (urgência real, ancoragem de valor, prova social). Evite exageros.", "Personalização: espelhe vocabulário do lead e contexto da conversa. Se citar dor/objetivo do lead, conecte diretamente ao benefício do produto.", "Objeções: antecipe 1 objeção provável (ex.: preço, tempo, complexidade) e responda de forma breve e empática.", "Comprimento padrão (modo vendas): 2-5 frases (ou conforme solicitado).", "Emojis: use no máximo 1-2 apenas se aumentarem a clareza/impacto.", "Se faltar informação crítica, faça 1 pergunta objetiva e já proponha o próximo passo (somente no modo vendas).", "Comprimento: mantenha entre -10% e +10% do tamanho original", 'Detecção de contexto: se a entrada for apenas saudação/abertura de script (ex.: "bom dia", "boa tarde", "olá, tudo bem?", "como vai?", cumprimentos e cordialidades), ative o modo "script neutro".', "Modo script neutro: apenas aperfeiçoe gramática, naturalidade e pontuação; mantenha a intenção e o estilo originais; NÃO adicionar produto, benefícios, preço, provas, urgência, CTA, links ou perguntas novas. Só preserve/ajuste o que já existe.", "Critério de ativação do modo vendas: só use a estrutura de vendas quando houver sinais claros (menção a produto/oferta/preço/funcionalidades, pergunta do lead sobre a solução, ou quando a mensagem já estiver em contexto comercial).", "Critério nomes e link: somente utilizar caso o texto ter eles, pois caso não trate como uma mensagem isolada e melhore apenas o contexto dela", "Saída: responda somente com a mensagem final (de vendas OU saudação aperfeiçoada), sem markdown, rótulos ou explicações."];
    return await m.IA("text", {
        agente: a,
        question: t,
        context: e
    })
}, ra = async (a, t, e) => {
    const {
        assistente: s
    } = ee.getState(), {
        activePerfil: o
    } = $.getState(), {
        IA: r
    } = R.getState();
    if (!r.activeIA || !a.trim()) return {
        success: !1,
        response: ""
    };
    let i;
    switch (t || s.model) {
        case "tradutor":
            const n = e || (o.idioma && o.idioma.length !== 0 ? o.idioma : "English");
            r.activeIA === "system" ? i = await $r(r.agenteIA, a, n) : i = await Vr(n, a);
            break;
        case "corretor_ortografico":
            r.activeIA === "system" ? i = await Hr(r.agenteIA, a) : i = await Wr(a);
            break;
        case "otimizador_texto":
            r.activeIA === "system" ? i = await Gr(r.agenteIA, a) : i = await Br(a);
            break
    }
    return i
}, Jr = "/assets/png/Translate.chunk.png", Ce = document.createElement("div");
Ce.setAttribute("data-id", "btn-tradutor");
Ce.setAttribute("class", "cursor-pointer !mx-1 lg:tooltip");
Ce.innerHTML = `<img src='${chrome.runtime.getURL("content/"+Jr)}' class='h-6 w-6 pulse shadow-2xl brightness-125 dark:brightness-100' />`;
Ce.addEventListener("click", () => ne.getState().translateMsg());
const Kr = a => {
        const {
            getListElement: t
        } = D.getState(), e = document.createElement("section");
        e.setAttribute("data-id", "audio-transcriber");
        const s = a.querySelector('section[data-id="audio-transcriber"]');
        return s || ((a.querySelector(t("useTradutor", "main_audio_1")) || a.querySelector(t("useTradutor", "main_audio_2"))).appendChild(e), e)
    },
    qt = (a, t) => {
        const {
            language: e
        } = _.getState(), s = document.createElement("div");
        s.setAttribute("data-id", "btn-trascription-audio"), s.className = "flex justify-center pb-3", s.innerHTML = `
        <div class="flex gap-2 text-[var(--primaria)] justify-center items-center mt-2 border border-solid rounded-2xl max-w-32 p-1 px-2 cursor-pointer pulse hover:bg-[var(--terciaria)]">
            <span>
                <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlnsxlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 60 60" xmlbase="preserve" style="
                    fill: var(--primaria);
                    stroke: var(--primaria);
                    height: 22px;
                    width: 22px;
                ">
                    <g>
                        <path d="M10 48.41V53a4 4 0 0 0-4 4v1a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-1a4 4 0 0 0-4-4v-4.59A14.02 14.02 0 0 0 28 35v-3a3 3 0 0 0-3-3 2.966 2.966 0 0 0-1 .184V23a10 10 0 0 0-20 0v6.184A2.966 2.966 0 0 0 3 29a3 3 0 0 0-3 3v3a14.02 14.02 0 0 0 10 13.41ZM20 57v1H8v-1a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2Zm-4-4h-4v-4.16a13.884 13.884 0 0 0 2 .16 13.884 13.884 0 0 0 2-.16Zm-2-38a8.008 8.008 0 0 1 7.931 7H18a1 1 0 0 0 0 2h4v4h-4a1 1 0 0 0 0 2h4v4h-4a1 1 0 0 0 0 2h3.931a7.993 7.993 0 0 1-15.862 0H10a1 1 0 0 0 0-2H6v-4h4a1 1 0 0 0 0-2H6v-4h4a1 1 0 0 0 0-2H6.069A8.008 8.008 0 0 1 14 15ZM2 32a1 1 0 0 1 2 0v3a10 10 0 0 0 20 0v-3a1 1 0 0 1 2 0v3a12 12 0 0 1-24 0ZM54 0H34a6.006 6.006 0 0 0-6 6v14a6.006 6.006 0 0 0 6 6v4.171a2.791 2.791 0 0 0 1.674 2.579 2.836 2.836 0 0 0 1.162.25 2.791 2.791 0 0 0 1.873-.727L45.684 26H54a6.006 6.006 0 0 0 6-6V6a6.006 6.006 0 0 0-6-6Zm4 20a4 4 0 0 1-4 4h-8.7a1 1 0 0 0-.669.257l-7.259 6.53A.824.824 0 0 1 36 30.172V25a1 1 0 0 0-1-1h-1a4 4 0 0 1-4-4V6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4Z" opacity="1" data-original="#000000"></path>
                        <path d="M53 9H35a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2ZM48 15H35a1 1 0 0 0 0 2h13a1 1 0 0 0 0-2Z" opacity="1" data-original="#000000"></path>
                    </g>
                </svg>
            </span>
    
            <span class="text-sm font-medium">
                ${e.trascrever}
            </span>
        </div>
    `, s.addEventListener("click", async function o() {
            const {
                trascreverAudio: r
            } = ne.getState();
            await ae("trascrever_audio") !== !0 && (a.setAttribute("translate", "await"), a.innerHTML = "", a.appendChild(ia()), r(a, t), s.removeEventListener("click", o))
        }), a.innerHTML = "", a.appendChild(s)
    },
    ia = () => {
        const {
            language: a
        } = _.getState(), t = document.createElement("div");
        return t.setAttribute("data-id", "await-trascription"), t.className = "flex justify-center pb-3", t.innerHTML = `
        <div class="px-2 flex gap-2 text-[var(--primaria)] justify-center items-center mt-2 border border-solid rounded-2xl max-w-32 p-1 cursor-pointer pulse hover:bg-[var(--terciaria)]">
            <svg class="animate-spin -ml-1 h-5 w-5 text-[var(--primaria)]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
 
            <span class="text-sm font-medium text-nowrap">
                ${a.aguarde}...
            </span>
        </div>
    `, t
    },
    Pt = a => {
        const t = document.createElement("div");
        return t.setAttribute("data-id", "viwer-text"), t.setAttribute("class", "selectable-text copyable-text"), t.innerHTML = `
        <span style="
            width: 336px;
            display: block;
            padding: 0 12px 12px 12px;
        ">
            <span>${a}</span>
        </span>
    `, t
    },
    ne = b()((a, t) => ({
        activeLanguage: {
            value: "pt",
            label: "Português"
        },
        activeMsgID: "",
        trascriptionAudio: [],
        stateTraducao: {
            message: !1,
            trascreverAudio: !1
        },
        setActiveLanguage: e => a(() => (localStorage.setItem("activeLanguage", JSON.stringify(e)), {
            activeLanguage: e
        })),
        insertBtnTradutor: () => {
            const {
                stateTraducao: e
            } = t(), {
                getSeletor: s,
                getListElement: o
            } = D.getState(), r = () => {
                s("allMensages", i => {
                    i == null || i.forEach(n => {
                        if (!e.message && !n.classList.contains(o("useTradutor", "camp_text_1")) && n.querySelector(o("useTradutor", "camp_text_2")) && (n.addEventListener("mouseenter", () => {
                                ne.setState({
                                    activeMsgID: n.getAttribute("data-id")
                                }), Ce.setAttribute("data-tip", _.getState().language.traduzirMensagem), n.querySelector(o("useTradutor", "add_btn_tradutor")).prepend(Ce)
                            }), n.classList.add(o("useTradutor", "camp_text_1"))), !e.trascreverAudio && (n.querySelector(o("useTradutor", "camp_audio_1")) || n.querySelector(o("useTradutor", "camp_audio_2")))) {
                            const c = n.getAttribute("data-id"),
                                l = ne.getState().trascriptionAudio.find(u => u.id === c),
                                d = Kr(n);
                            l ? (d.innerHTML = "", d.appendChild(Pt(l.text))) : d.getAttribute("translate") === "await" ? (d.innerHTML = "", d.appendChild(ia())) : qt(d, c)
                        }
                    })
                })
            };
            r(), setTimeout(() => {
                r()
            }, 1500), s("listMensages", i => {
                i == null || i.addEventListener("scroll", r)
            })
        },
        translateMsg: async () => {
            const e = _.getState().language,
                s = await m.Chat("getMessageById", ne.getState().activeMsgID);
            let o;
            switch (s.type) {
                case "image":
                case "video":
                case "document":
                    o = s.caption;
                    break;
                default:
                    o = s.body;
                    break
            }
            if (!o || o.length <= 1) {
                N({
                    type: "Error",
                    message: e.invalidTranslationMessage,
                    position: "top-right"
                });
                return
            }
            const r = await ra(o, "tradutor", ne.getState().activeLanguage.label);
            if (!r.success) {
                N({
                    type: "Error",
                    message: e.tryAgain,
                    position: "top-right"
                });
                return
            }
            await ae("useTradutor") !== !0 && m.Msg("replaceMensage", {
                mensagemID: s.id._serialized,
                text: r.response
            })
        },
        trascreverAudio: async (e, s) => {
            const {
                setTrascriptionAudio: o
            } = t(), {
                language: r,
                idioma: i
            } = _.getState();
            try {
                const n = await m.Chat("downloadMedia", s),
                    {
                        data: c
                    } = await ve.post(ye.audio_transcriber, {
                        audio: n,
                        language: i
                    }, {
                        headers: {
                            "Content-Type": "application/json",
                            accept: "application/json",
                            "Secret-Key": ye.cript_key
                        }
                    });
                o({
                    id: s,
                    text: c.transcription
                }), e.innerHTML = "", e.appendChild(Pt(c.transcription)), N({
                    type: "Success",
                    message: r.transcribe_audio_success,
                    position: "top-right"
                })
            } catch (n) {
                console.error(n), N({
                    type: "Error",
                    message: n.response.data.code ? r[n.response.data.code] : r.transcribe_audio_could_not,
                    position: "top-right"
                }), qt(e, s)
            } finally {
                e.removeAttribute("translate")
            }
        },
        setTrascriptionAudio: e => a(s => (O("useTrascription", "trascription-audio", [te.encryptData([...s.trascriptionAudio, e])]), {
            trascriptionAudio: [...s.trascriptionAudio, e]
        })),
        setStateTraducao: (e, s) => a(o => {
            const r = {
                ...o.stateTraducao,
                [e]: s
            };
            return O("useStateTraducao", "stateTraducao", [te.encryptData(r)]), {
                stateTraducao: r
            }
        })
    })),
    on = () => {
        const a = JSON.parse(localStorage.getItem("activeLanguage"));
        a && ne.setState({
            activeLanguage: a
        })
    };
(async () => {
    const a = await Q("useTrascription", "trascription-audio");
    if (a && a[0] && a[0][0]) {
        const t = te.decryptData(a[0][0]);
        ne.setState({
            trascriptionAudio: t
        })
    }
})();
(async () => {
    const a = await Q("useStateTraducao", "stateTraducao");
    if (a && a[0] && a[0][0]) {
        const t = te.decryptData(a[0][0]);
        ne.setState({
            stateTraducao: t
        })
    }
})();
const Zr = {
        aba: "x1rg5ohu x173ssrc x1xaadd7 x682dto x19cawur x12j7j87 x7e1eld x1pg5gke x1s688f xo5v014 x1u28eo4 x2b8uid x16dsc37 x18ba5f9 x1m50h0k x1i47u5t x1g9atge xlh56gj ",
        confgIcone: "x100vrsf x1vqgdyp x78zum5 x6s0dn4 ",
        iconeStyle: "_ajv6 x1y1aw1k x1sxyh0 xwib8y2 xurb0ha ",
        modalOptions: {
            content1: "_ak4w _ap4- xacj9c0 xfh8nwu xoqspk4 x12v9rci x138vmkv ",
            content2: "",
            content3: "x1i64zmx x1emribx ",
            animFather: "_ajv9",
            animExe: "x11t6m9b",
            animChildren: "x11xpdln x1d8287x x1h4ghdb "
        },
        listagem: {
            content1: "x13fj5qh x1xegmmw ",
            content2: "_aj-r _aj-q _aj-_ _ak_v _asi6 _ap51  ",
            content3: "x1c4vz4f xs83m0k xdl72j9 x1g77sc7 x78zum5 xozqiw3 x1oa3qoh x12fk4p8 xeuugli x2lwn1j x1nhvcw1 x1q0g3np x6s0dn4 x1ypdohk x1vqgdyp x13fj5qh x1dqj196 ",
            content4: "x1c4vz4f xs83m0k xdl72j9 x1g77sc7 x78zum5 xozqiw3 x1oa3qoh x12fk4p8 x2lwn1j xl56j7k x1q0g3np x1cy8zhl xt4ypqs xbmvrgn ",
            content5: "xdod15v xzwifym x6ikm8r x10wlt62 xlyipyv xuxw1ft "
        },
        footerIco: "_ajv6 x1y1aw1k x1sxyh0 xwib8y2 xurb0ha ",
        textarea: "_ak1l "
    },
    na = b()((a, t) => ({
        variaveisWA: Zr,
        isNewModel: !0,
        setIsNewModel: e => {
            a({
                isNewModel: e
            });
            const s = document.querySelector("main");
            s && s.setAttribute("isNewModel", String(t().isNewModel))
        }
    }));
async function rn() {
    const {
        domSelector: a
    } = D.getState(), {
        setIsNewModel: t
    } = na.getState(), e = a.newModel;
    switch (e.model) {
        case "taghtml":
            t(!!document.querySelector(e.parm));
            break;
        case "version":
            const s = await m.Conn("waVersion"),
                o = BigInt(s.replace(/\./g, "")),
                r = BigInt(e.parm.replace(/\./g, ""));
            o >= r ? t(!0) : t(!1);
            break;
        case "all":
            t(!0);
            break
    }
}
const Qr = b()(a => ({
    modalOptions: null,
    options: {},
    childrenRef: null,
    offset: 0,
    auxFunc: {
        mounted: null,
        desmouted: null
    },
    open: (t, e, s, o = 10, r = {
        mounted: null,
        desmouted: null
    }) => a(i => (r.mounted && r.mounted(), i.childrenRef !== null && i.auxFunc.desmouted && i.auxFunc.desmouted(), {
        modalOptions: t,
        options: e,
        childrenRef: s,
        offset: o,
        auxFunc: r
    })),
    close: () => a(t => (t.auxFunc.desmouted && t.auxFunc.desmouted(), {
        modalOptions: null,
        childrenRef: null,
        options: {}
    }))
}));

function nn() {
    const {
        modalOptions: a,
        options: t,
        childrenRef: e,
        offset: s,
        close: o
    } = Qr(), {
        variaveisWA: r
    } = na(), {
        refs: i,
        floatingStyles: n,
        update: c,
        elements: l
    } = ha({
        ...t,
        middleware: [Aa({
            padding: 5
        }), ba({
            padding: 5
        }), Sa({
            apply({
                availableWidth: d,
                availableHeight: u,
                elements: p
            }) {
                Object.assign(p.floating.style, {
                    maxWidth: `${d}px`,
                    maxHeight: `${u}px`
                })
            }
        }), wa(s)]
    });
    return k.useEffect(() => {
        if (a && l.reference && l.floating) return va(l.reference, l.floating, c)
    }, [a, l, c]), k.useEffect(() => {
        const d = u => {
            var v;
            const p = document.querySelector(".iziToast-wrapper"),
                A = document.querySelector('section[data-id="Modal Emoji"]');
            i.floating.current && !i.floating.current.contains(u.target) && !e.contains(u.target) && (!p || !p.contains(u.target)) && !((v = document.querySelector("#pane-side ._21S-L span")) != null && v.contains(u.target)) && !A && o()
        };
        return e && (i.setReference(e), document.addEventListener("click", d)), () => {
            document.removeEventListener("click", d)
        }
    }, [a, e]), a && g.jsx("section", {
        "data-id": "Modal Options",
        children: g.jsx("div", {
            ref: i.setFloating,
            role: "tooltip",
            className: "z-[9999]",
            style: n,
            children: g.jsx("div", {
                className: r.modalOptions.content1 + "!rounded-2xl animate__animated animate__zoomIn",
                style: {
                    position: "initial",
                    maxWidth: "100vw"
                },
                role: "application",
                children: g.jsx("ul", {
                    "data-testid": "attach-menu-popup",
                    className: r.modalOptions.content2,
                    children: g.jsx("div", {
                        className: r.modalOptions.content3,
                        children: a
                    })
                })
            })
        })
    })
}
export {
    kt as $, na as A, D as B, Z as C, I as D, et as E, ne as F, $ as G, Dr as H, rn as I, ee as J, xe as K, Zt as L, To as M, oa as N, uo as O, wo as P, Jo as Q, Go as R, ot as S, Ho as T, $o as U, Vo as V, Rt as W, _t as X, be as Y, Re as Z, Wo as _, bi as a, Pe as a$, Tt as a0, Oo as a1, jo as a2, Do as a3, zo as a4, Po as a5, qo as a6, Io as a7, No as a8, Fo as a9, Ni as aA, zi as aB, _a as aC, ki as aD, Ri as aE, _e as aF, Kt as aG, Yi as aH, Xi as aI, $i as aJ, bo as aK, gi as aL, Ki as aM, Bo as aN, an as aO, fi as aP, yi as aQ, po as aR, ui as aS, Ca as aT, Ci as aU, go as aV, Ge as aW, ke as aX, ge as aY, qe as aZ, he as a_, Eo as aa, Uo as ab, La as ac, Va as ad, Si as ae, hi as af, nn as ag, Ai as ah, Vi as ai, ji as aj, R as ak, qa as al, Ae as am, Fi as an, Bi as ao, Wi as ap, Ao as aq, xt as ar, Ei as as, mo as at, tr as au, ae as av, st as aw, lo as ax, Ui as ay, B as az, q as b, pi as b0, Qt as b1, Oi as b2, qi as b3, Di as b4, T as b5, Nr as b6, co as b7, Li as b8, Lo as b9, Ji as ba, Gi as bb, Pi as bc, Ii as bd, wi as be, Ti as bf, _i as bg, Y as c, W as d, li as e, di as f, xi as g, Qi as h, vi as i, en as j, mi as k, sn as l, on as m, Hi as n, C as o, X as p, Qr as q, ce as r, le as s, ho as t, x as u, Zi as v, Mi as w, tn as x, Jt as y, H as z
};