1import{j as e,r as x,M as Ue,T as qe,P as Ge,C as je,f as be,L as ze}from"./react-vendor-pafHdoJx.js";import{c as He,d as N,u as H,l as E,b as V,a as We,_ as Je,U as Xe,ak as Ye,V as Ke,W as Qe,j as Ze,C as ea}from"./index-Db0fDLGN.js";import{E as aa}from"./EntityList-DHyuL9ql.js";import{M as Ne}from"./ComplianceBadges-B6KO2l0w.js";import{O as sa}from"./ObjectDrawer-DyT69DrE.js";import"./map-vendor-Dr8zbd0c.js";import{L as P,al as ta,u as ra,r as Te,s as na,aB as Fe,aG as oa,D as ia,M as me,X as $e,v as ue,aC as la,aT as ca,I as pe,a7 as da,at as xe,l as Pe,dd as ke,bq as ua,cr as ma,j as we,as as pa,ad as Ce,an as xa,ae as ga,bL as Ve,av as ha,de as va,ay as fa,Q as le,bc as ya,aY as ja,o as ba,ap as Na,b8 as Be}from"./ui-vendor-DLXJn6s3.js";import{A as ka}from"./AdaInline-Ct5kRNHe.js";import{C as wa}from"./Comments-C_vFA2mA.js";import{A as Ca}from"./ActivityFeed-DAmzN5j6.js";import{b as Sa,m as Ea}from"./pii-mask-CjnkDN7A.js";import{b as Aa,e as Ma,a as _a}from"./export-utils-BHX8wKd9.js";import{C as Da}from"./ConciliacaoDoFeed-CaKlaxaz.js";import"./firebase-vendor-D3UzkAhn.js";const Ta={critical:{label:"Ação imediata",bg:"#fef2f2",fg:"#b91c1c",dot:"#dc2626"},warning:{label:"Acompanhar",bg:"#fff7ed",fg:"#9a3412",dot:"#ea580c"},monitor:{label:"Observar",bg:"#fefce8",fg:"#854d0e",dot:"#ca8a04"},ok:{label:"OK",bg:"transparent",fg:"var(--page-text-muted, #94a3b8)",dot:"var(--page-text-muted, #94a3b8)"}};function Fa({attention:s,hideOk:a=!0,showScore:r=!1,className:u}){if(a&&s.tier==="ok")return null;const l=Ta[s.tier],n=s.topReasons.length>0?s.topReasons.join(" · "):`Score ${s.score}`;return e.jsxs("span",{role:"status","aria-label":`Atenção ${l.label}: ${n}`,title:n,"data-testid":"driver-attention-badge","data-tier":s.tier,className:He("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[10px] font-semibold",u),style:{background:l.bg,color:l.fg},children:[e.jsx("span",{"aria-hidden":"true",className:"inline-block h-1.5 w-1.5 rounded-full",style:{background:l.dot}}),l.label,r&&e.jsxs("span",{className:"opacity-70","data-testid":"driver-attention-score",children:["(",s.score,")"]})]})}const A={compliance:35,performance:20,safety:25,healthJornada:15,engagement:10},ce={critical:70,warning:40,monitor:20};function $a(s){const a=[],r={compliance:0,performance:0,safety:0,healthJornada:0,engagement:0};if(typeof s.cnhDaysToExpire=="number"){if(s.cnhDaysToExpire<0)r.compliance=A.compliance,a.push({text:"CNH VENCIDA",weight:A.compliance});else if(s.cnhDaysToExpire<=7)r.compliance=Math.max(r.compliance,A.compliance*.85),a.push({text:`CNH vence em ${s.cnhDaysToExpire}d`,weight:A.compliance*.85});else if(s.cnhDaysToExpire<=30){const c=A.compliance*.4;c>r.compliance&&(r.compliance=c),a.push({text:`CNH vence em ${s.cnhDaysToExpire}d`,weight:c})}}if(typeof s.examDaysToExpire=="number"){if(s.examDaysToExpire<0)r.compliance=Math.max(r.compliance,A.compliance*.7),a.push({text:"Exame médico vencido",weight:A.compliance*.7});else if(s.examDaysToExpire<=14){const c=A.compliance*.3;c>r.compliance&&(r.compliance=c)}}if(typeof s.currentDrivingScore=="number"&&typeof s.previousDrivingScore=="number"&&s.previousDrivingScore>0){const c=s.previousDrivingScore-s.currentDrivingScore,p=c/s.previousDrivingScore;p>=.2?(r.performance=A.performance,a.push({text:`Score caiu ${Math.round(p*100)}%`,weight:A.performance})):p>=.1?(r.performance=A.performance*.6,a.push({text:`Score caiu ${Math.round(p*100)}%`,weight:r.performance})):c>=5&&(r.performance=A.performance*.3)}const u=s.recentInfractionCount??0,l=s.recentIncidentCount??0;l>=1?(r.safety=Math.min(A.safety,A.safety*(.6+.2*(l-1))),a.push({text:`${l} sinistro${l>1?"s":""} recente${l>1?"s":""}`,weight:r.safety})):u>=3?(r.safety=A.safety*.7,a.push({text:`${u} multas recentes`,weight:r.safety})):u>=1&&(r.safety=A.safety*.3);const n=s.recentAbsenceCount??0;n>=3?(r.healthJornada=A.healthJornada,a.push({text:`${n} faltas no mês`,weight:r.healthJornada})):n>=1&&(r.healthJornada=A.healthJornada*.5),typeof s.daysSinceLastEngagement=="number"&&s.daysSinceLastEngagement>=30?(r.engagement=A.engagement,a.push({text:`App não acessado há ${s.daysSinceLastEngagement}d`,weight:A.engagement})):typeof s.daysSinceLastEngagement=="number"&&s.daysSinceLastEngagement>=14&&(r.engagement=A.engagement*.5);const h=r.compliance+r.performance+r.safety+r.healthJornada+r.engagement,d=Math.min(100,Math.round(h)),t=d>=ce.critical?"critical":d>=ce.warning?"warning":d>=ce.monitor?"monitor":"ok",m=a.sort((c,p)=>p.weight-c.weight).slice(0,3).map(c=>c.text);return{score:d,tier:t,components:r,topReasons:m}}function Pa(s){if(!s)return"";try{return new Date(s).toLocaleDateString("pt-BR",{day:"2-digit",month:"long",year:"numeric"})}catch{return s}}function ee({linkedAt:s}){const a=Pa(s);return e.jsxs("div",{className:"rounded-lg p-2.5 flex items-start gap-2 text-[11px] leading-snug",style:{background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.30)",color:"#059669"},role:"note",children:[e.jsx(ia,{className:"w-3.5 h-3.5 shrink-0 mt-0.5","aria-hidden":"true"}),e.jsxs("span",{children:["Dados GPS sincronizados conforme consentimento do motorista",a?e.jsxs(e.Fragment,{children:[" em ",e.jsx("strong",{children:a})]}):""," via app Sentinel Driver. O acesso a esta tela fica registrado em auditoria."]})]})}function Va({driverId:s,linkedAt:a}){const[r,u]=x.useState([]),[l,n]=x.useState(!0),[h,d]=x.useState(null),[t,m]=x.useState(null);return x.useEffect(()=>{let c=!1;return n(!0),d(null),N.driverDetail(s).then(p=>{c||u((p==null?void 0:p.recentTrips)||[])}).catch(p=>{c||d((p==null?void 0:p.message)||"Erro ao buscar viagens")}).finally(()=>{c||n(!1)}),()=>{c=!0}},[s]),l?e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{linkedAt:a}),e.jsxs("div",{className:"flex items-center gap-2 text-xs py-6 justify-center",style:{color:"var(--page-text-muted)"},children:[e.jsx(P,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":"true"})," Carregando viagens GPSâ¦"]})]}):h?e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{linkedAt:a}),e.jsxs("div",{className:"rounded-lg p-3 text-xs",style:{background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.30
1)",color:"#EF4444"},role:"alert",children:[e.jsx(ta,{className:"w-3.5 h-3.5 inline mr-1","aria-hidden":"true"}),h]})]}):r.length===0?e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{linkedAt:a}),e.jsxs("div",{className:"rounded-xl p-6 text-center",style:{background:"var(--surface-secondary)",border:"1px solid var(--border-primary)"},children:[e.jsx(ra,{className:"w-7 h-7 mx-auto mb-2",style:{color:"var(--page-text-muted)"},"aria-hidden":"true"}),e.jsx("p",{className:"text-sm font-medium",style:{color:"var(--page-text)"},children:"Sem viagens GPS nos últimos 90 dias"}),e.jsx("p",{className:"text-xs mt-1 leading-relaxed",style:{color:"var(--page-text-muted)"},children:"As viagens aparecem aqui automaticamente quando o motorista está com o app Sentinel Driver instalado e ativo."})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{linkedAt:a}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(de,{label:"Viagens",value:String(r.length)}),e.jsx(de,{label:"Distância",value:`${(r.reduce((c,p)=>c+(p.distance||0),0)/1e3).toFixed(1)} km`}),e.jsx(de,{label:"Score médio",value:String(Math.round(r.filter(c=>(c.score||0)>0).reduce((c,p,i,g)=>c+(p.score||0)/g.length,0))||"â")})]}),e.jsxs("div",{className:"space-y-1.5",children:[r.slice(0,30).map(c=>{const p=c.tripId||c.id||c._id||"",i=t===p,g=(c.score||0)>=80?"#10B981":(c.score||0)>=60?"#F59E0B":"#EF4444";return e.jsxs("div",{className:"rounded-lg overflow-hidden",style:{background:"var(--surface-secondary)",border:"1px solid var(--border-primary)"},children:[e.jsxs("button",{onClick:()=>m(i?null:p),className:"w-full flex items-center justify-between gap-2 px-3 py-2 hover-surface text-left",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[i?e.jsx(Te,{className:"w-3.5 h-3.5 shrink-0"}):e.jsx(na,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx(Fe,{className:"w-3 h-3 shrink-0",style:{color:"var(--page-text-muted)"}}),e.jsx("span",{className:"text-xs truncate",style:{color:"var(--page-text)"},children:La(c.startTime)})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] shrink-0",children:[e.jsxs("span",{style:{color:"var(--page-text-muted)"},children:[((c.distance||0)/1e3).toFixed(1)," km"]}),e.jsx("span",{style:{color:"var(--page-text-muted)"},children:Ia(c.duration)}),(c.score||0)>0&&e.jsxs("span",{className:"px-1.5 py-0.5 rounded font-semibold",style:{background:`${g}22`,color:g},children:[e.jsx(oa,{className:"w-2.5 h-2.5 inline mr-0.5"}),c.score]})]})]}),i&&e.jsx(Ba,{tripId:p})]},p)}),r.length>30&&e.jsxs("p",{className:"text-[11px] text-center py-2",style:{color:"var(--page-text-muted)"},children:["mostrando 30 de ",r.length," viagens dos últimos 90 dias"]})]})]})}function de({label:s,value:a}){return e.jsxs("div",{className:"rounded-lg px-3 py-2",style:{background:"var(--surface-secondary)",border:"1px solid var(--border-primary)"},children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider",style:{color:"var(--page-text-muted)"},children:s}),e.jsx("p",{className:"text-sm font-semibold",style:{color:"var(--page-text)"},children:a})]})}function Ba({tripId:s}){var d;const[a,r]=x.useState(null),[u,l]=x.useState(!0),[n,h]=x.useState([]);return x.useEffect(()=>{let t=!1;return l(!0),N.tripDetail(s).then(m=>{if(t)return;r(m);const c=(m==null?void 0:m.locations)||(m==null?void 0:m.path)||(m==null?void 0:m.points)||(m==null?void 0:m.gpsPoints)||[],p=[];for(const i of c){const g=i.lat??i.latitude,f=i.lng??i.lon??i.longitude;typeof g=="number"&&typeof f=="number"&&p.push({lat:g,lng:f,speed:i.speed,ts:i.timestamp||i.ts})}h(p)}).catch(()=>{t||r(null)}).finally(()=>{t||l(!1)}),()=>{t=!0}},[s]),u?e.jsxs("div",{className:"px-3 py-4 text-xs text-center",style:{color:"var(--page-text-muted)"},children:[e.jsx(P,{className:"w-3 h-3 animate-spin inline mr-1"})," Carregando replayâ¦"]}):a?e.jsxs("div",{className:"px-3 pb-3 space-y-2",style:{borderTop:"1px solid var(--border-primary)"},children:[e.jsxs("div",{className:"grid grid-cols-4 gap-2 mt-2",children:[e.jsx(ae,{label:"Velocidade",value:a.speedScore}),e.jsx(ae,{label:"Aceleração",value:a.accelerationScore??a.accScore}),e.jsx(ae,{label:"Frenagem",value:a.brakingScore??a.brakeScore}),e.jsx(ae,{label:"Curvas",value:a.corneringScore})]}),((d=a==null?void 0:a._meta)==null?void 0:d.locationsSource)==="timestamp_fallback"&&e.jsx("div",{className:"rounded-md px-2 py-1 text-[10px]",style:{background:"rgba(59,130,246,0.06)",border:"1px solid rgba(59,130,246,0.20)",color:"var(--page-text-muted)"},children:"Trajeto reconstruÃdo por timestamp (viagem sem tripId nos pontos GPS)."}),n.length>=2?e.jsx("div",{className:"rounded-lg overflow-hidden",style:{border:"1px solid var(--border-primary)",height:300},children:e.jsxs(Ue,{center:[n[0].lat,n[0].lng],zoom:12,style:{height:"100%",width:"100%"},scrollWheelZoom:!1,children:[e.jsx(qe,{attribution:"© OpenStreetMap",url:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"}),e.jsx(Ge,{positions:n.map(t=>[t.lat,t.lng]),pathOptions:{color:"#3B82F6",weight:3}}),e.jsx(je,{center:[n[0].lat,n[0].lng],radius:6,pathOptions:{color:"#10B981",fillColor:"#10B981",fillOpacity:1},children:e.jsx(be,{children:"InÃcio"})}),e.jsx(je,{center:[n[n.length-1].lat,n[n.length-1].lng],radius:6,pathOptions:{color:"#EF4444",fillColor:"#EF4444",fillOpacity:1},children:e.jsx(be,{children:"Fim"})})]})}):e.jsx("div",{className:"rounded-lg p-3 text-[11px] leading-relaxed",style:{background:"var(--surface-secondary)",color:"var(--page-text-muted)"},children:"Pontos GPS desta viagem não estão disponÃveis (app pode não ter sincronizado o trajeto detalhado). Métricas resumidas acima continuam válidas."})]}):e.jsx("div",{className:"px-3 py-3 text-xs",style:{color:"var(--page-text-muted)"},children:"Detalhes da viagem indisponÃveis."})}function ae({label:s,value:a}){const r=typeof a=="number"?a:null,u=r===null?"var(--page-text-muted)":r>=80?"#10B981":r>=60?"#F59E0B":"#EF4444";return e.jsxs("div",{className:"rounded-md px-2 py-1.5 text-center",style:{background:"var(--surface-primary)",border:"1px solid var(--border-primary)"},children:[e.jsx("p",{className:"text-[9px] uppercase",style:{color:"var(--page-text-muted)"},children:s}),e.jsx("p",{className:"text-xs font-semibold",style:{color:u},children:r??"â"})]})}function La(s){if(!s)return"â";
1try{return new Date(s).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return s}}function Ia(s){if(!s||s<=0)return"â";const a=Math.floor(s/3600),r=Math.floor(s%3600/60);return a>0?`${a}h${r.toString().padStart(2,"0")}min`:`${r}min`}const Ra="Olá {nome}, sua CNH vence em breve (vencimento: dd/mm/aaaa). Por favor, envie uma foto da CNH renovada por aqui pra mantermos seu cadastro em dia e evitar bloqueio de novas viagens.";function Oa({open:s,onClose:a,targets:r,template:u,onDone:l}){const{toast:n}=H(),[h,d]=x.useState(""),[t,m]=x.useState(!1);if(x.useEffect(()=>{s&&(d(""),m(!1))},[s]),x.useEffect(()=>{if(!s)return;const f=j=>{j.key==="Escape"&&a()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[s,a]),!s)return null;const c=r.filter(f=>!!f.phone),p=r.length-c.length,i=c.length>0&&(u==="cnh_request"||h.trim().length>0)&&!t,g=async()=>{if(i){m(!0);try{const f=await N.bulkWhatsAppDrivers({driverIds:c.map(j=>j.driverId),...u?{template:u}:{message:h.trim()}});E("motoristas_bulk_whatsapp_sent",{count:f.queued,skippedNoPhone:f.skippedNoPhone,template:u||"free"}),n({title:`${f.queued} mensagem${f.queued===1?"":"s"} na fila de envio`,description:f.skippedNoPhone>0?`${f.skippedNoPhone} motorista(s) sem telefone foram pulados.`:"Envio em processamento pela fila do WhatsApp.",kind:"success"}),l==null||l(),a()}catch(f){n({title:"Não consegui enfileirar o envio",description:((f==null?void 0:f.message)||"").slice(0,200),kind:"error"})}finally{m(!1)}}};return e.jsxs("div",{className:"fixed inset-0 z-modal flex items-center justify-center p-4",role:"dialog","aria-modal":"true","aria-labelledby":"bulk-wa-title",onClick:a,"data-testid":"bulk-whatsapp-modal",children:[e.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{className:"relative w-full max-w-lg rounded-2xl shadow-2xl",style:{background:"var(--surface-primary)",border:"1px solid var(--border-primary)"},onClick:f=>f.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start gap-3 p-5 pb-3",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-xl flex items-center justify-center",style:{background:"#10B98120",color:"#10B981"},children:e.jsx(me,{className:"w-5 h-5","aria-hidden":"true"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h2",{id:"bulk-wa-title",className:"text-base font-bold",style:{color:"var(--page-text)"},children:u==="cnh_request"?"Pedir CNH renovada por WhatsApp":"WhatsApp em lote"}),e.jsxs("p",{className:"text-xs mt-0.5",style:{color:"var(--page-text-muted)"},children:[c.length," destinatário",c.length===1?"":"s"," com telefone",p>0&&` · ${p} sem telefone (será pulado)`]})]}),e.jsx("button",{onClick:a,disabled:t,className:"p-1 -m-1 rounded-md hover-surface transition-colors flex-shrink-0","aria-label":"Fechar",children:e.jsx($e,{className:"w-4 h-4",style:{color:"var(--page-text-muted)"},"aria-hidden":"true"})})]}),e.jsxs("div",{className:"px-5 space-y-3",children:[e.jsx("div",{className:"rounded-lg p-2.5 max-h-28 overflow-y-auto text-xs flex flex-wrap gap-1.5",style:{background:"var(--surface-secondary)"},"data-testid":"bulk-wa-recipients",children:c.length===0?e.jsx("span",{style:{color:"#EF4444"},children:"Nenhum dos selecionados tem telefone cadastrado."}):c.map(f=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full",style:{background:"var(--surface-tertiary)",color:"var(--page-text)"},children:[f.name,e.jsx("span",{className:"font-mono text-[10px]",style:{color:"var(--page-text-muted)"},children:f.phone})]},f.driverId))}),u==="cnh_request"?e.jsxs("div",{className:"rounded-lg p-3 text-xs leading-relaxed",style:{background:"var(--surface-secondary)",color:"var(--page-text)"},children:[e.jsxs("span",{className:"block text-[10px] font-semibold uppercase tracking-wider mb-1",style:{color:"var(--page-text-muted)"},children:["Mensagem (template fixo â ","{nome}"," e vencimento preenchidos por motorista)"]}),Ra]}):e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"bulk-wa-message",className:"text-xs font-medium block mb-1.5",style:{color:"var(--page-text-secondary)"},children:["Mensagem â use ","{nome}"," pra personalizar por motorista"]}),e.jsx("textarea",{id:"bulk-wa-message",value:h,onChange:f=>d(f.target.value),rows:4,maxLength:1e3,disabled:t,placeholder:"Ex.: Olá {nome}, lembrete: reunião de segurança sexta à s 9h.",className:"w-full rounded-lg p-2.5 text-sm resize-y",style:{background:"var(--surface-secondary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"}}),e.jsxs("div",{className:"text-[10px] text-right",style:{color:"var(--page-text-muted)"},children:[h.length,"/1000"]})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 p-4 mt-2 border-t",style:{borderColor:"var(--border-primary)"},children:[e.jsx("button",{onClick:a,disabled:t,className:"btn-secondary",children:"Cancelar"}),e.jsxs("button",{onClick:g,disabled:!i,className:"px-4 py-2 rounded-xl text-sm font-semibold transition-colors flex items-center gap-2 text-white disabled:opacity-50",style:{background:"#10B981"},"data-testid":"bulk-wa-send",children:[t&&e.jsx(P,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":"true"}),"Enviar pra fila"]})]})]})]})}function R(){return e.jsx("div",{className:"space-y-2","aria-label":"Carregando",children:[0,1,2].map(s=>e.jsx("div",{className:"h-10 rounded-lg animate-pulse",style:{background:"var(--surface-secondary)"}},s))})}function O({message:s}){return e.jsxs("div",{className:"rounded-xl p-4 text-sm",style:{background:"var(--surface-secondary)",border:"1px solid #EF4444",color:"#EF4444"},role:"alert",children:["Erro ao carregar: ",s]})}function W({title:s,body:a}){return e.jsxs("div",{className:"rounded-xl p-6 text-center",style:{background:"var(--surface-secondary)",border:"1px dashed var(--border-primary)"},children:[e.jsx("p",{className:"text-sm font-semibold mb-1",style:{color:"var(--page-text)"},children:s}),a&&e.jsx("p",{className:"text-xs leading-relaxed",style:{color:"var(--page-text-muted)"},children:a})]})}function oe({left:s,right:a,sub:r}){return e.jsxs("div",{className:"flex items-start justify-between gap-3 py-2.5 px-3 rounded-lg",style:{background:"var(--surface-secondary)"},children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm",style:{color:"var(--page-text)"},children:s}),r&&e.jsx("div",{className:"text-[11px] mt-0.5",style:{color:"var(--page-text-muted)"},children:r})]}),e.jsx("div",{className:"text-xs text-right shrink-0",style:{color:"var(--page-text-muted)"},children:a})]})}function ne(s){return s==null||!Number.isFinite(s)?"R$ â":s.toLocaleStr
1ing("pt-BR",{style:"currency",currency:"BRL"})}function ge(s){if(!s)return"â";const a=new Date(s);return isNaN(a.getTime())?"â":a.toLocaleDateString("pt-BR")}function K(s){if(!s)return"â";const a=new Date(s);return isNaN(a.getTime())?"â":a.toLocaleString("pt-BR",{dateStyle:"short",timeStyle:"short"})}function Ua(s){if(!s)return null;const a=new Date(s);return isNaN(a.getTime())?null:Math.ceil((a.getTime()-Date.now())/864e5)}const qa={DRIVING:"Direção",REST:"Descanso",WAITING:"Espera",LOADING:"Carga/descarga",MEAL:"Refeição"},Ga={DRIVING:"#3B82F6",REST:"#10B981",WAITING:"#9CA3AF",LOADING:"#F59E0B",MEAL:"#A855F7"};function za({driverId:s}){var d,t;const{data:a,loading:r,error:u}=V(()=>N.jornada({driverId:s,days:7}),[s]);if(r)return e.jsx(R,{});if(u)return e.jsx(O,{message:u});const l=(a==null?void 0:a.entries)||[];if(l.length===0)return e.jsx(W,{title:"Sem registros de jornada",body:"O motorista ainda não tem eventos DRIVING/REST nos últimos 7 dias. App DriverCopilot detecta automaticamente."});const n=((((d=a==null?void 0:a.summary)==null?void 0:d.totalDrivingMinutes)||0)/60).toFixed(1),h=((((t=a==null?void 0:a.summary)==null?void 0:t.totalRestMinutes)||0)/60).toFixed(1);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Se,{label:"Direção (7d)",value:`${n}h`,color:"#3B82F6"}),e.jsx(Se,{label:"Descanso (7d)",value:`${h}h`,color:"#10B981"})]}),e.jsx("div",{className:"space-y-1.5",children:l.slice(0,30).map(m=>e.jsx(oe,{left:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:Ga[m.type]||"#9CA3AF"},"aria-hidden":"true"}),e.jsx("span",{children:qa[m.type]||m.type}),m.autoDetected&&e.jsx("span",{className:"text-[9px] px-1 rounded",style:{background:"var(--surface-tertiary)"},children:"auto"})]}),sub:K(m.startTime),right:`${m.durationMinutes} min`},m.id))}),l.length>30&&e.jsxs("p",{className:"text-[11px] text-center",style:{color:"var(--page-text-muted)"},children:["Mostrando 30 de ",l.length," eventos."]})]})}function Se({label:s,value:a,color:r}){return e.jsxs("div",{className:"rounded-lg p-3",style:{background:"var(--surface-secondary)"},children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide",style:{color:"var(--page-text-muted)"},children:s}),e.jsx("div",{className:"text-lg font-bold mt-0.5",style:{color:r},children:a})]})}const Ha=10*1024*1024;function Wa(s){if(s==="application/pdf")return"pdf";const a=s.match(/^image\/(png|jpe?g|webp|heic|gif)$/);return a?a[1]==="jpeg"?"jpg":a[1]:"bin"}function Ja({driverId:s}){const{data:a,loading:r,error:u,silentRefetch:l}=V(()=>N.driverDetail(s),[s]),{orgId:n}=We(),{toast:h}=H(),[d,t]=x.useState(null);if(r)return e.jsx(R,{});if(u)return e.jsx(O,{message:u});const m=(a==null?void 0:a.documents)||{},c=async(p,i)=>{if(!n){h({title:"Sessão sem organização",description:"Saia e entre novamente pra habilitar upload.",kind:"error"});return}if(i.size>Ha){h({title:"Arquivo muito grande",description:"O limite é 10MB.",kind:"error"});return}if(!/^image\//.test(i.type)&&i.type!=="application/pdf"){h({title:"Formato não suportado",description:"Envie imagem (foto/scan) ou PDF.",kind:"error"});return}t(p);try{const{getStorage:g,ref:f,uploadBytes:j,getDownloadURL:w}=await Je(async()=>{const{getStorage:D,ref:S,uploadBytes:T,getDownloadURL:L}=await import("./firebase-vendor-D3UzkAhn.js").then(k=>k.M);return{getStorage:D,ref:S,uploadBytes:T,getDownloadURL:L}},[]),C=`orgs/${n}/drivers/${s}/docs/${p}-${Date.now()}.${Wa(i.type)}`,M=f(g(),C);await j(M,i,{contentType:i.type});const y=await w(M);await N.updateDriverDocument(s,p,{url:y,storagePath:C,fileName:i.name.slice(0,200),contentType:i.type,size:i.size}),E("motorista_doc_uploaded",{docType:p,contentType:i.type}),h({title:"Documento enviado",description:Xa(p),kind:"success"}),l()}catch(g){h({title:"Não consegui enviar o documento",description:((g==null?void 0:g.message)||"").slice(0,200),kind:"error"})}finally{t(null)}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{docType:"cnh",title:"CNH",subtitle:a!=null&&a.cnhCategoria?`Categoria ${a.cnhCategoria}${a.cnhNumero?` · nº ${a.cnhNumero}`:""}`:a!=null&&a.cnhNumero?`nº ${a.cnhNumero}`:null,validade:a==null?void 0:a.cnhValidade,doc:m.cnh,uploading:d==="cnh",onUpload:p=>c("cnh",p)}),e.jsx(se,{docType:"toxicologico",title:"Exame toxicológico",subtitle:"Lei 13.103/2015 â obrigatório a cada 2,5 anos",validade:a==null?void 0:a.toxicologicoValidade,doc:m.toxicologico,uploading:d==="toxicologico",onUpload:p=>c("toxicologico",p)}),((a==null?void 0:a.mopp)||m.mopp)&&e.jsx(se,{docType:"mopp",title:"MOPP",subtitle:"Movimentação de Produtos Perigosos",validade:a==null?void 0:a.moppValidade,doc:m.mopp,uploading:d==="mopp",onUpload:p=>c("mopp",p)}),e.jsx(se,{docType:"contrato",title:"Contrato",subtitle:"Contrato de trabalho / prestação de serviço",validade:void 0,showValidade:!1,doc:m.contrato,uploading:d==="contrato",onUpload:p=>c("contrato",p)}),e.jsx("p",{className:"text-[10px] mt-3",style:{color:"var(--page-text-muted)"},children:"Aceita foto/scan (imagem) ou PDF, até 10MB. O arquivo fica restrito à sua organização."})]})}function Xa(s){return{cnh:"CNH",toxicologico:"Exame toxicológico",mopp:"MOPP",contrato:"Contrato"}[s]}function se({docType:s,title:a,subtitle:r,validade:u,doc:l,uploading:n,onUpload:h,showValidade:d=!0}){const t=x.useRef(null),m=Ua(u),c=m==null?"unknown":m<0?"error":m<=30?"warn":"ok",p={ok:"#10B981",warn:"#F59E0B",error:"#EF4444",unknown:"#9CA3AF"},i={ok:"Válido",warn:m!=null&&m>=0?`Vence em ${m}d`:"Vencendo",error:m!=null?`Vencido há ${Math.abs(m)}d`:"Vencido",unknown:"Sem data"},g=!!(l!=null&&l.url),f=!!(l!=null&&l.contentType)&&l.contentType.startsWith("image/");return e.jsxs("div",{className:"rounded-lg p-3 space-y-2",style:{background:"var(--surface-secondary)"},"data-testid":`doc-row-${s}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium",style:{color:"var(--page-text)"},children:a}),r&&e.jsx("div",{className:"text-[11px] mt-0.5",style:{color:"var(--page-text-muted)"},children:r}),d&&e.jsxs("div",{className:"text-[11px] mt-0.5 font-mono",style:{color:"var(--page-text-muted)"},children:["Vencimento: ",ge(u)]})]}),d&&e.jsx("span",{className:"text-[10px] px-2 py-1 rounded-full font-semibold whitespace-nowrap",style:{background:p[c]+"22",color:p[c]},children:i[c]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1",children:g?e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f?e.jsx("a",{href:l.url,target:"_blank",rel:"noreferrer","aria-label":`Ver ${a} em tamanho real`,children:e.jsx("img",{src:l.url,alt:`Miniatura de ${a}`,className:"w-10 h-10 rounded object-cover shrink-0",style:{border:"1px solid var(--border-primary)"}})}):e.jsxs("a",{href:l.url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs underline",style:{color:"var(--page-text)"},children:[e.jsx(ue,{className:"w-3.5 h-3.5 shrink-0","aria-hidden":"true"}),"Ver PDF",e.jsx(la,{className:"w-3 h-3 shrink-0","aria-hidden":"true"})]}),e.jsxs("span",{className:"text-[10px] truncate",style:{color:"var(--page-text-muted)"},children:[l.fileName||"arquivo",l.uploadedAt?` · ${K(l.uploadedAt)}`:""]})]}):e.jsx("span",{className:"text-[11px]",style:{color:"var(--page-text-muted)"},children:"Nenhum arquivo anexado."})}),e.jsx("input",{ref:t,type:"file",accept:"image/*,application/pdf",className:"hidden","data-testid":`doc-file-input-${s}
1`,onChange:j=>{var C;const w=(C=j.target.files)==null?void 0:C[0];w&&h(w),j.target.value=""}}),e.jsxs("button",{type:"button",onClick:()=>{var j;return(j=t.current)==null?void 0:j.click()},disabled:n,className:"inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-semibold shrink-0 disabled:opacity-60",style:{background:"var(--surface-tertiary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"},"aria-label":g?`Substituir arquivo de ${a}`:`Enviar arquivo de ${a}`,children:[n?e.jsx(P,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":"true"}):e.jsx(ca,{className:"w-3.5 h-3.5","aria-hidden":"true"}),g?"Substituir":"Enviar arquivo"]})]})]})}const Ya={speeding:"Excesso de velocidade",red_light:"Avanço sinal vermelho",wrong_way:"Contramão",parking:"Estacionamento irregular",phone_use:"Uso celular",seatbelt:"Sem cinto"},Ka={pending:"Pendente",paid:"Pago",appealed:"Recurso",cancelled:"Cancelado"},Ee={pending:"#F59E0B",paid:"#10B981",appealed:"#3B82F6",cancelled:"#9CA3AF"};function Qa({driverId:s}){const{data:a,loading:r,error:u}=V(()=>N.infractions({driverId:s}),[s]);if(r)return e.jsx(R,{});if(u)return e.jsx(O,{message:u});const l=Array.isArray(a)?a:[];if(l.length===0)return e.jsx(W,{title:"Sem multas registradas",body:"Nenhuma infração foi cadastrada pra este motorista."});const n=l.filter(t=>t.status==="pending"),h=n.reduce((t,m)=>t+(m.fineAmount||0),0),d=n.reduce((t,m)=>t+(m.points||0),0);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ae,{label:"Pendente",value:ne(h),sub:`${n.length} multa${n.length===1?"":"s"}`,color:"#F59E0B"}),e.jsx(Ae,{label:"Pontos abertos",value:String(d),sub:"CNH",color:d>=20?"#EF4444":"#3B82F6"})]}),e.jsx("div",{className:"space-y-1.5",children:l.slice(0,20).map(t=>e.jsx(oe,{left:e.jsxs("span",{children:[Ya[t.infractionType]||t.infractionType,e.jsx("span",{className:"ml-2 text-[10px] px-1.5 py-0.5 rounded font-medium",style:{background:Ee[t.status]+"22",color:Ee[t.status]},children:Ka[t.status]||t.status})]}),sub:`${ge(t.date)}${t.vehiclePlate?` · ${t.vehiclePlate}`:""}${t.location?` · ${t.location}`:""}`,right:e.jsxs("div",{children:[e.jsx("div",{children:ne(t.fineAmount)}),t.points>0&&e.jsxs("div",{className:"text-[10px]",style:{color:"var(--page-text-muted)"},children:[t.points," pts"]})]})},t.id))}),l.length>20&&e.jsxs("p",{className:"text-[11px] text-center",style:{color:"var(--page-text-muted)"},children:["Mostrando 20 de ",l.length," multas."]})]})}function Ae({label:s,value:a,sub:r,color:u}){return e.jsxs("div",{className:"rounded-lg p-3",style:{background:"var(--surface-secondary)"},children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide",style:{color:"var(--page-text-muted)"},children:s}),e.jsx("div",{className:"text-lg font-bold mt-0.5",style:{color:u},children:a}),e.jsx("div",{className:"text-[10px]",style:{color:"var(--page-text-muted)"},children:r})]})}function Za({driverId:s}){const{data:a,loading:r,error:u}=V(()=>N.financeiroTitulos(void 0,void 0,s),[s]);if(r)return e.jsx(R,{});if(u)return e.jsx(O,{message:u});const l=(a==null?void 0:a.titulos)||[];if(l.length===0)return e.jsx(W,{title:"Sem pagamentos lançados",body:"Nenhum tÃtulo (a pagar ou receber) vinculado a este motorista."});const n=l.filter(t=>t.status==="aberto"),h=n.reduce((t,m)=>t+(m.valor||0),0),d=n.filter(t=>t.isVencido).length;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Me,{label:"Em aberto",value:ne(h),sub:`${n.length} tÃtulo${n.length===1?"":"s"}`,color:"#F59E0B"}),e.jsx(Me,{label:"Vencidos",value:String(d),sub:d>0?"requer atenção":"em dia",color:d>0?"#EF4444":"#10B981"})]}),e.jsx("div",{className:"space-y-1.5",children:l.slice(0,20).map(t=>e.jsx(oe,{left:e.jsxs("span",{children:[t.descricao||t.categoria||"TÃtulo",e.jsx("span",{className:"ml-2 text-[10px] px-1.5 py-0.5 rounded font-medium",style:{background:t.tipo==="pagar"?"#EF444422":"#10B98122",color:t.tipo==="pagar"?"#EF4444":"#10B981"},children:t.tipo==="pagar"?"a pagar":"a receber"})]}),sub:e.jsxs("span",{children:[t.categoria&&`${t.categoria} · `,"vence ",ge(t.vencimento),t.isVencido&&t.diasAtraso?e.jsxs("span",{style:{color:"#EF4444"}
1,children:[" · atrasado ",t.diasAtraso,"d"]}):null]}),right:e.jsxs("div",{children:[e.jsx("div",{style:{color:t.status==="pago"?"#10B981":"var(--page-text)"},children:ne(t.valor)}),e.jsx("div",{className:"text-[10px]",style:{color:"var(--page-text-muted)"},children:t.status==="pago"?"pago":"aberto"})]})},t.id))}),l.length>20&&e.jsxs("p",{className:"text-[11px] text-center",style:{color:"var(--page-text-muted)"},children:["Mostrando 20 de ",l.length," tÃtulos."]})]})}function Me({label:s,value:a,sub:r,color:u}){return e.jsxs("div",{className:"rounded-lg p-3",style:{background:"var(--surface-secondary)"},children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide",style:{color:"var(--page-text-muted)"},children:s}),e.jsx("div",{className:"text-lg font-bold mt-0.5",style:{color:u},children:a}),e.jsx("div",{className:"text-[10px]",style:{color:"var(--page-text-muted)"},children:r})]})}function es(s){return s?typeof s=="string"?s:typeof s=="object"&&typeof s._seconds=="number"?new Date(s._seconds*1e3).toISOString():null:null}function as({driverId:s}){const{data:a,loading:r,error:u}=V(()=>N.messageThreads({driverId:s}),[s]);if(r)return e.jsx(R,{});if(u)return e.jsx(O,{message:u});const l=Array.isArray(a)?a:[];return l.length===0?e.jsx(W,{title:"Sem conversas registradas",body:"Nenhuma thread WhatsApp foi iniciada com este motorista."}):e.jsxs("div",{className:"space-y-1.5",children:[l.slice(0,20).map(n=>{const h=n.unreadByManager||0;return e.jsx(oe,{left:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:n.lastMessageText||"(sem mensagens)"}),h>0&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-bold",style:{background:"#F97316",color:"white"},children:h})]}),sub:e.jsxs("span",{children:[n.lastMessageBy==="manager"?"Você â motorista":"Motorista â você"," · ",K(es(n.lastMessageAt))]}),right:e.jsx(ze,{to:`/comunicacao?thread=${n.id}`,className:"text-xs underline",style:{color:"#3B82F6"},children:"abrir"})},n.id)}),l.length>20&&e.jsxs("p",{className:"text-[11px] text-center pt-2",style:{color:"var(--page-text-muted)"},children:["Mostrando 20 de ",l.length," conversas."]})]})}function ss({driverId:s}){var L;const{data:a,loading:r,error:u,refetch:l}=V(()=>N.driverLinks(),[s]),{data:n}=V(()=>N.fleetConfigGet(),[]),{toast:h}=H(),d=(a||[]).find(k=>k.driverId===s),[t,m]=x.useState({}),[c,p]=x.useState(!1),[i,g]=x.useState(!1);if(x.useEffect(()=>{d!=null&&d.appModuleOverrides?m(d.appModuleOverrides):m({}),g(!1)},[d==null?void 0:d.id,d==null?void 0:d.appModuleOverrides]),r)return e.jsx(R,{});if(u)return e.jsx(O,{message:u});
1if(!d)return e.jsx(W,{title:"Motorista sem vÃnculo aprovado",body:"Pra configurar módulos individuais, o motorista precisa ter um vÃnculo ativo com a frota."});const f=d.driverType||"autonomo",j=((L=n==null?void 0:n.fleetConfig)==null?void 0:L.appModulePresets)||void 0,w=new Set((j==null?void 0:j[f])||Xe[f]),C=new Set(Ye(f,j,t)),M=k=>{const U=w.has(k),q=t[k];let $;q===void 0?$=!U:q!==U?$=void 0:$=!U,m(_=>{const J={..._};return $===void 0?delete J[k]:J[k]=$,J}),g(!0)},y=()=>{m({}),g(!0)},D=async()=>{if(d.id){p(!0);try{const k=Object.keys(t).length>0?t:null;await N.updateDriverLink(d.id,{appModuleOverrides:k}),E("driver_app_module_overrides_saved",{driverId:s,overrideCount:Object.keys(t).length}),h({title:"Salvo",description:"Módulos do motorista atualizados.",kind:"success"}),g(!1),l()}catch(k){h({title:"Erro ao salvar",description:((k==null?void 0:k.message)||"").slice(0,200),kind:"error"})}finally{p(!1)}}},S=Ke[f],T=Object.keys(t).length;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg p-3 flex items-start gap-2 text-xs",style:{background:"var(--surface-secondary)"},children:[e.jsx(pe,{className:"w-3.5 h-3.5 mt-0.5 shrink-0",style:{color:S.color},"aria-hidden":"true"}),e.jsxs("div",{style:{color:"var(--page-text-muted)"},children:["Categoria atual: ",e.jsx("strong",{style:{color:S.color},children:S.label}),". O preset da categoria define ",w.size," módulos visÃveis. Aqui você sobrescreve só pra este motorista."]})]}),e.jsx("div",{className:"rounded-lg overflow-hidden",style:{background:"var(--surface-secondary)",border:"1px solid var(--border-primary)"},children:e.jsx("ul",{className:"divide-y",style:{borderColor:"var(--border-primary)"},children:Qe.map(k=>{const U=w.has(k.id),q=t[k.id],$=q!==void 0,_=C.has(k.id);return e.jsx("li",{children:e.jsxs("button",{onClick:()=>M(k.id),className:"w-full flex items-center gap-3 px-3 py-2 hover-surface text-left","aria-label":`${k.label} â atualmente ${_?"ligado":"desligado"}, clique pra alternar`,children:[e.jsx("span",{className:"inline-block w-4 h-4 rounded shrink-0",style:{background:_?$?"#10B981":S.color:"transparent",border:`2px solid ${_?$?"#10B981":S.color:"#EF4444"}`,opacity:$?1:.65},"aria-hidden":"true"}),e.jsxs("span",{className:"flex-1 min-w-0 text-sm",style:{color:"var(--page-text)"},children:[e.jsx("span",{"aria-hidden":"true",children:k.icon})," ",k.label,e.jsx("span",{className:"ml-2 text-[10px]",style:{color:"var(--page-text-muted)"},children:$?q?"forçado ligado":"forçado desligado":U?"do preset":"não no preset"})]})]})},k.id)})})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("button",{onClick:y,disabled:T===0,className:"inline-flex items-center gap-1 text-[11px] px-2 py-1 rounded disabled:opacity-40",style:{color:"var(--page-text-muted)"},children:[e.jsx(da,{className:"w-3 h-3","aria-hidden":"true"}),"Voltar ao preset (",T," override",T===1?"":"s",")"]}),e.jsxs("button",{onClick:D,disabled:!i||c,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-white disabled:opacity-50",style:{background:"#F97316"},children:[c?e.jsx(P,{className:"w-3.5 h-3.5 animate-spin"}):null,i?"Salvar":"Salvo"]})]})]})}const te={critical:"#EF4444",high:"#F59E0B",medium:"#64748B"},ts=10;function rs(s){if(!s.occurredAt||!s.syncedAt)return 0;const a=Date.parse(s.syncedAt)-Date.parse(s.occurredAt);return Number.isFinite(a)?Math.max(0,Math.round(a/6e4)):0}function ns({driverId:s}){const{data:a,loading:r,error:u}=V(()=>N.driverDataFatigue(s),[s]),l=x.useMemo(()=>(a==null?void 0:a.items)??[],[a]);return r?e.jsx(R,{}):u?e.jsx(O,{message:u}):l.length===0?e.jsx(W,{title:"Nenhum alerta de fadiga",body:`Nada detectado pela câmera nos últimos ${(a==null?void 0:a.janelaDias)??45} dias. Se a câmera nunca foi ligada por este motorista, o silêncio não é sinal de nada.`}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 font-semibold",children:[e.jsx(xe,{size:16,className:"text-slate-500"}),l.length," alerta",l.length>
11?"s":""," em ",(a==null?void 0:a.janelaDias)??45," dias"]}),((a==null?void 0:a.criticos)??0)>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",style:{color:te.critical},children:[e.jsx(Pe,{size:15}),a.criticos," crÃtico",a.criticos>1?"s":""]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-slate-500",children:[e.jsx(ke,{size:15}),l.length-((a==null?void 0:a.comEvidencia)??0)," sem imagem"]})]}),e.jsx("ul",{className:"space-y-3",children:l.map(n=>{const h=rs(n);return e.jsx("li",{className:"rounded-xl border p-4",style:{borderColor:`${te[n.severidade]}44`},children:e.jsxs("div",{className:"flex gap-4",children:[n.keyframeUrl?e.jsx("img",{src:n.keyframeUrl,alt:`Evidência do alerta de ${n.rotulo}`,className:"h-24 w-32 shrink-0 rounded-lg object-cover",loading:"lazy"}):e.jsx("div",{className:"flex h-24 w-32 shrink-0 items-center justify-center rounded-lg bg-slate-100 text-slate-400",children:e.jsx(ke,{size:20})}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{size:16,style:{color:te[n.severidade]}}),e.jsx("span",{className:"font-semibold",style:{color:te[n.severidade]},children:n.rotulo})]}),e.jsxs("div",{className:"text-sm text-slate-600",children:[K(n.occurredAt),h>=ts&&e.jsxs("span",{className:"ml-2 inline-flex items-center gap-1 text-xs text-slate-500",title:"O aparelho estava sem sinal; o alerta chegou depois. A hora exibida é a do alerta.",children:[e.jsx(ma,{size:12}),"chegou ",h," min depois"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-1 text-xs text-slate-500 tabular-nums",children:[n.perclos!=null&&e.jsxs("span",{children:["olho fechado ",Math.round(n.perclos*100),"%"]}),n.piscadasPorMin!=null&&e.jsxs("span",{children:[Math.round(n.piscadasPorMin)," piscadas/min"]}),n.bocejos!=null&&n.bocejos>0&&e.jsxs("span",{children:[n.bocejos," bocejos"]}),n.lat!=null&&n.lng!=null&&e.jsx("a",{className:"text-blue-600 hover:underline",href:`https://www.google.com/maps?q=${n.lat},${n.lng}`,target:"_blank",rel:"noreferrer",children:"ver no mapa"})]})]})]})},n.id)})}),e.jsx("p",{className:"text-xs text-slate-400",children:"As imagens são capturadas apenas no instante do alerta â não há gravação contÃnua. Os links expiram em 15 minutos."})]})}function os({driverId:s,driverName:a,driverPhone:r}){const{data:u,loading:l,error:n,refetch:h}=V(()=>N.agentDriverCoaching(s),[s]),{toast:d}=H(),[t,m]=x.useState(!1),[c,p]=x.useState(!1);if(l)return e.jsx(R,{});if(n)return e.jsx(O,{message:n});const i=(u==null?void 0:u.coaching)||null,g=(i==null?void 0:i.result)||null,f=async()=>{m(!0);try{await N.runDriverCoaching(s),E("mentor_coaching_generated",{driverId:s}),d({title:"Coaching gerado",description:"Mentor preparou um feedback personalizado.",kind:"success"}),h()}catch(C){const M=((C==null?void 0:C.message)||"").slice(0,240);d({title:M.includes("402")?"Limite de IA atingido":"Erro ao gerar coaching",description:M||"Tente novamente em instantes.",kind:"error"})}finally{m(!1)}},j=async()=>{var y,D;if(!g||!r)return;const M=[g.greeting,(y=g.strengths)!=null&&y.length?`Pontos fortes: 2⢠${g.strengths.join(` 3⢠`)}`:null,(D=g.suggestions)!=null&&D.length?`Sugestões: 4${g.suggestions.map(S=>`⢠${S.area}: ${S.tip}`).join(` 5`)}`:null,g.overallMessage].filter(Boolean).join(` 6 7`);p(!0);try{await N.sendMessage({driverId:s,driverName:a,text:M,priority:"normal"}),E("mentor_coaching_sent_whatsapp",{driverId:s}),d({title:"Enviado",description:`Coaching enviado pro ${a||"motorista"}.`,kind:"success"})}catch(S){d({title:"Erro ao enviar",description:((S==null?void 0:S.message)||"").slice(0,200),kind:"error"})}finally{p(!1)}};if(!i||!g)return e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"rounded-xl p-4 text-center",style:{background:"var(--surface-secondary)",border:"1px dashed var(--border-primary)"},children:[e.jsx(we,{className:"w-6 h-6 mx-auto mb-2",style:{color:"#8B5CF6"},"aria-hidden":"true"}),e.jsx("p",{className:"text-sm font-semibold mb-1",style:{color:"var(--page-text)"},children:"Sem coaching ainda"}),e.jsx("p",{className:"text-xs mb-3",style:{color:"var(--page-text-muted)"},children:"Mentor analisa últimos 30 dias de eventos, scores e viagens e gera um plano personalizado em pt-BR."}),e.jsxs("button",{onClick:f,disabled:t,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-white disabled:opacity-60",style:{background:"#8B5CF6"},children:[t?e.jsx(P,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(we,{className:"w-3.5 h-3.5"}),t?"Gerandoâ¦":"Gerar coaching"]})]})});const w=i.inputSummary||{};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl p-3",style:{background:"linear-gradient(135deg, rgba(139,92,246,0.10), rgba(139,92,246,0.02))",border:"1px solid rgba(139,92,246,0.30)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-xl","aria-hidden":"true",children:g.emoji||"ð"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[11px] font-semibold uppercase tracking-wide",style:{color:"#8B5CF6"},children:["Mentor · ",i.fromAI?"IA":"determinÃstico"]}),e.jsx("div",{className:"text-[10px]",style:{color:"var(--page-text-muted)"},children:K(i.createdAt)})]})]}),e.jsxs("button",{onClick:f,disabled:t,className:"inline-flex items-center gap-1 text-[11px] px-2 py-1 rounded disabled:opacity-50",style:{color:"var(--page-text-muted)",background:"var(--surface-secondary)"},title:"Regerar coaching",children:[t?e.jsx(P,{className:"w-3 h-3 animate-spin"}):e.jsx(pa,{className:"w-3 h-3"}),"Regerar"]})]}),g.greeting&&e.jsx("p",{className:"text-sm mb-2",style:{color:"var(--page-text)"},children:g.greeting}),g.strengths&&g.strengths.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"text-[11px] font-semibold mb-1",style:{color:"#10B981"},children:"Pontos fortes"}),e.jsx("ul",{className:"text-xs space-y-0.5 pl-3",style:{color:"var(--page-text)"},children:g.strengths.map((C,M)=>e.jsx("li",{className:"list-disc",children:C},M))})]}),g.suggestions&&g.suggestions.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"text-[11px] font-semibold mb-1",style:{color:"#F59E0B"},children:"Sugestões práticas"}),e.jsx("ul",{className:"text-xs space-y-1",children:g.suggestions.map((C,M)=>e.jsxs("li",{className:"rounded p-2",style:{background:"var(--surface-primary)"},children:[e.jsxs("strong",{style:{color:"var(--page-text)"},children:[C.area,":"]})," ",e.jsx("span",{style:{color:"var(--page-text-muted)"},children:C.tip})]},M))})]}),g.overallMessage&&e.jsx("p",{className:"text-xs italic mt-2",style:{color:"var(--page-text-muted)"},children:g.overallMessage}),g.text&&!g.greeting&&e.jsx("p",{className:"text-xs whitespace-pre-wrap",style:{color:"var(--page-text)"},children:g.text})]}),e.jsxs("div",{className:"rounded-lg px-3 py-2 text-[11px] flex items-center justify-between gap-2",style:{background:"var(--surface-secondary)",color:"var(--page-text-muted)"},children:[e.jsxs("span",{children:["Base: ",w.trips||0," viagens · ",w.events||0," eventos ·
7score ",w.avgScore||0,"/100"]}),r&&e.jsxs("button",{onClick:j,disabled:c,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-white text-[10px] font-semibold disabled:opacity-50",style:{background:"#25D366"},children:[c?e.jsx(P,{className:"w-3 h-3 animate-spin"}):e.jsx(me,{className:"w-3 h-3"}),"Enviar por WhatsApp"]})]}),e.jsxs("section",{className:"mt-6 pt-6 border-t",style:{borderColor:"var(--page-border)"},children:[e.jsx("h3",{className:"text-sm font-bold mb-3",style:{color:"var(--page-text)"},children:"Alertas da câmera de fadiga"}),e.jsx(ns,{driverId:s})]})]})}const _e=s=>{if(!s)return"â";try{return new Date(s).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return"â"}};function is({onVinculado:s}){const{toast:a}=H(),[r,u]=x.useState(!1),[l,n]=x.useState(""),[h,d]=x.useState(""),[t,m]=x.useState(null),[c,p]=x.useState(null),[i,g]=x.useState(!1),[f,j]=x.useState(!1),w=x.useCallback(async y=>{const D=l.trim().toUpperCase(),S=h.trim().toLowerCase();if(!D||!S){a({title:"Faltam dados",description:"Informe o código e o e-mail.",kind:"warning"});return}g(!0);try{const T=await N.diagnosticarVinculoManual(D,S,y);m(T),p(T.sugerida),E("vinculo_manual_diagnostico",{contas:T.contas.length,varreu:y})}catch(T){a({title:"Não consegui consultar",description:((T==null?void 0:T.message)||"").slice(0,200),kind:"error"})}finally{g(!1)}},[l,h,a]),C=x.useCallback(async()=>{if(c){j(!0);try{const y=await N.vincularMotoristaManual(l.trim().toUpperCase(),h.trim().toLowerCase(),c);a({title:y.jaVinculado?"Já estava vinculado":"Motorista vinculado",description:y.jaVinculado?"Nada a fazer â o vÃnculo já existia.":"O vÃnculo já nasce aprovado. Ele aparece na lista agora.",kind:"success"}),E("vinculo_manual_criado",{jaVinculado:!!y.jaVinculado}),m(null),n(""),d(""),p(null),u(!1),s()}catch(y){a({title:"Não consegui vincular",description:((y==null?void 0:y.message)||"").slice(0,200),kind:"error"})}finally{j(!1)}}},[l,h,c,a,s]);if(!r)return e.jsxs("button",{onClick:()=>u(!0),className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors",style:{background:"var(--surface-tertiary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"},children:[e.jsx(Ce,{className:"w-3.5 h-3.5","aria-hidden":"true"}),"Vincular motorista existente"]});const M=t&&!t.impedimento&&c;return e.jsxs("div",{className:"rounded-xl p-4 w-full",style:{background:"var(--surface-secondary)",border:"1px solid var(--border-primary)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[e.jsx(Ce,{className:"w-4 h-4 mt-0.5 shrink-0",style:{color:"var(--page-text-muted)"},"aria-hidden":"true"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold",style:{color:"var(--page-text)"},children:"Vincular motorista existente"}),e.jsx("p",{className:"text-[11px] leading-relaxed mt-0.5",style:{color:"var(--page-text-muted)"},children:"Para quando o motorista já criou a conta no app e digitou o código, mas a solicitação não chegou à fila. Usa o mesmo código do convite."})]})]}),e.jsx("button",{onClick:()=>{u(!1),m(null)},className:"text-xs px-2 py-1 rounded",style:{color:"var(--page-text-muted)"},children:"Fechar"})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-[1fr_1.4fr_auto]",children:[e.jsx("input",{value:l,onChange:y=>n(y.target.value),placeholder:"S365-XXXXXX","aria-label":"Código de convite",className:"px-3 py-2 rounded-lg text-sm font-mono",style:{background:"var(--surface-primary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"}}),e.jsx("input",{value:h,onChange:y=>d(y.target.value),placeholder:"e-mail do motorista",type:"email","aria-label":"E-mail do motorista",className:"px-3 py-2 rounded-lg text-sm",style:{background:"var(--surface-primary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"}}),e.jsxs("button",{onClick:()=>w(!1),disabled:i,className:"inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold text-white disabled:opacity-60",style:{background:"#F97316"},children:[i?e.jsx(P,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":"true"}
7):e.jsx(xa,{className:"w-3.5 h-3.5","aria-hidden":"true"}),"Consultar"]})]}),t&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px]",style:{color:"var(--page-text-muted)"},children:[e.jsxs("span",{children:["Código:"," ",e.jsx("strong",{style:{color:"var(--page-text)"},children:t.codigo.existe?t.codigo.orgNome||"encontrado":"não encontrado"})]}),e.jsxs("span",{children:["Usos: ",t.codigo.usos,"/",t.codigo.maxUsos]}),t.codigo.vencido&&e.jsx("span",{style:{color:"var(--danger)"},children:"vencido"}),!t.codigo.ativo&&e.jsx("span",{style:{color:"var(--danger)"},children:"desativado"})]}),t.impedimento&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg p-3 text-xs",style:{background:"var(--surface-tertiary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"},children:[e.jsx(Pe,{className:"w-4 h-4 shrink-0 mt-0.5",style:{color:"var(--warning)"},"aria-hidden":"true"}),e.jsx("span",{children:t.impedimento})]}),t.contas.length>1&&e.jsxs("div",{className:"flex items-start gap-2 text-[11px]",style:{color:"var(--page-text-muted)"},children:[e.jsx(pe,{className:"w-3.5 h-3.5 shrink-0 mt-0.5","aria-hidden":"true"}),e.jsxs("span",{children:["Este e-mail tem ",e.jsxs("strong",{children:[t.contas.length," contas"]}),". Escolha a que o motorista está usando â vincular a errada cria um motorista que nunca aparece."]})]}),t.contas.map(y=>{const D=c===y.uid,S=y.jaVinculada||y.desabilitada;return e.jsxs("button",{onClick:()=>!S&&p(y.uid),disabled:S,className:"w-full text-left rounded-lg p-3 transition-colors disabled:opacity-50",style:{background:D?"var(--surface-tertiary)":"var(--surface-primary)",border:`1px solid ${D?"#F97316":"var(--border-primary)"}`},children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium",style:{color:"var(--page-text)"},children:[y.nome||"Sem nome",y.uid===t.sugerida&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold",style:{color:"#F97316"},children:"sugerida"})]}),e.jsx("p",{className:"text-[11px] font-mono truncate",style:{color:"var(--page-text-muted)"},children:y.uid})]}),D&&e.jsx(ga,{className:"w-4 h-4 shrink-0",style:{color:"#F97316"},"aria-hidden":"true"})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1.5 text-[11px]",style:{color:"var(--page-text-muted)"},children:[e.jsxs("span",{children:["Criada: ",_e(y.criadoEm)]}),e.jsxs("span",{children:["Ãltimo acesso: ",_e(y.ultimoAcessoEm)]}),y.temVinculoNestaOrg&&e.jsx("span",{style:{color:"var(--success)"},children:"já apareceu nesta frota"}),y.temDadosDeMotorista&&!y.temVinculoNestaOrg&&e.jsx("span",{children:"tem dados de motorista"}),y.jaVinculada&&e.jsx("span",{style:{color:"var(--success)"},children:"já vinculada"}),y.desabilitada&&e.jsx("span",{style:{color:"var(--danger)"},children:"desabilitada"})]})]},y.uid)}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap pt-1",children:[e.jsx("button",{onClick:()=>w(!0),disabled:i,className:"text-[11px] underline disabled:opacity-60",style:{color:"var(--page-text-muted)"},children:"Não é nenhuma dessas? Procurar contas duplicadas (mais lento)"}),e.jsxs("button",{onClick:C,disabled:!M||f,className:"inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold text-white disabled:opacity-40",style:{background:"var(--success)"},children:[f?e.jsx(P,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":"true"}):e.jsx(Ve,{className:"w-3.5 h-3.5","aria-hidden":"true"}),"Vincular e aprovar"]})]}),t.buscaTruncada&&e.jsx("p",{className:"text-[11px]",style:{color:"var(--page-text-muted)"},children:"A busca por contas duplicadas parou no limite â pode haver outras não listadas."})]})]})}function As({onNova:s,onAtivacao:a}){const{data:r,loading:u,error:l,silentRefetch:n}=V(()=>N.drivers(),[]),{data:h,silentRefetch:d}=V(()=>N.driverLinks("pending_org_approval"),[]),{toast:t}=H(),{confirmar:m}
7=Ze(),[c,p]=x.useState("todos"),[i,g]=x.useState(null),[f,j]=x.useState(null),[w,C]=x.useState(!1),[M,y]=x.useState(!1),[D,S]=x.useState(!1),[T,L]=x.useState(null),k=x.useCallback(async(o,v)=>{L(o);try{await N.approveDriver(o),E("motorista_link_approved",{from:"v3_pending_bar"}),t({title:"Motorista vinculado",description:v,kind:"success"}),d(),n()}catch(b){t({title:"Não consegui aprovar",description:((b==null?void 0:b.message)||"").slice(0,200),kind:"error"})}finally{L(null)}},[t,d,n]),U=x.useCallback(async(o,v)=>{if(await m({titulo:`Rejeitar a solicitação de "${v}"?`,descricao:"O motorista pode pedir de novo pelo app.",confirmar:"Rejeitar"})){L(o);try{await N.rejectDriver(o),E("motorista_link_rejected",{from:"v3_pending_bar"}),t({title:"Solicitação rejeitada",description:v,kind:"info"}),d()}catch(b){t({title:"Não consegui rejeitar",description:((b==null?void 0:b.message)||"").slice(0,200),kind:"error"})}finally{L(null)}}},[t,d,m]),q=x.useCallback(async()=>{C(!0);try{const o=await N.generateInviteCode();j(o.code),y(!1),E("motorista_invite_code_generated"),t({title:"Código gerado",description:o.code,kind:"success"})}catch(o){t({title:"Não consegui gerar o código",description:((o==null?void 0:o.message)||"").slice(0,200),kind:"error"})}finally{C(!1)}},[t]),$=x.useCallback(()=>{f&&navigator.clipboard.writeText(f).then(()=>{y(!0),E("motorista_invite_code_copied"),setTimeout(()=>y(!1),2e3)}).catch(()=>{t({title:"Não consegui copiar",description:"Copie manualmente.",kind:"error"})})},[f,t]);x.useEffect(()=>{l&&t({title:"Não consegui carregar motoristas",description:l.slice(0,200),kind:"error"})},[l,t]);const _=x.useMemo(()=>(r||[]).map(v=>{const b=v.cnhVencimento||v.cnhExpiresAt,B=b?ds(b):null,Z=B==null?"unknown":B<0?"error":B<=30?"warn":"ok",Y=v.driverId||v.id||v.uid||"",F=v.name||v.displayName||v.fullName||"â",Oe=$a({cnhDaysToExpire:B,examDaysToExpire:v.exameToxicoVencido?-1:null,currentDrivingScore:v.score||v.driverScore||v.avgScore||null});return{id:Y,driverId:Y,linkId:v.linkId,name:F,cpf:v.cpf||v.documento,status:v.status==="suspended"?"suspenso":v.status==="inactive"?"inativo":"ativo",vehicleAtual:v.currentVehiclePlate||v.vehiclePlate,currentVehicleId:v.currentVehicleId||void 0,currentVehiclePlate:v.currentVehiclePlate||void 0,viagensMes:v.tripsThisMonth||0,score:v.score||v.driverScore||0,cnhStatus:Z,jornadaStatus:v.jornadaRisk?"warn":"ok",examesStatus:v.exameToxicoVencido?"error":"ok",cnhVencimento:b,phone:v.phone||v.whatsapp,linkedAt:v.linkedAt||null,attention:Oe}}),[r]),J=x.useMemo(()=>c==="todos"?_:c==="ativos"?_.filter(o=>o.status==="ativo"):c==="cnh_vencendo"?_.filter(o=>o.cnhStatus==="warn"||o.cnhStatus==="error"):c==="jornada_risco"?_.filter(o=>o.jornadaStatus!=="ok"):c==="sem_viagem"?_.filter(o=>o.viagensMes===0):c==="atencao"?_.filter(o=>o.attention.tier!=="ok").sort((o,v)=>v.attention.score-o.attention.score):_,[_,c]),G=x.useCallback(o=>{p(o),E("motoristas_filter",{filter:o})},[]),Le=[{key:"name",label:"Nome",width:"1.5fr",render:o=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold text-white",style:{background:"var(--accent-brand)"},children:o.name.charAt(0).toUpperCase()}),e.jsx("span",{children:o.name})]}),sortValue:o=>o.name},{key:"status",label:"Status",width:100,render:o=>e.jsx(De,{status:o.status}),sortValue:o=>o.status},{key:"vehicleAtual",label:"VeÃculo",width:100,render:o=>e.jsx("span",{className:"font-mono",children:o.vehicleAtual||"â"})},{key:"viagensMes",label:"Viagens/mês",width:100,align:"right",render:o=>o.viagensMes,sortValue:o=>o.viagensMes},{key:"score",label:"Score",width:80,align:"right",render:o=>e.jsx("span",{style:{color:o.score>=80?"#10B981":o.score>=60?"#F59E0B":"#EF4444"},children:o.score}),sortValue:o=>o.score},{key:"compliance",label:"Compliance",width:160,render:o=>e.jsx(Ne,{c:{cnh:o.cnhStatus,jornada:o.jornadaStatus,exames:o.examesStatus}})},{key:"atencao",label:"Atenção",width:130,render:o=>e.jsx(Fa,{attention:o.attention}),sortValue:o=>o.attention.score}],he=_.filter(o=>o.cnhStatus==="warn"||o.cnhStatus==="error").length,[z,ve]=x.useState(null),[I,fe]=x.useState(null),[X,Q]=x.useState(null),ie=x.useCallback((o,v)=>{E("motoristas_bulk_open",{action:v?"cnh_request":"whatsapp",count:o.length}),ve({targets:o,template:v})},[]),Ie=x.useCallback(async()=>
7{const v=(I||[]).filter(B=>B.linkId).map(B=>B.linkId);if(v.length===0){t({title:"Nenhum vÃnculo pra suspender",description:"Os selecionados não têm vÃnculo ativo gerenciável.",kind:"error"});return}const b=await N.bulkDriverLinkStatus(v,"suspended");E("motoristas_bulk_suspend",{count:b.updated,skipped:b.skipped.length}),t({title:`${b.updated} motorista${b.updated===1?"":"s"} suspenso${b.updated===1?"":"s"}`,description:b.skipped.length>0?`${b.skipped.length} pulado(s).`:void 0,kind:"success"}),n()},[I,t,n]),Re=x.useCallback(async o=>{const v=o.filter(b=>b.linkId&&b.status==="suspenso").map(b=>b.linkId);if(v.length===0){t({title:"Nada pra reativar",description:"Selecione motoristas suspensos.",kind:"info"});return}try{const b=await N.bulkDriverLinkStatus(v,"approved");E("motoristas_bulk_reactivate",{count:b.updated}),t({title:`${b.updated} motorista${b.updated===1?"":"s"} reativado${b.updated===1?"":"s"}`,kind:"success"}),n()}catch(b){t({title:"Não consegui reativar",description:((b==null?void 0:b.message)||"").slice(0,200),kind:"error"})}},[t,n]),ye=x.useCallback(async(o,v)=>{const b=["Nome","Status","CNH situação","CNH validade","VeÃculo","Viagens/mês","Score"],B={ok:"Válida",warn:"Vencendo",error:"Vencida",unknown:"Sem data"},Z=o.map(F=>[F.name,F.status,B[F.cnhStatus]||F.cnhStatus,Aa(F.cnhVencimento),F.vehicleAtual||"â",F.viagensMes,F.score||"â"]),Y=`motoristas-${new Date().toISOString().slice(0,10)}`;try{v==="excel"?await Ma({filename:Y,sheetName:"Motoristas",headers:b,rows:Z}):await _a({filename:Y,title:"Motoristas â seleção",subtitle:`${o.length} motorista${o.length===1?"":"s"} selecionado${o.length===1?"":"s"}`,headers:b,rows:Z}),E("motoristas_bulk_export",{format:v,count:o.length}),t({title:"Exportação gerada",description:`${o.length} motorista(s) · ${v==="excel"?"Excel":"PDF"}`,kind:"success"})}catch(F){t({title:"Falha na exportação",description:((F==null?void 0:F.message)||"").slice(0,200),kind:"error"})}Q(null)},[t]);return e.jsxs("div",{"data-testid":"motoristas-list",children:[e.jsx(ps,{code:f,loading:w,copied:M,onGenerate:q,onCopy:$,onVinculado:()=>{n(),d()}}),e.jsx(ms,{pending:h||[],expanded:D,onToggle:()=>S(o=>!o),busy:T,onApprove:k,onReject:U}),e.jsx(Da,{eixo:"motoristas",acaoExtra:a?{label:"Convidar pelo app",onClick:a}:void 0}),e.jsx(aa,{rows:J,rowKey:o=>o.id,columns:Le,loading:u,filterChips:[{key:"todos",label:"Todos",active:c==="todos",onClick:()=>G("todos")},{key:"ativos",label:"Ativos",active:c==="ativos",onClick:()=>G("ativos")},{key:"cnh_vencendo",label:"CNH vencendo",active:c==="cnh_vencendo",onClick:()=>G("cnh_vencendo")},{key:"jornada_risco",label:"Jornada em risco",active:c==="jornada_risco",onClick:()=>G("jornada_risco")},{key:"sem_viagem",label:"Sem viagem mês",active:c==="sem_viagem",onClick:()=>G("sem_viagem")},{key:"atencao",label:"Por atenção",active:c==="atencao",onClick:()=>G("atencao")}],bulkActions:[{key:"msg",label:"WhatsApp",icon:e.jsx(me,{className:"w-3.5 h-3.5"}),run:async o=>ie(o)},{key:"cnh",label:"Pedir CNH",icon:e.jsx(ue,{className:"w-3.5 h-3.5"}),run:async o=>ie(o,"cnh_request")},{key:"exp",label:"Exportar",icon:e.jsx(ha,{className:"w-3.5 h-3.5"}),run:async o=>{E("motoristas_bulk_open",{action:"export",count:o.length}),Q(o)}},{key:"react",label:"Reativar",icon:e.jsx(Ve,{className:"w-3.5 h-3.5"}),run:async o=>Re(o)},{key:"susp",label:"Suspender",icon:e.jsx(va,{className:"w-3.5 h-3.5"}),variant:"destructive",run:async o=>{E("motoristas_bulk_open",{action:"suspend",count:o.length}),fe(o)}}],onRowOpen:o=>{E("motoristas_row_open"),g(o)},onCreate:s,createLabel:"Novo motorista",emptyTitle:"Sem motoristas cadastrados.",emptyBody:"Importe via planilha, convide pelo WhatsApp ou cadastre manualmente.",adaCard:he>=3?e.jsx(ka,{variant:"warn",title:`${he} motoristas com CNH vencida ou vencendo em 30 dias.`,body:"Quer que eu peça foto da CNH renovada pelo WhatsApp em lote?",actions:[{label:"Sim, pedir todas",onClick:()=>ie(_.filter(o=>o.cnhStatus==="warn"||o.cnhStatus==="error"),"cnh_request"),variant:"primary"},{label:"Ver lista",onClick:()=>G("cnh_vencendo"),variant:"ghost"}]}):void 0}),e.jsx(sa,{open:!!i,onClose:()=>g(null),title:(i==null?void 0:i.name)||"",subtitle:i&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{status:i.status}),e.jsx(Ne,{c:{cnh:i.cnhStatus,jornada:i.jornadaStatus,exames:i.examesStatus}}),i.phone&&e.jsx(cs,{phone:i.phone})]}),tabs:[{key:"resumo",label:"Resumo",content:i&&e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx(ls,{cpf:i.cpf,driverId:i.driverId}),e.jsx(us,{row:i,onChanged:n}),e.jsx(re,{label:"Viagens este mês",value:String(i.viagensMes)}),e.jsx(re,{label:"Score",value:String(i.score)}),e.jsx(re,{label:"CNH vencimento",value:i.cnhVencimento||"â"})]})},{key:"gps",label:"GPS",content:i&&e.jsx(Va,{driverId:i.driverId,driverName:i.name,linkedAt:i.linkedAt||void 0})},{key:"jornada",label:"Jornada",content:i&&e.jsx(za,{driverId:i.driverId})},{key:"documentos",label:"Documentos",content:i&&e.jsx(Ja,{driverId:i.driverId})},{key:"multas",label:"Multas",content:i&&e.jsx(Qa,{driverId:i.driverId})},{key:"pagamentos",label:"Pagamentos",content:i&&e.jsx(Za,{driverId:i.driverId})},{key:"mensagens",label:"Mensagens",content:i&&e.jsx(as,{driverId:i.driverId})},{key:"modulos",label:"Módulos",content:i&&e.jsx(ss,{driverId:i.driverId})},{key:"coaching",label:"Coaching IA",content:i&&e.jsx(os,{driverId:i.driverId,driverName:i.name,driverPhone:i.phone||void 0})},{key:"atividade",label:"Atividade",content:i&&e.jsx(Ca,{objectType:"motorista",objectId:i.id})},{key:"comentarios",label:"Comentários",content:i&&e.jsx(wa,{objectType:"motorista",objectId:i.id})}],size:"lg"}),e.jsx(Oa,{open:!!z,onClose:()=>ve(null),targets:((z==null?void 0:z.targets)||[]).map(o=>({driverId:o.driverId,name:o.name,phone:o.phone})),template:z==null?void 0:z.template}),e.jsx(ea,{open:!!I,onClose:()=>fe(null),title:`Suspender ${(I==null?void 0:I.length)||0} motorista${((I==null?void 0:I.length)||0)===1?"":"s"}?`,description:"Motoristas suspensos não recebem novas viagens. Você pode reativar depois pela ação em lote 'Reativar'.",confirmLabel:"Suspender selecionados",requireTyping:"SUSPENDER",onConfirm:Ie}),X&&e.jsxs("div",{className:"fixed inset-0 z-modal flex items-center justify-center p-4",role:"dialog","aria-modal":"true","aria-label":"Exportar seleção",onClick:()=>Q(null),"data-testid":"export-format-modal",children:[e.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{className:"relative w-full max-w-sm rounded-2xl shadow-2xl p-5",style:{background:"var(--surface-primary)",border:"1px solid var(--border-primary)"},onClick:o=>o.stopPropagation(),children:[e.jsxs("h2",{className:"text-base font-bold mb-1",style:{color:"var(--page-text)"},children:["Exportar ",X.length," motorista",X.length===1?"":"s"]}),e.jsx("p",{className:"text-xs mb-4",style:{color:"var(--page-text-muted)"},children:"Nome, status, CNH (situação e validade), veÃculo, viagens e score. CPF não é exportado."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>ye(X,"excel"),className:"flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-sm font-semibold text-white",style:{background:"#10B981"},children:[e.jsx(fa,{className:"w-4 h-4","aria-hidden":"true"}),"Excel (.xlsx)"]}
7),e.jsxs("button",{onClick:()=>ye(X,"pdf"),className:"flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-sm font-semibold text-white",style:{background:"#EF4444"},children:[e.jsx(ue,{className:"w-4 h-4","aria-hidden":"true"}),"PDF"]})]}),e.jsx("button",{onClick:()=>Q(null),className:"w-full mt-2 px-3 py-1.5 rounded-lg text-xs",style:{color:"var(--page-text-muted)"},children:"Cancelar"})]})]})]})}function De({status:s}){const a={ativo:{label:"Ativo",color:"#10B981"},inativo:{label:"Inativo",color:"#9CA3AF"},suspenso:{label:"Suspenso",color:"#EF4444"}},r=a[s]||a.ativo;return e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:r.color}}),r.label]})}function re({label:s,value:a}){return e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{style:{color:"var(--page-text-muted)"},children:s}),e.jsx("span",{style:{color:"var(--page-text)"},children:a})]})}function ls({cpf:s,driverId:a}){const[r,u]=x.useState(!1),l=Sa(s),n=!!s&&s!=="â";return e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{style:{color:"var(--page-text-muted)"},children:"CPF"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{style:{color:"var(--page-text)"},className:"font-mono text-xs",children:n?r?s:l:"â"}),n&&e.jsx("button",{type:"button",onClick:()=>{const h=!r;u(h),h&&E("pii_revealed",{field:"cpf",entity:"motorista",entityId:a})},className:"p-1 rounded hover-surface","aria-label":r?"Ocultar CPF":"Mostrar CPF (registrado em auditoria)",title:r?"Ocultar CPF":"Mostrar CPF (registrado em auditoria)",children:r?e.jsx(Be,{className:"w-3.5 h-3.5",style:{color:"var(--page-text-muted)"},"aria-hidden":"true"}):e.jsx(xe,{className:"w-3.5 h-3.5",style:{color:"var(--page-text-muted)"},"aria-hidden":"true"})})]})]})}function cs({phone:s}){const[a,r]=x.useState(!1);return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"font-mono text-[11px]",children:a?s:Ea(s)}),e.jsx("button",{type:"button",onClick:()=>{const u=!a;r(u),u&&E("pii_revealed",{field:"phone",entity:"motorista"})},className:"p-0.5 rounded hover-surface","aria-label":a?"Ocultar telefone":"Mostrar telefone",title:a?"Ocultar telefone":"Mostrar telefone",children:a?e.jsx(Be,{className:"w-3 h-3",style:{color:"var(--page-text-muted)"},"aria-hidden":"true"}):e.jsx(xe,{className:"w-3 h-3",style:{color:"var(--page-text-muted)"},"aria-hidden":"true"})})]})}function ds(s){const a=new Date(s);return isNaN(a.getTime())?0:Math.ceil((a.getTime()-Date.now())/(1e3*60*60*24))}function us({row:s,onChanged:a}){const{data:r}=V(()=>N.vehicles(),[]),[u,l]=x.useState(!1),[n,h]=x.useState(!1),[d,t]=x.useState(s.currentVehicleId||""),[m,c]=x.useState(null),p=r||[],i=p.find(j=>j.id===s.currentVehicleId),g=i?`${(i.plate||"").toUpperCase()} â ${i.model||i.brand||""}`.trim():s.currentVehiclePlate||"â";if(!s.linkId)return e.jsx(re,{label:"VeÃculo atual",value:g});if(!u)return e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{style:{color:"var(--page-text-muted)"},children:"VeÃculo atual"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{style:{color:"var(--page-text)"},children:g}),e.jsx("button",{onClick:()=>{t(s.currentVehicleId||""),l(!0),c(null)},className:"text-[10px] px-2 py-0.5 rounded hover-surface",style:{border:"1px solid var(--border-primary)",color:"var(--page-text-muted)"},children:"alterar"})]})]});const f=async j=>{if(s.linkId){h(!0),c(null);try{const w=j?p.find(M=>M.id===j):null,C=w?(w.plate||"").toUpperCase():null;await N.setDriverCurrentVehicle(s.linkId,j,C),E("motorista_vehicle_set",{driverId:s.driverId,hasVehicle:!!j}),l(!1),a()}catch(w){c((w==null?void 0:w.message)||"Falha ao salvar.")}finally{h(!1)}}};return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center gap-2",children:[e.jsx("span",{style:{color:"var(--page-text-muted)"},children:"VeÃculo atual"}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 justify-end max-w-[300px]",children:[e.jsxs("select",{value:d,onChange:j=>t(j.target.value),disabled:n,className:"text-xs px-2 py-1 rounded flex-1 min-w-0",style:{background:"var(--surface-secondary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"},"aria-label":"Selecionar veÃculo atual",children:[e.jsx("option",{value:"",children:"â sem veÃculo â"}),p.map(j=>e.jsxs("option",{value:j.id,children:[(j.plate||"").toUpperCase()," ",j.model?`· ${j.model}`:""]},j.id))]}),e.jsx("button",{onClick:()=>f(d||null),disabled:n,className:"text-[10px] px-2 py-1 rounded text-white font-semibold disabled:opacity-50",style:{background:"#F97316"},children:n?"â¦":"Salvar"}),e.jsx("button",{onClick:()=>{l(!1),c(null)},disabled:n,className:"text-[10px] px-2 py-1 rounded",style:{color:"var(--page-text-muted)"},children:"cancelar"})]})]}),m&&e.jsx("div",{className:"text-[10px] text-right",style:{color:"#EF4444"},children:m}),e.jsx("div",{className:"text-[10px] text-right",style:{color:"var(--page-text-muted)"},children:"Próximas viagens deste motorista serão atribuÃdas a este veÃculo automaticamente."})]})}function ms({pending:s,expanded:a,onToggle:r,busy:u,onApprove:l,onReject:n}){if(s.length===0)return null;const h=s.length;return e.jsxs("div",{className:"mb-3 rounded-xl overflow-hidden",style:{background:"var(--surface-secondary)",border:"1px solid #F59E0B"},"data-testid":"pending-approvals-bar",children:[e.jsxs("button",{onClick:r,className:"w-full flex items-center justify-between gap-3 px-4 py-2.5 text-left",style:{color:"var(--page-text)"},"aria-expanded":a,"aria-controls":"pending-approvals-list",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"p-1.5 rounded-lg shrink-0",style:{background:"#F59E0B20"},children:e.jsx(ba,{className:"w-4 h-4",style:{color:"#F59E0B"},"aria-hidden":"true"})}),e.jsxs("span",{className:"text-sm font-semibold",children:[h," ",h===1?"solicitação":"solicitações"," de vÃnculo aguardando aprovação"]})]}),e.jsx(Te,{className:"w-4 h-4 shrink-0 transition-transform",style:{color:"var(--page-text-muted)",transform:a?"rotate(180deg)":"rotate(0)"},"aria-hidden":"true"})]}),a&&e.jsx("ul",{id:"pending-approvals-list",className:"divide-y",style:{borderTop:"1px solid var(--border-primary)"},children:s.map(d=>e.jsxs("li",{className:"px-4 py-2.5 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",style:{color:"var(--page-text)"},children:d.driverName}),e.jsxs("div",{className:"text-xs truncate",style:{color:"var(--page-text-muted)"},children:[d.driverEmail||"â",d.inviteCode&&e.jsxs("span",{className:"ml-2 font-mono",children:["· ",d.inviteCode]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:()=>n(d.id,d.driverName),disabled:u===d.id,className:"inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold disabled:opacity-60",style:{background:"var(--surface-tertiary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"},"aria-label":`Rejeitar ${d.driverName}`,children:[e.jsx($e,{className:"w-3.5 h-3.5","aria-hidden":"true"}),"Rejeitar"]}),e.jsxs("button",{onClick:()=>l(d.id,d.driverName),disabled:u===d.id,className:"inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold text-white disabled:opacity-60",style:{background:"#10B981"},"aria-label":`Aprovar ${d.driverName}`,children:[u===d.id?e.jsx(P,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":"true"}):e.jsx(Na,{className:"w-3.5 h-3.5","aria-hidden":"true"}),"Aprovar"]})]})]},d.id))})]})}
7function ps({code:s,loading:a,copied:r,onGenerate:u,onCopy:l,onVinculado:n}){return e.jsxs("div",{className:"mb-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[e.jsx(le,{className:"w-4 h-4 mt-0.5 shrink-0",style:{color:"var(--page-text-muted)"},"aria-hidden":"true"}),e.jsx("div",{className:"text-xs leading-relaxed",style:{color:"var(--page-text-muted)"},children:"Vincular motorista à frota â gera um código que o motorista digita no app DriverCopilot."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(is,{onVinculado:n}),e.jsxs("button",{onClick:u,disabled:a,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors text-white disabled:opacity-60",style:{background:"#F97316"},"aria-label":"Gerar código de convite",children:[a?e.jsx(P,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":"true"}):e.jsx(le,{className:"w-3.5 h-3.5","aria-hidden":"true"}),"Gerar código de convite"]})]})]}),s&&e.jsxs("div",{className:"rounded-xl p-4",style:{background:"var(--surface-secondary)",border:"1px solid #F97316"},"data-testid":"invite-code-card",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"p-2 rounded-lg shrink-0",style:{background:"#F9731620"},children:e.jsx(le,{className:"w-6 h-6",style:{color:"#F97316"},"aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px]",style:{color:"var(--page-text-muted)"},children:"Código de convite gerado"}),e.jsx("p",{className:"text-2xl sm:text-3xl font-mono font-bold tracking-[0.2em] break-all",style:{color:"#F97316"},"data-testid":"invite-code-value",children:s}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[11px]",style:{color:"var(--page-text-muted)"},children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Fe,{className:"w-3 h-3","aria-hidden":"true"})," Válido por 7 dias"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ya,{className:"w-3 h-3","aria-hidden":"true"})," Uso único (1 motorista)"]})]})]})]}),e.jsxs("button",{onClick:l,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap",style:{background:"var(--surface-tertiary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"},"aria-label":r?"Código copiado":"Copiar código",children:[e.jsx(ja,{className:"w-3.5 h-3.5","aria-hidden":"true"}),r?"Copiado!":"Copiar código"]})]}),e.jsxs("div",{className:"mt-3 pt-3 flex items-start gap-2 text-[11px]",style:{borderTop:"1px solid var(--border-primary)",color:"var(--page-text-muted)"},children:[e.jsx(pe,{className:"w-3.5 h-3.5 shrink-0 mt-0.5","aria-hidden":"true"}),e.jsxs("span",{children:["O motorista insere o código no app DriverCopilot â Configurações â Vincular à Frota. Após a solicitação, ela aparece na lista com status ",e.jsx("strong",{children:"Pendente"})," até você aprovar."]})]})]})]})}export{As as MotoristasList};
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.