PageSourceSearch

https://app.hubmax.ai/assets/CSATSettings-CCx0X1AX.js

js hubmax.ai collected 2026-10-05 15:16:05 UTC 58,199 bytes, 8 lines download raw bytes

1import{r as N,b as Be,j as e}from"./vendor-react-c04Qizzb.js";import{a_ as Fe,aF as Ue,bn as pe,H as $,a7 as J,U as Y,b3 as Z,a as R,ci as Ve,cD as je,bh as ie,t as B,N as _e,cQ as ze,f2 as Ge,cS as he,c4 as Ne,c5 as ve,aw as F,bP as He,bQ as Qe,bR as Ke,bS as We,ab as Je,bT as Xe,bU as Ye,bV as Ze,bW as ea,av as ye,az as v,aA as G,aB as H,aC as Q,aD as K,aE as S,e7 as ge,cO as we,Q as O,cP as aa,O as E,ak as sa,aY as ta,bf as ra,x as oa,b0 as de,cI as na,aK as ia,v as da,w as la,y as ca,as as ma,bs as xa}from"./index-CS71Crlq.js";import{T as X}from"./templateApi-B7oQcxpV.js";import{C as ua,a as pa,b as ha,c as fe,d as ga,e as fa}from"./command-xZPg8RiT.js";import{C as ee}from"./checkbox-DUwyWP5_.js";import{E as ba}from"./formsService-B-ZZmH3r.js";import{S as ja}from"./webchatService-tagM4ZsL.js";import{u as _a}from"./useSettingsDirty-YlbZ5wvw.js";import{k as Na}from"./useCrmTags-CAkNh83d.js";import{c as ke,d as Ce}from"./csatScale-Cak1ZUnj.js";import{L as Se}from"./list-plus-CfwGziuD.js";import{F as qe}from"./SettingsSearch-pklPEDA8.js";import{S as Ae}from"./MultiSelect-foZj2D3l.js";import{T as va}from"./agencyDestinationsApi-Dh21BqPB.js";import{T as ya}from"./useLongPress-DvC0mrvk.js";import{C as wa}from"./SchedulingNaturalDate-zRWZv1qq.js";import"./vendor-utils-CbK4XRml.js";import"./vendor-query-Beh96XiU.js";import"./vendor-i18n-CTh7dEoX.js";import"./agencyPipelineConfiguration-BKpcDxKm.js";import"./statusService-BO7958ha.js";const Te=a=>{var s;return((s=a.name)==null?void 0:s.trim())||a.instance_name},Re=[{id:"general",label:"Geral",tagline:"Status do sistema",icon:Ve},{id:"notifications",label:"Notificações",tagline:"Alertas de qualidade",icon:je},{id:"triggers",label:"Gatilhos",tagline:"Regras de envio",icon:ie},{id:"rules",label:"Regras",tagline:"Conexoes e departamentos",icon:Se},{id:"templates",label:"Templates",tagline:"Mensagens e preview",icon:qe}];function ka(a){return a.replace(/[&<>]/g,s=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[s]||s)}function re(a){return ka(a).replace(/\*(.*?)\*/g,"<strong>$1</strong>").replace(/_(.*?)_/g,"<em>$1</em>").replace(/~(.*?)~/g,"<del>$1</del>").replace(/```(.*?)```/g,'<code class="bg-black/5 rounded px-1 py-0.5 text-xs font-mono">$1</code>').replace(/\n/g,"<br/>")}function ae(){try{if(typeof crypto<"u"&&"randomUUID"in crypto)return crypto.randomUUID()}catch{}return`rule-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function le(a,s,n){const p=(a==null?void 0:a.scope_type)==="sector"?"sector":"instance",l=Array.isArray(a==null?void 0:a.scope_ids)?a.scope_ids.map(x=>String(x||"").trim()).filter(Boolean):[];return{id:typeof(a==null?void 0:a.id)=="string"&&a.id?a.id:ae(),name:typeof(a==null?void 0:a.name)=="string"&&a.name.trim()?a.name.trim():`Regra ${s+1}`,enabled:typeof(a==null?void 0:a.enabled)=="boolean"?a.enabled:!0,scope_type:p,scope_ids:l,message_header:typeof(a==null?void 0:a.message_header)=="string"&&a.message_header.trim()?a.message_header:n.message_header,thank_you_message:typeof(a==null?void 0:a.thank_you_message)=="string"&&a.thank_you_message.trim()?a.thank_you_message:n.thank_you_message,follow_up_question:typeof(a==null?void 0:a.follow_up_question)=="string"?a.follow_up_question:n.follow_up_question,contact_cooldown_days:typeof(a==null?void 0:a.contact_cooldown_days)=="number"&&Number.isFinite(a.contact_cooldown_days)?a.contact_cooldown_days:null}}function Ca(a,s){const n=[];return Array.isArray(a==null?void 0:a.enabled_instances)&&a.enabled_instances.length>0&&n.push({id:ae(),name:"Conexoes selecionadas",enabled:!0,scope_type:"instance",scope_ids:a.enabled_instances.map(p=>String(p||"").trim()).filter(Boolean),message_header:s.message_header,thank_you_message:s.thank_you_message,follow_up_question:s.follow_up_question,contact_cooldown_days:null}),Array.isArray(a==null?void 0:a.excluded_sectors)&&a.excluded_sectors.forEach(p=>{const l=String(p||"").trim();l&&n.push({id:ae(),name:"Departamento sem pesquisa",enabled:!1,scope_type:"sector",scope_ids:[l],message_header:s.message_header,thank_you_message:s.thank_you_message,follow_up_question:s.follow_up_question,contact_cooldown_days:null})}),n}function be(a,s){if(!s||typeof s!="object")return a;const n=(i,d)=>Array.isArray(i)?i:d,p=(i,d)=>typeof i=="boolean"?i:d,l=(i,d)=>typeof i=="number"&&Number.isFinite(i)?i:d,x=(i,d)=>typeof i=="string"&&i.length>0?i:d;let o=x(s.message_header,a.message_header);if(!s.message_header&&typeof s.message_template=="string"){const i=s.message_template.indexOf("1️⃣");o=i>0?s.message_template.substring(0,i).trim():s.message_template}return{enabled:p(s.enabled,a.enabled),trigger_mode:s.trigger_mode==="manual"?"manual":"on_resolve",email_trigger_mode:s.email_trigger_mode==="on_resolve"||s.email_trigger_mode==="manual"?s.email_trigger_mode:"inherit",auto_reopen_threshold:typeof s.auto_reopen_threshold=="number"?s.auto_reopen_threshold:null,notify_manager_threshold:typeof s.notify_manager_threshold=="number"?s.notify_manager_threshold:s.notify_manager_threshold===null?null:a.notify_manager_threshold,notification_recipients:n(s.notification_recipients,a.notification_recipients),notification_channels:["system"],excluded_tags:n(s.excluded_tags,a.excluded_tags),excluded_sectors:n(s.excluded_sectors,a.excluded_sectors),enabled_
1instances:n(s.enabled_instances,a.enabled_instances),rules:Array.isArray(s.rules)&&s.rules.length>0?s.rules.map((i,d)=>le(i,d,a)):Ca(s,a),predefined_reasons:n(s.predefined_reasons,a.predefined_reasons),message_header:o,message_template:typeof s.message_template=="string"?s.message_template:void 0,thank_you_message:x(s.thank_you_message,a.thank_you_message),follow_up_question:x(s.follow_up_question,a.follow_up_question),contact_cooldown_days:l(s.contact_cooldown_days,a.contact_cooldown_days),auto_task_on_low_score:p(s.auto_task_on_low_score,a.auto_task_on_low_score),auto_task_threshold:l(s.auto_task_threshold,a.auto_task_threshold),google_review_url:x(s.google_review_url,a.google_review_url),promoter_min_score:l(s.promoter_min_score,a.promoter_min_score),google_review_message:x(s.google_review_message,a.google_review_message)}}function Sa(a){if(!Number.isInteger(a.contact_cooldown_days)||a.contact_cooldown_days<0||a.contact_cooldown_days>90)return"O intervalo por contato deve estar entre 0 e 90 dias.";if(a.notify_manager_threshold!==null&&(!Number.isInteger(a.notify_manager_threshold)||a.notify_manager_threshold<1||a.notify_manager_threshold>5))return"O limite de alerta deve estar entre 1 e 5.";if(!Number.isInteger(a.auto_task_threshold)||a.auto_task_threshold<1||a.auto_task_threshold>5)return"O limite da tarefa automática deve estar entre 1 e 5.";if(!Number.isInteger(a.promoter_min_score)||a.promoter_min_score<1||a.promoter_min_score>5)return"A nota mínima do Google deve estar entre 1 e 5.";if(a.google_review_url.trim())try{const s=new URL(a.google_review_url.trim());if(!["http:","https:"].includes(s.protocol))throw new Error("invalid protocol")}catch{return"Informe uma URL válida para a avaliação no Google."}return a.message_header.length>4096||a.thank_you_message.length>4096||a.follow_up_question.length>4096?"As mensagens não podem ultrapassar 4.096 caracteres.":(a.predefined_reasons||[]).filter(Boolean).length>5?"Você pode cadastrar no máximo 5 motivos.":null}function q({icon:a,title:s,description:n,enabled:p,onToggle:l,children:x,defaultOpen:o=!0,badge:i}){const[d,m]=N.useState(o);return e.jsxs("div",{className:"rounded-xl border border-border bg-card overflow-hidden",children:[e.jsxs("div",{role:"button",tabIndex:0,className:"w-full flex items-center gap-3 p-4 text-left cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>m(!d),onKeyDown:t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),m(!d))},"aria-expanded":d,children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-muted flex items-center justify-center shrink-0",children:e.jsx(a,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm text-foreground",children:s}),i]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),l!==void 0&&e.jsx(de,{checked:p,onCheckedChange:t=>{l(t)},onClick:t=>t.stopPropagation(),className:"mr-2"}),e.jsx(ia,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",d&&"rotate-180")})]}),d&&e.jsxs("div",{className:"px-4 pb-4 pt-0 space-y-4 animate-in fade-in duration-200",children:[e.jsx("div",{className:"border-t border-border pt-4"}),x]})]})}function qa({icon:a,label:s,description:n,checked:p,onChange:l}){return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[a&&e.jsx(a,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:s}),n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]})]}),e.jsx(de,{checked:p,onCheckedChange:l})]})}function ne(a){return a.trim().replace(/\s+/g," ")}function D(a){return ne(a).toLocaleLowerCase("pt-BR")}const oe="hsl(var(--muted-foreground))";function Aa({value:a,onChange:s}){const{data:n=[],isLoading:p}=Na(),[l,x]=N.useState(!1);Ne(l,ve);const[o,i]=N.useState(""),d=N.useMemo(()=>a??[],[a]),m=N.useMemo(()=>{const c=new Map;
1return n.forEach(f=>c.set(D(f.name),f)),c},[n]),t=N.useMemo(()=>d.map(c=>({name:c,tag:m.get(D(c))})),[m,d]),u=N.useMemo(()=>new Set(d.map(D)),[d]),g=c=>{const f=[...d];c.forEach(w=>{const U=ne(w);if(!U)return;const W=D(U);f.some(se=>D(se)===W)||f.push(U)}),f.length!==d.length&&s(f)},r=c=>{const f=D(c);s(d.filter(w=>D(w)!==f))},j=c=>{const f=D(c);u.has(f)?r(c):g([c])},C=c=>{if(!c.includes(",")){i(c);return}const f=c.split(",");g(f.slice(0,-1)),i(f[f.length-1]??"")},k=c=>{if(c.key!=="Enter"&&c.key!==",")return;const f=ne(o);f&&(c.preventDefault(),g([f]),i(""))},I=t.slice(0,3);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(da,{open:l,onOpenChange:x,children:[e.jsx(la,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",role:"combobox","aria-expanded":l,className:"min-h-11 h-auto w-full justify-between gap-2 bg-background px-3 py-2 text-left font-normal",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:[I.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"Buscar ou adicionar etiquetas..."}):I.map(({name:c,tag:f})=>e.jsxs("span",{className:"inline-flex max-w-[160px] items-center gap-1 rounded-md border border-border bg-muted px-2 py-0.5 text-xs text-foreground",children:[e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:(f==null?void 0:f.color)||oe}}),e.jsx("span",{className:"truncate",children:c})]},c)),t.length>I.length&&e.jsxs(E,{variant:"secondary",className:"text-xs font-normal",children:["+",t.length-I.length]})]}),e.jsx(wa,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),e.jsx(ca,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(ua,{children:[e.jsx(pa,{placeholder:"Digite para buscar...",value:o,onValueChange:C,onKeyDown:k,className:"h-10"}),e.jsx(ha,{children:p?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(Y,{className:"mr-2 inline h-4 w-4 animate-spin"}),"Carregando etiquetas..."]}):n.length===0?e.jsx(fe,{children:e.jsxs("div",{className:"px-3 py-4 text-center",children:[e.jsx("p",{className:"text-sm",children:"Nenhuma etiqueta cadastrada"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Digite e pressione Enter para adicionar manualmente."})]})}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{children:e.jsxs("div",{className:"px-3 py-4 text-center",children:[e.jsx("p",{className:"text-sm",children:"Nenhuma etiqueta encontrada"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Pressione Enter para adicionar manualmente."})]})}),e.jsx(ga,{children:n.map(c=>{const f=u.has(D(c.name));return e.jsxs(fa,{value:c.name,onSelect:()=>{j(c.name),i("")},className:"cursor-pointer",children:[e.jsx("div",{className:R("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border",f?"border-primary bg-primary text-primary-foreground":"border-border"),children:f&&e.jsx(ma,{className:"h-3 w-3"})}),e.jsx("span",{className:"mr-2 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:c.color||oe}}),e.jsx("span",{className:"truncate",children:c.name})]},c.id)})})]})})]})})]}),t.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map(({name:c,tag:f})=>e.jsxs(E,{variant:"secondary",className:"gap-1.5 pr-1 text-xs font-normal",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:(f==null?void 0:f.color)||oe}}),c,e.jsx("button",{type:"button",onClick:()=>r(c),className:"rounded-sm p-0.5 text-muted-foreground hover:bg-background hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":`Remover etiqueta ${c}`,children:e.jsx(xa,{className:"h-3 w-3"})})]},c))})]})}function Ya(){const a=Fe(),{markClean:s,markDirty:n,isDirty:p}=_a(),[l,x]=N.useState(null),o=Be(),{branding:i}=Ue(),[d,m]=N.useState("general"),[t,u]=N.useState(!0),[g,r]=N.useState(!1),[j,C]=N.useState([]),[k,I]=N.useState([]),[c,f]=N.useState([]),[w,U]=N.useState(null),[W,se]=N.useState(""),[y,A]=N.useState({enabled:!0,trigger_mode:"on_resolve",email_trigger_mode:"inherit",auto_reopen_threshold:null,notify_manager_threshold:2,notification_recipients:[],notification_channels:["system"],excluded_tags:[],excluded_sectors:[],enabled_
1instances:[],rules:[],predefined_reasons:[],message_header:`🌟 *Pesquisa de Satisfação*
2
3Como foi seu atendimento? Responda com um número:`,thank_you_message:"Obrigado pelo seu feedback! 🙏",follow_up_question:"Poderia nos contar o que aconteceu?",contact_cooldown_days:7,auto_task_on_low_score:!0,auto_task_threshold:2,google_review_url:"",promoter_min_score:4,google_review_message:"Que bom que você gostou! 🌟 Se puder, deixa uma avaliação pra gente, leva 1 minutinho e ajuda muito: {link}"});N.useEffect(()=>{Me()},[]),N.useEffect(()=>{l&&(JSON.stringify(y)===JSON.stringify(l)?s():n())},[l,s,n,y]);const Me=async()=>{var _;try{const h=await pe();if(!h){console.error("Tenant ID not found"),x(y);return}const{data:b}=await $.from("tenants").select("settings, name").eq("id",h).single();b!=null&&b.name&&se(b.name);const T=(_=b==null?void 0:b.settings)!=null&&_.csat?be(y,b.settings.csat):y;A(T),x(T);const{data:L}=await $.from("users").select("id, name, role, email, is_active").eq("tenant_id",h).eq("is_active",!0).order("name",{ascending:!0});C(L||[]);const{data:M}=await $.from("crm_sectors").select("id, name").eq("tenant_id",h);I(M||[]);const{data:P}=await $.from("whatsapp_instances").select("id, instance_name, name, phone, connection_type, status").eq("tenant_id",h).order("instance_name");f(P||[]),Pe(h).catch(()=>{})}catch(h){console.error("Error loading CSAT settings:",h),J.error("Não foi possível carregar as configurações.")}finally{u(!1)}},Pe=async _=>{try{const h=new Date(Date.now()-6048e5).toISOString(),[b,T]=await Promise.all([$.from("csat_feedbacks").select("score",{count:"exact"}).eq("tenant_id",_).gte("created_at",h),$.from("chats").select("id",{count:"exact",head:!0}).eq("tenant_id",_).eq("status","resolved").gte("updated_at",h)]),L=b.data||[],M=b.count??L.length,P=T.count??0,V=L.filter($e=>$e.score<=2).length,z=P>0?M/P*100:0,te=M>0?V/M*100:0;U({feedbacks:M,resolved:P,responseRate:Math.round(z),negativeCount:V,negativeRate:Math.round(te)})}catch(h){console.warn("[CSATSettings] Falha ao carregar stats 7d:",h)}},ce=async()=>{const _=Sa(y);if(_){J.error(_);return}r(!0);try{const h=await pe();if(!h)throw new Error("Tenant ID missing");const{data:b}=await $.from("tenants").select("settings").eq("id",h).single(),T=(y.rules||[]).map((z,te)=>le(z,te,y)).filter(z=>z.scope_ids.length>0),L={...y,rules:T,enabled_instances:T.length>0?[]:y.enabled_instances,excluded_sectors:T.length>0?[]:y.excluded_sectors,rating_scale:"1-5",message_template:ke(y.message_header),notification_channels:["system"]};delete L.delay_minutes;const M={...b==null?void 0:b.settings,csat:L},{error:P}=await $.rpc("update_tenant_settings_direct",{p_tenant_id:h,p_settings:M});if(P)throw P;const V=be(y,L);A(V),x(V),s(),J.success("Alterações de CSAT atualizadas.")}catch(h){console.error("Error saving settings:",h);const b=(h==null?void 0:h.code)==="42501"||/forbidden|unauthenticated/i.test((h==null?void 0:h.message)||"");J.error(b?"Você não tem permissão para alterar essas configurações.":"Não foi possível salvar. Tente novamente.")}finally{r(!1)}},me=_=>{A(h=>{const b=h.notification_recipients||[];return b.includes(_)?{...h,notification_recipients:b.filter(T=>T!==_)}:{...h,notification_recipients:[...b,_]}})},xe=_=>{A(h=>({...h,notification_channels:_==="system"?["system"]:[]}))},ue=_=>{A(h=>{const b=h.excluded_sectors||[];return b.includes(_)?{...h,excluded_sectors:b.filter(T=>T!==_)}:{...h,excluded_sectors:[...b,_]}})};return t?e.jsx("div",{className:"flex h-[50vh] items-center justify-center",children:e.jsx(Y,{className:"h-8 w-8 animate-spin text-primary"})}):a?e.jsx(Ta,{activeTab:d,setActiveTab:m,settings:y,setSettings:A,stats:w,users:j,sectors:k,instances:c,toggleRecipient:me,toggleChannel:xe,toggleExcludedSector:ue,saveSettings:ce,saving:g,isDirty:p,onReset:()=>l&&A(l),onBack:()=>o("/configuracoes"),onReport:()=>o("/dashboard/satisfacao"),brandName:i.company_name||W||"Empresa"}):e.jsxs(ba,{title:"Pesquisa de Satisfação",subtitle:"Gerencie a qualidade do atendimento e monitore o feedback dos clientes",icon:Z,onBack:()=>o("/configuracoes"),compactHeaderOnMobile:!0,hideSubtitleOnMobile:!0,inlineActionsOnMobile:!0,titleClassName:"max-sm:text-[22px] max-sm:leading-7 max-sm:truncate",actions:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>o("/dashboard/satisfacao"),className:"h-11 gap-1.5 max-sm:w-11 max-sm:rounded-full max-sm:px-0","aria-label":"Ver relatório de satisfação",children:[e.jsx(_e,{className:"h-4 w-4"}),e.jsx("span",{className:"max-sm:hidden",children:"Ver Relatório"})]}),e.jsx(B,{onClick:ce,className:"h-11 bg-primary text-primary-foreground hover:bg-primary/90 shadow-lg shadow-primary/20 max-sm:w-11 max-sm:rounded-full max-sm:px-0",disabled:g,"aria-label":"Salvar alterações",children:g?e.jsxs(e.Fragment,{children:[e.jsx(Y,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"max-sm:hidden",children:"Salvando..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ae,{className:"h-4 w-4"}),e.jsx("span",{className:"max-sm:hidden",children:"Salvar Alterações"})]})})]}),children:[w&&e.jsx("div",{className:"mb-6 rounded-xl border border-border bg-card",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 divide-y sm:divide-y-0 sm:divide-x divide-border",children:[e.jsxs("div",{className:"px-5 py-4",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Respostas"}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-1.5",children:[e.jsx("span",{className:"text-2xl font-bold tabular-nums text-slate-800 dark:text-slate-200",children:w.feedbacks}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"nos últimos 7 dias"})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Taxa de Resposta"}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-1.5",children:[e.jsxs("span",{className:"text-2xl font-bold tabular-nums text-slate-800 dark:text-slate-200",children:[w.responseRate,"%"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[w.feedbacks,"/",w.resolved," resolvidas"]})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Avaliações Negativas"}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-1.5",children:[e.jsxs("span",{className:R("text-2xl font-bold tabular-nums",w.negativeRate>
3=20?"text-rose-600 dark:text-rose-400":"text-slate-800 dark:text-slate-200"),children:[w.negativeRate,"%"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[w.negativeCount," ",w.negativeCount===1?"nota":"notas"," entre 1 e 2"]})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-8",children:[e.jsx("div",{className:"lg:col-span-1 space-y-1.5 lg:sticky lg:top-6 lg:self-start",children:Re.map(_=>{const h=_.icon,b=d===_.id;return e.jsxs("button",{onClick:()=>m(_.id),className:R("w-full min-h-11 flex items-center gap-3 p-3 rounded-xl transition-all duration-200 border text-left",b?"bg-card border-primary/20 dark:border-primary/30 shadow-md ring-1 ring-primary/20":"bg-transparent border-transparent hover:bg-card/50 hover:border-border"),children:[e.jsx("div",{className:R("h-9 w-9 rounded-lg flex items-center justify-center shrink-0",b?"bg-primary/10 dark:bg-primary/20 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(h,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:R("font-medium text-sm block",b?"text-foreground":"text-muted-foreground"),children:_.label}),e.jsx("span",{className:"text-xs text-muted-foreground truncate block",children:_.tagline})]})]},_.id)})}),e.jsxs("div",{className:"lg:col-span-3 space-y-4 animate-in fade-in duration-300",children:[d==="general"&&e.jsx(Ee,{settings:y,setSettings:A}),d==="notifications"&&e.jsx(De,{settings:y,setSettings:A,users:j,toggleRecipient:me,toggleChannel:xe}),d==="triggers"&&e.jsx(Oe,{settings:y,setSettings:A,sectors:k,instances:c,toggleExcludedSector:ue}),d==="rules"&&e.jsx(Ie,{settings:y,setSettings:A,sectors:k,instances:c}),d==="templates"&&e.jsx(Le,{settings:y,setSettings:A,brandName:i.company_name||W||"Empresa"})]},d)]})]})}function Ta({activeTab:a,setActiveTab:s,settings:n,setSettings:p,stats:l,users:x,sectors:o,instances:i,toggleRecipient:d,toggleChannel:m,toggleExcludedSector:t,saveSettings:u,saving:g,isDirty:r,onReset:j,onBack:C,onReport:k,brandName:I}){return e.jsxs(ze,{className:"bg-slate-50 dark:bg-slate-950",children:[e.jsx(Ge,{title:"Pesquisa de Satisfação",onBack:C,backLabel:"Voltar às configurações",actions:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:k,className:he,"aria-label":"Abrir relatório de satisfação",children:e.jsx(_e,{className:"h-5 w-5"})}),e.jsx("button",{type:"button",onClick:u,disabled:g,className:R(he,r&&"border-primary bg-primary text-primary-foreground"),"aria-label":"Salvar alterações",children:g?e.jsx(Y,{className:"h-5 w-5 animate-spin"}):e.jsx(Ae,{className:"h-5 w-5"})})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain px-4 pb-[calc(env(safe-area-inset-bottom)+6rem)] pt-1",children:[e.jsxs("div",{className:"flex flex-nowrap gap-3 overflow-x-auto snap-x snap-mandatory pb-2 scrollbar-hide","aria-label":"Resumo dos últimos 7 dias",children:[e.jsxs("div",{className:"w-[calc(100vw-64px)] max-w-[300px] shrink-0 snap-start rounded-xl border border-border bg-card px-4 py-3 text-center",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:"Respostas"}),e.jsx("p",{className:"mt-1 text-xl font-bold tabular-nums",children:(l==null?void 0:l.feedbacks)??0})]}),e.jsxs("div",{className:"w-[calc(100vw-64px)] max-w-[300px] shrink-0 snap-start rounded-xl border border-border bg-card px-4 py-3 text-center",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:"Resposta"}),e.jsxs("p",{className:"mt-1 text-xl font-bold tabular-nums",children:[(l==null?void 0:l.responseRate)??0,"%"]})]}),e.jsxs("div",{className:"w-[calc(100vw-64px)] max-w-[300px] shrink-0 snap-start rounded-xl border border-border bg-card px-4 py-3 text-center",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:"Negativas"}),e.jsxs("p",{className:R("mt-1 text-xl font-bold tabular-nums",((l==null?void 0:l.negativeRate)??0)>=20?"text-rose-600":"text-foreground"),children:[(l==null?void 0:l.negativeRate)??0,"%"]})]})]}),e.jsx("div",{role:"tablist","aria-label":"Seções da pesquisa de satisfação",className:"-mx-1 mb-4 flex gap-2 overflow-x-auto px-1 pb-1 scrollbar-none",children:Re.map(c=>{const f=c.icon,w=a===c.id;return e.jsx("button",{type:"button",role:"tab","aria-selected":w,onClick:()=>s(c.id),className:R("min-h-11 shrink-0 rounded-xl border px-3 text-sm font-medium transition-colors",w?"border-primary/30 bg-primary/10 text-primary":"border-transparent bg-muted/60 text-muted-foreground"),children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(f,{className:"h-4 w-4"}),c.label]})},c.id)})}),e.jsxs("div",{className:"space-y-4 animate-in fade-in duration-200",children:[a==="general"&&e.jsx(Ee,{settings:n,setSettings:p}),a==="notifications"&&e.jsx(De,{settings:n,setSettings:p,users:x,toggleRecipient:d,toggleChannel:m}),a==="triggers"&&e.jsx(Oe,{settings:n,setSettings:p,sectors:o,instances:i,toggleExcludedSector:t}),a==="rules"&&e.jsx(Ie,{settings:n,setSettings:p,sectors:o,instances:i}),a==="templates"&&e.jsx(Le,{settings:n,setSettings:p,brandName:I})]},a)]}),e.jsx(ja,{isDirty:r,isSaving:g,onSave:u,onReset:j,saveLabel:"Salvar alterações",mobileNavClearance:!0})]})}function Ee({settings:a,setSettings:s}){const[n,p]=N.useState(!1);Ne(n,ve);const l=x=>{if(!x&&a.enabled){p(!0);return}s(o=>({...o,enabled:x}))};return e.jsxs(e.Fragment,{children:[e.jsx(q,{icon:Z,title:"Status do Sistema",description:"Controle global de envio de pesquisas de satisfação",enabled:a.enabled,onToggle:l,children:e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border",children:[e.jsx(F,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:a.enabled?"O sistema está enviando pesquisas automaticamente ao resolver conversas. O bot é pausado temporariamente enquanto aguarda a resposta do cliente (timeout: 24h).":"Envio de pesquisas está desativado. Nenhuma pesquisa será enviada ao resolver conversas."})]})}),e.jsx(He,{open:n,onOpenChange:p,children:e.jsxs(Qe,{children:[e.jsxs(Ke,{children:[e.jsxs(We,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"h-5 w-5 text-amber-500"}),"Desativar Pesquisa de Satisfação?"]}),e.jsx(Xe,{asChild:!0,children:e.jsxs("div",{className:"space-y-3 text-sm text-muted-foreground",children:[e.jsxs("p",{children:["Ao desativar, ",e.jsx("strong",{className:"text-foreground",children:"nenhuma pesquisa nova será enviada"})," ao resolver conversas a partir de agora."]}),e.jsxs("div",{className:"rounded-lg border border-border bg-muted/50 p-3 space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:"O que permanece:"}),e.jsxs("ul",{className:"text-xs list-disc list-inside space-y-0.5",children:[e.jsx("li",{children:"Histórico de feedbacks já recebidos no Dashboard"}),e.jsx("li",{children:"Pesquisas pendentes (aguardando resposta do cliente)"}),e.jsx("li",{children:"Configurações de mensagens e notificações (não são apagadas)"})]})]}),e.jsx("p",{className:"text-xs",children:"Você pode reativar a qualquer momento, sem perder nada."})]})})]}),e.jsxs(Ye,{children:[e.jsx(Ze,{children:"Manter Ativo"}),e.jsx(ea,{onClick:()=>s(x=>({...x,enabled:!1})),className:"bg-rose-600 hover:bg-rose-700 text-white",children:"Desativar"})]})]})}),e.jsx(q,{icon:Z,title:"Escala de Avaliação",description:"Formato fixo para compatibilidade 
3com métricas",defaultOpen:!1,children:e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border",children:[e.jsx(ye,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["A escala de avaliação é fixa em ",e.jsx("strong",{children:"1 a 5"})," para garantir compatibilidade com as métricas do dashboard e o reconhecimento automático de notas pelo bot."]}),e.jsx("div",{className:"font-mono text-xs text-foreground/70 bg-background rounded-lg p-3 border border-border whitespace-pre-line",children:Ce})]})]})})]})}function De({settings:a,setSettings:s,users:n,toggleRecipient:p,toggleChannel:l}){var t,u,g;const[x,o]=N.useState(""),i=n.length>6,d=x.trim()?n.filter(r=>{var C,k;const j=x.toLowerCase();return((C=r.name)==null?void 0:C.toLowerCase().includes(j))||((k=r.email)==null?void 0:k.toLowerCase().includes(j))}):n,m=((t=a.notification_recipients)==null?void 0:t.length)||0;return e.jsxs(e.Fragment,{children:[e.jsx(q,{icon:je,title:"Alertas de Qualidade",description:"Configure quando disparar alertas de avaliação negativa",children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-medium",children:"Gatilho de Alerta"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Considerar "Avaliação Negativa" notas iguais ou inferiores a:'}),e.jsxs(G,{value:((u=a.notify_manager_threshold)==null?void 0:u.toString())||"disabled",onValueChange:r=>s(j=>({...j,notify_manager_threshold:r==="disabled"?null:parseInt(r)})),children:[e.jsx(H,{className:"w-full sm:w-[200px] bg-background",children:e.jsx(Q,{placeholder:"Selecione"})}),e.jsxs(K,{children:[e.jsx(S,{value:"disabled",children:"🔕 Desativar"}),e.jsx(S,{value:"1",children:"1 · Péssimo"}),e.jsx(S,{value:"2",children:"2 · Ruim"}),e.jsx(S,{value:"3",children:"3 · Regular"})]})]})]})})}),e.jsx(q,{icon:ie,title:"Recuperação Automática de Cliente",description:"Cria tarefa no Hub de Atividades quando a nota for baixa",enabled:a.auto_task_on_low_score,onToggle:r=>s(j=>({...j,auto_task_on_low_score:r})),children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-medium",children:"Criar tarefa quando nota for:"}),e.jsxs(G,{value:String(a.auto_task_threshold??2),onValueChange:r=>s(j=>({...j,auto_task_threshold:parseInt(r)})),disabled:!a.auto_task_on_low_score,children:[e.jsx(H,{className:"w-full sm:w-[260px] bg-background",children:e.jsx(Q,{})}),e.jsxs(K,{children:[e.jsx(S,{value:"1",children:"Apenas nota 1 (Péssimo)"}),e.jsx(S,{value:"2",children:"Notas 1 e 2 (Péssimo e Ruim)"}),e.jsx(S,{value:"3",children:"Notas 1, 2 e 3 (Péssimo a Regular)"})]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border",children:[e.jsx(F,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["A tarefa é atribuída automaticamente ao agente que fez o atendimento, com SLA de ",e.jsx("strong",{children:"4h para nota 1"})," e ",e.jsx("strong",{children:"24h para nota 2"}),". Aparece no Hub de Atividades e dispara notificação push. Evita que clientes insatisfeitos sejam esquecidos."]})]})]})}),e.jsx(q,{icon:ge,title:"Canais de Notificação",description:"Onde os alertas serão enviados",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(qa,{icon:ge,label:"Notificação no Painel",description:"Alertas internos do sistema (único canal disponível)",checked:((g=a.notification_channels)==null?void 0:g.includes("system"))||!1,onChange:()=>l("system")}),e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border bg-muted/40 p-3",children:[e.jsx(F,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"Alertas de nota baixa aparecem no painel e na central de notificações. E-mail e WhatsApp ainda não têm entrega configurada e não são exibid
3os como opções falsas."})]}),"                "]})}),e.jsx(q,{icon:we,title:"Destinatários do Alerta",description:"Quem deve receber as notificações de avaliação negativa",badge:n.length>0?e.jsxs(E,{variant:"secondary",className:"text-xs",children:[m," de ",n.length]}):void 0,children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Nenhum usuário ativo encontrado"}):e.jsxs("div",{className:"space-y-2",children:[i&&e.jsx(O,{placeholder:"Buscar por nome ou email...",value:x,onChange:r=>o(r.target.value),className:"h-9 text-sm bg-background"}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:x.trim()?`${d.length} resultado${d.length===1?"":"s"}`:`${n.length} usuário${n.length===1?"":"s"} ativo${n.length===1?"":"s"}`}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:()=>s(r=>({...r,notification_recipients:Array.from(new Set([...r.notification_recipients||[],...d.map(j=>j.id)]))})),disabled:d.length===0,className:"text-primary hover:underline disabled:opacity-40 disabled:no-underline",children:"Selecionar todos"}),e.jsx("button",{type:"button",onClick:()=>s(r=>({...r,notification_recipients:(r.notification_recipients||[]).filter(j=>!d.some(C=>C.id===j))})),disabled:m===0,className:"text-muted-foreground hover:text-foreground hover:underline disabled:opacity-40 disabled:no-underline",children:"Limpar"})]})]}),d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Nenhum usuário corresponde à busca"}):e.jsx(aa,{className:"h-[420px] rounded-lg border border-border bg-background/50",children:e.jsx("div",{className:"space-y-1 p-1.5 overscroll-contain",children:d.map(r=>{var j;return e.jsxs("label",{htmlFor:`user-${r.id}`,className:"flex items-center gap-3 p-3 rounded-md border border-border bg-card hover:bg-muted/30 transition-colors cursor-pointer",children:[e.jsx(ee,{id:`user-${r.id}`,checked:(j=a.notification_recipients)==null?void 0:j.includes(r.id),onCheckedChange:()=>p(r.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-foreground block truncate",children:r.name}),e.jsxs("span",{className:"text-xs text-muted-foreground truncate block",children:[r.role==="admin"?"Administrador":r.role==="agent"?"Atendente":r.role||"—"," • ",r.email]})]})]},r.id)})})})]})})]})}function Oe({settings:a,setSettings:s,sectors:n,instances:p,toggleExcludedSector:l}){const x=o=>{s(i=>{const d=i.enabled_instances||[],m=d.includes(o)?d.filter(t=>t!==o):[...d,o];return{...i,enabled_instances:m}})};return e.jsxs(e.Fragment,{children:[e.jsx(q,{icon:ie,title:"Modo de Disparo",description:"Quando a pesquisa deve ser enviada",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-medium",children:"Método"}),e.jsxs(G,{value:a.trigger_mode,onValueChange:o=>s(i=>({...i,trigger_mode:o})),children:[e.jsx(H,{className:"w-full bg-background",children:e.jsx(Q,{})}),e.jsxs(K,{children:[e.jsx(S,{value:"on_resolve",children:"✅ Ao resolver conversa (Automático)"}),e.jsx(S,{value:"manual",children:"🛑 Apenas envio manual"})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border mt-2",children:[e.jsx(F,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:a.trigger_mode==="manual"?"A pesquisa só será enviada quando um operador iniciar o envio manualmente.":"No modo automático, a pesquisa é enviada assim que a conversa é resolvida. O bot é pausado até o cliente responder ou o timeout de 24h expirar."})]})]})}),e.jsx(q,{icon:sa,title:"E-mail de atendimento",description:"O canal de e-mail herda o gatilho acima, mas não reenvia no mesmo ticket",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-medium",children:"Quando enviar no e-mail"}),e.jsxs(G,{value:a.email_trigger_mode,onValueChange:o=>s(i=>({...i,email_trigger_mode:o})),children:[e.jsx(H,{className:"w-full bg-background",children:e.jsx(Q,{})}),e.jsxs(K,{children:[e.jsx(S,{value:"inherit",children:"Seguir o padrão dos outros canais"}),e.jsx(S,{value:"on_resolve",children:"Ao encerrar o ticket"}),e.jsx(S,{value:"manual",children:"Somente envio manual"})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border mt-2",children:[e.jsx(F,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"No e-mail a pesquisa vai com notas clicáveis. O encerrar automático manda no máximo uma vez por ticket — fechar de novo a mesma conversa não dispara outra. Envio manual e o intervalo por contato continuam valendo. Dá para desligar o canal em E-mail de Atendimento."})]})]})}),e.jsx(q,{icon:we,title:"Limite por Contato",description:"Evitar múltiplas pesquisas ao mesmo cliente em sequência",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-medium",children:"Intervalo entre pesquisas"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"relative flex-1 max-w-[200px]",children:e.jsx(O,{type:"number",min:"0",max:"90",value:a.contact_cooldown_days,onChange:o=>s(i=>({...i,contact_cooldown_days:parseInt(o.target.value)||0})),className:"bg-background"})}),e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:a.contact_cooldown_days===0?"sem limite (enviar sempre)":"dias entre pesquisas ao mesmo contato"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Se o cliente já respondeu uma pesquisa nos últimos ",a.contact_cooldown_days||"X"," dias, novas resoluções não disparam pesquisa, evitando assédio e melhorando a taxa de resposta no longo prazo. Use ",e.jsx("strong",{children:"0"})," para desativar (envia em toda resolução)."]})]})}),e.jsx(q,{icon:va,title:"Etiquetas Excluídas",description:"Conversas com estas tags NÃO receberão pesquisa",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Aa,{value:a.excluded_tags,onChange:o=>s(i=>({...i,excluded_tags:o}))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Busque etiquetas cadastradas ou digite um nome e pressione Enter. Vírgula também adiciona múltiplas etiquetas."})]})}),e.jsx(q,{icon:ta,title:"Departamentos Excluídos",description:"Departamentos que não devem enviar pesquisa",badge:a.excluded_sectors.length>0?e.jsxs(E,{variant:"secondary",className:"text-xs",children:[a.excluded_sectors.length," excluído(s)"]}):void 0,children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Nenhum departamento cadastrado"}):e.jsx("div",{className:"space-y-1",children:n.map(o=>{var i;return e.jsxs("label",{htmlFor:`sec-${o.id}`,className:"flex items-center gap-3 p-3 rounded-lg border border-border hover:bg-muted/30 transition-colors cursor-pointer",children:[e.jsx(ee,{id:`sec-${o.id}`,checked:(i=a.excluded_sectors)==null?void 0:i.includes(o.id),onCheckedChange:()=>l(o.id)}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:o.name})]},o.id)})})}),e.jsx(q,{icon:ra,title:"Conexões Habilitadas",description:"Selecione quais conexões envi
3arão pesquisa de satisfação",badge:(a.enabled_instances||[]).length>0?e.jsxs(E,{variant:"secondary",className:"text-xs",children:[a.enabled_instances.length," selecionada(s)"]}):void 0,children:p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Nenhuma conexão encontrada"}):e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border mb-3",children:[e.jsx(F,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["Se nenhuma conexão for selecionada, ",e.jsx("strong",{children:"todas"})," as conexões enviarão pesquisa. Selecione conexões específicas para limitar o envio."]})]}),p.map(o=>e.jsxs("label",{htmlFor:`inst-${o.id}`,className:"flex items-center gap-3 p-3 rounded-lg border border-border hover:bg-muted/30 transition-colors cursor-pointer",children:[e.jsx(ee,{id:`inst-${o.id}`,checked:(a.enabled_instances||[]).includes(o.instance_name),onCheckedChange:()=>x(o.instance_name)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:Te(o)}),o.phone&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2 font-mono",children:o.phone})]}),e.jsx(E,{variant:"outline",className:"text-[10px] shrink-0",children:o.connection_type==="official"?"Cloud API":"Lite"})]},o.id))]})})]})}function Ie({settings:a,setSettings:s,sectors:n,instances:p}){const l=()=>{s(t=>{var u;return{...t,rules:[...t.rules||[],le({id:ae(),name:`Regra ${(t.rules||[]).length+1}`,enabled:!0,scope_type:"instance",scope_ids:[]},((u=t.rules)==null?void 0:u.length)||0,t)]}})},x=(t,u)=>{s(g=>({...g,rules:(g.rules||[]).map(r=>r.id===t?{...r,...u}:r)}))},o=t=>{s(u=>({...u,rules:(u.rules||[]).filter(g=>g.id!==t)}))},i=t=>{x(t,{message_header:a.message_header,thank_you_message:a.thank_you_message,follow_up_question:a.follow_up_question,contact_cooldown_days:null})},d=(t,u,g=[])=>{const r=t.scope_ids||[],C=[u,...g].some(k=>r.includes(k))?r.filter(k=>k!==u&&!g.includes(k)):[...r,u];x(t.id,{scope_ids:C})},m=t=>t.scope_type==="sector"?n.map(u=>({id:u.id,label:u.name,description:"Departamento",aliases:[]})):p.map(u=>({id:u.id,label:Te(u),description:[u.phone,u.connection_type==="official"?"Cloud API":"Lite"].filter(Boolean).join(" - "),aliases:[u.instance_name].filter(Boolean)}));return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl border border-border bg-card p-4",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Regras por conexao ou departamento"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"A configuracao global continua como padrao. Uma regra ativa personaliza o envio; uma regra inativa bloqueia o envio no escopo escolhido."})]}),e.jsxs(B,{type:"button",onClick:l,className:"w-full gap-2 bg-primary text-primary-foreground hover:bg-primary/90 sm:w-auto",children:[e.jsx(oa,{className:"h-4 w-4"}),"Adicionar regra"]})]})}),(a.rules||[]).length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-card p-8 text-center",children:[e.jsx(Se,{className:"mx-auto h-8 w-8 text-muted-foreground"}),e.jsx("h3",{className:"mt-3 text-sm font-semibold text-foreground",children:"Nenhuma regra personalizada"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Todas as conversas seguem a configuracao global enquanto nao houver regra especifica."})]}):e.jsx("div",{className:"space-y-3",children:(a.rules||[]).map((t,u)=>{const g=m(t);return e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"grid min-w-0 flex-1 grid-cols-1 gap-3 md:grid-cols-[1fr_180px]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{htmlFor:`csat-rule-name-${t.id}`,children:"Nome da regra"}),e.jsx(O,{id:`csat-rule-name-${t.id}`,value:t.name,onChange:r=>x(t.id,{name:r.target.value}),placeholder:`Regra ${u+1}`,className:"bg-background"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Escopo"}),e.jsxs(G,{value:t.scope_type,onValueChange:r=>x(t.id,{scope_type:r,scope_ids:[]}),children:[e.jsx(H,{className:"bg-background",children:e.jsx(Q,{})}),e.jsxs(K,{children:[e.jsx(S,{value:"instance",children:"Conexao"}),e.jsx(S,{value:"sector",children:"Departamento"})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border px-3 py-2",children:[e.jsx(de,{checked:t.enabled,onCheckedChange:r=>x(t.id,{enabled:r})}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:t.enabled?"Ativa":"Inativa"})]}
3),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>i(t.id),title:"Copiar mensagens globais",children:e.jsx(na,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>o(t.id),title:"Remover regra",children:e.jsx(ya,{className:"h-4 w-4 text-destructive"})})]})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx(v,{children:t.scope_type==="sector"?"Departamentos":"Conexoes"}),g.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground",children:"Nenhuma opcao encontrada para este escopo."}):e.jsx("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-2",children:g.map(r=>{const j=[r.id,...r.aliases].some(C=>t.scope_ids.includes(C));return e.jsxs("label",{className:"flex cursor-pointer items-center gap-3 rounded-lg border border-border p-3 transition-colors hover:bg-muted/30",children:[e.jsx(ee,{checked:j,onCheckedChange:()=>d(t,r.id,r.aliases)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:r.label}),r.description&&e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:r.description})]})]},r.id)})})]}),t.enabled?e.jsxs("div",{className:"mt-4 grid grid-cols-1 gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(v,{children:"Mensagem da pesquisa"}),e.jsx(X,{value:t.message_header,onChange:r=>x(t.id,{message_header:r.target.value}),className:"min-h-[90px] bg-background"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A escala fixa de 1 a 5 sera adicionada automaticamente."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Agradecimento"}),e.jsx(X,{value:t.thank_you_message,onChange:r=>x(t.id,{thank_you_message:r.target.value}),className:"min-h-[80px] bg-background"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Pergunta de nota baixa"}),e.jsx(X,{value:t.follow_up_question,onChange:r=>x(t.id,{follow_up_question:r.target.value}),className:"min-h-[80px] bg-background"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Cooldown proprio"}),e.jsx(O,{type:"number",min:"0",max:"90",value:t.contact_cooldown_days??"",onChange:r=>{const j=r.target.value;x(t.id,{contact_cooldown_days:j===""?null:Math.max(0,Number(j)||0)})},placeholder:`${a.contact_cooldown_days} dias (global)`,className:"bg-background"})]})]}):e.jsx("div",{className:"mt-4 rounded-lg border border-dashed border-border bg-muted/30 p-3 text-xs text-muted-foreground",children:"Esta regra bloqueia o envio da pesquisa para os escopos selecionados, mesmo com a configuracao global ativa."})]},t.id)})})]})}function Le({settings:a,setSettings:s,brandName:n}){var d;const[p,l]=N.useState("high"),x=ke(a.message_header).replace("{cliente}","João").replace("{agente}","Maria").replace("{ticket}","#1234"),o=(a.predefined_reasons||[]).filter(m=>m&&m.trim()),i=(()=>{let m=a.follow_up_question||"Poderia nos contar o que aconteceu?";if(o.length>0){const t=o.map((u,g)=>`${String.fromCodePoint(49+g)+"️⃣"} ${u}`).join(`
4`);m+=`
5
6${t}
7
8Responda com o número ou digite sua resposta:`}return m})();return e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(q,{icon:qe,title:"Mensagem Inicial",description:"Texto de apresentação da pesquisa",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-medium",children:"Texto de Introdução"}),e.jsx(X,{value:a.message_header,onChange:m=>s(t=>({...t,message_header:m.target.value})),rows:4,className:"font-mono text-sm bg-background resize-none",placeholder:"Ex: 🌟 *Pesquisa de Satisfação*\\n\\nComo foi seu atendimento?"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Variáveis:"}),["{cliente}","{agente}","{ticket}"].map(m=>e.jsx(E,{variant:"outline",className:"cursor-pointer hover:bg-muted text-xs font-mono",onClick:()=>{s(t=>({...t,message_header:t.message_header+" "+m}))},children:m},m))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"text-sm font-medium",children:"Escala de Notas"}),e.jsxs(E,{variant:"secondary",className:"text-[10px] gap-1",children:[e.jsx(ye,{className:"h-3 w-3"}),"Fixo"]})]}),e.jsx("div",{className:"font-mono text-sm bg-muted/50 rounded-lg p-3 border border-border text-muted-foreground whitespace-pre-line select-none",children:Ce}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"O bloco de notas é fixo para garantir que o bot reconheça as respostas numéricas (1 a 5) e as métricas do dashboard funcionem corretamente."})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border",children:[e.jsx(F,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["Use ",e.jsx("code",{className:"font-mono bg-background px-1 py-0.5 rounded text-xs border",children:"*texto*"})," para ",e.jsx("strong",{children:"negrito"}),","," ",e.jsx("code",{className:"font-mono bg-background px-1 py-0.5 rounded text-xs border",children:"_texto_"})," para ",e.jsx("em",{children:"itálico"})," e"," ",e.jsx("code",{className:"font-mono bg-background px-1 py-0.5 rounded text-xs border",children:"~texto~"})," para ",e.jsx("del",{children:"riscado"}),"."]})]})]})}),e.jsx(q,{icon:Z,title:"Fluxo de Resposta",description:"Mensagens automáticas após o cliente votar",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-medium",children:"Agradecimento (Nota Alta ≥ 4)"}),e.jsx(O,{value:a.thank_you_message,onChange:m=>s(t=>({...t,thank_you_message:m.target.value})),className:"bg-background"})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t border-border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(v,{className:"text-sm font-medium",children:"Convite pra avaliar no Google (Nota Alta)"}),e.jsx(E,{variant:"outline",className:"text-[10px]",children:"Opcional"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Quando o cliente dá uma nota alta, ele recebe um convite pra avaliar a empresa no Google. Cole o link e a mensagem; deixe o link em branco pra não enviar."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-xs text-muted-foreground",children:"Link de avaliação do Google"}),e.jsx(O,{value:a.google_review_url,onChange:m=>s(t=>({...t,google_review_url:m.target.value})),placeholder:"https://g.page/r/.../review",className:"bg-background"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-xs text-muted-foreground",children:"Enviar a partir da nota"}),e.jsxs("select",{value:a.promoter_min_score,onChange:m=>s(t=>({...t,promoter_min_score:Number(m.target.value)})),className:"h-9 w-full rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:4,children:"Nota 4 ou 5"}),e.jsx("option",{value:5,children:"Somente nota 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-xs text-muted-foreground",children:"Mensagem do convite"}),e.jsx(O,{value:a.google_review_message,onChange:m=>s(t=>({...t,google_review_message:m.target.value})),placeholder:"Use {link} onde o link deve aparecer",className:"bg-background"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ",e.jsx("span",{className:"font-mono",children:"{link}"})," pra inserir o link. Sem ele, o link vai no fim."]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-medium",children:"Investigação (Nota Baixa ≤ 3)"}),e.jsx(O,{value:a.follow_up_question,onChange:m=>s(t=>({...t,follow_up_question:m.target.value})),placeholder:"Ex: O que poderíamos ter feito melhor?",className:"bg-background"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enviado automaticamente quando a nota é 3 ou inferior."})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t border-border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(v,{className:"text-sm font-medium",children:"Motivos Pré-Definidos (Nota Baixa)"}),e.jsx(E,{variant:"outline",className:"text-[10px]",children:"Opcional"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Quando configurados, o cliente pode selecionar um motivo antes de digitar o comentário. Enviados como opções numeradas junto da pergunta de investigação."}),e.jsxs("div",{className:"space-y-2",children:[(a.predefined_reasons||[]).map((m,t)=>
8e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs font-bold text-muted-foreground w-5 shrink-0",children:[t+1,"."]}),e.jsx(O,{value:m,onChange:u=>{const g=[...a.predefined_reasons||[]];g[t]=u.target.value,s(r=>({...r,predefined_reasons:g}))},className:"bg-background h-9 text-sm",placeholder:`Motivo ${t+1}`}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-9 w-9 p-0 shrink-0 text-muted-foreground hover:text-red-500",onClick:()=>{const u=(a.predefined_reasons||[]).filter((g,r)=>r!==t);s(g=>({...g,predefined_reasons:u}))},children:"×"})]},t)),(a.predefined_reasons||[]).length<5&&e.jsx(B,{variant:"outline",size:"sm",className:"w-full text-xs",onClick:()=>{s(m=>({...m,predefined_reasons:[...m.predefined_reasons||[],""]}))},children:"+ Adicionar motivo"})]}),(a.predefined_reasons||[]).length>0&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/50 border border-border",children:[e.jsx(F,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:'O cliente poderá responder com o número do motivo ou digitar livremente. O motivo selecionado será salvo no campo "razão" do feedback.'})]})]})]})})]}),e.jsx("div",{className:"xl:sticky xl:top-6 xl:self-start",children:e.jsxs("div",{className:"rounded-xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wider",children:"Preview WhatsApp"}),e.jsxs("div",{className:"inline-flex rounded-lg border border-border bg-muted/30 p-0.5",children:[e.jsx("button",{type:"button",onClick:()=>l("high"),className:R("px-2.5 py-1 text-[11px] font-medium rounded-md transition-colors",p==="high"?"bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900":"text-muted-foreground hover:text-foreground"),children:"Nota alta (≥4)"}),e.jsx("button",{type:"button",onClick:()=>l("low"),className:R("px-2.5 py-1 text-[11px] font-medium rounded-md transition-colors",p==="low"?"bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900":"text-muted-foreground hover:text-foreground"),children:"Nota baixa (≤3)"})]})]}),e.jsxs("div",{className:"max-w-sm mx-auto bg-[#e5ddd5] dark:bg-[#0b141a] rounded-xl shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-[#008069] dark:bg-[#1f2c34] px-4 py-3 flex items-center gap-3 text-white",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-white/20 flex items-center justify-center text-xs font-bold",children:(d=n[0])==null?void 0:d.toUpperCase()}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-sm",children:n}),e.jsx("div",{className:"text-[10px] opacity-70",children:"online"})]})]}),e.jsxs("div",{className:"p-3 space-y-2 min-h-[360px]",children:[e.jsxs("div",{className:"bg-white dark:bg-[#202c33] p-2.5 rounded-lg rounded-tl-none shadow-sm max-w-[88%]",children:[e.jsx("p",{className:"text-[13px] text-slate-800 dark:text-slate-100 leading-relaxed",dangerouslySetInnerHTML:{__html:re(x)}}),e.jsx("div",{className:"text-[10px] text-slate-400 text-right mt-1",children:"10:30 ✓✓"})]}),e.jsxs("div",{className:"bg-[#d9fdd3] dark:bg-[#005c4b] p-2.5 rounded-lg rounded-tr-none shadow-sm max-w-[60%] ml-auto",children:[e.jsx("p",{className:"text-[13px] text-slate-800 dark:text-slate-100",children:p==="high"?"5":"2"}),e.jsx("div",{className:"text-[10px] text-slate-400 text-right mt-1",children:"10:31"})]}),p==="high"?e.jsxs("div",{className:"bg-white dark:bg-[#202c33] p-2.5 rounded-lg rounded-tl-none shadow-sm max-w-[88%]",children:[e.jsx("p",{className:"text-[13px] text-slate-800 dark:text-slate-100 leading-relaxed",dangerouslySetInnerHTML:{__html:re(a.thank_you_message)}}),e.jsx("div",{className:"text-[10px] text-slate-400 text-right mt-1",children:"10:31 ✓✓"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-white dark:bg-[#202c33] p-2.5 rounded-lg rounded-tl-none shadow-sm max-w-[88%]",children:[e.jsx("p",{className:"text-[13px] text-slate-800 dark:text-slate-100 leading-relaxed whitespace-pre-line",dangerouslySetInnerHTML:{__html:re(i)}}),e.jsx("div",{className:"text-[10px] text-slate-400 text-right mt-1",children:"10:31 ✓✓"})]}),o.length===0&&e.jsx("p",{className:"text-center text-[10px] text-muted-foreground
8/70 italic pt-1",children:"Adicione motivos pré-definidos para facilitar a resposta do cliente."})]})]})]}),e.jsx("p",{className:"text-center text-[11px] text-muted-foreground mt-3",children:"Visualização aproximada. A aparência real pode variar."})]})})]})}export{Ya as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.