PageSourceSearch

https://teledoc.med.br/assets/PatientApp-Cv-mBumA.js

js teledoc.med.br collected 2026-09-24 13:55:18 UTC 202,448 bytes, 6 lines download raw bytes

1import{r as o,d as Me,u as kt,c as Bt,j as e,L as Nt,i as aa,k as Ds,e as Ms,f as Ne,N as Is}from"./vendor_react-DkiuXrlk.js";import{C as Q}from"./Card-D1-SY2US.js";import{I as ve}from"./Input-B8hBgEzj.js";import{u as Re,L as Ls,S as Ts,B as M,g as es,a as V,t as Je,p as Ee,b as wt,c as Rs,d as We,e as la,f as zs,m as na,h as oa,i as ia,j as ns,A as Gt,k as ra,H as ca}from"./index-C1ByJG38.js";import{U as ts}from"./types-6ortOn7i.js";import{A as Fs,m as ss}from"./vendor_motion-mPVRFuhH.js";import{X as Bs,f as bs,g as Ae,L as pe,Q as Gs,h as zt,i as da,j as Hs,C as Ft,k as Os,S as lt,l as De,m as Be,D as Qe,e as Ue,n as ma,o as ua,P as xa,p as Mt,I as pa,A as ha,b as Ht,q as ga,V as Ws,r as ba,s as os,t as fa,u as Ot,F as ya,v as Us,w as fs,x as ja,y as qs,z as Ks,B as ys,T as nt,E as ot,G as Te,J as js,K as at,W as Ct,U as _t,N as as,O as va,R as Vs,Y as Qs,Z as Na,_ as Ys,$ as wa,a0 as Ca,a1 as _a,a2 as ka,a3 as Sa,a4 as $a,a5 as vs,a6 as Pa,a7 as Aa,a8 as Ea}from"./vendor_icons-CIE77zBt.js";import{S as Xs,L as Da}from"./LegalGuardianFields-JbmNBoFL.js";import{R as vt,A as ls,C as It,X as Lt,Y as Tt,T as Rt,a as Oe,B as Ma,b as Ia,c as $t,L as La,d as Ta,e as Ra}from"./vendor_charts-ClnJbZTU.js";import{p as za,i as Pt,g as Fa,s as Ba}from"./patientDemographics-DIy75QW6.js";import{E as Ga}from"./vendor_pdf-D9UlI7qi.js";import{E as Ha}from"./EmergencyQueueMediaTips-Bm1aW7C9.js";import{R as Oa,u as Wa,P as Ua,H as qa}from"./useHelpUnread-BhNq8QQZ.js";import{R as Ka}from"./ResetPassword-ZSLTqfL-.js";const Va=()=>{const[t,s]=o.useState("login"),[l,a]=o.useState(""),[x,p]=o.useState(""),[c,g]=o.useState(""),[f,j]=o.useState(!1),[P,w]=o.useState(""),[S,y]=o.useState(""),n=Me(),u=kt(),[_]=Bt(),{login:i}=Re(),v=()=>{var E;const r=(E=u.state)==null?void 0:E.from,A=r!=null&&r.pathname?`${r.pathname}${r.search||""}`:null,$=_.get("returnTo")||A;return $&&String($).startsWith("/patient")?String($):"/patient/dashboard"},B=async()=>{j(!0),w(""),y("");try{await i(l,x,ts.PATIENT),n(v(),{replace:!0})}catch(r){console.error("Login failed:",r),w(es(r,"Falha no login. Verifique suas credenciais."))}finally{j(!1)}},I=async()=>{if(!c){w("Informe seu E-mail ou CPF.");return}j(!0),w(""),y("");try{await V.post("/auth/forgot-password",{email:c,user_type:ts.PATIENT}),y("Se o cadastro existir, você receberá um link de redefinição por e-mail."),s("login")}catch(r){console.error("Recover failed:",r),w(es(r,"Erro ao processar solicitação."))}finally{j(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-primary-50 to-indigo-50 flex items-center justify-center p-4",children:e.jsxs(Q,{className:"w-full max-w-md text-center",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx(Ls,{className:"w-48 h-16",textClassName:"hidden"})}),e.jsx("h1",{className:"text-2xl font-bold text-gray-800 mb-2",children:"Bem-vindo"}),e.jsx("p",{className:"text-gray-500 mb-8",children:"Sua saúde conectada e inteligente."}),e.jsx("div",{className:"mb-8 flex justify-center",children:e.jsx(Ts,{size:"sm"})}),P&&e.jsx("div",{className:"mb-4 rounded-xl bg-red-50 text-red-700 px-4 py-3 text-sm text-left",children:P}),S&&e.jsx("div",{className:"mb-4 rounded-xl bg-emerald-50 text-emerald-700 px-4 py-3 text-sm text-left",children:S}),t==="login"&&e.jsxs("div",{className:"space-y-4 text-left",children:[e.jsx(ve,{label:"CPF ou E-mail",placeholder:"CPF ou [email protected]",autoComplete:"username",value:l,onChange:r=>a(r.target.value)}),e.jsx(ve,{label:"Senha",type:"password",placeholder:"••••••••",autoComplete:"current-password",value:x,onChange:r=>p(r.target.value)}),e.jsx(M,{className:"w-full",size:"lg",onClick:B,isLoading:f,children:"Acessar"}),e.jsxs("div",{className:"flex justify-between text-sm mt-4",children:[e.jsx(Nt,{to:"/patient/signup",className:"text-primary-600 font-bold hover:underline",children:"Criar conta"}),e.jsx("button",{onClick:()=>{s("recover"),w(""),y("")},className:"text-gray-500 hover:text-gray-700",children:"Esqueci minha senha"})]})]}),t==="recover"&&e.jsxs("div",{className:"space-y-4 text-left",children:[e.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Digite seu e-mail ou CPF para receber as instruções de recuperação."}),e.jsx(ve,{label:"CPF ou E-mail",placeholder:"000.000.000-00",value:c,onChange:r=>g(r.target.value)}),e.jsx(M,{className:"w-full",size:"lg",onClick:I,isLoading:f,children:"Enviar Instruções"}),e.jsx("button",{onClick:()=>{s("login"),w("")},className:"text-sm text-gray-500 hover:text-primary-600 mt-4 block w-full text-center",children:"Voltar"})]})]})})};function Se(t){return t.replace(/\D/g,"")}function Qa(t){return Se(t).slice(0,16).replace(/(\d{4})(?=\d)/g,"$1 ").trim()}function Ya(t){const s=Se(t).slice(0,4);return s.length<=2?s:`${s.slice(0,2)}/${s.slice(2)}`}function Xa(t){return Se(t).slice(0,11).replace(/(\d{3})(\d)/,"$1.$2").replace(/(\d{3})(\d)/,"$1.$2").replace(/(\d{3})(\d{1,2})$/,"$1-$2")}function Ja(t){const s=Se(t).slice(0,8);return s.length<=5?s:`${s.slice(0,5)}-${s.slice(5)}`}function Ut(t){return`R$ ${Number(t).toFixed(2).replace(".",",")}`}function Za(t){const s=Se(t);if(s.length<13)return!1;let l=0,a=!1;for(let x=s.length-1;x>=0;x-=1){let p=Number(s[x]);a&&(p*=2,p>9&&(p-=9)),l+=p,a=!a}return l%10===0}function el(t){const s=Se(t);return/^4/.test(s)?"Visa":/^5[1-5]/.test(s)||/^2[2-7]/.test(s)?"Mastercard":/^3[47]/.test(s)?"Amex":/^(4011|4312|4389|4514|4576|5041|5066|5067|6277|6362|6363)/.test(s)?"Elo":null}const tl=({until:t})=>{const[s,l]=o.useState(()=>Math.max(0,+new Date(t)-Date.now()));o.useEffect(()=>{const p=setInterval(()=>l(Math.max(0,+new Date(t)-Date.now())),1e3);return()=>clearInterval(p)},[t]);const a=Math.floor(s/6e4),x=Math.floor(s%6e4/1e3);return s<=0?e.jsx("p",{className:"text-xs text-red-600 font-semibold",children:"Pix expirado — gere um novo código."}):e.jsxs("p",{className:"text-xs text-slate-500",children:["Expira em ",e.jsxs("span",{className:"font-semibold text-slate-700",children:[a,":",String(x).padStart(2,"0")]})]})};function He(t,s,l,a){const x={content_name:l?`${t}:${l}`:t,currency:"BRL"};return s!=null&&Number.isFinite(Number(s))&&(x.value=Number(s)),l&&(x.content_ids=[l]),a?{...x,...a}:x}function gt(t){const s=He(t.purpose,t.amount);t.paymentId&&wt("Purchase",{...s,order_id:String(t.paymentId)},`purchase:${t.paymentId}`),t.isSubscription&&t.subscriptionId&&wt("Subscribe",s,`subscribe:${t.subscriptionId}`)}const Wt=({open:t,onClose:s,purpose:l,referenceId:a,appointmentId:x,summary:p,amount:c,isSubscription:g=!1,onSuccess:f})=>{var me;const[j,P]=o.useState("pix"),[w,S]=o.useState(!1),[y,n]=o.useState(""),[u,_]=o.useState(null),[i,v]=o.useState(!1),[B,I]=o.use
1State(!1),[r,A]=o.useState(""),[G,$]=o.useState(!1),[E,Y]=o.useState(null),[le,b]=o.useState(""),[H,R]=o.useState(""),[O,W]=o.useState(""),[ie,ce]=o.useState(""),[C,k]=o.useState(""),[D,J]=o.useState(""),[de,he]=o.useState(""),be=o.useMemo(()=>el(H),[H]),_e=!g,se=!!(E&&E.finalAmount<=0),ge=(me=E==null?void 0:E.coupon)==null?void 0:me.code,fe=E?Number(E.finalAmount):(u==null?void 0:u.amount)??c,d=(E==null?void 0:E.finalAmount)??(u==null?void 0:u.amount)??void 0,L=()=>la(),U=(T,ne,Z)=>{We({option:T,placement:"checkout",label:ne,extra:{...He(l,fe,a),...Z}})},K=(T,ne)=>{T&&Rs({paymentId:T,value:ne??d??0,contentName:l})};o.useEffect(()=>{t||(P("pix"),S(!1),n(""),_(null),I(!1),v(!1),A(""),$(!1),Y(null))},[t]),o.useEffect(()=>{t&&Je("InitiateCheckout",He(l,c,a))},[t,l,c,a]),o.useEffect(()=>{if(!(u!=null&&u.paymentId)||B)return;const T=setInterval(async()=>{var ne;try{const{data:Z}=await Ee.getStatus(u.paymentId),we=String(((ne=Z==null?void 0:Z.payment)==null?void 0:ne.status)||Z.status||"").toUpperCase();(we==="CONFIRMED"||we==="RECEIVED")&&(I(!0),gt({purpose:l,amount:u.amount,paymentId:u.paymentId,subscriptionId:u.subscriptionId,isSubscription:g}),K(u.paymentId,u.amount),f({paymentId:u.paymentId,subscriptionId:u.subscriptionId,status:we}))}catch{}},3e3);return()=>clearInterval(T)},[u,B,f]);const re=async()=>{var ne,Z,we;const T=r.trim();if(T.length<3){n("Informe um código de cupom válido.");return}n(""),$(!0);try{const{data:q}=await Ee.validateCoupon({code:T,purpose:l,referenceId:a});Y(q),_(null),U("aplicar_cupom","Aplicar cupom",{payment_method:q.finalAmount<=0?"coupon_free":"coupon",coupon_code:(ne=q.coupon)==null?void 0:ne.code,value:Number(q.finalAmount)})}catch(q){Y(null),n(((we=(Z=q==null?void 0:q.response)==null?void 0:Z.data)==null?void 0:we.message)||"Cupom inválido ou indisponível.")}finally{$(!1)}},ee=()=>{Y(null),A(""),_(null),n("")},$e=async()=>{var T,ne;if(ge){n(""),S(!0);try{const{data:Z}=await Ee.checkoutFree({purpose:l,couponCode:ge,referenceId:a,appointmentId:x,...L()});Z.approved||["CONFIRMED","RECEIVED"].includes(Z.status)?(I(!0),U("confirmar_gratis","Confirmar atendimento grátis",{payment_method:"coupon_free"}),Je("AddPaymentInfo",He(l,0,a,{payment_method:"coupon_free"})),gt({purpose:l,amount:Number(Z.amount)||0,paymentId:Z.paymentId}),K(Z.paymentId,Z.amount),f({paymentId:Z.paymentId,status:Z.status})):n("Não foi possível confirmar o cupom gratuito.")}catch(Z){n(((ne=(T=Z==null?void 0:Z.response)==null?void 0:T.data)==null?void 0:ne.message)||"Falha ao aplicar o cupom gratuito.")}finally{S(!1)}}},ye=async()=>{var T,ne,Z,we;n(""),S(!0),U("gerar_qr_pix","Gerar QR Code Pix",{payment_method:"pix"});try{if(g){const{data:q}=await Ee.createSubscription({planPurpose:l,billingType:"PIX",...L()});q.requiresPayment&&q.paymentId?(_({paymentId:q.paymentId,encodedImage:q.encodedImage,payload:q.payload,amount:q.amount,expirationDate:q.expirationDate,subscriptionId:q.subscriptionId}),Je("AddPaymentInfo",He(l,fe,a,{payment_method:"pix"}))):q.status==="ACTIVE"?(I(!0),gt({purpose:l,amount:q.amount,paymentId:q.paymentId,subscriptionId:q.subscriptionId,isSubscription:!0}),K(q.paymentId,q.amount),f({paymentId:q.paymentId,subscriptionId:q.subscriptionId,status:"ACTIVE"})):n("Não foi possível gerar o Pix da assinatura. Tente novamente.")}else{const{data:q}=await Ee.checkoutPix({purpose:l,referenceId:a,appointmentId:x,couponCode:ge,...L()});_({paymentId:q.paymentId,encodedImage:q.encodedImage,payload:q.payload,amount:q.amount,expirationDate:q.expirationDate}),Je("AddPaymentInfo",He(l,fe,a,{payment_method:"pix"}))}}catch(q){const Ce=(ne=(T=q==null?void 0:q.response)==null?void 0:T.data)==null?void 0:ne.code;n(Ce==="COUPON_USE_FREE_CHECKOUT"?"Este cupom zera o valor. Use o botão de confirmação gratuita.":((we=(Z=q==null?void 0:q.response)==null?void 0:Z.data)==null?void 0:we.message)||"Não foi possível gerar o Pix. Tente novamente.")}finally{S(!1)}},ke=async()=>{var ne,Z,we,q;if(n(""),!Za(H)){n("Número do cartão inválido.");return}if(Se(O).length<4){n("Validade inválida. Use MM/AA.");return}if(Se(ie).length<3){n("CVV inválido.");return}if(Se(D).length<8){n("CEP inválido.");return}if(Se(C).length!==11){n("CPF do titular inválido.");return}if(!String(de).trim()){n("Informe o número do endereço do titular.");return}if(!le.trim()){n("Informe o nome impresso no cartão.");return}const T=Se(O);S(!0),U("pagar_cartao","Pagar agora",{payment_method:"credit_card"});try{const Ce={holderName:le.trim(),number:Se(H),expiryMonth:T.slice(0,2),expiryYear:T.slice(2),ccv:Se(ie)},Le={name:le.trim(),cpfCnpj:Se(C),postalCode:Se(D),addressNumber:String(de).trim()};if(g){const{data:je}=await Ee.createSubscription({planPurpose:l,billingType:"CREDIT_CARD",card:Ce,holderInfo:Le,...L()});Je("AddPaymentInfo",He(l,fe,a,{payment_method:"credit_card"})),I(!0),gt({purpose:l,amount:fe,paymentId:je.paymentId,subscriptionId:je.subscriptionId,isSubscription:!0}
1),K(je.paymentId,je.amount),f({paymentId:je.paymentId,subscriptionId:je.subscriptionId,status:"ACTIVE"})}else{const{data:je}=await Ee.checkoutCard({purpose:l,referenceId:a,appointmentId:x,couponCode:ge,card:Ce,holderInfo:Le,...L()});Je("AddPaymentInfo",He(l,fe,a,{payment_method:"credit_card"})),je.approved?(I(!0),gt({purpose:l,amount:Number(je.amount)||fe,paymentId:je.paymentId,isSubscription:g}),K(je.paymentId,je.amount),f({paymentId:je.paymentId,status:je.status})):n("Não foi possível processar seu cartão. Verifique os dados e tente novamente.")}}catch(Ce){const Le=(Z=(ne=Ce==null?void 0:Ce.response)==null?void 0:ne.data)==null?void 0:Z.code;n(Le==="COUPON_USE_FREE_CHECKOUT"?"Este cupom zera o valor. Use o botão de confirmação gratuita.":((q=(we=Ce==null?void 0:Ce.response)==null?void 0:we.data)==null?void 0:q.message)||"Não foi possível processar seu cartão. Verifique os dados e tente novamente.")}finally{S(!1)}},Pe=async()=>{u!=null&&u.payload&&(await navigator.clipboard.writeText(u.payload),v(!0),U("copiar_pix","Copiar código Pix",{payment_method:"pix"}),setTimeout(()=>v(!1),2e3))},N=()=>{U("fechar_checkout","Fechar pagamento"),s()};return t?e.jsx(Fs,{children:e.jsxs("div",{className:"fixed inset-0 z-[80] flex items-end sm:items-center justify-center p-0 sm:p-4",children:[e.jsx(ss.div,{className:"absolute inset-0 bg-slate-900/50 backdrop-blur-sm",initial:{opacity:0}
1,animate:{opacity:1},exit:{opacity:0},onClick:N}),e.jsxs(ss.div,{role:"dialog","aria-modal":"true",className:"relative w-full sm:max-w-lg bg-white rounded-t-2xl sm:rounded-2xl shadow-2xl max-h-[95vh] overflow-y-auto",initial:{y:40,opacity:0},animate:{y:0,opacity:1},exit:{y:40,opacity:0},children:[e.jsxs("div",{className:"sticky top-0 bg-white border-b border-slate-100 px-5 py-4 flex items-center justify-between rounded-t-2xl z-10",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-secondary-500",children:"Pagamento seguro Teledoc"}),e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:p.title}),p.subtitle&&e.jsx("p",{className:"text-sm text-slate-500",children:p.subtitle})]}),e.jsx("button",{type:"button",onClick:N,className:"p-2 rounded-full hover:bg-slate-100","aria-label":"Fechar",children:e.jsx(Bs,{size:20})})]}),e.jsxs("div",{className:"px-5 pt-4",children:[e.jsxs("div",{className:"rounded-xl bg-gradient-to-r from-primary-600 to-secondary-500 text-white p-4 mb-4",children:[e.jsx("p",{className:"text-sm opacity-90",children:g?"Valor da assinatura":"Pagamento por consulta"}),E&&E.discountAmount>0?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm line-through opacity-70",children:Ut(E.originalAmount)}),e.jsx("p",{className:"text-2xl font-bold",children:se?"Grátis":Ut(E.finalAmount)}),e.jsxs("p",{className:"text-xs mt-1 opacity-90 flex items-center gap-1",children:[e.jsx(bs,{size:12}),"Cupom ",E.coupon.code," · −",Ut(E.discountAmount)]})]}):e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:p.amountLabel||"Consulte o valor"}),!g&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:"Valor avulso · sem mensalidade"})]})]}),B?e.jsxs("div",{className:"py-10 text-center space-y-3",children:[e.jsx(Ae,{className:"mx-auto text-secondary-500",size:56}),e.jsx("p",{className:"text-xl font-bold text-slate-900",children:"Pagamento confirmado!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:"Continuando seu atendimento…"})]}):e.jsxs(e.Fragment,{children:[_e&&e.jsxs("div",{className:"mb-4",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500 flex items-center gap-1 mb-1",children:[e.jsx(bs,{size:12})," Cupom de desconto"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:"flex-1 rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary-600/30 uppercase",value:r,onChange:T=>A(T.target.value.toUpperCase()),placeholder:"Código do cupom",disabled:G||w||!!u,onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),E||re())}}),E?e.jsx("button",{type:"button",onClick:ee,disabled:w||!!u,className:"px-4 rounded-xl border border-slate-200 text-sm font-semibold text-primary-600 hover:bg-slate-50 disabled:opacity-50",children:"Remover"}):e.jsx("button",{type:"button",onClick:re,disabled:G||w||!r.trim(),className:"px-4 rounded-xl bg-slate-800 text-white text-sm font-semibold hover:bg-slate-700 disabled:opacity-50 min-w-[88px]",children:G?e.jsx(pe,{className:"animate-spin mx-auto",size:16}):"Aplicar"})]})]}),se?e.jsxs("div",{className:"space-y-4 pb-6",children:[y&&e.jsx("div",{className:"rounded-xl bg-red-50 text-red-700 text-sm px-3 py-2 border border-red-100",children:y}),e.jsx("p",{className:"text-sm text-slate-600 text-center",children:"Cupom 100% aplicado. Confirme para continuar sem cobrança."}),e.jsx(M,{className:"w-full",onClick:$e,disabled:w,children:w?e.jsx(pe,{className:"animate-spin",size:18}):"Confirmar atendimento grátis"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2 p-1 bg-slate-100 rounded-xl mb-4",children:[e.jsxs("button",{type:"button",className:`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-semibold transition ${j==="pix"?"bg-white shadow text-primary-600":"text-slate-500"}`,onClick:()=>{P("pix"),U("pagamento_pix","Pix",{payment_method:"pix"})},children:[e.jsx(Gs,{size:16})," Pix"]}),e.jsxs("button",{type:"button",className:`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-semibold transition ${j==="card"?"bg-white shadow text-primary-600":"text-slate-500"}`,onClick:()=>{P("card"),U("pagamento_cartao","Cartão",{payment_method:"credit_card"})},children:[e.jsx(zt,{size:16})," Cartão"]})]}),y&&e.jsx("div",{className:"mb-3 rounded-xl bg-red-50 text-red-700 text-sm px-3 py-2 border border-red-100",children:y}),j==="pix"&&e.jsx("div",{className:"space-y-4 pb-6",children:u?e.jsxs("div",{className:"space-y-3 text-center",children:[u.encodedImage&&e.jsx("img",{src:`data:image/png;base64,${u.encodedImage}`,alt:"QR Code Pix",className:"mx-auto w-48 h-48 rounded-xl border border-slate-100"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Escaneie o QR ou copie o código Pix. A confirmação é automática."}),u.expirationDate&&e.jsx(tl,{until:u.expirationDate}),e.jsxs("button",{type:"button",onClick:Pe,className:"w-full flex items-center justify-center gap-2 rounded-xl border border-slate-200 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50",children:[e.jsx(da,{size:16}),i?"Copiado!":"Copiar código Pix"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-secondary-600 text-sm",children:[e.jsx(pe,{className:"animate-spin",size:14}),"Aguardando pagamento…"]})]}):e.jsx(M,{className:"w-full",onClick:ye,disabled:w,children:w?e.jsx(pe,{className:"animate-spin",size:18}):"Gerar QR Code Pix"})}),j==="card"&&e.jsxs("div",{className:"space-y-3 pb-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Nome no cartão"}),e.jsx("input",{className:"mt-1 w-full rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary-600/30",value:le,onChange:T=>b(T.target.value),autoComplete:"cc-name"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Número ",be&&e.jsxs("span",{className:"text-primary-600",children:["· ",be]})]}),e.jsx("input",{className:"mt-1 w-full rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary-600/30",value:H,onChange:T=>R(Qa(T.target.value)),inputMode:"numeric",autoComplete:"cc-number",placeholder:"0000 0000 0000 0000"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Validade"}),e.jsx("input",{className:"mt-1 w-full rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary-600/30",value:O,onChange:T=>W(Ya(T.target.value)),placeholder:"MM/AA",inputMode:"numeric",autoComplete:"cc-exp"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"CVV"}),e.jsx("input",{className:"mt-1 w-full rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary-600/30",value:ie,onChange:T=>ce(Se(T.target.value).slice(0,4)),inputMode:"numeric",autoComplete:"cc-csc",placeholder:"***"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"CPF do titular"}),e.jsx("input",{className:"mt-1 w-full rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary-600/30",value:C,onChange:T=>k(Xa(T.target.value)),inputMode:"numeric"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"CEP"}),e.jsx("input",{className:"mt-1 w-full rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary-600/30",value:D,onChange:T=>J(Ja(T.target.value)),inputMode:"numeric"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Número do endereço"}),e.jsx("input",{className:"mt-1 w-full rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary-600/30",value:de,onChange:T=>he(T.target.value),placeholder:"Ex.: 100",autoComplete:"address-line2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Pagamento à vista — sem parcelamento."}),e.jsx(M,{className:"w-full",onClick:ke,disabled:w,children:w?e.jsx(pe,{className:"animate-spin",size:18}):"Pagar agora"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-slate-400 pb-5",children:[e.jsx(Hs,{size:12}),"Ambiente seguro • Criptografia de ponta a ponta"]})]})]})]})}):null},z={screeningChat:(t,s)=>V.post("/patients/screening/chat",{messages:t,appointment_hash:s}),transcribeAudio:t=>{const s=new FormData;return s.append("audio",t),V.post("/patients/screening/transcribe",s,{headers:{"Content-Type":"multipart/form-data"}})},createAppointment:t=>V.post("/patients/appointments",t),getAppointments:()=>V.get("/patients/me/appointments"),prepareEmergency:t=>V.post("/patients/me/emergency/prepare",t||{}),startEmergency:t=>V.post("/patients/me/emergency/start",t),startEmergencyWithCredit:t=>V.post("/patients/me/emergency/start-with-credit",t||{}),getCredits:()=>V.get("/patients/me/credits"),abandonEmergency:t=>V.post("/patients/me/emergency/abandon",t),getSpecialties:()=>V.get("/patients/specialties"),getPlanCoverage:()=>V.get("/patients/me/plan-coverage"),getSpecialtyAvailability:(t,s,l)=>V.get(`/patients/specialties/${t}/availability`,{params:{from:s,to:l}}),reserveAppointment:t=>V.post("/patients/appointments/reserve",t),cancelAppointment:t=>V.post(`/patients/appointments/${t}/cancel`),rescheduleAppointment:(t,s)=>V.post(`/patients/appointments/${t}/reschedule`,s),getEmergencyWaitEstimate:()=>V.get("/patients/me/emergency/wait-estimate"),rateAppointment:(t,s,l)=>V.post(`/patients/appointments/${t}/rating`,{rating:s,comment:l}),getWellness:t=>V.get("/patients/me/wellness",{params:t||{days:7}}),updateWellnessGoals:t=>V.put("/patients/me/wellness/goals",t),logSleep:t=>V.post("/patients/me/wellness/sleep",t),logWater:t=>V.post("/patients/me/wellness/water",t),logActivity:t=>V.post("/patients/me/wellness/activity",t),logAlcohol:t=>V.post("/patients/me/wellness/alcohol",t),logSteps:t=>V.post("/patients/me/wellness/steps",t),logFood:t=>V.post("/patients/me/wellness/food",t),analyzeFood:t=>{const s=new FormData;return s.append("photo",t),V.post("/patients/me/wellness/food/analyze",s,{headers:{"Content-Type":"multipart/form-data"}})},logWeight:t=>V.post("/patients/me/wellness/weight",t),getWeightHistory:(t=30)=>V.get("/patients/me/wellness/weight",{params:{days:t}}),deleteWellnessLog:(t,s)=>V.delete(`/patients/me/wellness/${t}/${s}`),deleteWellnessDay:(t,s)=>V.delete(`/patients/me/wellness/${t}`,{params:{date:s}}),getHealthProfile:()=>V.get("/health-profile"),updateHealthProfile:t=>V.put("/health-profile",t),patchHealthProfile:t=>V.patch("/health-profile",t),getAppointmentMedicalDocuments:t=>V.get(`/medical-documents/${t}`),getAppointmentDetails:t=>V.get(`/patients/me/appointments/${t}/details`)};function Fe(t){return String(t||"").replace(/\D/g,"")}function Ns(t){const s=Fe(t);if(s.length!==8)return null;const l=Number(s.slice(0,2)),a=Number(s.slice(2,4)),x=Number(s.slice(4,8)),p=new Date(x,a-1,l);if(p.getFullYear()!==x||p.getMonth()!==a-1||p.getDate()!==l)return null;const c=new Date;return c.setHours(23,59,59,999),p>c||x<1900?null:`${String(x).padStart(4,"0")}-${String(a).padStart(2,"0")}-${String(l).padStart(2,"0")}`}function bt(t){return`R$ ${Number(t).toFixed(2).replace(".",",")}`}function qt(t){return t===1?"crédito":"créditos"}function sl(t){const s=Number(t)||49.9;return[{code:"PACK_1",credits:1,discount:0,label:"1 consulta",unit_amount:s,amount:s,savings:0},{code:"PACK_5",credits:5,discount:.05,label:"Pacote 5 consultas",unit_amount:s,amount:Math.round(s*5*.95*100)/100,savings:Math.round(s*5*.05*100)/100},{code:"PACK_10",credits:10,discount:.1,label:"Pacote 10 consultas",unit_amount:s,amount:Math.round(s*10*.9*100)/100,savings:Math.round(s*10*.1*100)/100}]}async function al(t){for(let s=0;s<8;s+=1){const{data:l}=await z.getCredits();if(Number(l.balance||0)>=t)return l;await new Promise(a=>setTimeout(a,1200))}return(await z.getCredits()).data}const ll=[{n:1,title:"Dados"},{n:2,title:"Perfil"},{n:3,title:"Créditos"}],nl=()=>{const t=Me(),{isAuthenticated:s,login:l}
1=Re(),[a,x]=o.useState(1),[p,c]=o.useState(!1),[g,f]=o.useState(!1),[j,P]=o.useState(""),[w,S]=o.useState(!1),[y,n]=o.useState([]),[u,_]=o.useState(49.9),[i,v]=o.useState("PACK_5"),[B,I]=o.useState(0),[r,A]=o.useState({name:"",document_number:"",email:"",phone:"",birth_date:"",gender:"",address_zipcode:"",emergency_contact_phone:"",password:""}),G=y.length?y:sl(u),$=G.find(C=>C.code===i)||G[0],E=bt($?$.amount:u);o.useEffect(()=>{s&&!p&&t("/patient/emergency",{replace:!0})},[s,p,t]),o.useEffect(()=>{Ee.getPublicPrices().then(({data:C})=>{var D,J;const k=(D=C.prices)==null?void 0:D.find(de=>de.code==="EMERGENCY");k&&_(Number(k.amount)),(J=C.credit_packs)!=null&&J.length&&n(C.credit_packs)}).catch(()=>{})},[]);const Y=(C,k)=>{A(D=>({...D,[C]:k}))},le=()=>{if(!r.name.trim()||!r.email.trim()||!r.document_number||!r.phone||!r.birth_date)return"Preencha nome, CPF, data de nascimento, e-mail e telefone.";if(Fe(r.document_number).length!==11)return"Informe um CPF válido.";if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r.email.trim()))return"Informe um e-mail válido.";const C=Fe(r.phone);return C.length<10||C.length>11?"Informe um telefone válido.":Ns(r.birth_date)?"":"Informe uma data de nascimento válida."},b=()=>{if(!r.gender)return"Selecione o sexo.";if(Fe(r.address_zipcode).length!==8)return"Informe um CEP válido.";const C=Fe(r.emergency_contact_phone);return C.length<10||C.length>11?"Informe um telefone de emergência válido.":r.password.length<6?"A senha deve ter pelo menos 6 caracteres.":""},H=async()=>{var C,k;try{const{data:D}=await Ee.getPrices(),J=(C=D.prices)==null?void 0:C.find(de=>de.code==="EMERGENCY");J&&_(Number(J.amount)),(k=D.credit_packs)!=null&&k.length&&n(D.credit_packs)}catch{}},R=async()=>{var C;if(P(""),a===1){const k=le();if(k){P(k);return}x(2);return}if(a===2){const k=b();if(k){P(k);return}f(!0);try{const{data:D}=await V.post("/auth/register/patient",{name:r.name.trim(),email:r.email.trim(),document_number:Fe(r.document_number),phone:Fe(r.phone)||void 0,birth_date:Ns(r.birth_date),gender:r.gender||void 0,address_zipcode:Fe(r.address_zipcode)||void 0,emergency_contact_phone:Fe(r.emergency_contact_phone)||void 0,password:r.password,...na()}),J=Number((D==null?void 0:D.patient_id)??(D==null?void 0:D.id)??((C=D==null?void 0:D.patient)==null?void 0:C.id));c(!0),J&&oa(J),ia({email:r.email.trim(),phone:r.phone}),await l(r.email.trim(),r.password,ts.PATIENT),await H(),x(3)}catch(D){c(!1),P(es(D,"Não foi possível criar sua conta. Se já possui cadastro, entre na plataforma."))}finally{f(!1)}}},O=async C=>{C!=null&&C.paymentId&&Rs({paymentId:C.paymentId,value:($==null?void 0:$.amount)??0,contentName:"CREDIT_PACK"}),S(!1),f(!0),P("");try{const k=($==null?void 0:$.credits)||1,D=await al(k);I(Number(D.balance||k)),x(4)}catch{I(($==null?void 0:$.credits)||1),x(4)}finally{f(!1)}},W=()=>{We({option:"iniciar_consulta_agora",placement:"signup_ready",label:"Iniciar consulta agora",destination:"/patient/emergency"}),t("/patient/emergency",{replace:!0})},ie=()=>{We({option:a===3?"acessar_sem_pagar":"acessar_plataforma",placement:a===3?"signup_packs":"signup_ready",label:a===3?"Acessar plataforma sem comprar agora":"Acessar plataforma",destination:"/patient/dashboard",extra:$?{content_ids:[$.code],num_items:$.credits,payment_method:"none"}:{payment_method:"none"}}),t("/patient/dashboard",{replace:!0})},ce=o.useMemo(()=>a===4?3:a,[a]);return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-primary-50 to-indigo-50 flex items-center justify-center p-4 py-10",children:[e.jsxs(Q,{className:"w-full max-w-2xl",padding:"lg",children:[e.jsx("div",{className:"flex justify-center mb-6",children:e.jsx(Ls,{className:"w-40 h-14",textClassName:"hidden"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900 text-center",children:"Criar conta"}),e.jsx("p",{className:"text-slate-500 text-center mt-1 mb-6",children:"Cadastre-se, e seja atendido agora."}),a<4&&e.jsx("div",{className:"flex items-center justify-center gap-2 mb-8",children:ll.map((C,k)=>{const D=ce===C.n,J=ce>C.n;return e.jsxs(aa.Fragment,{children:[k>0&&e.jsx("div",{className:`h-0.5 w-8 sm:w-12 ${J?"bg-primary-500":"bg-slate-200"}`}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${J||D?"bg-primary-600 text-white":"bg-slate-200 text-slate-500"}`,children:J?e.jsx(Ft,{size:16}):C.n}),e.jsx("span",{className:`text-[11px] font-semibold ${D?"text-primary-700":"text-slate-400"}`,children:C.title})]})]},C.n)})}),j&&e.jsx("div",{className:"mb-4 rounded-xl bg-red-50 text-red-700 px-4 py-3 text-sm",children:j}),a===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ve,{label:"Nome",placeholder:"Seu nome completo",value:r.name,onChange:C=>Y("name",C.target.value)}),e.jsx(ve,{label:"CPF",placeholder:"000.000.000-00",mask:"cpf",value:r.document_number,onChange:C=>Y("document_number",C.target.value)}),e.jsx(ve,{label:"Data de nascimento *",mask:"date",placeholder:"DD/MM/AAAA",value:r.birth_date,onChange:C=>Y("birth_date",C.target.value),required:!0}),e.jsx(ve,{label:"E-mail",type:"email",placeholder:"[email protected]",value:r.email,onChange:C=>Y("email",C.target.value)}),e.jsx(ve,{label:"Telefone",placeholder:"(00) 00000-0000",mask:"phone",value:r.phone,onChange:C=>Y("phone",C.target.value)}),e.jsx(M,{className:"w-full",size:"lg",onClick:R,children:"Continuar"})]}),a===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Xs,{value:r.gender,onCh
1ange:C=>Y("gender",C)}),e.jsx(ve,{label:"CEP",placeholder:"00000-000",mask:"cep",inputMode:"numeric",value:r.address_zipcode,onChange:C=>Y("address_zipcode",C.target.value)}),e.jsx(ve,{label:"Telefone de emergência",placeholder:"(00) 00000-0000",mask:"phone",value:r.emergency_contact_phone,onChange:C=>Y("emergency_contact_phone",C.target.value)}),e.jsx(ve,{label:"Senha",type:"password",placeholder:"Mínimo 6 caracteres",value:r.password,onChange:C=>Y("password",C.target.value)}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(M,{type:"button",variant:"outline",className:"flex-1",size:"lg",onClick:()=>{P(""),x(1)},children:"Voltar"}),e.jsx(M,{className:"flex-1",size:"lg",onClick:R,isLoading:g,children:"Continuar"})]})]}),a===3&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary-700 mb-2",children:[e.jsx(Os,{size:20}),e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Escolha seu pacote"})]}),e.jsx("p",{className:"text-sm text-slate-500 mb-5",children:"Pague agora. Depois você pode iniciar a consulta ou entrar na plataforma. O crédito só é descontado quando um profissional assume o atendimento."}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3 mb-6",children:G.map(C=>{const k=C.credits>0?C.amount/C.credits:C.amount,D=C.code==="PACK_5",J=i===C.code;return e.jsxs("button",{type:"button",onClick:()=>{v(C.code),zs(C)},className:`relative text-left rounded-2xl border-2 p-4 transition ${J?"border-primary-500 bg-primary-50 shadow-md":"border-slate-200 bg-white hover:border-primary-200"}`,children:[D&&e.jsx("span",{className:"absolute -top-2 left-3 text-[10px] font-bold uppercase tracking-wide bg-emerald-600 text-white px-2 py-0.5 rounded-full",children:"Mais vantajoso"}),e.jsx("p",{className:"text-3xl font-extrabold text-slate-900 mt-1",children:C.credits}),e.jsx("p",{className:"text-xs font-semibold text-slate-600 mb-2",children:C.credits===1?"consulta":"consultas"}),e.jsx("p",{className:"text-lg font-bold text-primary-700",children:bt(C.amount)}),e.jsxs("p",{className:"text-[11px] text-slate-500 mt-1",children:[bt(k)," por consulta"]}),C.savings>0&&e.jsxs("p",{className:"text-[11px] font-semibold text-emerald-700 mt-1",children:["Economia de ",bt(C.savings)]})]},C.code)})}),e.jsx(M,{className:"w-full",size:"lg",onClick:()=>{$&&We({option:"pagar_creditos",placement:"signup_packs",label:`Pagar ${E}`,destination:"checkout",extra:{content_ids:[$.code],value:$.amount,currency:"BRL",num_items:$.credits}}),S(!0)},disabled:g,children:g?e.jsx(pe,{className:"animate-spin"}):`Pagar ${E} e receber ${($==null?void 0:$.credits)||1} ${qt(($==null?void 0:$.credits)||1)}`}),e.jsx(M,{type:"button",variant:"outline",className:"w-full mt-3",size:"lg",onClick:ie,disabled:g,children:"Acessar plataforma sem comprar agora"})]}),a===4&&e.jsxs("div",{className:"text-center space-y-5",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-50 text-emerald-600 flex items-center justify-center mx-auto",children:e.jsx(Ft,{size:32})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"Conta pronta"}),e.jsxs("p",{className:"text-slate-500 mt-1",children:[B," ",qt(B)," na sua conta. Você já está autenticado."]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(M,{className:"w-full",size:"lg",onClick:W,icon:e.jsx(lt,{size:18}),children:"Iniciar consulta agora"}),e.jsx(M,{variant:"outline",className:"w-full",size:"lg",onClick:ie,children:"Acessar plataforma"})]})]}),a<4&&e.jsxs("p",{className:"text-center text-sm text-slate-500 mt-6",children:["Já tem conta?"," ",e.jsx(Nt,{to:"/patient",className:"font-semibold text-primary-700 hover:underline",children:"Entrar"})]})]}),e.jsx(Wt,{open:w,onClose:()=>S(!1),purpose:"CREDIT_PACK",referenceId:i,amount:$==null?void 0:$.amount,summary:{title:`${($==null?void 0:$.credits)||1} ${qt(($==null?void 0:$.credits)||1)} de consulta`,subtitle:"Pagamento do pacote na criação da conta",amountLabel:E},onSuccess:O})]})},ol=({value:t,max:s,colorClass:l,size:a=120,strokeWidth:x=10,children:p})=>{const c=(a-x)/2,g=c*2*Math.PI,f=Math.min(t/s,1),j=g-f*g;return e.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:a,height:a},children:[e.jsxs("svg",{className:"transform -rotate-90 w-full h-full",children:[e.jsx("circle",{cx:a/2,cy:a/2,r:c,strokeWidth:x,className:"stroke-slate-100 fill-none"}),e.jsx("circle",{cx:a/2,cy:a/2,r:c,strokeWidth:x,className:`fill-none transition-all duration-1000 ease-out ${l}`,strokeLinecap:"round",strokeDasharray:g,strokeDashoffset:j,stroke:"currentColor"})]}),e.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:p})]})},At=({label:t,current:s,unit:l,Icon:a,colorTheme:x,onLog:p,isLogging:c})=>e.jsxs(Q,{className:"p-3 border-0 shadow-sm rounded-xl flex items-center justify-between group overflow-hidden relative",children:[e.jsx("div",{className:`absolute -right-4 -bottom-4 w-16 h-16 bg-gradient-to-br ${x.bgGradient} opacity-10 rounded-full transition-transform group-hover:scale-150`}),e.jsxs("div",{className:"flex items-center gap-3 relative z-10",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg bg-gradient-to-br ${x.iconBg} text-white flex items-center justify-center shadow-sm shrink-0`,children:e.jsx(a,{size:18})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-wider text-slate-400 mb-0.5",children:t}),e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-lg font-extrabold text-slate-800",children:s}),l&&e.jsx("span",{className:"text-[10px] font-bold text-slate-400",children:l})]})]})]}
1),e.jsx("button",{onClick:p,disabled:c,className:"w-7 h-7 rounded-full bg-slate-100 text-slate-400 flex items-center justify-center hover:bg-teal-100 hover:text-teal-600 transition-colors disabled:opacity-50 relative z-10 shrink-0",title:"Registrar rapidamente",children:c?e.jsx(pe,{size:12,className:"animate-spin"}):e.jsx(xa,{size:14})})]}),il=({score:t,loading:s})=>e.jsxs(Q,{className:"p-3 border-0 shadow-sm rounded-xl flex items-center gap-3 relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 bottom-0 left-0 w-1 bg-gradient-to-b from-teal-400 to-cyan-500"}),e.jsx(ol,{value:t||0,max:100,colorClass:"text-teal-500",size:48,strokeWidth:4,children:e.jsx("span",{className:"text-sm font-extrabold text-slate-800",children:t!=null?Math.round(Number(t)):s?"…":"—"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-wider text-slate-400 mb-0.5",children:"Health Score"}),e.jsx("p",{className:"text-[10px] font-medium text-slate-500 leading-tight",children:"Média do período"})]})]}),rl=()=>{var D,J,de,he,be,_e,se,ge,fe;const t=Me(),s=kt(),{user:l}=Re(),a=new Date,x=new Date(a.getFullYear(),a.getMonth(),1).toISOString().slice(0,10),p=new Date(a.getFullYear(),a.getMonth()+1,0).toISOString().slice(0,10),[c,g]=o.useState(x),[f,j]=o.useState(p),[P,w]=o.useState(null),[S,y]=o.useState(null),[n,u]=o.useState(null),[_,i]=o.useState(null),[v,B]=o.useState(!0),[I,r]=o.useState(""),[A,G]=o.useState(null);o.useEffect(()=>{var L;const d=(L=s.state)==null?void 0:L.flash;d&&(r(String(d)),t(s.pathname,{replace:!0,state:{}}))},[s.state,s.pathname,t]),o.useEffect(()=>{let d=!1;return(async()=>{var L;B(!0);try{const[U,K,re,ee]=await Promise.allSettled([z.getEmergencyWaitEstimate(),z.getWellness({startDate:c,endDate:f}),z.getAppointments(),z.getCredits()]);if(d)return;if(U.status==="fulfilled"&&w(U.value.data.label||null),ee.status==="fulfilled"&&y(Number(ee.value.data.balance||0)),K.status==="fulfilled"&&u(K.value.data),re.status==="fulfilled"){const $e=Array.isArray(re.value.data)?re.value.data:((L=re.value.data)==null?void 0:L.appointments)||[],ye=$e.find(Pe=>Pe.status==="in_progress"),ke=$e.find(Pe=>Number(Pe.is_emergency)===1&&Pe.queue_status==="waiting"&&!["cancelled","completed","no_show","in_progress"].includes(Pe.status));ye!=null&&ye.hash?G({kind:"in_progress",hash:ye.hash,title:ye.specialty_name||(Number(ye.is_emergency)?"Pronto-atendimento":"Consulta")}):ke!=null&&ke.hash?G({kind:"waiting",hash:ke.hash,title:"Pronto-atendimento"}):G(null)}}finally{d||B(!1)}})(),()=>{d=!0}},[c,f]),o.useEffect(()=>{if(!I)return;const d=window.setTimeout(()=>r(""),4500);return()=>window.clearTimeout(d)},[I]);const $=async d=>{i(d),r("");try{d==="water"&&await z.logWater({amountMl:250}),d==="sleep"&&await z.logSleep({hours:7.5}),d==="activity"&&await z.logActivity({minutes:30,activityType:"Caminhada"}),d==="alcohol"&&await z.logAlcohol({consumed:!1});const{data:L}=await z.getWellness({startDate:c,endDate:f});u(L),r(d==="water"?"Água registrada (+250 ml).":d==="sleep"?"Sono registrado.":d==="activity"?"Atividade registrada.":"Dia sem álcool registrado.")}catch{r("Não foi possível registrar agora. Tente de novo.")}finally{i(null)}},E=(D=n==null?void 0:n.history)!=null&&D.water?[...n.history.water].reverse():[],Y=(J=n==null?void 0:n.history)!=null&&J.sleep?[...n.history.sleep].reverse():[],le=(de=n==null?void 0:n.history)!=null&&de.activity?[...n.history.activity].reverse():[],b=E.length>0?E.reduce((d,L)=>d+(L.ml||0),0)/E.length:0,H=Y.length>0?Y.reduce((d,L)=>d+(L.hours||0),0)/Y.length:0,R=le.length>0?le.reduce((d,L)=>d+(L.minutes||0),0)/le.length:0,O=()=>{const d=[];return b>0&&b<2e3?d.push({title:"Atenção à Hidratação",text:`Sua média é de apenas ${Math.round(b)}ml por dia neste período. Tente beber mais água.`,type:"warning",icon:Mt,color:"text-orange-500",bg:"bg-orange-50",border:"border-orange-100"}):b>=2e3&&d.push({title:"Hidratação Excelente",text:`Você está mantendo uma ótima média de ${Math.round(b)}ml por dia!`,type:"success",icon:Ae,color:"text-emerald-500",bg:"bg-emerald-50",border:"border-emerald-100"}),H>0&&H<7?d.push({title:"Sono Irregular",text:`Sua média de ${H.toFixed(1)}h por noite está abaixo do ideal (7h a 9h).`,type:"warning",icon:Mt,color:"text-amber-500",bg:"bg-amber-50",border:"border-amber-100"}):H>=7&&d.push({title:"Sono Restaurador",text:`Média de ${H.toFixed(1)}h de sono indica um excelente padrão de descanso.`,type:"success",icon:Ae,color:"text-emerald-500",bg:"bg-emerald-50",border:"border-emerald-100"}),R>0&&R<30?d.push({title:"Movimente-se Mais",text:`Sua média é de ${Math.round(R)} min/dia. Tente alcançar 30 min para melhor condicionamento.`,type:"warning",icon:Mt,color:"text-rose-500",bg:"bg-rose-50",border:"border-rose-100"}):R>=30&&d.push({title:"Excelente Condicionamento",text:`Ótimo! Você está mantendo uma média saudável de ${Math.round(R)} minutos de atividade diária.`,type:"success",icon:Ae,color:"text-emerald-500",bg:"bg-emerald-50",border:"border-emerald-100"}),d.length===0&&d.push({title:"Sem dados suficientes",text:"Registre seus hábitos diários para receber recomendações personalizadas.",type:"info",icon:pa,color:"text-blue-500",bg:"bg-blue-50",border:"border-blue-100"}),d},W=d=>{if(!d)return"";const L=d.split("T")[0].split("-");return L.length===3?`${L[2]}/${L[1]}`:d},ie=(n==null?void 0:n.score)??((he=n==null?void 0:n.healthScore)==null?void 0:he.score)??(n==null?void 0:n.healthScore)??((be=n==null?void 0:n.today)==null?void 0:be.score),ce=Number(((_e=n==null?void 0:n.today)==null?void 0:_e.waterMl)||((se=n==null?void 0:n.today)==null?void 0:se.water)||0),C=Number(((ge=n==null?void 0:n.today)==null?void 0:ge.sleepHours)||0),k=Number(((fe=n==null?void 0:n.today)==null?void 0:fe.activityMinutes)||0);return e.jsx("div",{className:"min-h-full bg-slate-50",children:e.jsxs("main",{className:"w-full px-4 sm:px-6 lg:px-8 py-4 sm:py-6 space-y-5",children:[e.jsx(Fs,{children:I&&e.jsxs(ss.div,{initial:{opacity:0,y:-8}
1,animate:{opacity:1,y:0},exit:{opacity:0,y:-8},className:"rounded-2xl bg-teal-50 text-teal-800 px-4 py-3 text-sm font-semibold flex items-center justify-between gap-3 border border-teal-100 shadow-sm",children:[e.jsx("span",{children:I}),e.jsx("button",{type:"button",onClick:()=>r(""),className:"p-1 rounded-lg hover:bg-white/60","aria-label":"Fechar",children:e.jsx(Bs,{size:16})})]})}),A&&e.jsxs(Q,{className:`rounded-2xl p-4 sm:p-5 border-0 shadow-lg relative overflow-hidden flex flex-col sm:flex-row items-center justify-between gap-4 ${A.kind==="in_progress"?"bg-gradient-to-r from-teal-700 to-teal-600 text-white":"bg-gradient-to-r from-amber-600 to-orange-500 text-white"}`,children:[e.jsx("div",{className:"absolute right-0 top-0 w-40 h-40 bg-white/10 blur-3xl rounded-full pointer-events-none"}),e.jsxs("div",{className:"relative z-10 flex items-center gap-4 w-full sm:w-auto",children:[e.jsx("div",{className:"w-12 h-12 bg-white/15 rounded-xl flex items-center justify-center shrink-0 border border-white/20",children:A.kind==="in_progress"?e.jsx(De,{size:22,className:"text-white"}):e.jsx(lt,{size:22,className:"text-white"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold leading-tight",children:A.kind==="in_progress"?"Consulta em andamento":"Você está na fila do pronto-atendimento"}),e.jsx("p",{className:"text-sm text-white/85 mt-0.5",children:A.kind==="in_progress"?`${A.title} — retome a chamada quando quiser.`:"Acompanhe a fila até o profissional iniciar o atendimento."})]})]}),e.jsx("div",{className:"relative z-10 w-full sm:w-auto",children:e.jsx(M,{className:"w-full sm:w-auto bg-white text-slate-900 hover:bg-slate-100 font-bold border-0 px-6 py-2.5 rounded-xl",onClick:()=>{A.kind==="in_progress"?t(`/call/patient/${A.hash}`):t(`/patient/emergency?resume=${encodeURIComponent(A.hash)}`)},children:A.kind==="in_progress"?"Retomar consulta":"Acompanhar fila"})})]}),!A&&e.jsx("section",{children:e.jsxs(Q,{className:"bg-gradient-to-r from-slate-900 to-slate-800 text-white rounded-2xl p-4 sm:p-5 border-0 shadow-lg relative overflow-hidden flex flex-col sm:flex-row items-center justify-between gap-4",children:[e.jsx("div",{className:"absolute right-0 top-0 w-48 h-48 bg-teal-500/20 blur-3xl rounded-full pointer-events-none"}),e.jsxs("div",{className:"relative z-10 flex items-center gap-4 w-full sm:w-auto",children:[e.jsx("div",{className:"w-12 h-12 bg-white/10 rounded-xl flex items-center justify-center shrink-0 border border-white/10",children:e.jsx(lt,{size:24,className:"text-teal-400"})}),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-bold flex flex-wrap items-center gap-2",children:["Clínico geral agora",P&&e.jsx("span",{className:"text-[10px] bg-white/10 px-2 py-0.5 rounded-full font-medium",children:P})]}),e.jsx("p",{className:"text-sm text-slate-300",children:S!=null?S>0?`${S} ${S===1?"crédito disponível":"créditos disponíveis"} · use na fila ou compre um pacote.`:"Compre 1, 5 ou 10 consultas e entre na fila quando quiser.":"Pagamento por consulta · fale com um clínico geral agora."})]})]}),e.jsxs("div",{className:"relative z-10 w-full sm:w-auto flex items-center gap-3",children:[S!=null&&e.jsxs("div",{className:"hidden sm:block text-right mr-1",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-slate-400",children:"Saldo"}),e.jsx("p",{className:"text-xl font-extrabold text-white",children:S})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 w-full sm:w-auto",children:[e.jsx(M,{className:"w-full sm:w-auto bg-teal-500 hover:bg-teal-600 text-white font-bold border-0 px-6 py-2.5 rounded-xl whitespace-nowrap shadow-md shadow-teal-900/50",onClick:()=>{const d=S!=null&&S>0;We({option:d?"usar_credito":"consultar_agora",placement:"patient_dashboard",label:d?"Usar 1 crédito":"Consultar agora",destination:"/patient/emergency"}),t("/patient/emergency")},children:S!=null&&S>0?"Usar 1 crédito":"Consultar agora"}),S!=null&&e.jsx(M,{variant:"outline",className:"w-full sm:w-auto border-white/40 text-white hover:bg-white/10 font-bold px-6 py-2.5 rounded-xl whitespace-nowrap",onClick:()=>{We({option:"comprar_mais_creditos",placement:"patient_dashboard",label:"Comprar mais créditos",de
1stination:"/patient/emergency?buy=1"}),t("/patient/emergency?buy=1")},children:"Comprar mais créditos"})]})]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("h2",{className:"text-xl font-extrabold text-slate-800 flex items-center gap-2 tracking-tight",children:[e.jsx(Be,{className:"text-teal-500",size:24})," Resumo de Bem-Estar"]}),e.jsxs("div",{className:"flex items-center gap-2 bg-white p-1.5 rounded-lg border border-slate-200 shadow-sm w-full sm:w-auto min-w-0",children:[e.jsx("input",{type:"date",value:c,onChange:d=>g(d.target.value),className:"text-xs font-semibold text-slate-600 bg-transparent border-0 focus:ring-0 cursor-pointer outline-none flex-1 min-w-0 sm:w-28"}),e.jsx("span",{className:"text-slate-300 font-medium text-xs shrink-0",children:"até"}),e.jsx("input",{type:"date",value:f,onChange:d=>j(d.target.value),className:"text-xs font-semibold text-slate-600 bg-transparent border-0 focus:ring-0 cursor-pointer outline-none flex-1 min-w-0 sm:w-28"})]})]}),e.jsxs("section",{className:"grid grid-cols-2 lg:grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-2 lg:col-span-1",children:e.jsx(il,{score:ie,loading:v})}),e.jsx(At,{label:"Água (Hoje)",current:ce,unit:"ml",Icon:Qe,colorTheme:{bgGradient:"from-cyan-300 to-blue-400",iconBg:"from-cyan-400 to-blue-500"},onLog:()=>$("water"),isLogging:_==="water"}),e.jsx(At,{label:"Sono (Hoje)",current:C,unit:"h",Icon:Ue,colorTheme:{bgGradient:"from-indigo-300 to-purple-400",iconBg:"from-indigo-400 to-purple-500"},onLog:()=>$("sleep"),isLogging:_==="sleep"}),e.jsx(At,{label:"Movimento (Hoje)",current:k,unit:"min",Icon:De,colorTheme:{bgGradient:"from-orange-300 to-rose-400",iconBg:"from-orange-400 to-rose-500"},onLog:()=>$("activity"),isLogging:_==="activity"}),e.jsx(At,{label:"Sem Álcool",current:"Hoje",unit:"",Icon:ma,colorTheme:{bgGradient:"from-emerald-300 to-teal-400",iconBg:"from-emerald-400 to-teal-500"},onLog:()=>$("alcohol"),isLogging:_==="alcohol"})]}),e.jsxs("section",{className:"grid grid-cols-1 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"lg:col-span-3 grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(Q,{className:"p-4 sm:p-5 rounded-2xl border-0 shadow-sm flex flex-col h-72",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-4 flex items-center gap-2",children:[e.jsx(Qe,{size:16,className:"text-blue-500"})," Consumo de Água (ml)"]}),e.jsx("div",{className:"flex-1 min-h-0 w-full",children:e.jsx(vt,{width:"100%",height:"100%",children:e.jsxs(ls,{data:E,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorWater",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#3b82f6",stopOpacity:.4}),e.jsx("stop",{offset:"95%",stopColor:"#3b82f6",stopOpacity:0})]})}),e.jsx(It,{strokeDasharray:"3 3",vertical:!1,stroke:"#e2e8f0"}),e.jsx(Lt,{dataKey:"date",tickFormatter:W,tick:{fontSize:10,fill:"#94a3b8"},tickLine:!1,axisLine:!1,minTickGap:20}),e.jsx(Tt,{tick:{fontSize:10,fill:"#94a3b8"},tickLine:!1,axisLine:!1,domain:[0,"dataMax + 500"]}),e.jsx(Rt,{contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 10px 15px -3px rgb(0 0 0 / 0.1)"},labelStyle:{fontWeight:"bold",color:"#64748b",marginBottom:"4px"},itemStyle:{fontWeight:"800",color:"#3b82f6"},labelFormatter:d=>W(d)}),e.jsx(Oe,{type:"monotone",dataKey:"ml",stroke:"#3b82f6",strokeWidth:3,fillOpacity:1,fill:"url(#colorWater)",activeDot:{r:6,fill:"#3b82f6",stroke:"#fff",strokeWidth:2}})]})})})]}),e.jsxs(Q,{className:"p-4 sm:p-5 rounded-2xl border-0 shadow-sm flex flex-col h-72",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-4 flex items-center gap-2",children:[e.jsx(Ue,{size:16,className:"text-indigo-500"})," Qualidade do Sono (h)"]}),e.jsx("div",{className:"flex-1 min-h-0 w-full",children:e.jsx(vt,{width:"100%",height:"100%",children:e.jsxs(Ma,{data:Y,margin:{top:10,right:10,left:-20,bottom:0},barSize:24,children:[e.jsx(It,{strokeDasharray:"3 3",vertical:!1,stroke:"#e2e8f0"}),e.jsx(Lt,{dataKey:"date",tickFormatter:W,tick:{fontSize:10,fill:"#94a3b8"}
1,tickLine:!1,axisLine:!1,minTickGap:20}),e.jsx(Tt,{tick:{fontSize:10,fill:"#94a3b8"},tickLine:!1,axisLine:!1,domain:[0,12],ticks:[0,4,8,12]}),e.jsx(Rt,{contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 10px 15px -3px rgb(0 0 0 / 0.1)"},labelStyle:{fontWeight:"bold",color:"#64748b",marginBottom:"4px"},itemStyle:{fontWeight:"800",color:"#6366f1"},cursor:{fill:"#f1f5f9"},labelFormatter:d=>W(d)}),e.jsx(Ia,{dataKey:"hours",fill:"#6366f1",radius:[4,4,0,0]})]})})})]}),e.jsxs(Q,{className:"p-4 sm:p-5 rounded-2xl border-0 shadow-sm flex flex-col h-72",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-4 flex items-center gap-2",children:[e.jsx(De,{size:16,className:"text-rose-500"})," Atividade Física (min)"]}),e.jsx("div",{className:"flex-1 min-h-0 w-full",children:e.jsx(vt,{width:"100%",height:"100%",children:e.jsxs(ls,{data:le,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorActivity",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#f43f5e",stopOpacity:.4}),e.jsx("stop",{offset:"95%",stopColor:"#f43f5e",stopOpacity:0})]})}),e.jsx(It,{strokeDasharray:"3 3",vertical:!1,stroke:"#e2e8f0"}),e.jsx(Lt,{dataKey:"date",tickFormatter:W,tick:{fontSize:10,fill:"#94a3b8"},tickLine:!1,axisLine:!1,minTickGap:20}),e.jsx(Tt,{tick:{fontSize:10,fill:"#94a3b8"},tickLine:!1,axisLine:!1,domain:[0,"auto"]}),e.jsx(Rt,{contentStyle:{borderRadius:"12px",border:"none",boxShadow:"0 10px 15px -3px rgb(0 0 0 / 0.1)"},labelStyle:{fontWeight:"bold",color:"#64748b",marginBottom:"4px"},itemStyle:{fontWeight:"800",color:"#f43f5e"},labelFormatter:d=>W(d)}),e.jsx(Oe,{type:"monotone",dataKey:"minutes",stroke:"#f43f5e",strokeWidth:3,fillOpacity:1,fill:"url(#colorActivity)",activeDot:{r:6,fill:"#f43f5e",stroke:"#fff",strokeWidth:2}})]})})})]})]}),e.jsxs(Q,{className:"p-5 rounded-2xl border-0 shadow-sm bg-gradient-to-b from-white to-slate-50 flex flex-col h-72 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-teal-100 flex items-center justify-center",children:e.jsx(Be,{size:14,className:"text-teal-600"})}),e.jsx("h3",{className:"text-sm font-bold text-slate-800",children:"Insights de Saúde"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto pr-2 space-y-3 custom-scrollbar",children:O().map((d,L)=>e.jsxs("div",{className:`p-3 rounded-xl border ${d.bg} ${d.border} flex gap-3 items-start`,children:[e.jsx(d.icon,{size:16,className:`${d.color} shrink-0 mt-0.5`}),e.jsxs("div",{children:[e.jsx("h4",{className:`text-xs font-bold ${d.color} mb-1`,children:d.title}),e.jsx("p",{className:"text-xs text-slate-600 font-medium leading-relaxed",children:d.text})]})]},L))})]})]}),e.jsx("section",{children:e.jsx("div",{className:"grid grid-cols-1 gap-3",children:e.jsxs("button",{type:"button",onClick:()=>t("/patient/profile"),className:"rounded-xl border border-slate-100 bg-white hover:border-teal-200 hover:shadow-sm p-4 text-left transition-all group flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-indigo-50 flex items-center justify-center shrink-0",children:e.jsx(ua,{className:"text-indigo-500",size:18})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-slate-800 text-sm",children:"Meu Perfil"}),e.jsx("p",{className:"text-xs font-medium text-slate-400 mt-0.5",children:"Gerencie seus dados e dependentes."})]})]})})})]})})},cl=()=>{const t=Me();return e.jsxs("div",{className:"min-h-full bg-slate-50 pb-20",children:[e.jsxs("header",{className:"w-full px-4 sm:px-6 lg:px-8",children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-gray-800",children:"Novo atendimento"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Escolha como prefere ser atendido"})]}),e.jsxs("main",{className:"w-full px-4 sm:px-6 lg:px-8 mt-6 grid sm:grid-cols-2 gap-4",children:[e.jsxs(Q,{className:"p-6 rounded-2xl border-0 shadow-lg flex flex-col",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-primary-50 text-primary-600 flex items-center justify-center mb-4",children:e.jsx(lt,{size:24})}),e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Pronto-atendimento 24 horas, 7 dias por semana"}),e.jsx("p",{className:"text-sm text-slate-500 mb-6 flex-1",children:"Pagamento por consulta: avaliação inicial, Pix ou cartão e fila com clínico geral — em minutos. Sem mensalidade."}),e.jsxs(M,{className:"w-full",onClick:()=>t("/patient/emergency"),children:["Atendimento agora ",e.jsx(ha,{size:16,className:"ml-2"})]})]}),e.jsxs(Q,{className:"p-6 rounded-2xl border-0 shadow-lg flex flex-col opacity-90",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-secondary-500/10 text-secondary-600 flex items-center justify-center mb-4",children:e.jsx(Ht,{size:24})}),e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"Especialidades"}),e.jsx("span",{className:"inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-amber-50 text-amber-700 border border-amber-200",children:"Em breve"})]}),e.jsx("p",{className:"text-sm text-slate-500 mb-6 flex-1",children:"Consultas agendadas por especialidade serão liberadas em breve. Por enquanto, use o pronto-atendimento."}),e.jsx(M,{className:"w-full",variant:"outline",disabled:!0,children:"Agendar consulta · Em breve"})]})]})]})},ws=new Set(["scheduled","confirmed","pending_payment","in_progress"]),dl={scheduled:"Agendada",confirmed:"Confirmada",pending_payment:"Aguardando pagamento",in_progress:"Em andamento",completed:"Concluída",cancelled:"Cancelada",no_show:"Não compareceu"},ml={prescription:"Receita",exam_request:"Exames",medical_certificate:"Atestado",referral:"Encaminhamento"},st=t=>!!Number(t.is_emergency),Cs=t=>st(t)&&t.status==="pending_payment",Kt=t=>t.status==="in_progress",_s=t=>st(t)&&t.queue_status==="waiting"&&!["completed","cancelled","no_show","in_progress"].includes(t.status),ul=()=>{const{user:t}
1=Re(),s=Me(),[l,a]=o.useState([]),[x,p]=o.useState(!0),[c,g]=o.useState(""),[f,j]=o.useState("upcoming"),[P,w]=o.useState(null),[S,y]=o.useState([]),[n,u]=o.useState(!1),[_,i]=o.useState(""),v=()=>{p(!0),g(""),z.getAppointments().then(({data:b})=>a(Array.isArray(b)?b:b.appointments||[])).catch(()=>g("Não foi possível carregar seus atendimentos.")).finally(()=>p(!1))};o.useEffect(v,[]);const B=o.useMemo(()=>l.filter(b=>ws.has(b.status)&&!Cs(b)).sort((b,H)=>+new Date(b.scheduled_datetime)-+new Date(H.scheduled_datetime)),[l]),I=o.useMemo(()=>l.filter(b=>!ws.has(b.status)&&!Cs(b)).sort((b,H)=>+new Date(H.scheduled_datetime)-+new Date(b.scheduled_datetime)),[l]),r=f==="upcoming"?B:I,A=b=>Kt(b)?!0:_s(b)||!["scheduled","confirmed"].includes(b.status)||st(b)?!1:(+new Date(b.scheduled_datetime)-Date.now())/6e4<=10,G=b=>_s(b),$=b=>f!=="upcoming"||Kt(b)||["cancelled","completed","no_show","pending_payment"].includes(b.status)?!1:["scheduled","confirmed"].includes(b.status),E=b=>st(b)||!["scheduled","confirmed"].includes(b.status)?!1:(+new Date(b.scheduled_datetime)-Date.now())/36e5>=2,Y=async b=>{var O,W,ie,ce;if(st(b)){if(!window.confirm(`Desistir deste pronto-atendimento?
2
3Se ainda não foi atendido e houve pagamento (Pix/cartão), o estorno será processado. Consultas 100% com cupom não geram estorno.`))return;i(""),g("");try{const{data:k}=await z.abandonEmergency({appointment_hash:b.hash,confirm:!0});i((k==null?void 0:k.message)||"Você saiu da fila."),v()}catch(k){g(((W=(O=k==null?void 0:k.response)==null?void 0:O.data)==null?void 0:W.message)||"Não foi possível cancelar.")}return}const R=(+new Date(b.scheduled_datetime)-Date.now())/36e5>=24?"Com 24h ou mais de antecedência, o estorno do valor pago será processado (cupom 100% não gera estorno).":"Cancelamentos com menos de 24h não geram estorno.";if(window.confirm(`Cancelar este agendamento?
4
5${R}`)){i(""),g("");try{const{data:C}=await z.cancelAppointment(b.id);i((C==null?void 0:C.message)||"Agendamento cancelado."),v()}catch(C){g(((ce=(ie=C==null?void 0:C.response)==null?void 0:ie.data)==null?void 0:ce.message)||"Não foi possível cancelar.")}}},le=async(b,H)=>{const R=await ns(`${Gt}/medical-documents/${b}/${H}/pdf`);if(!R.ok){g("Não foi possível abrir o documento.");return}const O=await R.blob(),W=URL.createObjectURL(O);window.open(W,"_blank"),setTimeout(()=>URL.revokeObjectURL(W),6e4)};return e.jsx("div",{className:"min-h-full bg-slate-50 pb-20",children:e.jsxs("main",{className:"w-full px-4 sm:px-6 lg:px-8 py-4 sm:py-10 space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-extrabold text-slate-800 tracking-tight",children:"Meus Atendimentos"}),e.jsx("p",{className:"text-sm text-slate-500 font-medium mt-1",children:"Acompanhe seu histórico e próximas consultas"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row w-full sm:w-auto gap-2",children:[e.jsx(M,{className:"w-full sm:w-auto font-bold text-slate-400 border-slate-200 cursor-not-allowed",variant:"outline",disabled:!0,children:"Agendar Especialidade · Em breve"}),e.jsx(M,{className:"w-full sm:w-auto bg-teal-500 hover:bg-teal-600 text-white font-bold",onClick:()=>s("/patient/emergency"),children:"Consultar Agora"})]})]}),_&&e.jsx("div",{className:"rounded-xl bg-emerald-50 border border-emerald-100 text-emerald-700 px-4 py-3 text-sm font-semibold",children:_}),c&&e.jsx("div",{className:"rounded-xl bg-rose-50 border border-rose-100 text-rose-700 px-4 py-3 text-sm font-semibold",children:c}),e.jsxs("div",{className:"flex bg-slate-200/50 p-1.5 rounded-xl w-full sm:w-fit",children:[e.jsx("button",{className:`flex-1 sm:px-8 py-2 rounded-lg text-sm font-bold transition-all ${f==="upcoming"?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,onClick:()=>j("upcoming"),children:"Próximas"}),e.jsx("button",{className:`flex-1 sm:px-8 py-2 rounded-lg text-sm font-bold transition-all ${f==="history"?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,onClick:()=>j("history"),children:"Histórico"})]}),x?e.jsx("div",{className:"py-20 flex justify-center",children:e.jsx(pe,{className:"animate-spin text-teal-600",
5size:32})}):r.length===0?e.jsxs(Q,{className:"p-8 sm:p-16 text-center rounded-3xl border-0 shadow-sm bg-white",children:[e.jsx("div",{className:"w-20 h-20 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Ht,{className:"text-slate-300",size:32})}),e.jsx("h3",{className:"text-lg font-bold text-slate-700 mb-2",children:"Nenhum atendimento por aqui."}),e.jsxs("p",{className:"text-sm text-slate-400 max-w-sm mx-auto leading-relaxed",children:["Você ainda não possui consultas ",f==="upcoming"?"futuras":"no seu histórico","."]})]}):e.jsx("div",{className:"space-y-4",children:r.map(b=>e.jsxs(Q,{className:`p-5 sm:p-6 rounded-2xl border border-transparent shadow-sm bg-white transition-all ${f==="history"||b.status==="completed"?"cursor-pointer hover:border-teal-200 hover:shadow-md":"hover:shadow-md"}`,onClick:()=>{(f==="history"||b.status==="completed")&&s(`/patient/agenda/${b.hash}`)},children:[e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between gap-5",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`w-12 h-12 rounded-xl flex items-center justify-center shrink-0 ${b.is_emergency?"bg-rose-50 text-rose-500":"bg-teal-50 text-teal-600"}`,children:b.is_emergency?e.jsx(lt,{size:24}):e.jsx(ga,{size:24})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-extrabold text-lg text-slate-800 leading-tight",children:b.specialty_name||(b.is_emergency?"Pronto-atendimento":"Consulta")}),e.jsx("p",{className:"text-sm font-medium text-slate-500 mt-1",children:b.is_emergency&&b.queue_status==="waiting"?"Aguardando profissional":b.professional_name?`Com ${b.professional_name}`:"Profissional a definir"}),e.jsxs("div",{className:"flex items-center gap-3 mt-4",children:[e.jsx("span",{className:`inline-block text-[10px] font-bold uppercase tracking-wider px-2.5 py-1 rounded-lg ${b.status==="cancelled"||b.status==="no_show"?"bg-rose-50 text-rose-600":"bg-slate-100 text-slate-600"}`,children:dl[b.status]||b.status}),e.jsx("span",{className:"text-sm font-bold text-slate-700",children:new Date(b.scheduled_datetime).toLocaleString("pt-BR",{dateStyle:"short",timeStyle:"short"})})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:items-end justify-center gap-2 border-t sm:border-t-0 sm:border-l border-slate-100 pt-4 sm:pt-0 sm:pl-5",children:[G(b)&&e.jsx(M,{className:"w-full sm:w-auto bg-teal-600 hover:bg-teal-700 shadow-md shadow-teal-900/10 font-bold",onClick:H=>{H.stopPropagation(),s(`/patient/emergency?resume=${encodeURIComponent(b.hash)}`)},children:"Acompanhar fila"}),A(b)&&e.jsxs(M,{className:"w-full sm:w-auto bg-teal-600 hover:bg-teal-700 shadow-md shadow-teal-900/10 font-bold",onClick:H=>{H.stopPropagation(),s(`/call/patient/${b.hash}`)},children:[e.jsx(Ws,{size:16,className:"mr-2"}),Kt(b)?"Retomar consulta":"Entrar na Sala"]}),f==="upcoming"&&E(b)&&e.jsx(M,{variant:"outline",className:"w-full sm:w-auto text-xs font-bold border-slate-200",onClick:H=>{H.stopPropagation(),s(`/patient/book?rescheduleId=${b.id}${b.specialty_id?`&specialtyId=${b.specialty_id}`:""}`)},children:"Reagendar"}),$(b)&&e.jsx(M,{variant:"outline",className:"w-full sm:w-auto text-xs font-bold text-rose-600 border-rose-200 hover:bg-rose-50",onClick:H=>{H.stopPropagation(),Y(b)},children:st(b)?"Desistir":"Cancelar"}),(f==="history"||b.status==="completed")&&e.jsx(M,{variant:"outline",title:"Ver Detalhes da Consulta",className:"w-12 h-12 p-0 rounded-full flex items-center justify-center shrink-0 border-slate-200 text-slate-500 hover:text-teal-600 hover:bg-teal-50 ml-auto",onClick:H=>{H.stopPropagation(),s(`/patient/agenda/${b.hash}`)},children:e.jsx(ba,{size:24})})]})]}),P===b.hash&&e.jsx("div",{className:"mt-5 border-t border-slate-100 pt-4 space-y-2",children:n?e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-slate-500",children:[e.jsx(pe,{className:"animate-spin text-teal-600",size:16})," Carregando documentos..."]}):S.length===0?e.jsx("p",{className:"text-sm font-medium text-slate-400",children:"Nenhum documento médico emitido nesta consulta."}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:S.map(H=>e.jsxs("button",{type:"button",className:"w-full flex items-center justify-between text-left text-sm font-bold rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 hover:bg-slate-100 hover:border-slate-300 transition-colors",onClick:()=>le(b.hash,H.hash),children:[e.jsx("span",{className:"text-slate-700",children:ml[H.document_type]||H.document_type}),e.jsx(os,{size:16,className:"text-teal-600"})]},H.hash))})})]},b.id))})]})})},xl={scheduled:"Agendada",confirmed:"Confirmada",pending_payment:"Aguardando pagamento",in_progress:"Em andamento",completed:"Concluída",cancelled:"Cancelada",no_show:"Não compareceu"},pl={prescription:"Receita",exam_request:"Pedido de Exame",medical_certificate:"Atestado Médico",referral:"Encaminhamento"},hl=()=>{const{hash:t}=Ds(),s=Me(),[l]=Bt(),{user:a}
5=Re(),[x,p]=o.useState(!0),[c,g]=o.useState(""),[f,j]=o.useState(null),[P,w]=o.useState([]),S=l.get("tab"),[y,n]=o.useState(S==="documents"||S==="attachments"||S==="chat"||S==="evolution"?S:"evolution");o.useEffect(()=>{const r=l.get("tab");(r==="documents"||r==="attachments"||r==="chat"||r==="evolution")&&n(r)},[l]),o.useEffect(()=>{if(!t)return;(async()=>{var A,G;try{p(!0);const[$,E]=await Promise.all([z.getAppointmentDetails(t),z.getAppointmentMedicalDocuments(t).catch(()=>({data:{data:[]}}))]);j($.data),w(E.data.data||[])}catch($){g(((G=(A=$.response)==null?void 0:A.data)==null?void 0:G.message)||"Erro ao carregar detalhes da consulta.")}finally{p(!1)}})()},[t]);const u=async r=>{if(t)try{const A=await ns(`${Gt}/medical-documents/${t}/${r}/pdf`);if(!A.ok)throw new Error("Não foi possível abrir");const G=await A.blob(),$=URL.createObjectURL(G);window.open($,"_blank"),setTimeout(()=>URL.revokeObjectURL($),6e4)}catch{alert("Erro ao abrir o documento.")}},_=async r=>{if(t)try{alert("Funcionalidade de download direto de anexos em implementação.")}catch{alert("Erro ao baixar o anexo.")}};if(x)return e.jsx("div",{className:"min-h-full bg-slate-50 flex items-center justify-center",children:e.jsx(pe,{className:"w-10 h-10 text-teal-600 animate-spin"})});if(c||!(f!=null&&f.appointment))return e.jsxs("div",{className:"min-h-full bg-slate-50 p-6 flex flex-col items-center justify-center",children:[e.jsx("div",{className:"text-rose-600 mb-4",children:c||"Consulta não encontrada."}),e.jsx(M,{onClick:()=>s("/patient/agenda"),variant:"outline",children:"Voltar para Agenda"})]});const{appointment:i,chat:v,attachments:B,evolutions:I}=f;return e.jsx("div",{className:"min-h-full bg-slate-50 pb-20",children:e.jsxs("main",{className:"w-full px-4 sm:px-6 lg:px-8 py-4 sm:py-10 space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4 mb-2",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-3 sm:gap-4 min-w-0",children:[e.jsx("button",{onClick:()=>s("/patient/agenda"),className:"w-10 h-10 flex items-center justify-center rounded-full bg-white border border-slate-200 hover:bg-slate-100 text-slate-600 transition-colors shrink-0",children:e.jsx(fa,{size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx("h1",{className:"text-xl sm:text-2xl font-extrabold text-slate-800 tracking-tight break-words",children:i.specialty_name?`Atendimento de ${i.specialty_name.toLowerCase()}`:i.is_emergency?"Pronto-atendimento":"Consulta"})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-1",children:[e.jsxs("span",{className:"text-sm font-medium text-slate-500",children:[new Date(i.scheduled_datetime).toLocaleDateString("pt-BR")," às ",new Date(i.scheduled_datetime).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})]}),e.jsx("span",{className:"text-slate-300 hidden sm:inline",children:"•"}),e.jsx("span",{className:`inline-block text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded ${i.status==="completed"?"bg-teal-50 text-teal-700":"bg-blue-50 text-blue-700"}`,children:xl[i.status]||i.status})]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:i.status==="in_progress"?e.jsxs(M,{onClick:()=>s(`/call/patient/${i.hash}`),className:"w-full md:w-auto bg-teal-600 hover:bg-teal-700 font-bold shadow-md shadow-teal-900/10",children:[e.jsx(Ws,{size:16,className:"mr-2"})," Retornar para Sala"]}):null})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-6 items-start mt-6",children:[e.jsx("div",{className:"lg:col-span-1 space-y-6",children:e.jsxs(Q,{className:"p-6 rounded-2xl border-0 shadow-sm bg-white flex flex-col items-center text-center",children:[e.jsx("div",{className:"w-24 h-24 rounded-full bg-slate-100 flex items-center justify-center overflow-hidden mb-4 border-4 border-white shadow-md",children:i.professional_photo?e.jsx("img",{src:i.professional_photo,alt:i.professional_name,className:"w-full h-full object-cover"}):e.jsx(Ot,{size:40,className:"text-slate-400"})}),e.jsx("h2",{className:"text-lg font-bold text-slate-800 leading-tight mb-1",children:i.professional_name||"Profissional"}),e.jsx("p",{className:"text-sm text-slate-500 font-medium",children:i.specialty_name||(i.is_emergency?"Clínico Geral":"Especialidade")}),i.registration_number&&e.jsxs("p",{className:"text-xs text-slate-400 mt-1",children:[i.registration_number," ",i.registration_state?`/ ${i.registration_state}`:""]})]})}),e.jsxs("div",{className:"lg:col-span-3",children:[e.jsx("div",{className:"flex gap-1 overflow-x-auto border-b border-slate-200 mb-6 px-1 -mx-1",children:[{id:"evolution",label:"Evolução clínica"},{id:"documents",label:"Documentos"},{id:"attachments",label:"Anexos"},{id:"chat",label:"Chat"}].map(r=>e.jsx("button",{onClick:()=>n(r.id),className:`px-3 sm:px-4 py-3 text-sm font-bold border-b-2 transition-colors shrink-0 ${y===r.id?"border-teal-600 text-teal-600":"border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300"}`,children:r.label},r.id))}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-sm border border-slate-100 min-h-[400px]",children:[y==="evolution"&&e.jsx("div",{className:"p-4 sm:p-8",children:I.length===0?e.jsxs("div",{className:"text-center py-20",children:[e.jsx(De,{className:"mx-auto text-slate-200 mb-4",size:48}),e.jsx("h3",{className:"text-lg font-bold text-slate-700 mb-2",children:"Sem registros ainda"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-sm mx-auto",children:"Nenhum prontuário registrado ou liberado para esta consulta."})]}):e.jsx("div",{className:"space-y-6",children:I.map((r,A)=>e.jsxs("div",{className:"bg-slate-50 rounded-xl p-5 border border-slate-100",children:[e.jsxs("p",{className:"text-xs font-bold text-slate-400 uppercase tracking-widest mb-4",children:["Anotado em ",new Date(r.created_at).toLocaleDateString("pt-BR")]}),e.jsx("div",{className:"space-y-4",children:r.items.map((G,$)=>e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-slate-700 mb-1",children:G.title}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed whitespace-pre-wrap",children:G.content||"N/A"})]},$))})]},A))})}),y==="documents"&&e.jsx("div",{className:"p-4 sm:p-8",children:P.length===0?e.jsxs("div",{className:"text-center py-20",children:[e.jsx(ya,{className:"mx-auto text-slate-200 mb-4",size:48}),e.jsx("h3",{className:"text-lg font-bold text-slate-700 mb-2",children:"Nenhum documento"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-sm mx-auto",children:"Nenhum documento médico emitido."})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:P.map(r=>e.jsxs("button",{onClick:()=>u(r.hash),className:"flex flex-col items-center justify-center gap-3 p-6 rounded-2xl border border-slate-200 bg-white hover:bg-slate-50 hover:border-blue-300 transition-colors text-center shadow-sm hover:shadow",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center shrink-0",children:e.jsx(Us,{size:20,className:"text-blue-600"})}),e.jsxs("div",{className:"w-full",children:[e.jsx("p",{className:"text-sm font-bold text-slate-700 truncate w-full",children:pl[r.document_type]||r.document_type}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:r.created_at?new Date(r.created_at).toLocaleDateString("pt-BR"):"Documento assinad
5o"})]})]},r.hash))})}),y==="attachments"&&e.jsx("div",{className:"p-4 sm:p-8",children:B.length===0?e.jsxs("div",{className:"text-center py-20",children:[e.jsx(fs,{className:"mx-auto text-slate-200 mb-4",size:48}),e.jsx("h3",{className:"text-lg font-bold text-slate-700 mb-2",children:"Sem anexos"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-sm mx-auto",children:"Nenhum arquivo enviado nesta consulta."})]}):e.jsx("div",{className:"space-y-3",children:B.map(r=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-xl bg-slate-50 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-slate-200 flex items-center justify-center text-slate-500",children:e.jsx(fs,{size:18})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-slate-700",children:r.file_name||r.hash}),e.jsxs("p",{className:"text-xs text-slate-500",children:["Enviado por ",r.sender_type==="patient"?"Você":"Profissional"," • ",new Date(r.created_at).toLocaleString("pt-BR",{dateStyle:"short",timeStyle:"short"})]})]})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>_(r.hash),children:"Baixar"})]},r.hash))})}),y==="chat"&&e.jsx("div",{className:"flex flex-col h-[600px]",children:e.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-4 bg-slate-50/50 rounded-b-2xl",children:v.length===0?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ja,{className:"mx-auto text-slate-200 mb-4",size:48}),e.jsx("p",{className:"text-sm text-slate-400 text-center italic",children:"Não houveram mensagens trocadas via chat de texto nesta consulta."})]})}):v.map((r,A)=>{const G=r.sender_type==="patient";return e.jsxs("div",{className:`flex flex-col max-w-[85%] ${G?"ml-auto items-end":"mr-auto items-start"}`,children:[e.jsx("div",{className:`px-4 py-2.5 rounded-2xl text-sm ${G?"bg-teal-600 text-white rounded-tr-none":"bg-white border border-slate-200 text-slate-700 rounded-tl-none shadow-sm"}`,children:r.message_content}),e.jsx("span",{className:"text-[10px] text-slate-400 mt-1 font-medium px-1",children:new Date(r.created_at).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})]},A)})})})]})]})]})]})})};function Vt(t){const s=String(t||"").replace(/\D/g,"");return s.length!==11?t||"—":s.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/,"$1.$2.$3-$4")}function Qt(t){const s=String(t||"").replace(/\D/g,"").slice(0,11);return s?s.length<=10?s.replace(/(\d{2})(\d)/,"($1) $2").replace(/(\d{4})(\d)/,"$1-$2"):s.replace(/(\d{2})(\d)/,"($1) $2").replace(/(\d{5})(\d)/,"$1-$2"):""}function Yt(t){return String(t||"").replace(/\D/g,"")}function gl(t){const s=String(t||"").replace(/\D/g,"").slice(0,8);return s?s.length<=5?s:`${s.slice(0,5)}-${s.slice(5)}`:""}function bl(t){return t?t.split(/\s+/).slice(0,2).map(s=>s[0]).join("").toUpperCase():"?"}const fl=()=>{const{user:t,setAuthData:s,token:l}
5=Re(),[a,x]=o.useState(!0),[p,c]=o.useState(!1),[g,f]=o.useState(""),[j,P]=o.useState(""),[w,S]=o.useState("patient"),[y,n]=o.useState({name:"",email:"",phone:"",birth_date:"",gender:"",document_number:"",address_street:"",address_number:"",address_city:"",address_state:"",address_zipcode:"",emergency_contact_name:"",emergency_contact_phone:"",legal_guardian_name:"",legal_guardian_document_number:"",legal_guardian_phone:"",legal_guardian_email:"",legal_guardian_relationship:""});o.useEffect(()=>{x(!0),V.get("/patients/me").then(({data:i})=>{const v=i.birth_date?String(i.birth_date).slice(0,10):"";n({name:i.name||(t==null?void 0:t.name)||"",email:i.email||(t==null?void 0:t.email)||"",phone:Qt(i.phone),birth_date:v,gender:i.gender||"",document_number:i.document_number||i.cpf||"",address_street:i.address_street||"",address_number:i.address_number||"",address_city:i.address_city||"",address_state:i.address_state||"",address_zipcode:gl(i.address_zipcode),emergency_contact_name:i.emergency_contact_name||"",emergency_contact_phone:Qt(i.emergency_contact_phone),...za(i),legal_guardian_phone:Qt(i.legal_guardian_phone),legal_guardian_document_number:Vt(i.legal_guardian_document_number).replace("—","")}),Pt(v)&&S("guardian")}).catch(()=>P("Não foi possível carregar seu perfil.")).finally(()=>x(!1))},[t]);const u=async()=>{var v,B;c(!0),f(""),P("");const i=Fa(y.birth_date,y);if(Object.keys(i).length>0){S("guardian"),P("Para paciente menor de idade, informe nome e telefone do responsável legal."),c(!1);return}if(!y.birth_date){P("Data de nascimento é obrigatória."),c(!1);return}try{await V.put("/patients/me",{name:y.name,phone:Yt(y.phone)||void 0,birth_date:y.birth_date,gender:y.gender||void 0,address_street:y.address_street,address_number:y.address_number,address_city:y.address_city,address_state:y.address_state,address_zipcode:Yt(y.address_zipcode)||void 0,emergency_contact_name:y.emergency_contact_name,emergency_contact_phone:Yt(y.emergency_contact_phone)||void 0,...Ba(y)}),l&&t&&s(l,{...t,name:y.name,email:y.email}),f("Perfil atualizado com sucesso.")}catch(I){P(((B=(v=I==null?void 0:I.response)==null?void 0:v.data)==null?void 0:B.message)||"Erro ao salvar perfil.")}finally{c(!1)}},_=(y.name||(t==null?void 0:t.name)||"Paciente").split(" ")[0];return e.jsxs("div",{className:"min-h-full bg-slate-50 pb-20",children:[e.jsxs("header",{className:"w-full px-4 sm:px-6 lg:px-8",children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-gray-800",children:"Meu Perfil"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Gerencie suas informações pessoais e de contato."})]}),e.jsxs("main",{className:"w-full px-4 sm:px-6 lg:px-8 mt-6 space-y-6",children:[a&&e.jsx("div",{className:"py-16 flex justify-center",children:e.jsx(pe,{className:"animate-spin text-primary-600"})}),j&&e.jsx("div",{className:"rounded-xl bg-red-50 text-red-700 px-4 py-3 text-sm",children:j}),g&&e.jsx("div",{className:"rounded-xl bg-emerald-50 text-emerald-700 px-4 py-3 text-sm",children:g}),!a&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[e.jsx("div",{className:"md:col-span-1",children:e.jsxs(Q,{className:"text-center h-full p-6",children:[e.jsx("div",{className:"w-28 h-28 mx-auto mb-4 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-3xl font-bold border-4 border-primary-50",children:t!=null&&t.avatar?e.jsx("img",{src:t.avatar,alt:"",className:"w-full h-full rounded-full object-cover"}):bl(y.name)}),e.jsx("h2",{className:"font-bold text-lg text-gray-800",children:y.name||_}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:Vt(y.document_number)}),e.jsx(M,{className:"w-full mt-4",variant:"outline",onClick:()=>window.location.href="/patient/wellness?tab=profile",children:"Perfil de saúde"})]})}),e.jsx("div",{className:"md:col-span-2 space-y-4",children:e.jsxs(Q,{className:"p-6",children:[Pt(y.birth_date)&&e.jsxs("div",{className:"flex border-b border-gray-100 mb-4",children:[e.jsx("button",{type:"button",onClick:()=>S("patient"),className:`flex-1 py-3 text-sm font-bold border-b-2 ${w==="patient"?"border-primary-600 text-primary-600":"border-transparent text-gray-500"}`,children:"Paciente"}),e.jsx("button",{type:"button",onClick:()=>S("guardian"),className:`flex-1 py-3 text-sm font-bold border-b-2 ${w==="guardian"?"border-primary-600 text-primary-600":"border-transparent text-gray-500"}`,children:"Responsável legal"})]}),(!Pt(y.birth_date)||w==="patient")&&e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"font-bold text-gray-800 mb
5-4 flex items-center gap-2",children:[e.jsx(Ot,{size:18,className:"text-primary-500"})," Dados pessoais"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ve,{label:"Nome completo",value:y.name,onChange:i=>n({...y,name:i.target.value})}),e.jsx(ve,{label:"CPF",value:Vt(y.document_number),disabled:!0}),e.jsx(ve,{label:"Data de nascimento *",type:"date",value:y.birth_date,onChange:i=>n({...y,birth_date:i.target.value}),required:!0}),e.jsx(Xs,{value:y.gender,onChange:i=>n({...y,gender:i})}),e.jsxs("h3",{className:"font-bold text-gray-800 mt-2 mb-2 flex items-center gap-2",children:[e.jsx(qs,{size:18,className:"text-primary-500"})," Contato"]}),e.jsx(ve,{label:"E-mail",type:"email",value:y.email,disabled:!0}),e.jsx(ve,{label:"Telefone",type:"tel",mask:"phone",placeholder:"(00) 00000-0000",value:y.phone,onChange:i=>n({...y,phone:i.target.value})}),e.jsx(ve,{label:"CEP (opcional)",mask:"cep",inputMode:"numeric",placeholder:"00000-000",value:y.address_zipcode,onChange:i=>n({...y,address_zipcode:i.target.value})}),e.jsxs("h3",{className:"font-bold text-gray-800 mt-2 mb-2 flex items-center gap-2",children:[e.jsx(Ks,{size:18,className:"text-primary-500"})," Emergência"]}),e.jsx(ve,{label:"Contato de emergência",value:y.emergency_contact_name,onChange:i=>n({...y,emergency_contact_name:i.target.value})}),e.jsx(ve,{label:"Telefone do contato",type:"tel",mask:"phone",placeholder:"(00) 00000-0000",value:y.emergency_contact_phone,onChange:i=>n({...y,emergency_contact_phone:i.target.value})}),e.jsx("div",{className:"pt-2 flex justify-end",children:e.jsx(M,{onClick:u,isLoading:p,icon:e.jsx(ys,{size:18}),className:"w-full sm:w-auto",children:"Salvar alterações"})})]})]}),Pt(y.birth_date)&&w==="guardian"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-bold text-gray-800 mb-4",children:"Responsável legal"}),e.jsx(Da,{values:y,compact:!0,onChange:(i,v)=>n({...y,[i]:v})}),e.jsx("div",{className:"pt-2 flex justify-end",children:e.jsx(M,{onClick:u,isLoading:p,icon:e.jsx(ys,{size:18}),className:"w-full sm:w-auto",children:"Salvar alterações"})})]})]})})]})]})]})},Js=({tips:t,title:s="Recomendações para você"})=>t.length?e.jsxs(Q,{className:"h-full p-6 rounded-3xl border-0 shadow-sm bg-white",padding:"none",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Be,{size:18,className:"text-primary-500"}),e.jsx("h3",{className:"font-bold text-slate-800",children:s})]}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:"Com base no que você registrou recentemente"}),e.jsx("div",{className:"space-y-2",children:t.map(l=>{const a=l.icon;return e.jsxs("div",{className:"flex gap-3 items-start rounded-2xl bg-slate-50 border border-slate-100 p-3",children:[e.jsx("div",{className:"w-9 h-9 shrink-0 rounded-full bg-white text-primary-600 flex items-center justify-center shadow-sm",children:e.jsx(a,{size:18})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-800 text-sm",children:l.title}),e.jsx("p",{className:"text-sm text-slate-600 mt-0.5 leading-relaxed",children:l.body})]})]},l.id)})})]}):null;function xe(t){if(!t)return"";if(t instanceof Date&&!Number.isNaN(t.getTime())){const s=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0");return`${s}-${l}-${a}`}return String(t).slice(0,10)}function tt(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function is(t){const[s,l,a]=xe(t).split("-").map(Number);return new Date(s,(l||1)-1,a||1,12,0,0,0)}function Xt(t,s){const l=is(t);return l.setDate(l.getDate()+s),xe(l)}function yl(t){return is(t).toLocaleDateString("pt-BR",{weekday:"short",day:"2-digit",month:"2-digit"})}function ft(t){const s=xe(t);if(!s)return"—";const l=is(s);return Number.isNaN(l.getTime())?"—":l.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}function jl(t=new Date){return t.toLocaleDateString("pt-BR",{weekday:"long",day:"numeric",month:"long"})}function ue(t,s=0){return t.toLocaleString("pt-BR",{maximumFractionDigits:s,minimumFractionDigits:s})}function Ve(t,s){return!s||s<=0?0:Math.max(0,Math.min(100,Math.round(t/s*100)))}function vl(t,s,l){const a=xe(t),x=s<=l?s:l,p=s<=l?l:s;return a>=x&&a<=p}function Ie(t){return t.length?t.reduce((s,l)=>s+l,0)/t.length:0}function ks(t){if(t.length<2)return 0;const s=Ie(t),l=t.reduce((a,x)=>a+(x-s)**2,0)/t.length;return Math.sqrt(l)}function Ge(t){const s=t/1e3;return`${s.toFixed(s>=10||Number.isInteger(s)?0:1).replace(".",",")} L`}function Nl(t){const{goalMl:s,todayMl:l,averageMl:a,daysLogged:x,daysOnGoal:p,variabilityMl:c}=t,g=[];return x===0?[{id:"w-start",icon:Qe,title:"Comece a registrar",body:`Anote o consumo para acompanhar a meta de ${Ge(s)} por dia.`},{id:"w-morning",icon:Be,title:"Comece o dia hidratado",body:"Um copo ao acordar (200–300 ml) ajuda a repor o que o corpo perdeu à noite."},{id:"w-spread",icon:nt,title:"Distribua ao longo do dia",body:"Beba em intervalos regulares em vez de grandes volumes de uma vez."}]:(a<s*.85?g.push({id:"w-below",icon:ot,title:"Abaixo da meta na média",body:`Média de ${Ge(a)}/dia. Tente somar ${(Math.max(200,s-a)/1e3).toFixed(1).replace(".",",")} L pela tarde.`}):a>
5=s?g.push({id:"w-ok",icon:Ae,title:"Hidratação no caminho certo",body:`Média de ${Ge(a)}, alinhada à meta de ${Ge(s)}.`}):g.push({id:"w-almost",icon:Te,title:"Quase na meta",body:`Média de ${Ge(a)}. Faltam cerca de ${Ge(s-a)} por dia.`}),p<Math.ceil(x/2)&&g.push({id:"w-days",icon:Te,title:"Poucos dias na meta",body:`Só ${p} de ${x} dias bateram ${Ge(s)}. Defina 2–3 horários fixos.`}),c>=600&&g.push({id:"w-var",icon:De,title:"Consumo irregular",body:"O volume oscilou bastante. Uma base mínima diária estabiliza a hidratação."}),l>0&&l<s*.5?g.push({id:"w-today",icon:Qe,title:"Hoje ainda está baixo",body:`Você está com ${Ge(l)}. Priorize pequenos goles até o fim do dia.`}):l>=s&&g.push({id:"w-done",icon:Be,title:"Meta de hoje concluída",body:"Ótimo. Continue hidratado sem exagerar de uma vez."}),g.slice(0,4))}function wl(t){const{goalHours:s,tonightHours:l,averageHours:a,nightsLogged:x,nightsOnGoal:p,qualityAvg:c,variability:g}=t,f=[],j=P=>`${P.toFixed(1).replace(".",",")}h`;return x===0?[{id:"s-start",icon:Ue,title:"Comece a registrar",body:"Anote horas e qualidade por alguns dias para liberar recomendações personalizadas."},{id:"s-routine",icon:js,title:"Rotina consistente",body:`Tente manter cerca de ${j(s)} por noite, em horários parecidos.`},{id:"s-screens",icon:Be,title:"Desacelere à noite",body:"Evite telas e cafeína nas 2 horas antes de dormir."}]:(a<s-.75?f.push({id:"s-debt",icon:ot,title:"Dívida de sono",body:`Média de ${j(a)}, cerca de ${j(s-a)} abaixo da meta. Antecipe o horário de dormir.`}):a>s+1.5?f.push({id:"s-over",icon:Ue,title:"Sono acima da média",body:`Média de ${j(a)}. Se acordar sem disposição, revise qualidade e horários.`}):f.push({id:"s-ok",icon:Ae,title:"Volume de sono no caminho certo",body:`Média de ${j(a)}, perto da meta de ${j(s)}.`}),p<Math.ceil(x/2)&&f.push({id:"s-nights",icon:Te,title:"Poucas noites na meta",body:`Só ${p} de ${x} noites bateram ${j(s)}.`}),g>=1.5&&f.push({id:"s-var",icon:De,title:"Horários irregulares",body:"Reduzir a diferença entre semana e fim de semana melhora disposição."}),c!=null&&c<=2.5&&f.push({id:"s-qual",icon:js,title:"Foque na qualidade",body:"Ambiente escuro e fresco, evite refeições pesadas à noite."}),l>0&&l<s*.75&&f.push({id:"s-today",icon:Ue,title:"Noite curta",body:`Hoje: ${j(l)}. Tente compensar com uma rotina mais cedo hoje à noite.`}),f.slice(0,4))}function Cl(t){const{goalMinutes:s,goalSteps:l,minutesToday:a,stepsToday:x,daysLogged:p,daysOnGoal:c,averageMinutes:g,averageSteps:f}=t,j=[];return p===0&&a<=0&&x<=0?[{id:"a-start",icon:De,title:"Comece a registrar",body:`Anote exercícios e passos para a meta de ${s} min e ${l.toLocaleString("pt-BR")} passos.`},{id:"a-walk",icon:at,title:"Caminhada conta",body:"20–30 min de caminhada já ajudam minutos e passos."}]:(g<s*.7?j.push({id:"a-min",icon:ot,title:"Pouco movimento na média",body:`Média de ${Math.round(g)} min/dia. Inclua um bloco curto de atividade.`}):j.push({id:"a-ok",icon:Ae,title:"Atividade no ritmo",body:`Média de ${Math.round(g)} min/dia vs meta de ${s} min.`}),f>0&&f<l*.7&&j.push({id:"a-steps",icon:Te,title:"Passos abaixo da meta",body:`Média de ${Math.round(f).toLocaleString("pt-BR")} passos. Uma caminhada extra após o almoço ajuda.`}),c<Math.ceil(Math.max(p,1)/2)&&p>0&&j.push({id:"a-days",icon:nt,title:"Poucos dias na meta",body:`Só ${c} de ${p} dias bateram ${s} min.`}),a<s&&a>=0&&j.push({id:"a-today",icon:De,title:"Ainda dá tempo hoje",body:`${a} min registrados. Faltam ${Math.max(0,s-a)} min para a meta.`}),j.slice(0,4))}function _l(t){const{todayUnits:s,weekUnits:l,weekDaysWithAlcohol:a,limitDays:x,daysLogged:p}=t;if(p===0&&s<=0)return[{id:"al-start",icon:Ct,title:"Comece a registrar",body:`Anote as doses para acompanhar o limite de ${x} dia${x===1?"":"s"} com álcool na semana.`},{id:"al-rest",icon:at,title:"Dias sem álcool ajudam",body:"Planeje no mínimo alguns dias da semana sem consumo."},{id:"al-dose",icon:Be,title:"O que conta como 1 dose",body:"Uma dose ≈ 350 ml de cerveja, 150 ml de vinho ou 50 ml de destilado."}];const c=[];return a>x?c.push({id:"al-over",icon:ot,title:"Acima do limite semanal",body:`${a} dias com álcool nesta janela, acima do limite de ${x}.`}
5):c.push({id:"al-ok",icon:Ae,title:"Dentro do limite",body:`${a} de ${x} dias com álcool no período.`}),s>=3&&c.push({id:"al-today",icon:Ct,title:"Consumo alto hoje",body:`${s} doses hoje. Intercale com água e evite dirigir.`}),l>=10&&c.push({id:"al-vol",icon:Te,title:"Volume semanal elevado",body:`${l} doses no período. Reduzir o volume também protege o sono.`}),c.push({id:"al-habit",icon:at,title:"Hábito que ajuda",body:"Defina dias secos na agenda — o fígado e o humor agradecem."}),c.slice(0,4)}function kl(t){const{caloriesToday:s,calorieGoal:l,averageKcal:a,daysLogged:x,mealsToday:p,proteinToday:c}=t;if(x===0&&s<=0)return[{id:"f-start",icon:_t,title:"Comece o diário",body:`Registre refeições para acompanhar a meta de ${l} kcal.`},{id:"f-photo",icon:Be,title:"Foto do prato",body:"A análise por imagem estima calorias e macronutrientes automaticamente."},{id:"f-protein",icon:at,title:"Inclua proteína",body:"Uma fonte de proteína em cada refeição ajuda na saciedade."}];const g=[];return l>0&&s>l*1.15?g.push({id:"f-over",icon:ot,title:"Acima da meta de calorias",body:`${Math.round(s)} kcal hoje, acima de ${l} kcal.`}):l>0&&s>0&&s<l*.6?g.push({id:"f-under",icon:at,title:"Ainda abaixo da meta",body:`${Math.round(s)} de ${l} kcal. Evite pular refeições.`}):s>0&&g.push({id:"f-ok",icon:Ae,title:"Calorias no ritmo",body:`${Math.round(s)} kcal de ${l} hoje.`}),a>0&&l>0&&a>l*1.1&&g.push({id:"f-avg",icon:Te,title:"Média do período alta",body:`Média de ${Math.round(a)} kcal/dia. Ajuste porções e bebidas calóricas.`}),p<=1&&s>0&&g.push({id:"f-meals",icon:_t,title:"Poucas refeições hoje",body:"Distribuir em 3 refeições reduz picos de fome."}),c>0&&c<50&&g.push({id:"f-pro",icon:at,title:"Proteína ainda baixa",body:`${Math.round(c)} g hoje. Ovos, iogurte, frango ou feijão complementam.`}),g.slice(0,4)}function Sl(t){const{current:s,goal:l,daysLogged:a,delta7:x}=t;if(a===0||s==null)return[{id:"p-start",icon:as,title:"Comece a pesar",body:"Registre em dias parecidos, de manhã, para ver a tendência com menos ruído."},{id:"p-habit",icon:Be,title:"Mesmo horário",body:"Pese-se em jejum, com a mesma balança."},{id:"p-goal",icon:Te,title:"Defina uma meta",body:"Uma meta em kg deixa o acompanhamento mais claro."}];const p=[];if(l&&l>0){const c=s-l;Math.abs(c)<=1?p.push({id:"p-near",icon:Ae,title:"Perto da meta",body:`Você está em ${s.toFixed(1).replace(".",",")} kg, próximo de ${l} kg.`}):c>0?p.push({id:"p-above",icon:Te,title:"Acima da meta",body:`${c.toFixed(1).replace(".",",")} kg acima de ${l} kg. Combine alimentação e atividade.`}):p.push({id:"p-below",icon:Te,title:"Abaixo da meta",body:`${Math.abs(c).toFixed(1).replace(".",",")} kg abaixo de ${l} kg. Confira se a meta ainda faz sentido.`})}return x!=null&&Math.abs(x)>=1.5&&p.push({id:"p-delta",icon:De,title:x>0?"Alta recente":"Queda recente",body:`${x>0?"+":""}${x.toFixed(1).replace(".",",")} kg nos últimos registros. Oscilações rápidas pedem consistência, não restrição extrema.`}),p.push({id:"p-habit2",icon:as,title:"Olhe a tendência",body:"O peso do dia varia. Compare médias semanais, não um único número."}),p.slice(0,4)}function $l(t){const{waterPct:s,sleepPct:l,activityPct:a,foodPct:x,hasWeightGoal:p}=t,c=[],g=[{id:"g-water",pct:s,title:"Meta de água",body:"Se a meta está difícil, reduza 200–300 ml e suba depois de 1 semana consistente."},{id:"g-sleep",pct:l,title:"Meta de sono",body:"Metas de 7–8h funcionam melhor do que saltos bruscos de horário."},{id:"g-act",pct:a,title:"Meta de atividade",body:"Comece com 20 min e evolua. Consistência vale mais que um dia intenso."},{id:"g-food",pct:x,title:"Meta de calorias",body:"Ajuste a meta se ela ficar acima ou abaixo do que você consegue registrar no dia a dia."}].filter(f=>f.pct>0&&f.pct<60);for(const f of g)c.push({id:f.id,icon:nt,title:f.title,body:f.body});return p||c.push({id:"g-weight",icon:as,title:"Inclua meta de peso",body:"Definir um alvo em kg deixa o histórico de peso mais útil."}),c.length===0&&c.push({id:"g-ok",icon:Ae,title:"Metas alinhadas",body:"Seu ritmo recente está próximo dos alvos. Mantenha e revise a cada 2–4 semanas."}
5),c.push({id:"g-review",icon:Te,title:"Revise com carinho",body:"Metas realistas aumentam a chance de manter o hábito — e o score de saúde."}),c.slice(0,4)}const Ss=[{days:7,label:"7d"},{days:14,label:"14d"},{days:30,label:"30d"}],Pl=({title:t,rows:s,emptyText:l="Nenhum registro neste período.",buildSummary:a,onDelete:x})=>{var i;const[p,c]=o.useState(()=>Xt(tt(),-13)),[g,f]=o.useState(()=>tt()),[j,P]=o.useState(null),[w,S]=o.useState(null),y=((i=Ss.find(v=>p===Xt(g,-(v.days-1))))==null?void 0:i.days)??null,n=o.useMemo(()=>s.filter(v=>vl(v.date,p,g)).sort((v,B)=>B.date.localeCompare(v.date)),[s,p,g]),u=n.length?a==null?void 0:a(n):null,_=n.filter(v=>v.onGoal).length;return e.jsxs(Q,{className:"p-6 rounded-3xl border-0 shadow-sm bg-white",padding:"none",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va,{size:18,className:"text-slate-500"}),e.jsx("h3",{className:"font-bold text-slate-800",children:t})]}),e.jsx("div",{className:"flex rounded-xl bg-slate-100 p-0.5",children:Ss.map(v=>e.jsx("button",{type:"button",onClick:()=>{c(Xt(tt(),-(v.days-1))),f(tt())},className:`px-2.5 py-1 text-[11px] font-bold rounded-lg ${y===v.days?"bg-white text-slate-800 shadow-sm":"text-slate-500"}`,children:v.label},v.days))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1",children:"De"}),e.jsx("input",{type:"date",className:"w-full rounded-xl bg-slate-50 border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary-200",value:p,max:g,onChange:v=>c(v.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1",children:"Até"}),e.jsx("input",{type:"date",className:"w-full rounded-xl bg-slate-50 border border-slate-200 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary-200",value:g,min:p,max:tt(),onChange:v=>f(v.target.value)})]})]}),u?e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3 rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("p",{className:"text-sm text-slate-600",children:u}),n.length>0&&e.jsxs("span",{className:"text-[11px] font-bold text-emerald-700 bg-emerald-50 px-2 py-1 rounded-lg whitespace-nowrap",children:[_,"/",n.length," na meta"]})]}):null,n.length===0?e.jsx("p",{className:"text-sm text-slate-400 py-8 text-center",children:l}):e.jsx("ul",{className:"divide-y divide-slate-100 max-h-80 overflow-y-auto",children:n.map(v=>e.jsxs("li",{className:"flex items-center gap-3 py-3",children:[e.jsx("span",{className:`w-2.5 h-2.5 rounded-full shrink-0 ${v.onGoal?"bg-emerald-500":"bg-slate-300"}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800 capitalize",children:yl(v.date)}),v.meta?e.jsx("p",{className:"text-xs text-slate-500 truncate",children:v.meta}):null]}),e.jsxs("div",{className:"text-right",children:[e.jsx("span",{className:"text-sm font-bold text-slate-800 whitespace-nowrap",children:v.value}),v.onGoal?e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-wide text-emerald-600",children:"Meta"}):null]}),x?j===v.id?e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{type:"button",disabled:w===v.id,onClick:async()=>{S(v.id);try{await x(v),P(null)}finally{S(null)}},className:"px-2 py-1 rounded-lg bg-red-50 text-red-700 text-[11px] font-bold hover:bg-red-100 disabled:opacity-50",children:w===v.id?"...":v.logId?"Excluir":"Excluir dia"}),e.jsx("button",{type:"button",onClick:()=>P(null),className:"px-2 py-1 rounded-lg bg-slate-100 text-slate-500 text-[11px] font-bold hover:bg-slate-200",children:"Não"})]}):e.jsx("button",{type:"button",title:v.logId?"Remover este registro":"Remover os registros deste dia",onClick:()=>P(v.id),className:"p-1.5 rounded-lg text-slate-400 hover:text-red-600 hover:bg-red-50 shrink-0",children:e.jsx(Vs,{size:15})}):null]},v.id))})]})},Zs=({historyTitle:t,track:s,emptyText:l,onDelete:a})=>e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[e.jsx(Pl,{title:t,rows:s.rows,emptyText:l,buildSummary:s.summary,onDelete:a}),e.jsx(Js,{tips:s.tips})]}),Al={blue:{icon:"bg-blue-100 text-blue-600",bar:"bg-blue-500",chip:"text-blue-600 bg-blue-50"},indigo:{icon:"bg-indigo-100 text-indigo-600",bar:"bg-indigo-500",chip:"text-indigo-600 bg-indigo-50"},orange:{icon:"bg-orange-100 text-orange-600",bar:"bg-orange-500",chip:"text-orange-600 bg-orange-50"},emerald:{icon:"bg-emerald-100 text-emerald-600",bar:"bg-emerald-500",chip:"text-emerald-600 bg-emerald-50"},rose:{icon:"bg-rose-100 text-rose-600",bar:"bg-rose-500",chip:"text-rose-600 bg-rose-50"},purple:{icon:"bg-purple-100 text-purple-600",bar:"bg-purple-500",chip:"text-purple-600 bg-purple-50"},slate:{icon:"bg-slate-100 text-slate-600",bar:"bg-slate-500",chip:"text-slate-600 bg-slate-50"}},Ze=({icon:t,tone:s="slate",label:l,value:a,hint:x,pct:p,points:c,invertBar:g=!1})=>{const f=Al[s],j=p==null?null:Math.max(0,Math.min(100,p)),P=j!=null&&(g?j<=100&&p!=null&&p<=100:j>=100);return e.jsxs("div",{className:"rounded-2xl bg-slate-50 border border-slate-100 p-4 flex flex-col justify-between min-h-[132px]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${f.icon}`,children:e.jsx(t,{size:20})}),c!=null&&e.jsxs("span",{className:`text-xs font-bold px-2 py-1 rounded-lg ${f.chip}`,children:[Math.round(c)," pts"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-slate-700",children:l}),e.jsx("p",{className:"text-lg font-extrabold text-slate-900 tracking-tight mt-0.5",children:a}),x?e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:x}):null,j!=null&&e.jsx("div",{className:"mt-3 h-1.5 rounded-full bg-slate-200 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${P?"bg-emerald-500":f.bar}`,style:{width:`${j}%`}})})]})]})},El=[{key:"sleep",label:"Sono"},{key:"water",label:"Água"},{key:"calories",label:"Calorias"},{key:"weight",label:"Peso"},{key:"alcohol",label:"Álcool"}];function yt(t,s){return[...t].map(a=>({...a,date:xe(a.date)})).filter(a=>a.date).sort((a,x)=>a.date.localeCompare(x.date)).slice(-s)}const Dl=({sleep:t,water:s,calories:l,alcohol:a,weight:x,sleepGoal:p,waterGoal:c,calorieGoal:g,weightGoal:f})=>{const[j,P]=o.useState(14),[w,S]=o.useState("water"),y=o.useMemo(()=>({sleep:yt(t,j).map(_=>({date:_.date,label:ft(_.date),hours:_.hours})),water:yt(s,j).map(_=>({date:_.date,label:ft(_.date),ml:_.ml})),calories:yt(l,j).map(_=>({date:_.date,label:ft(_.date),consumidas:_.consumed,queimadas:_.burned})),alcohol:yt(a,j).map(_=>({date:_.date,label:ft(_.date),units:_.units})),weight:yt(x,j).map(_=>({date:_.date,label:ft(_.date),weight:_.weight}))})[w],[t,s,l,a,x,j,w]),n=y.length===0;return e.jsxs(Q,{className:"flex-1 w-full p-6 sm:p-8 rounded-3xl border-0 shadow-sm bg-white",padding:"none",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-slate-800",children:"Evolução"}),e.jsxs("p",{className:"text-sm text-slate-500",children:["Últimos ",j," dias com registro"]})]}),e.jsx("div",{className:"flex rounded-xl bg-slate-100 p-1 self-start",children:[7,14,30].map(u=>e.jsxs("button",{type:"button",onClick:()=>P(u),className:`px-3 py-1.5 text-xs font-bold rounded-lg ${j===u?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[u,"d"]},u))})]}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-4",children:El.map(u=>e.jsx("button",{type:"button",onClick:()=>S(u.key),className:`px-3 py-1.5 rounded-full text-xs font-bold ${w===u.key?"bg-slate-800 text-white":"bg-slate-50 text-slate-600 border border-slate-200 hover:bg-slate-100"}`,children:u.label},u.key))}),n?e.jsx("div",{className:"h-52 flex items-center justify-center rounded-2xl bg-slate-50 border border-slate-100",children:e.jsx("p",{className:"text-sm text-slate-400",children:"Ainda não há registros neste gráfico."})}):e.jsx("div",{className:"h-56",children:e.jsx(vt,{width:"100%",height:"100%",children:e.jsxs(ls,{data:y,margin:{top:8,right:8,left:0,bottom:0},children:[e.jsx(It,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(Lt,{dataKey:"label",tick:{fontSize:11,fill:"#94a3b8"}
5,axisLine:!1,tickLine:!1}),e.jsx(Tt,{tick:{fontSize:11,fill:"#94a3b8"},axisLine:!1,tickLine:!1,width:42}),e.jsx(Rt,{contentStyle:{borderRadius:12,border:"1px solid #e2e8f0",fontSize:12},labelStyle:{fontWeight:700}}),w==="sleep"&&e.jsxs(e.Fragment,{children:[e.jsx(Oe,{type:"monotone",dataKey:"hours",name:"Horas",stroke:"#4f46e5",fill:"#4f46e533",strokeWidth:2}),e.jsx($t,{y:p,stroke:"#14b8a6",strokeDasharray:"4 4"})]}),w==="water"&&e.jsxs(e.Fragment,{children:[e.jsx(Oe,{type:"monotone",dataKey:"ml",name:"ml",stroke:"#2563eb",fill:"#2563eb33",strokeWidth:2}),e.jsx($t,{y:c,stroke:"#14b8a6",strokeDasharray:"4 4"})]}),w==="calories"&&e.jsxs(e.Fragment,{children:[e.jsx(La,{}),e.jsx(Oe,{type:"monotone",dataKey:"consumidas",name:"Consumidas",stroke:"#f97316",fill:"#f9731633",strokeWidth:2}),e.jsx(Oe,{type:"monotone",dataKey:"queimadas",name:"Queimadas",stroke:"#0f766e",fill:"#0f766e33",strokeWidth:2}),e.jsx($t,{y:g,stroke:"#94a3b8",strokeDasharray:"4 4"})]}),w==="alcohol"&&e.jsx(Oe,{type:"monotone",dataKey:"units",name:"Doses",stroke:"#a16207",fill:"#a1620733",strokeWidth:2}),w==="weight"&&e.jsxs(e.Fragment,{children:[e.jsx(Oe,{type:"monotone",dataKey:"weight",name:"kg",stroke:"#0f766e",fill:"#0f766e33",strokeWidth:2}),f!==""&&f!=null&&e.jsx($t,{y:Number(f),stroke:"#4f46e5",strokeDasharray:"4 4"})]})]})})})]})};function ea(t=new Date){const s=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0");return`${s}-${l}-${a}`}function $s(t,s){const[l,a,x]=t.split("-").map(Number),p=new Date(l,(a||1)-1,x||1);return p.setDate(p.getDate()+s),ea(p)}function Ps(t){const[s,l,a]=t.split("-");return`${a}/${l}/${s}`}const Jt=[{key:"water",label:"Água",hint:"Hidratação",icon:Qe,tone:"text-blue-600 bg-blue-50"},{key:"sleep",label:"Sono",hint:"Noite passada",icon:Ue,tone:"text-indigo-600 bg-indigo-50"},{key:"food",label:"Alimentação",hint:"Refeições",icon:_t,tone:"text-orange-600 bg-orange-50"},{key:"activity",label:"Atividade",hint:"Movimento",icon:De,tone:"text-rose-600 bg-rose-50"},{key:"alcohol",label:"Álcool",hint:"Doses",icon:Ct,tone:"text-purple-600 bg-purple-50"},{key:"weight",label:"Peso",hint:"Balança",icon:Qs,tone:"text-slate-600 bg-slate-100"}],Ml=[200,250,300,500,1e3],et=250,Il=["Ruim","Regular","Boa","Ótima","Excelente"],Ll=[{label:"Caminhada 30 min",minutes:30,activityType:"Caminhada"}
5,{label:"Corrida 20 min",minutes:20,activityType:"Corrida"},{label:"Musculação 45 min",minutes:45,activityType:"Musculação"},{label:"Yoga 30 min",minutes:30,activityType:"Yoga"}];function Tl(t,s){switch(t){case"water":return`${ue(s.waterToday/1e3,1)} L`;case"sleep":return s.sleepToday?`${ue(s.sleepToday,1)} h`:"—";case"food":return`${ue(s.caloriesToday)} kcal`;case"activity":return`${ue(s.activityToday)} min`;case"alcohol":return`${ue(s.alcoholWeek)} d`;default:return s.latestWeight!=null?`${ue(s.latestWeight,1)} kg`:"—"}}function Rl({value:t,goal:s,unit:l}){const a=Ve(t,s);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-end justify-between gap-2 mb-2",children:[e.jsxs("p",{className:"text-2xl font-extrabold text-slate-800 tracking-tight",children:[ue(t,l==="h"||l==="L"||l==="kg"?1:0),e.jsx("span",{className:"text-sm font-semibold text-slate-400 ml-1",children:l})]}),s>0&&e.jsxs("p",{className:"text-sm text-slate-500",children:["meta ",ue(s,l==="h"||l==="L"||l==="kg"?1:0)," ",l]})]}),s>0&&e.jsx("div",{className:"h-2 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary-500 transition-all",style:{width:`${a}%`}})})]})}const zl=({track:t,onTrackChange:s,stats:l,foodLogs:a,trackView:x,analyzing:p,analysis:c,setAnalysis:g,fileRef:f,onPhoto:j,saveAnalysis:P,recomputeTotals:w,onLogged:S,onMessage:y})=>{var Pe;const[n,u]=o.useState(!1),[_,i]=o.useState(null),[v,B]=o.useState("250"),[I,r]=o.useState("7.5"),[A,G]=o.useState("Boa"),[$,E]=o.useState(""),[Y,le]=o.useState(""),[b,H]=o.useState("Caminhada"),[R,O]=o.useState("30"),[W,ie]=o.useState(""),[ce,C]=o.useState("1"),[k,D]=o.useState("Cerveja"),[J,de]=o.useState(""),he=ea(),be=$s(he,-1),_e=$s(he,-60),[se,ge]=o.useState(he),fe=se===he,d=fe?"hoje":Ps(se),L=Jt.find(N=>N.key===t)||Jt[0],U=L.icon,K=Math.max(4,Math.ceil((l.waterGoal||2e3)/et)),re=Math.min(K,Math.round(l.waterToday/et)),ee=async(N,me)=>{u(!0);try{await N(),y(me),S()}catch{y("Não foi possível salvar este registro.")}finally{u(!1)}},$e=async N=>{u(!0);try{N.logId?await z.deleteWellnessLog(t,N.logId):await z.deleteWellnessDay(t,N.date),y("Registro removido."),S()}catch{y("Não foi possível remover este registro.")}finally{u(!1)}},ye=async N=>{u(!0);try{await z.deleteWellnessLog("food",N),i(null),y("Refeição removida."),S()}catch{y("Não foi possível remover esta refeição.")}finally{u(!1)}},ke=(()=>{switch(t){case"water":return{title:`Água de ${d}`,value:l.waterToday/1e3,goal:l.waterGoal/1e3,unit:"L"};case"sleep":return{title:`Sono de ${d}`,value:l.sleepToday,goal:l.sleepGoal,unit:"h"};case"food":return{title:`Alimentação de ${d}`,value:l.caloriesToday,goal:l.calorieGoal,unit:"kcal"};case"activity":return{title:`Atividade de ${d}`,value:l.activityToday,goal:l.activityGoal,unit:"min"};case"alcohol":return{title:"Álcool na semana",value:l.alcoholWeek,goal:l.alcoholLimit,unit:"d"};default:return{title:"Peso atual",value:l.latestWeight??0,goal:0,unit:"kg"}}})();return e.jsxs("div",{className:"grid lg:grid-cols-12 gap-6",children:[e.jsxs("div",{className:"lg:col-span-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-slate-800",children:"O que você quer registrar?"}),e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:"Escolha um hábito. O formulário e o histórico mudam junto."})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-1 gap-2",children:Jt.map(N=>{const me=N.icon,T=t===N.key;return e.jsxs("button",{type:"button",onClick:()=>s(N.key),className:`flex items-center gap-3 p-3 rounded-2xl text-left transition-all border ${T?"bg-slate-800 text-white border-slate-800 shadow-sm":"bg-white text-slate-700 border-slate-100 hover:border-slate-200 hover:bg-slate-50"}`,children:[e.jsx("span",{className:`w-10 h-10 rounded-full flex items-center justify-center ${T?"bg-white/15 text-white":N.tone}`,children:e.jsx(me,{size:18})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold",children:N.label}),e.jsx("span",{className:`block text-xs ${T?"text-slate-300":"text-slate-400"}`,children:Tl(N.key,l)})]})]},N.key)})})]}),e.jsxs("div",{className:"lg:col-span-8 space-y-6",children:[e.jsxs(Q,{className:"p-6 sm:p-8 rounded-3xl border-0 shadow-sm bg-white",padding:"none",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-5",children:[e.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center ${L.tone}`,children:e.jsx(U,{size:20})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-slate-800",children:ke.title}),e.jsx("p",{className:"text-sm text-slate-500",children:"Registre o valor real — sem atalho genérico."})]})]}),e.jsx("div",{className:"mb-6",children:t==="weight"&&l.latestWeight==null?e.jsx("p",{className:"text-sm text-slate-400",children:"Ainda não há peso registrado."}):e.jsx(Rl,{value:ke.value,goal:ke.goal,unit:ke.unit})}),e.jsxs("div",{className:"mb-5 p-3 rounded-2xl bg-slate-50 border border-slate-100",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ht,{size:16,className:"text-slate-500"}),e.jsx("span",{className:"text-sm font-semibold text-slate-700",children:"Data do registro"}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{type:"button",onClick:()=>ge(he),className:`px-3 py-1.5 rounded-xl text-xs font-bold ${fe?"bg-slate-800 text-white":"bg-white text-slate-600 border border-slate-200"}`,children:"Hoje"}),e.jsx("button",{type:"button",onClick:()=>ge(be),className:`px-3 py-1.5 rounded-xl text-xs font-bold ${se===be?"bg-slate-800 text-white":"bg-white text-slate-600 border border-slate-200"}`,children:"Ontem"}),e.jsx("input",{type:"date",min:_e,max:he,value:se,onChange:N=>{const me=N.target.value;me>=_e&&me<=he&&ge(me)},className:"rounded-xl bg-white border border-slate-200 px-3 py-1.5 text-sm text-slate-700 outline-none"})]}),!fe&&e.jsxs("p",{className:"text-xs text-amber-800 mt-2",children:["Este registro vai para ",Ps(se),", não para hoje."]})]}),t==="water"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-400",children:["Copos de ",et," ml"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from({length:K}).map((N,me)=>{const T=me<re;return e.jsx("button",{type:"button",disabled:n,title:`Registrar +${et} ml`,onClick:()=>ee(()=>z.logWater({amountMl:et,date:se}),`Água +${et} ml registrada.`),className:`w-10 h-12 rounded-lg border-2 flex items-end justify-center pb-1 disabled:opacity-50 ${T?"border-blue-400 bg-blue-100":"border-slate-200 bg-slate-50 hover:border-blue-300"}`,children:e.jsx("span",{className:`block w-6 rounded-sm ${T?"h-7 bg-blue-500":"h-2 bg-slate-200"}`})},me)})}),e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-400",children:"Ou escolha a quantidade"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Ml.map(N=>e.jsxs("button",{type:"button",disabled:n,onClick:()=>ee(()=>z.logWater({amountMl:N,date:se}),`Água +${N} ml registrada.`),className:"px-4 py-2 rounded-xl bg-blue-50 text-blue-700 text-sm font-bold hover:bg-blue-100 disabled:opacity-50",children:["+",N," ml"]},N))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"number",min:1,
5className:"flex-1 rounded-xl bg-slate-50 border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-blue-200",value:v,onChange:N=>B(N.target.value),placeholder:"Quantidade em ml"}),e.jsx(M,{disabled:n,onClick:()=>ee(()=>z.logWater({amountMl:Number(v),date:se}),`Água +${v} ml registrada.`),className:"px-5",children:n?e.jsx(pe,{size:16,className:"animate-spin"}):"Registrar"})]})]}),t==="sleep"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-semibold text-slate-600",children:"Horas dormidas"}),e.jsx("input",{type:"number",min:.5,max:24,step:.5,className:"mt-1 w-full rounded-xl bg-slate-50 border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-indigo-200",value:I,onChange:N=>r(N.target.value)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-slate-600 mb-2",children:"Qualidade"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Il.map(N=>e.jsx("button",{type:"button",onClick:()=>G(N),className:`px-3 py-1.5 rounded-xl text-sm font-bold ${A===N?"bg-indigo-600 text-white":"bg-slate-50 text-slate-600 border border-slate-200"}`,children:N},N))})]}),e.jsx(M,{disabled:n,onClick:()=>ee(()=>z.logSleep({hours:Number(I),quality:A,date:se}),`Sono de ${I}h registrado.`),children:"Salvar sono"})]}),t==="food"&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("input",{ref:f,type:"file",accept:"image/*",capture:"environment",className:"hidden",onChange:N=>{var me;return((me=N.target.files)==null?void 0:me[0])&&j(N.target.files[0])}}),e.jsx("button",{type:"button",onClick:()=>{var N;return!p&&((N=f.current)==null?void 0:N.click())},className:`w-full border-2 border-dashed rounded-2xl p-6 flex flex-col items-center text-center ${p?"border-slate-200 bg-slate-50":"border-teal-200 bg-teal-50/40 hover:bg-teal-50"}`,children:p?e.jsxs(e.Fragment,{children:[e.jsx(pe,{size:28,className:"animate-spin text-teal-600 mb-2"}),e.jsx("p",{className:"font-bold text-slate-700 text-sm",children:"Analisando o prato…"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{size:28,className:"text-teal-600 mb-2"}),e.jsx("p",{className:"font-bold text-slate-700",children:"Fotografar refeição"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"A IA estima calorias e macros"})]})}),c&&e.jsxs("div",{className:"space-y-3",children:[(c.items||[]).map((N,me)=>e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-6 gap-2 text-sm bg-slate-50 p-2 rounded-xl",children:[e.jsx("input",{className:"col-span-2 rounded-lg bg-white px-2 py-1 outline-none",value:N.name||"",onChange:T=>{const ne=[...c.items];ne[me]={...N,name:T.target.value},g({...c,items:ne,total:w(ne)})}}),e.jsx("input",{type:"number",className:"rounded-lg bg-white px-2 py-1 outline-none",placeholder:"kcal",value:N.kcal??"",onChange:T=>{const ne=[...c.items];ne[me]={...N,kcal:Number(T.target.value)},g({...c,items:ne,total:w(ne)})}}),["protein_g","carbs_g","fat_g"].map(T=>e.jsx("input",{type:"number",className:"rounded-lg bg-white px-2 py-1 outline-none",placeholder:T==="protein_g"?"P g":T==="carbs_g"?"C g":"G g",value:N[T]??"",onChange:ne=>{const Z=[...c.items];Z[me]={...N,[T]:Number(ne.target.value)},g({...c,items:Z,total:w(Z)})}},T))]},me)),e.jsxs("div",{className:"flex items-center justify-between bg-teal-50 rounded-xl px-4 py-3",children:[e.jsxs("p",{className:"font-bold text-teal-900",children:[((Pe=c.total)==null?void 0:Pe.kcal)||0," kcal"]}),e.jsx(M,{onClick:()=>P(se),className:"bg-teal-600 hover:bg-teal-700",children:"Salvar foto"})]})]}),e.jsxs("div",{className:"border-t border-slate-100 pt-4 space-y-3",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700",children:"Ou descreva a refeição"}),e.jsx("input",{className:"w-full rounded-xl bg-slate-50 border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-orange-200",placeholder:"Ex: Almoço — arroz, feijão e frango",value:$,onChange:N=>E(N.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"number",className:"flex-1 rounded-xl bg-slate-50 border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-orange-200",placeholder:"kcal",value:Y,onChange:N=>le(N.target.value)}),e.jsx(M,{disabled:n||!$.trim(),onClick:()=>ee(async()=>{await z.logFood({description:$,kcal:Number(Y||0),log_date:se,date:se}),E(""),le("")},"Refeição registrada."),children:"Salvar"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-400",children:"Últimas refeições"}),a.slice(0,5).map(N=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm bg-slate-50 rounded-xl px-3 py-2",children:[e.jsx("span",{className:"truncate text-slate-700",children:N.description}),e.jsxs("span",{className:"font-bold text-orange-600 whitespace-nowrap",children:[ue(Number(N.kcal||0
5))," kcal"]}),_===N.id?e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{type:"button",disabled:n,onClick:()=>ye(Number(N.id)),className:"px-2 py-1 rounded-lg bg-red-50 text-red-700 text-[11px] font-bold hover:bg-red-100 disabled:opacity-50",children:"Excluir"}),e.jsx("button",{type:"button",onClick:()=>i(null),className:"px-2 py-1 rounded-lg bg-white text-slate-500 text-[11px] font-bold",children:"Não"})]}):e.jsx("button",{type:"button",title:"Remover refeição",onClick:()=>i(N.id),className:"p-1 rounded-lg text-slate-400 hover:text-red-600 hover:bg-red-50 shrink-0",children:e.jsx(Vs,{size:14})})]},N.id)),a.length===0&&e.jsx("p",{className:"text-sm text-slate-400",children:"Nenhuma refeição ainda."})]})]}),t==="activity"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:Ll.map(N=>e.jsx("button",{type:"button",disabled:n,onClick:()=>ee(()=>z.logActivity({minutes:N.minutes,activityType:N.activityType,date:se}),`${N.activityType} de ${N.minutes} min registrada.`),className:"px-3 py-2 rounded-xl bg-rose-50 text-rose-700 text-sm font-bold hover:bg-rose-100 disabled:opacity-50",children:N.label},N.label))}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx("input",{className:"rounded-xl bg-slate-50 border border-slate-200 px-4 py-3 text-sm outline-none",placeholder:"Tipo (ex: Caminhada)",value:b,onChange:N=>H(N.target.value)}),e.jsx("input",{type:"number",className:"rounded-xl bg-slate-50 border border-slate-200 px-4 py-3 text-sm outline-none",placeholder:"Minutos",value:R,onChange:N=>O(N.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(nt,{size:16,className:"absolute left-3 top-3.5 text-slate-400"}),e.jsx("input",{type:"number",className:"w-full rounded-xl bg-slate-50 border border-slate-200 pl-9 pr-4 py-3 text-sm outline-none",placeholder:"Passos (opcional)",value:W,onChange:N=>ie(N.target.value)})]}),e.jsx(M,{disabled:n,onClick:()=>ee(async()=>{await z.logActivity({minutes:Math.max(1,Math.round(Number(R)||0)),activityType:b||"Exercício",date:se}),Number(W)>0&&await z.logSteps({steps:Math.round(Number(W)),mode:"add",date:se})},"Atividade registrada."),children:"Registrar"})]}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Hoje: ",ue(l.stepsToday)," passos"]})]}),t==="alcohol"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-slate-500",children:"Se não bebeu, não precisa registrar. O limite conta só os dias com doses. Uma dose ≈ 350 ml de cerveja, 150 ml de vinho ou 50 ml de destilado."}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[1,2,3].map(N=>e.jsxs("button",{type:"button",disabled:n,onClick:()=>ee(()=>z.logAlcohol({units:N,drinkType:k,date:se}),`${N} dose${N>1?"s":""} registrada${N>1?"s":""}.`),className:"px-4 py-2 rounded-xl bg-purple-50 text-purple-700 text-sm font-bold hover:bg-purple-100 disabled:opacity-50",children:[N," dose",N>1?"s":""]},N))}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx("select",{className:"rounded-xl bg-slate-50 border border-slate-200 px-4 py-3 text-sm outline-none",value:k,onChange:N=>D(N.target.value),children:["Cerveja","Vinho","Destilado","Outro"].map(N=>e.jsx("option",{value:N,children:N},N))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"number",min:1,className:"flex-1 rounded-xl bg-slate-50 border border-slate-200 px-4 py-3 text-sm outline-none",value:ce,onChange:N=>C(N.target.value)}),e.jsx(M,{disabled:n,onClick:()=>ee(()=>z.logAlcohol({units:Number(ce),drinkType:k,date:se}),"Doses registradas."),children:"Salvar"})]})]})]}),t==="weight"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"number",step:.1,className:"flex-1 rounded-xl bg-slate-50 border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-slate-200",placeholder:"Ex: 78.4",value:J,onChange:N=>de(N.target.value)}),e.jsx(M,{disabled:n||!J,onClick:()=>ee(async()=>{await z.logWeight({weight_kg:Number(J),log_date:se,date:se}),de("")},"Peso registrado."),children:"Registrar kg"})]})]}),e.jsx(Zs,{historyTitle:`Histórico de ${L.label.toLowerCase()}`,track:x,onDelete:$e})]})]})};function X(t,s=0){const l=Number(t);return Number.isFinite(l)?l:s}function Zt(t,s){const l=new Map;for(const a of t){const x=xe(s(a));if(!x)continue;const p=l.get(x)||[];p.push(a),l.set(x,p)}return l}function Fl(t,s,l,a){var q,Ce,Le,je,it,rt,ct,dt,mt,h,F,oe,ae,qe,St,ut,Ye,rs,cs,ds,ms,us,xs,ps,hs,gs;const x=tt(),p=X(((q=t==null?void 0:t.goals)==null?void 0:q.water_goal_ml)??((Ce=t==null?void 0:t.goals)==null?void 0:Ce.waterMl),a.waterLiters*1e3),c=X(((Le=t==null?void 0:t.goals)==null?void 0:Le.sleepHours)??((je
5=t==null?void 0:t.goals)==null?void 0:je.sleep_goal_hours),a.sleepHours),g=X(((it=t==null?void 0:t.goals)==null?void 0:it.activityMinutes)??((rt=t==null?void 0:t.goals)==null?void 0:rt.activity_goal_minutes),a.activityMinutes),f=X(((ct=t==null?void 0:t.goals)==null?void 0:ct.steps)??((dt=t==null?void 0:t.goals)==null?void 0:dt.steps_goal),a.steps),j=X(((mt=t==null?void 0:t.goals)==null?void 0:mt.calorieIntakeGoal)??((h=t==null?void 0:t.goals)==null?void 0:h.calorie_intake_goal),a.calorieIntakeGoal),P=X(((F=t==null?void 0:t.goals)==null?void 0:F.alcoholLimitDays)??((oe=t==null?void 0:t.goals)==null?void 0:oe.alcohol_limit_days),a.alcoholLimitDays),w=a.weightGoalKg===""?null:X(a.weightGoalKg,0)||null,S=((ae=t==null?void 0:t.history)==null?void 0:ae.water)||[],y=((qe=t==null?void 0:t.history)==null?void 0:qe.sleep)||[],n=((St=t==null?void 0:t.history)==null?void 0:St.activity)||[],u=((ut=t==null?void 0:t.history)==null?void 0:ut.steps)||[],_=((Ye=t==null?void 0:t.history)==null?void 0:Ye.alcohol)||[],i=((rs=t==null?void 0:t.history)==null?void 0:rs.food)||[],v=S.map(m=>X(m.ml)),B=S.map(m=>({id:`water-${xe(m.date)}`,date:xe(m.date),value:`${Math.round(X(m.ml)).toLocaleString("pt-BR")} ml`,meta:`${(X(m.ml)/1e3).toFixed(1).replace(".",",")} L`,onGoal:X(m.ml)>=p})),I=y.map(m=>X(m.hours)),r=y.map(m=>m.qualityRating!=null?X(m.qualityRating):null).filter(m=>m!=null&&m>0),A=y.map(m=>({id:`sleep-${xe(m.date)}`,date:xe(m.date),value:`${X(m.hours).toFixed(1).replace(".",",")} h`,meta:m.quality||void 0,onGoal:X(m.hours)>=c})),G=new Map(u.map(m=>[xe(m.date),X(m.steps)])),E=[...new Set([...n.map(m=>xe(m.date)),...u.map(m=>xe(m.date))])].filter(Boolean).sort((m,te)=>te.localeCompare(m)).map(m=>{var pt,ht;const te=X((pt=n.find(ze=>xe(ze.date)===m))==null?void 0:pt.minutes),Xe=G.get(m)||0,xt=X((ht=n.find(ze=>xe(ze.date)===m))==null?void 0:ht.caloriesBurned);return{id:`activity-${m}`,date:m,value:`${te} min`,meta:`${Xe.toLocaleString("pt-BR")} passos${xt?` · ${Math.round(xt)} kcal`:""}`,onGoal:te>=g||Xe>=f}}),Y=n.map(m=>X(m.minutes)),le=u.map(m=>X(m.steps)),b=_.map(m=>({id:`alcohol-${xe(m.date)}`,date:xe(m.date),value:`${X(m.units)} dose${X(m.units)===1?"":"s"}`,onGoal:X(m.units)===0})),H=_.map(m=>X(m.units)),R=_.filter(m=>X(m.units)>0).length,O=(l||[]).map((m,te)=>({id:`food-${m.id??`${xe(m.log_date||m.date)}-${te}`}`,date:xe(m.log_date||m.date),value:`${Math.round(X(m.kcal))} kcal`,meta:m.description||void 0,logId:m.id!=null?Number(m.id):void 0})),W=i.map(m=>X(m.kcal)),ie=(l||[]).filter(m=>xe(m.log_date||m.date)===x).length,ce=X((cs=t==null?void 0:t.today)==null?void 0:cs.protein_g),C=(s||[]).map((m,te)=>({id:`weight-${m.id??`${xe(m.log_date)}-${te}`}`,date:xe(m.log_date||m.logged_at),value:`${X(m.weight_kg).toFixed(1).replace(".",",")} kg`,onGoal:w!=null?Math.abs(X(m.weight_kg)-w)<=1:void 0,logId:m.id!=null?Number(m.id):void 0})),k=(s||[]).map(m=>X(m.weight_kg??m.weight_kg)).filter(m=>m>0),D=k.length?k[k.length-1]:null,J=k.length>=2?k[k.length-1]-k[Math.max(0,k.length-7)]:null,de=X(((ds=t==null?void 0:t.today)==null?void 0:ds.waterMl)??((ms=t==null?void 0:t.today)==null?void 0:ms.water)),he=X((us=t==null?void 0:t.today)==null?void 0:us.sleepHours),be=X((xs=t==null?void 0:t.today)==null?void 0:xs.activityMinutes),_e=X((ps=t==null?void 0:t.today)==null?void 0:ps.steps),se=X((hs=t==null?void 0:t.today)==null?void 0:hs.alcoholUnits),ge=X((gs=t==null?void 0:t.today)==null?void 0:gs.calories),fe=Nl({goalMl:p,todayMl:de,averageMl:Ie(v),daysLogged:v.length,daysOnGoal:B.filter(m=>m.onGoal).length,variabilityMl:ks(v)}),d=wl({goalHours:c,tonightHours:he,averageHours:Ie(I),nightsLogged:I.length,nightsOnGoal:A.filter(m=>m.onGoal).length,qualityAvg:r.length?Ie(r):null,variability:ks(I)}),L=Cl({goalMinutes:g,goalSteps:f,minutesToday:be,stepsToday:_e,daysLogged:E.length,daysOnGoal:E.filter(m=>m.onGoal).length,averageMinutes:Ie(Y),averageSteps:Ie(le)}),U=_l({todayUnits:se,weekUnits:H.reduce((m,te)=>m+te,0),weekDaysWithAlcohol:R,limitDays:P,daysLogged:_.length}),K=kl({caloriesToday:ge,calorieGoal:j,averageKcal:Ie(W),daysLogged:i.length||O.length,mealsToday:ie,proteinToday:ce}),re=Sl({current:D,goal:w,daysLogged:C.length,delta7:J}),ee=p>0?Math.round(Ie(v.length?v:[de])/p*100):0,$e=c>0?Math.round(Ie(I.length?I:[he])/c*100):0,ye=g>0?Math.round(Ie(Y.length?Y:[be])/g*100):0,ke=j>0?Math.round(Ie(W.length?W:[ge])/j*100):0,Pe=new Set([...B.map(m=>m.date),...A.map(m=>m.date),...E.map(m=>m.date),...i.map(m=>xe(m.date))]),N=Zt(B,m=>m.date),me=Zt(A,m=>m.date),T=Zt(E,m=>m.date),ne=new Map(i.map(m=>
5[xe(m.date),X(m.kcal)])),Z=[...Pe].filter(Boolean).sort((m,te)=>te.localeCompare(m)).map(m=>{var xt,pt,ht;const te=[];(xt=N.get(m))!=null&&xt.some(ze=>ze.onGoal)&&te.push("Água"),(pt=me.get(m))!=null&&pt.some(ze=>ze.onGoal)&&te.push("Sono"),(ht=T.get(m))!=null&&ht.some(ze=>ze.onGoal)&&te.push("Atividade");const Xe=ne.get(m);return Xe!=null&&j>0&&Xe<=j*1.1&&Xe>=j*.6&&te.push("Alimentação"),{id:`goals-${m}`,date:m,value:`${te.length} meta${te.length===1?"":"s"}`,meta:te.length?te.join(" · "):"Nenhuma meta batida neste dia",onGoal:te.length>=2}}),we=$l({waterPct:ee,sleepPct:$e,activityPct:ye,foodPct:ke,hasWeightGoal:w!=null&&w>0});return{water:{rows:B,tips:fe,summary:m=>`${m.length} dia${m.length===1?"":"s"} · ${m.filter(te=>te.onGoal).length} na meta de ${(p/1e3).toFixed(1).replace(".",",")} L`},sleep:{rows:A,tips:d,summary:m=>`${m.length} noite${m.length===1?"":"s"} · ${m.filter(te=>te.onGoal).length} na meta de ${c}h`},activity:{rows:E,tips:L,summary:m=>`${m.length} dia${m.length===1?"":"s"} · meta ${g} min / ${f.toLocaleString("pt-BR")} passos`},alcohol:{rows:b,tips:U,summary:m=>`${m.filter(te=>!te.onGoal).length} dia${m.filter(te=>!te.onGoal).length===1?"":"s"} com álcool · limite ${P} d/sem`},weight:{rows:C,tips:re,summary:m=>{var te;return m.length?`Último: ${((te=m[0])==null?void 0:te.value)||"—"}${w?` · meta ${w} kg`:""}`:null}},food:{rows:O,tips:K,summary:m=>`${m.length} refeição${m.length===1?"":"ões"} · meta ${j} kcal/dia`},goals:{rows:Z,tips:we,summary:m=>`${m.filter(te=>te.onGoal).length} de ${m.length} dias com pelo menos 2 metas batidas`}}}function Bl(t){return[t.water.tips[0],t.sleep.tips[0],t.activity.tips[0],t.food.tips[0]].filter(Boolean).slice(0,4)}const Gl=()=>{var ee,$e,ye,ke,Pe,N,me,T,ne,Z,we,q,Ce,Le,je,it,rt,ct,dt,mt;const{user:t}
5=Re(),[s,l]=o.useState("score"),[a,x]=o.useState(null),[p,c]=o.useState([]),[g,f]=o.useState([]),[j,P]=o.useState(!0),[w,S]=o.useState(!1),[y,n]=o.useState(null),[u,_]=o.useState({sleepHours:8,waterLiters:2,steps:8e3,activityMinutes:30,alcoholLimitDays:2,calorieIntakeGoal:2e3,weightGoalKg:"",validFrom:new Date().toISOString().split("T")[0],validUntil:""}),[i,v]=o.useState({}),[B,I]=o.useState(""),[r,A]=o.useState("water"),G=o.useRef(null);o.useEffect(()=>{const F=new URLSearchParams(window.location.search).get("tab");(F==="diary"||F==="goals"||F==="profile"||F==="score")&&l(F)},[]);const $=async(h=!1)=>{var F,oe;h||P(!0);try{const[ae,qe,St,ut]=await Promise.all([z.getWellness({days:30}),z.getWeightHistory(60),V.get("/patients/me/wellness/food",{params:{days:30}}),z.getHealthProfile().catch(()=>({data:{}}))]);x(ae.data),c(qe.data.history||[]),v(((F=ut.data)==null?void 0:F.profile)||ut.data||{}),f(St.data.logs||[]),(oe=ae.data)!=null&&oe.goals&&_(Ye=>({...Ye,sleepHours:Number(ae.data.goals.sleepHours||ae.data.goals.sleep_goal_hours||8),waterLiters:Number(ae.data.goals.waterLiters||(ae.data.goals.water_goal_ml?ae.data.goals.water_goal_ml/1e3:2)),steps:Number(ae.data.goals.steps||ae.data.goals.steps_goal||8e3),activityMinutes:Number(ae.data.goals.activityMinutes||ae.data.goals.activity_goal_minutes||30),alcoholLimitDays:Number(ae.data.goals.alcoholLimitDays||ae.data.goals.alcohol_limit_days||2),calorieIntakeGoal:Number(ae.data.goals.calorieIntakeGoal||ae.data.goals.calorie_intake_goal||2e3),weightGoalKg:ae.data.goals.weightGoalKg!=null?Number(ae.data.goals.weightGoalKg):"",validFrom:ae.data.goals.validFrom||ae.data.goals.valid_from||Ye.validFrom,validUntil:ae.data.goals.validUntil||ae.data.goals.valid_until||Ye.validUntil||""}))}catch{I("Não foi possível carregar o bem-estar.")}finally{h||P(!1)}};o.useEffect(()=>{$()},[]);const E=Number((a==null?void 0:a.score)??(a==null?void 0:a.healthScore)??((ee=a==null?void 0:a.today)==null?void 0:ee.score)??0),Y=((($e=a==null?void 0:a.history)==null?void 0:$e.sleep)||(a==null?void 0:a.sleepHistory)||[]).map((h,F)=>({day:h.day||h.date||h.log_date||`D${F+1}`,hours:Number(h.hours||h.duration_hours||h.value||0)})),le=(((ye=a==null?void 0:a.history)==null?void 0:ye.water)||[]).map((h,F)=>({day:h.date||`D${F+1}`,ml:Number(h.ml||0)})),b=(((ke=a==null?void 0:a.history)==null?void 0:ke.food)||[]).map((h,F)=>({day:h.date||`D${F+1}`,kcal:Number(h.kcal||0)})),H={};for(const h of((Pe=a==null?void 0:a.history)==null?void 0:Pe.activity)||[]){const F=h.date||"";F&&(H[F]=Number(h.caloriesBurned||h.calories_burned||0))}const R=[...new Set([...b.map(F=>F.day),...Object.keys(H)])].filter(Boolean).sort().map(F=>{var oe;return{day:F,consumidas:Number(((oe=b.find(ae=>ae.day===F))==null?void 0:oe.kcal)||0),queimadas:H[F]||0}}),O=(((N=a==null?void 0:a.history)==null?void 0:N.alcohol)||[]).map((h,F)=>({day:h.date||`D${F+1}`,units:Number(h.units||0)})),W=Number(((me=a==null?void 0:a.today)==null?void 0:me.waterMl)||((T=a==null?void 0:a.today)==null?void 0:T.water)||0),ie=Number(((ne=a==null?void 0:a.goals)==null?void 0:ne.water_goal_ml)||((Z=a==null?void 0:a.goals)==null?void 0:Z.waterMl)||u.waterLiters*1e3),ce=Number(((we=a==null?void 0:a.today)==null?void 0:we.calories)||0);Number(((q=a==null?void 0:a.today)==null?void 0:q.caloriesBurned)||0);const C=Number(((Ce=a==null?void 0:a.goals)==null?void 0:Ce.calorieIntakeGoal)||u.calorieIntakeGoal||2e3),k=(a==null?void 0:a.healthScore)||((Le=a==null?void 0:a.healthScore)==null?void 0:Le.scores)||{},D=k.scores||k,J=o.useMemo(()=>Fl(a,p,g,u),[a,p,g,u]),de=o.useMemo(()=>Bl(J),[J]),he=Number(((je=a==null?void 0:a.today)==null?void 0:je.sleepHours)??0),be=Number(((it=a==null?void 0:a.today)==null?void 0:it.steps)??0),_e=Number(((rt=a==null?void 0:a.today)==null?void 0:rt.activityMinutes)??0),se=Number(((ct=a==null?void 0:a.week)==null?void 0:ct.alcoholDays)??0),ge=p.length?Number(((dt=p[p.length-1])==null?void 0:dt.weight_kg)??((mt=p[p.length-1])==null?void 0:mt.weight_kg)):null,fe=async h=>{S(!0),n(null);try{const{data:F}=await z.analyzeFood(h);n(F)}catch{I("Não foi possível analisar a foto.")}finally{S(!1)}},d=h=>({kcal:h.reduce((F,oe)=>F+Number(oe.kcal||0),0),protein_g:h.reduce((F,oe)=>F+Number(oe.protein_g||0),0),carbs_g:h.reduce((F,oe)=>F+Number(oe.carbs_g||0),0),fat_g:h.reduce((F,oe)=>F+Number(oe.fat_g||0),0)}),L=async h=>{if(!(y!=null&&y.total))return;const F=(y.items||[]).map(ae=>ae.name).join(", "),oe=d(y.items||[]);
5await z.logFood({description:F||"Refeição fotografada",kcal:oe.kcal,protein_g:oe.protein_g,carbs_g:oe.carbs_g,fat_g:oe.fat_g,photo_path:y.photo_path,log_date:h,date:h}),n(null),I("Refeição salva no diário."),$()},U=async()=>{try{await z.updateWellnessGoals({sleepHours:u.sleepHours,waterLiters:u.waterLiters,steps:u.steps,activityMinutes:u.activityMinutes,alcoholLimitDays:u.alcoholLimitDays,calorieIntakeGoal:u.calorieIntakeGoal,validFrom:u.validFrom,validUntil:u.validUntil,...u.weightGoalKg!==""?{weightGoalKg:Number(u.weightGoalKg)}:{}}),I("Metas atualizadas."),$()}catch{I("Erro ao salvar metas.")}},K=async()=>{var h,F;try{const oe={weightKg:i.weightKg!=null&&i.weightKg!==""?Number(i.weightKg):null,heightCm:i.heightCm!=null&&i.heightCm!==""?Number(i.heightCm):null,bloodType:i.bloodType||null,activityLevel:i.activityLevel||null,healthConditions:Array.isArray(i.healthConditions)?i.healthConditions:[],allergies:Array.isArray(i.allergies)?i.allergies:[],medications:Array.isArray(i.medications)?i.medications:[],alcoholConsumption:i.alcoholConsumption||null,smokingHabit:i.smokingHabit||null,sleepQuality:i.sleepQuality||null,healthDescription:i.healthDescription||null},{data:ae}=await z.updateHealthProfile(oe);v((ae==null?void 0:ae.profile)||oe),I("Perfil de saúde salvo.")}catch(oe){I(((F=(h=oe==null?void 0:oe.response)==null?void 0:h.data)==null?void 0:F.message)||"Erro ao salvar perfil.")}},re=[{name:"Score",value:E,fill:"#3e4cad"}];return e.jsx("div",{className:"min-h-full bg-slate-50 pb-24",children:e.jsxs("main",{className:"w-full px-4 sm:px-6 lg:px-8 space-y-4",children:[e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-1 pt-1",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-extrabold text-slate-800 tracking-tight",children:"Bem-estar"}),e.jsx("p",{className:"text-sm text-slate-500 capitalize",children:jl()})]})}),e.jsx("div",{className:"flex justify-center md:justify-start mb-2",children:e.jsx("div",{className:"inline-flex bg-slate-200/60 p-1.5 rounded-2xl gap-1 overflow-x-auto w-full md:w-auto",children:["score","diary","goals","profile"].map(h=>{const F={score:"Dashboard",diary:"Diário",goals:"Metas",profile:"Perfil"},oe=s===h;return e.jsx("button",{onClick:()=>l(h),className:`px-3 sm:px-6 py-2.5 text-sm font-bold rounded-xl transition-all whitespace-nowrap flex-1 md:flex-none text-center ${oe?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700 hover:bg-slate-200/50"}`,children:F[h]},h)})})}),B&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-2xl bg-teal-50 border border-teal-100 px-4 py-3",children:[e.jsx("p",{className:"text-sm text-teal-800 font-medium",children:B}),e.jsx("button",{type:"button",onClick:()=>I(""),className:"text-xs font-bold text-teal-700 hover:underline",children:"Fechar"})]}),j&&e.jsx("div",{className:"py-16 flex justify-center",children:e.jsx(pe,{className:"animate-spin text-primary-600"})}),!j&&s==="score"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid lg:grid-cols-12 gap-6",children:[e.jsx("div",{className:"lg:col-span-5 flex",children:e.jsxs(Q,{className:"flex-1 w-full p-4 sm:p-8 rounded-3xl border-0 shadow-sm bg-gradient-to-br from-white to-slate-50 flex flex-col items-center justify-center relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 right-0 w-32 h-32 bg-primary-100 rounded-full blur-3xl -mr-10 -mt-10 opacity-50"}),e.jsx("div",{className:"absolute bottom-0 left-0 w-32 h-32 bg-teal-100 rounded-full blur-3xl -ml-10 -mb-10 opacity-50"}),e.jsx("h3",{className:"text-sm font-bold uppercase tracking-widest text-slate-400 mb-1 z-10",children:"Score de Saúde"}),e.jsx("p",{className:"text-xs font-semibold text-slate-400 mb-5 z-10",children:"Últimos 7 dias"}),e.jsxs("div",{className:"relative w-44 h-44 sm:w-56 sm:h-56 z-10 flex items-center justify-center",children:[e.jsx(vt,{width:"100%",height:"100%",children:e.jsx(Ta,{innerRadius:"70%",outerRadius:"100%",data:re,startAngle:90,endAngle:-270,children:e.jsx(Ra,{dataKey:"value",cornerRadius:20,background:{fill:"#f1f5f9"}})})}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center pointer-events-none",children:[e.jsx("span",{className:"text-5xl font-extrabold text-primary-600 tracking-tighter",children:Math.round(E)||"—"}),e.jsx("span",{className:"text-xs font-bold text-slate-400 mt-1 uppercase",children:"/ 100"})]})]}),e.jsx("div",{className:"mt-8 text-center z-10 px-4",children:e.jsx("p",{className:"text-slate-600 font-medium",children:E>=80?"Excelente ritmo — continue assim!":E>=50?"Bom progresso — pequenos ajustes fazem diferença.":"Vamos recomeçar com uma meta simples hoje."})})]})}),e.jsx("div",{className:"lg:col-span-7 flex",children:e.jsxs(Q,{className:"flex-1 w-full p-6 sm:p-8 rounded-3xl border-0 shadow-sm bg-white",children:[e.jsx("div",{className:"flex items-center justify-between mb-5",children:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-slate-800",children:"Hoje"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Progresso em relação às suas metas"})]})}),e.jsxs("div",{className:"grid grid-cols-2 xl:grid-cols-3 gap-3",children:[e.jsx(Ze,{icon:Qe,tone:"blue",label:"Água",value:`${ue(W)} ml`,hint:`Meta ${ue(ie)} ml`,pct:Ve(W,ie),points:D.water}
5),e.jsx(Ze,{icon:Ue,tone:"indigo",label:"Sono",value:`${ue(he,1)} h`,hint:u.sleepHours?`Meta ${u.sleepHours} h`:void 0,pct:Ve(he,Number(u.sleepHours||0)),points:D.sleep}),e.jsx(Ze,{icon:_t,tone:"orange",label:"Alimentação",value:`${ue(ce)} kcal`,hint:`Meta ${ue(C)} kcal`,pct:Ve(ce,C),points:D.food}),e.jsx(Ze,{icon:nt,tone:"emerald",label:"Passos",value:ue(be),hint:u.steps?`Meta ${ue(u.steps)}`:void 0,pct:Ve(be,Number(u.steps||0)),points:D.steps}),e.jsx(Ze,{icon:De,tone:"rose",label:"Atividade",value:`${ue(_e)} min`,hint:u.activityMinutes?`Meta ${u.activityMinutes} min`:void 0,pct:Ve(_e,Number(u.activityMinutes||0)),points:D.activity}),e.jsx(Ze,{icon:Ct,tone:"purple",label:"Álcool",value:`${ue(se)} d`,hint:`Limite ${u.alcoholLimitDays} d/sem`,pct:Ve(se,Number(u.alcoholLimitDays||1)),points:D.alcohol,invertBar:!0})]})]})})]}),e.jsxs("div",{className:"grid lg:grid-cols-12 gap-6",children:[e.jsx("div",{className:"lg:col-span-5 flex",children:e.jsx("div",{className:"flex-1 w-full",children:e.jsx(Js,{tips:de,title:"Recomendações para você"})})}),e.jsx("div",{className:"lg:col-span-7 flex",children:e.jsx(Dl,{sleep:Y.map(h=>({date:String(h.day).slice(0,10),hours:Number(h.hours)})),water:le.map(h=>({date:String(h.day).slice(0,10),ml:Number(h.ml)})),calories:R.map(h=>({date:String(h.day).slice(0,10),consumed:Number(h.consumidas||0),burned:Number(h.queimadas||0)})),alcohol:O.map(h=>({date:String(h.day).slice(0,10),units:Number(h.units)})),weight:p.map(h=>({date:String(h.log_date||h.date||"").slice(0,10),weight:Number(h.weight_kg)})),sleepGoal:Number(u.sleepHours||8),waterGoal:ie,calorieGoal:C,weightGoal:u.weightGoalKg})})]})]}),!j&&s==="diary"&&e.jsx(zl,{track:r,onTrackChange:A,stats:{waterToday:W,waterGoal:ie,sleepToday:he,sleepGoal:Number(u.sleepHours||0),caloriesToday:ce,calorieGoal:C,stepsToday:be,stepsGoal:Number(u.steps||0),activityToday:_e,activityGoal:Number(u.activityMinutes||0),alcoholWeek:se,alcoholLimit:Number(u.alcoholLimitDays||0),latestWeight:ge},foodLogs:g,trackView:J[r],analyzing:w,analysis:y,setAnalysis:n,fileRef:G,onPhoto:fe,saveAnalysis:L,recomputeTotals:d,onLogged:()=>$(!0),onMessage:I}),!j&&s==="goals"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid lg:grid-cols-12 gap-6",children:e.jsx("div",{className:"lg:col-span-12 space-y-6",children:e.jsxs(Q,{className:"p-4 sm:p-8 rounded-3xl border-0 shadow-sm bg-white",children:[e.jsxs("div",{className:"mb-8",children:[e.jsx("h3",{className:"text-xl font-bold text-slate-800",children:"Suas Metas Diárias"}),e.jsx("p",{className:"text-slate-500 mt-1",children:"Ajuste seus objetivos para personalizar o cálculo do seu Score de Saúde."})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-6 bg-slate-50 p-6 rounded-2xl border border-slate-100 mb-6",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Válidas a partir de"}),e.jsx("input",{type:"date",className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 transition-all outline-none",value:u.validFrom,onChange:h=>_({...u,validFrom:h.target.value})})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Até (Opcional)"}),e.jsx("input",{type:"date",className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 transition-all outline-none",value:u.validUntil,onChange:h=>_({...u,validUntil:h.target.value})})]})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-2 gap-6",children:[["sleepHours","Horas de sono","h",e.jsx(Ue,{size:18,className:"text-indigo-500"})],["waterLiters","Água","L",e.jsx(Qe,{size:18,className:"text-blue-500"})],["steps","Passos","passos",e.jsx(nt,{size:18,className:"text-emerald-500"})],["activityMinutes","Atividade","min",e.jsx(De,{size:18,className:"text-rose-500"})],["alcoholLimitDays","Álcool","d/sem",e.jsx(Ct,{size:18,className:"text-purple-500"})],["calorieIntakeGoal","Calorias diárias","kcal",e.jsx(_t,{size:18,className:"text-orange-500"})],["weightGoalKg","Meta de peso","kg",e.jsx(Qs,{size:18,className:"text-slate-500"})]].map(([h,F,oe,ae])=>e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-slate-700 mb-2",children:[ae,F]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"number",className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 font-medium transition-all outline-none",value:u[h],onChange:qe=>_({...u,[h]:qe.target.value===""?"":Number(qe.target.value)})}),e.jsx("span",{className:"absolute right-4 top-3 text-slate-400 text-sm font-medium",children:oe})]}),e.jsxs("p",{className:"text-xs text-slate-500 mt-2",children:[h==="sleepHours"&&`Hoje: ${ue(he,1)} h`,h==="waterLiters"&&`Hoje: ${ue(W/1e3,1)} L`,h==="steps"&&`Hoje: ${ue(be)} passos`,h==="activityMinutes"&&`Hoje: ${ue(_e)} min`,h==="alcoholLimitDays"&&`Esta semana: ${ue(se)}
5 dia(s)`,h==="calorieIntakeGoal"&&`Hoje: ${ue(ce)} kcal`,h==="weightGoalKg"&&(ge!=null?`Atual: ${ue(ge,1)} kg`:"Sem peso recente")]})]})},h))}),e.jsx("div",{className:"pt-4 border-t border-slate-100 flex justify-end",children:e.jsx(M,{onClick:U,className:"px-8 py-2.5 rounded-xl font-bold bg-slate-800 hover:bg-slate-900 shadow-sm",children:"Salvar Metas"})})]})]})})}),e.jsx(Zs,{historyTitle:"Histórico de metas",track:J.goals,emptyText:"Registre água, sono, atividade e refeições para ver o progresso das metas."})]}),!j&&s==="profile"&&e.jsx("div",{className:"space-y-6",children:e.jsxs(Q,{className:"p-4 sm:p-8 rounded-3xl border-0 shadow-sm bg-white",children:[e.jsxs("div",{className:"mb-8",children:[e.jsx("h3",{className:"text-xl font-bold text-slate-800",children:"Perfil de Saúde"}),e.jsx("p",{className:"text-slate-500 mt-1",children:"Esses dados ficam disponíveis ao médico durante a consulta para melhor contexto."})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-2 gap-6",children:[e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Peso (kg)"}),e.jsx("input",{type:"number",className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 transition-all outline-none",value:i.weightKg??"",onChange:h=>v({...i,weightKg:h.target.value===""?"":Number(h.target.value)})})]})}),e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Altura (cm)"}),e.jsx("input",{type:"number",className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 transition-all outline-none",value:i.heightCm??"",onChange:h=>v({...i,heightCm:h.target.value===""?"":Number(h.target.value)})})]})}),e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Tipo Sanguíneo"}),e.jsxs("select",{className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 transition-all outline-none",value:i.bloodType||"",onChange:h=>v({...i,bloodType:h.target.value}),children:[e.jsx("option",{value:"",children:"Selecione"}),["A+","A-","B+","B-","AB+","AB-","O+","O-"].map(h=>e.jsx("option",{value:h,children:h},h))]})]})}),e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Nível de Atividade"}),e.jsxs("select",{className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 transition-all outline-none",value:i.activityLevel||"",onChange:h=>v({...i,activityLevel:h.target.value}),children:[e.jsx("option",{value:"",children:"Selecione"}),["Sedentário","Leve","Moderado","Ativo","Muito Ativo","Extremamente Ativo"].map(h=>e.jsx("option",{value:h,children:h},h))]})]})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-2 gap-6",children:[e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Hábito de Álcool"}),e.jsxs("select",{className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 transition-all outline-none",value:i.alcoholConsumption||"",onChange:h=>v({...i,alcoholConsumption:h.target.value}),children:[e.jsx("option",{value:"",children:"Selecione"}),["Não bebo","Socialmente","1–2x por semana","Frequente"].map(h=>e.jsx("option",{value:h,children:h},h))]})]})}),e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Hábito de Fumo"}),e.jsxs("select",{className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 transition-all outline-none",value:i.smokingHabit||"",onChange:h=>v({...i,smokingHabit:h.target.value}),children:[e.jsx("option",{value:"",children:"Selecione"}),["Não fumo","Ex-fumante","Socialmente","Diariamente"].map(h=>e.jsx("option",{value:h,children:h},h))]})]})}),e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Qualidade do Sono"}),e.jsxs("select",{className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-2.5 text-slate-800 transition-all outline-none",value:i.sleepQuality||"",onChange:h=>v({...i,sleepQuality:h.target.value}),children:[e.jsx("option",{value:"",children:"Selecione"}),["Ruim","Regular","Boa","Ótima"].map(h=>e.jsx("option",{value:h,children:h},h))]})]})})]}),e.jsx("div",{className:"bg-red-50/50 p-4 rounded-2xl border border-red-100",children:e.jsxs("label",{className:"block",children:[e.jsxs("span",{className:"font-semibold text-red-700 block mb-2 flex items-center gap-2",children:[e.jsx(Ys,{size:16})," Alergias"]}),e.jsx("textarea",{className:"w-full bg-white rounded-xl border border-red-200 focus:border-red-500 focus:ring-2 focus:ring-red-500/20 px-4 py-3 text-slate-800 transition-all outline-none min-h-[80px]",placeholder:"Ex: Dipirona, Amendoim (Separe por vírgula)",value:Array.isArray(i.allergies)?i.allergies.join(", "):i.allergies||"",onChange:h=>v({...i,allergies:h.target.value.split(",").map(F=>
5F.trim()).filter(Boolean)})})]})}),e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Condições Crônicas"}),e.jsx("textarea",{className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-3 text-slate-800 transition-all outline-none min-h-[80px]",placeholder:"Ex: Hipertensão, Diabetes (Separe por vírgula)",value:Array.isArray(i.healthConditions)?i.healthConditions.join(", "):i.healthConditions||"",onChange:h=>v({...i,healthConditions:h.target.value.split(",").map(F=>F.trim()).filter(Boolean)})})]})}),e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Medicamentos em Uso"}),e.jsx("textarea",{className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-3 text-slate-800 transition-all outline-none min-h-[80px]",placeholder:"Ex: Losartana 50mg (Separe por vírgula)",value:Array.isArray(i.medications)?i.medications.join(", "):i.medications||"",onChange:h=>v({...i,medications:h.target.value.split(",").map(F=>F.trim()).filter(Boolean)})})]})}),e.jsx("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"font-semibold text-slate-700 block mb-2",children:"Observações Adicionais"}),e.jsx("textarea",{className:"w-full bg-white rounded-xl border border-slate-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-500/20 px-4 py-3 text-slate-800 transition-all outline-none min-h-[80px]",placeholder:"Informações adicionais relevantes para o médico",value:i.healthDescription||"",onChange:h=>v({...i,healthDescription:h.target.value})})]})}),e.jsx("div",{className:"pt-4 border-t border-slate-100 flex justify-end",children:e.jsx(M,{onClick:K,className:"px-8 py-2.5 rounded-xl font-bold bg-slate-800 hover:bg-slate-900 shadow-sm",children:"Salvar Perfil"})})]})]})})]})})},Hl={CONFIRMED:"bg-emerald-50 text-emerald-700",RECEIVED:"bg-emerald-50 text-emerald-700",PENDING:"bg-amber-50 text-amber-700",FAILED:"bg-red-50 text-red-700",REFUNDED:"bg-slate-100 text-slate-600",EXPIRED:"bg-slate-100 text-slate-500",CANCELLED:"bg-slate-100 text-slate-500",ACTIVE:"bg-emerald-50 text-emerald-700",PAST_DUE:"bg-amber-50 text-amber-700"},ta={CONFIRMED:"Confirmado",RECEIVED:"Recebido",PENDING:"Pendente",FAILED:"Falhou",REFUNDED:"Estornado",EXPIRED:"Expirado",CANCELLED:"Cancelado",ACTIVE:"Ativa",PAST_DUE:"Em atraso"},sa={EMERGENCY:"Pronto-atendimento",SPECIALTY:"Especialidade",SUBSCRIPTION_CHARGE:"Assinatura",CREDIT_PACK:"Pacote de créditos"};function Ol(t,s){const l=new Ga;l.setFontSize(18),l.text("Teledoc — Comprovante",14,20),l.setFontSize(11),l.text(`Paciente: ${s}`,14,32),l.text(`Referência: #${t.id}`,14,40),l.text(`Tipo: ${sa[t.type]||t.type}`,14,48),l.text(`Método: ${t.method==="PIX"?"Pix":`Cartão${t.card_brand?` ${t.card_brand}`:""}${t.card_last4?` ****${t.card_last4}`:""}`}`,14,56),l.text(`Valor: R$ ${Number(t.amount).toFixed(2).replace(".",",")}`,14,64),l.text(`Status: ${ta[t.status]||t.status}`,14,72),l.text(`Data: ${new Date(t.paid_at||t.created_at).toLocaleString("pt-BR")}`,14,80),l.text("Pagamento seguro Teledoc",14,96),l.save(`teledoc-recibo-${t.id}.pdf`)}const Wl=()=>{var y;const{user:t}=Re(),s=Me(),[l,a]=o.useState(!0),[x,p]=o.useState([]),[c,g]=o.useState(""),[f,j]=o.useState(""),[P,w]=o.useState("details"),S=()=>{a(!0),Ee.getHistory().then(({data:n})=>{p(n.payments||[])}).catch(()=>g("Não foi possível carregar o faturamento.")).finally(()=>a(!1))};return o.useEffect(S,[]),e.jsx("div",{className:"min-h-full bg-slate-50 pb-20",children:e.jsxs("main",{className:"w-full px-4 sm:px-6 lg:px-8 space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6 pt-4",children:[e.jsx("div",{className:"inline-flex bg-slate-200/60 p-1.5 rounded-2xl gap-1 overflow-x-auto w-full md:w-auto",children:["details","payments"].map(n=>{const u={details:"Detalhes da conta",payments:"Pagamentos"},_=P===n;return e.jsx("button",{onClick:()=>w(n),className:`flex-1 md:flex-none px-4 sm:px-6 py-2.5 rounded-xl text-sm font-bold whitespace-nowrap transition-all duration-300 ${_?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700 hover:bg-slate-200/50"}`,children:u[n]},n)})}),e.jsx(M,{variant:"outline",onClick:()=>
5s("/patient/plans"),className:"w-full sm:w-auto shrink-0 rounded-xl bg-white shadow-sm font-bold border-slate-200",children:"Ver Planos"})]}),f&&e.jsxs("div",{className:"rounded-xl bg-emerald-50 border border-emerald-100 text-emerald-700 px-4 py-3 text-sm flex items-center gap-2 font-medium shadow-sm",children:[e.jsx(Ae,{size:18})," ",f]}),c&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 text-red-700 px-4 py-3 text-sm flex items-center gap-2 font-medium shadow-sm",children:[e.jsx(ot,{size:18})," ",c]}),l&&e.jsx("div",{className:"py-20 flex justify-center",children:e.jsx(pe,{className:"animate-spin text-primary-600 w-8 h-8"})}),!l&&P==="details"&&e.jsxs("div",{className:"w-full space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500",children:[e.jsxs(Q,{className:"p-4 sm:p-8 rounded-3xl border-0 shadow-sm bg-white",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6 sm:mb-8 pb-6 sm:pb-8 border-b border-slate-100",children:[e.jsx("div",{className:"w-14 h-14 sm:w-16 sm:h-16 rounded-full bg-gradient-to-br from-primary-500 to-primary-700 text-white flex items-center justify-center text-2xl font-bold shadow-inner shrink-0",children:((y=t==null?void 0:t.name)==null?void 0:y.charAt(0).toUpperCase())||"P"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-bold text-slate-800 truncate",children:(t==null?void 0:t.name)||"Paciente"}),e.jsx("p",{className:"text-slate-500",children:"Paciente Teledoc"})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx("h3",{className:"text-lg font-bold text-slate-800",children:"Informações Pessoais"}),e.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100 flex items-start gap-3 transition-colors hover:border-slate-300",children:[e.jsx(Ot,{className:"text-slate-400 shrink-0 mt-0.5",size:20}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"Nome Completo"}),e.jsx("p",{className:"font-semibold text-slate-800 mt-1",children:(t==null?void 0:t.name)||"Não informado"})]})]}),e.jsxs("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100 flex items-start gap-3 transition-colors hover:border-slate-300",children:[e.jsx(qs,{className:"text-slate-400 shrink-0 mt-0.5",size:20}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"E-mail"}),e.jsx("p",{className:"font-semibold text-slate-800 mt-1",children:(t==null?void 0:t.email)||"Não informado"})]})]}),e.jsxs("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100 flex items-start gap-3 transition-colors hover:border-slate-300",children:[e.jsx(Ks,{className:"text-slate-400 shrink-0 mt-0.5",size:20}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"Telefone"}),e.jsx("p",{className:"font-semibold text-slate-800 mt-1",children:(t==null?void 0:t.phone)||"Não informado"})]})]}),e.jsxs("div",{className:"bg-slate-50 p-4 rounded-2xl border border-slate-100 flex items-start gap-3 transition-colors hover:border-slate-300",children:[e.jsx(wa,{className:"text-slate-400 shrink-0 mt-0.5",size:20}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"CPF"}),e.jsx("p",{className:"font-semibold text-slate-800 mt-1",children:(t==null?void 0:t.cpf)||"Não informado"})]})]})]})]})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-6",children:e.jsxs(Q,{className:"p-6 rounded-3xl border-0 shadow-sm bg-white",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-slate-100 flex items-center justify-center text-slate-600",children:e.jsx(Hs,{size:20})}),e.jsx("h3",{className:"font-bold text-slate-800",children:"Segurança"})]}),e.jsx("p",{className:"text-sm text-slate-600 mb-6 h-10",children:"Mantenha sua conta segura atualizando sua senha periodicamente."}),e.jsx(M,{variant:"outline",className:"w-full rounded-xl font-bold bg-slate-50 hover:bg-slate-100 border-transparent shadow-sm",children:"Alterar Senha"})]})})]}),!l&&P==="payments"&&e.jsx("div",{className:"w-full animate-in fade-in slide-in-from-bottom-4 duration-500",children:x.length===0?e.jsxs(Q,{className:"p-12 rounded-3xl border-0 shadow-sm bg-white text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-slate-50 flex items-center justify-center mx-auto mb-4 text-slate-400",children:e.jsx(zt,{size:24})}),e.jsx("h3",{className:"text-lg font-bold text-slate-800 mb-2",children:"Nenhum pagamento"}),e.jsx("p",{className:"text-slate-500",children:"O histórico das suas transações aparecerá aqui."})]}):e.jsxs(Q,{className:"rounded-3xl border-0 shadow-sm bg-white overflow-hidden",children:[e.jsx("div",{className:"p-6 border-b border-slate-100 bg-slate-50/30",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg",children:"Histórico de Transações"})}),e.jsx("div",{className:"divide-y divide-slate-100",children:x.map(n=>e.jsxs("div",{className:"p-4 sm:p-6 hover:bg-slate-50/50 transition-colors flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-primary-50 flex items-center justify-center text-primary-600 shrink-0",children:n.method==="PIX"?e.jsx(Gs,{size:20}):e.jsx(zt,{size:20})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-slate-800 text-base",children:sa[n.type]||n.type}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm font-medium text-slate-500 flex items-center gap-1",children:n.method==="PIX"?"Pix":`${n.card_brand||"Cartão"} ****${n.card_last4||"----"}`}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-slate-300"}),e.jsx("span",{className:"text-sm text-slate-500",children:new Date(n.paid_at||n.created_at).toLocaleStr
5ing("pt-BR",{dateStyle:"short",timeStyle:"short"})})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between sm:justify-end gap-4 sm:gap-4 pl-0 sm:pl-0",children:[e.jsxs("div",{className:"text-left sm:text-right",children:[e.jsxs("p",{className:"font-bold text-slate-800",children:["R$ ",Number(n.amount).toFixed(2).replace(".",",")]}),e.jsx("span",{className:`inline-block mt-1 text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full ${Hl[n.status]||"bg-slate-100"}`,children:ta[n.status]||n.status})]}),["CONFIRMED","RECEIVED"].includes(n.status)&&e.jsx("button",{type:"button",className:"w-10 h-10 rounded-xl bg-slate-100 hover:bg-primary-50 hover:text-primary-600 flex items-center justify-center text-slate-400 transition-colors",onClick:()=>Ol(n,(t==null?void 0:t.name)||"Paciente"),"aria-label":"Baixar recibo",title:"Baixar recibo em PDF",children:e.jsx(os,{size:18})})]})]},n.id))})]})})]})})};function Ke(t){return`R$ ${Number(t).toFixed(2).replace(".",",")}`}function jt(t){return t===1?"crédito":"créditos"}function Ul(t){const s=Number(t)||49.9;return[{code:"PACK_1",credits:1,discount:0,label:"1 consulta",unit_amount:s,amount:s,savings:0},{code:"PACK_5",credits:5,discount:.05,label:"Pacote 5 consultas",unit_amount:s,amount:Math.round(s*5*.95*100)/100,savings:Math.round(s*5*.05*100)/100},{code:"PACK_10",credits:10,discount:.1,label:"Pacote 10 consultas",unit_amount:s,amount:Math.round(s*10*.9*100)/100,savings:Math.round(s*10*.1*100)/100}]}function ql(t){const s=(t==null?void 0:t.estimated_minutes)??(t==null?void 0:t.estimatedMinutes);if(s==null||s==="")return null;const l=Number(s);return Number.isFinite(l)?l:null}async function Kl(t){for(let s=0;s<8;s+=1){const{data:l}=await z.getCredits();if(Number(l.balance||0)>=t)return l;await new Promise(a=>setTimeout(a,1200))}return(await z.getCredits()).data}const Vl=[{n:1,title:"Compre créditos",text:"Pague 1, 5 ou 10 consultas."},{n:2,title:"Descreva os sintomas",text:"Opcional, ajuda o médico."},{n:3,title:"Entre na fila",text:"Quando quiser, 24h."}],Ql=()=>{const t=Me(),[s]=Bt(),{user:l}
5=Re(),[a,x]=o.useState("intro"),[p,c]=o.useState(49.9),[g,f]=o.useState([]),[j,P]=o.useState(0),[w,S]=o.useState(!1),[y,n]=o.useState("PACK_5"),[u,_]=o.useState(""),[i,v]=o.useState(null),[B,I]=o.useState(null),[r,A]=o.useState(!1),[G,$]=o.useState(""),[E,Y]=o.useState(null),[le,b]=o.useState(""),[H,R]=o.useState(!1),[O,W]=o.useState(!1),[ie,ce]=o.useState(!!s.get("resume")),C=g.length?g:Ul(p),k=C.find(d=>d.code===y)||C[0],D=a==="packs"||a==="checkout"?1:a==="intro"?2:3,J=d=>{n(d.code),zs(d)};o.useEffect(()=>{const d=s.get("buy")==="1"||s.get("buy")==="true";Ee.getPrices().then(({data:L})=>{var K,re;const U=(K=L.prices)==null?void 0:K.find(ee=>ee.code==="EMERGENCY");U&&c(Number(U.amount)),(re=L.credit_packs)!=null&&re.length&&(f(L.credit_packs),L.credits_enabled!==!1&&(S(!0),x(ee=>ee==="queue"?ee:"packs")))}).catch(()=>{}),z.getCredits().then(({data:L})=>{var U;S(!0),P(Number(L.balance||0)),(U=L.packs)!=null&&U.length&&f(L.packs),L.unit_amount&&c(Number(L.unit_amount)),d?x(K=>K==="queue"?K:"packs"):Number(L.balance||0)>0?x(K=>K==="queue"?K:"intro"):x(K=>K==="queue"?K:"packs")}).catch(()=>{})},[s]),o.useEffect(()=>{let d=!1;const L=s.get("resume");return(async()=>{try{if(L){d||(I(L),x("queue"),ce(!1));return}const{data:U}=await z.getAppointments();if(d)return;const re=(Array.isArray(U)?U:(U==null?void 0:U.appointments)||[]).find(ee=>Number(ee.is_emergency)===1&&ee.queue_status==="waiting"&&!["cancelled","completed","no_show"].includes(ee.status));re!=null&&re.hash&&(I(re.hash),v(re.id),x("queue"))}catch{}finally{d||ce(!1)}})(),()=>{d=!0}},[s]);const de=async()=>{var d,L;a==="packs"&&k?We({option:"pagar_creditos",placement:"emergency_packs",label:`Pagar ${Ke(k.amount)}`,destination:"checkout",extra:{content_ids:[k.code],value:k.amount,currency:"BRL",num_items:k.credits}}):a==="intro"&&We({option:w&&j>0?"entrar_na_fila":"iniciar_consulta",placement:"emergency_intro",label:w?"Entrar na fila de atendimento":"Iniciar consulta",destination:w?"queue":"checkout"}),W(!0),b("");try{const U=u.trim()||"Pronto atendimento solicitado pelo paciente.",K=u.trim()?[{role:"user",content:`Sintomas: ${u.trim()}`}]:[];if(w&&j>0&&a==="intro"){const{data:ee}=await z.startEmergencyWithCredit({screening_history:K,summary:U,risk_level:"low"});v(ee.appointment_id),I(ee.appointment_hash),ee.already_in_queue||P($e=>Math.max(0,$e-1)),x("queue");return}if(w){if(a!=="packs"&&j<=0){x("packs");return}v(null),I(null),x("checkout"),A(!0);return}const{data:re}=await z.prepareEmergency({screening_history:K,summary:U,risk_level:"low"});if(re.already_in_queue){I(re.appointment_hash),v(re.appointment_id),x("queue");return}v(re.appointment_id),I(re.appointment_hash),x("checkout"),A(!0)}catch(U){b(((L=(d=U==null?void 0:U.response)==null?void 0:d.data)==null?void 0:L.message)||"Não foi possível iniciar o atendimento.")}finally{W(!1)}},he=async d=>{var L,U;if(d.paymentId){A(!1),W(!0);try{if(w){const ee=(k==null?void 0:k.credits)||1,$e=await Kl(ee),ye=Number($e.balance||0);P(ye),$(ye>0?`${ye} ${jt(ye)} adicionados. Descreva os sintomas e entre na fila.`:"Pagamento confirmado. Se o saldo não aparecer, atualize a página em alguns segundos."),x("intro");return}const{data:K}=await z.startEmergency({payment_id:d.paymentId,appointment_id:i||void 0});I(K.appointment_hash),x("queue");const re=K.appointment_id||i;re&&wt("Schedule",{content_name:"emergency"},`schedule:${re}`)}catch(K){b(((U=(L=K==null?void 0:K.response)==null?void 0:L.data)==null?void 0:U.message)||(w?"Pagamento confirmado. Atualize a tela para ver seus créditos.":"Pagamento confirmado, mas falhou ao entrar na fila. Tente novamente.")),w&&x("intro")}finally{W(!1)}}},be=o.useCallback(async()=>{if(B)try{const{data:d}=await V.get(`/emergency/waiting-time/${B}`);Y({position:d==null?void 0:d.position,estimated_minutes:ql(d),queue_status:(d==null?void 0:d.queue_status)||(d==null?void 0:d.status)}),((d==null?void 0:d.status)==="in_consultation"||(d==null?void 0:d.queue_status)==="in_consultation"||d!=null&&d.ready||(d==null?void 0:d.status)==="in_progress")&&t(`/call/patient/${B}`,{state:{postConsultPath:`/patient/post-consult/${B}`}})}catch{}},[B,t]);o.useEffect(()=>{if(a!=="queue"||!B)return;be();const d=setInterval(be,5e3);return()=>clearInterval(d)},[a,B,be]);const _e=async()=>{var d,L;if(B){if(!H){R(!0);return}try{const{data:U}=await z.abandonEmergency({appointment_hash:B,confirm:!0});t("/patient/dashboard",{state:{flash:w?"Você saiu da fila. O crédito voltou para sua conta.":(U==null?void 0:U.message)||"Você saiu da fila."}})}catch(U){b(((L=(d=U==null?void 0:U.response)==null?void 0:d.data)==null?void 0:L.message)||"Não foi possível sair da fila."),R(!1)}}},se=((l==null?void 0:l.name)||"Paciente").split(" ")[0],ge=Ke(w&&k?k.amount:p),fe=o.useMemo(()=>e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3 mb-6",children:Vl.map(d=>e.jsxs("div",{className:`rounded-xl border p-4 ${D===d.n?"border-primary-500 bg-primary-50":"border-slate-200 bg-white"}`,children:[e.jsxs("p",{className:"text-xs font-bold uppercase tracking-wide text-primary-600 mb-1",children:["Passo ",d.n]}),e.jsx("p",{className:"font-semibold text-slate-900",children:d.title}),e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:d.text})]},d.n))}),[D]);return ie?e.jsx("div",{className:"min-h-full bg-slate-50 flex items-center justify-center py-20",children:e.jsx(pe,{className:"animate-spin text-teal-600",
5size:32})}):e.jsxs("div",{className:"min-h-full bg-slate-50 pb-20",children:[e.jsxs("main",{className:"w-full max-w-4xl px-4 sm:px-6 lg:px-8 mt-4 sm:mt-8 space-y-6 mx-auto",children:[le&&e.jsx("div",{className:"rounded-xl bg-red-50 text-red-700 px-4 py-3 text-sm border border-red-100",children:le}),G&&a!=="queue"&&e.jsx("div",{className:"rounded-xl bg-emerald-50 text-emerald-800 px-4 py-3 text-sm border border-emerald-100 font-semibold",children:G}),w&&a!=="queue"&&fe,a==="packs"&&e.jsxs(Q,{className:"p-6 sm:p-8 rounded-2xl border-0 shadow-lg",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-3 mb-2 text-primary-600",children:[e.jsx(Os,{size:26,className:"shrink-0 mt-0.5 sm:mt-0"}),e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-900 leading-tight",children:"Compre créditos de consulta"})]}),e.jsx("p",{className:"text-slate-600 mb-2 leading-relaxed",children:"Pague agora. Depois descreva os sintomas e entre na fila. O crédito só é descontado quando um profissional assume o atendimento."}),e.jsx("p",{className:"text-sm text-slate-500 mb-6",children:"Se você sair da fila antes do médico assumir, o crédito volta. O valor do pacote não é estornado."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:C.map(d=>{const L=d.credits>0?d.amount/d.credits:d.amount,U=d.code==="PACK_5",K=y===d.code;return e.jsxs("button",{type:"button",onClick:()=>J(d),className:`relative text-left rounded-2xl border-2 p-5 transition ${K?"border-primary-500 bg-primary-50 shadow-md":"border-slate-200 bg-white hover:border-primary-200"}`,children:[U&&e.jsx("span",{className:"absolute -top-2.5 left-4 text-[10px] font-bold uppercase tracking-wide bg-emerald-600 text-white px-2 py-0.5 rounded-full",children:"Mais vantajoso"}),d.discount>0&&e.jsxs("span",{className:"absolute -top-2.5 right-4 text-[10px] font-bold uppercase tracking-wide bg-slate-900 text-white px-2 py-0.5 rounded-full",children:[Math.round(d.discount*100),"% off"]}),e.jsx("p",{className:"text-4xl font-extrabold text-slate-900 mt-2",children:d.credits}),e.jsx("p",{className:"text-sm font-semibold text-slate-600 mb-3",children:d.credits===1?"consulta":"consultas"}),e.jsx("p",{className:"text-2xl font-bold text-primary-700",children:Ke(d.amount)}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[Ke(L)," por consulta"]}),d.savings>0&&e.jsxs("p",{className:"text-xs font-semibold text-emerald-700 mt-2",children:["Economia de ",Ke(d.savings)]}),e.jsxs("p",{className:`mt-4 text-sm font-semibold flex items-center gap-1 ${K?"text-primary-700":"text-slate-400"}`,children:[K?e.jsx(Ft,{size:16}):null,K?"Selecionado":"Escolher"]})]},d.code)})}),e.jsx(M,{className:"w-full",size:"lg",onClick:de,disabled:O,children:O?e.jsx(pe,{className:"animate-spin"}):`Pagar ${ge} e receber ${(k==null?void 0:k.credits)||1} ${jt((k==null?void 0:k.credits)||1)}`}),j>0&&e.jsx(M,{type:"button",variant:"outline",className:"w-full mt-3",size:"lg",onClick:()=>x("intro"),children:"Já tenho créditos — ir para a fila"})]}),a==="intro"&&e.jsxs(Q,{className:"p-6 sm:p-8 rounded-2xl border-0 shadow-lg",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-3 mb-4 text-primary-600",children:[e.jsx(lt,{size:28,className:"shrink-0 mt-0.5 sm:mt-0"}),e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-900 leading-tight",children:"Médico agora, sem agendar"})]}),e.jsx("p",{className:"text-slate-600 mb-6 leading-relaxed",children:w?"Clínico geral 24h. Descreva os sintomas (opcional) e entre na fila.":"Informe os sintomas (opcional), pague por esta consulta e entre na fila com clínico geral — 24 horas, 7 dias por semana."}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-4 mb-6 flex gap-3 text-left",children:[e.jsx(Mt,{size:20,className:"text-amber-600 shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-amber-900 leading-relaxed",children:"A TeleDoc não é destinada ao atendimento de urgência ou emergência. Em situações de risco imediato à vida, agravamento súbito, dor intensa, falta de ar, perda de consciência, suspeita de AVC, infarto, trauma, sangramento importante ou qualquer outra situação emergencial, o usuário deverá buscar atendimento presencial adequado pelos meios de emergência disponíveis em sua localidade."})]}),e.jsx("div",{className:"rounded-xl bg-teal-50 border border-teal-100 text-slate-800 p-4 mb-6",children:w?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-teal-800",children:"Seu saldo"}),e.jsxs("p",{className:"text-2xl font-bold text-teal-950 mt-0.5",children:[j," ",jt(j)]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-teal-800",children:"Valor da consulta"}),e.jsx("p",{className:"text-2xl font-bold text-teal-950 mt-0.5",children:Ke(p)})]})}),e.jsx("label",{className:"block text-sm font-semibold text-slate-700 mb-2",children:"Descreva seus sintomas (opcional)"}),e.jsx("textarea",{value:u,onChange:d=>_(d.target.value),placeholder:"Ex.: dor de cabeça e febre baixa",rows:4,className:"w-full mb-6 px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 outline-none focus:border-primary-500 focus:ring-4 focus:ring-primary-100 resize-y"}),e.jsx(M,{className:"w-full",size:"lg",onClick:de,disabled:O||w&&j<=0,children:O?e.jsx(pe,{className:"animate-spin"}):w?"Entrar na fila de atendimento":"Iniciar consulta"}
5),w&&e.jsx(M,{type:"button",variant:"outline",className:"w-full mt-3",size:"lg",onClick:()=>x("packs"),children:"Comprar mais créditos"}),e.jsx("p",{className:"text-center text-xs text-slate-500 mt-3 leading-relaxed",children:w?j>0?"O crédito só é usado se um médico assumir. Se você sair da fila antes, ele volta.":"Compre créditos para entrar na fila.":"O pagamento é necessário antes de entrar na fila."})]}),a==="checkout"&&!r&&e.jsxs(Q,{className:"p-5 sm:p-8 text-center rounded-2xl",children:[e.jsx("p",{className:"mb-2 text-slate-800 font-semibold",children:w?`Pague ${ge} para adicionar ${k==null?void 0:k.credits} ${jt((k==null?void 0:k.credits)||1)}.`:"Finalize o pagamento para entrar na fila."}),e.jsx("p",{className:"mb-4 text-sm text-slate-500",children:w?"Depois você descreve os sintomas e entra na fila.":"O pagamento libera a fila do clínico geral."}),e.jsx(M,{onClick:()=>A(!0),children:"Abrir pagamento"})]}),a==="queue"&&e.jsxs(Q,{className:"p-5 sm:p-8 rounded-2xl text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-secondary-500/15 flex items-center justify-center",children:e.jsxs("span",{className:"relative flex h-4 w-4",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-secondary-500 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-4 w-4 bg-secondary-500"})]})}),e.jsxs("h2",{className:"text-xl font-bold text-slate-900",children:["Você está na fila, ",se]}),w&&e.jsx("div",{className:"max-w-md mx-auto rounded-xl bg-emerald-50 border border-emerald-100 px-4 py-3 text-sm text-emerald-900",children:"1 crédito reservado. Se desistir agora, ele volta. Só é descontado quando o profissional assumir."}),e.jsx("p",{className:"text-slate-500 text-sm",children:"Mantenha esta tela aberta. Você será chamado automaticamente."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 max-w-xs mx-auto",children:[e.jsxs("div",{className:"rounded-xl bg-slate-50 p-4",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Posição"}),e.jsx("p",{className:"text-2xl font-bold text-primary-600",children:(E==null?void 0:E.position)??"—"})]}),e.jsxs("div",{className:"rounded-xl bg-slate-50 p-4",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Espera estimada"}),e.jsx("p",{className:"text-2xl font-bold text-primary-600",children:(E==null?void 0:E.estimated_minutes)!=null?`${E.estimated_minutes} min`:"—"})]})]}),e.jsx(Ha,{className:"max-w-md mx-auto"}),e.jsx("button",{type:"button",onClick:_e,className:"text-xs text-slate-400 hover:text-red-500 underline mt-4 px-2 leading-relaxed max-w-md mx-auto",children:H?w?"Confirmar desistência — o crédito volta para sua conta":"Confirmar desistência — se houve pagamento, o estorno será processado (cupom 100% não gera estorno)":"Desistir do atendimento"}),H&&e.jsx("button",{type:"button",className:"block mx-auto text-xs text-slate-400 hover:text-slate-600",onClick:()=>R(!1),children:"Continuar na fila"})]})]}),e.jsx(Wt,{open:r,onClose:()=>A(!1),purpose:w?"CREDIT_PACK":"EMERGENCY",referenceId:w?y:void 0,appointmentId:w?void 0:i||void 0,amount:w?(k==null?void 0:k.amount)??p:p,summary:{title:w?`${(k==null?void 0:k.credits)||1} ${jt((k==null?void 0:k.credits)||1)} de consulta`:"Pronto-atendimento",subtitle:w?"Pague o pacote agora. Depois descreva os sintomas e entre na fila.":"Pagamento por consulta · clínico geral",amountLabel:ge},onSuccess:he})]})};function Et(t,s){const l=new Date(t);return l.setDate(l.getDate()+s),l}function Dt(t){return t.toISOString().slice(0,10)}function Yl(t){return t?t.startsWith("http")?t:`${Gt.replace(/\/api\/v1\/?$/,"")}${t.startsWith("/")?t:`/${t}`}`:null}function Xl(t){const s=g=>g.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),l=new Date(t.start.getTime()+18e5),a=["BEGIN:VCALENDAR","VERSION:2.0","BEGIN:VEVENT",`DTSTART:${s(t.start)}`,`DTEND:${s(l)}`,`SUMMARY:${t.title}`,`DESCRIPTION:${t.description}`,"END:VEVENT","END:VCALENDAR"].join(`\r
6`),x=new Blob([a],{type:"text/calendar"}),p=URL.createObjectURL(x),c=document.createElement("a");c.href=p,c.download="consulta-teledoc.ics",c.click(),URL.revokeObjectURL(p)}function As({name:t,photo:s}){const l=Yl(s);return l?e.jsx("img",{src:l,alt:t,className:"w-10 h-10 rounded-full object-cover border border-slate-200",onError:a=>{a.target.style.display="none"}}):e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center",children:e.jsx(Ot,{size:18})})}const Jl=()=>{const t=Me(),[s]=Bt(),l=s.get("rescheduleId")?Number(s.get("rescheduleId")):null,a=s.get("specialtyId")?Number(s.get("specialtyId")):null,[x,p]=o.use
6State([]),[c,g]=o.useState(null),[f,j]=o.useState(()=>{const R=new Date;return R.setHours(12,0,0,0),R}),[P,w]=o.useState({}),[S,y]=o.useState(Dt(new Date)),[n,u]=o.useState(null),[_,i]=o.useState(!1),[v,B]=o.useState(!1),[I,r]=o.useState(null),[A,G]=o.useState(null),[$,E]=o.useState(""),Y=!!(c!=null&&c.subscription_active&&(c.sessions_remaining==null||c.sessions_remaining>0));o.useEffect(()=>{z.getSpecialties().then(({data:R})=>{const O=R.specialties||[];if(p(O),a){const W=O.find(ie=>Number(ie.id)===a);W&&g(W)}}).catch(()=>E("Não foi possível carregar especialidades."))},[a]);const le=o.useMemo(()=>Array.from({length:7},(R,O)=>Et(f,O)),[f]);o.useEffect(()=>{if(!c)return;i(!0);const R=Dt(f),O=Dt(Et(f,6));z.getSpecialtyAvailability(c.id,R,O).then(({data:W})=>{w(W.days||{}),y(R),u(null)}).catch(()=>E("Não foi possível carregar a agenda.")).finally(()=>i(!1))},[c,f]);const b=async(R=!1)=>{var O,W,ie,ce,C,k;if(!(!c||!n)){i(!0),E("");try{if(l){const{data:J}=await z.rescheduleAppointment(l,{professional_id:n.professional_id,date:n.date,time:n.time});G({hash:J.appointment_hash||"",when:`${n.date} ${n.time}`,professional:n.professional_name});return}const{data:D}=await z.reserveAppointment({specialty_id:c.id,professional_id:n.professional_id,date:n.date,time:n.time,payment_source:R?"SUBSCRIPTION":"CHECKOUT"});r(D.appointment_id),D.requires_payment?B(!0):(G({hash:D.appointment_hash,when:`${n.date} ${n.time}`,professional:n.professional_name}),D.appointment_id&&wt("Schedule",{content_name:"specialty"},`schedule:${D.appointment_id}`))}catch(D){const J=((W=(O=D==null?void 0:D.response)==null?void 0:O.data)==null?void 0:W.message)||"Não foi possível reservar o horário.";if(!l&&R&&(((ie=D==null?void 0:D.response)==null?void 0:ie.status)===402||((ce=D==null?void 0:D.response)==null?void 0:ce.status)===403))try{const{data:de}=await z.reserveAppointment({specialty_id:c.id,professional_id:n.professional_id,date:n.date,time:n.time,payment_source:"CHECKOUT"});r(de.appointment_id),B(!0);return}catch(de){E(((k=(C=de==null?void 0:de.response)==null?void 0:C.data)==null?void 0:k.message)||J);return}E(J)}finally{i(!1)}}},H=()=>{B(!1),I&&wt("Schedule",{content_name:"specialty"},`schedule:${I}`),n&&c&&G({hash:"",when:`${n.date} ${n.time}`,professional:n.professional_name})};if(A){const R=n?new Date(`${n.date}T${n.time}:00`):new Date;return e.jsx("div",{className:"min-h-full bg-slate-50",children:e.jsx("main",{className:"w-full px-4 mt-10",children:e.jsxs(Q,{className:"p-8 rounded-2xl text-center space-y-4",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Tudo certo!"}),e.jsxs("p",{className:"text-slate-600",children:[c==null?void 0:c.name," com ",A.professional,e.jsx("br",{}),e.jsx("strong",{children:A.when})]}),e.jsxs(M,{className:"w-full",onClick:()=>
6Xl({title:`Consulta Teledoc — ${c==null?void 0:c.name}`,start:R,description:`Profissional: ${A.professional}`}),children:[e.jsx(Ca,{size:16,className:"mr-2"})," Adicionar ao calendário"]}),e.jsx(M,{variant:"outline",className:"w-full",onClick:()=>t("/patient/agenda"),children:"Ver meus atendimentos"})]})})})}return A?e.jsxs("div",{className:"min-h-full bg-slate-50 pb-24",children:[e.jsxs("main",{className:"w-full px-4 sm:px-6 lg:px-8 mt-8 space-y-6",children:[$&&e.jsx("div",{className:"rounded-xl bg-red-50 text-red-700 px-4 py-3 text-sm",children:$}),l&&e.jsx("p",{className:"text-sm text-slate-500",children:"Escolha um novo horário. Não haverá nova cobrança."}),c?e.jsxs(e.Fragment,{children:[!l&&e.jsx("button",{type:"button",className:"text-sm text-primary-600 font-semibold",onClick:()=>g(null),children:"← Trocar especialidade"}),Y&&e.jsxs("div",{className:"rounded-xl bg-secondary-500/10 text-secondary-700 px-4 py-3 text-sm font-medium",children:["Plano ativo: você pode agendar sem novo pagamento",c.sessions_remaining!=null?` (${c.sessions_remaining} sessões restantes neste mês)`:"","."]}),e.jsxs(Q,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"font-bold text-lg",children:c.name}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"button",className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>j(Et(f,-7)),children:e.jsx(_a,{size:18})}),e.jsx("button",{type:"button",className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>j(Et(f,7)),children:e.jsx(ka,{size:18})})]})]}),e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:le.map(R=>{var ce;const O=Dt(R),W=R.toLocaleDateString("pt-BR",{weekday:"short",day:"2-digit"}),ie=((ce=P[O])==null?void 0:ce.length)||0;return e.jsxs("button",{type:"button",onClick:()=>{y(O),u(null)},className:`min-w-[72px] rounded-xl px-3 py-2 text-sm font-semibold border ${S===O?"bg-primary-600 text-white border-primary-600":"bg-white text-slate-600 border-slate-200"}`,children:[e.jsx("div",{children:W}),e.jsxs("div",{className:"text-[10px] opacity-80",children:[ie," horários"]})]},O)})}),_?e.jsx("div",{className:"py-10 flex justify-center",children:e.jsx(pe,{className:"animate-spin text-primary-600"})}):e.jsxs("div",{className:"mt-4 space-y-6",children:[Object.entries((P[S]||[]).reduce((R,O)=>(R[O.professional_id]||(R[O.professional_id]={info:O,times:[]}),R[O.professional_id].times.push(O),R),{})).map(([R,O])=>e.jsxs("div",{className:"border border-slate-100 rounded-2xl p-4 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(As,{name:O.info.professional_name,photo:O.info.professional_photo}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-slate-900",children:O.info.professional_name}),e.jsx("p",{className:"text-xs text-slate-500",children:O.info.registration||"Registro profissional"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:O.times.map(W=>{const ie=(n==null?void 0:n.time)===W.time&&(n==null?void 0:n.professional_id)===W.professional_id&&(n==null?void 0:n.date)===S;return e.jsx("button",{type:"button",onClick:()=>u({...W,date:S}),className:`px-4 py-2 rounded-xl text-sm font-bold border transition ${ie?"bg-primary-600 text-white border-primary-600 shadow-sm":"bg-slate-50 text-slate-700 border-slate-200 hover:border-primary-600 hover:text-primary-600"}`,children:W.time},`${W.professional_id}-${W.time}`)})})]},R)),(P[S]||[]).length===0&&e.jsx("p",{className:"text-sm text-slate-400 py-4 text-center",children:"Nenhum horário neste dia."})]}),n&&e.jsxs("div",{className:"mt-6 rounded-xl bg-slate-50 p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(As,{name:n.professional_name,photo:n.professional_photo}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-900",children:n.professional_name}),e.jsxs("p",{className:"text-sm text-slate-500",children:[n.date.split("-").reverse().join("/")," às ",n.time,n.registration?` · ${n.registration}`:""]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[!l&&Y&&e.jsx(M,{disabled:_,onClick:()=>b(!0),children:_?e.jsx(pe,{className:"animate-spin"}):"Agendar com plano"}),!l&&!Y&&e.jsx(M,{disabled:_,onClick:()=>b(!1),children:_?e.jsx(pe,{className:"animate-spin"}):"Continuar para pagamento"}),l&&e.jsx(M,{disabled:_,onClick:()=>b(!1),children:_?e.jsx(pe,{className:"animate-spin"}):"Confirmar novo horário"}),!l&&Y&&e.jsx(M,{variant:"outline",disabled:_,onClick:()=>b(!1),children:"Pagar avulso"})]})]})]})]}):x.length===0&&!$?e.jsx(Q,{className:"p-10 text-center rounded-2xl text-slate-500",children:"Nenhuma especialidade disponível no momento."}):e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:x.map(R=>e.jsxs("button",{type:"button",onClick:()=>g(R),className:"text-left rounded-2xl border border-slate-100 p-5 hover:border-primary-600 hover:shadow-md transition bg-white",children:[e.jsx("h3",{className:"font-bold text-slate-900",children:R.name}),R.subscription_active?e.jsxs("p",{className:"text-sm text-secondary-600 mt-2 font-semibold",children:["Incluso no seu plano · ",R.sessions_remaining??0," sessões restantes"]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:"a partir de"}),e.jsxs("p",{className:"text-xl font-bold text-primary-600",children:["R$ ",Number(R.amount).toFixed(2).replace(".",",")]})]})]},R.id))})]}),!l&&e.jsx(Wt,{open:v,onClose:()=>
6B(!1),purpose:"SPECIALTY",referenceId:c?String(c.id):void 0,appointmentId:I||void 0,amount:c?Number(c.amount):void 0,summary:{title:(c==null?void 0:c.name)||"Consulta",subtitle:n?`${n.professional_name} · ${n.date} ${n.time}`:void 0,amountLabel:c?`R$ ${Number(c.amount).toFixed(2).replace(".",",")}`:void 0},onSuccess:H})]}):e.jsxs("div",{className:"min-h-full bg-slate-50 pb-24",children:[e.jsxs("header",{className:"w-full px-4 sm:px-6 lg:px-8",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-800",children:"Especialidades"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Consultas agendadas"})]}),e.jsx("main",{className:"w-full px-4 sm:px-6 lg:px-8 mt-6",children:e.jsxs(Q,{className:"p-5 sm:p-8 rounded-2xl text-center space-y-4 max-w-lg mx-auto",children:[e.jsx("span",{className:"inline-flex items-center px-3 py-1 rounded-full text-[11px] font-bold uppercase tracking-wider bg-amber-50 text-amber-700 border border-amber-200",children:"Em breve"}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Consultas por especialidade"}),e.jsx("p",{className:"text-slate-600 leading-relaxed",children:"Estamos preparando a agenda de especialistas. Por enquanto, você pode usar o pronto-atendimento 24/7 e o score de bem-estar."}),e.jsx(M,{className:"w-full",onClick:()=>t("/patient/emergency"),children:"Ir para pronto-atendimento"}),e.jsx(M,{variant:"outline",className:"w-full",onClick:()=>t("/patient/wellness"),children:"Abrir bem-estar"})]})})]})},Zl=[{purpose:"MENTAL_HEALTH_PLAN",code:"MENTAL_HEALTH_PLAN",planCode:"MENTAL_HEALTH",title:"Saúde Mental",icon:Sa,comingSoon:!0,benefits:["Sessões recorrentes com psicólogo","Até 4 sessões por mês","Agendamento sem novo pagamento","Acompanhamento contínuo"]},{purpose:"NUTRITION_PLAN",code:"NUTRITION_PLAN",planCode:"NUTRITION",title:"Nutrição",icon:$a,comingSoon:!0,benefits:["Acompanhamento com nutricionista","Até 4 sessões por mês","Agendamento incluso no plano","Metas e diário alimentar no app"]}],en=()=>
6{const t=Me(),[s,l]=o.useState([]),[a,x]=o.useState({}),[p,c]=o.useState(null),[g,f]=o.useState(!1),[j,P]=o.useState(!1),w=()=>{z.getPlanCoverage().then(({data:n})=>{const u={};(n.plans||[]).forEach(_=>{u[_.plan_code]=_}),x(u)}).catch(()=>{})};o.useEffect(()=>{Ee.getPrices().then(({data:n})=>l(n.prices||[])).catch(()=>{}),w()},[]);const S=n=>{const u=s.find(_=>_.code===n);return u?Number(u.amount):119.9},y=n=>{var i;const u=a[n],_=(i=u==null?void 0:u.specialty_ids)==null?void 0:i[0];t(_?`/patient/book?specialtyId=${_}`:"/patient/book")};return e.jsxs("div",{className:"min-h-full bg-slate-50 pb-20",children:[e.jsx("header",{className:"w-full px-4 sm:px-6 lg:px-8",children:e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-gray-800",children:"Planos de acompanhamento"})}),e.jsxs("main",{className:"w-full px-4 sm:px-6 lg:px-8 mt-6 space-y-6",children:[j&&e.jsx("div",{className:"rounded-xl bg-secondary-500/10 text-secondary-600 px-4 py-3 text-sm font-semibold",children:"Assinatura ativada! Você já pode agendar suas sessões inclusas."}),e.jsx("div",{className:"grid md:grid-cols-2 gap-6",children:Zl.map(n=>{const u=n.icon,_=S(n.code),i=a[n.planCode],v=!!(i!=null&&i.active);return e.jsxs(Q,{className:`p-6 rounded-2xl border-0 shadow-lg flex flex-col ${n.comingSoon?"opacity-90":""}`,children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-primary-50 text-primary-600 flex items-center justify-center",children:e.jsx(u,{size:24})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:n.title}),n.comingSoon&&e.jsx("span",{className:"inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-amber-50 text-amber-700 border border-amber-200",children:"Em breve"})]}),e.jsx("p",{className:"text-sm text-slate-500",children:n.comingSoon?"Disponível em breve":v?"Plano ativo":"Plano mensal"})]})]}),e.jsxs("p",{className:"text-3xl font-bold text-primary-600 mb-4",children:["R$ ",_.toFixed(2).replace(".",","),e.jsx("span",{className:"text-sm font-medium text-slate-400",children:"/mês"})]}),v&&i&&e.jsxs("p",{className:"text-sm text-secondary-600 font-semibold mb-3",children:[i.remaining," de ",i.limit," sessões restantes neste mês"]}),e.jsx("ul",{className:"space-y-2 mb-6 flex-1",children:n.benefits.map(B=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-slate-600",children:[e.jsx(Ft,{size:16,className:"text-secondary-500 mt-0.5 shrink-0"})," ",B]},B))}),n.comingSoon?e.jsx(M,{className:"w-full",disabled:!0,children:"Em breve"}):v?e.jsx(M,{className:"w-full",onClick:()=>y(n.planCode),disabled:i!=null&&i.remaining<=0,children:i!=null&&i.remaining<=0?"Limite mensal atingido":"Agendar sessão"}):e.jsx(M,{className:"w-full",onClick:()=>{c(n),f(!0)},children:"Assinar"})]},n.code)})}),e.jsx(M,{variant:"outline",className:"w-full",onClick:()=>t("/patient/billing"),children:"Gerenciar assinaturas no faturamento"})]}),p&&e.jsx(Wt,{open:g,onClose:()=>f(!1),purpose:p.purpose,isSubscription:!0,amount:S(p.code),summary:{title:`Plano ${p.title}`,subtitle:"Cobrança mensal",amountLabel:`R$ ${S(p.code).toFixed(2).replace(".",",")}/mês`},onSuccess:()=>{f(!1),P(!0),w()}})]})},tn={prescription:"Receita médica",exam_request:"Solicitação de exames",medical_certificate:"Atestado médico",referral:"Encaminhamento",report:"Relatório"};function sn(t){if(!t)return null;try{const s=sessionStorage.getItem(`teledoc_nps_${t}`);return s?(sessionStorage.removeItem(`teledoc_nps_${t}`),JSON.parse(s)):null}catch{return null}}const an=()=>{const{hash:t}
6=Ds(),s=kt(),l=Me(),[a,x]=o.useState(null),[p,c]=o.useState([]),[g,f]=o.useState(0),[j,P]=o.useState(""),[w,S]=o.useState(!1),[y,n]=o.useState(!0),[u,_]=o.useState(!1),[i,v]=o.useState("");o.useEffect(()=>{const r=s.state||null,A=sn(t),G=(r==null?void 0:r.npsRating)||(A==null?void 0:A.npsRating);G&&Number(G)>=1&&(f(Number(G)),P(String((r==null?void 0:r.npsFeedback)||(A==null?void 0:A.npsFeedback)||"")),S(!0))},[t,s.state]),o.useEffect(()=>{let r=!1;const A=async()=>{try{const{data:E}=await z.getAppointments(),le=(Array.isArray(E)?E:[]).find(b=>b.hash===t);if(!r){x(le||null);const b=Number((le==null?void 0:le.rating)||0);b>=1&&(f(b),P(String((le==null?void 0:le.feedback)||"")),S(!0))}if(t){const{data:b}=await z.getAppointmentMedicalDocuments(t);r||c(b.data||[])}}catch{}finally{r||n(!1)}};A();const G=setInterval(A,15e3),$=setTimeout(()=>clearInterval(G),180*1e3);return()=>{r=!0,clearInterval(G),clearTimeout($)}},[t]);const B=async r=>{if(!t)return;const A=await ns(`${Gt}/medical-documents/${t}/${r}/pdf`);if(!A.ok){v("Não foi possível abrir o documento.");return}const G=await A.blob(),$=URL.createObjectURL(G);window.open($,"_blank"),setTimeout(()=>URL.revokeObjectURL($),6e4)},I=async()=>{var r,A;if(!(a!=null&&a.id)||g<1){v("Selecione uma nota de 1 a 5.");return}_(!0),v("");try{await z.rateAppointment(a.id,g,j),S(!0)}catch(G){v(((A=(r=G==null?void 0:G.response)==null?void 0:r.data)==null?void 0:A.message)||"Não foi possível enviar a avaliação.")}finally{_(!1)}};return e.jsxs("div",{className:"w-full max-w-3xl mx-auto space-y-6 px-4 sm:px-6 lg:px-8 py-4",children:[y&&e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(pe,{className:"animate-spin text-primary-600"})}),!y&&e.jsxs(e.Fragment,{children:[e.jsxs(Q,{className:"p-5 sm:p-8 rounded-2xl text-center space-y-3",children:[e.jsx(Ae,{className:"mx-auto text-secondary-500",size:48}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Consulta concluída"}),e.jsxs("p",{className:"text-sm text-slate-500",children:[a!=null&&a.specialty_name||a!=null&&a.is_emergency?"Pronto-atendimento":"Consulta",a!=null&&a.professional_name?` com ${a.professional_name}`:""]}),e.jsx(Nt,{to:"/patient/dashboard",className:"text-sm text-primary-600 font-semibold inline-block pt-2",children:"Voltar ao início"})]}),e.jsxs(Q,{className:"p-6 rounded-2xl space-y-3",children:[e.jsxs("h2",{className:"font-bold text-slate-900 flex items-center gap-2",children:[e.jsx(Us,{size:18})," Documentos da consulta"]}),p.length===0?e.jsx("p",{className:"text-sm text-slate-500",children:"Nenhum documento disponível ainda. Se o profissional emitir receita ou atestado, eles aparecerão aqui."}):e.jsx("ul",{className:"space-y-2",children:p.map(r=>e.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-xl border border-slate-100 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800",children:tn[r.document_type]||r.document_type}),e.jsx("p",{className:"text-xs text-slate-400",children:r.signed_at||r.created_at?new Date(r.signed_at||r.created_at).toLocaleString("pt-BR"):""})]}),e.jsxs(M,{size:"sm",variant:"outline",onClick:()=>B(r.hash),children:[e.jsx(os,{size:14,className:"mr-1"})," PDF"]})]},r.hash))}),e.jsx(M,{variant:"outline",className:"w-full",onClick:()=>l(t?`/patient/agenda/${t}?tab=documents`:"/patient/agenda"),children:"Ver histórico de documentos"})]}),e.jsxs(Q,{className:"p-6 rounded-2xl space-y-4",children:[e.jsx("h2",{className:"font-bold text-slate-900",children:"Como foi o atendimento?"}),w?e.jsxs("div",{className:"space-y-3 text-center",children:[e.jsx("div",{className:"flex justify-center gap-2","aria-label":`Avaliação: ${g} de 5 estrelas`,children:[1,2,3,4,5].map(r=>e.jsx(vs,{size:28,className:r<=g?"fill-amber-400 text-amber-400":"text-slate-300"},r))}),e.jsxs("p",{className:"text-sm text-secondary-600 font-semibold",children:["Obrigado pela sua avaliação",g>=1?` (${g} ${g===1?"estrela":"estrelas"})`:"","!"]}),j?e.jsxs("p",{className:"text-sm text-slate-500 italic",children:["“",j,"”"]}):null]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex justify-center gap-2",children:[1,2,3,4,5].map(r=>e.jsx("button",{type:"button",onClick:()=>f(r),className:"p-1","aria-label":`${r} estrelas`,children:e.jsx(vs,{size:28,className:r<=g?"fill-amber-400 text-amber-400":"text-slate-300"})},r))}),e.jsx("textarea",{className:"w-full rounded-xl border border-slate-200 px-3 py-2 text-sm",rows:3,placeholder:"Comentário (opcional)",value:j,onChange:r=>P(r.target.value)}),i&&e.jsx("p",{className:"text-sm text-red-600",children:i}),e.jsx(M,{className:"w-full",onClick:I,disabled:u||g<1,children:u?e.jsx(pe,{className:"animate-spin"}):"Enviar avaliação"})]})]})]})]})},Es=[{path:"dashboard",label:"Início",Icon:Pa},{path:"agenda",label:"Agenda",Icon:Ht},{path:"wellness",label:"Bem-estar",Icon:Ys},{path:"billing",label:"Conta",Icon:zt}],ln=()=>{const t=kt(),s=Me(),{logout:l,user:a}=Re(),{unreadTickets:x}=Wa(),p="",c=o.useMemo(()=>
6{const P=t.pathname.split("/").filter(Boolean)[1]||"dashboard";return["triage"].includes(P)?"dashboard":["emergency","book","post-consult"].includes(P)?"agenda":P},[t.pathname]),g=()=>{l(),s("/patient",{replace:!0})},f=[{label:"Central de Ajuda",icon:e.jsx(Ea,{size:16,className:"text-slate-500"}),action:()=>s("/patient/help"),badge:x}];return e.jsxs("div",{className:"h-[100dvh] min-h-screen bg-gray-50 flex overflow-hidden",children:[e.jsxs("aside",{className:"hidden md:flex w-24 lg:w-28 bg-white border-r border-gray-100 flex-col items-center py-6 sticky top-0 h-full z-40 shadow-[4px_0_24px_rgba(0,0,0,0.02)] flex-shrink-0",children:[e.jsx("div",{className:"mb-8",children:e.jsx("img",{src:`${p}/favicon.png`,alt:"Teledoc",className:"w-12 h-12"})}),e.jsx("nav",{className:"flex-1 space-y-4 w-full px-2",children:Es.map(({path:j,label:P,Icon:w})=>{const S=c===j;return e.jsx(Nt,{to:`/patient/${j}`,children:e.jsxs("div",{className:`flex flex-col items-center gap-1 p-3 rounded-xl transition-all ${S?"bg-primary-50 text-primary-600":"text-gray-400 hover:text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(w,{size:24}),e.jsx("span",{className:"text-[11px] font-medium text-center leading-tight",children:P})]})},j)})}),e.jsx("div",{className:"mt-auto",children:e.jsx("button",{type:"button",onClick:g,className:"p-3 text-red-400 hover:bg-red-50 rounded-xl transition-colors","aria-label":"Sair",children:e.jsx(Aa,{size:24})})})]}),e.jsxs("main",{className:"flex-1 overflow-y-auto overflow-x-hidden h-full bg-gray-50 flex flex-col min-w-0",children:[e.jsx(Ua,{userName:(a==null?void 0:a.name)||"Paciente",userAvatar:(a==null?void 0:a.avatar)||void 0,title:"Portal do Paciente",basePath:"/patient",showBackButton:!1,onLogout:g,customMenuItems:f,headerActions:e.jsx("div",{className:"hidden lg:flex",children:e.jsx(Ts,{size:"xs"})})}),e.jsx("div",{className:"flex-1 pb-[calc(5.5rem+env(safe-area-inset-bottom,0px))] md:pb-24",children:e.jsxs(Ms,{children:[e.jsx(Ne,{path:"dashboard",element:e.jsx(rl,{})}),e.jsx(Ne,{path:"triage",element:e.jsx(cl,{})}),e.jsx(Ne,{path:"emergency",element:e.jsx(Ql,{})}),e.jsx(Ne,{path:"book",element:e.jsx(Jl,{})}),e.jsx(Ne,{path:"plans",element:e.jsx(en,{})}),e.jsx(Ne,{path:"agenda",element:e.jsx(ul,{})}),e.jsx(Ne,{path:"agenda/:hash",element:e.jsx(hl,{})}),e.jsx(Ne,{path:"wellness",element:e.jsx(Gl,{})}),e.jsx(Ne,{path:"billing",element:e.jsx(Wl,{})}),e.jsx(Ne,{path:"profile",element:e.jsx(fl,{})}),e.jsx(Ne,{path:"post-consult/:hash",element:e.jsx(an,{})}),e.jsx(Ne,{path:"help",element:e.jsx("div",{className:"px-4 sm:px-6 lg:px-8 py-4",children:e.jsx(qa,{})})}),e.jsx(Ne,{path:"/",element:e.jsx(Is,{to:"dashboard",replace:!0})})]})})]}),e.jsx("nav",{className:"md:hidden fixed bottom-0 inset-x-0 z-50 bg-white/95 backdrop-blur-xl border-t border-slate-100 pt-1.5 px-1 shadow-[0_-8px_24px_rgba(0,0,0,0.06)] pb-[max(0.4rem,env(safe-area-inset-bottom))]","aria-label":"Navegação principal",children:e.jsx("div",{className:"grid grid-cols-4 max-w-lg mx-auto",children:Es.map(({path:j,label:P,Icon:w})=>{const S=c===j;return e.jsxs(Nt,{to:`/patient/${j}`,className:`flex flex-col items-center justify-center gap-0.5 py-2 min-h-[3.25rem] rounded-xl mx-0.5 transition-colors touch-manipulation ${S?"text-primary-600 bg-primary-50":"text-slate-400"}`,"aria-current":S?"page":void 0,children:[e.jsx(w,{size:22,strokeWidth:S?2.4:2}),e.jsx("span",{className:"text-[10px] font-semibold leading-none",children:P})]},j)})})})]})},nn=()=>{const{pathname:t}=kt(),s=t.includes("/call"),l=t.replace(/^\/patient\/?/,""),a=l===""||l.startsWith("signup")||l.startsWith("cadastro")||l.startsWith("reset-password");return e.jsx(ca,{enabled:!s,authenticated:!0,accessCategory:"Cliente (paciente)",liftForBottomNav:!a})},vn=()=>e.jsx(ra,{children:e.jsxs(e.Fragment,{children:[e.jsxs(Ms,{children:[e.jsx(Ne,{path:"/",element:e.jsx(Va,{onLogin:()=>{}})}),e.jsx(Ne,{path:"/signup",element:e.jsx(nl,{})}),e.jsx(Ne,{path:"/cadastro",element:e.jsx(Is,{to:"/patient/signup",replace:!0})}),e.jsx(Ne,{path:"/reset-password",element:e.jsx(Ka,{})}),e.jsx(Ne,{path:"/*",element:e.jsx(Oa,{children:e.jsx(ln,{})})})]}),e.jsx(nn,{})]})});export{vn as PatientApp};

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.