1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BIzC3cLR.js","assets/COEsLHzF.js","assets/oJORGrjm.js","assets/B_0kXcuF.js","assets/DMm19d_b.js","assets/CyTcV1HU.js","assets/ClQeOjb7.js","assets/BaUacaRV.css","assets/S9VL_FhF.js","assets/DKjngN3Y.js","assets/BNdKR4Be.js","assets/BG3Sr4sx.js","assets/DwaTYf47.js","assets/ZWnnYSKs.js","assets/i8SO6cQl.js","assets/CbUpFlNf.js","assets/-att7kCV.js","assets/BTpdryHs.js","assets/DFdiJ1zT.js","assets/CURxehD6.js","assets/B-Fj82ii.js","assets/B6Wo5w2J.js","assets/C7FCWddm.js","assets/Bq1nbi-v.js","assets/FzBzSa_Y.js","assets/Bk5Hi5Mj.js","assets/BGt4VeKt.js","assets/BrqojTwk.js","assets/00tJghhi.js","assets/BrPuZavG.js","assets/BEenXsmd.js","assets/BY4HV-E6.js","assets/CaZw19MX.js","assets/DNRH5cMW.js","assets/BuG1THjb.js","assets/BrUH-3Z0.js","assets/V3x1wQE9.js","assets/N3splImn.js","assets/aHtmLCPF.js","assets/Bbzs22Yf.js","assets/Dk-SmNEj.js","assets/fO7fCnet.js","assets/3gFLmZoM.js","assets/DFCjkFV_.js","assets/BVR2grFz.js","assets/BJrDj_s1.js","assets/CvZ7Py9m.js","assets/YoPdeMQ5.js","assets/CE41C5T9.js","assets/C14hJf2Y.js","assets/DyAln150.js","assets/Bkdor74m.js","assets/D9LNXo46.js","assets/BlNcDnSz.js","assets/FS-saTdW.js","assets/D1nsa41v.js","assets/BJ1HIeMK.js","assets/B858MHld.js","assets/Bx0jTMU0.js","assets/CzP5vppB.js","assets/DEZ4TZ-R.js","assets/C0JjrY_3.js","assets/CR9XBSx0.js","assets/B6_GAPGM.js","assets/CNanFAST.js","assets/lIc8sPXL.js","assets/C07X6vC5.js","assets/BFsMTLnv.js","assets/BaQnULil.js","assets/DYTDfvC6.js","assets/CvqGuR9D.js","assets/CHNz8pI4.js","assets/Cs995y61.js","assets/NB0RTxLC.js","assets/CrClQepC.js","assets/B6Wa1b0B.js","assets/DKeMc9Dx.js","assets/BvOP0y2S.js","assets/CVghWHt6.js","assets/G_kzsMBZ.js","assets/B23Di4IF.js","assets/CX6thxh2.js","assets/BVln8Uht.js","assets/Bwtxn6LJ.js","assets/FlwxkqT-.js","assets/bS525dic.js","assets/Bg_S_ZeT.js","assets/Ctki_sAb.js","assets/Dbct9KQ1.js","assets/vC6cXO12.js","assets/CaV0bD4b.js","assets/BjapoYo5.js","assets/CWY0TOy0.js","assets/BWbQgJqL.js","assets/DwUlxQcU.js"])))=>i.map(i=>d[i]); 2import{q as $m,r as n,j as e,s as Pm,t as bd,u as Mm,v as vd,w as jd,x as yd,y as Tm,R as Mn,a as Nd}from"./COEsLHzF.js";import{a as _e,X as vt,w as Ce,x as Im,l as Sa,aM as Tn,A as Lm,b as rn,r as on,j as Wr,n as He,p as At,av as Ge,_ as ot,B as Pe,o as le,F as Xt,Q as Rm,P as ci,T as di,W as dt,O as ln,G as ui,H as mi,I as pi,J as xi,K as fi,M as hi,Y as As,aN as cn,aw as Om,a0 as Tr,aO as Rn,h as wd,t as Fm,ak as zm,aF as Ra,aG as Oa,aH as Fa,aP as xt,aC as en,aI as qm,aQ as Bm,aR as fo,ap as Ko,D as On,E as Um,aS as Hm,aT as Vm,aU as Ir,aV as kd,aW as Cd,aj as Hl,ai as Vl,S as Qo,d as Jo,e as Xo,f as Zo,g as Qs,aX as gi,aY as Sd,$ as Va,U as bi,k as Us,ab as Yo,L as Wm,aL as Gm,a8 as ho,a9 as go,aa as bo,a3 as _d,a4 as Ad,a5 as Ed,ad as Km,a7 as Qm,ac as Jm,aZ as Xm,az as Wl,a_ as Gl,aJ as Zm,R as Ym}from"./oJORGrjm.js";import{a as ep,c as tp,b as Kl}from"./DMm19d_b.js";import{c as Fn,i as Dd}from"./CVghWHt6.js";import{l as ap}from"./CyTcV1HU.js";import{a as vo,b as sp,W as np,w as Je}from"./DFCjkFV_.js";import{j as rp,k as _r,m as $d,t as vi,n as op,r as Pd,o as ip,C as ca,p as da,q as Xs,v as lp,w as Ar,x as Ql,y as cp,M as Rt,z as dp,A as up,D as _n,B as jo,E as mp,F as pp,G as xp,l as fp,H as hp,I as gp,c as bp,J as vp,g as Jl,K as jp,L as yp,N as Xl,O as Np,P as wp,Q as kp,R as Cp,S as Sp,T as Md,U as Td,V as ei,W as _p,X as Ap,Y as Ep,Z as fr,_ as Dp,$ as Zl,a0 as $p,a1 as Id,a2 as Pp,a3 as Mp,a4 as Tp,a5 as Ip,a6 as Ld,a7 as Lp,a8 as Rd,a9 as Rp,aa as Op,ab as Yl,a as Fp,ac as zp,ad as ec}from"./BWbQgJqL.js";import{c as qp,e as tc,d as ti,g as Lr,G as Od,h as Er,i as ac,W as Fd,j as Bp,k as Up}from"./Bkdor74m.js";import{u as ls,a as zd,P as qd}from"./CM0lWAG2.js";import{L as Hp}from"./gNgABFeC.js";import{W as Ua}from"./BMoX2S_x.js";import{T as ds}from"./DNRH5cMW.js";import{P as Dr}from"./C07X6vC5.js";import{M as ji}from"./C7FCWddm.js";import{T as Ba}from"./BG3Sr4sx.js";import{S as Vp}from"./Bq1nbi-v.js";import{T as Wp}from"./0KElVN4_.js";import{F as ai}from"./zXJJRCbr.js";import{Z as Es}from"./B23Di4IF.js";import{R as jt}from"./BGt4VeKt.js";import{u as Gn,c as Gp}from"./BJ1HIeMK.js";import{u as yi}from"./DyAln150.js";import{n as Ni}from"./bS525dic.js";import{u as Bd,a as Ud,P as Hd,D as Vd,e as Wd,S as Gd,v as Kd,f as Qd,g as Jd,C as Xd}from"./BUXPTkoM.js";import{b as Zd,e as Kp,r as Qp,j as Jp,l as Xp,c as Zp}from"./BVmmH2wp.js";import{C as Yp}from"./BJrDj_s1.js";import{S as Ha,H as ex,I as tx}from"./LF1qietP.js";import{P as us}from"./aHtmLCPF.js";import{T as Yd}from"./B6_GAPGM.js";import{M as ax}from"./D23bo3qs.js";import{S as xa}from"./-att7kCV.js";import{C as os}from"./Dfmaa1lY.js";import{E as Kn}from"./BnhaXou-.js";import{L as Rr}from"./CvqGuR9D.js";import{I as ma}from"./S9VL_FhF.js";import{L as Ft}from"./DKjngN3Y.js";import{B as ft}from"./DEZ4TZ-R.js";import{r as sx,e as sc,Q as nx}from"./DwUlxQcU.js";import{D as cs}from"./BVln8Uht.js";import{B as rx,E as ox,S as ix,D as lx}from"./fCD-e6AB.js";import{A as nc,a as rc,b as oc,c as ic,d as lc,e as cc,f as dc,g as uc}from"./B0thWzaQ.js";import{C as _t}from"./B-Fj82ii.js";import{C as ms}from"./CX6thxh2.js";import{A as dn}from"./Bwtxn6LJ.js";import{e as cx,g as dx,o as ux,p as mx,k as px}from"./BEenXsmd.js";import{C as un}from"./BnQYDur2.js";import{B as eu}from"./CrClQepC.js";import{M as fa}from"./B858MHld.js";import{U as tn}from"./CGkvZZNN.js";import{H as ws}from"./BjapoYo5.js";import{S as zn}from"./CR9XBSx0.js";import{C as wi}from"./N3splImn.js";import{C as ki}from"./CaZw19MX.js";import{U as xx}from"./DwaTYf47.js";import{f as Ci,m as tu,u as fx,a as au}from"./BCUs_VwF.js";import{f as hr}from"./D1nsa41v.js";import{F as yo}from"./Bg_S_ZeT.js";import{U as ps}from"./CURxehD6.js";import{E as hx,P as gx,U as bx,S as gr,b as mc}from"./Bzx4WRn5.js";import{C as su}from"./B6Wo5w2J.js";import{P as nu}from"./BBT5dB4g.js";import{P as Si}from"./DYTDfvC6.js";import{T as vx,a as jx,b as It,c as Lt}from"./C14hJf2Y.js";import{S as an}from"./CbUpFlNf.js";import{A as Ds,a as $s}from"./fIe1M0ga.js";import{C as qn,b as Or,c as Fr,a as Bn}from"./FS-saTdW.js";import{S as _i}from"./Bi8j29vI.js";import{c as No}from"./3gFLmZoM.js";import{I as sn}from"./BuG1THjb.js";import{S as Ai}from"./ZWnnYSKs.js";import{F as yx}from"./DUbsu2EG.js";import{A as Nx}from"./Ctki_sAb.js";import{P as wx}from"./Bbzs22Yf.js";import{E as kx}from"./BrUH-3Z0.js";import{E as Zs}from"./V3x1wQE9.js";import{M as Cx}from"./CaV0bD4b.js";import{M as Sx,r as _x}from"./C7I-IOWA.js";import{P as Ax}from"./BUiLPSH4.js";import{B as Ex}from"./DQzYZaBa.js";import{C as Dx,L as pc}from"./DQw3y7wr.js";import{C as ru}from"./CHNz8pI4.js";import{f as $x,d as Px}from"./BVR2grFz.js";import{T as Mx}from"./Bk5Hi5Mj.js";import{T as Tx}from"./D8QIF3_T.js";import{M as Ix}from"./vC6cXO12.js";import{m as wo,A as ou}from"./ClQeOjb7.js";import{Q as Lx}from"./DgPGqVYt.js";import{S as iu,K as Rx}from"./DT8Jgmbf.js";import{C as Ox}from"./BrqojTwk.js";import"./B_0kXcuF.js";import"./B5TQz8vf.js";import"./DPnhO5mb.js";import"./BHyqBTAt.js";import"./ondRvA6s.js";import"./CNanFAST.js";import"./Cs995y61.js";import"./BZLFhR2c.js";import"./BvOP0y2S.js";import"./DFF2eNqR.js";import"./DKeMc9Dx.js";/** 3 * @license lucide-react v0.462.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const An=_e("Angry",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 16s-1.5-2-4-2-4 2-4 2",key:"epbg0q"}],["path",{d:"M7.5 8 10 9",key:"olxxln"}],["path",{d:"m14 9 2.5-1",key:"1j6cij"}],["path",{d:"M9 10h.01",key:"qbtxuw"}],["path",{d:"M15 10h.01",key:"1qmjsl"}]]);/** 8 * @license lucide-react v0.462.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const Fx=_e("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);/** 13 * @license lucide-react v0.462.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const zx=_e("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/** 18 * @license lucide-react v0.462.0 - ISC 19 * 20 * This source code is licensed under the ISC license. 21 * See the LICENSE file in the root directory of this source tree. 22 */const qx=_e("AudioWaveform",[["path",{d:"M2 13a2 2 0 0 0 2-2V7a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0V4a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0v-4a2 2 0 0 1 2-2",ke
22y:"57tc96"}]]);/** 23 * @license lucide-react v0.462.0 - ISC 24 * 25 * This source code is licensed under the ISC license. 26 * See the LICENSE file in the root directory of this source tree. 27 */const Bx=_e("ChartNoAxesColumn",[["line",{x1:"18",x2:"18",y1:"20",y2:"10",key:"1xfpm4"}],["line",{x1:"12",x2:"12",y1:"20",y2:"4",key:"be30l9"}],["line",{x1:"6",x2:"6",y1:"20",y2:"14",key:"1r4le6"}]]);/** 28 * @license lucide-react v0.462.0 - ISC 29 * 30 * This source code is licensed under the ISC license. 31 * See the LICENSE file in the root directory of this source tree. 32 */const Ux=_e("FileChartColumn",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 18v-1",key:"zg0ygc"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"M16 18v-3",key:"j5jt4h"}]]);/** 33 * @license lucide-react v0.462.0 - ISC 34 * 35 * This source code is licensed under the ISC license. 36 * See the LICENSE file in the root directory of this source tree. 37 */const Hx=_e("FileCheck2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3 15 2 2 4-4",key:"1lhrkk"}]]);/** 38 * @license lucide-react v0.462.0 - ISC 39 * 40 * This source code is licensed under the ISC license. 41 * See the LICENSE file in the root directory of this source tree. 42 */const Vx=_e("FilePen",[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5",key:"1couwa"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/** 43 * @license lucide-react v0.462.0 - ISC 44 * 45 * This source code is licensed under the ISC license. 46 * See the LICENSE file in the root directory of this source tree. 47 */const xc=_e("Frown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 16s-1.5-2-4-2-4 2-4 2",key:"epbg0q"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** 48 * @license lucide-react v0.462.0 - ISC 49 * 50 * This source code is licensed under the ISC license. 51 * See the LICENSE file in the root directory of this source tree. 52 */const Gr=_e("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** 53 * @license lucide-react v0.462.0 - ISC 54 * 55 * This source code is licensed under the ISC license. 56 * See the LICENSE file in the root directory of this source tree. 57 */const Wx=_e("IdCard",[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]]);/** 58 * @license lucide-react v0.462.0 - ISC 59 * 60 * This source code is licensed under the ISC license. 61 * See the LICENSE file in the root directory of this source tree. 62 */const lu=_e("ImageOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);/** 63 * @license lucide-react v0.462.0 - ISC 64 * 65 * This source code is licensed under the ISC license. 66 * See the LICENSE file in the root directory of this source tree. 67 */const Gx=_e("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/** 68 * @license lucide-react v0.462.0 - ISC 69 * 70 * This source code is licensed under the ISC license. 71 * See the LICENSE file in the root directory of this source tree. 72 */const Kx=_e("LayoutTemplate",[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"9",height:"7",x:"3",y:"14",rx:"1",key:"jqznyg"}],["rect",{width:"5",height:"7",x:"16",y:"14",rx:"1",key:"q5h2i8"}]]);/** 73 * @license lucide-react v0.462.0 - ISC 74 * 75 * This source code is licensed under the ISC license. 76 * See the LICENSE file in the root directory of this source tree. 77 */const br=_e("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** 78 * @license lucide-react v0.462.0 - ISC 79 * 80 * This source code is licensed under the ISC license. 81 * See the LICENSE file in the root directory of this source tree. 82 */const Qx=_e("ListTree",[["path",{d:"M21 12h-8",key:"1bmf0i"}],["path",{d:"M21 6H8",key:"1pqkrb"}],["path",{d:"M21 18h-8",key:"1tm79t"}],["path",{d:"M3 6v4c0 1.1.9 2 2 2h3",key:"1ywdgy"}],["path",{d:"M3 10v6c0 1.1.9 2 2 2h3",key:"2wc746"}]]);/** 83 * @license lucide-react v0.462.0 - ISC 84 * 85 * This source code is licensed under the ISC license. 86 * See the LICENSE file in the root directory of this source tree. 87 */const ko=_e("Meh",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"8",x2:"16",y1:"15",y2:"15",key:"1xb1d9"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** 88 * @license lucide-react v0.462.0 - ISC 89 * 90 * This source code is licensed under the ISC license. 91 * See the LICENSE file in the root directory of this source tree. 92 */const Jx=_e("MessageSquareText",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M13 8H7",key:"14i4kc"}],["path",{d:"M17 12H7",key:"16if0g"}]]);/** 93 * @license lucide-react v0.462.0 - ISC 94 * 95 * This source code is licensed under the ISC license. 96 * See the LICENSE file in the root directory of this source tree. 97 */const Xx=_e("Monitor",[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]]);/** 98 * @license lucide-react v0.462.0 - ISC 99 * 100 * This source code is licensed under the ISC license. 101 * See the LICENSE file in the root directory of this source tree. 102 */const Zx=_e("PanelBottomOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}]]);/** 103 * @license lucide-react v0.462.0 - ISC 104 * 105 * This source code is licensed under the ISC license. 106 * See the LICENSE file in the root directory of this source tree. 107 */const fc=_e("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** 108 * @license lucide-react v0.462.0 - ISC 109 * 110 * This source code is licensed under the ISC license. 111 * See the LICENSE file in the root directory of this source tree.
112 */const Yx=_e("PanelTopOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"m15 14-3 3-3-3",key:"g215vf"}]]);/** 113 * @license lucide-react v0.462.0 - ISC 114 * 115 * This source code is licensed under the ISC license. 116 * See the LICENSE file in the root directory of this source tree. 117 */const ef=_e("PictureInPicture2",[["path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4",key:"daa4of"}],["rect",{width:"10",height:"7",x:"12",y:"13",rx:"2",key:"1nb8gs"}]]);/** 118 * @license lucide-react v0.462.0 - ISC 119 * 120 * This source code is licensed under the ISC license. 121 * See the LICENSE file in the root directory of this source tree. 122 */const tf=_e("PictureInPicture",[["path",{d:"M8 4.5v5H3m-1-6 6 6m13 0v-3c0-1.16-.84-2-2-2h-7m-9 9v2c0 1.05.95 2 2 2h3",key:"bcd8fb"}],["rect",{width:"10",height:"7",x:"12",y:"13.5",ry:"2",key:"136fx3"}]]);/** 123 * @license lucide-react v0.462.0 - ISC 124 * 125 * This source code is licensed under the ISC license. 126 * See the LICENSE file in the root directory of this source tree. 127 */const cu=_e("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/** 128 * @license lucide-react v0.462.0 - ISC 129 * 130 * This source code is licensed under the ISC license. 131 * See the LICENSE file in the root directory of this source tree. 132 */const af=_e("Rows2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]]);/** 133 * @license lucide-react v0.462.0 - ISC 134 * 135 * This source code is licensed under the ISC license. 136 * See the LICENSE file in the root directory of this source tree. 137 */const sf=_e("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/** 138 * @license lucide-react v0.462.0 - ISC 139 * 140 * This source code is licensed under the ISC license. 141 * See the LICENSE file in the root directory of this source tree. 142 */const nf=_e("Rss",[["path",{d:"M4 11a9 9 0 0 1 9 9",key:"pv89mb"}],["path",{d:"M4 4a16 16 0 0 1 16 16",key:"k0647b"}],["circle",{cx:"5",cy:"19",r:"1",key:"bfqh0e"}]]);/** 143 * @license lucide-react v0.462.0 - ISC 144 * 145 * This source code is licensed under the ISC license. 146 * See the LICENSE file in the root directory of this source tree. 147 */const du=_e("TvMinimal",[["path",{d:"M7 21h10",key:"1b0cd5"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}]]);/** 148 * @license lucide-react v0.462.0 - ISC 149 * 150 * This source code is licensed under the ISC license. 151 * See the LICENSE file in the root directory of this source tree. 152 */const hc=_e("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/** 153 * @license lucide-react v0.462.0 - ISC 154 * 155 * This source code is licensed under the ISC license. 156 * See the LICENSE file in the root directory of this source tree. 157 */const rf=_e("UserSearch",[["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}],["path",{d:"M10.3 15H7a4 4 0 0 0-4 4v2",key:"3bnktk"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}]]),js={instagram:{kind:"instagram",label:"Instagram",className:"bg-destructive/10 text-destructive-text"},facebook:{kind:"facebook",label:"Facebook",className:"bg-primary/10 text-primary-text"},meta_ads:{kind:"meta_ads",label:"Meta Ads",className:"bg-primary/10 text-primary-text"},google_ads:{kind:"google_ads",label:"Google Ads",className:"bg-warning/10 text-warning-text"},organic:{kind:"organic",label:"Orgânico",className:"bg-success/10 text-success-text"},site:{kind:"site",label:"Site",className:"bg-ink/10 text-muted-foreground"},indicacao:{kind:"indicacao",label:"Indicação",className:"bg-primary/10 text-primary-text"},qr:{kind:"qr",label:"QR Code",className:"bg-primary/10 text-primary-text"},prospeccao:{kind:"prospeccao",label:"Prospecção",className:"bg-warning/10 text-warning-text"},importacao:{kind:"importacao",label:"Importação",className:"bg-muted text-muted-foreground"},ligacao:{kind:"ligacao",label:"Ligação",className:"bg-success/10 text-success-text"}},of={instagram:"instagram",facebook:"facebook",meta_ads:"meta_ads",google_ads:"google_ads",whatsapp_organic:"organic",whatsapp:"organic",whatsapp_cloud:"organic",site:"site",website:"site",indicacao:"indicacao",referral:"indicacao",qr_campaign:"qr",field_prospecting:"prospeccao",mercos_import:"importacao",voice_call:"ligacao"};function lf(t){if(!t)return null;const a=(t.source_url||"").toLowerCase();return/instagram|igshid|ig\.me/.test(a)?"instagram":/facebook|fb\.me|fb\.com|fb\.watch|fbclid/.test(a)?"facebook":null}function Ei(t,a,s){var c;const r=((c=(a==null?void 0:a.headline)||(a==null?void 0:a.label))==null?void 0:c.trim())||void 0;if((a==null?void 0:a.source_type)==="qr_entry")return{...js.qr,tooltip:r?`Entrou pelo QR/link da campanha: ${r}`:"Entrou por um QR/link de campanha",campaignLabel:r};const i=(s||"").trim().toLowerCase();if(i==="facebook"||i==="instagram"){const u=js[i],m=a!=null&&a.headline?` · ${a.headline}`:"";return{...u,tooltip:`Veio de anúncio no ${u.label}${m}`,campaignLabel:r}}if(i==="mixed"){const u=js.meta_ads,m=a!=null&&a.headline?`: ${a.headline}`:"";return{...u,tooltip:`Veio de anúncio${m} · o anúncio roda no Facebook e no Instagram, e a Meta não diz por qual deles ESTE lead entrou`,campaignLabel:r}}const l=lf(a);if(l){const u=js[l],m=a!=null&&a.headline?` · ${a.headline}`:"";return{...u,tooltip:`Veio de anúncio no ${u.label}${m}`,campaignLabel:r}}const d=t?of[t.toLowerCase()]:void 0;if(d&&d!=="organic"){const u=js[d];return{...u,tooltip:`Origem do lead: ${u.label}`,campaignLabel:r}}if(a){const u=js.meta_ads,m=a.headline?`: ${a.headline}`:" (Meta)";return{...u,tooltip:`Veio de anúncio${m}`,campaignLabel:r}}if(d){const u=js[d];return{...u,tooltip:`Origem do lead: ${u.label}`}}return null}function cf(t){const a=String(t??"").replace(/\D/g,"");return a.length<10||a.length>15?null:`${a}@s.whatsapp.net`}function uu(t,a){const s=a||"Humano",r=t||"";let i="no comando";return r==="takeover"?i="assumiu":r==="reply"?i="respondeu":r==="manual"?i="silenciou o agente":r==="escalation:cotar_agv"?i="Cotar AGV":r.startsWith("escalation:")&&(i=`escalado (${r.slice(11)})`),`${s} ${i}`.trim()}const mu=$m,df=Pm,pu=n.forwardRef(({className:t,...a},s)=>e.jsx(yd,{className:Ce("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a,ref:s}));pu.displayName=yd.displayName;const uf=Im("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Di=n.forwardRef(({side:t="right",className:a,children:s,...r},i)=>e.jsxs(df,{children:[e.jsx(pu,{}),e.jsxs(bd,{ref:i,className:Ce(uf({side:t}),a),...r,children:[s,e.jsxs(Mm,{className:"absolute right-4 top-4 roun
157ded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[e.jsx(vt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Di.displayName=bd.displayName;const xu=({className:t,...a})=>e.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",t),...a});xu.displayName="SheetHeader";const $i=n.forwardRef(({className:t,...a},s)=>e.jsx(vd,{ref:s,className:Ce("text-lg font-semibold text-foreground",t),...a}));$i.displayName=vd.displayName;const fu=n.forwardRef(({className:t,...a},s)=>e.jsx(jd,{ref:s,className:Ce("text-sm text-muted-foreground",t),...a}));fu.displayName=jd.displayName;function Hs(t,a){return a||(t.endsWith("@newsletter")?"channel":t.endsWith("@broadcast")||t.startsWith("status@")?"broadcast":t.endsWith("@g.us")?"group":"individual")}function mf(t){return t?(localStorage.setItem("whatsapp-setup-session",t),t):null}function pf(t={}){const{autoConnect:a=!0,onMessage:s,onConnectionChange:r,sellerId:i}=t,{user:l}=Sa(),d=mf(l==null?void 0:l.id),c=i||d,u=n.useRef(null),m=n.useRef(null),[x,f]=n.useState(!1),{connection:p,setConnection:g,addMessage:y,addMessages:k,setChats:_,getMessages:N,getAllMessages:I,getStats:P,chats:D,selectedChatId:V,setSelectedChatId:R,reset:M,ensureSellerScope:$}=Tn(),C=n.useCallback(()=>{var L;if((L=u.current)!=null&&L.connected)return;const Q=c;if(!Q){console.log("[WhatsApp] No sellerId found in localStorage");return}console.log("[WhatsApp] Connecting to service...");const K=ap(np,{path:sp(),transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:15e3,auth:vo()});u.current=K,K.on("connect",()=>{console.log("[WhatsApp] Socket connected"),r==null||r(!0)}),K.on("disconnect",()=>{console.log("[WhatsApp] Socket disconnected"),r==null||r(!1)}),K.on("connect_error",S=>{var H;const B=(H=S==null?void 0:S.data)==null?void 0:H.code;B!=="TOKEN_INVALID"&&B!=="TOKEN_MISSING"||Lm().then(()=>{K.auth=vo(),console.log("[WhatsApp] Token renovado â reapresentando no socket")}).catch(()=>{})}),K.on(`message:${Q}`,S=>{var oe,O,be,fe;const B=S.chat_id||(S.fromMe?S.to:S.from);if(B==="status@broadcast"||B!=null&&B.includes("status@")){console.log("[WhatsApp] Ignorando status:",((oe=S.body)==null?void 0:oe.substring(0,30))||"(mÃdia)");return}if(!S.body&&S.type!=="chat"){console.log("[WhatsApp] Ignorando mensagem sem corpo:",S.type);return}if(S.fromMe&&N(B).some(je=>je.fromMe&&je.status==="pending"&&je.body===S.body)){console.log("[WhatsApp] Confirmando mensagem otimista:",(O=S.body)==null?void 0:O.substring(0,30));const{messagesByChat:je}=Tn.getState(),Ee=(je.get(B)||[]).map(Le=>Le.fromMe&&Le.status==="pending"&&Le.body===S.body?{...Le,id:S.message_id,status:"sent"}:Le),ye=new Map(je);ye.set(B,Ee),Tn.setState({messagesByChat:ye});return}console.log("[WhatsApp] Nova mensagem de chat:",{from:B,body:(be=S.body)==null?void 0:be.substring(0,50),fromMe:S.fromMe});const H=typeof S.timestamp=="number"?S.timestamp:Date.now(),W=H<1e12?H*1e3:H,X={id:S.message_id||`${Date.now()}-${Math.random().toString(36).slice(2)}`,chatId:B,body:S.body||"",fromMe:!!S.fromMe,timestamp:W,status:S.fromMe?"sent":"delivered",from:S.from||"",to:S.to||Q,source:S.source,author:S.author||void 0,authorName:S.authorName||void 0,type:S.type||void 0,duration:S.duration??void 0,hasMedia:!!S.hasMedia,mediaCaption:((fe=S.media)==null?void 0:fe.caption)??void 0};y(X),s==null||s(X)}),K.on(`connected:${Q}`,S=>{var H,W;console.log("[WhatsApp] Connection status update:",S),g({sellerId:Q,connected:!0,connectedNumber:(H=S.info)!=null&&H.whatsapp_number?`+${S.info.whatsapp_number}`:"",connectedName:((W=S.info)==null?void 0:W.name)||"Usuário",connectedAt:new Date().toISOString()}),m.current&&clearInterval(m.current),f(!0);const B=Date.now();m.current=setInterval(async()=>{var X;if(Date.now()-B>3e4){clearInterval(m.current),m.current=null,f(!1);return}try{const oe=await Je(`/api/whatsapp/chats/${Q}`);
157if(oe.ok){const O=await oe.json();if((((X=O.chats)==null?void 0:X.length)??0)>0){clearInterval(m.current),m.current=null,f(!1);const be=(O.chats||[]).map(fe=>({id:fe.id,name:fe.name,lastMessage:fe.lastMessage||"",lastMessageTimestamp:fe.lastMessageTimestamp||Date.now(),unreadCount:fe.unreadCount||0,isGroup:fe.isGroup||fe.id.includes("@g.us"),chatType:Hs(fe.id,fe.chatType),phone:fe.phone||fe.id.replace("@c.us","").replace("@g.us","").replace("@newsletter",""),pinned:fe.pinned||!1,archived:fe.archived||!1}));_(be)}}}catch{}},3e3)});const G=async()=>{var S;try{const B=await Je(`/api/whatsapp/indexeddb/${Q}`);if(B.ok){const W=(((S=(await B.json()).data)==null?void 0:S.chats)||[]).filter(X=>X.id).map(X=>{var oe,O;return{id:X.id,name:X.name,lastMessage:"",lastMessageTimestamp:X.timestamp?X.timestamp<1e12?X.timestamp*1e3:X.timestamp:Date.now(),unreadCount:X.unreadCount||0,isGroup:X.isGroup||((oe=X.id)==null?void 0:oe.includes("@g.us")),chatType:Hs(X.id,X.chatType),phone:X.phone||((O=X.id)==null?void 0:O.replace("@c.us","").replace("@g.us","").replace("@newsletter",""))||"",pinned:X.pinned||!1,archived:X.archived||!1}});W.length>0&&_(W)}}catch{}};return K.on(`data_ready:${Q}`,async()=>{console.log("[WhatsApp] Data ready â parando poll e carregando chats"),m.current&&(clearInterval(m.current),m.current=null),f(!1),await G(),[15e3,3e4,6e4].forEach(S=>{setTimeout(()=>G(),S)})}),K.on(`contacts_updated:${Q}`,()=>{console.log("[WhatsApp] Contacts updated â refreshing chat names"),G()}),K.on(`disconnected:${Q}`,S=>{console.log("[WhatsApp] Disconnected:",S),m.current&&(clearInterval(m.current),m.current=null),f(!1),g(null)}),K},[y,g,_,s,r,c,N]),b=n.useCallback(()=>{m.current&&(clearInterval(m.current),m.current=null),f(!1),u.current&&(u.current.disconnect(),u.current=null)},[]),v=n.useCallback(async()=>{var K,G;const Q=c;if(!Q)return null;try{const S=await(await Je(`/api/whatsapp/status/${Q}`)).json();return S.connected?(g({sellerId:Q,connected:!0,connectedNumber:(K=S.info)!=null&&K.whatsapp_number?`+${S.info.whatsapp_number}`:"",connectedName:((G=S.info)==null?void 0:G.name)||"Usurio"}),S):(g(null),null)}catch(L){return console.error("[WhatsApp] Error checking connection:",L),null}},[g,c]),F=n.useCallback(async()=>{const Q=c;if(!Q)return[];try{console.log("[WhatsApp] Loading chats from IndexedDB...");const K=await Je(`/api/whatsapp/indexeddb/${Q}/chats`);if(K.ok){const G=await K.json();console.log(`[WhatsApp] Loaded ${G.total} chats from IndexedDB`);const L=(G.chats||[]).map(S=>{var B,H;return{id:S.id,name:S.name,lastMessage:S.lastMessage||"",lastMessageTimestamp:S.timestamp?S.timestamp<1e12?S.timestamp*1e3:S.timestamp:Date.now(),unreadCount:S.unreadCount||0,isGroup:S.isGroup||((B=S.id)==null?void 0:B.includes("@g.us")),chatType:Hs(S.id,S.chatType),phone:S.phone||((H=S.id)==null?void 0:H.replace("@c.us","").replace("@g.us","").replace("@newsletter",""))||"",pinned:S.pinned||!1,archived:S.archived||!1}});return _(L),L}}catch(K){console.error("[WhatsApp] Error loading chats from IndexedDB:",K)}return[]},[_,c]),U=n.useCallback(async()=>{const Q=c;if(!Q)return null;try{console.log("[WhatsApp] Loading all data from IndexedDB...");const K=await Je(`/api/whatsapp/indexeddb/${Q}`);if(K.ok){const G=await K.json();console.log("[WhatsApp] IndexedDB stats:",G.stats);const L=(G.data.chats||[]).filter(S=>S.id).map(S=>{var B,H;return{id:S.id,name:S.name,lastMessage:"",lastMessageTimestamp:S.timestamp?S.timestamp<1e12?S.timestamp*1e3:S.timestamp:Date.now(),unreadCount:S.unreadCount||0,isGroup:S.isGroup||((B=S.id)==null?void 0:B.includes("@g.us")),chatType:Hs(S.id,S.chatType),phone:S.phone||((H=S.id)==null?void 0:H.replace("@c.us","").replace("@g.us","").replace("@newsletter",""))||"",pinned:S.pinned||!1,archived:S.archived||!1}});return _(L),{chats:L,contacts:G.data.contacts||[],groups:G.data.groups||[],stats:G.stats}}}catch(K){console.error("[WhatsApp] Error loading from IndexedDB:",K)}return null},[_,c]),te=n.useCallback(async(Q=!0)=>{const K=c;if(!K)return[];if(Q){const G=await F();if(G.length>0)return G;console.log("[WhatsApp] IndexedDB empty, falling back to regular API...")}try{const G=await Je(`/api/whatsapp/chats/${K}`);if(G.ok){const L=await G.json();console.log(`[WhatsApp] Loaded ${L.total} chats from API (source: ${L.source})`);const S=(L.chats||[]).map(B=>({id:B.id,name:B.name,lastMessage:B.lastMessage||"",lastMessageTimestamp:B.lastMessageTimestamp||Date.now(),unreadCount:B.unreadCount||0,isGroup:B.isGroup||B.id.includes("@g.us"),chatType:Hs(B.id,B.chatType),phone:B.phone||B.id.replace("@c.us","").replace("@g.us","").replace("@newsletter",""),pinned:B.pinned||!1,archived:B.archived||!1}));return _(S),S}}catch(G){console.error("[WhatsApp] Error loading chats:",G)}return[]},[_,F,c]),q=n.useCallback(async(Q,K=3)=>{const G=c;if(!G)return console.log("[WhatsApp] No sellerId found"),[];console.log(`[WhatsApp] Loading messages for chat: ${Q}`);for(let L=1;L<=K;L++)try{const S=await Je(`/api/whatsapp/messages/${G}/${encodeURIComponent(Q)}`);if(S.ok){const B=await S.json();console.log(`[WhatsApp] Loaded ${B.total} messages for chat ${Q}`);const H=(B.messages||[]).map(W=>({id:W.id||`${W.timestamp}-${Math.random().toString(36).slice(2)}`,chatId:Q,body:W.body||"",fromMe:!!W.fromMe,timestamp:W.timestamp<1e12?W.timestamp*1e3:W.timestamp,status:W.fromMe?"sent":"delivered",from:W.from||"",to:W.to||G,author:W.author||void 0,authorName:W.authorName||void 0,type:W.type||void 0,duration:W.duration??void 0,hasMedia:!!W.hasMedia,mediaCaption:W.mediaCaption??void 0}));return k(Q,H),H}else if(S.status===503){if(console.log(`[WhatsApp] Store not ready, retry ${L}/${K}...`),L<K){await new Promise(B=>setTimeout(B,2e3));continue}}else{const B=await S.json().catch(()=>({}));console.error(`[WhatsApp] Error loading messages (${S.status}):`,B)}}catch(S){console.error(`[WhatsApp] Error loading messages (attempt ${L}):`,S),L<K&&await new Promise(B=>setTimeout(B,1e3))}return console.log(`[WhatsApp] Failed to load messages after ${K} attempts`),[]},[k,c]),Z=n.useCallback(async(Q,K)=>{const G=c;if(!G||!K.trim())return null;const L={id:`temp-${Date.now()}`,chatId:Q,body:K.trim(),fromMe:!0,timestamp:Date.now(),status:"pending",from:(p==null?void 0:p.connectedNumber)||"",to:Q};y(L);try{if((await Je(`/api/whatsapp/send/${G}`,{method:"POST",body:JSON.stringify({to:Q,message:K.trim()})})).ok)return L}catch(S){console.error("[WhatsApp] Error sending message:",S)}return null},[y,p,c]),ae=n.useCallback(async()=>{const Q=c;if(!Q)return[];try{const K=await Je(`/api/whatsapp/chats/${Q}/reload`,{method:"POST"});if(K.ok){const L=((await K.json()).chats||[]).map(S=>({id:S.id,name:S.name,lastMessage:S.lastMessage||"",lastMessageTimestamp:S.lastMessageTimestamp||Date.now(),unreadCount:S.unreadCount||0,isGroup:S.isGroup||S.id.includes("@g.us"),chatType:Hs(S.id,S.chatType),phone:S.phone||S.id.replace("@c.us","").replace("@g.us","").replace("@newsletter",""),pinned:S.pinned||!1,archived:S.archived||!1}));return _(L),L}}catch(K){console.error("[WhatsApp] Error reloading chats:",K)}return[]},[_,c]),ce=n.useCallback(async()=>{const Q=c;if(!Q)return!1;try{return f(!0),(await Je(`/api/whatsapp/resync/${Q}`,{method:"POST"})).ok}catch{return f(!1),!1}},[c]);n.useEffect(()=>{$(c)},[c,$]),n.useEffect(()=>{let Q=!0;return(async()=>{var L;if(!(!a||!c||!Q)){(L=u.current)!=null&&L.connected||C();try{await v(),await te()}catch(S){console.error("[WhatsApp] Init error:",S)}}})(),()=>{Q=!1,b()}},[a,c]),n.useEffect(()=>{if(!a||!c)return;const Q=()=>
157{if(document.visibilityState!=="visible")return;const K=u.current;K?K.connected||(K.auth=vo(),K.connect()):C(),v().catch(()=>{}),te().catch(()=>{})};return document.addEventListener("visibilitychange",Q),window.addEventListener("focus",Q),()=>{document.removeEventListener("visibilitychange",Q),window.removeEventListener("focus",Q)}},[a,c,C,v,te]);const se=Array.from(D.values()).sort((Q,K)=>{if(Q.pinned&&!K.pinned)return-1;if(!Q.pinned&&K.pinned)return 1;const G=Q.lastMessageTimestamp||0;return(K.lastMessageTimestamp||0)-G});return{connection:p,isConnected:!!(p!=null&&p.connected),isSyncing:x,connect:C,disconnect:b,checkConnectionStatus:v,chats:se,loadChats:te,loadChatsFromIndexedDB:F,loadAllFromIndexedDB:U,reloadChats:ae,resyncChats:ce,selectedChatId:V,setSelectedChatId:R,getMessages:N,getAllMessages:I,loadChatMessages:q,sendMessage:Z,getStats:P,reset:M}}const xf=12e4,ff=15e3,hf={attention:void 0,active:"hot,warm",all:void 0,cold:"cold",closed:"closed,lost"};function gf(t){const[a,s]=n.useState("all"),[r,i]=n.useState([]),[l,d]=n.useState(!1),[c,u]=n.useState(null),[m,x]=n.useState([]),[f,p]=n.useState(!1),[g,y]=n.useState(!1),k=n.useRef(null),_=n.useRef(0),N=n.useRef(0),I=n.useCallback(async()=>{const C=++N.current;d(!0);try{const b=await rp({status:hf[a],pageSize:1e3,companyId:t});if(C!==N.current)return;i(b)}catch(b){if(C!==N.current)return;console.error("[useAgentInbox] loadLeads:",b)}finally{C===N.current&&d(!1)}},[a,t]),P=n.useCallback(async C=>{const b=++_.current;p(!0);try{const v=await _r(C);if(b!==_.current)return;x(v)}catch(v){if(b!==_.current)return;console.error("[useAgentInbox] loadConversation:",v),x([])}finally{b===_.current&&p(!1)}},[]);n.useEffect(()=>{I()},[I]),n.useEffect(()=>{if(k.current&&clearInterval(k.current),!c){x([]);return}P(c);const C=rn(),b=F=>{(F==null?void 0:F.leadId)===c&&P(c)},v=()=>C==null?void 0:C.emit("subscribe:lead",c);return C&&(C.connected&&v(),C.on("connect",v),C.on("lead:update",b),C.on("analysis:update",b)),k.current=setInterval(()=>P(c),C?xf:ff),()=>{k.current&&clearInterval(k.current),C&&(C.emit("unsubscribe:lead",c),C.off("connect",v),C.off("lead:update",b),C.off("analysis:update",b),on())}},[c,P]);const D=n.useRef(c);n.useEffect(()=>{D.current=c},[c]),n.useEffect(()=>{const C=rn();if(!C)return;let b=null;const v=F=>{b&&clearTimeout(b),b=setTimeout(()=>I(),600),F!=null&&F.leadId&&F.leadId===D.current&&P(F.leadId)};return C.on("inbox:lead-changed",v),()=>{b&&clearTimeout(b),C.off("inbox:lead-changed",v),on()}},[I,P]),n.useEffect(()=>{const C={t:0},b=()=>{if(document.hidden)return;const v=Date.now();v-C.t<1e3||(C.t=v,I(),D.current&&P(D.current))};return document.addEventListener("visibilitychange",b),window.addEventListener("focus",b),()=>{document.removeEventListener("visibilitychange",b),window.removeEventListener("focus",b)}},[I,P]);const V=n.useCallback(C=>{u(C)},[]),R=n.useCallback(async C=>{if(!c||!C.trim())return;y(!0);const b={id:`opt-${Date.now()}`,text:C.trim(),isOutgoing:!0,timestamp:new Date().toISOString()};x(v=>[...v,b]);try{await $d(c,C.trim())}catch(v){console.error("[useAgentInbox] sendMessage:",v),x(F=>F.filter(U=>U.id!==b.id))}finally{y(!1)}},[c]),M=n.useCallback(async C=>{var F;const b=((F=r.find(U=>U.id===C))==null?void 0:F.favoritedAt)??null,v=b?null:new Date().toISOString();i(U=>U.map(te=>te.id===C?{...te,favoritedAt:v}:te));try{const{favoritedAt:U}=await vi(C);i(te=>te.map(q=>q.id===C?{...q,favoritedAt:U}:q))}catch(U){console.error("[useAgentInbox] toggleFavorite:",U),i(te=>te.map(q=>q.id===C?{...q,favoritedAt:b}:q))}},[r]),$=r.find(C=>C.id===c)??null;return{filter:a,setFilter:s,leads:r,leadsLoading:l,selectedLeadId:c,selectedLead:$,selectLead:V,conversation:m,convLoading:f,sendMessage:R,sending:g,refreshLeads:I,toggleFavorite:M}}const bf=2e4;function vf(t="pending"){const a=Wr(),[s,r]=n.useState([]),[i,l]=n.useState(!0),[d,c]=n.useState(null),u=n.useCallback(async()=>{if(!a){r([]),l(!1);return}try{const m=await qp({companyId:a,status:t});r(m),c(null)}catch(m){c(He(m))}finally{l(!1)}},[a,t]);return n.useEffect(()=>{l(!0),u()},[u]),ls(u,bf),n.useEffect(()=>{if(!a)return;const m=rn();if(!m)return;const x=f=>{((f==null?void 0:f.type)==="agent_draft"||(f==null?void 0:f.type)==="agent_draft_stale")&&u()};return m.on("alert",x),()=>{m.off("alert",x),on()}},[a,u]),{drafts:s,loading:i,error:d,refresh:u,companyId:a}}const jf="/assets/t7-NKZdK.mp3";function yf(){const t=n.useRef(null),a=n.useRef(null),s=n.useCallback(()=>{try{let r=t.current;if(!r){const d=window.AudioContext||window.webkitAudioContext;if(!d)return;r=new d,t.current=r}r.state==="suspended"&&r.resume().catch(()=>{});const i=r.currentTime,l=[{f:880,t:0},{f:660,t:.12}];for(const d of l){const c=r.createOscillator(),u=r.createGain();c.type="sine",c.frequency.value=d.f;const m=i+d.t;u.gain.setValueAtTime(0,m),u.gain.linearRampToValueAtTime(.16,m+.012),u.gain.exponentialRampToValueAtTime(1e-4,m+.11),c.connect(u),u.connect(r.destination),c.start(m),c.stop(m+.13)}}catch{}},[]);return n.useCallback(()=>{try{let r=a.current;r||(r=new Audio(jf),r.preload="auto",r.volume=.6,a.current=r),r.currentTime=0;const i=r.play();i&&typeof i.catch=="function"&&i.catch(()=>s())}catch{s()}},[s])}function Nf(){const t=n.useRef(0),a=n.useRef(""),s=i=>
157i.replace(/^\(\d+\)\s*/,""),r=n.useCallback(()=>{const i=a.current||s(document.title);document.title=t.current>0?`(${t.current}) ${i}`:i},[]);return n.useEffect(()=>{if(a.current=s(document.title),typeof Notification<"u"&&Notification.permission==="default"){const l=()=>{try{Notification.requestPermission().catch(()=>{})}catch{}};window.addEventListener("pointerdown",l,{once:!0})}const i=()=>{document.hidden||(t.current=0,r())};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[r]),n.useCallback(i=>{if(document.hidden){t.current+=1,r();try{if(typeof Notification<"u"&&Notification.permission==="granted"){const l=new Notification(i.title,{body:i.body,tag:"leadsense-inbox",renotify:!0});l.onclick=()=>{try{window.focus()}catch{}l.close()}}}catch{}}},[r])}function Pi(t,a=Date.now()){const s=t!=null&&t.last_inbound_at?new Date(t.last_inbound_at).getTime():NaN;if(!Number.isFinite(s))return null;const r=Math.floor((a-s)/36e5);return r>=24?r:null}function Co(t){return typeof t!="number"||!Number.isFinite(t)?"":t.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function wf(t){if(!t)return"";const a=typeof t.premio_anual=="number"&&t.premio_anual>0?t.premio_anual:null,s=t.parcelamento_max||null,r=!!(s&&(s.parcelas??0)>1&&(s.valor_parcela??0)>0),i=[];if(a&&i.push(`${Co(a)}/ano`),r){const l=s.sem_juros?" sem juros":"";i.push(`${s.parcelas}x de ${Co(s.valor_parcela)}${l}`)}return i.length?i.join(" · "):typeof t.preco_mensal=="number"&&t.preco_mensal>0?`${Co(t.preco_mensal)}/mês`:""}function kf(t){if(!t)return!1;const a=t.preco_mensal,s=t.premio_anual;if(typeof a!="number"||typeof s!="number"||s<=0||!(Math.abs(a-s/12)<.05))return!1;const i=t.parcelamento_max,l=i&&i.valor_parcela;return!(typeof l=="number"&&Math.abs(l-a)<.05)}const vr=[{re:/```([\s\S]+?)```/g,tag:"code",borda:!1},{re:/\*([^\n*]+)\*/g,tag:"b",borda:!0},{re:/_([^\n_]+)_/g,tag:"i",borda:!0},{re:/~([^\n~]+)~/g,tag:"s",borda:!0}],gc=/[\p{L}\p{N}]/u,bc=/\s/;function Cf(t,a,s){switch(t){case"b":return e.jsx("strong",{className:"font-semibold",children:s},a);case"i":return e.jsx("em",{children:s},a);case"s":return e.jsx("span",{className:"line-through",children:s},a);case"code":return e.jsx("code",{className:"font-mono text-[0.9em] px-1 py-0.5 rounded bg-black/10",children:s},a)}}const Dn=/(https?:\/\/[^\s<]+|www\.[^\s<]+)/g;function Sf(t){let a=t.length;for(;a>0;){const s=t[a-1];if(".,;:!?".includes(s)){a-=1;continue}if(s===")"){const r=t.slice(0,a);if((r.match(/\(/g)||[]).length>=(r.match(/\)/g)||[]).length)break;a-=1;continue}break}return t.slice(0,a)}function vc(t,a){if(!Dn.test(t))return Dn.lastIndex=0,[t];Dn.lastIndex=0;const s=[];let r=0,i;for(;(i=Dn.exec(t))!==null;){const l=i[0],d=Sf(l);if(!d)continue;const c=i.index;c>r&&s.push(t.slice(r,c));const u=d.startsWith("www.")?`https://${d}`:d;s.push(e.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-2 break-all hover:opacity-80",children:d},`${a}.l${c}`)),r=c+d.length}return r<t.length&&s.push(t.slice(r)),s}function _f(t){return Array.from(t.matchAll(Dn),a=>[a.index??0,(a.index??0)+a[0].length])}function Af(t,a,s,r){const i=a.index;if(r.some(([m,x])=>i>m&&i<x))return!1;const l=i+a[0].length-1;if(r.some(([m,x])=>l>=m&&l<x-1))return!1;if(!t.borda)return!0;const d=s[i-1],c=s[i+a[0].length],u=a[1];return d!==void 0&&gc.test(d)||c!==void 0&&gc.test(c)?!1:!bc.test(u[0])&&!bc.test(u[u.length-1])}function Ef(t,a,s,r){t.re.lastIndex=s;let i;for(;(i=t.re.exec(a))!==null;){if(Af(t,i,a,r))return i;t.re.lastIndex=i.index+1}return null}function hu(t,a){const s=_f(t),r=vr.map(()=>{}),i=[];let l=0;for(;;){let d=null;for(let x=0;x<vr.length;x++){let f=r[x];(f===void 0||f!==null&&f.index<l)&&(f=r[x]=Ef(vr[x],t,l,s)),f&&(d===null||f.index<d.m.index)&&(d={m:f,tag:vr[x].tag})}if(d===null)break;const{m:c,tag:u}=d;c.index>l&&i.push(...vc(t.slice(l,c.index),`${a}.t${l}`));const m=u==="code"?c[1]:hu(c[1],`${a}.i${c.index}`);i.push(Cf(u,`${a}.w${c.index}`,m)),l=c.index+c[0].length}return l<t.length&&i.push(...vc(t.slice(l),`${a}.t${l}`)),i}function zr(t){return t?hu(t,"wa"):t??null}const Df=[{kind:"superseded",label:"Já respondi",hint:"Respondi manualmente antes; o rascunho ficou obsoleto (não é erro dela)"},{kind:"wrong_content",label:"Conteúdo errado",hint:"Informação errada ou inventada"},{kind:"wrong_timing",label:"Momento errado",hint:"Conteúdo ok, mas fora de hora nesta conversa"},{kind:"wrong_tone",label:"Tom ruim",hint:"Conteúdo ok, mas o jeito de dizer não serve"},{kind:"housekeeping",label:"Limpeza",hint:"Fila velha, follow-up repetido"}];function $f(t){const a=new Date(t.created_at).getTime();if(!Number.isFinite(a))return null;const s=r=>{const i=r?new Date(r).getTime():NaN;return Number.isFinite(i)&&i>a};return s(t.last_inbound_at)?"O cliente mandou mensagem depois que este rascunho foi gerado.":t.last_message_from==="seller"&&s(t.last_contact_at)?"Um humano já respondeu este lead depois que o rascunho foi gerado.":null}function si(t){var a;return(((a=t.agent_payload)==null?void 0:a.extra_messages)??[]).filter(s=>!!s&&!!s.trim())}function Pf(t,a,s){const r=si(s),i=a.length!==r.length||a.some((l,d)=>l.trim()!==(r[d]??"").trim());return t.trim()!==(s.proposed_text??"").trim()||i}
157function Mf(t,a){return t?[t,a.trim()].filter(Boolean).join(": "):a}function Tf(t,a,s){return Math.min(Math.max(t,a),s)}function jc({value:t,minPx:a=96,maxPx:s=320,...r}){const i=n.useRef(null);return n.useLayoutEffect(()=>{const l=i.current;l&&(l.style.height="auto",l.style.height=`${Tf(l.scrollHeight,a,s)}px`)},[t,a,s]),e.jsx("textarea",{ref:i,value:t,style:{maxHeight:s},...r})}function If({sentiment:t}){const a={hot:{cls:"bg-destructive/10 text-destructive",Icon:ai},warm:{cls:"bg-warning/15 text-warning",Icon:Wp},cold:{cls:"bg-primary/10 text-primary-text",Icon:Vp}},{cls:s,Icon:r}=a[t.classification]??a.cold;return e.jsxs("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full font-medium flex items-center gap-0.5 ${s}`,title:`Termômetro do lead: ${t.score}/100`,children:[e.jsx(r,{className:"w-3 h-3"}),"Lead ",t.score,t.urgency&&e.jsx("span",{title:"urgência",children:e.jsx(Es,{className:"w-3 h-3"})}),t.objection&&e.jsx("span",{title:"objeção",children:e.jsx(Rm,{className:"w-3 h-3"})}),t.frustration&&e.jsx("span",{title:"frustração",children:e.jsx(Ba,{className:"w-3 h-3"})})]})}function So({tom:t,children:a}){const s=t==="perigo"?"bg-destructive/10 border-destructive/30 text-destructive":"bg-warning/10 border-warning/40 text-warning-foreground";return e.jsxs("div",{className:`px-3 py-2 rounded-lg border flex items-start gap-2 ${s}`,children:[e.jsx(Ba,{className:`w-4 h-4 flex-shrink-0 mt-0.5 ${t==="perigo"?"text-destructive":"text-warning"}`}),e.jsx("span",{className:"text-[11px] leading-snug",children:a})]})}function jr({titulo:t,onClick:a,disabled:s,className:r,children:i}){return e.jsx(Pe,{type:"button",variant:"outline",size:"icon",className:`h-9 w-9 flex-shrink-0 ${r??""}`,title:t,"aria-label":t,disabled:s,onClick:a,children:i})}function gu({draft:t,persona:a,onResolved:s,onReviewCotacao:r}){var S,B;const{toast:i}=At(),[l,d]=n.useState(t.proposed_text??""),[c,u]=n.useState(()=>si(t)),[m,x]=n.useState(!1),[f,p]=n.useState(!1),[g,y]=n.useState(""),[k,_]=n.useState(null),[N,I]=n.useState(!1),[P,D]=n.useState(null),V=$f(t),R=Pi(t),M=JSON.stringify(((S=t.agent_payload)==null?void 0:S.extra_messages)??[]);n.useEffect(()=>{d(t.proposed_text??""),u(si(t)),x(!1),p(!1),y(""),_(null),I(!1)},[t.id,t.proposed_text,M]);const $=t.agent_payload,C=($==null?void 0:$.pending_tool_calls)??[],b=$==null?void 0:$.sentiment,v=$==null?void 0:$.presentation_summary,F=v
157==null?void 0:v.recomendada,U=((v==null?void 0:v.propostas)??[]).find(H=>H.proposta_id&&H.proposta_id===(F==null?void 0:F.proposta_id)),te=wf(U),q=kf(U),Z=Pf(l,c,t),ae=t.message_category==="cotacao"&&typeof r=="function",ce=!P&&!!l.trim()&&!(V&&!Z),se=async(H,W,X)=>{D(H);try{await W(),i({title:X}),s()}catch(oe){i({title:"Erro",description:He(oe),variant:"destructive"})}finally{D(null)}},Q=()=>Z?se("edit",()=>tc(t.id,l.trim(),!1,R!==null,c),"Enviado!"):se("approve",()=>ti(t.id,!1,void 0,R!==null),"Aprovado e enviado!"),K=()=>Z?se("audio",()=>tc(t.id,l.trim(),!0,R!==null,c),"Enviado como áudio!"):se("audio",()=>ti(t.id,!0,void 0,R!==null),"Enviado como áudio!"),G=R!==null?Z?"Enviar editado mesmo assim":"Enviar mesmo assim":Z?"Enviar editado":"Enviar",L="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm leading-relaxed resize-y focus:outline-none focus:ring-2 focus:ring-ring";return e.jsx("div",{className:"flex justify-end","data-testid":"draft-bubble",children:e.jsxs("div",{className:"max-w-[85%] w-full flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-center justify-end gap-1.5 text-[11px] font-medium text-warning pr-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-warning flex-shrink-0"}),$!=null&&$.copilot?e.jsxs(e.Fragment,{children:[e.jsx(Hp,{className:"w-3 h-3"})," Sugestão de ",a," · você no comando"]}):e.jsxs(e.Fragment,{children:[a," pediu sua revisão · ainda não enviado"]})]}),e.jsxs("div",{className:"rounded-2xl rounded-br-sm border border-dashed border-warning/60 bg-warning/5 p-3 flex flex-col gap-2",children:[R!==null&&e.jsxs(So,{tom:"atencao",children:[e.jsxs("strong",{children:["O cliente não fala há ",R,"h."]})," Fora da janela de 24h a Meta só entrega ",e.jsx("strong",{children:"template aprovado"}),", e cobra por ele; texto livre ela costuma recusar (erro 131047) â aà a mensagem não chega e a recusa em volume derruba a qualidade do número. Você pode enviar mesmo assim: se a Meta recusar, o rascunho volta pra fila com o motivo."]}),V&&e.jsxs(So,{tom:"perigo",children:[e.jsx("strong",{children:V})," Releia antes de enviar: o envio direto fica bloqueado enquanto isso, use o lápis pra editar ou descarte."]}),($==null?void 0:$.agv_perdedora)&&e.jsxs(So,{tom:"perigo",children:[e.jsx("strong",{children:"Isto é a cotação AGV, e ela PERDEU pro multicálculo."})," O cliente já recebeu (ou vai receber) a outra cotação â enviar isto manda uma ",e.jsx("strong",{children:"segunda"})," ","oferta, redundante, pro mesmo cliente. Só envie se for de propósito (ex.: usar na negociação com o preço em mãos)."]}),(b||C.length>0)&&e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx(Ge,{className:"w-3.5 h-3.5 text-warning flex-shrink-0"}),b&&e.jsx(If,{sentiment:b}),C.map((H,W)=>e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-warning/15 text-warning font-medium flex items-center gap-0.5",title:"Ação irreversÃvel: executa só no envio",children:[e.jsx(Ua,{className:"w-3 h-3"})," ",H.name," (executa ao enviar)"]},W))]}),v&&e.jsxs("div",{className:"rounded-lg border border-primary/40 bg-primary/5 px-3 py-1.5 text-xs flex items-center gap-2 flex-wrap",children:[e.jsx(ot,{className:"w-3 h-3 text-primary flex-shrink-0"}),e.jsx("span",{className:"font-medium text-foreground",children:(U==null?void 0:U.plano)??(F==null?void 0:F.plano)??"Proposta"}),!!te&&e.jsx("span",{className:"font-semibold text-foreground",children:te}),q&&e.jsx("span",{className:"text-[10px] text-muted-foreground",title:"A seguradora cotou este plano no ano; o valor mensal do payload é o anual dividido por 12 e não é uma forma de pagamento oferecida.",children:"(sem mensalidade avulsa)"}),(F==null?void 0:F.justificativa)&&e.jsx("span",{className:"text-muted-foreground italic truncate",children:F.justificativa})]}),m?e.jsx(jc,{value:l,autoFocus:!0,onChange:H=>d(H.target.value),"aria-label":"Texto da mensagem",className:L}):e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap break-words text-foreground",children:zr(l)}),(((B=$==null?void 0:$.buttons)==null?void 0:B.length)??0)>0&&e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:$.buttons.map(H=>e.jsx("span",{className:"text-[11px] px-2 py-1 rounded-full border border-primary/30 text-primary",children:H.title},H.id))}),Z&&e.jsx("p",{className:"text-[10px] text-warning",children:"Editado, será enviado o texto acima."}),c.length>0&&e.jsxs("div",{className:"flex flex-col gap-1.5 pt-1 border-t border-dashed border-warning/40",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:c.length===1?"+1 mensagem que vai junto":`+${c.length} mensagens que vão junto`}),c.map((H,W)=>m?e.jsx(jc,{value:H,minPx:64,maxPx:200,onChange:X=>u(oe=>oe.map((O,be)=>be===W?X.target.value:O)),"aria-label":`Mensagem ${W+2}`,className:L},W):e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap break-words text-foreground
157/90",children:zr(H)},W)),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Enviadas em sequência, na ordem acima."})]}),f&&e.jsxs("div",{className:"space-y-2 pt-1 border-t border-dashed border-warning/40",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Df.map(H=>e.jsx("button",{type:"button",onClick:()=>_(k===H.kind?null:H.kind),title:H.hint,className:`rounded-full border px-2.5 py-1 text-xs transition-colors ${k===H.kind?"border-primary bg-primary text-primary-foreground":"border-input text-muted-foreground hover:text-foreground hover:border-foreground/30"}`,children:H.label},H.kind))}),e.jsx("input",{value:g,onChange:H=>y(H.target.value),autoFocus:!0,placeholder:k?"Detalhe (opcional)":"Por que está descartando? (vira dado de treino)",className:"w-full rounded-lg border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:N,onChange:H=>I(H.target.checked),className:"rounded border-input"}),"Pedir uma nova sugestão da IA no lugar desta (fica sem nada até lá)"]})]}),e.jsx("div",{className:"flex items-center gap-1.5 pt-0.5",children:f?e.jsxs(e.Fragment,{children:[e.jsxs(Pe,{variant:"destructive",className:"flex-1 h-9 gap-1.5",disabled:!!P,onClick:()=>se("discard",()=>Lr(t.id,Mf(k,g),N),N?"Descartado, gerando nova":"Descartado"),children:[P==="discard"?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(ds,{className:"w-4 h-4"}),N?"Descartar e pedir nova sugestão":"Descartar"]}),e.jsx(jr,{titulo:"Cancelar o descarte",disabled:!!P,onClick:()=>p(!1),children:e.jsx(vt,{className:"w-4 h-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(jr,{titulo:m?"Parar de editar":"Editar a mensagem",disabled:!!P,className:m?"text-primary border-primary/40 bg-primary/10":"",onClick:()=>x(H=>!H),children:e.jsx(Dr,{className:"w-4 h-4"})}),e.jsx(jr,{titulo:"Descartar",disabled:!!P,className:"text-destructive border-destructive/30 hover:bg-destructive/10",onClick:()=>p(!0),children:e.jsx(ds,{className:"w-4 h-4"})}),!ae&&e.jsx(jr,{titulo:"Enviar como áudio (voz)",disabled:!!P||!l.trim(),className:"text-primary border-primary/30 hover:bg-primary/10",onClick:K,children:P==="audio"?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(ji,{className:"w-4 h-4"})}),ae?e.jsxs(Pe,{className:"flex-1 h-9 gap-1.5 bg-primary hover:bg-primary/90 text-primary-foreground",disabled:!!P,onClick:()=>r==null?void 0:r(),title:"Revise as propostas e o texto antes de enviar a cotação",children:[e.jsx(ot,{className:"w-4 h-4"})," Revisar cotação"]}):e.jsxs(Pe,{className:"flex-1 h-9 gap-1.5 bg-success hover:bg-success/90 text-success-foreground",disabled:!ce,title:V&&!Z?"A conversa andou: edite o texto ou descarte":R!==null?"Fora da janela de 24h: a Meta pode recusar (131047)":void 0,onClick:Q,children:[P==="approve"||P==="edit"?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(Xt,{className:"w-4 h-4"}),G]})]})})]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground text-right pr-1",children:[a," continua pausada até você decidir."]})]})})}const Lf={vidros:"vidros",carro_reserva:"carro reserva",carro_reserva_ar:"carro reserva com ar",assistencia_24h:"assistência 24h",protecao_pneus:"proteção de pneus",reparo_rapido:"reparo rápido",despesas_extras:"despesas extras"};function _o(t){const a=Number(t)||0;return a%1e3===0?`R$ ${a/1e3} mil`:`R$ ${String(a).replace(/\B(?=(\d{3})+(?!\d))/g,".")}`}function Rf(t){const a=[],s=t||{},r=s.danos_materiais,i=s.danos_corporais,l=r!=null&&i!=null&&Number(r)===Number(i);for(const[d,c]of Object.entries(s)){if(d==="franquia_tipo"){a.push({label:c===1?"franquia reduzida":"franquia normal",on:!0});continue}if(d==="danos_materiais"||d==="danos_corporais"){if(l){d==="danos_materiais"&&a.push({label:`terceiros ${_o(c)}`,on:!0});continue}const m=d==="danos_materiais"?"danos materiais":"danos corporais";a.push({label:`${m} ${_o(c)}`,on:!0});continue}if(d==="danos_morais"||d==="app_morte"){const m=d==="danos_morais"?"danos morais":"APP morte";a.push({label:`${m} ${_o(c)}`,on:Number(c)>0});continue}const u=Lf[d];u&&a.push({label:u,on:!!c})}return a}
157function Of({leadId:t,refreshSignal:a,canRequote:s,onRequoted:r}){const{toast:i}=At(),[l,d]=n.useState(null),[c,u]=n.useState(!1),m=n.useCallback(async()=>{if(!t||!s){d(null);return}const g=await op(t);d(g)},[t,s]);n.useEffect(()=>{m()},[m,a]);const x=n.useCallback(async()=>{if(!(!t||!l||c)){u(!0);try{await Pd(t,l.cobertura),d(null),i({title:"Recotação enfileirada",description:"As novas propostas aparecem em ~1 min."}),r==null||r()}catch(g){i({title:"Não deu pra recotar",description:He(g),variant:"destructive"})}finally{u(!1)}}},[t,l,c,i,r]),f=n.useCallback(async()=>{!t||c||(d(null),await ip(t))},[t,c]);if(!l||!s)return null;const p=Rf(l.cobertura);return e.jsx("div",{className:"mx-4 mb-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2.5",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-primary mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold leading-tight",children:l.question}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:"Detectado na sua mensagem. Confirma que eu recoto com essa cobertura?"}),p.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:p.map(g=>e.jsxs("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full border ${g.on?"bg-success/10 text-success-text border-success/30":"bg-destructive/10 text-destructive border-destructive/30"}`,children:[g.on?"com":"sem"," ",g.label]},g.label))}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Pe,{size:"sm",className:"h-7 text-xs",onClick:()=>void x(),disabled:c,children:[c?e.jsx(le,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Xt,{className:"w-3.5 h-3.5"}),"Sim, recotar"]}),e.jsxs(Pe,{size:"sm",variant:"ghost",className:"h-7 text-xs",onClick:()=>void f(),disabled:c,children:[e.jsx(vt,{className:"w-3.5 h-3.5"}),"Não"]})]})]})]})})}function Kr(t){return t?t.enabled.includes("cotacao"):!0}function Mi(t){return t?!t.disabled.includes("ai_analysis"):!0}const Ff="https://sistema.cronosmulticalculo.com.br";function zf(t){const a=(t??"").trim();return!a||a==="x"?null:`${Ff}/calculo/${encodeURIComponent(a)}/detalhes`}function qf(t){const a=/^sgcor::([^:]+)::/.exec((t??"").trim());return a&&a[1]!=="x"?a[1]:null}const Bf=["kicker","titulo","subtitulo","rodape"];function Uf(t){return Bf.includes(t)}function Hf(t,a,s){const r=a.split(".");if(r.length===1)return!Uf(a)||(t[a]??"")===s?null:{kind:"scalar",field:a,value:s};if(r.length!==3)return null;const[i,l,d]=r;if(i!=="coberturas"&&i!=="assistencias"||d!=="titulo"&&d!=="desc"||!/^\d+$/.test(l))return null;const c=Number(l),u=t[i];return c>=u.length||(u[c][d]??"")===s?null:{kind:"item",list:i,index:c,prop:d,value:s}}function Vf(t){const a={kicker:"marca (topo)",titulo:"tÃtulo",subtitulo:"subtÃtulo",rodape:"rodapé"};if(a[t])return a[t];const[s,r,i]=t.split(".");return`${s==="coberturas"?"cobertura":s==="assistencias"?"assistência":s} ${Number(r)+1} · ${i==="desc"?"descrição":"tÃtulo"}`}const Wf={price_sensitive:"SensÃvel a preço (2 baratas + 1 qualidade)",quality_sensitive:"Valoriza cobertura (2 premium + 1 média)",balanced:"Equilibrado (barata + média + premium)",todas:"Poucas opções (todas exibidas)"},yr={alto:{label:"Perfil ALTO",cls:"bg-success/15 text-success-text border-success/30"},medio:{label:"Perfil MÃDIO",cls:"bg-warning/15 text-warning-text border-warning/30"},basico:{label:"Perfil BÃSICO",cls:"bg-primary/15 text-primary-text border-primary/30"},desconhecido:{label:"Perfil indefinido",cls:"bg-muted text-muted-foreground border-border"}};function yc({items:t,onChange:a}){const s=(r,i)=>a(t.map((l,d)=>d===r?{...l,...i}:l));return e.jsxs("div",{className:"space-y-1.5",children:[t.map((r,i)=>e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("input",{value:r.titulo,onChange:l=>s(i,{titulo:l.target.value}),placeholder:"TÃtulo",className:"w-full rounded border border-input bg-background px-2 py-1 text-[11px] font-medium focus:outline-none focus:ring-1 focus:ring-ring"}),e.jsx("input",{value:r.desc??"",onChange:l=>s(i,{desc:l.target.value}),placeholder:"Descrição",className:"w-full rounded border border-input bg-background px-2 py-1 text-[11px] text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"})]}),e.jsx("button",{onClick:()=>a(t.filter((l,d)=>
157d!==i)),className:"mt-1 text-muted-foreground/50 hover:text-destructive",title:"Remover",children:e.jsx(ds,{className:"w-3.5 h-3.5"})})]},i)),e.jsxs("button",{onClick:()=>a([...t,{titulo:"",desc:""}]),className:"flex items-center gap-1 text-[11px] text-primary hover:underline",children:[e.jsx(us,{className:"w-3 h-3"})," adicionar"]})]})}function Cs(t){return t==null?"-":"R$ "+Number(t).toFixed(2).replace(".",",").replace(/\B(?=(\d{3})+(?!\d))/g,".")}function Gf(t){return t.preco_texto?t.preco_texto:t.is_assinatura===!1&&!!t.premio_anual&&(t.parcelas_max||0)>1&&t.valor_parcela?`${t.parcelas_max}x de ${Cs(t.valor_parcela)}`:t.premio_mensal?`${Cs(t.premio_mensal)}/mês`:t.premio_anual?`${Cs(t.premio_anual/12)}/mês equiv.`:Cs(null)}function Nc(t){return t.premio_anual?Number(t.premio_anual):t.premio_mensal?Number(t.premio_mensal)*12:t.valor_parcela&&(t.parcelas_max||0)>1?Number(t.valor_parcela)*Number(t.parcelas_max):null}function Ao(t){const a=(t.cobertura_detalhe||[]).filter(s=>s.label&&s.value);return a.length?a.slice(0,4).map(s=>`${s.label}: ${s.value}`).join(" · "):t.cobertura_tipo||""}const rs={assistencia_24h:!0,carro_reserva:!0,carro_reserva_ar:!0,vidros:!0,protecao_pneus:!1,reparo_rapido:!0,despesas_extras:!1,franquia_tipo:1,danos_materiais:1e5,danos_corporais:1e5,danos_morais:0,app_morte:5e3},Nr=6,$r=[["assistencia_24h","Assistência 24h"],["carro_reserva","Carro reserva"],["carro_reserva_ar","Carro reserva c/ ar"],["vidros","Vidros"],["protecao_pneus","Proteção pneus/rodas"],["reparo_rapido","Reparo rápido"],["despesas_extras","Despesas extras"]],Kf=new Set([...$r.map(([t])=>t),"franquia_tipo","danos_materiais","danos_corporais","danos_morais","app_morte"]),wc={guincho_km:"Guincho (km)"};function kc(t){if(wc[t])return wc[t];const a=t.replace(/_/g," ");return a.charAt(0).toUpperCase()+a.slice(1)}function En(t){return{...rs,...t||{}}}const Qf=[0,5e4,1e5,15e4,2e5],Jf=[0,5e4,1e5,15e4,2e5],Xf=[0,1e4,3e4,5e4],Zf=[0,5e3,1e4,2e4];function Yf(t){return t?t>=1e3?`R$ ${(t/1e3).toLocaleString("pt-BR")} mil`:`R$ ${t}`:"Não"}function eh(t,a){return t.includes(a)?t:[...t,a].sort((s,r)=>s-r)}function th({p:t,checked:a,isRec:s,pos:r,onToggle:i,onRec:l}){const{attributes:d,listeners:c,setNodeRef:u,transform:m,transition:x,isDragging:f}=Jd({id:t.proposta_id}),p={transform:Xd.Transform.toString(m),transition:x,opacity:f?.5:1},g=Zd(Kp(t.proposta_id)),y=g?null:zf(qf(t.proposta_id)),k=g??y,_=g?"Abrir este cálculo no portal da Suhai":"Abrir este cálculo no Cronos (SGCOR)";return e.jsxs("div",{ref:u,style:p,className:`group relative flex items-start gap-2 p-2 rounded-lg text-xs border transition-colors ${s?"border-primary bg-primary/10 ring-1 ring-primary/30":a?"border-primary/25 bg-primary/5":"border-dashed border-border bg-muted/20"}`,children:[e.jsx("button",{...d,...c,className:"mt-0.5 cursor-grab active:cursor-grabbing text-muted-foreground/30 hover:text-muted-foreground touch-none",title:"Arrastar pra reordenar",children:e.jsx(Gr,{className:"w-4 h-4"})}),e.jsx("button",{type:"button",onClick:i,"aria-pressed":a,title:a?"IncluÃda no documento (clique pra tirar)":"Fora do documento (clique pra incluir)",className:`mt-0.5 w-4 h-4 rounded-[4px] border flex items-center justify-center flex-shrink-0 transition-colors ${a?"bg-primary border-primary text-primary-foreground":"border-input hover:border-primary/50"}`,children:a&&e.jsx(Xt,{className:"w-2.5 h-2.5",strokeWidth:3})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[r!=null&&e.jsx("span",{className:"flex-shrink-0 w-4 h-4 rounded-full bg-primary/15 text-primary text-[9px] font-bold flex items-center justify-center tabular-nums",children:r}),e.jsx("button",{type:"button",onClick:i,className:"font-semibold truncate text-left hover:underline decoration-dotted underline-offset-2",children:t.seguradora}),s&&e.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-0.5 rounded-full bg-primary/15 text-primary px-1.5 py-px text-[9px] font-semibold uppercase tracking-wide",children:[e.jsx(Ha,{className:"w-2 h-2",fill:"
157currentColor"})," recomendada"]}),k&&e.jsx("a",{href:k,target:"_blank",rel:"noreferrer",onClick:N=>N.stopPropagation(),title:_,className:"flex-shrink-0 text-muted-foreground/40 hover:text-primary",children:e.jsx(Kn,{className:"w-3 h-3"})})]}),t.plano&&e.jsx("div",{className:"text-muted-foreground truncate",children:t.plano}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-baseline gap-x-1.5 gap-y-0.5",children:[e.jsx("b",{className:"text-primary text-[13px] leading-none",children:Gf(t)}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[Nc(t)!=null&&e.jsxs("span",{title:"Custo no ano",children:[Cs(Nc(t)),"/ano · "]}),"franquia ",Cs(t.franquia),e.jsx(Rr,{className:"w-2.5 h-2.5 inline ml-0.5 align-text-top text-muted-foreground/50"})]})]}),Ao(t)&&e.jsx("div",{className:"text-[10px] text-muted-foreground truncate mt-0.5",title:Ao(t),children:Ao(t)})]}),e.jsx("button",{type:"button",title:s?"à a recomendada (clique pra desmarcar)":"Marcar como recomendada",onClick:l,disabled:!a,className:`mt-0.5 flex-shrink-0 transition-colors ${s?"text-primary":"text-muted-foreground/30 hover:text-primary/70"} disabled:opacity-20 disabled:hover:text-muted-foreground/30`,children:e.jsx(Ha,{className:"w-4 h-4",fill:s?"currentColor":"none"})})]})}function Ss(t){if(t.curated)return!0;if(!t.quote_sent_at)return!1;const a=new Date(t.quote_sent_at).getTime();if(!Number.isFinite(a))return!1;if(!t.updated_at)return!0;const s=new Date(t.updated_at).getTime();return!Number.isFinite(s)||a>=s}function Ti({leadId:t,openSignal:a,refetchSignal:s,autoOpenAllowed:r=!1,floating:i=!1,confirmarVendaConcluida:l=!1,onUseSuggestion:d}){const{toast:c}=At(),[u,m]=n.useState([]),[x,f]=n.useState(!1),[p,g]=n.useState(!1),y=n.useRef(null),[k,_]=n.useState(null),[N,I]=n.useState(!1),[P,D]=n.useState([]),[V,R]=n.useState(new Set),[M,$]=n.useState(null),[C,b]=n.useState(null),[v,F]=n.useState(null),[U,te]=n.useState([]),[q,Z]=n.useState(null),[ae,ce]=n.useState(!1),[se,Q]=n.useState(""),[K,G]=n.useState(!1),[L,S]=n.useState(!1),[B,H]=n.useState("editor"),[W,X]=n.useState(!1),oe=n.useCallback(()=>{H("editor"),ut("content")},[]),[O,be]=n.useState(""),[fe,pe]=n.useState(""),[Me,je]=n.useState(""),[Oe,Ee]=n.useState(""),[ye,Le]=n.useState([]),[Ne,Se]=n.useState([]),[ke,ht]=n.useState(!1),[yt,Ye]=n.useState(!1),Nt=n.useRef(null),[Zt,Et]=n.useState(null),ha=n.useRef(!1),ga=n.useRef({kicker:O,titulo:fe,subtitulo:Me,rodape:Oe,coberturas:ye,assistencias:Ne});ga.current={kicker:O,titulo:fe,subtitulo:Me,rodape:Oe,coberturas:ye,assistencias:Ne};const[it,ut]=n.useState("curate"),[Yt,ba]=n.useState(""),[va,wt]=n.useState(!1),[zt,ea]=n.useState(!1),[J,he]=n.useState(!0),Fe=J&&!zt,[Ke,lt]=n.useState(rs),[ze,et]=n.useState(0),[ta,qt]=n.useState(0),[mt,Bt]=n.useState(ca),[tt,xs]=n.useState("agger"),[Ut,pn]=n.useState(!1),[Wa,Ht]=n.useState(null),w=n.useMemo(()=>["agger","suhai","agv","coonecta"].filter(T=>T==="agger"||!!(Wa!=null&&Wa[T])),[Wa]),qe=tt==="agger"||tt==="suhai",{user:Vt}=Sa(),fs=(Vt==null?void 0:Vt.role)==="admin"||(Vt==null?void 0:Vt.role)==="super_admin",at=mt<ca,Wt=u.some(A=>String(A.proposta_id||"").startsWith("suhai-portal::")),[ne,Dt]=n.useState(null),[Ve,gt]=n.useState(!1),[Gt,Ga]=n.useState([]),st=Gt.filter(A=>!Kf.has(A.key)),aa=A=>lt(T=>({...T,[A]:!T[A]})),re=(A,T)=>lt(Y=>({...Y,[A]:T})),Xe=(A,T)=>lt(Y=>({...Y,[A]:T})),[_a,hs]=n.useState(!1),$t=Ke.franquia_tipo!==rs.franquia_tipo||Ke.danos_materiais!==rs.danos_materiais||Ke.danos_corporais!==rs.danos_corporais||Ke.danos_morais!==rs.danos_morais||Ke.app_morte!==rs.app_morte,Ka=n.useRef(null),[Aa,Ea]=n.useState(!1),[sa,ja]=n.useState(0),Qa=Bd(Ud(Hd,{activationConstraint:{distance:4}})),xe=n.useMemo(()=>new Map(u.map(A=>[A.proposta_id,A])),[u]);n.useEffect(()=>{let A=!0;if(m([]),f(!1),g(!1),ea(!1),he(!0),b(null),F(null),lt(rs),et(0),qt(0),Bt(ca),Dt(null),y.current=null,!!t)return da(t).then(T=>{A&&T.exists&&T.propostas.length&&(y.current=t,g(Ss(T)),m(T.propostas),D(T.propostas.map(Y=>Y.proposta_id)),R(new Set(T.propostas.map(Y=>Y.proposta_id))),$(T.recomendada_id??null),b(T.perfil_ia??null),F(T.perfil_socioeconomico??null),lt(En(T.cobertura_aplicada)),qt(T.desconto_aplicad
157o??0),et(T.desconto_aplicado??0),he(T.pdf_curadoria_enabled!==!1),te(T.veiculos??[]),Z(T.placa??null))}),()=>{A=!1}},[t]),n.useEffect(()=>{if(!x||!t)return;let A=!0;return Xs(t).then(T=>{A&&(Dt(T.desconto_mes??null),Ga(T.coberturas_cotaveis??[]),Ht(T.motores??null))}).catch(()=>{}),()=>{A=!1}},[x,t]),n.useEffect(()=>{if(!t)return;let A=!0;return X(!1),lp(t).then(T=>{A&&(be(T.kicker??""),pe(T.titulo??""),je(T.subtitulo??""),Ee(T.rodape??""),Le(T.coberturas??[]),Se(T.assistencias??[]),ht(!!T.has_company_default),X(!0))}),()=>{A=!1}},[t]);const Te=n.useMemo(()=>P.filter(A=>V.has(A)),[P,V]),nt=n.useMemo(()=>({proposta_ids:Te,recomendada_id:M,...q?{placa:q}:{},...W?{conteudo:{kicker:O,titulo:fe,subtitulo:Me,rodape:Oe,coberturas:ye,assistencias:Ne}}:{}}),[Te,M,q,W,O,fe,Me,Oe,ye,Ne]);n.useEffect(()=>{M&&!V.has(M)&&$(Te[0]??null)},[V,M,Te]),n.useEffect(()=>{if(!a||a<=0||!t)return;let A=!0;return da(t).then(T=>{!A||!T.exists||!T.propostas.length||(y.current=t,g(Ss(T)),m(T.propostas),D(T.propostas.map(Y=>Y.proposta_id)),R(new Set(T.propostas.map(Y=>Y.proposta_id))),$(T.recomendada_id??null),lt(En(T.cobertura_aplicada)),qt(T.desconto_aplicado??0),te(T.veiculos??[]),Z(T.placa??null),ut("curate"),f(!0))}),()=>{A=!1}},[a,t]),n.useEffect(()=>{if(!s||s<=0||!t)return;let A=!0;return da(t).then(T=>{!A||!T.exists||!T.propostas.length||(y.current=t,g(Ss(T)),m(T.propostas),D(T.propostas.map(Y=>Y.proposta_id)),R(new Set(T.propostas.map(Y=>Y.proposta_id))),$(T.recomendada_id??null),lt(En(T.cobertura_aplicada)),qt(T.desconto_aplicado??0),te(T.veiculos??[]),Z(T.placa??null))}),()=>{A=!1}},[s,t]);const na=n.useCallback(()=>{t&&da(t).then(A=>{!A.exists||!A.propostas.length||(y.current=t,g(Ss(A)),m(A.propostas),D(A.propostas.map(T=>T.proposta_id)),R(new Set(A.propostas.map(T=>T.proposta_id))),$(A.recomendada_id??null),b(A.perfil_ia??null),F(A.perfil_socioeconomico??null),lt(En(A.cobertura_aplicada)),qt(A.desconto_aplicado??0),te(A.veiculos??[]),Z(A.placa??null))}).catch(()=>{})},[t]);ls(na,zd,!!t&&r&&!p&&!x&&(y.current!==t||u.length===0));const Kt=!!u.length&&!p&&y.current===t,Pt=n.useCallback(async A=>{await A();for(let we=0;we<40;we+=1){await new Promise(kt=>setTimeout(kt,3e3));const Ze=await Ar(t).catch(()=>null);if(Ze&&(Ze.status==="done"||Ze.status==="error"))break}const T=await da(t);let Y=0;return T.exists&&T.propostas.length&&(m(T.propostas),D(T.propostas.map(we=>we.proposta_id)),R(new Set(T.propostas.map(we=>we.proposta_id))),$(T.recomendada_id??null),b(T.perfil_ia??null),F(T.perfil_socioeconomico??null),Y=T.desconto_aplicado??0,qt(Y)),Y},[t]),ue=n.useCallback(async()=>{if(!(!t||Ve)){gt(!0);try{const A=await Pt(async()=>{tt==="agv"?await Ql(t,{confirmarVendaConcluida:l}):tt==="coonecta"?await cp(t,{confirmarVendaConcluida:l}):await Pd(t,Ke,null,ze||null,mt,{confirmarVendaConcluida:l,...Ut?{motor:tt}:{}})});c({title:"Cotação atualizada",description:qe?A>0?`Preços recalculados com a cobertura editada e ${A}% de desconto.`:"Preços recalculados com a cobertura editada.":`Recotado na ${Rt[tt].nome}.`}),et(A),Bt(ca)}catch(A){const T=tt==="agv"?dp(He(A)):null;T?_(T):c({title:"Não consegui re-cotar",description:He(A),variant:"destructive"})}finally{gt(!1)}}},[t,Ke,Ve,c,ze,mt,l,tt,Ut,qe,Pt]),xn=n.useCallback(async A=>{if(t){I(!0);try{const T=await Pt(()=>Ql(t,{confirmarVendaConcluida:l,modeloEscolhido:A}));_(null),c({title:"Cotação atualizada",description:`Recotado na AGV (${A}).`}),et(T),Bt(ca)}catch(T){c({title:"Não consegui re-cotar",description:He(T),variant:"destructive"})}finally{I(!1)}}},[t,l,c,Pt]),Ts=n.useCallback(()=>{k&&(d==null||d(k.pergunta)),_(null)},[k,d]),Ja=n.useCallback(async A=>{if(!(!t||A===q)){ce(!0);try{const T=await da(t,A);T.exists&&T.propostas.length&&(m(T.propostas),D(T.propostas.map(Y=>Y.proposta_id)),R(new Set(T.propostas.map(Y=>Y.proposta_id))),$(T.recomendada_id??null),b(T.perfil_ia??null),F(T.perfil_socioeconomico??null),lt(En(T.cobertura_aplicada)),qt(T.desconto_aplicado??0),Z(T.placa??A),et(T.desconto_aplicado??0),Bt(ca))}finally{ce(!1)}}},[t,q]),gs=n.useCallback(()=>{ut("curate"),H("editor"),f(!0),ja(A=>A+1)},[]);n.useEffect(()=>{$t&&hs(!0)},[$t]),n.useEffect(()=>{if(!sa||!x)return;const A=setTimeout(()=>{var T;(T=Ka.current)==null||T.scrollIntoView({behavior:"smooth",block:"center"}),Ea(!0),setTimeout(()=>Ea(!1),1600)},120);return()=>clearTimeout(A)},[sa,x]);const Xa=n.useCallback((A,T)=>{const Y=Hf(ga.current,A,T);return Y?Y.kind==="scalar"?({kicker:be,titulo:pe,subtitulo:je,rodape:Ee}[Y.field](Y.value),!0):((Y.list==="coberturas"?Le:Se)(Ze=>Ze.map((kt,Ls)=>Ls===Y.index?{...kt,[Y.prop]:Y.value}:kt)),!0):!1},[]);n.useEffect(()=>{if(!x)return;const A=T=>{var we;const Y=T.data;if(!(!Y||Y.source!=="leadsense-cms")&&T.source===((we=Nt.current)==null?void 0:we.contentWindow)&&typeof Y.field=="str
157ing"){if(Y.type==="focus"){Et(Y.field);return}if(Y.type==="blur"){Et(null);return}Y.type==="edit"&&Xa(Y.field,typeof Y.value=="string"?Y.value:"")&&(ha.current=!0)}};return window.addEventListener("message",A),()=>{window.removeEventListener("message",A),Et(null)}},[x,Xa]);const bs=JSON.stringify(nt);n.useEffect(()=>{if(!x||!t||!Te.length){Q("");return}if(ha.current){ha.current=!1;return}let A=!0;G(!0);const T=setTimeout(()=>{up(t,nt,{editable:!0}).then(Y=>{A&&(Q(Y),Et(null))}).finally(()=>{A&&G(!1)})},400);return()=>{A=!1,clearTimeout(T)}},[x,t,bs]);const ya=n.useCallback(A=>R(T=>{const Y=new Set(T);return Y.has(A)?Y.delete(A):Y.add(A),Y}),[]),Da=A=>{const{active:T,over:Y}=A;Y&&T.id!==Y.id&&D(we=>Qd(we,we.indexOf(String(T.id)),we.indexOf(String(Y.id))))},Za=async()=>{if(t){Ye(!0);try{await mp(t,{kicker:O,titulo:fe,subtitulo:Me,rodape:Oe,coberturas:ye,assistencias:Ne}),ht(!0),c({title:"Padrão da empresa salvo",description:"Vale pras próximas cotações desta empresa."})}catch(A){c({title:"Falha ao salvar",description:He(A),variant:"destructive"})}finally{Ye(!1)}}},Is=async()=>{if(!(!t||!Te.length)){ut("send"),wt(!0);try{const A=await pp(t,nt);ba(A)}finally{wt(!1)}}},Ya=async()=>{if(!t||!Te.length)return;const A={...nt,mensagem:Yt,skip_pdf:zt},T=Te.length;g(!0),f(!1),ut("curate"),c({title:"Enviando cotaçãoâ¦",description:Fe?`${T} ${T===1?"opção":"opções"} + PDF indo pro cliente.`:`${T} ${T===1?"opção":"opções"}, só texto, sem PDF.`});try{await xp(t,A),c({title:"Cotação enviada",description:`${T} ${T===1?"opção":"opções"} pro cliente.`})}catch(Y){g(!1),c({title:"Falha ao enviar",description:He(Y),variant:"destructive"})}};return u.length?e.jsxs(e.Fragment,{children:[i?!x&&e.jsx("div",{className:"absolute bottom-24 right-5 z-30 flex flex-col items-end gap-2 animate-in fade-in slide-in-from-bottom-2",children:e.jsxs("button",{type:"button",onClick:gs,className:`flex items-center gap-2 pl-4 pr-5 py-3 rounded-full bg-card border shadow-xl ring-1 ring-black/5 transition-colors text-sm font-semibold ${Kt?"text-warning border-warning/50 hover:bg-warning/5 animate-pulse":"text-primary border-primary/25 hover:bg-primary/5"}`,title:Kt?"Cotação pronta e AINDA NÃO enviada pro cliente â clique pra revisar":"Revisar, personalizar cobertura e enviar a cotação",children:[e.jsx(br,{className:"w-4 h-4"}),p?"Ver cotação":"Revisar cotação"," (",u.length,")"]})}):e.jsxs("button",{type:"button",onClick:gs,className:`w-full flex items-center gap-2 px-3 py-2 rounded-lg border bg-card transition-colors text-xs font-semibold ${Kt?"border-warning/50 text-warning hover:bg-warning/5 animate-pulse":"border-border hover:bg-muted/50"}`,title:Kt?"Cotação pronta e AINDA NÃO enviada pro cliente":void 0,children:[e.jsx(br,{className:`w-4 h-4 ${Kt?"text-warning":"text-primary"}`}),Kt?"Cotação não enviada · revisar":"Revisar e enviar cotação"," (",u.length,")"]}),x&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-background flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 h-14 border-b flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ot,{className:"w-5 h-5 text-primary flex-shrink-0"}),e.jsx("h3",{className:"text-sm font-bold truncate",children:"Cotação: monte o documento"})]}),e.jsx("div",{className:"md:hidden flex items-center gap-1 bg-muted rounded-lg p-1 mx-2",children:["editor","doc"].map(A=>e.jsxs("button",{onClick:()=>H(A),className:`flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-semibold ${B===A?"bg-card shadow-sm text-foreground":"text-muted-foreground"}`,children:[A==="editor"?e.jsx(Vx,{className:"w-3.5 h-3.5"}):e.jsx(ot,{className:"w-3.5 h-3.5"}),A==="editor"?"Editar":"Documento"]},A))}),e.jsx("button",{onClick:()=>!L&&f(!1),className:"text-muted-foreground hover:text-foreground flex-shrink-0",children:e.jsx(vt,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-1 md:grid-cols-[380px_1fr]",children:[it==="curate"?e.jsxs("div",{className:`${B==="editor"?"block":"hidden"} md:block overflow-y-auto p-3 border-r`,children:[U.length>1&&e.jsxs("div",{className:"mb-2.5",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1 flex items-center gap-1",children:[e.jsx(Yp,{className:"w-3 h-3"})," Carro (",U.length,") · escolha qual enviar"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:U.map(A=>{const T=(A.placa||null)===q;return e.jsxs("button",{type:"button",onClick:()=>Ja(A.placa||null),disabled:ae||T,className:`px-2.5 py-1 rounded-lg border text-[11px] font-medium transition-colors ${T?"bg-primary/10 border-primary/40 text-primary":"border-border hover:bg-muted/50 text-foreground"} disabled:opacity-60`,title:A.veiculo||A.placa||"",children:[ae&&T&&e.jsx(le,{className:"w-3 h-3 inline mr-1 animate-spin"}),A.placa||"sem placa",e.jsxs("span",{className:"text-muted-foreground",children:[" · ",A.total_propostas??0]})]},A.placa||"sem-placa")})})]}),C&&(C.valor_fipe!=null||C.cep||C.idade!=null||C.perfil||C.recomendada)&&e.jsxs("div",{className:"mb-2.5 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-primary mb-1 flex items-center gap-1",children:[e.jsx(ci,{className:"w-3 h-3"})," Decisão da IA · perfil do cliente"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-foreground",children:[v&&v.nivel&&e.jsx("span",{className:`inline-flex items-center rounded-full border px-1.5 py-0.5 text-[10px] font-semibold ${(yr[v.nivel]??yr.desconhecido).cls}`,title:v.motivo||void 0,children:(yr[v.nivel]??yr.desconhecido).label}),typeof C.valor_fipe=="number"&&C.valor_fipe>0&&e.jsxs("span",{children:["FIPE: ",e.jsx("b",{children:Cs(C.valor_fipe)})]}),C.cep&&e.jsxs("span",{children:["CEP: ",e.jsx("b",{children:C.cep})]}),typeof C.idade=="number"&&C.idade>0&&e.jsxs("span",{children:["Idade: ",e.jsx("b",{children:C.idade})]}),C.perfil&&e.jsxs("span",{children:["Perfil: ",e.jsx("b",{children:Wf[C.perfil]??C.perfil})]})]}),C.recomendada&&(C.recomendada.seguradora||C.recomendada.plano)&&e.jsxs("p",{className:"text-[11px] text-foreground mt-1 leading-snug",children:[e.jsx(Ha,{className:"w-3 h-3 inline-block text-primary align-text-bottom mr-0.5"}),"Recomendada: ",e.jsx("b",{children:[C.recomendada.seguradora,C.recomendada.plano].filter(
157Boolean).join(" · ")}),C.recomendada.justificativa&&e.jsxs("span",{className:"text-muted-foreground italic",children:[" · ",C.recomendada.justificativa]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx(br,{className:"w-3 h-3 text-muted-foreground"}),e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Seguradoras"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:[Te.length," de ",u.length," no documento"]}),e.jsxs("span",{className:"ml-auto text-[10px] text-muted-foreground/70 flex items-center gap-1",children:[e.jsx(Gr,{className:"w-3 h-3"})," arraste pra ordenar"]})]}),Te.length>Nr&&e.jsxs("p",{className:"text-[10px] text-warning-text bg-warning/10 border border-warning/20 rounded-md px-2 py-1 mb-1.5 leading-relaxed",children:["O comparativo envia as ",e.jsxs("b",{children:[Nr," primeiras"]})," (é o que cabe numa página). As ",Te.length-Nr," de baixo da linha ficam de fora â reordene pra escolher quais vão."]}),e.jsx(Vd,{sensors:Qa,collisionDetection:Wd,onDragEnd:Da,children:e.jsx(Gd,{items:P,strategy:Kd,children:e.jsx("div",{className:"space-y-1",children:P.map(A=>{const T=xe.get(A);if(!T)return null;const Y=V.has(A),we=Y?Te.indexOf(A)+1:null;return e.jsxs(n.Fragment,{children:[we===Nr+1&&e.jsxs("div",{className:"flex items-center gap-2 py-0.5","aria-hidden":!0,children:[e.jsx("span",{className:"h-px flex-1 bg-warning/40"}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider font-semibold text-warning-text",children:"daqui pra baixo não vai"}),e.jsx("span",{className:"h-px flex-1 bg-warning/40"})]}),e.jsx(th,{p:T,checked:Y,isRec:M===A,pos:we,onToggle:()=>ya(A),onRec:()=>$(M===A?null:A)})]},A)})})})}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2 leading-relaxed",children:["A caixa inclui no documento e a ",e.jsx(Ha,{className:"w-2.5 h-2.5 inline align-text-top"})," marca a recomendada. Pra mudar a copy, clique no texto do documento ao lado. O texto que acompanha o PDF você revisa na hora de enviar."]}),e.jsxs("div",{ref:Ka,className:`mt-3 rounded-lg border px-3 py-2 transition-colors ${Aa?"border-primary ring-2 ring-primary/40 bg-primary/5":"border-border bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(di,{className:"w-3 h-3 text-muted-foreground"}),e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Cobertura · re-cotar"}),e.jsxs("span",{className:"ml-auto text-[10px] text-muted-foreground tabular-nums",children:[$r.filter(([A])=>Ke[A]).length,"/",$r.length," inclusos"]})]}),w.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2 pb-2 border-b border-border/60",children:w.map(A=>{const T=Rt[A],Y=tt===A;return e.jsx("button",{type:"button",onClick:()=>{xs(A),pn(!0)},disabled:Ve,title:T.porque,"aria-pressed":Y,className:`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] transition-colors disabled:opacity-50 ${Y?"border-primary bg-primary/10 text-primary font-semibold":"border-border bg-background text-muted-foreground hover:border-input hover:text-foreground"}`,children:T.nome},A)})}),!qe&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mb-2 italic",children:[Rt[tt].nome," cota com regras próprias da seguradora â cobertura, desconto e comissão abaixo não se aplicam a este motor."]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[$r.map(([A,T])=>{const Y=Ke[A];return e.jsxs("button",{type:"button",onClick:()=>aa(A),disabled:Ve||!qe,"aria-pressed":Y,title:Y?`${T}: incluso (clique pra tirar)`:`${T}: fora (clique pra incluir)`,className:`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] transition-colors disabled:opacity-50 ${Y?"border-primary/40 bg-primary/10 text-primary font-medium":"border-border bg-background text-muted-foreground hover:border-input hover:text-foreground"}`,children:[Y?e.jsx(Xt,{className:"w-2.5 h-2.5 flex-shrink-0",strokeWidth:3}):e.jsx(us,{className:"w-2.5 h-2.5 flex-shrink-0 opacity-50"}),T]},A)}),st.filter(A=>A.tipo==="bool").map(A=>{const T=!!Ke[A.key],Y=kc(A.key);return e.jsxs("button",{type:"button",onClick:()=>re(A.key,!T),disabled:Ve||!qe,"aria-pressed":T,title:A.descricao||Y,className:`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] transition-colors disabled:opacity-50 ${T?"border-primary/40 bg-primary/10 text-primary font-medium":"border-border bg-background text-muted-foreground hover:border-input hover:text-foreground"}`,children:[T?e.jsx(Xt,{className:"w-2.5 h-2.5 flex-shrink-0",strokeWidth:3}):e.jsx(us,{className:"w-2.5 h-2.5 flex-shrink-0 opacity-50"}),Y]},A.key)})]}),st.filter(A=>A.tipo==="int").length>0&&e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:st.filter(A=>A.tipo==="int").map(A=>e.jsxs("label",{className:"text-[11px] text-muted-foreground",title:A.descricao,children:[kc(A.key),e.jsx("input",{type:"number",min:0,disabled:Ve||!qe,value:Ke[A.key]==null?"":String(Ke[A.key]),placeholder:"padrão da seguradora",onChange:T=>re(A.key,T.target.value===""?null:Number(T.target.value)),className:"mt-0.5 w-full rounded border bg-background px-2 py-1 text-xs disabled:opacity-50"})]},A.key))}),e.jsxs("button",{type:"button",onClick:()=>hs(A=>!A),className:"mt-2.5 w-full flex items-center gap-1 rounded-md py-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",children:[e.jsx(dt,{className:`w-3 h-3 transition-transform ${_a?"":"-rotate-90"}`}),"Franquia e limites (RCF)",$t&&e.jsx("span",{className:"ml-1 normal-case tracking-normal text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium",children:"modificado"})]}),_a&&e.jsxs("div",{className:"mt-1 space-y-1.5 rounded-md bg-background/60 border border-border/60 px-2 py-1.5",children:[e.jsxs("label",{className:"flex items-center justify-between gap-2 text-[11px] text-foreground",children:["Franquia",e.jsxs("select",{value:Ke.franquia_tipo,onChange:A=>Xe("franquia_tipo",Number(A.target.value)),disabled:Ve||!qe,className:"rounded border border-input bg-background px-1.5 py-0.5 text-[11px] focus:outline-none focus:ring-1 focus:ring-ring",children:[e.jsx("option",{value:1,children:"Reduzida"}),e.jsx("option",{value:2,children:"Normal"})]})]}),[["danos_materiais","Danos materiais",Qf],["danos_corporais","Danos corporais",Jf],["danos_morais","Danos morais",Xf],["app_morte","APP morte",Zf]].map(([A,T,Y])=>e.jsxs("label",{className:"flex items-center justify-between gap-2 text-[11px] text-foreground",children:[T,e.jsx("select",{value:Ke[A],onChange:we=>Xe(A,Number(we.target.value)),disabled:Ve||!qe,className:"rounded border border-input bg-background px-1.5 py-0.5 text-[11px] focus:outline-none focus:ring-1 focus:ring-ring",children:eh(Y,Number(Ke[A])).map(we=>e.jsx("option",{value:we,children:Yf(we)},we))})]},A))]}),Wt&&e.jsxs("div",{className:`mt-2.5 pt-2.5 border-t transition-colors ${ze>0?"border-primary/30":"border-border"}`,children:[e.jsxs("div",{className:"flex items-center gap-1 text-[11px]",children:[e.jsx(Yd,{className:`w-3 h-3 flex-shrink-0 ${ze>0?"text-primary":"text-muted-foreground"}`}),e.jsx("span",{className:"text-foreground",children:"Desconto"}),e.jsxs("span",{className:"text-muted-foreground cursor-help underline decoration-dotted underline-offset-2",title:`Abatimento no prêmio do cliente, até ${_n}% â teto TÃCNICO da seguradora cotada (a Suhai recusa a cotação inteira acima disso). A comissão do corretor NÃO é afetada.`,children:["até ",_n,"%"]}),e.jsx("span",{className:`ml-auto tabular-nums font-semibold ${ze>0?"text-primary text-[13px]":"text-muted-foreground"}`,children:ze>0?`${String(ze).replace(".",",")}%`:ta>0?`${String(ta).replace(".",",")}
157% já aplicado`:"sem desconto"})]}),ta>0&&e.jsxs("p",{className:"mt-1 text-[10px] leading-snug text-muted-foreground",children:["Os preços acima já saÃram com ",e.jsxs("b",{className:"font-semibold text-foreground",children:[String(ta).replace(".",","),"% de desconto"]}),".",ze>0&&" O novo percentual SUBSTITUI esse (não soma)."]}),e.jsx("input",{type:"range",min:0,max:_n,step:.5,value:ze,onChange:A=>et(Number(A.target.value)),disabled:Ve||!qe,"aria-label":"Desconto no prêmio do cliente",className:"mt-1.5 w-full h-1 accent-primary cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"}),e.jsxs("div",{className:"relative h-3 text-[9px] text-muted-foreground/70 tabular-nums mt-0.5",children:[e.jsx("span",{className:"absolute left-0",children:"0"}),e.jsx("span",{className:"absolute -translate-x-1/2",style:{left:`${3/_n*100}%`},title:"1º degrau da escada do agente",children:"3%"}),e.jsxs("span",{className:"absolute right-0",children:[_n,"%"]})]}),ne&&!ne.indisponivel&&e.jsxs("div",{className:"mt-2 pt-1.5 border-t border-border/60 text-[10px] leading-snug",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Média do mês"}),e.jsxs("span",{className:"text-muted-foreground/70 cursor-help underline decoration-dotted underline-offset-2",title:`Média PONDERADA pelo prêmio vendido: desconto concedido ÷ prêmio total das vendas de ${ne.mes}. Teto de ${ne.teto_pct}%. Cotação que não fechou não entra â desconto só custa quando vira venda.`,children:["(teto ",ne.teto_pct,"%)"]}),e.jsx("span",{className:`ml-auto tabular-nums font-semibold ${ne.media_pct==null?"text-muted-foreground":ne.estourou?"text-warning-text":"text-foreground"}`,children:ne.media_pct==null?"sem venda medida":`${String(ne.media_pct).replace(".",",")}%`})]}),ne.sem_premio>0&&e.jsxs("div",{className:"text-muted-foreground/70 mt-0.5",children:[ne.com_premio," de ",ne.vendas," vendas na conta"," ","(",ne.sem_premio," sem prêmio registrado)"]}),ne.estourou&&e.jsx("div",{className:"text-warning-text mt-0.5",children:"Acima do teto do mês. O desconto segue liberado: decidir cortar é chamada do gestor, não do sistema."})]})]}),fs&&Wt&&e.jsxs("div",{className:`mt-2 pt-2 border-t transition-colors ${at?"border-warning/40":"border-border"}`,children:[e.jsxs("div",{className:"flex items-center gap-1 text-[11px]",children:[e.jsx(ln,{className:`w-3 h-3 flex-shrink-0 ${at?"text-warning-text":"text-muted-foreground"}`}),e.jsx("span",{className:"text-foreground",children:"Comissão"}),e.jsx("span",{className:"text-muted-foreground cursor-help underline decoration-dotted underline-offset-2",title:`Comissão do corretor embutida no prêmio. ${ca}% é o teto (o padrão do corretor â acima disso a seguradora não paga mais rápido, só encarece o cliente); baixar derruba o preço do cliente e a receita da corretora na mesma proporção. Piso de polÃtica ${jo}%. Só admin.`,children:"admin"}),e.jsxs("span",{className:`ml-auto tabular-nums font-semibold ${at?"text-warning-text text-[13px]":"text-muted-foreground"}`,children:[mt,"%",!at&&" (padrão)"]})]}),e.jsx("input",{type:"range",min:jo,max:ca,step:1,value:mt,onChange:A=>Bt(Number(A.target.value)),disabled:Ve||!qe,"aria-label":"Comissão do corretor",className:"mt-1.5 w-full h-1 accent-warning cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"}),e.jsxs("div",{className:"flex justify-between text-[9px] text-muted-foreground/70 tabular-nums mt-0.5",children:[e.jsxs("span",{children:[jo,"% (piso)"]}),e.jsxs("span",{children:[ca,"% (padrão)"]})]})]}),ze>0&&at&&fs&&Wt&&e.jsxs("p",{className:"mt-1.5 text-[10px] text-muted-foreground leading-relaxed",children:["Desconto e comissão reduzida ",e.jsx("b",{className:"font-semibold text-foreground",children:"somam"}),": o corte no preço do cliente é o efeito das duas juntas, e a receita da corretora cai na parte da comissão."]}),!Wt&&u.length>0&&e.jsx("p",{className:"mt-2.5 pt-2.5 border-t border-border text-[10px] text-muted-foreground leading-relaxed",children:"Desconto e comissão não aparecem aqui porque esta cotação não veio do portal da seguradora â pelo multicálculo esses dois não têm efeito no preço."}),e.jsx("button",{type:"button",onClick:ue,disabled:Ve,className:"mt-2.5 w-full inline-flex items-center justify-center gap-1.5 h-9 rounded-md bg-primary text-primary-foreground text-xs font-medium shadow-sm hover:bg-primary/90 active:scale-[0.99] disabled:opacity-60 disabled:active:scale-100 transition-all",children:Ve?e.jsxs(e.Fragment,{children:[e.jsx(le,{className:"w-3.5 h-3.5 animate-spin"})," Re-cotando⦠(~1 min)"]}):e.jsxs(e.Fragment,{children:[e.jsx(jt,{className:"w-3.5 h-3.5"}),qe?ze>0&&at?`Re-cotar com ${ze}% de desconto e comissão de ${mt}%`:ze>0?`Re-cotar com ${ze}% de desconto`:at?`Re-cotar com comissão de ${mt}%`:"Re-cotar com esta cobertura":`Re-cotar na ${Rt[tt].nome}`]})}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1.5 leading-relaxed",children:Ve?"Buscando os preços novos em todas as seguradoras. Dá pra continuar atendendo, isso roda em segundo plano.":ze>0&&at?e.jsxs(e.Fragment,{children:["Desconto de ",e.jsxs("b",{className:"font-semibold text-foreground",children:[ze,"%"]})," no prêmio somado a comissão em ",e.jsxs("b",{className:"font-semibold text-foreground",children:[mt,"%"]})," (padrão é ",ca,"%): o preço do cliente cai pelas duas alavancas, e a ",e.jsx("b",{className:"font-semibold text-foreground",children:"receita da corretora cai na parte da comissão"}),". Fica registrado quem aplicou."]}):ze>0?e.jsxs(e.Fragment,{children:["Os preços saem com ",e.jsxs("b",{className:"font-semibold text-foreground",children:[ze,"% de abatimento"]})," no prêmio do cliente. A comissão não muda. A cotação anterior fica guardada."]}):at?e.jsxs(e.Fragment,{children:["Comissão em ",e.jsxs("b",{className:"font-semibold text-foreground",children:[mt,"%"]})," (padrão é ",ca,"%): o preço do cliente cai e a ",e.jsx("b",{className:"font-semibold text-foreground",children:"receita da corretora cai junto"}),". Fica registrado quem aplicou."]}):"Recalcula os preços com a cobertura escolhida (vale pra todas as seguradoras). A cotação anterior fica guardada."})]})]}):it==="content"?e.jsxs("div",{className:`${B==="editor"?"block":"hidden"} md:block overflow-y-auto p-3 border-r`,children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1 flex items-center gap-1.5",children:[e.jsx(hc,{className:"w-3.5 h-3.5"})," Conteúdo do documento",ke&&e.jsx("span",{className:"ml-auto text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium",children:"padrão da empresa"})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mb-2 leading-relaxed",children:["O caminho rápido é clicar no texto do documento ao lado e escrever. Aqui ficam as coisas que não dá pra fazer clicando: ",e.jsx("b",{className:"font-semibold",children:"adicionar/remover"})," item de lista e salvar o padrão da empresa."]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Marca (topo do documento)"}),e.jsx("input",{value:O,onChange:A=>be(A.target.value),className:"w-full rounded border border-input bg-background px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-ring"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"TÃtulo"}),e.jsx("input",{value:fe,onChange:A=>pe(A.target.value),className:"w-full rounded border border-input bg-background px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-ring"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"SubtÃtulo"}),e.jsx("textarea",{value:Me,onChange:A=>je(A.target.value),rows:2,className:"w-full rounded border border-input bg-background px-2 py-1 text-xs resize-y focus:outline-none focus:ring-1 focus:ring-ring"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground block mb-1",children:"Coberturas inclusas"}),e.jsx(yc,{items:ye,onChange:Le})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground block mb-1",children:"Assistência 24h"}),e.jsx(yc,{items:Ne,onChange:Se})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Rodapé"}),e.jsx("textarea",{value:Oe,onChange:A=>Ee(A.target.value),rows:3,className:"w-full rounded border border-input bg-background px-2 py-1 text-[11px] resize-y focus:outline-none focus:ring-1 focus:ring-ring"})]}),e.jsxs("button",{onClick:Za,disabled:yt||!W,className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-lg border border-primary/30 text-primary text-[11px] font-medium hover:bg-primary/5 disabled:opacity-50",title:"Salva este conteúdo como padrão pras próximas cotações da empresa (gestor/admin)",children:[yt?e.jsx(le,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ln,{className:"w-3.5 h-3.5"}),"Salvar como padrão da empresa"]})]})]}):e.jsxs("div",{className:`${B==="editor"?"block":"hidden"} md:block overflow-y-auto p-3 border-r`,children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1.5",children:Fe?"Mensagem que vai junto do PDF":"Mensagem que o cliente recebe"}),va?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground py-4",children:[e.jsx(le,{className:"w-4 h-4 animate-spin"})," gerando mensagemâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx("textarea",{value:Yt,onChange:A=>ba(A.target.value),rows:12,className:"w-full rounded-lg border border-input bg-background px-3 py-2 text-sm leading-relaxed resize-y focus:outline-none focus:ring-2 focus:ring-ring"}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1 text-right",children:[Yt.length," caracteres"]}),J?e.jsxs("label",{className:"mt-2 flex items-start gap-2 rounded-lg border border-border bg-muted/30 px-3 py-2 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx("input",{type:"checkbox",checked:zt,onChange:A=>ea(A.target.checked),className:"mt-0.5 h-3.5 w-3.5 accent-primary"}),e.jsxs("span",{className:"text-[11px] leading-relaxed",children:[e.jsxs("span",{className:"font-semibold flex items-center gap-1",children:[e.jsx(ot,{className:"w-3 h-3"}
157)," Enviar só o texto (sem PDF)"]}),e.jsx("span",{className:"text-muted-foreground",children:"O cliente recebe só esta mensagem, o PDF não é anexado."})]})]}):e.jsxs("div",{className:"mt-2 flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/5 px-3 py-2",children:[e.jsx(ot,{className:"w-3.5 h-3.5 text-warning mt-0.5 flex-shrink-0"}),e.jsxs("span",{className:"text-[11px] leading-relaxed",children:[e.jsx("span",{className:"font-semibold block",children:"O PDF não é anexado nesta empresa"}),e.jsx("span",{className:"text-muted-foreground",children:"O cliente recebe só a mensagem acima. O documento ao lado é preview interno â dá pra baixar pelo visualizador de cotação e mandar na mão. Ligar o anexo é ajuste na configuração da empresa, não dá pra mudar por aqui."})]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1 leading-relaxed",children:Fe?"Essa é a mensagem que o cliente recebe junto do PDF. Edite à vontade; *texto* vira negrito no WhatsApp.":"Só o texto acima vai pro cliente. Edite à vontade; *texto* vira negrito no WhatsApp."})]})]}),e.jsxs("div",{className:`${B==="doc"?"flex":"hidden"} md:flex flex-col relative bg-muted/30 overflow-hidden`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 border-b bg-card/60 text-[10px] text-muted-foreground flex-shrink-0",children:[e.jsx(ax,{className:"w-3 h-3 text-primary flex-shrink-0"}),Zt?e.jsxs("span",{className:"text-primary font-medium",children:["Editando: ",Vf(Zt)," · Enter confirma, Esc desfaz"]}):e.jsxs("span",{children:["Clique em qualquer texto do documento pra editar direto aqui.",!J&&e.jsx("span",{className:"text-warning font-medium",children:" · preview interno, não vai anexado"})]}),K&&e.jsx(le,{className:"w-3 h-3 animate-spin ml-auto flex-shrink-0"})]}),se?e.jsx("iframe",{ref:Nt,srcDoc:se,title:"Documento da cotação",sandbox:"allow-scripts",className:"w-full flex-1 min-h-0 bg-white"}):e.jsx("div",{className:"flex flex-1 items-center justify-center text-xs text-muted-foreground p-6 text-center",children:Te.length?"gerando documentoâ¦":"selecione ao menos uma seguradora"})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 px-4 py-3 border-t flex-shrink-0",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:it==="curate"?`${Te.length} de ${u.length} no documento`:it==="content"?"Listas do documento: vale pra esta cotação (e pra todas, se salvar como padrão)":Fe?"Revise o PDF e a mensagem antes de enviar":"Revise a mensagem antes de enviar (sem PDF anexado)"}),e.jsx("div",{className:"flex gap-2",children:it==="curate"?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:oe,className:"px-3 py-2 rounded-lg border text-xs hover:bg-muted flex items-center gap-1.5",title:"Adicionar/remover itens das listas e salvar o padrão da empresa (a copy você edita clicando no documento)",children:[e.jsx(hc,{className:"w-3.5 h-3.5"})," Listas e padrão"]}),e.jsx("button",{onClick:()=>f(!1),className:"px-3 py-2 rounded-lg border text-xs hover:bg-muted",children:"Cancelar"}),e.jsxs("button",{onClick:Is,disabled:!Te.length,className:"px-4 py-2 rounded-lg bg-primary text-primary-foreground text-xs font-medium hover:bg-primary/90 disabled:opacity-50 flex items-center gap-2",children:["Revisar e enviar (",Te.length,")"]})]}):it==="content"?e.jsxs("button",{onClick:()=>ut("curate"),className:"px-3 py-2 rounded-lg border text-xs hover:bg-muted flex items-center gap-1.5",children:[e.jsx(br,{className:"w-3.5 h-3.5"})," Voltar pra curadoria"]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>ut("curate"),disabled:L,className:"px-3 py-2 rounded-lg border text-xs hover:bg-muted disabled:opacity-50",children:"Voltar"}),e.jsxs("button",{onClick:Ya,disabled:L||va||!Te.length,className:"px-4 py-2 rounded-lg bg-success text-success-foreground text-xs font-medium hover:bg-success/90 disabled:opacity-50 flex items-center gap-2",children:[L?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(xa,{className:"w-4 h-4"}),"Confirmar e enviar pro cliente"]})]})})]})]}),e.jsx(ui,{open:!!k,onOpenChange:A=>!A&&_(null),children:e.jsxs(mi,{className:"max-w-md",children:[e.jsxs(pi,{children:[e.jsxs(xi,{className:"flex items-center gap-2 text-base",children:[e.jsx(os,{className:"w-4 h-4 text-warning-text"})," Qual é o veÃculo do cliente?"]}),e.jsx(fi,{children:"A placa informada resolveu mais de um modelo. Escolha o certo pra recotar, ou pergunte direto pro cliente."})]}),e.jsx("div",{className:"space-y-1.5",children:k==null?void 0:k.opcoes.map(A=>e.jsxs("button",{onClick:()=>xn(A),disabled:N,className:"w-full text-left px-3 py-2 rounded-lg border text-sm hover:bg-muted hover:border-primary disabled:opacity-50 flex items-center justify-between gap-2",children:[e.jsx("span",{children:A}),N&&e.jsx(le,{className:"w-3.5 h-3.5 animate-spin shrink-0"})]},A))}),e.jsxs(hi,{className:"sm:justify-between",children:[e.jsxs("button",{onClick:Ts,disabled:N||!d,title:d?void 0:"Abra a conversa do lead pra usar esta opção",className:"px-3 py-2 rounded-lg border text-xs hover:bg-muted disabled:opacity-50 flex items-center gap-1.5",children:[e.jsx(Jx,{className:"w-3.5 h-3.5"})," Perguntar pro cliente"]}),e.jsx("button",{onClick:()=>_(null),className:"px-3 py-2 rounded-lg border text-xs hover:bg-muted",children:"Cancelar"})]})]})})]}):null}const ah=/R\$\s*([\d.]+,\d{2})/g;function sh(t){return Number(t.replace(/\./g,"").replace(",","."))}function bu(t){const a=[];for(const s of t.matchAll(ah)){const r=sh(s[1]);Number.isFinite(r)&&r>0&&a.push(r)}return a}function nh(t){var r,i,l,d;const a=[],s=c=>{typeof c=="number"&&c>0&&a.push(c)};return s(t.premio_mensal),s(t.premio_anual),s((r=t.parcelamento_max)==null?void 0:r.valor_parcela),s((i=t.parcelamento_max)==null?void 0:i.total),s((l=t.parcelamento_sem_juros)==null?void 0:l.valor_parcela),s((d=t.parcelamento_sem_juros)==null?void 0:d.total),t.preco_texto&&a.push(...bu(t.preco_texto)),a}const rh=.02;function oh(t,a){return Math.abs(t-a)<=Math.max(t,a)*rh}function ih(t,a){const s=bu(t);if(!s.length||!a.length)return[];const r=a.flatMap(nh);return r.length?s.filter(i=>!r.some(l=>oh(i,l))):[]}function lh(t){const a=(t||"").trim().toLowerCase();return!a||a.includes("nome")}function Cc(t){const a=new Set,s=/\{\{\s*(\d+)\s*\}\}/g;let r;for(;(r=s.exec(t||""))!==null;)a.add(parseInt(r[1],10));return a.size}function ch(t){const a=((t==null?void 0:t.components)||[]).find(s=>String(s.type||"").toUpperCase()==="HEADER");return a&&String(a.format||"TEXT").toUpperCase()==="TEXT"&&a.text||""}function Sc(t,a){return String(t||"").replace(/\{\{\s*(\d+)\s*\}\}/g,(s,r)=>{const i=a[parseInt(r,10)-1];return i||`{{${r}}}`})}
157function dh({open:t,onOpenChange:a,companyId:s,mode:r,leadId:i,leadName:l,checklist:d,onSent:c}){var K;const{toast:u}=At(),[m,x]=n.useState([]),[f,p]=n.useState(!1),[g,y]=n.useState(""),[k,_]=n.useState([]),[N,I]=n.useState([]),[P,D]=n.useState(""),[V,R]=n.useState(""),[M,$]=n.useState(""),[C,b]=n.useState(!1),v=n.useMemo(()=>m.find(G=>G.id===g)||null,[m,g]),F=n.useMemo(()=>Cc((v==null?void 0:v.body_text)||null),[v]),U=n.useMemo(()=>ch(v),[v]),te=n.useMemo(()=>Cc(U)===1,[U]),q=n.useMemo(()=>(l||"").trim().split(/\s+/)[0]||"",[l]),Z=(K=v==null?void 0:v.variable_labels)==null?void 0:K[0],ae=((v==null?void 0:v.variable_field_keys)||[]).join("|");n.useEffect(()=>{t&&(p(!0),fp(s||void 0,"approved").then(G=>{x(G),G.length===1&&y(G[0].id)}).catch(G=>u({title:"Falha ao carregar templates",description:G==null?void 0:G.message,variant:"destructive"})).finally(()=>p(!1)))},[t,s,u]),n.useEffect(()=>{const G=ae?ae.split("|"):[],L=[];_(Array.from({length:F},(S,B)=>{const H=d?sx(G[B]||null,{leadFirstName:q,checklist:d}):"";return H?(L[B]=!0,H):B===0&&q&&lh(Z)?(L[B]=!0,q):(L[B]=!1,"")})),I(L),D(te&&q?q:"")},[g,F,te,q,Z,ae,d]),n.useEffect(()=>{t||(y(""),R(""),$(""),I([]))},[t]);const ce=n.useMemo(()=>{if(!v)return"";const G=[];return U&&G.push(Sc(U,te?[P]:[])),G.push(Sc(v.body_text||"",k)),G.filter(Boolean).join(` 158 159`)},[v,U,te,P,k]),se=!!v&&!C&&k.slice(0,F).every(G=>G.trim())&&(!te||P.trim())&&(r==="reply"?!!i:V.trim().length>=10);async function Q(){if(v){b(!0);try{if(r==="reply")await hp(i,v.id,k,te?P:void 0),u({title:"Template enviado"}),c==null||c(i);else{const{lead_id:G}=await gp({phone:V,name:M.trim()||void 0,templateId:v.id,bodyParams:k,headerParam:te?P:void 0,companyId:s||void 0});u({title:"Conversa iniciada",description:"Mensagem enviada ao número."}),c==null||c(G)}a(!1)}catch(G){u({title:"Falha ao enviar",description:He(G),variant:"destructive"})}finally{b(!1)}}}return e.jsx(ui,{open:t,onOpenChange:a,children:e.jsxs(mi,{className:"max-w-lg",children:[e.jsxs(pi,{children:[e.jsx(xi,{children:r==="new"?"Nova conversa (template)":"Enviar template"}),e.jsx(fi,{children:r==="new"?"Primeira mensagem a um número novo exige um template aprovado pela Meta.":"Reengaja o lead fora da janela de 24h com um template aprovado."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[r==="new"&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ft,{htmlFor:"tpl-phone",children:"Telefone (com DDD)"}),e.jsx(ma,{id:"tpl-phone",placeholder:"27998887766",value:V,onChange:G=>R(G.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ft,{htmlFor:"tpl-name",children:"Nome (opcional)"}),e.jsx(ma,{id:"tpl-name",placeholder:"João",value:M,onChange:G=>$(G.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ft,{children:"Template"}),f?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(le,{className:"w-4 h-4 animate-spin"})," Carregandoâ¦"]}):m.length===0?e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Nenhum template aprovado. Crie e submeta um em ",e.jsx("b",{children:"Templates"}),"."]}):e.jsxs("select",{value:g,onChange:G=>y(G.target.value),className:"w-full bg-background border border-input rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring",children:[e.jsx("option",{value:"",children:"Selecioneâ¦"}),m.map(G=>e.jsxs("option",{value:G.id,children:[G.name," (",G.language,")"]},G.id))]})]}),v&&te&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ft,{children:"Variável do tÃtulo"}),e.jsx(ma,{value:P,onChange:G=>D(G.target.value),placeholder:"valor do {{1}} do tÃtulo"})]}),v&&Array.from({length:F}).map((G,L)=>{var S;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(Ft,{className:"flex items-center gap-1.5",children:[((S=v.variable_labels)==null?void 0:S[L])||`Variável {{${L+1}}}`,N[L]&&e.jsxs(ft,{variant:"secondary",className:"gap-1",children:[e.jsx(jt,{className:"w-3 h-3"})," automático"]})]}),e.jsx(ma,{value:k[L]||"",onChange:B=>{const H=[...k];H[L]=B.target.value,_(H),I(W=>{const X=[...W];return X[L]=!1,X})},placeholder:`valor do {{${L+1}}}`})]},L)}),v&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ft,{children:"Preview"}),e.jsx("div",{className:"rounded-lg bg-muted/40 border border-input p-3 text-sm whitespace-pre-wrap",children:ce}),e.jsx(ft,{variant:"secondary",className:"mt-1",children:v.category})]})]}),e.jsxs(hi,{children:[e.jsx(Pe,{variant:"outline",onClick:()=>a(!1),disabled:C,children:"Cancelar"}),e.jsxs(Pe,{onClick:Q,disabled:!se,children:[C?e.jsx(le,{className:"w-4 h-4 animate-spin mr-2"}
159):e.jsx(xa,{className:"w-4 h-4 mr-2"}),"Enviar"]})]})]})})}const Qr=n.createContext(null);Qr.displayName="PanelGroupContext";const We={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},Ii=10,Ps=n.useLayoutEffect,_c=Tm.useId,uh=typeof _c=="function"?_c:()=>null;let mh=0;function Li(t=null){const a=uh(),s=n.useRef(t||a||null);return s.current===null&&(s.current=""+mh++),t??s.current}function vu({children:t,className:a="",collapsedSize:s,collapsible:r,defaultSize:i,forwardedRef:l,id:d,maxSize:c,minSize:u,onCollapse:m,onExpand:x,onResize:f,order:p,style:g,tagName:y="div",...k}){const _=n.useContext(Qr);if(_===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:N,expandPanel:I,getPanelSize:P,getPanelStyle:D,groupId:V,isPanelCollapsed:R,reevaluatePanelConstraints:M,registerPanel:$,resizePanel:C,unregisterPanel:b}=_,v=Li(d),F=n.useRef({callbacks:{onCollapse:m,onExpand:x,onResize:f},constraints:{collapsedSize:s,collapsible:r,defaultSize:i,maxSize:c,minSize:u},id:v,idIsFromProps:d!==void 0,order:p});n.useRef({didLogMissingDefaultSizeWarning:!1}),Ps(()=>{const{callbacks:te,constraints:q}=F.current,Z={...q};F.current.id=v,F.current.idIsFromProps=d!==void 0,F.current.order=p,te.onCollapse=m,te.onExpand=x,te.onResize=f,q.collapsedSize=s,q.collapsible=r,q.defaultSize=i,q.maxSize=c,q.minSize=u,(Z.collapsedSize!==q.collapsedSize||Z.collapsible!==q.collapsible||Z.maxSize!==q.maxSize||Z.minSize!==q.minSize)&&M(F.current,Z)}),Ps(()=>{const te=F.current;return $(te),()=>{b(te)}},[p,v,$,b]),n.useImperativeHandle(l,()=>({collapse:()=>{N(F.current)},expand:te=>{I(F.current,te)},getId(){return v},getSize(){return P(F.current)},isCollapsed(){return R(F.current)},isExpanded(){return!R(F.current)},resize:te=>{C(F.current,te)}}),[N,I,P,R,v,C]);const U=D(F.current,i);return n.createElement(y,{...k,children:t,className:a,id:v,style:{...U,...g},[We.groupId]:V,[We.panel]:"",[We.panelCollapsible]:r||void 0,[We.panelId]:v,[We.panelSize]:parseFloat(""+U.flexGrow).toFixed(1)})}const ju=n.forwardRef((t,a)=>n.createElement(vu,{...t,forwardedRef:a}));vu.displayName="Panel";ju.displayName="forwardRef(Panel)";let ni=null,Pr=-1,is=null;function ph(t,a){if(a){const s=(a&Cu)!==0,r=(a&Su)!==0,i=(a&_u)!==0,l=(a&Au)!==0;if(s)return i?"se-resize":l?"ne-resize":"e-resize";if(r)return i?"sw-resize":l?"nw-resize":"w-resize";if(i)return"s-resize";if(l)return"n-resize"}switch(t){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function xh(){is!==null&&(document.head.removeChild(is),ni=null,is=null,Pr=-1)}function Eo(t,a){var s,r;const i=ph(t,a);if(ni!==i){if(ni=i,is===null&&(is=document.createElement("style"),document.head.appendChild(is)),Pr>=0){var l;(l=is.sheet)===null||l===void 0||l.removeRule(Pr)}Pr=(s=(r=is.sheet)===null||r===void 0?void 0:r.insertRule(`*{cursor: ${i} !important;}`))!==null&&s!==void 0?s:-1}}function yu(t){return t.type==="keydown"}function Nu(t){return t.type.startsWith("pointer")}function wu(t){return t.type.startsWith("mouse")}function Jr(t){if(Nu(t)){if(t.isPrimary)return{x:t.clientX,y:t.clientY}}else if(wu(t))return{x:t.clientX,y:t.clientY};return{x:1/0,y:1/0}}function fh(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function hh(t,a,s){return t.x<a.x+a.width&&t.x+t.width>a.x&&t.y<a.y+a.height&&t.y+t.height>a.y}function gh(t,a){if(t===a)throw new Error("Cannot compare node with itself");const s={a:Dc(t),b:Dc(a)};let r;for(;s.a.at(-1)===s.b.at(-1);)t=s.a.pop(),a=s.b.pop(),r=t;ve(r,"Stacking order can only be calculated for elements with a common ancestor");const i={a:Ec(Ac(s.a)),b:Ec(Ac(s.b))};if(i.a===i.b){const l=r.childNodes,d={a:s.a.at(-1),b:s.b.at(-1)};let c=l.length;for(;c--;){const u=l[c];if(u===d.a)return 1;if(u===d.b)return-1}}return Math.sign(i.a-i.b)}const bh=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function vh(t){var a;const s=getComputedStyle((a=ku(t))!==null&&a!==void 0?a:t).display;return s==="flex"||s==="inline-flex"}function jh(t){const a=getComputedStyle(t);return!!(a.position==="fixed"||a.zIndex!=="auto"&&(a.position!=="static"||vh(t))||+
159a.opacity<1||"transform"in a&&a.transform!=="none"||"webkitTransform"in a&&a.webkitTransform!=="none"||"mixBlendMode"in a&&a.mixBlendMode!=="normal"||"filter"in a&&a.filter!=="none"||"webkitFilter"in a&&a.webkitFilter!=="none"||"isolation"in a&&a.isolation==="isolate"||bh.test(a.willChange)||a.webkitOverflowScrolling==="touch")}function Ac(t){let a=t.length;for(;a--;){const s=t[a];if(ve(s,"Missing node"),jh(s))return s}return null}function Ec(t){return t&&Number(getComputedStyle(t).zIndex)||0}function Dc(t){const a=[];for(;t;)a.push(t),t=ku(t);return a}function ku(t){const{parentNode:a}=t;return a&&a instanceof ShadowRoot?a.host:a}const Cu=1,Su=2,_u=4,Au=8,yh=fh()==="coarse";let pa=[],nn=!1,ks=new Map,Xr=new Map;const Un=new Set;function Nh(t,a,s,r,i){var l;const{ownerDocument:d}=a,c={direction:s,element:a,hitAreaMargins:r,setResizeHandlerState:i},u=(l=ks.get(d))!==null&&l!==void 0?l:0;return ks.set(d,u+1),Un.add(c),qr(),function(){var x;Xr.delete(t),Un.delete(c);const f=(x=ks.get(d))!==null&&x!==void 0?x:1;if(ks.set(d,f-1),qr(),f===1&&ks.delete(d),pa.includes(c)){const p=pa.indexOf(c);p>=0&&pa.splice(p,1),Oi(),i("up",!0,null)}}}function wh(t){const{target:a}=t,{x:s,y:r}=Jr(t);nn=!0,Ri({target:a,x:s,y:r}),qr(),pa.length>0&&(Br("down",t),t.preventDefault(),Eu(a)||t.stopImmediatePropagation())}function Do(t){const{x:a,y:s}=Jr(t);if(nn&&t.buttons===0&&(nn=!1,Br("up",t)),!nn){const{target:r}=t;Ri({target:r,x:a,y:s})}Br("move",t),Oi(),pa.length>0&&t.preventDefault()}function $o(t){const{target:a}=t,{x:s,y:r}=Jr(t);Xr.clear(),nn=!1,pa.length>0&&(t.preventDefault(),Eu(a)||t.stopImmediatePropagation()),Br("up",t),Ri({target:a,x:s,y:r}),Oi(),qr()}function Eu(t){let a=t;for(;a;){if(a.hasAttribute(We.resizeHandle))return!0;a=a.parentElement}return!1}function Ri({target:t,x:a,y:s}){pa.splice(0);let r=null;(t instanceof HTMLElement||t instanceof SVGElement)&&(r=t),Un.forEach(i=>{const{element:l,hitAreaMargins:d}=i,c=l.getBoundingClientRect(),{bottom:u,left:m,right:x,top:f}=c,p=yh?d.coarse:d.fine;if(a>=m-p&&a<=x+p&&s>=f-p&&s<=u+p){if(r!==null&&document.contains(r)&&l!==r&&!l.contains(r)&&!r.contains(l)&&gh(r,l)>0){let y=r,k=!1;for(;y&&!y.contains(l);){if(hh(y.getBoundingClientRect(),c)){k=!0;break}y=y.parentElement}if(k)return}pa.push(i)}})}function Po(t,a){Xr.set(t,a)}function Oi(){let t=!1,a=!1;pa.forEach(r=>{const{direction:i}=r;i==="horizontal"?t=!0:a=!0});let s=0;Xr.forEach(r=>{s|=r}),t&&a?Eo("intersection",s):t?Eo("horizontal",s):a?Eo("vertical",s):xh()}let Mo=new AbortController;function qr(){Mo.abort(),Mo=new AbortController;const t={capture:!0,signal:Mo.signal};Un.size&&(nn?(pa.length>0&&ks.forEach((a,s)=>{const{body:r}=s;a>0&&(r.addEventListener("contextmenu",$o,t),r.addEventListener("pointerleave",Do,t),r.addEventListener("pointermove",Do,t))}),window.addEventListener("pointerup",$o,t),window.addEventListener("pointercancel",$o,t)):ks.forEach((a,s)=>{const{body:r}=s;a>0&&(r.addEventListener("pointerdown",wh,t),r.addEventListener("pointermove",Do,t))}))}function Br(t,a){Un.forEach(s=>{const{setResizeHandlerState:r}=s,i=pa.includes(s);r(t,i,a)})}function kh(){const[t,a]=n.useState(0);return n.useCallback(()=>a(s=>s+1),[])}function ve(t,a){if(!t)throw console.error(a),Error(a)}function Ms(t,a,s=Ii){return t.toFixed(s)===a.toFixed(s)?0:t>a?1:-1}function za(t,a,s=Ii){return Ms(t,a,s)===0}function Ot(t,a,s){return Ms(t,a,s)===0}function Ch(t,a,s){if(t.length!==a.length)return!1;for(let r=0;r<t.length;r++){const i=t[r],l=a[r];if(!Ot(i,l,s))return!1}return!0}function Ys({panelConstraints:t,panelIndex:a,size:s}){const r=t[a];ve(r!=null,`Panel constraints not found for index ${a}`);let{collapsedSize:i=0,collapsible:l,maxSize:d=100,minSize:c=0}=r;if(Ms(s,c)<0)if(l){const u=(i+c)/2;Ms(s,u)<0?s=i:s=c}else s=c;return s=Math.min(d,s),s=parseFloat(s.toFixed(Ii)),s}function $n({delta:t,initialLayout:a,panelConstraints:s,pivotIndices:r,prevLayout:i,trigger:l}){if(Ot(t,0))return a;const d=[...a],[c,u]=r;ve(c!=null,"Invalid first pivot index"),ve(u!=null,"Invalid second pivot index");let m=0;if(l==="keyboard"){{const f=t<0?u:c,p=s[f];ve(p,`Panel constraints not found for index ${f}`);const{collapsedSize:g=0,collapsible:y,minSize:k=0}=p;if(y){const _=a[f];if(ve(_!=null,`Previous layout not found for panel index ${f}`),Ot(_,g)){const N=k-_;Ms(N,Math.abs(t))>0&&(t=t<0?0-N:N)}}}{const f=t<0?c:u,p=s[f];
159ve(p,`No panel constraints found for index ${f}`);const{collapsedSize:g=0,collapsible:y,minSize:k=0}=p;if(y){const _=a[f];if(ve(_!=null,`Previous layout not found for panel index ${f}`),Ot(_,k)){const N=_-g;Ms(N,Math.abs(t))>0&&(t=t<0?0-N:N)}}}}{const f=t<0?1:-1;let p=t<0?u:c,g=0;for(;;){const k=a[p];ve(k!=null,`Previous layout not found for panel index ${p}`);const N=Ys({panelConstraints:s,panelIndex:p,size:100})-k;if(g+=N,p+=f,p<0||p>=s.length)break}const y=Math.min(Math.abs(t),Math.abs(g));t=t<0?0-y:y}{let p=t<0?c:u;for(;p>=0&&p<s.length;){const g=Math.abs(t)-Math.abs(m),y=a[p];ve(y!=null,`Previous layout not found for panel index ${p}`);const k=y-g,_=Ys({panelConstraints:s,panelIndex:p,size:k});if(!Ot(y,_)&&(m+=y-_,d[p]=_,m.toPrecision(3).localeCompare(Math.abs(t).toPrecision(3),void 0,{numeric:!0})>=0))break;t<0?p--:p++}}if(Ch(i,d))return i;{const f=t<0?u:c,p=a[f];ve(p!=null,`Previous layout not found for panel index ${f}`);const g=p+m,y=Ys({panelConstraints:s,panelIndex:f,size:g});if(d[f]=y,!Ot(y,g)){let k=g-y,N=t<0?u:c;for(;N>=0&&N<s.length;){const I=d[N];ve(I!=null,`Previous layout not found for panel index ${N}`);const P=I+k,D=Ys({panelConstraints:s,panelIndex:N,size:P});if(Ot(I,D)||(k-=D-I,d[N]=D),Ot(k,0))break;t>0?N--:N++}}}const x=d.reduce((f,p)=>p+f,0);return Ot(x,100)?d:i}function Sh({layout:t,panelsArray:a,pivotIndices:s}){let r=0,i=100,l=0,d=0;const c=s[0];ve(c!=null,"No pivot index found"),a.forEach((f,p)=>{const{constraints:g}=f,{maxSize:y=100,minSize:k=0}=g;p===c?(r=k,i=y):(l+=k,d+=y)});const u=Math.min(i,100-l),m=Math.max(r,100-d),x=t[c];return{valueMax:u,valueMin:m,valueNow:x}}function Hn(t,a=document){return Array.from(a.querySelectorAll(`[${We.resizeHandleId}][data-panel-group-id="${t}"]`))}function Du(t,a,s=document){const i=Hn(t,s).findIndex(l=>l.getAttribute(We.resizeHandleId)===a);return i??null}function $u(t,a,s){const r=Du(t,a,s);return r!=null?[r,r+1]:[-1,-1]}function Pu(t,a=document){var s;if(a instanceof HTMLElement&&(a==null||(s=a.dataset)===null||s===void 0?void 0:s.panelGroupId)==t)return a;
159const r=a.querySelector(`[data-panel-group][data-panel-group-id="${t}"]`);return r||null}function Zr(t,a=document){const s=a.querySelector(`[${We.resizeHandleId}="${t}"]`);return s||null}function _h(t,a,s,r=document){var i,l,d,c;const u=Zr(a,r),m=Hn(t,r),x=u?m.indexOf(u):-1,f=(i=(l=s[x])===null||l===void 0?void 0:l.id)!==null&&i!==void 0?i:null,p=(d=(c=s[x+1])===null||c===void 0?void 0:c.id)!==null&&d!==void 0?d:null;return[f,p]}function Ah({committedValuesRef:t,eagerValuesRef:a,groupId:s,layout:r,panelDataArray:i,panelGroupElement:l,setLayout:d}){n.useRef({didWarnAboutMissingResizeHandle:!1}),Ps(()=>{if(!l)return;const c=Hn(s,l);for(let u=0;u<i.length-1;u++){const{valueMax:m,valueMin:x,valueNow:f}=Sh({layout:r,panelsArray:i,pivotIndices:[u,u+1]}),p=c[u];if(p!=null){const g=i[u];ve(g,`No panel data found for index "${u}"`),p.setAttribute("aria-controls",g.id),p.setAttribute("aria-valuemax",""+Math.round(m)),p.setAttribute("aria-valuemin",""+Math.round(x)),p.setAttribute("aria-valuenow",f!=null?""+Math.round(f):"")}}return()=>{c.forEach((u,m)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[s,r,i,l]),n.useEffect(()=>{if(!l)return;const c=a.current;ve(c,"Eager values not found");const{panelDataArray:u}=c,m=Pu(s,l);ve(m!=null,`No group found for id "${s}"`);const x=Hn(s,l);ve(x,`No resize handles found for group id "${s}"`);const f=x.map(p=>{const g=p.getAttribute(We.resizeHandleId);ve(g,"Resize handle element has no handle id attribute");const[y,k]=_h(s,g,u,l);if(y==null||k==null)return()=>{};const _=N=>{if(!N.defaultPrevented)switch(N.key){case"Enter":{N.preventDefault();const I=u.findIndex(P=>P.id===y);if(I>=0){const P=u[I];ve(P,`No panel data found for index ${I}`);const D=r[I],{collapsedSize:V=0,collapsible:R,minSize:M=0}=P.constraints;if(D!=null&&R){const $=$n({delta:Ot(D,V)?M-V:V-D,initialLayout:r,panelConstraints:u.map(C=>C.constraints),pivotIndices:$u(s,g,l),prevLayout:r,trigger:"keyboard"});r!==$&&d($)}}break}}};return p.addEventListener("keydown",_),()=>{p.removeEventListener("keydown",_)}});return()=>{f.forEach(p=>p())}},[l,t,a,s,r,i,d])}function $c(t,a){if(t.length!==a.length)return!1;for(let s=0;s<t.length;s++)if(t[s]!==a[s])return!1;return!0}function Mu(t,a){const s=t==="horizontal",{x:r,y:i}=Jr(a);return s?r:i}function Eh(t,a,s,r,i){const l=s==="horizontal",d=Zr(a,i);ve(d,`No resize handle element found for id "${a}"`);const c=d.getAttribute(We.groupId);ve(c,"Resize handle element has no group id attribute");let{initialCursorPosition:u}=r;const m=Mu(s,t),x=Pu(c,i);ve(x,`No group element found for id "${c}"`);const f=x.getBoundingClientRect(),p=l?f.width:f.height;return(m-u)/p*100}function Dh(t,a,s,r,i,l){if(yu(t)){const d=s==="horizontal";let c=0;t.shiftKey?c=100:i!=null?c=i:c=10;let u=0;switch(t.key){case"ArrowDown":u=d?0:c;break;case"ArrowLeft":u=d?-c:0;break;case"ArrowRight":u=d?c:0;break;case"ArrowUp":u=d?0:-c;break;case"End":u=100;break;case"Home":u=-100;break}return u}else return r==null?0:Eh(t,a,s,r,l)}function $h({panelDataArray:t}){const a=Array(t.length),s=t.map(l=>l.constraints);let r=0,i=100;for(let l=0;l<t.length;l++){const d=s[l];ve(d,`Panel constraints not found for index ${l}`);const{defaultSize:c}=d;c!=null&&(r++,a[l]=c,i-=c)}for(let l=0;l<t.length;l++){const d=s[l];ve(d,`Panel constraints not found for index ${l}`);const{defaultSize:c}=d;if(c!=null)continue;const u=t.length-r,m=i/u;r++,a[l]=m,i-=m}return a}function Vs(t,a,s){a.forEach((r,i)=>{const l=t[i];ve(l,`Panel data not found for index ${i}`);const{callbacks:d,constraints:c,id:u}=l,{collapsedSize:m=0,collapsible:x}=c,f=s[u];if(f==null||r!==f){s[u]=r;const{onCollapse:p,onExpand:g,onResize:y}=d;y&&y(r,f),x&&(p||g)&&(g&&(f==null||za(f,m))&&!za(r,m)&&g(),p&&(f==null||!za(f,m))&&za(r,m)&&p())}})}function wr(t,a){if(t.length!==a.length)return!1;for(let s=0;s<t.length;s++)if(t[s]!=a[s])return!1;return!0}function Ph({defaultSize:t,dragState:a,layout:s,panelData:r,panelIndex:i,precision:l=3}){const d=s[i];let c;return d==null?c=t!=null?t.toPrecision(l):"1":r.length===1?c="1":c=d.toPrecision(l),{flexBasis:0,flexGrow:c,flexShrink:1,overflow:"hidden",pointerEvents:a!==null?"none":void 0}}function Mh(t,a=10){let s=null;return(...i)=>{s!==null&&clearTimeout(s),s=setTimeout(()=>
159{t(...i)},a)}}function Pc(t){try{if(typeof localStorage<"u")t.getItem=a=>localStorage.getItem(a),t.setItem=(a,s)=>{localStorage.setItem(a,s)};else throw new Error("localStorage not supported in this environment")}catch(a){console.error(a),t.getItem=()=>null,t.setItem=()=>{}}}function Tu(t){return`react-resizable-panels:${t}`}function Iu(t){return t.map(a=>{const{constraints:s,id:r,idIsFromProps:i,order:l}=a;return i?r:l?`${l}:${JSON.stringify(s)}`:JSON.stringify(s)}).sort((a,s)=>a.localeCompare(s)).join(",")}function Lu(t,a){try{const s=Tu(t),r=a.getItem(s);if(r){const i=JSON.parse(r);if(typeof i=="object"&&i!=null)return i}}catch{}return null}function Th(t,a,s){var r,i;const l=(r=Lu(t,s))!==null&&r!==void 0?r:{},d=Iu(a);return(i=l[d])!==null&&i!==void 0?i:null}function Ih(t,a,s,r,i){var l;const d=Tu(t),c=Iu(a),u=(l=Lu(t,i))!==null&&l!==void 0?l:{};u[c]={expandToSizes:Object.fromEntries(s.entries()),layout:r};try{i.setItem(d,JSON.stringify(u))}catch(m){console.error(m)}}function Mc({layout:t,panelConstraints:a}){const s=[...t],r=s.reduce((l,d)=>l+d,0);if(s.length!==a.length)throw Error(`Invalid ${a.length} panel layout: ${s.map(l=>`${l}%`).join(", ")}`);if(!Ot(r,100)&&s.length>0)for(let l=0;l<a.length;l++){const d=s[l];ve(d!=null,`No layout data found for index ${l}`);const c=100/r*d;s[l]=c}let i=0;for(let l=0;l<a.length;l++){const d=s[l];ve(d!=null,`No layout data found for index ${l}`);const c=Ys({panelConstraints:a,panelIndex:l,size:d});d!=c&&(i+=d-c,s[l]=c)}if(!Ot(i,0))for(let l=0;l<a.length;l++){const d=s[l];ve(d!=null,`No layout data found for index ${l}`);const c=d+i,u=Ys({panelConstraints:a,panelIndex:l,size:c});if(d!==u&&(i-=u-d,s[l]=u,Ot(i,0)))break}return s}const Lh=100,Pn={getItem:t=>(Pc(Pn),Pn.getItem(t)),setItem:(t,a)=>{Pc(Pn),Pn.setItem(t,a)}},Tc={};function Ru({autoSaveId:t=null,children:a,className:s="",direction:r,forwardedRef:i,id:l=null,onLayout:d=null,keyboardResizeBy:c=null,storage:u=Pn,style:m,tagName:x="div",...f}){const p=Li(l),g=n.useRef(null),[y,k]=n.useState(null),[_,N]=n.useState([]),I=kh(),P=n.useRef({}),D=n.useRef(new Map),V=n.useRef(0),R=n.useRef({autoSaveId:t,direction:r,dragState:y,id:p,keyboardResizeBy:c,onLayout:d,storage:u}),M=n.useRef({layout:_,panelDataArray:[],panelDataArrayChanged:!1});n.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),n.useImperativeHandle(i,()=>({getId:()=>R.current.id,getLayout:()=>{const{layout:L}=M.current;return L},setLayout:L=>{const{onLayout:S}=R.current,{layout:B,panelDataArray:H}=M.current,W=Mc({layout:L,panelConstraints:H.map(X=>X.constraints)});$c(B,W)||(N(W),M.current.layout=W,S&&S(W),Vs(H,W,P.current))}}),[]),Ps(()=>{R.current.autoSaveId=t,R.current.direction=r,R.current.dragState=y,R.current.id=p,R.current.onLayout=d,R.current.storage=u}
159),Ah({committedValuesRef:R,eagerValuesRef:M,groupId:p,layout:_,panelDataArray:M.current.panelDataArray,setLayout:N,panelGroupElement:g.current}),n.useEffect(()=>{const{panelDataArray:L}=M.current;if(t){if(_.length===0||_.length!==L.length)return;let S=Tc[t];S==null&&(S=Mh(Ih,Lh),Tc[t]=S);const B=[...L],H=new Map(D.current);S(t,B,H,_,u)}},[t,_,u]),n.useEffect(()=>{});const $=n.useCallback(L=>{const{onLayout:S}=R.current,{layout:B,panelDataArray:H}=M.current;if(L.constraints.collapsible){const W=H.map(be=>be.constraints),{collapsedSize:X=0,panelSize:oe,pivotIndices:O}=ys(H,L,B);if(ve(oe!=null,`Panel size not found for panel "${L.id}"`),!za(oe,X)){D.current.set(L.id,oe);const fe=Js(H,L)===H.length-1?oe-X:X-oe,pe=$n({delta:fe,initialLayout:B,panelConstraints:W,pivotIndices:O,prevLayout:B,trigger:"imperative-api"});wr(B,pe)||(N(pe),M.current.layout=pe,S&&S(pe),Vs(H,pe,P.current))}}},[]),C=n.useCallback((L,S)=>{const{onLayout:B}=R.current,{layout:H,panelDataArray:W}=M.current;if(L.constraints.collapsible){const X=W.map(Me=>Me.constraints),{collapsedSize:oe=0,panelSize:O=0,minSize:be=0,pivotIndices:fe}=ys(W,L,H),pe=S??be;if(za(O,oe)){const Me=D.current.get(L.id),je=Me!=null&&Me>=pe?Me:pe,Ee=Js(W,L)===W.length-1?O-je:je-O,ye=$n({delta:Ee,initialLayout:H,panelConstraints:X,pivotIndices:fe,prevLayout:H,trigger:"imperative-api"});wr(H,ye)||(N(ye),M.current.layout=ye,B&&B(ye),Vs(W,ye,P.current))}}},[]),b=n.useCallback(L=>{const{layout:S,panelDataArray:B}=M.current,{panelSize:H}=ys(B,L,S);return ve(H!=null,`Panel size not found for panel "${L.id}"`),H},[]),v=n.useCallback((L,S)=>{const{panelDataArray:B}=M.current,H=Js(B,L);return Ph({defaultSize:S,dragState:y,layout:_,panelData:B,panelIndex:H})},[y,_]),F=n.useCallback(L=>{const{layout:S,panelDataArray:B}=M.current,{collapsedSize:H=0,collapsible:W,panelSize:X}=ys(B,L,S);return ve(X!=null,`Panel size not found for panel "${L.id}"`),W===!0&&za(X,H)},[]),U=n.useCallback(L=>{const{layout:S,panelDataArray:B}=M.current,{collapsedSize:H=0,collapsible:W,panelSize:X}=ys(B,L,S);return ve(X!=null,`Panel size not found for panel "${L.id}"`),!W||Ms(X,H)>0},[]),te=n.useCallback(L=>{const{panelDataArray:S}=M.current;S.push(L),S.sort((B,H)=>{const W=B.order,X=H.order;return W==null&&X==null?0:W==null?-1:X==null?1:W-X}),M.current.panelDataArrayChanged=!0,I()},[I]);Ps(()=>{if(M.current.panelDataArrayChanged){M.current.panelDataArrayChanged=!1;const{autoSaveId:L,onLayout:S,storage:B}=R.current,{layout:H,panelDataArray:W}=M.current;let X=null;if(L){const O=Th(L,W,B);O&&(D.current=new Map(Object.entries(O.expandToSizes)),X=O.layout)}X==null&&(X=$h({panelDataArray:W}));const oe=Mc({layout:X,panelConstraints:W.map(O=>O.constraints)});$c(H,oe)||(N(oe),M.current.layout=oe,S&&S(oe),Vs(W,oe,P.current))}}),Ps(()=>{const L=M.current;return()=>{L.layout=[]}},[]);const q=n.useCallback(L=>{let S=!1;const B=g.current;return B&&window.getComputedStyle(B,null).getPropertyValue("direction")==="rtl"&&(S=!0),function(W){W.preventDefault();const X=g.current;if(!X)return()=>null;const{direction:oe,dragState:O,id:be,keyboardResizeBy:fe,onLayout:pe}=R.current,{layout:Me,panelDataArray:je}=M.current,{initialLayout:Oe}=O??{},Ee=$u(be,L,X);let ye=Dh(W,L,oe,O,fe,X);const Le=oe==="horizontal";Le&&S&&(ye=-ye);const Ne=je.map(ht=>ht.constraints),Se=$n({delta:ye,initialLayout:Oe??Me,panelConstraints:Ne,pivotIndices:Ee,prevLayout:Me,trigger:yu(W)?"keyboard":"mouse-or-touch"}),ke=!wr(Me,Se);(Nu(W)||wu(W))&&V.current!=ye&&(V.current=ye,!ke&&ye!==0?Le?Po(L,ye<0?Cu:Su):Po(L,ye<0?_u:Au):Po(L,0)),ke&&(N(Se),M.current.layout=Se,pe&&pe(Se),Vs(je,Se,P.current))}},[]),Z=n.useCallback((L,S)=>{const{onLayout:B}=R.current,{layout:H,panelDataArray:W}=M.current,X=W.map(Me=>Me.constraints),{panelSize:oe,pivotIndices:O}=ys(W,L,H);ve(oe!=null,`Panel size not found for panel "${L.id}"`);const fe=Js(W,L)===W.length-1?oe-S:S-oe,pe=$n({delta:fe,initialLayout:H,panelConstraints:X,pivotIndices:O,prevLayout:H,trigger:"imperative-api"});wr(H,pe)||(N(pe),M.current.layout=pe,B&&B(pe),Vs(W,pe,P.current))},[]),ae=n.useCallback((L,S)=>{const{layout:B,panelDataArray:H}=M.current,{collapsedSize:W=0,collapsible:X}=S,{collapsedSize:oe=0,collapsible:O,maxSize:be=100,minSize:fe=0}=L.constraints,{panelSize:pe}=ys(H,L,B);pe!=null&&(X&&O&&za(pe,W)?za(W,oe)||Z(L,oe):pe<fe?Z(L,fe):pe>be&&Z(L,be))}
159,[Z]),ce=n.useCallback((L,S)=>{const{direction:B}=R.current,{layout:H}=M.current;if(!g.current)return;const W=Zr(L,g.current);ve(W,`Drag handle element not found for id "${L}"`);const X=Mu(B,S);k({dragHandleId:L,dragHandleRect:W.getBoundingClientRect(),initialCursorPosition:X,initialLayout:H})},[]),se=n.useCallback(()=>{k(null)},[]),Q=n.useCallback(L=>{const{panelDataArray:S}=M.current,B=Js(S,L);B>=0&&(S.splice(B,1),delete P.current[L.id],M.current.panelDataArrayChanged=!0,I())},[I]),K=n.useMemo(()=>({collapsePanel:$,direction:r,dragState:y,expandPanel:C,getPanelSize:b,getPanelStyle:v,groupId:p,isPanelCollapsed:F,isPanelExpanded:U,reevaluatePanelConstraints:ae,registerPanel:te,registerResizeHandle:q,resizePanel:Z,startDragging:ce,stopDragging:se,unregisterPanel:Q,panelGroupElement:g.current}),[$,y,r,C,b,v,p,F,U,ae,te,q,Z,ce,se,Q]),G={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return n.createElement(Qr.Provider,{value:K},n.createElement(x,{...f,children:a,className:s,id:l,ref:g,style:{...G,...m},[We.group]:"",[We.groupDirection]:r,[We.groupId]:p}))}const Ou=n.forwardRef((t,a)=>n.createElement(Ru,{...t,forwardedRef:a}));Ru.displayName="PanelGroup";Ou.displayName="forwardRef(PanelGroup)";function Js(t,a){return t.findIndex(s=>s===a||s.id===a.id)}function ys(t,a,s){const r=Js(t,a),l=r===t.length-1?[r-1,r]:[r,r+1],d=s[r];return{...a.constraints,panelSize:d,pivotIndices:l}}function Rh({disabled:t,handleId:a,resizeHandler:s,panelGroupElement:r}){n.useEffect(()=>{if(t||s==null||r==null)return;const i=Zr(a,r);if(i==null)return;const l=d=>{if(!d.defaultPrevented)switch(d.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{d.preventDefault(),s(d);break}case"F6":{d.preventDefault();const c=i.getAttribute(We.groupId);ve(c,`No group element found for id "${c}"`);const u=Hn(c,r),m=Du(c,a,r);ve(m!==null,`No resize element found for id "${a}"`);const x=d.shiftKey?m>0?m-1:u.length-1:m+1<u.length?m+1:0;u[x].focus();break}}};return i.addEventListener("keydown",l),()=>{i.removeEventListener("keydown",l)}},[r,t,a,s])}function Fu({children:t=null,className:a="",disabled:s=!1,hitAreaMargins:r,id:i,onBlur:l,onClick:d,onDragging:c,onFocus:u,onPointerDown:m,onPointerUp:x,style:f={},tabIndex:p=0,tagName:g="div",...y}){var k,_;const N=n.useRef(null),I=n.useRef({onClick:d,onDragging:c,onPointerDown:m,onPointerUp:x});n.useEffect(()=>{I.current.onClick=d,I.current.onDragging=c,I.current.onPointerDown=m,I.current.onPointerUp=x});const P=n.useContext(Qr);if(P===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:D,groupId:V,registerResizeHandle:R,startDragging:M,stopDragging:$,panelGroupElement:C}=P,b=Li(i),[v,F]=n.useState("inactive"),[U,te]=n.useState(!1),[q,Z]=n.useState(null),ae=n.useRef({state:v});Ps(()=>{ae.current.state=v}),n.useEffect(()=>{if(s)Z(null);else{const K=R(b);Z(()=>K)}},[s,b,R]);const ce=(k=r==null?void 0:r.coarse)!==null&&k!==void 0?k:15,se=(_=r==null?void 0:r.fine)!==null&&_!==void 0?_:5;n.useEffect(()=>{if(s||q==null)return;const K=N.current;ve(K,"Element ref not attached");let G=!1;return Nh(b,K,D,{coarse:ce,fine:se},(S,B,H)=>{if(!B){F("inactive");return}switch(S){case"down":{F("drag"),G=!1,ve(H,'Expected event to be defined for "down" action'),M(b,H);const{onDragging:W,onPointerDown:X}=I.current;W==null||W(!0),X==null||X();break}case"move":{const{state:W}=ae.current;G=!0,W!=="drag"&&F("hover"),ve(H,'Expected event to be defined for "move" action'),q(H);break}case"up":{F("hover"),$();const{onClick:W,onDragging:X,onPointerUp:oe}=I.current;X==null||X(!1),oe==null||oe(),G||W==null||W();break}}})},[ce,D,s,se,R,b,q,M,$]),Rh({disabled:s,handleId:b,resizeHandler:q,panelGroupElement:C});const Q={touchAction:"none",userSelect:"none"};return n.createElement(g,{...y,children:t,className:a,id:i,onBlur:()=>{te(!1),l==null||l()},onFocus:()=>{te(!0),u==null||u()},ref:N,role:"separator",style:{...Q,...f},tabIndex:p,[We.groupDirection]:D,[We.groupId]:V,[We.resizeHandle]:"",[We.resizeHandleActive]:v==="drag"?"pointer":U?"keyboard":void 0,[We.resizeHandleEnabled]:!s,[We.resizeHandleId]:b,[We.resizeHandleState]:v})}
159Fu.displayName="PanelResizeHandle";const Oh=({className:t,...a})=>e.jsx(Ou,{className:Ce("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",t),...a}),Ic=ju,Fh=({withHandle:t,className:a,...s})=>e.jsx(Fu,{className:Ce("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 [&[data-panel-group-direction=vertical]>div]:rotate-90",a),...s,children:t&&e.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e.jsx(Gr,{className:"h-2.5 w-2.5"})})});function Lc(t){if(!t||t.manualQuote!==!0)return null;const a=(t.sentByName||"").trim()||(t.senderType==="seller"?(t.senderName||"").trim():"");return a?`Cotação manual · ${a}`:"Cotação manual"}const zh={aprovado:{label:"aprovado",tone:"ia"},editado:{label:"editado",tone:"humano"},manual:{label:"manual",tone:"humano"}};function To(t){if(!t||t.senderType==="client")return null;const a=String(t.origin||"");return zh[a]||null}const qh=["client","agent","seller","system"],Bh=/An[áa]lise autom[áa]tica do documento \(([^,]+),\s*confian[çc]a\s*(\d+)%\)/i;function zu(t){return t===!0||t==="true"}function Uh(t){const a=t.senderType;return a&&qh.includes(a)?a:zu(t.isOutgoing)?"agent":"client"}function qu(t){const a=t==null?void 0:t.match(Bh);return a?{tipo:a[1].trim(),confianca:a[2]}:null}function Bu(t){const a=Uh(t);return a==="system"?zu(t.isOutgoing)?"automatico":qu(t.text)?"nota_ocr":"nota":a==="client"?"cliente":a==="seller"?"vendedor":"agente"}function Hh(t){var i;const a=Bu(t);if(a==="cliente"||a==="nota"||a==="nota_ocr")return null;if(a==="automatico")return"Automático";if(a==="vendedor")return t.senderName||"Vendedor";const s=(((i=t.text)==null?void 0:i.match(/^\*([^*\n]+)\*/))||[])[1],r=t.senderName||s||"Agente";return t.sentByName?`${r} · ${t.sentByName}`:t.authorInferred?r:`${r} · autônomo`}function Vh(t){return Number(String(t).trim().replace(/\./g,"").replace(",","."))}function Uu({leadId:t,leadName:a,companyId:s,open:r,onOpenChange:i,onMarked:l,prefill:d}){const{toast:c}=At(),[u,m]=n.useState([]),[x,f]=n.useState(""),[p,g]=n.useState(""),[y,k]=n.useState(""),[_,N]=n.useState(!1),[I,P]=n.useState(!1);n.useEffect(()=>{r&&(f(""),g(""),k(""),m([]),N(!0),Promise.all([Xs(t).catch(()=>
159null),da(t).catch(()=>null)]).then(([M,$])=>{var v;const C=[],b=M==null?void 0:M.slots.find(F=>F.key==="placa");if(b!=null&&b.value&&C.push(b.value.toUpperCase()),m(C),C.length&&f(C[0]),$!=null&&$.exists&&((v=$.propostas)!=null&&v.length)){const F=$.propostas.find(U=>U.proposta_id===$.recomendada_id)??$.propostas[0];if(F){k(F.seguradora||"");const U=F.premio_anual??(F.premio_mensal!=null?F.premio_mensal*12:null);U&&g(String(U).replace(".",","))}}d!=null&&d.placa&&f(String(d.placa).toUpperCase()),d!=null&&d.seguradora&&k(String(d.seguradora)),(d==null?void 0:d.valor)!=null&&d.valor!==""&&g(String(d.valor).replace(".",","))}).finally(()=>N(!1)))},[r,t]);const D=Vh(p),V=!p||!Number.isFinite(D)||D<=0,R=async()=>{if(!(V||I)){P(!0);try{const M=await bp(t,{dealValue:D,placa:x.trim().toUpperCase()||null,seguradora:y.trim()||null},s);c({title:"Venda registrada"}),l(M),i(!1)}catch(M){c({title:"Falha ao registrar venda",description:He(M),variant:"destructive"})}finally{P(!1)}}};return e.jsx(ui,{open:r,onOpenChange:i,children:e.jsxs(mi,{className:"sm:max-w-[420px]",children:[e.jsxs(pi,{children:[e.jsxs(xi,{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-success-text"})," Marcar venda"]}),e.jsxs(fi,{children:["Registra uma venda para ",e.jsx("span",{className:"font-medium",children:a||"este lead"}),". Pode marcar várias (uma por placa/veÃculo)."]})]}),_?e.jsxs("div",{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[e.jsx(le,{className:"w-4 h-4 animate-spin"})," Buscando dados da cotaçãoâ¦"]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ft,{htmlFor:"sale-placa",children:["Placa ",u.length>0&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(da cotação)"})]}),e.jsx(ma,{id:"sale-placa",list:"sale-placa-options",value:x,onChange:M=>f(M.target.value),placeholder:"Opcional, ex.: ABC1D23",maxLength:16,className:"uppercase"}),u.length>0&&e.jsx("datalist",{id:"sale-placa-options",children:u.map(M=>e.jsx("option",{value:M},M))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ft,{htmlFor:"sale-valor",children:"Valor da venda (R$) *"}),e.jsx(ma,{id:"sale-valor",value:p,onChange:M=>g(M.target.value),onKeyDown:M=>{M.key==="Enter"&&R()},placeholder:"Ex.: 2.500,00",autoFocus:!0}),p&&V&&e.jsx("p",{className:"text-xs text-destructive",children:"Informe um valor positivo."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ft,{htmlFor:"sale-seguradora",children:["Seguradora ",e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(opcional)"})]}),e.jsx(ma,{id:"sale-seguradora",value:y,onChange:M=>k(M.target.value),placeholder:"Ex.: Porto Seguro",maxLength:120})]})]}),e.jsxs(hi,{children:[e.jsx(Pe,{variant:"ghost",onClick:()=>i(!1),disabled:I,children:"Cancelar"}),e.jsxs(Pe,{onClick:R,disabled:V||I||_,children:[I&&e.jsx(le,{className:"w-4 h-4 mr-2 animate-spin"}),"Registrar venda"]})]})]})})}function Wh({leadId:t,leadName:a,companyId:s,onDecided:r}){const{toast:i}=At(),[l,d]=n.useState(null),[c,u]=n.useState(!1),[m,x]=n.useState(!1),f=n.useCallback(()=>{vp(t).then(N=>d(N[0]??null)).catch(()=>d(null))},[t]);if(n.useEffect(()=>{d(null),f()},[f]),!l)return null;const p=l.fields||{},g=p.premio??p.valor,y=[p.seguradora,p.placa,g!=null&&g!==""?`R$ ${g}`:null,p.vigencia?`vigência ${p.vigencia}`:null].filter(Boolean).join(" · "),k=async N=>{try{await Jl(l.id,"confirmed",N==null?void 0:N.id)}catch{}d(null),r()},_=async()=>{if(!m){x(!0);try{await Jl(l.id,"dismissed"),d(null),r()}catch(N){i({title:"Falha ao descartar",description:He(N),variant:"destructive"})}finally{x(!1)}}};return e.jsxs("div",{className:"flex items-center gap-2 border-b bg-success/10 px-3 sm:px-5 py-2 flex-shrink-0",children:[e.jsx(rx,{className:"h-4 w-4 shrink-0 text-success-text"}),e.jsxs("div",{className:"min-w-0 flex-1 text-xs sm:text-sm",children:[e.jsx("span",{className:"font-medium text-success-text",children:l.source==="apolice"?"Apólice recebida â venda detectada":"Fechamento detectado na conversa"}),y&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",y]})]}),e.jsx(Pe,{size:"sm",className:"h-7 px-2.5 text-xs",onClick:()=>u(!0),disabled:m,children:"Registrar venda"}),e.jsx(Pe,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs text-muted-foreground",onClick:_,disabled:m,title:"Não é venda (descarta e reabre o funil)",children:m?e.jsx(le,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(vt,{className:"h-3.5 w-3.5"})}),e.jsx(Uu,{leadId:t,leadName:a,companyId:s,open:c,onOpenChange:u,onMarked:k,prefill:{placa:p.placa??null,seguradora:p.seguradora??null,valor:g??null}})]})}const Rc=[{key:"iniciando",label:"Iniciando a cotação"},{key:"veiculo",label:"Identificando o veÃculo"},{key:"seguradoras",label:"Consultando as seguradoras"},{key:"calculo",label:"Calculando os preços"}],Io=["iniciando","veiculo","seguradoras","calculo"];function In(t){return(t==null?void 0:t.stage)==="transmitindo"||(t==null?void 0:t.stage)==="transmitida"||(t==null?void 0:t.stage)==="transmissao_falhou"}function Yr(t){return!!t&&(t.status==="error"||t.stage==="falhou")}function Hu(t){return!!t&&(t.status==="done"||t.stage==="concluida")}function Vu(t){return!t||In(t)?!1:!Hu(t)&&!Yr(t)}function Gh(t){if(!t||In(t))return!1;if(Vu(t))return!0;const a=t.diagnostico??null,s=!!(a&&(a.resumo||a.grupos&&a.grupos.length));return!!a&&(Yr(t)||s)}function Oc({progress:t}){var _,N;const[a,s]=n.useState(!1);if(!t)return null;if(t.stage==="transmitindo"||t.stage==="transmitida"||t.stage==="transmissao_falhou"){const I=t.stage==="transmissao_falhou",P=t.stage==="transmitida",D=I?Ba:P?Xt:le;return e.jsx("div",{className:"border-b bg-card px-5 py-1.5 flex-shrink-0 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-[11px] font-semibold text-foreground flex-shrink-0",children:"Proposta"}),e.jsx(D,{className:`h-3.5 w-3.5 flex-shrink-0 ${I?"text-warning":P?"text-success":"text-primary"} ${!I&&!P?"animate-spin":""}`}),e.jsx("span",{className:`text-[11px] truncate ${I?"text-warning":"text-foreground"}`,children:I?"Não foi transmitida":P?"Transmitida para a seguradora":"Transmitindoâ¦"}),I&&t.detail&&e.jsxs("span",{className:"text-[10px] text-muted-foreground truncate",title:t.detail,children:["· ",t.detail]})]})})}const r=Yr(t),i=Hu(t),l=i?Io.length:Io.indexOf(t.stage==="falhou"?"calculo":t.stage);let d=le,c="text-primary",u=!0,m=((_=Rc[Math.max(0,Math.min(l,Rc.length-1))])==null?void 0:_.label)??"Iniciando a cotação",x="text-foreground";if(i){d=Xt,c="text-success",u=!1;const I=t.propostas_count;m=I?`${I}
159 ${I===1?"opção enviada":"opções enviadas"} ao cliente`:"Propostas enviadas ao cliente"}else r&&(d=Ba,c="text-warning",u=!1,x="text-warning",m="Atendente vai finalizar");const f=!i&&!r?(t.seguradoras??[]).filter(Boolean):[],p=t.diagnostico??null,g=!!(p&&(p.resumo||p.grupos&&p.grupos.length)),y=!!p&&(r||g),k=!!((N=p==null?void 0:p.acao_nossa)!=null&&N.length);return e.jsxs("div",{className:"border-b bg-card px-5 py-1.5 flex-shrink-0 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-[11px] font-semibold text-foreground flex-shrink-0",children:"Cotação"}),e.jsx(d,{className:`h-3.5 w-3.5 flex-shrink-0 ${c} ${u?"animate-spin":""}`}),e.jsx("span",{className:`text-[11px] truncate ${x}`,children:m}),r&&t.detail&&e.jsxs("span",{className:"text-[10px] text-muted-foreground truncate",children:["· ",t.detail]}),f.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground truncate",title:f.join(", "),children:["· ",Xh(f)]}),y&&e.jsxs("button",{type:"button",onClick:()=>s(I=>!I),className:`text-[10px] flex items-center gap-0.5 flex-shrink-0 ml-auto hover:text-foreground ${k?"text-warning":"text-muted-foreground"}`,"aria-expanded":a,children:[a?e.jsx(dt,{className:"h-3 w-3"}):e.jsx(As,{className:"h-3 w-3"}),r?"Por que não cotou":"Por que essas opções",k&&` (${p.acao_nossa.length} recuperável${p.acao_nossa.length>1?"is":""})`]}),!i&&!r&&e.jsxs("span",{className:"text-[10px] text-muted-foreground ml-auto flex-shrink-0",children:[Math.max(0,l)+1,"/",Io.length]})]}),y&&a&&e.jsx(Jh,{diag:p})]})}const Kh={dado_nosso_corrigido:"Dado nosso estava errado e foi corrigido automaticamente",falta_dado_do_cliente:"Falta o cliente confirmar um dado",falha_tecnica:"Falha técnica na plataforma da seguradora",entrega_falhou:"A cotação foi calculada, mas não chegou ao cliente"},Qh={cpf:"CPF",cep:"CEP",placa:"Placa",modelo:"Marca/modelo",nome:"Nome",data_nascimento:"Data de nascimento"};function Jh({diag:t}){const a=t.fixes??[],s=t.grupos??[];return e.jsxs("div",{className:"mt-1.5 rounded-md border bg-muted/40 px-3 py-2 space-y-1.5",children:[t.causa!=="cotou"&&e.jsxs("p",{className:"text-[11px] text-foreground",children:[Kh[t.causa??""]??"Não foi possÃvel concluir a cotação",t.campo&&e.jsxs("span",{className:"text-muted-foreground",children:[" · campo: ",Qh[t.campo]??t.campo]})]}),t.resumo&&e.jsx("p",{className:"text-[11px] text-foreground",children:t.resumo}),s.length>0&&e.jsx("ul",{className:"space-y-0.5",children:s.map(r=>e.jsxs("li",{className:"text-[10px] flex items-start gap-1",children:[e.jsx("span",{className:r.acao_nossa?"text-warning":"text-muted-foreground",children:r.acao_nossa?"â":"·"}),e.jsxs("span",{className:"text-muted-foreground",children:[e.jsx("span",{className:"text-foreground",children:r.seguradoras.join(", ")}),": ",r.label,r.acao_nossa&&r.exemplo&&e.jsx("span",{className:"block font-mono opacity-70 break-words",children:r.exemplo})]})]},r.id))}),a.length>0&&e.jsx("ul",{className:"space-y-0.5",children:a.map((r,i)=>e.jsxs("li",{className:"text-[10px] text-muted-foreground flex items-start gap-1",children:[e.jsx(Ua,{className:"h-3 w-3 mt-0.5 flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-foreground",children:r.field}),r.from!=null&&e.jsxs(e.Fragment,{children:[" : ",String(r.from)," â"]})," ",String(r.to),r.why&&e.jsxs("span",{className:"text-muted-foreground",children:[" (",r.why,")"]})]})]},`${r.field}-${i}`))}),t.mensagem&&e.jsx("p",{className:"text-[10px] text-muted-foreground font-mono break-words",children:t.mensagem})]})}function Xh(t){const a=t.length===1?"respondeu":"responderam";return t.length<=2?`${t.join(" e ")} ${a}`:`${t.slice(0,2).join(", ")} e mais ${t.length-2} ${a}`}const Zh={etapa:Od,cotacao:cu,dados:ms,proposta:ot,janela:_t},Yh={neutro:"text-muted-foreground",positivo:"text-success",atencao:"text-warning-text"},Fc="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] leading-none";function eg({chips:t,aberta:a=null,aoAcionar:s,ordemClasse:r=""}){return t.length===0?null:e.jsx("div",{className:`flex flex-wrap items-center gap-1 border-t bg-card px-3 sm:px-5 py-1 flex-shrink-0 ${r}`,children:t.map(i=>{const l=Zh[i.id],d=Yh[i.tom];if(i.acao==="nenhuma")return e.jsxs("span",{className:`${Fc} ${d}`,children:[e.jsx(l,{className:"h-3 w-3 flex-shrink-0","aria-hidden":"true"}),i.rotulo]},i.id);const c=i.acao==="expande"&&a===i.id;return e.jsxs("button",{type:"button",onClick:()=>s==null?void 0:s(i.id),"aria-expanded":i.acao==="expande"?c:void 0,className:`${Fc} ${d} cursor-pointer hover:bg-muted ${c?"bg-muted":""}`,children:[e.jsx(l,{className:"h-3 w-3 flex-shrink-0","aria-hidden":"true"}),i.rotulo,i.acao==="expande"?e.jsx(dt,{className:`h-3 w-3 flex-shrink-0 transition-transform ${c?"rotate-180":""}`,"aria-hidden":"true"}):e.jsx(dn,{className:"h-3 w-3 flex-shrink-0","aria-hidden":"true"})]},i.id)})})}function tg({chips:t,secoes:a,alertaEm:s=null,aoAcionarChip:r,posicao:i="rodape",abrirPorPadrao:l=null}){const[d,c]=n.useState(s??l??null);n.useEffect(()=>{s&&c(s)},[s]);const u=n.useCallback(p=>{const g=t.find(y=>y.id===p);if((g==null?void 0:g.acao)==="dropdown"){r==null||r(p);return}p!=="janela"&&c(y=>y===p?null:p)},[t,r]),m=d?a[d]:null,x=i==="topo"?"[&>*]:md:order-2":"[&>*]:md:order-6",f=i==="topo"?"md:order-3":"md:order-7";return e.jsxs(e.Fragment,{children:[m&&e.jsx("div",{className:`contents ${x}`,children:m}),e.jsx(eg,{chips:t,aberta:d,aoAcionar:u,ordemClasse:f})]})}function ag(t){var l,d,c,u;const{cotacaoProgress:a,checklist:s,jornada:r,propostaVisivel:i}=t;return(a==null?void 0:a.stage)==="transmissao_falhou"?"proposta":(d=(l=a==null?void 0:a.diagnostico)==null?void 0:l.acao_nossa)!=null&&d.length?"cotacao":s!=null&&s.nome_revisar||(u=(c=s==null?void 0:s.cotacao_desatualizada)==null?void 0:c.campos)!=null&&u.length?"dados":(r==null?void 0:r.vistoria_status)==="divergente"||i&&!r?"proposta":null}function sg(t){const{etapa:a,propostas:s,cotacaoFalhou:r,cotacaoEmAndamento:i,cotacaoComDetalhe:l,cotacaoEnviada:d,cotacaoSecaoVisivel:c=!0,preenchidos:u,total:m,prontoPraCotar:x,vendaEncerrada:f,propostaVisivel:p,temJornada:g,horasForaDaJanela:y,transmissao:k}=t,_=[],N=c&&!!l;if(a&&_.push({id:"etapa",rotulo:a,tom:"neutro",acao:"expande"}),r)_.push({id:"cotacao",rotulo:"Cotação falhou",tom:"atencao",acao:N?"expande":"nenhuma"});else if(s){const P=d===!1;_.push({id:"cotacao",rotulo:`${s} ${s===1?"opção":"opções"}${P?" · não enviada":""}`,tom:P?"atencao":"neutro",acao:P?"dropdown":N?"expande":"nenhuma"})}else i&&_.push({id:"cotacao",rotulo:"Cotandoâ¦",tom:"neutro",acao:c?"expande":"nenhuma"});if(typeof u=="number"&&typeof m=="number"&&m>0&&_.push({id:"dados",rotulo:`Dados ${u}/${m}`,tom:x&&!f?"positivo":"neutro",acao:"expande"}),k==="transmitindo"||k==="transmitida"||k==="transmissao_falhou"){const P=k==="transmissao_falhou"?"Não transmitida":k==="transmitida"?"Transmitida":"Transmitindoâ¦";_.push({id:"proposta",rotulo:P,tom:k==="transmissao_falhou"?"atencao":"neutro",acao:"expande"})}else p&&_.push(g?{id:"proposta",rotulo:"Proposta",tom:"neutro",acao:"expande"}:{id:"proposta",rotulo:"não registrada",tom:"atencao",acao:"expande"});return typeof y=="number"&&y>0&&_.push({id:"janela",rotulo:`${y}h`,tom:"atencao",acao:"nenhuma"}),_}const Wu=["class","data-theme","lang","dir"];function Gu(t){for(const a of Wu){const s=document.documentElement.getAttribute(a);s===null?t.documentElement.removeAttribute(a):t.documentElement.setAttribute(a,s)}}function ng(t){var r;const a=new MutationObserver(()=>Gu(t));a.observe(document.documentElement,{attributes:!0,attributeFilter:Wu});const s=new MutationObserver(i=>{for(const l of i)for(const d of Array.from(l.addedNodes))(d instanceof HTMLStyleElement||d instanceof HTMLLinkElement)&&t.head.appendChild(d.cloneNode(!0))});s.observe(document.head,{childList:!0}),(r=t.defaultView)==null||r.addEventListener("pagehide",()=>{a.disconnect(),s.disconnect()})}function rg(t){for(const a of Array.from(document.styleSheets))try{const s=Array.from(a.cssRules).map(i=>i.cssText).join(` 160`),r=t.createElement("style");r.textContent=s,t.head.appendChild(r)}catch{if(a.href){const s=t.createElement("link");s.rel="stylesheet",s.href=a.href,t.head.appendChild(s)}}t.body.style.margin="0",t.body.style.overflow="hidden",Gu(t),ng(t)}function og(t){const[a,s]=n.useState(null),r=n.useRef(null),[i]=n.useState(()=>document.createElement("div")),l=n.useRef(t);n.useEffect(()=>{l.current=t},[t]);const d=n.useCallback(()=>{var u;(u=r.current)==null||u.close(),r.current=null,s(null)},[]);n.useEffect(()=>()=>{var u;(u=r.current)==null||u.close()},[]);const c=n.useCallback(u=>{const m=window.documentPictureInPicture;m!==void 0&&m.requestWindow({width:(u==null?void 0:u.largura)??480,height:(u==null?void 0:u.altura)??800}).then(x=>
160{r.current=x,rg(x.document),x.document.body.appendChild(i),x.addEventListener("pagehide",()=>{r.current=null,s(null),l.current()}),s(x.document)}).catch(x=>{console.error("[sidebar] não foi possÃvel abrir a janela",x)})},[i]);return{documento:a,suportado:typeof window<"u"&&window.documentPictureInPicture!==void 0,host:i,abrir:c,fechar:d}}const ig={success:"success",warning:"warning",info:"info",neutro:"secondary"};function Lo({r:t}){return e.jsx(ft,{variant:ig[t.tom],size:"sm",title:t.title,children:t.texto})}function zc({jornada:t}){return e.jsxs(e.Fragment,{children:[t.vistoria===!0&&e.jsx(ft,{variant:"success",size:"sm",title:t.vistoria_at?`Vistoria em ${new Date(t.vistoria_at).toLocaleString("pt-BR")}`:void 0,children:"vistoria feita"}),t.vistoria_status==="nao_necessario"&&e.jsx(ft,{variant:"secondary",size:"sm",title:"A Suhai não exige vistoria prévia nesta proposta. Não há o que cobrar do cliente.",children:"não exige vistoria"}),t.vistoria===!1&&t.vistoria_status==="agendada"&&e.jsx(ft,{variant:"warning",size:"sm",title:"Ordem de serviço cadastrada: a vistoria foi marcada e ainda não aconteceu.",children:"vistoria agendada"}),t.vistoria_status==="divergente"&&e.jsx(ft,{variant:"warning",size:"sm",title:"A lista da seguradora diz 'não necessário', mas há uma etapa de Vistoria Prévia cadastrada no workflow desta proposta. Confira direto no portal antes de confiar num dos dois.",children:"confira vistoria"}),t.vistoria===!1&&t.vistoria_status!=="agendada"&&e.jsx(ft,{variant:"warning",size:"sm",title:t.vistoria_status==="cancelada"?"Vistoria cancelada no portal da seguradora.":void 0,children:t.vistoria_status==="cancelada"?"vistoria cancelada":"vistoria pendente"})]})}function qc({jornada:t}){var a,s,r;return e.jsxs(e.Fragment,{children:[((a=t.links)==null?void 0:a.vistoria)&&e.jsx("a",{href:t.links.vistoria,target:"_blank",rel:"noreferrer",className:"text-[11px] text-primary hover:underline",title:"Link de vistoria enviado ao cliente",children:"link da vistoria"}),((s=t.links)==null?void 0:s.boleto)&&e.jsx("a",{href:t.links.boleto,target:"_blank",rel:"noreferrer",className:"text-[11px] text-primary hover:underline",children:"boleto"}),((r=t.links)==null?void 0:r.apolice)&&e.jsx("a",{href:t.links.apolice,target:"_blank",rel:"noreferrer",className:"text-[11px] text-primary hover:underline",children:"apólice"})]})}function lg({jornada:t}){const[a,s]=n.useState(!1);if(!t)return null;const r=Qp(t),i=Jp(t),l=Xp(t.id_proposta),d=r.find(m=>m.key==="proxima"),c=r.filter(m=>m.key!=="proxima"),u=t.vistoria===null&&!t.vistoria_status&&t.pago===null&&t.apolice===null&&r.length===0;return e.jsxs("div",{className:"border-b bg-card px-3 sm:px-5 py-1.5 flex-shrink-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-[11px] font-semibold text-foreground",children:"Proposta"}),t.numero_proposta&&e.jsx("span",{className:"text-[11px] text-muted-foreground font-mono",children:t.numero_proposta}),l&&e.jsx("a",{href:l,target:"_blank",rel:"noreferrer",className:"inline-flex items-center text-muted-foreground hover:text-primary",title:"Abrir esta proposta no portal da Suhai",children:e.jsx(Kn,{className:"h-3 w-3"})}),t.status_desc&&e.jsx("span",{className:"text-[10px] text-muted-foreground uppercase",children:t.status_desc}),i?e.jsxs(e.Fragment,{children:[d&&e.jsx(Lo,{r:d}),e.jsxs("button",{type:"button",onClick:()=>s(m=>!m),"aria-expanded":a,className:"inline-flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground",title:"Vistoria, pagamento e apólice desta proposta",children:[a?e.jsx(dt,{className:"h-3 w-3"}):e.jsx(As,{className:"h-3 w-3"}),"Histórico"]})]}):e.jsxs(e.Fragment,{children:[e.jsx(zc,{jornada:t}),r.map(m=>e.jsx(Lo,{r:m},m.key)),t.apolice===!0&&e.jsx(ft,{variant:"success",size:"sm",children:"apólice emitida"}),e.jsx(qc,{jornada:t})]})]}),i&&a&&e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-border/50 pt-1",children:[e.jsx(zc,{jornada:t}),c.map(m=>e.jsx(Lo,{r:m},m.key)),t.apolice===!0&&e.jsx(ft,{variant:"success",size:"sm",title:t.apolice_at?`Emitida em ${new Date(t.apolice_at).toLocaleStr
160ing("pt-BR")}`:void 0,children:"apólice emitida"}),t.apolice===!1&&e.jsx(ft,{variant:"secondary",size:"sm",title:"O emissor respondeu que não há apólice para esta proposta.",children:"apólice não emitida"}),e.jsx(qc,{jornada:t})]}),u&&e.jsx("div",{className:"text-[10px] text-muted-foreground/70 mt-0.5",title:"Ou a seguradora ainda não devolveu esses campos, ou ainda não sabemos lê-los. Não significa que o cliente não fez.",children:"sem confirmação da seguradora sobre vistoria e pagamento"})]})}function cg(t){if(!t||t.apolice===!0)return!1;const a=t.vistoria===!1&&t.vistoria_status!=="nao_necessario",s=t.pago===!1;return a||s}function dg({jornada:t,companyId:a,podeAgir:s,aoDeclarar:r,declarando:i}){var p;const[l,d]=n.useState(!1),[c,u]=n.useState(null),m=n.useCallback(async()=>{if(!(!(t!=null&&t.id)||l)){d(!0),u(null);try{const g=await Zp(t.id,a??void 0);u(g.cobrou?g.enviado===!1?"Virou rascunho no inbox â aprove pra sair.":"Cobrança enviada.":`Não cobrei: ${g.motivo||"sem motivo"}`)}catch(g){u(He(g))}finally{d(!1)}}},[t==null?void 0:t.id,a,l]);if(!t)return e.jsx("div",{className:"border-b bg-warning/5 px-3 sm:px-5 py-1.5 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-[11px] font-semibold text-foreground",children:"Proposta"}),e.jsx(ft,{variant:"warning",size:"sm",children:"não registrada"}),e.jsx("span",{className:"text-[10px] leading-snug text-muted-foreground",children:"Este lead já passou da escolha do plano e não há proposta registrada. Sem ela o acompanhamento de vistoria e pagamento não roda, e o follow-up volta a tratar o cliente como quem só recebeu cotação."}),s&&!i&&e.jsx("button",{type:"button",onClick:r,className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-primary/40 px-2 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10",children:"Registrar proposta emitida"})]})});const x=!t.checked_at,f=cg(t);return e.jsxs(e.Fragment,{children:[e.jsx(lg,{jornada:t}),e.jsx("div",{className:"border-b bg-card px-3 sm:px-5 py-1 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[t.origem==="manual"&&e.jsx(ft,{variant:"secondary",size:"sm",title:"Proposta declarada pelo operador (transmitida à mão no portal da seguradora).",children:"registrada à mão"}),x&&e.jsx("span",{className:"text-[10px] text-muted-foreground",title:"O acompanhamento consulta o portal a cada 15 minutos. Enquanto não consultar pela primeira vez, vistoria e pagamento ficam em branco â é espera, não erro.",children:"aguardando a primeira consulta ao portal"}),((p=t.links)==null?void 0:p.vistoria)&&e.jsxs("a",{href:t.links.vistoria,target:"_blank",rel:"noreferrer",className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] font-medium text-muted-foreground hover:bg-muted",children:[e.jsx(Kn,{className:"h-3 w-3"})," Abrir vistoria"]}),s&&f&&e.jsxs("button",{type:"button",onClick:m,disabled:l,title:"Manda a cobrança da pendência pelo mesmo caminho do follow-up automático (respeita janela de envio, rascunho pendente e do-not-contact).",className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-primary/40 px-2 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10 disabled:opacity-50",children:[l?e.jsx(le,{className:"h-3 w-3 animate-spin"}):e.jsx(xa,{className:"h-3 w-3"}),l?"Cobrandoâ¦":"Cobrar agora"]}),c&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:c})]})})]})}const ug=["duvidas_iniciais","coleta_dados_cotacao","cotacao","apresentacao_proposta","coleta_documentos","efetivacao","aguardando_pagamento","pos_venda"],mg="coleta_documentos";function Bc(t){return ug.indexOf(String(t||""))}function pg(t){const a=Bc(t);return a>=0&&a>=Bc(mg)}function xg(t){return t.encerrada?"pos_venda":t.temJornada?"proposta":pg(t.saleStep)?"sem_registro":"cotacao"}function Uc(t){return t==="cotacao"}function Ro(t){return t!=="cotacao"}const mn={quote:{label:"Cotação",cls:"bg-success/10 text-success-text ring-success/30",icon:cs},negotiation:{label:"Negociação",cls:"bg-success/10 text-success-text ring-success/30",icon:ws},handoff:{label:"Transferiu",cls:"bg-warning/10 text-warning-text ring-warning/30",icon:tn},escalate:{label:"Escalou",cls:"bg-warning/10 text-warning-text ring-warning/30",icon:tn},collect:{label:"Coletou",cls:"bg-primary/10 text-primary-text ring-primary/30",icon:ms},followup:{label:"Follow-up",cls:"bg-primary/10 text-primary-text ring-primary/30",icon:_t},objection:{label:"Objeção",cls:"bg-destructive/10 text-destructive-text ring-destructive/30",icon:fa},action:{label:"Ação",cls:"bg-warning/10 text-warning-text ring-warning/30",icon:Ua},takeover:{label:"Humano assumiu",cls:"bg-warning/10 text-warning-text ring-warning/30",icon:tn},respond:{label:"Respondeu",cls:"bg-primary/10 text-primary-text ring-primary/30",icon:fa}},fg={autonomous:"autônomo",auto:"autônomo",draft:"rascunho"},hg={duvidas_iniciais:"Tirando dúvidas",coleta_dados_cotacao:"Coletando dados","captura-de-dados":"Coletando dados","coleta-de-dados":"Coletando dados",coleta_dados:"Coletando dados",cotacao:"Cotação feita",apresentacao_proposta:"Proposta apresentada",coleta_documentos:"Coletando documentos",efetivacao:"Fechando",aguardando_pagamento:"Aguardando pagamento",pos_venda:"Pós-venda",negociacao:"Negociação",qualificacao:"Qualificação","primeiro-atendimento":"Primeiro atendimento",fechado:"Fechado",perdido:"Perdido"};function Ku(t){return t?hg[t]||t.replace(/[-_]/g," ").replace(/^\w/,a=>a.toUpperCase()):"-"}
160const gg={nome:"nome",placa:"placa",modelo:"modelo",marca:"marca",ano_fabricacao:"ano de fabricação",ano_modelo:"ano do modelo",ano:"ano",cpf:"CPF",cep:"CEP",estado_civil:"estado civil",uso:"uso do veÃculo",moradia:"moradia",condutor_jovem:"condutor jovem (18-26)",blindado:"blindagem",data_nascimento:"data de nascimento",valor_fipe:"valor FIPE",chassi:"chassi"};function Hc(t){return t?gg[t]||String(t).replace(/_/g," "):"-"}const bg=/não está disponÃvel|não está implementada|não se aplica|indispon[Ãi]vel para esta empresa/i,vg=[{re:/placa|veiculo|fipe/i,label:"Consultei o veÃculo",icon:zn},{re:/cotac|cotar|quote|premio/i,label:"Cotei o seguro",icon:cs},{re:/pdf|proposta|apresent/i,label:"Preparei a proposta",icon:Hx},{re:/boleto|pagamento|pix|cobranc/i,label:"Gerei a cobrança",icon:cu},{re:/cpf|cnpj|cep|cadastr|salv|coleta|dados|associado/i,label:"Registrei os dados do cliente",icon:Wx},{re:/handoff|escal|transfer|humano/i,label:"Encaminhei pra um atendente",icon:tn},{re:/agenda|calendar|follow/i,label:"Agendei um retorno",icon:_t}];function jg(t){const a=vg.find(s=>s.re.test(t));return a?{label:a.label,icon:a.icon}:{label:"Executei uma ação",icon:Ua}}function Fi(t){const a=new Date(t);return Number.isNaN(a.getTime())?"":a.toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:cn()})}const yg={cpf:"CPF",cnpj:"CNPJ",cep:"CEP",nome:"Nome",telefone:"Telefone",email:"E-mail",placa:"Placa",chassi:"Chassi",ano:"Ano",ano_modelo:"Ano modelo",ano_fabricacao:"Ano fabricação",uso:"Uso",garagem:"Garagem",estado_civil:"Estado civil",condutor_jovem:"Condutor jovem",dados_veiculo:"VeÃculo",veiculo:"VeÃculo",fipe:"FIPE",valor:"Valor",preco:"Preço",preco_mensal:"Preço mensal",premio:"Prêmio",parcela:"Parcela",parcelas:"Parcelas",seguradora:"Seguradora",plano:"Plano",cobertura:"Cobertura",pdf_url:"PDF",numero_proposta:"Nº proposta",proposta_id:"ID proposta",status:"Status",ok:"OK",data_nascimento:"Nascimento",genero:"Gênero"},Ng=/valor|preco|preço|premio|prêmio|fipe|parcela|mensal|total/i,wg=/^https?:\/\//i,kg=/(^|_)id$|^_?id$|_id$|token|hash|signature|_key$|worksite|correlation|request_id|trace|session/i;function Qu(t){return kg.test(t)}function Cg(t){return yg[t]||t.replace(/_/g," ").replace(/^\w/,a=>a.toUpperCase())}function Sg(t){return t.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function _s(t){if(typeof t=="string"){const a=t.trim();if(a.startsWith("{")||a.startsWith("["))try{return JSON.parse(a)}catch{}}return t}function Vc({k:t,v:a}){if(typeof a=="string"&&wg.test(a)){const s=/pdf/i.test(t)||/\.pdf(\?|$)/i.test(a);return e.jsxs("a",{href:a,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-primary hover:underline break-all",children:[s?e.jsx(ot,{className:"w-3 h-3"}):e.jsx(Kn,{className:"w-3 h-3"}),s?"Abrir PDF":"Abrir link"]})}return typeof a=="number"&&Ng.test(t)?e.jsx(e.Fragment,{children:Sg(a)}):typeof a=="boolean"?e.jsx(e.Fragment,{children:a?"sim":"não"}):a==null||a===""?e.jsx("span",{className:"text-muted-foreground",children:"-"}):e.jsx(e.Fragment,{children:String(a)})}const _g=["plano","seguradora","nome","titulo","descricao","label"];function Ag(t){const a=_g.find(i=>typeof t[i]=="string"&&t[i]),s=a?String(t[a]):null,r=Object.entries(t).filter(([i])=>i!==a&&!Qu(i));return{title:s,rest:r}}function Ur({data:t,depth:a=0}){const s=_s(t);if(s==null||typeof s!="object")return e.jsx("div",{className:"text-[11px] text-foreground/80 whitespace-pre-wrap break-words",children:String(s??"-")});if(Array.isArray(s))return s.length===0?e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"-"}):s.every(i=>i&&typeof i=="object"&&"label"in i&&"value"in i)?e.jsx("div",{className:Ce("space-y-0.5",a>0&&"mt-0.5 border-l border-border pl-2"),children:s.map((i,l)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs("span",{className:"text-[11px] text-muted-foreground shrink-0",children:[String(i.label),":"]}),e.jsx("span",{className:"text-[11px] text-foreground/90 break-words",children:e.jsx(Vc,{k:String(i.label),v:i.value})})]},l))}):s.every(i=>i&&typeof _s(i)=="object")?e.jsx("div",{className:"space-y-1.5 mt-0.5",children:s.map((i,l)=>{const{title:d,rest:c}=Ag(_s(i));return e.jsxs("div",{className:"rounded border border-border/60 bg-background/40 p-1.5",children:[d&&e.jsx("div",{className:"text-[11px] font-semibold text-foreground mb-0.5",children:d}),e.jsx(Ur,{data:Object.fromEntries(c),depth:a+1})]},l)})}
160):e.jsx("span",{className:"text-[11px] text-foreground/90 break-words",children:s.map(i=>String(i)).join(", ")});const r=Object.entries(s).filter(([i])=>!Qu(i));return e.jsx("div",{className:Ce("space-y-0.5",a>0&&"mt-0.5 border-l border-border pl-2"),children:r.map(([i,l])=>{const d=l&&typeof _s(l)=="object";return e.jsxs("div",{className:Ce(!d&&"flex gap-1.5"),children:[e.jsxs("span",{className:"text-[11px] text-muted-foreground shrink-0",children:[Cg(i),":"]}),d?e.jsx(Ur,{data:l,depth:a+1}):e.jsx("span",{className:"text-[11px] text-foreground/90 break-words",children:e.jsx(Vc,{k:i,v:l})})]},i)})})}function Eg(t){if(typeof t!="string"||!t)return{};const a={},s=t.indexOf('"propostas"'),r=s>=0?t.slice(0,s).replace(/[,\s]*$/,""):t.replace(/[,\s]*$/,"");try{Object.assign(a,JSON.parse(r.endsWith("}")?r:r+"}"))}catch{}if(s>=0){const i=t.indexOf("[",s),l=[];if(i>=0){let d=0,c=-1,u=!1,m=!1;for(let x=i+1;x<t.length;x++){const f=t[x];if(u){m?m=!1:f==="\\"?m=!0:f==='"'&&(u=!1);continue}if(f==='"'){u=!0;continue}if(f==="{")d===0&&(c=x),d++;else if(f==="}"&&(d--,d===0&&c>=0)){try{l.push(JSON.parse(t.slice(c,x+1)))}catch{}c=-1}}}l.length&&(a.propostas=l)}return a}function Dg(t){const a=_s(t);if(!a||typeof a!="object")return null;const s=a;if(Array.isArray(s.propostas))return s.propostas;for(const r of Object.values(s)){const i=_s(r);if(i&&typeof i=="object"&&Array.isArray(i.propostas))return i.propostas}return null}function $g({t}){const a=t.arguments&&typeof t.arguments=="object"&&Object.keys(t.arguments).length>0,s=_s(t.result_summary),r=!!(s&&typeof s=="object"&&s._truncated===!0),i=r&&Number(s.bytes)||null,l=r?Eg(String(s.preview||"")):null,d=r?String(s.preview||""):"",c=r?l&&Object.keys(l).length?l:null:s,u=c!=null&&c!=="",m=Dg(c),x=t.seguradoras_cotadas&&t.seguradoras_cotadas.length?t.seguradoras_cotadas:m?Array.from(new Set(m.map(g=>typeof g.seguradora=="string"?g.seguradora:null).filter(Boolean))):[],f=t.outcome==="needs_input",p=!f&&!t.ok&&!!t.error&&bg.test(t.error);return e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx(Ua,{className:"w-3 h-3 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-mono text-[11px] font-semibold text-foreground/90",children:t.tool_name}),e.jsxs("span",{className:Ce("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium",f?"bg-primary/10 text-primary-text":t.ok?"bg-success/10 text-success-text":p?"bg-muted text-muted-foreground":"bg-destructive/10 text-destructive"),children:[f?e.jsx(os,{className:"w-2.5 h-2.5"}):t.ok?e.jsx(ki,{className:"w-2.5 h-2.5"}):e.jsx(wi,{className:"w-2.5 h-2.5"}),f?"pediu um dado":t.ok?"ok":p?"não se aplica":"erro"]}),t.duration_ms!=null&&!p&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[(t.duration_ms/1e3).toFixed(1),"s"]})]}),a&&!p&&e.jsxs("div",{className:"mt-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold mb-0.5",children:"enviou"}),e.jsx(Ur,{data:t.arguments})]}),p?e.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground italic",children:"Não se aplica a esta empresa, ignorado, não afetou o atendimento."}):t.error?e.jsxs("div",{className:"mt-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-destructive font-semibold",children:"erro"}),e.jsx("pre",{className:"mt-0.5 max-h-32 overflow-auto rounded bg-destructive/5 p-1.5 text-[10px] leading-tight font-mono text-destructive whitespace-pre-wrap break-words",children:t.error})]}):(u||r)&&e.jsxs("div",{className:"mt-1.5",children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold mb-0.5 flex items-center gap-1.5",children:["voltou",r&&e.jsxs("span",{className:"normal-case rounded-full bg-warning/10 text-warning-text px-1.5 py-0.5 text-[9px] font-medium",children:["truncado",i?` · ${(i/1024).toFixed(1)} KB`:"",", parcial"]})]}),x.length>0&&e.jsxs("div",{className:"mb-1.5 flex flex-wrap items-center gap-1",children:[e.jsxs("span",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold mr-0.5",children:["Cotado em (",x.length,")"]}),x.map(g=>e.jsx("span",{className:"inline-flex items-center rounded-full bg-primary/10 text-primary px-2 py-0.5 text-[10px] font-medium",children:g},g))]}),c?e.jsx(Ur,{data:c}):e.jsx("pre",{className:"max-h-40 overflow-auto rounded bg-background/60 p-1.5 text-[10px] leading-tight font-mono text-foreground
160/70 whitespace-pre-wrap break-words",children:d})]})]})}function qa({icon:t,label:a,children:s}){return e.jsxs("div",{className:"flex gap-2.5",children:[e.jsx(t,{className:"w-3.5 h-3.5 mt-0.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold",children:a}),e.jsx("div",{className:"text-xs text-foreground/90 leading-snug break-words",children:s})]})]})}const Pg=3*60*1e3;function kr({title:t,subtitle:a,text:s,onExpand:r}){return e.jsxs("div",{onClick:r,className:Ce("rounded-lg border bg-muted/30 p-2",r&&"cursor-pointer hover:bg-muted/50 transition-colors"),children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-foreground/80",children:t}),a&&e.jsx("div",{className:"text-[10px] text-muted-foreground",children:a}),e.jsx("p",{className:"mt-0.5 line-clamp-3 text-[11px] leading-snug text-foreground/70",children:s||"Vazio."})]})}const Mg={acao_irreversivel:{label:"Ação irreversÃvel",hint:"O turno ia disparar ação sem volta (emissão/cobrança) â por isso passa por humano."},proposta:{label:"Proposta",hint:"A resposta apresentou proposta/cotação ao cliente."},repeticao:{label:"Repetição",hint:"A resposta repetia, palavra por palavra, algo que já havia sido dito."},valores:{label:"Valores",hint:"A resposta cita preço/valor â turno sensÃvel, conferido contra a cotação real."},contorno_objecao:{label:"Contorno de objeção",hint:"O cliente objetou neste turno e a resposta é o contorno."},operacional:{label:"Operacional",hint:"O turno executou ferramenta (consulta/registro), não foi só conversa."},conversa:{label:"Conversa",hint:"Turno conversacional: sem ação executada e sem preço citado."}},Tg={objection:"objeção",price_mention:"falou de preço",coverage_request:"pediu cobertura"},Ig={hot:"quente",warm:"morno",cold:"frio",quente:"quente",morno:"morno",frio:"frio"};function ka({title:t,subtitle:a,hint:s,onExpand:r,children:i}){return e.jsxs("div",{onClick:r,title:s||void 0,className:Ce("rounded-lg border bg-muted/30 p-2",r&&"cursor-pointer hover:bg-muted/50 transition-colors"),children:[e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-foreground/80",children:t}),a&&e.jsx("span",{className:"text-[10px] text-muted-foreground truncate",children:a})]}),e.jsx("div",{className:"mt-0.5 text-[11px] leading-snug text-foreground/70",children:i})]})}function Lg({r:t}){var l,d,c,u,m,x;const a=t.digression_attempts||0,s=Math.max(0,(t.ask_attempts||0)-(t.answer_attempts||0)-a),r=t.stall_threshold!=null&&s>=t.stall_threshold-1,i=t.action==="handoff_agv"?"Entregou pro consultor":t.action==="quote"?"Decidiu cotar":t.is_retry?`Re-perguntou ${t.field||""}`.trim():`Pediu ${t.field||"o próximo dado"}`;return e.jsxs(e.Fragment,{children:[e.jsxs(ka,{title:"Motor de coleta",subtitle:"regra, sem LLM",hint:"Decide qual dado falta, quando cotar e quando escalar. DeterminÃstico: não passa por modelo de linguagem.",children:[e.jsx("span",{className:Ce("font-medium",t.action==="handoff_agv"?"text-warning-text":"text-foreground/90"),children:i}),t.rule&&e.jsx("p",{className:"mt-0.5 text-[10px] text-muted-foreground",children:t.rule})]}),e.jsxs(ka,{title:"Insistência neste campo",subtitle:t.field||"â",hint:"A trava conta perguntas IGNORADAS: perguntadas, menos as em que o cliente tentou responder (mesmo errando), menos as em que ele perguntou/objetou. Typo e divagação não contam como recusa.",children:[e.jsxs("span",{className:Ce("font-medium",r?"text-warning-text":"text-foreground/90"),children:[t.ask_attempts," pergunta(s) · ",t.answer_attempts," tentativa(s) do cliente",a>0?` · ${a} divagação(ões)`:""]}),e.jsxs("p",{className:"mt-0.5 text-[10px] text-muted-foreground",children:[s," ignorada(s)",t.stall_threshold!=null?` · escala em ${t.stall_threshold}`:"",t.stall_hard_cap!=null?` · teto ${t.stall_hard_cap}`:"",t.cpf_refused?" · CPF recusado":""]})]}),((l=t.extractions)==null?void 0:l.length)>0&&e.jsx(ka,{title:"Extração de dados",subtitle:`${t.extractions.length} passada(s) nesta rajada`,hint:"O extrator lê UMA mensagem por vez, sem histórico. Passada que esperava um campo e voltou vazia é dado que pode ter se perdido.",children:e.jsx("div",{className:"space-y-0.5",children:t.extractions.slice(-4).map((f,p)=>{var y;const g=!((y=f.keys)!=null&&y.length);return e.jsxs("div",{className:"flex items-baseline gap-1 text-[10px]",children:[e.jsx("span",{className:"text-muted-foreground",children:"esperava"}
160),e.jsx("span",{className:"font-medium text-foreground/80",children:f.expected||"â"}),e.jsx("span",{className:"text-muted-foreground",children:"â"}),e.jsx("span",{className:Ce("font-medium",g?"text-destructive":"text-success"),children:g?"nada":f.keys.join(", ")}),g&&f.answered_attempt&&e.jsx("span",{className:"text-muted-foreground",children:"(tinha a forma do campo)"})]},p)})})}),(((d=t.missing_required)==null?void 0:d.length)>0||((c=t.filled_keys)==null?void 0:c.length)>0)&&e.jsxs(ka,{title:"Estado da coleta",subtitle:`${((u=t.filled_keys)==null?void 0:u.length)||0} preenchido(s)`,children:[e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"text-foreground/80",children:"falta:"})," ",(m=t.missing_required)!=null&&m.length?t.missing_required.join(", "):"nada obrigatório"]}),((x=t.filled_keys)==null?void 0:x.length)>0&&e.jsxs("p",{className:"mt-0.5 text-[10px] text-muted-foreground line-clamp-2",children:[e.jsx("span",{className:"text-foreground/80",children:"tem:"})," ",t.filled_keys.join(", ")]})]})]})}function Rg({detail:t}){const[a,s]=n.useState(null),r=t.message_category?Mg[t.message_category]:null,i=t.negotiation_prediction,l=t.sentiment,d=t.tool_calls||[],c=t.model==="coleta_deterministica"||!!t.collect_reasoning&&!t.message_category&&!i&&!t.response_text_b,u=i?Object.entries(Tg).filter(([m])=>i[m]):[];return e.jsxs(qa,{icon:Ge,label:"SaÃda de cada agente neste turno",children:[e.jsxs("div",{className:"mt-1 grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:[t.collect_reasoning&&e.jsx(Lg,{r:t.collect_reasoning}),t.message_category&&e.jsxs(ka,{title:"Classificador",subtitle:"regra determinÃstica",hint:r==null?void 0:r.hint,children:[e.jsx("span",{className:"font-medium text-foreground/90",children:(r==null?void 0:r.label)||t.message_category}),r&&e.jsx("p",{className:"mt-0.5 text-[10px] text-muted-foreground line-clamp-2",children:r.hint})]}),i&&e.jsxs(ka,{title:"Ãrbitro de negociação",subtitle:"antes do LLM",hint:"Decide, sem chamar modelo, se o turno é negociação/objeção. Hoje só observa (não troca o modelo).",children:[e.jsx("span",{className:Ce("font-medium",i.predicted?"text-warning-text":"text-foreground/90"),children:i.predicted?"Turno de negociação":"Turno normal"}),e.jsxs("p",{className:"mt-0.5 text-[10px] text-muted-foreground",children:["etapa ",i.stage||"â",u.length>0?` · ${u.map(([,m])=>m).join(", ")}`:" · nenhum sinal de negociação"]})]}),l&&(l.score!=null||l.classification)&&e.jsxs(ka,{title:"Termômetro do cliente",subtitle:"heurÃstica do turno",children:[e.jsxs("span",{className:"font-medium text-foreground/90",children:[l.score!=null?`${l.score}`:"â",l.classification?` · ${Ig[l.classification]||l.classification}`:""]}),e.jsx("p",{className:"mt-0.5 text-[10px] text-muted-foreground",children:[l.trend?`tendência ${l.trend}`:null,l.objection?"objeção":null,l.urgency?"urgência":null,l.frustration?"frustração":null].filter(Boolean).join(" · ")||"sem sinal de alerta"})]}),t.response_text&&e.jsxs(ka,{title:"Agente que respondeu",subtitle:t.model||"modelo principal",onExpand:()=>s(a==="main"?null:"main"),children:[e.jsx("p",{className:"line-clamp-3",children:t.response_text}),e.jsx("p",{className:"mt-0.5 text-[10px] text-primary",children:"Clique pra ver o texto completo"})]}),t.response_text_b&&e.jsxs(ka,{title:"2ª opinião",subtitle:`${t.model_b||"Haiku"} · não enviada`,onExpand:()=>s(a==="ab"?null:"ab"),children:[e.jsx("p",{className:"line-clamp-3",children:t.response_text_b}),e.jsx("p",{className:"mt-0.5 text-[10px] text-primary",children:"Clique pra comparar com a enviada"})]}),d.length>0&&e.jsxs(ka,{title:"Ferramentas",subtitle:`${d.length} no turno`,children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:d.map((m,x)=>{var f;return e.jsxs("span",{title:m.from_audit?"Execução achada na auditoria, fora do trace do turno":void 0,className:Ce("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px]",m.ok===!1?"bg-destructive/10 text-destructive":"bg-background/60 text-muted-foreground"),children:[m.ok===!1?e.jsx(wi,{className:"w-2.5 h-2.5"}):e.jsx(ki,{className:"w-2.5 h-2.5"}),m.name,m.deferred?" · adiada":"",((f=m.io)==null?void 0:f.duration_ms)!=null?` · ${m.io.duration_ms}ms`:""]},x)})}),d.some(m=>m.io)?e.jsx("div",{className:"mt-1 space-y-1",children:d.filter(m=>m.io).map((m,x)=>{var f,p,g;return e.jsxs("div",{className:"rounded border bg-card/60 p-1",children:[e.jsx("p",{className:"text-[9px] font-semibold uppercase tracking-wide text-muted-foreground",children:m.name}),((f=m.io)==null?void 0:f.arguments)&&e.jsxs("p",{className:"mt-0.5 break-all text-[9px] leading-snug text-foreground
160/70",children:[e.jsx("span",{className:"text-muted-foreground",children:"enviou "}),m.io.arguments]}),((p=m.io)==null?void 0:p.result)&&e.jsxs("p",{className:"mt-0.5 break-all text-[9px] leading-snug text-foreground/70",children:[e.jsx("span",{className:"text-muted-foreground",children:"voltou "}),m.io.result]}),((g=m.io)==null?void 0:g.error)&&e.jsx("p",{className:"mt-0.5 break-all text-[9px] leading-snug text-destructive",children:m.io.error})]},x)})}):e.jsx("p",{className:"mt-0.5 text-[10px] text-muted-foreground",children:"O que cada uma enviou e recebeu está em âFerramentasâ, acima."})]})]}),c&&e.jsxs("p",{className:"mt-1.5 text-[10px] leading-snug text-muted-foreground",children:["Este turno foi decidido por ",e.jsx("span",{className:"font-medium text-foreground/80",children:"regra"}),", sem chamar modelo de linguagem: quem escolheu o próximo passo foi o motor de coleta acima. Por isso não há classificador, árbitro de negociação, termômetro nem 2ª opinião neste turno."]}),a==="main"&&e.jsxs("div",{className:"mt-2 rounded-lg border bg-muted/30 p-2",children:[e.jsxs("p",{className:"mb-1 text-[10px] font-semibold text-muted-foreground",children:[t.model||"modelo principal"," · enviada ao cliente"]}),e.jsx("p",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-words text-[10px] leading-relaxed text-foreground/80",children:t.response_text}),e.jsx("button",{onClick:()=>s(null),className:"mt-1 text-[10px] font-medium text-muted-foreground hover:text-foreground",children:"Fechar"})]}),a==="ab"&&e.jsxs("div",{className:"mt-2 rounded-lg border bg-muted/30 p-2",children:[e.jsxs("p",{className:"mb-1.5 text-[10px] font-semibold text-muted-foreground",children:[t.model||"modelo principal"," (enviada) vs. ",t.model_b||"Haiku"," (alternativa, só comparação)"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded border bg-card p-1.5",children:[e.jsx("p",{className:"mb-1 text-[9px] font-medium text-success",children:"Enviada ao cliente"}),e.jsx("p",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-words text-[10px] leading-relaxed text-foreground/80",children:t.response_text||"â"})]}),e.jsxs("div",{className:"rounded border bg-card p-1.5",children:[e.jsx("p",{className:"mb-1 text-[9px] font-medium text-muted-foreground",children:"Alternativa (não enviada)"}),e.jsx("p",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-words text-[10px] leading-relaxed text-foreground/80",children:t.response_text_b})]})]}),e.jsx("button",{onClick:()=>s(null),className:"mt-1.5 text-[10px] font-medium text-muted-foreground hover:text-foreground",children:"Fechar"})]})]})}function Og({leadId:t,companyId:a,decisionCreatedAt:s}){var p;const[r,i]=n.useState(null),[l,d]=n.useState("loading"),[c,u]=n.useState(!1);if(n.useEffect(()=>{if(!t||!a){d("not_found");return}let g=!0;d("loading"),i(null),u(!1);const y=new Date(s).getTime();return cx({companyId:a,leadId:t,limit:50}).then(async k=>{if(!g)return;let _=null;for(const I of k.turns){if(!I.created_at)continue;const P=Math.abs(new Date(I.created_at).getTime()-y);P<=Pg&&(!_||P<_.diff)&&(_={traceId:I.trace_id,diff:P})}if(!_){g&&d("not_found");return}const N=await dx(_.traceId,{companyId:a});g&&(i(N),d("found"))}).catch(()=>{g&&d("error")}),()=>{g=!1}},[t,a,s]),l==="loading")return e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground py-1",children:[e.jsx(le,{className:"w-3 h-3 animate-spin"})," Carregando como a IA pensouâ¦"]});if(l!=="found"||!r)return null;const m=r.flow==="coleta_cotacao",x=!m&&r.prompt_available===!1,f="Turno anterior ao lançamento do Fluxo de Pensamento (24/07) â não capturamos o prompt/contexto exato usado.";return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(qa,{icon:ci,label:"Como a IA pensou nesse turno",children:[e.jsxs("div",{className:"mt-1 grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:[e.jsx(kr,{title:"Workflow",subtitle:m?"Coleta determinÃstica":x?"Turno histórico":r.workflow?`${r.workflow.name} · ${r.workflow.stage||"sem etapa"}`:"Sem workflow ativo",text:m?"Decisão por regra (collection_spec) â não passa pelo LLM.":x?f:(p=r.workflow)==null?void 0:p.stage_instructions_excerpt}),e.jsx(kr,{title:"Playbook",subtitle:x?"Turno histórico":r.playbook_name,text:x?f:r.tone_guidance_excerpt}),e.jsx(kr,{title:"Contexto da conversa",text:x?f:r.flow_guidance}),e.jsx(kr,{title:"Prompt final",text:m?"Sem prompt â decisão por regra, não usa LLM.":x?f:"Clique pra ver o prompt completo (system + user).",onExpand:!m&&!x?()=>u(!0):void 0})]}),c&&e.jsxs("div",{className:"mt-2 rounded-lg border bg-muted/30 p-2",children:[e.jsx("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-words text-[10px] leading-relaxed text-foreground
160/80",children:`ââ SYSTEM ââ 161 162${r.system_prompt||""} 163 164ââ USER ââ 165 166${r.user_content||""}`}),e.jsx("button",{onClick:()=>u(!1),className:"mt-1 text-[10px] font-medium text-muted-foreground hover:text-foreground",children:"Fechar"})]}),e.jsxs("p",{className:"mt-1.5 text-[10px] text-muted-foreground/70",children:["Custo: ",r.cost_usd!=null?`US$ ${r.cost_usd.toFixed(4)}`:"â"," · modelo ",r.model||"â"]})]}),e.jsx(Rg,{detail:r})]})}function Fg({d:t,leadId:a,companyId:s}){const r=mn[t.kind]||mn.respond,i=r.icon,l=(t.tool_calls||[]).filter(d=>d&&d.name);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:Ce("inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold ring-1",r.cls),children:[e.jsx(i,{className:"w-3.5 h-3.5"})," ",r.label]}),t.mode&&e.jsx("span",{className:"rounded-full bg-muted px-2.5 py-1 text-[11px] font-medium text-muted-foreground",children:fg[t.mode]||t.mode}),t.sale_step&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-muted px-2.5 py-1 text-[11px] font-medium text-muted-foreground",children:[e.jsx(Od,{className:"w-3 h-3"})," ",Ku(t.sale_step)]}),e.jsx("span",{className:"ml-auto text-[11px] text-muted-foreground",children:Fi(t.created_at)})]}),t.trigger_message&&e.jsxs("div",{className:"rounded-lg border-l-2 border-muted-foreground/30 bg-muted/30 py-2 pl-3 pr-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold mb-0.5",children:"Cliente disse"}),e.jsxs("p",{className:"text-xs text-foreground/80 italic leading-snug break-words",children:["â",t.trigger_message,"â"]})]}),t.summary&&e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold mb-1",children:"O que o agente fez"}),e.jsx("p",{className:"text-sm text-foreground leading-snug whitespace-pre-wrap break-words",children:t.summary})]}),e.jsxs("div",{className:"space-y-3",children:[t.rule&&e.jsx(qa,{icon:Es,label:"Por quê",children:t.rule}),t.collect_detail&&e.jsx(qa,{icon:zn,label:"O que entendi da mensagem",children:e.jsxs("div",{className:"space-y-1 mt-0.5",children:[e.jsxs("div",{children:["Esperava: ",e.jsx("span",{className:"font-medium",children:Hc(t.collect_detail.expected_field)}),t.collect_detail.is_retry&&e.jsx("span",{className:"ml-1.5 rounded bg-warning/10 text-warning-text px-1.5 py-0.5 text-[10px] font-medium",children:"re-pergunta"})]}),Object.keys(t.collect_detail.understood||{}).length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Object.entries(t.collect_detail.understood||{}).map(([d,c])=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-[11px]",children:[Hc(d),": ",e.jsx("span",{className:"font-medium text-foreground/80",children:String(c)})]},d))}):e.jsxs("div",{className:"text-muted-foreground",children:["Nada identificado nesta resposta",t.collect_detail.is_retry?", por isso re-perguntei":"","."]})]})}),Array.isArray(t.tool_detail)?t.tool_detail.length>0?e.jsx(qa,{icon:Ua,label:"Ferramentas (o que chamou e o que voltou)",children:e.jsx("div",{className:"space-y-1.5 mt-1",children:t.tool_detail.map((d,c)=>e.jsx($g,{t:d},c))})}):e.jsx(qa,{icon:Ua,label:"Ferramentas",children:e.jsx("span",{className:"text-muted-foreground",children:"Nenhuma ferramenta usada neste turno (resposta direta)."})}):l.length>0&&e.jsx(qa,{icon:Ua,label:"Ferramentas usadas",children:e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-0.5",children:l.map((d,c)=>e.jsxs("span",{className:Ce("inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px]",d.ok===!1?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground"),children:[d.ok===!1?e.jsx(wi,{className:"w-3 h-3"}):e.jsx(ki,{className:"w-3 h-3"}),d.name,d.deferred?" · adiada":""]},c))})})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsx(Og,{leadId:a,companyId:s,decisionCreatedAt:t.created_at})})]})}function zg({d:t}){const a=mn[t.kind]||mn.respond,s=a.icon,r=Array.isArray(t.tool_detail)?t.tool_detail:[],i=r.length?r.map(c=>({name:c.tool_name,insurers:c.seguradoras_cotadas||[]})):(t.tool_calls||[]).map(c=>({name:c.name,insurers:[]})),l=new Set,d=i.reduce((c,u)=>{const m=jg(u.name);let x=m.label;return/cotei/i.test(x)&&u.insurers.length&&(x=`Cotei em ${u.insurers.length} seguradora${u.insurers.length>
1661?"s":""}: ${u.insurers.slice(0,4).join(", ")}${u.insurers.length>4?"â¦":""}`),l.has(x)||(l.add(x),c.push({label:x,icon:m.icon})),c},[]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:Ce("inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold ring-1",a.cls),children:[e.jsx(s,{className:"w-3.5 h-3.5"})," ",a.label]}),t.sale_step&&e.jsx("span",{className:"rounded-full bg-muted px-2.5 py-1 text-[11px] font-medium text-muted-foreground",children:Ku(t.sale_step)}),e.jsx("span",{className:"ml-auto text-[11px] text-muted-foreground",children:Fi(t.created_at)})]}),t.summary&&e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold mb-1",children:"O que o assistente fez"}),e.jsx("p",{className:"text-sm text-foreground leading-snug whitespace-pre-wrap break-words",children:t.summary})]}),d.length>0&&e.jsx("div",{className:"space-y-1.5",children:d.map((c,u)=>{const m=c.icon;return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-foreground/90",children:[e.jsx("span",{className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary",children:e.jsx(m,{className:"w-3.5 h-3.5"})}),c.label]},u)})}),t.kind==="collect"&&t.rule&&e.jsx(qa,{icon:Es,label:"Por quê",children:e.jsx("span",{className:"text-foreground/80",children:t.rule})}),t.trigger_message&&e.jsx(qa,{icon:fa,label:"O cliente disse",children:e.jsxs("span",{className:"italic",children:["â",t.trigger_message,"â"]})})]})}function qg({pendingDraft:t,isCotacao:a,onResolved:s,tookOver:r,onTakeover:i,onReturnToAgent:l}){const{toast:d}=At(),[c,u]=n.useState(null),m=async(p,g,y)=>{u(p);try{await g(),d({title:y}),s==null||s()}catch(k){d({title:"Erro",description:He(k),variant:"destructive"})}finally{u(null)}},x=Pi(t),f=!!i||!!l;return!t&&!f?null:e.jsxs("div",{className:"border-t bg-background px-4 py-3 space-y-2",children:[t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-[11px] font-medium text-warning flex items-center gap-1.5",children:[e.jsx(ci,{className:"w-3.5 h-3.5"})," O assistente preparou uma resposta pra este cliente"]}),x!==null&&e.jsxs("div",{className:"text-[10px] text-warning-foreground bg-warning/10 border border-warning/40 rounded-md px-2 py-1.5 leading-snug",children:[e.jsxs("strong",{children:["O cliente não fala há ",x,"h."]})," Fora das 24h a Meta só entrega template aprovado (e cobra); texto livre ela costuma recusar (131047). Dá pra enviar mesmo assim â se recusar, o rascunho volta pra fila."]}),e.jsxs("div",{className:"flex gap-2",children:[a?e.jsxs("div",{className:"flex-1 rounded-md bg-muted/60 px-2.5 py-2 text-[11px] text-muted-foreground flex items-center gap-1.5",children:[e.jsx(ot,{className:"w-3.5 h-3.5 shrink-0"})," Revise e envie a cotação pelo botão de cotação no chat."]}):e.jsxs(Pe,{size:"sm",className:"flex-1 gap-1.5",disabled:!!c,onClick:()=>m("approve",()=>ti(t.id,!1,void 0,x!==null),"Enviado!"),children:[c==="approve"?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(xa,{className:"w-4 h-4"}),x!==null?"Enviar mesmo assim":"Aprovar e enviar"]}),e.jsxs(Pe,{size:"sm",variant:"outline",className:"gap-1.5",disabled:!!c,onClick:()=>m("discard",()=>Lr(t.id,"descartado pelo vendedor"),"Descartado"),children:[c==="discard"?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(ds,{className:"w-4 h-4"}),"Descartar"]})]}),!a&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Pra editar o texto antes de enviar, use a caixa de resposta no chat."})]}),f&&(r?e.jsxs(Pe,{size:"sm",variant:"outline",className:"w-full gap-1.5",disabled:!!c,onClick:()=>m("return",async()=>l==null?void 0:l(),"Conversa devolvida ao assistente"),children:[c==="return"?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(xx,{className:"w-4 h-4"}),"Devolver ao assistente"]}):e.jsxs(Pe,{size:"sm",variant:"outline",className:"w-full gap-1.5",disabled:!!c,onClick:()=>m("takeover",async()=>i==null?void 0:i(),"Você assumiu a conversa"),children:[c==="takeover"?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(tn,{className:"w-4 h-4"}),"Assumir a conversa"]}))]})}function Bg({leadId:t,companyId:a=null,open:s,onOpenChange:r,focusId:i,pendingDraft:l=null,draftIsCotacao:d=!1,onDraftResolved:c,tookOver:u=!1,onTakeover:m,onReturnToAgent:x}){const{user:f}=Sa(),p=(f==null?void 0:f.role)==="admin"||(f==null?void 0:f.role)==="manager"||(f==null?void 0:f.role)==="super_admin",[g,y]=n.useState([]),[k,_]=n.useState(!1),[N,I]=n.useState(null),[P,D]=n.useState(null),[V,R]=n.useState(!1);n.useEffect(()=>{if(!s||!t)return;let b=!0;return _(!0),I(null),Er(t).then(v=>{b&&y(v)}).catch(()=>{b&&I("Não consegui carregar as decisões.")}).finally(()=>{b&&_(!1)}),()=>{b=!1}},[s,t]),n.useEffect(()=>{s&&D(i??null)},[s,i]);const M=P&&g.find(b=>b.id===P)||null,$=g.filter(b=>b.kind==="followup").length,C=V?g.filter(b=>b.kind!=="followup"):g;return e.jsx(mu,{open:s,onOpenChange:r,children:e.jsxs(Di,{side:"right",className:"w-full sm:max-w-md p-0 flex flex-col",children:[e.jsx(xu,{className:"px-5 py-4 border-b",children:e.jsx($i,{className:"flex items-center gap-2 text-base",children:M?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>D(null),className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(un,{className:"w-4 h-4"})," Decisões"]}),e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx("span",{children:"Detalhe"})]}):e.jsxs(e.Fragment,{children:[e.jsx(eu,{className:"w-4 h-4 text-primary"})," ",p?"Decisões do agente":"O que o assistente fez"]})})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:k?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-8 justify-center",children:[e.jsx(le,{className:"w-4 h-4 animate-spin"})," Carregandoâ¦"]}):N?e.jsx("p",{className:"text-sm text-destructive py-8 text-center",children:N}):g.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"Nenhuma decisão do agente registrada ainda para este lead."}):M?e.jsxs("div",{className:"space-y-5",children:[p?e.jsx(Fg,{d:M,leadId:t,companyId:a}):e.jsx(zg,{d:M}),e.jsxs("button",{onClick:()=>D(null),className:"w-full inline-flex items-center justify-center gap-1.5 rounded-lg border border-border bg-card py-2 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors",children:[e.jsx(Qx,{
166className:"w-3.5 h-3.5"})," Ver histórico completo (",g.length,")"]})]}):e.jsxs(e.Fragment,{children:[$>0&&e.jsxs("button",{onClick:()=>R(b=>!b),className:"mb-3 inline-flex items-center gap-1.5 rounded-full border border-border px-2.5 py-1 text-[11px] font-medium text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors",children:[e.jsx(_t,{className:"w-3 h-3"}),V?`Mostrar follow-up (${$})`:`Esconder follow-up (${$})`]}),e.jsx("ol",{className:"space-y-2.5",children:C.map(b=>{const v=mn[b.kind]||mn.respond,F=v.icon;return e.jsx("li",{children:e.jsxs("button",{onClick:()=>D(b.id),className:Ce("w-full text-left rounded-xl border bg-card p-3 transition-colors hover:bg-muted/40",i===b.id?"border-primary/60":"border-border"),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:Ce("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-semibold ring-1",v.cls),children:[e.jsx(F,{className:"w-3 h-3"})," ",v.label]}),b.mode==="draft"&&e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground",children:"rascunho"}),e.jsx("span",{className:"ml-auto text-[10px] text-muted-foreground",children:Fi(b.created_at)})]}),b.summary&&e.jsx("p",{className:"text-xs text-foreground/90 leading-snug line-clamp-2",children:b.summary})]})},b.id)})}),V&&C.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"Só há follow-up automático neste lead. Nenhuma outra decisão registrada."})]})}),e.jsx(qg,{pendingDraft:l,isCotacao:d,onResolved:c,tookOver:u,onTakeover:m,onReturnToAgent:x})]})})}function Ug(){const[t,a]=n.useState(!1),s=n.useRef(null),r=n.useRef([]),i=n.useRef(null),l=n.useRef(null),d=n.useRef(null),c=()=>{d.current=null;const p=l.current;l.current=null,p&&p.close().catch(()=>{})},u=n.useCallback(async()=>{const p=await navigator.mediaDevices.getUserMedia({audio:!0}),g=new MediaRecorder(p,{mimeType:"audio/webm"});r.current=[],g.ondataavailable=y=>{y.data.size>0&&r.current.push(y.data)},g.onstop=()=>{var k;const y=new Blob(r.current,{type:"audio/webm"});p.getTracks().forEach(_=>_.stop()),c(),(k=i.current)==null||k.call(i,y.size>0?y:null),i.current=null},s.current=g;try{const y=window.AudioContext||window.webkitAudioContext,k=new y,_=k.createAnalyser();_.fftSize=128,_.smoothingTimeConstant=.7,k.createMediaStreamSource(p).connect(_),l.current=k,d.current=_}catch{}g.start(),a(!0)},[]),m=n.useCallback(()=>new Promise(p=>{const g=s.current;if(!g||g.state==="inactive"){c(),a(!1),p(null);return}i.current=p,g.stop(),a(!1)}),[]),x=n.useCallback(()=>{const p=s.current;i.current=null,p&&p.state!=="inactive"&&p.stop(),c(),a(!1)},[]),f=n.useCallback(p=>{const g=d.current;if(!g)return[];const y=new Uint8Array(g.frequencyBinCount);g.getByteFrequencyData(y);const k=Math.max(1,Math.floor(y.length/p)),_=[];for(let N=0;N<p;N+=1){let I=0;for(let P=0;P<k;P+=1)I+=y[N*k+P]||0;_.push(Math.min(1,I/k/170))}return _},[]);return{recording:t,start:u,stop:m,cancel:x,sampleLevels:f}}const Hg={moto:{kind:"moto",label:"ð Moto",className:"bg-warning/10 text-warning-text"},auto:{kind:"auto",label:"ð Auto",className:"bg-primary/10 text-primary-text"}};function Wc(t,a){const s=String(t||"").toLowerCase().trim();if(!s)return null;const r=Hg[s];if(!r){const i=s.charAt(0).toUpperCase()+s.slice(1);return{kind:s,label:i,className:"bg-muted text-muted-foreground",tooltip:a?`Campanha: ${a}`:`Canal: ${i}`}}return{...r,tooltip:a?`Campanha: ${a}`:`Canal de ${r.kind}`}}const Vg={duvidas_iniciais:{label:"Dúvidas",className:"bg-ink/10 text-muted-foreground"},coleta_dados_cotacao:{label:"Coleta",className:"bg-primary/10 text-primary-text"},cotacao:{label:"Cotando",className:"bg-primary/10 text-primary-text"},apresentacao_proposta:{label:"Proposta",className:"bg-primary/10 text-primary-text"},coleta_documentos:{label:"Documentos",className:"bg-warning/10 text-warning-text"},efetivacao:{label:"Efetivação",className:"bg-success/10 text-success-text"},aguardando_pagamento:{label:"Pagamento",className:"bg-warning/10 text-warning-text"},pos_venda:{label:"Pós-venda",className:"bg-success/10 text-success-text"}};function Wg(t,a){return a&&!["venda_seguro","vendas"].includes(a)||!t?null:Vg[t]??null}function Gg(t){const a=t.mime||"",s=t.filename||"",r=a.includes("pdf")||!!t.filename&&/\.pdf$/i.test(s),i=a.startsWith("image/")||!!t.filename&&/\.(png|jpe?g|webp|gif)$/i.test(s);return{isPdf:r,isImg:i,previewable:r||i}}function Kg({className:t}
166){return e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:t,"aria-hidden":"true",children:e.jsx("path",{d:"M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"})})}const Qg=6e4;function Gc(t){return(t||"").toLowerCase().normalize("NFD").replace(/[Ì-ͯ]/g,"")}const Jg=48*60*60*1e3,Kc={meta:["meta_ads","instagram","facebook"],qr:["qr"],organic:["organic"]},Qc=[{id:"all",label:"Todas as origens",short:"Origem"},{id:"meta",label:"Meta Ads",short:"Meta Ads"},{id:"qr",label:"QR Code",short:"QR Code"},{id:"organic",label:"Orgânico",short:"Orgânico"},{id:"outras",label:"Outras origens",short:"Outras"}],Jc=[{id:"all",label:"Todos",short:"Follow-up"},{id:"pendente",label:"Com follow-up pendente",short:"Follow-up pendente"},{id:"sem_fup",label:"Esconder follow-up sem resposta",short:"Sem follow-up"},{id:"esgotada",label:"Régua esgotada / inativo",short:"Régua esgotada"}],Oo=[{id:"all",label:"Qualquer perÃodo",short:"PerÃodo",horas:0},{id:"12h",label:"Ãltimas 12 horas",short:"12h",horas:12},{id:"24h",label:"Ãltimas 24 horas",short:"24h",horas:24},{id:"7d",label:"Ãltimos 7 dias",short:"7 dias",horas:24*7}];function Cr(t){return t?!!(t.docId||t.msgId||t.sellerId&&t.mediaId):!1}function eo({docId:t,msgId:a,sellerId:s,mediaId:r,leadId:i}
166){return t?Pp(t):a&&i?Mp(i,a):s&&r?Tp(s,r):Promise.resolve(null)}function Xg({sellerId:t,mediaId:a,docId:s,msgId:r,leadId:i,onZoom:l}){const[d,c]=n.useState(null),[u,m]=n.useState(!1);return n.useEffect(()=>{let x=!0,f=null;return eo({docId:s,msgId:r,sellerId:t,mediaId:a,leadId:i}).then(g=>{x&&g?(f=g,c(g)):x&&m(!0)}).catch(()=>x&&m(!0)),()=>{x=!1,f&&URL.revokeObjectURL(f)}},[t,a,s]),u?e.jsxs("div",{className:"text-[11px] opacity-70 flex items-center gap-1",children:[e.jsx(lu,{className:"w-3 h-3"})," Imagem (não consegui carregar)"]}):d?e.jsx("img",{src:d,alt:"Imagem recebida",onClick:()=>l==null?void 0:l(d),className:"rounded-lg max-w-full max-h-72 object-contain cursor-zoom-in",title:"Clique pra ampliar"}):e.jsxs("div",{className:"flex items-center gap-1 text-[11px] opacity-70",children:[e.jsx(le,{className:"w-3 h-3 animate-spin"})," carregando imagemâ¦"]})}function Zg({sellerId:t,mediaId:a,msgId:s,leadId:r}){const[i,l]=n.useState(null),[d,c]=n.useState(!1);return n.useEffect(()=>{let u=!0,m=null;return eo({msgId:s,sellerId:t,mediaId:a,leadId:r}).then(x=>{u&&x?(m=x,l(x)):u&&c(!0)}).catch(()=>u&&c(!0)),()=>{u=!1,m&&URL.revokeObjectURL(m)}},[t,a,s,r]),d?e.jsx("div",{className:"text-[11px] opacity-70",children:"VÃdeo (não consegui carregar)"}):i?e.jsx("video",{src:i,controls:!0,className:"rounded-lg max-w-full max-h-72"}):e.jsxs("div",{className:"flex items-center gap-1 text-[11px] opacity-70",children:[e.jsx(le,{className:"w-3 h-3 animate-spin"})," carregando vÃdeoâ¦"]})}function Xc(t){if(!Number.isFinite(t)||t<0)return"0:00";const a=Math.floor(t/60),s=Math.floor(t%60);return`${a}:${String(s).padStart(2,"0")}`}function Yg({sellerId:t,mediaId:a,docId:s,msgId:r,link:i,leadId:l}){const[d,c]=n.useState(null),[u,m]=n.useState(!1),[x,f]=n.useState(!1),[p,g]=n.useState(0),[y,k]=n.useState(0),_=n.useRef(null);n.useEffect(()=>{let D=!0,V=null;return(i&&l?Id(l,i):eo({docId:s,msgId:r,sellerId:t,mediaId:a,leadId:l})).then(M=>{D&&M?(V=M,c(M)):D&&m(!0)}).catch(()=>D&&m(!0)),()=>{D=!1,V&&URL.revokeObjectURL(V)}},[t,a,s,r,i,l]);const N=n.useCallback(()=>{const D=_.current;D&&(D.paused?(D.play(),f(!0)):(D.pause(),f(!1)))},[]),I=n.useCallback(D=>{const V=_.current;if(!V||!y)return;const R=D.currentTarget.getBoundingClientRect(),M=Math.min(1,Math.max(0,(D.clientX-R.left)/R.width));V.currentTime=M*y,g(V.currentTime)},[y]);if(u)return e.jsx("div",{className:"text-[11px] opacity-70",children:"Ãudio (não consegui carregar)"});if(!d)return e.jsxs("div",{className:"flex items-center gap-1 text-[11px] opacity-70",children:[e.jsx(le,{className:"w-3 h-3 animate-spin"})," carregando áudioâ¦"]});const P=y>0?p/y*100:0;return e.jsxs("div",{className:"flex items-center gap-2.5 min-w-[190px] max-w-[240px] py-0.5",children:[e.jsx("button",{onClick:N,className:"flex-shrink-0 w-9 h-9 rounded-full flex items-center justify-center opacity-90 hover:opacity-100 transition-opacity",style:{border:"1.5px solid currentColor"},title:x?"Pausar":"Reproduzir",children:x?e.jsx(nu,{className:"w-4 h-4"}):e.jsx(Si,{className:"w-4 h-4 ml-0.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{onClick:I,className:"relative h-1.5 rounded-full overflow-hidden cursor-pointer",children:[e.jsx("div",{className:"absolute inset-0 rounded-full",style:{backgroundColor:"currentColor",opacity:.2}}),e.jsx("div",{className:"absolute inset-y-0 left-0 rounded-full",style:{backgroundColor:"currentColor",opacity:.7,width:`${P}%`}})]}),e.jsxs("div",{className:"flex justify-between mt-1 text-[10px] tabular-nums opacity-70",children:[e.jsx("span",{children:Xc(p)}),e.jsx("span",{children:Xc(y)})]})]}),e.jsx("audio",{ref:_,src:d,preload:"metadata",className:"hidden",onLoadedMetadata:D=>k(D.currentTarget.duration),onTimeUpdate:D=>g(D.currentTarget.currentTime),onEnded:()=>{f(!1),g(0)},onPause:()=>f(!1),onPlay:()=>f(!0)})]})}function eb({media:t,leadId:a}){const{toast:s}=At(),[r,i]=n.useState(null),[l,d]=n.useState(!1),[c,u]=n.useState(!1),[m,x]=n.useState(!1),f=t.filename||"documento",{isPdf:p,previewable:g}=Gg(t),y=n.useRef(null);n.useEffect(()=>()=>{r&&URL.revokeObjectURL(r)},[r]);const k=n.useCallback(async I=>{if(r)return r;d(!0);let P=null;try{P=t.link?await Id(a,t.link):await eo({docId:t.docId,msgId:t.msgId,sellerId:t.sellerId,mediaId:t.mediaId,leadId:a})}catch{P=null}return d(!1),P?i(P):(u(!0),I!=null&&I.silent||s({title:"Não consegui abrir o documento",description:"Sua sessão pode ter expirado. Faça login de novo e tente de novo.",variant:"destructive"})),P},[r,t,a,s]);n.useEffect(()=>{if(!g)return;const I=y.current;if(!I||typeof IntersectionObserver>"u"){k({silent:!0});return}const P=new IntersectionObserver(D=>{D.some(V=>V.isIntersecting)&&(k({silent:!0}),P.disconnect())},{rootMargin:"200px"});return P.observe(I),()=>P.disconnect()},[g]);const _=async()=>{const I=await k();if(!I)return;const P=document.createElement("a");P.href=I,P.download=f,P.click()},N=!!r&&g;return e.jsxs("div",{ref:y,children:[N?e.jsxs("div",{className:"rounded-lg border overflow-hidden bg-background/70 max-w-[260px]",children:[e.jsxs("button",{type:"button",onClick:()=>x(!0),className:"relative block w-full h-40 bg-white overflow-hidden group",title:"Abrir documento",children:[p?e.jsx("iframe",{src:`${r}#toolbar=0&navpanes=0&view=FitH`,title:f,className:"w-full h-[220px] pointer-events-none -mt-1"}):e.jsx("img",{src:r,alt:f,className:"w-full h-full object-cover"}),e.jsx("span",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/5 transition-colors"})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-t",children:[e.jsx(ot,{className:"w-4 h-4 text-primary shrink-0"}),e.jsx("span",{className:"text-[11px] font-medium truncate flex-1 text-foreground",children:f}),e.jsx("button",{onClick:_,className:"text-[11px] text-primary hover:underline shrink-0",children:"Baixar"})]})]}):e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border bg-background/70 px-3 py-2 max-w-[260px]",children:[e.jsx(ot,{className:"w-5 h-5 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-medium truncate text-foreground",children:f}),e.jsxs("div",{className:"flex gap-3 mt-0.5",children:[e.jsx("button",{onClick:async()=>{await k()&&x(!0)},disabled:l,className:"text-[11px] text-primary hover:underline",children:l?"â¦":c?"Tentar de novo":"Ver"}),e.jsx("button",{onClick:_,disabled:l,className:"text-[11px] text-primary hover:underline",children:"Baixar"})]})]})]}),m&&r&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4",onClick:()=>x(!1),children:e.jsxs("div",{className:"bg-background rounded-xl shadow-2xl w-full max-w-4xl h-[88vh] flex flex-col overflow-hidden",onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b",children:[e.jsx("span",{className:"text-xs font-semibold truncate",children:f}),e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:"Abrir em nova aba"}),e.jsxs("button",{onClick:_,className:"text-xs text-primary hover:underline flex items-center gap-1",children:[e.jsx(On,{className:"w-3.5 h-3.5"})," Baixar"]}),e.jsx("button",{onClick:()=>x(!1),children:e.jsx(vt,{className:"w-5 h-5 text-muted-foreground"})})]})]}),p?e.jsx("iframe",{src:r,title:f,className:"flex-1 w-full bg-white"}):e.jsx("img",{src:r,alt:f,className:"flex-1 w-full object-contain bg-black/5"})]})})]})}function Zc(t){if(!t)return"";const a=new Date(t);return Number.isNaN(a.getTime())?"":a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:cn()})}const tb=/^([0-9A-Z])\1+$|^[O0]{5,7}$/i;function ab(t,a){return t==="placa"&&a&&tb.test(a)?"0km (sem placa)":a}const sb={quote:"Cotação",negotiation:"Negociação",collect:"Coleta",handoff:"Transferência",escalate:"Transferência",followup:"Follow-up",objection:"Ob
166jeção",action:"Ação",takeover:"Humano assumiu",respond:"Resposta"};function nb(t){return sb[t.kind]||"Decisão"}const rb={"primeiro-atendimento":"Primeiro atendimento","captura-de-dados":"Captura de dados",apresentacao_proposta:"Proposta apresentada",negociacao:"Negociação",fechado:"Fechado",perdido:"Perdido",ativacao:"Ativação"};function ob(t){return t?rb[t]||t.replace(/[-_]/g," "):"-"}function Yc(t){if(!t)return null;const a=new Date(t);return Number.isNaN(a.getTime())?null:`${a.getFullYear()}-${a.getMonth()}-${a.getDate()}`}function ib(t){if(!t)return"";const a=new Date(t);if(Number.isNaN(a.getTime()))return"";const s=i=>new Date(i.getFullYear(),i.getMonth(),i.getDate()).getTime(),r=Math.round((s(new Date)-s(a))/864e5);return r<=0?"Hoje":r===1?"Ontem":r<7?a.toLocaleDateString("pt-BR",{weekday:"long"}):a.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})}function lb(t){const a=[];for(const s of t){const r=a[a.length-1];r&&r.day===s.day?r.nodes.push(s.node):a.push({day:s.day,nodes:[s.node]})}return a}function cb(t){if(!t)return"";const a=Date.now()-new Date(t).getTime();if(Number.isNaN(a))return"";const s=Math.floor(a/6e4);if(s<1)return"agora";if(s<60)return`há ${s}min`;const r=Math.floor(s/60);return r<24?`há ${r}h`:`há ${Math.floor(r/24)}d`}const ed=["bg-chart-1/15 text-chart-1","bg-chart-2/15 text-chart-2","bg-c
166hart-3/15 text-chart-3","bg-chart-4/15 text-chart-4","bg-chart-5/15 text-chart-5","bg-chart-6/15 text-chart-6","bg-chart-7/15 text-chart-7","bg-chart-8/15 text-chart-8"];function td(t){const a=t.trim().split(/\s+/).filter(Boolean);return a.length===0?"":a.length===1?a[0].slice(0,2).toUpperCase():(a[0][0]+a[a.length-1][0]).toUpperCase()}function ad(t){let a=0;for(let s=0;s<t.length;s++)a=a*31+t.charCodeAt(s)>>>0;return ed[a%ed.length]}function Fo(t){return/[a-zA-ZÃ-ÿ]/.test(t)&&t.trim().toLowerCase()!=="lead"}const db=Mn.memo(function({sampleLevels:a,sendingAudio:s,onCancel:r,onSend:i}){const[l,d]=n.useState(0),[c,u]=n.useState([]);n.useEffect(()=>{const x=setInterval(()=>d(g=>g+1),1e3);let f=0;const p=()=>{u(a(28)),f=requestAnimationFrame(p)};return f=requestAnimationFrame(p),()=>{clearInterval(x),cancelAnimationFrame(f)}},[a]);const m=x=>`${Math.floor(x/60)}:${String(x%60).padStart(2,"0")}`;return e.jsxs("div",{className:"flex-1 flex items-center gap-3",children:[e.jsx("button",{onClick:r,disabled:s,title:"Cancelar gravação",className:"h-9 w-9 flex items-center justify-center rounded-full text-destructive hover:bg-destructive/10 disabled:opacity-50",children:e.jsx(ds,{className:"w-5 h-5"})}),e.jsxs("span",{className:"flex items-center gap-2 text-sm text-foreground tabular-nums",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-destructive animate-pulse"}),m(l)]}),e.jsx("div",{className:"flex-1 flex items-center gap-0.5 h-6 overflow-hidden","aria-hidden":"true",children:Array.from({length:28}).map((x,f)=>e.jsx("span",{className:"w-0.5 rounded bg-success transition-[height] duration-75",style:{height:`${Math.max(8,(c[f]??0)*100)}%`}},f))}),e.jsx("button",{onClick:i,disabled:s,title:"Enviar áudio",className:"h-10 w-10 flex items-center justify-center rounded-full bg-success text-success-foreground hover:bg-success/90 disabled:opacity-50",children:s?e.jsx(le,{className:"w-5 h-5 animate-spin"}):e.jsx(xa,{className:"w-5 h-5"})})]})});function ub({drafts:t,refresh:a,refreshLeads:s,onExit:r,renderAnalysis:i,leads:l=[],onCotacaoReady:d,onOpenNav:c,openRequest:u}){var _l,Al,El,Dl,$l,Pl,Ml,Tl,Il,Ll,Rl,Ol,Fl;const m=Wr(),{user:x}=Sa(),{query:f}=Gn(m||void 0),p=Kr((_l=f.data)==null?void 0:_l.capabilities),g=Mi((Al=f.data)==null?void 0:Al.capabilities),y=Om(x==null?void 0:x.role),[k,_]=n.useState(!1),[N,I]=n.useState(!1),[P,D]=n.useState(!1),[V,R]=n.useState(""),[M,$]=n.useState(!1),C=Tr(o=>{var h;return((h=o.companies.find(E=>E.id===m))==null?void 0:h.name)||null}),{layout:b}=Rn(),{toast:v}=At(),F=wd(),[U,te]=Fm(),[q,Z]=n.useState(()=>typeof window>"u"||window.innerWidth>=768),ae=og(n.useCallback(()=>Z(!0),[])),ce=ae.documento!==null,[se,Q]=n.useState(()=>typeof window<"u"&&window.innerWidth<768);n.useEffect(()=>{const o=window.matchMedia("(max-width: 767px)"),h=()=>Q(o.matches);return h(),o.addEventListener("change",h),()=>o.removeEventListener("change",h)},[]);const K=n.useRef(null),G=n.useCallback(o=>{K.current=o,o&&ae.host.parentNode!==o&&o.appendChild(ae.host)},[ae.host]);n.useEffect(()=>{if(ce)return;const o=K.current;o&&ae.host.parentNode!==o&&o.appendChild(ae.host)},[ce,ae.host]);const[L,S]=n.useState([]),[B,H]=n.useState("active"),[W,X]=n.useState(""),[oe,O]=n.useState("all"),[be,fe]=n.useState("all"),[pe,Me]=n.useState("all"),[je,Oe]=n.useState("all"),[Ee,ye]=n.useState(new Set),[Le,Ne]=n.useState(!1),[Se,ke]=n.useState(!1),ht=[oe!=="all",be!=="all",pe!=="all",je!=="all",Ee.size>0,Le].filter(Boolean).length,[yt,Ye]=n.useState(new Map),[Nt,Zt]=n.useState(!1);n.useEffect(()=>{const o=W.trim();if(!m||o.length<2){Ye(new Map),Zt(!1);return}let h=!1;Zt(!0);const E=setTimeout(()=>{jp(m,o).then(ee=>{h||Ye(new Map(ee.map(ie=>[ie.leadId,ie.matchedMessage])))}).catch(()=>{h||Ye(new Map)}).finally(()=>{h||Zt(!1)})},350);return()=>{h=!0,clearTimeout(E)}},[W,m]);const Et=n.useMemo(()=>{const o=new Map;for(const h of l)o.set(h.id,h.status);return o},[l]),ha=n.useMemo(()=>{const o=new Map;for(const h of l)o.set(h.id,h.closingScore);return o},[l]),ga=n.useMemo(()=>{const o=new Map;for(const h of l)o.set(h.id,Ei(h.source,h.referral,h.adPlatform));return o},[l]),it=n.useMemo(()=>{const o=new Map;for(const h of l){const E=Wc(h.channelProduto,h.channelLabel);E&&o.set(h.id,E)}return o},[l]),ut=n.useMemo(()=>{const o=new Map;let h=0;for(const ee of l){const ie=Wc(ee.channelProduto,ee.channelLabel);ie?o.set(ie.label,(o.get(ie.label)||0)+1):h+=1}
166const E=[...o.entries()].sort((ee,ie)=>ie[1]-ee[1]).map(([ee,ie])=>({id:ee,label:ee,n:ie}));return h>0&&E.push({id:"principal",label:"Número principal",n:h}),E},[l]),Yt=n.useMemo(()=>{const o=new Map;for(const h of l)o.set(h.id,Wg(h.saleStep,h.agentFlow));return o},[l]),[ba,va]=n.useState(new Map);n.useEffect(()=>{va(o=>{if(o.size===0)return o;const h=new Map(o);for(const E of l)h.has(E.id)&&h.get(E.id)===!!E.funnelArchivedAt&&h.delete(E.id);return h.size===o.size?o:h})},[l]);const wt=n.useMemo(()=>{const o=new Set;for(const h of l)h.funnelArchivedAt&&o.add(h.id);for(const[h,E]of ba)E?o.add(h):o.delete(h);return o},[l,ba]),[zt,ea]=n.useState(new Map);n.useEffect(()=>{ea(o=>{if(o.size===0)return o;const h=new Map(o);for(const E of l)h.has(E.id)&&h.get(E.id)===!!E.favoritedAt&&h.delete(E.id);return h.size===o.size?o:h})},[l]);const J=n.useMemo(()=>{const o=new Set;for(const h of l)h.favoritedAt&&o.add(h.id);for(const[h,E]of zt)E?o.add(h):o.delete(h);return o},[l,zt]),he=n.useCallback(async(o,h)=>{ea(E=>new Map(E).set(o,!h));try{await vi(o,m)}catch(E){console.error("[AgentConversations] toggleFavorite:",E),v({title:"Falha ao favoritar",description:E instanceof Error?E.message:"",variant:"destructive"}),ea(ee=>new Map(ee).set(o,h))}},[v]),[Fe,Ke]=n.useState([]),[lt,ze]=n.useState(new Map),et=Ee.size===0,ta=n.useCallback(o=>et||Ee.has(o),[et,Ee]),qt=n.useCallback(o=>{ye(h=>{if(h.size===0)return new Set(Fe.filter(ee=>ee.id!==o).map(ee=>ee.id));const E=new Set(h);return E.has(o)?E.delete(o):E.add(o),E.size===0||E.size===Fe.length?new Set:E})},[Fe]),[mt,Bt]=n.useState(new Set),tt=n.useMemo(()=>{const o=new Set;for(const h of l){if(!h.followUpSentAt||mt.has(h.id))continue;const E=new Date(h.followUpSentAt).getTime();(h.attendanceWaitingSince?new Date(h.attendanceWaitingSince).getTime():0)>E||o.add(h.id)}return o},[l,mt]),xs=n.useMemo(()=>{const o=new Set;for(const h of l)h.doNotContact&&o.add(h.id);return o},[l]),Ut=n.useCallback(()=>m?Ci(m).then(o=>{const h=o.stages.map($e=>({id:$e.id,nome:$e.nome,cor:$e.cor}));Ke(h);const E=new Map(h.map($e=>[$e.id,$e])),ee=new Map,ie=new Set;for(const $e of o.leads){const Ae=E.get($e.stageId);Ae&&ee.set($e.id,Ae),$e.stageSource==="inactive"&&ie.add($e.id)}ze(ee),Bt(ie)}).catch(()=>{}):(Ke([]),ze(new Map),Bt(new Set),Promise.resolve()),[m]);n.useEffect(()=>{Ut()},[Ut]),ls(Ut,qd);const pn=n.useCallback(async(o,h)=>{try{const E=await tu(o,h);await Ut(),v({title:"Etapa atualizada",description:E!=null&&E.reopened?"Lead reaberto (saiu de Fechado).":void 0})}catch(E){v({title:"Não consegui mudar a etapa",description:E instanceof Error?E.message:"",variant:"destructive"})}},[Ut,v]),Wa=["admin","manager"].includes(((x==null?void 0:x.role)||"").toLowerCase()),Ht=n.useCallback(async(o,h)=>{try{h?await fx(o):await au(o),va(E=>new Map(E).set(o,!h)),a(),await Ut(),v({title:h?"Conversa desarquivada":"Conversa arquivada"})}catch(E){v({title:h?"Não consegui desarquivar":"Não consegui arquivar",description:E instanceof Error?E.message:"",variant:"destructive"})}},[Ut,a,v]),[w,qe]=n.useState(null);n.useEffect(()=>{qe(null)},[m]);const[Vt,fs]=n.useState(0),[at,Wt]=n.useState(!1),[ne,Dt]=n.useState(!1),[Ve,gt]=n.useState(null),[Gt,Ga]=n.useState({open:!1,mode:"reply"}),[st,aa]=n.useState([]),[re,Xe]=n.useState(null),_a=(re==null?void 0:re.jornada)??null,[hs,$t]=n.useState(null),[Ka,Aa]=n.useState(""),[Ea,sa]=n.useState(null),[ja,Qa]=n.useState(!1),[xe,Te]=n.useState(null),[nt,na]=n.useState(null),[Kt,Pt]=n.useState(null),[ue,xn]=n.useState(0),[Ts,Ja]=n.useState(!1),[gs,Xa]=n.useState(!1),[bs,ya]=n.useState([]),[Da,Za]=n.useState([]),[Is,Ya]=n.useState(null),A=w?((El=l.find(o=>o.id===w.leadId))==null?void 0:El.attendanceOwner)==="humano":!1,[T,Y]=n.useState(null),we=T??A;n.useEffect(()=>{T!==null&&A===T&&Y(null)},[A,T]);const[Ze,kt]=n.useState([]),[Ls,fn]=n.useState(null),[Be,ra]=n.useState(""),[Na,Mt]=n.useState(!1),[oa,Jn]=n.useState(!1),{recording:to,start:hn,stop:Xn,cancel:vs,sampleLevels:Zn}=Ug(),[Qt,gn]=n.useState(!1),[j,z]=n.useState(null),[de,ge]=n.useState(null),[Ue,ct]=n.useState(!1),[me,bt]=n.useState(!1),[ia,Yn]=n.useState(""),[bn,er]=n.useState("outro"),Bi=n.useRef(null);n.useEffect(()=>{Y(null),ra(""),D(!1),$t(null),bt(!1),Yn(""),er("outro"),Wt(!1),Dt(!1),gt(null)},[w==null?void 0:w.leadId]),n.useEffect(()=>{Dt(!1),gt(null)},[Be]),n.useEffect(()=>{if(!w||w.name)return;const o=L.find(ie=>ie.leadId===w.leadId),h=l.find(ie=>ie.id===w.leadId),E=(o==null?void 0:o.contactPhone)||(h==null?void 0:h.contactPhone)||"",ee=(o==null?void 0:o.contactName)||(h==null?void 0:h.contactName)||E;(ee||E)&&qe({leadId:w.leadId,name:ee,phone:E})},[w,L,l]);const Ui=n.useCallback(async()=>
166{if(!w){D(!1);return}const o=V.trim();if(!o||o===w.name){D(!1);return}$(!0);try{const E=(await yp(w.leadId,o)).contactName||o;qe(ee=>ee&&{...ee,name:E}),S(ee=>ee.map(ie=>ie.leadId===w.leadId?{...ie,contactName:E}:ie)),D(!1)}catch(h){v({title:"Falha ao renomear",description:h instanceof Error?h.message:"",variant:"destructive"})}finally{$(!1)}},[w,V,v]),Hi=n.useCallback((o,h)=>{$t(o),Aa(h||""),sa(null)},[]),Vi=n.useCallback(async o=>{if(!w){$t(null);return}const h=Ka.trim();if(!h){$t(null);return}Qa(!0),sa(null);try{const E=await Xl(w.leadId,o,h);Xe(E),$t(null)}catch(E){sa(E instanceof Error?E.message:"falha ao salvar")}finally{Qa(!1)}},[w,Ka]),[tr,rm]=n.useState(""),[ao,Wi]=n.useState(!1),[Gi,Ki]=n.useState(null),[Qi,ar]=n.useState(null),Ji=n.useCallback(async()=>{if(w){Wi(!0),ar(null),Ki(null);try{const o=await Np(w.leadId,tr);o||ar("CPF não encontrado na base da seguradora"),Ki(o)}catch(o){ar(o instanceof Error?o.message:"falha na consulta")}finally{Wi(!1)}}},[w,tr]),om=n.useCallback(async(o,h)=>{if(w)try{const E=await Xl(w.leadId,o,h);Xe(E)}catch(E){ar(E instanceof Error?E.message:"falha ao aplicar")}},[w]),sr=(x==null?void 0:x.role)==="admin"||(x==null?void 0:x.role)==="super_admin"||(x==null?void 0:x.role)==="manager",[vn,so]=n.useState(!1),[no,Rs]=n.useState(!1),[nr,rr]=n.useState(""),[ro,or]=n.useState(""),[ir,Xi]=n.useState(!1),[Zi,Os]=n.useState(null),es=!!(re!=null&&re.encerrada),jn=xg({saleStep:(Dl=l.find(o=>o.id===(w==null?void 0:w.leadId)))==null?void 0:Dl.saleStep,temJornada:!!_a,encerrada:es}),[im,oo]=n.useState(b.cotacaoExpandidaPadrao);n.useEffect(()=>{oo(b.cotacaoExpandidaPadrao)},[w==null?void 0:w.leadId,b.cotacaoExpandidaPadrao]);const yn=Uc(jn)||im,lm=!es||vn,cm=!!re&&(re.ready_to_quote||!!(($l=re.motores)!=null&&$l.agv)&&re.slots.some(o=>o.key==="placa"&&o.filled)&&re.slots.some(o=>o.key==="cep"&&o.filled)),[$a,Yi]=n.useState(null),el=n.useCallback(async o=>{if(!(!(w!=null&&w.leadId)||$a)){Yi(o);try{await wp(w.leadId,o,{confirmarVendaConcluida:vn}),v({title:`Cotação na ${Rt[o].nome} enfileirada`,description:o==="agger"?"Recalculando com os dados atuais. As propostas atualizam em alguns segundos.":"Chega como rascunho pra você revisar antes de enviar."})}catch(h){v({title:`Não deu pra cotar na ${Rt[o].nome}`,description:h instanceof Error?h.message:"",variant:"destructive"})}finally{Yi(null)}}},[w==null?void 0:w.leadId,$a,vn,v]),[Nn,tl]=n.useState(!1),dm=n.useCallback(async()=>{var o,h;if(!(!(w!=null&&w.leadId)||Nn)){tl(!0);try{const E=await kp(w.leadId);v({title:"Proposta transmitida",description:[E.numero_proposta?`Número: ${E.numero_proposta}.`:null,(o=E.avisos)!=null&&o.length?E.avisos.join(" "):"Enviada ao cliente."].filter(Boolean).join(" "),variant:(h=E.avisos)!=null&&h.length?"destructive":void 0})}catch(E){v({title:"Não deu pra transmitir",description:E instanceof Error?E.message:"",variant:"destructive"})}finally{tl(!1)}}},[w==null?void 0:w.leadId,Nn,v]),um=n.useCallback(async()=>{if(!(w!=null&&w.leadId)||ir)return;const o=nr.trim();if(!o){Os("Informe o id da proposta no portal.");return}Xi(!0),Os(null);try{await Cp(w.leadId,{idProposta:o,numeroProposta:o,linkVistoria:ro.trim()||void 0}),v({title:"Proposta registrada",description:"A partir de agora o agente não recota este lead, e o acompanhamento de vistoria e pagamento passa a valer."}),Rs(!1),rr(""),or(""),Xs(w.leadId,m).then(Xe).catch(()=>{})}catch(h){Os(h instanceof Error?h.message:"não deu pra registrar")}finally{Xi(!1)}},[w,ir,nr,ro,m,v]),io=n.useCallback(o=>!!re&&re.slots.some(h=>h.key===o&&h.filled),[re]),lr=n.useMemo(()=>{if(!re)return[];const o=!!re.ready_to_quote,h=io("placa")&&io("cep");return["agger","suhai","agv","coonecta"].filter(ee=>{var ie;return!!((ie=re.motores)!=null&&ie[ee])}).map(ee=>{const ie=ee==="agv"?h:o;return{motor:ee,pronto:ie,falta:ie?null:ee==="agv"?"falta placa ou CEP":"falta veÃculo, CPF ou CEP"}})},[re,io]),al=sr&&lm&&lr.length>0,cr=sr&&!es,pt=n.useCallback(()=>{m&&Sp(m).then(S).catch(()=>{})},[m]);n.useEffect(()=>{pt()},[pt]),ls(pt,zd);const Pa=new Map,dr=new Map,sl=o=>o.message_category==="correcao"?1:0;for(const o of t){dr.set(o.lead_id,(dr.get(o.lead_id)??0)+1);const h=Pa.get(o.lead_id);if(!h){Pa.set(o.lead_id,o);continue}const E=sl(o),ee=sl(h);if(E>ee){Pa.set(o.lead_id,o);continue}E<ee||new Date(o.created_at).getTime()>=new Date(h.created_at).getTime()&&Pa.set(o.lead_id,o)}const Fs=new Map;for(const o of L)Fs.set(o.leadId,{leadId:o.leadId,name:o.contactName||o.contactPhone||"Lead",phone:o.contactPhone||"",draft:Pa.get(o.leadId)??null,draftCount:dr.get(o.leadId)??0,lastAt:o.lastMessageAt,lastIsOutgoing:o.lastIsOutgoing,canal:o.canal??null,lastMessage:o.lastMessage});for(const[o,h]of Pa)Fs.has(o)||Fs.set(o,{leadId:o,name:h.contact_name||h.contact_phone||"Lead",phone:h.contact_phone||"",draft:h,draftCount:dr.get(o)??1,lastAt:h.created_at});for(const o of l)Fs.has(o.id)||!o.lastContactAt||Fs.set(o.id,{leadId:o.id,name:o.contactName||o.contactPhone||"Lead",phone:o.contactPhone||"",draft:Pa.get(o.id)??null,lastAt:o.lastContactAt});let Re=[...Fs.values()];const mm=o=>!!o.lastAt&&Date.now()-new Date(o.lastAt).getTime()<Jg,nl=o=>o.draft||mm(o)?!1:wt.has(o.leadId)||Et.get(o.leadId)==="lost"?!0:mt.has(o.leadId),rl=Re.length,ol=Re.filter(nl).length,pm=rl-ol;if(B!=="all"&&(Re=Re.filter(o=>B==="archived"===nl(o))),B==="pending"&&(Re=Re.filter(o=>o.draft)),oe!=="all"&&(Re=Re.filter(o=>{var E;const h=(E=ga.get(o.leadId))==null?void 0:E.kind;if(oe==="outras"){const ee=Object.values(Kc).flat();return!h||!ee.includes(h)}return!!h&&Kc[oe].includes(h)})),be!=="all"&&(Re=Re.filter(o=>be==="pendente"?tt.has(o.leadId):be==="sem_fup"?!tt.has(o.leadId):mt.has(o.leadId))),pe!=="all"){const o=Oo.find(E=>E.id===pe).horas,h=Date.now()-o*36e5;Re=Re.filter(E=>!!E.lastAt&&new Date(E.lastAt).getTime()>=h)}if(je!=="all"&&(Re=Re.filter(o=>{const h=it.get(o.leadId);return je==="principal"?!h:(h==null?void 0:h.label)===je})),Le&&(Re=Re.filter(o=>J.has(o.leadId))),Ee.size>0&&(Re=Re.filter(o=>{var E;const h=(E=lt.get(o.leadId))==null?void 0:E.id;return h!=null&&Ee.has(h)})),W.trim()){const o=Gc(W),h=W.replace(/\D/g,"");Re=Re.filter(E=>Gc(E.name).includes(o)||!!h&&(E.phone||"").replace(/\D/g,"").includes(h)||yt.has(E.leadId))}Re.sort((o,h)=>new Date(h.lastAt||0).getTime()-new Date(o.lastAt||0).getTime());
166const ur=Pa.size,lo=((Pl=Re[0])==null?void 0:Pl.leadId)??null,il=((Ml=Re[0])==null?void 0:Ml.name)??"",ll=((Tl=Re[0])==null?void 0:Tl.phone)??"";n.useEffect(()=>{typeof window<"u"&&!window.matchMedia("(min-width: 768px)").matches||!w&&lo&&qe({leadId:lo,name:il,phone:ll})},[lo,il,ll,w]);const cl=n.useRef(!1);n.useEffect(()=>{if(cl.current)return;const o=U.get("lead");if(!o&&!U.get("filtro"))return;cl.current=!0,o&&qe({leadId:o,name:"",phone:""});const h=new URLSearchParams(U);h.delete("lead"),h.delete("filtro"),te(h,{replace:!0})},[U,te]),n.useEffect(()=>{u&&qe({leadId:u.leadId,name:u.name||"",phone:u.phone||""})},[u==null?void 0:u.leadId,u==null?void 0:u.nonce]);const Qe=w?Pa.get(w.leadId)??null:null,{config:co}=yi((Qe==null?void 0:Qe.company_id)||null),xm=Ni(co==null?void 0:co.agent_display_name),zs=!!w&&(!!Qe&&Qe.message_category==="cotacao"||(xe==null?void 0:xe.status)==="done"&&(xe==null?void 0:xe.lead_id)===w.leadId),mr=n.useRef(null);n.useEffect(()=>{mr.current=(w==null?void 0:w.leadId)??null},[w==null?void 0:w.leadId]);const la=n.useCallback((o,h=!0)=>{h&&Ja(!0),_r(o).then(E=>{o===mr.current&&aa(E)}).catch(()=>{}).finally(()=>Ja(!1)),Er(o).then(E=>{o===mr.current&&ya(E)}).catch(()=>{o===mr.current&&ya([])})},[]),pr=n.useRef(null),uo=n.useRef(!0),wn=n.useRef(!0),kn=n.useCallback(()=>{const o=pr.current;o&&(o.scrollTop=o.scrollHeight)},[]),[fm,dl]=n.useState(!0),hm=n.useCallback(()=>{const o=pr.current;if(!o)return;const h=o.scrollHeight-o.scrollTop-o.clientHeight<120;uo.current=h,dl(h)},[]),xr=n.useCallback(()=>{wn.current=!1},[]),gm=n.useCallback(o=>{["ArrowUp","PageUp","Home","ArrowDown","PageDown","End"].includes(o.key)&&xr()},[xr]);n.useLayoutEffect(()=>{(wn.current||uo.current)&&kn()},[st,Qe==null?void 0:Qe.id,kn]),n.useEffect(()=>{const o=pr.current;if(!o)return;const h=()=>{wn.current&&kn()};return o.addEventListener("load",h,!0),()=>o.removeEventListener("load",h,!0)},[kn]),n.useEffect(()=>{wn.current=!0,uo.current=!0,dl(!0)},[w==null?void 0:w.leadId]);const{decByMsg:bm,decUnlinkedAsc:ul}=n.useMemo(()=>{const o=new Map,h=[];if(bs.length){const E=new Set(st.map(ee=>ee.id));for(const ee of bs)ee.message_id&&E.has(ee.message_id)&&!o.has(ee.message_id)?o.set(ee.message_id,ee):h.push(ee);h.sort((ee,ie)=>new Date(ee.created_at).getTime()-new Date(ie.created_at).getTime())}return{decByMsg:o,decUnlinkedAsc:h}},[bs,st]),ml=n.useMemo(()=>[...Da].sort((o,h)=>new Date(o.created_at).getTime()-new Date(h.created_at).getTime()),[Da]),Ma=n.useMemo(()=>[...st].sort((o,h)=>new Date(o.timestamp).getTime()-new Date(h.timestamp).getTime()),[st]),pl=o=>e.jsx("div",{className:"flex justify-center my-2",children:e.jsxs("button",{onClick:()=>{Ya(o.id),Xa(!0)},title:o.summary||"Ver a decisão do agente",className:"inline-flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1 text-[11px] font-medium text-muted-foreground shadow-sm hover:border-primary/40 hover:text-foreground transition-colors",children:[e.jsx(eu,{className:"w-3 h-3 text-primary"})," ",nb(o),e.jsx(As,{className:"w-3 h-3 opacity-60"})]})},`dec-${o.id}`),xl=o=>e.jsx("div",{className:"flex justify-center my-2",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-success/30 bg-success/10 px-3 py-1 text-[11px] font-medium text-success-text",children:[e.jsx(yo,{className:"w-3 h-3"})," â ",ob(o.to_stage)]})},`stage-${o.id}`);n.useEffect(()=>{const o=rn();if(!o)return;const h=E=>{if((E==null?void 0:E.type)!=="agent_no_suggestion"||!w||E.leadId!==w.leadId)return;const ee=E.reason==="aguardando_cliente"?"Sem nova sugestão agora, a vez é do cliente responder.":E.reason==="handoff"?"Agente em silêncio, você assumiu este chat.":"O agente não tem o que sugerir agora.";v({title:"Sugestão descartada",description:ee})};return o.on("alert",h),()=>{o.off("alert",h),on()}},[w==null?void 0:w.leadId,v]);const ts=n.useRef(null);n.useEffect(()=>{if(kt([]),fn(null),ts.current=null,!w)return;const o=w.leadId,h=rn();if(!h)return;ts.current=h;const E=()=>h.emit("subscribe:lead",o);h.connected&&E(),h.on("connect",E);const ee=De=>{(De==null?void 0:De.leadId)===o&&kt((De.viewers||[]).filter(rt=>rt.userId!==(x==null?void 0:x.id)))},ie=De=>{(De==null?void 0:De.leadId)!==o||!De.userId||De.userId===(x==null?void 0:x.id)||fn(De.typing?{userId:De.userId,userName:De.userName??null}:null)};h.on("presence:update",ee),h.on("typing:update",ie);let $e=!1,Ae=null;const Ie=De=>{$e!==De&&($e=De,h.emit(De?"presence:idle":"presence:active"))},Tt=()=>{Ae&&clearTimeout(Ae),Ae=setTimeout(()=>Ie(!0),Qg)},as=()=>!document.hidden&&document.hasFocus(),ss=()=>{as()&&(Ie(!1),Tt())},Ct=()=>{as()?(Ie(!1),Tt()):Ie(!0)},St=["mousemove","mousedown","keydown","scroll","touchstart"];return St.forEach(De=>
166window.addEventListener(De,ss,{passive:!0})),document.addEventListener("visibilitychange",Ct),window.addEventListener("blur",Ct),window.addEventListener("focus",Ct),Tt(),()=>{h.emit("typing:stop",o),h.emit("unsubscribe:lead",o),h.off("connect",E),h.off("presence:update",ee),h.off("typing:update",ie),St.forEach(De=>window.removeEventListener(De,ss)),document.removeEventListener("visibilitychange",Ct),window.removeEventListener("blur",Ct),window.removeEventListener("focus",Ct),Ae&&clearTimeout(Ae),on(),ts.current=null}},[w==null?void 0:w.leadId,x==null?void 0:x.id]);const qs=n.useRef(null),vm=n.useCallback(()=>{if(!w||!ts.current)return;const o=w.leadId;ts.current.emit("typing:start",o),qs.current&&clearTimeout(qs.current),qs.current=setTimeout(()=>{var h;(h=ts.current)==null||h.emit("typing:stop",o)},3e3)},[w]),mo=n.useCallback(()=>{qs.current&&(clearTimeout(qs.current),qs.current=null),w&&ts.current&&ts.current.emit("typing:stop",w.leadId)},[w]),Cn=(w==null?void 0:w.leadId)??null;n.useEffect(()=>{if(!Cn){aa([]),ya([]),Za([]),Xe(null),Te(null),na(null),Pt(null),so(!1),Rs(!1),rr(""),or(""),Os(null),Rs(!1),rr(""),or(""),Os(null);return}const o=Cn;let h=!0;aa([]),ya([]),Za([]),Xe(null),Te(null),na(null),Pt(null),so(!1),Ja(!0);const E=()=>Xs(o,m).then(Ie=>h&&Xe(Ie)).catch(()=>{}),ee=()=>Ar(o).then(Ie=>h&&Te(Ie)).catch(()=>{}),ie=()=>da(o).then(Ie=>{h&&(na(Ie.perfil_socioeconomico??null),Pt(Ie.exists?Ss(Ie):null))}).catch(()=>{}),$e=()=>Er(o).then(Ie=>h&&ya(Ie)).catch(()=>{}),Ae=()=>ac(o).then(Ie=>h&&Za(Ie)).catch(()=>{});return _r(o).then(Ie=>h&&aa(Ie)).catch(()=>{}).finally(()=>h&&Ja(!1)),E(),ee(),ie(),$e(),Ae(),()=>{h=!1}},[Cn,m]);const jm=n.useCallback(()=>{if(!w)return;const o=w.leadId;_r(o).then(aa).catch(()=>{}),Xs(o,m).then(Xe).catch(()=>{}),Ar(o).then(Te).catch(()=>{}),da(o).then(h=>{na(h.perfil_socioeconomico??null),Pt(h.exists?Ss(h):null)}).catch(()=>{}),Er(o).then(ya).catch(()=>{}),ac(o).then(Za).catch(()=>{})},[w,m]);ls(jm,12e3,!!w);const ym=n.useCallback(()=>{w&&Ar(w.leadId).then(Te).catch(()=>{})},[w]);ls(ym,4e3,!!w&&(xe==null?void 0:xe.status)==="running");const fl=n.useRef(void 0),hl=n.useRef(new Set);n.useEffect(()=>{const o=fl.current,h=xe==null?void 0:xe.status;if(fl.current=h,!w||h!=="done"||(xe==null?void 0:xe.lead_id)!==w.leadId)return;const E=!!o&&o!=="done",ee=!hl.current.has(w.leadId);if(E||ee){hl.current.add(w.leadId),(typeof window>"u"||window.innerWidth>=768)&&Z(!0),d==null||d();const ie=w.leadId;Xs(ie,m).then(Xe).catch(()=>{}),da(ie).then($e=>{na($e.perfil_socioeconomico??null),Pt($e.exists?Ss($e):null)}).catch(()=>{})}},[xe==null?void 0:xe.status,xe==null?void 0:xe.lead_id,w,d,m]);const gl=n.useCallback(()=>{a(),pt(),w&&setTimeout(()=>la(w.leadId,!1),800)},[a,pt,w,la]),bl=n.useCallback(async()=>{if(w)try{await Md(w.leadId),Qe&&await Lr(Qe.id,"assumido pelo vendedor").catch(()=>{}),Y(!0),v({title:"Você assumiu a conversa",description:"O agente foi pausado neste chat."}),a(),s==null||s(),pt()}catch(o){v({title:"Erro ao assumir",description:o instanceof Error?o.message:"",variant:"destructive"})}},[w,Qe,v,a,s,pt]),vl=n.useCallback(async()=>{if(w)try{await Td(w.leadId),Y(!1),v({title:"Devolvido ao agente"}),a(),s==null||s()}catch(o){v({title:"Erro",description:o instanceof Error?o.message:"",variant:"destructive"})}},[w,v,a,s]),[Nm,jl]=n.useState(!1),wm=n.useCallback(async()=>{if(w){_(!0);try{const o=await ei(w.leadId);v({title:"Lead zerado",description:`${o.mongo.conversations} conversa + ${o.mongo.analyses} análises apagadas. Pronto pra testar.`}),aa([]),Xe(null),Te(null),na(null),Pt(null),pt(),a()}catch(o){v({title:"Falha no reset",description:o instanceof Error?o.message:"",variant:"destructive"})}finally{_(!1)}}},[w,v,pt,a]),yl=n.useCallback(()=>{w&&jl(!0)},[w]),Ta=n.useMemo(()=>w?l.find(o=>o.id===w.leadId):void 0,[w,l]),Ia=!!(Ta!=null&&Ta.doNotContact),[km,Nl]=n.useState(!1),po=n.useCallback(async()=>{if(!w)return;const o=!Ia;I(!0);try{await _p(w.leadId,o),v({title:o?"Lead silenciado":"Lead reativado",description:o?"O agente e o follow-up automático pararam pra este lead.":"O agente e o follow-up voltaram a valer pra este lead."}),pt(),a()}catch(h){v({title:"Falha",description:h instanceof Error?h.message:"",variant:"destructive"})}finally{I(!1)}},[w,Ia,v,pt,a]),wl=n.useCallback(()=>
166{if(w){if(!Ia){Nl(!0);return}po()}},[w,Ia,po]),Cm=w?L.find(o=>o.leadId===w.leadId):null,Bs=Pi(Cm),kl=n.useCallback(async()=>{if(!(!w||!Be.trim())){if(Bs!==null&&!at){Wt(!0);return}if(!ne&&/R\$/.test(Be))try{const o=await da(w.leadId),h=ih(Be,o.propostas||[]);if(h.length){gt(h),Dt(!0);return}}catch{}Mt(!0),mo();try{await $d(w.leadId,Be.trim(),{cotacaoManual:me,cotacaoManualId:ia.trim()||void 0,cotacaoManualMotor:bn}),Qe&&await Lr(Qe.id,"vendedor respondeu manualmente").catch(()=>{}),ra(""),me&&(bt(!1),Yn(""),er("outro"),v({title:"Cotação manual registrada",description:ia.trim()?"O lead conta como cotado e o agente consegue consultar essa cotação depois.":"O lead conta como cotado e sai da fila de recuperação."})),Y(!0),setTimeout(()=>la(w.leadId,!1),600),a()}catch(o){v({title:"Falha ao enviar",description:o instanceof Error?o.message:"",variant:"destructive"})}finally{Mt(!1)}}},[w,Be,Qe,me,ia,bn,la,a,v,mo,Bs,at,ne]),Sm=n.useCallback(async()=>{if(w)try{await hn()}catch{v({title:"Sem acesso ao microfone",description:"Permita o microfone no navegador.",variant:"destructive"})}},[w,hn,v]),_m=n.useCallback(()=>{vs()},[vs]),Am=n.useCallback(async()=>{if(!w)return;const o=await Xn();if(o){Jn(!0);try{const h=await new Promise((E,ee)=>{const ie=new FileReader;ie.onload=()=>E(String(ie.result).split(",")[1]||""),ie.onerror=()=>ee(new Error("falha ao ler o áudio")),ie.readAsDataURL(o)});await Ap(w.leadId,h,o.type||"audio/webm"),Y(!0),v({title:"Ãudio enviado"}),setTimeout(()=>la(w.leadId,!1),600),a()}catch(h){v({title:"Falha ao enviar áudio",description:h instanceof Error?h.message:"",variant:"destructive"})}finally{Jn(!1)}}},[w,Xn,la,a,v]),Cl=n.useCallback(o=>{if(!o)return;const h=o.type.startsWith("image/");if(!h&&o.type!=="application/pdf"){v({title:"Só foto ou PDF",variant:"destructive"});return}if(o.size>6*1024*1024){v({title:"Arquivo muito grande",description:"Máximo 6MB.",variant:"destructive"});return}z(E=>(E&&URL.revokeObjectURL(E.url),{file:o,url:URL.createObjectURL(o),isImage:h}))},[v]),xo=n.useCallback(()=>{z(o=>(o&&URL.revokeObjectURL(o.url),null))},[]),Sl=n.useCallback(async()=>{if(!w||!j)return;const{file:o}=j;gn(!0);try{const h=await new Promise((E,ee)=>{const ie=new FileReader;ie.onload=()=>E(String(ie.result).split(",")[1]||""),ie.onerror=()=>ee(new Error("falha ao ler o arquivo")),ie.readAsDataURL(o)});await Ep(w.leadId,h,o.name,Be.trim()||void 0,o.type,{cotacaoManual:me,cotacaoManualId:ia.trim()||void 0,cotacaoManualMotor:bn}),xo(),ra(""),me&&(bt(!1),Yn(""),er("outro")),Y(!0),v({title:me?"Cotação manual enviada":j.isImage?"Imagem enviada":"PDF enviado",description:o.name}),setTimeout(()=>la(w.leadId,!1),600),a()}catch(h){v({title:"Falha ao enviar",description:h instanceof Error?h.message:"",variant:"destructive"})}finally{gn(!1)}},[w,j,Be,me,ia,bn,xo,la,a,v]);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex-1 min-w-0 md:flex-none md:w-[300px] flex-col border-r bg-card ${w?"hidden md:flex":"flex"}`,children:[e.jsxs("div",{className:"px-3 py-3 border-b flex items-center gap-2",children:[c&&e.jsx("button",{onClick:c,"aria-label":"Abrir menu",className:"md:hidden -ml-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground [-webkit-tap-highlight-color:transparent]",children:e.jsx(zm,{className:"w-5 h-5"})}),r&&e.jsx("button",{onClick:r,className:"text-muted-foreground hover:text-foreground",title:"Sair",children:e.jsx(un,{className:"w-4 h-4"})}),e.jsx(Ge,{className:"w-4 h-4 text-warning"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"text-sm font-semibold leading-tight truncate",children:"Inbox"}),C&&e.jsx("span",{className:"text-[10px] text-muted-foreground truncate leading-tight",children:C})]}),e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs font-medium px-2 py-1 rounded-md border border-input hover:bg-muted",title:"Nova mensagem",children:[e.jsx(us,{className:"w-3.5 h-3.5"})," Nova ",e.jsx(dt,{className:"w-3 h-3"})]})}),e.jsxs(Fa,{align:"end",className:"w-52",children:[e.jsxs(xt,{onClick:()=>Ga({open:!0,mode:"new"}),children:[e.jsx(fa,{className:"w-4 h-4 mr-2"})," Nova conversa"]}),e.jsxs(xt,{onClick:()=>
166F("/outbound"),children:[e.jsx(en,{className:"w-4 h-4 mr-2"})," Mensagem em massa"]})]})]}),ur>0&&e.jsx("span",{className:"text-xs font-bold bg-warning text-white rounded-full min-w-[20px] h-5 flex items-center justify-center px-1.5",children:ur})]}),e.jsx(ox,{companyId:m,onAbrirLead:(o,h)=>qe({leadId:o,name:h,phone:""}),onDescartado:()=>{a(),pt()}}),e.jsx(ix,{companyId:m,recarregarEm:Vt,onAbrirLead:(o,h)=>qe({leadId:o,name:h,phone:""}),onDecided:()=>{a(),pt()}}),e.jsx("div",{className:"px-3 pt-2 pb-1",children:e.jsxs("div",{className:"relative",children:[Nt?e.jsx(le,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none animate-spin"}):e.jsx(zn,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none"}),e.jsx("input",{value:W,onChange:o=>X(o.target.value),placeholder:"Buscar por nome, telefone ou mensagem",className:"w-full pl-7 pr-7 py-1.5 text-xs rounded-md border border-input bg-background outline-none focus:ring-1 focus:ring-ring"}),W&&e.jsx("button",{onClick:()=>X(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",title:"Limpar busca",children:e.jsx(vt,{className:"w-3.5 h-3.5"})})]})}),e.jsxs("div",{className:"px-3 py-2 border-b flex flex-wrap items-center gap-1",children:[[["all","Todas",rl],["active","Ativas",pm],["archived","Arquivadas",ol]].map(([o,h,E])=>e.jsxs(Mn.Fragment,{children:[e.jsxs("button",{onClick:()=>H(o),className:`text-[11px] font-medium px-2 py-1 rounded-md transition-colors whitespace-nowrap ${B===o||o==="active"&&B==="pending"?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"}`,children:[h,E>0&&e.jsx("span",{className:"ml-1 opacity-60",children:E})]}),o==="active"&&(B==="active"||B==="pending")&&e.jsxs("button",{onClick:()=>H(B==="pending"?"active":"pending"),title:"Só as conversas com rascunho esperando aprovação (subconjunto das ativas)",className:`-ml-0.5 text-[11px] font-medium px-2 py-1 rounded-md transition-colors whitespace-nowrap flex items-center gap-1 ${B==="pending"?"bg-warning/15 text-warning-text":"text-muted-foreground hover:bg-muted"}`,children:[e.jsx(As,{className:"w-3 h-3 opacity-40"}),"Pendentes",ur>0&&e.jsx("span",{className:"opacity-60",children:ur})]})]},o)),e.jsxs("button",{onClick:()=>ke(o=>!o),"aria-expanded":Se,className:`md:hidden ml-auto text-[11px] font-medium px-2 py-1 rounded-md transition-colors flex items-center gap-1 ${ht>0||Se?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"}`,children:[e.jsx(di,{className:"w-3 h-3 flex-shrink-0"}),"Filtros",ht>0&&e.jsx("span",{className:"opacity-60",children:ht}),e.jsx(dt,{className:`w-3 h-3 flex-shrink-0 opacity-70 transition-transform ${Se?"rotate-180":""}`})]}),e.jsxs("div",{className:`${Se?"contents":"hidden"} md:contents`,children:[e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsxs("button",{title:"Filtrar por origem do lead (de onde ele veio)",className:`ml-auto text-[11px] font-medium px-2 py-1 rounded-md transition-colors flex items-center gap-1 ${oe!=="all"?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"}`,children:[e.jsx(en,{className:"w-3 h-3 flex-shrink-0"}),Qc.find(o=>o.id===oe).short,e.jsx(dt,{className:"w-3 h-3 flex-shrink-0 opacity-70"})]})}),e.jsx(Fa,{align:"end",className:"w-52",children:Qc.map(({id:o,label:h})=>e.jsx(xt,{onClick:()=>O(o),className:`text-xs gap-2 ${oe===o?"bg-primary/10 text-primary font-medium":""}`,children:e.jsx("span",{children:h})},o))})]}),e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsxs("button",{title:"Filtrar por estado do follow-up",className:`text-[11px] font-medium px-2 py-1 rounded-md transition-colors flex items-center gap-1 ${be!=="all"?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"}`,children:[e.jsx(_t,{className:"w-3 h-3 flex-shrink-0"}),Jc.find(o=>o.id===be).short,e.jsx(dt,{className:"w-3 h-3 flex-shrink-0 opacity-70"})]})}),e.jsx(Fa,{align:"end",className:"w-56",children:Jc.map(({id:o,label:h})=>e.jsx(xt,{onClick:()=>fe(o),className:`text-xs gap-2 ${be===o?"bg-primary/10 text-primary font-medium":""}`,children:e.jsx("span",{children:h})},o))})]}),e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsxs("button",{title:"Filtrar pela última mensagem da conversa",className:`text-[11px] font-medium px-2 py-1 rounded-md transition-colors flex items-center gap-1 ${pe!=="all"?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"}`,children:[e.jsx(ex,{className:"w-3 h-3 flex-shrink-0"}),Oo.find(o=>o.id===pe).short,e.jsx(dt,{className:"w-3 h-3 flex-shrink-0 opacity-70"})]})}),e.jsx(Fa,{align:"end",className:"w-56",children:Oo.map(({id:o,label:h})=>e.jsx(xt,{onClick:()=>Me(o),className:`text-xs gap-2 ${pe===o?"bg-primary/10 text-primary font-medium":""}`,children:e.jsx("span",{children:h})},o))})]}),ut.length>1&&e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsxs("button",{title:"Filtrar pelo canal de entrada (qual número/campanha o cliente procurou)",className:`text-[11px] font-medium px-2 py-1 rounded-md transition-colors flex items-center gap-1 ${je!=="all"?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"}`,children:[e.jsx(Yd,{className:"w-3 h-3 flex-shrink-0"}),je==="all"?"Canal":((Il=ut.find(o=>o.id===je))==null?void 0:Il.label)??"Canal",e.jsx(dt,{className:"w-3 h-3 flex-shrink-0 opacity-70"})]})}),e.jsxs(Fa,{align:"end",className:"w-56",children:[e.jsx(xt,{onClick:()=>Oe("all"),className:`text-xs gap-2 ${je==="all"?"bg-primary/10 text-primary font-medium":""}`,children:e.jsx("span",{children:"Todos os canais"})}),ut.map(o=>e.jsxs(xt,{onClick:()=>Oe(o.id),className:`text-xs gap-2 ${je===o.id?"bg-primary/10 text-primary font-medium":""}`,children:[e.jsx("span",{className:"flex-1 truncate",children:o.label}),e.jsx("span",{className:"opacity-60",children:o.n})]},o.id))]})]}),e.jsxs("button",{onClick:()=>Ne(o=>!o),"aria-pressed":Le,title:"Mostrar só as conversas favoritadas",className:`text-[11px] font-medium px-2 py-1 rounded-md transition-colors flex items-center gap-1 ${Le?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"}`,children:[e.jsx(Ha,{className:`w-3 h-3 flex-shrink-0 ${Le?"fill-current":""}`}),"Favoritos"]}),Fe.length>0&&e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsxs("button",{title:"Filtrar por etapa do funil (marque quantas quiser)",className:`text-[11px] font-medium px-2 py-1 rounded-md transition-colors flex items-center gap-1 ${Ee.size>0?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"}`,children:[e.jsx(yo,{className:"w-3 h-3 flex-shrink-0"}),Ee.size===0?"Etapa":Ee.size===1?((Ll=Fe.find(o=>Ee.has(o.id)))==null?void 0:Ll.nome)??"Etapa":`${Ee.size} etapas`,e.jsx(dt,{className:"w-3 h-3 flex-shrink-0 opacity-70"})]})}),e.jsxs(Fa,{align:"end",className:"w-56",children:[e.jsxs(xt,{onClick:()=>ye(new Set),className:`text-xs gap-2 ${et?"bg-primary/10 text-primary font-medium":""}`,children:[e.jsx(yo,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsx("span",{children:"Todas as etapas"})]}),Fe.map(o=>e.jsx(qm,{checked:ta(o.id),onCheckedChange:()=>qt(o.id),onSelect:h=>h.preventDefault(),className:"text-xs pl-2 [&>span:first-child]:hidden",children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:`w-3.5 h-3.5 rounded-[4px] border flex items-center justify-center flex-shrink-0 transition-colors ${ta(o.id)?"bg-primary border-primary text-primary-foreground":"border-input"}`,children:ta(o.id)&&e.jsx(Xt,{className:"w-2.5 h-2.5",strokeWidth:3})}),e.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:o.cor}}),e.jsx("span",{children:o.nome})]})},o.id))]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-none pb-[env(safe-area-inset-bottom)]",children:Re.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center p-6 gap-2",children:[e.jsx(Bm,{className:"w-8 h-8 text-muted-foreground opacity-40"}),m?B==="pending"?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nenhum rascunho pendente."}):B==="archived"?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Nenhuma conversa arquivada.",e.jsx("br",{}),"Entram aqui as inativas (cliente em silêncio ou régua esgotada), as perdidas e as que você arquivar na mão."]}):W.trim()||oe!=="all"||be!=="all"||je!=="all"||Ee.size>0||pe!=="all"||Le?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Nenhuma conversa com esse filtro/busca.",e.jsx("br",{}),e.jsx("button",{onClick:()=>{X(""),O("all"),fe("all"),Oe("all"),ye(new Set),Me("all"),Ne(!1)},className:"mt-1 text-primary hover:underline",children:"Limpar filtros"})]}):e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Nenhuma conversa do agente",C?` em ${C}`:" nesta empresa"," ainda.",e.jsx("br",{}),e.jsx("span",{className:"opacity-70",children:"Confira se a empresa selecionada acima é a correta."})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Selecione uma empresa no seletor acima para ver as conversas do agente."})]}):Re.map(o=>{var De;const h=b.density==="compact",E=ha.get(o.leadId),ee=Et.get(o.leadId),ie=ee==="hot"?"bg-[hsl(var(--status-hot))]":ee==="warm"?"bg-[hsl(var(--status-warm))]":ee==="cold"?"bg-[hsl(var(--status-cold))]":null,$e=ee==="hot"?"Lead quente":ee==="warm"?"Lead morno":ee==="cold"?"Lead frio":"",Ae=ga.get(o.leadId),Ie=Yt.get(o.leadId),Tt=lt.get(o.leadId),as=tt.has(o.leadId),ss=xs.has(o.leadId),Ct=wt.has(o.leadId),St=J.has(o.leadId);return e.jsxs("div",{className:"relative group",children:[Wa&&e.jsx("span",{role:"button",tabIndex:0,title:Ct?"Desarquivar conversa":"Arquivar conversa",onClick:rt=>{rt.stopPropagation(),Ht(o.leadId,Ct)},onKeyDown:rt=>{(rt.key==="Enter"||rt.key===" ")&&(rt.preventDefault(),rt.stopPropagation(),Ht(o.leadId,Ct))},className:"absolute right-2 bottom-2 z-10 p-1 rounded text-muted-foreground opacity-0 group-hover:opacity-100 focus:opacity-100 hover:bg-background hover:text-foreground cursor-pointer transition-opacity",children:Ct?e.jsx(Fx,{className:"w-3.5 h-3.5"}):e.jsx(zx,{className:"w-3.5 h-3.5"})}),e.jsx("span",{role:"button",tabIndex:0,title:St?"Remover dos favoritos":"Favoritar conversa",onClick:rt=>{rt.stopPropagation(),he(o.leadId,St)},onKeyDown:rt=>{(rt.key==="Enter"||rt.key===" ")&&(rt.preventDefault(),rt.stopPropagation(),he(o.leadId,St))},className:`absolute right-2 top-2 z-10 p-1 rounded cursor-pointer transition-opacity hover:bg-background ${St?"opacity-100":"opacity-0 group-hover:opacity-100 focus:opacity-100"}`,children:e.jsx(Ha,{className:`w-3.5 h-3.5 ${St?"fill-warning text-warning-text":"text-muted-foreground"}`})}),e.jsxs("button",{onClick:()=>qe({leadId:o.leadId,name:o.name,phone:o.phone}),className:`w-full text-left flex items-start gap-3 border-b transition-colors ${h?"px-3 py-2":"px-3 py-3.5"} ${(w==null?void 0:w.leadId)===o.leadId?"bg-primary/10 border-l-2 border-l-primary":"hover:bg-muted border-l-2 border-l-transparent"}`,children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[Fo(o.name)?e.jsx("div",{className:`${h?"w-7 h-7":"w-9 h-9"} rounded-full flex items-center justify-center text-xs font-semibold ${ad(o.name)}`,children:td(o.name)}):e.jsx("div",{className:`${h?"w-7 h-7":"w-9 h-9"} rounded-full flex items-center justify-center ${o.draft?"bg-warning/10":"bg-primary/10"}`,children:e.jsx(Ge,{className:`${h?"w-3.5 h-3.5":"w-4 h-4"} ${o.draft?"text-warning":"text-primary"}`})}),ie&&e.jsx("span",{title:$e,className:`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background ${ie} ${ee==="hot"?"ring-2 ring-[hsl(var(--status-hot))]/30":""}`})]}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1 pr-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate min-w-0",children:o.name}),e.jsx("span",{className:"text-[10px] text-muted-foreground flex-shrink-0",children:cb(o.lastAt)}
166)]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[g&&b.showScore&&E!=null?`Score ${E} · `:"",hr(o.phone)]}),b.showPreview&&!o.draft&&o.lastMessage&&e.jsx("div",{className:"text-[11px] text-muted-foreground truncate",children:o.lastMessage}),W.trim()&&yt.has(o.leadId)&&e.jsxs("div",{className:"text-[11px] text-primary/80 truncate flex items-center gap-1",children:[e.jsx(zn,{className:"w-2.5 h-2.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:yt.get(o.leadId)})]}),(Ae||Tt||Ie||o.draft||as||ss||o.canal)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-1.5 gap-y-1",children:[o.canal&&e.jsxs("span",{className:"text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground font-medium flex-shrink-0 inline-flex items-center gap-0.5 max-w-[140px]",title:`Conversa entrou pelo número ${o.canal.fone?hr(o.canal.fone):"(desconhecido)"}${o.canal.label?` â ${o.canal.label}`:""}${o.canal.produto?` · linha de ${o.canal.produto}`:""}`,children:[e.jsx(en,{className:"w-2.5 h-2.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:o.canal.label||(o.canal.fone?hr(o.canal.fone):"canal")})]}),as&&e.jsxs("span",{className:"text-[9px] px-1 py-0.5 rounded bg-primary/15 text-primary font-medium flex-shrink-0 inline-flex items-center gap-0.5",title:"Follow-up enviado, aguardando retorno do cliente",children:[e.jsx(_t,{className:"w-2.5 h-2.5"})," Follow up"]}),ss&&e.jsxs("span",{className:"text-[9px] px-1 py-0.5 rounded bg-warning/15 text-warning font-medium flex-shrink-0 inline-flex items-center gap-0.5",title:"Lead silenciado: agente e follow-up automático parados",children:[e.jsx(fo,{className:"w-2.5 h-2.5"})," silenciado"]}),Ae&&(Ae.kind==="facebook"?e.jsx("span",{className:`p-0.5 rounded flex-shrink-0 inline-flex ${Ae.className}`,title:Ae.tooltip,children:e.jsx(Kg,{className:"w-3 h-3"})}):Ae.kind==="instagram"?e.jsx("span",{className:`p-0.5 rounded flex-shrink-0 inline-flex ${Ae.className}`,title:Ae.tooltip,children:e.jsx(tx,{className:"w-3 h-3"})}):e.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded font-medium flex-shrink-0 ${Ae.className}`,title:Ae.tooltip,children:Ae.label})),it.get(o.leadId)&&e.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded font-medium flex-shrink-0 ${it.get(o.leadId).className}`,title:it.get(o.leadId).tooltip,children:it.get(o.leadId).label}),(Ae==null?void 0:Ae.campaignLabel)&&e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded font-medium flex-shrink min-w-0 max-w-[140px] truncate bg-muted text-muted-foreground",title:`Campanha: ${Ae.campaignLabel}`,children:Ae.campaignLabel}),Tt?e.jsxs("span",{className:"text-[9px] px-1 py-0.5 rounded font-medium flex-shrink-0 inline-flex items-center gap-1 bg-muted text-foreground",title:`Etapa do funil: ${Tt.nome}`,children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:Tt.cor}}),Tt.nome]}):Ie?e.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded font-medium flex-shrink-0 ${Ie.className}`,title:`Etapa da venda: ${Ie.label}`,children:Ie.label}):null,o.draft&&e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-warning/20 text-warning font-medium flex-shrink-0",title:(o.draftCount??1)>1?`${o.draftCount} rascunhos pendentes â o painel mostra 1 por vez`:"rascunho aguardando aprovação",children:(o.draftCount??1)>1?`aprovar ${o.draftCount}`:"aprovar"}),((De=o.draft)==null?void 0:De.message_category)==="correcao"&&e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-destructive/20 text-destructive font-medium flex-shrink-0",title:"Correção de dado já enviado ao cliente â mandar ANTES da cotação nova",children:"correção"})]}),o.draft&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:o.draft.proposed_text||"(anexo/ação)"})]})]})]},o.leadId)})})]}),e.jsx("div",{className:`relative flex-1 min-w-0 min-h-0 ${w?"flex":"hidden md:flex"}`,children:e.jsxs(Oh,{direction:"horizontal",autoSaveId:"agent-inbox-chat-analysis",className:"min-w-0 min-h-0",children:[e.jsx(Ic,{defaultSize:70,minSize:35,className:"flex flex-col min-w-0 min-h-0",children:e.jsxs("div",{className:`flex-1 flex-col min-w-0 min-h-0 relative ${w?"flex":"hidden md:flex"}`,children:[w?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"h-16 border-b bg-card flex items-center gap-2 sm:gap-3 px-3 sm:px-5 flex-shrink-0 md:order-1",children:[e.jsx("button",{onClick:()=>qe(null),"aria-label":"Voltar para a lista",className:"md:hidden -ml-1 flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(un,{className:"h-5 w-5"})}),e.jsx("div",{className:`w-9 h-9 shrink-0 rounded-full flex items-center justify-center text-sm font-semibold ${Fo(w.name)?ad(w.name):"bg-primary/10 text-primary"}`,children:Fo(w.name)?td(w.name):(w.name||"?").slice(0,2).toUpperCase()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[P?e.jsx("input",{autoFocus:!0,value:V,onChange:o=>R(o.target.value),onBlur:Ui,onKeyDown:o=>{o.key==="Enter"&&(o.preventDefault(),o.stopPropagation(),Ui()),o.key==="Escape"&&(o.preventDefault(),o.stopPropagation(),D(!1))},disabled:M,maxLength:120,className:"w-full bg-background border border-input rounded px-2 py-0.5 text-sm font-semibold outline-none focus:ring-2 focus:ring-ring"}):e.jsxs("button",{type:"button",onClick:()=>{R(w.name||""),D(!0)},className:"group flex items-center gap-1 max-w-full text-left",title:"Editar nome do cliente",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground truncate",children:w.name}),e.jsx(Dr,{className:"w-3 h-3 text-muted-foreground opacity-0 group-hover:opacity-100 flex-shrink-0"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:hr(w.phone)}),nt&&nt.nivel&&nt.nivel!=="desconhecido"&&e.jsx("span",{className:`inline-flex flex-shrink-0 items-center rounded-full border px-1.5 py-px text-[9px] font-semibold ${(fr[nt.nivel]??fr.desconhecido).cls}`,title:nt.motivo||void 0,children:(fr[nt.nivel]??fr.desconhecido).label})]})]}),Ze.length>0&&(()=>{const o=Ze.some(ee=>!ee.idle),h=Ze.length===1?`${Ze[0].userName||"Alguém"}${Ze[0].idle?" · ausente":""}`:`${Ze.length} pessoas`,E=`Também vendo esta conversa: ${Ze.map(ee=>`${ee.userName||ee.userEmail||"alguém"}${ee.idle?" (ausente)":""}`).join(", ")}`;return e.jsxs("div",{className:`flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-[11px] font-medium ${o?"bg-warning/15 text-warning":"bg-muted text-muted-foreground"}`,title:E,children:[e.jsx(ps,{className:"w-3 h-3"}),e.jsx("span",{className:"hidden sm:inline",children:h})]})})(),e.jsxs("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[e.jsxs("button",{onClick:()=>ct(!0),className:"flex shrink-0 items-center gap-1.5 h-7 rounded-md border border-primary/30 px-2 sm:px-2.5 text-xs font-medium text-primary hover:bg-primary/10 transition-colors",title:"Marcar venda (por placa)",children:[e.jsx(cs,{className:"w-3.5 h-3.5"})," ",e.jsx("span",{className:"hidden sm:inline",children:"Marcar venda"})]}),e.jsx("button",{onClick:wl,disabled:N,className:`p-1.5 rounded-md disabled:opacity-50 transition-colors ${Ia?"text-warning bg-warning/10 hover:bg-warning/20":"text-muted-foreground
166/60 hover:text-warning-text hover:bg-warning/10"}`,title:Ia?"Lead silenciado: agente e follow-up parados. Clique pra reativar":"Silenciar: para o agente e o follow-up automático pra este lead (sem prazo, reversÃvel)",children:N?e.jsx(le,{className:"w-4 h-4 animate-spin"}):Ia?e.jsx(fo,{className:"w-4 h-4"}):e.jsx(Ko,{className:"w-4 h-4"})}),y&&e.jsx("button",{onClick:yl,disabled:k,className:"p-1.5 rounded-md text-muted-foreground/60 hover:text-destructive hover:bg-destructive/10 disabled:opacity-50 transition-colors",title:"Zerar histórico e dados do lead (teste): apaga conversa, análises e estado",children:k?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(ds,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>la(w.leadId),className:"p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted",title:"Recarregar conversa",children:e.jsx(jt,{className:`w-4 h-4 ${Ts?"animate-spin":""}`})}),i&&e.jsxs("button",{onClick:()=>Z(o=>!o),className:`relative p-1.5 rounded-lg transition-colors ${q?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground hover:bg-muted"}`,title:zs?"Análise IA â cotação pronta pra revisar":"Análise IA",children:[e.jsx(fc,{className:"w-4 h-4"}),zs&&!q&&e.jsx("span",{className:"absolute top-0.5 right-0.5 w-1.5 h-1.5 rounded-full bg-warning animate-pulse"})]})]}),e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsxs("button",{"aria-label":"Ações da conversa",className:"relative shrink-0 rounded-lg p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground sm:hidden",children:[e.jsx(hx,{className:"h-5 w-5"}),zs&&!q&&e.jsx("span",{className:"absolute top-0.5 right-0.5 w-1.5 h-1.5 rounded-full bg-warning animate-pulse"})]})}),e.jsxs(Fa,{align:"end",className:"w-56",children:[e.jsxs(xt,{onClick:()=>ct(!0),children:[e.jsx(cs,{className:"mr-2 h-4 w-4"})," Marcar venda"]}),i&&e.jsxs(xt,{onClick:()=>Z(o=>!o),children:[e.jsx(fc,{className:"mr-2 h-4 w-4"}),q?"Esconder análise IA":"Análise IA",zs&&!q&&e.jsx("span",{className:"ml-1.5 w-1.5 h-1.5 rounded-full bg-warning inline-block"})]}),e.jsxs(xt,{onClick:()=>la(w.leadId),children:[e.jsx(jt,{className:"mr-2 h-4 w-4"})," Recarregar conversa"]}),e.jsxs(xt,{onClick:wl,disabled:N,children:[Ia?e.jsx(Ko,{className:"mr-2 h-4 w-4"}):e.jsx(fo,{className:"mr-2 h-4 w-4"}),Ia?"Reativar agente e follow-up":"Silenciar (parar agente e follow-up)"]}),y&&e.jsxs(xt,{onClick:yl,disabled:k,className:"text-destructive focus:text-destructive",children:[e.jsx(ds,{className:"mr-2 h-4 w-4"})," Zerar histórico do lead"]})]})]})]}),p&&e.jsx(Uu,{leadId:w.leadId,leadName:w.name,companyId:m,open:Ue,onOpenChange:ct,onMarked:()=>{a(),pt()}}),e.jsx(nc,{open:km,onOpenChange:Nl,children:e.jsxs(rc,{children:[e.jsxs(oc,{children:[e.jsxs(ic,{children:["Silenciar ",w.name||w.phone,"?"]}),e.jsx(lc,{children:"O agente para de responder e o follow-up automático para de vez (não expira â fica até você reverter)."})]}),e.jsxs(cc,{children:[e.jsx(dc,{children:"Cancelar"}),e.jsx(uc,{onClick:()=>void po(),children:"Silenciar"})]})]})}),e.jsx(nc,{open:Nm,onOpenChange:jl,children:e.jsxs(rc,{children:[e.jsxs(oc,{children:[e.jsxs(ic,{children:["Zerar histórico de ",w.name||w.phone,"?"]}),e.jsx(lc,{children:"Apaga conversa, análises e dados (Postgres). Não dá pra desfazer."})]}),e.jsxs(cc,{children:[e.jsx(dc,{children:"Cancelar"}),e.jsx(uc,{onClick:()=>void wm(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Zerar histórico"})]})]})}),p&&e.jsx(Wh,{leadId:w.leadId,leadName:w.name,companyId:m,onDecided:()=>{a(),pt(),fs(o=>o+1)}}),e.jsxs("div",{ref:pr,onScroll:hm,onWheel:xr,onTouchMove:xr,onKeyDown:gm,className:"flex-1 overflow-y-auto scrollbar-none p-4 space-y-2 bg-[#f2f3f5] dark:bg-[#0b141a] md:order-4",children:[Ts&&st.length===0?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(le,{className:"w-6 h-6 text-primary animate-spin"})}):st.length===0?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sem histórico carregado"})}):lb(Ma.map((o,h)=>{var zl,ql,Bl,Ul;const E=Yc(o.timestamp),ee=h>0?Yc(Ma[h-1].timestamp):null,$e=E&&E!==ee?e.jsx("div",{className:"sticky top-2 z-10 flex justify-center my-2 pointer-events-none",children:e.jsx("span",{className:"text-[10px] font-medium px-2.5 py-1 rounded-full bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border backdrop-blur-sm capitalize",children:ib(o.timestamp)})},`day-${o.id}`):null,Ae=new Date(o.timestamp).getTime(),Ie=h>0?new Date(Ma[h-1].timestamp).getTime():-1/0,Tt=[];for(const Jt of ul){const Sn=new Date(Jt.created_at).getTime();Sn>Ie&&Sn<=Ae&&Tt.push(Jt)}const as=bm.get(o.id);as&&Tt.push(as);const ss=Tt.map(Jt=>pl(Jt)),Ct=ml.filter(Jt=>{const Sn=new Date(Jt.created_at).getTime();return Sn>Ie&&Sn<=Ae}).map(Jt=>xl(Jt)),St=Bu(o);if(St==="nota"||St==="nota_ocr"){const Jt=St==="nota_ocr"?qu(o.text):null;return{day:E,node:e.jsxs(Mn.Fragment,{children:[$e,ss,Ct,Jt?e.jsx("div",{className:"flex justify-center my-2",children:e.jsxs("span",{title:o.text||"",className:"inline-flex items-center gap-1.5 rounded-full border border-border/30 bg-ink/10 px-3 py-1 text-[11px] font-medium text-muted-foreground",children:[e.jsx(ot,{className:"w-3 h-3"})," Documento: ",Jt.tipo," · ",Jt.confianca,"%"]})}):e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"max-w-[80%] rounded-lg px-3 py-1.5 bg-muted text-muted-foreground text-[11px] text-center whitespace-pre-wrap break-words border border-dashed",children:o.text})})]},o.id)}}const De=St==="cliente",rt=St==="vendedor",Em=rt?ps:Ge,Dm=Hh(o);return{day:E,node:e.jsxs(Mn.Fragment,{children:[$e,ss,Ct,e.jsx("div",{className:`flex ${De?"justify-start":"justify-end"}`,children:e.jsxs("div",{className:`max-w-[68%] rounded-2xl px-4 py-2.5 shadow-sm text-sm whitespace-pre-wrap break-words ${De?"bg-card border text-foreground rounded-bl-sm":rt?"bg-warning text-white rounded-br-sm":"bg-primary text-primary-foreground rounded-br-sm"}`,children:[!De&&e.jsxs("div",{className:"text-[10px] font-semibold opacity-80 mb-0.5 flex items-center gap-1",children:[e.jsx(Em,{className:"w-3 h-3"})," ",Dm,To(o)&&e.jsx("span",{className:`ml-0.5 rounded px-1 py-[1px] text-[9px] font-bold uppercase tracking-wide ${To(o).tone==="ia"?"bg-white/25":"bg-black/25"}`,children:To(o).label})]}),Lc(o)&&e.jsxs("div",{className:"mb-1 inline-flex items-center gap-1 rounded-full bg-white/20 px-2 py-0.5 text-[10px] font-semibold",children:[e.jsx(cs,{className:"w-3 h-3"})," ",Lc(o)]}),((zl=o.media)==null?void 0:zl.kind)==="image"&&Cr(o.media)&&e.jsx("div",{className:"mb-1",children:e.jsx(Xg,{sellerId:o.media.sellerId,mediaId:o.media.mediaId,docId:o.media.docId,msgId:o.media.msgId,leadId:w==null?void 0:w.leadId,onZoom:ge})}),((ql=o.media)==null?void 0:ql.kind)==="video"&&Cr(o.media)&&e.jsx("div",{className:"mb-1",children:e.jsx(Zg,{sellerId:o.media.sellerId,mediaId:o.media.mediaId,msgId:o.media.msgId,leadId:w==null?void 0:w.leadId})}),((Bl=o.media)==null?void 0:Bl.kind)==="audio"&&(Cr(o.media)||o.media.link)&&e.jsx("div",{className:"mb-1",children:e.jsx(Yg,{sellerId:o.media.sellerId,mediaId:o.media.mediaId,docId:o.media.docId,msgId:o.media.msgId,link:o.media.link,leadId:w==null?void 0:w.leadId})}),((Ul=o.media)==null?void 0:Ul.kind)==="document"&&(Cr(o.media)||o.media.link)&&e.jsx("div",{className:"mb-1",children:e.jsx(eb,{media:o.media,leadId:(w==null?void 0:w.leadId)||""})}),o.text&&!(o.media&&/^(\[(image|imagem|document|documento|video|v[Ãi]deo|audio|voice)\]|ð|ð·|ð¬)/i.test(o.text.trim()))?zr(o.text):null,Zc(o.timestamp)&&e.jsx("div",{className:`text-[10px] mt-1 text-right ${De?"text-muted-foreground":"opacity-70"}`,children:Zc(o.timestamp)})]})})]},o.id)}})).map((o,h)=>e.jsx("div",{className:"relative space-y-2",children:o.nodes},`daygroup-${h}`)),Ma.length>0&&ul.filter(o=>new Date(o.created_at).getTime()>
166new Date(Ma[Ma.length-1].timestamp).getTime()).map(o=>pl(o)),Ma.length>0&&ml.filter(o=>new Date(o.created_at).getTime()>new Date(Ma[Ma.length-1].timestamp).getTime()).map(o=>xl(o)),Qe&&!we&&e.jsx(gu,{draft:Qe,persona:xm,onResolved:gl}),Qe&&!we&&!fm&&e.jsx("div",{className:"sticky bottom-2 z-10 flex justify-center pointer-events-none",children:e.jsxs("button",{type:"button",onClick:()=>{wn.current=!0,kn()},className:"pointer-events-auto inline-flex items-center gap-1.5 rounded-full bg-warning px-3 py-1.5 text-[11px] font-medium text-white shadow-lg hover:bg-warning/90",children:[e.jsx(Ge,{className:"w-3 h-3"})," Rascunho aguardando sua revisão",e.jsx(dt,{className:"w-3 h-3"})]})})]}),e.jsx(tg,{posicao:b.barraContextoPosicao,abrirPorPadrao:p&&yn&&re?"dados":null,chips:sg({etapa:((Rl=lt.get(w.leadId))==null?void 0:Rl.nome)??null,propostas:(xe==null?void 0:xe.propostas_count)??null,cotacaoFalhou:Yr(xe),cotacaoEmAndamento:Vu(xe),cotacaoComDetalhe:Gh(xe),cotacaoSecaoVisivel:yn&&!In(xe),cotacaoEnviada:Kt,preenchidos:(re==null?void 0:re.filled_count)??null,total:(re==null?void 0:re.total)??null,prontoPraCotar:!!(re!=null&&re.ready_to_quote),vendaEncerrada:es,propostaVisivel:p&&Ro(jn),temJornada:!!_a,horasForaDaJanela:Bs,transmissao:(xe==null?void 0:xe.stage)??null}),alertaEm:ag({cotacaoProgress:xe,checklist:re,jornada:_a,propostaVisivel:p&&Ro(jn)}),aoAcionarChip:o=>{o==="cotacao"&&Kt===!1&&xn(h=>h+1)},secoes:{etapa:e.jsx(e.Fragment,{children:Fe.length>0&&e.jsxs("div",{className:"border-b bg-card px-3 sm:px-5 py-1.5 flex items-center gap-2 flex-shrink-0",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground flex-shrink-0",children:"Etapa do funil:"}),e.jsxs("select",{value:((Ol=lt.get(w.leadId))==null?void 0:Ol.id)??"",onChange:o=>{const h=Number(o.target.value);h&&pn(w.leadId,h)},className:"text-[11px] rounded border border-input bg-background px-1.5 py-0.5 text-foreground focus:outline-none focus:ring-1 focus:ring-ring",children:[e.jsx("option",{value:"",disabled:!0,children:"selecionar"}),Fe.map(o=>e.jsx("option",{value:o.id,children:o.nome},o.id))]}),e.jsx("span",{className:"hidden sm:inline text-[10px] text-muted-foreground truncate",children:"corrige se a IA classificou errado"})]})}),cotacao:e.jsx(e.Fragment,{children:p&&yn&&!In(xe)&&e.jsx(Oc,{progress:xe})}),dados:e.jsxs(e.Fragment,{children:[p&&!yn&&re&&e.jsx("div",{className:"border-b bg-card px-3 sm:px-5 py-1 flex-shrink-0",children:e.jsxs("button",{type:"button",onClick:()=>oo(!0),className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",title:"Placa, CPF, veÃculo e as ações de cotação deste lead",children:[e.jsx(As,{className:"h-3 w-3"}),"Dados da cotação",e.jsxs("span",{className:"text-[10px]",children:["(",re.filled_count,"/",re.total,")"]})]})}),p&&yn&&re&&e.jsxs("div",{className:"border-b bg-card px-3 sm:px-5 py-1.5 flex-shrink-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 mb-1",children:[Uc(jn)?e.jsx("span",{className:"text-[11px] font-semibold text-foreground",children:"Dados da cotação"}):e.jsxs("button",{type:"button",onClick:()=>oo(!1),className:"inline-flex items-center gap-1 text-[11px] font-semibold text-foreground hover:text-primary",title:"Recolher os dados da cotação",children:[e.jsx(dt,{className:"h-3 w-3"})," Dados da cotação"]}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[re.filled_count,"/",re.total]}),re.zero_km&&e.jsx(ft,{variant:"info",size:"sm",children:"0km"}),es?e.jsx(ft,{variant:"success",size:"sm",title:"Apólice já emitida (ver a jornada da proposta). As ações de cotação estão desligadas pra não criar cotação nova num cliente que já tem contrato.",children:"venda concluÃda"}):re.ready_to_quote&&e.jsx(ft,{variant:"success",size:"sm",children:"pronto pra cotar"})]}),re.nome_revisar&&e.jsxs("div",{className:"mb-1.5 rounded border border-warning/40 bg-warning/10 px-2 py-1",children:[e.jsx("p",{className:"text-[11px] font-medium text-warning-text",children:"Confira o nome do contato"}),e.jsxs("p",{className:"mt-0.5 text-[10px] leading-snug text-muted-foreground",children:["No inbox aparece ",e.jsx("span",{className:"font-medium text-foreground",children:re.nome_revisar.atual}),", mas o CPF é de ",e.jsx("span",{className:"font-medium text-foreground",children:re.nome_revisar.documento}),". Pode ser o celular de um familiar â o nome não foi alterado."]}),e.jsx("button",{type:"button",className:"mt-1 text-[10px] font-medium text-warning-text hover:underline dark:text-warning-text",onClick:async()=>
166{if(Cn)try{await Dp(Cn),Xe(o=>o&&{...o,nome_revisar:null})}catch{}},children:"Ok, verifiquei"})]}),re.cotacao_desatualizada&&((Fl=re.cotacao_desatualizada.campos)==null?void 0:Fl.length)>0&&e.jsxs("div",{className:"mb-1.5 rounded border border-warning/40 bg-warning/10 px-2 py-1",children:[e.jsx("p",{className:"text-[11px] font-medium text-warning-text",children:es?"Dado alterado depois da emissão":"A cotação enviada está desatualizada"}),e.jsx("ul",{className:"mt-0.5 space-y-0.5",children:re.cotacao_desatualizada.campos.map(o=>{var h;return e.jsxs("li",{className:"text-[10px] leading-snug text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:((h=[...re.slots||[],...re.slots_editaveis||[]].find(E=>E.key===o.campo))==null?void 0:h.label)||o.campo}),": ",o.de===null||o.de===""?"(vazio)":String(o.de)," â ",String(o.para),". ",es?"A apólice saiu com o valor antigo; corrigir aqui não muda o documento â é endosso na seguradora.":o.impacto==="documento"?"A proposta no portal ainda está com o valor antigo. Recote pra ela sair com o novo.":"O preço que o cliente recebeu foi calculado com o valor antigo."]},o.campo)})})]}),sr&&es&&!vn&&cm&&e.jsxs("div",{className:"mb-1.5 flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Recotação desligada: a venda já foi emitida."}),e.jsx("button",{type:"button",onClick:()=>so(!0),title:"Libera as ações de cotação neste lead (renovação, endosso). Cria cotação de verdade na conta da corretora.",className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] font-medium text-muted-foreground hover:bg-muted",children:"Recotar mesmo assim"})]}),(al||cr)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-1.5",children:[al&&(lr.length===1?(()=>{const o=lr[0],h=$a===o.motor;return e.jsxs("button",{type:"button",onClick:()=>el(o.motor),disabled:!!$a||!o.pronto,title:o.pronto?`${Rt[o.motor].nome}: ${Rt[o.motor].porque}. Vira rascunho pra você revisar.`:`${Rt[o.motor].nome}: ${o.falta}`,className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-primary/40 px-2 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10 disabled:opacity-50",children:[e.jsx(jt,{className:`w-3 h-3 ${h?"animate-spin":""}`}),h?"Cotandoâ¦":o.motor==="agger"?"Recotar":e.jsxs(e.Fragment,{children:["Recotar na",e.jsx("span",{className:"hidden sm:inline",children:" "}),Rt[o.motor].nome]})]})})():e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:!!$a,title:"Escolher em qual seguradora recotar. Toda cotação daqui vira rascunho pra você revisar.",className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-primary/40 px-2 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10 disabled:opacity-50",children:[e.jsx(jt,{className:`w-3 h-3 ${$a?"animate-spin":""}`}),$a?`Cotando na ${Rt[$a].nome}â¦`:e.jsxs(e.Fragment,{children:["Recotar em",e.jsx("span",{className:"hidden sm:inline",children:" â¦"})]})]})}),e.jsx(Fa,{align:"start",className:"w-64",children:lr.map(({motor:o,pronto:h,falta:E})=>e.jsxs(xt,{disabled:!h||!!$a,onClick:()=>el(o),className:"flex flex-col items-start gap-0.5",children:[e.jsx("span",{className:"text-[12px] font-medium",children:Rt[o].nome}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:h?Rt[o].porque:E})]},o))})]})),cr&&e.jsxs("button",{type:"button",onClick:dm,disabled:Nn,title:"Transmite a proposta que o cliente já escolheu direto pra seguradora e manda o PDF pro WhatsApp dele. Ação irreversÃvel â cria proposta real.",className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-primary/40 px-2 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10 disabled:opacity-50",children:[e.jsx(xa,{className:`w-3 h-3 ${Nn?"animate-pulse":""}`}),Nn?"Transmitindoâ¦":"Transmitir"]}),cr&&!no&&e.jsx("button",{type:"button",onClick:()=>Rs(!0),title:"Você transmitiu a proposta no portal da seguradora? Registre aqui: o agente para de recotar este lead e o acompanhamento de vistoria e pagamento passa a valer.",className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] font-medium text-muted-foreground hover:bg-muted",children:"Emiti a proposta no portal"})]}),cr&&no&&e.jsx("div",{className:"mb-1.5",children:e.jsxs("div",{className:"rounded border border-border bg-muted/40 px-2 py-1.5",children:[e.jsx("p",{className:"mb-1 text-[10px] leading-snug text-muted-foreground",children:"Número da proposta no portal da seguradora. à ele que o acompanhamento usa pra consultar vistoria e pagamento."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("input",{value:nr,onChange:o=>rr(o.target.value),placeholder:"ex.: 11985463",className:"w-32 rounded border border-border bg-background px-1.5 py-0.5 text-[11px]"}),e.jsx("input",{value:ro,onChange:o=>or(o.target.value),placeholder:"link da vistoria (opcional)",className:"w-52 rounded border border-border bg-background px-1.5 py-0.5 text-[11px]"}),e.jsx("button",{type:"button",onClick:um,disabled:ir||!nr.trim(),className:"inline-flex items-center gap-1 rounded-full border border-primary/40 px-2 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10 disabled:opacity-50",children:ir?"Registrandoâ¦":"Registrar"}),e.jsx("button",{type:"button",onClick:()=>
166{Rs(!1),Os(null)},className:"text-[11px] text-muted-foreground hover:underline",children:"cancelar"})]}),Zi&&e.jsx("p",{className:"mt-1 text-[10px] text-destructive",children:Zi})]})}),e.jsxs("div",{className:"mt-2 rounded border border-dashed px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("input",{value:tr,onChange:o=>rm(o.target.value),onKeyDown:o=>{o.key==="Enter"&&Ji()},placeholder:"CPF (só números)",inputMode:"numeric",disabled:ao,className:"w-40 rounded border bg-background px-2 py-1 text-[11px] disabled:opacity-50"}),e.jsx("button",{type:"button",onClick:()=>void Ji(),disabled:ao||tr.replace(/\D/g,"").length!==11,className:"rounded border px-2 py-1 text-[11px] hover:bg-muted disabled:opacity-50",children:ao?"buscandoâ¦":"Buscar na base"}),Qi&&e.jsx("span",{className:"text-[10px] text-destructive",children:Qi})]}),Gi&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1",children:[[["nome","Nome"],["data_nascimento","Nascimento"],["sexo","Sexo"],["estado_civil","Estado civil"]].map(([o,h])=>{const E=Gi[o];return E?e.jsxs("button",{type:"button",title:`Aplicar ${h.toLowerCase()} = ${E}`,onClick:()=>void om(o,String(E)),className:"rounded-full border px-2 py-0.5 text-[10px] hover:border-primary hover:text-primary",children:[h,": ",e.jsx("strong",{children:String(E)})]},o):null}),e.jsx("span",{className:"self-center text-[10px] text-muted-foreground",children:"clique pra aplicar"})]})]}),e.jsx("div",{className:"flex gap-1.5 overflow-x-auto scrollbar-none",children:[...re.slots,...re.slots_editaveis??[]].map(o=>{if(hs===o.key)return e.jsxs("span",{className:"flex-shrink-0 inline-flex flex-col gap-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-1 py-0.5 rounded border border-primary/40 bg-card",children:[e.jsxs("span",{className:"text-muted-foreground",children:[o.label,":"]}),e.jsx("input",{autoFocus:!0,value:Ka,disabled:ja,onChange:E=>Aa(E.target.value),onKeyDown:E=>{E.key==="Enter"&&(E.preventDefault(),E.stopPropagation(),Vi(o.key)),E.key==="Escape"&&(E.preventDefault(),E.stopPropagation(),$t(null))},className:"w-24 bg-transparent outline-none text-foreground text-[10px]"}),e.jsx("button",{type:"button",disabled:ja,onClick:()=>Vi(o.key),title:"Salvar",className:"text-success hover:opacity-70",children:e.jsx(su,{className:"w-3 h-3"})}),e.jsx("button",{type:"button",disabled:ja,onClick:()=>$t(null),title:"Cancelar",className:"text-muted-foreground hover:text-foreground",children:e.jsx(vt,{className:"w-2.5 h-2.5"})})]}),Ea&&e.jsx("span",{className:"text-[9px] text-destructive px-1",children:Ea})]},o.key);if(o.filled){const E=ab(o.key,o.value);return e.jsxs("span",{className:"group flex-shrink-0 inline-flex items-center whitespace-nowrap text-[10px] rounded border bg-primary/5 border-primary/20 text-foreground hover:border-primary/50",children:[e.jsxs("button",{type:"button",onClick:()=>Hi(o.key,o.value),title:`${o.label}: ${E}, clique pra corrigir`,className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded-l",children:["â ",o.label,E?`: ${E}`:"",e.jsx(Dr,{className:"w-2.5 h-2.5 text-muted-foreground opacity-0 group-hover:opacity-100"})]}),o.key==="placa"&&e.jsx("button",{type:"button",onClick:()=>Zl(w.leadId,o.key).then(Xe).catch(()=>{}),title:"Marcar como 0km (sem placa): descarta esse valor",className:"px-1 py-0.5 text-muted-foreground/40 hover:text-destructive border-l border-primary/20",children:e.jsx(vt,{className:"w-2.5 h-2.5"})})]},o.key)}const h=!!o.covered;return e.jsxs("span",{title:h?`${o.label}: normalmente vem da placa. Clique no lápis pra informar na mão.`:void 0,className:`flex-shrink-0 inline-flex items-center whitespace-nowrap text-[10px] rounded border border-dashed ${h?"border-border/50 opacity-60":o.required?"border-warning/40":"border-border"}`,children:[e.jsxs("button",{type:"button",onClick:()=>o.question&&ra(o.question),title:o.question?`Sugerir resposta: "${o.question}"`:`${o.label} (pendente)`,className:"px-1.5 py-0.5 text-muted-foreground hover:text-foreground hover:bg-muted rounded-l",children:["â ",o.label]}),e.jsx("button",{type:"button",onClick:()=>Hi(o.key,null),title:`Preencher ${o.label}
166 na mão`,className:"px-1 py-0.5 text-muted-foreground/50 hover:text-primary border-l border-dashed border-inherit",children:e.jsx(Dr,{className:"w-2.5 h-2.5"})}),e.jsx("button",{type:"button",onClick:()=>Zl(w.leadId,o.key).then(Xe).catch(()=>{}),title:o.key==="placa"?"Cancelar etapa (carro 0km, sem placa)":"Cancelar esta etapa",className:"px-1 py-0.5 text-muted-foreground/40 hover:text-destructive border-l border-dashed border-inherit",children:e.jsx(vt,{className:"w-2.5 h-2.5"})})]},o.key)})})]})]}),proposta:e.jsxs(e.Fragment,{children:[p&&In(xe)&&e.jsx(Oc,{progress:xe}),p&&Ro(jn)&&e.jsx(dg,{jornada:_a,companyId:m,podeAgir:sr,declarando:no,aoDeclarar:()=>Rs(!0)})]})}},w.leadId),e.jsxs("div",{className:"border-t bg-card flex-shrink-0 md:order-8",children:[g&&e.jsxs("div",{className:"px-4 pt-2 flex items-center gap-2 text-[11px]",children:[e.jsxs("span",{className:`flex items-center gap-1 ${we?"text-warning font-medium":"text-muted-foreground"}`,children:[e.jsx(Ge,{className:"w-3 h-3"}),we?`${uu(Ta==null?void 0:Ta.attendanceReason,Ta==null?void 0:Ta.attendanceByName)}, agente pausado`:"Agente ativo"]}),we?e.jsx("button",{onClick:vl,className:"ml-auto text-primary hover:underline",children:"Devolver ao agente"}):e.jsxs("button",{onClick:bl,className:"ml-auto text-warning font-medium hover:underline flex items-center gap-1",children:[e.jsx(tn,{className:"w-3 h-3"})," Assumir pra mim"]})]}),j&&e.jsxs("div",{className:"mx-4 mt-2 p-2 rounded-lg border bg-muted/40 flex items-center gap-3",children:[j.isImage?e.jsx("img",{src:j.url,alt:"",onClick:()=>ge(j.url),className:"h-16 w-16 object-cover rounded-md border cursor-zoom-in",title:"Clique pra ver a imagem"}):e.jsx("iframe",{src:j.url,title:"PDF",className:"h-16 w-16 rounded-md border bg-white"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-medium truncate",children:j.file.name}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[j.isImage?"Imagem":"PDF"," · pronto pra enviar"]})]}),e.jsx("button",{onClick:xo,disabled:Qt,className:"text-muted-foreground hover:text-foreground text-lg leading-none px-1",title:"Cancelar",children:"Ã"})]}),Ls&&e.jsxs("div",{className:"px-4 pt-1.5 flex items-center gap-1.5 text-[11px] text-muted-foreground italic",children:[e.jsx(le,{className:"w-3 h-3 animate-spin"}),Ls.userName||"Alguém"," está digitando..."]}),e.jsxs("div",{className:"px-4 py-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] flex flex-col gap-2",children:[e.jsx("input",{ref:Bi,type:"file",accept:"application/pdf,image/*",className:"hidden",onChange:o=>{var E;const h=(E=o.target.files)==null?void 0:E[0];h&&Cl(h),o.target.value=""}}),to?e.jsx(db,{sampleLevels:Zn,sendingAudio:oa,onCancel:_m,onSend:Am}):e.jsxs(e.Fragment,{children:[p&&me&&e.jsxs("div",{className:"w-full flex flex-wrap items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsx("input",{value:ia,onChange:o=>Yn(o.target.value),placeholder:"ID da cotação (opcional)",disabled:Qt||Na||oa,className:"h-7 min-w-0 flex-1 rounded border border-input bg-background px-2 text-[11px] focus:outline-none focus:ring-1 focus:ring-ring disabled:opacity-50",title:"O que você digitou no portal da seguradora â sem isso, um PDF anexado ainda tenta ser lido sozinho, mas nada fica gravado se você só mandar o preço em texto."}),e.jsx("select",{value:bn,onChange:o=>er(o.target.value),disabled:Qt||Na||oa||!ia.trim(),className:"h-7 rounded border border-input bg-background px-1.5 text-[11px] disabled:opacity-50",title:"Onde você cotou",children:Object.entries($p).map(([o,h])=>e.jsx("option",{value:o,children:h},o))})]}),p&&me&&!j&&!Be.trim()&&e.jsxs("div",{className:"w-full text-xs rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 mb-2",children:[e.jsx("strong",{children:"Falta a mensagem."}),' "Cotação manual" só registra quando você digita o texto (ou anexa o PDF/print) e clica em Enviar â não existe um botão separado de salvar.']}),Bs!==null&&e.jsxs("div",{className:"w-full text-xs rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 mb-2",children:[e.jsxs("strong",{children:["O cliente não fala há ",Bs,"h."]})," Fora das 24h a Meta só entrega template aprovado (e cobra); texto livre ela costuma recusar (131047), e a recusa só aparece como falha na lista.",!at&&" Clique em enviar de novo pra mandar mesmo assim."]}),Ve&&Ve.length>0&&e.jsxs("div",{className:"w-full text-xs rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 mb-2",children:[e.jsxs("strong",{children:[Ve.length===1?"Esse valor":"Esses valores"," não"," ",Ve.length===1?"bate":"batem"," com nenhuma cotação deste lead: "," ",Ve.map(o=>
166o.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})).join(", "),"."]})," ","Confira se não é engano antes de mandar. Clique em enviar de novo pra mandar mesmo assim."]}),e.jsx("textarea",{value:Be,rows:1,onChange:o=>{ra(o.target.value),vm(),o.currentTarget.style.height="auto",o.currentTarget.style.height=Math.min(o.currentTarget.scrollHeight,120)+"px"},onBlur:mo,onKeyDown:o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),j?Sl():kl())},onPaste:o=>{var ee;const h=Array.from(((ee=o.clipboardData)==null?void 0:ee.items)||[]).find(ie=>ie.type.startsWith("image/")),E=h==null?void 0:h.getAsFile();if(E){o.preventDefault();const ie=(E.type.split("/")[1]||"png").replace("jpeg","jpg"),$e=E.name?E:new File([E],`colado-${Date.now()}.${ie}`,{type:E.type});Cl($e)}},placeholder:j?"Legenda (opcional)â¦":"Responder como vendedor... (shift+enter quebra linha, cole uma imagem aqui)",className:"w-full bg-background border border-input rounded-lg px-4 py-2 text-sm outline-none focus:ring-2 focus:ring-ring resize-none max-h-[120px] leading-relaxed"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>{var o;return(o=Bi.current)==null?void 0:o.click()},disabled:Qt||Na||oa,className:"h-9 w-9 flex items-center justify-center rounded-lg border border-input hover:bg-muted disabled:opacity-50",title:"Anexar foto ou PDF",children:e.jsx(gx,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Ga({open:!0,mode:"reply"}),disabled:Qt||Na||oa,className:"h-9 w-9 flex items-center justify-center rounded-lg border border-input hover:bg-muted disabled:opacity-50",title:"Enviar template Meta (reengajar fora da janela de 24h)",children:e.jsx(Kx,{className:"w-4 h-4"})}),e.jsx("button",{onClick:Sm,disabled:Qt||Na||oa||!!j,className:"h-9 w-9 flex items-center justify-center rounded-lg border border-input hover:bg-muted disabled:opacity-50",title:"Gravar áudio (sai como vendedor)",children:oa?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(ji,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[p&&e.jsxs("button",{onClick:()=>bt(o=>!o),disabled:Qt||Na||oa,"aria-pressed":me,className:`h-9 px-2 flex items-center gap-1.5 rounded-lg border text-[11px] font-medium disabled:opacity-50 ${me?"border-warning bg-warning text-white":"border-input text-muted-foreground hover:bg-muted"}`,title:me?"Marcado: esta mensagem leva a cotação que você fez à m
166ão (carimba o lead como cotado)":"Marcar que esta mensagem leva uma cotação feita à mão no portal da seguradora",children:[e.jsx(cs,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"hidden lg:inline",children:me?"Cotação manual":"Cotei à mão"})]}),e.jsx("button",{onClick:()=>j?Sl():kl(),disabled:j?Qt:!Be.trim()||Na,className:"h-9 w-9 flex items-center justify-center rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50",title:Bs!==null?at?"Enviar mesmo assim (fora da janela de 24h)":"Fora da janela de 24h â clique pra ver o aviso":"Enviar",children:Na||Qt?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(xa,{className:"w-4 h-4"})})]})]})]})]})]})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center bg-muted/20 text-center",children:[e.jsx(Ge,{className:"w-10 h-10 text-primary/40 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Selecione uma conversa do agente"})]}),p&&w&&!q&&e.jsx("div",{className:"hidden md:block",children:e.jsx(Ti,{leadId:w.leadId,confirmarVendaConcluida:vn,autoOpenAllowed:zs,openSignal:ue,floating:!0,onUseSuggestion:o=>ra(o)})})]})}),(q||ce)&&w&&Nd.createPortal(i==null?void 0:i({leadId:w.leadId,name:w.name,phone:w.phone,messages:st,onUseSuggestion:o=>ra(o),onClose:()=>ce?ae.fechar():Z(!1),hasPendingCotacaoDraft:zs,pip:{suportado:ae.suportado&&!se,ativo:ce,alternar:()=>ce?ae.fechar():ae.abrir()}}),ae.host),q&&w&&!ce&&e.jsxs(e.Fragment,{children:[e.jsx(Fh,{withHandle:!0,className:"hidden md:flex"}),e.jsx(Ic,{defaultSize:30,minSize:22,maxSize:60,className:"absolute inset-0 z-30 flex md:static md:z-auto flex-col min-w-0 min-h-0",children:e.jsx("div",{ref:G,className:"flex flex-1 flex-col min-w-0 min-h-0"})})]})]})}),e.jsx(dh,{open:Gt.open,onOpenChange:o=>Ga(h=>({...h,open:o})),companyId:m,mode:Gt.mode,leadId:Gt.mode==="reply"?w==null?void 0:w.leadId:void 0,leadName:Gt.mode==="reply"?w==null?void 0:w.name:void 0,checklist:Gt.mode==="reply"?re:null,onSent:o=>{pt(),o&&(Gt.mode==="new"&&qe({leadId:o,name:"",phone:""}),setTimeout(()=>la(o,!1),600))}}),e.jsx(Bg,{leadId:(w==null?void 0:w.leadId)??null,companyId:m,open:gs,onOpenChange:o=>{Xa(o),o||Ya(null)},focusId:Is,pendingDraft:we?null:Qe,draftIsCotacao:!!Qe&&Qe.message_category==="cotacao",onDraftResolved:gl,tookOver:we,onTakeover:bl,onReturnToAgent:vl}),de&&e.jsxs("div",{className:"fixed inset-0 z-[60] bg-black/80 flex items-center justify-center p-4 cursor-zoom-out",onClick:()=>ge(null),children:[e.jsx("img",{src:de,alt:"Imagem",className:"max-w-full max-h-full object-contain rounded-lg"}),e.jsx("button",{onClick:()=>ge(null),className:"absolute top-4 right-4 text-white/90 hover:text-white text-3xl leading-none",title:"Fechar",children:"Ã"})]})]})}function ri(t){Um.put("/api/auth/me/ui-preferences",t).catch(()=>{})}function wa(t){const s={...Rn.getState().layout,...t};Rn.getState().setLayout(s),ri({layout:s})}const ua=10,Ca=20,mb=15,Hr=5,oi=1,Ln=[mb,ua];function zi(t,a=Ca){if(t.length<oi||t.length>Hr)return`Use de ${oi} a ${Hr} degraus.`;for(const s of t)if(!Number.isFinite(s)||s<ua||s>=a)return`Cada degrau precisa estar entre ${ua} e ${a-1}%.`;for(let s=1;s<t.length;s+=1)if(t[s]>=t[s-1])return"A escada precisa ser decrescente: cada objeção seguinte cede MAIS comissão que a anterior.";return null}function Ju(t){if(!Number.isFinite(t)||t<=ua)return`A comissão padrão precisa ser maior que o piso (${ua}%).`}const zo=["1ª","2ª","3ª","4ª","5ª"];function Xu({enabled:t,degraus:a,onChange:s,titulo:r,descricao:i,padrao:l,onChangePadrao:d}){const c=zi(a,l),u=Ju(l);function m(p,g){s({enabled:t,degraus:a.map((y,k)=>k===p?g:y)})}function x(p){s({enabled:t,degraus:a.filter((g,y)=>y!==p)})}function f(){if(a.length>=Hr)return;const p=a[a.length-1]??ua,g=Math.max(ua,p-2);s({enabled:t,degraus:[...a,g]})}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:r}),e.jsx("div",{className:"text-sm text-muted-foreground",children:i})]}),e.jsx(an,{checked:t,onCheckedChange:p=>s({enabled:p,degraus:a})})]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-stretch gap-3 rounded-lg border bg-muted/30 p-4",children:[e.jsxs("div",{className:"w-40 shrink-0 rounded-md border bg-background p-3",children:[e.jsx("div",{className:"text-xs font-medium uppercase text-muted-foreground",children:"1ª cotação"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[e.jsx(ma,{id:"escada-comissao-padrao",type:"number",min:ua+1,className:"h-9 w-16 text-2xl font-semibold",value:l,onCh
166ange:p=>d(Number(p.target.value))}),e.jsx("span",{className:"text-lg font-semibold",children:"%"})]}),e.jsxs(Ft,{htmlFor:"escada-comissao-padrao",className:"mt-1 block text-xs text-muted-foreground",children:["Comissão padrão deste canal. Acima de ",Ca,"% encarece o cliente; sem teto â o piso de ",ua,"% é o único limite."]})]}),a.map((p,g)=>e.jsxs("div",{className:"flex items-stretch gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center justify-center px-1 text-center text-xs text-muted-foreground",children:[e.jsx(dn,{className:"h-4 w-4"}),e.jsxs("span",{children:[zo[g]??`${g+1}ª`," reclamação",e.jsx("br",{}),"de preço"]})]}),e.jsxs("div",{className:"relative w-40 shrink-0 rounded-md border-2 border-primary/40 bg-background p-3",children:[a.length>oi&&e.jsx("button",{type:"button",onClick:()=>x(g),className:"absolute right-1 top-1 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":`Remover ${zo[g]??`${g+1}ª`} objeção`,children:e.jsx(vt,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"text-xs font-medium uppercase text-muted-foreground",children:[zo[g]??`${g+1}ª`," objeção"]}),e.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[e.jsx(ma,{id:`escada-comissao-degrau-${g}`,type:"number",min:ua,max:l-1,className:"h-9 w-16 text-2xl font-semibold",value:p,onChange:y=>m(g,Number(y.target.value))}),e.jsx("span",{className:"text-lg font-semibold",children:"%"})]}),e.jsx(Ft,{htmlFor:`escada-comissao-degrau-${g}`,className:"mt-1 block text-xs text-muted-foreground",children:g===a.length-1?"Fica aqui nas reclamações seguintes.":"Editável."})]})]},g)),a.length<Hr&&e.jsxs("div",{className:"flex items-stretch gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center justify-center px-1 text-center text-xs text-muted-foreground",children:[e.jsx(dn,{className:"h-4 w-4"}),e.jsxs("span",{children:["reclama",e.jsx("br",{}),"de novo"]})]}),e.jsxs("button",{type:"button",onClick:f,className:"flex w-40 shrink-0 flex-col items-center justify-center gap-1 rounded-md border border-dashed p-3 text-muted-foreground hover:border-primary/40 hover:text-primary",children:[e.jsx(us,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Adicionar degrau"})]})]})]}),u&&e.jsx("p",{className:"text-xs text-destructive",children:u}),c&&e.jsx("p",{className:"text-xs text-destructive",children:c}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A escada não regride: se o cliente aceitar num degrau, a comissão não volta pra trás. Uma reclamação além do último degrau configurado mantém a comissão nele, não inventa mais um."})]})]})}const qi=8,Vr=5,ii=1,pb=[3,5];function Zu(t,a=qi){if(t.length<ii||t.length>Vr)return`Use de ${ii} a ${Vr} degraus.`;for(const s of t)if(!Number.isFinite(s)||s<=0||s>a)return`Cada degrau precisa estar entre 1 e ${a}%, que é o teto desta conta na seguradora.`;for(let s=1;s<t.length;s+=1)if(t[s]<=t[s-1])return"A escada precisa ser crescente: cada objeção seguinte dá MAIS desconto que a anterior.";return null}function qo(t=qi){const a=pb.filter(s=>s<=t);return a.length?a:t>=1?[Math.floor(t)]:[]}const Bo=["1ª","2ª","3ª","4ª","5ª"];function xb({enabled:t,degraus:a,teto:s,tetoMedido:r,onChange:i,titulo:l,descricao:d}){const c=Zu(a,s);function u(p,g){i({enabled:t,degraus:a.map((y,k)=>k===p?g:y)})}function m(p){i({enabled:t,degraus:a.filter((g,y)=>y!==p)})}function x(){if(a.length>=Vr)return;const p=a[a.length-1]??0,g=Math.min(s,p+2);g<=p||i({enabled:t,degraus:[...a,g]})}const f=a.length>=Vr||a[a.length-1]>=s;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l}),e.jsx("div",{className:"text-sm text-muted-foreground",children:d})]}),e.jsx(an,{checked:t,onCheckedChange:p=>i({enabled:p,degraus:a})})]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-stretch gap-3 rounded-lg border bg-muted/30 p-4",children:[e.jsxs("div",{className:"w-40 shrink-0 rounded-md border bg-background p-3",children:[e.jsx("div",{className:"text-xs font-medium uppercase text-muted-foreground",children:"1ª cotação"}),e.jsx("div",{className:"mt-1 text-2xl font-semibold",children:"0%"}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:"Preç
166o cheio. Desconto é resposta a objeção, não item de catálogo."})]}),a.map((p,g)=>e.jsxs("div",{className:"flex items-stretch gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center justify-center px-1 text-center text-xs text-muted-foreground",children:[e.jsx(dn,{className:"h-4 w-4"}),e.jsxs("span",{children:[Bo[g]??`${g+1}ª`," reclamação",e.jsx("br",{}),"de preço"]})]}),e.jsxs("div",{className:"relative w-40 shrink-0 rounded-md border-2 border-primary/40 bg-background p-3",children:[a.length>ii&&e.jsx("button",{type:"button",onClick:()=>m(g),className:"absolute right-1 top-1 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":`Remover ${Bo[g]??`${g+1}ª`} objeção`,children:e.jsx(vt,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"text-xs font-medium uppercase text-muted-foreground",children:[Bo[g]??`${g+1}ª`," objeção"]}),e.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[e.jsx(ma,{id:`escada-desconto-degrau-${g}`,type:"number",min:1,max:s,className:"h-9 w-16 text-2xl font-semibold",value:p,onChange:y=>u(g,Number(y.target.value))}),e.jsx("span",{className:"text-lg font-semibold",children:"%"})]}),e.jsx(Ft,{htmlFor:`escada-desconto-degrau-${g}`,className:"mt-1 block text-xs text-muted-foreground",children:g===a.length-1?"Fica aqui nas reclamações seguintes.":"Editável."})]})]},g)),!f&&e.jsxs("div",{className:"flex items-stretch gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center justify-center px-1 text-center text-xs text-muted-foreground",children:[e.jsx(dn,{className:"h-4 w-4"}),e.jsxs("span",{children:["reclama",e.jsx("br",{}),"de novo"]})]}),e.jsxs("button",{type:"button",onClick:x,className:"flex w-40 shrink-0 flex-col items-center justify-center gap-1 rounded-md border border-dashed p-3 text-muted-foreground hover:border-primary/40 hover:text-primary",children:[e.jsx(us,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Adicionar degrau"})]})]})]}),c&&e.jsx("p",{className:"text-xs text-destructive",children:c}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Teto de ",s,"% nesta conta",r?", medido na seguradora. Acima disso ela recusa a cotação inteira, e o lead fica sem preço.":". à o limite conhecido â o teto real desta conta ainda não foi medido, então pode ser menor."]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A escada não regride: se o cliente aceitar num degrau, o desconto não volta pra trás. Uma reclamação além do último degrau mantém o desconto nele, não inventa mais um. Não soma com a negociação de comissão, é uma alavanca OU outra."})]})]})}const fb=window.location.origin;function hb(){const t=localStorage.getItem("authToken")||sessionStorage.getItem("authToken")||"";return t?{Authorization:`Bearer ${t}`}:{}}function gb({companyId:t,persona:a}){const{toast:s}=At(),[r,i]=n.useState([]),[l,d]=n.useState(!0),[c,u]=n.useState(null),[m,x]=n.useState({}),[f,p]=n.useState({}),[g,y]=n.useState({}),[k,_]=n.useState(null),[N,I]=n.useState(null);n.useEffect(()=>{let C=!0;return(async()=>{var b,v,F,U,te;d(!0),u(null);try{const{credentials:q}=await No.list(t),Z=await Promise.all(q.map(async se=>{try{const{profile:Q}=await No.getChannelProfile(se.sellerId,t);return{cred:se,perfil:Q}}catch{return{cred:se,perfil:null}}}));if(!C)return;i(Z);const ae={},ce={};for(const{cred:se,perfil:Q}of Z){const K=Q==null?void 0:Q.pricingComissao,G=(b=Q==null?void 0:Q.pricingDesconto)==null?void 0:b.degraus,L=!!(K!=null&&K.enabled&&((v=K==null?void 0:K.degraus)!=null&&v.length)),S=!!(G!=null&&G.length);!L&&!S||(ae[se.sellerId]=L?{enabled:!0,degraus:(K==null?void 0:K.degraus)??[],padrao:(K==null?void 0:K.padrao)??Ca}:{enabled:!1,degraus:[...Ln],padrao:Ca},ce[se.sellerId]=S?{enabled:!0,degraus:G??[]}:{enabled:!1,degraus:[]})}x(ae),p(ce);try{const se=await fetch(`${fb}/api/outbound/insurer-credentials/${t}`,{headers:hb()});if(se.ok){const Q=await se.json(),K=(te=(U=(F=Q==null?void 0:Q.credentials)==null?void 0:F.suhai)==null?void 0:U.valores)==null?void 0:te.desconto_max_pct,G=Number(K);C&&Number.isFinite(G)&&G>0&&I(G)}}catch{}}catch(q){C&&u(He(q))}finally{C&&d(!1)}})(),()=>{C=!1}},[t]);const P=N??qi,D=r.filter(C=>C.perfil&&!m[C.cred.sellerId]);function V(C){x(b=>({...b,[C]:{enabled:!0,degraus:[...Ln],padrao:Ca}})),p(b=>({...b,[C]:{enabled:!1,degraus:qo(P)}})),y(b=>({...b,[C]:!0}))}function R(C){const b=m[C],v=f[C];if(b!=null&&b.enabled){const F=b.padrao??Ca,U=Ju(F);if(U)return U;const te=zi(b.degraus,F);if(te)return te}if(v!=null&&v.enabled){const F=Zu(v.degraus,P);
166if(F)return F}return null}async function M(C){if(R(C))return;const b=m[C],v=f[C];_(C);try{await No.saveChannelPricing(C,{...b?{comissao:{enabled:b.enabled,degraus:b.degraus,padrao:b.padrao??Ca}}:{},...v?{desconto:v.enabled?{degraus:v.degraus}:null}:{}}),y(F=>({...F,[C]:!1})),s({title:"Salvo",description:"Escada do canal atualizada. Vale no próximo turno (cache de 60s)."})}catch(F){s({title:"Erro ao salvar",description:He(F),variant:"destructive"})}finally{_(null)}}if(l)return e.jsx(_i,{className:"h-40 w-full"});if(c)return e.jsxs(Ds,{variant:"destructive",children:[e.jsx(sn,{className:"h-4 w-4"}),e.jsxs($s,{children:["Não consegui carregar os canais: ",c]})]});const $=r.filter(C=>!C.perfil);return e.jsxs("div",{className:"space-y-4",children:[r.length===0&&e.jsxs(Ds,{children:[e.jsx(sn,{className:"h-4 w-4"}),e.jsx($s,{children:"Esta empresa ainda não tem número cadastrado. A escada acima, da empresa, vale para todos os canais."})]}),Object.keys(m).map(C=>{var te,q;const b=r.find(Z=>Z.cred.sellerId===C),v=m[C],F=f[C]??{enabled:!1,degraus:qo(P)},U=R(C);return e.jsxs(qn,{children:[e.jsxs(Or,{className:"flex flex-row items-center justify-between gap-4 space-y-0",children:[e.jsxs(Fr,{className:"text-base",children:[(b==null?void 0:b.cred.label)||((te=b==null?void 0:b.perfil)==null?void 0:te.label)||"Canal",(b==null?void 0:b.cred.phoneNumberId)&&e.jsxs("span",{className:"ml-2 font-mono text-xs text-muted-foreground",children:["PNID ",b.cred.phoneNumberId]}),((q=b==null?void 0:b.perfil)==null?void 0:q.produto)&&e.jsx("span",{className:"ml-2 rounded bg-muted px-2 py-0.5 text-xs uppercase text-muted-foreground",children:b.perfil.produto})]}),e.jsxs(Pe,{size:"sm",onClick:()=>M(C),disabled:!g[C]||k===C||!!U,children:[k===C?e.jsx(le,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ai,{className:"mr-2 h-4 w-4"}),"Salvar"]})]}),e.jsxs(Bn,{className:"space-y-6",children:[e.jsx(Xu,{enabled:v.enabled,degraus:v.degraus,onChange:Z=>{x(ae=>{var ce;return{...ae,[C]:{...Z,padrao:(ce=ae[C])==null?void 0:ce.padrao}}}),y(ae=>({...ae,[C]:!0}))},padrao:v.padrao??Ca,onChangePadrao:Z=>{x(ae=>({...ae,[C]:{...ae[C],padrao:Z}})),y(ae=>({...ae,[C]:!0}))},titulo:"Ligar a negociação de comissão neste número",descricao:`Vale só para os leads que chegam NESTE número. A cada reclamação de preço do MESMO cliente, ${a} baixa a comissão um degrau e re-cota. Não soma com desconto, é uma alavanca OU outra.`}),e.jsx("div",{className:"border-t pt-6",children:e.jsx(xb,{enabled:F.enabled,degraus:F.degraus.length?F.degraus:qo(P),teto:P,tetoMedido:N!==null,onChange:Z=>{p(ae=>({...ae,[C]:Z})),y(ae=>({...ae,[C]:!0}))},titulo:"Ligar a negociação de desconto neste número",descricao:`Vale só para os leads que chegam NESTE número. A cada reclamação de preço do MESMO cliente, ${a} sobe o desconto um degrau e re-cota, dentro do teto da conta na seguradora.`})}),U&&e.jsx("p",{className:"text-xs text-destructive",children:U})]})]},C)}),D.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Adicionar escada para:"}),D.map(({cred:C,perfil:b})=>e.jsxs(Pe,{variant:"outline",size:"sm",onClick:()=>V(C.sellerId),children:[e.jsx(us,{className:"mr-2 h-4 w-4"}),C.label||C.phoneNumberId||C.sellerId.slice(0,8),(b==null?void 0:b.produto)&&e.jsx("span",{className:"ml-2 text-xs uppercase text-muted-foreground",children:b.produto})]},C.sellerId))]}),$.length>0&&e.jsxs(Ds,{children:[e.jsx(sn,{className:"h-4 w-4"}),e.jsxs($s,{children:[$.length===1?"Um número ainda não tem":`${$.length} números ainda não têm`," ","perfil de canal, então não podem ter escada própria ainda. Configure o canal em Integrações (produto, portfólio e seguradoras) e ele aparece aqui."]})]})]})}const sd=window.location.origin;function nd(){const t=localStorage.getItem("authToken")||sessionStorage.getItem("authToken")||"";return t?{Authorization:`Bearer ${t}`}:{}}function bb({companyId:t}){const{toast:a}=At(),[s,r]=n.useState(!0),[i,l]=n.useState(null),[d,c]=n.useState(!1),[u,m]=n.useState(!1),[x,f]=n.useState(30),[p,g]=n.useState(30),[y,k]=n.useState(!1),[_,N]=n.useState(!1),I=n.useRef(!0);n.useEffect(()=>()=>{I.current=!1},[]);const P=n.useCallback(async()=>{r(!0),l(null);try{const V=await fetch(`${sd}/api/outbound/agv-config/${t}`,{headers:nd()});if(!V.ok)throw new Error(`HTTP ${V.status}`);const R=await V.json();if(!I.current)return;c(R.credencial_propria_configurada),m(R.habilitado),f(R.stall_minutos),g(R.stall_minutos_piso),k(!1)}catch(V){I.current&&l(He(V))}finally{I.current&&r(!1)}},[t]);n.useEffect(()=>{P()},[P]);async function D(){N(!0);try{const V=await fetch(`${sd}/api/outbound/agv-config/${t}`,{method:"PUT",headers:{"Content-Type":"application/json",...nd()},body:JSON.stringify({habilitado:u,stall_minutos:x})}),R=await V.json().catch(()=>({}));if(!V.ok)throw new Error(R.error||`HTTP ${V.status}`);k(!1),a({title:"Salvo",description:"Configuração da AGV atualizada."})}catch(V){a({title:"Erro ao salvar",description:He(V),variant:"destructive"})}finally{N(!1)}}return s?e.jsx(_i,{className:"h-40 w-full"}):e.jsxs(qn,{children:[e.jsx(Or,{children:e.jsx(Fr,{className:"text-lg",children:"AGV: seguradora de último recurso"})}),e.jsxs(Bn,{className:"space-y-4",children:[i&&e.jsx(Ds,{variant:"destructive",children:e.jsxs($s,{children:["Não consegui carregar: ",i]})}),!d&&e.jsxs(Ds,{children:[e.jsx(sn,{className:"h-4 w-4"}),e.jsx($s,{children:"Configure a credencial própria da AGV na aba Integrações antes de ligar esta opção. Sem ela, o motor da AGV cotaria na conta padrão do sistema, não na desta empresa."})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:"Cotar automaticamente na AGV quando não há outro motor pronto"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Só dispara quando o cliente já mandou placa e CEP, nenhuma outra seguradora está pronta pra cotar, e o cliente ficou parado pelo tempo configurado abaixo."})]}),e.jsx(an,{className:"shrink-0 mt-1",checked:u,disabled:!d,onCheckedChange:V=>{m(V),k(!0)}})]}),e.jsxs("div",{className:"space-y-1 max-w-xs",children:[e.jsx(Ft,{htmlFor:"agv-stall-minutos",className:"text-sm",children:"Minutos parado antes de acionar"}),e.jsx(ma,{id:"agv-stall-minutos",type:"number",min:p,max:1440,value:x,disabled:!u,onChange:V=>{f(Math.max(p,Math.min(1440,parseInt(V.target.value||String(p),10)||p))),k(!0)}}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["MÃnimo ",p," minutos: a varredura que dispara a AGV já aplica esse piso pra toda empresa, então um valor menor não teria efeito."]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(Pe,{onClick:D,disabled:!y||_,children:[_?e.jsx(le,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Salvar"]})})]})]})}function vb({companyId:t}){var P,D,V;const{query:a}=Gn(t),{toast:s}=At(),r=ep(),i=Ni((V=(D=(P=a.data)==null?void 0:P.agent)==null?void 0:D.config)==null?void 0:V.agent_display_name),[l,d]=n.useState(!1),[c,u]=n.useState(Ln),[m,x]=n.useState(Ca),[f,p]=n.useState(!1),[g,y]=n.useState(!1),[k,_]=n.useState(!1);n.useEffect(()=>{var C,b;const $=((((b=(C=a.data)==null?void 0:C.agent)==null?void 0:b.config)||{}).pricing||{}).moto_comissao||{};d(!!$.enabled),x(Number.isFinite(Number($.padrao))&&Number($.padrao)>ua?Number($.padrao):Ca),Array.isArray($.degraus)&&$.degraus.length>0?(u($.degraus.map(Number)),_(!1)):Number.isFinite(Number($.objecao_pct))?(u([Ln[0],Number($.objecao_pct)]),_(!0)):(u([...Ln]),_(!!$.enabled)),p(!1)},[a.data]);const N=l?zi(c,m):null;async function I(){if(!(!t||N)){y(!0);try{await Gp(t,{pricing:{moto_comissao:{enabled:l,degraus:c,padrao:m}}}),await r.invalidateQueries({queryKey:["company-config",t]}),p(!1),s({title:"Salvo",description:"Escada de comissão do canal moto atualizada."})}catch(R){s({title:"Erro ao salvar",description:He(R),variant:"destructive"})}finally{y(!1)}}}return t?a.isLoading?e.jsx(_i,{className:"h-52 w-full"}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(Pe,{onClick:I,disabled:!f||g||!!N,children:[g?e.jsx(le,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Salvar"]})}),e.jsxs(qn,{children:[e.jsx(Or,{children:e.jsx(Fr,{className:"text-lg",children:"Suhai: negociação de preço no canal moto"})}),e.jsxs(Bn,{className:"space-y-4",children:[l&&k&&e.jsxs(Ds,{children:[e.jsx(sn,{className:"h-4 w-4"}),e.jsx($s,{children:"Esta empresa foi configurada antes da escada de vários degraus, então os valores abaixo ainda não estão todos salvos: o que veio do cadastro é o último degrau. Confira os percentuais e clique em Salvar para confirmar a escada inteira."})]}),e.jsx(Xu,{enabled:l,degraus:c,onChange:R=>{d(R.enabled),u(R.degraus),p(!0)},padrao:m,onChangePadrao:R=>{x(R),p(!0)},titulo:"Ligar a negociação de comissão",descricao:`Só vale no canal cadastrado como moto (produto do número = moto). A cada reclamação de preço do MESMO cliente, ${i} baixa a comissão um degrau e re-cota. Não soma com desconto,
166é uma alavanca OU outra.`})]})]}),e.jsxs(qn,{children:[e.jsx(Or,{children:e.jsx(Fr,{className:"text-lg",children:"Escada por número"})}),e.jsxs(Bn,{children:[e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Quando um número tem escada própria, ela vence a da empresa para os leads que chegam nele. Sem escada própria, o número usa a de cima."}),e.jsx(gb,{companyId:t,persona:i})]})]}),e.jsx(bb,{companyId:t})]}):e.jsxs(Ds,{children:[e.jsx(sn,{className:"h-4 w-4"}),e.jsx($s,{children:"Selecione uma empresa no seletor do topo."})]})}const jb=n.lazy(()=>Va(()=>import("./BIzC3cLR.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(t=>({default:t.ProfileTab}))),yb=n.lazy(()=>Va(()=>import("./i8SO6cQl.js").then(t=>t.b),__vite__mapDeps([14,1,2,3,4,5,6,7,15,10,16,17,18,19,20,21,11,22,23,24,25,26,27,28,13])).then(t=>({default:t.NotificationsTab}))),Nb=n.lazy(()=>Va(()=>import("./BrPuZavG.js"),__vite__mapDeps([29,1,2,3,4,5,6,7,10,30,31,8,9,32,33,34,35,36,37,38,13,39,40,41,42,43,44,45,21,11,46,47])).then(t=>({default:t.IntegrationsTab}))),wb=n.lazy(()=>Va(()=>import("./CE41C5T9.js"),__vite__mapDeps([48,1,4,2,3,5,6,7,8,9,15,10,49,50,51,30,31,32,33,34,35,36,37,38,13,39,40,52,53,54,43,42,55,44,56,11,19,57,58,20]))),kb=n.lazy(()=>Va(()=>import("./CzP5vppB.js"),__vite__mapDeps([59,2,1,3,4,5,6,7,8,60,61,38,62,63,64,65,66,33,32]))),Cb=n.lazy(()=>Va(()=>import("./BFsMTLnv.js"),__vite__mapDeps([67,1,2,3,4,5,6,7,18,49,68,69,33,22,70,26,71,8,72,60,9,47,73,74,34,75,13,76,11,77,78,38]))),Sb=n.lazy(()=>Va(()=>import("./G_kzsMBZ.js"),__vite__mapDeps([79,1,2,3,4,5,6,7,8,72,9,15,38,80,16,81,57,82,13,33,20,83]))),_b=n.lazy(()=>Va(()=>import("./FlwxkqT-.js"),__vite__mapDeps([84,1,2,3,4,5,6,7,18,8,72,44,50,85,51,73,38,86,33,87,13,83,88,89,90,91,81,57,11]))),Ab=n.lazy(()=>Va(()=>import("./CWY0TOy0.js"),__vite__mapDeps([92,1,2,3,4,5,6,7,8,9,72,60,15,50,85,43,93,94,26,35,36,38,16,33,34])));function La(){return e.jsx("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:e.jsx(le,{className:"h-5 w-5 animate-spin"})})}const Eb=[{value:"America/Sao_Paulo",label:"BrasÃlia (BRT, GMT-3)"},{value:"America/Manaus",label:"Manaus (AMT, GMT-4)"},{value:"America/Rio_Branco",label:"Rio Branco (ACT, GMT-5)"},{value:"America/Noronha",label:"Fernando de Noronha (GMT-2)"},{value:"Europe/Lisbon",label:"Lisboa (WET/WEST)"},{value:"UTC",label:"UTC"}];function Uo({icon:t,title:a,desc:s,children:r}){return e.jsxs("section",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-primary/10 text-primary",children:e.jsx(t,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:a}),s&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:s})]})]}),r]})}function Ns({active:t,onClick:a,icon:s,label:r}){return e.jsxs("button",{type:"button",onClick:a,className:Ce("flex-1 flex items-center gap-2.5 rounded-xl border px-4 py-3 text-sm font-medium transition-colors",t?"border-primary bg-primary/10 text-foreground":"border-border bg-background text-muted-foreground hover:bg-accent"),children:[e.jsx(s,{className:"h-4 w-4"}),r,t&&e.jsx(Xt,{className:"h-4 w-4 ml-auto text-primary"})]})}function Db({id:t,label:a,hidden:s,onToggle:r}){const{attributes:i,listeners:l,setNodeRef:d,transform:c,transition:u,isDragging:m}=Jd({id:t}),x={transform:Xd.Transform.toString(c),transition:u,opacity:m?.5:1};return e.jsxs("div",{ref:d,style:x,className:Ce("flex items-center gap-2 rounded-xl border px-3 py-2.5 text-sm transition-colors",s?"border-dashed border-border bg-muted/20 text-muted-foreground":"border-border bg-background text-foreground"),children:[e.jsx("button",{type:"button",...i,...l,className:"cursor-grab active:cursor-grabbing text-muted-foreground/40 hover:text-muted-foreground touch-none",title:"Arrastar pra reordenar",children:e.jsx(Gr,{className:"h-4 w-4"})}),e.jsx("span",{className:"flex-1 font-medium",children:a}),e.jsx("button",{type:"button",onClick:r,"aria-pressed":!s,title:s?"Oculta â clique pra mostrar":"VisÃvel â clique pra ocultar",className:Ce("h-4 w-4 roun
166ded-[4px] border flex items-center justify-center flex-shrink-0 transition-colors",s?"border-input hover:border-primary/50":"bg-primary border-primary text-primary-foreground"),children:!s&&e.jsx(Xt,{className:"h-2.5 w-2.5",strokeWidth:3})})]})}function rd({order:t,hidden:a,labels:s,onChange:r}){const i=Bd(Ud(Hd,{activationConstraint:{distance:4}})),l=new Set(a),d=u=>{const{active:m,over:x}=u;if(!x||m.id===x.id)return;const f=t.indexOf(String(m.id)),p=t.indexOf(String(x.id));f===-1||p===-1||r({order:Qd(t,f,p),hidden:a})},c=u=>{const m=l.has(u)?a.filter(x=>x!==u):[...a,u];r({order:t,hidden:m})};return e.jsx(Vd,{sensors:i,collisionDetection:Wd,onDragEnd:d,children:e.jsx(Gd,{items:t,strategy:Kd,children:e.jsx("div",{className:"space-y-1.5",children:t.map(u=>e.jsx(Db,{id:u,label:s[u]??u,hidden:l.has(u),onToggle:()=>c(u)},u))})})})}function Qn({children:t}){return e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1.5",children:"Pré-visualização"}),e.jsx("div",{className:"rounded-xl border border-border bg-muted/30 p-3",children:t})]})}function $b({order:t,hidden:a}){const s=new Set(a),r=t.filter(l=>!s.has(l)),i=r.length>0?r:["analise"];return e.jsx(Qn,{children:e.jsx("div",{className:"flex gap-1 flex-wrap",children:i.map((l,d)=>e.jsx("span",{className:Ce("px-2.5 py-1 rounded-md text-xs font-medium",d===0?"bg-primary/15 text-primary":"text-muted-foreground"),children:gi[l]??l},l))})})}const Pb="Status · Cotação · Sugestões";function Mb({order:t,hidden:a}){const s=new Set(a);return e.jsx(Qn,{children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg bg-background/60 border border-border px-2.5 py-1.5 text-xs text-muted-foreground",children:[e.jsx(Rr,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"truncate",children:[Pb," ",e.jsx("span",{className:"opacity-70",children:"(fixos)"})]})]}),t.map(r=>{const i=s.has(r);return e.jsxs("div",{className:Ce("flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs",i?"text-muted-foreground/50 line-through":"bg-background border border-border/60 text-foreground"),children:[i?e.jsx(kx,{className:"h-3 w-3 shrink-0"}):e.jsx(Zs,{className:"h-3 w-3 shrink-0 text-primary"}),e.jsx("span",{className:"truncate",children:Sd[r]??r})]},r)})]})})}function Tb({density:t,showPreview:a,showScore:s}){const r=t==="compact";return e.jsx(Qn,{children:e.jsx("div",{className:"rounded-lg border border-border bg-background overflow-hidden",children:[{name:"Ana Souza",phone:"(27) 99999-9999",score:82,msg:"Perfeito, vou confirmar e te aviso!"},{name:"Marcos Lima",phone:"(27) 98888-8888",score:41,msg:"Ainda tô decidindo, obrigado"}].map((i,l)=>e.jsxs("div",{className:Ce("flex items-start gap-2.5",r?"p-2":"p-3",l===0&&"border-b border-border"),children:[e.jsx("div",{className:Ce("rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-semibold shrink-0",r?"w-6 h-6":"w-8 h-8"),children:i.name.split(" ").map(d=>d[0]).join("")}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-xs font-medium text-foreground truncate",children:i.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate",children:[s?`Score ${i.score} · `:"",i.phone]}),a&&e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:i.msg})]})]},i.name))})})}function Ib({expandida:t}){return e.jsx(Qn,{children:e.jsxs("div",{className:"rounded-lg border border-border bg-background px-3 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1 text-[11px] font-semibold text-foreground",children:[t?e.jsx(dt,{className:"h-3 w-3"}):e.jsx(As,{className:"h-3 w-3"}),"Dados da cotação",e.jsx("span",{className:"text-muted-foreground font-normal",children:"3/14"})]}),t&&e.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:["Placa GDP7Q28","CPF","CEP 14940228"].map(a=>e.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:a},a))})]})})}function Lb({posicao:t}){const a=e.jsxs("div",{className:"flex items-center gap-1.5 rounded-md border border-border bg-muted/40 px-2 py-1",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] text-muted-foreground",children:[e.jsx(Fd,{className:"h-2.5 w-2.5"})," Coleta de Dados"]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] text-muted-foreground",children:[e.jsx(ot,{className:"h-2.5 w-2.5"})," Dados 3/14"]})]}),s=e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[70%] rounded-lg bg-primary/15 px-2 py-1 text-[10px] text-foreground",children:"Me dá só uns minutinhos..."})});return e.jsx(Qn,{children:e.jsxs("div",{className:"flex flex-col gap-1.5 rounded-lg border border-border bg-background p-2",children:[e.jsx("div",{className:"h-4 rounded bg-muted/60 px-1.5 flex items-center text-[9px] text-muted-foreground",children:"Maikan"}),t==="topo"&&a,s,t==="rodape"&&a,e.jsx("div",{className:"h-4 rounded border border-dashed border-border"})]})})}function Rb({onClose:t,companyId:a,isAdmin:s}){const{isDark:r,setDark:i}=Hm(),{tz:l,setTz:d}=Vm(),{layout:c}=Rn(),{user:u}=Sa(),m=(u==null?void 0:u.role)==="admin"||(u==null?void 0:u.role)==="super_admin"||(u==null?void 0:u.role)==="manager",x=(u==null?void 0:u.role)==="manager",[f,p]=n.useState("aparencia"),g=D=>{i(D),ri({theme:D?"dark":"light",timezone:l})},y=D=>{d(D),ri({theme:r?"dark":"light",timezone:D})},k=Ir(kd,c.tabsOrder),_=Ir(Cd,c.blocksOrder),N=!l,I=Intl.DateTimeFormat().resolvedOptions().timeZone,P=new Date().toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:cn()});return e.jsxs("div",{"data-testid":"inbox-settings",className:"flex-1 min-w-0 flex flex-col bg-muted/20 overflow-hidden",children:[e.jsxs("div",{className:"h-16 border-b bg-card flex items-center gap-3 px-5 flex-shrink-0",children:[t&&e.jsxs("button",{onClick:t,className:"flex items-center gap-1.5 rounded-lg border border-border px-2.5 py-1.5 text-sm font-medium text-foreground hover:bg-accent transition-colors",children:[e.jsx(Nx,{className:"h-4 w-4"}),"Voltar ao inbox"]}),e.jsx("h1",{className:"text-base font-semibold text-foreground",children:"Configurações"})]}),e.jsxs(vx,{value:f,onValueChange:p,className:"flex-1 min-h-0 flex flex-col",children:[e.jsx("div",{className:"border-b bg-card px-5 py-2.5 flex-shrink-0",children:e.jsx("div",{className:"max-w-6xl mx-auto",children:e.jsxs(jx,{className:"bg-transparent p-0 gap-1 justify-start",children:[e.jsxs(It,{value:"perfil",className:"gap-1.5",children:[e.jsx(ps,{className:"h-3.5 w-3.5"}),"Perfil"]}
166),e.jsxs(It,{value:"notificacoes",className:"gap-1.5",children:[e.jsx(Ko,{className:"h-3.5 w-3.5"}),"Notificações"]}),e.jsxs(It,{value:"integracoes",className:"gap-1.5",children:[e.jsx(wx,{className:"h-3.5 w-3.5"}),"Integrações"]}),e.jsx(It,{value:"aparencia",children:"Aparência"}),e.jsx(It,{value:"layout",children:"Layout do Inbox"}),m&&e.jsxs(e.Fragment,{children:[e.jsxs(It,{value:"agente",className:"gap-1.5",children:[e.jsx(Ge,{className:"h-3.5 w-3.5"}),"Agente"]}),e.jsxs(It,{value:"playbooks",className:"gap-1.5",children:[e.jsx(fa,{className:"h-3.5 w-3.5"}),"Playbooks"]}),e.jsxs(It,{value:"voz",className:"gap-1.5",children:[e.jsx(Ge,{className:"h-3.5 w-3.5"}),"Voz"]}),e.jsxs(It,{value:"automacoes",className:"gap-1.5",children:[e.jsx(Es,{className:"h-3.5 w-3.5"}),"Automações"]}),e.jsxs(It,{value:"workflow",className:"gap-1.5",children:[e.jsx(Fd,{className:"h-3.5 w-3.5"}),"Workflow"]}),e.jsxs(It,{value:"templates",className:"gap-1.5",children:[e.jsx(ot,{className:"h-3.5 w-3.5"}),"Templates"]})]}),(s||x)&&e.jsxs(It,{value:"cotacoes",className:"gap-1.5",children:[e.jsx(cs,{className:"h-3.5 w-3.5"}),"Cotações"]}),s&&e.jsxs(It,{value:"flags",className:"gap-1.5",children:[e.jsx(di,{className:"h-3.5 w-3.5"}),"Flags"]})]})})}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsx(Lt,{value:"perfil",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"max-w-6xl mx-auto px-5 py-6",children:e.jsx(n.Suspense,{fallback:e.jsx(La,{}),children:e.jsx(jb,{isAdmin:!!s,isManager:x})})})}),e.jsx(Lt,{value:"notificacoes",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"max-w-6xl mx-auto px-5 py-6",children:e.jsx(n.Suspense,{fallback:e.jsx(La,{}),children:e.jsx(yb,{})})})}),e.jsx(Lt,{value:"integracoes",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"max-w-6xl mx-auto px-5 py-6",children:e.jsx(n.Suspense,{fallback:e.jsx(La,{}),children:e.jsx(Nb,{isAdmin:!!s,isManager:x,companyId:a})})})}),e.jsx(Lt,{value:"aparencia",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"max-w-6xl mx-auto px-5 py-6",children:e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-5 items-start",children:[e.jsx(Uo,{icon:r?Hl:Vl,title:"Tema",desc:"Como o inbox aparece pra você.",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ns,{active:!r,onClick:()=>g(!1),icon:Vl,label:"Claro"}),e.jsx(Ns,{active:r,onClick:()=>g(!0),icon:Hl,label:"Escuro"})]})}),e.jsx(Uo,{icon:_t,title:"Fuso horário",desc:"Fuso usado pra mostrar o horário das mensagens. Não muda o horário em que a mensagem foi enviada, só como ele aparece pra você.",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ns,{active:N,onClick:()=>y(""),icon:Xx,label:`Local do navegador (${I})`}),e.jsxs("div",{className:Ce("flex items-center gap-2.5 rounded-xl border px-4 py-3 transition-colors",N?"border-border bg-background":"border-primary bg-primary/10"),children:[e.jsx(_t,{className:Ce("h-4 w-4 shrink-0",N?"text-muted-foreground":"text-primary")}),e.jsx("span",{className:"text-sm font-medium text-foreground shrink-0",children:"Fuso fixo"}),e.jsxs(Qo,{value:l||void 0,onValueChange:D=>y(D),children:[e.jsx(Jo,{className:"h-9 ml-auto w-[15rem]",children:e.jsx(Xo,{placeholder:"Escolher um fusoâ¦"})}),e.jsx(Zo,{children:Eb.map(D=>e.jsx(Qs,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("p",{"data-testid":"tz-now-preview",className:"text-xs text-muted-foreground px-1 pt-1",children:["Agora seriam ",e.jsx("span",{className:"font-semibold text-foreground",children:P}),N?" (local)":` (${l})`,". Dica: os relatórios do sistema usam BrasÃlia."]})]})})]})})}),e.jsx(Lt,{value:"layout",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"max-w-6xl mx-auto px-5 py-6",children:e.jsx(Uo,{icon:Gx,title:"Layout do Inbox",desc:"Arraste pra reordenar, clique na caixinha pra mostrar/ocultar. Vale pra você em qualquer dispositivo.",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6 items-start",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:"Abas do painel de análise"}),e.jsx(rd,{order:k,hidden:c.hiddenTabs,labels:gi,onChange:({order:D,hidden:V})=>wa({tabsOrder:D,hiddenTabs:V})})]}),e.jsx($b,{order:k,hidden:c.hiddenTabs})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6 items-start",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:"Blocos da aba Análise"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Score, cotação e sugestão de resposta ficam fora daqui â têm posição fixa."}),e.jsx(rd,{order:_,hidden:c.hiddenBlocks,labels:Sd,onChange:({order:D,hidden:V})=>wa({blocksOrder:D,hiddenBlocks:V})})]}),e.jsx(Mb,{order:_,hidden:c.hiddenBlocks})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6 items-start",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:"Densidade da lista de chats"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ns,{active:c.density==="comfortable",onClick:()=>wa({density:"comfortable"}),icon:af,label:"Confortável"}),e.jsx(Ns,{active:c.density==="compact",onClick:()=>wa({density:"compact"}),icon:sf,label:"Compacta"})]}),e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border bg-background px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Prévia da última mensagem"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Mostra um trecho da conversa embaixo do nome, na lista."})]}),e.jsx(an,{checked:c.showPreview,onCheckedChange:D=>wa({showPreview:D})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border bg-background px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Score na lista"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Mostra o score de fechamento junto da prévia."})]}),e.jsx(an,{checked:c.showScore,onCheckedChange:D=>wa({showScore:D})})]})]})]}),e.jsx(Tb,{density:c.density,showPreview:c.showPreview,showScore:c.showScore})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6 items-start",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:"Dados da cotação"}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-border bg-background px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Abrir a faixa por padrão"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ao entrar numa conversa, mostra a faixa de placa/CPF/veÃculo já expandida em vez de recolhida. Fora da fase de cotação â nela ela sempre abre, é o assunto do momento."})]}),e.jsx(an,{checked:c.cotacaoExpandidaPadrao,onCheckedChange:D=>wa({cotacaoExpandidaPadrao:D})})]})]}),e.jsx(Ib,{expandida:c.cotacaoExpandidaPadrao})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6 items-start",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:"Faixa de contexto do chat (desktop)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Onde a etapa do funil, a cotação e a proposta aparecem na tela da conversa. No celular ela sempre fica embaixo, colada no campo de resposta â a tela é curta demais pra abrir mão desse espaço lá."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ns,{active:c.barraContextoPosicao==="rodape",onClick:()=>wa({barraContextoPosicao:"rodape"}),icon:Zx,label:"Embaixo (padrão)"}),e.jsx(Ns,{active:c.barraContextoPosicao==="topo",onClick:()=>wa({barraContextoPosicao:"topo"}),icon:Yx,label:"No topo"})]})]}),e.jsx(Lb,{posicao:c.barraContextoPosicao})]})]})})})}),m&&e.jsxs(e.Fragment,{children:[e.jsx(Lt,{value:"agente",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"px-5 py-6",children:e.jsx(n.Suspense,{fallback:e.jsx(La,{}),children:e.jsx(wb,{})})})}),e.jsx(Lt,{value:"playbooks",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"px-5 py-6",children:e.jsx(n.Suspense,{fallback:e.jsx(La,{}),children:e.jsx(kb,{embedded:!0})})})}),e.jsx(Lt,{value:"voz",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"px-5 py-6",children:e.jsx(n.Suspense,{fallback:e.jsx(La,{}),children:e.jsx(Cb,{})})})}),e.jsx(Lt,{value:"automacoes",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"px-5 py-6",children:e.jsx(n.Suspense,{fallback:e.jsx(La,{}),children:e.jsx(Sb,{embedded:!0})})})}),e.jsx(Lt,{value:"workflow",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"px-5 py-6",children:e.jsx(n.Suspense,{fallback:e.jsx(La,{}),children:e.jsx(_b,{embedded:!0})})})}),e.jsx(Lt,{value:"templates",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"px-5 py-6",children:e.jsx(n.Suspense,{fallback:e.jsx(La,{}),children:e.jsx(Ab,{embedded:!0})})})})]}),(s||x)&&e.jsx(Lt,{value:"cotacoes",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"max-w-6xl mx-auto px-5 py-6",children:e.jsx(vb,{c
166ompanyId:a??void 0})})}),s&&e.jsx(Lt,{value:"flags",className:"mt-0 focus-visible:outline-none",children:e.jsx("div",{className:"max-w-6xl mx-auto px-5 py-6",children:e.jsx(yx,{companyId:a??void 0})})})]})]})]})}const Ob=["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"],Fb=(t,a)=>`${Ob[t]??"?"} ${a}h`;function zb({leadId:t}){const[a,s]=n.useState(null),[r,i]=n.useState(!0),[l,d]=n.useState(!1),c=n.useRef(null);return n.useEffect(()=>{var m;if(!t)return;(m=c.current)==null||m.abort();const u=new AbortController;return c.current=u,i(!0),d(!1),ux(t,u.signal).then(s).catch(x=>{x instanceof DOMException&&x.name==="AbortError"||d(!0)}).finally(()=>{c.current===u&&i(!1)}),()=>u.abort()},[t]),r?e.jsx("div",{className:"rounded-lg border border-border p-3 animate-pulse",children:e.jsx("div",{className:"h-3 w-32 bg-muted rounded"})}):l||!a?null:e.jsxs("div",{className:"rounded-lg border border-border p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground mb-2",children:[e.jsx(_t,{className:"w-3.5 h-3.5"}),"Melhor horário pra falar"]}),a.enoughData&&a.topSlots.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.topSlots.map(u=>e.jsx("span",{className:"px-2 py-0.5 rounded-md bg-primary/10 text-primary text-xs font-medium",children:Fb(u.dayOfWeek,u.hour)},`${u.dayOfWeek}-${u.hour}`))}),e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-1.5",children:["Baseado em ",a.totalInbound," mensagens deste contato."]})]}):e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Histórico ainda curto pra sugerir horário (",a.totalInbound," msg)."]})]})}function Vn(t){if(t.unavailable)return`${t.seguradora||"Seguradora"} · sem PDF`;if(t.source==="seguradora")return t.seguradora||"Seguradora";const a=(t.filename||"").replace(/\.pdf$/i,"").replace(/[-_]/g," ").trim();return t.source==="comparativo"?a||"Comparativo":a||"Enviado"}const qb={comparativo:"PDF comparativo que geramos",enviado:"PDF já enviado ao cliente",seguradora:"PDF oficial da seguradora (o cliente não recebeu)"},Yu={comparativo:"Nosso comparativo",enviado:"Enviado ao cliente",seguradora:"Oficial da seguradora"},od={sessao_morta:"A sessão do SGCOR caiu e só o time de operações consegue reautenticar â avise em vez de tentar de novo, reclicar não resolve sozinho."},em={integracao_direta:"Cotamos direto com a seguradora e esta cotação não tem PDF dela. Re-cotar já traz o PDF quando a seguradora oferece;
166 o nosso comparativo cobre o cliente.",link_invalido:"A seguradora devolveu um link de PDF que não dá pra abrir. Vale reportar."};function Bb(t,a){const[s,r]=n.useState([]),[i,l]=n.useState(null),[d,c]=n.useState(null),[u,m]=n.useState(!1),[x,f]=n.useState(0),[p,g]=n.useState([]),[y,k]=n.useState({});n.useEffect(()=>{let D=!0;if(r([]),l(null),f(0),g([]),k({}),!!t)return Bp(t).then(V=>{D&&r(V)}),()=>{D=!1}},[t]),n.useEffect(()=>{if(a&&!i){const D=s.filter(M=>!M.unavailable),V=M=>M.source!=="seguradora"||M.cached===!0,R=D.find(V)||D[0];R&&l(R.id)}},[a,i,s]),n.useEffect(()=>{let D=!0,V=null;const R=i;return c(null),a&&t&&R&&(m(!0),Up(t,R).then(({url:M,reason:$})=>{if(D){if(M){V=M,c(M);return}g(C=>C.includes(R)?C:[...C,R]),k(C=>({...C,[R]:$}))}}).finally(()=>D&&m(!1))),()=>{D=!1,V&&URL.revokeObjectURL(V)}},[a,t,i,x]),n.useEffect(()=>{if(!a||!i||d||u||x!==0||!p.includes(i))return;const D=s.find(V=>!V.unavailable&&V.id!==i&&!p.includes(V.id));D&&l(D.id)},[a,i,d,u,x,p,s]);const _=n.useCallback(D=>{l(D),f(0),g(V=>V.filter(R=>R!==D)),k(V=>{const{[D]:R,...M}=V;return M})},[]),N=n.useCallback(()=>f(D=>D+1),[]),I=n.useMemo(()=>s.find(D=>D.id===i)||null,[s,i]),P=n.useMemo(()=>s.filter(D=>p.includes(D.id)&&D.id!==i).map(Vn),[s,p,i]);return{items:s,openableCount:s.filter(D=>!D.unavailable).length,selectedId:i,selected:I,url:d,loading:u,failed:!!i&&p.includes(i),failReason:(i&&p.includes(i)?y[i]:null)??null,attempt:x,falharamSemPedido:P,select:_,retry:N}}function Ub(t){var a;return(a=t==null?void 0:t.id)!=null&&a.startsWith("suhai:")?Zd(t.id.slice(6)):null}function id(t){try{return new Date(t).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return t}}function Hb({source:t,className:a}){return t==="seguradora"?e.jsx(ln,{className:a}):t==="enviado"?e.jsx(xa,{className:a}):e.jsx(Ux,{className:a})}function Vb({item:t,active:a,onSelect:s}){const r=!!t.unavailable;return e.jsxs("button",{type:"button",disabled:r,onClick:()=>!r&&s(),"aria-pressed":a,title:r?`Sem PDF oficial. ${em[t.reason||"integracao_direta"]||""}`:`${qb[t.source||"enviado"]||""} · ${id(t.created_at)}`,className:`shrink-0 flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-left transition-colors ${r?"border-dashed border-border text-muted-foreground/60 cursor-not-allowed":a?"border-primary bg-primary/10":"border-border hover:bg-muted/50"}`,children:[e.jsx(Hb,{source:t.source,className:`w-4 h-4 shrink-0 ${a?"text-primary":"text-muted-foreground"}`}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:`block text-[11px] font-semibold leading-tight capitalize ${a?"text-primary":""}`,children:Vn(t)}),e.jsx("span",{className:"block text-[10px] leading-tight text-muted-foreground",children:r?"sem PDF":`${Yu[t.source||"enviado"]||""} · ${id(t.created_at)}`})]})]})}function Sr({icon:t,label:a,onClick:s,href:r,download:i}){const l="inline-flex items-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground";return r?e.jsxs("a",{href:r,download:i,target:i?void 0:"_blank",rel:"noopener noreferrer",className:l,title:a,children:[e.jsx(t,{className:"w-3.5 h-3.5"})," ",a]}):e.jsxs("button",{type:"button",onClick:s,className:l,title:a,children:[e.jsx(t,{className:"w-3.5 h-3.5"})," ",a]})}function Wb(){return e.jsx("p",{className:"mx-3 mt-2 shrink-0 rounded border border-warning/40 bg-warning/10 px-2 py-1 text-[11px] leading-snug text-warning-text",children:"Documento interno. à o cálculo completo da seguradora: traz todas as combinações de cobertura do produto (inclusive as que não foram oferecidas) e os valores à vista, não o parcelado que o cliente recebeu. Para mandar preço ao cliente, use o comparativo."})}function ld({state:t,onRetry:a,className:s}){var p;const{url:r,loading:i,failed:l,failReason:d,attempt:c,openableCount:u,items:m,selected:x,falharamSemPedido:f}=t;return i||!r&&!l&&u>0?e.jsxs("div",{className:`flex items-center justify-center gap-2 text-xs text-muted-foreground ${s||""}`,children:[e.jsx(le,{className:"w-4 h-4 animate-spin"})," Carregando PDFâ¦"]}):r?e.jsx("iframe",{src:r,title:x?`Cotação · ${Vn(x)}
166`:"Cotação",className:`w-full bg-white ${s||""}`}):u===0?e.jsxs("div",{className:`flex flex-col items-center justify-center gap-2 px-6 text-center ${s||""}`,children:[e.jsx(ot,{className:"w-8 h-8 text-muted-foreground/40"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Nenhuma seguradora desta cotação emitiu PDF oficial.",e.jsx("br",{}),em[((p=m[0])==null?void 0:p.reason)||"integracao_direta"]]})]}):e.jsxs("div",{className:`flex flex-col items-center justify-center gap-2 px-6 text-center ${s||""}`,children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:d&&od[d]?od[d]:c===0?"Não consegui carregar o PDF agora.":"Ainda não veio. A seguradora à s vezes demora pra gerar o arquivo."}),f.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground/80",children:["Também não abriu: ",f.join(", "),"."]}),e.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(jt,{className:"w-3 h-3"})," Tentar de novo"]})]})}function Gb({state:t}){const[a,s]=n.useState(!1),{items:r,openableCount:i,selectedId:l,selected:d,url:c,falharamSemPedido:u,select:m,retry:x}=t;if(n.useEffect(()=>{if(!a)return;const g=y=>{y.key==="Escape"&&s(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[a]),r.length===0)return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-2 px-8 text-center",children:[e.jsx(ot,{className:"w-8 h-8 text-muted-foreground/40"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nenhum PDF de cotação para este lead ainda."}),e.jsx("p",{className:"text-[11px] text-muted-foreground/70",children:"Assim que uma cotação rodar, o comparativo e os PDFs das seguradoras aparecem aqui."})]});const f=(d==null?void 0:d.filename)||"cotacao.pdf",p=Ub(d);return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-muted-foreground",children:i===1?"1 documento":`${i} documentos`}),c&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Sr,{icon:Cx,label:"Tela cheia",onClick:()=>s(!0)}),e.jsx(Sr,{icon:Kn,label:"Nova aba",href:c}),e.jsx(Sr,{icon:On,label:"Baixar",href:c,download:f}),p&&e.jsx(Sr,{icon:ln,label:"Abrir no portal",href:p})]})]}),e.jsx("div",{className:"flex shrink-0 gap-1.5 overflow-x-auto border-b border-border px-3 py-2 scrollbar-none",children:r.map(g=>e.jsx(Vb,{item:g,active:l===g.id,onSelect:()=>m(g.id)},g.id))}),(d==null?void 0:d.source)==="seguradora"&&e.jsx(Wb,{}),c&&u.length>0&&e.jsxs("p",{className:"shrink-0 px-3 pt-2 text-[11px] text-muted-foreground",children:[u.join(", ")," não abriu agora (a seguradora gera o PDF na hora e à s vezes falha). Mostrando ",d?Vn(d):"outro documento","."]}),e.jsx(ld,{state:t,onRetry:x,className:"min-h-0 flex-1"}),a&&Nd.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[60] flex flex-col bg-black/80 backdrop-blur-sm",role:"dialog","aria-modal":"true","aria-label":"PDF da cotação em tela cheia",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 px-4 py-2 text-white",children:[e.jsxs("span",{className:"truncate text-sm font-semibold",children:[d?Vn(d):"Cotação",(d==null?void 0:d.source)&&e.jsx("span",{className:"ml-2 text-xs font-normal text-white/60",children:Yu[d.source]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p&&e.jsxs("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 rounded-md border border-white/25 px-2 py-1 text-[11px] text-white/85 hover:bg-white/10",children:[e.jsx(ln,{className:"w-3.5 h-3.5"})," Abrir no portal"]}),e.jsxs("a",{href:c||void 0,download:f,className:"inline-flex items-center gap-1 rounded-md border border-white/25 px-2 py-1 text-[11px] text-white/85 hover:bg-white/10",children:[e.jsx(On,{className:"w-3.5 h-3.5"})," Baixar"]}),e.jsx("button",{type:"button",onClick:()=>s(!1),title:"Fechar (Esc)",className:"rounded-md border border-white/25 p-1 text-white/85 hover:bg-white/10",children:e.jsx(vt,{className:"w-4 h-4"})})]})]}),(d==null?void 0:d.source)==="seguradora"&&e.jsx("p",{className:"mx-4 mb-2 rounded border border-warning/50 bg-warning/20 px-2 py-1 text-[11px] leading-snug text-warning-text",children:"Documento interno: cálculo completo da seguradora, com combinações que não foram oferecidas e valores à vista. Não é o que o cliente recebeu."}),e.jsx(ld,{state:t,onRetry:x,className:"mx-4 mb-4 min-h-0 flex-1 rounded-lg"})]}),document.body)]})}function Ws({label:t,value:a,title:s}){return e.jsxs("div",{className:"ls-kv",children:[e.jsx("span",{className:"ls-kv-label",children:t}),e.jsx("span",{className:"ls-kv-value truncate",title:s??a??void 0,children:a||"â"})]})}function Kb(t){if(!t)return null;try{const a=new URL(t),s=a.pathname==="/"?"":a.pathname;return`${a.hostname.replace(/^www\./,"")}${s}`.slice(0,42)}catch{return t.slice(0,42)}}function Qb({leadId:t,source:a,referral:s}){var p,g;const[r,i]=n.useState(null),[l,d]=n.useState(!1),c=n.useRef(null);n.useEffect(()=>{var k;if(!t)return;(k=c.current)==null||k.abort();const y=new AbortController;return c.current=y,i(null),d(!1),mx(t,y.signal).then(i).catch(_=>{_ instanceof DOMException&&_.name==="AbortError"||d(!0)}),()=>y.abort()},[t]);const u=(r==null?void 0:r.publisherPlatform)??((((p=r==null?void 0:r.publisherPlatforms)==null?void 0:p.length)??0)>1?"mixed":null),m=Ei(a,s,u);if(l&&!s||!r&&!s)return null;const x=r!=null&&r.utmSource||r!=null&&r.utmMedium?`${r.utmSource||"â"} / ${r.utmMedium||"â"}`:null,f=m?e.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded font-medium ${m.className}`,title:m.tooltip,children:m.label}):e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded font-medium bg-muted text-muted-foreground",children:"Sem origem"});return r&&!r.hasAttribution?e.jsxs("div",{className:"ls-section",children:[e.jsxs("div",{className:"ls-section-title",children:[e.jsx(en,{className:"w-3 h-3"})," Origem do tráfego"]}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[f,e.jsx("span",{children:"sem rastro de campanha â entrou direto no WhatsApp."})]})]}):e.jsxs("div",{className:"ls-section",children:[e.jsxs("div",{className:"ls-section-title",children:[e.jsx(en,{className:"w-3 h-3"})," Origem do tráfego"]}),e.jsxs("div",{className:"ls-kv",children:[e.jsx("span",{className:"ls-kv-label",children:"Canal"}),e.jsx("span",{className:"ls-kv-value",children:f})]}),(((g=r==null?void 0:r.publisherPlatforms)==null?void 0:g.length)??0)>1&&e.jsx(Ws,{label:"Entregue em",value:r.publisherPlatforms.join(" + "),title:"Plataformas em que este ANÃNCIO roda. A Meta não informa por qual delas cada lead entrou."}),e.jsx(Ws,{label:"Campanha",value:(r==null?void 0:r.campaignName)??null}),e.jsx(Ws,{label:"Criativo",value:(r==null?void 0:r.creativeName)??(s==null?void 0:s.headline)??null}),e.jsx(Ws,{label:"Conjunto",value:(r==null?void 0:r.adsetName)??null}),e.jsxs("div",{className:"ls-kv",children:[e.jsx("span",{className:"ls-kv-label",children:"utm source/medium"}),e.jsxs("span",{className:"ls-kv-value truncate",title:r!=null&&r.utmInferred?"Inferido do Click-to-WhatsApp: o link do anúncio não tem utm. Taguear o link substitui o palpite pelo dado.":void 0,children:[x||"â",(r==null?void 0:r.utmInferred)&&x&&e.jsx("span",{className:"ml-1 font-normal text-muted-foreground",children:"(inferido)"})]})]}),e.jsx(Ws,{label:"Veio de",value:Kb((r==null?void 0:r.sourceUrl)??(s==null?void 0:s.source_url)??null),title:(r==null?void 0:r.sourceUrl)??(s==null?void 0:s.source_url)??void 0}),e.jsx(Ws,{label:"Anúncio (ID)",value:(r==null?void 0:r.adId)??(s==null?void 0:s.source_id)??null,title:"ad_id na Meta â é por ele que o custo (Insights) e o CAPI casam com este lead"}),r&&r.resolvedFrom==="referral"&&e.jsx("p",{className:"mt-2 text-[10px] text-muted-foreground",children:"Nome da campanha/conjunto aparece quando a conta de anúncios Meta estiver conectada."}),((r==null?void 0:r.adHeadline)||(r==null?void 0:r.adBody)||(s==null?void 0:s.headline)||(s==null?void 0:s.body))&&e.jsxs("details",{className:"mt-2 group",children:[e.jsx("summary",{className:"cursor-pointer text-[10px] uppercase tracking-wide text-muted-foreground",children:"Texto do anúncio"}),e.jsxs("div",{className:"mt-1.5 rounded-md bg-primary/5 px-2 py-1.5",children:[((r==null?void 0:r.adHeadline)||(s==null?void 0:s.headline))&&e.jsx("p",{className:"text-xs font-medium text-foreground",children:(r==null?void 0:r.adHeadline)||(s==null?void 0:s.headline)}),((r==null?void 0:r.adBody)||(s==null?void 0:s.body))&&e.jsx("p",{className:"text-[11px] text-muted-foreground whitespace-pre-line",children:(r==null?void 0:r.adBody)||(s==null?void 0:s.body)})]})]})]})}const Jb="https://leadsense.solutions/api/analysis",Xb={cotar_proposta:"Cotação calculada",resolver_placa:"Placa consultada",buscaPlaca:"Placa consultada",buscar_leads:"Leads consultados",buscar_lead:"Lead consultado",buscar_produtos:"Produtos consultados",buscar_playbook:"Playbook consultado",buscar_metricas:"Métricas consultadas"};function Zb(t){return Xb[t]||"Consulta ao sistema"}async function Yb(t,a,s){const r=localStorage.getItem("authToken");if(!r)throw new Error("Não autenticado. Faça login primeiro.");const i=await fetch(`${Jb}/agent/chat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}
166,body:JSON.stringify({message:t,leadId:s||null,history:a.slice(-10).map(l=>({role:l.role==="tool"||l.role==="agent"?"assistant":l.role,content:l.content}))})});if(!i.ok){const l=await i.json().catch(()=>({}));throw new Error(l.detail||`Erro ${i.status}`)}return i.json()}function ev({leadId:t}){const[a,s]=n.useState([{role:"system",content:"Assistente LeadSense pronto. Pergunte sobre produtos, leads, playbooks ou qualquer dado do sistema.",ts:Date.now()}]),[r,i]=n.useState(""),[l,d]=n.useState(!1),c=n.useRef(null),u=n.useRef(null);n.useEffect(()=>{const x=c.current;x&&requestAnimationFrame(()=>{x.scrollTop=x.scrollHeight})},[a,l]);const m=n.useCallback(async()=>{var g;const x=r.trim();if(!x||l)return;const f={role:"user",content:x,ts:Date.now()},p=[...a,f];s(p),i(""),u.current&&(u.current.style.height="38px"),d(!0);try{const y=await Yb(x,a,t),k=(y.toolCalls||[]).map(_=>({role:"tool",content:Zb(_.tool),ts:Date.now()}));s(_=>[..._,...k,{role:"agent",content:y.reply,ts:Date.now()}])}catch(y){s(k=>[...k,{role:"system",content:He(y),ts:Date.now()}])}finally{d(!1),(g=u.current)==null||g.focus()}},[r,l,a,t]);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border flex items-start gap-2",children:[e.jsx(Ge,{className:"w-4 h-4 text-primary mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold leading-tight",children:"Agente LeadSense"}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-tight mt-0.5",children:"Consulte produtos, leads e playbooks. O agente busca no banco pra responder."})]})]}),e.jsxs("div",{ref:c,className:"flex-1 overflow-y-auto scrollbar-none px-3 py-3 space-y-2",children:[a.map((x,f)=>{if(x.role==="system")return e.jsx("div",{className:"text-[11px] text-muted-foreground text-center py-1 px-2",children:x.content},f);if(x.role==="tool")return e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground px-2 py-1",children:[e.jsx(Ua,{className:"w-3 h-3 flex-shrink-0"}),e.jsx("span",{className:"break-words min-w-0",children:x.content})]},f);const p=x.role==="user";return e.jsx("div",{className:`flex ${p?"justify-end":"justify-start"}`,children:e.jsx("div",{className:`max-w-[85%] rounded-2xl px-3 py-2 text-sm break-words ${p?"bg-primary text-primary-foreground rounded-br-sm whitespace-pre-wrap":"bg-muted text-foreground rounded-bl-sm"}`,children:p?x.content:e.jsx("div",{className:"leading-relaxed [&_p]:mb-1.5 [&_p:last-child]:mb-0 [&_strong]:font-semibold [&_ul]:list-disc [&_ul]:pl-4 [&_ul]:my-1 [&_ol]:list-decimal [&_ol]:pl-4 [&_ol]:my-1 [&_li]:mb-0.5 [&_code]:text-xs [&_code]:bg-foreground
166/10 [&_code]:px-1 [&_code]:rounded",children:e.jsx(Sx,{remarkPlugins:[_x],children:x.content})})})},f)}),l&&e.jsx("div",{className:"flex justify-start",children:e.jsxs("div",{className:"bg-muted rounded-2xl rounded-bl-sm px-3 py-2 flex items-center gap-1",children:[e.jsx(le,{className:"w-3.5 h-3.5 animate-spin text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"pensandoâ¦"})]})})]}),e.jsxs("div",{className:"border-t border-border p-2 flex items-end gap-2",children:[e.jsx("textarea",{ref:u,value:r,onChange:x=>{i(x.target.value),x.currentTarget.style.height="38px",x.currentTarget.style.height=Math.min(x.currentTarget.scrollHeight,96)+"px"},onKeyDown:x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),m())},placeholder:"Ex: Quais produtos temos cadastrados?",rows:1,className:"flex-1 resize-none bg-muted/50 border border-border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary",style:{height:38,maxHeight:96}}),e.jsx("button",{onClick:()=>void m(),disabled:l||!r.trim(),className:"flex-shrink-0 w-9 h-9 rounded-lg bg-primary text-primary-foreground flex items-center justify-center disabled:opacity-40 transition-opacity",title:"Enviar",children:e.jsx(xa,{className:"w-4 h-4"})})]})]})}const tv=[{tool:"search_products",label:"Buscar produtos",desc:"Encontra produtos/planos cadastrados da empresa por nome ou descrição.",icon:Ax},{tool:"get_lead_info",label:"Dados de um lead",desc:"Score, classificação e contexto do lead em conversa.",icon:rf},{tool:"list_playbooks",label:"Listar playbooks",desc:"Playbooks de venda disponÃveis pra empresa.",icon:Ex},{tool:"get_recent_leads",label:"Leads recentes",desc:"Lista os leads mais recentes com seus scores.",icon:bi}];function av(){return e.jsxs("div",{className:"px-4 py-4 space-y-4 overflow-y-auto scrollbar-none",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ge,{className:"w-4 h-4 text-primary mt-0.5 flex-shrink-0"}),e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["O ",e.jsx("strong",{className:"text-foreground",children:"Agente LeadSense"})," responde suas perguntas consultando o banco de dados em tempo real. Pergunte em linguagem natural na aba ",e.jsx("strong",{className:"text-foreground",children:"Chat"}),", ele decide sozinho quais consultas fazer."]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2",children:"O que ele consegue consultar"}),e.jsx("div",{className:"space-y-1.5",children:tv.map(t=>{const a=t.icon;return e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-border bg-card px-3 py-2",children:[e.jsx("span",{className:"w-7 h-7 rounded-md bg-primary/10 text-primary flex items-center justify-center flex-shrink-0",children:e.jsx(a,{className:"w-3.5 h-3.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold leading-tight",children:t.label}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-tight mt-0.5",children:t.desc})]})]},t.tool)})})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"Quando um chat está selecionado, o assistente recebe o lead como contexto, dá pra perguntar coisas como âqual o score desse lead?â ou âque produto encaixa pra ele?â."})]})}function sv(t){const a=String(t||"").toLowerCase();return a==="admin"||a==="super_admin"||a==="manager"||a==="marketing"}function Mr(t){const a=String(t||"").replace(/\D/g,""),s=a.match(/^(\d{2})(\d{2})(\d{4,5})(\d{4})$/);return s?`+${s[1]} ${s[2]} ${s[3]}-${s[4]}`:a}const cd="Olá! Quero saber mais.";function nv(t,a="Falar no WhatsApp"){return`<a href="${String(t).replace(/&/g,"&")}" target="_blank" rel="noopener">${a}</a>`}function dd({valor:t,rotulo:a="Copiar link",icone:s}){const[r,i]=n.useState(!1);return e.jsxs("button",{type:"button",className:"ls-copy-btn inline-flex items-center gap-1",onClick:()=>{var l;(l=navigator.clipboard)==null||l.writeText(t).then(()=>{i(!0),setTimeout(()=>i(!1),1500)},()=>{})},children:[r?e.jsx(Xt,{className:"w-3 h-3"}):s||e.jsx(ru,{className:"w-3 h-3"}),r?"Copiado":a]})}function rv({qr:t}){return t.erro?e.jsxs("div",{className:"rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(Ba,{className:"w-3.5 h-3.5"}),t.label||Mr(t.phone)]}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:t.erro})]}):e.jsxs("div",{className:"rounded-lg border border-border p-3",children:[e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"text-sm font-medium",children:t.label||"Número"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Mr(t.phone)})]}),t.qr&&e.jsx("img",{src:t.qr,alt:`QR code do número ${Mr(t.phone)}`,className:"w-40 h-40 rounded bg-white p-1"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(dd,{valor:t.link}),e.jsx(dd,{valor:nv(t.link),rotulo:"Copiar botão do site",icone:e.jsx(Dx,{className:"w-3 h-3"})}),t.qrSvg&&e.jsxs("a",{className:"ls-copy-btn inline-flex items-center gap-1",href:`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t.qrSvg)}`,download:`qr-${t.phone}.svg`,children:[e.jsx(On,{className:"w-3 h-3"})," Baixar SVG"]})]}),e.jsx("p",{className:"mt-2 break-all text-[11px] leading-tight text-muted-foreground",children:t.link})]})}function ov(){const{user:t}=Sa(),a=sv(t==null?void 0:t.role),[s,r]=n.useState(null),[i,l]=n.useState(null),[d,c]=n.useState(cd),[u,m]=n.useState(!1),[x,f]=n.useState(!1),[p,g]=n.useState(null),y=n.useCallback(()=>{a&&(m(!0),g(null),sc.numeros().then(N=>{var P;r(N.numeros);const I=(P=N.numeros.find(D=>D.texto))==null?void 0:P.texto;I&&c(I)}).catch(N=>g(N.message)).finally(()=>m(!1)))},[a]);n.useEffect(y,[y]);const k=()=>{f(!0),g(null),sc.gerarTodos(d.trim()||void 0).then(N=>{l(N.numeros),y()}).catch(N=>g(N.message)).finally(()=>f(!1))},_=i||(s||[]).filter(N=>!!N.gerado&&!!N.link&&!!N.token).map(N=>({seller_id:N.seller_id,phone:N.phone,label:N.label,status:N.status,token:N.token,marker:N.marker||"",link:N.link,qr:N.qr??null,qrSvg:N.qrSvg??null}));return a?e.jsxs("div",{className:"ls-tabpane space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Link e QR de entrada por número"}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Um endereço para cada número da empresa: use no ",e.jsx("strong",{children:"botão do site"}),", na bio ou impresso como QR. Quem entra por ele abre o WhatsApp com a frase já escrita e o lead entra atribuÃdo ",e.jsx("strong",{children:"à quele número"}),"."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium",htmlFor:"qr-frase",children:"Frase que o cliente envia"}),e.jsx("textarea",{id:"qr-frase",className:"ls-input mt-1 w-full text-xs",rows:2,value:d,onChange:N=>c(N.target.value),placeholder:cd}),e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"Ela aparece escrita pro cliente antes de ele enviar. Um marcador invisÃvel de origem é acrescentado ao final."})]}),u&&!s&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(le,{className:"w-3.5 h-3.5 animate-spin"})," Carregando os númerosâ¦"]}),s&&s.length===0&&e.jsxs("div",{className:"rounded-lg border border-border p-3 text-xs text-muted-foreground",children:["Nenhum número Cloud ativo nesta empresa. Conecte um em ",e.jsx("strong",{children:"WhatsApp â Números"}),"."]}),s&&s.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[s.length," número",s.length>
1661?"s":""," ativo",s.length>1?"s":"",":"," ",s.map(N=>N.label||Mr(N.phone)).join(", ")]}),e.jsxs("button",{type:"button",className:"ls-use-btn inline-flex items-center justify-center gap-2",onClick:k,disabled:x,children:[x?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(nx,{className:"w-4 h-4"}),x?"Gerandoâ¦":`Gerar link e QR de todos os números (${s.length})`]}),s.some(N=>N.gerado)&&!i&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Já existe link gerado para ",s.filter(N=>N.gerado).length," deste",s.length>1?"s números":" número"," â está abaixo, pronto pra copiar. Gerar de novo devolve o ",e.jsx("strong",{children:"mesmo"})," link e o ",e.jsx("strong",{children:"mesmo"})," QR: o que já está impresso continua valendo. Só a frase muda."]})]}),p&&e.jsx("div",{className:"rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-xs",children:p}),_.length>0&&e.jsx("div",{className:"space-y-3",children:_.map(N=>e.jsx(rv,{qr:N},N.seller_id))})]}):e.jsx("div",{className:"ls-tabpane",children:e.jsx("div",{className:"ls-empty-state",children:"Gerar QR de entrada é ação de gestor."})})}function iv(t){if(!t)return"";const a=Date.now()-new Date(t).getTime(),s=Math.floor(a/6e4);if(s<1)return"agora";if(s<60)return`${s}m`;const r=Math.floor(s/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function lv({companyId:t,onSelectPhoneInChat:a}){const[s,r]=n.useState([]),[i,l]=n.useState(!1),[d,c]=n.useState(null),[u,m]=n.useState({}),[x,f]=n.useState(!1),p=n.useCallback(async()=>{l(!0),c(null);try{const y=await Ip({companyId:t});r(y),y.length>0?(f(!0),Ld(y,t).then(m).catch(()=>m({})).finally(()=>f(!1))):m({})}catch(y){console.error("[PrioridadesTab] load:",y),c("Não consegui carregar agora.")}finally{l(!1)}},[t]);n.useEffect(()=>{p()},[p]);const g=n.useCallback(async(y,k)=>{var N;y.stopPropagation();const _=((N=s.find(I=>I.id===k))==null?void 0:N.favoritedAt)??null;r(I=>I.map(P=>P.id===k?{...P,favoritedAt:_?null:new Date().toISOString()}:P));try{await vi(k,t)}catch(I){console.error("[PrioridadesTab] toggleFavorite:",I),r(P=>P.map(D=>D.id===k?{...D,favoritedAt:_}:D))}},[s,t]);return e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 pt-2 pb-2 border-b border-border flex-shrink-0",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Conversas recentes e favoritadas"}),e.jsx("button",{onClick:p,disabled:i,className:"p-1 rounded-full text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40",title:"Atualizar",children:e.jsx(jt,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-none",children:i&&s.length===0?e.jsx("div",{className:"p-3 space-y-2",children:Array.from({length:4}).map((y,k)=>e.jsx("div",{className:"h-14 rounded-lg bg-muted animate-pulse"},k))}):d?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-10 px-4",children:d}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-10 px-4",children:"Nenhuma conversa recente ou favoritada ainda."}):e.jsx("div",{className:"p-2 space-y-1",children:s.map(y=>{const k=u[y.id];return e.jsxs("button",{onClick:()=>{y.phone&&(a==null||a(y.phone))},className:"w-full text-left flex items-start gap-2 p-2.5 rounded-lg border hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:Fn(y.name||void 0,y.phone||void 0,y.id)}),e.jsx("span",{className:"text-[10px] text-muted-foreground flex-shrink-0",children:iv(y.lastContactAt)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5 truncate",children:k===void 0&&x?"Gerando recapâ¦":k===null?"Sem análise ainda":k||""})]}),e.jsx("button",{onClick:_=>g(_,y.id),title:y.favoritedAt?"Remover dos favoritos":"Favoritar",className:"flex-shrink-0 p-1 rounded-full",children:e.jsx(Ha,{className:`w-3.5 h-3.5 ${y.favoritedAt?"fill-warning text-warning-text":"text-muted-foreground
166/40"}`})})]},y.id)})})})]})}const ud="https://leadsense.solutions/api/analysis",Ho="leadsense_analysis_";function cv(t={}){const{cacheEnabled:a=!0,debounceMs:s=1500}=t,[r,i]=n.useState(null),[l,d]=n.useState(!1),[c,u]=n.useState(null),[m,x]=n.useState(!1),f=n.useRef(null),p=n.useRef(null),g=n.useRef(null),y=n.useRef(null),k=n.useCallback(R=>{if(!a)return null;try{const M=localStorage.getItem(`${Ho}${R}`);if(M){const $=JSON.parse(M);if(Date.now()-$.timestamp<10*60*1e3)return $}}catch(M){console.error("[useAnalysis] Error reading cache:",M)}return null},[a]),_=n.useCallback((R,M,$)=>{if(a)try{const C={analysis:M,messageCount:$,timestamp:Date.now()};localStorage.setItem(`${Ho}${R}`,JSON.stringify(C))}catch(C){console.error("[useAnalysis] Error saving cache:",C)}},[a]),N=n.useCallback(()=>{var R;(R=p.current)!=null&&R.leadId&&localStorage.removeItem(`${Ho}${p.current.leadId}`),i(null),x(!1),u(null)},[]),I=n.useCallback(async R=>{var C;g.current&&g.current.abort(),g.current=new AbortController,d(!0),u(null);const M=localStorage.getItem("authToken"),$={"Content-Type":"application/json",...M?{Authorization:`Bearer ${M}`}:{}};try{console.log("[useAnalysis] Sending analysis request for:",R.leadId);const b=await fetch(`${ud}/analyze/smart`,{method:"POST",headers:$,body:JSON.stringify(R),signal:g.current.signal});if(!b.ok){const F=await b.text();console.error("[useAnalysis] /analyze/smart",b.status,F);const U=new Error("analise indisponivel");throw U.response={status:b.status,data:F},U}const v=await b.json();if(console.log("[useAnalysis] Analysis received:",{score:v.closingScore,classification:v.classification,emotions:(C=v.emotions)==null?void 0:C.length}),_(R.leadId,v,R.messages.length),R.leadId!==y.current){console.log("[useAnalysis] resposta de outro lead descartada:",R.leadId);return}i(v),x(!1),v.deepAnalysisPending&&setTimeout(async()=>{var F;if(R.leadId===y.current)try{const U=await fetch(`${ud}/analyze`,{method:"POST",headers:$,body:JSON.stringify(R),signal:(F=g.current)==null?void 0:F.signal});if(U.ok){const te=await U.json();if(console.log("[useAnalysis] Deep analysis received"),_(R.leadId,te,R.messages.length),R.leadId!==y.current)return;i(te)}}catch(U){if(U instanceof Error&&U.name==="AbortError")return;console.error("[useAnalysis] Deep analysis fetch failed:",U)}},3e3)}catch(b){if(b instanceof Error&&b.name==="AbortError"){console.log("[useAnalysis] Request aborted");return}const v=He(b,{acao:"analisar a conversa"});u(v),console.error("[useAnalysis] Error:",b)}finally{d(!1)}},[_]),P=n.useCallback(R=>{y.current!==R&&(y.current=R,g.current&&g.current.abort(),f.current&&clearTimeout(f.current),i(null),u(null),x(!1))},[]),D=n.useCallback(async R=>{P(R.leadId),p.current=R;const M=k(R.leadId);if(M)if(i(M.analysis),M.messageCount<R.messages.length)x(!0);else{x(!1);return}f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{I(R)},s)},[k,I,s,P]),V=n.useCallback(async()=>{p.current&&(f.current&&clearTimeout(f.current),N(),await I(p.current))},[N,I]);return n.useEffect(()=>()=>{f.current&&clearTimeout(f.current),g.current&&g.current.abort()},[]),{analysis:r,loading:l,error:c,isStale:m,analyze:D,forceAnalyze:V,clearCache:N,setActiveLead:P}}function tm(t){return(t||"").toLowerCase().normalize("NFD").replace(/[Ì-ͯ]/g,"").trim()}function li(t){const a=tm(t);return mc[a]??mc[t]??t.charAt(0).toUpperCase()+t.slice(1)}function dv(t){const a=new Map;for(const s of t){const r=li(s.type),i=a.get(r);(!i||s.confidence>i.confidence)&&a.set(r,s)}return[...a.values()]}function uv(t,a,s){const r=a==="sent"&&s?new Date(s):new Date(t);if(isNaN(r.getTime()))return"";const i=new Date,l=r.toDateString()===i.toDateString(),d=r.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:cn()});if(l)return a==="sent"?`Enviado hoje à s ${d}`:`Hoje à s ${d}`;const c=r.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});return a==="sent"?`Enviado em ${c} ${d}`:`${c} à s ${d}`}const mv={nome:"Nome",placa:"Placa",cpf:"CPF",cep:"CEP",uso:"Uso",ano_fabricacao:"Ano fab.",ano_modelo:"Ano modelo",estado_civil:"Estado civil",moradia:"Moradia",condutor_jovem:"Condutor 18-26",data_nascimento:"Nascimento"},md=["placa","cpf","cep","uso"];
166function pv({leadId:t}){var F,U,te;const a=Wr(),{user:s}=Sa(),{config:r}=yi(a),{query:i}=Gn(a||void 0),l=Kr((F=i.data)==null?void 0:F.capabilities),d=((s==null?void 0:s.role)==="manager"||(s==null?void 0:s.role)==="admin"||(s==null?void 0:s.role)==="super_admin")&&!!(s!=null&&s.companyId)&&s.companyId===a,[c,u]=n.useState(null),[m,x]=n.useState(!1),[f,p]=n.useState([]),[g,y]=n.useState(!1),[k,_]=n.useState(0);n.useEffect(()=>{if(!t){u(null);return}let q=!0;return x(!0),Ci(a).then(Z=>{q&&u(Z)}).catch(()=>{}).finally(()=>{q&&x(!1)}),()=>{q=!1}},[t,a,k]),n.useEffect(()=>{if(!t||!d){p([]);return}let q=!0;return $x().then(Z=>{q&&p(Z)}).catch(()=>{}),()=>{q=!1}},[t,d,k]);const N=async q=>{if(!(!q||g)){y(!0);try{await Px(q),_(Z=>Z+1)}catch{}finally{y(!1)}}};if(!t)return e.jsx("div",{className:"ls-tabpane",children:e.jsxs("div",{className:"ls-empty-state",children:[e.jsx(ms,{className:"w-8 h-8 mx-auto opacity-40"}),e.jsx("p",{children:"Abra uma conversa pra ver onde o lead está no workflow de venda."})]})});if(m&&!c)return e.jsx("div",{className:"ls-tabpane",children:e.jsx("div",{className:"ls-empty-state",children:e.jsx(le,{className:"w-6 h-6 mx-auto animate-spin opacity-60"})})});const I=[...(c==null?void 0:c.stages)??[]].sort((q,Z)=>q.posicao-Z.posicao);if(!I.length)return e.jsx("div",{className:"ls-tabpane",children:e.jsxs("div",{className:"ls-empty-state",children:[e.jsx(ms,{className:"w-8 h-8 mx-auto opacity-40"}),e.jsxs("p",{children:["Nenhum workflow de venda configurado. Defina as etapas em ",e.jsx("strong",{children:"Funil â Workflows"}),"."]})]})});const P=((c==null?void 0:c.leads)??[]).find(q=>q.id===t||q.leadId===t)??null,D=P?I.findIndex(q=>q.id===P.stageId||q.slug===P.stageSlug):-1,V=D>=0?I[D]:null,R=D>=0?I.slice(D+1).find(q=>!q.is_final)??null:I[0],M=((V==null?void 0:V.agent_instructions)||"").trim()||(R?`Conduzir o lead para a etapa: ${R.nome}`:""),$=D>=0?D+1:0,C=I.length,b=C?Math.round($/C*100):0,v=((U=c==null?void 0:c.activeWorkflow)==null?void 0:U.name)||"Workflow de venda";return e.jsxs("div",{className:"ls-tabpane",children:[e.jsxs("div",{className:"ls-section",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[d&&f.length>0?e.jsxs("select",{className:"text-sm font-semibold rounded px-1.5 py-0.5 max-w-[72%] truncate",style:{color:"var(--ls-text)",background:"transparent",border:"1px solid var(--ls-border)"},value:((te=f.find(q=>q.is_active))==null?void 0:te.id)||"",disabled:g,onChange:q=>N(q.target.value),title:"Trocar o workflow ativo da empresa",children:[!f.some(q=>q.is_active)&&e.jsx("option",{value:"",children:"Selecione um workflowâ¦"}),f.map(q=>e.jsxs("option",{value:q.id,children:[q.name,q.is_active?" (ativo)":""]},q.id))]}):e.jsx("span",{className:"text-sm font-semibold truncate",style:{color:"var(--ls-text)"},children:v}),e.jsx("span",{className:"text-xs flex-shrink-0 ml-2",style:{color:"var(--ls-text-muted)"},children:$>0?`${$}/${C}`:`-/${C}`})]}),e.jsx("div",{className:"ls-pb-bar",children:e.jsx("div",{className:"ls-pb-fill",style:{width:`${b}%`}})}),e.jsxs("div",{className:"flex justify-between text-[10px] mt-1",style:{color:"var(--ls-text-muted)"},children:[e.jsx("span",{className:"truncate",children:V?`Etapa: ${V.nome}`:"Sem etapa detectada ainda"}),e.jsxs("span",{className:"flex-shrink-0 ml-2",children:[b,"%"]})]})]}),M&&e.jsxs("div",{className:"ls-section",style:{borderLeft:"3px solid var(--ls-primary)"},children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-widest",style:{color:"var(--ls-primary)"},children:"O que fazer agora"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",style:{color:"var(--ls-text)"},children:M})]}),l&&(()=>{const q=(r==null?void 0:r.required_fields)||[],Z=[...md,...q.filter(ce=>!md.includes(ce))],ae=(r==null?void 0:r.custom_required_fields)||[];return!Z.length&&!ae.length?null:e.jsxs("div",{className:"ls-section",children:[e.jsx("div",{className:"ls-section-title",children:"Dados mÃnimos pra cotar"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[Z.map(ce=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{background:"rgba(127,127,127,0.14)",color:"var(--ls-text)"},children:mv[ce]||ce},ce)),ae.map(ce=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",title:ce.description||"",style:{background:"rgba(127,127,127,0.14)",color:"var(--ls-text)"},children:ce.label},ce.key))]})]})})(),e.jsxs("div",{className:"ls-section",children:[e.jsx("div",{className:"ls-section-title",children:"Etapas da venda"}),e.jsx("div",{children:I.map((q,Z)=>{const ae=D>=0&&Z<D,ce=Z===D,se=ae?"â":ce?"â":"â",Q=ce?q.cor||"var(--ls-primary)":ae?"var(--ls-success, hsl(var(--success)))":"var(--ls-text-muted)";return e.jsxs("div",{className:`ls-check-item ${ae||ce?"":"dim"}`,children:[e.jsx("span",{className:"ls-check-icon",style:{color:Q},children:se}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"ls-check-head",children:[e.jsx("span",{className:`ls-check-name ${ae||ce?"":"dim"}`,children:q.nome}),ce&&e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full font-semibold",style:{background:q.cor||"var(--ls-primary)",color:"#fff"},children:"agora"}),(q.agent_mode==="draft"||q.agent_mode==="graduated")&&e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded font-medium",title:q.agent_mode==="draft"?"Gate: o agente rascunha aqui (revisão humana antes de enviar)":"Gate parcial: alto risco rascunha, baixo risco envia",style:{background:q.agent_mode==="draft"?"rgba(245,158,11,0.16)":"rgba(14,165,233,0.16)",color:q.agent_mode==="draft"?"hsl(var(--warning-text))":"hsl(var(--primary-text))"},children:q.agent_mode==="draft"?"revisão":"gradual"})]}
166),ce&&q.description&&e.jsx("p",{className:"ls-check-details",children:q.description})]})]},q.id)})})]})]})}const xv={pending:"Pendente",sending:"Enviando",sent:"Enviado",failed:"Falhou",canceled:"Cancelado"};function fv(t){const[a,s]=n.useState("loading");return n.useEffect(()=>{if(!t){s("sem_sessao");return}let r=!0;return Je(`/api/whatsapp/status/${t}`).then(i=>i.json()).then(i=>{r&&(i.channel==="cloud"?s("cloud"):i.channel==="baileys"&&i.connected?s("baileys"):s("sem_sessao"))}).catch(()=>{r&&s("sem_sessao")}),()=>{r=!1}},[t]),a}function hv(t,a){const[s,r]=n.useState({sellerId:null,pronto:!1});n.useEffect(()=>{if(!t){r({leadId:t,sellerId:null,pronto:!0});return}let l=!0;return r({leadId:t,sellerId:null,pronto:!1}),Lp(t).then(d=>{l&&r({leadId:t,sellerId:d,pronto:!0})}).catch(()=>{l&&r({leadId:t,sellerId:null,pronto:!0})}),()=>{l=!1}},[t]);const i=s.pronto&&s.leadId===t;return{sellerId:i&&s.sellerId||a,carregando:!i}}function gv({sellerId:t,chatId:a,chatName:s,canal:r="baileys"}){const{toast:i}=At(),[l,d]=n.useState([]),[c,u]=n.useState(!1),[m,x]=n.useState(!1),[f,p]=n.useState(""),[g,y]=n.useState(""),[k,_]=n.useState(""),[N,I]=n.useState(!1),P=n.useCallback(async()=>{if(t){u(!0);try{const $=await Je(`/api/whatsapp/schedule/${t}`);if($.ok){const C=await $.json();d(C.scheduled??[])}}catch{}finally{u(!1)}}},[t]);n.useEffect(()=>{P()},[P]),ls(P,qd);const D=async $=>{if(confirm("Cancelar esse agendamento?"))try{await Je(`/api/whatsapp/schedule/${t}/${$}`,{method:"DELETE"}),await P(),i({title:"Agendamento cancelado"})}catch{i({title:"Erro ao cancelar",variant:"destructive"})}},V=async $=>{if(confirm("Excluir esse agendamento da lista? Não dá pra desfazer."))try{await Je(`/api/whatsapp/schedule/${t}/${$}?purge=1`,{method:"DELETE"}),await P(),i({title:"Agendamento excluÃdo"})}catch{i({title:"Erro ao excluir",variant:"destructive"})}},R=async()=>{if(!(!f.trim()||!g||!k||!a)){I(!0);try{const $=new Date(`${g}T${k}:00`).toISOString(),C=await Je(`/api/whatsapp/schedule/${t}`,{method:"POST",body:JSON.stringify({chatId:a,contactName:s,message:f,scheduledFor:$})});if(!C.ok){const F=await C.json().catch(()=>({}));throw new Error(F.error||"Erro ao criar agendamento")}const b=await C.json().catch(()=>({}));x(!1),p(""),y(""),_(""),await P();const v=b.previsao;i({title:"Mensagem agendada!",description:v!=null&&v.frase?`Se saÃsse agora: ${v.frase}.`:void 0,variant:(v==null?void 0:v.via)==="bloqueado"?"destructive":void 0})}catch($){i({title:"Erro",description:He($),variant:"destructive"})}finally{I(!1)}}},M=new Date().toISOString().slice(0,10);return e.jsxs("div",{className:"ls-tabpane",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"ls-section-title",style:{marginBottom:0},children:"Mensagens agendadas"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:P,className:"ls-icon-btn",children:e.jsx(jt,{className:`w-3.5 h-3.5 ${c?"animate-spin":""}`})}),a&&(r==="baileys"||r==="cloud")&&e.jsxs("button",{onClick:()=>x($=>!$),className:"ls-btn-sm primary",children:[e.jsx(us,{className:"w-3 h-3"}),"Agendar"]})]})]}),r==="sem_sessao"&&e.jsx("div",{className:"ls-section text-[11px]",style:{color:"var(--ls-text-muted)"},children:"Conecte seu WhatsApp para agendar mensagens."}),m&&a&&(r==="baileys"||r==="cloud")&&e.jsxs("div",{className:"ls-section",children:[e.jsx("div",{className:"ls-ai-label",style:{color:"var(--ls-text-secondary)"},children:"Novo agendamento"}),e.jsxs("p",{className:"text-[10px] mb-2",style:{color:"var(--ls-text-muted)"},children:["Para: ",e.jsx("strong",{children:s||a})]}),r==="cloud"&&e.jsx("p",{className:"text-[10px] mb-2",style:{color:"var(--ls-text-muted)"},children:"Na hora do envio o sistema confere a janela da Meta. Dentro das 72h de um anúncio vai o texto, sem custo. Dentro de 24h vai o texto, cobrado pela Meta. Fora disso vai o template de reengajamento da empresa no lugar do texto, também cobrado."}),e.jsx("textarea",{value:f,onChange:$=>p($.target.value),rows:3,placeholder:"Mensagem a ser enviada...",className:"ls-textarea"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"ls-field-label",children:"Data"}),e.jsx("input",{type:"date",min:M,value:g,onChange:$=>y($.target.value),className:"ls-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"ls-field-label",children:"Hora"}),e.jsx("input",{type:"time",value:k,onChange:$=>_($.target.value),className:"ls-input"})]})]}),e.jsxs("div",{className:"ls-action-buttons",children:[e.jsx("button",{onClick:()=>x(!1),className:"ls-btn-sm ghost ls-btn-block",children:"Cancelar"}),e.jsx("button",{onClick:R,disabled:N||!f.trim()||!g||!k,className:"ls-btn-sm primary ls-btn-block",children:N?e.jsxs(e.Fragment,{children:[e.jsx(le,{className:"w-3 h-3 animate-spin"}),"Agendandoâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(_t,{className:"w-3 h-3"}),"Confirmar"]})})]})]}),c&&l.length===0?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx("div",{className:"ls-spinner"})}):l.length===0?e.jsxs("div",{className:"ls-empty-state",children:[e.jsx(_t,{className:"w-8 h-8 mx-auto opacity-40"}),e.jsx("p",{children:"Nenhuma mensagem agendada"}),a&&e.jsx("p",{style:{fontSize:10,opacity:.7,marginTop:4},children:'Clique em "Agendar" para criar um agendamento para esta conversa'})]}):e.jsx(e.Fragment,{children:l.map($=>e.jsxs("div",{className:"ls-sched-item",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"ls-sched-name",children:Fn($.contact_name,null,$.chat_id)}),e.jsx("span",{className:`ls-status ${$.status}`,children:xv[$.status]??$.status})]}),e.jsx("p",{className:"ls-sched-preview line-clamp-2",children:$.message.length>120?`${$.message.slice(0,120)}â¦`:$.message}),e.jsxs("div",{className:"ls-sched-meta",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_t,{className:"w-3 h-3"}),uv($.scheduled_for,$.status,$.sent_at)]}),$.status==="pending"?e.jsx("button",{onClick:()=>D($.id),className:"ls-sched-cancel",children:"Cancelar"}):e.jsx("button",{onClick:()=>V($.id),className:"ls-sched-cancel",title:"Excluir do histórico",children:"Excluir"})]}),$.status==="failed"&&$.failed_reason&&e.jsx("p",{className:"ls-sched-fail",children:$.failed_reason})]},$.id))})]})}const bv={venda:"fechamento",recovery:"reativação",suporte:"satisfação",prospeccao:"qualificação",onboarding:"progresso"},vv={venda:{hot:"Quente",warm:"Morno",cold:"Frio"},recovery:{hot:"Reativado",warm:"Em processo",cold:"Perdido"},suporte:{hot:"Satisfeito",warm:"Em risco",cold:"Churn iminente"},prospeccao:{hot:"Qualificado",warm:"Em qualificação",cold:"Desqualificado"},onboarding:{hot:"Completo",warm:"Em andamento",cold:"Parado"}},jv={venda:"probabilidade de fechamento",recovery:"probabilidade de reativação",suporte:"nÃvel de satisfação do cliente",prospeccao:"Ãndice de qualificação",onboarding:"progresso do onboarding"},yv={interest:Zs,enthusiasm:ai,frustration:An,urgency:Es,hesitation:os,satisfaction:gr,confusion:xc,negotiation:ws,objection:Ba,neutral:ko,trust:ws,doubt:os,curiosity:Zs,indecision:os,commitment:ws,interesse:Zs,curiosidade:Zs,entusiasmo:ai,alegria:gr,satisfacao:gr,otimismo:gr,confianca:ws,compromisso:ws,negociacao:ws,frustracao:An,frustacao:An,raiva:An,impaciencia:An,urgencia:Es,ansiedade:Es,confusao:xc,duvida:os,hesitacao:os,indecisao:os,desconfianca:Ba,resistencia:Ba,objecao:Ba,neutralidade:ko,neutro:ko};function Nv({score:t,classification:a,title:s}){const i=2*Math.PI*15,l=Math.max(0,Math.min(1,t/100));return e.jsxs("div",{className:"ls-mini-gauge",title:s,children:[e.jsxs("svg",{className:"ls-mini-gauge-svg",viewBox:"0 0 36 36",children:[e.jsx("circle",{className:"ls-score-bg",cx:"18",cy:"18",r:15}),e.jsx("circle",{className:`ls-score-progress ls-score-progress-${a}`,cx:"18",cy:"18",r:15,strokeDasharray:i,strokeDashoffset:i*(1-l)})]}),e.jsx("div",{className:"ls-mini-gauge-value",children:t})]})}
166const wv={preco:"Preço",prazo:"Prazo",concorrente:"Concorrente",confianca:"Confiança",necessidade:"Necessidade",qualidade:"Qualidade",pagamento:"Pagamento",outro:"Outro"},kv={direta:"Direta",empatica:"Empática",consultiva:"Consultiva"};function pd({title:t,warn:a=!1,defaultOpen:s=!0,storageKey:r,open:i,onToggle:l,children:d}){const[c,u]=n.useState(()=>{if(r)try{const p=localStorage.getItem(r);if(p!=null)return p==="1"}catch{}return s}),m=i!==void 0,x=m?i:c,f=()=>{if(m){l==null||l();return}u(p=>{const g=!p;if(r)try{localStorage.setItem(r,g?"1":"0")}catch{}return g})};return e.jsxs("div",{className:"ls-section",children:[e.jsxs("button",{type:"button",onClick:f,className:`ls-section-title ${a?"warn":""} w-full text-left cursor-pointer`,style:x?void 0:{marginBottom:0},title:x?"Recolher":"Expandir",children:[e.jsx(dt,{className:`w-3.5 h-3.5 transition-transform ${x?"":"-rotate-90"}`}),t]}),x&&d]})}const Vo={boas_vindas:"Boas-vindas",confirma_endereco:"Confirmação de endereço",endereco_novo:"Novo endereço",sede_propria_ou_locada:"Sede própria ou locada",tem_folha:"Folha de pagamento",quem_folha:"Quem está em folha",tem_afastado:"Afastados/pensão",sindicato:"Sindicato",sindicato_nome:"Nome do sindicato",gestor_folha:"Gestor da folha",contato_rh:"Contato RH/DP",certificado_digital:"Certificado digital",transicao_contador:"Transição de contador",contato_contador_anterior:"Contador anterior",contato_doc_responsavel:"Responsável por docs",contato_doc_pessoa:"Contato responsável",agendamento:"Agendamento de reunião"};function xd({lead:t,messages:a,onClose:s,onUseSuggestion:r,mode:i,onMode:l,onboardingSession:d,autoSwitch:c=!1,sellerId:u,chatId:m,chatName:x,hideSuggestions:f=!1,cotacaoReviewSignal:p,cotacaoRefetchSignal:g,hasPendingCotacaoDraft:y=!1,pip:k,showCotacaoCuradoria:_=!0,onSelectPhoneInChat:N}){var ha,ga,it,ut,Yt,ba,va,wt,zt,ea;const[I,P]=n.useState(null),[D,V]=n.useState(0),[R,M]=n.useState(null),[$,C]=n.useState("analise"),{layout:b}=Rn(),v=Bb((t==null?void 0:t.id)??null,$==="cotacao"),F=v.items.length>0,U=hv(t==null?void 0:t.id,u),te=U.sellerId,q=fv(te),Z=U.carregando?"loading":q,ae=Wr(),{query:ce}=Gn(ae||void 0),se=Kr((ha=ce.data)==null?void 0:ha.capabilities),Q=Mi((ga=ce.data)==null?void 0:ga.capabilities),K=n.useMemo(()=>kd.filter(J=>(J!=="agendamentos"||Z==="baileys"||Z==="cloud"||Z==="loading")&&(J!=="cotacao"||F&&se)),[Z,F,se]),G=n.useMemo(()=>{const he=Ir(K,b.tabsOrder).filter(Fe=>K.includes(Fe)).filter(Fe=>!b.hiddenTabs.includes(Fe));return he.length>0?he:["analise"]},[K,b.tabsOrder,b.hiddenTabs]);n.useEffect(()=>{G.includes($)||C(G[0])},[$,G]);const[L,S]=n.useState("chat"),B=n.useMemo(()=>Ir(Cd,b.blocksOrder).filter(he=>!b.hiddenBlocks.includes(he)),[b.blocksOrder,b.hiddenBlocks]),H=n.useMemo(()=>new Set(b.collapsedBlocks),[b.collapsedBlocks]),W=n.useCallback(J=>{const he=H.has(J)?b.collapsedBlocks.filter(Fe=>Fe!==J):[...b.collapsedBlocks,J];wa({collapsedBlocks:he})},[H,b.collapsedBlocks]),X=n.useRef(void 0),oe=n.useMemo(()=>({leadId:t.id,contactName:t.contactName,contactPhone:t.contactPhone,messages:a.map(J=>({text:J.text,isOutgoing:J.isOutgoing,timestamp:J.timestamp})),useCase:i}),[t,a,i]),{analysis:O,loading:be,error:fe,analyze:pe,forceAnalyze:Me,setActiveLead:je}=cv({cacheEnabled:!0,debounceMs:1500}),Oe=n.useRef(null),Ee=n.useRef(0);n.useEffect(()=>{t.id!==Oe.current&&(Oe.current=t.id,Ee.current=a.length,je(t.id),a.length>0&&pe(oe))},[t.id,a.length,oe,pe,je]),n.useEffect(()=>{t.id===Oe.current&&a.length>Ee.current&&(Ee.current=a.length,pe(oe))},[t.id,a.length,oe,pe]),n.useEffect(()=>{V(0),M(null)},[t.id]),n.useEffect(()=>{const J=X.current;X.current=i,J!==void 0&&J!==i&&a.length>0&&pe(oe)},[i]),n.useEffect(()=>{const J=O==null?void 0:O.suggested_mode;if(!c||!J||J===i||J===R)return;const he=setTimeout(()=>{l==null||l(J)},5e3);return()=>clearTimeout(he)},[O==null?void 0:O.suggested_mode,i,c,R,l]);const ye=(J,he)=>{navigator.clipboard.writeText(J),P(he),setTimeout(()=>P(null),2e3)},Le=(O==null?void 0:O.classification)??"cold",Ne=O==null?void 0:O.scoreTrend,Se=(O==null?void 0:O.suggestedResponses)??[],ke=Se[D],ht=(O==null?void 0:O.suggestedResponse)??"",yt=(Ne==null?void 0:Ne.direction)==="rising"?Mx:(Ne==null?void 0:Ne.direction)==="falling"?Tx:Ix;(Ne==null?void 0:Ne.direction)==="rising"||Ne==null||Ne.direction;const Ye=[];
166if(O!=null&&O.leadDetails){const J=O.leadDetails;J.company&&Ye.push({label:"Empresa",value:J.company}),J.role&&Ye.push({label:"Cargo",value:J.role}),J.productInterest&&Ye.push({label:"Interesse",value:J.productInterest}),J.budget&&Ye.push({label:"Orçamento",value:J.budget}),J.timeline&&Ye.push({label:"Prazo",value:J.timeline})}const Nt=O==null?void 0:O.suggested_mode,Zt=Nt&&Nt!==i&&Nt!==R,Et={perfil:O!=null&&O.conversationSummary||(((it=O==null?void 0:O.insights)==null?void 0:it.length)??0)>0?e.jsxs("div",{className:"ls-section ls-client-summary",children:[e.jsxs("button",{type:"button",onClick:()=>W("perfil"),className:"ls-section-title flex items-center gap-1 w-full text-left cursor-pointer",title:H.has("perfil")?"Expandir perfil":"Recolher perfil",children:[e.jsx(dt,{className:`w-3.5 h-3.5 transition-transform ${H.has("perfil")?"-rotate-90":""}`}),"Perfil do Cliente"]}),!H.has("perfil")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"ls-client-summary-stats",children:[e.jsxs("div",{className:"ls-client-stat",children:[e.jsx("span",{className:"ls-client-stat-value",children:a.length}),e.jsx("span",{className:"ls-client-stat-label",children:"interações"})]}),e.jsxs("div",{className:"ls-client-stat",children:[e.jsx("span",{className:"ls-client-stat-value",children:((ut=O==null?void 0:O.objections)==null?void 0:ut.length)??0}),e.jsx("span",{className:"ls-client-stat-label",children:"atritos"})]}),e.jsxs("div",{className:"ls-client-stat",children:[e.jsx("span",{className:"ls-client-stat-value ls-client-stat-value--texto capitalize",children:O!=null&&O.isQuickAnalysis?"â¦":(Yt=O==null?void 0:O.emotions)!=null&&Yt[0]?li(O.emotions[0].type):"Neutro"}),e.jsx("span",{className:"ls-client-stat-label",children:"sentimento"})]})]}),(O==null?void 0:O.conversationSummary)&&e.jsx("p",{className:"ls-client-summary-text",children:O.conversationSummary}),(O==null?void 0:O.insights)&&O.insights.length>0&&e.jsx("ul",{className:"ls-client-highlights",children:O.insights.map((J,he)=>e.jsx("li",{children:J},he))})]})]}):null,objecoes:O!=null&&O.objections&&O.objections.length>0?e.jsx(pd,{title:`Objeções (${O.objections.length})`,warn:!0,open:!H.has("objecoes"),onToggle:()=>W("objecoes"),children:e.jsx("div",{children:O.objections.map((J,he)=>e.jsxs("div",{className:"ls-objection",children:[e.jsx("span",{className:"ls-objection-type",children:wv[J.type]??J.type}),e.jsxs("p",{className:"ls-objection-quote",children:['"',J.text,'"']}),e.jsxs("div",{className:"ls-objection-counter",children:["â ",J.suggestedCounter]})]},he))})}):null,plano_acao:O!=null&&O.actionPlan&&O.actionPlan.length>0?e.jsxs("div",{className:"ls-section",children:[e.jsx("div",{className:"ls-section-title",children:"Plano de ação"}),e.jsx("ol",{className:"ls-action-list",children:O.actionPlan.map((J,he)=>e.jsxs("li",{className:"ls-action-item",children:[e.jsx("span",{className:"ls-action-num",children:he+1}),e.jsx("span",{children:J})]},he))})]}):null,bant:Ye.length>0||(((va=(ba=O==null?void 0:O.leadDetails)==null?void 0:ba.painPoints)==null?void 0:va.length)??0)>0?e.jsxs(pd,{title:"Dados do lead (IA)",open:!H.has("bant"),onToggle:()=>W("bant"),children:[Ye.length>0&&e.jsx("div",{className:"mb-3",children:Ye.map(({label:J,value:he})=>e.jsxs("div",{className:"ls-kv",children:[e.jsx("span",{className:"ls-kv-label",children:J}),e.jsx("span",{className:"ls-kv-value",children:he})]},J))}),((wt=O==null?void 0:O.leadDetails)==null?void 0:wt.painPoints)&&O.leadDetails.painPoints.length>0&&e.jsx("div",{className:"ls-emotions",children:O.leadDetails.painPoints.map((J,he)=>e.jsx("span",{className:"ls-tag muted",children:J},he))})]}):null,melhor_horario:t!=null&&t.id?e.jsx(zb,{leadId:t.id}):null,origem_trafego:t!=null&&t.id?e.jsx(Qb,{leadId:t.id,source:t.source??null,referral:t.referral??null}):null};return e.jsxs(wo.div,{initial:{x:340,opacity:0},animate:{x:0,opacity:1},exit:{x:340,opacity:0},transition:{type:"spring",damping:25,stiffness:200},className:"ls-panel absolute inset-0 z-30 md:static md:z-auto flex h-full w-full min-h-0 flex-col border-l overflow-hidden",children:[e.jsxs("div",{className:"ls-header flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3",children:[e.jsxs("div",{className:"ls-logo",children:[e.jsx("span",{children:"Análise IA"}),e.jsxs("span",{className:"ls-header-pill",children:[e.jsx("span",{className:"ls-header-pill-dot"}),be?"Analisando":"Ativo"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>
166Me(),className:"ls-header-btn",title:"Reanalisar",children:e.jsx(jt,{className:`w-3.5 h-3.5 ${be?"animate-spin":""}`})}),(k==null?void 0:k.suportado)&&e.jsx("button",{onClick:k.alternar,className:"ls-header-btn",title:k.ativo?"Trazer de volta pra aba":"Destacar numa janela","aria-label":k.ativo?"Trazer a análise de volta pra aba":"Destacar a análise numa janela",children:k.ativo?e.jsx(ef,{className:"w-3.5 h-3.5"}):e.jsx(tf,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:s,className:"ls-header-btn",title:"Fechar",children:e.jsx(un,{className:"w-3.5 h-3.5"})})]})]}),e.jsx("div",{className:"flex items-center justify-between px-4 pb-3",children:e.jsx("div",{className:"flex gap-1 overflow-x-auto scrollbar-none",style:{maskImage:"linear-gradient(to right, #000 calc(100% - 24px), transparent)",WebkitMaskImage:"linear-gradient(to right, #000 calc(100% - 24px), transparent)"},children:G.map(J=>e.jsxs("button",{onClick:()=>C(J),className:`ls-htab ${$===J?"active":""}`,children:[gi[J],J==="cotacao"&&v.openableCount>1&&e.jsx("span",{className:"ls-htab-count",children:v.openableCount})]},J))})}),Zt&&e.jsxs("div",{className:"ls-mode-suggest mx-3 mb-3",children:[e.jsx(Ge,{className:"w-3 h-3 flex-shrink-0"}),e.jsxs("span",{children:["IA detectou ",e.jsx("strong",{children:(zt=bx.find(J=>J.id===Nt))==null?void 0:zt.label})]}),e.jsx("button",{onClick:()=>{l==null||l(Nt),M(Nt)},className:"ls-mode-suggest-btn",children:"Trocar"}),e.jsx("button",{onClick:()=>M(Nt),className:"ls-mode-suggest-x",children:e.jsx(vt,{className:"w-3 h-3"})})]})]}),$==="cotacao"&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:e.jsx(Gb,{state:v})}),$==="workflow"&&e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-none",children:e.jsx(pv,{leadId:(t==null?void 0:t.id)??null})}),$==="agendamentos"&&te&&e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-none",children:e.jsx(gv,{sellerId:te,chatId:m??null,chatName:x??null,canal:Z})}),$==="configuracao"&&e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-none",children:e.jsx(ov,{})}),$==="prioridades"&&e.jsx(lv,{companyId:ae||void 0,onSelectPhoneInChat:N}),$==="assistente"&&e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[e.jsx("div",{className:"flex gap-1 px-3 pt-2 pb-2 border-b border-border flex-shrink-0",children:[["chat","Chat"],["sobre","Sobre"]].map(([J,he])=>e.jsx("button",{onClick:()=>S(J),className:`ls-htab ${L===J?"active":""}`,children:he},J))}),e.jsx("div",{className:"flex-1 min-h-0",children:L==="chat"?e.jsx(ev,{leadId:(t==null?void 0:t.id)??null}):e.jsx(av,{})})]}),$==="analise"&&e.jsxs("div",{className:"ls-content scrollbar-none",children:[!O&&!be&&!fe&&e.jsxs("div",{className:"ls-empty-state",children:[e.jsx(fa,{className:"w-10 h-10 mx-auto opacity-40"}),e.jsx("p",{children:"Aguardando mensagens para analisar"})]}),fe&&e.jsxs("div",{className:"ls-error-state",children:[e.jsx("p",{className:"ls-error-message",children:fe}),e.jsx("button",{className:"ls-retry-btn",onClick:()=>Me(),children:"Tentar novamente"})]}),i==="onboarding"&&d&&e.jsx(wo.div,{initial:{opacity:0}
166,animate:{opacity:1},className:"space-y-3",children:e.jsx(qn,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Bn,{className:"pt-4 pb-4 px-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ms,{className:"w-4 h-4 text-primary-text"}),e.jsx("span",{className:"text-xs font-semibold text-primary-text uppercase tracking-wider",children:"Sessão de Onboarding"}),e.jsx("span",{className:`ml-auto text-[10px] px-1.5 py-0.5 rounded-full border font-medium ${d.status==="completed"?"bg-success/10 text-success-text border-success/20":"bg-primary/10 text-primary-text border-primary/20"}`,children:d.status==="completed"?"ConcluÃdo":"Em andamento"})]}),d.company_data&&e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Empresa"}),e.jsx("span",{className:"font-medium text-right max-w-[150px] truncate",children:d.company_data.nome_fantasia||d.company_data.razao_social})]}),d.company_data.atividade_principal&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Atividade"}),e.jsx("span",{className:"text-right max-w-[150px] text-[10px]",children:d.company_data.atividade_principal})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"CNPJ"}),e.jsx("span",{className:"font-mono text-[10px]",children:d.cnpj})]})]}),(()=>{const J=Object.keys(Vo).length,he=Object.keys(d.answers||{}).length,Fe=Math.round(he/J*100);return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Progresso"}),e.jsxs("span",{className:"font-medium",children:[he,"/",J," etapas"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${d.status==="completed"?"bg-success":"bg-primary"}`,style:{width:`${Fe}%`}})}),d.current_step&&d.status==="active"&&e.jsxs("p",{className:"text-[10px] text-primary-text flex items-center gap-1",children:[e.jsx(_t,{className:"w-3 h-3"}),"Etapa atual: ",Vo[d.current_step]||d.current_step]})]})})(),Object.keys(d.answers||{}).length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1.5",children:"Respostas"}),e.jsx("div",{className:"space-y-1",children:Object.entries(d.answers).map(([J,he])=>e.jsxs("div",{className:"flex justify-between gap-2 text-xs",children:[e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:[Vo[J]||J,":"]}),e.jsx("span",{className:"font-medium text-right",children:he})]},J))})]})]})})}),i==="onboarding"&&!d&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(ms,{className:"w-8 h-8 text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Nenhuma sessão de onboarding ativa para este contato"})]}),(O||be)&&i!=="onboarding"&&e.jsx(ou,{mode:"wait",children:e.jsxs(wo.div,{initial:{opacity:0}
166,animate:{opacity:1},className:"space-y-3",children:[Q&&e.jsx("div",{className:"ls-compact-status",children:be&&!O?e.jsx("div",{className:"ls-spinner",style:{margin:"4px auto"}}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"ls-compact-status-row",children:[e.jsx(Nv,{score:(O==null?void 0:O.closingScore)??0,classification:Le,title:`${jv[i??"venda"]}: ${(O==null?void 0:O.closingScore)??0}/100`}),O&&e.jsx("span",{className:`ls-classification ls-class-${Le}`,children:((ea=vv[i??"venda"])==null?void 0:ea[Le])??Le}),Ne&&e.jsxs("span",{className:`ls-score-trend ls-trend-${Ne.direction}`,children:[e.jsx(yt,{className:"w-3.5 h-3.5"}),Ne.direction==="stable"?"Estável":`${Ne.direction==="rising"?"+":"-"}${Math.abs(Ne.delta)} pts`]})]}),e.jsxs("p",{className:"ls-contact-name",children:[bv[i??"venda"],t.contactName?` · ${t.contactName}`:""]}),O&&(O.isQuickAnalysis||O.emotions.length>0)&&e.jsx("div",{className:"ls-emotions",children:O.isQuickAnalysis?e.jsxs("span",{className:"ls-emotion-tag",style:{opacity:.6},children:[e.jsx(le,{className:"w-3 h-3 animate-spin"})," analisandoâ¦"]}):dv(O.emotions).map((J,he)=>e.jsxs("span",{className:`ls-emotion-tag${J.evidence?" ls-emotion-tag-evidence":""}`,title:J.evidence?`"${J.evidence}"`:void 0,children:[(()=>{const Fe=yv[tm(J.type)]??fa;return e.jsx(Fe,{className:"w-3 h-3"})})(),li(J.type),J.confidence>=70&&e.jsxs("span",{className:"ls-emotion-pct",children:[Math.round(J.confidence),"%"]})]},he))})]})}),se&&_&&(t==null?void 0:t.id)&&e.jsx(Ti,{leadId:t.id,openSignal:p,refetchSignal:g,autoOpenAllowed:y,onUseSuggestion:r}),se&&F&&e.jsxs("button",{type:"button",onClick:()=>C("cotacao"),className:"flex w-full items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-left transition-colors hover:bg-muted/50",children:[e.jsx(ot,{className:"w-4 h-4 shrink-0 text-primary"}),e.jsxs("span",{className:"flex-1 text-xs font-semibold",children:["PDFs da cotação",v.openableCount>1?` · ${v.openableCount}`:""]}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Abrir aba"}),e.jsx(As,{className:"w-3.5 h-3.5 text-muted-foreground"})]}),Q&&!f&&(Se.length>0||ht)&&e.jsxs("div",{className:"ls-section",children:[e.jsx("div",{className:"ls-ai-label",children:Se.length>1?`${Se.length} abordagens geradas por IA`:"Sugestão de resposta"}),Se.length>1&&e.jsx("div",{className:"ls-tone-tabs",children:Se.map((J,he)=>e.jsx("button",{onClick:()=>V(he),className:`ls-tone-tab ${D===he?"active":""}`,children:kv[J.tone]??J.tone},he))}),e.jsx("div",{className:"ls-suggestion",children:(ke==null?void 0:ke.text)??ht}),e.jsxs("div",{className:"ls-action-buttons",children:[e.jsxs("button",{className:"ls-use-btn",onClick:()=>r((ke==null?void 0:ke.text)??ht),children:[e.jsx(xa,{className:"w-3.5 h-3.5"}),"Usar"]}),e.jsx("button",{className:`ls-copy-btn ${I===((ke==null?void 0:ke.tone)??"default")?"ls-btn-success":""}`,onClick:()=>ye((ke==null?void 0:ke.text)??ht,(ke==null?void 0:ke.tone)??"default"),children:I===((ke==null?void 0:ke.tone)??"default")?e.jsxs(e.Fragment,{children:[e.jsx(Xt,{className:"w-3.5 h-3.5"}),"Copiado"]}):e.jsxs(e.Fragment,{children:[e.jsx(ru,{className:"w-3.5 h-3.5"}),"Copiar"]})})]})]}),B.map(J=>e.jsx(Mn.Fragment,{children:Et[J]},J))]},`analysis-${t.id}`)})]})]})}const Gs="https://leadsense.solutions".replace(/\/$/,"");function Cv(t,a=3e4){const[s,r]=n.useState([]),[i,l]=n.useState([]),[d,c]=n.useState(!1),u=n.useCallback(async()=>{c(!0);try{const k=await fetch(`${Gs}/api/onboarding/sessions`,{headers:Us()});k.ok&&r((await k.json()).sessions??[])}catch{}finally{c(!1)}},[]),m=n.useCallback(async()=>{try{const k=await fetch(`${Gs}/api/onboarding/briefing-senders`,{headers:Us()});k.ok&&l((await k.json()).senders??[])}catch{}},[]),x=n.useCallback(async k=>{const _=await fetch(`${Gs}/api/onboarding/start`,{method:"POST",headers:{"Content-Type":"application/json",...Us()},body:JSON.stringify(k)}),N=await _.json();if(!_.ok)throw new Error(N.error||_.statusText);return await u(),N},[u]),f=n.useCallback(async k=>{await fetch(`${Gs}/api/onboarding/session/${k}`,{method:"DELETE",headers:Us()}),await u()},[u]),p=n.useCallback(async(k,_)=>{const N=await fetch(`${Gs}/api/onboarding/briefing-senders`,{method:"POST",headers:{"Content-Type":"application/json",...Us()},body:JSON.stringify({phone:k,name:_})});if(!N.ok)throw new Error((await N.json()).error);await m()},[m]),g=n.useCallback(async k=>{await fetch(`${Gs}/api/onboarding/briefing-senders/${k}`,{method:"DELETE",headers:Us()}),await m()},[m]);n.useEffect(()=>{t&&(u(),m())},[t,u,m]),ls(u,a,t);const y=n.useCallback(k=>{const _=k.replace(/\D/g,"");return s.find(N=>N.phone===_||N.phone.endsWith(_)||_.endsWith(N.phone))},[s]);return{sessions:s,senders:i,loading:d,fetchSessions:u,sessionByPhone:y,startSession:x,cancelSession:f,addSender:p,removeSender:g,active:s.filter(k=>k.status==="active"),completed:s.filter(k=>k.status==="completed")}}function Sv(t,a=!0){const s=tp({queries:t.map(l=>({queryKey:["funnel-multi",l.id],queryFn:()=>Ci(l.id),staleTime:15e3,refetchInterval:6e4,enabled:a}))}),r=new Map,i=[];
166return s.forEach((l,d)=>{const c=t[d],u=l.data;if(u){for(const m of u.stages)r.has(m.slug)||r.set(m.slug,m);for(const m of u.leads){const x=r.get(m.stageSlug);i.push({...m,stageId:(x==null?void 0:x.id)??m.stageId,companyId:c.id,companyName:c.name})}}}),{stages:Array.from(r.values()).sort((l,d)=>l.posicao-d.posicao),leads:i,isLoading:s.some(l=>l.isLoading),refetch:()=>{s.forEach(l=>l.refetch())}}}const _v=[],Av={autonomous:{label:"Autônomo",cls:"bg-success/15 text-success-text border border-success/30"},graduated:{label:"Semi",cls:"bg-warning/15 text-warning-text border border-warning/30"},draft:{label:"Semi",cls:"bg-warning/15 text-warning-text border border-warning/30"}};function am(t){if(!t)return"";const a=Date.now()-new Date(t).getTime(),s=Math.floor(a/6e4);if(s<1)return"agora";if(s<60)return`${s}m`;const r=Math.floor(s/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function Wn(t){return t.split(" ").slice(0,2).map(a=>a[0]).join("").toUpperCase()}const Ev="https://leadsense.solutions/api/analysis".replace(/\/api\/analysis\/?$/,"");function Dv(t){const a=Math.floor(t/60),s=t%60;return`${a}:${String(s).padStart(2,"0")}`}function $v({msg:t,sellerId:a,chatId:s}){const[r,i]=n.useState(null),[l,d]=n.useState(!1),[c,u]=n.useState(null),[m,x]=n.useState(!1),[f,p]=n.useState(!1),g=n.useRef(null),y=`/api/whatsapp/media/${a}/${encodeURIComponent(s)}/${t.id}`,k=n.useCallback(async()=>{if(!(r||l)){d(!0);try{const I=await Je(y);if(!I.ok)return;const P=await I.blob();i(URL.createObjectURL(P))}catch{}finally{d(!1)}}},[r,l,y]),_=n.useCallback(async()=>{await k(),g.current&&(f?(g.current.pause(),p(!1)):(g.current.play(),p(!0)))},[k,f]),N=n.useCallback(async()=>{if(!(c||m)){x(!0);try{const I=await Je(y);if(!I.ok)return;const P=await I.blob(),D=new File([P],"audio.ogg",{type:P.type||"audio/ogg"}),V=new FormData;V.append("file",D);const R=localStorage.getItem("authToken"),M=await fetch(`${Ev}/transcribe`,{method:"POST",headers:R?{Authorization:`Bearer ${R}`}:{},body:V});if(M.ok){const $=await M.json();$.text&&u($.text)}}catch{}finally{x(!1)}}},[c,m,y]);return e.jsxs("div",{className:"flex flex-col gap-1.5 min-w-[160px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:_,disabled:l,className:"w-8 h-8 rounded-full flex items-center justify-center bg-current/10 hover:bg-current/20 transition-colors flex-shrink-0",children:l?e.jsx(le,{className:"w-4 h-4 animate-spin"}):f?e.jsx(nu,{className:"w-4 h-4"}):e.jsx(Si,{className:"w-4 h-4 ml-0.5"})}),e.jsxs("div",{className:"flex-1 flex items-center gap-1.5",children:[e.jsx(qx,{className:"w-4 h-4 opacity-50"}),e.jsx("span",{className:"text-[11px] opacity-70",children:t.duration?Dv(t.duration):"Ãudio"})]})]}),r&&e.jsx("audio",{ref:g,src:r,onEnded:()=>p(!1),onPause:()=>p(!1),style:{display:"none"}}),c?e.jsx("p",{className:"text-xs opacity-80 italic leading-relaxed border-l-2 border-current/30 pl-2",children:c}):e.jsxs("button",{onClick:N,disabled:m,className:"flex items-center gap-1 text-[10px] opacity-50 hover:opacity-90 transition-opacity w-fit",children:[m?e.jsx(le,{className:"w-3 h-3 animate-spin"}):e.jsx(ji,{className:"w-3 h-3"}),m?"Transcrevendo...":"Transcrever"]})]})}const Wo=new Map;function sm(t){let a=Wo.get(t);return a||(a=Je(t).then(async s=>{if(!s.ok)throw new Error(`media ${s.status}`);return URL.createObjectURL(await s.blob())}).catch(s=>{throw Wo.delete(t),s}),Wo.set(t,a)),a}function Pv({msg:t,sellerId:a,chatId:s}){const r=t.type==="sticker",[i,l]=n.useState(null),[d,c]=n.useState(!1),u=`/api/whatsapp/media/${a}/${encodeURIComponent(s)}/${t.id}`;n.useEffect(()=>{let f=!0;return c(!1),sm(u).then(p=>{f&&l(p)}).catch(()=>{f&&c(!0)}),()=>{f=!1}},[u]);const m=(t.mediaCaption||"").trim(),x=r?"Figurinha":"Imagem";return d?e.jsxs("p",{className:"text-sm leading-relaxed flex items-center gap-1.5 opacity-70",children:[e.jsx(lu,{className:"w-4 h-4"})," ",x," indisponÃvel"]}):e.jsxs("div",{className:"flex flex-col gap-1.5",children:[i?e.jsx("img",{src:i,alt:m||x,onClick:()=>window.open(i,"_blank","noopener"),className:r?"max-h-32 w-auto object-contain cursor-zoom-in":"max-w-[240px] rounded-lg object-contain cursor-zoom-in"}):e.jsx("div",{className:`flex items-center justify-center bg-current/5 rounded-lg ${r?"w-24 h-24":"w-[200px] h-[140px]"}`,children:e.jsx(le,{className:"w-4 h-4 animate-spin opacity-50"})}),m&&e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap break-words",children:m})]})}function nm(t){const[a,s]=n.useState(null),[r,i]=n.useState(!1),[l,d]=n.useState(!1),c=n.useCallback(async()=>
166{if(a)return a;i(!0),d(!1);try{const u=await sm(t);return s(u),u}catch{return d(!0),null}finally{i(!1)}},[t,a]);return{url:a,carregando:r,falhou:l,carregar:c}}function Mv({msg:t,sellerId:a,chatId:s}){const r=`/api/whatsapp/media/${a}/${encodeURIComponent(s)}/${t.id}`,{carregando:i,falhou:l,carregar:d}=nm(r),c=(t.body||"").trim(),u=!c||c==="[document]"?"Documento":c,m=async()=>{const x=await d();if(!x)return;const f=document.createElement("a");f.href=x,f.download=u,document.body.appendChild(f),f.click(),f.remove()};return e.jsxs("button",{onClick:m,disabled:i,className:"flex items-center gap-2.5 text-left max-w-[240px] disabled:opacity-60",children:[e.jsx("span",{className:"flex-shrink-0 w-9 h-9 rounded-lg bg-current/10 flex items-center justify-center",children:i?e.jsx(le,{className:"w-4 h-4 animate-spin"}):e.jsx(ot,{className:"w-4 h-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm leading-snug break-words",children:u}),e.jsx("span",{className:"block text-[11px] opacity-70 flex items-center gap-1",children:l?"indisponÃvel":e.jsxs(e.Fragment,{children:[e.jsx(On,{className:"w-3 h-3"})," baixar"]})})]})]})}function Tv({msg:t,sellerId:a,chatId:s}){const r=`/api/whatsapp/media/${a}/${encodeURIComponent(s)}/${t.id}`,{url:i,carregando:l,falhou:d,carregar:c}=nm(r),u=(t.mediaCaption||"").trim()||(t.body==="[video]"?"":(t.body||"").trim());return e.jsxs("div",{className:"flex flex-col gap-1.5",children:[i?e.jsx("video",{src:i,controls:!0,autoPlay:!0,className:"max-w-[240px] rounded-lg"}):e.jsx("button",{onClick:c,disabled:l,className:"w-[200px] h-[140px] rounded-lg bg-current/5 flex flex-col items-center justify-center gap-1.5 disabled:opacity-60",children:l?e.jsx(le,{className:"w-5 h-5 animate-spin opacity-60"}):e.jsxs(e.Fragment,{children:[e.jsx(Si,{className:"w-6 h-6 opacity-70"}),e.jsx("span",{className:"text-[11px] opacity-70",children:d?"VÃdeo indisponÃvel":"Ver vÃdeo"})]})}),u&&e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap break-words",children:u})]})}const Go=[{id:"all",label:"Todos abertos",icon:fa},{id:"attention",label:"Precisa de atenção",icon:Ox},{id:"active",label:"Ativos (bot)",icon:Ge},{id:"cold",label:"Frios",icon:_t},{id:"closed",label:"Encerrados",icon:su}],fd={all:"Abertos",attention:"Atenção",active:"Ativos",cold:"Frios",closed:"Encerrados"},Iv=[{id:"all",label:"Todos"},{id:"aguardando_nos",label:"Responder"},{id:"aguardando_cliente",label:"Aguardando"},{id:"resolvido",label:"Resolvidos"}],hd=[{id:"individual",label:"Conversas",icon:ps},{id:"group",label:"Grupos",icon:bi},{id:"community",label:"Comunidades",icon:du},{id:"all",label:"Todos",icon:fa}];function ns({icon:t,label:a,active:s,onClick:r,badge:i}){return e.jsxs(_d,{children:[e.jsx(Ad,{asChild:!0,children:e.jsxs("button",{onClick:r,"aria-label":a,className:`relative w-11 h-11 rounded-xl flex items-center justify-center transition-colors [-webkit-tap-highlight-color:transparent] ${s?"bg-primary text-primary-foreground":"text-sidebar-foreground/55 [@media(hover:hover)]:hover:bg-sidebar-accent [@media(hover:hover)]:hover:text-sidebar-foreground"}`,children:[e.jsx(t,{className:"w-[18px] h-[18px]"}),!!i&&i>0&&e.jsx("span",{className:"absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-primary text-primary-foreground text-[9px] font-bold flex items-center justify-center border-2 border-sidebar",children:i>9?"9+":i})]})}),e.jsx(Ed,{side:"right",children:a})]})}function gd({isSyncing:t,connectedNumber:a,onDisconnect:s,showDisconnect:r=!0,mode:i,onboardingSessions:l=[],onboardingLoading:d,onSelectPhoneInChat:c,companies:u=[],activeCompanyId:m,onCompanyChange:x,allCompanies:f,onToggleKanban:p,kanbanActive:g,onToggleKpis:y,kpisActive:k,viewSellers:_=[],viewSellerId:N,ownSellerId:I,onViewSellerChange:P,settingsActive:D,onToggleSettings:V,className:R,onNavigate:M}){const{user:$,logout:C}=Sa(),b=wd(),v=()=>{C(),b("/login")},[F,U]=n.useState(null);n.useEffect(()=>{let se=!0;return px({companyId:m}).then(Q=>{se&&U(Q.agent_mode)}).catch(()=>{}),()=>{se=!1}},[m]);const te=F?Av[F]:null,q=l.filter(se=>se.status==="active"),Z=u.length>0&&!!x||!!P&&_.length>0,ae=!!N&&N!==I,ce=F==="autonomous"?"bg-success":te?"bg-warning":"bg-sidebar-foreground
166/30";return e.jsx(Gm,{delayDuration:200,children:e.jsxs("div",{className:`w-[64px] h-full flex-shrink-0 flex flex-col items-center bg-sidebar text-sidebar-foreground border-r border-sidebar-border py-3 gap-1 ${R??""}`,children:[e.jsx(ns,{icon:un,label:"Painel (Funil)",onClick:()=>{b("/funil"),M==null||M()}}),i==="onboarding"&&e.jsxs(ho,{children:[e.jsx(go,{asChild:!0,children:e.jsxs("button",{"aria-label":"Sessões de onboarding",className:"relative w-11 h-11 rounded-xl flex items-center justify-center text-sidebar-foreground/55 hover:bg-sidebar-accent hover:text-sidebar-foreground transition-colors",children:[e.jsx(ms,{className:"w-[18px] h-[18px]"}),q.length>0&&e.jsx("span",{className:"absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-primary text-primary-foreground text-[9px] font-bold flex items-center justify-center border-2 border-sidebar",children:q.length>9?"9+":q.length})]})}),e.jsxs(bo,{side:"right",align:"start",className:"w-72 p-2",children:[e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground px-1 mb-1.5 flex items-center gap-1",children:["Sessões ativas",d&&e.jsx(jt,{className:"w-3 h-3 animate-spin"})]}),q.length===0?e.jsx("p",{className:"text-xs text-muted-foreground px-1 py-2",children:"Nenhuma sessão ativa"}):e.jsx("div",{className:"space-y-0.5 max-h-80 overflow-y-auto",children:q.map(se=>{var G,L,S;const Q=((G=se.company_data)==null?void 0:G.nome_fantasia)||((L=se.company_data)==null?void 0:L.razao_social)||se.client_name||se.phone,K=Object.keys(se.answers||{}).length;return e.jsxs("button",{onClick:()=>c==null?void 0:c(se.phone),className:"w-full flex items-center gap-2 px-2 py-2 rounded-md text-left hover:bg-muted transition-colors",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-primary/15 flex items-center justify-center flex-shrink-0",children:e.jsx(ms,{className:"w-3.5 h-3.5 text-primary-text"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-foreground truncate",children:Q}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[K," etapas · ",((S=se.current_step)==null?void 0:S.replace(/_/g," "))||"-"]})]}),e.jsx(dn,{className:"w-3 h-3 text-muted-foreground/50 flex-shrink-0"})]},se.phone)})})]})]}),t&&e.jsxs(_d,{children:[e.jsx(Ad,{asChild:!0,children:e.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center text-primary",children:e.jsx(jt,{className:"w-[18px] h-[18px] animate-spin"})})}),e.jsx(Ed,{side:"right",children:"Sincronizando conversasâ¦"})]}),e.jsx("div",{className:"flex-1"}),y?e.jsx(ns,{icon:Yo,label:"KPIs",active:k,onClick:()=>{y(),M==null||M()}}):e.jsx(ns,{icon:Yo,label:"KPIs",onClick:()=>{b("/funil"),M==null||M()}}),p&&e.jsx(ns,{icon:iu,label:"Kanban",active:g,onClick:()=>{p(),M==null||M()}}),Km($==null?void 0:$.role)&&e.jsxs(e.Fragment,{children:[e.jsx(ns,{icon:en,label:"Marketing",onClick:()=>{b("/conteudo"),M==null||M()}}),e.jsx(ns,{icon:Qm,label:"Fila de leads",onClick:()=>{b("/fila"),M==null||M()}}),e.jsx(ns,{icon:Jm,label:"Pós-venda",onClick:()=>{b("/pos-venda"),M==null||M()}})]}),Z&&e.jsxs(ho,{children:[e.jsx(go,{asChild:!0,children:e.jsxs("button",{"aria-label":"Empresa e vendedor",className:`relative w-11 h-11 rounded-xl flex items-center justify-center transition-colors ${ae?"text-warning-text hover:bg-sidebar-accent":"text-sidebar-foreground/55 hover:bg-sidebar-accent hover:text-sidebar-foreground"}`,children:[e.jsx(ln,{className:"w-[18px] h-[18px]"}),ae&&e.jsx("span",{className:"absolute top-1 right-1 w-2 h-2 rounded-full bg-warning border-2 border-sidebar"})]})}),e.jsxs(bo,{side:"right",align:"end",className:"w-64 p-3 space-y-3",children:[u.length>0&&x&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-1 block",children:"Empresa (admin)"}),e.jsxs(Qo,{value:f?"__all__":m??"__self__",onValueChange:se=>x(se==="__self__"?void 0:se),children:[e.jsx(Jo,{className:"w-full h-8 text-xs",children:e.jsx(Xo,{})}),e.jsxs(Zo,{children:[e.jsx(Qs,{value:"__self__",children:"Minha empresa"}),u.map(se=>e.jsx(Qs,{value:se.id,children:se.name},se.id)),u.length>1&&e.jsx(Qs,{value:"__all__",children:"Todos"})]})]})]}),P&&_.length>0&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-1 block",children:"Ver inbox de"}),e.jsxs(Qo,{value:N??"__self__",onValueChange:se=>P(se==="__self__"?void 0:se),children:[e.jsx(Jo,{className:"w-full h-8 text-xs",children:e.jsx(Xo,{})}),e.jsxs(Zo,{children:[e.jsx(Qs,{value:"__self__",children:"Minha inbox"}),_.filter(se=>se.id!==I).map(se=>e.jsx(Qs,{value:se.id,children:se.name},se.id))]})]}),ae&&e.jsx("p",{className:"text-[10px] text-warning mt-1",children:"Somente leitura"})]})]})]}),V&&e.jsx(ns,{icon:Xm,label:"Configurações",active:!!D,onClick:()=>{V(),M==null||M()}}),e.jsxs(ho,{children:[e.jsx(go,{asChild:!0,children:e.jsxs("button",{"aria-label":"Conta",className:"relative mt-1",children:[e.jsx("span",{className:"w-9 h-9 rounded-full bg-primary flex items-center justify-center text-primary-foreground text-xs font-bold",children:$?Wn($.name):"?"}),e.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-sidebar ${ce}`})]})}),e.jsxs(bo,{side:"right",align:"end",className:"w-60 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-3",children:[e.jsx("span",{className:"w-9 h-9 rounded-full bg-primary flex items-center justify-center text-primary-foreground text-xs font-bold flex-shrink-0",children:$?Wn($.name):"?"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:($==null?void 0:$.name)??"Vendedor"}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:a||"Não conectado"})]})]}),te&&e.jsxs("div",{className:"flex items-center justify-between text-xs mb-3 px-0.5",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agente"}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[10px] font-semibold ${te.cls}`,children:te.label})]}),r&&e.jsxs("button",{onClick:s,className:"w-full flex items-center gap-2 px-2 py-2 rounded-md text-sm text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors",children:[e.jsx(Wl,{className:"w-4 h-4"}),"Desconectar WhatsApp"]}),e.jsx("div",{className:"h-px bg-border my-1"}),e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-2 px-2 py-2 rounded-md text-sm text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors",children:[e.jsx(Wl,{className:"w-4 h-4"}),"Sair da conta"]})]})]})]})})}function Lv({chats:t,selectedId:a,onSelect:s,isSyncing:r,searchQuery:i,onSearchChange:l,formatChatDate:d,leadForChat:c,draftForChat:u,onResync:m,attendanceFilter:x,onAttendanceFilter:f,leads:p,filter:g,onFilter:y,chatTypeFilter:k,onChatTypeFilter:_,iaHabilitada:N,favoritesOnly:I,onFavoritesOnly:P,onToggleFavorite:D}){var C;const V=n.useMemo(()=>({all:p.filter(b=>!["closed","lost"].includes(b.status)).length,attention:p.filter(b=>b.status==="hot").length,active:p.filter(b=>["hot","warm"].includes(b.status)).length,cold:p.filter(b=>b.status==="cold").length,closed:p.filter(b=>["closed","lost"].includes(b.status)).length}),[p]),R=(Go.find(b=>b.id===g)??Go[0]).icon,M=g!=="all"||k!=="individual",$=k!=="individual"?((C=hd.find(b=>b.id===k))==null?void 0:C.label)??fd[g]:fd[g];return e.jsxs("div",{className:`flex-1 min-w-0 md:flex-none md:w-[320px] flex-col border-r bg-card ${a?"hidden md:flex":"flex"}`,children:[e.jsxs("div",{className:"px-4 h-14 flex items-center justify-between border-b flex-shrink-0",children:[e.jsx("h1",{className:"text-base font-semibold text-foreground",children:"Conversas"}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:()=>P(!I),title:I?"Mostrar todas as conversas":"Só favoritas",className:`p-2 rounded-full transition-colors ${I?"text-warning-text bg-warning/10":"text-muted-foreground hover:text-foreground hover:bg-muted"}`,children:e.jsx(Ha,{className:`w-[18px] h-[18px] ${I?"fill-warning":""}`})}),m&&e.jsx("button",{onClick:m,disabled:r,className:"p-2 -mr-2 rounded-full text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40",title:"Carregar mais chats do WhatsApp",children:e.jsx(jt,{className:`w-[18px] h-[18px] ${r?"animate-spin":""}`})})]}),e.jsx("div",{className:"px-3 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center bg-muted rounded-lg px-3 py-2 gap-2",children:[e.jsx(zn,{className:"w-4 h-4 text-muted-foreground flex-shrink-0"}),e.jsx("input",{type:"text",placeholder:"Buscar conversa...",value:i,onChange:b=>l(b.target.value),className:"bg-transparent border-none outline-none text-sm text-foreground placeholder:text-muted-foreground w-full"})]})}),e.jsxs("div",{className:"px-3 pb-2 flex items-center gap-1 overflow-x-auto scrollbar-none flex-shrink-0",children:[e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsxs("button",{title:"Filtrar conversas",className:`text-[11px] px-2 py-1 rounded-full whitespace-nowrap transition-colors flex items-center gap-1 flex-shrink-0 ${M?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted"}`,children:[e.jsx(R,{className:"w-3 h-3 flex-shrink-0"}),$,e.jsx(dt,{className:"w-3 h-3 flex-shrink-0 opacity-70"})]})}),e.jsxs(Fa,{align:"start",className:"w-48",children:[N&&e.jsxs(e.Fragment,{children:[e.jsx(Gl,{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Leads"}),Go.map(({id:b,label:v,icon:F})=>e.jsxs(xt,{onClick:()=>y(b),className:`text-xs gap-2 ${g===b?"bg-accent font-medium":""}`,children:[e.jsx(F,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsx("span",{className:"flex-1",children:v}),V[b]>0&&e.jsx("span",{className:"text-muted-foreground",children:V[b]})]},b)),e.jsx(Zm,{})]}),e.jsx(Gl,{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Tipo de conversa"}),hd.map(({id:b,label:v,icon:F})=>e.jsxs(xt,{onClick:()=>_(b),className:`text-xs gap-2 ${k===b?"bg-accent font-medium":""}`,children:[e.jsx(F,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsx("span",{className:"flex-1",children:v})]},`ct-${b}`))]})]}),e.jsx("span",{className:"w-px h-4 bg-border mx-1 flex-shrink-0","aria-hidden":!0}),Iv.map(({id:b,label:v})=>e.jsx("button",{onClick:()=>f(b),className:`text-[11px] px-2 py-1 rounded-full whitespace-nowrap transition-colors ${x===b?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted"}`,children:v},`att-${b}`))]}),e.jsx("div",{className:"border-b flex-shrink-0"}),r&&e.jsx("div",{className:"h-0.5 w-full overflow-hidden bg-muted",children:e.jsx("div",{className:"h-full bg-primary animate-[loading-bar_1.5s_ease-in-out_infinite]",style:{width:"40%",animation:"loading-bar 1.5s ease-in-out infinite"}})}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-none",children:r&&t.length===0?e.jsx("div",{className:"space-y-0",children:Array.from({length:6}).map((b,v)=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-3 border-b",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-muted animate-pulse flex-shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-3 bg-muted animate-pulse rounded",style:{width:`${60+v%3*15}%`}}),e.jsx("div",{className:"h-2.5 bg-muted animate-pulse rounded",style:{width:`${40+v%4*10}%`}})]})]},v))}):t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-6 text-center",children:[e.jsx(fa,{className:"w-10 h-10 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma conversa encontrada"})]}):t.map(b=>{const v=c(b),F=N?(v==null?void 0:v.status)==="hot"?"hot":(v==null?void 0:v.status)==="warm"?"warm":v?"cold":null:null,U=b.chatType||(b.isGroup?"group":"individual"),te=U==="group"?bi:U==="community"?du
166:U==="channel"?nf:U==="broadcast"?Ym:ps,q=U==="group"?"Grupo":U==="community"?"Comunidade":U==="channel"?"Canal":U==="broadcast"?"Broadcast":null;return e.jsxs("div",{className:"relative group",children:[e.jsxs("button",{onClick:()=>s(b.id),className:`w-full text-left flex items-center gap-3 px-3 py-3 pr-8 border-b transition-colors ${a===b.id?"bg-primary/10 border-l-2 border-l-primary":"hover:bg-muted border-l-2 border-l-transparent"}`,children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold ${U==="individual"?"bg-primary/10 text-primary":U==="group"||U==="community"?"bg-primary/10 text-primary-text":U==="channel"?"bg-warning/10 text-warning-text":"bg-muted text-muted-foreground"}`,children:U==="individual"?Wn(Dd(b.name)?"?":b.name):e.jsx(te,{className:"w-5 h-5"})}),F&&e.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 rounded-full border-2 border-background ${F==="hot"?"bg-[hsl(var(--status-hot))]":F==="warm"?"bg-[hsl(var(--status-warm))]":"bg-[hsl(var(--status-cold))]"}`})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex justify-between items-center mb-0.5",children:[e.jsxs("span",{className:"text-sm font-medium text-foreground truncate flex items-center gap-1.5",children:[Fn(b.name,b.phone,b.id),U==="individual"&&(v?e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-primary/10 text-primary font-medium flex-shrink-0",title:"Lead em acompanhamento",children:"lead"}):e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground font-medium flex-shrink-0",title:"Contato sem interação registrada ainda",children:"novo"})),(()=>{const Z=v?Ei(v.source,v.referral,v.adPlatform):null;return Z?e.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded font-medium flex-shrink-0 ${Z.className}`,title:Z.tooltip,children:Z.label}):null})(),q&&e.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded font-normal flex-shrink-0 ${U==="group"||U==="community"?"bg-primary/10 text-primary-text":U==="channel"?"bg-warning/10 text-warning-text":"bg-muted text-muted-foreground"}`,children:q}),(u==null?void 0:u(b))&&e.jsxs("span",{className:"text-[9px] px-1 py-0.5 rounded bg-warning/20 text-warning font-medium flex items-center gap-0.5 flex-shrink-0",title:"Rascunho do agente aguardando aprovação",children:[e.jsx(Ge,{className:"w-2.5 h-2.5"})," aprovar"]}),(v==null?void 0:v.attendanceStatus)==="aguardando_nos"&&e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-destructive/15 text-destructive-text font-medium flex-shrink-0",title:"Cliente aguardando resposta",children:"responder"}),(v==null?void 0:v.attendanceStatus)==="resolvido"&&e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-success/15 text-success-text font-medium flex-shrink-0",title:"Atendimento resolvido",children:"resolvido"}),(v==null?void 0:v.attendanceOwner)==="humano"&&e.jsxs("span",{className:"text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground font-medium flex-shrink-0 flex items-center gap-0.5",title:"Humano assumiu a conversa",children:[e.jsx(ps,{className:"w-2.5 h-2.5"})," humano"]})]}),e.jsx("span",{className:`text-[10px] flex-shrink-0 ml-1 ${b.unreadCount>0?"text-primary":"text-muted-foreground"}`,children:b.lastMessageTimestamp?d(b.lastMessageTimestamp):""})]}),e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsxs("span",{className:"text-xs text-muted-foreground truncate flex-1",children:[v&&N?`Score ${v.closingScore} · `:"",b.lastMessage||""]}),(v==null?void 0:v.attendanceStatus)==="aguardando_nos"&&v.attendanceWaitingSince&&e.jsx("span",{className:"text-[10px] text-destructive-text flex-shrink-0",title:"Tempo aguardando resposta",children:am(v.attendanceWaitingSince)}),b.unreadCount>0&&e.jsx("span",{className:"bg-primary text-primary-foreground text-[10px] rounded-full min-w-[18px] h-[18px] flex items-center justify-center px-1 flex-shrink-0",children:b.unreadCount>99?"99+":b.unreadCount})]})]})]}),v&&e.jsx("button",{onClick:Z=>{Z.stopPropagation(),D(v.id)},title:v.favoritedAt?"Remover dos favoritos":"Favoritar conversa",className:`absolute top-2.5 right-2 p-1 rounded-full transition-opacity ${v.favoritedAt?"opacity-100":"opacity-0 group-hover:opacity-100 focus:opacity-100"}`,children:e.jsx(Ha,{className:`w-3.5 h-3.5 ${v.favoritedAt?"fill-warning text-warning-text":"text-muted-foreground"}`})})]},b.id)})})]})}const Dy=()=>{const{user:t}=Sa(),a=(t==null?void 0:t.role)==="admin"||(t==null?void 0:t.role)==="super_admin"||(t==null?void 0:t.role)==="manager",[s,r]=n.useState([]),[i,l]=n.useState(void 0),d=i??(t==null?void 0:t.id),c=!!i&&i!==(t==null?void 0:t.id),[u,m]=n.useState(null),[x,f]=n.useState(!0),[p,g]=n.useState(!1),y=Tr(N=>N.selectedCompanyId)??void 0;n.useEffect(()=>{if(!a){r([]);return}Rd(y).then(r).catch(()=>r([]))},[a,y]),n.useEffect(()=>{d&&(m(null),Je(`/api/whatsapp/status/${d}`).then(N=>N.json()).then(N=>m(!!N.connected)).catch(()=>m(!1)))},[d]);const k=n.useCallback(async()=>
166{if(!(!(t!=null&&t.id)||c)){try{await Je(`/api/whatsapp/disconnect/${t.id}`,{method:"POST"})}catch(N){console.error("[AgentInbox] disconnect error:",N)}m(!1)}},[t==null?void 0:t.id,c]),_=a&&s.length>0?e.jsxs("select",{value:i??"",onChange:N=>l(N.target.value||void 0),className:"rounded-md bg-card border border-input text-foreground text-xs px-3 py-1.5 outline-none focus:ring-1 focus:ring-primary cursor-pointer",title:"Ver a inbox de outro vendedor (somente leitura)",children:[e.jsx("option",{value:"",children:"Minha inbox"}),s.filter(N=>N.id!==(t==null?void 0:t.id)).map(N=>e.jsx("option",{value:N.id,children:N.name},N.id))]}):null;return u===null?e.jsx("div",{className:"flex items-center justify-center h-full min-h-[400px]",children:e.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full"})}):!u&&c?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full min-h-[400px] p-8",children:[_&&e.jsx("div",{className:"mb-6",children:_}),e.jsx("h1",{className:"text-2xl font-heading font-bold mb-2",children:"Agent Inbox"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-sm",children:"Esse vendedor ainda não conectou o WhatsApp. Nada pra mostrar aqui."})]}):!u&&!x?a&&!p?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full min-h-[400px] p-8",children:[_&&e.jsx("div",{className:"mb-6",children:_}),e.jsx(Ge,{className:"w-10 h-10 text-primary mb-3"}),e.jsx("h1",{className:"text-2xl font-heading font-bold mb-2",children:"Agent Inbox"}),e.jsx("p",{className:"text-muted-foreground mb-8 text-center max-w-sm",children:"Acompanhe as conversas do agente no WhatsApp da empresa sem precisar conectar um número próprio."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Pe,{onClick:()=>f(!0),className:"gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"})," Ver conversas do agente"]}),e.jsxs(Pe,{variant:"outline",onClick:()=>g(!0),className:"gap-2",children:[e.jsx(fa,{className:"w-4 h-4"})," Conectar meu WhatsApp"]})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full min-h-[400px] p-8",children:[_&&e.jsx("div",{className:"mb-6",children:_}),e.jsx("h1",{className:"text-2xl font-heading font-bold mb-2",children:"Agent Inbox"}),e.jsx("p",{className:"text-muted-foreground mb-8 text-center max-w-sm",children:"Conecte seu WhatsApp para começar a receber e responder mensagens dos seus leads."}),e.jsx(Lx,{sellerId:t==null?void 0:t.id,sellerName:(t==null?void 0:t.name)||"Vendedor",onSuccess:()=>m(!0)}),a&&e.jsx("button",{onClick:()=>{g(!1),f(!0)},className:"mt-6 text-sm text-muted-foreground hover:text-foreground underline",children:"Pular e ver só as conversas do agente"})]}):e.jsx(Rv,{onDisconnect:k,startInAgentView:!u,viewSellers:s,viewSellerId:i,onViewSellerChange:a?l:void 0},d)};function Ks(t){const a=t.replace(/\D/g,"");return a.startsWith("55")&&a.length>=12?a.slice(2):a}const Rv=({onDisconnect:t,startInAgentView:a=!1,viewSellers:s=[],viewSellerId:r,onViewSellerChange:i})=>{var Qt,gn;const{user:l}=Sa(),d=(l==null?void 0:l.role)==="admin"||(l==null?void 0:l.role)==="super_admin",c=d,u=d||(l==null?void 0:l.role)==="manager",m=d||(l==null?void 0:l.role)==="manager",x=!!r&&r!==(l==null?void 0:l.id),f=r||(l==null?void 0:l.id),[p,g]=n.useState([]),y=Tr(j=>j.selectedCompanyId),k=Tr(j=>j.setSelectedCompanyId),N=(l==null?void 0:l.role)==="admin"||(l==null?void 0:l.role)==="super_admin"?y??void 0:(l==null?void 0:l.companyId)??void 0,I=j=>k(j??null),[P,D]=n.useState(!1),V=j=>{if(j==="__all__"){D(!0);return}D(!1),I(j)},{query:R}=Gn(N),M=Kr((Qt=R.data)==null?void 0:Qt.capabilities),$=Mi((gn=R.data)==null?void 0:gn.capabilities);n.useEffect(()=>{const j=localStorage.getItem("authToken");fetch("https://leadsense.solutions/api/auth/companies",{headers:j?{Authorization:`Bearer ${j}`}:{}}).then(z=>z.ok?z.json():null).then(z=>{Array.isArray(z)&&g(z)}).catch(()=>{})},[]);const C=r??(m||l==null?void 0:l.id),{connection:b,isSyncing:v,chats:F,selectedChatId:U,setSelectedChatId:te,getMessages:q,sendMessage:Z,loadChatMessages:ae,getStats:ce,resyncChats:se}=pf({autoConnect:!!C,sellerId:C}),{filter:Q,setFilter:K,leads:G,refreshLeads:L,toggleFavorite:S}=gf(N);n.useEffect(()=>{!$&&Q!=="all"&&K("all")},[$,Q,K]),n.useEffect(()=>{i==null||i(void 0),te(null)},[N,i,te]);const[B,H]=n.useState(()=>typeof window>"u"||window.innerWidth>=768),[W,X]=n.useState(""),[oe,O]=n.useState(!1),[be,fe]=n.useState(""),[pe,Me]=n.useState("individual"),[je,Oe]=n.useState("venda"),[Ee,ye]=n.useState(!1),[Le,Ne]=n.useState(!1),[Se,ke]=n.useState("list"),ht=n.useMemo(()=>
166{if(P)return p;if(!N)return[];const j=p.find(z=>z.id===N);return[{id:N,name:(j==null?void 0:j.name)||""}]},[P,N,p]),{stages:yt,leads:Ye,isLoading:Nt,refetch:Zt}=Sv(ht,Se==="kanban"),Et=n.useMemo(()=>{const j=new Map;for(const z of yt)j.set(z.id,[]);for(const z of Ye){const de=j.get(z.stageId);de&&de.push(z)}for(const z of j.values())z.sort((de,ge)=>ge.score-de.score);return j},[yt,Ye]),ha=Kl({mutationFn:({leadId:j,stageId:z})=>tu(j,z),onError:j=>Ht({title:"Não consegui mover o card",description:He(j),variant:"destructive"}),onSettled:()=>Zt()}),ga=Kl({mutationFn:j=>au(j),onError:j=>Ht({title:"Não consegui arquivar o card",description:He(j),variant:"destructive"}),onSuccess:()=>Ht({title:"Card arquivado",description:"Saiu do funil. A conversa continua no inbox."}),onSettled:()=>Zt()}),it=["admin","super_admin","manager"].includes(((l==null?void 0:l.role)||"").toLowerCase()),[ut,Yt]=n.useState(null),ba=j=>{if(P&&j.companyId&&j.companyId!==N){V(j.companyId),Ht({title:`Trocando pra ${j.companyName||"a empresa"}...`,description:"Clique no card de novo pra abrir a conversa."});return}Yt({leadId:j.id,name:j.nome,phone:j.telefone,nonce:Date.now()}),ke("list")},va=20,wt=n.useMemo(()=>{const j=[];for(const z of Et.values())for(const de of z.slice(0,va))j.push({id:de.id,name:de.nome});return j},[Et]),[zt,ea]=n.useState({}),[J,he]=n.useState(!1),Fe=n.useMemo(()=>{const j={};for(const z of wt)j[z.id]=zt[z.id]??null;return j},[wt,zt]),Ke=wt.map(j=>j.id).sort().join(",");n.useEffect(()=>{if(Se!=="kanban"||wt.length===0)return;let j=!1;return he(!0),Ld(wt,N).then(z=>{j||ea(de=>({...de,...z}))}).catch(z=>console.error("[AgentInbox] recap do Kanban:",z)).finally(()=>{j||he(!1)}),()=>{j=!0}},[Se,Ke]);const[lt,ze]=n.useState([]),[et,ta]=n.useState(!1),[qt,mt]=n.useState([]),[Bt,tt]=n.useState(0),[xs,Ut]=n.useState(0),[pn,Wa]=n.useState(0),{toast:Ht}=At(),{sessions:w,loading:qe,sessionByPhone:Vt}=Cv(je==="onboarding"),fs=n.useRef(null),at=n.useRef(null);ce(),Tn(j=>{var z;return U?((z=j.messagesByChat.get(U))==null?void 0:z.length)??0:0});const Wt=U?q(U):_v,ne=F.find(j=>j.id===U)??null,{drafts:Dt,refresh:Ve}=vf("pending"),gt=Dt.length,[Gt]=n.useState(!0),Ga=n.useMemo(()=>{const j=new Map;for(const z of Dt)z.contact_phone&&j.set(Ks(z.contact_phone),z);return j},[Dt]),st=n.useCallback(j=>{const z=Ks(j.phone||j.id.replace("@c.us","").replace("@g.us",""));return Ga.get(z)??null},[Ga]),aa=n.useMemo(()=>{const j=new Map;for(const z of G)j.set(Ks(z.contactPhone),z);return j},[G]),re=n.useCallback(j=>{const z=Ks(j.phone||j.id.replace("@c.us","").replace("@g.us",""));return aa.get(z)??null},[aa]),[Xe,_a]=n.useState("all"),[hs,$t]=n.useState(!1),Ka={all:null,attention:["hot"],active:["hot","warm"],cold:["cold"],closed:["closed","lost"]},Aa=F.filter(j=>{if(j.archived||be&&!j.name.toLowerCase().includes(be.toLowerCase())||pe!=="all"&&(j.chatType||(j.isGroup?"group":"individual"))!==pe)return!1;if(Q!=="all"){const z=Ka[Q];if(z){const de=re(j);if(!de||!z.includes(de.status))return!1}}if(Xe!=="all"){const z=re(j);if(!z||z.attendanceStatus!==Xe)return!1}if(hs){const z=re(j);if(!(z!=null&&z.favoritedAt))return!1}return!0}).sort((j,z)=>{var me,bt;const de=st(j)?1:0,ge=st(z)?1:0;if(de!==ge)return ge-de;const Ue=(me=re(j))!=null&&me.favoritedAt?1:0,ct=(bt=re(z))!=null&&bt.favoritedAt?1:0;return Ue!==ct?ct-Ue:j.pinned&&!z.pinned?-1:!j.pinned&&z.pinned?1:(z.lastMessageTimestamp||0)-(j.lastMessageTimestamp||0)}),Ea=F.reduce((j,z)=>j+(z.unreadCount||0),0),sa=yf(),ja=Nf(),Qa=n.useRef(null),xe=n.useRef(null);n.useEffect(()=>{Qa.current!==null&&Ea>Qa.current&&(sa(),ja({title:"Nova mensagem",body:"Você tem mensagens novas no inbox."})),Qa.current=Ea},[Ea,sa,ja]),n.useEffect(()=>{xe.current!==null&>>xe.current&&(sa(),ja({title:"Sugestão do agente",body:"Há um rascunho do agente aguardando aprovação."})),xe.current=gt},[gt,sa,ja]),n.useEffect(()=>{var j;(j=fs.current)==null||j.scrollIntoView({behavior:"smooth"})},[Wt]),n.useEffect(()=>{var j;U&&((j=at.current)==null||j.focus())},[U]);const Te=Tn(j=>j.updateChat),nt=n.useCallback(async j=>{te(j),Te(j,{unreadCount:0});const z=F.find(ge=>ge.id===j);if(z){const ge=z.phone||z.id.replace("@c.us","").replace("@g.us",""),Ue=Vt(ge);(Ue==null?void 0:Ue.status)==="active"&&Oe("onboarding")}const de=q(j).length>0;de||O(!0);try{await ae(j)}finally{de||O(!1)}},[te,Te,F,Vt,Oe,q,ae]),na=n.useCallback(j=>{const z=j.replace(/\D/g,""),de=F.find(ge=>{const Ue=(ge.phone||ge.id.replace("@c.us","").replace("@g.us","")).replace(/\D/g,"");return Ue===z||Ue.endsWith(z)||z.endsWith(Ue)});de&&nt(de.id)},[F,nt]),Kt=n.useCallback(async()=>
166{if(x||!W.trim()||!U)return;const j=W;X(""),await Z(U,j)},[x,W,U,Z]),Pt=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),et?Is():Kt())},ue=n.useMemo(()=>ne?re(ne):null,[ne,re]),xn=n.useCallback(async()=>{if(ue)try{ue.attendanceStatus==="resolvido"?await Rp(ue.id,N):await Op(ue.id,N),L()}catch(j){console.error("toggle resolve falhou",j)}},[ue,L,N]),Ts=n.useCallback(async()=>{if(ue)try{await Md(ue.id),L()}catch(j){console.error("takeover falhou",j)}},[ue,L]),Ja=n.useCallback(async()=>{if(ue)try{await Td(ue.id),L()}catch(j){console.error("return-to-agent falhou",j)}},[ue,L]),[gs,Xa]=n.useState(!1),bs=n.useCallback(async()=>{if(ue&&window.confirm(`Zerar TODO o histórico e estado de ${ue.contactName||ue.contactPhone}? Apaga conversa, análises e dados (Postgres). Não dá pra desfazer.`)){Xa(!0);try{let j;try{j=await ei(ue.id)}catch(z){if((z==null?void 0:z.codigo)!=="venda_concluida")throw z;const ge=He(z);if(!window.confirm(`${ge} 167 168Zerar mesmo assim?`))return;j=await ei(ue.id,!0)}Ht({title:"Lead zerado",description:`${j.mongo.conversations} conversa + ${j.mongo.analyses} análises apagadas. Pronto pra testar.`}),L(),U&&await ae(U).catch(()=>{})}catch(j){Ht({title:"Falha no reset",description:He(j),variant:"destructive"})}finally{Xa(!1)}}},[ue,U,L,ae,Ht]),ya=n.useMemo(()=>{if(!ue||ue.attendanceOwner!=="humano")return null;const j=ue.attendanceSince?am(ue.attendanceSince):"";return`${uu(ue.attendanceReason,ue.attendanceByName)} ${j}`.trim()},[ue]);n.useEffect(()=>{if(!ue){ze([]);return}let j=!1;return Yl(ue.id).then(z=>{j||ze(z)}).catch(()=>{}),()=>{j=!0}},[ue]);const Da=n.useCallback(()=>{Rd(N).then(mt).catch(()=>{})},[N]);n.useEffect(()=>{Da()},[Da]);const Za=n.useCallback(async j=>{if(ue)try{await Fp(ue.id,j,N),L(),Da()}catch(z){console.error("assign falhou",z)}},[ue,L,Da,N]),Is=n.useCallback(async()=>{if(!W.trim()||!ue)return;const j=W;X("");try{await zp(ue.id,j),ze(await Yl(ue.id))}catch(z){console.error("addNote falhou",z)}},[W,ue]),Ya=n.useMemo(()=>{const j=ge=>ge<1e12?ge*1e3:ge,z=Wt.map(ge=>({kind:"msg",ms:j(Number(ge.timestamp)||0),msg:ge})),de=lt.map(ge=>({kind:"note",ms:new Date(ge.createdAt).getTime()||0,note:ge}));return[...z,...de].sort((ge,Ue)=>ge.ms-Ue.ms)},[Wt,lt]),A=n.useCallback(j=>{var z;X(j),(z=at.current)==null||z.focus()},[]),T=j=>{const z=j<1e12?j*1e3:j;return new Date(z).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:cn()})},Y=j=>{const z=new Date(j),de=new Date;de.setHours(0,0,0,0);const ge=new Date(z);ge.setHours(0,0,0,0);const Ue=Math.floor((de.getTime()-ge.getTime())/864e5);if(Ue===0)return"Hoje";if(Ue===1)return"Ontem";if(Ue>1&&Ue<7)return z.toLocaleDateString("pt-BR",{weekday:"long"});const ct=z.getFullYear()===de.getFullYear();return z.toLocaleDateString("pt-BR",ct?{day:"2-digit",month:"long"}:{day:"2-digit",month:"long",year:"numeric"})},we=j=>{const z=j<1e12?j*1e3:j,de=new Date(z),ge=new Date;ge.setHours(0,0,0,0);const Ue=new Date(de);Ue.setHours(0,0,0,0);const ct=Math.floor((ge.getTime()-Ue.getTime())/864e5);return ct===0?de.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:cn()}):ct===1?"ontem":ct<7?de.toLocaleDateString("pt-BR",{weekday:"short"}):de.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})},Ze=ne?re(ne):null,kt=ne?Ze??ec({id:ne.id,contactName:Fn(ne.name,ne.phone,ne.id),contactPhone:ne.phone||ne.id.replace("@c.us","").replace("@g.us",""),status:"warm",closingScore:50,lastContactAt:ne.lastMessageTimestamp?new Date(ne.lastMessageTimestamp<1e12?ne.lastMessageTimestamp*1e3:ne.lastMessageTimestamp).toISOString():null}):null,Ls=Wt.map(j=>({id:j.id,text:j.body||"",isOutgoing:j.fromMe,timestamp:new Date(j.timestamp<1e12?j.timestamp*1e3:j.timestamp).toISOString()})),fn=ne?Wn(Dd(ne.name)?"?":ne.name):"",Be=ne?st(ne):null,{config:ra}=yi((Be==null?void 0:Be.company_id)||null),Na=Ni(ra==null?void 0:ra.agent_display_name),Mt=n.useMemo(()=>{let j=null;for(const z of Dt)z.created_at&&(!j||new Date(z.created_at).getTime()<new Date(j.created_at).getTime())&&(j=z);return j},[Dt]),oa=n.useMemo(()=>{if(!(Mt!=null&&Mt.created_at))return null;const j=Math.floor((Date.now()-new Date(Mt.created_at).getTime())/6e4);if(!Number.isFinite(j)||j<1)return"agora";if(j<60)return`há ${j}min`;const z=Math.floor(j/60);return z<24?`há ${z}h`:`há ${Math.floor(z/24)}d`},[Mt]),Jn=n.useCallback(()=>{const j=Mt!=null&&Mt.contact_phone?Ks(Mt.contact_phone):null;if(!j)return;const z=Aa.find(de=>Ks(de.phone||de.id.replace("@c.us","").replace("@g.us",""))===j);z&&nt(z.id)},[Mt,Aa,nt]),[to,hn]=n.useState(!1);n.useEffect(()=>{xe.current!==null&>>xe.current&&hn(!1)},[gt]);const Xn=()=>
168{if(Ve(),Gt){const j=Aa.find(z=>z.id!==U&&st(z));j&&nt(j.id)}},vs=(Ze==null?void 0:Ze.id)??null;n.useEffect(()=>{if(!U||!vs)return;const j=rn();if(!j)return;const z=de=>{de!=null&&de.leadId&&de.leadId===vs&&(ae(U).catch(()=>{}),Ve(),Wa(ge=>ge+1))};return j.on("inbox:lead-changed",z),()=>{j.off("inbox:lead-changed",z),on()}},[U,vs,ae,Ve]);const Zn={isSyncing:v,connectedNumber:(b==null?void 0:b.connectedNumber)||(a?"Agente (WhatsApp da empresa)":""),onDisconnect:t,showDisconnect:!a,mode:je,onboardingSessions:w,onboardingLoading:qe,onSelectPhoneInChat:na,companies:p,activeCompanyId:N,onCompanyChange:V,allCompanies:P,onToggleKanban:()=>ke(j=>j==="kanban"?"list":"kanban"),kanbanActive:Se==="kanban",onToggleKpis:()=>ke(j=>j==="kpis"?"list":"kpis"),kpisActive:Se==="kpis",viewSellers:s,viewSellerId:r,ownSellerId:l==null?void 0:l.id,onViewSellerChange:i,settingsActive:Ee,onToggleSettings:()=>ye(j=>!j)};return e.jsxs("div",{className:"h-[100dvh] flex flex-col bg-background overflow-hidden",children:[gt>0&&!to&&e.jsxs("div",{className:"flex items-center gap-2 border-b border-warning/30 bg-warning/15 px-3 py-1.5 text-xs text-foreground flex-shrink-0 sm:px-4 sm:text-sm",children:[e.jsx(Ge,{className:"h-4 w-4 flex-shrink-0 text-warning-text"}),e.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[e.jsx("strong",{children:gt})," ",gt===1?"rascunho":"rascunhos"," aguardando aprovação",oa&&e.jsxs("span",{className:"text-muted-foreground",children:[" · o mais antigo ",oa]})]}),e.jsx("button",{type:"button",onClick:Jn,className:"flex-shrink-0 rounded-md px-2 py-0.5 font-medium text-warning-text underline-offset-2 hover:bg-warning/20 hover:underline",children:"Revisar"}),e.jsx("button",{type:"button",onClick:()=>hn(!0),"aria-label":"Dispensar aviso da fila de aprovação",className:"flex-shrink-0 rounded-md p-0.5 text-muted-foreground hover:bg-warning/20 hover:text-foreground",children:e.jsx(vt,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex-1 flex overflow-hidden relative",children:[e.jsx(gd,{...Zn,className:"hidden md:flex"}),e.jsx(mu,{open:Le,onOpenChange:Ne,children:e.jsxs(Di,{side:"left",className:"w-auto p-0 border-0 bg-transparent [&>button]:hidden md:hidden",children:[e.jsx($i,{className:"sr-only",children:"Navegação"}),e.jsx(fu,{className:"sr-only",children:"Modos de análise, empresa e configurações do inbox"}),e.jsx(gd,{...Zn,onNavigate:()=>Ne(!1)})]})}),Ee&&e.jsx("div",{className:"absolute inset-y-0 right-0 left-0 md:left-[64px] z-40 flex bg-background",children:e.jsx(Rb,{onClose:()=>ye(!1),companyId:N,isAdmin:d})}),Se==="kanban"&&e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-4 h-14 flex items-center gap-2 border-b flex-shrink-0 bg-card",children:[e.jsx(iu,{className:"w-[18px] h-[18px] text-primary"}),e.jsx("h1",{className:"text-base font-semibold text-foreground",children:"Kanban"}),P&&e.jsx("span",{className:"text-[11px] px-1.5 py-0.5 rounded-md bg-primary/10 text-primary-text font-medium",children:"Todas as empresas"}),e.jsx("div",{className:"flex-1"}),e.jsxs("button",{onClick:()=>ke("list"),title:"Ver como lista",className:"inline-flex items-center gap-1.5 h-8 px-2.5 rounded-md text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:[e.jsx(pc,{className:"w-3.5 h-3.5"})," Lista"]})]}),e.jsx("div",{className:"flex-1 overflow-auto p-3",children:Nt&&yt.length===0?e.jsx("div",{className:"text-sm text-muted-foreground p-3",children:"Carregando Kanban..."}):yt.length===0?e.jsx("div",{className:"text-sm text-muted-foreground p-3",children:"Nenhuma etapa configurada."}):e.jsx(Rx,{stages:yt,leadsByStage:Et,embedded:!0,onCardClick:ba,onMoveLead:(j,z)=>ha.mutate({leadId:j,stageId:z}),onArchive:it?j=>{window.confirm(`Arquivar "${j.nome||"este card"}"? Ele sai do funil. A conversa continua no inbox e dá pra reverter.`)&&ga.mutate(j.id)}:void 0,showCompanyBadge:P,recapByLeadId:Fe,recapsLoading:J})})]}),Se==="kpis"&&e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-4 h-14 flex items-center gap-2 border-b flex-shrink-0 bg-card",children:[e.jsx(Yo,{className:"w-[18px] h-[18px] text-primary"}),e.jsx("h1",{className:"text-base font-semibold text-foreground",children:"KPIs"}),e.jsx("div",{className:"flex-1"}),e.jsx(Wm,{to:"/funil",className:"inline-flex items-center gap-1.5 h-8 px-2.5 rounded-md text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",title:"Ver todos os detalhes (fora do Inbox)",children:"Ver tudo"}),e.jsxs("button",{onClick:()=>ke("list"),title:"Ver como lista",className:"inline-flex items-center gap-1.5 h-8 px-2.5 rounded-md text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:[e.jsx(pc,{className:"w-3.5 h-3.5"})," Lista"]})]}),e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(lx,{onAbrirLead:(j,z)=>
168{Yt({leadId:j,name:z,phone:null,nonce:Date.now()}),ke("list")}})})]}),!Gt&&Se==="list"&&e.jsxs(e.Fragment,{children:[e.jsx(Lv,{chats:Aa,selectedId:U,onSelect:nt,isSyncing:v,searchQuery:be,onSearchChange:fe,formatChatDate:we,leadForChat:re,draftForChat:st,onResync:se,attendanceFilter:Xe,onAttendanceFilter:_a,leads:G,filter:Q,onFilter:K,chatTypeFilter:pe,onChatTypeFilter:Me,iaHabilitada:$,favoritesOnly:hs,onFavoritesOnly:$t,onToggleFavorite:S}),e.jsxs("div",{className:`flex-1 flex-col min-w-0 relative ${ne?"flex":"hidden md:flex"}`,children:[ne?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"h-16 border-b bg-card flex items-center justify-between px-3 sm:px-5 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0",children:[e.jsx("button",{onClick:()=>te(null),"aria-label":"Voltar para a lista",className:"md:hidden -ml-1 flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(un,{className:"h-5 w-5"})}),e.jsx("div",{className:"w-9 h-9 shrink-0 rounded-full bg-primary/10 flex items-center justify-center text-primary text-sm font-semibold",children:fn}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:Fn(ne.name,ne.phone,ne.id)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ne.phone||ne.id.replace("@c.us","")})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ue&&qt.length>0&&e.jsxs("select",{value:ue.assignedTo||"",onChange:j=>Za(j.target.value||null),className:"h-8 text-xs rounded-md border border-input bg-background px-2 max-w-[160px] outline-none focus:ring-2 focus:ring-ring",title:"Atribuir vendedor (responsável pelo lead)",children:[e.jsx("option",{value:"",children:"Sem dono"}),qt.map(j=>e.jsxs("option",{value:j.id,children:[j.name," (",j.openLeads,")"]},j.id))]}),ue&&(ue.attendanceOwner==="humano"?e.jsxs(Pe,{variant:"outline",size:"sm",className:"h-8 text-xs",onClick:Ja,title:"Devolver a conversa pro agente (reativa o bot)",children:[e.jsx(Ge,{className:"w-3.5 h-3.5 mr-1"})," Devolver ao agente"]}):e.jsxs(Pe,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:Ts,title:"Assumir a conversa (silencia o agente)",children:[e.jsx(ps,{className:"w-3.5 h-3.5 mr-1"})," Assumir"]})),ue&&e.jsx(Pe,{variant:ue.attendanceStatus==="resolvido"?"outline":"ghost",size:"sm",className:"h-8 text-xs",onClick:xn,title:ue.attendanceStatus==="resolvido"?"Reabrir atendimento":"Marcar atendimento como resolvido",children:ue.attendanceStatus==="resolvido"?"Reabrir":"Resolver"}),ue&&c&&e.jsx(Pe,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground/60 hover:text-destructive hover:bg-destructive/10",disabled:gs,onClick:bs,title:"Zerar histórico e dados do lead (teste): apaga conversa, análises e estado",children:gs?e.jsx(le,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ds,{className:"w-3.5 h-3.5"})}),e.jsx(Pe,{variant:"ghost",size:"icon",className:`h-8 w-8 ${B?"text-primary bg-primary/10":""}`,onClick:()=>H(j=>!j),title:"Análise IA",children:e.jsx(Bx,{className:"w-4 h-4"})})]})]}),ue&&(ue.attendanceOwner==="humano"?e.jsxs("div",{className:"px-5 py-1.5 bg-warning/10 border-b border-warning/20 text-[11px] text-warning-text flex items-center gap-1.5 flex-shrink-0",children:[e.jsx(ps,{className:"w-3 h-3"})," ",ya||"Humano no comando",", agente pausado neste chat"]}):e.jsxs("div",{className:"px-5 py-1.5 bg-primary/5 border-b text-[11px] text-muted-foreground flex items-center gap-1.5 flex-shrink-0",children:[e.jsx(Ge,{className:"w-3 h-3"})," Agente ativo neste chat"]})),e.jsxs("div",{className:"flex-1 overflow-y-auto scrollbar-none p-4 space-y-2 bg-muted/20",children:[oe?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(jt,{className:"w-6 h-6 text-primary animate-spin"})}):Ya.length===0?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma mensagem carregada"})}):Ya.map((j,z)=>{const de=z>0?Ya[z-1]:null,ge=bt=>{const ia=new Date(bt);return`${ia.getFullYear()}-${ia.getMonth()}-${ia.getDate()}`},ct=!de||ge(de.ms)!==ge(j.ms)?e.jsx("div",{className:"flex justify-center my-2",children:e.jsx("span",{className:"text-[11px] font-medium px-3 py-1 rounded-full bg-muted text-muted-foreground shadow-sm",children:Y(j.ms)})},`sep-${j.ms}`):null;if(j.kind==="note"){const bt=j.note;return e.jsxs(n.Fragment,{children:[ct,e.jsx("div",{className:"flex justify-center",children:e.jsxs("div",{className:"max-w-[82%] rounded-lg px-3 py-2 bg-warning/10 border border-warning/30 text-warning-text",children:[e.jsxs("p",{className:"text-[10px] font-semibold mb-0.5 flex items-center gap-1",children:[e.jsx(Rr,{className:"w-3 h-3"})," Nota interna · ",bt.authorName||"Equipe"]}),e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap break-words",children:bt.body}),e.jsx("p",{className:"text-[10px] text-right mt-1 text-warning-text/70",children:T(j.ms)})]})})]},`note-${bt.id}`)}const me=j.msg;return e.jsxs(n.Fragment,{children:[ct,e.jsxs("div",{className:`flex items-end gap-2 ${me.fromMe?"justify-end":"justify-start"}`,children:[!me.fromMe&&e.jsx("div",{className:"w-7 h-7 rounded-full bg-muted flex items-center justify-center text-[10px] font-semibold text-muted-foreground flex-shrink-0",children:ne!=null&&ne.isGroup?Wn(me.authorName||me.author||"?"):fn}),e.jsxs("div",{className:`max-w-[68%] rounded-2xl px-4 py-2.5 shadow-sm ${me.fromMe?"bg-primary text-primary-foreground rounded-br-sm":"bg-card border text-foreground rounded-bl-sm"}`,children:[(ne==null?void 0:ne.isGroup)&&!me.fromMe&&(me.authorName||me.author)&&e.jsx("p",{className:"text-[11px] font-semibold text-primary mb-1",children:me.authorName||me.author}),(me.type==="ptt"||me.type==="audio")&&U&&f?e.jsx($v,{msg:me,sellerId:f,chatId:U}):(me.type==="image"||me.type==="sticker")&&me.hasMedia&&U&&f?e.jsx(Pv,{msg:me,sellerId:f,chatId:U}):me.type==="video"&&me.hasMedia&&U&&f?e.jsx(Tv,{msg:me,sellerId:f,chatId:U}):me.type==="document"&&me.hasMedia&&U&&f?e.jsx(Mv,{msg:me,sellerId:f,chatId:U}):e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap break-words",children:zr(me.body)}),e.jsx("p",{className:`text-[10px] text-right mt-1 ${me.fromMe?"text-primary-foreground
168/60":"text-muted-foreground"}`,children:T(me.timestamp)})]})]})]},me.id)}),Be&&Be.message_category!=="cotacao"&&e.jsx(gu,{draft:Be,persona:Na,onResolved:Xn,onReviewCotacao:()=>{H(!0),tt(j=>j+1)}}),e.jsx("div",{ref:fs})]}),!x&&M&&e.jsx(Of,{leadId:vs,refreshSignal:pn,canRequote:u,onRequoted:()=>{H(!0),tt(j=>j+1)}}),x?e.jsxs("div",{className:"border-t px-4 py-3 flex-shrink-0 bg-muted/30 text-center text-xs text-muted-foreground flex items-center justify-center gap-2",children:[e.jsx(Zs,{className:"w-3.5 h-3.5"}),"Monitorando a inbox de outro vendedor, somente leitura"]}):e.jsxs("div",{className:`border-t px-4 py-3 flex-shrink-0 ${et?"bg-warning/5":"bg-card"}`,children:[e.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[e.jsx("button",{onClick:()=>ta(!1),className:`text-[11px] px-2 py-0.5 rounded-full transition-colors ${et?"bg-muted text-muted-foreground hover:bg-muted":"bg-primary text-primary-foreground"}`,children:"Cliente"}),e.jsxs("button",{onClick:()=>ta(!0),className:`text-[11px] px-2 py-0.5 rounded-full transition-colors ${et?"bg-warning text-warning-foreground":"bg-muted text-muted-foreground hover:bg-muted"}`,title:"Comentário interno: o cliente NÃO vê",children:[e.jsx(Rr,{className:"w-3 h-3 inline-block mr-1 align-text-bottom"})," Nota interna"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:at,type:"text",placeholder:et?"Nota interna (o cliente não vê)...":"Responder como vendedor...",value:W,onChange:j=>X(j.target.value),onKeyDown:Pt,className:"flex-1 bg-background border border-input rounded-lg px-4 py-2.5 text-sm text-foreground placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-ring"}),e.jsx(Pe,{onClick:et?Is:Kt,disabled:!W.trim(),size:"icon",className:`h-10 w-10 flex-shrink-0 ${et?"bg-warning hover:bg-warning text-warning-foreground":""}`,children:e.jsx(xa,{className:"w-4 h-4"})})]})]})]}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center bg-muted/20",children:e.jsxs("div",{className:"text-center max-w-xs",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center mx-auto mb-4",children:e.jsx(Ge,{className:"w-8 h-8 text-primary"})}),e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-1",children:"Agent Inbox"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Selecione uma conversa para supervisionar o agente em tempo real"})]})}),M&&!x&&!B&&(kt==null?void 0:kt.id)&&e.jsx("div",{className:"hidden md:block",children:e.jsx(Ti,{leadId:kt.id,openSignal:Bt,refetchSignal:xs,autoOpenAllowed:(Be==null?void 0:Be.message_category)==="cotacao",floating:!0})})]}),e.jsx(ou,{children:B&&kt&&e.jsx(xd,{lead:kt,messages:Ls,onClose:()=>H(!1),onUseSuggestion:A,mode:je,onMode:Oe,onboardingSession:ne?Vt(ne.phone||ne.id.replace("@c.us","").replace("@g.us","")):null,autoSwitch:!0,sellerId:l==null?void 0:l.id,chatId:(ne==null?void 0:ne.id)??null,chatName:(ne==null?void 0:ne.name)??null,cotacaoReviewSignal:Bt,cotacaoRefetchSignal:xs,hasPendingCotacaoDraft:(Be==null?void 0:Be.message_category)==="cotacao",showCotacaoCuradoria:!0,hideSuggestions:!!Be,onSelectPhoneInChat:na})})]}),Gt&&Se==="list"&&e.jsx(ub,{drafts:Dt,refresh:Ve,refreshLeads:L,leads:G,onExit:void 0,onOpenNav:()=>Ne(!0),renderAnalysis:({leadId:j,name:z,phone:de,messages:ge,onUseSuggestion:Ue,onClose:ct,hasPendingCotacaoDraft:me,pip:bt})=>e.jsx(xd,{lead:ec({id:j,contactName:z,contactPhone:de,status:"warm",closingScore:50,lastContactAt:null}),messages:ge,onClose:ct,onUseSuggestion:Ue,mode:je,onMode:Oe,autoSwitch:!1,sellerId:l==null?void 0:l.id,chatId:cf(de),chatName:z,hideSuggestions:!0,showCotacaoCuradoria:!0,cotacaoReviewSignal:Bt,cotacaoRefetchSignal:xs,hasPendingCotacaoDraft:me,pip:bt}),onCotacaoReady:()=>Ut(j=>j+1),openRequest:ut})]})]})};export{Dy as AgentInbox,Dy 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.