PageSourceSearch

https://www.xpark.ai/assets/AdminBandi-BdSGkY0i.js

js xpark.ai collected 2026-10-05 14:02:33 UTC 41,666 bytes, 23 lines download raw bytes

1import{h as we,aI as $e,ad as Ge,r as p,av as He,j as e,ai as Q,ae as Y,af as Fe,ag as se,aG as Ue,aF as We,al as Qe,d as I,g as R,f as te,B as A,J as X,aJ as he,aB as Xe,aK as Ye,a8 as ge,I as ae,K as Je,ab as Ze}from"./index-FWKSGZPO.js";import{L as z}from"./label--tnD4pjg.js";import{C as D,a as B,b as T,d as q,c as V}from"./card-DTQVPU97.js";import{S as ea,a as aa,b as ta,c as sa,d as ra}from"./select-CNpOZwnZ.js";import{c as ke}from"./index-BdQq_4o_.js";import{B as O}from"./badge-Cpd-8HxK.js";import{P as ve}from"./pencil-BFL_pWo_.js";import{S as ie}from"./save-BrOyRopU.js";import{S as na}from"./settings-2-BOYOyyl5.js";import{B as oa}from"./bot-BJNvdIwS.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const je=we("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const oe=we("UserRound",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);var Se=["PageUp","PageDown"],Ce=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Pe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},J="Slider",[de,ia,da]=$e(J),[Me,Ka]=Ge(J,[da]),[la,ne]=Me(J),Ee=p.forwardRef((r,n)=>{const{name:o,min:i=0,max:a=100,step:d=1,orientation:l="horizontal",disabled:m=!1,minStepsBetweenThumbs:x=0,defaultValue:j=[i],value:b,onValueChange:u=()=>{},onValueCommit:g=()=>{},inverted:k=!1,form:C,...s}=r,h=p.useRef(new Set),f=p.useRef(0),w=l==="horizontal"?ca:ma,[_=[],$]=He({prop:b,defaultProp:j,onChange:t=>{var y;(y=[...h.current][f.current])==null||y.focus(),u(t)}}),Z=p.useRef(_);function ee(t){const c=ha(_,t);K(t,c)}function G(t){K(t,f.current)}function H(){const t=Z.current[f.current];_[f.current]!==t&&g(_)}function K(t,c,{commit:y}={commit:!1}){const v=ba(d),N=ya(Math.round((t-i)/d)*d+i,v),P=ke(N,[i,a]);$((S=[])=>{const E=xa(S,P,c);if(ja(E,x*d)){f.current=E.indexOf(P);const L=String(E)!==String(S);return L&&y&&g(E),L?E:S}else return S})}return e.jsx(la,{scope:r.__scopeSlider,name:o,disabled:m,min:i,max:a,valueIndexToChangeRef:f,thumbs:h.current,values:_,orientation:l,form:C,children:e.jsx(de.Provider,{scope:r.__scopeSlider,children:e.jsx(de.Slot,{scope:r.__scopeSlider,children:e.jsx(w,{"aria-disabled":m,"data-disabled":m?"":void 0,...s,ref:n,onPointerDown:Q(s.onPointerDown,()=>{m||(Z.current=_)}),min:i,max:a,inverted:k,onSlideStart:m?void 0:ee,onSlideMove:m?void 0:G,onSlideEnd:m?void 0:H,onHomeKeyDown:()=>!m&&K(i,0,{commit:!0}),onEndKeyDown:()=>!m&&K(a,_.length-1,{commit:!0}),onStepKeyDown:({event:t,direction:c})=>{if(!m){const N=Se.includes(t.key)||t.shiftKey&&Ce.includes(t.key)?10:1,P=f.current,S=_[P],E=d*N*c;K(S+E,P,{commit:!0})}}})})})})});Ee.displayName=J;var[Re,Ae]=Me(J,{startEdge:"left",endEdge:"right",size:"width",direction:1}),ca=p.forwardRef((r,n)=>{const{min:o,max:i,dir:a,inverted:d,onSlideStart:l,onSlideMove:m,onSlideEnd:x,onStepKeyDown:j,...b}=r,[u,g]=p.useState(null),k=Y(n,w=>g(w)),C=p.useRef(void 0),s=Fe(a),h=s==="ltr",f=h&&!d||!h&&d;function M(w){const _=C.current||u.getBoundingClientRect(),$=[0,_.width],ee=pe($,f?[o,i]:[i,o]);return C.current=_,ee(w-_.left)}return e.jsx(Re,{scope:r.__scopeSlider,startEdge:f?"left":"right",endEdge:f?"right":"left",direction:f?1:-1,size:"width",children:e.jsx(De,{dir:s,"data-orientation":"horizontal",...b,ref:k,style:{...b.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const _=M(w.clientX);l==null||l(_)},onSlideMove:w=>{const _=M(w.clientX);m==null||m(_)},onSlideEnd:()=>{C.current=void 0,x==null||x()},onStepKeyDown:w=>{const $=Pe[f?"from-left":"from-right"].includes(w.key);j==null||j({event:w,direction:$?-1:1})}})})}),ma=p.forwardRef((r,n)=>{const{min:o,max:i,inverted:a,onSlideStart:d,onSlideMove:l,onSlideEnd:m,onStepKeyDown:x,...j}=r,b=p.useRef(null),u=Y(n,b),g=p.useRef(void 0),k=!a;function C(s){const h=g.current||b.current.getBoundingClientRect(),f=[0,h.height],w=pe(f,k?[i,o]:[o,i]);return g.current=h,w(s-h.top)}return e.jsx(Re,{scope:r.__scopeSlider,startEdge:k?"bottom":"top",endEdge:k?"top":"bottom",size:"height",direction:k?1:-1,children:e.jsx(De,{"data-orientation":"vertical",...j,ref:u,style:{...j.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:s=>{const h=C(s.clientY);d==null||d(h)},onSlideMove:s=>{const h=C(s.clientY);l==null||l(h)},onSlideEnd:()=>{g.current=void 0,m==null||m()},onStepKeyDown:s=>{const f=Pe[k?"from-bottom":"from-top"].includes(s.key);x==null||x({event:s,direction:f?-1:1})}})})}),De=p.forwardRef((r,n)=>{const{__scopeSlider:o,onSlideStart:i,onSlideMove:a,onSlideEnd:d,onHomeKeyDown:l,onEndKeyDown:m,onStepKeyDown:x,...j}=r,b=ne(J,o);return e.jsx(se.span,{...j,ref:n,onKeyDown:Q(r.onKeyDown,u=>{u.key==="Home"?(l(u),u.preventDefault()):u.key==="End"?(m(u),u.preventDefault()):Se.concat(Ce).includes(u.key)&&
11(x(u),u.preventDefault())}),onPointerDown:Q(r.onPointerDown,u=>{const g=u.target;g.setPointerCapture(u.pointerId),u.preventDefault(),b.thumbs.has(g)?g.focus():i(u)}),onPointerMove:Q(r.onPointerMove,u=>{u.target.hasPointerCapture(u.pointerId)&&a(u)}),onPointerUp:Q(r.onPointerUp,u=>{const g=u.target;g.hasPointerCapture(u.pointerId)&&(g.releasePointerCapture(u.pointerId),d(u))})})}),Be="SliderTrack",Te=p.forwardRef((r,n)=>{const{__scopeSlider:o,...i}=r,a=ne(Be,o);return e.jsx(se.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...i,ref:n})});Te.displayName=Be;var le="SliderRange",qe=p.forwardRef((r,n)=>{const{__scopeSlider:o,...i}=r,a=ne(le,o),d=Ae(le,o),l=p.useRef(null),m=Y(n,l),x=a.values.length,j=a.values.map(g=>Ie(g,a.min,a.max)),b=x>1?Math.min(...j):0,u=100-Math.max(...j);return e.jsx(se.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...i,ref:m,style:{...r.style,[d.startEdge]:b+"%",[d.endEdge]:u+"%"}})});qe.displayName=le;var ce="SliderThumb",ze=p.forwardRef((r,n)=>{const o=ia(r.__scopeSlider),[i,a]=p.useState(null),d=Y(n,m=>a(m)),l=p.useMemo(()=>i?o().findIndex(m=>m.ref.current===i):-1,[o,i]);return e.jsx(ua,{...r,ref:d,index:l})}),ua=p.forwardRef((r,n)=>{const{__scopeSlider:o,index:i,name:a,...d}=r,l=ne(ce,o),m=Ae(ce,o),[x,j]=p.useState(null),b=Y(n,M=>j(M)),u=x?l.form||!!x.closest("form"):!0,g=Ue(x),k=l.values[i],C=k===void 0?0:Ie(k,l.min,l.max),s=fa(i,l.values.length),h=g==null?void 0:g[m.size],f=h?ga(h,C,m.direction):0;return p.useEffect(()=>{if(x)return l.thumbs.add(x),()=>{l.thumbs.delete(x)}},[x,l.thumbs]),e.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[m.startEdge]:`calc(${C}% + ${f}px)`},children:[e.jsx(de.ItemSlot,{scope:r.__scopeSlider,children:e.jsx(se.span,{role:"slider","aria-label":r["aria-label"]||s,"aria-valuemin":l.min,"aria-valuenow":k,"aria-valuemax":l.max,"aria-orientation":l.orientation,"data-orientation":l.orientation,"data-disabled":l.disabled?"":void 0,tabIndex:l.disabled?void 0:0,...d,ref:b,style:k===void 0?{display:"none"}:r.style,onFocus:Q(r.onFocus,()=>{l.valueIndexToChangeRef.current=i})})}),u&&e.jsx(Ve,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:k},i)]})});ze.displayName=ce;var pa="RadioBubbleInput",Ve=p.forwardRef(({__scopeSlider:r,value:n,...o},i)=>{const a=p.useRef(null),d=Y(a,i),l=We(n);return p.useEffect(()=>{const m=a.current;if(!m)return;const x=window.HTMLInputElement.prototype,b=Object.getOwnPropertyDescriptor(x,"value").set;if(l!==n&&b){const u=new Event("input",{bubbles:!0});b.call(m,n),m.dispatchEvent(u)}},[l,n]),e.jsx(se.input,{style:{display:"none"},...o,ref:d,defaultValue:n})});Ve.displayName=pa;function xa(r=[],n,o){const i=[...r];return i[o]=n,i.sort((a,d)=>a-d)}function Ie(r,n,o){const d=100/(o-n)*(r-n);return ke(d,[0,100])}function fa(r,n){return n>2?`Value ${r+1} of ${n}`:n===2?["Minimum","Maximum"][r]:void 0}function ha(r,n){if(r.length===1)return 0;const o=r.map(a=>Math.abs(a-n)),i=Math.min(...o);return o.indexOf(i)}function ga(r,n,o){const i=r/2,d=pe([0,50],[0,i]);return(i-d(n)*o)*o}function va(r){return r.slice(0,-1).map((n,o)=>r[o+1]-n)}function ja(r,n){if(n>0){const o=va(r);return Math.min(...o)>=n}return!0}function pe(r,n){return o=>{if(r[0]===r[1]||n[0]===n[1])return n[0];const i=(n[1]-n[0])/(r[1]-r[0]);return n[0]+i*(o-r[0])}}function ba(r){return(String(r).split(".")[1]||"").length}function ya(r,n){const o=Math.pow(10,n);return Math.round(r*o)/o}var Ke=Ee,_a=Te,Na=qe,wa=ze;const Le=p.forwardRef(({className:r,...n},o)=>e.jsxs(Ke,{ref:o,className:Qe("relative flex w-full touch-none select-none items-center",r),...n,children:[e.jsx(_a,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(Na,{className:"absolute h-full bg-primary"})}),e.jsx(wa,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));
11Le.displayName=Ke.displayName;function W(r){return r.branch===!0}function me(r){return r.kind==="settings"}function ue(r){return r.kind==="ai"}function be(r){return!me(r)&&!ue(r)}const Oe=[{id:"inicio",title:"Início da conversa",description:"Primeiras trocas: como a Bandy recebe o cliente antes de qualquer qualificação.",kind:"main",nodes:[{kind:"settings",field:"welcome_message",title:"Saudação inicial",trigger:"Cliente manda a primeira mensagem"},{key:"saudacao_repetida",trigger:"Cliente cumprimenta de novo depois de já atendido"},{key:"triagem_menu",trigger:"A intenção do cliente não ficou clara"}]},{id:"qualificacao",title:"Qualificação",description:"Coleta dos dados mínimos (aeroporto, datas) antes de cotar.",kind:"main",nodes:[{key:"pedido_aeroporto",trigger:"Cliente quer reservar mas não disse o aeroporto"},{key:"pedido_datas",trigger:"Cliente não disse data/horário de entrada e saída"},{kind:"ai",title:"Interpretação de datas",trigger:"Cliente responde com data/horário em linguagem natural",description:"A IA interpreta datas em formato brasileiro (30/7 às 2h, amanhã 14h, meia-noite) e confirma com o cliente quando falta informação."}]},{id:"marcas",title:"Origens por marca (Valetina, Aerovalet, Multipark)",description:"Trilhas específicas de cada marca parceira, entre a qualificação e a cotação. Depois desta seção, o cliente entra no fluxo padrão de cotação.",kind:"branch",nodes:[{branch:!0,label:"Cliente chegou pelo site/botão da Multipark",nodes:[{key:"multipark_boas_vindas",trigger:"Cliente chega pela saudação automática do site da Multipark"},{key:"multipark_escopo",trigger:"Cliente pede unidade fora de GRU/VCP pelo canal Multipark"}]},{branch:!0,label:"Cliente cita Valetina ou Aerovalet (valet, só em GRU)",nodes:[{key:"valetina_pedido_datas",trigger:"Cliente quer valet mas ainda não informou as datas"},{key:"consultando_disponibilidade",trigger:"Cliente já deu as datas e a Bandy vai cotar"},{key:"valet_24h_aviso",trigger:"Entrada solicitada com menos de 24h de antecedência"},{key:"valet_vcp_indisponivel",trigger:"Cliente pede valet em VCP (não existe)"}]},{kind:"ai",title:"Cotação da marca",trigger:"Datas confirmadas",description:"Depois da qualificação da marca, a cotação, o seguro e o Pix seguem a trilha principal normalmente."}]},{id:"reserva",title:"Cotação",description:"Jornada padrão do cliente, do primeiro pedido de cotação até o Pix aprovado.",kind:"main",nodes:[{key:"cotacao_single",trigger:"Cliente pede cotação com aeroporto e datas",attached:[{key:"cotacao_pergunta_seguro",trigger:"Complemento quando a categoria é Coberta ou Descoberta"},{key:"cotacao_valet_cta",trigger:"Complemento quando a categoria é Valet"},{key:"cotacao_pergunta_confirmar",trigger:"Complemento quando o seguro já vem incluso"}]},{key:"seguro_adicionado",trigger:'Cliente aceita o seguro ("sim")'},{key:"pix_gerado",trigger:"Cliente confirma a reserva"},{key:"pagamento_pendente_1",trigger:'Cliente pergunta "já caiu?" ou avisa que pagou (1ª vez)'},{key:"pagamento_pendente_2",trigger:"Cliente insiste que pagou (2ª vez)"},{key:"pagamento_divergente_handoff",trigger:"Cliente insiste novamente sem que o pagamento tenha sido aprovado",handoff:!0},{branch:!0,label:"Ramo lateral — Comprovante recebido",nodes:[{key:"comprovante_recebido",trigger:"Cliente envia comprovante em PDF ou foto",handoff:!0}]},{branch:!0,label:"Ramo lateral — 2ª via do Pix",nodes:[{key:"pix_reenviado",trigger:"Cliente pede a 2ª via do Pix"}]}]},{id:"pos_pagamento",title:"Pós-pagamento",description:"O que acontece depois que o Pix é aprovado.",kind:"main",nodes:[{kind:"ai",title:"Coleta de dados do cliente",trigger:"Pix aprovado",description:"A IA coleta nome, placa e e-mail do cliente para liberar a entrada."},{kind:"settings",field:"confirmation_message",title:"Confirmação da reserva",trigger:"Dados completos, reserva confirmada"},{key:"pos_venda_followup",trigger:"Cliente com reserva volta com dúvida"}]},{id:"transferencia",title:"Transferência para humano",description:"Textos disparados sempre que a Bandy sai de cena e chama o time.",kind:"main",no
11des:[{kind:"settings",field:"transfer_message",title:"Mensagem de transferência",trigger:"Sempre que a Bandy transfere",handoff:!0},{key:"transferencia_confirmada",trigger:"Cliente aceitou a oferta de transferência"}]},{id:"desvios",title:"Desvios de rota",description:"Situações que podem acontecer a qualquer momento e mudam o rumo da conversa.",kind:"branch",nodes:[{branch:!0,label:"Cliente cita código de outro canal (HO-...) ou Elisa/Horácio, sem dizer que pagou",nodes:[{key:"outro_canal_oferta",trigger:"Bandy identifica menção a outro canal"},{key:"transferencia_confirmada",trigger:"Cliente aceita a transferência"}]},{branch:!0,label:"Cliente cita outro canal E diz que já pagou",nodes:[{key:"outro_canal_pago_handoff",trigger:"Menção a outro canal com pagamento já feito",handoff:!0}]},{branch:!0,label:"Cliente quer alterar reserva já feita",nodes:[{key:"alteracao_reserva_oferta",trigger:"Cliente pede alteração de reserva existente"},{key:"transferencia_confirmada",trigger:"Cliente aceita a transferência"}]},{branch:!0,label:"Pedido fora do escopo",nodes:[{key:"fora_escopo",trigger:"Pedido que a Bandy não cobre",handoff:!0}]}]},{id:"sistema",title:"Interno",description:"Mensagens que a Bandy dispara para o time, não para o cliente.",kind:"system",nodes:[{key:"handoff_alerta_time",trigger:"Enviada ao time no WhatsApp em toda transferência"}]}],ka=new Set(Oe.flatMap(r=>r.nodes.flatMap(n=>{if(W(n))return n.nodes.filter(be).flatMap(i=>[i.key]);if(!be(n))return[];const o=[n.key];return n.attached&&o.push(...n.attached.map(i=>i.key)),o})));function F(r){const n=new Set,o=/\{\s*([a-zA-Z0-9_]+)\s*\}/g;let i;for(;(i=o.exec(r))!==null;)n.add(i[1]);return[...n]}function ye(r){try{return new Date(r).toLocaleString("pt-BR")}catch{return r}}const _e=r=>`__settings__:${r}`;function Sa(){const[r,n]=p.useState(!0),[o,i]=p.useState([]),[a,d]=p.useState(null),[l,m]=p.useState(null),[x,j]=p.useState(""),[b,u]=p.useState(!1);p.useEffect(()=>{g()},[]);async function g(){n(!0);const[t,c]=await Promise.all([I.from("bandi_templates").select("key, stage, description, text, updated_at, updated_by").order("stage",{ascending:!0}).order("key",{ascending:!0}),I.from("bandi_settings").select("id, welcome_message, transfer_message, confirmation_message, updated_at").eq("singleton",!0).maybeSingle()]);t.error?(R.error("Erro ao carregar templates: "+t.error.message),i([])):i(t.data||[]),c.error?(R.error("Erro ao carregar settings: "+c.error.message),d(null)):d(c.data||null),n(!1)}const k=p.useMemo(()=>{const t=new Map;for(const c of o)t.set(c.key,c);return t},[o]),C=p.useMemo(()=>o.filter(t=>!ka.has(t.key)),[o]);function s(t){m(t.key),j(t.text)}function h(t){m(_e(t)),j(String((a==null?void 0:a[t])??""))}function f(){m(null),j("")}async function M(t){var E;const c=F(t.text),y=F(x),v=c.filter(L=>!y.includes(L));if(v.length>0&&!window.confirm(`Você removeu ${v.length===1?"o campo":"os campos"} { ${v.join(", ")} } do texto. Esses valores não aparecerão mais na mensagem enviada ao cliente. Deseja salvar mesmo assim?`))return;if(!x.trim()){R.error("O texto não pode ficar vazio.");return}u(!0);const{data:N}=await I.auth.getUser(),P=((E=N==null?void 0:N.user)==null?void 0:E.id)??null,{error:S}=await I.from("bandi_templates").update({text:x,updated_by:P}).eq("key",t.key);if(u(!1),S){R.error("Erro ao salvar: "+S.message);return}R.success("Template salvo. Efeito em até 1 minuto."),m(null),j(""),await g()}async function w(t){var xe;if(!a){R.error("Settings ainda não carregado.");return}const c=String(a[t]??""),y=F(c),v=F(x),N=y.filter(fe=>!v.includes(fe));if(N.length>0&&!window.confirm(`Você removeu ${N.length===1?"o campo":"os campos"} { ${N.join(", ")} } do texto. Esses valores não aparecerão mais na mensagem enviada ao cliente. Deseja salvar mesmo assim?`))return;if(!x.trim()){R.error("O texto não pode ficar vazio.");return}u(!0);const{data:P}=await I.auth.getUser(),S=((xe=P==null?void 0:P.user)==null?void 0:xe.id)??null,E={[t]:x,updated_by:S},{error:L}=await I.from("bandi_settings").update(E).eq("id",a.id);if(u(!1),L){R.error("Erro ao salvar: "+L.message);return}R.success("Mensagem salva. Efeito em até 1 minuto."),m(null),j(""),await g()}if(r)return e.jsx("div",{className:"flex items-center justify-center h-40",children:e.jsx(te,{className:"h-5 w-5 animate-spin text-muted-foreground"})});if(o.length===0&&!a)return e.jsx(D,{children:e.jsxs(B,{children:[e.jsx(T,{children:"Mensagens da Bandy"}),e.jsx(q,{children:"Nenhum template ou configuração cadastrada ainda."})]})});const _=t=>{const c=l===t.key,y=F(c?x:t.text);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:t.description||t.key}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-1",children:[e.jsx(O,{variant:"secondary",className:"font-mono text-[10px]",children:t.key}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["editado em ",ye(t.updated_at)]})]})]}),!c&&e.jsxs(A,{variant:"outline",size:"sm",onClick:()=>s(t),children:[e.jsx(ve,{className:"h-3.5 w-3.5 mr-1"})," Editar"]})]}),c?e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{className:"font-mono text-xs min-h-[120px]",value:x,onChange:v=>j(v.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{size:"sm",onClick:()=>M(t),disabled:b,children:[b?e.jsx(te,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(ie,{className:"h-3.5 w-3.5 mr-1"}),"Salvar"]}),e.jsxs(A,{size:"sm",variant:"ghost",onClick:f,disabled:b,children:[e.jsx(he,{className:"h-3.5 w-3.5 mr-1"})," Cancelar"]})]})]}):e.jsx("pre",{className:"whitespace-pre-wrap text-sm font-sans bg-muted/30 rounded p-3 border",children:t.text}),y.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Campos automáticos:"}),y.map(v=>e.jsx(O,{variant:"outline",className:"font-mono text-[10px]",children:`{${v}}`},v))]})]})},$=t=>{const c=String((a==null?void 0:a[t.field])??""),y=_e(t.field),v=l===y,N=F(v?x:c),P=t.handoff?"border-l-4 border-l-amber-500":"";return e.jsxs("div",{className:`rounded-lg border bg-card p-4 ${P}`,children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center rounded-full bg-primary/10 text-primary text-[11px] font-medium px-2 py-0.5",children:[e.jsx(oe,{className:"h-3 w-3 mr-1"}),"Quando: ",t.trigger]}),e.jsxs(O,{variant:"outline",className:"text-[10px]",children:[e.jsx(na,{className:"h-3 w-3 mr-1"})," configuração"]}),t.handoff&&e.jsx(O,{className:"bg-amber-500/15 text-amber-700 dark:text-amber-400 border-amber-500/30",variant:"outline",children:"transfere para humano"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-1",children:[e.jsxs(O,{variant:"secondary",className:"font-mono text-[10px]",children:["bandi_settings.",t.field]}),(a==null?void 0:a.updated_at)&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["editado em ",ye(a.updated_at)]})]})]}),!v&&a&&e.jsxs(A,{variant:"outline",size:"sm",onClick:()=>h(t.field),children:[e.jsx(ve,{className:"h-3.5 w-3.5 mr-1"})," Editar"]})]}),v?e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{className:"font-mono text-xs min-h-[120px]",value:x,onChange:S=>j(S.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{size:"sm",onClick:()=>w(t.field),disabled:b,children:[b?e.jsx(te,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(ie,{className:"h-3.5 w-3.5 mr-1"}),"Salvar"]}),e.jsxs(A,{size:"sm",variant:"ghost",onClick:f,disabled:b,children:[e.jsx(he,{className:"h-3.5 w-3.5 mr-1"})," Cancelar"]})]})]}):c?e.jsx("pre",{className:"whitespace-pre-wrap text-sm font-sans bg-muted/30 rounded p-3 border",children:c}):e.jsxs("div",{className:"text-xs text-muted-foreground italic",children:["Campo ",e.jsx("code",{className:"font-mono",children:t.field})," ainda sem texto configurado."]}),N.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Campos automáticos:"}),N.map(S=>e.jsx(O,{variant:"outline",className:"font-mono text-[10px]",children:`{${S}}`},S))]})]})]})},Z=t=>e.jsxs("div",{className:"rounded-lg border border-dashed bg-muted/20 p-4",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center rounded-full bg-primary/10 text-primary text-[11px] font-medium px-2 py-0.5",children:[e.jsx(oe,{className:"h-3 w-3 mr-1"}),"Quando: ",t.trigger]}),e.jsxs(O,{variant:"outline",className:"text-[10px]",children:[e.jsx(Ye,{className:"h-3 w-3 mr-1"})," IA conduz"]})]}),e.jsx("div",{className:"text-sm font-medium",children:t.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:t.description})]}),ee=t=>{const c=k.get(t.key),y=t.handoff?"border-l-4 border-l-amber-500":"";return e.jsxs("div",{className:`rounded-lg border bg-card p-4 ${y}`,children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center rounded-full bg-primary/10 text-primary text-[11px] font-medium px-2 py-0.5",children:[e.jsx(oe,{className:"h-3 w-3 mr-1"}),"Quando: ",t.trigger]}),t.handoff&&e.jsx(O,{className:"bg-amber-500/15 text-amber-700 dark:text-amber-400 border-amber-500/30",variant:"outline",children:"transfere para humano"})]}),c?_(c):e.jsxs("div",{className:"text-xs text-muted-foreground italic",children:["Mensagem ",e.jsx("code",{className:"font-mono",children:t.key})," ainda não cadastrada no banco."]}),t.attached&&t.attached.length>0&&e.jsxs("div",{className:"mt-4 space-y-3 border-t pt-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Complementos disparados de
11ntro deste passo"}),t.attached.map(v=>{const N=k.get(v.key);return e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[e.jsx("div",{className:"mb-2",children:e.jsxs("span",{className:"inline-flex items-center rounded-full bg-secondary text-secondary-foreground text-[11px] px-2 py-0.5",children:["Quando: ",v.trigger]})}),N?_(N):e.jsxs("div",{className:"text-xs text-muted-foreground italic",children:["Mensagem ",e.jsx("code",{className:"font-mono",children:v.key})," ainda não cadastrada no banco."]})]},v.key)})]})]})},G=t=>me(t)?$(t):ue(t)?Z(t):ee(t),H=(t,c)=>me(t)?`settings:${t.field}:${c}`:ue(t)?`ai:${t.title}:${c}`:`${t.key}-${c}`,K=()=>e.jsx("div",{className:"flex justify-center py-1","aria-hidden":!0,children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsx(Xe,{className:"h-3.5 w-3.5 text-muted-foreground -mt-1"})]})});return e.jsxs(D,{children:[e.jsxs(B,{children:[e.jsx(T,{children:"Fluxo de atendimento da Bandy"}),e.jsx(q,{children:"Veja a jornada do cliente de cima para baixo, com o gatilho que dispara cada mensagem. Edite qualquer texto no próprio nó. As alterações entram em vigor em até 1 minuto."})]}),e.jsxs(V,{className:"space-y-8",children:[e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-xs text-muted-foreground",children:["Mantenha os campos entre chaves (ex.: ",e.jsx("code",{className:"font-mono",children:"{valor}"}),","," ",e.jsx("code",{className:"font-mono",children:"{codigo_reserva}"}),") intactos, pois são preenchidos automaticamente no envio."]}),Oe.map(t=>e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide",children:t.title}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:t.description})]}),t.kind==="main"?e.jsx("div",{className:"space-y-0",children:t.nodes.map((c,y)=>{const v=W(c)?`branch-${y}`:H(c,y),N=t.nodes[y-1],P=y>0&&!W(c)&&N&&!W(N);return e.jsxs("div",{children:[P&&K(),W(c)?e.jsxs("div",{className:"mt-3 ml-4 sm:ml-8 border-l-2 border-l-amber-500/40 pl-4 space-y-3",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wide text-amber-700 dark:text-amber-400",children:c.label}),c.nodes.map((S,E)=>e.jsx("div",{children:G(S)},H(S,E)))]}):G(c)]},v)})}):e.jsx("div",{className:"space-y-4",children:t.nodes.map((c,y)=>W(c)?e.jsxs("div",{className:"ml-2 sm:ml-4 border-l-2 border-l-amber-500/40 pl-4 space-y-3",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wide text-amber-700 dark:text-amber-400",children:c.label}),c.nodes.map((v,N)=>e.jsxs("div",{children:[N>0&&K(),G(v)]},H(v,N)))]},`br-${y}`):e.jsx("div",{children:G(c)},H(c,y)))})]},t.id)),C.length>0&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide",children:"Outras mensagens"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Templates cadastrados no banco que ainda não estão mapeados no fluxo acima."})]}),e.jsx("div",{className:"space-y-3",children:C.map(t=>e.jsx("div",{className:"rounded-lg border bg-card p-4",children:_(t)},t.key))})]})]})]})}const U={bot_name:"Bandy",empresa:"xpark",aeroportos:"GRU, VCP, CNF ou CGH",canal_atendimento:"WhatsApp",tom:"direto, curto, prático, WhatsApp brasileiro",assinatura_voucher:"O número de contato do dia da reserva sai no voucher",link_reembolso:"https://cx.bandeirapark.online/solicitar-cancelamento",horario_equipe:"segunda a sexta, das 8h às 18h"},re=`Olá {{nome}}! Sua reserva no Xpark.ai foi confirmada.
12
13Código da reserva: {{codigo}}
14Período: {{periodo_inicio}}{{entrada_hora_sep}} a {{periodo_fim}}{{saida_hora_sep}}
15Total: {{total}}{{bloco_servico}}{{bloco_endereco}}
16
17Qualquer dúvida, é só responder esta mensagem (informe o código {{codigo}} se precisar de suporte).`,Ne=[{key:"nome",desc:"primeiro nome do cliente"},{key:"codigo",desc:"código da reserva (ex: XPARKGRU-7F3A9K)"},{key:"periodo_inicio",desc:"data de início (DD/MM/AAAA)"},{key:"periodo_fim",desc:"data de fim (DD/MM/AAAA)"},{key:"entrada_hora",desc:"hora de entrada (HH:MM, vazio se não houver)"},{key:"saida_hora",desc:"hora de saída (HH:MM, vazio se não houver)"},{key:"entrada_hora_sep",desc:"' às HH:MM' pronto pra colar depois da data de entrada"},{key:"saida_hora_sep",desc:"' às HH:MM' pronto pra colar depois da data de saída"},{key:"total",desc:"valor formatado (R$ 0,00)"},{key:"unidade",desc:"nome da unidade"},{key:"endereco",desc:"endereço da unidade"},{key:"maps",desc:"link do Google Maps"},{key:"bloco_endereco",desc:"bloco pronto de endereço (vazio se não houver)"},{key:"tipo_vaga",desc:"tipo do serviço (Vaga coberta, Vaga descoberta, Valet)"},{key:"bloco_servico",desc:"linha pronta com o tipo de vaga (vazio se desconhecido)"}];function Ca(r){const n={nome:"Lucas",codigo:"XPARKGRU-7F3A9K",periodo_inicio:"13/06/2026",periodo_fim:"15/06/2026",entrada_hora:"11:00",saida_hora:"15:00",entrada_hora_sep:" às 11:00",
17saida_hora_sep:" às 15:00",total:"R$ 44,38",unidade:"Bandeira Park GRU",endereco:"Av. Monteiro Lobato, 1234 - Guarulhos/SP",maps:"https://maps.google.com/?q=Bandeira+Park+GRU",bloco_endereco:`
18
19Endereço da unidade:
20Bandeira Park GRU
21Av. Monteiro Lobato, 1234 - Guarulhos/SP
22https://maps.google.com/?q=Bandeira+Park+GRU`,tipo_vaga:"Vaga coberta",bloco_servico:`
23🅿️ Serviço: Vaga coberta`};return r.replace(/\{\{\s*([a-z_]+)\s*\}\}/gi,(o,i)=>n[i.toLowerCase()]??`{{${i}}}`)}const Pa=[{value:"google/gemini-2.5-flash",label:"Gemini 2.5 Flash (recomendado)"},{value:"google/gemini-2.5-pro",label:"Gemini 2.5 Pro (mais caro)"},{value:"google/gemini-2.5-flash-lite",label:"Gemini 2.5 Flash Lite (econômico)"},{value:"google/gemini-3-flash-preview",label:"Gemini 3 Flash Preview"},{value:"openai/gpt-5",label:"GPT-5"},{value:"openai/gpt-5-mini",label:"GPT-5 Mini"}],Ma={greeting:"Saudação",qualifying:"Qualificando",quoting:"Cotando",closing:"Fechando",payment:"Pagamento",paid:"Pago",post_sale:"Pós-venda",human_handoff:"Humano"};function La(){const[r,n]=p.useState(!0),[o,i]=p.useState(!1),[a,d]=p.useState(null),[l,m]=p.useState(null),[x,j]=p.useState([]);p.useEffect(()=>{u(),b()},[]);async function b(){const{data:s}=await I.from("bandi_conversation_state").select("phone, stage, slots, turnos_sem_progresso, ultimo_turno_em").order("ultimo_turno_em",{ascending:!1}).limit(30);j(s||[])}async function u(){n(!0);const{data:s,error:h}=await I.from("bandi_settings").select("*").eq("singleton",!0).maybeSingle();h&&R.error("Erro ao carregar configurações"),s&&(d(s),m(s)),n(!1)}async function g(){if(!a)return;i(!0);const{error:s}=await I.from("bandi_settings").update({bot_name:a.bot_name,model:a.model,temperature:a.temperature,enabled:a.enabled,system_prompt:a.system_prompt,welcome_message:a.welcome_message,transfer_message:a.transfer_message,daily_token_budget:a.daily_token_budget,max_stuck_turns:a.max_stuck_turns,handoff_on_budget:a.handoff_on_budget,template_vars:a.template_vars||{},confirmation_message:a.confirmation_message}).eq("id",a.id);if(i(!1),s){R.error("Erro ao salvar: "+s.message);return}R.success("Configurações salvas. Aplicadas na próxima mensagem."),m(a)}function k(){l&&d(l)}const C=a&&l&&JSON.stringify(a)!==JSON.stringify(l);return r?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(te,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-semibold flex items-center gap-2",children:[e.jsx(oa,{className:"h-6 w-6"})," ",a.bot_name||"Bandy"," IA"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Personalize o comportamento da assistente que responde no WhatsApp."})]}),e.jsxs("div",{className:"flex gap-2",children:[C&&e.jsxs(A,{variant:"outline",onClick:k,disabled:o,children:[e.jsx(je,{className:"h-4 w-4 mr-2"})," Descartar"]}),e.jsxs(A,{onClick:g,disabled:!C||o,children:[o?e.jsx(te,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ie,{className:"h-4 w-4 mr-2"}),"Salvar"]})]})]}),e.jsxs(D,{children:[e.jsxs(B,{children:[e.jsx(T,{children:"Geral"}),e.jsx(q,{children:"Ativação global e identidade do bot."})]}),e.jsxs(V,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx(z,{className:"text-sm",children:"Bandy ativa globalmente"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Se desligar, nenhuma conversa receberá resposta automática."})]}),e.jsx(ge,{checked:a.enabled,onCheckedChange:s=>d({...a,enabled:s})})]}),e.jsxs("div",{className:"grid gap-2 max-w-sm",children:[e.jsx(z,{children:"Nome do bot"}),e.jsx(ae,{value:a.bot_name,onChange:s=>d({...a,bot_name:s.target.value})})]})]})]}),e.jsxs(D,{children:[e.jsxs(B,{children:[e.jsx(T,{children:"Modelo"}),e.jsx(q,{children:"Modelo de IA e nível de criatividade nas respostas."})]}),e.jsxs(V,{className:"space-y-5",children:[e.jsxs("div",{className:"grid gap-2 max-w-md",children:[e.jsx(z,{children:"Modelo"}),e.jsxs(ea,{value:a.model,onValueChange:s=>d({...a,model:s}),children:[e.jsx(aa,{children:e.jsx(ta,{})}),e.jsx(sa,{children:Pa.map(s=>e.jsx(ra,{value:s.value,children:s.label},s.value))})]})]}),e.jsxs("div",{className:"space-y-2 max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(z,{children:"Temperatura"}),e.jsx("span",{className:"text-sm tabular-nums text-muted-foreground",children:Number(a.temperature).toFixed(2)})]}
23),e.jsx(Le,{value:[Number(a.temperature)],min:0,max:1,step:.05,onValueChange:([s])=>d({...a,temperature:s})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"0 = previsível e direta · 1 = mais criativa. Recomendado: 0.2–0.4."})]})]})]}),e.jsxs(D,{children:[e.jsxs(B,{children:[e.jsx(T,{children:"Variáveis de personalização"}),e.jsxs(q,{children:["Valores reutilizáveis dentro do prompt e das mensagens fixas. Use a sintaxe ",e.jsx("code",{children:"{{chave}}"})," no prompt."]})]}),e.jsxs(V,{className:"space-y-3",children:[Object.entries({...U,...a.template_vars||{}}).map(([s,h])=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ae,{className:"font-mono text-xs max-w-[220px]",value:s,onChange:f=>{const M=f.target.value.replace(/[^a-zA-Z0-9_]/g,""),w={...a.template_vars||U},_=w[s];delete w[s],M&&(w[M]=_??""),d({...a,template_vars:w})}}),e.jsx(ae,{value:String(h??""),onChange:f=>{const M={...a.template_vars||U};M[s]=f.target.value,d({...a,template_vars:M})}}),e.jsx(A,{variant:"ghost",size:"icon",onClick:()=>{const f={...a.template_vars||U};delete f[s],d({...a,template_vars:f})},children:e.jsx(Je,{className:"h-4 w-4"})})]},s)),e.jsxs(A,{variant:"outline",size:"sm",onClick:()=>{const s={...a.template_vars||U};let h=1;for(;s[`var_${h}`]!==void 0;)h++;s[`var_${h}`]="",d({...a,template_vars:s})},children:[e.jsx(Ze,{className:"h-4 w-4 mr-1"})," Adicionar variável"]})]})]}),e.jsxs(D,{children:[e.jsxs(B,{children:[e.jsx(T,{children:"Prompt do sistema"}),e.jsx(q,{children:"Define identidade, tom, regras e fluxo de atendimento da Bandy."})]}),e.jsxs(V,{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Inserir variável:"}),Object.keys({...U,...a.template_vars||{}}).map(s=>e.jsx("button",{type:"button",onClick:()=>d({...a,system_prompt:(a.system_prompt||"")+` {{${s}}}`}),className:"text-[11px] font-mono px-2 py-0.5 rounded border bg-muted hover:bg-accent transition",children:`{{${s}}}`},s))]}),e.jsx(X,{className:"font-mono text-xs min-h-[420px]",value:a.system_prompt,onChange:s=>d({...a,system_prompt:s.target.value})}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Use ",e.jsx("code",{children:"{{chave}}"}),' para inserir valores definidos no card "Variáveis de personalização" acima. Substituição acontece em tempo de execução.']})]})]}),e.jsxs(D,{children:[e.jsxs(B,{children:[e.jsx(T,{children:"Mensagens fixas"}),e.jsx(q,{children:"Textos que a Bandy usa em situações específicas."})]}),e.jsxs(V,{className:"space-y-5",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(z,{children:"Mensagem de transferência para humano"}),e.jsx(X,{value:a.transfer_message,onChange:s=>d({...a,transfer_message:s.target.value}),rows:2})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(z,{children:"Mensagem de boas-vindas (opcional)"}),e.jsx(X,{placeholder:"Ex.: Olá! Sou a Bandy, posso ajudar com sua reserva?",value:a.welcome_message||"",onChange:s=>d({...a,welcome_message:s.target.value}),rows:2})]})]})]}),e.jsxs(D,{children:[e.jsxs(B,{children:[e.jsx(T,{children:"Mensagem de confirmação de reserva"}),e.jsx(q,{children:"Texto enviado automaticamente no WhatsApp logo após a reserva ser confirmada. Deixe vazio para usar o padrão."})]}),e.jsxs(V,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Inserir variável:"}),Ne.map(s=>e.jsx("button",{type:"button",title:s.desc,onClick:()=>d({...a,confirmation_message:(a.confirmation_message??re)+` {{${s.key}}}`}),className:"text-[11px] font-mono px-2 py-0.5 rounded border bg-muted hover:bg-accent transition",children:`{{${s.key}}}`},s.key)),e.jsxs(A,{type:"button",variant:"outline",size:"sm",className:"ml-auto",onClick:()=>d({...a,confirmation_message:re}),children:[e.jsx(je,{className:"h-3.5 w-3.5 mr-1"})," Restaurar padrão"]})]}),e.jsx(X,{className:"font-mono text-xs min-h-[180px]",placeholder:re,value:a.confirmation_message??"",onChange:s=>d({...a,confirmation_message:s.target.value})}),e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Pré-visualização"}),e.jsx("pre",{className:"whitespace-pre-wrap text-xs font-sans",children:Ca(a.confirmation_message||re)})]}),e.jsx("ul",{className:"text-[11px] text-muted-foreground grid sm:grid-cols-2 gap-x-4",children:Ne.map(s=>e.jsxs("li",{children:[e.jsx("code",{className:"font-mono",children:`{{${s.key}}}`}),": ",s.desc]},s.key))})]})]}),e.jsxs(D,{children:[e.jsxs(B,{children:[e.jsx(T,{children:"Limites e custo"}),e.jsx(q,{children:"Controle quando a Bandy pausa e transfere para humano."})]}),e.jsxs(V,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx(z,{className:"text-sm",children:"Transferir para humano ao estourar orçamento"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Se desligado, a Bandy nunca é interrompida por custo, só pelo botão manual."})]}),e.jsx(ge,{checked:a.handoff_on_budget,onCheckedChange:s=>d({...a,handoff_on_budget:s})})]}),e.jsxs("div",{className:"grid gap-2 max-w-sm",children:[e.jsx(z,{children:"Orçamento diário de tokens por conversa"}),e.jsx(ae,{type:"number",min:1e4,step:1e4,value:a.daily_token_budget,onChange:s=>d({...a,daily_token_budget:Math.max(0,Number(s.target.value)||0)}),disabled:!a.handoff_on_budget}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Soma dos tokens usados nas últimas 24h, por telefone. Padrão: 500.000. Referência: Gemini Flash ≈ 1.000 mensagens longas."})]}),e.jsxs("div",{className:"grid gap-2 max-w-sm",children:[e.jsx(z,{children:"Máximo de turnos sem progresso"}),e.jsx(ae,{type:"number",min:1,max:50,value:a.max_stuck_turns,onChange:s=>d({...a,max_stuck_turns:Math.max(1,Number(s.target.value)||1)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Quantas mensagens seguidas sem avanço (sem novos dad
23os / mudança de estágio) antes de transferir para humano. Padrão: 8."})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Última atualização: ",new Date(a.updated_at).toLocaleString("pt-BR")]}),e.jsx(Sa,{}),e.jsxs(D,{children:[e.jsxs(B,{children:[e.jsx(T,{children:"Conversas ativas"}),e.jsx(q,{children:"Estágio da máquina de estados e slots coletados por telefone (últimas 30)."})]}),e.jsxs(V,{children:[x.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma conversa registrada ainda."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left border-b",children:[e.jsx("th",{className:"py-2 pr-3",children:"Telefone"}),e.jsx("th",{className:"py-2 pr-3",children:"Estágio"}),e.jsx("th",{className:"py-2 pr-3",children:"Slots"}),e.jsx("th",{className:"py-2 pr-3",children:"Stuck"}),e.jsx("th",{className:"py-2 pr-3",children:"Último turno"})]})}),e.jsx("tbody",{children:x.map(s=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-2 pr-3 font-mono",children:s.phone}),e.jsx("td",{className:"py-2 pr-3",children:e.jsx("span",{className:"inline-block px-2 py-0.5 rounded bg-secondary text-secondary-foreground",children:Ma[s.stage]||s.stage})}),e.jsx("td",{className:"py-2 pr-3 text-muted-foreground",children:Object.entries(s.slots||{}).filter(([h,f])=>f!==null&&f!==""&&f!==void 0).map(([h])=>h).join(", ")||"—"}),e.jsx("td",{className:"py-2 pr-3",children:s.turnos_sem_progresso}),e.jsx("td",{className:"py-2 pr-3 text-muted-foreground",children:new Date(s.ultimo_turno_em).toLocaleString("pt-BR")})]},s.phone))})]})}),e.jsx(A,{variant:"outline",size:"sm",className:"mt-3",onClick:b,children:"Atualizar"})]})]})]}):e.jsx("div",{className:"text-muted-foreground",children:"Nenhuma configuração encontrada."})}export{La 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.