import {
    S as J,
    C as Ae,
    U as le,
    W as P,
    G as ee,
    R as K,
    g as f,
    r as F,
    _ as ce,
    j as g,
    I as j,
    E as Q,
    O as Zt,
    h as ea,
    P as x,
    f as Oe,
    N as Je,
    i as vt,
    k as ta,
    w as aa
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf10.js";
import {
    a as be,
    A as sa
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf6.js";
import {
    a as k
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf4.js";
import {
    X as Ft,
    G as U
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf8.js";
import {
    c as b
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf7.js";
import {
    V as Ie,
    W as m
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf18.js";
import {
    g as oa,
    r as ia
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf.js";
import {
    d as Lt,
    l as na,
    u as ra,
    b as ca,
    f as da,
    s as la,
    c as ua,
    o as pa
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf9.js";
import {
    b as y,
    u as I
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf19.js";
import {
    G as ma
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf2.js";
import {
    O as fa
} from "./v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf3.js";
const re = 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: ""
        }
    },
    setLabel: e => {
        a({
            label: e
        });
        const s = document.querySelector("main");
        s && s.setAttribute("plugin-ico-color", String(t().label.cor_primaria))
    }
}));
async function Ki() {
    try {
        const t = await (await fetch(chrome.runtime.getURL("/label/config/utils.json"))).json();
        try {
            const s = (await be.get(`${Ie.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
            };
            re.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: ""
                }
            };
            re.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 Ee = {
        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
        }
    },
    Ue = b()(a => ({
        userFreeLimity: Ee,
        setUserFreeLimity: t => {
            J("wpp-functions", "functions", [Ae.encryptData(t)]), a(e => ({
                ...e,
                userFreeLimity: t
            }))
        },
        setUserFreeLimityPluginPage: () => a(t => ({
            ...t,
            plugin_page: !0
        }))
    })),
    Nt = a => {
        var s;
        if (M.getState().user.estado) return !1;
        const t = Ue.getState().userFreeLimity;
        if (le.subtrData(t.date.old) > 1) {
            const o = {
                ...Ee
            };
            for (const i in o)
                if (Object.prototype.hasOwnProperty.call(o, i)) {
                    const n = o[i];
                    n.quant = 0, n.tag === "date" && (n.old = Date.now()), n.tag === a && (n.quant = 1)
                } return Ue.getState().setUserFreeLimity(o), !1
        }
        if (t[a] || (t[a] = Ee[a]), t[a].quant === ((s = t[a]) == null ? void 0 : s.max)) return !0;
        const e = {
            ...t
        };
        return e[a].quant++, Ue.getState().setUserFreeLimity(t), !1
    },
    ue = async (a, t = !1) => {
        let e = !1;
        return y.getState().plugin_page ? M.getState().user.estado ? e = !1 : e = await P("exe-CheckUserFreeLock", a) : e = Nt(a), e && !t && Z.getState().openRendertype("user_free"), e
    }, Qi = async () => {
        let a = Ee;
        const t = await ee("wpp-functions", "functions");
        t[0] && t[0][0] && (a = Ae.decryptData(t[0][0])), Ue.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(Nt(a.dados)),
        id: a.id
    })
});
window.addEventListener("message", a => {
    if (a.data.type === "Ev" && a.data.action === "chat.active_chat") {
        const t = JSON.parse(a.data.model);
        t && (t.id = {
            server: "@" + t.id.split("@")[1],
            user: t.id.split("@")[0],
            _serialized: t.id
        }, R.setState({
            activeChat: t
        }))
    }
});
const R = b()(() => ({
    activeChat: null
}));
chrome.runtime.onMessage.addListener(a => {
    switch (a.action) {
        case "updateActivePerfil":
            const {
                activePerfil: t, perfil: e
            } = O.getState(), {
                updatePerfil: s
            } = a.dados, o = e.filter(n => n.userID !== s.userID), i = [s, ...o];
            t.userID === s.userID ? O.setState({
                activePerfil: s,
                perfil: i
            }) : O.setState({
                perfil: i
            });
            break;
        case "BackupPerfil":
            (async () => {
                const n = await K("perfil");
                O.setState({
                    perfil: n
                })
            })();
            break
    }
});
const At = {
    cargo: "",
    cidade: "",
    estado: "",
    dataNascimento: "",
    email: "",
    empresa: "",
    entrada: "",
    observacoes: "",
    origemLead: "",
    produtos: [],
    saida: "",
    sexo: "",
    valNegocio: [],
    idioma: "",
    userID: ""
};
let We = null;
const O = b()((a, t) => ({
    perfil: [],
    activePerfil: At,
    activeUser: {
        picture: "",
        labels: []
    },
    setActiveUser: async ({
        id: e,
        labels: s
    }) => {
        const o = await m.Contact("getProfilePictureUrl", e._serialized),
            n = (await m.Labels("getAllLabels")).filter(r => s.includes(r.id));
        a({
            activeUser: {
                picture: o,
                labels: n
            }
        })
    },
    setActivePerfil: e => a(s => {
        e = e.replace("@c.us", "").replace("@g.us", "");
        const o = s.perfil.find(i => i.userID === e);
        return o ? {
            activePerfil: o
        } : {
            activePerfil: {
                ...At,
                userID: e
            }
        }
    }),
    updateActivePerfil: (e, s) => {
        const {
            activePerfil: o
        } = O.getState(), i = {
            ...o,
            [e]: s
        };
        a({
            activePerfil: i
        }), We && clearTimeout(We), We = setTimeout(async () => {
            if (await ue("perfilDoContato") === !0) return;
            const {
                perfil: n
            } = O.getState(), r = {
                ...o,
                [e]: s
            }, c = n.filter(d => d.userID !== o.userID), l = [r, ...c];
            f("perfil", l), y.getState().plugin_page ? P("updateActivePerfil", {
                updatePerfil: r
            }, !1) : chrome.runtime.sendMessage({
                action: "updateActivePerfil",
                dados: {
                    updatePerfil: r
                }
            }), a({
                perfil: l
            })
        }, 1e3)
    },
    getValorNegocio: () => {
        const {
            activePerfil: e
        } = O.getState(), {
            idioma: s
        } = I();
        let o = 0;
        if (e.valNegocio)
            for (let c of e.valNegocio) o += parseFloat(c.valor);
        const i = {
                pt: {
                    locale: "pt-BR",
                    currency: "BRL"
                },
                en: {
                    locale: "en-US",
                    currency: "USD"
                },
                es: {
                    locale: "es-ES",
                    currency: "EUR"
                }
            },
            {
                locale: n,
                currency: r
            } = i[s] || i.pt;
        return o.toLocaleString(n, {
            style: "currency",
            currency: r
        })
    },
    getPerfilContato: e => {
        const {
            perfil: s
        } = t();
        e = e.replace("@g.us", "").replace("@c.us", "");
        const o = s.find(n => n.userID === e);
        if (!o) return null;
        let i = 0;
        if (o.valNegocio)
            for (let n of o.valNegocio) i += parseFloat(n.valor);
        return {
            ...o,
            valorNegocioTotal: i.toLocaleString("pt-BR", {
                style: "currency",
                currency: "BRL"
            })
        }
    }
}));
R.subscribe(a => {
    a.activeChat && a.activeChat.id.user && (O.getState().setActiveUser(a.activeChat), O.getState().setActivePerfil(a.activeChat.id.user))
});
const ga = async a => {
    O.setState({
        perfil: a
    }), await f("perfil", a), chrome.runtime.sendMessage({
        action: "BackupPerfil"
    })
}, Yi = a => {
    const t = [...O.getState().perfil],
        s = ((o, i) => o.concat(i).reduce((c, l) => (c.find(u => u.userID === l.userID) || c.push(l), c), []))(t, a);
    ga(s)
};
(async () => {
    const a = await K("perfil");
    O.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 It = [{
        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
    }],
    Ke = {
        id: "metaAds",
        active: !1,
        url: "",
        param: It,
        sent: []
    },
    Xi = ["metaAds", "serviceCompleted", "respostaRapida", "autoAtendimento", "followUp", "agendamento", "crm", "labels", "messages"],
    W = b()(a => ({
        webhook: [],
        activeHook: Ke,
        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: It,
                    sent: []
                }
            }
        }),
        setDadosWebHook: (t, e, s) => a(o => {
            let i = null,
                n = [];
            return o.webhook.find(c => c.id === t) ? n = o.webhook.map(c => c.id === t ? (i = {
                ...c,
                [e]: s
            }, i) : c) : (i = {
                ...o.activeHook,
                [e]: s
            }, n = [i, ...o.webhook]), f("webhook", n), {
                activeHook: i,
                webhook: n
            }
        }),
        setDadosParam: (t, e) => a(s => {
            const o = s.activeHook.param.map(c => c.id === e ? {
                id: c.id,
                active: !c.active
            } : c);
            let i = {
                    ...s.activeHook,
                    param: o
                },
                n = [];
            return s.webhook.find(c => c.id === t) ? n = s.webhook.map(c => c.id === t ? i : c) : n = [i, ...s.webhook], f("webhook", n), {
                activeHook: i,
                webhook: n
            }
        }),
        dispartWebhook: async (t, e, s, o) => {
            const {
                timeout: i
            } = W.getState(), {
                getPerfilContato: n
            } = O.getState(), r = M.getState().user.login;
            if (y.getState().plugin_page) {
                ha(t, e, s, o);
                return
            }
            const c = W.getState().webhook.find(S => S.id === e);
            if (!c || !c.active) return;
            if (i && clearTimeout(i), await ue("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 = n(t), l.user = r, 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 = le.dayDate(),
                v = le.timeDate(),
                h = {
                    id: o || F(),
                    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 E = S.webhook.map(w => {
                    if (w.id === e) {
                        const L = w.sent.map(ae => ae.id === o ? h : ae);
                        return {
                            ...w,
                            sent: L
                        }
                    }
                    return w
                });
                return f("webhook", E), {
                    activeHook: E.find(w => w.id === e),
                    webhook: E
                }
            } : S => {
                const E = S.webhook.map(w => {
                    if (w.id === e) {
                        const L = w.sent;
                        return L.length >= 30 && L.pop(), {
                            ...w,
                            sent: [h, ...L]
                        }
                    }
                    return w
                });
                return f("webhook", E), {
                    activeHook: E.find(w => w.id === e),
                    webhook: E
                }
            })
        }
    })),
    Zi = async () => {
        let t = (await K("webhook") || []).map(s => s.param.find(i => i.id === "user") ? s : {
            ...s,
            param: [...s.param, {
                id: "user",
                active: !1
            }]
        });
        const e = t.find(s => s.id === "metaAds") || Ke;
        W.setState({
            activeHook: e,
            webhook: t
        })
    }, en = a => {
        f("webhook", a);
        const t = a.find(e => e.id === "metaAds") || Ke;
        W.setState({
            activeHook: t,
            webhook: a
        })
    }, ha = (a, t, e, s) => {
        P("dispartWebhook", {
            userID: a,
            webhookID: t,
            eventDetails: e,
            sendID: s
        })
    }, bt = () => {
        var a = new KeyboardEvent("keydown", {
            code: "Escape",
            which: 27,
            bubbles: !0,
            composed: !0,
            keyCode: 27,
            cancelable: !0,
            key: "Escape"
        });
        document.dispatchEvent(a)
    }, va = {
        trasferirAtendimento: {
            text: "",
            active: !1
        },
        finalizarAtendimento: {
            text: "",
            active: !1,
            arquivar: !1
        }
    }, fe = b()(a => ({
        atendimento: va,
        activeTrasferencia: null,
        trasferencias: [],
        renderTrasferencia: t => a(e => {
            const {
                modal: s
            } = Z.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
            } = fe.getState(), {
                plugin_page: s
            } = y.getState();
            if (bt(), s ? P("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
            } = fe.getState(), {
                plugin_page: o
            } = y.getState();
            if (bt(), o ? P("serviceCompleted", t) : W.getState().dispartWebhook(t, "serviceCompleted", {
                    type: "Trasferido"
                }), s.trasferirAtendimento.active) {
                const i = `*_Atendimento Transferido para ${e}_*: 
 ${s.trasferirAtendimento.text}`;
                m.Chat("sendTxt", {
                    id: t,
                    msg: i
                })
            }
        }
    }));
(async () => {
    const a = await K("atendimento") || void 0;
    a && fe.setState({
        atendimento: a
    })
})();
fe.subscribe(a => {
    a.activeTrasferencia && Z.getState().openRendertype("receive_atendimento", !1)
});
const tn = a => {
        fe.setState({
            atendimento: a
        }), f("atendimento", a)
    },
    Aa = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf48.js")), []));

function ba() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Aa, {})
    })
}
const Sa = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf49.js")), []));

function wa() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Sa, {})
    })
}
const ya = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf50.js")), []));

function Ca() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(ya, {})
    })
}
const xa = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf51.js")), []));

function Ma() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(xa, {})
    })
}
const Ta = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf52.js")), []));

function ka() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Ta, {})
    })
}
const _a = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf53.js")), []));

function Ra() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(_a, {})
    })
}
const Ua = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf54.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_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf55.js")), []));

function La() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Fa, {})
    })
}
const Z = 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 i;
        switch (t) {
            case "Active_IA":
                i = g.jsx(wa, {});
                break;
            case "user_free":
                i = g.jsx(Ma, {});
                break;
            case "access_duplicate":
                i = g.jsx(Ca, {});
                break;
            case "receive_atendimento":
                i = g.jsx(Ea, {});
                break;
            case "Modelo_Selecao":
                i = g.jsx(Ra, {});
                break;
            case "ModalLeads":
                i = g.jsx(La, {});
                break;
            case "assinatura":
                i = g.jsx(ba, {});
                break;
            case "login":
                i = g.jsx(ka, {});
                break
        }
        Z.getState().open(i, e, s, o)
    }
}));

function an() {
    const {
        modal: a,
        btnClose: t,
        close: e,
        disableClose: s
    } = Z(), o = k.useRef(null), i = k.useRef(null);
    return k.useEffect(() => {
        const n = r => {
            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 && !i.current.contains(r.target) && (!c || !c.contains(r.target)) && !l && !d && !u && e()
        };
        return a && document.addEventListener("mousedown", n), () => {
            document.removeEventListener("mousedown", n)
        }
    }, [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: i,
                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(Ft, {
                        className: "w-full h-full text-[var(--primary-strong)]"
                    })
                }), g.jsx("div", {
                    className: "w-full h-full",
                    children: a
                })]
            })
        })
    })
}
Z.subscribe(a => {
    const {
        trasferencias: t,
        alterRenderTrasferencia: e
    } = fe.getState();
    t.length !== 0 && !a.modal && e()
});
async function Na(a) {
    try {
        return (await be.post(`${Ie.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 Ia = () => {
        const a = new Date,
            t = a.toLocaleString(),
            e = a.getTimezoneOffset(),
            s = (() => {
                const i = -e,
                    n = String(Math.floor(Math.abs(i) / 60)).padStart(2, "0"),
                    r = String(Math.abs(i) % 60).padStart(2, "0");
                return `${i>=0?"+":"-"}${n}:${r}`
            })(),
            o = Intl.DateTimeFormat().resolvedOptions().timeZone;
        return {
            localDateTime: t,
            timezoneOffset: s,
            timezoneName: o
        }
    },
    qa = async a => {
        let t = "GRATUITO";
        a.estado && (t = "ASSINANTE");
        const {
            user: e
        } = await m.Conn("getMyDeviceId"), s = await K("modalLead");
        return {
            state_user: t,
            user: a,
            cadastro_lead: s,
            phone: e,
            navegador: navigator.userAgent,
            horario: Ia()
        }
    }, qt = async a => {
        const t = re.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 n = new Date(s).getTime();
                if ((e - n) / (1e3 * 60 * 60) < o) return
            }
            const i = await qa(a);
            be.post(t.webhook_login_clients, i, {
                headers: {
                    "Content-Type": "application/json"
                }
            }), localStorage.setItem("8fd5ad24df1e1b800d670e563b1b83591980060a==", new Date().toISOString())
        }
    }, Fe = {
        realizou_login: !1,
        estado: !1,
        login: "",
        senha: "",
        token: ""
    }, M = b()(a => ({
        user: Fe,
        setUser: t => {
            const e = Ae.encryptData(t);
            J("wpp-client", "client", [e]), chrome.runtime.sendMessage({
                action: "post-user",
                user: t
            }), a({
                user: t
            })
        },
        setRemoveUser: () => {
            const t = {
                ...Fe,
                realizou_login: !0
            };
            J("wpp-client", "client", [Ae.encryptData(t)]), chrome.runtime.sendMessage({
                action: "post-user",
                user: t
            }), a(e => ({
                ...e,
                user: t
            }))
        },
        setUserPluginPage: t => a({
            user: t
        })
    })), Pt = async a => {
        const {
            language: t
        } = I.getState(), {
            label: e
        } = re.getState(), {
            setUser: s
        } = M.getState(), {
            openRendertype: o
        } = Z.getState();
        if (!a.estado) {
            a.realizou_login && o("login");
            return
        }
        const i = await Na({
            email: a.login,
            token: a.token,
            chromeStoreID: e.chromeStoreID
        });
        i.success ? s(a) : (s(Fe), i.msg_id === "login_duplicado" ? o("access_duplicate") : i.plugin_origem ? (j({
            type: "Error",
            message: t[i.msg_id] + i.plugin_origem,
            position: "top-right"
        }), o("login")) : (j({
            type: "Error",
            message: t[i.msg_id],
            position: "top-right"
        }), o("login")))
    }, sn = async () => {
        let a = Fe;
        const t = await ee("wpp-client", "client");
        t[0] && t[0][0] && (a = Ae.decryptData(t[0][0])), Pt(a), qt(a)
    };
chrome.runtime.onMessage.addListener(async a => {
    a.action === "get-user" && chrome.runtime.sendMessage({
        action: a.action,
        response: JSON.stringify(M.getState().user),
        id: a.id
    }), a.action === "post-user" && y.getState().plugin_page && M.getState().setUserPluginPage(a.user), a.action === "license_update" && (qt(M.getState().user), M.getState().user.estado && Pt(M.getState().user))
});
const Pa = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_9_8cb79d4f-81e0-49c1-b597-7f2344477fbf56.js")), []));

function St({
    notificacao: a
}) {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Pa, {
            notificacao: a
        })
    })
}
const ie = 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
            } = re.getState();
            if (e.chromeStoreID.length === 0) return;
            const o = (await be.get(`${Ie.backend}api/notificacao/get?wl_id=${e.chromeStoreID}`, {
                headers: {
                    "Content-Type": "application/json",
                    accept: "application/json"
                }
            })).data.notificacoes;
            a({
                notificacoes_modal: o.filter(i => i.viewer === "MODAL"),
                notificacoes_box: o.filter(i => i.viewer === "NOTIFY"),
                notificacoes_inbox: o.filter(i => i.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
        } = M.getState(), i = e.notificacoes_modal.filter(n => n.client === "PREMIUM" && s.estado || n.client === "FREE" && s.estado === !1 || n.client === "ALL").filter(n => !e.notificacoes_modalIDVisible.includes(n.id));
        return {
            notificacoes_modal: i,
            modal: i.length !== 0 ? g.jsx(St, {
                notificacao: i[0]
            }) : null
        }
    }),
    closeNotificacoes_modal: () => {
        a({
            modal: null
        });
        const {
            notificacoes_modal: e
        } = t(), s = [...e];
        s.shift(), ie.getState().setNotificacoes_ModalVisible(e[0].id), setTimeout(() => {
            a({
                notificacoes_modal: s,
                modal: s.length !== 0 ? g.jsx(St, {
                    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
        } = M.getState();
        return ie.getState().notificacoes_box.filter(i => i.client === "PREMIUM" && e.estado || i.client === "FREE" && e.estado === !1 || i.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 => ie.getState().notificacoes_boxIDVisible.includes(e),
    renderNotificacoes_inbox: () => a(e => {
        const {
            user: s
        } = M.getState(), i = e.notificacoes_inbox.filter(n => n.client === "PREMIUM" && s.estado || n.client === "FREE" && s.estado === !1 || n.client === "ALL").filter(n => !e.notificacoes_inboxIDVisible.includes(n.id));
        return {
            notificacoes_inbox: i,
            active_inbox_notify: i.length !== 0 ? i[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 on() {
    const {
        modal: a
    } = ie();
    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 !pr-3",
                children: [g.jsx("span", {
                    className: "absolute w-5 h-5 top-3 right-3 pulse !cursor-pointer",
                    onClick: () => ie.getState().closeNotificacoes_modal(),
                    children: g.jsx(Ft, {
                        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" && ie.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 && ie.setState({
        notificacoes_modalIDVisible: a
    }), t && t.length !== 0 && ie.setState({
        notificacoes_boxIDVisible: t
    }), e && e.length !== 0 && ie.setState({
        notificacoes_inboxIDVisible: e
    })
})();
const za = async (a, t, e, s, o = !1) => {
    const n = C.getState().crm.map(r => r.id === a ? {
        ...r,
        name: t,
        desc: e,
        hexColor: s
    } : r);
    Q({
        stopPropag: o,
        action: "editCrm",
        waitForResponse: !1,
        data: {
            crmID: a,
            name: t,
            desc: e,
            hexColor: s
        }
    }), !o && f("crm", n), C.setState({
        crm: n
    })
}, Da = async (a, t = !1) => {
    const s = C.getState().crm.filter(o => o.id !== a);
    Q({
        stopPropag: t,
        action: "removeCrm",
        waitForResponse: !1,
        data: a
    }), !t && f("crm", s), C.setState({
        crm: s
    })
}, ja = async ({
    id: a = F(),
    ativeCRM: t,
    name: e,
    hexColor: s
}, o = !1) => {
    const n = C.getState().crm.map(r => {
        if (r.id === t) {
            const c = {
                id: a,
                name: e,
                hexColor: s,
                chats: []
            };
            return {
                ...r,
                list: [...r.list, c]
            }
        }
        return r
    });
    Q({
        stopPropag: o,
        action: "addNewTabCRM",
        waitForResponse: !1,
        data: {
            id: a,
            ativeCRM: t,
            name: e,
            hexColor: s
        }
    }), !o && f("crm", n), C.setState({
        crm: n
    })
}, Oa = async (a, t = !1) => {
    const s = [...C.getState().crm, ...a].reduce((o, i) => o.find(r => r.id === i.id) ? o : o.concat([i]), []);
    Q({
        stopPropag: t,
        action: "setCrm",
        waitForResponse: !1,
        data: a
    }), !t && f("crm", s), C.setState({
        crm: s
    })
}, Wa = async (a, t, e, s = !1) => {
    const i = C.getState().crm.map(n => n.id === a ? {
        ...n,
        list: n.list.map(r => r.id === t ? {
            ...r,
            name: e
        } : r)
    } : n);
    Q({
        stopPropag: s,
        action: "editTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            abaID: t,
            name: e
        }
    }), !s && f("crm", i), C.setState({
        crm: i
    })
}, Ba = async (a, t, e, s = !1) => {
    const i = C.getState().crm.map(n => n.id === a ? {
        ...n,
        list: n.list.map(r => r.id === t ? {
            ...r,
            chats: r.chats.filter(c => c.id !== e)
        } : r)
    } : n);
    Q({
        stopPropag: s,
        action: "removeChatTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            abaID: t,
            chatID: e
        }
    }), !s && f("crm", i), C.setState({
        crm: i
    })
}, Va = async (a, t, e, s = !1) => {
    const i = C.getState().crm.map(n => n.id === a ? {
        ...n,
        list: n.list.map(r => r.id === t ? {
            ...r,
            hexColor: e
        } : r)
    } : n);
    Q({
        stopPropag: s,
        action: "changeColorTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            abaID: t,
            hexColor: e
        }
    }), !s && f("crm", i), C.setState({
        crm: i
    })
}, zt = async (a, t, e, s, o = !1) => {
    const i = C.getState().crm;
    a = a.replace("@c.us", "").replace("@g.us", "");
    let n;
    t ? n = i.map(r => ({
        ...r,
        list: r.list.map(c => ({
            ...c,
            chats: c.chats.filter(l => l.id !== a)
        }))
    })) : n = i.map(r => r.id === e ? {
        ...r,
        list: r.list.map(c => c.id === s ? {
            ...c,
            chats: c.chats.filter(l => l.id !== a)
        } : c)
    } : r), Q({
        stopPropag: o,
        action: "setRemoveUserCRM",
        waitForResponse: !1,
        data: {
            userID: a,
            isAll: t,
            crmID: e,
            abaID: s
        }
    }), !o && f("crm", n), C.setState({
        crm: n
    })
}, Dt = a => {
    const t = C.getState().crm;
    let e = 0;
    return t.map(s => {
        s.list.map(o => {
            o.chats.map(i => {
                i.id === a && e++
            })
        })
    }), e
}, jt = async (a, t, e, s, o = !1) => {
    const i = C.getState().crm;
    a = a.replace("@c.us", "").replace("@g.us", "");
    let n = i.map(r => r.id === t ? {
        ...r,
        list: r.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
        })
    } : r);
    Q({
        stopPropag: o,
        action: "setNewUserCRM",
        waitForResponse: !1,
        data: {
            userID: a,
            crmID: t,
            abaID: e,
            insertPosition: s
        }
    }), !o && f("crm", n), C.setState({
        crm: n
    })
}, $a = (a, t, e, s, o, i = !1) => {
    const r = C.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
        })
    }));
    Q({
        stopPropag: i,
        action: "moveUserTabCRM",
        waitForResponse: !1,
        data: {
            chat: a,
            source: t,
            destination: e,
            insertPosition: s,
            duplicate: o
        }
    }), !i && f("crm", r), C.setState({
        crm: r
    })
}, Ga = (a, t, e, s, o = !1) => {
    const n = C.getState().crm.map(r => r.id === a ? {
        ...r,
        list: r.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
        })
    } : r);
    Q({
        stopPropag: o,
        action: "orderUserInTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            columnID: t,
            indexHome: e,
            indexDestination: s
        }
    }), !o && f("crm", n), C.setState({
        crm: n
    })
}, Ha = (a, t, e, s = !1) => {
    const i = C.getState().crm.map(n => {
        if (n.id === a) {
            const r = [...n.list],
                [c] = r.splice(t, 1);
            return r.splice(e, 0, c), {
                ...n,
                list: r
            }
        }
        return n
    });
    Q({
        stopPropag: s,
        action: "sortUserTabsCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            indexHome: t,
            indexDestination: e
        }
    }), !s && f("crm", i), C.setState({
        crm: i
    })
}, Ja = (a, t, e = !1) => {
    const o = C.getState().crm.map(i => i.id === a ? {
        ...i,
        list: i.list.filter(n => n.id !== t)
    } : i);
    Q({
        stopPropag: e,
        action: "deleteTabCRM",
        waitForResponse: !1,
        data: {
            crmID: a,
            abaID: t
        }
    }), !e && f("crm", o), C.setState({
        crm: o
    })
}, Ka = Zt({
    setCrm: a => {
        Oa(a.data, !0)
    },
    editCrm: a => {
        const {
            crmID: t,
            name: e,
            desc: s,
            hexColor: o
        } = a.data;
        za(t, e, s, o, !0)
    },
    removeCrm: a => {
        Da(a.data, !0)
    },
    addNewTabCRM: a => {
        ja(a.data, !0)
    },
    editTabCRM: a => {
        const {
            crmID: t,
            abaID: e,
            name: s
        } = a.data;
        Wa(t, e, s, !0)
    },
    removeChatTabCRM: a => {
        const {
            crmID: t,
            abaID: e,
            chatID: s
        } = a.data;
        Ba(t, e, s, !0)
    },
    changeColorTabCRM: a => {
        const {
            crmID: t,
            abaID: e,
            hexColor: s
        } = a.data;
        Va(t, e, s, !0)
    },
    setRemoveUserCRM: a => {
        const {
            userID: t,
            isAll: e,
            crmID: s,
            abaID: o
        } = a.data;
        zt(t, e, s, o, !0)
    },
    setNewUserCRM: a => {
        const {
            userID: t,
            crmID: e,
            abaID: s,
            insertPosition: o
        } = a.data;
        jt(t, e, s, o, !0)
    },
    moveUserTabCRM: a => {
        const {
            chat: t,
            source: e,
            destination: s,
            insertPosition: o,
            duplicate: i
        } = a.data;
        $a(t, e, s, o, i, !0)
    },
    orderUserInTabCRM: a => {
        const {
            crmID: t,
            columnID: e,
            indexHome: s,
            indexDestination: o
        } = a.data;
        Ga(t, e, s, o, !0)
    },
    sortUserTabsCRM: a => {
        const {
            crmID: t,
            indexHome: e,
            indexDestination: s
        } = a.data;
        Ha(t, e, s, !0)
    },
    deleteTabCRM: a => {
        const {
            crmID: t,
            abaID: e
        } = a.data;
        Ja(t, e, !0)
    }
});
chrome.runtime.onMessage.addListener(Ka);
const C = b()(() => ({
        crm: []
    })),
    Qa = "1.7",
    Ya = "",
    Xa = "true",
    Za = "true",
    es = {
        timer: "60000",
        enable_two_send: !1
    },
    ts = {
        model: "taghtml",
        parm: "body.color-refresh"
    },
    as = {
        model: "querySelector",
        selector: ["#app"]
    },
    ss = {
        model: "querySelector",
        selector: ["body > div"]
    },
    os = {
        model: "Element",
        selector: "#pane-side"
    },
    is = {
        model: "querySelector",
        selector: ["#app > div > div ._aigs"]
    },
    ns = {
        model: "Element",
        selector: "two"
    },
    rs = {
        model: "querySelector",
        selector: [".two._aigs > div:nth-child(5)"]
    },
    cs = {
        model: "Element",
        selector: "x10l6tqk"
    },
    ds = {
        model: "querySelector",
        selector: [".lexical-rich-text-input > div"]
    },
    ls = {
        model: "querySelector",
        selector: ["[data-icon='search']"]
    },
    us = {
        model: "querySelector",
        selector: ["header > div > div > div > div > span > div > div:nth-child(1)", "header > div._ak0w"]
    },
    ps = {
        model: "querySelector",
        selector: ["header > header > div > span > div"]
    },
    ms = {
        model: "querySelector",
        selector: ["#side > div._ak9t > div"]
    },
    fs = {
        model: "querySelector",
        selector: ["#main > header > div.xeuugli > div > div"]
    },
    gs = {
        model: "querySelector",
        selector: ["#main ._amm9", "#main .x1n2onr6.x1vjfegm.x1cqoux5.x14yy4lh"]
    },
    hs = {
        model: "querySelector",
        selector: ["#main > header :nth-child(3) div"]
    },
    vs = {
        model: "querySelector",
        selector: ["footer ._ak1m"]
    },
    As = {
        model: "querySelector",
        selector: ["footer > div"]
    },
    bs = {
        model: "querySelector",
        selector: ["footer div[contenteditable=true]"]
    },
    Ss = {
        model: "querySelector",
        selector: ["footer > div.copyable-area > div"]
    },
    ws = {
        model: "querySelector",
        selector: ["#main > div.x1n2onr6.x1vjfegm.x1cqoux5.x14yy4lh"]
    },
    ys = {
        model: "querySelector",
        selector: ["._1VZX7 ._3Uu1_, ._ak1r > div"]
    },
    Cs = {
        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"]
    },
    xs = {
        model: "querySelector",
        selector: ["#main > footer > div.copyable-area > div > span > div > div._ak1m > div > button[tabindex='-1']"]
    },
    Ms = {
        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"]
    },
    Ts = {
        model: "querySelector",
        selector: ["#main > div.x1n2onr6.x1vjfegm.x1cqoux5.x14yy4lh > div > div.x10l6tqk.x13vifvy"]
    },
    ks = {
        model: "querySelectorAll",
        selector: ["#main div > div[data-id]"]
    },
    _s = {
        model: "querySelector",
        selector: ["#main > footer"]
    },
    Rs = {
        model: "querySelector",
        selector: ["#side div[tabindex='-1']"]
    },
    Us = {
        model: "querySelector",
        selector: ["#side > div:nth-child(2)"]
    },
    Es = {
        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"]
    },
    Fs = {
        model: "querySelector",
        selector: ["#pane-side > div > div > div"]
    },
    Ls = {
        model: "querySelectorAll",
        selector: ["#pane-side > div > div > div > div  div[aria-selected]", "#pane-side > div > div > div div[role='button'] > div"]
    },
    Ns = {
        model: "Element",
        selector: "div._ak8l > div._ak8j > div._ak8i"
    },
    Is = {
        model: "Element",
        selector: "x10l6tqk xh8yej3 x1g42fcv"
    },
    qs = {
        model: "Element",
        selector: "__reactFiber"
    },
    Ps = {
        model: "querySelector",
        selector: ["#side div._ai04 > button"]
    },
    zs = {
        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'
        }
    },
    Ds = {
        model: "querySelector",
        selector: ["div.two._aigs > div._aigw"]
    },
    js = {
        model: "querySelector",
        selector: ["#main > span:nth-child(8)", "#main > :last-child"]
    },
    Os = {
        model: "querySelector",
        selector: ["#main > span:nth-child(7)", "#main > span:nth-child(8)", "#main > span:nth-child(9)"]
    },
    Ws = {
        model: "querySelector",
        selector: ["#app > div > div > span:nth-child(4)", "#app > div > span:nth-child(4)"]
    },
    Bs = {
        model: "querySelector",
        selector: ["#app > div > div.x78zum5.xdt5ytf.x5yr21d > div > header > div > div:nth-child(2) > div", "header > div > div:nth-child(2) > div"]
    },
    Vs = {
        model: "querySelector",
        selector: ["#main header"]
    },
    $s = {
        model: "querySelector",
        selector: ["#main > footer > div > div > span > div > div._ak1r > div"]
    },
    Gs = {
        model: "querySelector",
        selector: ["#side"]
    },
    Hs = {
        model: "listElement",
        list: {
            div_filters: "_akap _akan _arj9"
        }
    },
    Js = {
        model: "querySelectorAll",
        selector: ["#side > div:nth-of-type(2) button"]
    },
    Ks = {
        version: Qa,
        update_path: Ya,
        update_path_active: Xa,
        disabeldOldMenu: Za,
        wpp_mensagens: es,
        newModel: ts,
        app: as,
        afiliadoMain: ss,
        paneSide: os,
        waPage: is,
        two: ns,
        menuLateral: rs,
        closeChat: cs,
        chatListInput: ds,
        searchInput: ls,
        downAba: us,
        chatListHeader: ps,
        searchCamp: ms,
        chatName: fs,
        menuVertical: gs,
        menuHorizontal: hs,
        menuFooter: vs,
        respostaRapida: As,
        footerTextArea: bs,
        mainAudio: Ss,
        assChat: ws,
        assInput: ys,
        assBtn: Cs,
        assEmoji: xs,
        assCitacao: Ms,
        listMensages: Ts,
        allMensages: ks,
        assistenteChat: _s,
        trasferidos: Rs,
        notification: Us,
        quotedMsg: Es,
        listChats: Fs,
        listChatsUsers: Ls,
        listChatAtendimento: Ns,
        insertAtendente: Is,
        reactFiber: qs,
        updateChatList: Ps,
        useTradutor: zs,
        chatList: Ds,
        observerFooter: js,
        observerFooterNewModel: Os,
        whatsModal: Ws,
        menu_whats: Bs,
        actionMonitor: Vs,
        footerIconsLeft: $s,
        side: Gs,
        chatFiltersContainer: Hs,
        chatFilters: Js
    },
    V = b()((a, t) => ({
        domSelector: Ks,
        getDomSelector: e => {
            const {
                domSelector: s
            } = t();
            return s[e]
        },
        getSeletor: (e, s = o => null) => {
            const {
                getDomSelector: o
            } = t(), i = o(e);
            let n = null;
            if (!i) return null;
            for (let r of i.selector) {
                let c = null;
                if (i.model === "querySelector" ? c = document.querySelector(r) : i.model === "querySelectorAll" && (c = document.querySelectorAll(r)), c) {
                    n = c, s(c);
                    break
                }
            }
            return n || console.warn("Tag error: ", i.selector.toString()), n
        },
        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
        } = V.getState();
        t.version !== a.dados.version && window.location.reload()
    }
});
const Qs = {
        crm: !0,
        quick_replies: !0,
        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
    },
    Ys = {
        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: !1,
        google_funcs: !1
    },
    Ot = () => {
        const {
            label: a
        } = re.getState();
        return a.chromeStoreID == "gjlfpggiddcminhebiejofeglfjmleli" ? Ys : Qs
    },
    Wt = 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: Ot(),
        setActiveMenu: t => a(e => {
            const s = {
                ...e.activeMenu,
                [t]: !e.activeMenu[t]
            };
            return J("usePluginMenu", "pluginMenu", [s]), {
                activeMenu: s
            }
        }),
        tema: "default",
        setTema: t => a(() => {
            J("ThemeMenu", "activeTheme", [t]);
            const e = document.querySelector("main");
            return e && e.setAttribute("theme-active", String(t)), {
                tema: t
            }
        }),
        chatsIA: !1,
        setChatsIA: t => a(() => (J("chatsIA", "state", [t]), {
            chatsIA: t
        }))
    })),
    nn = async () => {
        let a = !0;
        const t = localStorage.getItem("active-view-menu");
        t && t == "false" && (a = !1);
        let e = Ot();
        const s = await ee("usePluginMenu", "pluginMenu");
        s && s[0] && s[0][0] && (e = s[0][0]);
        let o = "default";
        const i = await ee("ThemeMenu", "activeTheme");
        i && i[0] && i[0][0] && (o = i[0][0]);
        let n = !0;
        const r = await ee("chatsIA", "state");
        r && r[0] && typeof r[0][0] == "boolean" && (n = r[0][0]), Wt.setState({
            activeView: a,
            activeMenu: e,
            tema: o,
            chatsIA: n
        })
    }, rn = () => {
        const {
            setActiveView: a,
            setActiveHeader: t
        } = Wt.getState();
        V.getState().getSeletor("whatsModal", e => {
            new MutationObserver(o => {
                for (const i of o) i.type === "childList" && (i.addedNodes.length > 0 && (a(!1), t(!1)), i.removedNodes.length > 0 && (a(!0), t(!0)))
            }).observe(e, {
                childList: !0
            })
        })
    }, wt = {
        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: []
            }
        }
    }, pe = b()(a => ({
        model: "Create",
        activeColapse: "acionamento",
        setActiveColapse: t => a(() => ({
            activeColapse: t
        })),
        activeAutoAtt: {
            id: F(),
            nome: "",
            active: !0,
            acionamento: [],
            acao: [],
            regras: wt,
            usedLenght: 0
        },
        setActiveAutoAtt: (t, e) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                [t]: e
            }
        })),
        setResetDefaultAutoAtt: () => a(t => ({
            model: "Create",
            activeAutoAtt: {
                id: F(),
                nome: "",
                active: !0,
                acionamento: [],
                acao: [],
                regras: wt,
                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: F(),
                    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(i => i.id === t ? {
                ...i,
                text: e
            } : i);
            return {
                activeAutoAtt: {
                    ...s.activeAutoAtt,
                    acionamento: o
                }
            }
        }),
        setAcionamentoChave: (t, e) => a(s => {
            const o = s.activeAutoAtt.acionamento.map(i => i.id === t ? {
                ...i,
                chaves: i.chaves ? [e, ...i.chaves] : [e]
            } : i);
            return {
                activeAutoAtt: {
                    ...s.activeAutoAtt,
                    acionamento: o
                }
            }
        }),
        setAcionamentoRemoveChave: (t, e) => a(s => {
            const o = s.activeAutoAtt.acionamento.map(i => i.id === t ? {
                ...i,
                chaves: i.chaves.filter(n => n !== e)
            } : i);
            return {
                activeAutoAtt: {
                    ...s.activeAutoAtt,
                    acionamento: o
                }
            }
        }),
        setAcionamentoanuncioID: (t, e) => a(s => {
            const o = s.activeAutoAtt.acionamento.map(i => i.id === t ? {
                ...i,
                anuncioID: e
            } : i);
            return {
                activeAutoAtt: {
                    ...s.activeAutoAtt,
                    acionamento: o
                }
            }
        }),
        setCreateAcao: (t, e = {}) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                acao: [...s.activeAutoAtt.acao, {
                    id: F(),
                    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),
                [i] = o.splice(t.source.index, 1);
            return o.splice(t.destination.index, 0, i), {
                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
            } = Le.getState(), {
                activeAutoAtt: e
            } = pe.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 ? (pe.getState().setActiveColapse("acionamento"), {
                success: !1,
                message: "O auto atendimento deve ter ao menos um acionamento"
            }) : t.length === 0 ? (pe.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 ? (pe.getState().setActiveColapse("regras"), {
                success: !1,
                message: "O nome da assinatura deve ser preenchido"
            }) : s != null && s.active && !(s.desativarAss || s.persAss.active) ? (pe.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(r => o[r].active) ? (pe.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)
                        }
                    }
                }
            }
        }))
    })), Be = {
        cancelAfterChat: {
            type: "cancelAfterChat",
            propriedades: {
                active: !1
            }
        },
        responderGrupos: {
            type: "responderGrupos",
            propriedades: {
                active: !1
            }
        },
        assinatura: {
            type: "assinatura",
            propriedades: {
                active: !1,
                desativarAss: !1,
                persAss: {
                    active: !1,
                    nameAss: ""
                }
            }
        }
    }, me = b()((a, t) => ({
        model: "Create",
        activeColapse: "funil",
        addAbaInFunil: e => a(s => {
            try {
                const o = {
                    ...s.activeFollowUp.funil
                };
                return o.abas.some(n => n.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(i => i.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(n => n.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,
                i = o.abas.some(r => r.id === e),
                n = o.etiquetas.some(r => r.id === e);
            return i || n
        },
        removeLabelInFunil: e => a(s => {
            try {
                const o = {
                    ...s.activeFollowUp.funil
                };
                return o.etiquetas = o.etiquetas.filter(i => i.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: F(),
            nome: "",
            active: !0,
            funil: {
                id: F(),
                abas: [],
                etiquetas: []
            },
            acionamento: {
                type: "dispararAoEntrar",
                timing: {
                    days: 0,
                    hours: 0,
                    minutes: 0
                }
            },
            acao: [],
            regras: Be
        },
        setActiveFollowUp: (e, s) => a(o => ({
            activeFollowUp: {
                ...o.activeFollowUp,
                [e]: s
            }
        })),
        setResetDefaultFollowUp: () => a(e => ({
            model: "Create",
            activeFollowUp: {
                id: F(),
                nome: "",
                active: !0,
                funil: {
                    id: F(),
                    abas: [],
                    etiquetas: []
                },
                acionamento: {
                    type: "dispararAoEntrar",
                    timing: {
                        days: 0,
                        hours: 0,
                        minutes: 0
                    }
                },
                acao: [],
                regras: Be
            },
            activeColapse: "funil"
        })),
        setEditFollowUp: e => a(() => (e.regras || (e.regras = Be), 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: F(),
            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: F(),
                    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(i => i.id === e ? {
                    ...i,
                    propriedades: {
                        ...i.propriedades,
                        ...s
                    }
                } : i)
            }
        })),
        sortAcoes: e => a(s => {
            const o = [...s.activeFollowUp.acao],
                i = Array.from(o),
                [n] = i.splice(e.source.index, 1);
            return i.splice(e.destination.index, 0, n), {
                activeFollowUp: {
                    ...s.activeFollowUp,
                    acao: i
                }
            }
        }),
        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,
                    i = {
                        ...o
                    };
                return e === "persAss" ? (i.persAss = {
                    ...o.persAss,
                    active: !o.persAss.active
                }, i.persAss.active && (i.desativarAss = !1)) : e === "desativarAss" && (i.persAss = {
                    ...o.persAss,
                    active: !1
                }, i.desativarAss = !o.desativarAss), {
                    activeFollowUp: {
                        ...s.activeFollowUp,
                        regras: {
                            ...s.activeFollowUp.regras,
                            assinatura: {
                                ...s.activeFollowUp.regras.assinatura,
                                propriedades: i
                            }
                        }
                    }
                }
            })
        },
        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
            } = Ne.getState(), {
                activeFollowUp: s
            } = me.getState(), o = s.regras.assinatura.propriedades || null, i = s.acionamento.type || null, {
                days: n,
                hours: r,
                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 ? (me.getState().setActiveColapse("funil"), {
                success: !1,
                message: "O funil deve ter ao menos uma aba ou etiqueta adicionada"
            }) : !i && !n && !r && !c ? (me.getState().setActiveColapse("acionamento"), {
                success: !1,
                message: "O acionamento deve ter ao menos um tempo configurado"
            }) : e.length === 0 ? (me.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 ? (me.getState().setActiveColapse("regras"), {
                success: !1,
                message: "O nome da assinatura deve ser preenchido"
            }) : o != null && o.active && !(o.desativarAss || o.persAss.active) ? (me.getState().setActiveColapse("regras"), {
                success: !1,
                message: "A assinatura deve ter ao menos uma opção ativa"
            }) : {
                success: !0
            }
        }
    })), we = {
        useAcaoRespostaRapida: {
            size: "medium",
            arrow: !1,
            overflow: !1
        },
        useAcaoAutoAtendimento: {
            size: "large",
            inputName: "my-accordion-2",
            OnOpen: () => pe.getState().setActiveColapse("script"),
            arrow: !0,
            overflow: !0
        },
        useAcaoFollowUp: {
            size: "large",
            inputName: "my-accordion-2",
            OnOpen: () => me.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
        }
    }, ye = a => b()((t, e) => ({
        model: a,
        setModel: s => t({
            model: s
        }),
        acao: [],
        setAcao: s => t({
            acao: s
        }),
        setCreateAcao: (s, o = {}) => t(i => ({
            acao: [...i.acao, {
                id: F(),
                type: s,
                propriedades: o
            }]
        })),
        setRemoveAcao: s => t(o => ({
            acao: o.acao.filter(i => i.id !== s)
        })),
        setAcaoPropriedades: (s, o) => t(i => ({
            acao: i.acao.map(n => n.id === s ? {
                ...n,
                propriedades: {
                    ...n.propriedades,
                    ...o
                }
            } : n)
        })),
        clearAcao: () => t({
            acao: []
        }),
        sortAcoes: s => t(o => {
            const i = [...o.acao],
                n = Array.from(i),
                [r] = n.splice(s.oldIndex, 1);
            return n.splice(s.newIndex, 0, r), {
                acao: n
            }
        }),
        updateAcaoRowField: (s, o, i, n, r) => 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 === i ? {
                            ...u,
                            [n]: r
                        } : u)
                    })
                }
            })
        }))
    })), Bt = ye(we.useAcaoRespostaRapida), Le = ye(we.useAcaoAutoAtendimento), Ne = ye(we.useAcaoFollowUp), Xs = ye(we.useAcaoEditAndSendRes), Zs = ye(we.useAcaoEnvioEmMassa), eo = ye(we.useAcaoEnvioEmMassaNew), cn = {
        useAcaoRespostaRapida: Bt,
        useAcaoAutoAtendimento: Le,
        useAcaoFollowUp: Ne,
        useAcaoEditAndSendRes: Xs,
        useAcaoEnvioEmMassa: Zs,
        useAcaoEnvioEmMassaNew: eo
    }, Ce = b()(a => ({
        autoAtendimento: [],
        createAutoAtendimento: t => a(e => {
            const {
                acao: s
            } = Le.getState(), i = [{
                ...t,
                acao: s
            }, ...e.autoAtendimento];
            return f("autoatendimento", i), {
                autoAtendimento: i
            }
        }),
        editAutoAtendimento: t => a(e => {
            const {
                acao: s
            } = Le.getState(), o = {
                ...t,
                acao: s
            }, i = e.autoAtendimento.map(n => n.id === o.id ? o : n);
            return f("autoatendimento", i), {
                autoAtendimento: i
            }
        }),
        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,
                i = e.autoAtendimento.filter(c => c.nome.startsWith(o + " (Cópia")).length,
                r = [{
                    ...s,
                    id: F(),
                    nome: `${o} (Cópia${i>0?` ${i+1}`:""})`,
                    usedLenght: 0
                }, ...e.autoAtendimento];
            return f("autoatendimento", r), {
                autoAtendimento: r
            }
        }),
        getAutoAtendimento: t => Ce.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
            }
        })
    })), to = a => {
        Ce.setState({
            autoAtendimento: a
        }), f("autoatendimento", a)
    }, dn = a => {
        const t = Ce.getState().autoAtendimento,
            e = new Set(t.map(s => s.id));
        a.forEach(s => {
            e.has(s.id) || (t.push(s), e.add(s.id))
        }), to(t)
    }, ln = async () => {
        const a = await K("autoatendimento") || [];
        Ce.setState({
            autoAtendimento: a
        })
    }, ao = 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(i => i.id === e.id ? e : i);
            return f("respostasRapidas", o), {
                quickReplies: o
            }
        }),
        getQuickReply: (e, s) => {
            const {
                quickReplies: o
            } = t(), i = o.find(r => r.id === e);
            return (i == null ? void 0 : i[s]) || i
        },
        deleteQuickReply: e => a(s => {
            const o = s.quickReplies.filter(i => i.id !== e);
            return f("respostasRapidas", o), {
                quickReplies: o
            }
        }),
        sortQuickReply: e => a(() => (f("respostasRapidas", e), {
            quickReplies: e
        }))
    }));
var so = ia();
const Ve = oa(so),
    xe = b(a => ({
        contatos: [],
        setContatos: async t => (await f("contatos", t), y.getState().plugin_page ? P("setContatos", {
            contatos: t
        }, !1) : chrome.runtime.sendMessage({
            action: "setContatos",
            dados: {
                contatos: t
            }
        }), a(() => ({
            contatos: t
        })), {
            contatos: t
        })
    })),
    oo = async a => {
        xe.setState({
            contatos: a
        }), m.Utils("contatoInit", a), await f("contatos", a), chrome.runtime.sendMessage({
            action: "contatos-backup-update"
        })
    }, un = a => {
        const t = [...xe.getState().contatos];
        a.forEach(e => {
            const s = t.findIndex(o => o.id === e.id);
            s === -1 ? t.push(e) : t[s] = e
        }), oo(t)
    }, io = async () => {
        const a = await K("contatos") || [];
        m.Utils("contatoInit", a), xe.setState({
            contatos: a
        })
    }, {
        setContatos: no
    } = xe.getState();
chrome.runtime.onMessage.addListener(a => {
    switch (a.action) {
        case "setContatos":
            chrome.storage.local.get("contatos", t => {
                JSON.stringify(t.contatos) !== JSON.stringify(xe.getState().contatos) && (no(t.contatos), m.Utils("contatoInit", t.contatos))
            });
            break;
        case "contatos-backup-update":
            io();
            break
    }
});
const qe = b()(a => ({
    chatName: {
        name: "",
        number: "",
        autoSave: !1
    },
    setAutoSaveChatName: t => a(e => (J("autoSaveChat", "autoSave", [t]), {
        chatName: {
            ...e.chatName,
            autoSave: t
        }
    })),
    getActiveChat: async t => {
        const {
            contatos: e,
            setContatos: s
        } = xe.getState(), {
            chatName: o,
            setAutoSaveChatName: i
        } = qe.getState(), n = await m.Utils("getContato", t), r = e.find(c => c.id === t);
        if (a(r ? {
                chatName: {
                    ...o,
                    name: r.name,
                    number: t
                }
            } : {
                chatName: {
                    ...o,
                    name: n.name,
                    number: t
                }
            }), o.autoSave && await ue("contatos") === !0) {
            i(!1);
            return
        }
        if (o.autoSave && !r && n.name !== n.number) {
            const c = {
                id: t,
                name: n.name
            };
            m.Utils("contatoSave", c);
            const l = [...e, c];
            s(l)
        }
    }
}));
R.subscribe(a => {
    qe.getState().getActiveChat(a.activeChat.id._serialized)
});
(async () => {
    const a = await ee("autoSaveChat", "autoSave");
    a && a[0] && a[0][0] && qe.getState().setAutoSaveChatName(a[0][0])
})();
const N = b()(a => ({
    assinatura: {
        multiAtendimento: !1,
        active: !1,
        name: ""
    },
    timeout: null,
    setAssinatura: (t, e) => a(s => {
        const o = {
            ...s.assinatura,
            [t]: e
        };
        return J("useAssinatura", "assinatura", [o]), s.dispartAssMultiAtendimento(), {
            assinatura: o
        }
    }),
    setMultiATendimento: () => a(t => {
        const {
            connect: e,
            disconnect: s
        } = H.getState(), {
            whatsappID: o
        } = y.getState(), {
            language: i
        } = I.getState(), n = {
            ...t.assinatura
        };
        return t.assinatura.multiAtendimento ? (n.multiAtendimento = !1, s()) : n.name.length < 2 ? j({
            type: "Error",
            message: i.insiraUmNomeCom3Caracteres,
            position: "top-right"
        }) : (n.multiAtendimento = !0, e(o)), J("useAssinatura", "assinatura", [n]), {
            assinatura: n
        }
    }),
    sendTextChat: async () => {
        var l, d;
        const t = H.getState().addLocalAtendente,
            {
                assinatura: e
            } = N.getState(),
            s = (d = (l = R.getState().activeChat) == null ? void 0 : l.id) == null ? void 0 : d._serialized,
            {
                getSeletor: o
            } = V.getState(),
            {
                language: i
            } = I.getState(),
            n = o("footerTextArea"),
            r = [...(n == null ? void 0 : n.childNodes) ?? []].map(u => u.innerText !== `
` ? u.innerText : "").join(`
`);
        if (!n || !r.trim()) return;
        let c;
        await ue("assinatura") === !0 ? (c = r, N.getState().setAssinatura("active", !1), j({
            type: "Info",
            message: i.assinaturaDesativada,
            position: "top-right"
        })) : c = e.active ? `*_${e.name}:_* 
${r}` : r, 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
        } = V.getState(), {
            activeChat: e
        } = R.getState();
        if (!e) return;
        const s = l => {
                l.key === "Enter" && N.getState().assinatura.active && (l.stopPropagation(), N.getState().sendTextChat())
            },
            o = Ve(t("assChat"));
        o.off("keypress"), o.on("keypress", s);
        const i = l => {
            l.key === "Enter" && !l.shiftKey && !l.altKey && N.getState().assinatura.active && (l.preventDefault(), l.stopPropagation(), N.getState().sendTextChat())
        };
        t("assInput", l => {
            var u;
            const d = Ve(l);
            d.off("keydown"), d[0] && !d.data("keydownEventAdded") && ((u = d[0]) == null || u.addEventListener("keydown", i, !0), d == null || d.data("keydownEventAdded", !0))
        });
        const n = l => {
            N.getState().assinatura.active && (l.preventDefault(), l.stopPropagation(), N.getState().sendTextChat())
        };
        t("assBtn", l => {
            var u;
            const d = Ve(l);
            d == null || d.off("click"), d[0] && !d.data("ClickEventAdded") && ((u = d[0]) == null || u.addEventListener("click", n, !0), d == null || d.data("ClickEventAdded", !0))
        });
        const r = t("mainAudio"),
            c = new MutationObserver(l => {
                l[0].removedNodes.length !== 0 && (o.off("keypress"), c.disconnect(), N.getState().configAssinatura())
            });
        r && c.observe(r, {
            childList: !0
        })
    },
    insertName: () => {
        var n, r;
        const {
            chatName: t
        } = qe.getState(), e = (r = (n = R.getState().activeChat) == null ? void 0 : n.id) == null ? void 0 : r._serialized, {
            getSeletor: s
        } = V.getState(), o = s("footerTextArea"), i = [...(o == null ? void 0 : o.childNodes) ?? []].map(c => c.innerText !== `
` ? c.innerText : "").join(`
`);
        m.Chat("setInputText", {
            txt: i.trim() ? i + " " + t.name : t.name,
            id: e
        })
    },
    dispartAssMultiAtendimento: () => {
        var s, o;
        const {
            timeout: t
        } = N.getState(), e = (o = (s = R.getState().activeChat) == null ? void 0 : s.id) == null ? void 0 : o._serialized;
        t && clearTimeout(t), a({
            timeout: setTimeout(() => {
                H.getState().update(e)
            }, 2500)
        })
    }
}));
R.subscribe(a => {
    N.getState().configAssinatura()
});
const pn = async () => {
    const a = await ee("useAssinatura", "assinatura");
    a && a[0] && a[0][0] && N.setState({
        assinatura: a[0][0]
    })
};

function ro(a) {
    return U({
        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 mn(a) {
    return U({
        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 fn(a) {
    return U({
        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 gn(a) {
    return U({
        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 hn(a) {
    return U({
        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 vn(a) {
    return U({
        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 An(a) {
    return U({
        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 bn(a) {
    return U({
        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 Sn(a) {
    return U({
        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 wn(a) {
    return U({
        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 yn(a) {
    return U({
        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 Cn(a) {
    return U({
        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 xn(a) {
    return U({
        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 Mn(a) {
    return U({
        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 Tn(a) {
    return U({
        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 kn(a) {
    return U({
        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 _n(a) {
    return U({
        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 Rn(a) {
    return U({
        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 Un(a) {
    return U({
        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 En(a) {
    return U({
        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 X = b()((a, t) => ({
        initSubscribeUserTabs: !1,
        FollowUp: [],
        createFollowUp: e => a(s => {
            const {
                acao: o
            } = Ne.getState(), n = [{
                ...e,
                acao: o
            }, ...s.FollowUp];
            return f("FollowUp", n), {
                FollowUp: n
            }
        }),
        editFollowUp: e => a(s => {
            const {
                acao: o
            } = Ne.getState(), i = {
                ...e,
                acao: o
            }, n = s.FollowUp.map(r => r.id === i.id ? i : r);
            return f("FollowUp", n), {
                FollowUp: n
            }
        }),
        deleteFollowUp: e => {
            const s = I.getState().language;
            ea({
                icon: g.jsx(ro, {
                    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(i => {
                    const n = i.FollowUp.filter(r => r.id !== e.id);
                    return f("FollowUp", n), {
                        FollowUp: n
                    }
                }), j({
                    type: "Success",
                    message: s.followUpRemovedSuccess,
                    position: "top-right"
                })
            }
        },
        duplicateFollowUp: e => a(s => {
            const o = I.getState().language,
                i = s.getFollowById(e),
                n = i.nome.includes(`(${o.copy}`) ? i.nome.split(` (${o.copy}`)[0] : i.nome,
                r = s.FollowUp.filter(d => d.nome.startsWith(n + ` (${o.copy}`)).length,
                l = [{
                    ...i,
                    id: F(),
                    nome: `${n} (${o.copy}${r>0?` ${r+1}`:""})`
                }, ...s.FollowUp];
            return f("FollowUp", l), {
                FollowUp: l
            }
        }),
        getFollowById: e => t().FollowUp.find(s => s.id === e),
        switchActive: e => a(s => {
            const o = I.getState().language,
                i = s.getFollowById(e);
            if (i.funil.abas.length === 0 && i.funil.etiquetas.length === 0) return j({
                type: "Error",
                message: o.followUpNotAllowedToActive,
                position: "top-right"
            }), s;
            const r = s.FollowUp.map(c => c.id === e ? {
                ...c,
                active: !c.active
            } : c);
            return f("FollowUp", r), {
                FollowUp: r
            }
        }),
        disableFollowUp: e => a(s => {
            const o = s.FollowUp.map(i => i.id === e ? {
                ...i,
                active: !1
            } : i);
            return f("FollowUp", o), {
                FollowUp: o
            }
        }),
        addChatToFollowUp: (e, s, o, i) => a(n => {
            try {
                const r = n.FollowUp.map(c => {
                    if (c.id === e) {
                        const l = {
                            ...o,
                            date: c.acionamento.type === "timing" ? Date.now() : null
                        };
                        if (i === "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 (i === "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", r), {
                    FollowUp: r
                }
            } catch (r) {
                return console.error("❌ Erro ao adicionar chat ao follow-up:", r), n
            }
        }),
        removeChatFromFollowUp: (e, s, o, i) => a(n => {
            try {
                const r = n.FollowUp.map(c => {
                    if (c.id === e) {
                        if (i === "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 (i === "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", r), {
                    FollowUp: r
                }
            } catch (r) {
                return console.error("Erro ao remover chat do follow-up:", r), n
            }
        }),
        removeTabFromFunnels: e => a(s => {
            const o = s.FollowUp.map(i => {
                const n = i.funil.abas.filter(r => !e.some(c => c.id === r.id));
                return n.length !== i.funil.abas.length ? {
                    ...i,
                    funil: {
                        ...i.funil,
                        abas: n
                    }
                } : i
            });
            return f("FollowUp", o), {
                FollowUp: o
            }
        })
    })),
    co = a => {
        X.setState({
            FollowUp: a
        }), f("FollowUp", a)
    },
    Fn = a => {
        const t = X.getState().FollowUp,
            e = new Set(t.map(s => s.id));
        a.forEach(s => {
            e.has(s.id) || (t.push(s), e.add(s.id))
        }), co(t)
    },
    Ln = async () => {
        try {
            const a = await K("FollowUp") || [];
            X.setState({
                FollowUp: a
            })
        } catch (a) {
            console.error("Failed to initialize FollowUp:", a)
        }
    };

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

function Qe(a, t) {
    const {
        assinatura: e
    } = N.getState();
    return t.desativar ? a : t.personalizar ? `*_${t.nome}:_*
${a}` : e.active ? `*_${e.name}:_*
${a}` : a
}
const po = async (a, t) => {
    let e = "";
    return (t.includes("#nome") || t.includes("#primeiroNome")) && (e = (await m.Utils("getContato", a)).name), e
}, mo = () => {
    const {
        idioma: a
    } = I.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]
}, fo = () => {
    const {
        idioma: a
    } = I.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 Pe(a, t) {
    const e = await po(a, t);
    try {
        t = t.replaceAll("#saudação", mo), t = t.replaceAll("#periodo-dia", fo), 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 go = 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 ze(a, t) {
    const {
        getPerfilContato: e
    } = O.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", go(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 Ye(a, t) {
    if (t.includes("#mencionar-todos") && a.includes("@g.us")) {
        const s = (await m.Group("getParticipants", a)).map(i => i.id.toString()),
            o = s.map(i => " @" + i.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
    }
}
async function ho(a, t, e) {
    await ge(a, t.composing, "txt");
    let {
        mentionedList: s,
        msg: o
    } = await Ye(a, t.mensagem);
    o = await Pe(a, o), o = ze(a, o), o = Qe(o, e);
    const i = await m.Chat("sendTxt", {
        id: a,
        msg: o,
        mentionedList: s
    });
    return await Me(t.aguarde), i
}
async function vo(a, t, e) {
    await ge(a, t.composing, "txt");
    let {
        mentionedList: s,
        msg: o
    } = await Ye(a, t.mensagem);
    o = await Pe(a, o), o = ze(a, o), o = Qe(o, e);
    const i = await m.Chat("sendImage", {
        id: a,
        msg: o,
        mentionedList: s,
        base64: t.base64,
        isViewOnce: t.isViewOnce
    });
    return await Me(t.aguarde), i
}
async function Ao(a, t, e) {
    await ge(a, t.composing, "txt");
    let {
        mentionedList: s,
        msg: o
    } = await Ye(a, t.mensagem);
    o = await Pe(a, o), o = ze(a, o), o = Qe(o, e);
    const i = await m.Chat("sendVideo", {
        id: a,
        msg: o,
        mentionedList: s,
        base64: t.base64,
        microVideo: t.microVideo,
        isViewOnce: t.isViewOnce
    });
    return await Me(t.aguarde), i
}
async function bo(a, t) {
    return await ge(a, t.composing, "audio"), await m.Chat("sendAudio", {
        id: a,
        base64: t.base64
    })
}
async function So(a, t) {
    return await m.Chat("sendDoc", {
        id: a,
        base64: t.base64,
        name: t.base64Name
    })
}
async function wo(a, t) {
    return await m.Chat("sendPixKeyMessage", {
        id: a,
        keyType: t.keyType,
        name: t.name,
        key: t.key
    })
}
async function yo(a, t) {
    return await m.Chat("sendGroupInviteMessage", {
        id: a,
        groupID: t.groupID
    })
}
async function Co(a, t) {
    return await m.Chat("sendContact", {
        id: a,
        phone: t.userID,
        name: t.userName
    })
}
async function xo(a, t) {
    return await m.Chat("linkPreview", {
        id: a,
        link: t.link,
        title: t.title,
        description: t.description
    })
}
async function Mo(a, t) {
    return await m.Chat("sticker", {
        id: a,
        base64: t.base64
    })
}
async function To(a, t, e) {
    const {
        setNewUser: s
    } = z.getState();
    t === "abas" ? s(a, e) : jt(a, t, e, 0)
}
async function yt(a, t, e, s) {
    const {
        setRemoveUser: o
    } = z.getState();
    (e === "abas" || t === !0) && o(a, t, s), e !== "abas" && zt(a, t, e, s)
}
async function Ct(a, t, e) {
    const s = [{
        labelId: t,
        type: e
    }];
    await m.Labels("addOrRemoveLabels", {
        id: a,
        label: s
    })
}
async function ko(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 xt(a, t = !1) {
    t ? await m.Chat("desarquivar", a) : await m.Chat("arquivar", a)
}
const B = b()(a => ({
        pin: [],
        pinChat: () => {
            const t = R.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 (!M.getState().user.estado && e.pin.length > 0) return Z.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 = R.getState().activeChat) == null ? void 0 : s.id) == null ? void 0 : o._serialized;
            return t ? !!B.getState().pin.find(i => i.chatID === t) : !1
        },
        usedPin: (t, e) => {
            const o = B.getState().pin.find(i => i.chatID === t);
            o && B.getState().setUnpinChat(o), e === "pin" && B.getState().setPinChat(t)
        }
    })),
    _o = async a => {
        B.setState({
            pin: a
        }), m.Functions("FixChats", {
            action: "pinStorage",
            pin: a
        }), f("pinChat", a)
    }, Nn = a => {
        const t = [...B.getState().pin],
            s = ((o, i) => o.concat(i).reduce((c, l) => (c.find(u => u.chatID === l.chatID) || c.push(l), c), []))(t, a);
        _o(s)
    };
async function In() {
    const a = await K("pinChat");
    m.Functions("FixChats", {
        action: "pinStorage",
        pin: a
    }), B.setState({
        pin: a
    })
}
async function Mt(a, t) {
    const {
        usedPin: e
    } = B.getState();
    e(a, t)
}
async function Ro(a) {
    await m.Chat("markIsUnread", {
        id: a
    })
}
async function Uo(a, t) {
    const {
        socket: e,
        multi_atendente: s,
        atendente: o
    } = H.getState(), {
        whatsappID: i
    } = y.getState(), n = s.find(c => c.email === t.email) || {
        id: "NaN",
        whatsappID: i,
        activeChat: "closeChat",
        userLogado: !0,
        email: t.email,
        assinaturaActive: !1,
        assinatura: t.email,
        deviceID: NaN
    }, r = {
        chatID: a,
        whatsappID: i,
        atendente: n,
        status: "Transferido",
        dataUltimaInteracao: Date.now()
    };
    e.emit("transferir_atendimento", {
        attID: n.id,
        remetenteID: o.id,
        chatID: a.replace(/@c\.us/g, ""),
        text: t.mensagem,
        urgencia: t.urgencia
    }, r)
}
async function Eo(a) {
    await m.BlockList("blockContact", a)
}
async function Fo(a, t, e) {
    try {
        const {
            sendAction: s
        } = Yt.getState(), {
            getQuickReply: o
        } = ao.getState(), i = o(t);
        await s(i, a, e)
    } catch (s) {
        console.error("Error ao tentar enviar a resposta rapida pelo SendAction", s)
    }
}
const he = async (a, t) => {
    let e = await Pe(a, t);
    return e = ze(a, e), e
};
async function Lo(a, t) {
    await ge(a, t.composing, "txt");
    let e = {
        ...t,
        title: await he(a, t.title),
        description: await he(a, t.description),
        footer: await he(a, t.footer),
        buttonText: await he(a, t.buttonText),
        sections: await Promise.all(t.sections.map(async o => ({
            ...o,
            rows: await Promise.all(o.rows.map(async i => ({
                ...i,
                title: await he(a, i.title),
                description: await he(a, i.description)
            })))
        })))
    };
    const s = await m.Chat("sendListMessage", {
        id: a,
        options: e
    });
    return await Me(t.aguarde), s
}
const Re = () => {
    j({
        type: "Info",
        message: "Não é possível atribuir um contato não salvo a uma aba, etiqueta, fixá-lo ou transferi-lo de atendimento.",
        position: "top-right"
    })
};
async function Xe(a, t, e, s) {
    const {
        addMonitor: o,
        deleteMonitor: i,
        updateMonitor: n
    } = uo.getState(), r = [], c = F();
    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 (!n(c, l, d)) {
            r.push(!1);
            break
        }
        switch (d.type) {
            case "txt":
                r.push(await ho(x(a), d.propriedades, e));
                break;
            case "image":
                r.push(await vo(x(a), d.propriedades, e));
                break;
            case "video":
                r.push(await Ao(x(a), d.propriedades, e));
                break;
            case "audio":
                r.push(await bo(x(a), d.propriedades));
                break;
            case "doc":
                r.push(await So(x(a), d.propriedades));
                break;
            case "pix":
                r.push(await wo(x(a), d.propriedades));
                break;
            case "groupInvite":
                r.push(await yo(x(a), d.propriedades));
                break;
            case "contact":
                r.push(await Co(x(a), d.propriedades));
                break;
            case "linkPreview":
                r.push(await xo(x(a), d.propriedades));
                break;
            case "sticker":
                r.push(await Mo(x(a), d.propriedades));
                break;
            case "addCRM":
                a.includes("@lid") ? Re() : await To(Oe(a), d.propriedades.crmID, d.propriedades.abaID);
                break;
            case "removeCRM":
                await yt(Oe(a), !1, d.propriedades.crmID, d.propriedades.abaID);
                break;
            case "removeAllCRM":
                await yt(Oe(a), !0);
                break;
            case "addLabel":
                a.includes("@lid") ? Re() : await Ct(x(a), d.propriedades.labelID, "add");
                break;
            case "removeLabel":
                await Ct(x(a), d.propriedades.labelID, "remove");
                break;
            case "removeAllLabel":
                await ko(x(a));
                break;
            case "timer":
                await Me(d.propriedades.segundos);
                break;
            case "composing":
                await ge(x(a), d.propriedades.segundos, "txt");
                break;
            case "recording":
                await ge(x(a), d.propriedades.segundos, "audio");
                break;
            case "arquivar":
                await xt(x(a));
                break;
            case "desarquivar":
                await xt(x(a), !0);
                break;
            case "fixarChat":
                a.includes("@lid") ? Re() : await Mt(x(a), "pin");
                break;
            case "desfixarChat":
                await Mt(x(a), "unpin");
                break;
            case "marcarNaoLido":
                await Ro(x(a));
                break;
            case "transferir":
                a.includes("@lid") ? Re() : await Uo(x(a), d.propriedades);
                break;
            case "bloquear":
                await Eo(x(a));
                break;
            case "respostaRapida":
                await Fo(x(a), d.propriedades.respostaRapidaID, e);
                break;
            case "list":
                await Lo(x(a), d.propriedades);
                break;
            default:
                console.warn(`No handler found for action type: ${d.type}`);
                break
        }
    }
    return i(c), r.length === 0 || r.every(l => l && l.id)
}
async function Ze(a, t) {
    const {
        language: e
    } = I.getState(), {
        label: s
    } = re.getState();
    if (await ue("followUp", !0) === !0) {
        Je("followUp", e.btnPremium, s.checkout);
        return
    }
    const o = t.regras.assinatura.propriedades;
    await Xe(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: i
                } = e,
                n = {
                    ...o,
                    id: x(o.id)
                },
                r = X.getState().FollowUp.filter(c => c.active);
            if (r.length === 0) return;
            if (s === "add") {
                Io(n, i, r);
                const c = r.filter(l => l.acionamento.type === "timing");
                i.forEach(l => {
                    qo(n, l.id, c)
                })
            } else if (s === "remove") {
                No(n, i, r);
                const c = r.filter(l => l.acionamento.type === "timing");
                i.forEach(l => {
                    Po(n, l.id, c)
                })
            }
        }
    })
})();

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

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

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

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

function zo() {
    const a = X.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(i => {
                if (!i.date) return;
                const n = le.convertTimingToMilliseconds(s.acionamento.timing);
                t >= i.date + n && e.push({
                    chat: i,
                    abaId: o.id,
                    followUp: s
                })
            })
        }), s.funil.etiquetas.forEach(o => {
            o.chats.forEach(i => {
                if (!i.date) return;
                const n = le.convertTimingToMilliseconds(s.acionamento.timing);
                t >= i.date + n && e.push({
                    chat: i,
                    etiquetaId: o.id,
                    followUp: s
                })
            })
        })
    }), e.forEach(({
        chat: s,
        abaId: o,
        etiquetaId: i,
        followUp: n
    }) => {
        Ze(s.id, n), o ? X.getState().removeChatFromFollowUp(n.id, o, s.id, "tab") : i && X.getState().removeChatFromFollowUp(n.id, i, s.id, "label")
    })
}
chrome.runtime.onMessage.addListener(async a => {
    switch (a.action) {
        case "dispatch_timing_follow":
            zo();
            break
    }
});

function Do() {
    z.subscribe((a, t) => {
        if (!a.userTabs || !X.getState().initSubscribeUserTabs) return;
        const e = a.userTabs || [],
            o = (t.userTabs || []).filter(i => !e.some(n => n.id === i.id));
        o.length !== 0 && X.getState().removeTabFromFunnels(o)
    })
}
const jo = [{
        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
    }],
    z = b()(a => ({
        userTabs: [],
        systemTabs: jo,
        activeTab: {
            type: "tab",
            id: 1
        },
        sortUserTabs: (t, e) => a(s => {
            const o = [...s.userTabs],
                [i] = o.splice(t, 1),
                n = [...o.slice(0, e), i, ...o.slice(e)];
            return f("userTabs", n), y.getState().plugin_page ? P("userTabs-sortUserTabs", {
                home: t,
                destination: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-sortUserTabs",
                dados: {
                    home: t,
                    destination: e
                }
            }), {
                userTabs: n
            }
        }),
        setNewUser: async (t, e) => {
            var r;
            const s = t.replace("@c.us", "").replace("@g.us", "");
            if ((r = z.getState().userTabs.find(c => c.id === e)) == null ? void 0 : r.chats.find(c => c.id === t || c.id === s)) return;
            const {
                name: i
            } = await m.Utils("getContato", t), n = z.getState().userTabs.map(c => {
                if (c.id === e) {
                    if (!M.getState().user.estado && c.chats.length >= 5) return Z.getState().openRendertype("user_free"), c;
                    {
                        const l = {
                            ...c,
                            chats: [...c.chats, {
                                id: t,
                                name: i
                            }]
                        };
                        return W.getState().dispartWebhook(t, "crm", {
                            id: e,
                            type: "NewUser",
                            name: l.tag
                        }), l
                    }
                } else return c
            });
            f("userTabs", n), y.getState().plugin_page ? P("userTabs-setNewUser", {
                userID: t,
                id: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setNewUser",
                dados: {
                    userID: t,
                    id: e
                }
            }), a(c => ({
                ...c,
                userTabs: n
            }))
        },
        setChatsTab: async (t, e, s = !0) => {
            const o = z.getState().userTabs.map(i => i.id === e ? {
                ...i,
                chats: t
            } : i);
            z.setState({
                userTabs: o
            }), s && (f("userTabs", o), y.getState().plugin_page ? P("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(i => {
                if (i.id === e) {
                    const n = t.filter(r => !i.chats.some(c => c.id === r.id));
                    return {
                        ...i,
                        chats: [...i.chats, ...n]
                    }
                }
                return i
            });
            return f("userTabs", o), y.getState().plugin_page ? P("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 i = o.userTabs.map(n => {
                if (n.id === e) {
                    const r = n.chats.filter(c => !t.some(l => l.id === c.id));
                    return {
                        ...n,
                        chats: r
                    }
                }
                if (n.id === s) {
                    const r = [...n.chats, ...t.filter(c => !n.chats.some(l => l.id === c.id))];
                    return {
                        ...n,
                        chats: r
                    }
                }
                return n
            });
            return f("userTabs", i), y.getState().plugin_page ? P("userTabs-setMoveChats", {
                chats: t,
                source: e,
                destination: s
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setMoveChats",
                dados: {
                    chats: t,
                    source: e,
                    destination: s
                }
            }), {
                userTabs: i
            }
        }),
        setRemoveUser: (t, e, s) => a(o => {
            const i = t.replace("@c.us", "").replace("@g.us", ""),
                n = o.userTabs.map(r => e ? {
                    ...r,
                    chats: r.chats.filter(c => c.id !== i && c.id !== t)
                } : r.id === s ? {
                    ...r,
                    chats: r.chats.filter(c => c.id !== i && c.id !== t)
                } : {
                    ...r
                });
            if (e) W.getState().dispartWebhook(i, "crm", {
                id: s,
                type: "RemoveUser-All"
            });
            else {
                const r = o.userTabs.find(c => c.id === s);
                r && W.getState().dispartWebhook(i, "crm", {
                    id: s,
                    type: "RemoveUser",
                    name: r.tag
                })
            }
            return f("userTabs", n), y.getState().plugin_page ? P("userTabs-setRemoveUser", {
                userID: i,
                isAll: e,
                id: s
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setRemoveUser",
                dados: {
                    userID: i,
                    isAll: e,
                    id: s
                }
            }), {
                userTabs: n
            }
        }),
        setEditUserTabName: (t, e) => a(s => {
            const o = s.userTabs.map(i => i.id === t ? {
                ...i,
                tag: e
            } : i);
            return f("userTabs", o), y.getState().plugin_page ? P("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 ? P("userTabs-setRemoveTab", {
                id: t
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setRemoveTab",
                dados: {
                    id: t
                }
            }), {
                userTabs: s
            }
        }),
        setCreateUserTab: t => a(e => {
            const s = {
                    id: F(),
                    chats: [],
                    tag: t,
                    type: "user",
                    hide: !1
                },
                o = [s, ...e.userTabs];
            return f("userTabs", o), y.getState().plugin_page ? P("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 ? P("userTabs-setVisibilityUserTab", {
                id: t
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setVisibilityUserTab",
                dados: {
                    id: t
                }
            }), {
                userTabs: s
            }
        }),
        getUserAbasTam: t => z.getState().userTabs.filter(s => s.chats.filter(o => o.id === t).length > 0).length,
        getTabByID: t => z.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 J("SystemTabsDB", "SystemTabs", [Ae.encryptData(s)]), {
                systemTabs: s
            }
        }),
        setActiveTab: t => a(e => ({
            ...e,
            activeTab: t
        }))
    }));
z.subscribe(() => {
    tt.getState().chatListTabs(), Do()
});
const Vt = 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(i => i.selecionados.find(n => n.id === e) ? {
        selecionados: i.selecionados.filter(r => {
            if (r.id !== e) return r
        })
    } : {
        selecionados: [...i.selecionados, {
            id: e,
            type: s,
            ...o && {
                chats: o
            }
        }]
    }),
    renderFiltroPersonalizado: () => {
        z.getState().setActiveTab({
            id: "custom",
            type: "custom"
        }), m.ListChat("custom", t().selecionados)
    }
}));
Vt.subscribe(async a => {
    z.getState().setActiveTab({
        id: "custom",
        type: "custom"
    }), m.ListChat("custom", {
        selecionados: a.selecionados,
        user: M.getState().user
    })
});
const $t = ["chat", "image", "document", "video", "ptt", "vcard", "sticker", "poll_creation", "location", "list_response"];

function Oo(a) {
    if (a.id.fromMe || !$t.includes(a.type)) return;
    const {
        autoAtendimento: t
    } = Ce.getState();
    t.forEach(e => {
        e.active && Wo(a, e)
    })
}
const Wo = async (a, t) => {
    var u, p, A, v, h, S, E, w, L, ae, _e, st, ot, it, nt, rt, ct, dt, lt, ut, pt, mt, ft, gt, ht;
    const {
        getUserAbasTam: e,
        userTabs: s
    } = z.getState(), o = C.getState().crm, {
        isBusiness: i
    } = y.getState(), n = a.id.remote.toString().replace(/@(.*)/, "");
    if (!t.regras.responderGrupos.propriedades.active && a.author) return;
    const r = await m.Chat("getActiveChat", "@");
    if (t.regras.responderChatAtivo.propriedades.active && r === 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", n)).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 se = l[c],
            {
                horaInicio: Y,
                horaFim: q,
                periodoAtivacao: D,
                active: oe
            } = t.regras.responderDias.propriedades[se] || {};
        if (!Y || !q || !oe || D && !le.isValidInterval(Y, q)) return
    }
    const {
        labels: d
    } = await m.Chat("get", a.id.remote);
    if (!(i && ((S = (h = (v = t.regras) == null ? void 0 : v.notResponderChatEtiquetado) == null ? void 0 : h.propriedades) == null ? void 0 : S.active) === !0 && d.length > 0) && !(i && ((L = (w = (E = t.regras) == null ? void 0 : E.notResponderEtiqueta) == null ? void 0 : w.propriedades) == null ? void 0 : L.active) === !0 && t.regras.notResponderEtiqueta.propriedades.labelID.some(q => d.includes(q))) && !(i && ((st = (_e = (ae = t == null ? void 0 : t.regras) == null ? void 0 : ae.responderEtiqueta) == null ? void 0 : _e.propriedades) == null ? void 0 : st.active) === !0 && !t.regras.responderEtiqueta.propriedades.labelID.some(q => d.includes(q))) && !(((nt = (it = (ot = t == null ? void 0 : t.regras) == null ? void 0 : ot.notResponderChatCRM) == null ? void 0 : it.propriedades) == null ? void 0 : nt.active) === !0 && e(n) + Dt(n) !== 0)) {
        if (((dt = (ct = (rt = t == null ? void 0 : t.regras) == null ? void 0 : rt.notResponderCRM) == null ? void 0 : ct.propriedades) == null ? void 0 : dt.active) === !0) {
            const se = t.regras.notResponderCRM.propriedades.crm;
            let Y = !0;
            for (const q of se)
                if (q.crmID === "abas")(lt = s.find(D => D.id === q.abaID)) == null || lt.chats.forEach(D => {
                    D.id === n && (Y = !1)
                });
                else
                    for (const D of o) D.id === q.crmID && ((ut = D.list.find(oe => oe.id === q.abaID)) == null || ut.chats.forEach(oe => {
                        oe.id === n && (Y = !1)
                    }));
            if (!Y) return
        }
        if (((ft = (mt = (pt = t == null ? void 0 : t.regras) == null ? void 0 : pt.responderCRM) == null ? void 0 : mt.propriedades) == null ? void 0 : ft.active) === !0) {
            const se = t.regras.responderCRM.propriedades.crm;
            let Y = !1;
            for (const q of se)
                if (q.crmID === "abas")(gt = s.find(D => D.id === q.abaID)) == null || gt.chats.forEach(D => {
                    D.id === n && (Y = !0)
                });
                else
                    for (const D of o) D.id === q.crmID && ((ht = D.list.find(oe => oe.id === q.abaID)) == null || ht.chats.forEach(oe => {
                        oe.id === n && (Y = !0)
                    }));
            if (!Y) return
        }
        Bo(a, t)
    }
}, Bo = async (a, t) => {
    const e = I.getState().language,
        {
            label: s
        } = re.getState(),
        {
            updateUsedLenght: o
        } = Ce.getState(),
        i = async () => {
            if (await ue("autoatendimento", !0) === !0) {
                Je("autoAtendimento", e.btnPremium, s.checkout);
                return
            }
            const n = t.regras.assinatura.propriedades;
            Xe(a.id.remote.toString(), t.acao, {
                desativar: n.active ? n.desativarAss : !1,
                personalizar: n.active ? n.persAss.active : !1,
                nome: n.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 n of t.acionamento) {
        if (n.type === "message_Received" && (n.text == a.body || n.text == a.caption)) {
            i();
            break
        }
        if (n.type === "keyword") {
            let r = !1;
            if (n.chaves.forEach(c => {
                    (a.type === "chat" || a.type === "list_response") && a.body.toLowerCase().includes(c.toLowerCase()) && (r = !0)
                }), r) {
                i();
                break
            }
        }
        if (n.type === "day_Message") {
            const r = a.id.remote.replace(/@(.*)/, ""),
                c = (await m.Chat("getMessages", {
                    id: r,
                    quant: -1
                })).reverse();
            c.shift();
            const l = c.find(d => d.id.fromMe === !1 && $t.includes(d.type));
            if (l) {
                const d = parseInt(l.t.toString() + "000");
                if (!le.isDataDeHoje(d)) {
                    i();
                    break
                }
            }
        }
        if (n.type === "customer_Message") {
            const r = a.id.remote.replace(/@(.*)/, "");
            if ((await m.Chat("getMessages", {
                    id: r
                })).filter(d => d.type !== "e2e_notification" && d.type !== "notification_template").length === 1) {
                i();
                break
            }
        }
    }
}, T = b((a, t) => ({
    workflows: [],
    currentWorkflow: null,
    saveToStorage: e => {
        f("fluxo", e)
    },
    getSourceNode: (e, s) => {
        const o = t().workflows.find(r => r.id === s);
        if (!o) return null;
        const i = o.edges.find(r => r.target === e);
        if (!i) return null;
        const n = o.nodes.find(r => r.id === i.source);
        return n || null
    },
    getTargetNode: (e, s) => {
        const o = t().workflows.find(r => r.id === s);
        if (!o) return null;
        const i = o.edges.find(r => r.source === e);
        if (!i) return null;
        const n = o.nodes.find(r => r.id === i.target);
        return n || null
    },
    getAllTargetNodes: (e, s) => {
        const o = t().workflows.find(r => r.id === s);
        if (!o) return [];
        const i = o.edges.filter(r => r.source === e);
        return i.length ? i.map(r => o.nodes.find(c => c.id === r.target)).filter(Boolean) : []
    },
    getTargetNodeByBestMatch: (e, s, o) => {
        const i = t().workflows.find(d => d.id === s);
        if (!i) return null;
        const n = i.nodes.find(d => d.id === e);
        if (!n || n.type !== "send-answers") return null;
        const r = i.edges.filter(d => d.source === e);
        if (!r.length) return null;
        const c = r.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 = i.nodes.find(d => d.id === c.target);
        return l || null
    },
    getTargetNodeByRowId: (e, s, o) => {
        const i = t().workflows.find(u => u.id === s);
        if (!i) return null;
        const n = i.nodes.find(u => u.id === e);
        if (!n || n.type !== "send-list") return null;
        const r = n == null ? void 0 : n.data;
        if (!r || !(r != null && r.sections)) return null;
        const c = r.sections.flatMap(u => u.rows).find(u => u.rowId === o);
        if (!c) return null;
        const l = i.edges.find(u => u.source === e && u.sourceHandle === `on-response-${c.rowId}`);
        if (!l) return null;
        const d = i.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(i => i.type === "init");
        return s ? e.edges.some(i => i.source === s.id) : !1
    },
    getVariableByNodeId: (e, s) => {
        const o = t().workflows.find(n => n.id === s);
        if (!o) return;
        const i = o.variaveis.find(n => n.nodeId === e);
        if (i) return i
    },
    updateVariableAsync: async (e, s, o, i) => new Promise(n => {
        a(r => {
            const c = r.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: i
                        } : h) : [...p.clients, {
                            userId: e,
                            value: i
                        }];
                        return {
                            ...p,
                            clients: v
                        }
                    });
                    return {
                        ...d,
                        variaveis: u
                    }
                }),
                l = r.currentWorkflow && r.currentWorkflow.id === o && c.find(d => d.id === o) || r.currentWorkflow;
            return t().saveToStorage({
                workflows: c,
                currentWorkflow: l
            }), setTimeout(() => n(), 0), {
                workflows: c,
                currentWorkflow: l
            }
        })
    }),
    delay: e => new Promise(s => setTimeout(s, e))
}));
async function qn() {
    const t = ((await K("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 Pn(a) {
    var l;
    const {
        workflows: t,
        currentWorkflow: e
    } = a, s = T.getState(), o = new Set(s.workflows.map(d => d.name)), i = d => {
        let u = d,
            p = 1;
        for (; o.has(u);) u = `${d} (${p})`, p++;
        return u
    }, n = t.map(d => {
        s.workflows.find(v => v.id === d.id) && (d.id = F());
        const p = s.workflows.find(v => v.id === d.id);
        if (p) {
            const v = {
                ...p,
                ...d
            };
            return v.name !== p.name && (v.name = i(v.name)), v
        }
        const A = i(d.name);
        return {
            ...d,
            name: A
        }
    }), r = e ? ((l = s.currentWorkflow) == null ? void 0 : l.id) === e.id ? {
        ...s.currentWorkflow,
        ...e
    } : e : s.currentWorkflow, c = {
        workflows: n,
        currentWorkflow: r
    };
    T.setState(c), T.getState().saveToStorage(c)
}

function zn(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 G = b((a, t) => ({
        progresses: {},
        resetUserProgress: e => {
            a(s => {
                const {
                    [e]: o, ...i
                } = s.progresses;
                return {
                    progresses: i
                }
            })
        },
        updateUserProgress: (e, s, o) => {
            a(i => ({
                progresses: {
                    ...i.progresses,
                    [e]: {
                        currentNodeId: o,
                        workflowId: s
                    }
                }
            }))
        },
        getUserProgress: e => t().progresses[e]
    })),
    Tt = 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)
    }));

function Vo(a, t) {
    let e;
    try {
        e = a()
    } catch {
        return
    }
    return {
        getItem: o => {
            var i;
            const n = c => c === null ? null : JSON.parse(c, t == null ? void 0 : t.reviver),
                r = (i = e.getItem(o)) != null ? i : null;
            return r instanceof Promise ? r.then(n) : n(r)
        },
        setItem: (o, i) => e.setItem(o, JSON.stringify(i, t == null ? void 0 : t.replacer)),
        removeItem: o => e.removeItem(o)
    }
}
const $e = a => t => {
        try {
            const e = a(t);
            return e instanceof Promise ? e : {
                then(s) {
                    return $e(s)(e)
                },
                catch (s) {
                    return this
                }
            }
        } catch (e) {
            return {
                then(s) {
                    return this
                },
                catch (s) {
                    return $e(s)(e)
                }
            }
        }
    },
    $o = (a, t) => (e, s, o) => {
        let i = {
                storage: Vo(() => localStorage),
                partialize: h => h,
                version: 0,
                merge: (h, S) => ({
                    ...S,
                    ...h
                }),
                ...t
            },
            n = !1;
        const r = new Set,
            c = new Set;
        let l = i.storage;
        if (!l) return a((...h) => {
            console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`), e(...h)
        }, s, o);
        const d = () => {
                const h = i.partialize({
                    ...s()
                });
                return l.setItem(i.name, {
                    state: h,
                    version: i.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;
            n = !1, r.forEach(w => {
                var L;
                return w((L = s()) != null ? L : p)
            });
            const E = ((S = i.onRehydrateStorage) == null ? void 0 : S.call(i, (h = s()) != null ? h : p)) || void 0;
            return $e(l.getItem.bind(l))(i.name).then(w => {
                if (w)
                    if (typeof w.version == "number" && w.version !== i.version) {
                        if (i.migrate) {
                            const L = i.migrate(w.state, w.version);
                            return L instanceof Promise ? L.then(ae => [!0, ae]) : [!0, L]
                        }
                        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 L;
                const [ae, _e] = w;
                if (A = i.merge(_e, (L = s()) != null ? L : p), e(A, !0), ae) return d()
            }).then(() => {
                E == null || E(A, void 0), A = s(), n = !0, c.forEach(w => w(A))
            }).catch(w => {
                E == null || E(void 0, w)
            })
        };
        return o.persist = {
            setOptions: h => {
                i = {
                    ...i,
                    ...h
                }, h.storage && (l = h.storage)
            },
            clearStorage: () => {
                l == null || l.removeItem(i.name)
            },
            getOptions: () => i,
            rehydrate: () => v(),
            hasHydrated: () => n,
            onHydrate: h => (r.add(h), () => {
                r.delete(h)
            }),
            onFinishHydration: h => (c.add(h), () => {
                c.delete(h)
            })
        }, i.skipHydration || v(), A || p
    },
    Go = $o,
    Gt = b()(Go((a, t) => ({
        sessions: {},
        startSession: (e, s) => {
            const o = {
                userID: e,
                workflowId: s,
                lastInteraction: new Date().toISOString()
            };
            a(i => ({
                sessions: {
                    ...i.sessions,
                    [e]: o
                }
            }))
        },
        endSession: e => {
            a(s => {
                const {
                    [e]: o, ...i
                } = s.sessions;
                return {
                    sessions: i
                }
            })
        },
        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"
    })),
    Ge = ["chat", "image", "document", "video", "list", "list_response", "ptt", "vcard", "sticker", "poll_creation", "location"];
async function Ho(a, t) {
    const e = (t.acionamentos ?? []).filter(o => {
            var i;
            return !!((i = o == null ? void 0 : o.data) != null && i.active)
        }),
        s = a.id.remote.toString();
    for (const o of e) switch (o.type) {
        case "aoReceberMensagem":
            return !0;
        case "porPalavraChave": {
            const i = o.data;
            if ((a.type === "chat" || a.type === "list_response") && i.chaves.some(n => a.body.toLowerCase().includes(n.toLowerCase()))) return !0;
            break
        }
        case "primeiraMensagemDoClienteNoDia": {
            if (vt(s)) break;
            const i = a.t * 1e3,
                n = new Date(i),
                r = new Date;
            if (n.getDate() !== r.getDate() || n.getMonth() !== r.getMonth() || n.getFullYear() !== r.getFullYear()) break;
            const l = (await m.Chat("getMessages", {
                id: s,
                quant: 20
            })).filter(d => {
                if (d.id.fromMe !== !1 || !Ge.includes(d.type)) return !1;
                const u = d.t * 1e3,
                    p = new Date(u);
                return p.getDate() === r.getDate() && p.getMonth() === r.getMonth() && p.getFullYear() === r.getFullYear()
            });
            if (l.sort((d, u) => d.t - u.t), l.length > 0 && l[0].t === a.t) return !0;
            break
        }
        case "primeiraMensagemDoCliente": {
            if (vt(s)) break;
            if ((await m.Chat("getMessages", {
                    id: s,
                    quant: 50
                })).filter(r => r.id.fromMe === !1 && Ge.includes(r.type)).length === 1) return !0;
            break
        }
        default:
            continue
    }
    return !1
}
async function Ht(a, t) {
    var o, i;
    const e = (o = t.regras) == null ? void 0 : o.find(n => n.type === "responderChatAtivo");
    return !e || !((i = e.propriedades) != null && i.active) ? !0 : await m.Chat("getActiveChat", "@") !== a.id.remote.toString()
}
async function Jo(a, t) {
    const {
        getUserAbasTam: e,
        userTabs: s
    } = z.getState(), o = C.getState().crm, {
        isBusiness: i
    } = y.getState(), n = a.id.remote.toString().replace(/@(.*)/, ""), {
        labels: r
    } = 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 Ht(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 (!le.isValidInterval(h, S)) return !1;
            break
        }
        case "notResponderChatEtiquetado": {
            if (i && r.length > 0) return !1;
            break
        }
        case "notResponderEtiqueta": {
            if (i) {
                const {
                    labelID: u
                } = d.propriedades;
                if (r.some(p => u.includes(p))) return !1
            }
            break
        }
        case "responderEtiqueta": {
            if (i) {
                const {
                    labelID: u
                } = d.propriedades;
                if (!r.some(p => u.includes(p))) return !1
            }
            break
        }
        case "notResponderChatCRM": {
            if (e(n) + Dt(n) !== 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 === n))) {
                        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 === n))) {
                            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 === n))) {
                        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 === n))) {
                            p = !0;
                            break
                        } if (!p) return !1;
            break
        }
    }
    return !0
}
const et = 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(i => ({
                updatedVariables: {
                    ...i.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(i => {
                    i.startsWith(`${e}:`) && delete o[i]
                }), {
                    updatedVariables: o
                }
            })
        }
    })),
    te = 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
        }
    },
    Ko = (a, t) => {
        const {
            getSession: e,
            getLastInteractionDate: s
        } = Gt.getState();
        if (!e(a)) return !0;
        const i = t.cooldown;
        if (!i || i.value <= 0) return !0;
        const n = te(i),
            r = s(a).getTime();
        return Date.now() - r >= n
    },
    Qo = a => {
        const t = a.nodes.find(s => s.type === "init");
        return t ? a.edges.some(s => s.source === t.id) : !1
    },
    Yo = (a, t, e) => ({
        id: `virtual-${Date.now()}`,
        type: a,
        data: t,
        index: -1,
        position: {
            x: 0,
            y: 0
        },
        send: {
            type: "timeout",
            data: t
        }
    }),
    Xo = async (a, t) => {
        let e = "";
        return (t.includes("#nome") || t.includes("#primeiroNome")) && (e = (await m.Utils("getContato", a)).name), e
    }, Zo = () => {
        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]
    }, ei = () => {
        const t = new Date().getHours();
        return t >= 6 && t < 12 ? "Bom dia" : t >= 12 && t < 18 ? "Boa tarde" : "Boa noite"
    }, ke = async (a, t) => {
        const e = await Xo(a, t);
        try {
            t = t.replaceAll("#saudação", Zo()), t = t.replaceAll("#periodo-dia", ei()), 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
    }, ti = (a, t) => {
        var i;
        const {
            assinatura: e
        } = N.getState(), s = (i = t == null ? void 0 : t.regras) == null ? void 0 : i.find(n => n.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 De(a, t, e) {
    const s = await ke(a, t);
    return ti(s, e)
}
const de = (a, t, e) => t.replace(/{{(.*?)}}/g, (o, i) => {
    const n = i.trim(),
        c = T.getState().workflows.find(d => d.id === e.id).variaveis.find(d => d.name.trim() === n);
    if (!c) return "";
    const l = c.clients.find(d => d.userId === a);
    return (l == null ? void 0 : l.value) ?? ""
});
async function ai(a, t, e, s) {
    var o, i;
    try {
        if (!(a != null && a.message)) return;
        const n = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(u => u.type === "simulateWriting"),
            r = (n == null ? void 0 : n.propriedades) ?? {
                active: !1
            },
            c = te((i = e.globalSettings) == null ? void 0 : i.blockTransitionDelay),
            l = typeof c == "number" && c > 0 ? c : 0;
        (r.active || l > 0) && await m.Chat("markIsComposing", {
            id: t,
            timer: l
        });
        let d = a.message;
        d = await De(t, d, e), d = de(t, d, e), await m.Chat("sendTxt", {
            id: t,
            msg: d
        })
    } catch (n) {
        throw console.error(`Erro ao enviar mensagem para ${t}:`, n), n
    }
}
const Te = b(() => ({
    files: []
}));
async function Dn() {
    const a = await K("fluxoFiles") || [];
    Te.setState({
        files: a
    })
}
chrome.storage.onChanged.addListener((a, t) => {
    var e;
    if ((e = a.fluxoFiles) != null && e.newValue) {
        const s = a.fluxoFiles.newValue;
        Te.setState({
            files: s
        })
    }
});
async function si(a, t, e, s) {
    var o, i;
    try {
        const n = Te.getState().files.find(p => p.nodeRefId === s);
        if (!(n != null && n.base64)) return;
        const r = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(p => p.type === "simulateWriting"),
            c = (r == null ? void 0 : r.propriedades) ?? {
                active: !1
            },
            l = te((i = e.globalSettings) == null ? void 0 : i.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 De(t, u, e), u = de(t, u, e), await m.Chat("sendImage", {
            id: t,
            base64: n.base64.toString(),
            msg: u
        })
    } catch (n) {
        throw console.error(`Erro ao enviar imagem para ${t}:`, n), n
    }
}
async function oi(a, t, e, s) {
    var o, i;
    try {
        const n = Te.getState().files.find(p => p.nodeRefId === s);
        if (!(n != null && n.base64)) return;
        const r = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(p => p.type === "simulateWriting"),
            c = (r == null ? void 0 : r.propriedades) ?? {
                active: !1
            },
            l = te((i = e.globalSettings) == null ? void 0 : i.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 De(t, u, e), u = de(t, u, e), await m.Chat("sendVideo", {
            id: t,
            base64: n.base64.toString(),
            msg: u
        })
    } catch (n) {
        throw console.error(`Erro ao enviar video para ${t}:`, n), n
    }
}
async function ii(a, t, e, s) {
    var o, i;
    try {
        const n = Te.getState().files.find(u => u.nodeRefId === s);
        if (!(n != null && n.base64)) return;
        const r = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(u => u.type === "simulateWriting"),
            c = (r == null ? void 0 : r.propriedades) ?? {
                active: !1
            },
            l = te((i = e.globalSettings) == null ? void 0 : i.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: n.base64.toString()
        })
    } catch (n) {
        throw console.error(`Erro ao enviar áudio para ${t}:`, n), n
    }
}
async function ni(a, t, e, s) {
    var o, i;
    try {
        const n = Te.getState().files.find(u => u.nodeRefId === s);
        if (!(n != null && n.base64)) return;
        const r = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(u => u.type === "simulateWriting"),
            c = (r == null ? void 0 : r.propriedades) ?? {
                active: !1
            },
            l = te((i = e.globalSettings) == null ? void 0 : i.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: n.base64.toString(),
            name: n.name
        })
    } catch (n) {
        throw console.error(`Erro ao enviar documento para ${t}:`, n), n
    }
}
async function ri(a, t, e, s) {
    var o, i;
    try {
        if (!(a != null && a.question)) return;
        const n = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(u => u.type === "simulateWriting"),
            r = (n == null ? void 0 : n.propriedades) ?? {
                active: !1
            },
            c = te((i = e.globalSettings) == null ? void 0 : i.blockTransitionDelay),
            l = typeof c == "number" && c > 0 ? c : 0;
        (r.active || l > 0) && await m.Chat("markIsComposing", {
            id: t,
            timer: l
        });
        let d = a.question;
        d = await De(t, d, e), d = de(t, d, e), await m.Chat("sendTxt", {
            id: t,
            msg: d
        })
    } catch (n) {
        throw console.error(`Erro ao enviar mensagem para ${t}:`, n), n
    }
}
async function ci(a, t, e, s) {
    var o, i;
    try {
        if (!(a != null && a.sections)) return;
        const {
            language: n
        } = I.getState(), r = (o = e == null ? void 0 : e.regras) == null ? void 0 : o.find(S => S.type === "simulateWriting"), c = (r == null ? void 0 : r.propriedades) ?? {
            active: !1
        }, l = te((i = e.globalSettings) == null ? void 0 : i.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 || `${n.escolhaUmaOpcao}`;
        u = await ke(t, u), p = await ke(t, p), A = await ke(t, A), v = await ke(t, v), u = de(t, u, e), p = de(t, p, e), A = de(t, A, e), v = de(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(E => ({
                    rowId: E.rowId,
                    title: E.title,
                    description: E.description || ""
                }))
            }))
        };
        await m.Chat("sendListMessage", {
            id: t,
            options: h
        })
    } catch (n) {
        throw console.error(`Erro ao enviar lista para ${t}:`, n), n
    }
}
const di = {
    "send-text": (a, t, e, s) => ai(a, t, e),
    "send-image": (a, t, e, s) => si(a, t, e, s),
    "send-video": (a, t, e, s) => oi(a, t, e, s),
    "send-audio": (a, t, e, s) => ii(a, t, e, s),
    "send-document": (a, t, e, s) => ni(a, t, e, s),
    "send-answers": (a, t, e, s) => ri(a, t, e),
    "send-list": (a, t, e, s) => ci(a, t, e)
};
let kt = 0;
const li = 1e4;
async function ne(a, t, e) {
    const {
        language: s
    } = I.getState(), {
        label: o
    } = re.getState(), {
        getSourceNode: i,
        updateVariableAsync: n
    } = T.getState(), {
        getLastMessage: r,
        isVariableUpdated: c,
        markVariableAsUpdated: l
    } = et.getState();
    if (a.type === "init") return;
    if (await ue("fluxo", !0)) {
        const h = Date.now();
        h - kt >= li && (kt = h, Je("fluxo", s.btnPremium, o.checkout));
        return
    }
    const d = a.type,
        u = di[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 = r(t),
        v = i(a.id, e.id);
    A && v && !c(t, v.id) && (await n(t, v.id, e.id, A), l(t, v.id)), await u(p, t, e, a.id)
}
const ui = .7,
    pi = 2,
    ve = a => a.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9\s]/g, "").replace(/\s+/g, " ").trim(),
    mi = (a, t) => {
        const e = Math.max(a.length, t.length);
        return e === 0 ? 1 : (e - Lt(a, t)) / e
    },
    Jt = (a, t) => {
        const {
            options: e,
            typeDetection: s,
            allowNumberDetection: o
        } = t, i = ve(a);
        let n = null;
        if (o) {
            const c = parseInt(i, 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 => ve(l.text) === i) || null;
            case "contains":
                let c = 0;
                if (e.forEach(l => {
                        const d = ve(l.text);
                        if (i.includes(d)) {
                            n = l;
                            return
                        }
                        const u = mi(i, d);
                        u > c && u >= ui && (c = u, n = l)
                    }), n) return n;
                break;
            case "startsWith":
                return e.find(l => i.startsWith(ve(l.text))) || null;
            case "endsWith":
                return e.find(l => i.endsWith(ve(l.text))) || null
        }
        let r = 1 / 0;
        return e.forEach(c => {
            const l = Lt(i, ve(c.text));
            l < r && l <= pi && (r = l, n = c)
        }), n
    },
    fi = (a, t) => a.send.data.waitTime ? te(a.send.data.waitTime) : null,
    gi = (a, t) => {
        const {
            getAllTargetNodes: e
        } = T.getState(), s = e(a.id, t.id).find(o => o.send.type === "timeout");
        return s || null
    },
    hi = async (a, t, e) => new Promise(s => {
        const o = async i => {
            if (i.data.type === "Ev" && i.data.action === "chat.new_message") {
                const n = JSON.parse(i.data.model);
                n.id.remote.toString() === a && !n.id.fromMe && (n.body && !ta(n.body) && et.getState().setLastMessage(a, n.body), window.removeEventListener("message", o), s(n))
            }
        };
        window.addEventListener("message", o)
    }), _t = async (a, t) => new Promise(e => {
        let s = !1,
            o, i;
        const n = r => {
            s || (s = !0, i && window.removeEventListener("message", i), clearTimeout(o), e(r))
        };
        o = setTimeout(() => n("timeout"), t), i = r => {
            if (r.data.type === "Ev" && r.data.action === "chat.new_message") {
                const c = JSON.parse(r.data.model);
                c.id.remote.toString() === a && !c.id.fromMe && (clearTimeout(o), o = setTimeout(() => n("timeout"), t))
            }
        }, window.addEventListener("message", i)
    }), vi = a => {
        var e, s;
        const t = ((s = (e = a.globalSettings) == null ? void 0 : e.absenceMessage) == null ? void 0 : s.waitTime) ?? null;
        return t ? te(t) : null
    }, je = async (a, t, e) => {
        var u, p;
        const s = fi(a),
            o = gi(a, e),
            i = (u = e.globalSettings) == null ? void 0 : u.absenceMessage,
            n = i && ((p = i.message) == null ? void 0 : p.trim()),
            r = n ? vi(e) : null,
            c = hi(t, a.id, e.id);
        if (!s && !r) return await c;
        const l = [c];
        if (s) {
            const A = _t(t, s).then(() => "node-timeout");
            l.push(A)
        }
        if (r) {
            const A = _t(t, r).then(() => "global-timeout");
            l.push(A)
        }
        const d = await Promise.race(l);
        if (d === "node-timeout") return o ? await Rt(o, t, e) : G.getState().resetUserProgress(t), null;
        if (d === "global-timeout") {
            if (n) {
                const A = {
                        message: i.message,
                        type: "send-text",
                        waitTime: i.waitTime
                    },
                    v = Yo("send-text", A);
                await Rt(v, t, e)
            } else G.getState().resetUserProgress(t);
            return null
        }
        return d
    }, Ai = async (a, t, e) => {
        const s = T.getState().getTargetNode(a.id, e.id);
        return s && G.getState().updateUserProgress(t, e.id, s.id), s
    }, Rt = async (a, t, e) => (await ne(a, t, e), G.getState().resetUserProgress(t), null), Kt = async (a, t, e) => {
        const s = a.data,
            {
                noMatch: o
            } = s,
            {
                sendPersonalizedMessage: i,
                endPersonalizedMessage: n,
                repeatBlock: r
            } = o || {};
        if (!(i != null && i.active) && !(n != null && n.active) && !r) return G.getState().resetUserProgress(t), null;
        if (n != null && n.active) {
            const l = {
                ...a,
                data: {
                    ...s,
                    question: n.personalizedMessage || ""
                }
            };
            return await ne(l, t, e), G.getState().resetUserProgress(t), null
        }
        const c = {
            ...a,
            data: {
                ...s,
                question: T.getState().getRetryQuestion(s)
            }
        };
        G.getState().updateUserProgress(t, e.id, c.id), await ne(c, t, e);
        try {
            const l = await je(a, t, e);
            if (l === null) return null;
            const d = l.body,
                u = Jt(d, s);
            if (u) {
                const p = T.getState().getTargetNodeByBestMatch(a.id, e.id, u.index);
                if (p) return G.getState().updateUserProgress(t, e.id, p.id), await ne(p, t, e), p
            }
            return !u && (r || i != null && i.active) ? await Kt(a, t, e) : (G.getState().resetUserProgress(t), null)
        } catch (l) {
            return console.error("Erro inesperado em handleNoMatchNode:", l), G.getState().resetUserProgress(t), null
        }
    }, bi = async (a, t, e) => {
        const s = T.getState().getSourceNode(a.id, e.id);
        return await je(s, t, e) === null ? null : (await ne(a, t, e), T.getState().getTargetNode(a.id, e.id))
    }, Si = async (a, t, e) => {
        const s = T.getState().getSourceNode(a.id, e.id);
        if (!s || s.type !== "send-answers") return null;
        const o = await je(s, t, e);
        if (o === null) return null;
        const i = o.body,
            n = s.data,
            r = Jt(i, n);
        if (!r) {
            const l = await Kt(s, t, e);
            return l ? T.getState().getTargetNode(l.id, e.id) : null
        }
        const c = T.getState().getTargetNodeByBestMatch(s.id, e.id, r.index);
        return c ? (await ne(c, t, e), T.getState().getTargetNode(c.id, e.id)) : null
    }, Qt = 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 je(s, t, e);
        if (o === null) return null;
        const i = s.data,
            n = i.sections.flatMap(u => u.rows.map(p => p.rowId)),
            r = (d = (l = o.listResponse) == null ? void 0 : l.singleSelectReply) == null ? void 0 : d.selectedRowId;
        if (!r || !n.includes(r)) {
            const {
                noMatch: u
            } = i, {
                repeatBlock: p
            } = u || {};
            if (p) return await ne(s, t, e), await Qt(a, t, e)
        }
        const c = T.getState().getTargetNodeByRowId(s.id, e.id, r);
        return c ? (G.getState().updateUserProgress(t, e.id, c.id), await ne(c, t, e), T.getState().getTargetNode(c.id, e.id)) : null
    }, wi = async (a, t, e) => (await ne(a, t, e), T.getState().getTargetNode(a.id, e.id));
async function yi({
    msg: a,
    manualActivation: t
}) {
    if (a.id.fromMe || !Ge.includes(a.type)) return;
    const e = a.id.remote.toString(),
        s = Gt.getState();
    if (Tt.getState().isProcessing(e)) return;
    const o = t ? [t.workflow] : T.getState().workflows.filter(i => i.active);
    if (o.length) {
        for (const i of o) {
            if (!Qo(i) || !t && !Ko(e, i) || !t && (!await Ho(a, i) || !await Jo(a, i))) continue;
            et.getState().resetUpdatedVariables(e);
            const n = G.getState(),
                r = Tt.getState(),
                c = i.nodes.find(d => d.type === "init");
            if (!c) continue;
            s.startSession(e, i.id);
            let l = n.getUserProgress(e);
            if ((!l || l.workflowId !== i.id) && (n.resetUserProgress(e), n.updateUserProgress(e, i.id, c.id), l = {
                    currentNodeId: c.id,
                    workflowId: i.id
                }), !r.isProcessing(e)) {
                r.addProcessingUser(e);
                try {
                    let d = i.nodes.find(u => u.id === l.currentNodeId);
                    if (!d) {
                        n.resetUserProgress(e), s.endSession(e);
                        continue
                    }
                    for (; d;) {
                        if (s.updateLastInteraction(e), d.type !== "init" && !t && !await Ht(a, i)) {
                            n.resetUserProgress(e), s.endSession(e), d = null;
                            break
                        }
                        switch (!0) {
                            case d.type === "init":
                                d = await Ai(d, e, i);
                                break;
                            case d.send.type === "timeout":
                                n.resetUserProgress(e), d = null;
                                break;
                            case d.send.type === "on-response":
                                d = await bi(d, e, i);
                                break;
                            case d.send.type === "next-block":
                                d = await wi(d, e, i);
                                break;
                            case /^on-response-\d+$/.test(d.send.type):
                                d = await Si(d, e, i);
                                break;
                            case /^on-response-[a-zA-Z0-9-]+$/.test(d.send.type):
                                d = await Qt(d, e, i);
                                break;
                            default:
                                d = null
                        }
                        if (d) n.updateUserProgress(e, i.id, d.id);
                        else {
                            n.resetUserProgress(e), s.updateLastInteraction(e);
                            break
                        }
                    }
                    n.resetUserProgress(e), s.updateLastInteraction(e)
                } catch {
                    n.resetUserProgress(e), s.endSession(e)
                } finally {
                    r.removeProcessingUser(e)
                }
            }
        }
        G.getState().resetUserProgress(e)
    }
}
const Ut = W.getState().dispartWebhook;
window.addEventListener("message", a => {
    if (a.data.type === "Ev" && a.data.action === "chat.new_message") {
        const t = JSON.parse(a.data.model);
        if (a.data.author && (t.author = a.data.author), Oo(t), yi({
                msg: t,
                manualActivation: null
            }), lo(t), Ut(t.from.replace(/@.*/g, ""), "messages", t), t.ctwaContext) {
            const e = t.from;
            Ut(e.replace(/@c\.us/g, ""), "metaAds")
        }
        t.id.fromMe && t.type === "chat" && !t.author && H.getState().filterAtendimento(t), z.getState().activeTab.type === "custom" && setTimeout(() => {
            tt.getState().chatListTabs()
        }, 1e3)
    }
});
const tt = b()(() => ({
    chatListTabs: async () => {
        const {
            activeTab: a,
            userTabs: t
        } = z.getState(), {
            selecionados: e
        } = Vt.getState();
        if ((a == null ? void 0 : a.type) !== "default-filter")
            if ((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", M.getState().user);
                    break;
                case 6:
                    await m.ListChat("trasferencias", M.getState().user);
                    break;
                default:
                    await m.ListChat("UserTabs", t.find(s => s.id === a.id).chats);
                    break
            } else a.type === "custom" ? m.ListChat("custom", {
                selecionados: e,
                user: M.getState().user
            }) : await m.ListChat("UserLabels", a.id)
    }
}));
async function Ci() {
    const {
        user: a
    } = M.getState(), t = await K("initDate");
    return t ? a.estado ? !1 : (Date.now() - t) / (1440 * 60 * 1e3) >= 3 : (f("initDate", Date.now()), !1)
}
const H = 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: i
            } = M.getState(), {
                assinatura: n,
                setMultiATendimento: r
            } = N.getState(), c = (h = (v = R.getState().activeChat) == null ? void 0 : v.id) == null ? void 0 : h._serialized, {
                openRendertype: l
            } = Z.getState(), d = y.getState().browserID;
            if (await Ci()) {
                l("user_free"), r();
                return
            }
            const p = na(Ie.webSocket["multi-atendimento"], {
                path: "/ws/socket.io",
                transports: ["websocket"]
            });
            p.open(), p.on("connection", null);
            const A = {
                id: "",
                user_id: d,
                whatsappID: e,
                userLogado: i.estado,
                email: i.login,
                assinaturaActive: n.active,
                assinatura: n.name,
                activeChat: c
            };
            p.emit("connect-atendente", A), m.MultiAtendimento("start"), s(c), o(p), a({
                socket: p,
                active: !0,
                unsubscribeUserLogin: M.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: i
            } = t(), {
                user: n
            } = M.getState(), {
                assinatura: r
            } = N.getState(), {
                whatsappID: c,
                browserID: l
            } = y.getState();
            if (i && o) {
                const d = {
                    ...o,
                    whatsappID: c,
                    userLogado: n.estado,
                    activeChat: e,
                    email: n.login,
                    assinaturaActive: r.active,
                    assinatura: r.name
                };
                s.emit("update-atendente", d), a({
                    atendente: d
                })
            }
        },
        active_atendentes: e => a(() => {
            var i, n;
            const s = (n = (i = R.getState().activeChat) == null ? void 0 : i.id) == null ? void 0 : n._serialized,
                {
                    whatsappID: o
                } = y.getState();
            return {
                multi_atendente: e,
                chatActive_atentendes: e.filter(r => r.whatsappID === o && r.activeChat === s)
            }
        }),
        send_atendimento: (e, s) => {
            const {
                whatsappID: o
            } = y.getState(), {
                socket: i,
                atendente: n,
                active: r
            } = t(), c = {
                chatID: e,
                whatsappID: o,
                atendente: n,
                status: s,
                dataUltimaInteracao: Date.now()
            };
            r && n && i.emit("update-atendimento", c)
        },
        trasferir_atendimento: (e, s, o) => {
            var u;
            const {
                socket: i,
                atendente: n
            } = t(), {
                user: r,
                _serialized: c
            } = (u = R.getState().activeChat) == null ? void 0 : u.id, {
                whatsappID: l
            } = y.getState(), d = {
                chatID: c,
                whatsappID: l,
                atendente: e,
                status: "Transferido",
                dataUltimaInteracao: Date.now()
            };
            i.emit("transferir_atendimento", {
                attID: e.id,
                remetenteID: n.id,
                chatID: r,
                text: s,
                urgencia: o
            }, d)
        },
        getMyAtendimento: () => {
            const {
                atendimentos: e
            } = H.getState(), {
                browserID: s
            } = y.getState();
            return e.filter(o => {
                var i;
                return ((i = o.atendente) == null ? void 0 : i.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
            } = fe.getState();
            e.on("connected-atentende", ({
                atendente: i,
                atendimentos: n
            }) => {
                var c, l;
                H.setState({
                    atendente: i
                }), m.MultiAtendimento("setAtendimento", {
                    atendimentos: n,
                    user: M.getState().user
                }), H.setState({
                    atendimentos: n
                });
                const r = (l = (c = R.getState().activeChat) == null ? void 0 : c.id) == null ? void 0 : l._serialized;
                s(r)
            }), e.on("active-atendentes", i => {
                H.getState().active_atendentes(i)
            }), e.on("active-atendimento", i => {
                m.MultiAtendimento("setAtendimento", {
                    atendimentos: i,
                    user: M.getState().user
                }), tt.getState().chatListTabs(), H.setState({
                    atendimentos: i
                })
            }), e.on("transferir_atendimento", i => {
                o(i)
            })
        },
        addLocalAtendente: (e, s) => a(o => {
            const {
                whatsappID: i
            } = y.getState(), {
                atendente: n
            } = t(), r = {
                chatID: e,
                whatsappID: i,
                atendente: n,
                status: s,
                dataUltimaInteracao: Date.now()
            }, c = o.atendimentos.filter(l => l.chatID !== e);
            return {
                atendimentos: [r, ...c]
            }
        })
    })),
    jn = async () => {
        const {
            connect: a
        } = H.getState(), {
            assinatura: t
        } = N.getState();
        if (t.multiAtendimento) {
            const {
                user: e
            } = await m.Conn("getMyDeviceId");
            a(e)
        }
    };
R.subscribe(a => {
    H.getState().update(a.activeChat.id._serialized)
});
const xi = (a, t) => {
        a.forEach(e => {
            e.addedNodes.forEach(s => {
                t(e)
            })
        })
    },
    Mi = a => {
        const {
            update: t
        } = H.getState(), {
            getElement: e
        } = V.getState(), {
            setIsOpen: s
        } = Se.getState();
        xi(a, o => {
            var n;
            const i = o.addedNodes[0];
            (i == null ? void 0 : i.id) === "main" ? s(!0): (n = i == null ? void 0 : i.classList) != null && n.contains(e("closeChat")) && (t("closeChat"), s(!1))
        })
    },
    Ti = a => {
        const {
            setIsThree: t
        } = Se.getState(), {
            getElement: e
        } = V.getState();
        a[0].target.classList.contains(e("two")) ? t(!1) : t(!0)
    },
    He = (a, t, e) => {
        new MutationObserver(t).observe(a, e)
    },
    Et = () => {
        const {
            getSeletor: a
        } = V.getState();
        a("menuLateral", t => {
            He(t, Mi, {
                childList: !0
            })
        }), a("waPage", t => {
            He(t, Ti, {
                attributes: !0
            })
        })
    };
aa(V.getState().getElement("paneSide"), () => {
    R.subscribe(() => {
        Et()
    }), Et(), V.getState().getSeletor("whatsModal", a => {
        He(a, t => {
            const {
                setIsOpen: e
            } = Se.getState();
            t[0].addedNodes.length > 0 ? e(!1) : e(!0)
        }, {
            childList: !0
        })
    })
});
const Se = 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 i = {
            ...o.menuContent,
            [e]: s
        };
        return J("MenuContentDB", "MenuContent", [i]), {
            menuContent: i
        }
    }),
    assinatura: {
        desativar: !1,
        personalizar: !1,
        nome: ""
    },
    setAssinatura: (e, s) => a(o => {
        let i = o.assinatura;
        return e === "desativar" && s ? i = {
            ...o.assinatura,
            desativar: !0,
            personalizar: !1
        } : e === "personalizar" && s ? i = {
            ...o.assinatura,
            personalizar: !0,
            desativar: !1
        } : i = {
            ...o.assinatura,
            [e]: s
        }, J("menulatera-assinatura", "assinatura", [i]), {
            assinatura: i
        }
    })
}));
(async () => {
    const a = await ee("MenuContentDB", "MenuContent");
    a && a[0] && a[0][0] && Se.setState({
        menuContent: a[0][0]
    });
    const t = await ee("menulatera-assinatura", "assinatura");
    t && t[0] && t[0][0] && Se.setState({
        assinatura: t[0][0]
    })
})();
const Yt = 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(i => i.id === e.id ? e : i);
        return f("respostasRapidasAcao", o), {
            actions: o
        }
    }),
    deleteActions: e => a(s => {
        const o = s.actions.filter(i => i.id !== e);
        return f("respostasRapidasAcao", o), {
            actions: o
        }
    }),
    edit: e => {
        const {
            actions: s
        } = t(), o = s.find(i => i.id === e);
        o && Bt.setState({
            acao: o.acao
        })
    },
    getAction: e => {
        const {
            actions: s
        } = t();
        return s.find(i => i.id === e).acao || []
    },
    sendAction: async (e, s, o) => {
        var u;
        const {
            actions: i
        } = t(), {
            activeChat: n
        } = R.getState(), {
            assinatura: r
        } = Se.getState(), {
            language: c
        } = I.getState(), {
            dispartWebhook: l
        } = W.getState();
        let d = [];
        if (e.type === "script")
            for (const [p, {
                    id: A,
                    timer: v
                }] of e.script.entries()) {
                const h = i.find(S => S.id === A);
                h && h.acao && (p > 0 && d.push({
                    id: F(),
                    propriedades: {
                        segundos: v
                    },
                    type: "timer"
                }), d.push(...h.acao))
            } else d = (u = i.find(p => p.id === e.id)) == null ? void 0 : u.acao;
        if (d && d.length > 0) {
            const p = s || n.id._serialized;
            await Xe(p, d, o || r, "useAcaoRespostaRapida"), l(p.replace(/@(?:g|c)\.us/g, ""), "respostaRapida", {
                id: e.id,
                type: e.type,
                name: e.titulo,
                categoria: e.categoria
            })
        } else j({
            type: "Error",
            message: c.createResNotAction,
            position: "top-right"
        })
    }
}));
chrome.runtime.onMessage.addListener(a => {
    switch (a.action) {
        case "sendAction-Res":
            Yt.getState().sendAction(a.dados.res, a.dados.userID);
            break
    }
});
const _ = 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
            } = I.getState(), s = _.getState().IA.keyGemini, o = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${s}`;
            try {
                await be.post(o, {
                    contents: [{
                        parts: [{
                            text: "hello"
                        }]
                    }]
                });
                const n = new ma(s).getGenerativeModel({
                    model: "gemini-2.0-flash"
                });
                t && j({
                    type: "Success",
                    message: e.useIAchaveAPI,
                    position: "top-right"
                });
                const r = {
                    ..._.getState().IA,
                    activeIA: "Gemini",
                    instanceGemini: n
                };
                _.setState({
                    IA: r
                }), f("IA", r)
            } catch (i) {
                _.setState({
                    IA: {
                        ..._.getState().IA,
                        activeIA: null,
                        instanceGemini: null
                    }
                }), i instanceof sa && i.status === 429 ? (console.error("Erro ao validar a chave Gemini:", i.status), j({
                    type: "Error",
                    message: e.useIAFreeTeste,
                    position: "top-right"
                })) : t && j({
                    type: "Error",
                    message: e.useIAchaveAPI,
                    position: "top-right"
                })
            }
        },
        validateGPTKey: (t = !0) => {
            const {
                language: e
            } = I.getState(), s = () => {
                const o = {
                    ..._.getState().IA,
                    activeIA: null,
                    instanceGPT: null
                };
                _.setState({
                    IA: o
                }), t && j({
                    type: "Error",
                    message: e.ChaveDaApiGPTInvalida,
                    position: "top-right"
                })
            };
            be.get("https://api.openai.com/v1/engines", {
                headers: {
                    Authorization: `Bearer ${_.getState().IA.keyGPT}`
                }
            }).then(() => {
                try {
                    const o = new fa({
                        apiKey: _.getState().IA.keyGPT || "",
                        dangerouslyAllowBrowser: !0
                    });
                    t && j({
                        type: "Success",
                        message: e.chaveGPTProntaParaUso,
                        position: "top-right"
                    });
                    const i = {
                        ..._.getState().IA,
                        activeIA: "GPT",
                        instanceGPT: o
                    };
                    _.setState({
                        IA: i
                    }), f("IA", i)
                } catch {
                    s()
                }
            }).catch(o => {
                s(), console.error("Erro ao realizar a ativação da key do gemini: " + o)
            })
        }
    })),
    On = async a => {
        switch (_.setState({
                IA: a
            }), a.activeIA) {
            case "Gemini":
                _.getState().validateGeminiKey(!1);
                break;
            case "GPT":
                _.getState().validateGPTKey(!1);
                break
        }
    }, Wn = async () => {
        const a = await K("IA") || [];
        switch (_.setState({
                IA: a
            }), a.activeIA) {
            case "Gemini":
                _.getState().validateGeminiKey(!1);
                break;
            case "GPT":
                _.getState().validateGPTKey(!1);
                break
        }
    }, $ = b()(a => ({
        assistente: {
            active: !1,
            model: "tradutor"
        },
        textAssistente: "",
        setAssistente: (t, e) => a(s => {
            const o = {
                ...s.assistente,
                [t]: e
            };
            J("useAssistente", "assistente", [o]), t === "active" && !s.assistente.active && $.getState().manipulatedInputText(), t === "model" && setTimeout(() => {
                $.getState().reloadText()
            }, 2500);
            const i = document.querySelector("main");
            return i && i.setAttribute("active-assistente-chat", String(o.active)), {
                assistente: {
                    ...s.assistente,
                    [t]: e
                }
            }
        }),
        formatTextAssistente: async t => {
            const e = await Ii(t);
            e.success && a({
                textAssistente: e.response
            })
        },
        manipulatedInputText: () => {
            const {
                getSeletor: t
            } = V.getState(), {
                activeChat: e
            } = R.getState();
            if (!e || !e.canSend) return;
            const s = t("footerTextArea");
            if (!s) return;
            let o = null;
            const i = () => {
                o && clearTimeout(o), o = setTimeout(() => {
                    const r = [...(s == null ? void 0 : s.childNodes) ?? []].map(c => c.innerText !== `
` ? c.innerText : "").join(`
`);
                    $.getState().formatTextAssistente(r)
                }, 3e3)
            };
            new MutationObserver(i).observe(s, {
                subtree: !0,
                childList: !0,
                attributes: !0
            }), s.addEventListener("copy", i), s.addEventListener("paste", i), s.addEventListener("cut", i), t("assChat", r => {
                const c = l => {
                    l.key === "Enter" && l.altKey && (l.stopPropagation(), $.getState().sendAssistenteMenssage())
                };
                r.addEventListener("keydown", c), setTimeout(() => {
                    r.scrollTop = r.scrollHeight
                }, 500)
            }), t("assInput", r => {
                r == null || r.addEventListener("keydown", c => {
                    c.key === "Enter" && c.altKey && (c.preventDefault(), c.stopPropagation(), $.getState().sendAssistenteMenssage())
                }, !0)
            })
        },
        reloadText: () => {
            const {
                getSeletor: t
            } = V.getState(), e = t("footerTextArea"), s = [...(e == null ? void 0 : e.childNodes) ?? []].map(o => o.innerText !== `
` ? o.innerText : "").join(`
`);
            $.getState().formatTextAssistente(s)
        },
        sendAssistenteMenssage: async () => {
            var n, r;
            const {
                assinatura: t
            } = N.getState(), e = (r = (n = R.getState().activeChat) == null ? void 0 : n.id) == null ? void 0 : r._serialized, {
                textAssistente: s
            } = $.getState(), {
                getSeletor: o
            } = V.getState();
            if (s.length === 0 || await ue("assistente_chat")) return;
            let i = s;
            t.active && (i = `*_${t.name}:_* 
${i}`), a({
                textAssistente: ""
            }), m.Functions("sendTextChat", {
                chatID: e,
                formattedMessage: i
            }), o("assEmoji", c => {
                c == null || c.click()
            }), o("assCitacao", c => {
                c == null || c.click()
            })
        }
    }));
R.subscribe(a => {
    $.setState({
        textAssistente: ""
    });
    const {
        assistente: t,
        manipulatedInputText: e
    } = $.getState();
    if (!t.active) return;
    const s = a.activeChat.draftMessage;
    s && s.text && s.text.length > 0 && $.getState().formatTextAssistente(s.text), e()
});
(async () => {
    const a = await ee("useAssistente", "assistente");
    a && a[0] && a[0][0] && $.setState({
        assistente: a[0][0]
    })
})();
const ki = async a => {
    const {
        instanceGPT: t
    } = _.getState().IA, {
        language: e
    } = I.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" && j({
            type: "Error",
            message: e.limiteDeUsoAtingidoOpenAI,
            position: "top-right"
        }), console.error(s), {
            success: !1,
            response: null
        }
    }
}, _i = async a => {
    const {
        instanceGemini: t
    } = _.getState().IA, s = (await t.generateContent(a)).response;
    return {
        success: !!(s && s.text()),
        response: s.text()
    }
};
async function at(a) {
    const {
        IA: t
    } = _.getState(), {
        openRendertype: e
    } = Z.getState(), {
        setAssistente: s
    } = $.getState(), {
        language: o
    } = I.getState();
    let i;
    switch (t.activeIA) {
        case "Gemini":
            i = await _i(a);
            break;
        case "GPT":
            i = await ki(a);
            break;
        default:
            e("Active_IA"), j({
                type: "Info",
                message: o.keyAPI_IA,
                position: "top-right"
            }), s("active", !1), i = {
                success: !1,
                response: ""
            };
            break
    }
    return i
}
async function Ri(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 at(t);
    return {
        success: e.success,
        response: e.success ? (() => {
            const s = /\[([^\]]*?)\]/g;
            return e.response.match(s)[0].slice(1, -1)
        })() : ""
    }
}
async function Ui(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 at(t);
    return {
        success: e.success,
        response: e.success ? (() => {
            const s = /\[([^\]]*?)\]/g;
            return e.response.match(s)[0].slice(1, -1)
        })() : ""
    }
}
async function Ei(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 at(e);
    return {
        success: s.success,
        response: s.success ? (() => {
            const o = /\[([^\]]*?)\]/g;
            return s.response.match(o)[0].slice(1, -1)
        })() : ""
    }
}
const Fi = async (a, t, e) => {
    const s = ["Traduza o texto para o idioma " + e];
    return await m.IA("text", {
        agente: a,
        question: t,
        context: s
    })
}, Li = 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
    })
}, Ni = 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
    })
}, Ii = async (a, t, e) => {
    const {
        assistente: s
    } = $.getState(), {
        activePerfil: o
    } = O.getState(), {
        IA: i
    } = _.getState();
    if (!i.activeIA || !a.trim()) return {
        success: !1,
        response: ""
    };
    let n;
    switch (t || s.model) {
        case "tradutor":
            const r = e || (o.idioma && o.idioma.length !== 0 ? o.idioma : "English");
            i.activeIA === "system" ? n = await Fi(i.agenteIA, a, r) : n = await Ei(r, a);
            break;
        case "corretor_ortografico":
            i.activeIA === "system" ? n = await Li(i.agenteIA, a) : n = await Ri(a);
            break;
        case "otimizador_texto":
            i.activeIA === "system" ? n = await Ni(i.agenteIA, a) : n = await Ui(a);
            break
    }
    return n
}, qi = {
    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 "
}, Xt = b()((a, t) => ({
    variaveisWA: qi,
    isNewModel: !0,
    setIsNewModel: e => {
        a({
            isNewModel: e
        });
        const s = document.querySelector("main");
        s && s.setAttribute("isNewModel", String(t().isNewModel))
    }
}));
async function Bn() {
    const {
        domSelector: a
    } = V.getState(), {
        setIsNewModel: t
    } = Xt.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, "")),
                i = BigInt(e.parm.replace(/\./g, ""));
            o >= i ? t(!0) : t(!1);
            break;
        case "all":
            t(!0);
            break
    }
}
const Pi = b()(a => ({
    modalOptions: null,
    options: {},
    childrenRef: null,
    offset: 0,
    auxFunc: {
        mounted: null,
        desmouted: null
    },
    open: (t, e, s, o = 10, i = {
        mounted: null,
        desmouted: null
    }) => a(n => (i.mounted && i.mounted(), n.childrenRef !== null && n.auxFunc.desmouted && n.auxFunc.desmouted(), {
        modalOptions: t,
        options: e,
        childrenRef: s,
        offset: o,
        auxFunc: i
    })),
    close: () => a(t => (t.auxFunc.desmouted && t.auxFunc.desmouted(), {
        modalOptions: null,
        childrenRef: null,
        options: {}
    }))
}));

function Vn() {
    const {
        modalOptions: a,
        options: t,
        childrenRef: e,
        offset: s,
        close: o
    } = Pi(), {
        variaveisWA: i
    } = Xt(), {
        refs: n,
        floatingStyles: r,
        update: c,
        elements: l
    } = ra({
        ...t,
        middleware: [da({
            padding: 5
        }), la({
            padding: 5
        }), ua({
            apply({
                availableWidth: d,
                availableHeight: u,
                elements: p
            }) {
                Object.assign(p.floating.style, {
                    maxWidth: `${d}px`,
                    maxHeight: `${u}px`
                })
            }
        }), pa(s)]
    });
    return k.useEffect(() => {
        if (a && l.reference && l.floating) return ca(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"]');
            n.floating.current && !n.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 && (n.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: n.setFloating,
            role: "tooltip",
            className: "z-[9999]",
            style: r,
            children: g.jsx("div", {
                className: i.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: i.modalOptions.content2,
                    children: g.jsx("div", {
                        className: i.modalOptions.content3,
                        children: a
                    })
                })
            })
        })
    })
}
export {
    So as $, Xt as A, Se as B, Go as C, Vo as D, Yt as E, eo as F, uo as G, Eo as H, Bn as I, Mt as J, xt as K, Lo as L, Ro as M, ge as N, Me as O, ko as P, Ct as Q, Fo as R, Ze as S, Uo as T, yt as U, To as V, Mo as W, xo as X, Co as Y, yo as Z, wo as _, nn as a, Vt as a$, bo as a0, Ao as a1, vo as a2, ho as a3, wa as a4, Ia as a5, $ as a6, rn as a7, an as a8, Vn as a9, ba as aA, fn as aB, hn as aC, xe as aD, Bt as aE, Pn as aF, zn as aG, Fn as aH, co as aI, tn as aJ, Nn as aK, _o as aL, On as aM, en as aN, dn as aO, to as aP, Yi as aQ, ga as aR, un as aS, oo as aT, Ve as aU, Ce as aV, pe as aW, Le as aX, me as aY, Ne as aZ, Xi as a_, on as aa, En as ab, kn as ac, N as ad, _ as ae, ka as af, H as ag, fe as ah, Sn as ai, Un as aj, Rn as ak, ro as al, bt as am, bn as an, ao, jo as ap, Ii as aq, ue as ar, Xe as as, Zs as at, An as au, qe as av, B as aw, wn as ax, O as ay, Mn as az, z as b, _n as b0, Cn as b1, Tn as b2, T as b3, yi as b4, Xs as b5, vn as b6, xn as b7, yn as b8, cn as b9, mn as ba, gn as bb, X as c, W as d, Qi as e, Ki as f, ln as g, qn as h, sn as i, Dn as j, Zi as k, Wn as l, Ln as m, M as n, Z as o, Pi as p, re as q, ie as r, io as s, In as t, C as u, pn as v, jn as w, Wt as x, R as y, V as z
};