PageSourceSearch

https://oticasvidereworkspace.lovable.app/assets/ManagerPortal-DsdYmTqX.js

js oticasvidereworkspace.lovable.app collected 2026-10-03 03:34:43 UTC 197,041 bytes, 42 lines download raw bytes

1import{c as Ct,r as l,s as w,j as e,B as nt,R as Dt,x as _a,T as Os,C as As,L as Be,H as ds,l as ms,P as ja,d as ge,I as ha,J as us,X as wt,b as Ia,w as fa,K as Ms,N as Bs,O as Ls,Q as Is,V as Ts,W as Us,Y as qs,Z as Ta,_ as Ps,y as ps,k as zt}from"./index-D4We9MQH.js";import{d as ea}from"./csvExport-DWrPlWew.js";import{A as xs}from"./activity-BV2kL4sv.js";import{D as kt}from"./download-nzmogrxb.js";import{F as gs}from"./file-text-BvtfosfW.js";import{D as hs}from"./dollar-sign-Qn2A4sfh.js";import{S as ta}from"./search-BFBC9axV.js";import{P as va}from"./plus-VmBq9j9n.js";import{d as na,F as oa}from"./prescriptionPdf-B-ERX6Rx.js";import{u as Ht,w as Rs,r as Vs}from"./xlsx-BBWTpfDg.js";import{C as Ua}from"./calendar-DhZrSjIz.js";import{P as qa,a as Pa,b as Ra}from"./popover-DiGt-FBF.js";import{U as zs}from"./upload-DQgdDzy5.js";import{M as Hs,H as Ws}from"./monitor-BvUUm0Vl.js";import{T as ba}from"./trash-2-D-2wB5p1.js";import{f as qe,d as Va}from"./format-NqOr7LIR.js";import{S as fs}from"./save-BFKRwwgm.js";import{F as Ks}from"./filter-CSPpaU0Q.js";import{p as Zs,e as za,a as Gs}from"./videreQuote-BmAqjG_B.js";import{g as Ys}from"./opto-videre-logo-2026.png.asset-DkN0duf0.js";import{T as Qs}from"./trophy-Dp6MTBHI.js";import{m as bs,a as ys,p as Ha}from"./pt-BR-CuJ_YFnV.js";import{L as _s}from"./log-in-MXD-j8dm.js";import"./endOfMonth-CJPWvX6h.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const js=Ct("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const vs=Ct("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
12 * @license lucide-react v0.462.0 - ISC
13 *
14 * This source code is licensed under the ISC license.
15 * See the LICENSE file in the root directory of this source tree.
16 */const Js=Ct("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/**
17 * @license lucide-react v0.462.0 - ISC
18 *
19 * This source code is licensed under the ISC license.
20 * See the LICENSE file in the root directory of this source tree.
21 */const Ut=Ct("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/**
22 * @license lucide-react v0.462.0 - ISC
23 *
24 * This source code is licensed under the ISC license.
25 * See the LICENSE file in the root directory of this source tree.
26 */const la=Ct("FileSpreadsheet",[["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 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/**
27 * @license lucide-react v0.462.0 - ISC
28 *
29 * This source code is licensed under the ISC license.
30 * See the LICENSE file in the root directory of this source tree.
31 */const Xs=Ct("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]);/**
32 * @license lucide-react v0.462.0 - ISC
33 *
34 * This source code is licensed under the ISC license.
35 * See the LICENSE file in the root directory of this source tree.
36 */const en=Ct("SquareKanban",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 7v7",key:"1x2jlm"}],["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M16 7v9",key:"1hp2iy"}]]);function pt(s,n){const c=nn(s);let g;if(c.date){const F=on(c.date,2);g=ln(F.restDateString,F.year)}if(!g||isNaN(g.getTime()))return new Date(NaN);const S=g.getTime();let N=0,L;if(c.time&&(N=rn(c.time),isNaN(N)))return new Date(NaN);if(c.timezone){if(L=cn(c.timezone),isNaN(L))return new Date(NaN)}else{const F=new Date(S+N),$=new Date(0);return $.setFullYear(F.getUTCFullYear(),F.getUTCMonth(),F.getUTCDate()),$.setHours(F.getUTCHours(),F.getUTCMinutes(),F.getUTCSeconds(),F.getUTCMilliseconds()),$}return new Date(S+N+L)}
36const Wt={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},tn=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,an=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,sn=/^([+-])(\d{2})(?::?(\d{2}))?$/;function nn(s){const n={},i=s.split(Wt.dateTimeDelimiter);let c;if(i.length>2)return n;if(/:/.test(i[0])?c=i[0]:(n.date=i[0],c=i[1],Wt.timeZoneDelimiter.test(n.date)&&(n.date=s.split(Wt.timeZoneDelimiter)[0],c=s.substr(n.date.length,s.length))),c){const g=Wt.timezone.exec(c);g?(n.time=c.replace(g[1],""),n.timezone=g[1]):n.time=c}return n}function on(s,n){const i=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+n)+"})|(\\d{2}|[+-]\\d{"+(2+n)+"})$)"),c=s.match(i);if(!c)return{year:NaN,restDateString:""};const g=c[1]?parseInt(c[1]):null,S=c[2]?parseInt(c[2]):null;return{year:S===null?g:S*100,restDateString:s.slice((c[1]||c[2]).length)}}function ln(s,n){if(n===null)return new Date(NaN);const i=s.match(tn);if(!i)return new Date(NaN);const c=!!i[4],g=Mt(i[1]),S=Mt(i[2])-1,N=Mt(i[3]),L=Mt(i[4]),F=Mt(i[5])-1;if(c)return xn(n,L,F)?dn(n,L,F):new Date(NaN);{const $=new Date(0);return!un(n,S,N)||!pn(n,g)?new Date(NaN):($.setUTCFullYear(n,S,Math.max(g,N)),$)}}function Mt(s){return s?parseInt(s):1}function rn(s){const n=s.match(an);if(!n)return NaN;const i=ra(n[1]),c=ra(n[2]),g=ra(n[3]);return gn(i,c,g)?i*bs+c*ys+g*1e3:NaN}function ra(s){return s&&parseFloat(s.replace(",","."))||0}function cn(s){if(s==="Z")return 0;const n=s.match(sn);if(!n)return 0;const i=n[1]==="+"?-1:1,c=parseInt(n[2]),g=n[3]&&parseInt(n[3])||0;return hn(c,g)?i*(c*bs+g*ys):NaN}function dn(s,n,i){const c=new Date(0);c.setUTCFullYear(s,0,4);const g=c.getUTCDay()||7,S=(n-1)*7+i+1-g;return c.setUTCDate(c.getUTCDate()+S),c}const mn=[31,null,31,30,31,30,31,31,30,31,30,31];function Ns(s){return s%400===0||s%4===0&&s%100!==0}function un(s,n,i){return n>=0&&n<=11&&i>=1&&i<=(mn[n]||(Ns(s)?29:28))}function pn(s,n){return n>=1&&n<=(Ns(s)?366:365)}function xn(s,n,i){return n>=1&&n<=53&&i>=0&&i<=6}function gn(s,n,i){return s===24?n===0&&i===0:i>=0&&i<60&&n>=0&&n<60&&s>=0&&s<25}function hn(s,n){return n>=0&&n<=59}const Wa=[{id:"today",label:"Hoje",days:0},{id:"7d",label:"7 dias",days:7},{id:"30d",label:"30 dias",days:30}],Ka={compareceu:{label:"Compareceu",Icon:ms},falta:{label:"Não compareceu",Icon:ds},venda:{label:"Venda",Icon:hs},os:{label:"OS",Icon:gs}},Bt=s=>{var n;return s.action==="venda"?"venda":s.action==="os"||s.action==="observacao"?"os":((n=s.metadata)==null?void 0:n.to)==="no_show"?"falta":"compareceu"},Kt=s=>new Date(s).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}),Za=s=>{const n=(s||"").replace(/\D/g,""),i=n.startsWith("55")?n.slice(2):n;return i.length===11?`(${i.slice(0,2)}) ${i.slice(2,7)}-${i.slice(7)}`:i.length===10?`(${i.slice(0,2)}) ${i.slice(2,6)}-${i.slice(6)}`:s},Zt=s=>{const n=s.comp+s.falta;return n?Math.round(s.comp/n*100):null},fn=()=>{var f;const[s,n]=l.useState("7d"),[i,c]=l.useState([]),[g,S]=l.useState([]),[N,L]=l.useState("all"),[F,$]=l.useState("all"),[V,O]=l.useState(!0),[Y,K]=l.useState({}),[ue,j]=l.useState({}),D=l.useMemo(()=>{var U;const d=new Date,_=((U=Wa.find(J=>J.id===s))==null?void 0:U.days)??7;return _===0?d.setHours(0,0,0,0):d.setDate(d.getDate()-_),d.toISOString()},[s]),z=l.useCallback(async()=>{O(!0);const[{data:d},{data:_}]=await Promise.all([w.from("manager_updates").select("id, action, title, detail, store_sigla, manager_email, manager_name, metadata, created_at, entity_id").gte("created_at",D).order("created_at",{ascending:!1}).limit(2e3),w.from("manager_profiles").select("store_sigla, store_name")]),U=d||[];c(U),S((_||[]).filter(ne=>ne.store_sigla&&ne.store_sigla!=="ALL").map(ne=>({sigla:ne.store_sigla,email:ne.store_name})));const J=[...new Set(U.map(ne=>ne.entity_id).filter(Boolean))];if(J.length){const ne=[],Me=[];for(let B=0;B<J.length;B+=200){const{data:ce}=await w.from("appointments").select("id, contact_id").in("id",J.slice(B,B+200));ce&&ne.push(...ce);const{data:Fe}=await w.from("contacts").select("id, phone_number").in("id",J.slice(B,B+200));Fe&&Me.push(...Fe)}const $e=[...new Set(ne.map(B=>
36B.contact_id).filter(Boolean))],we={};for(let B=0;B<$e.length;B+=200){const{data:ce}=await w.from("contacts").select("id, phone_number").in("id",$e.slice(B,B+200));(ce||[]).forEach(Fe=>{Fe.phone_number&&(we[Fe.id]=Fe.phone_number)})}const Ce={};ne.forEach(B=>{we[B.contact_id]&&(Ce[B.id]=we[B.contact_id])}),Me.forEach(B=>{B.phone_number&&(Ce[B.id]=B.phone_number)}),K(Ce);const me=[...new Set([...$e,...Me.map(B=>B.id)])],Se=[];for(let B=0;B<me.length;B+=200){const{data:ce}=await w.from("conversations").select("contact_id, assigned_user_id, last_message_at").in("contact_id",me.slice(B,B+200)).order("last_message_at",{ascending:!1});ce&&Se.push(...ce)}const R={};Se.forEach(B=>{!R[B.contact_id]&&B.assigned_user_id&&(R[B.contact_id]=B.assigned_user_id)});const Ve=[...new Set(Object.values(R))],Pe={};if(Ve.length){const{data:B}=await w.from("team_members").select("id, name").in("id",Ve);(B||[]).forEach(ce=>{Pe[ce.id]=ce.name})}const Ye={};ne.forEach(B=>{const ce=Pe[R[B.contact_id]];ce&&(Ye[B.id]=ce)}),Me.forEach(B=>{const ce=Pe[R[B.id]];ce&&(Ye[B.id]=ce)}),j(Ye)}else K({}),j({});O(!1)},[D]);l.useEffect(()=>{z()},[z]);const v=l.useMemo(()=>{const d={compareceu:0,falta:0,venda:0,os:0};return i.forEach(_=>{d[Bt(_)]+=1}),d},[i]),G=l.useMemo(()=>{const d=new Map;return g.forEach(_=>d.set(_.sigla,{sigla:_.sigla,total:0,comp:0,falta:0,venda:0,os:0,last:null,who:_.email||""}
36)),i.forEach(_=>{const U=_.store_sigla||"—";let J=d.get(U);J||(J={sigla:U,total:0,comp:0,falta:0,venda:0,os:0,last:null,who:""},d.set(U,J)),J.total+=1;const ne=Bt(_);ne==="compareceu"?J.comp++:ne==="falta"?J.falta++:ne==="venda"?J.venda++:J.os++,(!J.last||new Date(_.created_at)>new Date(J.last))&&(J.last=_.created_at,J.who=_.manager_email||_.manager_name||"")}),[...d.values()].sort((_,U)=>{const J=Zt(_)??-1,ne=Zt(U)??-1;return!_.last!=!U.last?_.last?1:-1:J!==ne?J-ne:U.falta-_.falta||_.sigla.localeCompare(U.sigla)})},[i,g]),p=l.useMemo(()=>i.filter(d=>(N==="all"||(d.store_sigla||"—")===N)&&(F==="all"||Bt(d)===F)),[i,N,F]),W=G.filter(d=>!d.last).length,P=G.filter(d=>d.comp+d.falta>=5&&(Zt(d)??100)<70).length,A=v.compareceu+v.falta?Math.round(v.compareceu/(v.compareceu+v.falta)*100):0,M=(f=i[0])!=null&&f.created_at?Kt(i[0].created_at):"Sem registros",ie=()=>ea(`supervisao_${s}.csv`,p.map(d=>({data:Kt(d.created_at),unidade:d.store_sigla||"",gerente:d.manager_email||d.manager_name||"",tipo:Ka[Bt(d)].label,registro:d.title,telefone:d.entity_id&&Y[d.entity_id]?Za(Y[d.entity_id]):"",consultor:d.entity_id&&ue[d.entity_id]||"",detalhe:d.detail||""})),";"),se=d=>{var _;L(d),(_=document.getElementById("supervision-records"))==null||_.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("section",{className:"overflow-hidden rounded-lg border border-border bg-card shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-4 border-b border-border px-4 py-4 lg:flex-row lg:items-center lg:justify-between lg:px-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-bold text-foreground",children:[e.jsx(xs,{className:"h-4 w-4 text-primary"}),"Central de Supervisão"]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Prioridades e desempenho das unidades no período."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"flex rounded-md bg-muted p-1",children:Wa.map(d=>e.jsx(nt,{type:"button",size:"sm",variant:s===d.id?"secondary":"ghost",onClick:()=>n(d.id),className:"h-8 px-4 text-xs",children:d.label},d.id))}),e.jsx(nt,{type:"button",size:"icon",variant:"outline",onClick:z,"aria-label":"Atualizar supervisão",children:e.jsx(Dt,{className:`h-4 w-4 ${V?"animate-spin":""}`})}),e.jsxs(nt,{type:"button",size:"sm",onClick:ie,className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Exportar"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-px bg-border lg:grid-cols-4",children:[e.jsxs("button",{type:"button",onClick:()=>{L("all"),$("all")},className:"bg-card p-4 text-left transition-colors hover:bg-muted/50",children:[e.jsx("p",{className:"text-[11px] font-bold uppercase text-destructive",children:"Sem atualização"}),e.jsx("p",{className:"mt-1 text-2xl font-bold text-foreground",children:W}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"unidades no período"})]}),e.jsxs("button",{type:"button",onClick:()=>$("falta"),className:"bg-card p-4 text-left transition-colors hover:bg-muted/50",children:[e.jsx("p",{className:"text-[11px] font-bold uppercase text-amber-600",children:"Faltas altas"}),e.jsx("p",{className:"mt-1 text-2xl font-bold text-foreground",children:P}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"abaixo de 70%"})]}),e.jsxs("button",{type:"button",onClick:()=>$("compareceu"),className:"bg-card p-4 text-left transition-colors hover:bg-muted/50",children:[e.jsx("p",{className:"text-[11px] font-bold uppercase text-primary",children:"Comparecimento"}),e.jsxs("p",{className:"mt-1 text-2xl font-bold text-foreground",children:[A,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.compareceu," de ",v.compareceu+v.falta," registros"]})]}),e.jsxs("button",{type:"button",onClick:()=>{L("all"),$("all")},className:"bg-card p-4 text-left transition-colors hover:bg-muted/50",children:[e.jsx("p",{className:"text-[11px] font-bold uppercase text-muted-foreground",children:"Atividade"}),e.jsx("p",{className:"mt-1 text-2xl font-bold text-foreground",children:i.length}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Última: ",M]})]})]})]}),e.jsxs("section",{className:"overflow-hidden rounded-lg border border-border bg-card shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3 lg:px-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-foreground",children:"Fila de atenção por unidade"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sem atualização e menor comparecimento aparecem primeiro."})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[G.length-W,"/",G.length," ativas"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[760px] text-left",children:[e.jsx("thead",{className:"border-b border-border bg-muted/50",children:e.jsxs("tr",{className:"text-[11px] font-bold uppercase text-muted-foreground",children:[e.jsx("th",{className:"px-4 py-3 lg:px-6",children:"Unidade"}),e.jsx("th",{className:"px-4 py-3 text-center",children:"Situação"}),e.jsx("th",{className:"px-4 py-3 text-center",children:"Comparecimento"}),e.jsx("th",{className:"px-4 py-3 text-center",children:"Faltas"}),e.jsx("th",{className:"px-4 py-3",children:"Última atividade"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Registros"})]})}),e.jsx("tbody",{className:"divide-y divide-border",children:G.map(d=>{const _=Zt(d),U=!d.last||_!==null&&d.comp+d.falta>=5&&_<70,J=!U&&_!==null&&_<80;return e.jsxs("tr",{className:U?"bg-destructive/5":"transition-colors hover:bg-muted/30",children:[e.jsxs("td",{className:"px-4 py-3 lg:px-6",children:[e.jsx("div",{className:"font-semibold text-foreground",children:d.sigla}),e.jsx("div",{className:"max-w-[220px] truncate text-xs text-muted-foreground",children:d.who||"Gerente não identificado"})]}),e.jsx("td",{className:"px-4 py-3 text-center",children:e.jsx("span",{className:`inline-flex rounded-full px-2.5 py-1 text-[10px] font-bold uppercase ${U?"bg-destructive/10 text-destructive":J?"bg-amber-100 text-amber-700":"bg-emerald-100 text-emerald-700"}`,children:d.last?U?"Atenção":J?"Acompanhar":"Atualizado":"Sem atualização"})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:`text-sm font-bold ${U?"text-destructive":J?"text-amber-700":"text-emerald-700"}`,children:_===null?"—":`${_}%`}),e.jsx("div",{className:"h-1.5 w-24 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:`h-full rounded-full ${U?"bg-destructive":J?"bg-amber-500":"bg-emerald-600"}`,style:{width:`${_??0}%`}})})]})}),e.jsx("td",{className:"px-4 py-3 text-center text-sm font-semibold text-foreground",children:d.falta}),e.jsx("td",{className:"px-4 py-3 text-xs text-muted-foreground",children:d.last?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_a,{className:"h-3.5 w-3.5"}),Kt(d.last)]}):e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(Os,{className:"h-3.5 w-3.5"}),"Nenhum registro"]})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs(nt,{type:"button",size:"sm",variant:"ghost",onClick:()=>se(d.sigla),className:"gap-1 text-primary",children:[d.total,e.jsx(As,{className:"h-3.5 w-3.5"})]})})]},d.sigla)})})]})})]}),e.jsxs("section",{id:"supervision-records",className:"scroll-mt-4 overflow-hidden rounded-lg border border-border bg-card shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3 lg:px-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-foreground",children:"Registros recentes"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.length," registros",N!=="all"?` de ${N}`:""]})]}),(N!=="all"||F!=="all")&&e.jsx(nt,{type:"button",size:"sm",variant:"ghost",onClick:()=>{L("all"),$("all")},children:"Limpar filtros"})]}),V?e.jsx("div",{className:"flex h-28 items-center justify-center",children:e.jsx(Be,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):p.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Nenhum registro no período."}):e.jsx("div",{className:"divide-y divide-border",children:p.slice(0,300).map(d=>{const _=Bt(d),U=Ka[_],J=d.entity_id?Y[d.entity_id]:null,ne=d.entity_id?ue[d.entity_id]:null,Me=_==="falta"?"bg-destructive/10 text-destructive":_==="compareceu"?"bg-emerald-100 text-emerald-700":_==="venda"?"bg-amber-100 text-amber-700":"bg-primary/10 text-primary";return e.jsxs("div",{className:"flex items-start gap-3 px-4 py-3 lg:px-6",children:[e.jsx("div",{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${Me}`,children:e.jsx(U.Icon,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:d.title}),d.detail&&e.jsx("div",{className:"text-xs text-muted-foreground",children:d.detail}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${Me}`,children:U.label}),e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5",children:d.store_sigla||"—"}),ne&&e.jsxs("span",{children:["Consultor: ",ne]}),J&&e.jsxs("a",{href:`https://wa.me/${J.replace(/\D/g,"")}`,target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 font-medium text-emerald-700",children:[e.jsx(ja,{className:"h-3 w-3"}),Za(J)]}),e.jsx("span",{children:d.manager_email||d.manager_name||"—"}),e.jsx("span",{children:Kt(d.created_at)})]})]})]},d.id)})})]})]})},Ga=s=>
36s.toLocaleString("pt-BR",{style:"currency",currency:"BRL",maximumFractionDigits:0}),bn=s=>s?Math.floor((Date.now()-new Date(s).getTime())/864e5):0,yn=({storeSigla:s,storeName:n,onNewAppointment:i})=>{const[c,g]=l.useState([]),[S,N]=l.useState([]),[L,F]=l.useState(!0),[$,V]=l.useState(!1),[O,Y]=l.useState(""),K=l.useMemo(()=>{const A=s.toUpperCase().startsWith("BIOPTO:")?s.slice(s.indexOf(":")+1):s;return A.toUpperCase()==="ALL"?[]:A.split("+").map(M=>M.trim().toUpperCase()).filter(Boolean)},[s]),ue=l.useCallback(async()=>{V(!0);try{const[{data:A},M]=await Promise.all([w.from("pipeline_stages").select("id, title, color, position").eq("is_active",!0).order("position"),(async()=>{let d=w.from("deals").select("id, title, value, stage_id, loja, created_at, stage_entered_at, contact_id").is("archived_at",null).order("stage_entered_at",{ascending:!1}).limit(600);return K.length===1?d=d.eq("loja",K[0]):K.length>1&&(d=d.in("loja",K)),d})()]);g((A==null?void 0:A.map(d=>({...d,color:d.color||"#94A3B8"})))||[]);const ie=M.data||[],se=Array.from(new Set(ie.map(d=>d.contact_id).filter(Boolean))),f=new Map;for(let d=0;d<se.length;d+=200){const{data:_}=await w.from("contacts").select("id, name, call_name, phone_number").in("id",se.slice(d,d+200));_==null||_.forEach(U=>f.set(U.id,{name:U.name||U.call_name,phone:U.phone_number}))}N(ie.map(d=>{var _,U;return{...d,contactName:d.contact_id?((_=f.get(d.contact_id))==null?void 0:_.name)??null:null,contactPhone:d.contact_id?((U=f.get(d.contact_id))==null?void 0:U.phone)??null:null}}))}finally{F(!1),V(!1)}},[K]);l.useEffect(()=>{ue()},[ue]);const[j,D]=l.useState(null),[z,v]=l.useState(null),[G,p]=l.useState(null),W=l.useCallback(async(A,M)=>{const ie=S,se=S.find(d=>d.id===A);if(!se||se.stage_id===M)return;N(d=>d.map(_=>_.id===A?{..._,stage_id:M,stage_entered_at:new Date().toISOString()}:_));const{error:f}=await w.from("deals").update({stage_id:M,stage_entered_at:new Date().toISOString()}).eq("id",A);f&&(N(ie),p("Não foi possível mover o card. Tente novamente."),setTimeout(()=>p(null),4e3))},[S]),P=l.useMemo(()=>{const A=O.trim().toLowerCase();return A?S.filter(M=>(M.contactName||"").toLowerCase().includes(A)||(M.title||"").toLowerCase().includes(A)||(M.contactPhone||"").includes(A.replace(/\D/g,""))):S},[S,O]);return L?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Be,{className:"w-6 h-6 animate-spin text-gray-400"})}):e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold",style:{color:"#101935"},children:"Funil de Vendas"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[K.length?`Unidade ${K.join(" + ")}`:"Todas as unidades"," · ",P.length," cards ativos"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ta,{className:"w-4 h-4 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2"}),e.jsx("input",{value:O,onChange:A=>Y(A.target.value),placeholder:"Buscar nome ou telefone",className:"pl-8 pr-3 py-2 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#E8530E]/30",style:{background:"#fff",color:"#101935",border:"1px solid #E2E8F0"}})]}),e.jsx("button",{onClick:ue,className:"p-2 rounded-lg text-gray-500 hover:text-[#101935]",style:{background:"#fff",border:"1px solid #E2E8F0"},title:"Atualizar",children:e.jsx(Dt,{className:`w-4 h-4 ${$?"animate-spin":""}`})}),i&&e.jsxs("button",{onClick:i,style:{background:"#E8530E"},className:"flex items-center gap-1.5 text-white text-sm font-semibold rounded-lg px-3.5 py-2",children:[e.jsx(va,{className:"w-4 h-4"})," Adicionar agendamento"]})]})]}),G&&e.jsx("div",{className:"text-xs font-semibold text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2",children:G}),e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-3",children:c.map(A=>{const M=P.filter(f=>f.stage_id===A.id),ie=M.reduce((f,d)=>f+Number(d.value||0),0),se=z===A.id;return e.jsxs("div",{onDragOver:f=>{f.preventDefault(),v(A.id)},onDragLeave:()=>v(f=>f===A.id?null:f),onDrop:f=>{f.preventDefault();const d=j||f.dataTransfer.getData("text/plain");v(null),D(null),d&&W(d,A.id)},className:"shrink-0 w-[260px] rounded-xl transition-colors",style:{background:se?"#FFF6F1":"#fff",border:`1px solid ${se?"#E8530E":"#F0F2F8"}`},children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5 border-b",style:{borderColor:"#F0F2F8"},children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0",style:{background:A.color}}),e.jsx("span",{className:"text-sm font-semibold truncate",style:{color:"#101935"},children:A.title})]}),e.jsx("span",{className:"text-[11px] font-semibold text-gray-500 bg-gray-100 rounded-full px-2 py-0.5",children:M.length})]}),ie>0&&e.jsx("div",{className:"px-3 pt-2 text-[11px] font-semibold text-emerald-600",children:Ga(ie)}),e.jsxs("div",{className:"p-2 flex flex-col gap-2 max-h-[62vh] overflow-y-auto",children:[M.length===0&&e.jsx("div",{className:"text-[11px] text-gray-400 text-center py-6",children:"Sem cards"}),M.map(f=>{const d=bn(f.stage_entered_at||f.created_at);return e.jsxs("div",{draggable:!0,onDragStart:_=>{D(f.id),_.dataTransfer.setData("text/plain",f.id),_.dataTransfer.effectAllowed="move"},onDragEnd:()=>{D(null),v(null)},className:`rounded-lg p-2.5 cursor-grab active:cursor-grabbing ${j===f.id?"opacity-50":""}`,style:{background:"#F8FAFC",border:"1px solid #EEF2F7"},children:[e.jsx("p",{className:"text-sm font-semibold truncate",style:{color:"#101935"},children:f.contactName||f.title||"Sem nome"}),f.contactPhone&&e.jsxs("p",{className:"text-[11px] text-gray-500 flex items-center gap-1 mt-0.5",children:[e.jsx(ja,{className:"w-3 h-3"})," ",f.contactPhone]}),e.jsxs("div",{className:"flex items-center justify-between mt-1.5",children:[f.loja&&e.jsx("span",{className:"text-[10px] font-semibold text-gray-500 bg-gray-200/70 rounded px-1.5 py-0.5",children:f.loja}),e.jsxs("span",{className:`text-[10px] flex items-center gap-1 ${d>3?"text-red-500 font-semibold":"text-gray-400"}`,children:[e.jsx(_a,{className:"w-3 h-3"})," ",d,"d"]})]}),Number(f.value||0)>0&&e.jsx("p",{className:"text-[11px] font-semibold text-emerald-600 mt-1",children:Ga(Number(f.value))})]},f.id)})]})]},A.id)})})]})},ia=["OV","OB","Bio Opto","Loja","Reativação","Outros"],ya=[{v:"comprou",label:"Comprou"},{v:"nao_comprou",label:"Não comprou"},{v:"reavaliacao",label:"Reavaliação"},{v:"patologia",label:"Patologia"},{v:"retorno",label:"Retorno"},{v:"encaminhamento",label:"Encaminhamento"}],ca=Object.fromEntries(ya.map(s=>[s.v,s.label])),da={comprou:{borderColor:"#047857",color:"#047857",background:"#ECFDF5"},nao_comprou:{borderColor:"#B91C1C",color:"#B91C1C",background:"#FEF2F2"},reavaliacao:{borderColor:"#1D4ED8",color:"#1D4ED8",background:"#EFF6FF"},patologia:{borderColor:"#B45309",color:"#B45309",background:"#FFFBEB"},retorno:{borderColor:"#7C3AED",color:"#7C3AED",background:"#F5F3FF"},encaminhamento:{borderColor:"#0F766E",color:"#0F766E",background:"#F0FDFA"}},st=s=>s.sale_type||(s.pathology?"patologia":s.purchased===!0?"comprou":s.purchased===!1?"nao_comprou":""),Ya=s=>
36({sale_type:s||null,pathology:s==="patologia",purchased:s==="comprou"?!0:s==="nao_comprou"?!1:null}),Lt=s=>{const n=parseInt(String(s??"").replace(/\D/g,""),10);return Number.isFinite(n)&&n>=0&&n<=120?n:null},It=(s,n,i)=>`${String(s||"").replace(/\s*ultima\s*a[./]?\s*v.*$/i,"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z ]/g," ").replace(/\s+/g," ")}|${String(n||"").replace(/\D/g,"")}|${i||""}`,ma=s=>(s==null?void 0:s.code)==="23505"||/duplicate key|eye_exams_unique_dedup_key/i.test((s==null?void 0:s.message)||""),Gt="Receita duplicada: esse cliente já tem uma receita cadastrada nessa data.",ws=s=>{const n=String(s||"").toUpperCase().startsWith("BIOPTO:")?s.slice(s.indexOf(":")+1):s;return String(n||"").split("+").map(i=>i.trim().toUpperCase()).filter(Boolean)},_n={SBC1:["SBC2"],SBC3:["SBC2"]},jn=s=>{const n=ws(s),i=n.flatMap(c=>_n[c]||[]);return Array.from(new Set([...n,...i]))},Qa=()=>new Date(new Date().toLocaleString("en-US",{timeZone:"America/Sao_Paulo"})).toISOString().slice(0,10),ua=s=>{const n=String(s||"").replace(/\D/g,"");return n.length===11?`(${n.slice(0,2)}) ${n.slice(2,7)}-${n.slice(7)}`:n.length===10?`(${n.slice(0,2)}) ${n.slice(2,6)}-${n.slice(6)}`:s||"—"},ve=(s,n=!0)=>{const i=String(s||"").trim().replace(",",".");if(!i)return"";const c=Number(i.replace("+",""));if(Number.isNaN(c))return i;const g=c.toFixed(2);return n&&c>0?`+${g}`:g},bt=(s,n,i)=>{if(!s&&!n&&!i)return"—";const c=[s||"0.00"];return n&&c.push(`${n}`),i&&c.push(`${i}°`),c.join(" / ")},vn=s=>{const n=String(s||"").trim();if(!n)return null;const i=n.match(/^(\d{1,2})[\/\-\.](\d{1,2})[\/\-\.](\d{4})$/);if(i){const[,g,S,N]=i,L=Number(g),F=Number(S),$=Number(N);return L<1||L>31||F<1||F>12||$<2e3?null:`${$}-${String(F).padStart(2,"0")}-${String(L).padStart(2,"0")}`}const c=n.match(/^(\d{4})[\/\-\.](\d{1,2})[\/\-\.](\d{1,2})$/);if(c){const[,g,S,N]=c,L=Number(N),F=Number(S),$=Number(g);return L<1||L>31||F<1||F>12||$<2e3?null:`${$}-${String(F).padStart(2,"0")}-${String(L).padStart(2,"0")}`}return null},Nn=s=>{const n=String(s||"").replace(/\D/g,"");return n.length===13&&n.startsWith("55")?n.slice(2):n},wn={data:["data","data_exame","data do exame","dt"],unidade:["unidade","unit","sigla","loja","store"],cliente:["cliente","paciente","nome","nome do cliente","patient_name"],telefone:["telefone","fone","celular","whatsapp","patient_phone"],optometrista:["optometrista","optometrista_name","optometrista name","profissional"],od_longe_esf:["od_longe_esf","od_esf","od esferico","od esférico","od_longe_esferico","od sphere","od longe esf"],od_longe_cil:["od_longe_cil","od_cil","od cilindrico","od cilíndrico","od longe cil"],od_longe_eixo:["od_longe_eixo","od_eixo","od eixo","od longe eixo","od axis"],oe_longe_esf:["oe_longe_esf","oe_esf","oe esferico","oe esférico","oe_longe_esferico","oe sphere","oe longe esf"],oe_longe_cil:["oe_longe_cil","oe_cil","oe cilindrico","oe cilíndrico","oe longe cil"],oe_longe_eixo:["oe_longe_eixo","oe_eixo","oe eixo","oe longe eixo","oe axis"],od_perto_esf:["od_perto_esf","od_perto_esferico","od perto esf","od perto esferico"],od_perto_cil:["od_perto_cil","od_perto_cilindrico","od perto cil"],od_perto_eixo:["od_perto_eixo","od_perto_eixo2","od perto eixo"],oe_perto_esf:["oe_perto_esf","oe_perto_esferico","oe perto esf"],oe_perto_cil:["oe_perto_cil","oe_perto_cilindrico","oe perto cil"],oe_perto_eixo:["oe_perto_eixo","oe perto eixo"],adicao:["adicao","adição","add"],observacao:["observacao","observação","obs","notas","notes"],fonte:["fonte","origem","source"]},Ja=s=>{const n=String(s||"").trim().toLowerCase().replace(/[_.\s]+/g,"_");for(const[i,c]of Object.entries(wn))if(c.includes(n)||i===n)return i;return n},be="w-full px-3 py-3 sm:px-2.5 sm:py-2 rounded-xl sm:rounded-lg border text-base sm:text-sm outline-none focus:border-[#E8530E]",ye={borderColor:"#E5E7EB",background:"#fff",color:"#101935"},De="text-[11px] font-semibold uppercase tracking-wide text-gray-500 mb-1 block",Ke="w-full min-w-0 px-1.5 py-1 rounded-md border text-[11px] outline-none focus:border-[#E8530E]",Ze={borderColor:"#E5E7EB",color:"#101935",background:"#fff"},Xa=({profile:s,view:n})=>{const i=l.useMemo(()=>ws(s.store_sigla),[s.store_sigla]),c=l.useMemo(()=>jn(s.store_sigla),[s.store_sigla]),g=c.includes("ALL"),S=["opto","optometrista"].includes(String(s.role||"").toLowerCase()),N=n??(S?"form":"full"),L=N==="form",F=N!=="form",$=N==="full"&&!S,[V,O]=l.useState([]),[Y,K]=l.useState(!0),[ue,j]=l.useState(!1),[D,z]=l.useState(!1),[v,G]=l.useState(""),[p,W]=l.useState("todas"),[P,A]=l.useState("todas"),[M,ie]=l.useState([]),[se,f]=l.useState(null),d=l.useRef(null),[_,U]=l.useState(null),[J,ne]=l.useState([]),[Me,$e]=l.useState(!1),[we,Ce]=l.useState(!1),me=F,Se=S,[R,Ve]=l.useState(null),[Pe,Ye]=l.useState(!1),B=(t,h)=>Ve(b=>b&&{...b,[t]:h}),[ce,Fe]=l.useState("planilha"),[_e,Ge]=l.useState(null),ke=l.useRef([]),et=l.useRef({}),Te=async(t,h)=>{var b;Ge(t.id);try{const{data:y}=await w.auth.getUser(),k=Oe=>String(Oe??"").trim()||null,oe={patient_name:String(t.patient_name||"").trim(),patient_phone:String(t.patient_phone||"").replace(/\D/g,"")||null,exam_date:t.exam_date,store_sigla:String(t.store_sigla||"").toUpperCase(),optometrist_name:k(t.optometrist_name),od_acuity:k(t.od_acuity),oe_acuity:k(t.oe_acuity),os_number:k(t.os_number),patient_age:Lt(t.patient_age),...Ya(st(t)),observations:k(t.observations),source:k(t.source),purchase_updated_at:new Date().toISOString(),purchase_updated_by_email:((b=y.user)==null?void 0:b.email)||null};Se&&(oe.od_sphere=k(t.od_sphere),oe.od_cylinder=k(t.od_cylinder),oe.od_axis=k(t.od_axis),oe.oe_sphere=k(t.oe_sphere),oe.oe_cylinder=k(t.oe_cylinder),oe.oe_axis=k(t.oe_axis),oe.addition=k(t.addition));const{error:q}=await w.from("eye_exams").update(oe).eq("id",t.id);if(q){ge.error("Não foi possível salvar. Só o gerente da unidade pode editar.");return}h!=null&&h.silent}finally{Ge(null)}},rt=l.useCallback(t=>{const h=et.current;h[t]&&clearTimeout(h[t]),h[t]=setTimeout(()=>{delete h[t];const b=ke.current.find(y=>y.id===t);b&&Te(b,{silent:!0})},1200)},[Se]);l.useEffect(()=>{const t=et.current;return()=>{Object.values(t).forEach(clearTimeout)}},[]);const je=(t,h,b)=>{O(y=>{const k=y.map(oe=>oe.id===t?{...oe,[h]:b}:oe);return ke.current=k,k}),rt(t)};l.useEffect(()=>{ke.current=V},[V]);const it=l.useMemo(()=>({store_sigla:i.length===1&&!g?i[0]:"",patient_name:"",patient_phone:"",patient_age:"",exam_date:Qa(),optometrist_name:"",od_sphere:"",od_cylinder:"",od_axis:"",oe_sphere:"",oe_cylinder:"",oe_axis:"",od_near_sphere:"",od_near_cylinder:"",od_near_axis:"",oe_near_sphere:"",oe_near_cylinder:"",oe_near_axis:"",addition:"",od_acuity:"",oe_acuity:"",observations:"",source:""}),[i,g]),[ae,ot]=l.useState(it),Le=(t,h)=>ot(b=>({...b,[t]:h})),Ue=l.useCallback(async()=>
36{if(!F){O([]),K(!1);return}K(!0);const t=1e3,h=[];for(let b=0;b<2e4;b+=t){let y=w.from("eye_exams").select("*").order("exam_date",{ascending:!1}).order("created_at",{ascending:!1}).range(b,b+t-1);g||(y=y.in("store_sigla",c));const{data:k,error:oe}=await y;if(oe){ge.error("Não foi possível carregar as receitas.");break}const q=k||[];if(h.push(...q),q.length<t)break}O(h),K(!1)},[c,g,F]);l.useEffect(()=>{Ue()},[Ue]),l.useEffect(()=>{w.auth.getUser().then(({data:t})=>{var h;return f(((h=t.user)==null?void 0:h.id)||null)}),w.from("stores").select("sigla, name").eq("is_active",!0).order("sigla").then(({data:t})=>ie(t||[]))},[]);const ze=l.useMemo(()=>g?M.map(t=>({sigla:t.sigla.toUpperCase(),name:t.name})):c.map(t=>{var h;return{sigla:t,name:((h=M.find(b=>b.sigla.toUpperCase()===t))==null?void 0:h.name)||t}}),[g,M,c]),$t=l.useMemo(()=>{const t=new Map;return V.forEach(h=>{const b=String(h.source||"").trim()||"Sem fonte";t.set(b,(t.get(b)||0)+1)}),[...t.entries()].sort((h,b)=>h[0].localeCompare(b[0],"pt-BR"))},[V]),[Qe,xt]=l.useState("mes"),[He,We]=l.useState(""),[Ie,jt]=l.useState(""),ct=t=>t?new Date(`${t}T12:00:00`):void 0,Et=t=>t?qe(t,"yyyy-MM-dd"):"",gt=l.useMemo(()=>{if(Qe==="todos")return null;if(Qe==="periodo")return He&&Ie?{start:He,end:Ie}:null;const t=new Date,h=k=>`${k.getFullYear()}-${String(k.getMonth()+1).padStart(2,"0")}-${String(k.getDate()).padStart(2,"0")}`,b=h(t);if(Qe==="hoje")return{start:b,end:b};if(Qe==="mes")return{start:h(new Date(t.getFullYear(),t.getMonth(),1)),end:b};const y=(t.getDay()+6)%7;return{start:h(new Date(t.getFullYear(),t.getMonth(),t.getDate()-y)),end:b}},[Qe,He,Ie]),Ee=l.useMemo(()=>{const t=v.trim().toLowerCase();return V.filter(h=>gt&&(h.exam_date<gt.start||h.exam_date>gt.end)||p!=="todas"&&h.store_sigla.toUpperCase()!==p||P!=="todas"&&(String(h.source||"").trim()||"Sem fonte")!==P?!1:t?`${h.patient_name} ${h.patient_phone||""} ${h.optometrist_name||""}`.toLowerCase().includes(t):!0)},[V,v,p,P,gt]),[ht,Ot]=l.useState(new Set);l.useEffect(()=>{w.from("stores").select("sigla, store_type").then(({data:t})=>{Ot(new Set((t||[]).filter(h=>h.store_type==="franquia"&&h.sigla).map(h=>String(h.sigla).toUpperCase())))})},[]);const a=l.useCallback(t=>!ht.has(String(t.store_sigla||"").toUpperCase()),[ht]),C=l.useCallback(t=>{const h=t.filter(a),b=h.filter(y=>y.purchased===!0||y.purchased===!1).length;return b>0?Math.round(h.filter(y=>y.purchased===!0).length/b*100):0},[a]),X=l.useMemo(()=>{const t=Ee.length,h=Ee.filter(de=>de.purchased===!0).length,b=Ee.filter(de=>de.purchased===!1).length,y=Ee.filter(de=>de.pathology).length,k=Ee.filter(de=>!st(de)).length,oe=Ee.filter(de=>String(de.os_number||"").trim()).length,q=new Set(Ee.map(de=>String(de.store_sigla||"").toUpperCase())).size,Oe=C(Ee),re=new Date,Ae=de=>`${de.getFullYear()}-${String(de.getMonth()+1).padStart(2,"0")}-${String(de.getDate()).padStart(2,"0")}`,pe=Ae(re),Ne=Ae(new Date(re.getFullYear(),re.getMonth(),re.getDate()-(re.getDay()+6)%7)),at=Ae(new Date(re.getFullYear(),re.getMonth(),1)),Je=v.trim().toLowerCase(),Xe=V.filter(de=>p!=="todas"&&de.store_sigla.toUpperCase()!==p||P!=="todas"&&(String(de.source||"").trim()||"Sem fonte")!==P?!1:!Je||`${de.patient_name} ${de.patient_phone||""} ${de.optometrist_name||""}`.toLowerCase().includes(Je)),qt=C(Xe.filter(de=>de.exam_date===pe)),aa=C(Xe.filter(de=>de.exam_date>=Ne&&de.exam_date<=pe)),Pt=C(Xe.filter(de=>de.exam_date>=at&&de.exam_date<=pe)),Nt=new Map;Ee.forEach(de=>{const dt=String(de.source||"").trim()||"Sem fonte";Nt.set(dt,(Nt.get(dt)||0)+1)});const Rt=[...Nt.entries()].sort((de,dt)=>dt[1]-de[1]).slice(0,4);return{total:t,comprou:h,naoComprou:b,patologias:y,semInfo:k,comOs:oe,unidades:q,conv:Oe,convDia:qt,convSemana:aa,convMes:Pt,fontes:Rt}},[Ee,V,v,p,P,C]),Q=200,[H,ee]=l.useState(1);l.useEffect(()=>{ee(1)},[v,p,P,ce,Qe,He,Ie]);const o=Math.max(1,Math.ceil(Ee.length/Q)),r=l.useMemo(()=>Ee.slice((H-1)*Q,H*Q),[Ee,H]),u=async t=>{var h,b;if(t.preventDefault(),!ae.patient_name.trim()){ge.error("Informe o nome do cliente.");return}if(!ae.store_sigla){ge.error("Selecione a unidade.");return}z(!0);try{const{data:y}=await w.auth.getUser(),k={...ae,store_sigla:ae.store_sigla.toUpperCase(),patient_name:ae.patient_name.trim(),patient_phone:ae.patient_phone.replace(/\D/g,"")||null,patient_age:Lt(ae.patient_age),od_sphere:ve(ae.od_sphere),od_cylinder:ve(ae.od_cylinder,!1),oe_sphere:ve(ae.oe_sphere),oe_cylinder:ve(ae.oe_cylinder,!1),od_near_sphere:ve(ae.od_near_sphere),od_near_cylinder:ve(ae.od_near_cylinder,!1),oe_near_sphere:ve(ae.oe_near_sphere),oe_near_cylinder:ve(ae.oe_near_cylinder,!1),addition:ve(ae.addition),od_acuity:String(ae.od_acuity||"").trim()||null,oe_acuity:String(ae.oe_acuity||"").trim()||null,source:String(ae.source||"").trim()||null,created_by:((h=y.user)==null?void 0:h.id)||null,created_by_email:((b=y.user)==null?void 0:b.email)||null},oe=It(k.patient_name,k.patient_phone,k.exam_date),{data:q}=await w.from("eye_exams").select("id, patient_name, patient_phone, exam_date").eq("exam_date",k.exam_date).limit(500);if((q||[]).some(re=>It(re.patient_name,re.patient_phone,re.exam_date)===oe)){ge.error(Gt);return}const{error:Oe}=await w.from("eye_exams").insert(k);if(Oe){ge.error(ma(Oe)?Gt:Oe.message);return}ge.success("Receita registrada!"),ot({...it}),L||(j(!1),Ue())}finally{z(!1)}},I=async()=>{var t;if(R){if(!String(R.patient_name||"").trim()){ge.error("Informe o nome do cliente.");return}Ye(!0);try{const{data:h}=await w.auth.getUser(),b={patient_name:String(R.patient_name).trim(),patient_phone:String(R.patient_phone||"").replace(/\D/g,"")||null,exam_date:R.exam_date,optometrist_name:R.optometrist_name||null,od_acuity:String(R.od_acuity||"").trim()||null,oe_acuity:String(R.oe_acuity||"").trim()||null,observations:R.observations||null,source:String(R.source||"").trim()||null,os_number:String(R.os_number||"").trim()||null,patient_age:Lt(R.patient_age),...Ya(st(R)),purchase_updated_at:new Date().toISOString(),purchase_updated_by_email:((t=h.user)==null?void 0:t.email)||null};Se&&(b.od_sphere=ve(R.od_sphere||""),b.od_cylinder=ve(R.od_cylinder||"",!1),b.od_axis=R.od_axis||null,b.oe_sphere=ve(R.oe_sphere||""),b.oe_cylinder=ve(R.oe_cylinder||"",!1),b.oe_axis=R.oe_axis||null,b.od_near_sphere=ve(R.od_near_sphere||""),b.od_near_cylinder=ve(R.od_near_cylinder||"",!1),b.od_near_axis=R.od_near_axis||null,b.oe_near_sphere=ve(R.oe_near_sphere||""),b.oe_near_cylinder=ve(R.oe_near_cylinder||"",!1),b.oe_near_axis=R.oe_near_axis||null,b.addition=ve(R.addition||""));const{error:y}=await w.from("eye_exams").update(b).eq("id",R.id);if(y){ge.error(ma(y)?Gt:"Não foi possível salvar. Só o gerente da unidade pode editar.");return}ge.success("Receita atualizada!"),Ve(null),Ue()}finally{Ye(!1)}}},x=async t=>{if(!confirm(`Apagar a receita de ${t.patient_name}?`))return;const{data:h,error:b}=await w.from("eye_exams").delete().eq("id",t.id).select("id");if(b||!(h!=null&&h.length)){ge.error("Sem permissão para apagar esta receita.");return}ge.success("Receita apagada."),Ue()},he=()=>{const t=[{data:"05/09/2026",unidade:"VC1",cliente:"Maria Silva",telefone:"11990000000",optometrista:"Dra. Ana",od_longe_esf:"-1.50",od_longe_cil:"-0.75",od_longe_eixo:"180",oe_longe_esf:"-1.25",oe_longe_cil:"-0.50",oe_longe_eixo:"90",od_perto_esf:"",od_perto_cil:"",od_perto_eixo:"",oe_perto_esf:"",oe_perto_cil:"",oe_perto_eixo:"",adicao:"+2.00",observacao:"Armação preferida metal",fonte:"Loja"}],h=Ht.json_to_sheet(t),b=Ht.book_new();Ht.book_append_sheet(b,h,"Modelo"),Rs(b,"modelo_importacao_receitas.xlsx")},fe=async t=>{U(null),ne([]);const h=t.name.toLowerCase().endsWith(".csv")||t.type==="text/csv",b=h?await t.text():"";let y=[];
36if(h){const q=b.split(/\r?\n/).filter(Boolean);if(!q.length){ne(["Arquivo vazio"]);return}const Oe=q[0].includes(";")?";":",",Ae=q[0].split(Oe).map(pe=>pe.trim().replace(/^["']|["']$/g,"")).map(Ja);y=q.slice(1).map(pe=>{const Ne=[];if(Oe===";")pe.split(";").forEach(Je=>Ne.push(Je.replace(/^["']|["']$/g,"")));else{const Je=/(?:,|\n|^)("(?:(?:"")*[^"]*)*"|[^",\n]*)/g;let Xe;for(;(Xe=Je.exec(pe))!==null;)Xe.index===Je.lastIndex&&Je.lastIndex++,Ne.push(Xe[1]?Xe[1].replace(/^"|"$/g,"").replace(/""/g,'"'):Xe[1])}const at={};return Ae.forEach((Je,Xe)=>{at[Je]=(Ne[Xe]||"").trim()}),at})}else{let q;try{const re=await t.arrayBuffer(),Ae=Vs(re,{type:"array"}),pe=Ae.Sheets[Ae.SheetNames[0]];q=Ht.sheet_to_json(pe,{header:1,defval:""})}catch(re){ne([`Não foi possível ler a planilha: ${(re==null?void 0:re.message)||"arquivo inválido"}`]);return}if(!q.length){ne(["Planilha vazia"]);return}const Oe=q[0].map(re=>Ja(String(re||"")));y=q.slice(1).map(re=>{const Ae={};return Oe.forEach((pe,Ne)=>{Ae[pe]=String(re[Ne]||"").trim()}),Ae})}const k=[],oe=y.map((q,Oe)=>{const re=Oe+2,Ae=vn(q.data);Ae||k.push(`Linha ${re}: data inválida (use dd/mm/aaaa)`);const pe=String(q.unidade||"").toUpperCase();pe?!g&&!c.includes(pe)&&k.push(`Linha ${re}: unidade ${pe} fora do seu escopo`):k.push(`Linha ${re}: unidade obrigatória`);const Ne=String(q.cliente||"").trim();return Ne||k.push(`Linha ${re}: nome do cliente obrigatório`),{store_sigla:pe,patient_name:Ne,patient_phone:Nn(q.telefone)||null,exam_date:Ae||Qa(),optometrist_name:String(q.optometrista||"").trim()||null,od_sphere:ve(q.od_longe_esf),od_cylinder:ve(q.od_longe_cil,!1),od_axis:String(q.od_longe_eixo||"").trim()||null,oe_sphere:ve(q.oe_longe_esf),oe_cylinder:ve(q.oe_longe_cil,!1),oe_axis:String(q.oe_longe_eixo||"").trim()||null,od_near_sphere:ve(q.od_perto_esf),od_near_cylinder:ve(q.od_perto_cil,!1),od_near_axis:String(q.od_perto_eixo||"").trim()||null,oe_near_sphere:ve(q.oe_perto_esf),oe_near_cylinder:ve(q.oe_perto_cil,!1),oe_near_axis:String(q.oe_perto_eixo||"").trim()||null,addition:ve(q.adicao),observations:String(q.observacao||"").trim()||null,source:String(q.fonte||"").trim()||null}});if(k.length){ne(k),U(null);return}U(oe)},tt=async()=>{if(!(!_||!_.length)){$e(!0);try{const{data:t}=await w.auth.getUser(),h=new Set;let b=0;const y=_.filter(pe=>{const Ne=It(pe.patient_name,pe.patient_phone,pe.exam_date);return h.has(Ne)?(b++,!1):(h.add(Ne),!0)}),k=Array.from(new Set(y.map(pe=>pe.exam_date).filter(Boolean))),oe=new Set;if(k.length){const{data:pe}=await w.from("eye_exams").select("patient_name, patient_phone, exam_date").in("exam_date",k).limit(5e3);(pe||[]).forEach(Ne=>oe.add(It(Ne.patient_name,Ne.patient_phone,Ne.exam_date)))}let q=0;const Oe=y.filter(pe=>{const Ne=It(pe.patient_name,pe.patient_phone,pe.exam_date);return oe.has(Ne)?(q++,!1):!0}).map(pe=>{var Ne,at;return{...pe,created_by:((Ne=t.user)==null?void 0:Ne.id)||null,created_by_email:((at=t.user)==null?void 0:at.email)||null}}),re=b+q;if(!Oe.length){ge.error(`Nenhuma receita nova: ${re} duplicada(s) ignorada(s).`);return}const{error:Ae}=await w.from("eye_exams").insert(Oe);if(Ae){ge.error(ma(Ae)?Gt:Ae.message);return}ge.success(re?`${Oe.length} receita(s) importada(s) · ${re} duplicada(s) ignorada(s).`:`${Oe.length} receita(s) importada(s)!`),U(null),ne([]),d.current&&(d.current.value=""),Ue()}finally{$e(!1)}}},lt=()=>{ea(`receitas_${s.store_sigla}.csv`,Ee.map(t=>({data:t.exam_date.split("-").reverse().join("/"),unidade:t.store_sigla,cliente:t.patient_name,idade:t.patient_age??"",telefone:t.patient_phone||"",optometrista:t.optometrist_name||"",fonte:t.source||"",od_longe:bt(t.od_sphere,t.od_cylinder,t.od_axis),oe_longe:bt(t.oe_sphere,t.oe_cylinder,t.oe_axis),od_perto:bt(t.od_near_sphere,t.od_near_cylinder,t.od_near_axis),oe_perto:bt(t.oe_near_sphere,t.oe_near_cylinder,t.oe_near_axis),adicao:t.addition||"",venda:ca[st(t)]||"",os:t.os_number||"",observacao:t.observations||""})))},vt=(t,h)=>{const b=h?`${t}_near`:t,y=t==="od"?"OD":"OE";return e.jsxs("div",{className:"grid grid-cols-[52px_1fr_1fr_1fr] sm:grid-cols-[110px_1fr_1fr_1fr] gap-1.5 sm:gap-2 items-center",children:[e.jsx("span",{className:"text-[11px] sm:text-xs font-bold",style:{color:"#101935"},children:y}),e.jsx("input",{className:be,style:ye,inputMode:"text",placeholder:"Esf.",value:ae[`${b}_sphere`],onChange:k=>Le(`${b}_sphere`,k.target.value)}),e.jsx("input",{className:be,style:ye,inputMode:"text",placeholder:"Cil.",value:ae[`${b}_cylinder`],onChange:k=>Le(`${b}_cylinder`,k.target.value)}),e.jsx("input",{className:be,style:ye,inputMode:"text",placeholder:"Eixo",value:ae[`${b}_axis`],onChange:k=>Le(`${b}_axis`,k.target.value)})]})};return e.jsxs("div",{className:`space-y-4 ${we?"max-w-[430px] mx-auto w-full":""}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-lg font-bold flex items-center gap-2",style:{color:"#101935"},children:[e.jsx(ha,{className:"w-5 h-5 text-[#E8530E]"}),N==="form"?"Inserir receita":N==="history"?"Histórico de receitas":"Receitas / Exames"]}),e.jsx("p",{className:"text-xs text-gray-500",children:N==="form"?`${g?"Todas as unidades":c.join(" · ")}
36 · preencha os dados do exame`:`${g?"Todas as unidades":c.join(" · ")} · ${Ee.length} registro${Ee.length!==1?"s":""}`})]}),N==="history"&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("button",{onClick:()=>Fe(t=>t==="planilha"?"cards":"planilha"),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium border hover:bg-gray-50",style:{borderColor:ce==="planilha"?"#E8530E":"#E5E7EB",background:ce==="planilha"?"#FFF1E8":"#fff",color:ce==="planilha"?"#E8530E":"#4B5563"},children:[e.jsx(la,{className:"w-4 h-4"}),ce==="planilha"?"Ver em cartões":"Ver em planilha"]}),e.jsxs("button",{onClick:lt,className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium border text-gray-600 hover:bg-gray-50",style:{borderColor:"#E5E7EB",background:"#fff"},children:[e.jsx(kt,{className:"w-4 h-4"}),"CSV"]})]}),$&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("button",{onClick:he,className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium border text-gray-600 hover:bg-gray-50",style:{borderColor:"#E5E7EB",background:"#fff"},children:[e.jsx(la,{className:"w-4 h-4"}),"Modelo"]}),e.jsxs("button",{onClick:()=>{var t;return(t=d.current)==null?void 0:t.click()},className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium border text-gray-600 hover:bg-gray-50",style:{borderColor:"#E5E7EB",background:"#fff"},children:[e.jsx(zs,{className:"w-4 h-4"}),"Importar"]}),e.jsx("input",{ref:d,type:"file",accept:".csv,.xlsx,.xls",className:"hidden",onChange:t=>{var b;const h=(b=t.target.files)==null?void 0:b[0];h&&fe(h).catch(y=>ne([`Falha ao ler o arquivo: ${(y==null?void 0:y.message)||"erro desconhecido"}`])),t.target.value=""}}),e.jsxs("button",{onClick:lt,className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium border text-gray-600 hover:bg-gray-50",style:{borderColor:"#E5E7EB",background:"#fff"},children:[e.jsx(kt,{className:"w-4 h-4"}),"CSV"]}),e.jsxs("button",{onClick:()=>Fe(t=>t==="planilha"?"cards":"planilha"),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium border hover:bg-gray-50",style:{borderColor:ce==="planilha"?"#E8530E":"#E5E7EB",background:ce==="planilha"?"#FFF1E8":"#fff",color:ce==="planilha"?"#E8530E":"#4B5563"},children:[e.jsx(la,{className:"w-4 h-4"}),ce==="planilha"?"Ver em cartões":"Ver em planilha"]}),e.jsxs("button",{onClick:()=>Ce(t=>!t),title:we?"Ver como computador":"Ver como celular",className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium border hover:bg-gray-50",style:{borderColor:we?"#E8530E":"#E5E7EB",background:we?"#FFF1E8":"#fff",color:we?"#E8530E":"#4B5563"},children:[we?e.jsx(Hs,{className:"w-4 h-4"}):e.jsx(us,{className:"w-4 h-4"}),we?"Ver computador":"Ver celular"]}),e.jsxs("button",{onClick:()=>j(t=>!t),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-semibold text-white bg-[#E8530E] hover:opacity-90",children:[ue?e.jsx(wt,{className:"w-4 h-4"}):e.jsx(va,{className:"w-4 h-4"}),ue?"Fechar":"Nova receita"]})]})]}),(_||J.length>0)&&$&&e.jsxs("div",{className:"rounded-2xl p-4 sm:p-5 space-y-4",style:{background:"#fff",border:"1px solid #F0F2F8"},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-bold",style:{color:"#101935"},children:J.length>0?"Erros na planilha":`Importar ${_==null?void 0:_.length} receita(s)`}),e.jsxs("button",{onClick:()=>{U(null),ne([]),d.current&&(d.current.value="")},className:"text-xs text-gray-500 hover:text-gray-700 flex items-center gap-1",children:[e.jsx(wt,{className:"w-3 h-3"}),"Limpar"]})]}),J.length>0&&e.jsx("div",{className:"rounded-xl p-3 text-xs space-y-1 max-h-60 overflow-auto",style:{background:"#FEF2F2",color:"#991B1B"},children:J.map((t,h)=>e.jsxs("div",{children:["• ",t]},h))}),_&&_.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overflow-auto max-h-60 rounded-xl border",style:{borderColor:"#E5E7EB"},children:[e.jsxs("table",{className:"min-w-full text-xs",children:[e.jsx("thead",{className:"bg-gray-50 sticky top-0",children:e.jsx("tr",{children:["data","unidade","cliente","telefone","optometrista","od_longe","oe_longe","adicao"].map(t=>e.jsx("th",{className:"px-3 py-2 text-left font-semibold text-gray-600 uppercase",children:t},t))})}),e.jsx("tbody",{children:_.slice(0,50).map((t,h)=>e.jsxs("tr",{className:"border-t",style:{borderColor:"#F3F4F6"},children:[e.jsx("td",{className:"px-3 py-2",children:String(t.exam_date).split("-").reverse().join("/")}),e.jsx("td",{className:"px-3 py-2",children:t.store_sigla}),e.jsx("td",{className:"px-3 py-2",children:t.patient_name}),e.jsx("td",{className:"px-3 py-2",children:ua(t.patient_phone)}),e.jsx("td",{className:"px-3 py-2",children:t.optometrist_name||"—"}),e.jsx("td",{className:"px-3 py-2",children:bt(t.od_sphere,t.od_cylinder,t.od_axis)}),e.jsx("td",{className:"px-3 py-2",children:bt(t.oe_sphere,t.oe_cylinder,t.oe_axis)}),e.jsx("td",{className:"px-3 py-2",children:t.addition||"—"})]},h))})]}),_.length>50&&e.jsxs("div",{className:"px-3 py-2 text-xs text-gray-500 bg-gray-50",children:["...e mais ",_.length-50," linhas"]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{onClick:()=>{U(null),ne([]),d.current&&(d.current.value="")},className:"px-4 py-2 rounded-lg text-sm border text-gray-600",style:{borderColor:"#E5E7EB"},children:"Cancelar"}),e.jsxs("button",{onClick:tt,disabled:Me,className:"flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-semibold text-white bg-[#E8530E] disabled:opacity-60",children:[Me&&e.jsx(Be,{className:"w-4 h-4 animate-spin"}),"Confirmar importação"]})]})]})]}),(N==="form"||N==="full"&&ue)&&e.jsxs("form",{onSubmit:u,className:"rounded-2xl p-4 sm:p-5 space-y-5",style:{background:"#fff",border:"1px solid #F0F2F8"},children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("label",{className:De,children:"Nome do cliente *"}),e.jsx("input",{className:be,style:ye,value:ae.patient_name,onChange:t=>Le("patient_name",t.target.value),placeholder:"Nome completo"})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Idade"}),e.jsx("input",{className:be,style:ye,inputMode:"numeric",value:ae.patient_age,onChange:t=>Le("patient_age",t.target.value.replace(/\D/g,"").slice(0,3)),placeholder:"Ex.: 58"})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Telefone"}),e.jsx("input",{className:be,style:ye,inputMode:"tel",value:ae.patient_phone,onChange:t=>Le("patient_phone",t.target.value),placeholder:"(11) 90000-0000"})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Data do exame"}),e.jsx("input",{type:"date",className:be,style:ye,value:ae.exam_date,onChange:t=>Le("exam_date",t.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Unidade *"}),e.jsxs("select",{className:be,style:ye,value:ae.store_sigla,onChange:t=>Le("store_sigla",t.target.value),children:[e.jsx("option",{value:"",children:"Selecione"}),ze.map(t=>e.jsxs("option",{value:t.sigla,children:[t.sigla," — ",t.name]},t.sigla))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Fonte do cliente"}
36),e.jsxs("select",{className:be,style:ye,value:ae.source,onChange:t=>Le("source",t.target.value),children:[e.jsx("option",{value:"",children:"Selecione"}),ia.map(t=>e.jsx("option",{value:t,children:t},t))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Optometrista"}),e.jsx("input",{className:be,style:ye,value:ae.optometrist_name,onChange:t=>Le("optometrist_name",t.target.value),placeholder:"Quem realizou o exame"})]})]}),e.jsxs("div",{className:"rounded-xl p-3 sm:p-4 space-y-3",style:{background:"#F8FAFF",border:"1px solid #EEF1F8"},children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-1",children:[e.jsx("span",{className:"text-xs font-bold uppercase tracking-wide",style:{color:"#101935"},children:"Receita"}),e.jsx("span",{className:"text-[11px] text-gray-400",children:"Use ponto ou vírgula: 1,25 · -0,75"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"grid grid-cols-[52px_1fr_1fr_1fr] sm:grid-cols-[110px_1fr_1fr_1fr] gap-1.5 sm:gap-2",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase text-gray-500 self-end",children:"Longe"}),e.jsx("span",{className:De+" !mb-0 !text-[10px] sm:!text-[11px]",children:"Esférico"}),e.jsx("span",{className:De+" !mb-0 !text-[10px] sm:!text-[11px]",children:"Cilíndrico"}),e.jsx("span",{className:De+" !mb-0 !text-[10px] sm:!text-[11px]",children:"Eixo"})]}),vt("od"),vt("oe")]}),e.jsxs("div",{className:"grid grid-cols-[52px_1fr] sm:grid-cols-[110px_240px] gap-1.5 sm:gap-2 items-center",children:[e.jsx("span",{className:"text-[11px] sm:text-xs font-bold",style:{color:"#101935"},children:"Adição"}),e.jsx("input",{className:be,style:ye,inputMode:"text",value:ae.addition,onChange:t=>Le("addition",t.target.value),placeholder:"+2,00"})]}),e.jsxs("div",{className:"grid grid-cols-[52px_1fr] sm:grid-cols-[110px_240px] gap-1.5 sm:gap-2 items-center",children:[e.jsx("span",{className:"text-[11px] sm:text-xs font-bold",style:{color:"#101935"},children:"Acuidade visual"}),e.jsx("input",{className:be,style:ye,value:ae.od_acuity||"",onChange:t=>{Le("od_acuity",t.target.value),Le("oe_acuity","")},placeholder:"Ex.: 20/20"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[e.jsxs("div",{className:"grid grid-cols-[52px_1fr_1fr_1fr] sm:grid-cols-[110px_1fr_1fr_1fr] gap-1.5 sm:gap-2",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase text-gray-500 self-end",children:"Perto"}),e.jsx("span",{className:De+" !mb-0 !text-[10px] sm:!text-[11px]",children:"Esférico"}),e.jsx("span",{className:De+" !mb-0 !text-[10px] sm:!text-[11px]",children:"Cilíndrico"}),e.jsx("span",{className:De+" !mb-0 !text-[10px] sm:!text-[11px]",children:"Eixo"})]}),vt("od",!0),vt("oe",!0)]})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Observação"}),e.jsx("textarea",{className:be,style:ye,rows:2,value:ae.observations,onChange:t=>Le("observations",t.target.value),placeholder:"Observações do exame"})]}),e.jsxs("div",{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>{ot({...it}),L||j(!1)},className:"w-full sm:w-auto px-4 py-3 sm:py-2 rounded-lg text-sm border text-gray-600",style:{borderColor:"#E5E7EB"},children:L?"Limpar":"Cancelar"}),e.jsxs("button",{type:"submit",disabled:D,className:"w-full sm:w-auto flex items-center justify-center gap-2 px-5 py-3 sm:py-2 rounded-lg text-sm font-semibold text-white bg-[#E8530E] disabled:opacity-60",children:[D&&e.jsx(Be,{className:"w-4 h-4 animate-spin"}),"Salvar receita"]})]})]}),F&&!Y&&e.jsxs("div",{className:"rounded-2xl p-3",style:{background:"#fff",border:"1px solid #F0F2F8"},children:[e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-2",children:[{label:"Receitas",value:X.total,color:"#101935"},{label:"Comprou",value:X.comprou,color:"#047857"},{label:"Não comprou",value:X.naoComprou,color:"#B91C1C"},{label:"Patologia",value:X.patologias,color:"#B45309"},{label:"Não informado",value:X.semInfo,color:"#6B7280"},{label:"Conversão (próprias)",value:`${X.conv}%`,color:"#E8530E"},{label:"Com OS",value:X.comOs,color:"#3730A3"}].map(t=>e.jsxs("div",{className:"rounded-xl px-3 py-2",style:{background:"#F8FAFF"},children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-gray-500",children:t.label}),e.jsx("div",{className:"text-lg font-bold",style:{color:t.color},children:t.value})]},t.label))}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-[11px] text-gray-600",children:[e.jsxs("span",{className:"font-semibold text-gray-500",children:[X.unidades," unidade",X.unidades!==1?"s":""," ·"]}),e.jsxs("span",{className:"px-2 py-0.5 rounded-full font-semibold",style:{background:"#FFF1E8",color:"#E8530E"}
36,children:["Conversão próprias — Hoje: ",X.convDia,"% · Semana: ",X.convSemana,"% · Mês: ",X.convMes,"%"]}),X.fontes.map(([t,h])=>e.jsxs("button",{type:"button",onClick:()=>A(P===t?"todas":t),className:"px-2 py-0.5 rounded-full transition-colors",style:{background:P===t?"#FFF1E8":"#F3F4F6",color:P===t?"#E8530E":"#4B5563",fontWeight:P===t?700:400,border:P===t?"1px solid #E8530E":"1px solid transparent"},children:[t,": ",h]},t))]})]}),F&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(ta,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:`${be} pl-9`,style:ye,value:v,onChange:t=>G(t.target.value),placeholder:"Buscar por cliente, telefone ou optometrista"})]}),e.jsx("div",{className:"flex rounded-lg overflow-hidden border",style:{borderColor:"#E5E7EB"},children:[["hoje","Hoje"],["semana","Semana"],["mes","Mês"],["todos","Todos"],["periodo","Período"]].map(([t,h])=>e.jsx("button",{type:"button",onClick:()=>xt(t),className:"px-3 py-2 text-[11px] font-semibold transition-colors",style:Qe===t?{background:"#E8530E",color:"#fff"}:{background:"#fff",color:"#6B7280"},children:h},t))}),Qe==="periodo"&&e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsxs(qa,{children:[e.jsx(Pa,{asChild:!0,children:e.jsxs(nt,{type:"button",variant:"outline","aria-label":"Data inicial das receitas",className:Ia("h-9 w-[138px] justify-start px-2 text-left text-xs font-normal",!He&&"text-muted-foreground"),children:[e.jsx(fa,{className:"mr-1.5 h-3.5 w-3.5"}),He?qe(ct(He),"dd/MM/yyyy"):"Data inicial"]})}),e.jsx(Ra,{className:"w-auto p-0",align:"start",children:e.jsx(Ua,{mode:"single",selected:ct(He),onSelect:t=>We(Et(t)),initialFocus:!0,className:"p-3 pointer-events-auto"})})]}),e.jsx("span",{className:"text-gray-500",children:"até"}),e.jsxs(qa,{children:[e.jsx(Pa,{asChild:!0,children:e.jsxs(nt,{type:"button",variant:"outline","aria-label":"Data final das receitas",className:Ia("h-9 w-[138px] justify-start px-2 text-left text-xs font-normal",!Ie&&"text-muted-foreground"),children:[e.jsx(fa,{className:"mr-1.5 h-3.5 w-3.5"}),Ie?qe(ct(Ie),"dd/MM/yyyy"):"Data final"]})}),e.jsx(Ra,{className:"w-auto p-0",align:"start",children:e.jsx(Ua,{mode:"single",selected:ct(Ie),onSelect:t=>jt(Et(t)),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),(g||c.length>1)&&e.jsxs("select",{className:be+" max-w-[220px]",style:ye,value:p,onChange:t=>W(t.target.value),children:[e.jsx("option",{value:"todas",children:"Todas as unidades"}),ze.map(t=>e.jsx("option",{value:t.sigla,children:t.sigla},t.sigla))]}),e.jsxs("select",{className:be+" max-w-[210px]",style:ye,value:P,"aria-label":"Filtrar receitas por fonte",onChange:t=>A(t.target.value),children:[e.jsx("option",{value:"todas",children:"Todas as fontes"}),$t.map(([t,h])=>e.jsxs("option",{value:t,children:[t," (",h,")"]},t))]}),P!=="todas"&&e.jsxs("button",{type:"button",onClick:()=>A("todas"),className:"flex items-center gap-1 px-3 py-2 rounded-lg text-[11px] font-semibold border hover:bg-gray-50",style:{borderColor:"#E8530E",background:"#FFF1E8",color:"#E8530E"},children:[e.jsx(wt,{className:"w-3.5 h-3.5"}),"Limpar fonte"]})]}),F&&(Y?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Be,{className:"w-6 h-6 animate-spin text-gray-400"})}):Ee.length===0?e.jsx("div",{className:"rounded-2xl py-12 text-center text-sm text-gray-500",style:{background:"#fff",border:"1px solid #F0F2F8"},children:"Nenhuma receita registrada ainda."}):ce==="planilha"?e.jsxs("div",{className:"rounded-2xl overflow-hidden",style:{background:"#fff",border:"1px solid #F0F2F8"},children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-[1226px] w-full table-fixed text-[11px]",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[86px]"}),e.jsx("col",{}),e.jsx("col",{className:"w-[96px]"}),e.jsx("col",{className:"w-[104px]"}),e.jsx("col",{className:"w-[100px]"}),e.jsx("col",{className:"w-[80px]"}),e.jsx("col",{className:"w-[112px]"}),e.jsx("col",{className:"w-[112px]"}),e.jsx("col",{className:"w-[50px]"}),e.jsx("col",{className:"w-[70px]"}),e.jsx("col",{className:"w-[104px]"}),e.jsx("col",{className:"w-[56px]"}),e.jsx("col",{}),e.jsx("col",{className:"w-[66px]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-gray-600 uppercase text-[10px] tracking-wide",children:[e.jsx("th",{className:"px-2 py-2 text-left",children:"Data"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Cliente"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Telefone"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Unidade"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Opto"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Fonte"}),e.jsx("th",{className:"px-2 py-2 text-left",title:"Esférico / Cilíndrico / Eixo",children:"Longe OD"}),e.jsx("th",{className:"px-2 py-2 text-left",title:"Esférico / Cilíndrico / Eixo",children:"Longe OE"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Ad."}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Acuidade"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Venda"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"OS"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Observação"}),e.jsx("th",{className:"px-2 py-2 text-left",children:"Ações"})]})}),e.jsx("tbody",{children:r.map(t=>{var h,b;return e.jsxs("tr",{className:"border-t",style:{borderColor:"#F0F2F8"},children:[e.jsx("td",{className:"px-2 py-1.5 whitespace-nowrap text-gray-600",children:me?e.jsx("input",{type:"date",className:Ke,style:Ze,value:t.exam_date||"",onChange:y=>je(t.id,"exam_date",y.target.value)}):t.exam_date.split("-").reverse().join("/")}),e.jsx("td",{className:"px-2 py-1.5 font-semibold",style:{color:"#101935"},title:t.patient_name,children:me?e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx("input",{className:Ke+" font-semibold flex-1 min-w-0",style:Ze,value:t.patient_name||"",onChange:y=>je(t.id,"patient_name",y.target.value)}),e.jsx("input",{className:Ke+" !w-[52px] shrink-0 text-center",style:Ze,inputMode:"numeric",placeholder:"Idade",title:"Idade",value:t.patient_age??"",onChange:y=>je(t.id,"patient_age",Lt(y.target.value))})]}):e.jsxs("span",{className:"block truncate",children:[t.patient_name,t.patient_age!=null&&e.jsxs("span",{className:"ml-1 font-normal text-gray-500",children:["(",t.patient_age," anos)"]})]})}),e.jsx("td",{className:"px-2 py-1.5 whitespace-nowrap text-gray-600",children:me?e.jsx("input",{className:Ke,style:Ze,value:t.patient_phone||"",placeholder:"Telefone",onChange:y=>je(t.id,"patient_phone",y.target.value)}):ua(t.patient_phone)}),e.jsx("td",{className:"px-2 py-1.5 font-semibold",style:{color:"#101935"},title:((h=ze.find(y=>y.sigla===String(t.store_sigla||"").toUpperCase()))==null?void 0:h.name)||String(t.store_sigla||""),children:me?e.jsxs("select",{className:Ke+" font-semibold",style:Ze,value:String(t.store_sigla||"").toUpperCase(),onChange:y=>je(t.id,"store_sigla",y.target.value),children:[!ze.some(y=>y.sigla===String(t.store_sigla||"").toUpperCase())&&e.jsx("option",{value:String(t.store_sigla||"").toUpperCase(),children:t.store_sigla}),ze.map(y=>e.jsx("option",{value:y.sigla,title:y.name,children:y.sigla},y.sigla))]}):String(t.store_sigla||"—")}),e.jsx("td",{className:"px-2 py-1.5 text-gray-600",title:t.optometrist_name||void 0,children:me?e.jsx("input",{className:Ke,style:Ze,value:t.optometrist_name||"",placeholder:"Optometrista",onChange:y=>je(t.id,"optometrist_name",y.target.value)}):e.jsx("span",{className:"block truncate",children:t.optometrist_name||"—"})}),e.jsx("td",{className:"px-2 py-1.5",children:me?e.jsxs("select",{className:Ke,style:Ze,value:t.source||"",onChange:y=>je(t.id,"source",y.target.value),children:[e.jsx("option",{value:"",children:"—"}),ia.map(y=>e.jsx("option",{value:y,children:y},y))]}):e.jsx("span",{className:"text-gray-600",children:t.source||"—"})}),e.jsx("td",{className:"px-2 py-1.5 whitespace-nowrap text-gray-600",children:Se?e.jsxs("div",{className:"flex gap-1",children:[e.jsx("input",{className:Ke,style:Ze,placeholder:"Esf",value:t.od_sphere||"",onChange:y=>je(t.id,"od_sphere",y.target.value)}),e.jsx("input",{className:Ke,style:Ze,placeholder:"Cil",value:t.od_cylinder||"",onChange:y=>je(t.id,"od_cylinder",y.target.value)}),e.jsx("input",{className:Ke,style:Ze,placeholder:"Eixo",value:t.od_axis||"",onChange:y=>je(t.id,"od_axis",y.target.value)})]}):bt(t.od_sphere,t.od_cylinder,t.od_axis)}),e.jsx("td",{className:"px-2 py-1.5 whitespace-nowrap text-gray-600",children:Se?e.jsxs("div",{className:"flex gap-1",children:[e.jsx("input",{className:Ke,style:Ze,placeholder:"Esf",value:t.oe_sphere||"",onChange:y=>je(t.id,"oe_sphere",y.target.value)}),e.jsx("input",{className:Ke,style:Ze,placeholder:"Cil",value:t.oe_cylinder||"",onChange:y=>je(t.id,"oe_cylinder",y.target.value)}),e.jsx("input",{className:Ke,style:Ze,placeholder:"Eixo",value:t.oe_axis||"",onChange:y=>je(t.id,"oe_axis",y.target.value)})]}):bt(t.oe_sphere,t.oe_cylinder,t.oe_axis)}),e.jsx("td",{className:"px-2 py-1.5 text-gray-600",children:Se?e.jsx("input",{className:Ke,style:Ze,placeholder:"Ad.",value:t.addition||"",onChange:y=>je(t.id,"addition",y.target.value)}):t.addition||"—"}),e.jsx("td",{className:"px-2 py-1.5 text-gray-600",children:me?e.jsx("input",{className:Ke,style:Ze,placeholder:"Acuidade",value:t.od_acuity||t.oe_acuity||"",onChange:y=>{je(t.id,"od_acuity",y.target.value),je(t.id,"oe_acuity","")}}):t.od_acuity||t.oe_acuity||"—"}),e.jsx("td",{className:"px-2 py-1.5",children:me?e.jsxs("select",{className:"w-full px-1.5 py-1 rounded-md border text-[11px] font-semibold",style:da[st(t)]||{borderColor:"#E5E7EB",color:"#101935"},value:st(t),onChange:y=>{const k=y.target.value;je(t.id,"sale_type",k||null),je(t.id,"pathology",k==="patologia"),je(t.id,"purchased",k==="comprou"?!0:k===""?null:!1)},children:[e.jsx("option",{value:"",children:"Não informado"}),ya.map(y=>e.jsx("option",{value:y.v,children:y.label},y.v))]}):e.jsx("span",{className:"text-xs font-semibold",style:{color:((b=da[st(t)])==null?void 0:b.color)||"#6B7280"},children:ca[st(t)]||"—"})}),e.jsx("td",{className:"px-2 py-1.5",children:me?e.jsx("input",{className:"w-full px-1.5 py-1 rounded-md border text-[11px]",style:{borderColor:"#E5E7EB",color:"#101935"},value:t.os_number||"",placeholder:"OS",onChange:y=>je(t.id,"os_number",y.target.value)}):e.jsx("span",{className:"text-gray-600",children:t.os_number||"—"})}),e.jsx("td",{className:"px-2 py-1.5",children:me?e.jsx("input",{className:"w-full px-1.5 py-1 rounded-md border text-[11px]",style:{borderColor:"#E5E7EB",color:"#101935"},value:t.observations||"",placeholder:"Observação",onChange:y=>je(t.id,"observations",y.target.value)}):e.jsx("span",{className:"text-gray-600",children:t.observations||"—"})}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[me&&e.jsx("span",{title:_e===t.id?"Salvando...":"Alterações salvas automaticamente",className:`flex h-7 w-7 items-center justify-center rounded-md text-white ${_e===t.id?"bg-gray-400":"bg-emerald-500"}`,children:_e===t.id?e.jsx(Be,{className:"w-3 h-3 animate-spin"}):e.jsx(Ms,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>{var y;return na({...t,store_name:((y=ze.find(k=>k.sigla===String(t.store_sigla).toUpperCase()))==null?void 0:y.name)||null})},title:"Baixar receita",className:"p-1.5 rounded-md border text-[#101935] hover:bg-gray-50",style:{borderColor:"#E5E7EB"},children:e.jsx(oa,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>x(t),title:"Excluir receita",className:"p-1.5 rounded-md border text-gray-400 hover:text-red-600 hover:bg-red-50",style:{borderColor:"#E5E7EB"},children:e.jsx(ba,{className:"w-3.5 h-3.5"})})]})})]},t.id)})})]})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 border-t",style:{borderColor:"#F0F2F8"},children:[e.jsxs("span",{className:"text-[11px] text-gray-500",children:["Mostrando ",(H-1)*Q+1,"–",Math.min(H*Q,Ee.length)," de ",Ee.length," receitas"]}),o>1&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>ee(t=>Math.max(1,t-1)),disabled:H===1,className:"px-2.5 py-1 rounded-md border text-[11px] font-semibold disabled:opacity-40",style:{borderColor:"#E5E7EB",color:"#101935"},children:"Anterior"}),e.jsxs("span",{className:"text-[11px] text-gray-600",children:["Página ",H," de ",o]}),e.jsx("button",{onClick:()=>ee(t=>Math.min(o,t+1)),disabled:H===o,className:"px-2.5 py-1 rounded-md border text-[11px] font-semibold disabled:opacity-40",style:{borderColor:"#E5E7EB",color:"#101935"},children:"Próxima"})]})]})]}):e.jsx("div",{className:"space-y-2",children:Ee.map(t=>e.jsxs("div",{className:"rounded-2xl p-4",style:{background:"#fff",border:"1px solid #F0F2F8"},children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-sm",style:{color:"#101935"},children:[t.patient_name,t.patient_age!=null&&e.jsxs("span",{className:"ml-1 font-normal text-gray-500",children:["(",t.patient_age," anos)"]})]}),e.jsxs("div",{className:"text-xs text-gray-500",children:[ua(t.patient_phone)," · ",t.exam_date.split("-").reverse().join("/")," ·"," ",e.jsx("span",{className:"px-1.5 py-0.5 rounded",style:{background:"#F3F4F6"},children:t.store_sigla}),t.optometrist_name?` · ${t.optometrist_name}`:""]}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"px-2 py-0.5 rounded-full text-[11px] font-semibold",style:{background:t.os_number?"#EEF2FF":"#F3F4F6",color:t.os_number?"#3730A3":"#6B7280"}
36,children:["OS: ",t.os_number||"—"]}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[11px] font-semibold",style:(()=>{const h=da[st(t)];return h?{background:h.background,color:h.color}:{background:"#F3F4F6",color:"#6B7280"}})(),children:ca[st(t)]||"Compra não informada"}),e.jsxs("span",{className:"px-2 py-0.5 rounded-full text-[11px] font-semibold",style:{background:t.source?"#FEF3C7":"#F3F4F6",color:t.source?"#92400E":"#6B7280"},children:["Fonte: ",t.source||"—"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[me&&e.jsx("button",{onClick:()=>Ve(t),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold border hover:bg-gray-50",style:{borderColor:"#E8530E",color:"#E8530E"},children:"Editar"}),e.jsxs("button",{onClick:()=>{var h;return na({...t,store_name:((h=ze.find(b=>b.sigla===String(t.store_sigla).toUpperCase()))==null?void 0:h.name)||null})},className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold border text-[#101935] hover:bg-gray-50",style:{borderColor:"#E5E7EB"},children:[e.jsx(oa,{className:"w-4 h-4"}),"Baixar receita"]}),(me||se&&t.created_by===se)&&e.jsx("button",{onClick:()=>x(t),className:"p-2 rounded-lg text-gray-400 hover:text-red-600 hover:bg-red-50",children:e.jsx(ba,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"mt-3 overflow-hidden rounded-xl border",style:{borderColor:"#EEF1F8"},children:e.jsxs("table",{className:"w-full text-xs text-center",style:{color:"#101935"},children:[e.jsx("thead",{style:{background:"#F8FAFF"},children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wide text-gray-500",children:[e.jsx("th",{className:"px-2 py-2 text-left w-24",children:" "}),e.jsx("th",{className:"px-2 py-2",children:"Esférico"}),e.jsx("th",{className:"px-2 py-2",children:"Cilíndrico"}),e.jsx("th",{className:"px-2 py-2",children:"Eixo"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-t",style:{borderColor:"#EEF1F8"},children:[e.jsx("td",{className:"px-2 py-2 text-left font-semibold",children:"Longe · OD"}),e.jsx("td",{className:"px-2 py-2",children:t.od_sphere||"—"}),e.jsx("td",{className:"px-2 py-2",children:t.od_cylinder||"—"}),e.jsx("td",{className:"px-2 py-2",children:t.od_axis?`${t.od_axis}°`:"—"})]}),e.jsxs("tr",{className:"border-t",style:{borderColor:"#EEF1F8"},children:[e.jsx("td",{className:"px-2 py-2 text-left font-semibold",children:"Longe · OE"}),e.jsx("td",{className:"px-2 py-2",children:t.oe_sphere||"—"}),e.jsx("td",{className:"px-2 py-2",children:t.oe_cylinder||"—"}),e.jsx("td",{className:"px-2 py-2",children:t.oe_axis?`${t.oe_axis}°`:"—"})]}),e.jsxs("tr",{className:"border-t",style:{borderColor:"#EEF1F8",background:"#FCFDFF"},children:[e.jsx("td",{className:"px-2 py-2 text-left font-semibold",children:"Adição"}),e.jsx("td",{className:"px-2 py-2",colSpan:3,children:t.addition||"—"})]}),e.jsxs("tr",{className:"border-t",style:{borderColor:"#EEF1F8"},children:[e.jsx("td",{className:"px-2 py-2 text-left font-semibold",children:"Acuidade"}),e.jsxs("td",{className:"px-2 py-2",colSpan:3,children:["OD ",t.od_acuity||"—"," · OE ",t.oe_acuity||"—"]})]}),e.jsxs("tr",{className:"border-t",style:{borderColor:"#EEF1F8"},children:[e.jsx("td",{className:"px-2 py-2 text-left font-semibold",children:"Perto · OD"}),e.jsx("td",{className:"px-2 py-2",children:t.od_near_sphere||"—"}),e.jsx("td",{className:"px-2 py-2",children:t.od_near_cylinder||"—"}),e.jsx("td",{className:"px-2 py-2",children:t.od_near_axis?`${t.od_near_axis}°`:"—"})]}),e.jsxs("tr",{className:"border-t",style:{borderColor:"#EEF1F8"},children:[e.jsx("td",{className:"px-2 py-2 text-left font-semibold",children:"Perto · OE"}),e.jsx("td",{className:"px-2 py-2",children:t.oe_near_sphere||"—"}),e.jsx("td",{className:"px-2 py-2",children:t.oe_near_cylinder||"—"}),e.jsx("td",{className:"px-2 py-2",children:t.oe_near_axis?`${t.oe_near_axis}°`:"—"})]})]})]})}),t.observations&&e.jsx("div",{className:"mt-2 text-xs text-gray-600",children:t.observations}),e.jsx("div",{className:"mt-3",children:e.jsxs("button",{type:"button",onClick:async()=>{var h;try{await na({...t,store_name:((h=ze.find(b=>b.sigla===String(t.store_sigla).toUpperCase()))==null?void 0:h.name)||null})}catch(b){console.error("Falha ao gerar receita",b),alert("Não foi possível gerar a receita. Tente novamente.")}},className:"w-full sm:w-auto flex items-center justify-center gap-2 px-4 py-3 sm:py-2 rounded-lg text-sm font-semibold text-white bg-[#E8530E]",children:[e.jsx(oa,{className:"w-4 h-4"}),"Baixar receita (PDF)"]})})]},t.id))})),R&&me&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-3 overflow-auto",style:{background:"rgba(16,25,53,.45)"},onClick:()=>!Pe&&Ve(null),children:e.jsxs("div",{className:"w-full max-w-2xl rounded-2xl p-4 sm:p-5 space-y-4 my-6",style:{background:"#fff"},onClick:t=>t.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-bold",style:{color:"#101935"},children:"Editar receita"}),e.jsx("button",{onClick:()=>Ve(null),className:"p-1.5 rounded-lg text-gray-400 hover:bg-gray-100",children:e.jsx(wt,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("label",{className:De,children:"Nome do cliente *"}),e.jsx("input",{className:be,style:ye,value:R.patient_name||"",onChange:t=>B("patient_name",t.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Idade"}),e.jsx("input",{className:be,style:ye,inputMode:"numeric",placeholder:"Ex.: 58",value:R.patient_age??"",onChange:t=>B("patient_age",Lt(t.target.value))})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Telefone"}),e.jsx("input",{className:be,style:ye,inputMode:"tel",value:R.patient_phone||"",onChange:t=>B("patient_phone",t.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Data do exame"}),e.jsx("input",{type:"date",className:be,style:ye,value:R.exam_date||"",onChange:t=>B("exam_date",t.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("label",{className:De,children:"Optometrista"}),e.jsx("input",{className:be,style:ye,value:R.optometrist_name||"",onChange:t=>B("optometrist_name",t.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Fonte do cliente"}),e.jsxs("select",{className:be,style:ye,value:R.source||"",onChange:t=>B("source",t.target.value),children:[e.jsx("option",{value:"",children:"Não informado"}),ia.map(t=>e.jsx("option",{value:t,children:t},t))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Número da OS"}),e.jsx("input",{className:be,style:ye,value:R.os_number||"",onChange:t=>B("os_number",t.target.value),placeholder:"Ex.: 12345"})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Venda"}),e.jsxs("select",{className:be,style:ye,value:st(R),onChange:t=>{const h=t.target.value;B("sale_type",h||null),B("pathology",h==="patologia"),B("purchased",h==="comprou"?!0:h===""?null:!1)},children:[e.jsx("option",{value:"",children:"Não informado"}),ya.map(t=>e.jsx("option",{value:t.v,children:t.label},t.v))]})]})]}),e.jsxs("div",{className:"rounded-xl p-3 space-y-2",style:{background:"#F8FAFF",border:"1px solid #EEF1F8"},children:[e.jsx("span",{className:"text-xs font-bold uppercase tracking-wide",style:{color:"#101935"},children:"Graus"}),[["Longe · OD","od_sphere","od_cylinder","od_axis"],["Longe · OE","oe_sphere","oe_cylinder","oe_axis"],["Perto · OD","od_near_sphere","od_near_cylinder","od_near_axis"],["Perto · OE","oe_near_sphere","oe_near_cylinder","oe_near_axis"]].map(([t,h,b,y])=>e.jsxs("div",{className:"grid grid-cols-[62px_1fr_1fr_1fr] sm:grid-cols-[110px_1fr_1fr_1fr] gap-1.5 items-center",children:[e.jsx("span",{className:"text-[11px] font-semibold text-gray-600",children:t}),e.jsx("input",{className:be,style:ye,placeholder:"Esf.",value:R[h]||"",disabled:!Se,onChange:k=>B(h,k.target.value)}),e.jsx("input",{className:be,style:ye,placeholder:"Cil.",value:R[b]||"",disabled:!Se,onChange:k=>B(b,k.target.value)}),e.jsx("input",{className:be,style:ye,placeholder:"Eixo",value:R[y]||"",disabled:!Se,onChange:k=>B(y,k.target.value)})]},t)),e.jsxs("div",{className:"grid grid-cols-[62px_1fr] sm:grid-cols-[110px_240px] gap-1.5 items-center",children:[e.jsx("span",{className:"text-[11px] font-semibold text-gray-600",children:"Adição"}),e.jsx("input",{className:be,style:ye,value:R.addition||"",disabled:!Se,onChange:t=>B("addition",t.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-[62px_1fr] sm:grid-cols-[110px_240px] gap-1.5 items-center",children:[e.jsx("span",{className:"text-[11px] font-semibold text-gray-600",children:"Acuidade visual"}),e.jsx("input",{className:be,style:ye,placeholder:"Ex.: 20/20",value:R.od_acuity||R.oe_acuity||"",onChange:t=>{B("od_acuity",t.target.value),B("oe_acuity",null)}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:De,children:"Observação"}),e.jsx("textarea",{className:be,style:ye,rows:2,value:R.observations||"",onChange:t=>B("observations",t.target.value)})]}),e.jsxs("div",{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>Ve(null),className:"w-full sm:w-auto px-4 py-3 sm:py-2 rounded-lg text-sm border text-gray-600",style:{borderColor:"#E5E7EB"},children:"Cancelar"}),e.jsxs("button",{type:"button",onClick:I,disabled:Pe,className:"w-full sm:w-auto flex items-center justify-center gap-2 px-5 py-3 sm:py-2 rounded-lg text-sm font-semibold text-white bg-[#E8530E] disabled:opacity-60",children:[Pe&&e.jsx(Be,{className:"w-4 h-4 animate-spin"}),"Salvar alterações"]})]})]})})]})},Cn=s=>
36{const n=String(s||"").toUpperCase().startsWith("BIOPTO:")?s.slice(s.indexOf(":")+1):s;return String(n||"").split("+").map(i=>i.trim().toUpperCase()).filter(Boolean)},pa=()=>new Date(new Date().toLocaleString("en-US",{timeZone:"America/Sao_Paulo"})).toISOString().slice(0,10),es=(s,n)=>{const i=new Date(`${s}T12:00:00`);return i.setDate(i.getDate()+n),i.toISOString().slice(0,10)},En=s=>{const n=String(s||"").replace(/\D/g,"");return n.length===11?`(${n.slice(0,2)}) ${n.slice(2,7)}-${n.slice(7)}`:n.length===10?`(${n.slice(0,2)}) ${n.slice(2,6)}-${n.slice(6)}`:s||"—"},Sn=s=>{const n=String(s||"").toLowerCase();return n==="attended"||n==="completed"?{label:"Compareceu",bg:"#ECFDF5",color:"#047857"}:n==="no_show"?{label:"Não veio",bg:"#FEF2F2",color:"#B91C1C"}:n==="cancelled"?{label:"Cancelado",bg:"#F3F4F6",color:"#6B7280"}:{label:"Agendado",bg:"#EFF6FF",color:"#1D4ED8"}},ts="w-full px-3 py-2.5 sm:py-2 rounded-xl sm:rounded-lg border text-base sm:text-sm outline-none focus:border-[#E8530E]",as={borderColor:"#E5E7EB",background:"#fff",color:"#101935"},Fn=({profile:s})=>{const n=l.useMemo(()=>Cn(s.store_sigla),[s.store_sigla]),i=n.includes("ALL"),[c,g]=l.useState([]),[S,N]=l.useState(!0),[L,F]=l.useState(""),[$,V]=l.useState(()=>pa()),[O,Y]=l.useState(!1),K=$,ue=$,j=l.useCallback(async()=>{N(!0);try{const{data:v,error:G}=await w.from("appointments").select("id, date, time, title, status, description, observations, contact_id, client_name, whatsapp_name, metadata").gte("date",K).lte("date",ue).order("date",{ascending:!0}).order("time",{ascending:!0}).limit(1e3);if(G)throw G;const p=v||[],W=[...new Set(p.map(M=>M.contact_id).filter(Boolean))],P={};for(let M=0;M<W.length;M+=200){const{data:ie}=await w.from("contacts").select("id, name, call_name, phone_number").in("id",W.slice(M,M+200));(ie||[]).forEach(se=>{P[se.id]={name:se.call_name||se.name||"Cliente",phone:se.phone_number||""}})}const A=p.map(M=>{const ie=M.metadata||{},se=String(ie.store_sigla||"").toUpperCase()||"—",f=P[M.contact_id]||null,d=String(ie.person_name||ie.name||M.client_name||"").trim(),_=String(M.whatsapp_name||(f==null?void 0:f.name)||"").trim();return{id:M.id,date:M.date,time:M.time,title:M.title,status:M.status,unit:se,name:d||_||String(M.title||"").trim()||"Cliente",phone:(f==null?void 0:f.phone)||"",observations:M.observations||M.description||null}}).filter(M=>i||O||n.includes(M.unit)||M.unit==="—");g(A)}finally{N(!1)}},[K,ue,n,i,O]);l.useEffect(()=>{j()},[j]);const D=l.useMemo(()=>{const v=L.trim().toLowerCase();return v?c.filter(G=>`${G.name} ${G.phone}`.toLowerCase().includes(v)):c},[c,L]),z=l.useMemo(()=>{const v={};return D.forEach(G=>{var p;(v[p=G.date]||(v[p]=[])).push(G)}),Object.entries(v).sort(([G],[p])=>G.localeCompare(p))},[D]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-lg font-bold flex items-center gap-2",style:{color:"#101935"},children:[e.jsx(Ut,{className:"w-5 h-5 text-[#E8530E]"}),"Agendamentos do dia"]}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i||O?"Todas as unidades":n.join(" · ")," · ",$.split("-").reverse().join("/")," · ",D.length," agendamento",D.length!==1?"s":""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!i&&e.jsx("button",{onClick:()=>Y(v=>!v),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium border ${O?"text-white":"text-gray-600 hover:bg-gray-50"}`,style:O?{borderColor:"#E8530E",background:"#E8530E"}:{borderColor:"#E5E7EB",background:"#fff"},children:"Todas as lojas"}),e.jsxs("button",{onClick:j,className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium border text-gray-600 hover:bg-gray-50",style:{borderColor:"#E5E7EB",background:"#fff"},children:[e.jsx(Dt,{className:"w-4 h-4"}),"Atualizar"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(ta,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:`${ts} pl-9`,style:as,value:L,onChange:v=>F(v.target.value),placeholder:"Buscar por cliente ou telefone"})]}),e.jsx("button",{onClick:()=>V(v=>es(v,-1)),className:"px-3 py-2 rounded-lg text-sm font-medium border text-gray-600 hover:bg-gray-50",style:{borderColor:"#E5E7EB",background:"#fff"},children:"‹ Dia anterior"}),e.jsx("input",{type:"date",className:ts+" max-w-[170px]",style:as,value:$,onChange:v=>V(v.target.value||pa())}),e.jsx("button",{onClick:()=>V(v=>es(v,1)),className:"px-3 py-2 rounded-lg text-sm font-medium border text-gray-600 hover:bg-gray-50",style:{borderColor:"#E5E7EB",background:"#fff"},children:"Próximo dia ›"}),e.jsx("button",{onClick:()=>V(pa()),className:"px-3 py-2 rounded-lg text-sm font-medium border text-gray-600 hover:bg-gray-50",style:{borderColor:"#E5E7EB",background:"#fff"},children:"Hoje"})]}),S?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Be,{className:"w-6 h-6 animate-spin text-gray-400"})}):z.length===0?e.jsx("div",{className:"rounded-2xl py-12 text-center text-sm text-gray-500",style:{background:"#fff",border:"1px solid #F0F2F8"},children:"Nenhum agendamento neste dia."}):e.jsx("div",{className:"space-y-3",children:z.map(([v,G])=>e.jsxs("div",{className:"rounded-2xl overflow-hidden",style:{background:"#fff",border:"1px solid #F0F2F8"},children:[e.jsxs("div",{className:"px-4 py-2.5 text-xs font-bold uppercase tracking-wide",style:{background:"#F8FAFF",color:"#101935"},children:[v.split("-").reverse().join("/")," · ",G.length]}),e.jsx("div",{children:G.map(p=>{var P;const W=Sn(p.status);return e.jsxs("div",{className:"px-4 py-3 border-t flex flex-wrap items-center justify-between gap-2",style:{borderColor:"#F3F4F6"},children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold text-sm truncate",style:{color:"#101935"},children:p.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[En(p.phone)," · ",e.jsx("span",{className:"px-1.5 py-0.5 rounded",style:{background:"#F3F4F6"},children:p.unit}),p.observations?` · ${p.observations}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",style:{color:"#101935"},children:((P=p.time)==null?void 0:P.slice(0,5))||"—"}),e.jsx("span",{className:"text-[11px] font-semibold px-2 py-0.5 rounded-full",style:{background:W.bg,color:W.color},children:W.label})]})]}
36,p.id)})})]},v))})]})},Xt={"cdba8da8-223f-4741-b930-40b58f0b81bd":"ALL","1128f715-e4c0-47e4-86af-4ff88b416a85":"Monique","d7023404-ad69-4628-8b45-b873638b959f":"Emilly"},ss={gestao:"gerente",receita:"receita",central:"Central",planilha:"planilha",venda:"venda",compra:"compra na loja"},kn={agendado:"Agendado",a_atualizar:"A atualizar",compareceu:"Compareceu",nao_compareceu:"Não compareceu",cancelado:"Cancelado",remarcado:"Remarcado",duplicado:"Duplicado",sem_data:"Falta a data"},Yt=200,Re=()=>new Date().toISOString().slice(0,10),Dn=()=>Re().slice(0,8)+"01",ns=s=>({SUZ:"SZN",SUZANO:"SZN","SBC1/KIDS":"SBC1"})[String(s||"").toUpperCase()]||String(s||"").toUpperCase(),xa=["ITB","SR","SZN","CPA"],_t=s=>{if(!s)return"";const[n,i,c]=s.slice(0,10).split("-");return`${c}/${i}/${n}`},Cs=s=>{const n=(s||"").replace(/\D/g,"").replace(/^55/,"");return n.length===11?`(${n.slice(0,2)}) ${n.slice(2,7)}-${n.slice(7)}`:n.length===10?`(${n.slice(0,2)}) ${n.slice(2,6)}-${n.slice(6)}`:s||""},ut="w-full bg-transparent px-1 py-0.5 text-[11px] rounded border border-transparent hover:border-gray-200 focus:border-[#E8530E] focus:outline-none",Es=(s,n)=>{switch(s){case"data_registro":return n.data_registro?_t(n.data_registro):"";case"telefone":return Cs(n.telefone);case"data_agendamento":return n.data_agendamento?_t(n.data_agendamento):"";case"horario":return(n.horario||"").slice(0,5);case"compareceu":return n.compareceu?"Compareceu":"Não compareceu";case"venda":return n.venda?"Sim":"Não";default:return n[s]||""}},os=({active:s,open:n,onClick:i})=>e.jsx("button",{onClick:i,title:"Filtrar / ordenar",className:`p-0.5 rounded hover:bg-gray-200 ${s?"text-[#E8530E]":n?"text-gray-600":"text-gray-300"}`,children:e.jsx(Ks,{className:"w-3 h-3"})}),$n=({colKey:s,rows:n,active:i,open:c,sortDir:g,onToggle:S,onClose:N,onChange:L,onSort:F,onTextFilter:$})=>{const[V,O]=l.useState(""),[Y,K]=l.useState(i),ue=l.useMemo(()=>{const D=new Map;return n.forEach(z=>{const v=Es(s,z)||"(vazio)";D.set(v,(D.get(v)||0)+1)}),[...D.entries()].sort((z,v)=>{if(s==="data_registro"||s==="data_agendamento"){const G=p=>p==="(vazio)"?"99999999":p.split("/").reverse().join("");return G(z[0]).localeCompare(G(v[0]))}return z[0].localeCompare(v[0],"pt-BR",{numeric:!0})})},[n,s]);if(l.useEffect(()=>{c&&K(i)},[c,i]),!c)return e.jsx(os,{active:i!==void 0,open:!1,onClick:S});const j=ue.filter(([D])=>D.toLowerCase().includes(V.trim().toLowerCase()));return e.jsxs(e.Fragment,{children:[e.jsx(os,{active:i!==void 0,open:!0,onClick:N}),e.jsx("div",{className:"fixed inset-0 z-40",onClick:N}),e.jsxs("div",{className:"absolute left-1/2 -translate-x-1/2 top-full mt-1 z-50 w-56 bg-white border border-gray-200 rounded-lg shadow-xl p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1.5",children:[e.jsxs("button",{onClick:()=>F("asc"),className:`flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium border ${g==="asc"?"bg-[#101935] text-white border-[#101935]":"bg-white text-gray-600"}`,children:[e.jsx(vs,{className:"w-3 h-3"})," A → Z"]}),e.jsxs("button",{onClick:()=>F("desc"),className:`flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium border ${g==="desc"?"bg-[#101935] text-white border-[#101935]":"bg-white text-gray-600"}`,children:[e.jsx(js,{className:"w-3 h-3"})," Z → A"]})]}),e.jsx("input",{value:V,onChange:D=>O(D.target.value),placeholder:"Buscar valores...",className:"w-full mb-1.5 px-2 py-1 text-[11px] border border-gray-200 rounded bg-white text-gray-700 focus:border-[#E8530E] focus:outline-none"}),$&&V.trim()&&e.jsxs("button",{onClick:()=>{$(V.trim()),N()},className:"w-full mb-1.5 px-2 py-1.5 rounded text-[11px] font-semibold bg-[#E8530E] text-white hover:opacity-90",children:['Ver só clientes com "',V.trim(),'"']}),e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 text-[10px] whitespace-nowrap",children:[e.jsx("button",{onClick:()=>K(ue.map(D=>D[0])),className:"text-[#3B176B] font-semibold hover:underline",children:"Marcar todos"}),e.jsx("span",{className:"text-gray-300",children:"|"}),e.jsx("button",{onClick:()=>K([]),className:"text-[#E8530E] font-semibold hover:underline",children:"Desmarcar todos"}),e.jsx("span",{className:"text-gray-300",children:"|"}),e.jsx("button",{onClick:()=>K(void 0),className:"text-gray-500 font-semibold hover:underline",children:"Limpar"})]}),e.jsxs("div",{className:"max-h-48 overflow-y-auto divide-y divide-gray-50",children:[j.map(([D,z])=>{const v=Y?Y.includes(D):!0;return e.jsxs("label",{className:"flex items-center gap-2 px-1 py-1 hover:bg-gray-50 rounded cursor-pointer text-[11px] text-gray-700",children:[e.jsx("input",{type:"checkbox",className:"accent-[#E8530E]",checked:v,onChange:()=>{const G=Y?[...Y]:ue.map(W=>W[0]),p=v?G.filter(W=>W!==D):[...G,D];
36K(p.length===ue.length?void 0:p)}}),e.jsx("span",{className:"flex-1 truncate",title:D,children:D}),e.jsx("span",{className:"text-gray-400 text-[10px]",children:z})]},D)}),!j.length&&e.jsx("div",{className:"text-[11px] text-gray-400 px-1 py-2",children:"Nenhum valor encontrado."})]}),e.jsxs("div",{className:"flex gap-1.5 pt-2 mt-1 border-t border-gray-100",children:[e.jsx("button",{onClick:()=>{L(Y),N()},className:"flex-1 px-2 py-1.5 rounded text-[11px] font-semibold bg-[#E8530E] text-white",children:"Aplicar"}),e.jsx("button",{onClick:N,className:"px-2 py-1.5 rounded text-[11px] font-semibold border bg-white text-gray-600",children:"Cancelar"})]})]})]})},On=({userId:s})=>{const n=Xt[s],i=n==="Emilly"?["ob"]:["ob","bioopto"],[c,g]=l.useState("ob"),[S,N]=l.useState([]),[L,F]=l.useState(!0),[$,V]=l.useState(""),[O,Y]=l.useState(n==="ALL"?"todos":n),[K,ue]=l.useState("mes"),[j,D]=l.useState(Dn()),[z,v]=l.useState(Re().slice(0,7)+"-31"),[G,p]=l.useState(0),[W,P]=l.useState({}),[A,M]=l.useState({}),[ie,se]=l.useState(null),[f,d]=l.useState({key:"data_registro",dir:"desc"}),[_,U]=l.useState(null),[J,ne]=l.useState(null),[Me,$e]=l.useState(!1),[we,Ce]=l.useState(""),[me,Se]=l.useState(null),[R,Ve]=l.useState([]),[Pe,Ye]=l.useState("propria"),[B,ce]=l.useState(!0),[Fe,_e]=l.useState(null),[Ge,ke]=l.useState(!1),et=l.useCallback(async()=>{F(!0);const o=[];for(let u=0;;u+=1e3){const{data:I,error:x}=await w.from("comercial_interno_agendamentos").select("*").eq("planilha",c).neq("status","duplicado").order("data_registro",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(u,u+999);if(x){ge.error("Erro ao carregar: "+x.message);break}if(o.push(...I||[]),!I||I.length<1e3)break}const r=c==="bioopto"?o.filter(u=>xa.includes(ns(u.unidade))):o;N(r),P({}),p(0),F(!1),M({}),d({key:"data_registro",dir:"desc"}),se(null),U(null),ne(null),ue("mes"),Ce(""),V(""),Se(null)},[c]);l.useEffect(()=>{et()},[et]),l.useEffect(()=>{Promise.all([w.from("stores").select("sigla,name,store_type").eq("is_active",!0).order("sigla"),w.from("comercial_interno_config").select("importacao_planilhas_ativa").eq("id",!0).maybeSingle()]).then(([o,r])=>{o.data&&Ve(o.data),r.data&&ce(r.data.importacao_planilhas_ativa)})},[]);const Te=l.useMemo(()=>{const o=$.trim().toLowerCase(),r=Re().slice(0,7);return S.filter(u=>{if(u.id.startsWith("novo-"))return!0;const I=R.find(fe=>fe.sigla===ns(u.unidade)),x=u.unidade==="VC1+VC2"?"propria":I==null?void 0:I.store_type;if(Pe!=="todas"&&x!==Pe||O!=="todos"&&u.vendedor!==O)return!1;const he=u.data_agendamento||"";if(K==="mes"&&!(c==="bioopto"?(u.data_registro||"").startsWith(r):he.startsWith(r))||K==="ativos"&&!(he>=Re()&&!u.compareceu&&!u.venda)||K==="hoje"&&he!==Re()||K==="custom"&&he&&(he<j||he>z)||K==="custom"&&!he&&u.data_registro&&((u.data_registro||"")<j||(u.data_registro||"")>z)||o&&!`${u.nome} ${u.telefone} ${u.unidade}`.toLowerCase().includes(o)||we&&!(u.nome||"").toLowerCase().includes(we.toLowerCase()))return!1;for(const[fe,tt]of Object.entries(A))if(tt&&!tt.includes(Es(fe,u)||"(vazio)"))return!1;return!0})},[S,$,O,K,j,z,A,we,R,Pe,c]),rt=l.useMemo(()=>{if(Ge){const r=Re(),u=new Date(Date.now()-30*864e5).toISOString().slice(0,10);return S.filter(I=>{const x=I.data_agendamento||"";return!(I.id.startsWith("novo-")||!x||x>=r||x<u||I.compareceu||I.venda||I.followup_realizado_em||["cancelado","duplicado","sem_data","remarcado"].includes(I.status)||O!=="todos"&&I.vendedor!==O)})}if(!me)return Te;const o=Re();return Te.filter(r=>me==="comp"?r.compareceu:me==="venda"?r.venda:me==="futuros"?(r.data_agendamento||"")>=o:!r.compareceu&&!!r.comparecimento_alerta)},[Te,me,Ge,S,O]),je=(o,r)=>{switch(o){case"data_registro":return r.data_registro||"";case"data_agendamento":return r.data_agendamento||"";case"horario":return(r.horario||"").slice(0,5);case"compareceu":return r.compareceu?"Compareceu":"Não compareceu";case"venda":return r.venda?"Sim":"Não";default:return r[o]||""}},it=l.useMemo(()=>{if(!f)return rt;const{key:o,dir:r}=f;return[...rt].sort((u,I)=>{const x=je(o,u),he=je(o,I);if(!x&&he)return 1;if(x&&!he)return-1;if(!x&&!he)return 0;const fe=x.localeCompare(he,"pt-BR",{numeric:!0});return r==="asc"?fe:-fe})},[rt,f]),ae=l.useMemo(()=>({total:Te.filter(o=>o.status!=="sem_data").length,comp:Te.filter(o=>o.compareceu&&o.status!=="sem_data").length,venda:Te.filter(o=>o.venda).length,futuros:Te.filter(o=>o.status==="agendado"&&(o.data_agendamento||"")>=Re()).length,verificar:Te.filter(o=>!o.compareceu&&o.comparecimento_alerta).length,semData:Te.filter(o=>o.status==="sem_data").length}),[Te]),ot=l.useMemo(()=>["Emilly","Monique"].map(o=>{const r=Te.filter(x=>x.vendedor===o&&x.status!=="sem_data"),u=r.filter(x=>x.compareceu).length,I=r.filter(x=>
36x.status!=="cancelado").length;return{vendedor:o,total:r.length,attended:u,rate:I?Math.round(u*1e3/I)/10:0}}).filter(o=>o.total>0),[Te]),Le=l.useMemo(()=>{const o=Re(),r=new Date(Date.now()-30*864e5).toISOString().slice(0,10);return S.filter(u=>{if(u.id.startsWith("novo-"))return!1;const I=u.data_agendamento||"";return!(!I||I>=o||I<r||u.compareceu||u.venda||["cancelado","duplicado","sem_data","remarcado"].includes(u.status)||O!=="todos"&&u.vendedor!==O)}).sort((u,I)=>(I.data_agendamento||"").localeCompare(u.data_agendamento||""))},[S,O]),Ue=l.useMemo(()=>Le.filter(o=>!o.followup_realizado_em),[Le]),ze=l.useMemo(()=>new Set(Ue.map(o=>o.id)),[Ue]),$t=async o=>{const r={followup_realizado_em:new Date().toISOString(),followup_realizado_por:s},{error:u}=await w.from("comercial_interno_agendamentos").update(r).eq("id",o.id);if(u)return ge.error("Não salvou: "+u.message);N(I=>I.map(x=>x.id===o.id?{...x,...r}:x)),ge.success(`Follow-up de ${o.nome} marcado como realizado.`)},Qe=it.slice(G*Yt,G*Yt+Yt),xt=Math.max(1,Math.ceil(it.length/Yt)),He=o=>({...o,...W[o.id]||{}}),We=(o,r)=>P(u=>({...u,[o]:{...u[o]||{},...r}})),Ie=(o,r)=>{if(r==="compareceu"&&o.data_agendamento&&o.data_agendamento>Re()){const u=(o.telefone||"").replace(/\D/g,"").slice(-11),I=S.filter(x=>x.id!==o.id&&x.compareceu&&(x.telefone||"").replace(/\D/g,"").slice(-11)===u&&!!x.data_agendamento&&x.data_agendamento<=Re()).map(x=>x.data_agendamento).sort().at(-1);_e({id:o.id,originalDate:o.data_agendamento,actualDate:I||Re(),suggestedDate:I});return}We(o.id,{status:r,compareceu:r==="compareceu",compareceu_origem:r==="compareceu"?"gestao":o.compareceu_origem})},jt=()=>{if(Fe){if(!Fe.actualDate||Fe.actualDate>Re())return ge.error("A data da visita não pode ser futura.");We(Fe.id,{data_agendamento:Fe.actualDate,data_anterior:Fe.originalDate,status:"compareceu",compareceu:!0,compareceu_origem:"gestao"}),_e(null),ge.info("Data real preenchida. Clique em salvar para confirmar o comparecimento.")}},ct=(o,r)=>{M(u=>{const I={...u};return r?I[o]=r:delete I[o],I}),p(0)},Et=(o,r)=>{d(u=>u&&u.key===o&&u.dir===r?null:{key:o,dir:r}),p(0)},gt=o=>{d(r=>!r||r.key!==o?{key:o,dir:"asc"}:r.dir==="asc"?{key:o,dir:"desc"}:null),p(0)},Ee=()=>{M({}),d(null),Ce(""),Se(null),p(0)},ht=Object.keys(A).length+(f?1:0)+(we?1:0),Ot=async o=>{const r={...W[o.id],historico:!1},u=(r.nome??o.nome??"").trim();if(!u)return ge.error("Preencha o nome do cliente antes de salvar.");if(/^[\d\s+()-]+$/.test(u))return ge.error("O nome não pode ser só números.");const I=r.data_agendamento??o.data_agendamento,x=r.unidade??o.unidade;if(!I)return ge.error("Informe a data do agendamento antes de salvar.");if(!x||x==="VC1+VC2")return ge.error("Escolha uma unidade válida antes de salvar.");const he={...r,nome:u,data_agendamento:I,unidade:x,criado_por_origem:"gestao"},fe=o.id.startsWith("novo-"),tt=!fe&&!!o.data_agendamento&&(o.data_agendamento!==I||r.horario!==void 0&&r.horario!==o.horario);let lt=fe?null:o.id;if(fe){const{data:k}=await w.rpc("ci_find_open_person",{p_planilha:o.planilha,p_telefone:(r.telefone??o.telefone)||"",p_nome:u,p_data:I});k&&(lt=k)}const{vendedor:vt,...t}=he,h=lt?await w.from("comercial_interno_agendamentos").update(fe?{...t,criado_por_origem:void 0,vendedor:he.vendedor??o.vendedor}:he).eq("id",lt).select("*").maybeSingle():await w.from("comercial_interno_agendamentos").insert({...o,...he,id:void 0}).select("*").maybeSingle();let b=h.data;const y=h.error;if(y)return ge.error("Não salvou: "+y.message);if(!b){let k=lt;if(!k){const{data:oe}=await w.rpc("ci_find_open_person",{p_planilha:o.planilha,p_telefone:(r.telefone??o.telefone)||"",p_nome:u,p_data:I});k=oe||null}if(k){const{data:oe}=await w.from("comercial_interno_agendamentos").select("*").eq("id",k).maybeSingle();b=oe}if(!b)return P(oe=>{const q={...oe};return delete q[o.id],q}),fe&&N(oe=>oe.filter(q=>q.id!==o.id)),ge.success("Salvo."),et()}N(k=>{const oe=k.filter(q=>q.id!==o.id&&q.id!==b.id);return k.some(q=>q.id===b.id)&&!fe?k.map(q=>q.id===b.id?b:q):[b,...oe]}),P(k=>{const oe={...k};return delete oe[o.id],oe}),ge.success(fe&&lt?"Essa pessoa já tinha agendamento aberto: a linha dela foi atualizada.":tt?"Remarcado na mesma linha.":"Salvo e enviado para a agenda")},a=async(o,r)=>
36{const u=o.comparecimento_alerta,I=r?{compareceu:!0,compareceu_origem:"receita",comparecimento_alerta:null}:{comparecimento_alerta:null,alertas_descartados:[...o.alertas_descartados||[],u==null?void 0:u.exam_id].filter(Boolean)},{data:x,error:he}=await w.from("comercial_interno_agendamentos").update(I).eq("id",o.id).select("*").maybeSingle();if(he)return ge.error("Não salvou: "+he.message);N(fe=>fe.map(tt=>tt.id===o.id?x??{...tt,...I}:tt)),ge.success(r?"Comparecimento confirmado":"Alerta descartado")},C=async o=>{if(o.id.startsWith("novo-")){N(I=>I.filter(x=>x.id!==o.id)),U(null),ne(null);return}const{data:r,error:u}=await w.from("comercial_interno_agendamentos").update({status:"cancelado"}).eq("id",o.id).select("*").maybeSingle();if(u)return ge.error("Não cancelou: "+u.message);N(I=>I.map(x=>x.id===o.id?r??{...x,status:"cancelado"}:x)),U(null),ge.success("Agendamento cancelado e preservado no histórico.")},X=async()=>{if(Me)return;$e(!0);const o=n==="ALL"?O!=="todos"?O:"Monique":n,r=`novo-${Date.now()}`,u={id:r,planilha:c,vendedor:o,nome:"",data_registro:Re(),telefone:null,unidade:null,data_agendamento:Re(),horario:"09:30",compareceu:!1,venda:!1,observacao:null,historico:!1,appointment_id:null,
36status:"agendado"};N(I=>[u,...I]),P(I=>({...I,[r]:{nome:""}})),ue("todos"),Ye("todas"),Y(n==="ALL"?"todos":n),M({}),d(null),Ce(""),V(""),Se(null),p(0),ne(r),U(null),ge.info("Preencha nome, unidade, data e hora. A linha só será criada ao salvar."),$e(!1)},Q=async()=>{const o=!B,{error:r}=await w.from("comercial_interno_config").update({importacao_planilhas_ativa:o,updated_by:s}).eq("id",!0);if(r)return ge.error("Não foi possível alterar a importação.");ce(o),ge.success(o?"Importação ligada.":"Importação pausada.")},H=()=>ea(`comercial-interno-${c}.csv`,it.map(o=>({Data:o.data_registro||"",Nome:o.nome,Telefone:o.telefone||"",Unidade:o.unidade||"","Data agend.":o.data_agendamento||"",Horário:(o.horario||"").slice(0,5),Compareceu:o.compareceu?"Compareceu":"Não compareceu",Venda:o.venda?"Sim":"Não",Vendedor:o.vendedor,Observação:o.observacao||""}))),ee=[{key:"data_registro",label:"Data",w:"w-[8%]"},{key:"nome",label:"Nome",w:"w-[15%]"},{key:"telefone",label:"Telefone",w:"w-[11%]"},{key:"unidade",label:"Unidade",w:"w-[7%]"},{key:"data_agendamento",label:"Data agend.",w:"w-[10%]"},{key:"horario",label:"Hora",w:"w-[7%]"},{key:"compareceu",label:"Compareceu",w:"w-[12%]"},{key:"venda",label:"Venda",w:"w-[6%]",center:!0},{key:"vendedor",label:"Vendedor",w:"w-[8%]"},{key:"observacao",label:"Observação",w:""}];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-bold text-[#101935] mr-2",children:"Comercial Interno"}),i.map(o=>e.jsx("button",{onClick:()=>g(o),className:`px-3 py-1.5 rounded-lg text-sm font-medium ${c===o?"bg-[#3B176B] text-white":"bg-white border text-gray-600"}`,children:o==="ob"?"Agendamentos OB":"Bio Opto"},o)),e.jsx("div",{className:"flex-1"}),n==="ALL"&&e.jsx(nt,{variant:"outline",size:"sm",onClick:Q,children:B?"Importação ligada":"Importação pausada"}),e.jsxs(nt,{size:"sm",onClick:X,disabled:Me,children:[Me?e.jsx(Be,{className:"w-4 h-4 animate-spin"}):e.jsx(va,{className:"w-4 h-4"}),"Novo agendamento"]}),e.jsxs("button",{onClick:H,className:"flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm border bg-white text-gray-700",children:[e.jsx(kt,{className:"w-4 h-4"}),"Excel"]})]}),e.jsxs("div",{className:"flex flex-nowrap gap-1.5",children:[[{id:"all",label:"Agendamentos",v:ae.total,on:me===null},{id:"comp",label:"Compareceram",v:ae.comp,on:me==="comp"},{id:"venda",label:"Vendas",v:ae.venda,on:me==="venda"},{id:"futuros",label:"Próximos",v:ae.futuros,on:me==="futuros"},{id:"verificar",label:"A verificar",v:ae.verificar,on:me==="verificar"}].map(o=>e.jsxs("button",{onClick:()=>{Se(r=>o.id==="all"||r===o.id?null:o.id),ke(!1),p(0)},title:o.id==="all"?"Mostrar todos os agendamentos":`Mostrar somente ${o.label.toLowerCase()}`,className:`flex-1 min-w-0 flex items-baseline justify-between gap-1 rounded-lg border px-2 py-1.5 text-left transition-colors ${o.on?"bg-[#E8530E]/10 border-[#E8530E]":"bg-white border-gray-200 hover:border-gray-300"}`,children:[e.jsx("span",{className:`text-[10px] uppercase truncate ${o.on?"text-[#E8530E]":"text-gray-500"}`,children:o.label}),e.jsx("span",{className:`text-base font-bold shrink-0 ${o.on?"text-[#E8530E]":"text-[#101935]"}`,children:o.v})]},o.id)),e.jsxs("button",{onClick:()=>{ke(o=>!o),Se(null),p(0)},title:"Clientes dos últimos 30 dias que faltaram e ainda não receberam o contato",className:`flex-1 min-w-0 flex items-baseline justify-between gap-1 rounded-lg border px-2 py-1.5 text-left transition-colors ${Ge?"bg-orange-500 border-orange-600":Ue.length>0?"bg-orange-50 border-orange-400 hover:border-orange-500":"bg-white border-gray-200 hover:border-gray-300"}`,children:[e.jsx("span",{className:`text-[10px] uppercase truncate ${Ge?"text-white":Ue.length>0?"text-orange-600":"text-gray-500"}`,children:"Não compareceu"}),e.jsx("span",{className:`text-base font-bold shrink-0 ${Ge?"text-white":Ue.length>0?"text-orange-600":"text-[#101935]"}`,children:Ue.length})]})]}),n==="ALL"&&ot.length>0&&e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:ot.map(o=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-white px-3 py-2 text-sm",children:[e.jsx("strong",{className:"text-[#101935]",children:o.vendedor}),e.jsxs("span",{className:"text-gray-600",children:[o.total," agendamentos · ",o.attended," 
36comparecimentos · ",o.rate,"%"]})]},o.vendedor))}),ae.semData>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:[e.jsxs("span",{children:[e.jsx("strong",{children:ae.semData})," pendência",ae.semData>1?"s":"",": falta a data do agendamento."]}),e.jsx("button",{onClick:()=>{M(o=>({...o,data_agendamento:["(vazio)"]})),ue("todos"),p(0)},className:"font-semibold underline",children:"Completar agora"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[[["mes","Mês atual"],["hoje","Agendados hoje"],["ativos","Ativos (a realizar)"],["todos","Todos"],["custom","Período"]].map(([o,r])=>e.jsx("button",{onClick:()=>{ue(o),o==="hoje"&&d({key:"data_agendamento",dir:"asc"}),p(0)},className:`px-3 py-1.5 rounded-lg text-xs font-semibold border ${K===o?"bg-[#101935] text-white border-[#101935]":"bg-white text-gray-600"}`,children:r},o)),K==="custom"&&e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("input",{type:"date",value:j,onChange:o=>{D(o.target.value),p(0)},className:"px-2 py-1.5 text-xs border rounded-lg bg-white"}),e.jsx("span",{className:"text-gray-500",children:"até"}),e.jsx("input",{type:"date",value:z,onChange:o=>{v(o.target.value),p(0)},className:"px-2 py-1.5 text-xs border rounded-lg bg-white"})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(ta,{className:"w-4 h-4 absolute left-2 top-2 text-gray-400"}),e.jsx("input",{value:$,onChange:o=>{V(o.target.value),p(0)},placeholder:"Buscar nome, telefone ou unidade",className:"w-full pl-8 pr-2 py-1.5 text-sm border rounded-lg bg-white text-gray-700"})]}),n==="ALL"&&e.jsxs("select",{value:O,onChange:o=>{Y(o.target.value),p(0)},className:"px-2 py-1.5 text-sm border rounded-lg bg-white text-gray-700",children:[e.jsx("option",{value:"todos",children:"Todos vendedores"}),e.jsx("option",{children:"Monique"}),c==="ob"&&e.jsx("option",{children:"Emilly"})]}),e.jsxs("select",{value:Pe,onChange:o=>{Ye(o.target.value),p(0)},className:"px-2 py-1.5 text-sm border rounded-lg bg-white text-gray-700",children:[e.jsx("option",{value:"propria",children:"Lojas próprias"}),e.jsx("option",{value:"franquia",children:"Franquias"}),e.jsx("option",{value:"todas",children:"Todas as lojas"})]}),we&&e.jsxs("span",{className:"flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-semibold bg-[#E8530E]/10 text-[#E8530E] border border-[#E8530E]/40",children:['Cliente: "',we,'"',e.jsx("button",{onClick:()=>{Ce(""),p(0)},className:"ml-1 font-bold hover:opacity-70",title:"Remover filtro de cliente",children:"×"})]}),ht>0&&e.jsxs("button",{onClick:Ee,className:"px-3 py-1.5 rounded-lg text-xs font-semibold border border-[#E8530E] text-[#E8530E] bg-white",children:["Limpar ",ht," filtro",ht>1?"s":""," de coluna"]})]}),L?e.jsx("div",{className:"py-16 flex justify-center",children:e.jsx(Be,{className:"w-6 h-6 animate-spin text-[#E8530E]"})}):e.jsx("div",{className:"bg-white rounded-xl border overflow-x-auto min-h-[360px] max-h-[65vh] overflow-y-auto",children:e.jsxs("table",{className:"w-full min-w-[1000px] table-fixed text-[11px]",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500 uppercase text-[10px] sticky top-0 z-10 shadow-sm",children:e.jsxs("tr",{children:[ee.map(o=>e.jsx("th",{className:`${o.w} p-1.5 ${o.center?"text-center":"text-left"}`,children:e.jsxs("div",{className:`flex items-center gap-0.5 ${o.center?"justify-center":""}`,children:[e.jsxs("button",{onClick:()=>gt(o.key),title:"Clique para ordenar em ordem crescente; clique novamente para inverter",className:`flex items-center gap-0.5 min-w-0 truncate hover:text-[#E8530E] ${(f==null?void 0:f.key)===o.key?"text-[#E8530E]":""}`,children:[e.jsx("span",{className:"truncate",title:o.label,children:o.label}),(f==null?void 0:f.key)===o.key&&(f.dir==="asc"?e.jsx(vs,{className:"w-3 h-3 shrink-0"}):e.jsx(js,{className:"w-3 h-3 shrink-0"}))]}),e.jsx("div",{className:"relative",children:e.jsx($n,{colKey:o.key,rows:S,active:A[o.key],open:ie===o.key,sortDir:(f==null?void 0:f.key)===o.key?f.dir:null,onToggle:()=>se(r=>r===o.key?null:o.key),onClose:()=>se(null),onChange:r=>ct(o.key,r),onSort:r=>Et(o.key,r),onTextFilter:o.key==="nome"?r=>{Ce(r),p(0)}:void 0})})]})},o.key)),e.jsx("th",{className:"w-[8%] p-1.5 text-center",children:"Ações"})]})}),e.jsxs("tbody",{children:[Qe.map(o=>{const r=He(o),u=!!W[r.id],I=(r.data_agendamento||"")>=Re()&&!r.compareceu;return e.jsxs("tr",{"data-row-id":r.id,"data-new":J===r.id?"1":void 0,className:`border-t hover:bg-gray-50 ${u?"bg-orange-50":""} ${r.compareceu?"bg-green-50/50":""} ${J===r.id?"ring-2 ring-inset ring-[#E8530E]/40":""}`,children:[e.jsx("td",{className:"p-1",children:e.jsx("input",{type:"date",className:ut,value:r.data_registro||"",onChange:x=>We(r.id,{data_registro:x.target.value||null})})}),e.jsx("td",{className:"p-1",children:e.jsx("input",{className:ut+" font-medium",value:r.nome,title:r.nome,onChange:x=>We(r.id,{nome:x.target.value})})}),e.jsx("td",{className:"p-1",children:e.jsx("input",{className:ut,value:Cs(r.telefone),title:r.telefone||"",onChange:x=>We(r.id,{telefone:x.target.value.replace(/\D/g,"")})})}),e.jsx("td",{className:"p-1",children:e.jsxs("select",{className:ut+" text-center font-semibold",title:r.unidade==="VC1+VC2"?"Sem prova da loja: conta metade em VC1 e metade em VC2":void 0,value:r.unidade||"",onChange:x=>We(r.id,{unidade:x.target.value}),children:[e.jsx("option",{value:"",children:"Escolher"}),r.unidade==="VC1+VC2"&&e.jsx("option",{value:"VC1+VC2",children:"VC1+VC2 (½ cada)"}),c==="bioopto"&&r.unidade&&!xa.includes(r.unidade)&&r.unidade!=="VC1+VC2"&&e.jsx("option",{value:r.unidade,children:r.unidade}),(c==="bioopto"?R.filter(x=>xa.includes(x.sigla)):R).map(x=>e.jsx("option",{value:x.sigla,children:x.sigla},x.sigla))]})}),e.jsx("td",{className:`p-1 ${I?"bg-orange-100/60 rounded":""}`,children:e.jsx("input",{type:"date",className:ut,value:r.data_agendamento||"",onChange:x=>We(r.id,{data_agendamento:x.target.value||null})})}),e.jsx("td",{className:"p-1",children:e.jsx("input",{type:"time",className:ut,value:(r.horario||"").slice(0,5),onChange:x=>We(r.id,{horario:x.target.value||null})})}),e.jsxs("td",{className:"p-1",children:[e.jsx("select",{title:r.compareceu&&r.compareceu_origem?`Marcado por: ${ss[r.compareceu_origem]||r.compareceu_origem}`:"",disabled:r.status==="sem_data",className:`${ut} font-semibold ${r.status==="compareceu"?"text-green-700":r.status==="sem_data"?"text-amber-700":"text-gray-700"}`,value:r.status,onChange:x=>Ie(r,x.target.value),children:["agendado","a_atualizar","compareceu","nao_compareceu","cancelado","sem_data"].map(x=>e.jsx("option",{value:x,children:kn[x]},x))}),(r.remarcacoes||0)>0&&e.jsxs("div",{className:"mt-0.5 inline-block rounded bg-blue-100 px-1.5 py-0.5 text-[9px] font-bold leading-none text-blue-800",title:(r.historico_auditoria||[]).filter(x=>(x==null?void 0:x.acao)==="remarcado").map(x=>`${_t(x.de_data||x.data_anterior)}${x.de_horario?" "+String(x.de_horario).slice(0,5):""} → ${_t(x.para_data||x.nova_data)}${x.para_horario?" "+String(x.para_horario).slice(0,5):""}
36 · ${x.em?new Date(x.em).toLocaleString("pt-BR"):""}`).join(`
37`)||(r.data_anterior?`Data anterior: ${_t(r.data_anterior)}`:"Remarcado"),children:["remarcado ",r.remarcacoes,"x"]}),!r.compareceu&&r.comparecimento_alerta&&(()=>{var he,fe;const x=r.comparecimento_alerta;return e.jsxs("div",{className:"mt-1 rounded border border-amber-400 bg-amber-50 p-1 text-[10px] leading-tight text-amber-900",title:`Receita de ${x.paciente}${x.telefone?" · "+x.telefone:""} · ${x.unidade} · ${(he=x.data)==null?void 0:he.split("-").reverse().join("/")}${x.optometrista?" · "+x.optometrista:""}`,children:[e.jsx("div",{className:"font-bold",children:"⚠ Verificar: possível receita"}),e.jsxs("div",{className:"truncate",children:[x.paciente," · ",x.unidade," · ",(fe=x.data)==null?void 0:fe.split("-").reverse().slice(0,2).join("/")]}),e.jsxs("div",{className:"mt-0.5 flex gap-1",children:[e.jsx("button",{onClick:()=>a(o,!0),className:"rounded bg-green-600 px-1.5 py-0.5 font-bold text-white",children:"É ela"}),e.jsx("button",{onClick:()=>a(o,!1),className:"rounded bg-gray-200 px-1.5 py-0.5 text-gray-700",children:"Não é"})]})]})})(),Ge&&ze.has(r.id)&&e.jsxs("div",{className:"mt-1 rounded border border-orange-400 bg-orange-50 p-1 text-[10px] leading-tight text-orange-900",title:`Cliente não compareceu em ${_t(r.data_agendamento)} e precisa de follow-up`,children:[e.jsx("div",{className:"font-bold",children:"⚠ Follow-up pendente"}),e.jsxs("div",{className:"truncate",children:["Não compareceu · ",_t(r.data_agendamento)]}),e.jsxs("div",{className:"mt-0.5 flex gap-1",children:[r.telefone&&e.jsx("a",{href:`https://wa.me/55${r.telefone.replace(/\D/g,"").replace(/^55/,"")}`,target:"_blank",rel:"noreferrer",className:"rounded bg-green-600 px-1.5 py-0.5 font-bold text-white",children:"WhatsApp"}),e.jsx("button",{onClick:()=>$t(o),className:"rounded bg-orange-500 px-1.5 py-0.5 font-bold text-white",children:"Realizado"})]})]})]}),e.jsxs("td",{className:"p-1 text-center",title:r.venda&&r.venda_origem?`Marcado por: ${ss[r.venda_origem]||r.venda_origem}`:"",children:[e.jsx("input",{type:"checkbox",checked:r.venda,disabled:r.venda_origem==="central",title:r.venda_origem==="central"?"Marcada pela Central de Conferência (venda aprovada)":"",onChange:x=>We(r.id,{venda:x.target.checked,venda_origem:"gestao",...x.target.checked?{compareceu:!0,status:"compareceu",compareceu_origem:"gestao"}:{}})}),r.venda&&r.venda_origem==="central"&&e.jsx("div",{className:"text-[9px] leading-none text-green-700 font-semibold",children:"Central"})]}),e.jsx("td",{className:"p-1",children:n==="ALL"?e.jsxs("select",{className:ut,value:r.vendedor,onChange:x=>We(r.id,{vendedor:x.target.value}),children:[e.jsx("option",{children:"Monique"}),c==="ob"&&e.jsx("option",{children:"Emilly"})]}):r.vendedor}),e.jsx("td",{className:"p-1",children:e.jsx("input",{className:ut,value:r.observacao||"",title:r.observacao||"",onChange:x=>We(r.id,{observacao:x.target.value})})}),e.jsx("td",{className:"p-1 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[u&&e.jsx("button",{onClick:()=>Ot(o),title:"Salvar",className:"p-1 rounded bg-[#E8530E] text-white",children:e.jsx(fs,{className:"w-3.5 h-3.5"})}),_===r.id?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>C(o),className:"px-2 py-0.5 rounded bg-red-600 text-white text-[10px] font-bold whitespace-nowrap",children:r.id.startsWith("novo-")?"Descartar":"Cancelar"}),e.jsx("button",{onClick:()=>U(null),title:"Cancelar",className:"p-0.5 rounded border border-gray-300 text-gray-500 hover:bg-gray-100 bg-white",children:e.jsx(wt,{className:"w-3 h-3"})})]}):e.jsx("button",{onClick:()=>U(r.id),title:r.id.startsWith("novo-")?"Descartar rascunho":"Cancelar sem apagar",className:"p-1 rounded text-gray-300 hover:text-red-600 hover:bg-red-50",children:e.jsx(ba,{className:"w-3.5 h-3.5"})})]})})]},r.id)}),!Qe.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:12,className:"p-8 text-center text-gray-400",children:"Nenhum agendamento."})})]})]})}),xt>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx("button",{disabled:G===0,onClick:()=>p(o=>
37o-1),className:"px-3 py-1 border rounded disabled:opacity-40",children:"Anterior"}),e.jsxs("span",{children:["Página ",G+1," de ",xt]}),e.jsx("button",{disabled:G+1>=xt,onClick:()=>p(o=>o+1),className:"px-3 py-1 border rounded disabled:opacity-40",children:"Próxima"})]}),Fe&&e.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/40 p-4",role:"dialog","aria-modal":"true","aria-labelledby":"early-visit-title",children:e.jsxs("div",{className:"w-full max-w-sm rounded-lg border bg-white p-4 shadow-xl",children:[e.jsx("h3",{id:"early-visit-title",className:"text-base font-bold text-[#101935]",children:"Veio antes da data?"}),e.jsx("p",{className:"mt-1 text-sm text-gray-600",children:"Em que dia aconteceu o comparecimento?"}),Fe.suggestedDate&&e.jsxs("p",{className:"mt-2 rounded-md border border-green-200 bg-green-50 px-2 py-1.5 text-xs text-green-800",children:["Sugestão: outro agendamento deste telefone compareceu em ",_t(Fe.suggestedDate),"."]}),e.jsx("input",{type:"date",max:Re(),value:Fe.actualDate,onChange:o=>_e(r=>r?{...r,actualDate:o.target.value}:null),className:"mt-3 w-full rounded-md border bg-white px-3 py-2 text-sm text-gray-800"}),e.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[e.jsx(nt,{variant:"outline",size:"sm",onClick:()=>_e(null),children:"Cancelar"}),e.jsx(nt,{size:"sm",onClick:jt,children:"Usar esta data"})]})]})})]})},An=()=>new Date(Date.now()-3*36e5).toISOString().slice(0,7);function Mn({userId:s}){const[n,i]=l.useState(An()),[c,g]=l.useState([]),[S,N]=l.useState(!1),[L,F]=l.useState(null),[$,V]=l.useState({}),[O,Y]=l.useState(!1),[K,ue]=l.useState(""),j=async()=>{var A,M,ie,se;N(!0),F(null);const{data:p,error:W}=await w.functions.invoke(`conciliacao-comparecimento?mes=${n}`,{method:"GET"});if(N(!1),W||!(p!=null&&p.ok)){F((W==null?void 0:W.message)||(p==null?void 0:p.error)||"Erro ao carregar");return}g(p.linhas);const P={};for(const f of p.linhas)P[f.loja]={a:((M=(A=f.central)==null?void 0:A.agendamentos)==null?void 0:M.toString())??"",c:((se=(ie=f.central)==null?void 0:ie.comparecimentos)==null?void 0:se.toString())??""};V(P)};l.useEffect(()=>{j()},[n]);const D=()=>{const p={...$};for(const W of K.split(`
38`)){const P=W.trim().split(/[\s;,\t]+/).filter(Boolean);if(P.length<3)continue;const A=P[0].toUpperCase()==="SUZ"?"SZN":P[0].toUpperCase(),M=P.slice(1).map(f=>f.replace(/\D/g,"")).filter(Boolean),[ie,se]=M.length>=3?[M[1],M[2]]:[M[0],M[1]];p[A]={a:ie,c:se}}V(p),ue("")},z=async()=>{Y(!0);const p=Object.entries($).filter(([,P])=>P.a!==""||P.c!=="").map(([P,A])=>({mes:`${n}-01`,unidade:P,agendamentos:A.a===""?null:Number(A.a),comparecimentos:A.c===""?null:Number(A.c),atualizado_por:s})),{error:W}=await w.from("central_conciliacao").upsert(p,{onConflict:"mes,unidade"});if(Y(!1),W){F(W.message);return}j()},v=l.useMemo(()=>c.reduce((p,W)=>{var P;return{feed:p.feed+W.feed.comparecimentos,central:p.central+(((P=W.central)==null?void 0:P.comparecimentos)??0),ci:p.ci+W.comercial_interno.comparecimentos}},{feed:0,central:0,ci:0}),[c]),G=p=>p==null?"text-gray-400":p===0?"text-green-700":Math.abs(p)<=3?"text-amber-600":"text-red-600";return e.jsxs("div",{className:"p-3 sm:p-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("h2",{className:"text-2xl font-bold",style:{color:"#101935"},children:"Conciliação de comparecimento"}),e.jsx("input",{type:"month",value:n,onChange:p=>i(p.target.value),className:"border rounded-lg px-3 py-1.5 text-sm"}),e.jsxs("button",{onClick:j,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm",children:[e.jsx(Dt,{className:"w-4 h-4"}),"Atualizar"]}),e.jsxs("button",{onClick:z,disabled:O,className:"flex items-center gap-1.5 px-4 py-1.5 rounded-lg text-sm font-semibold text-white",style:{background:"#E8530E"},children:[O?e.jsx(Be,{className:"w-4 h-4 animate-spin"}):e.jsx(fs,{className:"w-4 h-4"}),"Salvar números da Central"]})]}),e.jsx("p",{className:"text-sm text-gray-500",children:"Feed = o que a Central recebe (pelo dia em que o cliente foi agendado). Central = números digitados da tela da Central. Comercial Interno = agendamentos da Monique e da Emilly."}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:[["Feed",v.feed],["Central",v.central],["Comercial Interno",Math.round(v.ci)]].map(([p,W])=>e.jsxs("div",{className:"rounded-xl border bg-white p-4",children:[e.jsxs("div",{className:"text-xs uppercase text-gray-500",children:[p," — comparecimentos"]}),e.jsx("div",{className:"text-2xl font-bold",style:{color:"#101935"},children:W})]},p))}),e.jsxs("details",{className:"rounded-xl border bg-white p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:"Colar números da Central"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Uma loja por linha: ",e.jsx("b",{children:"LOJA agendamentos comparecimentos"})," (ou leads, agendamentos, comparecimentos, como na tela da Central)."]}),e.jsx("textarea",{value:K,onChange:p=>ue(p.target.value),rows:5,className:"w-full border rounded-lg p-2 text-sm mt-2 font-mono",placeholder:`SBC2 416 84 44
39ITB 287 82 41`}),e.jsx("button",{onClick:D,className:"mt-2 px-3 py-1.5 rounded-lg border text-sm",children:"Aplicar na tabela"})]}),L&&e.jsx("div",{className:"text-sm text-red-600",children:L}),S?e.jsxs("div",{className:"flex items-center gap-2 text-gray-500",children:[e.jsx(Be,{className:"w-4 h-4 animate-spin"}),"Carregando…"]}):e.jsx("div",{className:"overflow-x-auto rounded-xl border bg-white",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-50 text-xs uppercase text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-2 text-left",children:"Loja"}),e.jsx("th",{className:"p-2 text-right",children:"Feed agend."}),e.jsx("th",{className:"p-2 text-right",children:"Feed comp."}),e.jsx("th",{className:"p-2 text-left",children:"Origem (venda / receita / marcação)"}),e.jsx("th",{className:"p-2 text-right",children:"Central agend."}),e.jsx("th",{className:"p-2 text-right",children:"Central comp."}),e.jsx("th",{className:"p-2 text-right",children:"Com. Interno comp."}),e.jsx("th",{className:"p-2 text-right",children:"Dif."}),e.jsx("th",{className:"p-2 text-left",children:"Motivo da divergência"})]})}),e.jsx("tbody",{children:c.map(p=>{var W,P;return e.jsxs("tr",{className:"border-t align-top",children:[e.jsx("td",{className:"p-2 font-semibold",children:p.loja}),e.jsx("td",{className:"p-2 text-right",children:p.feed.agendamentos}),e.jsx("td",{className:"p-2 text-right font-semibold",children:p.feed.comparecimentos}),e.jsxs("td",{className:"p-2 text-gray-500",children:[p.feed.por_venda," / ",p.feed.por_receita," / ",p.feed.por_marcacao]}),e.jsx("td",{className:"p-2 text-right",children:e.jsx("input",{className:"w-16 border rounded px-1 text-right",value:((W=$[p.loja])==null?void 0:W.a)??"",onChange:A=>V({...$,[p.loja]:{...$[p.loja]??{a:"",c:""},a:A.target.value.replace(/\D/g,"")}})})}),e.jsx("td",{className:"p-2 text-right",children:e.jsx("input",{className:"w-16 border rounded px-1 text-right",value:((P=$[p.loja])==null?void 0:P.c)??"",onChange:A=>V({...$,[p.loja]:{...$[p.loja]??{a:"",c:""},c:A.target.value.replace(/\D/g,"")}})})}),e.jsx("td",{className:"p-2 text-right",children:p.comercial_interno.comparecimentos}),e.jsx("td",{className:`p-2 text-right font-bold ${G(p.diferenca_feed_central)}`,children:p.diferenca_feed_central==null?"—":p.diferenca_feed_central>0?`+${p.diferenca_feed_central}`:p.diferenca_feed_central}),e.jsx("td",{className:"p-2 text-xs text-gray-600 max-w-md",children:e.jsx("ul",{className:"list-disc pl-4 space-y-0.5",children:p.motivos.map((A,M)=>e.jsx("li",{children:A},M))})})]},p.loja)})})]})})]})}const ls=({color:s="#E8530E",className:n="",compact:i})=>{const[c,g]=l.useState(Bs()),[S]=l.useState(Ls());if(l.useEffect(()=>Is(g),[]),S)return null;const N="inline-flex items-center justify-center gap-2 rounded-xl font-semibold text-white transition-opacity hover:opacity-90 "+(i?"px-3 py-2 text-xs":"px-4 py-2.5 text-sm w-full sm:w-auto");return c?e.jsxs("button",{type:"button",onClick:()=>{Ts()},className:`${N} ${n}`,style:{background:s},children:[e.jsx(kt,{className:"w-4 h-4"}),"Instalar no celular"]}):e.jsxs(Us,{to:"/instalar",className:`${N} ${n}`,style:{background:s},children:[e.jsx(us,{className:"w-4 h-4"}),"Instalar no celular"]})},Ss=Ys.url,Fs="b2b9df16-22a7-44b2-9fab-b5c34dbda550",Na="02f47f67-cbf5-4b62-b732-d35e1cb4ff96",rs=(s,n)=>{const i=n!=null&&n.os_numero?String(n.os_numero).replace(/\D/g,""):"",c=n!=null&&n.observacao?String(n.observacao):"";if(i||c)return{os:i||null,obs:c||null};const g=(s||"").trim();if(!g)return{os:null,obs:null};const S=g.replace(/\D/g,"");if(/^\d{2,6}$/.test(g))return{os:g,obs:null};const N=g.match(/(?:^|\bos[:\s#-]*)(\d{2,6})\b/i);if(N){const L=g.replace(N[0],"").trim().replace(/^[·,;–-]\s*/,"");return{os:N[1],obs:L||null}}return{os:S.length>=2&&S.length<=6&&S===g?g:null,obs:g}},Tt=s=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",maximumFractionDigits:0}).format(s),ga={scheduled:{label:"Agendado",dot:"bg-blue-400"},confirmed:{label:"Confirmado",dot:"bg-cyan-400"},attended:{label:"Compareceu",dot:"bg-emerald-500"},attended_no_budget:{label:"Compareceu (sem orçamento)",dot:"bg-
39amber-500"},completed:{label:"Concluído",dot:"bg-green-500"},cancelled:{label:"Cancelado",dot:"bg-red-400"},no_show:{label:"Falta",dot:"bg-orange-400"},pending:{label:"Pendente",dot:"bg-gray-400"}};async function is(s){const n=new Set,i=s===Na?"OB":"OV";let c=0;const g=1e3;for(;;){const{data:S,error:N}=await w.from("conversations").select("contact_id").or(`channel_id.eq.${s},brand_queue.eq.${i}`).not("contact_id","is",null).range(c,c+g-1);if(N||!S||S.length===0||(S.forEach(L=>L.contact_id&&n.add(L.contact_id)),S.length<g))break;c+=g}return n}function Bn(s,n,i){const c=`${s||""} ${n||""}`.toUpperCase();return i.find(g=>new RegExp(`\\b${g}\\b`).test(c))||"—"}function cs(s){const n=String(s??"").trim();if(!n)return"—";const i=n.toLowerCase().replace(/[\s._-]/g,"");return i.includes("bioopto")||i.includes("biopto")?"Monique":n}function yt(s){const n=(s||"").toLowerCase();return!n||n==="—"?null:n.includes("biopto")||n.includes("bio opto")||n.includes("bio-opto")?{label:"Monique",cls:"bg-emerald-50 text-emerald-600 border-emerald-200"}:n.includes("gabriel")||n.includes("victoria")||n.includes("vitoria")?{label:"O.V",cls:"bg-orange-50 text-orange-600 border-orange-200"}:n.includes("monique")||n.includes("emily")||n.includes("emilly")||n.includes("emili")?{label:"Exame de vista gratuito",cls:"bg-violet-50 text-violet-600 border-violet-200"}:n.includes("deise")?{label:"Reativação",cls:"bg-sky-50 text-sky-600 border-sky-200"}:null}function Ln(s,n){if(!s)return null;if(s===Fs)return{label:"O.V",cls:"bg-orange-50 text-orange-600 border-orange-200"};if(s===Na)return{label:"Exame de vista gratuito",cls:"bg-violet-50 text-violet-600 border-violet-200"};const i=(n||"").toLowerCase();return i.includes("reativ")?{label:"Reativação",cls:"bg-sky-50 text-sky-600 border-sky-200"}:i.includes("instagram")?{label:"Instagram",cls:"bg-pink-50 text-pink-600 border-pink-200"}:i.includes("kommo")?{label:"Kommo",cls:"bg-teal-50 text-teal-600 border-teal-200"}:n?{label:n,cls:"bg-slate-50 text-slate-600 border-slate-200"}:null}async function Ft(s){try{const{data:n}=await w.auth.getUser(),i=n==null?void 0:n.user;if(!i)return;s.entityId&&await w.from("manager_updates").delete().eq("entity_id",s.entityId).eq("action",s.action).eq("user_id",i.id),await w.from("manager_updates").insert({user_id:i.id,manager_email:i.email??null,manager_name:s.profile.store_name||i.email||"Gerente",store_sigla:s.profile.store_sigla,action:s.action,title:s.title,detail:s.detail??null,entity_type:s.entityType??null,entity_id:s.entityId??null,metadata:s.metadata??{}})}catch(n){console.error("[manager_updates] log falhou",n)}}function ks(){l.useEffect(()=>{const s=document.documentElement,n=document.body,i=s.className,c=n.className,g=()=>{s.classList.remove("dark"),s.classList.add("light"),n.classList.remove("dark"),n.classList.add("light")};g();const S=new MutationObserver(()=>{s.classList.contains("dark")&&g()});return S.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>{S.disconnect(),s.className=i,n.className=c}},[])}const In=({onLogin:s})=>{ks();const[n,i]=l.useState(""),[c,g]=l.useState(""),[S,N]=l.useState(!1),[L,F]=l.useState(""),$=async V=>{V.preventDefault(),F(""),N(!0);try{const{error:O}=await w.auth.signInWithPassword({email:n,password:c});if(O){F("E-mail ou senha incorretos.");return}s()}catch{F("Erro inesperado.")}finally{N(!1)}};return e.jsx("div",{style:{background:"#F5F7FB",minHeight:"100vh",colorScheme:"light"},className:"flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-sm",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("img",{src:Ss,alt:"Videre atendimento",width:1024,height:1024,className:"mx-auto mb-4 h-20 w-20 rounded-2xl object-cover"}),e.jsx("h1",{className:"text-2xl font-bold",style:{color:"#101935"},children:"Videre atendimento"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Agendamentos e receitas · Acesso restrito"})]}),e.jsxs("form",{onSubmit:$,style:{background:"#fff",border:"1px solid #F0F2F8"},className:"rounded-2xl shadow-sm p-6 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"E-mail"}),e.jsx("input",{type:"email",required:!0,value:n,onChange:V=>i(V.target.value),placeholder:"[email protected]",style:{background:"#fff",color:"#101935",border:"1px solid #E2E8F0"},className:"px-3 py-2.5 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#E8530E]/30 focus:border-[#
39E8530E]"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Senha"}),e.jsx("input",{type:"password",required:!0,value:c,onChange:V=>g(V.target.value),placeholder:"••••••••",style:{background:"#fff",color:"#101935",border:"1px solid #E2E8F0"},className:"px-3 py-2.5 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#E8530E]/30 focus:border-[#E8530E]"})]}),L&&e.jsx("p",{className:"text-xs text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2",children:L}),e.jsx("button",{type:"submit",disabled:S,className:"w-full py-2.5 bg-[#E8530E] hover:bg-[#d44a0c] disabled:opacity-60 text-white font-semibold rounded-lg text-sm transition-colors flex items-center justify-center gap-2",children:S?e.jsx(Be,{className:"w-4 h-4 animate-spin"}):"Entrar"})]})]})})},Tn=s=>String(s||"").replace(/\D/g,""),Un=s=>{const n=Tn(s);return n?n.startsWith("55")?n:`55${n}`:""},Ds=({units:s,profile:n,onClose:i,onCreated:c})=>{const[g,S]=l.useState(""),[N,L]=l.useState(""),[F,$]=l.useState(s[0]||""),[V,O]=l.useState(qe(new Date,"yyyy-MM-dd")),[Y,K]=l.useState("09:00"),[ue,j]=l.useState(""),[D,z]=l.useState(""),[v,G]=l.useState([]),[p,W]=l.useState(!1),[P,A]=l.useState(null);l.useEffect(()=>{w.from("team_members").select("name, status").eq("status","active").then(({data:f})=>{const d=(f||[]).filter(_=>String(_.name||"").trim()).map(_=>String(_.name).trim()).filter(_=>!/^(nina|clara)/i.test(_));G([...new Set(d)].sort((_,U)=>_.localeCompare(U)))})},[]);const M=async()=>{var d,_;if(A(null),!g.trim())return A("Informe o nome do cliente.");if(/^[\d\s+()-]+$/.test(g.trim()))return A("O nome não pode ser só números. Coloque o telefone no campo Telefone.");const f=Un(N);if(f.length<12)return A("Telefone inválido. Use DDD + número.");if(!F)return A("Selecione a unidade.");if(!V||!Y)return A("Informe data e horário.");W(!0);try{const{data:U}=await w.auth.getUser(),J=((d=U==null?void 0:U.user)==null?void 0:d.id)||null,ne=f.replace(/^55/,""),{data:Me}=await w.from("contacts").select("id, name, phone_number").or(`phone_number.eq.${f},phone_number.eq.${ne},phone_number.eq.+${f}`).limit(1);let $e=(_=Me==null?void 0:Me[0])==null?void 0:_.id;if($e){const{error:Ce}=await w.from("contacts").update({name:g.trim(),phone_number:f}).eq("id",$e);if(Ce)throw Ce}if(!$e){const{data:Ce,error:me}=await w.from("contacts").insert({name:g.trim(),phone_number:f}).select("id").single();if(me)throw me;$e=Ce.id}const{error:we}=await w.from("appointments").insert({title:`Agendamento ${F} - ${g.trim()}`,description:ue.trim()||null,observations:ue.trim()||null,date:V,time:Y,type:"meeting",status:"scheduled",contact_id:$e,client_name:g.trim(),user_id:J,metadata:{store_sigla:F,store_sigla_source:"manager_portal",seller:D.trim()||"Sem vendedor",brand:"OB",canal:"O.B",created_by_manager:!0,manager_store:n.store_sigla,source:"manager_portal"}});if(we)throw we;await Ft({profile:n,action:"agendamento",title:`${g.trim()} → Agendamento criado`,detail:`${V} ${Y} · ${F}`,entityType:"appointment",entityId:$e||null,metadata:{unit:F,date:V,time:Y,phone:f}}),c(),i()}catch(U){A((U==null?void 0:U.message)||"Não foi possível salvar o agendamento.")}finally{W(!1)}},ie="w-full px-3 py-2 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#E8530E]/30",se={background:"#fff",color:"#101935",border:"1px solid #E2E8F0"};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/40 p-0 sm:p-4",onClick:i,children:e.jsxs("div",{onClick:f=>f.stopPropagation(),style:{background:"#fff"},className:"w-full sm:max-w-md rounded-t-2xl sm:rounded-2xl shadow-xl p-5 max-h-[92vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-base font-bold",style:{color:"#101935"},children:"Novo agendamento"}),e.jsx("button",{onClick:i,className:"p-1 text-gray-400 hover:text-gray-600",children:e.jsx(wt,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold uppercase tracking-wider text-gray-400",children:"Nome do cliente"}),e.jsx("input",{className:ie,style:se,value:g,onChange:f=>S(f.target.value),placeholder:"Nome completo"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold uppercase tracking-wider text-gray-400",children:"Telefone (WhatsApp)"}),e.jsx("input",{className:ie,style:se,value:N,onChange:f=>L(f.target.value),placeholder:"11 99999-9999",inputMode:"tel"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold uppercase tracking-wider text-gray-400",children:"Unidade"}),e.jsxs("select",{className:ie,style:se,value:F,onChange:f=>$(f.target.value),children:[s.length===0&&e.jsx("option",{value:"",children:"—"}),s.map(f=>e.jsx("option",{value:f,children:f},f))]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold uppercase tracking-wider text-gray-400",children:"Data"}),e.jsx("input",{type:"date",className:ie,style:se,value:V,onChange:f=>O(f.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold uppercase tracking-wider text-gray-400",children:"Horário"}),e.jsx("input",{type:"time",className:ie,style:se,value:Y,onChange:f=>K(f.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold uppercase tracking-wider text-gray-400",children:"Consultor"}),e.jsxs("select",{className:ie,style:se,value:D,onChange:f=>z(f.target.value),children:[e.jsx("option",{value:"",children:"Sem vendedor"}),v.map(f=>e.jsx("option",{value:f,children:f},f))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold uppercase tracking-wider text-gray-400",children:"Observação / OS (opcional)"}),e.jsx("input",{className:ie,style:se,value:ue,onChange:f=>j(f.target.value),placeholder:"Ex.: exame de vista, criança 7 anos..."})]}),P&&e.jsx("div",{className:"text-xs text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2",children:P}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("button",{onClick:M,disabled:p,style:{background:"#E8530E"},className:"flex-1 flex items-center justify-center gap-2 text-white font-semibold rounded-lg px-4 py-2.5 text-sm disabled:opacity-60",children:[p?e.jsx(Be,{className:"w-4 h-4 animate-spin"}):e.jsx(Ut,{className:"w-4 h-4"}),"Salvar agendamento"]}),e.jsx("button",{onClick:i,className:"px-4 py-2.5 text-sm text-gray-500 rounded-lg",style:{border:"1px solid #E2E8F0"},children:"Cancelar"})]}),e.jsx("p",{className:"text-[11px] text-gray-400",children:"O agendamento a
39parece imediatamente no dashboard central e no funil de vendas."})]})]})})},qn=({storeSigla:s,storeName:n,profile:i})=>{const[c,g]=l.useState([]),[S,N]=l.useState(!0),[L,F]=l.useState(!1),[$,V]=l.useState(qe(new Date,"yyyy-MM")),[O,Y]=l.useState(""),[K,ue]=l.useState("all"),[j,D]=l.useState(!0),[z,v]=l.useState("all"),[G,p]=l.useState(""),[W,P]=l.useState(new Set),[A,M]=l.useState([]),[ie,se]=l.useState({vendas:0,receita:0}),[f,d]=l.useState(!1),_=l.useRef(null),U=l.useRef(0),J=s.toUpperCase().startsWith("BIOPTO:")?s.slice(s.indexOf(":")+1):s,ne=J.toUpperCase()==="ALL"?A:J.split("+").map(a=>a.trim().toUpperCase()).filter(Boolean);l.useEffect(()=>{w.from("stores").select("sigla").eq("is_active",!0).then(({data:a})=>{M((a||[]).map(C=>String(C.sigla||"").toUpperCase()).filter(Boolean))})},[]);const Me=l.useCallback(async()=>{if(_.current)return _.current;const[a,C]=await Promise.all([is(Fs),is(Na)]);return _.current={ov:a,ob:C},_.current},[]),$e=l.useCallback(async(a=!0)=>{a?N(!0):F(!0);const C=s.toUpperCase().startsWith("BIOPTO:"),X=C?s.slice(s.indexOf(":")+1):s,[Q,H]=$.split("-").map(Number),ee=qe(new Date(Q,H-1,1),"yyyy-MM-dd"),o=qe(new Date(Q,H,0),"yyyy-MM-dd"),r=m=>String(m||"").replace(/\D/g,"").replace(/^55/,""),u=new Set,I=new Set,x=new Set,he={},fe={},tt=Me(),lt=(async()=>{const m=[];for(let te=0;te<50;te++){const{data:T,error:Z}=await w.from("appointments").select("id, date, time, title, status, description, observations, contact_id, user_id, metadata, client_name").gte("date",ee).lte("date",o).order("date",{ascending:!0}).order("time",{ascending:!0}).order("id",{ascending:!0}).range(te*1e3,te*1e3+1e3-1);if(Z){console.error("[AgendamentosTab] appointments query error:",Z);break}if(!T||T.length===0||(m.push(...T),T.length<1e3))break}return m})(),vt=(async()=>{try{const{data:m}=await w.from("deals").select("contact_id, value, won_at, tags, loja, owner_id").not("won_at","is",null).contains("tags",["venda-importada"]).gte("won_at",new Date(Q,H-1,1).toISOString()).lte("won_at",new Date(Q,H,0,23,59,59).toISOString()).limit(5e3),E=[...new Set((m||[]).map(T=>T.contact_id).filter(Boolean))],te={};for(let T=0;T<E.length;T+=200){const{data:Z}=await w.from("contacts").select("id, name, call_name, phone_number").in("id",E.slice(T,T+200));(Z||[]).forEach(le=>{te[le.id]={phone:r(le.phone_number),name:le.call_name||le.name||"—"}})}(m||[]).forEach(T=>{const Z=te[T.contact_id],le=Z==null?void 0:Z.phone;if(!le)return;const xe=(T.tags||[]).includes("venda-importada");u.add(le),he[le]=(he[le]||0)+Number(T.value||0),xe&&(I.add(le),T.contact_id&&x.add(T.contact_id));const mt=fe[le];(!mt||xe&&!mt.imported)&&(fe[le]={phone:le,name:Z.name,value:0,loja:String(T.loja||"").toUpperCase()||"—",won_at:T.won_at,imported:xe,owner_id:T.owner_id||null,contact_id:T.contact_id}),fe[le].value=he[le],(!fe[le].loja||fe[le].loja==="—")&&(fe[le].loja=String(T.loja||"").toUpperCase()||"—")})}catch(m){console.error("[AgendamentosTab] won-by-phone query error:",m)}})(),[,t]=await Promise.all([vt,lt]),h=t.filter(m=>{var E;return!((E=m==null?void 0:m.metadata)!=null&&E.duplicado_de)}),b=[...new Set(h.map(m=>m.contact_id).filter(Boolean))],y=[...new Set(h.map(m=>m.user_id).filter(Boolean))],k={},oe={},q={},Oe={},re={},Ae={}
39,pe=new Set,Ne={},at={};await Promise.all([(async()=>{const m=[];for(let E=0;E<b.length;E+=200)m.push(b.slice(E,E+200));await Promise.all(m.map(async E=>{const{data:te}=await w.from("deals").select("contact_id, owner_id, won_at, loja").in("contact_id",E);(te||[]).forEach(T=>{if(T.contact_id&&(T.owner_id&&(Ne[T.contact_id]=T.owner_id),T.loja&&!at[T.contact_id]&&(at[T.contact_id]=String(T.loja).toUpperCase()),T.won_at)){const Z=new Date(T.won_at);Z>=new Date(Q,H-1,1)&&Z<=new Date(Q,H,0,23,59,59)&&pe.add(T.contact_id)}})}))})(),(async()=>{for(let m=0;m<b.length;m+=200){const{data:E,error:te}=await w.from("contacts").select("id, name, call_name, phone_number, created_at").in("id",b.slice(m,m+200));te&&console.error("[AgendamentosTab] contacts query error:",te),(E||[]).forEach(T=>{k[T.id]={name:T.name,call_name:T.call_name,phone_number:T.phone_number,created_at:T.created_at}})}})(),(async()=>{for(let m=0;m<y.length;m+=100){const{data:E}=await w.from("team_members").select("user_id, name").in("user_id",y.slice(m,m+100));(E||[]).forEach(te=>{te.user_id&&(oe[te.user_id]=te.name)})}})(),(async()=>{const{data:m}=await w.from("channels_safe").select("id, name");(m||[]).forEach(E=>{Oe[E.id]=E.name});for(let E=0;E<b.length;E+=200){const{data:te}=await w.from("conversations").select("id, contact_id, channel_id, last_message_at, created_at, metadata, updated_at").in("contact_id",b.slice(E,E+200)),T={};(te||[]).forEach(Z=>{var At;if(Z.id&&Z.contact_id&&(Ae[Z.id]=Z.contact_id),!Z.contact_id||!Z.channel_id)return;const le=Z.last_message_at||Z.created_at||"";(!T[Z.contact_id]||le>T[Z.contact_id])&&(T[Z.contact_id]=le,q[Z.contact_id]=Z.channel_id);const xe=(At=Z.metadata)==null?void 0:At.ultimo_orcamento,mt=String((xe==null?void 0:xe.data)||Z.updated_at||""),ft=Zs(xe==null?void 0:xe.valor),Vt=za(String((xe==null?void 0:xe.referencia)||(xe==null?void 0:xe.reference)||(xe==null?void 0:xe.linha)||(xe==null?void 0:xe.resumo)||""));ft!==null&&(!re[Z.contact_id]||mt>re[Z.contact_id].at)&&(re[Z.contact_id]={value:ft,at:mt,reference:Vt})})}})()]);const Je=Object.keys(Ae),Xe=()=>{const m=++U.current,E=[];for(let te=0;te<Je.length;te+=150)E.push(Je.slice(te,te+150));Promise.all(E.map(async te=>{const{data:T,error:Z}=await w.from("messages").select("conversation_id, content, sent_at").in("conversation_id",te).eq("from_type","human").or("content.ilike.%R$%,content.ilike.%valor%,content.ilike.%fica%,content.ilike.%total%").order("sent_at",{ascending:!1}).limit(3e3);return Z?(console.error("[AgendamentosTab] quote messages query error:",Z),[]):T||[]})).then(te=>{if(m!==U.current)return;const T={};te.flat().forEach(Z=>{const le=Ae[Z.conversation_id];if(!le)return;const xe=Gs(Z.content||""),mt=za(Z.content||""),ft=String(Z.sent_at||"");xe&&(!T[le]||ft>T[le].at)&&(T[le]={value:xe,at:ft,reference:mt})}),Object.keys(T).length&&g(Z=>Z.map(le=>{const xe=T[le.contact_id||""];return!xe||le.quoted_at&&le.quoted_at>xe.at?le:{...le,quoted_value:xe.value,quoted_at:xe.at,quote_reference:xe.reference}}))}).catch(te=>console.error("[AgendamentosTab] quote scan",te))},qt=await tt,aa=["EMILY","MONIQUE","CLARA"],Pt=(m,E)=>{const te=String((E==null?void 0:E.brand)||"").toUpperCase();if(te==="OB"||te==="BIOPTO")return"OB";if(te==="OV")return"OV";const T=String((E==null?void 0:E.seller)||"").toUpperCase();return aa.some(Z=>T.includes(Z))||qt.ob.has(m)?"OB":qt.ov.has(m)?"OV":"—"},Nt={},Rt=[...new Set([...Object.values(Ne),...Object.values(fe).map(m=>m.owner_id).filter(Boolean)])];for(let m=0;m<Rt.length;m+=100){const{data:E}=await w.from("team_members").select("id, name").in("id",Rt.slice(m,m+100));(E||[]).forEach(te=>
39{Nt[te.id]=te.name})}const de=h.map(m=>{var ft,Vt,At,Fa,ka,Da,$a,Oa,Aa,Ma,Ba,La;const E=k[m.contact_id]||null,te=(ft=m.metadata)!=null&&ft.store_sigla?String(m.metadata.store_sigla).toUpperCase():null,T=A.length>0?Bn(m.title||"",m.description,A):null,Z=te||T||at[m.contact_id||""]||"—",le=String(((Vt=m.metadata)==null?void 0:Vt.seller)||((At=m.metadata)==null?void 0:At.owner_name)||((Fa=m.metadata)==null?void 0:Fa.vendedor)||"").trim(),xe=String(((ka=m.metadata)==null?void 0:ka.brand)||"").toUpperCase()==="BIOPTO"||String(((Da=m.metadata)==null?void 0:Da.source)||"").toLowerCase().includes("biopto"),mt=String((($a=m.metadata)==null?void 0:$a.person_name)||((Oa=m.metadata)==null?void 0:Oa.name)||"").trim();return{id:m.id,contact_id:m.contact_id||"",contact_created:(E==null?void 0:E.created_at)||"",contact_name:mt||(m.client_name&&!/^\d+$/.test(String(m.client_name).trim())?String(m.client_name).trim():"")||(E==null?void 0:E.call_name)||(E==null?void 0:E.name)||"—",contact_phone:(E==null?void 0:E.phone_number)||"",unit:Z,date:m.date,time:m.time||"",status:m.status,seller_name:cs((xe?"Biopto":"")||m.user_id&&oe[m.user_id]||le||Nt[Ne[m.contact_id||""]||""]||"—"),description:m.description,observations:m.observations||null,os_numero:rs(m.observations||null,m.metadata).os,observacao:rs(m.observations||null,m.metadata).obs,brand:Pt(m.contact_id||"",m.metadata),channel:(xe?yt("Biopto"):null)||Ln(q[m.contact_id||""],Oe[q[m.contact_id||""]||""])||yt(m.user_id&&oe[m.user_id]||le||""),deal_won:pe.has(m.contact_id||"")||!!(E!=null&&E.phone_number)&&u.has(r(E.phone_number)),system_sale:x.has(m.contact_id||"")||!!(E!=null&&E.phone_number)&&I.has(r(E.phone_number)),sale_value:he[r((E==null?void 0:E.phone_number)||"")]||0,quoted_value:((Aa=re[m.contact_id||""])==null?void 0:Aa.value)||null,quoted_at:((Ma=re[m.contact_id||""])==null?void 0:Ma.at)||null,quote_reference:((Ba=re[m.contact_id||""])==null?void 0:Ba.reference)||null,is_biopto:String(((La=m.metadata)==null?void 0:La.brand)||"").toUpperCase()==="BIOPTO"}}),dt=qe(new Date,"yyyy-MM-dd");de.sort((m,E)=>{const te=m.date===dt,T=E.date===dt;if(te&&!T)return-1;if(!te&&T)return 1;if(te&&T)return(m.time||"").localeCompare(E.time||"");const Z=m.date>dt,le=E.date>dt;return Z&&le?m.date.localeCompare(E.date)||(m.time||"").localeCompare(E.time||""):!Z&&!le?E.date.localeCompare(m.date)||(m.time||"").localeCompare(E.time||""):Z&&!le?-1:1});const wa=X.split("+").map(m=>m.trim().toUpperCase()).filter(Boolean);let St=X!=="ALL"?de.filter(m=>wa.includes(String(m.unit).toUpperCase())):de;C&&(St=St.filter(m=>m.is_biopto)),St=St.filter(m=>{const E=String(m.contact_name||"").trim(),te=E!==""&&E!=="—",T=r(m.contact_phone||"").length>=10;return te||T});const $s=new Set(St.map(m=>r(m.contact_phone)).filter(Boolean)),Ca=[];C||Object.values(fe).forEach(m=>{if(!m.phone||$s.has(m.phone)||X!=="ALL"&&!wa.includes(m.loja))return;const E=m.won_at?m.won_at.slice(0,10):"";Ca.push({id:`sale:${m.contact_id}:${m.phone}`,contact_id:m.contact_id,contact_created:m.won_at||"",contact_name:m.name,contact_phone:m.phone,unit:m.loja,date:E,time:"",status:"attended",seller_name:cs(Nt[m.owner_id||""]||"—"),description:"Venda registrada no sistema",observations:null,os_numero:null,observacao:null,brand:Pt(m.contact_id,null),deal_won:!0,system_sale:m.imported,sale_value:m.value,sale_only:!0})});const Ea=[...Ca,...St];g(Ea);const sa=new Set;let Sa=0;Ea.forEach(m=>{if(!m.deal_won)return;const E=r(m.contact_phone)||m.contact_id;sa.has(E)||(sa.add(E),Sa+=he[r(m.contact_phone)]||0)}),se({vendas:sa.size,receita:Sa}),N(!1),F(!1),Xe()},[s,$,A,Me]);l.useEffect(()=>{$e()},[$e]);const[we,Ce]=l.useState(null),[me,Se]=l.useState(""),[R,Ve]=l.useState(""),[Pe,Ye]=l.useState(!1),B=a=>{Ce(a.id),Ve(a.os_numero||""),Se(a.observacao||"")},ce=async a=>{const C=R.replace(/\D/g,"").slice(0,6);if(C&&C.length<2){alert("A OS deve ter de 2 a 6 dígitos.");return}const X=me.trim();Ye(!0);const Q=c.find(u=>u.id===a),H=[C?`OS ${C}`:"",X].filter(Boolean).join(" · ")||null,{data:ee}=await w.from("appointments").select("metadata").eq("id",a).maybeSingle(),o={...(ee==null?void 0:ee.metadata)||{},os_numero:C||null,observacao:X||null},{error:r}=await w.from("appointments").update({observations:H,description:H||(Q==null?void 0:Q.description)||null,metadata:o}).eq("id",a);if(r){Ye(!1),alert("Não foi possível salvar: "+r.message);return}else{const u=c.find(I=>I.id===a);g(I=>I.map(x=>x.id===a?{...x,observations:H,os_numero:C||null,observacao:X||null,description:H||x.description}:x)),Ft({profile:i,action:"os",title:`${(u==null?void 0:u.contact_name)||"Cliente"} → ${C?`OS ${C}`:"OS removida"}`,detail:H||"(registro limpo)",entityType:"appointment",entityId:(u==null?void 0:u.contact_id)||a,metadata:{unit:u==null?void 0:u.unit,date:u==null?void 0:u.date,time:u==null?void 0:u.time,os_numero:C||null,observacao:X||null}}),C&&(u!=null&&u.deal_won)&&((u==null?void 0:u.sale_value)||0)>=40&&(u!=null&&u.unit)&&u.unit!=="—"&&w.from("vendas_evento").upsert({unidade:u.unit,vendedor:u.seller_name!=="—"?u.seller_name:null,valor:u.sale_value,canal:u.brand,os_numero:C,origem:"gerentes",metadata:{appointment_id:a,contact_id:u.contact_id,observacao:X||null}},{onConflict:"os_numero,unidade",ignoreDuplicates:!0}).then(()=>{},()=>{})}Ye(!1),Ce(null)},Fe=["EMB","TS"].includes(String(s||"").toUpperCase()),[_e,Ge]=l.useState(null),[ke,et]=l.useState({name:"",phone:"",date:"",time:""}),[Te,rt]=l.useState(!1),je=a=>{Ge(a),et({name:a.contact_name==="—"?"":a.contact_name,phone:String(a.contact_phone||"").replace(/\D/g,""),date:a.date||"",time:String(a.time||"").slice(0,5)})},it=async()=>
39{if(!_e)return;const a=ke.name.trim();let C=ke.phone.replace(/\D/g,"");if(!a||/^[\d\s+()-]+$/.test(a)){alert("Informe o nome do cliente (não pode ser só números).");return}if((C.length===10||C.length===11)&&(C="55"+C),C.length<12||C.length>13){alert("Telefone inválido. Use DDD + número.");return}if(!ke.date||!ke.time){alert("Informe data e horário.");return}rt(!0);const{data:X}=await w.from("appointments").select("metadata").eq("id",_e.id).maybeSingle(),Q=(X==null?void 0:X.metadata)||{},H=Q.manual_edit||{},ee=ke.time.length===5?ke.time+":00":ke.time,{error:o}=await w.from("appointments").update({date:ke.date,time:ee,client_name:a,metadata:{...Q,manual_edit:{original_date:H.original_date||_e.date,original_time:H.original_time||_e.time,original_name:H.original_name||_e.contact_name,at:new Date().toISOString()}}}).eq("id",_e.id);if(o){rt(!1),alert("Não foi possível salvar: "+o.message);return}if(_e.contact_id){const{error:r}=await w.from("contacts").update({name:a,phone_number:C}).eq("id",_e.contact_id);r&&alert("Agendamento salvo, mas o contato não foi atualizado: "+r.message)}Ft({profile:i,action:"status",title:`${a} → agendamento editado`,detail:`${_e.date} ${String(_e.time||"").slice(0,5)} → ${ke.date} ${ke.time}`,entityType:"appointment",entityId:_e.contact_id||_e.id,metadata:{unit:_e.unit,before:{name:_e.contact_name,phone:_e.contact_phone,date:_e.date,time:_e.time},after:{name:a,phone:C,date:ke.date,time:ke.time}}}),rt(!1),Ge(null),$e()},ae=async a=>{const C=a.status==="attended"?"no_show":a.status==="no_show"?"scheduled":"attended";await ot(a,C)},ot=async(a,C)=>{var Q;if(C===a.status)return;P(H=>new Set(H).add(a.id));const{error:X}=await w.from("appointments").update({status:C}).eq("id",a.id);X||(g(H=>H.map(ee=>ee.id===a.id?{...ee,status:C}:ee)),Ft({profile:i,action:"status",title:`${a.contact_name} → ${((Q=ga[C])==null?void 0:Q.label)||C}`,detail:`Agendamento ${a.date} ${String(a.time||"").slice(0,5)} · ${a.unit}`,entityType:"appointment",entityId:a.contact_id||a.id,metadata:{from:a.status,to:C,unit:a.unit}})),P(H=>{const ee=new Set(H);return ee.delete(a.id),ee})},Le="mp_vendas_lancadas",Ue=qe(new Date,"yyyy-MM-dd"),[ze,$t]=l.useState(()=>{try{const a=JSON.parse(localStorage.getItem(Le)||"{}");return Object.fromEntries(Object.entries(a).filter(([,C])=>C===Ue))}catch{return{}}}),Qe=a=>{$t(a);try{localStorage.setItem(Le,JSON.stringify(a))}catch{}},xt=async a=>{var X;if(!a.contact_id)return;const C=!a.deal_won;P(Q=>new Set(Q).add(a.id+":venda"));try{const{data:Q}=await w.from("deals").select("id").eq("contact_id",a.contact_id).order("created_at",{ascending:!1}).limit(1),H=(X=Q==null?void 0:Q[0])==null?void 0:X.id;if(H){const{error:ee}=await w.from("deals").update(C?{won_at:new Date().toISOString(),stage:"Ganho",lost_at:null,...a.unit!=="—"?{loja:a.unit}:{}}:{won_at:null,stage:"Em Atendimento"}).eq("id",H);if(ee){alert("Não foi possível salvar a venda: "+ee.message);return}}else if(C){const ee="11111111-0000-4000-8000-000000000001",o={id:"11111111-0000-4000-8000-000000000013"},{error:r}=await w.from("deals").insert({contact_id:a.contact_id,title:a.contact_name,stage:"Ganho",stage_id:o==null?void 0:o.id,pipeline_id:ee,brand:a.brand==="OB"?"OB":"OV",won_at:new Date().toISOString(),loja:a.unit!=="—"?a.unit:null});if(r){alert("Não foi possível salvar a venda: "+r.message);return}}g(ee=>ee.map(o=>o.contact_id===a.contact_id?{...o,deal_won:C}:o));{const ee={...ze};c.filter(o=>o.contact_id===a.contact_id).forEach(o=>{C?ee[o.id]=Ue:delete ee[o.id]}),Qe(ee)}se(ee=>({...ee,vendas:Math.max(0,ee.vendas+(C?1:-1))})),Ft({profile:i,action:"venda",title:`${a.contact_name} → ${C?"Venda confirmada":"Venda removida"}`,detail:`${a.brand} · ${a.unit} · ${a.date}`,entityType:"deal",entityId:a.contact_id,metadata:{unit:a.unit,brand:a.brand,won:C}})}finally{P(Q=>{const H=new Set(Q);return H.delete(a.id+":venda"),H})}},He=qe(new Date,"yyyy-MM-dd"),We=[...new Set(c.map(a=>a.unit).filter(a=>a&&a!=="—"))].sort(),Ie=c.filter(a=>!O||a.date===O).filter(a=>ze[a.id]===Ue||!j?!0:a.deal_won||a.system_sale?!1:["scheduled","confirmed","pending",null,""].includes(a.status??"scheduled")).filter(a=>K==="all"||a.status===K).filter(a=>z==="all"||a.unit===z).filter(a=>{if(!G)return!0;const C=G.toLowerCase();return a.contact_name.toLowerCase().includes(C)||a.contact_phone.includes(C)||(a.description||"").toLowerCase().includes(C)}),jt=a=>a.deal_won||["attended","completed","attended_no_budget"].includes(a.status||""),ct=a=>
39!jt(a)&&(a.status==="no_show"||a.date<He&&a.status!=="cancelled"),Et=c.filter(jt).length,gt=c.filter(ct).length,Ee=c.filter(a=>!jt(a)&&!ct(a)&&a.status!=="cancelled").length,ht=c.filter(a=>!!a.date&&a.date<He&&!a.deal_won&&["scheduled","confirmed","pending"].includes(a.status||"scheduled")).length,Ot=[{label:"AGENDAMENTOS DO MÊS",val:String(c.length),cls:"#101935",b:"#CBD5E1"},{label:"COMPARECERAM (MÊS)",val:String(Et),cls:"#059669",b:"#10B981"},{label:"NÃO COMPARECERAM (MÊS)",val:String(gt),cls:"#F97316",b:"#F97316"},{label:"PENDENTES (MÊS)",val:String(Ee),cls:"#2563EB",b:"#3B82F6"},{label:"A ATUALIZAR (ATRASADOS)",val:String(ht),cls:"#B45309",b:"#F59E0B"},{label:"VENDAS DO MÊS",val:String(ie.vendas),cls:"#C2410C",b:"#E8530E"},{label:"RECEITA DO MÊS",val:Tt(ie.receita),cls:"#047857",b:"#10B981"}];return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{style:{background:"#fff",border:"1px solid #F0F2F8"},className:"rounded-xl shadow-sm p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 mb-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-base sm:text-lg font-bold",style:{color:"#101935"},children:["Agendamentos — ",n]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Marque ✓ para confirmar comparecimento"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-bold",style:{background:"#FFF3EE",color:"#C2410C",border:"1px solid #FED7AA"},children:[e.jsx(Qs,{className:"w-3.5 h-3.5"})," ",ie.vendas," vendas"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-bold",style:{background:"#ECFDF5",color:"#047857",border:"1px solid #A7F3D0"},children:[Tt(ie.receita)," de receita"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("button",{onClick:()=>d(!0),style:{background:"#E8530E"},className:"flex items-center gap-1.5 text-white font-semibold rounded-lg px-3 py-1.5 text-sm hover:opacity-90 transition-opacity",children:[e.jsx(Ut,{className:"w-4 h-4"})," Novo agendamento"]}),e.jsx("input",{type:"month",value:$,onChange:a=>{V(a.target.value),Y("")},style:{background:"#fff",color:"#101935",border:"1px solid #E2E8F0"},className:"px-3 py-1.5 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#E8530E]/30"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{type:"date",value:O,min:$+"-01",max:$+"-31",onChange:a=>Y(a.target.value),title:"Filtrar por dia específico",style:{background:O?"#FFF3EE":"#fff",color:"#101935",border:`1px solid ${O?"#E8530E":"#E2E8F0"}`},className:"px-3 py-1.5 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#E8530E]/30"}),O&&e.jsx("button",{onClick:()=>Y(""),title:"Limpar filtro de dia",style:{border:"1px solid #E2E8F0",background:"#fff"},className:"p-1.5 rounded-lg hover:bg-gray-50 text-gray-400 hover:text-gray-600 transition-colors text-xs",children:"✕"})]}),e.jsx("button",{onClick:()=>$e(!1),disabled:L,style:{border:"1px solid #E2E8F0",background:"#fff"},className:"p-2 rounded-lg hover:bg-gray-50 text-gray-500 transition-colors disabled:opacity-50",children:e.jsx(Dt,{className:`w-4 h-4 ${L?"animate-spin":""}`})})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-2 mb-4",children:Ot.map(({label:a,val:C,cls:X,b:Q})=>e.jsxs("div",{className:"rounded-lg p-3 border-l-4",style:{background:"#F9FAFB",border:"1px solid #F0F2F8",borderLeftColor:Q,borderLeftWidth:4},children:[e.jsx("div",{className:"text-[9px] font-semibold uppercase tracking-wider text-gray-400 mb-1",children:a}),e.jsx("div",{className:"text-lg sm:text-xl font-bold tabular-nums",style:{color:X},children:C})]},a))}),e.jsxs("div",{className:"flex flex-col sm:flex-row flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center rounded-lg px-3 py-2 text-xs font-semibold whitespace-nowrap",style:{border:"1px solid #E2E8F0",background:"#101935",color:"#fff"},children:["Todos (",c.length,")"]}),e.jsxs("button",{onClick:()=>D(a=>
39!a),title:"Mostrar apenas agendamentos ainda não preenchidos",style:{border:`1px solid ${j?"#E8530E":"#E2E8F0"}`,background:j?"#FFF3EE":"#fff",color:j?"#C2410C":"#64748B"},className:"flex items-center gap-2 rounded-lg px-3 py-2 text-xs font-semibold whitespace-nowrap transition-colors",children:[e.jsx("span",{className:`w-3.5 h-3.5 rounded border flex items-center justify-center ${j?"bg-[#E8530E] border-[#E8530E] text-white":"border-gray-300"}`,children:j?"✓":""}),"Somente pendentes (",Ie.length,")"]}),e.jsx("input",{type:"text",placeholder:"Buscar por nome, telefone, obs...",value:G,onChange:a=>p(a.target.value),style:{background:"#fff",color:"#101935",border:"1px solid #E2E8F0"},className:"flex-1 min-w-0 px-3 py-2 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#E8530E]/30"}),e.jsxs("select",{value:z,onChange:a=>v(a.target.value),style:{background:"#fff",color:"#101935",border:"1px solid #E2E8F0"},className:"px-3 py-2 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#E8530E]/30",children:[e.jsx("option",{value:"all",children:"Todas unidades"}),We.map(a=>e.jsx("option",{value:a,children:a},a))]}),e.jsxs("select",{value:K,onChange:a=>ue(a.target.value),style:{background:"#fff",color:"#101935",border:"1px solid #E2E8F0"},className:"px-3 py-2 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#E8530E]/30",children:[e.jsx("option",{value:"all",children:"Todos status"}),Object.entries(ga).map(([a,{label:C}])=>e.jsx("option",{value:a,children:C},a))]})]})]}),S?e.jsx("div",{className:"flex items-center justify-center h-40",children:e.jsx(Be,{className:"w-6 h-6 animate-spin text-gray-300"})}):Ie.length===0?e.jsx("div",{style:{background:"#fff",border:"1px solid #F0F2F8"},className:"rounded-xl shadow-sm p-12 text-center text-sm text-gray-400",children:O?e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsxs("span",{children:["Nenhum agendamento em ",O.split("-").reverse().join("/")," — o mês tem ",c.length," agendamento",c.length!==1?"s":"","."]}),e.jsx("button",{onClick:()=>Y(""),className:"rounded-lg px-4 py-2 text-xs font-semibold text-white",style:{background:"#E8530E"},children:"Ver o mês inteiro"})]}):"Nenhum agendamento encontrado."}):e.jsxs(e.Fragment,{children:[_e&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{background:"rgba(16,25,53,0.45)"},onClick:()=>!Te&&Ge(null),children:e.jsxs("div",{className:"w-full max-w-sm rounded-xl p-4 shadow-xl",style:{background:"#fff"},onClick:a=>a.stopPropagation(),children:[e.jsx("h3",{className:"font-bold mb-3",style:{color:"#101935"},children:"Editar agendamento"}),e.jsxs("div",{className:"flex flex-col gap-2 text-sm",children:[e.jsxs("label",{className:"text-xs text-gray-500",children:["Nome",e.jsx("input",{className:"mt-1 w-full border rounded-lg px-3 py-2",value:ke.name,onChange:a=>et(C=>({...C,name:a.target.value}))})]}),e.jsxs("label",{className:"text-xs text-gray-500",children:["Telefone (DDD + número)",e.jsx("input",{inputMode:"numeric",className:"mt-1 w-full border rounded-lg px-3 py-2",value:ke.phone,onChange:a=>et(C=>({...C,phone:a.target.value}))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"flex-1 text-xs text-gray-500",children:["Data",e.jsx("input",{type:"date",className:"mt-1 w-full border rounded-lg px-3 py-2",value:ke.date,onChange:a=>et(C=>({...C,date:a.target.value}))})]}),e.jsxs("label",{className:"w-28 text-xs text-gray-500",children:["Hora",e.jsx("input",{type:"time",className:"mt-1 w-full border rounded-lg px-3 py-2",value:ke.time,onChange:a=>et(C=>({...C,time:a.target.value}))})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx("button",{disabled:Te,onClick:()=>Ge(null),className:"px-3 py-2 rounded-lg border text-sm",children:"Cancelar"}),e.jsx("button",{disabled:Te,onClick:it,className:"px-3 py-2 rounded-lg text-sm font-semibold",style:{background:"#E8530E",color:"#fff"},children:Te?"Salvando…":"Salvar"})]})]})}),e.jsx("div",{className:"hidden md:block w-full",style:{background:"#fff",border:"1px solid #F0F2F8"},children:e.jsxs("div",{className:"rounded-xl shadow-sm overflow-hidden",children:[e.jsx("div",{className:"overflow-x-auto xl:overflow-x-visible",children:e.jsxs("table",{className:"w-full text-[11px] table-fixed min-w-[1080px] xl:min-w-0",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[5%]"}),e.jsx("col",{className:"w-[14%]"}),e.jsx("col",{className:"w-[8.5%]"}),e.jsx("col",{className:"w-[4%]"}),e.jsx("col",{className:"w-[6.5%]"}),e.jsx("col",{className:"w-[4%]"}),e.jsx("col",{className:"w-[5%]"}),e.jsx("col",{className:"w-[7%]"}),e.jsx("col",{className:"w-[9%]"}),e.jsx("col",{className:"w-[5.5%]"}),e.jsx("col",{className:"w-[7%]"}),e.jsx("col",{className:"w-[10%]"}),e.jsx("col",{className:"w-[4.5%]"}),e.jsx("col",{className:"w-[9.5%]"})]}),e.jsx("thead",{children:e.jsx("tr",{style:{background:"#F9FAFB",borderBottom:"1px solid #F0F2F8"},children:["DATA","NOME","TELEFONE","UN.","AGEND.","HORA","DIAS","VENDEDOR","CANAL","VALOR","REFERÊNCIA","COMPAR.","VENDA","OS"].map(a=>e.jsx("th",{className:"px-1.5 py-2 text-[9px] font-semibold uppercase tracking-wide text-gray-400 text-left truncate first:pl-3 last:pr-3",children:a},a))})}),e.jsx("tbody",{children:Ie.map(a=>{["attended","completed","attended_no_budget"].includes(a.status||""),a.status;const C=W.has(a.id),X=a.date===He,Q=a.date?Va(pt(a.date),new Date):null,H=!!a.date&&a.date<He&&["scheduled","confirmed","pending"].includes(a.status||"scheduled")&&!a.deal_won,ee=!!a.system_sale||!!a.sale_only;return e.jsxs("tr",{style:{borderBottom:"1px solid #F9FAFB",background:ee?"#ECFDF5":H?"#FEF9C3":X?"#FFF7ED":"#fff"},className:"hover:bg-gray-50 transition-colors",children:[e.jsx("td",{className:"px-1.5 py-1.5 pl-3 whitespace-nowrap text-[11px] text-gray-500",children:a.contact_created?qe(pt(a.contact_created),"dd/MM/yy"):"—"}),e.jsx("td",{className:"px-1.5 py-1.5 overflow-hidden",children:e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",title:a.contact_name,style:{color:"#101935"},children:a.contact_name}),Fe&&e.jsx("button",{onClick:()=>je(a),title:"Editar agendamento",className:"shrink-0 text-[10px] px-1 rounded border border-gray-200 text-gray-500 hover:bg-gray-100",children:"✏️"}),a.brand!=="—"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded-full border shrink-0 ${a.brand==="OB"?"bg-violet-50 text-violet-600 border-violet-200":"bg-orange-50 text-orange-600 border-orange-200"}`,children:a.brand})]})}),e.jsx("td",{className:"px-1.5 py-1.5 truncate text-[11px] text-gray-500",children:a.contact_phone||"—"}),e.jsx("td",{className:"px-1.5 py-1.5 truncate",children:e.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded",style:{background:"#F3F4F6",color:"#374151"},children:a.unit})}),e.jsx("td",{className:"px-1.5 py-1.5 whitespace-nowrap",children:e.jsx("span",{className:`text-[11px] font-medium ${X?"text-[#E8530E]":""}`,style:X?{}:{color:"#101935"},children:a.date?qe(pt(a.date),"dd/MM/yyyy"):"—"})}),e.jsx("td",{className:"px-1.5 py-1.5 whitespace-nowrap text-[11px] text-gray-600",children:a.time?a.time.slice(0,5):"—"}),e.jsx("td",{className:"px-1.5 py-1.5 whitespace-nowrap text-center",children:Q!==null?e.jsxs("div",{className:"flex flex-col items-center leading-tight",children:[e.jsx("span",{className:`text-[11px] font-bold tabular-nums ${Q<0?"text-red-500":Q===0?"text-[#E8530E]":Q<=3?"text-amber-500":"text-gray-400"}`,children:Q<0?`${Math.abs(Q)}d atrás`:Q===0?"Hoje":`${Q}d`}),H&&e.jsx("span",{className:"text-[9px] font-bold px-1 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-300 mt-0.5",children:"ATUALIZAR"})]}):"—"}),e.jsx("td",{className:"px-1.5 py-1.5 text-[11px] text-gray-700",children:e.jsx("span",{className:"block break-words leading-tight font-medium",title:a.seller_name,children:a.seller_name})}),e.jsx("td",{className:"px-1.5 py-1.5 overflow-hidden",children:a.channel||yt(a.seller_name)?e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded-full border inline-block max-w-full truncate ${(a.channel||yt(a.seller_name)).cls}`,children:(a.channel||yt(a.seller_name)).label}):e.jsx("span",{className:"text-[11px] text-gray-400",children:"—"})}),e.jsx("td",{className:"px-1.5 py-1.5 whitespace-nowrap text-right",children:a.quoted_value?e.jsx("span",{className:"text-[11px] font-bold text-amber-700 tabular-nums",title:a.quoted_at?`Orçado em ${new Date(a.quoted_at).toLocaleStr
39ing("pt-BR")}`:"Último orçamento enviado",children:Tt(a.quoted_value)}):e.jsx("span",{className:"text-gray-300",children:"—"})}),e.jsx("td",{className:"px-1.5 py-1.5 overflow-hidden",children:a.quote_reference?e.jsx("span",{className:"inline-block max-w-full truncate rounded-md bg-violet-50 px-1.5 py-0.5 text-[10px] font-bold text-violet-700",title:a.quote_reference,children:a.quote_reference}):e.jsx("span",{className:"text-gray-300",children:"—"})}),e.jsx("td",{className:"px-1.5 py-1.5 text-center",children:C?e.jsx(Be,{className:"w-3 h-3 animate-spin mx-auto text-gray-400"}):e.jsxs("select",{value:a.status||"scheduled",onChange:o=>ot(a,o.target.value),title:ee?"Registrado pelo sistema (planilha) — você pode corrigir":"Status do comparecimento",className:"text-[11px] font-semibold rounded-lg px-1 py-1 w-full outline-none cursor-pointer",style:{border:"1px solid #E2E8F0",background:a.status==="attended"?"#ECFDF5":a.status==="attended_no_budget"?"#FFFBEB":a.status==="no_show"||a.status==="cancelled"?"#FEF2F2":"#fff",color:a.status==="attended"?"#047857":a.status==="attended_no_budget"?"#B45309":a.status==="no_show"||a.status==="cancelled"?"#B91C1C":"#475569"},children:[e.jsx("option",{value:"scheduled",children:"Pendente"}),e.jsx("option",{value:"attended",children:"Compareceu"}),e.jsx("option",{value:"attended_no_budget",children:"Compareceu s/ orçamento"}),e.jsx("option",{value:"no_show",children:"Não compareceu"}),e.jsx("option",{value:"cancelled",children:"Cancelado"})]})}),e.jsxs("td",{className:"px-1.5 py-1.5 text-center",children:[e.jsx("button",{onClick:()=>{ee||xt(a)},disabled:ee||W.has(a.id+":venda")||!a.contact_id,title:ee?"Venda registrada pelo sistema (planilha) — não editável":a.deal_won?"Venda confirmada — clique para desmarcar":"Clique para marcar venda",className:`w-6 h-6 rounded-md border-2 flex items-center justify-center mx-auto transition-all font-bold text-base cursor-pointer
40                                ${ee?"bg-emerald-600 border-emerald-600 text-white cursor-not-allowed":a.deal_won?"bg-[#E8530E] border-[#E8530E] text-white hover:brightness-110":"border-gray-300 hover:border-gray-400 bg-white text-gray-300"}`,children:W.has(a.id+":venda")?e.jsx(Be,{className:"w-3 h-3 animate-spin"}):a.deal_won?"✓":"·"}),a.deal_won&&!!a.sale_value&&e.jsx("span",{className:"block mt-0.5 text-[10px] font-bold text-emerald-700 tabular-nums",children:Tt(a.sale_value)}),ze[a.id]===Ue&&e.jsx("span",{className:"block mt-0.5 text-[9px] font-bold px-1 py-0.5 rounded",style:{background:"#ECFDF5",color:"#047857",border:"1px solid #A7F3D0"},children:"✓ lançada"})]}),e.jsx("td",{className:`px-1.5 py-1.5 pr-3 ${we===a.id?"relative overflow-visible":"overflow-hidden"}`,children:we===a.id?e.jsxs("div",{className:"absolute right-1 top-1 z-30 w-72 flex flex-col gap-1.5 rounded-lg border border-blue-300 bg-white p-2 shadow-xl",children:[e.jsx("input",{autoFocus:!0,inputMode:"numeric",className:"text-xs border border-blue-300 rounded px-2 py-1 w-full outline-none",value:R,onChange:o=>Ve(o.target.value.replace(/\D/g,"").slice(0,6)),onKeyDown:o=>{o.key==="Enter"&&ce(a.id),o.key==="Escape"&&Ce(null)},placeholder:"OS (2 a 6 dígitos)",title:"OS — 2 a 6 dígitos"}),e.jsx("input",{className:"text-xs border border-blue-300 rounded px-2 py-1 w-full outline-none",value:me,onChange:o=>Se(o.target.value),onKeyDown:o=>{o.key==="Enter"&&ce(a.id),o.key==="Escape"&&Ce(null)},placeholder:"Observação"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:()=>ce(a.id),disabled:Pe,className:"flex-1 text-xs bg-blue-500 text-white rounded px-2 py-1 hover:bg-blue-600",children:Pe?"Salvando...":"Salvar"}),e.jsx("button",{onClick:()=>Ce(null),className:"text-xs text-gray-500 border rounded px-2 py-1 hover:text-gray-700",children:"Cancelar"})]})]}):e.jsx("button",{onClick:()=>B(a),className:"text-left w-full group",children:a.os_numero||a.observacao?e.jsxs("span",{className:"text-[11px] truncate block text-gray-700",children:[a.os_numero&&e.jsxs("strong",{className:"tabular-nums",children:["OS ",a.os_numero]}),a.os_numero&&a.observacao?" · ":"",a.observacao]}):e.jsx("span",{className:"text-[11px] truncate block text-gray-300 group-hover:text-gray-400",children:"+ OS / observação"})})})]},a.id)})})]})}),e.jsxs("div",{className:"px-4 py-2.5 flex items-center justify-between text-[11px] text-gray-400",style:{background:"#F9FAFB",borderTop:"1px solid #F0F2F8"},children:[e.jsxs("span",{children:[Ie.length," agendamento",Ie.length!==1?"s":""]}),e.jsxs("span",{children:[Ie.filter(a=>["attended","completed","attended_no_budget"].includes(a.status||"")).length," compareceram · ",Ie.filter(a=>["scheduled","confirmed","pending"].includes(a.status||"")).length," pendentes"]})]})]})}),e.jsxs("div",{className:"flex flex-col gap-3 md:hidden",children:[Ie.map(a=>{const C=["attended","completed","attended_no_budget"].includes(a.status||""),X=a.status==="no_show",Q=W.has(a.id),H=a.date?Va(pt(a.date),new Date):null,ee=ga[a.status||""]||{label:a.status||"—",dot:"bg-gray-400"},o=!!a.date&&a.date<qe(new Date,"yyyy-MM-dd")&&["scheduled","confirmed","pending"].includes(a.status||"scheduled")&&!a.deal_won,r=!!a.system_sale||!!a.sale_only;return e.jsxs("div",{style:{background:r?"#ECFDF5":o?"#FEFCE8":"#fff",border:`1px solid ${r?"#A7F3D0":o?"#FDE68A":"#F0F2F8"}`},className:"rounded-2xl shadow-sm p-4",children:[r&&e.jsx("div",{className:"mb-2 text-[11px] font-bold px-2 py-1 rounded-lg bg-emerald-100 text-emerald-700 border border-emerald-300 inline-block",children:"🔒 Comparecimento e venda registrados pelo sistema"}),o&&e.jsx("div",{className:"mb-2 text-[11px] font-bold px-2 py-1 rounded-lg bg-amber-100 text-amber-700 border border-amber-300 inline-block",children:"Atualize este agendamento"}),e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{className:"font-bold text-[16px] leading-snug",style:{color:"#101935"},children:a.contact_name}),Fe&&e.jsx("button",{onClick:()=>je(a),className:"ml-2 text-xs px-2 py-1 rounded-lg border border-gray-200 text-gray-600",children:"✏️ Editar"}),a.brand!=="—"&&e.jsx("span",{className:`text-[11px] font-bold px-2 py-0.5 rounded-full border ${a.brand==="OB"?"bg-violet-50 text-violet-600 border-violet-200":"bg-orange-50 text-orange-600 border-orange-200"}`,children:a.brand}),e.jsx("span",{className:"text-[11px] font-semibold px-2 py-0.5 rounded",style:{background:"#F3F4F6",color:"#374151"},children:a.unit})]}),a.contact_phone&&e.jsxs("a",{href:`tel:${a.contact_phone}`,className:"flex items-center gap-1.5 mt-1 text-sm text-gray-500",children:[e.jsx(ja,{className:"w-4 h-4"}),a.contact_phone]}),a.quoted_value&&e.jsxs("div",{className:"mt-1 text-sm font-bold text-amber-700 tabular-nums",children:["OrÃ
40§ado: ",Tt(a.quoted_value),a.quoted_at?e.jsxs("span",{className:"ml-1 text-[11px] font-normal text-gray-400",children:["em ",new Date(a.quoted_at).toLocaleDateString("pt-BR")]}):null]}),a.quote_reference&&e.jsxs("div",{className:"mt-1 text-xs font-semibold text-violet-700",children:["Referência: ",a.quote_reference]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:()=>{r||xt(a)},disabled:r||W.has(a.id+":venda")||!a.contact_id,title:a.deal_won?"Venda confirmada — toque para desmarcar":"Marcar venda",className:`w-11 h-11 rounded-xl border-2 flex flex-col items-center justify-center transition-all font-bold text-lg
41                          ${a.deal_won?"bg-[#E8530E] border-[#E8530E] text-white":"border-gray-300 bg-white text-gray-300"}`,children:[W.has(a.id+":venda")?e.jsx(Be,{className:"w-5 h-5 animate-spin"}):a.deal_won?"✓":"·",e.jsx("span",{className:"text-[8px] font-semibold leading-none",children:"VENDA"})]}),e.jsxs("button",{onClick:()=>ae(a),disabled:Q,title:C?"Compareceu — toque para marcar falta":X?"Falta — toque para limpar":"Marcar compareceu",className:`w-11 h-11 rounded-xl border-2 flex flex-col items-center justify-center transition-all font-bold text-lg cursor-pointer
42                          ${C?"bg-emerald-500 border-emerald-500 text-white":X?"bg-rose-500 border-rose-500 text-white":"border-gray-300 bg-white text-gray-300"}`,children:[Q?e.jsx(Be,{className:"w-5 h-5 animate-spin"}):C?"✓":X?"✗":"·",e.jsx("span",{className:"text-[8px] font-semibold leading-none",children:"COMPAR."})]})]})]}),e.jsxs("select",{value:a.status||"scheduled",disabled:Q,onChange:u=>ot(a,u.target.value),className:"w-full text-sm font-semibold rounded-xl px-3 py-2.5 mb-3 outline-none",style:{border:"1px solid #E2E8F0",background:a.status==="attended"?"#ECFDF5":a.status==="attended_no_budget"?"#FFFBEB":a.status==="no_show"||a.status==="cancelled"?"#FEF2F2":"#fff",color:a.status==="attended"?"#047857":a.status==="attended_no_budget"?"#B45309":a.status==="no_show"||a.status==="cancelled"?"#B91C1C":"#475569"},children:[e.jsx("option",{value:"scheduled",children:"Pendente"}),e.jsx("option",{value:"attended",children:"Compareceu"}),e.jsx("option",{value:"attended_no_budget",children:"Compareceu s/ orçamento (exame de vista)"}),e.jsx("option",{value:"no_show",children:"Não compareceu"}),e.jsx("option",{value:"cancelled",children:"Cancelado"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 text-sm mb-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(fa,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"font-medium",style:{color:"#101935"},children:a.date?qe(pt(a.date),"dd/MM/yyyy"):"—"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(_a,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-gray-600 font-medium",children:a.time?a.time.slice(0,5):"—"})]}),a.seller_name!=="—"&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ps,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{className:"text-gray-600 truncate",children:a.seller_name}),(a.channel||yt(a.seller_name))&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded-full border shrink-0 ${(a.channel||yt(a.seller_name)).cls}`,children:(a.channel||yt(a.seller_name)).label})]}),H!==null&&e.jsx("div",{className:`text-sm font-bold tabular-nums ${H<0?"text-red-500":H===0?"text-[#E8530E]":H<=3?"text-amber-500":"text-gray-400"}`,children:H<0?`${Math.abs(H)}d atrás`:H===0?"Hoje":`${H}d`})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${ee.dot}`}),e.jsx("span",{className:"text-sm text-gray-500",children:ee.label})]}),ze[a.id]===Ue&&e.jsx("div",{className:"mb-2",children:e.jsx("span",{className:"text-[11px] font-bold px-2 py-0.5 rounded",style:{background:"#ECFDF5",color:"#047857",border:"1px solid #A7F3D0"},children:"✓ lançada"})}),we===a.id?e.jsxs("div",{className:"flex flex-col gap-1.5 mt-1",children:[e.jsx("input",{autoFocus:!0,inputMode:"numeric",className:"text-sm border border-blue-300 rounded-lg px-3 py-2.5 w-full outline-none",value:R,onChange:u=>Ve(u.target.value.replace(/\D/g,"").slice(0,6)),onKeyDown:u=>{u.key==="Enter"&&ce(a.id),u.key==="Escape"&&Ce(null)},placeholder:"OS (2 a 6 dígitos)"}),e.jsx("input",{className:"text-sm border border-blue-300 rounded-lg px-3 py-2.5 w-full outline-none",value:me,onChange:u=>Se(u.target.value),onKeyDown:u=>{u.key==="Enter"&&ce(a.id),u.key==="Escape"&&Ce(null)},placeholder:"Observação"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>ce(a.id),disabled:Pe,className:"text-sm bg-blue-500 text-white rounded-lg px-3 py-2.5 flex-1",children:Pe?"...":"Salvar"}),e.jsx("button",{onClick:()=>Ce(null),className:"text-sm text-gray-400 px-3 py-2.5",children:"✕"})]})]}):e.jsx("button",{onClick:()=>B(a),className:"text-left w-full mt-1 py-1.5",children:a.os_numero||a.observacao?e.jsxs("span",{className:"text-sm text-gray-700",children:[a.os_numero&&e.jsxs("strong",{className:"tabular-nums",children:["OS ",a.os_numero]}),a.os_numero&&a.observacao?" · ":"",a.observacao]}):e.jsx("span",{className:"text-sm text-gray-400",children:"+ adicionar OS / observação"})})]},a.id)}),e.jsxs("div",{className:"text-center text-xs text-gray-400 py-2",children:[Ie.length," agendamentos"]})]})]}),f&&e.jsx(Ds,{units:ne,profile:i,onClose:()=>d(!1),onCreated:()=>$e(!1)})]})},Qt={compareceu:{label:"Compareceu",color:"#059669",bg:"#ECFDF5",Icon:ms},falta:{label:"Nao compareceu",color:"#DC2626",bg:"#FEF2F2",Icon:ds},venda:{label:"Venda",color:"#E8530E",bg:"#FFF7ED",Icon:hs},os:{label:"OS",color:"#7C3AED",bg:"#F5F3FF",Icon:gs},acesso:{label:"Acesso",color:"#2563EB",bg:"#EFF6FF",Icon:_s}},Jt=s=>{var n;return s.action==="acesso"?"acesso":s.action==="venda"?"venda":s.action==="os"||s.action==="observacao"?"os":((n=s.metadata)==null?void 0:n.to)==="no_show"?"falta":"compareceu"},Pn=({profile:s})=>{const[n,i]=l.useState([]),[c,g]=l.useState(!0),[S,N]=l.useState("minha"),[L,F]=l.useState("all"),$=l.useCallback(async()=>{g(!0);let j=w.from("manager_updates").select("id, manager_name, manager_email, store_sigla, action, title, detail, metadata, created_at").order("created_at",{ascending:!1}).limit(300);if(S==="minha"&&s.store_sigla!=="ALL"){const v=(s.store_sigla.toUpperCase().startsWith("BIOPTO:")?s.store_sigla.slice(s.store_sigla.indexOf(":")+1):s.store_sigla).split("+").map(G=>
42G.trim().toUpperCase()).filter(Boolean);j=v.length>1?j.in("store_sigla",v):j.eq("store_sigla",v[0]||s.store_sigla)}const{data:D}=await j;i(D||[]),g(!1)},[S,s.store_sigla]);l.useEffect(()=>{$()},[$]);const V=zt.useMemo(()=>{const j={compareceu:0,falta:0,venda:0,os:0,acesso:0};return n.forEach(D=>{j[Jt(D)]+=1}),j},[n]),O=zt.useMemo(()=>{const j=new Map;return n.filter(D=>D.action==="acesso").forEach(D=>{const z=D.manager_email||D.manager_name||D.store_sigla||D.id,v=j.get(z);v?(v.total+=1,D.created_at>v.last&&(v.last=D.created_at)):j.set(z,{nome:D.manager_name||D.manager_email||"Gerente",sigla:D.store_sigla||"-",last:D.created_at,total:1})}),[...j.values()].sort((D,z)=>z.last.localeCompare(D.last))},[n]),Y=zt.useMemo(()=>n.filter(j=>L==="all"||Jt(j)===L),[n,L]),K=zt.useMemo(()=>{const j=new Map;return Y.forEach(D=>{const z=qe(pt(D.created_at),"dd/MM/yyyy");j.has(z)||j.set(z,[]),j.get(z).push(D)}),[...j.entries()]},[Y]),ue=()=>{ea(`atualizacoes_${s.store_sigla}.csv`,Y.map(j=>({data:qe(pt(j.created_at),"dd/MM/yyyy HH:mm"),unidade:j.store_sigla||"",gerente:j.manager_name||j.manager_email||"",tipo:Qt[Jt(j)].label,registro:j.title,detalhe:j.detail||""})),";")};return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{style:{background:"#fff",border:"1px solid #F0F2F8"},className:"rounded-xl shadow-sm p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold",style:{color:"#101935"},children:"Central de atualizacoes"}),e.jsx("p",{className:"text-xs text-gray-500",children:"Acessos, comparecimentos, vendas e OS registrados no app."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:ue,style:{border:"1px solid #E2E8F0",background:"#fff"},className:"p-2.5 rounded-lg text-gray-500 active:bg-gray-100",title:"Exportar relatorio",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:$,style:{border:"1px solid #E2E8F0",background:"#fff"},className:"p-2.5 rounded-lg text-gray-500 active:bg-gray-100",children:e.jsx(Dt,{className:`w-4 h-4 ${c?"animate-spin":""}`})})]})]}),s.store_sigla!=="ALL"&&e.jsx("div",{className:"flex rounded-lg overflow-hidden text-sm mt-3",style:{border:"1px solid #E2E8F0"},children:[["minha","Minha unidade"],["todas","Todas"]].map(([j,D])=>e.jsx("button",{onClick:()=>N(j),style:{background:S===j?"#101935":"#fff",color:S===j?"#fff":"#6B7280"},className:"flex-1 px-3 py-2.5 font-medium",children:D},j))}),e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-3",children:Object.keys(Qt).map(j=>{const D=Qt[j],z=L===j,v=V[j],G=n.length?Math.round(v/n.length*100):0;return e.jsxs("button",{onClick:()=>F(z?"all":j),style:{background:z?D.bg:"#fff",border:`1px solid ${z?D.color:"#F0F2F8"}`},className:"rounded-xl p-3 text-left",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium",style:{color:D.color},children:[e.jsx(D.Icon,{className:"w-3.5 h-3.5"}),D.label]}),e.jsx("div",{className:"text-2xl font-bold mt-0.5",style:{color:"#101935"},children:v}),e.jsx("div",{className:"h-1.5 rounded-full mt-1.5",style:{background:"#F1F5F9"},children:e.jsx("div",{className:"h-full rounded-full",style:{width:`${G}%`,background:D.color}})})]},j)})})]}),e.jsxs("div",{style:{background:"#fff",border:"1px solid #F0F2F8"},className:"rounded-xl shadow-sm p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(_s,{className:"w-4 h-4",style:{color:"#2563EB"}}),e.jsx("span",{className:"text-sm font-bold",style:{color:"#101935"},children:"Gerentes que acessaram"}),e.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded-full",style:{background:"#EFF6FF",color:"#2563EB"},children:O.length})]}),O.length===0?e.jsx("p",{className:"text-xs text-gray-400",children:"Nenhum acesso registrado no periodo."}):e.jsx("div",{className:"flex flex-col divide-y",style:{borderColor:"#F1F5F9"},children:O.map(j=>e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{background:"#EFF6FF"},children:e.jsx(ps,{className:"w-4 h-4",style:{color:"#2563EB"}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",style:{color:"#101935"},children:j.nome}),e.jsxs("div",{className:"text-[11px] text-gray-500",children:[j.sigla," · ultimo acesso ",qe(pt(j.last),"dd/MM 'as' HH:mm",{locale:Ha})]})]}),e.jsxs("span",{className:"text-[11px] text-gray-500 shrink-0 px-2 py-0.5 rounded-full",style:{background:"#F3F4F6"},children:[j.total," ",j.total===1?"dia":"dias"]})]},j.nome+j.sigla))})]}),c?e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(Be,{className:"w-6 h-6 animate-spin text-gray-300"})}):Y.length===0?e.jsx("div",{style:{background:"#fff",border:"1px solid #F0F2F8"},className:"rounded-xl shadow-sm p-10 text-center text-sm text-gray-400",children:"Nenhuma atualizacao registrada ainda."}):K.map(([j,D])=>e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("span",{className:"text-xs font-bold",style:{color:"#101935"},children:j}),e.jsxs("span",{className:"text-[11px] text-gray-400",children:[D.length," registros"]})]}),D.map(z=>{const v=Qt[Jt(z)];return e.jsx("div",{style:{background:"#fff",border:"1px solid #F0F2F8",borderLeft:`4px solid ${v.color}`}
42,className:"rounded-xl shadow-sm p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-full flex items-center justify-center shrink-0",style:{background:v.bg},children:e.jsx(v.Icon,{className:"w-4 h-4",style:{color:v.color}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-semibold leading-snug",style:{color:"#101935"},children:z.title}),e.jsx("span",{className:"text-[11px] text-gray-400 shrink-0",children:qe(pt(z.created_at),"HH:mm",{locale:Ha})})]}),z.detail&&e.jsx("p",{className:"text-sm text-gray-600 mt-1 break-words",children:z.detail}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 text-[11px] text-gray-500 flex-wrap",children:[e.jsx("span",{className:"px-2 py-0.5 rounded-full font-medium",style:{background:v.bg,color:v.color},children:v.label}),e.jsx("span",{className:"px-2 py-0.5 rounded-full",style:{background:"#F3F4F6"},children:z.store_sigla||"-"}),e.jsx("span",{className:"truncate",children:z.manager_name||z.manager_email||"Gerente"})]})]})]})},z.id)})]},j))]})},Rn=({profile:s})=>{const[n,i]=l.useState(!1),[c,g]=l.useState([]),[S,N]=l.useState(0),L=s.store_sigla.toUpperCase().startsWith("BIOPTO:")?s.store_sigla.slice(s.store_sigla.indexOf(":")+1):s.store_sigla,F=L.toUpperCase()==="ALL"?c:L.split("+").map($=>$.trim().toUpperCase()).filter(Boolean);return l.useEffect(()=>{w.from("stores").select("sigla").eq("is_active",!0).then(({data:$})=>{g(($||[]).map(V=>String(V.sigla||"").toUpperCase()).filter(Boolean))})},[]),e.jsxs(e.Fragment,{children:[e.jsx(yn,{storeSigla:s.store_sigla,storeName:s.store_name,onNewAppointment:()=>i(!0)},S),n&&e.jsx(Ds,{units:F,profile:s,onClose:()=>i(!1),onCreated:()=>N($=>$+1)})]})},Vn=({profile:s,onLogout:n})=>{ks();const i=["opto","optometrista"].includes(String(s.role||"").toLowerCase()),[c,g]=l.useState(i?"receitas":"agendamentos"),[S,N]=l.useState(!1),L=s.store_sigla==="ALL"&&!i,F=String(s.store_sigla||"").toUpperCase().split("+").map(O=>O.trim()),$=!i&&(F.includes("KIDS")||F.includes("SBC1"));l.useEffect(()=>{L&&g("agendamentos")},[L]),l.useEffect(()=>{!$&&c==="funil"&&g("agendamentos")},[$,c]),l.useEffect(()=>{i&&!["receitas","historico","exames-agenda"].includes(c)&&g("receitas"),!i&&["historico","exames-agenda"].includes(c)&&g("agendamentos")},[i,c]),l.useEffect(()=>{const O=new Date().toISOString().slice(0,10),Y=`mgr-access:${s.store_sigla}:${O}`;localStorage.getItem(Y)||(localStorage.setItem(Y,"1"),Ft({profile:s,action:"acesso",title:`${s.store_name||s.store_sigla} acessou o app`,detail:`Acesso em ${new Date().toLocaleString("pt-BR")}`,entityType:"acesso",entityId:null,metadata:{day:O}}))},[s]);const V=i?[["receitas","Nova receita",ha],["historico","Histórico",Ws],["exames-agenda","Agendamentos",Ut]]:[["agendamentos","Agendamentos",Ut],...$?[["funil","Funil",en]]:[],["receitas","Receitas",ha],["atualizacoes","Atualizações",Js],...L?[["supervisao","Supervisão",xs]]:[],...Xt[s.user_id||""]?[["comercial-interno","Comercial Interno",qs],["conciliacao","Conciliação",Xs]]:[]];return e.jsxs("div",{style:{minHeight:"100vh",background:"#F5F7FB",colorScheme:"light"},children:[e.jsxs("header",{style:{background:"#fff",borderBottom:"1px solid #F0F2F8"},className:"shadow-sm sticky top-0 z-20",children:[e.jsxs("div",{className:"w-full px-3 sm:px-4 flex items-center justify-between h-14 gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("img",{src:Ss,alt:"Videre atendimento",width:1024,height:1024,className:"h-9 w-9 rounded-lg object-cover"}),e.jsxs("div",{className:"hidden sm:block",children:[e.jsx("span",{className:"font-bold text-sm",style:{color:"#101935"},children:"Gerentes"}),e.jsx("span",{className:"text-gray-300 mx-1.5",children:"·"}),e.jsx("span",{className:"text-sm text-gray-500",children:s.store_sigla==="ALL"?"⭐ Supervisor":s.store_name})]}),e.jsx("span",{className:"sm:hidden font-bold text-sm",style:{color:"#101935"},children:"Gerentes"})]}),e.jsx("nav",{className:"hidden sm:flex gap-1",children:V.map(([O,Y,K])=>e.jsxs("button",{onClick:()=>g(O),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${c===O?"bg-[#E8530E] text-white":"text-gray-500 hover:text-[#101935] hover:bg-gray-100"}`,children:[e.jsx(K,{className:"w-4 h-4"}),Y]},O))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{compact:!0,color:"#E8530E",className:"hidden sm:inline-flex"}),e.jsxs("button",{onClick:n,className:"hidden sm:flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm text-gray-500 hover:text-red-600 hover:bg-red-50 transition-colors",children:[e.jsx(Ta,{className:"w-4 h-4"}),"Sair"]}),e.jsx("button",{onClick:()=>N(O=>!O),className:"sm:hidden p-2 rounded-lg text-gray-500 hover:bg-gray-100",children:S?e.jsx(wt,{className:"w-5 h-5"}):e.jsx(Ps,{className:"w-5 h-5"})})]})]}),S&&e.jsxs("div",{style:{background:"#fff",borderTop:"1px solid #F0F2F8"},className:"sm:hidden px-4 py-3 flex flex-col gap-1",children:[V.map(([O,Y,K])=>e.jsxs("button",{onClick:()=>{g(O),N(!1)},className:`flex items-center gap-2 px-3 py-3 rounded-lg text-base font-medium transition-colors text-left ${c===O?"bg-[#E8530E] text-white":"text-gray-600 hover:bg-gray-100"}`,children:[e.jsx(K,{className:"w-5 h-5"}),Y]},O)),e.jsx(ls,{color:"#E8530E",className:"mt-1"}),e.jsxs("button",{onClick:n,className:"flex items-center gap-2 px-3 py-3 rounded-lg text-base text-red-600 hover:bg-red-50 transition-colors",children:[e.jsx(Ta,{className:"w-5 h-5"}),"Sair"]})]})]}),e.jsxs("main",{className:"w-full px-2 sm:px-3 py-5 pb-24 sm:pb-8",children:[c==="agendamentos"&&e.jsx(qn,{storeSigla:s.store_sigla,storeName:s.store_name,profile:s}),c==="funil"&&$&&e.jsx(Rn,{profile:s}),c==="receitas"&&e.jsx(Xa,{profile:s}),c==="historico"&&e.jsx(Xa,{profile:s,view:"history"}),c==="exames-agenda"&&e.jsx(Fn,{profile:s}),c==="atualizacoes"&&e.jsx(Pn,{profile:s}),c==="supervisao"&&e.jsx(fn,{}),c==="comercial-interno"&&Xt[s.user_id||""]&&e.jsx(On,{userId:s.user_id||""}),c==="conciliacao"&&Xt[s.user_id||""]&&e.jsx(Mn,{userId:s.user_id||""})]}),e.jsx("nav",{className:"sm:hidden fixed bottom-0 inset-x-0 z-30 flex",style:{background:"#fff",borderTop:"1px solid #F0F2F8",paddingBottom:"env(safe-area-inset-bottom)"},children:V.map(([O,Y,K])=>e.jsxs("button",{onClick:()=>{g(O),N(!1)},className:"flex-1 flex flex-col items-center gap-0.5 py-2.5 text-[11px] font-medium",style:{color:c===O?"#E8530E":"#94A3B8"},children:[e.jsx(K,{className:"w-5 h-5"}),Y]},O))})]})},go=()=>{const[s,n]=l.useState("loading"),[i,c]=l.useState(null),g=l.useCallback(async F=>{const{data:$}=await w.from("manager_profiles").select("id, user_id, store_sigla, store_name, role").eq("user_id",F).maybeSingle();c($??{id:"admin",store_sigla:"ALL",store_name:"Todas as Unidades",role:"gerente"}),n("portal")},[]),S=l.useCallback(async()=>{const{data:{session:F}}=await w.auth.getSession();if(!F){n("login");return}await g(F.user.id)},[g]);l.useEffect(()=>{S()},[S]);const N=l.useCallback(async()=>{const{data:{session:F}}=await w.auth.getSession();F&&await g(F.user.id)},[g]),L=l.useCallback(async()=>{await w.auth.signOut(),c(null),n("login")},[]);return s==="loading"?e.jsx("div",{style:{minHeight:"100vh",background:"#F5F7FB"},className:"flex items-center justify-center",children:e.jsx(Be,{className:"w-6 h-6 animate-spin text-gray-400"})}):s==="login"?e.jsx(In,{onLogin:N}):e.jsx(Vn,{profile:i,onLogout:L})};export{go 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.