import {
    S as J,
    C as Ae,
    U as le,
    W as z,
    G as ee,
    R as K,
    g as f,
    r as E,
    _ as ce,
    j as g,
    I as j,
    E as Q,
    O as ea,
    h as ta,
    P as M,
    f as Oe,
    N as Je,
    i as vt,
    k as aa,
    w as sa
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec510.js";
import {
    a as be,
    A as oa
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec56.js";
import {
    a as k
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec54.js";
import {
    X as Ft,
    G as U
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec58.js";
import {
    c as b
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec57.js";
import {
    V as Ie,
    W as m
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec518.js";
import {
    g as ia,
    r as na
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec5.js";
import {
    d as Nt,
    l as ra,
    u as ca,
    b as da,
    f as la,
    s as ua,
    c as pa,
    o as ma
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec59.js";
import {
    b as y,
    u as I
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec519.js";
import {
    G as fa
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec52.js";
import {
    O as ga
} from "./v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec53.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: ""
        },
        videos_tutoriais: {
            resposta_rapida: "",
            mensagens_agendadas: "",
            envio_em_massa: "",
            status: "",
            auto_atendimento: "",
            fluxo: "",
            follow_up: "",
            api: "",
            webhook: ""
        }
    },
    setLabel: e => {
        a({
            label: e
        });
        const s = document.querySelector("main");
        s && s.setAttribute("plugin-ico-color", String(t().label.cor_primaria))
    }
}));
async function Qi() {
    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: ""
                },
                videos_tutoriais: {
                    resposta_rapida: "",
                    mensagens_agendadas: "",
                    envio_em_massa: "",
                    status: "",
                    auto_atendimento: "",
                    fluxo: "",
                    follow_up: "",
                    api: "",
                    webhook: ""
                }
            };
            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 Le = {
        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: Le,
        setUserFreeLimity: t => {
            J("wpp-functions", "functions", [Ae.encryptData(t)]), a(e => ({
                ...e,
                userFreeLimity: t
            }))
        },
        setUserFreeLimityPluginPage: () => a(t => ({
            ...t,
            plugin_page: !0
        }))
    })),
    It = a => {
        var s;
        if (x.getState().user.estado) return !1;
        const t = Ue.getState().userFreeLimity;
        if (le.subtrData(t.date.old) > 1) {
            const o = {
                ...Le
            };
            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] = Le[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 ? x.getState().user.estado ? e = !1 : e = await z("exe-CheckUserFreeLock", a) : e = It(a), e && !t && Z.getState().openRendertype("user_free"), e
    }, Yi = async () => {
        let a = Le;
        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(It(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 ? z("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 ha = async a => {
    O.setState({
        perfil: a
    }), await f("perfil", a), chrome.runtime.sendMessage({
        action: "BackupPerfil"
    })
}, Xi = 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);
    ha(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 qt = [{
        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: qt,
        sent: []
    },
    Zi = ["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: qt,
                    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 = x.getState().user.login;
            if (y.getState().plugin_page) {
                va(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 || E(),
                    status: !!p,
                    code: d,
                    userID: t,
                    date: `${A.day}/${A.month}/${A.year} as ${v.hours}:${v.minutes}:${v.seconds}`
                };
            s && (h.eventDetails = s), a(o ? S => {
                const L = S.webhook.map(w => {
                    if (w.id === e) {
                        const F = w.sent.map(ae => ae.id === o ? h : ae);
                        return {
                            ...w,
                            sent: F
                        }
                    }
                    return w
                });
                return f("webhook", L), {
                    activeHook: L.find(w => w.id === e),
                    webhook: L
                }
            } : S => {
                const L = S.webhook.map(w => {
                    if (w.id === e) {
                        const F = w.sent;
                        return F.length >= 30 && F.pop(), {
                            ...w,
                            sent: [h, ...F]
                        }
                    }
                    return w
                });
                return f("webhook", L), {
                    activeHook: L.find(w => w.id === e),
                    webhook: L
                }
            })
        }
    })),
    en = 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
        })
    }, tn = a => {
        f("webhook", a);
        const t = a.find(e => e.id === "metaAds") || Ke;
        W.setState({
            activeHook: t,
            webhook: a
        })
    }, va = (a, t, e, s) => {
        z("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)
    }, Aa = {
        trasferirAtendimento: {
            text: "",
            active: !1
        },
        finalizarAtendimento: {
            text: "",
            active: !1,
            arquivar: !1
        }
    }, fe = b()(a => ({
        atendimento: Aa,
        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 ? z("serviceCompleted", t) : W.getState().dispartWebhook(t, "serviceCompleted", {
                    type: "Finalizado"
                }), e.finalizarAtendimento.active) {
                const o = `*_Atendimento Finalizado_* 
 ` + e.finalizarAtendimento.text;
                m.Chat("sendTxt", {
                    id: t,
                    msg: o
                })
            }
            e.finalizarAtendimento.arquivar && m.Chat("arquivar", t)
        },
        trasferirAtendimento: (t, e) => {
            const {
                atendimento: s
            } = fe.getState(), {
                plugin_page: o
            } = y.getState();
            if (bt(), o ? z("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 an = a => {
        fe.setState({
            atendimento: a
        }), f("atendimento", a)
    },
    ba = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec548.js")), []));

function Sa() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(ba, {})
    })
}
const wa = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec549.js")), []));

function ya() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(wa, {})
    })
}
const Ca = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec550.js")), []));

function xa() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Ca, {})
    })
}
const Ma = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec551.js")), []));

function Ta() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Ma, {})
    })
}
const ka = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec552.js")), []));

function _a() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(ka, {})
    })
}
const Ra = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec553.js")), []));

function Ua() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(Ra, {})
    })
}
const La = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec554.js")), []));

function Ea() {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(La, {})
    })
}
const Fa = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec555.js")), []));

function Na() {
    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(ya, {});
                break;
            case "user_free":
                i = g.jsx(Ta, {});
                break;
            case "access_duplicate":
                i = g.jsx(xa, {});
                break;
            case "receive_atendimento":
                i = g.jsx(Ea, {});
                break;
            case "Modelo_Selecao":
                i = g.jsx(Ua, {});
                break;
            case "ModalLeads":
                i = g.jsx(Na, {});
                break;
            case "assinatura":
                i = g.jsx(Sa, {});
                break;
            case "login":
                i = g.jsx(_a, {});
                break
        }
        Z.getState().open(i, e, s, o)
    }
}));

function sn() {
    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 Ia(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 qa = () => {
        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
        }
    },
    Pa = 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: qa()
        }
    }, Pt = 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 Pa(a);
            be.post(t.webhook_login_clients, i, {
                headers: {
                    "Content-Type": "application/json"
                }
            }), localStorage.setItem("8fd5ad24df1e1b800d670e563b1b83591980060a==", new Date().toISOString())
        }
    }, Ee = {
        realizou_login: !1,
        estado: !1,
        login: "",
        senha: "",
        token: ""
    }, x = b()(a => ({
        user: Ee,
        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 = {
                ...Ee,
                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
        })
    })), zt = async a => {
        const {
            language: t
        } = I.getState(), {
            label: e
        } = re.getState(), {
            setUser: s
        } = x.getState(), {
            openRendertype: o
        } = Z.getState();
        if (!a.estado) {
            a.realizou_login && o("login");
            return
        }
        const i = await Ia({
            email: a.login,
            token: a.token,
            chromeStoreID: e.chromeStoreID
        });
        i.success ? s(a) : (s(Ee), 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")))
    }, on = async () => {
        let a = Ee;
        const t = await ee("wpp-client", "client");
        t[0] && t[0][0] && (a = Ae.decryptData(t[0][0])), zt(a), Pt(a)
    };
chrome.runtime.onMessage.addListener(async a => {
    a.action === "get-user" && chrome.runtime.sendMessage({
        action: a.action,
        response: JSON.stringify(x.getState().user),
        id: a.id
    }), a.action === "post-user" && y.getState().plugin_page && x.getState().setUserPluginPage(a.user), a.action === "license_update" && (Pt(x.getState().user), x.getState().user.estado && zt(x.getState().user))
});
const za = k.lazy(() => __vitePreload(() => import(chrome.runtime.getURL("content/assets/js/v_7_4_2_12_5cc5c70e-17b9-46d5-a61c-750829962ec556.js")), []));

function St({
    notificacao: a
}) {
    return g.jsx(k.Suspense, {
        fallback: g.jsx(g.Fragment, {}),
        children: g.jsx(za, {
            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
        } = x.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
        } = x.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
        } = x.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 nn() {
    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 Da = 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
    })
}, ja = 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
    })
}, Oa = async ({
    id: a = E(),
    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
    })
}, Wa = 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
    })
}, 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,
            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
    })
}, 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,
            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
    })
}, $a = 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
    })
}, Dt = 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
    })
}, jt = 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
}, Ot = 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
    })
}, Ga = (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
    })
}, Ha = (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
    })
}, Ja = (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
    })
}, Ka = (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
    })
}, Qa = ea({
    setCrm: a => {
        Wa(a.data, !0)
    },
    editCrm: a => {
        const {
            crmID: t,
            name: e,
            desc: s,
            hexColor: o
        } = a.data;
        Da(t, e, s, o, !0)
    },
    removeCrm: a => {
        ja(a.data, !0)
    },
    addNewTabCRM: a => {
        Oa(a.data, !0)
    },
    editTabCRM: a => {
        const {
            crmID: t,
            abaID: e,
            name: s
        } = a.data;
        Ba(t, e, s, !0)
    },
    removeChatTabCRM: a => {
        const {
            crmID: t,
            abaID: e,
            chatID: s
        } = a.data;
        Va(t, e, s, !0)
    },
    changeColorTabCRM: a => {
        const {
            crmID: t,
            abaID: e,
            hexColor: s
        } = a.data;
        $a(t, e, s, !0)
    },
    setRemoveUserCRM: a => {
        const {
            userID: t,
            isAll: e,
            crmID: s,
            abaID: o
        } = a.data;
        Dt(t, e, s, o, !0)
    },
    setNewUserCRM: a => {
        const {
            userID: t,
            crmID: e,
            abaID: s,
            insertPosition: o
        } = a.data;
        Ot(t, e, s, o, !0)
    },
    moveUserTabCRM: a => {
        const {
            chat: t,
            source: e,
            destination: s,
            insertPosition: o,
            duplicate: i
        } = a.data;
        Ga(t, e, s, o, i, !0)
    },
    orderUserInTabCRM: a => {
        const {
            crmID: t,
            columnID: e,
            indexHome: s,
            indexDestination: o
        } = a.data;
        Ha(t, e, s, o, !0)
    },
    sortUserTabsCRM: a => {
        const {
            crmID: t,
            indexHome: e,
            indexDestination: s
        } = a.data;
        Ja(t, e, s, !0)
    },
    deleteTabCRM: a => {
        const {
            crmID: t,
            abaID: e
        } = a.data;
        Ka(t, e, !0)
    }
});
chrome.runtime.onMessage.addListener(Qa);
const C = b()(() => ({
        crm: []
    })),
    Ya = "1.7",
    Xa = "",
    Za = "true",
    es = "true",
    ts = {
        timer: "60000",
        enable_two_send: !1
    },
    as = {
        model: "taghtml",
        parm: "body.color-refresh"
    },
    ss = {
        model: "querySelector",
        selector: ["#app"]
    },
    os = {
        model: "querySelector",
        selector: ["body > div"]
    },
    is = {
        model: "Element",
        selector: "#pane-side"
    },
    ns = {
        model: "querySelector",
        selector: ["#app > div > div ._aigs"]
    },
    rs = {
        model: "Element",
        selector: "two"
    },
    cs = {
        model: "querySelector",
        selector: [".two._aigs > div:nth-child(5)"]
    },
    ds = {
        model: "Element",
        selector: "x10l6tqk"
    },
    ls = {
        model: "querySelector",
        selector: [".lexical-rich-text-input > div"]
    },
    us = {
        model: "querySelector",
        selector: ["[data-icon='search']"]
    },
    ps = {
        model: "querySelector",
        selector: ["header > div > div > div > div > span > div > div:nth-child(1)", "header > div._ak0w"]
    },
    ms = {
        model: "querySelector",
        selector: ["header > header > div > span > div"]
    },
    fs = {
        model: "querySelector",
        selector: ["#side > div._ak9t > div"]
    },
    gs = {
        model: "querySelector",
        selector: ["#main > header > div.xeuugli > div > div"]
    },
    hs = {
        model: "querySelector",
        selector: ["#main ._amm9", "#main .x1n2onr6.x1vjfegm.x1cqoux5.x14yy4lh"]
    },
    vs = {
        model: "querySelector",
        selector: ["#main > header :nth-child(3) div"]
    },
    As = {
        model: "querySelector",
        selector: ["footer ._ak1m"]
    },
    bs = {
        model: "querySelector",
        selector: ["footer > div"]
    },
    Ss = {
        model: "querySelector",
        selector: ["footer div[contenteditable=true]"]
    },
    ws = {
        model: "querySelector",
        selector: ["footer > div.copyable-area > div"]
    },
    ys = {
        model: "querySelector",
        selector: ["#main > div.x1n2onr6.x1vjfegm.x1cqoux5.x14yy4lh"]
    },
    Cs = {
        model: "querySelector",
        selector: ["._1VZX7 ._3Uu1_, ._ak1r > div"]
    },
    xs = {
        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"]
    },
    Ms = {
        model: "querySelector",
        selector: ["#main > footer > div.copyable-area > div > span > div > div._ak1m > div > button[tabindex='-1']"]
    },
    Ts = {
        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"]
    },
    ks = {
        model: "querySelector",
        selector: ["#main > div.x1n2onr6.x1vjfegm.x1cqoux5.x14yy4lh > div > div.x10l6tqk.x13vifvy"]
    },
    _s = {
        model: "querySelectorAll",
        selector: ["#main div > div[data-id]"]
    },
    Rs = {
        model: "querySelector",
        selector: ["#main > footer"]
    },
    Us = {
        model: "querySelector",
        selector: ["#side div[tabindex='-1']"]
    },
    Ls = {
        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"]
    },
    Ns = {
        model: "querySelectorAll",
        selector: ["#pane-side > div > div > div > div  div[aria-selected]", "#pane-side > div > div > div div[role='button'] > div"]
    },
    Is = {
        model: "Element",
        selector: "div._ak8l > div._ak8j > div._ak8i"
    },
    qs = {
        model: "Element",
        selector: "x10l6tqk xh8yej3 x1g42fcv"
    },
    Ps = {
        model: "Element",
        selector: "__reactFiber"
    },
    zs = {
        model: "querySelector",
        selector: ["#side div._ai04 > button"]
    },
    Ds = {
        model: "listElement",
        list: {
            main_audio_1: "div._amk6._amlo",
            main_audio_2: "div._ak49._ak48",
            camp_text_1: "row-translate",
            camp_text_2: "span.selectable-text",
            add_btn_tradutor: "div.x1c4vz4f.x1q0g3np.x6s0dn4._amj_",
            camp_audio_1: 'div[role="slider"] > canvas',
            camp_audio_2: 'div[role="slider"] div._ahwf'
        }
    },
    js = {
        model: "querySelector",
        selector: ["div.two._aigs > div._aigw"]
    },
    Os = {
        model: "querySelector",
        selector: ["#main > span:nth-child(8)", "#main > :last-child"]
    },
    Ws = {
        model: "querySelector",
        selector: ["#main > span:nth-child(7)", "#main > span:nth-child(8)", "#main > span:nth-child(9)"]
    },
    Bs = {
        model: "querySelector",
        selector: ["#app > div > div > span:nth-child(4)", "#app > div > span:nth-child(4)"]
    },
    Vs = {
        model: "querySelector",
        selector: ["#app > div > div.x78zum5.xdt5ytf.x5yr21d > div > header > div > div:nth-child(2) > div", "header > div > div:nth-child(2) > div"]
    },
    $s = {
        model: "querySelector",
        selector: ["#main header"]
    },
    Gs = {
        model: "querySelector",
        selector: ["#main > footer > div > div > span > div > div._ak1r > div"]
    },
    Hs = {
        model: "querySelector",
        selector: ["#side"]
    },
    Js = {
        model: "listElement",
        list: {
            div_filters: "_akap _akan _arj9"
        }
    },
    Ks = {
        model: "querySelectorAll",
        selector: ["#side > div:nth-of-type(2) div[role=tab]", "#side > div:nth-of-type(2) button"]
    },
    Qs = {
        version: Ya,
        update_path: Xa,
        update_path_active: Za,
        disabeldOldMenu: es,
        wpp_mensagens: ts,
        newModel: as,
        app: ss,
        afiliadoMain: os,
        paneSide: is,
        waPage: ns,
        two: rs,
        menuLateral: cs,
        closeChat: ds,
        chatListInput: ls,
        searchInput: us,
        downAba: ps,
        chatListHeader: ms,
        searchCamp: fs,
        chatName: gs,
        menuVertical: hs,
        menuHorizontal: vs,
        menuFooter: As,
        respostaRapida: bs,
        footerTextArea: Ss,
        mainAudio: ws,
        assChat: ys,
        assInput: Cs,
        assBtn: xs,
        assEmoji: Ms,
        assCitacao: Ts,
        listMensages: ks,
        allMensages: _s,
        assistenteChat: Rs,
        trasferidos: Us,
        notification: Ls,
        quotedMsg: Es,
        listChats: Fs,
        listChatsUsers: Ns,
        listChatAtendimento: Is,
        insertAtendente: qs,
        reactFiber: Ps,
        updateChatList: zs,
        useTradutor: Ds,
        chatList: js,
        observerFooter: Os,
        observerFooterNewModel: Ws,
        whatsModal: Bs,
        menu_whats: Vs,
        actionMonitor: $s,
        footerIconsLeft: Gs,
        side: Hs,
        chatFiltersContainer: Js,
        chatFilters: Ks
    },
    V = b()((a, t) => ({
        domSelector: Qs,
        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") {
                    if (c = document.querySelector(r), c) {
                        n = c, s(c);
                        break
                    }
                } else if (i.model === "querySelectorAll" && (c = document.querySelectorAll(r), c && c.length > 0)) {
                    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 Ys = {
        crm: !0,
        quick_replies: !1,
        env_massa: !0,
        ia: !0,
        calendar: !0,
        flow: !0,
        funnil_crm: !0,
        att_atendimento: !0,
        follow_up: !0,
        status: !0,
        api: !0,
        webhook: !0,
        links: !0,
        start_chat: !0,
        afiliate_link: !0,
        google_funcs: !0
    },
    Xs = {
        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
    },
    Wt = () => {
        const {
            label: a
        } = re.getState();
        return a.chromeStoreID == "gjlfpggiddcminhebiejofeglfjmleli" ? Xs : Ys
    },
    Bt = 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: Wt(),
        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
        }))
    })),
    rn = async () => {
        let a = !0;
        const t = localStorage.getItem("active-view-menu");
        t && t == "false" && (a = !1);
        let e = Wt();
        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]), Bt.setState({
            activeView: a,
            activeMenu: e,
            tema: o,
            chatsIA: n
        })
    }, cn = () => {
        const {
            setActiveView: a,
            setActiveHeader: t
        } = Bt.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: E(),
            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: E(),
                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: E(),
                    type: t
                }]
            }
        })),
        setRemoveAcionamento: t => a(e => ({
            activeAutoAtt: {
                ...e.activeAutoAtt,
                acionamento: e.activeAutoAtt.acionamento.filter(s => s.id !== t)
            }
        })),
        setAcionamentoText: (t, e) => a(s => {
            const o = s.activeAutoAtt.acionamento.map(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: E(),
                    type: t,
                    propriedades: e
                }]
            }
        })),
        setRemoveAcao: t => a(e => ({
            activeAutoAtt: {
                ...e.activeAutoAtt,
                acao: e.activeAutoAtt.acao.filter(s => s.id !== t)
            }
        })),
        setAcaoPropriedades: (t, e) => a(s => ({
            activeAutoAtt: {
                ...s.activeAutoAtt,
                acao: s.activeAutoAtt.acao.map(o => o.id === t ? {
                    ...o,
                    propriedades: {
                        ...o.propriedades,
                        ...e
                    }
                } : o)
            }
        })),
        sortAcoes: t => a(e => {
            const s = [...e.activeAutoAtt.acao],
                o = Array.from(s),
                [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
            } = Fe.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: E(),
            nome: "",
            active: !0,
            funil: {
                id: E(),
                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: E(),
                nome: "",
                active: !0,
                funil: {
                    id: E(),
                    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: E(),
            abas: [],
            etiquetas: []
        }), {
            model: "Edit",
            activeFollowUp: e,
            activeColapse: "funil"
        })),
        setTimingAcionamento: e => a(s => ({
            activeFollowUp: {
                ...s.activeFollowUp,
                acionamento: {
                    ...s.activeFollowUp.acionamento,
                    timing: e
                }
            }
        })),
        setDispararAcionamento: e => a(s => ({
            activeFollowUp: {
                ...s.activeFollowUp,
                acionamento: {
                    ...s.activeFollowUp.acionamento,
                    type: e
                }
            }
        })),
        setCreateAcao: (e, s = {}) => a(o => ({
            activeFollowUp: {
                ...o.activeFollowUp,
                acao: [...o.activeFollowUp.acao, {
                    id: E(),
                    type: e,
                    propriedades: s
                }]
            }
        })),
        setRemoveAcao: e => a(s => ({
            activeFollowUp: {
                ...s.activeFollowUp,
                acao: s.activeFollowUp.acao.filter(o => o.id !== e)
            }
        })),
        setAcaoPropriedades: (e, s) => a(o => ({
            activeFollowUp: {
                ...o.activeFollowUp,
                acao: o.activeFollowUp.acao.map(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: E(),
                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)
                    })
                }
            })
        }))
    })), Vt = ye(we.useAcaoRespostaRapida), Fe = ye(we.useAcaoAutoAtendimento), Ne = ye(we.useAcaoFollowUp), Zs = ye(we.useAcaoEditAndSendRes), eo = ye(we.useAcaoEnvioEmMassa), to = ye(we.useAcaoEnvioEmMassaNew), dn = {
        useAcaoRespostaRapida: Vt,
        useAcaoAutoAtendimento: Fe,
        useAcaoFollowUp: Ne,
        useAcaoEditAndSendRes: Zs,
        useAcaoEnvioEmMassa: eo,
        useAcaoEnvioEmMassaNew: to
    }, Ce = b()(a => ({
        autoAtendimento: [],
        createAutoAtendimento: t => a(e => {
            const {
                acao: s
            } = Fe.getState(), i = [{
                ...t,
                acao: s
            }, ...e.autoAtendimento];
            return f("autoatendimento", i), {
                autoAtendimento: i
            }
        }),
        editAutoAtendimento: t => a(e => {
            const {
                acao: s
            } = Fe.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: E(),
                    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
            }
        })
    })), ao = a => {
        Ce.setState({
            autoAtendimento: a
        }), f("autoatendimento", a)
    }, ln = 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))
        }), ao(t)
    }, un = async () => {
        const a = await K("autoatendimento") || [];
        Ce.setState({
            autoAtendimento: a
        })
    }, so = 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 oo = na();
const Ve = ia(oo),
    xe = b(a => ({
        contatos: [],
        setContatos: async t => (await f("contatos", t), y.getState().plugin_page ? z("setContatos", {
            contatos: t
        }, !1) : chrome.runtime.sendMessage({
            action: "setContatos",
            dados: {
                contatos: t
            }
        }), a(() => ({
            contatos: t
        })), {
            contatos: t
        })
    })),
    io = async a => {
        xe.setState({
            contatos: a
        }), m.Utils("contatoInit", a), await f("contatos", a), chrome.runtime.sendMessage({
            action: "contatos-backup-update"
        })
    }, pn = 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
        }), io(t)
    }, no = async () => {
        const a = await K("contatos") || [];
        m.Utils("contatoInit", a), xe.setState({
            contatos: a
        })
    }, {
        setContatos: ro
    } = 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) && (ro(t.contatos), m.Utils("contatoInit", t.contatos))
            });
            break;
        case "contatos-backup-update":
            no();
            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 mn = async () => {
    const a = await ee("useAssinatura", "assinatura");
    a && a[0] && a[0][0] && N.setState({
        assinatura: a[0][0]
    })
};

function co(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 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: "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 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: "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 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: "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 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: "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 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: "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 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 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 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: "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 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: "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 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-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 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-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 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: "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 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: "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 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 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 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: "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 _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: "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 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: "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 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: "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 Ln(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;
            ta({
                icon: g.jsx(co, {
                    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: E(),
                    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
            }
        })
    })),
    lo = 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))
        }), lo(t)
    },
    Nn = async () => {
        try {
            const a = await K("FollowUp") || [];
            X.setState({
                FollowUp: a
            })
        } catch (a) {
            console.error("Failed to initialize FollowUp:", a)
        }
    };

function uo(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 po = 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 mo = async (a, t) => {
    let e = "";
    return (t.includes("#nome") || t.includes("#primeiroNome")) && (e = (await m.Utils("getContato", a)).name), e
}, fo = () => {
    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]
}, go = () => {
    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 mo(a, t);
    try {
        t = t.replaceAll("#saudação", fo), t = t.replaceAll("#periodo-dia", go), 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 ho = 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", ho(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 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("sendTxt", {
        id: a,
        msg: o,
        mentionedList: s
    });
    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("sendImage", {
        id: a,
        msg: o,
        mentionedList: s,
        base64: t.base64,
        isViewOnce: t.isViewOnce
    });
    return await Me(t.aguarde), i
}
async function bo(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 So(a, t) {
    return await ge(a, t.composing, "audio"), await m.Chat("sendAudio", {
        id: a,
        base64: t.base64
    })
}
async function wo(a, t) {
    return await m.Chat("sendDoc", {
        id: a,
        base64: t.base64,
        name: t.base64Name
    })
}
async function yo(a, t) {
    return await m.Chat("sendPixKeyMessage", {
        id: a,
        keyType: t.keyType,
        name: t.name,
        key: t.key
    })
}
async function Co(a, t) {
    return await m.Chat("sendGroupInviteMessage", {
        id: a,
        groupID: t.groupID
    })
}
async function xo(a, t) {
    return await m.Chat("sendContact", {
        id: a,
        phone: t.userID,
        name: t.userName
    })
}
async function Mo(a, t) {
    return await m.Chat("linkPreview", {
        id: a,
        link: t.link,
        title: t.title,
        description: t.description
    })
}
async function To(a, t) {
    return await m.Chat("sticker", {
        id: a,
        base64: t.base64
    })
}
async function ko(a, t, e) {
    const {
        setNewUser: s
    } = q.getState();
    t === "abas" ? s(a, e) : Ot(a, t, e, 0)
}
async function yt(a, t, e, s) {
    const {
        setRemoveUser: o
    } = q.getState();
    (e === "abas" || t === !0) && o(a, t, s), e !== "abas" && Dt(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 _o(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 (!x.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)
        }
    })),
    Ro = async a => {
        B.setState({
            pin: a
        }), m.Functions("FixChats", {
            action: "pinStorage",
            pin: a
        }), f("pinChat", a)
    }, In = 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);
        Ro(s)
    };
async function qn() {
    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 Uo(a) {
    await m.Chat("markIsUnread", {
        id: a
    })
}
async function Lo(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
        } = Xt.getState(), {
            getQuickReply: o
        } = so.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 No(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
    } = po.getState(), r = [], c = E();
    o({
        id: c,
        userID: a,
        sendAction: "Actived",
        remetente: s,
        actionsTam: t.length,
        actionIndice: 0,
        activeAction: t[0]
    });
    for (const [l, d] of t.entries()) {
        if (!n(c, l, d)) {
            r.push(!1);
            break
        }
        switch (d.type) {
            case "txt":
                r.push(await vo(M(a), d.propriedades, e));
                break;
            case "image":
                r.push(await Ao(M(a), d.propriedades, e));
                break;
            case "video":
                r.push(await bo(M(a), d.propriedades, e));
                break;
            case "audio":
                r.push(await So(M(a), d.propriedades));
                break;
            case "doc":
                r.push(await wo(M(a), d.propriedades));
                break;
            case "pix":
                r.push(await yo(M(a), d.propriedades));
                break;
            case "groupInvite":
                r.push(await Co(M(a), d.propriedades));
                break;
            case "contact":
                r.push(await xo(M(a), d.propriedades));
                break;
            case "linkPreview":
                r.push(await Mo(M(a), d.propriedades));
                break;
            case "sticker":
                r.push(await To(M(a), d.propriedades));
                break;
            case "addCRM":
                a.includes("@lid") ? Re() : await ko(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(M(a), d.propriedades.labelID, "add");
                break;
            case "removeLabel":
                await Ct(M(a), d.propriedades.labelID, "remove");
                break;
            case "removeAllLabel":
                await _o(M(a));
                break;
            case "timer":
                await Me(d.propriedades.segundos);
                break;
            case "composing":
                await ge(M(a), d.propriedades.segundos, "txt");
                break;
            case "recording":
                await ge(M(a), d.propriedades.segundos, "audio");
                break;
            case "arquivar":
                await xt(M(a));
                break;
            case "desarquivar":
                await xt(M(a), !0);
                break;
            case "fixarChat":
                a.includes("@lid") ? Re() : await Mt(M(a), "pin");
                break;
            case "desfixarChat":
                await Mt(M(a), "unpin");
                break;
            case "marcarNaoLido":
                await Uo(M(a));
                break;
            case "transferir":
                a.includes("@lid") ? Re() : await Lo(M(a), d.propriedades);
                break;
            case "bloquear":
                await Eo(M(a));
                break;
            case "respostaRapida":
                await Fo(M(a), d.propriedades.respostaRapidaID, e);
                break;
            case "list":
                await No(M(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: M(o.id)
                },
                r = X.getState().FollowUp.filter(c => c.active);
            if (r.length === 0) return;
            if (s === "add") {
                qo(n, i, r);
                const c = r.filter(l => l.acionamento.type === "timing");
                i.forEach(l => {
                    Po(n, l.id, c)
                })
            } else if (s === "remove") {
                Io(n, i, r);
                const c = r.filter(l => l.acionamento.type === "timing");
                i.forEach(l => {
                    zo(n, l.id, c)
                })
            }
        }
    })
})();

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 === "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 qo(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 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().addChatToFollowUp(o.id, t, a, "label")
    })
}

function zo(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 Do() {
    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":
            Do();
            break
    }
});

function jo() {
    q.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 Oo = [{
        id: 1,
        name: "tab_all",
        visibility: !0
    }, {
        id: 2,
        name: "tab_groups",
        visibility: !0
    }, {
        id: 3,
        name: "tab_unread",
        visibility: !0
    }, {
        id: 4,
        name: "tab_1_1",
        visibility: !0
    }, {
        id: 5,
        name: "tab_atendentes",
        visibility: !0
    }],
    q = b()(a => ({
        userTabs: [],
        systemTabs: Oo,
        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 ? z("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 = q.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 = q.getState().userTabs.map(c => {
                if (c.id === e) {
                    if (!x.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 ? z("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 = q.getState().userTabs.map(i => i.id === e ? {
                ...i,
                chats: t
            } : i);
            q.setState({
                userTabs: o
            }), s && (f("userTabs", o), y.getState().plugin_page ? z("userTabs-setChatsTab", {
                chats: t,
                id: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setChatsTab",
                dados: {
                    chats: t,
                    id: e
                }
            }))
        },
        setCopyChats: (t, e) => a(s => {
            const o = s.userTabs.map(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 ? z("userTabs-setCopyChats", {
                chats: t,
                id: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setCopyChats",
                dados: {
                    chats: t,
                    id: e
                }
            }), {
                userTabs: o
            }
        }),
        setMoveChats: (t, e, s) => a(o => {
            const 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 ? z("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 ? z("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 ? z("userTabs-setEditUserTabName", {
                id: t,
                tabName: e
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setEditUserTabName",
                dados: {
                    id: t,
                    tabName: e
                }
            }), {
                userTabs: o
            }
        }),
        setRemoveTab: t => a(e => {
            const s = e.userTabs.filter(o => o.id !== t);
            return f("userTabs", s), y.getState().plugin_page ? z("userTabs-setRemoveTab", {
                id: t
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setRemoveTab",
                dados: {
                    id: t
                }
            }), {
                userTabs: s
            }
        }),
        setCreateUserTab: t => a(e => {
            const s = {
                    id: E(),
                    chats: [],
                    tag: t,
                    type: "user",
                    hide: !1
                },
                o = [s, ...e.userTabs];
            return f("userTabs", o), y.getState().plugin_page ? z("userTabs-setCreateUserTab", {
                newUserTab: s
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setCreateUserTab",
                dados: {
                    newUserTab: s
                }
            }), {
                userTabs: o
            }
        }),
        setVisibilityUserTab: t => a(e => {
            const s = e.userTabs.map(o => o.id === t ? {
                ...o,
                hide: !o.hide
            } : o);
            return f("userTabs", s), y.getState().plugin_page ? z("userTabs-setVisibilityUserTab", {
                id: t
            }) : chrome.runtime.sendMessage({
                action: "userTabs-setVisibilityUserTab",
                dados: {
                    id: t
                }
            }), {
                userTabs: s
            }
        }),
        getUserAbasTam: t => q.getState().userTabs.filter(s => s.chats.filter(o => o.id === t).length > 0).length,
        getTabByID: t => q.getState().userTabs.find(s => s.id === t),
        setVisibilitySystemTab: t => a(e => {
            const s = e.systemTabs.map(o => o.id === t ? {
                ...o,
                visibility: !o.visibility
            } : o);
            return J("SystemTabsDB", "SystemTabs", [Ae.encryptData(s)]), {
                systemTabs: s
            }
        }),
        setActiveTab: t => a(e => ({
            ...e,
            activeTab: t
        }))
    }));
q.subscribe(() => {
    tt.getState().chatListTabs(), jo()
});
const $t = 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: () => {
        q.getState().setActiveTab({
            id: "custom",
            type: "custom"
        }), m.ListChat("custom", t().selecionados)
    }
}));
$t.subscribe(async a => {
    a.selecionados.length === 1 && a.selecionados[0].id === "tab_unread" ? (q.getState().setActiveTab({
        id: 0,
        type: "default-filter"
    }), m.ListChat("nao-lido")) : (q.getState().setActiveTab({
        id: "custom",
        type: "custom"
    }), m.ListChat("custom", {
        selecionados: a.selecionados,
        user: x.getState().user
    }))
});
const Gt = ["chat", "image", "document", "video", "ptt", "vcard", "sticker", "poll_creation", "location", "list_response", "call_log"];

function Wo(a) {
    if (a.id.fromMe || !Gt.includes(a.type)) return;
    const {
        autoAtendimento: t
    } = Ce.getState();
    t.forEach(e => {
        e.active && Bo(a, e)
    })
}
const Bo = async (a, t) => {
    var u, p, A, v, h, S, L, w, F, ae, _e, st, ot, it, nt, rt, ct, dt, lt, ut, pt, mt, ft, gt, ht;
    const {
        getUserAbasTam: e,
        userTabs: s
    } = q.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: P,
                periodoAtivacao: D,
                active: oe
            } = t.regras.responderDias.propriedades[se] || {};
        if (!Y || !P || !oe || D && !le.isValidInterval(Y, P)) 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 && ((F = (w = (L = t.regras) == null ? void 0 : L.notResponderEtiqueta) == null ? void 0 : w.propriedades) == null ? void 0 : F.active) === !0 && t.regras.notResponderEtiqueta.propriedades.labelID.some(P => d.includes(P))) && !(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(P => d.includes(P))) && !(((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) + jt(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 P of se)
                if (P.crmID === "abas")(lt = s.find(D => D.id === P.abaID)) == null || lt.chats.forEach(D => {
                    D.id === n && (Y = !1)
                });
                else
                    for (const D of o) D.id === P.crmID && ((ut = D.list.find(oe => oe.id === P.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 P of se)
                if (P.crmID === "abas")(gt = s.find(D => D.id === P.abaID)) == null || gt.chats.forEach(D => {
                    D.id === n && (Y = !0)
                });
                else
                    for (const D of o) D.id === P.crmID && ((ht = D.list.find(oe => oe.id === P.abaID)) == null || ht.chats.forEach(oe => {
                        oe.id === n && (Y = !0)
                    }));
            if (!Y) return
        }
        Vo(a, t)
    }
}, Vo = 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 = (await m.Chat("getMessages", {
                id: a.id.remote,
                quant: 5
            })).reverse();
            console.log(r), r.shift();
            const c = r.find(l => l.id.fromMe === !1 && Gt.includes(l.type));
            if (c) {
                const l = parseInt(c.t.toString() + "000");
                if (!le.isDataDeHoje(l)) {
                    i();
                    break
                }
            }
        }
        if (n.type === "customer_Message") {
            const r = await m.Chat("getMessages", {
                id: a.id.remote,
                quant: 5
            });
            if (console.log(r), r.filter(l => l.type !== "e2e_notification" && l.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 Pn() {
    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 zn(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 = E());
        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 Dn(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 $o(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)
                }
            }
        }
    },
    Go = (a, t) => (e, s, o) => {
        let i = {
                storage: $o(() => 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 F;
                return w((F = s()) != null ? F : p)
            });
            const L = ((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 F = i.migrate(w.state, w.version);
                            return F instanceof Promise ? F.then(ae => [!0, ae]) : [!0, F]
                        }
                        console.error("State loaded from storage couldn't be migrated since no migrate function was provided")
                    } else return [!1, w.state];
                return [!1, void 0]
            }).then(w => {
                var F;
                const [ae, _e] = w;
                if (A = i.merge(_e, (F = s()) != null ? F : p), e(A, !0), ae) return d()
            }).then(() => {
                L == null || L(A, void 0), A = s(), n = !0, c.forEach(w => w(A))
            }).catch(w => {
                L == null || L(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
    },
    Ho = Go,
    Ht = b()(Ho((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 Jo(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 Jt(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 Ko(a, t) {
    const {
        getUserAbasTam: e,
        userTabs: s
    } = q.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 Jt(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) + jt(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
        }
    },
    Qo = (a, t) => {
        const {
            getSession: e,
            getLastInteractionDate: s
        } = Ht.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
    },
    Yo = a => {
        const t = a.nodes.find(s => s.type === "init");
        return t ? a.edges.some(s => s.source === t.id) : !1
    },
    Xo = (a, t, e) => ({
        id: `virtual-${Date.now()}`,
        type: a,
        data: t,
        index: -1,
        position: {
            x: 0,
            y: 0
        },
        send: {
            type: "timeout",
            data: t
        }
    }),
    Zo = async (a, t) => {
        let e = "";
        return (t.includes("#nome") || t.includes("#primeiroNome")) && (e = (await m.Utils("getContato", a)).name), e
    }, ei = () => {
        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]
    }, ti = () => {
        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 Zo(a, t);
        try {
            t = t.replaceAll("#saudação", ei()), t = t.replaceAll("#periodo-dia", ti()), 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
    }, ai = (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 ai(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 si(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 jn() {
    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 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("sendImage", {
            id: t,
            base64: n.base64.toString(),
            msg: u
        })
    } catch (n) {
        throw console.error(`Erro ao enviar imagem para ${t}:`, n), n
    }
}
async function ii(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 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("sendAudio", {
            id: t,
            base64: n.base64.toString()
        })
    } catch (n) {
        throw console.error(`Erro ao enviar áudio para ${t}:`, n), n
    }
}
async function ri(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 ci(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 di(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(L => ({
                    rowId: L.rowId,
                    title: L.title,
                    description: L.description || ""
                }))
            }))
        };
        await m.Chat("sendListMessage", {
            id: t,
            options: h
        })
    } catch (n) {
        throw console.error(`Erro ao enviar lista para ${t}:`, n), n
    }
}
const li = {
    "send-text": (a, t, e, s) => si(a, t, e),
    "send-image": (a, t, e, s) => oi(a, t, e, s),
    "send-video": (a, t, e, s) => ii(a, t, e, s),
    "send-audio": (a, t, e, s) => ni(a, t, e, s),
    "send-document": (a, t, e, s) => ri(a, t, e, s),
    "send-answers": (a, t, e, s) => ci(a, t, e),
    "send-list": (a, t, e, s) => di(a, t, e)
};
let kt = 0;
const ui = 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 >= ui && (kt = h, Je("fluxo", s.btnPremium, o.checkout));
        return
    }
    const d = a.type,
        u = li[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 pi = .7,
    mi = 2,
    ve = a => a.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9\s]/g, "").replace(/\s+/g, " ").trim(),
    fi = (a, t) => {
        const e = Math.max(a.length, t.length);
        return e === 0 ? 1 : (e - Nt(a, t)) / e
    },
    Kt = (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 = fi(i, d);
                        u > c && u >= pi && (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 = Nt(i, ve(c.text));
            l < r && l <= mi && (r = l, n = c)
        }), n
    },
    gi = (a, t) => a.send.data.waitTime ? te(a.send.data.waitTime) : null,
    hi = (a, t) => {
        const {
            getAllTargetNodes: e
        } = T.getState(), s = e(a.id, t.id).find(o => o.send.type === "timeout");
        return s || null
    },
    vi = 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 && !aa(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)
    }), Ai = 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 = gi(a),
            o = hi(a, e),
            i = (u = e.globalSettings) == null ? void 0 : u.absenceMessage,
            n = i && ((p = i.message) == null ? void 0 : p.trim()),
            r = n ? Ai(e) : null,
            c = vi(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 = Xo("send-text", A);
                await Rt(v, t, e)
            } else G.getState().resetUserProgress(t);
            return null
        }
        return d
    }, bi = 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), Qt = 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 = Kt(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 Qt(a, t, e) : (G.getState().resetUserProgress(t), null)
        } catch (l) {
            return console.error("Erro inesperado em handleNoMatchNode:", l), G.getState().resetUserProgress(t), null
        }
    }, Si = 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))
    }, wi = 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 = Kt(i, n);
        if (!r) {
            const l = await Qt(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
    }, Yt = 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 Yt(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
    }, yi = async (a, t, e) => (await ne(a, t, e), T.getState().getTargetNode(a.id, e.id));
async function Ci({
    msg: a,
    manualActivation: t
}) {
    if (a.id.fromMe || !Ge.includes(a.type)) return;
    const e = a.id.remote.toString(),
        s = Ht.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 (!Yo(i) || !t && !Qo(e, i) || !t && (!await Jo(a, i) || !await Ko(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 Jt(a, i)) {
                            n.resetUserProgress(e), s.endSession(e), d = null;
                            break
                        }
                        switch (!0) {
                            case d.type === "init":
                                d = await bi(d, e, i);
                                break;
                            case d.send.type === "timeout":
                                n.resetUserProgress(e), d = null;
                                break;
                            case d.send.type === "on-response":
                                d = await Si(d, e, i);
                                break;
                            case d.send.type === "next-block":
                                d = await yi(d, e, i);
                                break;
                            case /^on-response-\d+$/.test(d.send.type):
                                d = await wi(d, e, i);
                                break;
                            case /^on-response-[a-zA-Z0-9-]+$/.test(d.send.type):
                                d = await Yt(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), Wo(t), Ci({
                msg: t,
                manualActivation: null
            }), uo(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), q.getState().activeTab.type === "custom" && setTimeout(() => {
            tt.getState().chatListTabs()
        }, 1e3)
    }
});
let Lt = null;
const tt = b()(() => ({
    chatListTabs: async () => {
        const {
            activeTab: a,
            userTabs: t
        } = q.getState(), {
            selecionados: e
        } = $t.getState();
        let s;
        if ((a == null ? void 0 : a.type) !== "default-filter") {
            if ((a == null ? void 0 : a.type) === "tab") switch (a.id) {
                case 1:
                    s = "tab-1-tudo";
                    break;
                case 2:
                    s = "tab-2-grupos";
                    break;
                case 3:
                    s = "tab-3-nao-lido";
                    break;
                case 4:
                    s = "tab-4-1:1";
                    break;
                case 5:
                    s = `tab-5-atendimento-${x.getState().user}`;
                    break;
                case 6:
                    s = `tab-6-trasferencias-${x.getState().user}`;
                    break;
                default:
                    s = `tab-${a.id}-UserTabs`;
                    break
            } else a.type === "custom" ? s = `custom-${JSON.stringify(e)}-${x.getState().user}` : s = `label-${a.id}`;
            if (Lt !== s)
                if (Lt = s, (a == null ? void 0 : a.type) === "tab") switch (a.id) {
                    case 1:
                        await m.ListChat("tudo");
                        break;
                    case 2:
                        await m.ListChat("grupos");
                        break;
                    case 3:
                        await m.ListChat("nao-lido");
                        break;
                    case 4:
                        await m.ListChat("1:1");
                        break;
                    case 5:
                        await m.ListChat("atendimento", x.getState().user);
                        break;
                    case 6:
                        await m.ListChat("trasferencias", x.getState().user);
                        break;
                    default:
                        await m.ListChat("UserTabs", t.find(o => o.id === a.id).chats);
                        break
                } else a.type === "custom" ? m.ListChat("custom", {
                    selecionados: e,
                    user: x.getState().user
                }) : await m.ListChat("UserLabels", a.id)
        }
    }
}));
async function xi() {
    const {
        user: a
    } = x.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
            } = x.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 xi()) {
                l("user_free"), r();
                return
            }
            const p = ra(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: x.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
            } = x.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: x.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: x.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]
            }
        })
    })),
    On = 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 Mi = (a, t) => {
        a.forEach(e => {
            e.addedNodes.forEach(s => {
                t(e)
            })
        })
    },
    Ti = a => {
        const {
            update: t
        } = H.getState(), {
            getElement: e
        } = V.getState(), {
            setIsOpen: s
        } = Se.getState();
        Mi(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))
        })
    },
    ki = 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, Ti, {
                childList: !0
            })
        }), a("waPage", t => {
            He(t, ki, {
                attributes: !0
            })
        })
    };
sa(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 Xt = 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 && Vt.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: E(),
                    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":
            Xt.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 fa(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 oa && 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 ga({
                        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)
            })
        }
    })),
    Wn = async a => {
        switch (_.setState({
                IA: a
            }), a.activeIA) {
            case "Gemini":
                _.getState().validateGeminiKey(!1);
                break;
            case "GPT":
                _.getState().validateGPTKey(!1);
                break
        }
    }, Bn = 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 qi(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 _i = 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
        }
    }
}, Ri = 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 Ri(a);
            break;
        case "GPT":
            i = await _i(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 Ui(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 Li(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
    })
}, Ni = 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
    })
}, Ii = 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
    })
}, qi = 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 Ni(i.agenteIA, a) : n = await Ui(a);
            break;
        case "otimizador_texto":
            i.activeIA === "system" ? n = await Ii(i.agenteIA, a) : n = await Li(a);
            break
    }
    return n
}, Pi = {
    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 "
}, Zt = b()((a, t) => ({
    variaveisWA: Pi,
    isNewModel: !0,
    setIsNewModel: e => {
        a({
            isNewModel: e
        });
        const s = document.querySelector("main");
        s && s.setAttribute("isNewModel", String(t().isNewModel))
    }
}));
async function Vn() {
    const {
        domSelector: a
    } = V.getState(), {
        setIsNewModel: t
    } = Zt.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 zi = 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 $n() {
    const {
        modalOptions: a,
        options: t,
        childrenRef: e,
        offset: s,
        close: o
    } = zi(), {
        variaveisWA: i
    } = Zt(), {
        refs: n,
        floatingStyles: r,
        update: c,
        elements: l
    } = ca({
        ...t,
        middleware: [la({
            padding: 5
        }), ua({
            padding: 5
        }), pa({
            apply({
                availableWidth: d,
                availableHeight: u,
                elements: p
            }) {
                Object.assign(p.floating.style, {
                    maxWidth: `${d}px`,
                    maxHeight: `${u}px`
                })
            }
        }), ma(s)]
    });
    return k.useEffect(() => {
        if (a && l.reference && l.floating) return da(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 {
    wo as $, Zt as A, Se as B, Ho as C, $o as D, Xt as E, to as F, po as G, Eo as H, Vn as I, Mt as J, xt as K, No as L, Uo as M, ge as N, Me as O, _o as P, Ct as Q, Fo as R, Ze as S, Lo as T, yt as U, ko as V, To as W, Mo as X, xo as Y, Co as Z, yo as _, rn as a, $t as a$, So as a0, bo as a1, Ao as a2, vo as a3, ya as a4, qa as a5, $ as a6, cn as a7, sn as a8, $n as a9, Sa as aA, gn as aB, vn as aC, xe as aD, Vt as aE, zn as aF, Dn as aG, Fn as aH, lo as aI, an as aJ, In as aK, Ro as aL, Wn as aM, tn as aN, ln as aO, ao as aP, Xi as aQ, ha as aR, pn as aS, io as aT, Ve as aU, Ce as aV, pe as aW, Fe as aX, me as aY, Ne as aZ, Zi as a_, nn as aa, En as ab, _n as ac, N as ad, _ as ae, _a as af, H as ag, fe as ah, wn as ai, Ln as aj, Un as ak, co as al, bt as am, Sn as an, so as ao, Oo as ap, qi as aq, ue as ar, Xe as as, eo as at, bn as au, qe as av, B as aw, yn as ax, O as ay, Tn as az, q as b, Rn as b0, xn as b1, kn as b2, T as b3, Ci as b4, Zs as b5, An as b6, Mn as b7, Cn as b8, dn as b9, fn as ba, hn as bb, X as c, W as d, Yi as e, Qi as f, un as g, Pn as h, on as i, jn as j, en as k, Bn as l, Nn as m, x as n, Z as o, zi as p, re as q, ie as r, no as s, qn as t, C as u, mn as v, On as w, Bt as x, R as y, V as z
};