1import{k as Sa,r,j as e,i as da,d as Tr,u as Cr}from"./vendor_react-DkiuXrlk.js";import{a as S,B as Vt,l as hs}from"./index-C1ByJG38.js";import{E as Er}from"./vendor_pdf-D9UlI7qi.js";import{V as ve}from"./vendor_video-C4WhhxgJ.js";import{A as P,g as Y}from"./config-CuzF-lP3.js";import{E as ge,t as ka,m as ua,a2 as Rr,ay as Pr,a8 as $r,S as zr,ao as Mr,an as Bt,b9 as js,X as Ge,L as _a,u as Ut,_ as Lr,Y as Ar,e as Dr,D as Ir,l as Ta,bb as Or,bc as Ot,A as Ca,V as gs,av as bs,C as Mt,bd as Fr,x as ma,be as pa,bf as Vr,v as Lt,ah as fa,bg as Br,bh as xa,w as Ur,R as qr,a5 as ha,bi as Wr}from"./vendor_icons-CIE77zBt.js";import{T as Gr}from"./TermsOfUse-DRARJYkL.js";import{C as Jr}from"./Card-D1-SY2US.js";import{A as Hr,m as he}from"./vendor_motion-mPVRFuhH.js";import{f as Qr}from"./patientDemographics-DIy75QW6.js";const Ft={getProfile:()=>S.get("/professionals/me"),updateProfile:i=>S.put("/professionals/me/profile",i),uploadAvatar:i=>{const n=new FormData;return n.append("avatar",i),S.post("/professionals/me/avatar",n,{headers:{"Content-Type":"multipart/form-data"}})},changePassword:(i,n)=>S.put("/professionals/me/password",{oldPassword:i,newPassword:n}),getTelegramStatus:()=>S.get("/professionals/me/telegram"),unlinkTelegram:()=>S.delete("/professionals/me/telegram"),uploadDocument:(i,n,o,p)=>{const v=new FormData;return v.append("document",i),v.append("document_type",n),v.append("document_name",o),p&&v.append("specialty_id",p.toString()),S.post("/professionals/me/documents",v,{headers:{"Content-Type":"multipart/form-data"}})},getDocuments:()=>S.get("/professionals/me/documents"),downloadDocument:i=>S.get(`/professionals/me/documents/${i}/download`,{responseType:"blob"}),deleteDocument:i=>S.delete(`/professionals/me/documents/${i}`),getSpecialties:()=>S.get("/professionals/me/specialties"),getAllSpecialties:()=>S.get("/professionals/specialties/all"),addSpecialty:(i,n,o)=>S.post("/professionals/me/specialties",{specialty_id:i,years_experience:n,is_primary:o}),removeSpecialty:i=>S.delete(`/professionals/me/specialties/${i}`),getTemplates:()=>S.get("/professionals/me/templates"),createTemplate:i=>S.post("/professionals/me/templates",i),updateTemplate:(i,n)=>S.put(`/professionals/me/templates/${i}`,n),deleteTemplate:i=>S.delete(`/professionals/me/templates/${i}`),getTemplateItems:i=>S.get(`/professionals/me/templates/${i}/items`),createTemplateItem:(i,n)=>S.post(`/professionals/me/templates/${i}/items`,n),updateTemplateItem:(i,n,o)=>S.put(`/professionals/me/templates/${i}/items/${n}`,o),deleteTemplateItem:(i,n)=>S.delete(`/professionals/me/templates/${i}/items/${n}`),reorderTemplateItems:(i,n)=>S.put(`/professionals/me/templates/${i}/items/reorder`,{items:n}),getSchedule:()=>S.get("/professionals/me/schedule"),saveSchedule:i=>S.post("/professionals/me/schedule",i),getPatients:()=>S.get("/professionals/me/patients"),getPatientDetails:i=>S.get(`/professionals/me/patients/${i}`),getPatientWellness:i=>S.get(`/professionals/me/patients/${i}/wellness`),getAppointments:i=>S.get("/professionals/me/appointments",{params:i}),getAppointmentByHash:i=>S.get(`/professionals/me/appointments/${i}`),getAppointmentDocuments:i=>S.get(`/professionals/me/appointments/${i}/documents`),uploadAppointmentDocument:(i,n,o)=>{const p=new FormData;return p.append("file",n),o&&p.append("description",o),S.post(`/professionals/me/appointments/${i}/documents`,p,{headers:{"Content-Type":"multipart/form-data"}})},deleteAppointmentDocument:(i,n)=>S.delete(`/professionals/me/appointments/${i}/documents/${n}`),completeAppointment:(i,n)=>S.post(`/professionals/appointments/${i}/complete`,n),getDashboardStats:(i,n)=>S.get("/professionals/me/dashboard/stats",{params:{start_date:i,end_date:n}})},Kr="teledoc:mevo-prescription-updated",ys=i=>{typeof window>"u"||window.dispatchEvent(new CustomEvent(Kr,{detail:{appointmentHash:String(i||"").trim()}}))},Xr=i=>{const n=String(i||"").trim().toLowerCase();return["cancel"].includes(n)?"reopen":["excluded"].includes(n)?"close"
1:["prescricao","emission"].includes(n)?"sync":"ignore"},At={async start(i){return(await S.post(`/medical-documents/${i}/mevo/start`)).data.data},async reopen(i){return(await S.post(`/medical-documents/${i}/mevo/session`)).data.data},async getInfo(i){return(await S.get(`/medical-documents/${i}/mevo/info`)).data.data},async sendEvent(i,n){return(await S.post(`/medical-documents/${i}/mevo/events`,n)).data}},ga=({message:i,onRetry:n})=>{const{hash:o}=Sa(),[p,v]=r.useState(null),[c,M]=r.useState(!1),[_,T]=r.useState(!0);r.useEffect(()=>{const D=setTimeout(()=>T(!1),500);return()=>clearTimeout(D)},[]),r.useEffect(()=>{o?fetch(`${P}/consultations/${o}/info`).then(D=>D.json()).then(D=>{D.customerLogo?v(D.customerLogo.startsWith("http")?D.customerLogo:`${P}${D.customerLogo}`):v("/logo.png")}).catch(D=>{console.error("Error fetching info:",D),v("/logo.png")}):v("/logo.png")},[o]);const V=!c||_;return e.jsx("div",{className:"min-h-screen bg-slate-50 flex items-center justify-center p-4",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl max-w-md w-full p-8 border border-gray-100 text-center",children:[e.jsxs("div",{className:"flex justify-center mb-8",children:[V&&e.jsx("div",{className:"h-24 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}),p&&e.jsx("img",{src:p,alt:"Logo",className:`h-20 object-contain ${V?"hidden":""}`,onLoad:()=>M(!0),onError:D=>{M(!0),D.currentTarget.src="/logo.png"}})]}),e.jsx("div",{className:"flex justify-center mb-6",children:e.jsx("div",{className:"p-4 bg-red-50 rounded-full text-red-500",children:e.jsx(ge,{size:48})})}),e.jsx("h2",{className:"text-2xl font-bold text-slate-800 mb-4",children:"Não foi possÃvel conectar"}),e.jsx("p",{className:"text-slate-600 mb-8 leading-relaxed",children:i}),n&&e.jsxs("button",{onClick:n,className:"w-full py-4 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold text-lg transition-all shadow-lg shadow-blue-200 flex items-center justify-center gap-2",children:[e.jsx(ka,{size:20}),"Tentar novamente"]})]})})},Yr=({appointmentHash:i,transcript:n,className:o})=>{var C,j,W,O;const[p,v]=r.useState(null),[c,M]=r.useState(!1),[_,T]=r.useState(!1),[V,D]=r.useState("insights"),[Q,$]=r.useState([]),[L,g]=r.useState(""),[A,y]=r.useState(!1),b=async()=>{if(!n||n.length<10){alert("Aguarde o inÃcio da conversa...");return}M(!0),$([]);try{const k=await fetch(`${P}/copilot/analyze`,{method:"POST",headers:Y(),body:JSON.stringify({appointment_hash:i,transcript:n})});if(k.ok){const m=await k.json();v(m.data),D("insights")}else alert("Não foi possÃvel gerar insights.")}catch(k){console.error("Error:",k)}finally{M(!1)}},q=async()=>{if(!L.trim())return;const k={role:"user",content:L};$(m=>[...m,k]),g(""),y(!0);try{const m=await fetch(`${P}/copilot/chat`,{method:"POST",headers:Y(),body:JSON.stringify({appointment_hash:i,transcript:n,messages:[...Q,k]})});if(m.ok){const E=await m.json();E.success&&E.message&&$(F=>[...F,E.message])}}catch(m){console.error("Chat Error:",m)}finally{y(!1)}};return e.jsxs("div",{className:`flex flex-col h-full bg-white border-l border-gray-100 shadow-xl w-[450px] fixed right-0 top-0 bottom-0 z-50 transform transition-transform duration-300 ${_?"translate-x-0":"translate-x-full"} ${o}`,children:[e.jsx("button",{onClick:()=>T(!_),className:"absolute -left-12 top-[58%] -translate-y-1/2 bg-indigo-600 text-white p-3 rounded-l-xl shadow-lg hover:bg-indigo-700 transition-colors",children:e.jsx(ua,{size:24,className:c?"animate-spin":""})}),e.jsxs("div",{className:"bg-gradient-to-r from-indigo-50 to-purple-50 border-b border-gray-200 p-4 flex justify-between items-center shadow-sm z-10",children:[e.jsxs("h2",{className:"font-bold text-gray-800 flex items-center gap-2 text-lg",children:[e.jsx(ua,{className:"text-indigo-600",size:20}),"Copiloto clÃnico por IA"]}),e.jsx("button",{onClick:()=>T(!1),children:e.jsx(Rr,{size:20,className:"text-gray-400 hover:text-gray-600"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto bg-gray-50/50 p-4 space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(Vt,{onClick:b,isLoading:c,className:"w-full bg-indigo-600 hover:bg-indigo-700 text-white shadow-md mb-2 py-3 rounded-xl",icon:e.jsx(Pr,{size:16}),children:c?"Analisando...":p?"Atualizar Análise":"Gerar Análise Completa"}
1),!p&&!c&&Q.length===0&&e.jsx("div",{className:"p-6 text-gray-400 text-sm italic border border-dashed border-gray-200 rounded-xl mt-4",children:"Inicie a conversa para receber insights em tempo real e interagir com a IA."})]}),e.jsx(Hr,{children:p&&e.jsxs(he.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold text-gray-400 uppercase tracking-wider mb-2",children:[e.jsx("div",{className:"h-px bg-gray-200 flex-1"}),"Análise ClÃnica",e.jsx("div",{className:"h-px bg-gray-200 flex-1"})]}),((C=p.perguntas)==null?void 0:C.length)>0&&e.jsx(Dt,{title:"Sugestões",icon:e.jsx($r,{size:16,className:"text-blue-500"}),colorClass:"bg-blue-50 border-blue-100",children:e.jsx("ul",{className:"space-y-2",children:p.perguntas.map((k,m)=>e.jsxs("li",{className:"text-sm text-gray-700 flex gap-2 leading-relaxed",children:[e.jsx("span",{className:"text-blue-400 mt-1",children:"â¢"}),e.jsx("span",{children:k})]},m))})}),((j=p.hipoteses)==null?void 0:j.length)>0&&e.jsx(Dt,{title:"Hipóteses",icon:e.jsx(zr,{size:16,className:"text-yellow-600"}),colorClass:"bg-yellow-50 border-yellow-100",children:e.jsx("ul",{className:"space-y-2",children:p.hipoteses.map((k,m)=>e.jsxs("li",{className:"text-sm font-medium text-gray-700 flex gap-2 leading-relaxed",children:[e.jsx("span",{className:"text-yellow-500 mt-1",children:"â¢"}),e.jsx("span",{children:k})]},m))})}),((W=p.propedeutica)==null?void 0:W.length)>0&&e.jsx(Dt,{title:"Propedêutica",icon:e.jsx(Mr,{size:16,className:"text-purple-500"}),colorClass:"bg-purple-50 border-purple-100",children:e.jsx("ul",{className:"space-y-2",children:p.propedeutica.map((k,m)=>e.jsxs("li",{className:"text-sm text-gray-700 flex gap-2 leading-relaxed",children:[e.jsx("span",{className:"text-purple-400 mt-1",children:"â¢"}),e.jsx("span",{children:k})]},m))})}),((O=p.terapeutica)==null?void 0:O.length)>0&&e.jsx(Dt,{title:"Conduta",icon:e.jsx(Bt,{size:16,className:"text-green-500"}),colorClass:"bg-green-50 border-green-100",children:e.jsx("ul",{className:"space-y-2",children:p.terapeutica.map((k,m)=>e.jsxs("li",{className:"text-sm text-gray-700 flex gap-2 leading-relaxed",children:[e.jsx("span",{className:"text-green-400 mt-1",children:"â¢"}),e.jsx("span",{children:k})]},m))})})]})}),(p||Q.length>0)&&e.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold text-gray-400 uppercase tracking-wider py-2",children:[e.jsx("div",{className:"h-px bg-gray-200 flex-1"}),"Converse sobre a análise",e.jsx("div",{className:"h-px bg-gray-200 flex-1"})]}),e.jsxs("div",{className:"space-y-4 pb-2",children:[Q.map((k,m)=>e.jsx("div",{className:`flex ${k.role==="user"?"justify-end":"justify-start"}`,children:e.jsx("div",{className:`max-w-[90%] p-4 rounded-2xl text-sm leading-relaxed ${k.role==="user"?"bg-indigo-600 text-white rounded-tr-none":"bg-white border border-gray-200 text-gray-700 rounded-tl-none shadow-sm"}`,children:k.role==="user"?k.content:e.jsx(Zr,{content:k.content})})},m)),A&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white border border-gray-100 p-4 rounded-2xl rounded-tl-none shadow-sm",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"w-2 h-2 bg-gray-400 rounded-full animate-bounce"}),e.jsx("div",{className:"w-2 h-2 bg-gray-400 rounded-full animate-bounce delay-75"}),e.jsx("div",{className:"w-2 h-2 bg-gray-400 rounded-full animate-bounce delay-150"})]})})})]})]}),e.jsxs("div",{className:"p-4 bg-white border-t border-gray-100 z-10",children:[e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx("textarea",{value:L,onChange:k=>g(k.target.value),onKeyDown:k=>{k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),q())},placeholder:"Pergunte sobre o caso...",className:"flex-1 bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none min-h-[50px] max-h-32",rows:1}),e.jsx("button",{onClick:q,disabled:!L.trim()||A,className:"p-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 disabled:opacity-50 transition-colors mb-0.5",children:e.jsx(js,{size:18})})]}),e.jsx("div",{className:"mt-2 text-center",children:e.jsx("p",{className:"text-[10px] text-gray-400 uppercase tracking-wide",children:"AI Assistente - Validar clinicamente"})})]})]})},Zr=({content:i})=>e.jsx("div",{className:"space-y-1",children:i.split(` 2`).map((n,o)=>{const p=n.trim();if(p.startsWith("- ")||p.startsWith("* ")){const v=p.substring(2);return e.jsxs("div",{className:"flex gap-2 ml-1",children:[e.jsx("span",{className:"opacity-60 mt-1.5 min-w-[4px] h-[4px] rounded-full bg-current block"}),e.jsx("span",{className:"flex-1",children:vs(v)})]},o)}if(/^\d+\.\s/.test(p)){const v=p.indexOf("."),c=p.substring(0,v+1),M=p.substring(v+1);return e.jsxs("div",{className:"flex gap-1 ml-1",children:[e.jsx("span",{className:"font-bold opacity-80 min-w-[1.2em]",children:c}),e.jsx("span",{className:"flex-1",children:vs(M)})]},o)}return p?e.jsx("div",{children:vs(n)},o):e.jsx("div",{className:"h-2"},o)})}),vs=i=>{const n=i.split(/(\*\*.*?\*\*)/g);return e.jsx(e.Fragment,{children:n.map((o,p)=>o.startsWith("**")&&o.endsWith("**")?e.jsx("strong",{className:"font-bold",children:o.slice(2,-2)},p):e.jsx("span",{children:o},p))})},Dt=({title:i,icon:n,colorClass:o,children:p})=>e.jsxs(Jr,{className:`border ${o} shadow-sm overflow-hidden`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 pb-2 border-b border-gray-200/50",children:[n,e.jsx("h3",{className:"font-bold text-gray-800 text-sm",children:i})]}),p]}),en=({open:i,appointmentHash:n,onClose:o})=>{const[p,v]=r.useState(!1),[c,M]=r.useState(""),[_,T]=r.useState(null),V=(_==null?void 0:_.modalUrl)||(_==null?void 0:_.ModalURL)||(_==null?void 0:_.prescription_url)||"",D=!!V,Q=r.useMemo(()=>{const A="".split(",").map(b=>
2b.trim()).filter(Boolean),y=(()=>{try{return V?new URL(V).origin:""}catch{return""}})();return Array.from(new Set([...A,y,"https://emr-homolog.nexodata.com.br","https://emr.nexodata.com.br","https://nexodata.com.br"].filter(Boolean)))},[V]),$=r.useCallback(async()=>{var A,y;if(!n){M("Hash da consulta indisponÃvel para abrir o receituário.");return}v(!0),M("");try{const b=await At.start(n);T(b)}catch(b){const q=((y=(A=b==null?void 0:b.response)==null?void 0:A.data)==null?void 0:y.message)||(b==null?void 0:b.message)||"Falha ao iniciar o receituário Mevo.";M(q)}finally{v(!1)}},[n]);r.useCallback(async()=>{var A,y;if(n){v(!0),M("");try{await $()}catch(b){M(((y=(A=b==null?void 0:b.response)==null?void 0:A.data)==null?void 0:y.message)||(b==null?void 0:b.message)||"Não foi possÃvel atualizar a prescrição.")}finally{v(!1)}}},[n,$]);const L=r.useCallback(async()=>{var A,y,b,q,C;if(n){v(!0),M("");try{const j=await At.getInfo(n),W=((A=j==null?void 0:j.mevo)==null?void 0:A.prescription_url)||((y=j==null?void 0:j.mevo)==null?void 0:y.modalUrl)||((b=j==null?void 0:j.mevo)==null?void 0:b.ModalURL)||"";j!=null&&j.mevo&&T(O=>O&&{...O,idPrescricao:j.mevo.idPrescricao||O.idPrescricao,mevoPrescriptionId:j.mevo.idPrescricao||O.mevoPrescriptionId,modalUrl:W||O.modalUrl,ModalURL:W||O.ModalURL,prescription_url:W||O.prescription_url,QRCodeURL:j.mevo.QRCodeURL??O.QRCodeURL??null,CodigoValidacao:j.mevo.CodigoValidacao??O.CodigoValidacao??null}),ys(n)}catch(j){M(((C=(q=j==null?void 0:j.response)==null?void 0:q.data)==null?void 0:C.message)||(j==null?void 0:j.message)||"Não foi possÃvel atualizar a prescrição.")}finally{v(!1)}}},[n]),g=r.useCallback(async()=>{var A,y;if(n){v(!0),M("");try{const b=await At.reopen(n);T(b),ys(n)}catch(b){M(((y=(A=b==null?void 0:b.response)==null?void 0:A.data)==null?void 0:y.message)||(b==null?void 0:b.message)||"Não foi possÃvel reabrir a prescrição.")}finally{v(!1)}}},[n]);return r.useEffect(()=>{if(!i){T(null),M(""),v(!1);return}$()},[i,$]),r.useEffect(()=>{if(!i||!n)return;const A=async y=>{if(!Q.includes(y.origin))return;
2const b=typeof y.data=="string"?(()=>{try{return JSON.parse(y.data)}catch{return{type:y.data}}})():y.data;if(!b||typeof b!="object")return;const q=String(b.type||b.eventType||b.event||"").trim().toLowerCase(),C=Xr(q);if(C!=="ignore")try{if(await At.sendEvent(n,{type:q,idPrescricao:(_==null?void 0:_.idPrescricao)||void 0,payload:b}),C==="reopen"){await g();return}if(C==="close"){ys(n),o();return}C==="sync"&&await L()}catch(j){console.error("Mevo postMessage relay failed:",j)}};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[Q,n,i,g,_==null?void 0:_.idPrescricao,L,o]),i?e.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-[80] flex items-center justify-center p-0 sm:p-4",children:e.jsxs(he.div,{initial:{opacity:0,scale:.96},animate:{opacity:1,scale:1},className:"w-full h-full sm:h-[94vh] sm:w-[min(96vw,1360px)] bg-white rounded-none sm:rounded-2xl shadow-2xl overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 px-4 py-4 sm:px-6 border-b border-slate-200",children:[e.jsxs("h3",{className:"text-xl font-black text-slate-900 flex items-center gap-2",children:[e.jsx(Bt,{size:22,className:"text-blue-600"}),"Receituário Mevo"]}),e.jsx("button",{onClick:o,className:"text-slate-400 hover:text-slate-600",children:e.jsx(Ge,{size:24})})]}),c&&e.jsxs("div",{className:"mx-4 sm:mx-6 mt-4 p-4 rounded-xl border border-red-200 bg-red-50 text-red-700 flex items-start gap-3",children:[e.jsx(ge,{size:18,className:"mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-bold",children:"Não foi possÃvel iniciar o receituário."}),e.jsx("p",{className:"mt-1",children:c})]})]}),e.jsx("div",{className:"flex-1 min-h-0 bg-slate-100",children:p&&!D?e.jsx("div",{className:"h-full flex items-center justify-center text-slate-500",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx(_a,{size:28,className:"animate-spin text-blue-600"}),e.jsx("span",{className:"text-sm font-medium",children:"Preparando o prescritor da Mevo..."})]})}):V?e.jsx("iframe",{title:"Mevo Prescritor",src:V,className:"h-full w-full min-h-0 border-0",referrerPolicy:"strict-origin-when-cross-origin",allow:"clipboard-write; fullscreen"}):e.jsx("div",{className:"h-full flex items-center justify-center p-6 text-center text-slate-500",children:e.jsxs("div",{className:"max-w-sm",children:[e.jsx(Bt,{size:32,className:"mx-auto mb-3 text-slate-400"}),e.jsx("p",{className:"font-semibold text-slate-700",children:"Aguardando uma URL válida da Mevo."}),e.jsx("p",{className:"text-sm mt-2",children:"Se a sessão não abrir automaticamente, tente atualizar ou abrir em nova aba."})]})})})]})}):null};function We(i){if(!i)return[];if(Array.isArray(i))return i.map(String).map(n=>n.trim()).filter(Boolean);if(typeof i=="string"){try{if(i.trim().startsWith("[")){const n=JSON.parse(i);if(Array.isArray(n))return n.map(String).map(o=>o.trim()).filter(Boolean)}}catch{}return i.split(",").map(n=>n.trim()).filter(Boolean)}return[]}function ba(i){if(!i)return"--";const n=String(i).replace(/\D/g,"");return n.length===11?`(${n.slice(0,2)}) ${n.slice(2,7)}-${n.slice(7)}`:n.length===10?`(${n.slice(0,2)}) ${n.slice(2,6)}-${n.slice(6)}`:i}function tn(i){if(!i)return"--";const n=new Date(String(i).includes("T")?i:`${i}T00:00:00`);return Number.isNaN(n.getTime())?"--":n.toLocaleDateString("pt-BR")}function ya(i){return i==null||Number.isNaN(Number(i))?"#64748b":i>=70?"#22c55e":i>=50?"#f59e0b":"#ef4444"}function It({title:i,icon:n,children:o,tone:p="slate"}){const v={slate:"border-slate-200 bg-white",red:"border-red-100 bg-red-50/70",teal:"border-teal-100 bg-teal-50/60"},c={slate:"text-slate-600",red:"text-red-700",teal:"text-teal-700"};return e.jsxs("section",{className:`rounded-xl border p-3 space-y-2.5 ${v[p]}`,children:[e.jsxs("h4",{className:`text-[11px] font-bold uppercase tracking-wide flex items-center gap-1.5 ${c[p]}`,children:[n,i]}),o]})}function va({children:i,danger:n}){return e.jsx("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-semibold border ${n?"bg-red-100 text-red-700 border-red-200":"bg-white text-slate-700 border-slate-200"}`,children:i})}function me({label:i,value:n}){return e.jsxs("div",{className:"rounded-lg bg-white/80 border border-black/5 px-2.5 py-2 text-center",children:[e.jsx("p",{className:"text-[10px] uppercase font-bold text-slate-400 mb-0.5",children:i}),e.jsx("p",{className:"text-sm font-bold text-slate-800 truncate",children:n??"--"})]})}const sn=({appointment:i})=>{var q;const n=i==null?void 0:i.patient,[o,p]=r.useState(null),[v,c]=r.useState(!1),[M,_]=r.useState(!1);if(r.useEffect(()=>{const C=n==null?void 0:n.hash;if(!C){p(null);return}let j=!1;return c(!0),_(!1),Ft.getPatientWellness(C).then(W=>{j||p(W.data)}).catch(()=>{j||(p(null),_(!0))}).finally(()=>{j||c(!1)}),()=>{j=!0}},[n==null?void 0:n.hash]),!n)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-sm text-slate-500",children:"Carregando dados do pacienteâ¦"});const T=n.health_profile||{},V=[...new Set([...We(n.allergies),...We(T.allergies)])],D=[...new Set([...We(n.medical_conditions),...We(T.health_conditions)])],Q=[...new Set([...We(n.medications),...We(T.medications)])],$=T.blood_type||n.blood_type,L=T.height_cm??n.height,g=T.weight_kg??n.weight,A=n.age,y=(q=o==null?void 0:o.healthScore)==null?void 0:q.score,b=o==null?void 0:o.bmi;return e.jsxs("div",{className:"space-y-3 flex-1",children:[e.jsx("div",{className:"rounded-xl border border-slate-200 bg-white p-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary-50 text-primary-600 flex items-center justify-center shrink-0",children:e.jsx(Ut,{size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-bold text-slate-900 truncate",children:n.name||"Paciente"}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[A!=null?`${A} anos`:"Idade --"," · ",Qr(n.gender,"Sexo --"),$?` · ${$}`:""]})]})]})}),e.jsx(It,{title:"Cadastro",icon:e.jsx(Ut,{size:12}),children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs text-slate-700",children:[e.jsxs("p",{children:["Nascimento: ",e.jsx("strong",{children:tn(n.birth_date)})]}),e.jsxs("p",{children:["Documento: ",e.jsx("strong",{children:n.document_number||"--"})]}),e.jsxs("p",{className:"col-span-2",children:["Telefone: ",e.jsx("strong",{children:ba(n.phone)})]}),n.email&&e.jsxs("p",{className:"col-span-2 truncate",children:["E-mail: ",e.jsx("strong",{children:n.email})]}),(n.emergency_contact_name||n.emergency_contact_phone)&&e.jsxs("p",{className:"col-span-2",children:["Emergência:"," ",e.jsx("strong",{children:[n.emergency_contact_name,ba(n.emergency_contact_phone)].filter(
2Boolean).join(" · ")})]})]})}),e.jsxs(It,{title:"Saúde",icon:e.jsx(Lr,{size:12}),tone:"red",children:[V.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-bold text-red-600 mb-1.5",children:"Alergias"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:V.map(C=>e.jsxs(va,{danger:!0,children:[e.jsx(ge,{size:12}),C]},C))})]}):e.jsx("p",{className:"text-xs text-slate-500",children:"Nenhuma alergia registrada."}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[$&&e.jsx(me,{label:"Sangue",value:$}),L!=null&&L!==""&&e.jsx(me,{label:"Altura",value:`${L} cm`}),g!=null&&g!==""&&e.jsx(me,{label:"Peso",value:`${g} kg`}),T.activity_level&&e.jsx(me,{label:"Atividade",value:T.activity_level}),T.smoking_habit&&e.jsx(me,{label:"Fumo",value:T.smoking_habit}),T.alcohol_consumption&&e.jsx(me,{label:"Ãlcool",value:T.alcohol_consumption}),T.sleep_quality&&e.jsx(me,{label:"Sono",value:T.sleep_quality})]}),D.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-bold text-slate-500 mb-1.5",children:"Condições"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:D.map(C=>e.jsx(va,{children:C},C))})]}),Q.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-bold text-slate-500 mb-1.5",children:"Medicamentos"}),e.jsx("ul",{className:"space-y-1",children:Q.map(C=>e.jsxs("li",{className:"flex items-center gap-2 text-xs text-slate-700",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-500 shrink-0"}),C]},C))})]}),T.health_description&&e.jsx("p",{className:"text-xs text-slate-600 bg-white/80 rounded-lg p-2 border border-red-50 leading-relaxed",children:T.health_description})]}),e.jsx(It,{title:"Bem-estar",icon:e.jsx(Ta,{size:12}),tone:"teal",children:v?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-500 py-2",children:[e.jsx(_a,{size:14,className:"animate-spin"}),"Carregando indicadoresâ¦"]}):M||!n.hash?e.jsx("p",{className:"text-xs text-slate-500",children:"Indicadores de bem-estar indisponÃveis."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-14 h-14 rounded-full border-4 flex items-center justify-center shrink-0 bg-white",style:{borderColor:ya(y)},children:e.jsx("span",{className:"text-lg font-bold",style:{color:ya(y)},children:y??"--"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold text-slate-700",children:"Score de saúde"}),e.jsx("p",{className:"text-[11px] text-slate-500 leading-snug",children:"Baseado em água, sono, peso, atividade e álcool."})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(me,{label:"IMC",value:e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",children:[e.jsx(Ar,{size:12,className:"text-slate-400"}),b||"--"]})}),e.jsx(me,{label:"Sono méd.",value:e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",children:[e.jsx(Dr,{size:12,className:"text-slate-400"}),(o==null?void 0:o.averageSleep)!=null?`${o.averageSleep}h`:"--"]})}),e.jsx(me,{label:"Ãgua hoje",value:e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",children:[e.jsx(Ir,{size:12,className:"text-slate-400"}),(o==null?void 0:o.waterToday)!=null?`${o.waterToday} ml`:"--"]})}),e.jsx(me,{label:"Ativ. sem.",value:(o==null?void 0:o.weeklyActivityMinutes)!=null?`${o.weeklyActivityMinutes} min`:"--"})]})]})}),(i==null?void 0:i.observations)&&e.jsx(It,{title:"Observações do agendamento",icon:e.jsx(ge,{size:12}),children:e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed bg-amber-50/80 border border-amber-100 rounded-lg p-2",children:i.observations})})]})},an=({appointmentHash:i,onComplete:n})=>{const[o,p]=r.useState([{id:"1",role:"model",text:"Olá! Vamos fazer uma avaliação inicial dos seus sintomas. Qual o principal motivo da sua consulta hoje?",timestamp:new Date}]),[v,c]=r.useState(""),[M,_]=r.useState(!1),[T,V]=r.useState(!1),[D,Q]=r.useState(""),$=r.useRef(null),L=r.useRef(null),g=r.useRef(!1),[A,y]=r.useState(null),[b,q]=r.useState(!1);da.useEffect(()=>{const m=async()=>{try{const F=await fetch(`${P}/consultations/${i}/info`);if(F.ok){const H=await F.json();H.customerLogo&&y(H.customerLogo.startsWith("http")?H.customerLogo:`${P}${H.customerLogo}`)}}catch(F){console.error("Error fetching info:",F)}finally{q(!0)}},E=async()=>{try{await fetch(`${P}/consultations/${i}/screening/start`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch(F){console.error("Error marking screening as started:",F)}};return m(),E(),()=>{if(g.current=!0,$.current&&$.current.state==="recording")try{$.current.stop()}catch(F){console.error("Error stopping screening recorder on unmount:",F)}
2L.current&&(L.current.getTracks().forEach(F=>F.stop()),L.current=null),$.current=null,V(!1)}},[i]);const C=async()=>{if(!v.trim())return;const m={id:Date.now().toString(),role:"user",text:v,timestamp:new Date};p(E=>[...E,m]),c(""),_(!0);try{const E=o.map(u=>({role:u.role==="model"?"assistant":"user",text:u.text}));E.push({role:"user",text:m.text});const H=await(await fetch(`${P}/consultations/${i}/screening/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:E})})).json();if(H.success){const u={id:(Date.now()+1).toString(),role:"model",text:H.response,timestamp:new Date};p(ee=>[...ee,u])}}catch(E){console.error("Screening error:",E)}finally{_(!1)}},j=async()=>{try{const m=await navigator.mediaDevices.getUserMedia({audio:!0}),E=new MediaRecorder(m);$.current=E,L.current=m,g.current=!1;const F=[];E.ondataavailable=H=>F.push(H.data),E.onstop=async()=>{if(g.current){L.current&&(L.current.getTracks().forEach(ee=>ee.stop()),L.current=null),$.current=null;return}const H=new Blob(F,{type:"audio/webm"}),u=new FormData;u.append("audio",H,"recording.webm"),_(!0);try{const Re=await(await fetch(`${P}/consultations/${i}/screening/transcribe`,{method:"POST",body:u})).json();Re.success&&c(Ie=>(Ie?Ie+" ":"")+Re.transcription)}catch(ee){console.error("Transcription error:",ee)}finally{_(!1)}L.current&&(L.current.getTracks().forEach(ee=>ee.stop()),L.current=null),$.current=null},E.start(),V(!0)}catch(m){console.error("Mic error:",m),Q("Não foi possÃvel acessar o microfone. Verifique as permissões do navegador.")}},W=()=>{$.current&&T&&(g.current=!1,$.current.stop(),V(!1))},O=async()=>{_(!0);try{g.current=!0;const m=o.map(E=>({role:E.role==="model"?"assistant":"user",text:E.text}));await fetch(`${P}/consultations/${i}/screening/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conversation_history:m})}),$.current&&T?$.current.stop():L.current&&(L.current.getTracks().forEach(E=>E.stop()),L.current=null),n()}catch(m){console.error("Completion error:",m),Q("Não foi possÃvel finalizar a avaliação. Tente novamente.")}finally{_(!1)}},k=r.useRef(null);return da.useEffect(()=>{var m;(m=k.current)==null||m.scrollIntoView({behavior:"smooth"})},[o]),e.jsx("div",{className:"fixed inset-0 z-[60] bg-white flex flex-col",children:e.jsxs("div",{className:"flex-1 max-w-2xl mx-auto w-full p-4 flex flex-col h-full",children:[" ",e.jsxs("div",{className:"text-center mb-4 mt-2 flex-shrink-0",children:[" ",e.jsx("div",{className:"flex justify-center mb-2",children:A?e.jsx("img",{src:A,alt:"Logo",className:"h-12 object-contain",onError:m=>{m.currentTarget.src="/logo.png",m.currentTarget.className="h-10 object-contain"}}):e.jsx("img",{src:"/logo.png",alt:"Teledoc",className:"h-10 object-contain"})}),e.jsx("h2",{className:"text-xl font-bold text-primary-900",children:"Avaliação inicial de sintomas"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Responda para agilizar seu atendimento e para que o profissional tenha informações mais assertivas sobre o seu caso."}),D&&e.jsx("p",{className:"text-sm text-red-600 mt-2",children:D})]}),e.jsxs("div",{className:"flex-1 bg-gray-50 p-4 rounded-2xl overflow-y-auto mb-4 border border-gray-100 shadow-inner min-h-0",children:[o.map(m=>e.jsx("div",{className:`mb-4 flex ${m.role==="user"?"justify-end":"justify-start"}`,children:e.jsx("div",{className:`max-w-[85%] px-4 py-2 rounded-2xl text-sm shadow-sm ${m.role==="user"?"bg-primary-600 text-white rounded-br-none":"bg-white text-gray-700 border border-gray-200 rounded-bl-none"}`,children:m.text})},m.id)),M&&e.jsx("div",{className:"flex justify-start mb-4",children:e.jsxs("div",{className:"bg-white px-4 py-2 rounded-2xl text-sm border border-gray-200 shadow-sm flex items-center gap-2",children:[e.jsx("div",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce"}),e.jsx("div",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce delay-100"}),e.jsx("div",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce delay-200"})]})}),e.jsx("div",{ref:k})]}),e.jsxs("div",{className:"relative mb-2 flex-shrink-0",children:[" ",e.jsx("textarea",{value:v,onCh
2ange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),C())},placeholder:"Digite sua resposta...",className:"w-full p-3 pr-24 rounded-2xl border-2 border-gray-200 focus:border-primary-500 focus:ring-0 outline-none text-base resize-none bg-white shadow-sm transition-colors",rows:2}),e.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-2",children:[e.jsx("button",{onClick:T?W:j,className:`p-2 rounded-full transition-all ${T?"bg-red-50 text-red-500 hover:bg-red-100 animate-pulse":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,title:"Gravar áudio",children:T?e.jsx(Or,{size:18}):e.jsx(Ot,{size:18})}),e.jsx("button",{onClick:C,disabled:!v.trim()||M,className:"p-2 bg-primary-600 text-white rounded-full hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",title:"Enviar",children:e.jsx(js,{size:18})})]})]}),e.jsxs("div",{className:"flex justify-between items-center pt-2 border-t border-gray-100 flex-shrink-0",children:[e.jsx("p",{className:"text-[10px] text-gray-400",children:"Suas respostas serão enviadas para o médico."}),e.jsxs(Vt,{onClick:O,disabled:M||o.length<3,size:"sm",className:"rounded-full px-6 text-xs",children:["Finalizar ",e.jsx(Ca,{size:14,className:"ml-1"})]})]})]})})},ja=({hasRoom:i=!1,hasRemoteParticipant:n=!1,isLocalMediaReady:o=!1,showScreening:p=!1,showNPSModal:v=!1,npsSubmitted:c=!1,isConsultationCompleted:M=!1}={})=>p||v||c||M?!1:!i&&!n&&o,rn=({mode:i,status:n,showNPSModal:o=!1,npsSubmitted:p=!1}={})=>i==="patient"&&n==="completed"&&!o&&!p,wa=async(i,n)=>{if(!i||!n)return!1;if(n.muted=!0,i.mediaStreamTrack&&typeof MediaStream<"u")n.srcObject=new MediaStream([i.mediaStreamTrack]);else if(typeof i.attach=="function")i.attach(n);else return!1;if(typeof n.play=="function")try{await n.play()}catch{}return!0},Na=(i,n=null)=>{for(const o of i||[])o!==n&&typeof(o==null?void 0:o.remove)=="function"&&o.remove()};function nn(){try{if(!localStorage.getItem("auth_token"))return!1;const n=localStorage.getItem("user");if(!n||n==="undefined")return!1;const o=JSON.parse(n),p=String((o==null?void 0:o.role)||"").toUpperCase(),v=String((o==null?void 0:o.user_type)||"").toLowerCase();return p==="PATIENT"||v==="patient"}catch{return!1}}function on(i){return/soap/i.test(String((i==null?void 0:i.title)||""))}function ln(i=[]){var o;const n=i.find(on);return(n==null?void 0:n.id)??((o=i[0])==null?void 0:o.id)??""}const cn=4e3,dn=15,un=({patientName:i,onEndCall:n,mode:o="doctor"})=>{var zt,ia;const{hash:p,id:v}=Sa(),c=p||v,M=c?`twilioRoomName:${c}`:null,_=Tr(),T=Cr(),V=r.useCallback(t=>{var l;const s=(l=T.state)==null?void 0:l.postConsultPath,a=t!=null&&t.npsRating&&t.npsRating>=1?{npsRating:t.npsRating,npsFeedback:t.npsFeedback||""}:void 0;if(s){_(s,{replace:!0,state:a});return}if(o==="patient"&&nn()&&c){_(`/patient/post-consult/${c}`,{replace:!0,state:a});return}if(o==="patient"&&typeof n=="function"){const d=window.location.pathname||"";if(d.includes("/call/patient/")||d.match(/\/call\/[^/]+$/)){if(a&&c)try{sessionStorage.setItem(`teledoc_nps_${c}`,JSON.stringify(a))}catch{}n();return}}if(c){_(`/patient-access/exit/${c}`,{replace:!0});return}n()},[c,T.state,o,_,n]),[D,Q]=r.useState(()=>{if(o==="doctor")return!0;const t=p||v;return!!(t&&localStorage.getItem(`terms_accepted_for_${t}`)==="true")}),[$,L]=r.useState(null),[g,A]=r.useState(null),y=r.useRef(null),b=r.useRef(!1),q=r.useRef(!1),C=r.useRef(null),j=r.useRef([]),W=r.useRef(null),O=r.useRef(null),k=r.useRef([]),m=r.useRef(null),E=r.useRef(!1),[F,H]=r.useState(null),[u,ee]=r.useState(null),Re=r.useRef(null),[Ie,qt]=r.useState(!1),[be,lt]=r.useState({doctor_present:!1,patient_present:!1,both_present:!1,waiting_for_role:null,waiting_message:null,current_role_state:null}),[ct,ae]=r.useState(null),[dt,re]=r.useState(null),[Wt,Gt]=r.useState(!1),[Jt,Ea]=r.useState(!0),[Je,Ra]=r.useState(""),Pa=o==="doctor"?"doctor":"patient",ws=r.useRef(((ia=(zt=globalThis.crypto)==null?void 0:zt.randomUUID)==null?void 0:ia.call(zt))||`video-${Date.now()}-${Math.random().toString(36).slice(2)}`),je=r.useRef(null),we=r.useRef(null),He=r.useRef(0),[ut,Ht]=r.useState(!1),[$a,Qt]=r.useState(0),mt=r.useRef(0),K=r.useRef(null),Ns=r.useRef(async()=>{}),Oe=r.useRef(!1),Qe=r.useRef(null),B=r.useRef({audio:null,video:null}),Ke=r.useRef(!1),pt=r.useRef(0),[Pe,ft]=r.useState(!1),[$e,xt]=r.useState(!1);r.useEffect(()=>{y.current=g},[g]),r.useEffect(()=>{Re.current=u},[u]);const[ze,Ss]=r.useState(!1),[J,ht]=r.useState(null),[Kt,ks]=r.useState(o==="patient"),_s=r.useRef(!1),[Ts,ye]=r.useState(null),[Cs,Es]=r.useState("");r.useEffect(()=>{o==="doctor"&&(Ft.getProfile().then(t=>Ra(t.data.name)).catch(t=>console.error("Error fetching profile:",t)),c&&Ft.getAppointmentByHash(c).then(t=>{var s,a,l,d,x;(a=(s=t.data)==null?void 0:s.data)!=null&&a.screening&&(ht({summary:t.data.data.screening.summary,risk_level:t.data.data.screening.risk_level}),ye("completed")),(x=(d=(l=t.data)==null?void 0:l.data)==null?void 0:d.patient)!=null&&x.name&&Es(t.data.data.patient.name)}).catch(t=>console.error("Non-critical: Failed to load screening info",t)))},[o,c]),r.useEffect(()=>{o==="doctor"&&c&&(async()=>{try{const s=await fetch(`${P}/consultations/${c}/screening/status`);if(s.ok){const a=await s.json();Es(a.patient_name||""),a.screening_status==="completed"?(ye("completed"),a.screening_summary&&(!J||J.summary!==a.screening_summary)&&(ht({summary:a.screening_summary,risk_level:a.screening_risk_level}),Be.current!=="triage"&&ss(!0))):a.screening_status==="in_progress"?ye("in_progress"):ye("not_started")}}catch(s){console.error("Error polling screening status:",s)}})()},[o,c]),r.useEffect(()=>{const t=setTimeout(()=>Ea(!1),500);return()=>clearTimeout(t)},[]);const[za,gt]=r.useState(!1),[ne,Rs]=r.useState(!1),[Xt,Ps]=r.useState(!1),[Yt,$s]=r.useState(!1),[Ne,Fe]=r.useState(!1),[te,zs]=r.useState(!0),[se,bt]=r.useState(!0),[mn,pn]=r.useState(0),[Se,Ms]=r.useState(""),[Zt,Ls]=r.useState(!1),[Ma,Me]=r.useState(!1),[pe,Xe]=r.useState(!1),[Ye,La]=r.useState(0),[es,Aa]=r.useState(""),[fe,Da]=r.useState(!1),[Le,Ve]=r.useState(!1),[Ia,oe]=r.useState("form"),[xe,Oa]=r.useState([]),[ie,Ze]=r.useState(""),[yt,As]=r.useState(!1),[Fa,Va]=r.useState(!1),le=r.useRef(!1),ce=r.useRef(null),vt=r.useRef(0),[jt,wt]=r.useState(null),[ke,Ds]=r.useState(!1),[fn,Is]=r.useState(!1),[Os,Ba]=r.useState(null),[Ua,Fs]=r.useState(!1),[qa,ts]=r.useState(!1),[Wa,Ga]=r.useState([]),[Ja,Ha]=r.useState([]),[Vs,Qa]=r.useState([]),[_e,Bs]=r.useState(""),[Te,Us]=r.useState(""),[Ka,Xa]=r.useState("");r.useEffect(()=>{const t=async()=>{try{const s=await navigator.mediaDevices.enumerateDevices();Ga(s.filter(d=>d.kind==="audioinput")),Ha(s.filter(d=>d.kind==="videoinput")),Qa(s.filter(d=>d.kind==="audiooutput"));const a=s.find(d=>d.kind==="audioinput"),l=s.find(d=>d.kind==="videoinput");a&&!_e&&Bs(a.deviceId),l&&!Te&&Us(l.deviceId)}catch(s){console.error("Error fetching devices:",s)}};return t(),navigator.mediaDevices.addEventListener("devicechange",t),()=>navigator.mediaDevices.removeEventListener("devicechange",t)},[]);const Ya=async t=>{var s;if(Bs(t),g&&g.localParticipant){const a=Array.from(g.localParticipant.audioTracks.values())[0];a&&((s=a.track)==null||s.stop(),g.localParticipant.unpublishTrack(a.track));const l=await ve.createLocalAudioTrack({deviceId:{exact:t},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0});g.localParticipant.publishTrack(l)}
2else if(B.current.audio){B.current.audio.stop();const a=await ve.createLocalAudioTrack({deviceId:{exact:t},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0});B.current.audio=a,ft(!!(B.current.audio&&B.current.video))}},Za=async t=>{var s;if(Us(t),g&&g.localParticipant){const a=Array.from(g.localParticipant.videoTracks.values())[0];a&&((s=a.track)==null||s.stop(),g.localParticipant.unpublishTrack(a.track));const l=await ve.createLocalVideoTrack({deviceId:{exact:t},width:{min:640,ideal:1280,max:1920},height:{min:480,ideal:720,max:1080},frameRate:24});g.localParticipant.publishTrack(l),Z.current&&l.attach(Z.current),bt(!0),re(null)}else{const a=B.current.video;a&&(a.detach().forEach(d=>d.remove()),a.stop());const l=await ve.createLocalVideoTrack({deviceId:{exact:t},width:{min:640,ideal:1280,max:1920},height:{min:480,ideal:720,max:1080},frameRate:24});B.current.video=l,Z.current&&l.attach(Z.current),bt(!0),re(null),ft(!!(B.current.audio&&B.current.video))}};r.useEffect(()=>{c&&o==="doctor"&&Ft.getAppointmentByHash(c).then(t=>{var s;(s=t.data)!=null&&s.data&&(Ba(t.data.data),t.data.data.notes&&Ms(t.data.data.notes))}).catch(t=>console.error("Non-critical: Failed to load existing notes",t))},[c,o]);const qs=r.useCallback(async()=>{if(!(!c||o!=="doctor"))try{As(!0);const t=await fetch(`${P}/documents/templates?appointmentHash=${c}`,{headers:Y()});if(!t.ok)throw new Error("Failed to load templates");const a=(await t.json()).data||[];if(Oa(a),!ie&&a.length>0&&Ze(ln(a)),a.length===0&&!le.current){le.current=!0;const l=await fetch(`${P}/documents/generate`,{method:"POST",headers:Y(),body:JSON.stringify({appointmentHash:c,notes:Se,skipAi:!0,consultationContext:{notes:Se,transcriptionHistory:qe.current}})});if(l.ok){const d=await l.json();Ue({documentId:d.documentId,status:d.status||"completed",title:"Evolução ClÃnica",template_title:d.template_title||"SOAP - Modelo Padrão",items:d.items||[],template_id:d.template_id}),d.template_id&&Ze(d.template_id),oe("document")}}}catch(t){if(console.error("Error loading evolution templates:",t),!le.current&&c){le.current=!0;try{const s=await fetch(`${P}/documents/generate`,{method:"POST",headers:Y(),body:JSON.stringify({appointmentHash:c,notes:Se,skipAi:!0})});if(s.ok){const a=await s.json();Ue({documentId:a.documentId,status:a.status||"completed",title:"Evolução ClÃnica",template_title:a.template_title||"SOAP - Modelo Padrão",items:a.items||[],template_id:a.template_id}),oe("document")}}catch(s){console.error("Error creating manual evolution:",s),le.current=!1}}}finally{As(!1),Va(!0)}},[c,o,ie,Se]),et=r.useCallback(async()=>{var t;if(!(!c||o!=="doctor"||!Le))try{Is(!0);const s=await fetch(`${P}/documents/${c}`,{headers:Y()});if(!s.ok)throw new Error("Failed to load generated documents");const l=((t=(await s.json()).data)==null?void 0:t[0])||null;if(Ue(d=>le.current&&(d==null?void 0:d.status)==="completed"||(d==null?void 0:d.status)==="completed"&&((d==null?void 0:d.items)||[]).length&&(!l||l.status==="processing")?d:l),l!=null&&l.template_id&&!ie&&Ze(l.template_id),l&&l.status==="processing"&&!le.current){if(vt.current+=1,vt.current>=dn){le.current=!0,wt("A IA demorou demais para gerar a evolução. Preencha manualmente para encerrar a consulta."),Ue(d=>d?{...d,status:"failed"}:{status:"failed",items:[]});return}ce.current&&window.clearTimeout(ce.current),ce.current=window.setTimeout(et,cn)}}catch(s){console.error("Error loading generated document:",s)}finally{Is(!1)}},[c,o,ie,Le]);r.useEffect(()=>{if(Le&&o==="doctor"&&c){let t=!1;return(async()=>{xe.length===0&&await qs(),t||await et()})(),()=>{t=!0}}else ce.current&&(window.clearTimeout(ce.current),ce.current=null)},[Le,c,o,xe.length,qs,et]),r.useEffect(()=>{Le||(oe("form"),le.current=!1,vt.current=0,wt(null))},[Le]);const[G,Nt]=r.useState(o==="doctor"?"transcription":"chat"),[St,kt]=r.useState(0),[er,ss]=r.useState(!1),Be=r.useRef(G),Ws=r.useRef(0),[tr,as]=r.useState(!1);r.useEffect(()=>{Be.current=G,G==="chat"&&kt(0),G==="triage"&&ss(!1)},[G]);const[I,Ue]=r.useState(null),[xn,rs]=r.useState("idle"),[Gs,Js]=r.useState(!1),[Hs,ns]=r.useState(!1),[_t,Qs]=r.useState(""),[sr,Ks]=r.useState([]),ar=r.useRef(null),os=r.useRef(null),Z=r.useRef(null),Ce=r.useRef(null),Tt=r.useRef(null),rr=()=>
2[B.current.audio,B.current.video].filter(Boolean),tt=r.useCallback((t,s=Z.current)=>wa(t,s),[]),nr=r.useCallback(t=>{Z.current=t,t&&B.current.video&&tt(B.current.video,t)},[tt]),is=t=>{if(!(!t||typeof t!="object")){try{if("detach"in t&&typeof t.detach=="function"){const s=t.detach();s==null||s.forEach(a=>{var l;(a==null?void 0:a.srcObject)instanceof MediaStream&&(a.srcObject.getTracks().forEach(d=>d.stop()),a.srcObject=null),(l=a==null?void 0:a.remove)==null||l.call(a)})}}catch{}try{const s=t.mediaStreamTrack;s&&s.readyState!=="ended"&&s.stop()}catch{}try{"stop"in t&&typeof t.stop=="function"&&t.stop()}catch{}}},Xs=()=>{const{audio:t,video:s}=B.current;t&&t.stop(),s&&(Na(s.detach(),Z.current),s.stop()),B.current={audio:null,video:null},ft(!1),xt(!1)},or=()=>{E.current=!1,Me(!1);const t=s=>{if(s)try{s.ondataavailable=null,s.onstop=null,s.onerror=null,s.state!=="inactive"&&s.stop()}catch{}};t(C.current),t(O.current),C.current=null,O.current=null,m.current=null,W.current&&(clearInterval(W.current),W.current=null)},Ys=t=>{var s;t.track&&is(t.track);try{(s=t.unpublish)==null||s.call(t)}catch{}},Zs=()=>{pt.current+=1,Ke.current=!1,or();const t=y.current;if(t)try{t.localParticipant.tracks.forEach(s=>{Ys(s)})}catch{}Xs(),Z.current&&(Z.current.srcObject=null),Ce.current&&(Ce.current.srcObject=null)},ls=async()=>{if(Ke.current||y.current||$e)return;if(!se&&!te){xt(!0);return}const t=pt.current;Ke.current=!0;try{const s=te?ve.createLocalAudioTrack(_e?{deviceId:{exact:_e},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}):Promise.resolve(null),a=se?ve.createLocalVideoTrack(Te?{deviceId:{exact:Te},width:{min:640,ideal:1280,max:1920},height:{min:480,ideal:720,max:1080},frameRate:24}:{width:{min:640,ideal:1280,max:1920},height:{min:480,ideal:720,max:1080},frameRate:24}):Promise.resolve(null),[l,d]=await Promise.allSettled([s,a]),x=l.status==="fulfilled"?l.value:null,w=d.status==="fulfilled"?d.value:null;if(t!==pt.current){is(x),is(w);return}B.current={audio:x,video:w},w&&tt(w),re(null),ae(null),ft(!!(x||w)),xt(!0),d.status==="rejected"&&(console.error("Error creating preview video track:",d.reason),re("Não foi possÃvel ativar a câmera. Verifique as permissões do navegador.")),l.status==="rejected"&&(console.error("Error creating preview audio track:",l.reason),re("Não foi possÃvel ativar um ou mais dispositivos. Você poderá ativá-los após entrar na sala."))}catch(s){console.error("Unexpected error preparing local preview tracks:",s),xt(!0)}finally{t===pt.current&&(Ke.current=!1)}},ir=t=>{if(!t)return"Não informado";const s=new Date(t);return Number.isNaN(s.getTime())?"Não informado":s.toLocaleString("pt-BR",{dateStyle:"short",timeStyle:"short"})},cs=()=>{const t=Os||{},s=t.patient||{};return{patientName:s.name||i||(u==null?void 0:u.patientName)||"Paciente",patientBirthDate:s.birth_date?new Date(s.birth_date).toLocaleDateString("pt-BR"):"Não informado",doctorName:t.professional_name||(u==null?void 0:u.doctorName)||Je||"Profissional",specialtyName:t.specialty_name||"ClÃnica Geral",consultationDate:ir(t.scheduled_datetime),companyName:t.company_name||(u==null?void 0:u.customerTradeName)||"Não informado"}},[Ae,ds]=r.useState([]),qe=r.useRef([]);r.useEffect(()=>{qe.current=Ae},[Ae]);const[us,lr]=r.useState(!1);r.useEffect(()=>{const t=()=>{lr(window.innerWidth<768)};return t(),window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),r.useEffect(()=>{c&&!_s.current?(async()=>{var s,a,l,d,x,w;try{const h=await fetch(`${P}/consultations/${c}/info`);if(h.ok){const f=await h.json();ee(f),qt(f.isProfessionalBusy||!1),lt({doctor_present:((s=f.presence)==null?void 0:s.doctor_present)||!1,patient_present:((a=f.presence)==null?void 0:a.patient_present)||!1,both_present:((l=f.presence)==null?void 0:l.both_present)||!1,waiting_for_role:((d=f.presence)==null?void 0:d.waiting_for_role)||null,waiting_message:((x=f.presence)==null?void 0:x.waiting_message)||null,current_role_state:((w=f.presence)==null?void 0:w.current_role_state)||null}),f.screening_enabled&&!f.screening_completed&&Ss(!0),rn({mode:o,status:f.status,showNPSModal:!1,npsSubmitted:!1})&&Xe(!0)}}catch(h){console.error("Error fetching consultation info:",h)}finally{_s.current=!0,o==="patient"&&ks(!1)}})():o==="doctor"&&ks(!1)},[c,o]),r.useEffect(()=>(u!=null&&u.customerTradeName&&(document.title=u.customerTradeName),()=>{document.title="Teledoc"}),[u==null?void 0:u.customerTradeName]);const st=r.useCallback(()=>
2{if(Oe.current||K.current)return;const t=mt.current;mt.current+=1;const s=Math.min(3e4,1e3*2**Math.min(t,5)),a=s+Math.round(Math.random()*s*.2);t>=3&&ae("Ainda tentando restabelecer a chamada. Verifique sua conexão."),K.current=window.setTimeout(()=>{K.current=null,Oe.current||(ae(null),Ns.current())},a)},[]),at=async()=>{if(!(q.current||!c||$||y.current||b.current)){q.current=!0;try{console.log("Fetching token...");const t=await fetch(`${P}/video/token`,{method:"POST",headers:Y(),body:JSON.stringify({identity:o==="doctor"?Je?`Dr(a). ${Je}`:"Dr(a). Profissional":void 0,appointment_hash:c})});if(!t.ok){let a=`Erro ao conectar (${t.status})`;try{const l=await t.json();l.message&&(a=l.message),t.status===423&&l.presence&<({doctor_present:l.presence.doctor_present||!1,patient_present:l.presence.patient_present||!1,both_present:l.presence.both_present||!1,waiting_for_role:l.presence.waiting_for_role||null,waiting_message:l.presence.waiting_message||null,current_role_state:l.presence.current_role_state||null})}catch(l){console.error("Error parsing error response:",l),t.status===403&&(a="Acesso negado. Verifique se o link está correto."),t.status===404&&(a="Serviço não encontrado.")}console.error("Token fetch failed:",a),ae(t.status===423?null:a),(t.status===423||t.status>=500)&&st();return}const s=await t.json();s.token?(K.current&&(window.clearTimeout(K.current),K.current=null),L(s.token),ae(null),M&&sessionStorage.setItem(M,s.room),s.customerInfo&&ee(a=>({...a,...s.customerInfo}))):(console.error("Failed to get token:",s.message),ae("Erro ao conectar: "+(s.message||"Token não recebido")),st())}catch(t){console.error("Error fetching token:",t),ae("Erro de conexão com o servidor. Verifique sua internet e tente novamente."),st()}finally{q.current=!1}}};Ns.current=at;const cr=()=>{Q(!0)};r.useEffect(()=>{o==="patient"&&D&&!ze&&!$&&!Kt&&!pe&&!fe&&ut&&be.both_present&&$e&&at()},[o,D,ze,$,Kt,pe,fe,ut,be.both_present,$e]),r.useEffect(()=>{o==="doctor"&&c&&!$&&Je&&!ne&&ut&&be.both_present&&$e&&at()},[o,c,$,Je,ne,ut,be.both_present,$e]);const ea=!!(c&&!ze&&!pe&&!fe&&!ne&&(o==="doctor"||D));r.useEffect(()=>{if(!y.current){if(!ea){(B.current.audio||B.current.video)&&Xs();return}$e||Ke.current||ls().catch(t=>{console.error("Error preparing local preview tracks:",t)})}},[ea,$e,se,te,_e,Te]),r.useEffect(()=>{if(!ja({hasRoom:!!g,hasRemoteParticipant:!!F,isLocalMediaReady:Pe,showScreening:ze,showNPSModal:pe,npsSubmitted:fe,isConsultationCompleted:ne}))return;const t=B.current.video;t&&Z.current&&tt(t)},[g,F,Pe,ze,pe,fe,ne]);const[ta,dr]=r.useState(0);r.useEffect(()=>{if(!g)return;const s=(()=>{const a=Array.from(g.localParticipant.audioTracks.values())[0],l=a==null?void 0:a.track;if(l&&l.kind==="audio"){const d=l.mediaStreamTrack;if(d){const x=new(window.AudioContext||window.webkitAudioContext),w=x.createMediaStreamSource(new MediaStream([d])),h=x.createAnalyser();h.fftSize=32,w.connect(h);const f=new Uint8Array(h.frequencyBinCount),R=()=>{if(x.state==="closed")return;h.getByteFrequencyData(f);const U=f.reduce((N,z)=>N+z)/f.length;dr(U),requestAnimationFrame(R)};return R(),()=>{x.state!=="closed"&&x.close()}}}})();return()=>{s&&s()}},[g]);const de=(t,s={})=>{fetch(`${P}/video/telemetry`,{method:"POST",headers:{...Y(),"x-video-session-id":ws.current},keepalive:!0,body:JSON.stringify({event:t,role:Pa,code:s.code,duration_ms:s.durationMs,media_mode:s.mediaMode,network_quality:s.networkQuality})}).catch(()=>{})},Ct=(t={})=>{const{clearRoomName:s=!0,clearConnectionState:a=!0,clearToken:l=!0}=t,d=y.current;if(K.current&&(window.clearTimeout(K.current),K.current=null),Zs(),d){y.current=null;try{d.disconnect()}catch{}}m.current=null,s&&M&&sessionStorage.removeItem(M),a&&(A(null),H(null)),l&&L(null)},Et=!!(c&&!pe&&!fe&&!ne),ur=t=>t instanceof Error?t.message:String(t||"Erro desconhecido"),ms=()=>{Oe.current=!0,rt(),Ct(),o==="patient"&&c?Xe(!0):n()},sa=()=>{var s;Oe.current=!1,mt.current=0,K.current&&(window.clearTimeout(K.current),K.current=null),He.current=0,((s=je.current)==null?void 0:s.readyState)===WebSocket.OPEN?at():Qt(a=>a+1),Xe(!1)};r.useEffect(()=>{const t=()=>{Oe.current=!0,K.current&&(window.clearTimeout(K.current),K.current=null);const s=y.current;s&&(y.current=null,s.disconnect());const a=je.current;a&&a.readyState<WebSocket.CLOSING&&a.close(1e3,"Consultation page leaving")};return window.addEventListener("beforeunload",t),window.addEventListener("pagehide",t),()=>{window.removeEventListener("beforeunload",t),window.removeEventListener("pagehide",t)}},[]);const mr=async()=>
2{if(Ye)try{await fetch(`${P}/video/nps`,{method:"POST",headers:Y(),body:JSON.stringify({appointment_hash:c,rating:Ye,feedback:es})}),Da(!0),setTimeout(()=>{V({npsRating:Ye,npsFeedback:es})},2e3)}catch(t){console.error("Error submitting NPS:",t),V()}};r.useEffect(()=>{if(!$||!c||y.current||b.current)return;let t=!1;b.current=!0;const s=(M?sessionStorage.getItem(M):null)||c,a=rr(),l=a.length===2?"audio_video":a.length===1?"degraded":"receive_only",d=()=>({name:s,tracks:a.length>0?a:void 0,audio:!1,video:!1,bandwidthProfile:{video:{mode:"collaboration",renderDimensions:{high:{height:720,width:1280},standard:{height:480,width:640},low:{height:180,width:320}}}},maxAudioBitrate:4e4,maxVideoBitrate:l==="audio_video"?8e5:4e5,networkQuality:{local:2,remote:1}}),x=h=>{y.current=h,A(h),mt.current=0,de("connection_succeeded",{durationMs:Qe.current?Date.now()-Qe.current:void 0,mediaMode:l}),o==="doctor"&&fetch(`${P}/consultations/${c}/start`,{method:"POST"}).catch(N=>console.error("Error starting consultation:",N)),console.log(`Connected to Room: ${h.name}`);const f=N=>{N.kind==="video"&&Z.current&&wa(N,Z.current)};Array.from(h.localParticipant.tracks.values()).forEach(N=>{N.track&&f(N.track)}),h.localParticipant.on("trackPublished",N=>{N.track&&f(N.track)});const R=N=>{Na(N.detach(),N.kind==="video"?Ce.current:null)},U=N=>{H(N),de("remote_participant_connected"),N.tracks.forEach(z=>{if(z.isSubscribed&&z.track){const X=z.track;X.kind==="video"&&Ce.current?X.attach(Ce.current):X.kind==="audio"&&(X.attach(),X.mediaStreamTrack&&(m.current=X.mediaStreamTrack,E.current&&ps(X.mediaStreamTrack)))}}),N.on("trackSubscribed",z=>{de("remote_track_subscribed"),z.kind==="video"&&Ce.current?z.attach(Ce.current):z.kind==="audio"&&(z.attach(),z.mediaStreamTrack&&(m.current=z.mediaStreamTrack,E.current&&ps(z.mediaStreamTrack)))}),N.on("trackUnsubscribed",z=>{de("remote_track_unsubscribed"),(z.kind==="audio"||z.kind==="video")&&R(z)})};
2h.participants.forEach(U),h.on("participantConnected",U),h.on("participantDisconnected",N=>{N.tracks.forEach(z=>{const X=z.track;X&&(X.kind==="audio"||X.kind==="video")&&R(X)}),m.current=null,H(null),de("remote_participant_disconnected")}),h.localParticipant.on("networkQualityLevelChanged",N=>{de("network_quality_changed",{networkQuality:N})}),h.on("reconnecting",N=>{re("Reconectando a chamadaâ¦"),de("reconnecting",{code:N.code})}),h.on("reconnected",()=>{re(null),de("reconnected")}),h.on("disconnected",(N,z)=>{if(de("disconnected",{code:z==null?void 0:z.code}),y.current===h&&(y.current=null,m.current=null,A(null),H(null),L(null),!(Oe.current||t))){if(Number(z==null?void 0:z.code)===53205){re(null),ae("A chamada foi aberta em outra aba ou página.");return}st()}})};return(async()=>{if(!t)try{Qe.current=Date.now(),de("connection_started",{mediaMode:l});const h=await ve.connect($,d());if(t){h.localParticipant.tracks.forEach(f=>{f.track&&Ys(f)}),h.disconnect();return}x(h)}catch(h){if(t)return;const f=ur(h);console.error("Error connecting to Twilio:",h),de("connection_failed",{code:h==null?void 0:h.code,durationMs:Qe.current?Date.now()-Qe.current:void 0,mediaMode:l}),console.error("Initial Twilio connection error:",f),L(null),re("Não foi possÃvel conectar. Tentando novamenteâ¦"),st()}})().finally(()=>{b.current=!1}),()=>{t=!0,b.current=!1,y.current&&Ct({clearConnectionState:!0,clearToken:!1})}},[$,c,o]),r.useEffect(()=>{if(g){const s=Array.from(g.localParticipant.audioTracks.values())[0];te?s!=null&&s.track?s.track.enable():(async()=>{const l=await ve.createLocalAudioTrack(_e?{deviceId:{exact:_e},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0});g.localParticipant.publishTrack(l)})().catch(l=>{console.error("Error creating local audio track:",l),ae("Não foi possÃvel ativar o microfone. Verifique as permissões do navegador."),zs(!1)}):s!=null&&s.track&&s.track.disable();return}const t=B.current.audio;te?t?t.enable():(Pe||se)&&ls().catch(s=>{console.error("Error creating preview audio track:",s)}):t&&t.disable()},[te,g,_e,se,Pe]),r.useEffect(()=>{if(g){const s=Array.from(g.localParticipant.videoTracks.values())[0];se?s!=null&&s.track?s.track.enable():(async()=>{const l=await ve.createLocalVideoTrack(Te?{deviceId:{exact:Te},width:{min:640,ideal:1280,max:1920},height:{min:480,ideal:720,max:1080},frameRate:24}:{width:{min:640,ideal:1280,max:1920},height:{min:480,ideal:720,max:1080},frameRate:24});g.localParticipant.publishTrack(l),Z.current&&l.attach(Z.current),re(null)})().catch(l=>{console.error("Error creating local video track:",l),re("Não foi possÃvel ativar a câmera. Verifique as permissões do navegador."),bt(!1)}):s!=null&&s.track&&s.track.disable();return}const t=B.current.video;se?t?(t.enable(),tt(t)):(Pe||te)&&ls().catch(s=>{console.error("Error creating preview video track:",s)}):t&&t.disable()},[se,g,Te,te,Pe]),r.useEffect(()=>{G==="transcription"&&c&&(async()=>{try{const s=await fetch(`${P}/transcription/${c}`);if(s.ok){const a=await s.json();ds(a.data||[])}}catch(s){console.error("Error fetching transcriptions:",s)}})()},[G,c]);const ps=t=>{var s;try{if(((s=O.current)==null?void 0:s.state)==="recording")return;if(t.readyState!=="live"){console.warn("Remote audio track is not live, skipping recording.");return}const a=new MediaStream([t]),l=new MediaRecorder(a,{mimeType:"audio/webm"});O.current=l,k.current=[],l.ondataavailable=d=>{d.data.size>0&&k.current.push(d.data)},l.onstop=()=>{if(k.current.length>0){const d=new Blob(k.current,{type:"audio/webm"});aa(d,"patient").catch(console.error)}if(k.current=[],E.current&&l.state==="inactive"&&t.readyState==="live")try{l.start()}catch(d){console.error("Error restarting remote recorder:",d)}},l.start()}catch(a){console.error("Error starting remote recording:",a)}},pr=async()=>{if(!(!g||!c)){Me(!0),E.current=!0;try{const t=Array.from(g.localParticipant.audioTracks.values())[0],s=t==null?void 0:t.track;if(!s){alert("Nenhuma faixa de áudio disponÃvel. Verifique se seu microfone está ativado."),Me(!1),E.current=!1;return}const a=s.mediaStreamTrack;if(!a){alert("Não foi possÃvel acessar o áudio do microfone."),Me(!1),E.current=!1;return}const l=new MediaStream([a]),d=new MediaRecorder(l,{mimeType:"audio/webm"});
2C.current=d,j.current=[],d.ondataavailable=x=>{x.data.size>0&&j.current.push(x.data)},d.onstop=()=>{if(j.current.length>0){const x=new Blob(j.current,{type:"audio/webm"});aa(x,"professional").catch(console.error)}if(j.current=[],E.current&&d.state==="inactive")try{d.start()}catch(x){console.error("Error restarting recorder:",x)}},d.onstart=()=>{console.log("Transcription recording started successfully")},d.onerror=x=>{console.error("MediaRecorder error:",x),Me(!1),E.current=!1},d.start(),m.current&&ps(m.current),setTimeout(()=>{E.current&&(W.current=setInterval(()=>{C.current&&C.current.state==="recording"&&C.current.stop(),O.current&&O.current.state==="recording"&&O.current.stop()},4e3))},500)}catch(t){console.error("Error starting transcription:",t),alert("Erro ao iniciar transcrição. Verifique se o microfone está funcionando."),Me(!1),E.current=!1}}},rt=()=>{W.current&&(clearInterval(W.current),W.current=null),C.current&&C.current.state==="recording"&&C.current.stop(),O.current&&O.current.state==="recording"&&O.current.stop(),Me(!1),E.current=!1},aa=async(t,s)=>{if(c)try{const a=new FormData;a.append("audio",t,"audio.webm"),a.append("speaker_type",s);const l=qe.current.length>0?qe.current[qe.current.length-1].text:"";a.append("last_transcription",l);const d=await fetch(`${P}/transcription/${c}/transcribe`,{method:"POST",body:a});if(d.ok){const x=await d.json();x.text&&x.text.trim()&&ds(w=>[...w,{speaker_type:x.speaker_type,text:x.text,created_at:new Date().toISOString()}])}}catch(a){console.error("Error sending audio for transcription:",a)}},fr=()=>{Zt?(rt(),Ls(!1)):(Ls(!0),pr())};r.useEffect(()=>{const t=()=>{var a;Zs();try{(a=y.current)==null||a.disconnect()}catch{}y.current=null},s=()=>{t()};return window.addEventListener("pagehide",s),()=>{window.removeEventListener("pagehide",s),t(),ce.current&&window.clearTimeout(ce.current)}},[]),r.useEffect(()=>{os.current&&os.current.scrollIntoView({behavior:"smooth"})},[Ae]);const xr=async t=>{var a;const s=(a=t.target.files)==null?void 0:a[0];if(s&&c){rs("uploading");const l=new FormData;l.append("file",s),l.append("sender_type",o==="doctor"?"professional":"patient");try{const d=await fetch(`${P}/consultations/${c}/documents`,{method:"POST",body:l});if(d.ok){const x=await d.json();x.message&&Pt(x.message),rs("success")}else console.error("Upload failed"),alert("Erro ao enviar arquivo.")}catch(d){console.error("Error uploading:",d),alert("Erro ao enviar arquivo.")}finally{setTimeout(()=>rs("idle"),3e3),Tt.current&&(Tt.current.value="")}}},Rt=r.useCallback(t=>{var s,a;return{id:String(t.id),sender:t.sender_type==="professional"?(s=Re.current)!=null&&s.doctorName?`Dr(a). ${Re.current.doctorName}`:"Dr(a). Profissional":((a=Re.current)==null?void 0:a.patientName)||"Paciente",text:t.message_content,timestamp:new Date(t.created_at),isSelf:o==="doctor"&&t.sender_type==="professional"||o==="patient"&&t.sender_type==="patient",type:t.message_type,fileUrl:t.file_url?t.file_url.startsWith("http")?t.file_url:`${P}${t.file_url.replace(/^\/api\/v1/,"")}`:void 0,fileName:t.file_name||void 0}},[o]),Pt=r.useCallback(t=>{const s=Rt(t);Ks(a=>a.some(l=>l.id===s.id)?a:(Ws.current=a.length+1,!s.isSelf&&Be.current!=="chat"&&kt(l=>l+1),[...a,s]))},[Rt]),$t=r.useCallback(async()=>{if(c)try{const t=await fetch(`${P}/consultations/${c}/chat`);if(t.ok){const a=(await t.json()).map(Rt);Ks(l=>{const d=new Set(l.map(f=>f.id)),x=a.filter(f=>!d.has(f.id)&&!f.isSelf).length,w=new Map(l.map(f=>[f.id,f]));a.forEach(f=>{w.set(f.id,f)});const h=Array.from(w.values()).sort((f,R)=>f.timestamp.getTime()-R.timestamp.getTime());return Be.current!=="chat"&&x>0?kt(f=>f+x):Be.current==="chat"&&kt(0),Ws.current=h.length,h})}}catch(t){console.error("Error fetching chat:",t)}},[c,Rt]);r.useEffect(()=>{$t()},[$t]),r.useEffect(()=>{if(!Et)return;const t=()=>{var s;((s=je.current)==null?void 0:s.readyState)!==WebSocket.OPEN&&(He.current=0,we.current&&(window.clearTimeout(we.current),we.current=null),Qt(a=>a+1))};return window.addEventListener("online",t),()=>window.removeEventListener("online",t)},[Et]),r.useEffect(()=>{if(!c||!Et)return;let t=!1;const s=hs.API_URL.startsWith("http")?hs.API_URL:`${window.location.origin}${hs.API_URL}
2`,a=new URL(`${s.replace(/\/$/,"")}/ws/consultations`);a.protocol=a.protocol==="https:"?"wss:":"ws:",a.searchParams.set("appointment_hash",c),a.searchParams.set("session_id",ws.current);const l=o==="doctor"?localStorage.getItem("auth_token"):null,d=l?["teledoc-consultation-v1",l]:["teledoc-consultation-v1"],x=new WebSocket(a.toString(),d);return je.current=x,x.onopen=()=>{t||(He.current=0,Ht(!0))},x.onmessage=w=>{var h;if(!(t||typeof w.data!="string"))try{const f=JSON.parse(w.data),R=f.payload||{};if((f.type==="subscribed"||f.type==="presence_updated")&&R.presence&&(lt({doctor_present:!!R.presence.doctor_present,patient_present:!!R.presence.patient_present,both_present:!!R.presence.both_present,waiting_for_role:R.presence.waiting_for_role||null,waiting_message:R.presence.waiting_message||null,current_role_state:R.presence.current_role_state||null}),f.type==="presence_updated"))return;if(f.type==="subscribed"&&R.consultation){$t();const U=R.consultation;if(((h=U.eligibility)==null?void 0:h.status)==="ineligible"&&window.dispatchEvent(new CustomEvent("teledoc:eligibility-updated",{detail:{appointmentHash:c,allowed:!1,status:"ineligible"}})),U.status&&(ee(N=>N&&{...N,status:U.status}),o==="patient"&&U.status==="completed"&&(Ct({clearConnectionState:!0,clearToken:!0}),Xe(!0))),qt(!!U.isProfessionalBusy),o==="doctor"&&U.screening){const N=U.screening;N.screening_status==="completed"?(ye("completed"),ht({summary:N.screening_summary||"",risk_level:N.screening_risk_level||""})):N.screening_status==="in_progress"?ye("in_progress"):ye("not_started")}return}if(f.type==="chat_created"){Pt(R);return}if(f.type==="screening_updated"&&o==="doctor"){const U=R.screening_status;U==="completed"?(ye("completed"),ht({summary:R.screening_summary||"",risk_level:R.screening_risk_level||""}),Be.current!=="triage"&&ss(!0)):U==="in_progress"&&ye("in_progress");return}if(f.type==="consultation_status_updated"&&R.status){ee(U=>U&&{...U,status:R.status}),o==="patient"&&R.status==="completed"&&(Ct({clearConnectionState:!0,clearToken:!0}),Xe(!0));return}if(f.type==="professional_busy_updated"){qt(!!R.isProfessionalBusy);return}f.type==="eligibility_updated"&&window.dispatchEvent(new CustomEvent("teledoc:eligibility-updated",{detail:{appointmentHash:c,applicable:!!R.applicable,allowed:R.allowed!==!1,status:R.status||null,message:R.message||null}}))}catch(f){console.error("Invalid consultation realtime event:",f)}},x.onclose=()=>{if(je.current===x&&(je.current=null),t)return;Ht(!1),lt({doctor_present:!1,patient_present:!1,both_present:!1,waiting_for_role:null,waiting_message:null,current_role_state:null});const w=He.current;He.current+=1;const h=Math.min(3e4,1e3*2**Math.min(w,5)),f=h+Math.round(Math.random()*h*.2);we.current=window.setTimeout(()=>{we.current=null,t||Qt(R=>R+1)},f)},()=>{t=!0,we.current&&(window.clearTimeout(we.current),we.current=null),je.current===x&&(je.current=null),x.close(1e3,"Consultation view closed"),Ht(!1)}},[Pt,c,$t,o,$a,Et]);const ra=async()=>{if(_t.trim()&&c)try{const t=await fetch(`${P}/consultations/${c}/chat`,{method:"POST",headers:Y(),body:JSON.stringify({sender_type:o==="doctor"?"professional":"patient",message_content:_t,message_type:"text"})});if(!t.ok)throw new Error("Chat message was rejected.");const s=await t.json();s.message&&Pt(s.message),Qs("")}catch(t){console.error("Error sending message:",t),alert("Erro ao enviar mensagem.")}},hr=async(t="completed")=>{if(!c)return!1;try{const s=await fetch(`${P}/consultations/${c}/complete`,{method:"POST",headers:Y(),body:JSON.stringify({status:t})});if(!s.ok){const a=await s.json().catch(()=>null);return s.status===404&&String((a==null?void 0:a.message)||"").toLowerCase().includes("finalizado")?(rt(),Rs(!0),!0):(alert("Erro ao finalizar: "+((a==null?void 0:a.message)||"tente novamente")),!1)}return rt(),Rs(!0),!0}catch(s){return console.error("Error completing consultation:",s),alert("Erro ao finalizar consulta."),!1}},na=async t=>{if(!(!c||Yt)){if(gt(!1),t==="no_show"){$s(!0);try{const s=await fetch(`${P}/consultations/${c}/complete`,{method:"POST",headers:Y(),body:JSON.stringify({status:t})});if(s.ok)rt(),alert("Falta registrada com sucesso!"),ms();else{const a=await s.json().catch(()=>null);alert("Erro ao finalizar: "+((a==null?void 0:a.message)||"tente novamente"))}}catch(s){console.error("Error completing consultation:",s),alert("Erro ao finalizar consulta.")}finally{$s(!1)}return}Fe(!0),Ve(!0),oe(I?"document":"form")}},gr=async()=>{var t;if(!Xt){Ps(!0);try{if(!((t=I==null?void 0:I.items)!=null&&t.length)){alert("Nenhuma evolução para salvar.");return}if(!await oa({silent:!0}))return;if(Ne){if(!await hr("completed"))return;Ve(!1),oe("form"),Fe(!1),ms();return}alert("Evolução salva com sucesso!")}finally{Ps(!1)}}},br=async()=>
2{if(!I){alert("Nenhum documento para gerar PDF.");return}if(I.status&&I.status!=="completed"){alert("A evolução ainda está sendo gerada. Tente novamente em instantes.");return}const t=window.open("about:blank","_blank");if(!t){alert("Não foi possÃvel abrir o PDF em uma nova aba. Permita pop-ups para este site e tente novamente.");return}if(t.opener=null,!await oa({silent:!0})){t.close(),alert("Não foi possÃvel salvar a evolução antes de gerar o PDF.");return}const a=new Er,l="Evolução ClÃnica",d=cs();String(d.patientName||i||"Paciente").replace(/[\\/:*?"<>|]+/g,"_");const x=a.internal.pageSize.getWidth(),w=a.internal.pageSize.getHeight(),h=16,f=16,R=16,U=18,N=x-h-f,z=4.2,X=2.2,fs=Ee=>{ue+Ee>w-U&&(a.addPage(),ue=R)},wr=(Ee,De)=>{a.setFontSize(De);const it=a.splitTextToSize(Ee||"",N);return Math.max(it.length,1)*z};a.setFontSize(18),a.text(l,x/2,R,{align:"center"}),a.setFontSize(10);const Nr=[`Paciente: ${d.patientName}`,`Nascimento: ${d.patientBirthDate}`,`Médico: ${d.doctorName}`,`Especialidade: ${d.specialtyName}`,`Consulta: ${d.consultationDate}`,`Unidade/Empresa: ${d.companyName}`];let ue=R+10;Nr.forEach(Ee=>{const De=a.splitTextToSize(Ee,N);fs(De.length*z),a.text(De,h,ue),ue+=De.length*z+1}),ue+=2,a.setFontSize(11),a.setFont("helvetica","bold");const la=`Modelo utilizado: ${I.template_title||I.templateTitle||"Não informado"}`;fs(wr(la,11)+2),a.text(la,h,ue),ue+=6,a.setFont("helvetica","normal"),a.setFontSize(10),(I.items||[]).forEach(Ee=>{a.setFont("helvetica","bold");const De=Ee.item_title||"Campo",it=a.splitTextToSize(De,N),kr=String(Ee.item_content||"").trim()||"Não informado",xs=a.splitTextToSize(kr,N),_r=it.length*z+1+xs.length*z+X;fs(_r),a.text(it,h,ue),ue+=it.length*z+1,a.setFont("helvetica","normal"),a.text(xs,h,ue),ue+=xs.length*z+X});const Sr=a.output("blob"),ca=URL.createObjectURL(Sr);t.location.href=ca,window.setTimeout(()=>URL.revokeObjectURL(ca),6e4)},nt=cs();if(ct&&!pe&&!fe&&!ne)return e.jsx(ga,{message:ct,onRetry:()=>{ae(null),sa()}});if(!D){const t=u!=null&&u.customerLogo?u.customerLogo.startsWith("http")?u.customerLogo:`${P}${u.customerLogo}`:void 0;return e.jsx("div",{className:"min-h-screen bg-slate-50 flex items-center justify-center p-4",children:e.jsx(Gr,{onAccept:cr,logoUrl:t,customerId:u==null?void 0:u.customerId})})}const ot=async t=>{const s=!!(t!=null&&t.skipAi)||xe.length===0||!ie;if(!c||!s&&!ie)return;s?(le.current=!0,ce.current&&(window.clearTimeout(ce.current),ce.current=null)):(le.current=!1,vt.current=0,wt(null)),Ds(!0);let a=!1,l="Não foi possÃvel gerar a evolução com IA. Preencha manualmente para encerrar a consulta.";try{const d={notes:Se,transcriptionHistory:qe.current};await fetch(`${P}/professionals/me/appointments/${c}/notes`,{method:"PUT",headers:Y(),body:JSON.stringify({notes:Se})}).catch(w=>{console.warn("Failed to save evolution notes before generation:",w)});const x=await fetch(`${P}/documents/generate`,{method:"POST",headers:Y(),body:JSON.stringify({appointmentHash:c,templateId:ie||void 0,notes:Se,consultationContext:d,skipAi:s})});if(x.ok){const w=await x.json(),h=xe.find(f=>String(f.id)===String(ie));Ue({documentId:w.documentId,status:w.status||(s?"completed":"processing"),title:"Evolução ClÃnica",template_title:w.template_title||(h==null?void 0:h.title)||"Não informado",items:w.items||[],template_id:w.template_id||ie,metadata:cs()}),w.template_id&&Ze(w.template_id),oe("document"),w.status!=="completed"&&et()}else{const w=await x.json().catch(()=>null);s?alert((w==null?void 0:w.message)||"Erro ao gerar documento."):(a=!0,l=(w==null?void 0:w.message)||l)}}catch(d){console.error("Error generating document:",d),s?alert("Erro ao gerar documento."):a=!0}finally{Ds(!1)}a&&(wt(l),await ot({skipAi:!0}))},yr=(t,s)=>{Ue(a=>a&&{...a,items:(a.items||[]).map(l=>l.id===t?{...l,item_content:s}:l)})},oa=async t=>{var s;if(!((s=I==null?void 0:I.items)!=null&&s.length))return t!=null&&t.silent||alert("Nenhuma evolução para salvar."),!1;try{for(const a of I.items)a.id&&await fetch(`${P}/documents/items/${a.id}`,{method:"PUT",headers:Y(),body:JSON.stringify({content:a.item_content||""})});return t!=null&&t.silent||alert("Evolução salva com sucesso!"),et(),!0}catch(a){return console.error("Error saving generated document:",a),t!=null&&t.silent||alert("Erro ao salvar evolução."),!1}},vr=async()=>
2{if(c)try{(await fetch(`${P}/transcription/${c}`,{method:"DELETE"})).ok?(ds([]),as(!1)):alert("Erro ao limpar transcrição.")}catch(t){console.error("Error clearing transcription:",t),alert("Erro ao limpar transcrição.")}},jr=ja({hasRoom:!!g,hasRemoteParticipant:!!F,isLocalMediaReady:Pe,showScreening:ze,showNPSModal:pe,npsSubmitted:fe,isConsultationCompleted:ne});return Kt&&o==="patient"?e.jsx("div",{className:"fixed inset-0 z-50 bg-gradient-to-br from-blue-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center max-w-md px-8",children:[e.jsx("div",{className:"mb-6",children:u!=null&&u.customerLogo?e.jsx("img",{src:u.customerLogo.startsWith("http")?u.customerLogo:`${P}${u.customerLogo}`,alt:"Logo",className:"h-12 mx-auto object-contain",onError:t=>{t.currentTarget.src="/logo.png"}}):e.jsx("img",{src:"/logo.png",alt:"Teledoc",className:"h-10 mx-auto object-contain"})}),e.jsx("h2",{className:"text-xl font-bold text-gray-800 mb-2",children:"Preparando seu atendimento"}),e.jsx("p",{className:"text-gray-500 text-sm",children:"Por favor, aguarde enquanto configuramos sua consulta..."})]})}):o!=="doctor"&&ze&&c?e.jsx(an,{appointmentHash:c,onComplete:()=>Ss(!1)}):ct&&!pe&&!fe&&!ne?e.jsx(ga,{message:ct,onRetry:()=>{ae(null),at()}}):e.jsxs("div",{className:"flex flex-col md:flex-row bg-slate-50 text-slate-800 overflow-hidden font-sans",style:{height:"100vh",maxHeight:"100vh"},children:[e.jsxs("div",{className:"flex-1 relative flex flex-col bg-white overflow-hidden md:border-r border-gray-200",children:[e.jsxs("div",{className:"absolute top-4 left-4 z-10 bg-white/90 backdrop-blur-md px-4 py-2 rounded-full border border-gray-200 flex items-center gap-3 shadow-sm max-[500px]:hidden",children:[o==="patient"&&e.jsxs(e.Fragment,{children:[(!Wt||Jt)&&e.jsx("div",{className:"h-12 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}),u!=null&&u.customerLogo?e.jsx("img",{src:u.customerLogo.startsWith("http")?u.customerLogo:`${P}${u.customerLogo}`,alt:"Logo",className:`h-12 object-contain ${!Wt||Jt?"hidden":""}`,onLoad:()=>Gt(!0),onError:t=>{Gt(!0),t.currentTarget.src="/logo.png"}}):e.jsx("img",{src:"/logo.png",alt:"Teledoc",className:`h-8 object-contain ${!Wt||Jt?"hidden":""}`,onLoad:()=>Gt(!0)})]}),e.jsx("div",{className:`w-2 h-2 rounded-full ${g?"bg-green-500":"bg-red-500"} animate-pulse`}),e.jsx("span",{className:"text-sm font-medium text-gray-600",children:g?"Conectado":o==="doctor"?be.patient_present?"Conectando com o paciente...":"Aguardando o paciente entrar na chamada.":be.waiting_message||"Aguardando conexão..."}),dt&&e.jsxs("div",{className:"ml-4 px-3 py-1 bg-amber-100 text-amber-800 text-xs font-bold rounded-full flex items-center gap-2",children:[e.jsx(ge,{size:12}),dt]}),o==="patient"&&Ie&&!g&&e.jsxs("div",{className:"ml-4 px-3 py-1 bg-yellow-100 text-yellow-800 text-xs font-bold rounded-full flex items-center gap-2 animate-pulse",children:[e.jsx(ge,{size:12}),"O profissional está em outro atendimento e logo iniciará."]})]}),e.jsxs("div",{className:"bg-slate-100 relative overflow-hidden flex items-center justify-center group flex-1 w-full",children:[e.jsx("video",{ref:Ce,autoPlay:!0,playsInline:!0,className:"w-full h-full object-cover"}),!F&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-slate-400 bg-slate-50",children:[e.jsx("div",{className:"w-24 h-24 bg-slate-100 rounded-full flex items-center justify-center mb-4 animate-pulse",children:e.jsx(gs,{size:40,className:"opacity-20"})}),o==="patient"?e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("p",{className:"font-medium text-center px-8 max-[500px]:hidden",children:be.waiting_message||(Ie?"O profissional está com um atraso de aproximadamente 5 minutos. Ele(a) já está ciente da sua consulta e em breve iniciará a chamada. Agradecemos por aguardar.":"O profissional está se conectando ao seu atendimento em instantes.")}),e.jsxs("div",{className:"hidden max-[500px]:flex flex-col items-center gap-2 px-8 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm font-medium text-gray-600",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${g?"bg-green-500":"bg-red-500"} animate-pulse max-[500px]:hidden`}),e.jsx("span",{children:g?"Conectado":be.waiting_message||"Aguardando conexão..."})]}),dt&&e.jsxs("div",{className:"px-3 py-1 bg-amber-100 text-amber-800 text-xs font-bold rounded-full flex items-center gap-2",children:[e.jsx(ge,{size:12,className:"max-[500px]:hidden"}),dt]}),Ie&&!g&&e.jsxs("div",{className:"px-3 py-1 bg-yellow-100 text-yellow-800 text-xs font-bold rounded-full flex items-center gap-2 animate-pulse",children:[e.jsx(ge,{size:12,className:"max-[500px]:hidden"}),"O profissional está em outro atendimento e logo iniciará."]})]})]}):e.jsx("div",{className:"text-center px-8",children:Ts==="in_progress"?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"w-16 h-16 mx-auto bg-blue-100 rounded-full flex items-center justify-center",children:e.jsx(bs,{size:32,className:"text-blue-600 animate-pulse"})}),e.jsxs("p",{className:"font-bold text-blue-700",children:[Cs||"O paciente"," está realizando a triagem com IA"]}),e.jsx("p",{className:"text-sm text-gray-500",children:"Aguarde enquanto coletamos informações sobre os sintomas do paciente."}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-blue-600",children:[e.jsx("div",{className:"w-2 h-2 bg-blue-600 rounded-full animate-bounce",style:{animationDelay:"0ms"}}),e.jsx("div",{className:"w-2 h-2 bg-blue-600 rounded-full animate-bounce",style:{animationDelay:"150ms"}}),e.jsx("div",{className:"w-2 h-2 bg-blue-600 rounded-full animate-bounce",style:{animationDelay:"300ms"}})]})]}):Ts==="completed"&&!F?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"w-16 h-16 mx-auto bg-green-100 rounded-full flex items-center justify-center",children:e.jsx(Mt,{size:32,className:"text-green-600"})}),e.jsx("p",{className:"font-bold text-green-700",children:"Triagem concluÃda!"}),e.jsxs("p",{className:"text-sm text-gray-500",children:[Cs||"O paciente"," finalizou a triagem. Aguardando entrada na sala."]})]}):e.jsx("p",{className:"font-medium",children:be.patient_present?"Conectando com o paciente...":"Aguardando o paciente entrar na chamada."})})]}),F&&e.jsxs("div",{className:"absolute bottom-4 left-4 bg-black/40 backdrop-blur-md px-4 py-2 rounded-xl text-white",children:[e.jsx("h3",{className:"text-lg font-bold",children:o==="patient"?(u==null?void 0:u.doctorName)||F.identity:(u==null?void 0:u.patientName)||F.identity}),o==="patient"&&u&&e.jsxs("p",{className:"text-sm opacity-90",children:["Registro profissional: ",u.doctorCRM]})]})]}),!Gs&&(g||jr)&&e.jsx(he.div,{drag:!0,dragConstraints:{left:0,right:300,top:0,bottom:300},className:"absolute top-4 max-[500px]:top-auto max-[500px]:bottom-[calc((100vw-2rem)/5+2.5rem)] right-4 w-28 h-36 md:top-4 md:right-4 md:w-56 md:h-48 bg-slate-800 rounded-xl overflow-hidden shadow-2xl border-2 md:border-4 border-white cursor-move z-20",children:e.jsxs("div",{className:"relative w-full h-full",children:[e.jsx("video",{ref:nr,autoPlay:!0,playsInl
2ine:!0,muted:!0,className:"w-full h-full object-cover transform scale-x-[-1]"}),!se&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-white text-xs",children:"Câmera desligada"}),e.jsx("div",{className:"absolute bottom-2 right-2 flex gap-0.5 items-end h-4",children:[...Array(3)].map((t,s)=>e.jsx("div",{className:"w-1 bg-green-500 rounded-full transition-all duration-75",style:{height:`${Math.min(100,Math.max(20,ta*(1+s*.5)))}%`,opacity:te?1:.3}},s))}),e.jsx("button",{onClick:()=>Js(!0),className:"absolute top-2 right-2 p-1 bg-black/50 hover:bg-red-500 rounded text-white opacity-0 group-hover:opacity-100 transition-all",title:"Minimizar",children:e.jsx(Ge,{size:14})})]})}),Gs&&e.jsx("button",{onClick:()=>Js(!1),className:"absolute top-4 right-4 p-3 bg-white border border-gray-200 rounded-full shadow-lg hover:bg-gray-50 z-20 text-slate-700",title:"Restaurar",children:e.jsx(Fr,{size:20})}),e.jsxs("div",{className:"h-auto py-3 md:py-0 md:h-24 bg-white border-t border-gray-100 flex flex-wrap max-[500px]:flex-nowrap max-[500px]:[&>button]:scale-90 md:flex-nowrap items-center justify-center gap-3 max-[500px]:gap-1 md:gap-4 px-4 max-[500px]:px-2 md:px-8 z-30 shadow-[0_-4px_20px_rgba(0,0,0,0.05)] shrink-0",children:[e.jsxs("button",{onClick:()=>ns(!Hs),className:`md:hidden p-3 max-[500px]:flex max-[500px]:flex-1 max-[500px]:min-w-0 max-[500px]:aspect-square max-[500px]:p-0 max-[500px]:items-center max-[500px]:justify-center rounded-full border transition-all shadow-sm relative ${o==="doctor"?"bg-teal-50 text-teal-700 border-teal-100 hover:bg-teal-100":"bg-blue-50 text-blue-600 border-blue-100 hover:bg-blue-100"}`,title:o==="doctor"?"Dados do paciente":"Chat",children:[o==="doctor"?e.jsx(Ut,{size:20,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)]"}):e.jsx(ma,{size:20,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)]"}),St>0&&e.jsx("span",{className:"absolute top-0 right-0 w-2.5 h-2.5 bg-red-500 rounded-full border-2 border-white"})]}),e.jsx("button",{onClick:()=>zs(!te),className:`p-3 max-[500px]:flex max-[500px]:flex-1 max-[500px]:min-w-0 max-[500px]:aspect-square max-[500px]:p-0 max-[500px]:items-center max-[500px]:justify-center md:p-4 roun
2ded-full transition-all shadow-sm border ${te?"bg-gray-100 text-gray-700 border-gray-200 hover:bg-gray-200":"bg-red-50 text-red-500 border-red-100 hover:bg-red-100"}`,children:te?e.jsx(Ot,{size:20,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)] md:w-6 md:h-6"}):e.jsx(pa,{size:20,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)] md:w-6 md:h-6"})}),e.jsx("button",{onClick:()=>bt(!se),className:`p-3 max-[500px]:flex max-[500px]:flex-1 max-[500px]:min-w-0 max-[500px]:aspect-square max-[500px]:p-0 max-[500px]:items-center max-[500px]:justify-center md:p-4 rounded-full transition-all shadow-sm border ${se?"bg-gray-100 text-gray-700 border-gray-200 hover:bg-gray-200":"bg-red-50 text-red-500 border-red-100 hover:bg-red-100"}`,children:se?e.jsx(gs,{size:24,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)]"}):e.jsx(Vr,{size:24,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)]"})}),o==="doctor"&&e.jsx("button",{onClick:()=>{Fe(!1),Ve(!0)},className:"p-3 max-[500px]:flex max-[500px]:flex-1 max-[500px]:min-w-0 max-[500px]:aspect-square max-[500px]:p-0 max-[500px]:items-center max-[500px]:justify-center md:p-4 roun
2ded-full bg-gray-100 text-gray-700 border border-gray-200 hover:bg-gray-200 transition-all shadow-sm",title:"Evolução ClÃnica",children:e.jsx(Lt,{size:24,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)]"})}),o==="doctor"&&e.jsx("button",{onClick:()=>Fs(!0),className:"p-3 md:p-4 rounded-full bg-gray-100 text-gray-700 border border-gray-200 hover:bg-gray-200 transition-all shadow-sm hidden md:flex",title:"Receituário",children:e.jsx(Bt,{size:24})}),e.jsx("button",{onClick:()=>ts(!0),className:"p-3 max-[500px]:flex max-[500px]:flex-1 max-[500px]:min-w-0 max-[500px]:aspect-square max-[500px]:p-0 max-[500px]:items-center max-[500px]:justify-center md:p-4 rounded-full bg-gray-100 text-gray-700 border border-gray-200 hover:bg-gray-200 transition-all shadow-sm",title:"Configurações de Ãudio/VÃdeo",children:e.jsx(fa,{size:24,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)] md:w-6 md:h-6"})}),e.jsx("div",{className:"w-px h-8 max-[500px]:hidden md:h-10 bg-gray-200 mx-1 md:mx-2"}),e.jsx("button",{onClick:()=>o==="doctor"&&!ne?gt(!0):ms(),className:"p-3 max-[500px]:flex max-[500px]:flex-1 max-[500px]:min-w-0 max-[500px]:aspect-square max-[500px]:p-0 max-[500px]:items-center max-[500px]:justify-center md:p-4 roun
2ded-full bg-red-500 text-white hover:bg-red-600 transition-all shadow-md",children:e.jsx(Br,{size:20,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)] md:w-6 md:h-6"})}),o==="doctor"&&!ne&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-8 max-[500px]:hidden md:h-10 bg-gray-200 mx-1 md:mx-2"}),e.jsxs("button",{onClick:()=>gt(!0),className:"px-4 py-2 max-[500px]:flex-1 max-[500px]:min-w-0 max-[500px]:aspect-square max-[500px]:px-0 max-[500px]:py-0 max-[500px]:justify-center max-[500px]:gap-0 md:px-6 md:py-3 rounded-full bg-blue-600 text-white hover:bg-blue-700 transition-all shadow-md font-bold text-xs md:text-sm flex items-center gap-2",children:[e.jsx(Mt,{size:16,className:"max-[500px]:w-[clamp(1.25rem,7vw,2.25rem)] max-[500px]:h-[clamp(1.25rem,7vw,2.25rem)] md:w-5 md:h-5"}),e.jsx("span",{className:"hidden md:inline",children:"Finalizar Consulta"}),e.jsx("span",{className:"max-[500px]:hidden md:hidden",children:"Concluir"})]})]})]})]}),e.jsxs(he.div,{initial:!1,animate:!us||Hs?{y:0}:{y:"100%"},transition:{type:"spring",damping:25,stiffness:200},drag:us?"y":!1,dragConstraints:{top:0},dragElastic:.2,onDragEnd:(t,s)=>{s.offset.y>100&&ns(!1)},className:"fixed inset-x-0 bottom-0 z-40 bg-white border-t border-gray-100 flex flex-col shadow-2xl md:static md:w-96 md:border-l md:border-t-0 md:transform-none md:translate-y-0 h-[85vh] rounded-t-3xl md:h-auto md:rounded-none",children:[e.jsx("div",{className:"md:hidden w-full flex flex-col items-center justify-center pt-3 pb-2 bg-white border-b border-gray-100 rounded-t-3xl cursor-grab active:cursor-grabbing",onClick:()=>ns(!1),children:e.jsx("div",{className:"w-16 h-1.5 bg-gray-300 rounded-full mb-2"})}),e.jsxs("div",{className:"flex border-b border-gray-100 overflow-x-auto",children:[o==="doctor"&&J&&e.jsxs("button",{onClick:()=>Nt("triage"),className:`flex-1 min-w-0 py-3 px-1 text-xs sm:text-sm font-bold flex items-center justify-center gap-1.5 transition-colors relative ${G==="triage"?"bg-amber-50 text-amber-600 border-b-2 border-amber-600":"text-gray-500 hover:bg-gray-50"}`,children:[e.jsx(bs,{size:16})," Triagem",G!=="triage"&&er&&e.jsx("span",{className:"absolute top-2 right-1 flex items-center justify-center w-3 h-3 bg-amber-500 rounded-full border-2 border-white animate-pulse"})]}),o==="doctor"&&e.jsxs("button",{onClick:()=>Nt("transcription"),className:`flex-1 min-w-0 py-3 px-1 text-xs sm:text-sm font-bold flex items-center justify-center gap-1.5 transition-colors ${G==="transcription"?"bg-purple-50 text-purple-600 border-b-2 border-purple-600":"text-gray-500 hover:bg-gray-50"}`,children:[e.jsx(xa,{size:16})," ",e.jsx("span",{className:"truncate",children:"Transcrição"})]}),o==="doctor"&&e.jsxs("button",{onClick:()=>Nt("patient"),className:`flex-1 min-w-0 py-3 px-1 text-xs sm:text-sm font-bold flex items-center justify-center gap-1.5 transition-colors ${G==="patient"?"bg-teal-50 text-teal-700 border-b-2 border-teal-600":"text-gray-500 hover:bg-gray-50"}`,children:[e.jsx(Ut,{size:16})," Paciente"]}),e.jsxs("button",{onClick:()=>Nt("chat"),className:`flex-1 min-w-0 py-3 px-1 text-xs sm:text-sm font-bold flex items-center justify-center gap-1.5 transition-colors relative ${G==="chat"?"bg-blue-50 text-blue-600 border-b-2 border-blue-600":"text-gray-500 hover:bg-gray-50"}`,children:[e.jsx(ma,{size:16})," Chat",G!=="chat"&&St>0&&e.jsx("span",{className:"absolute top-2 right-1 flex items-center justify-center w-5 h-5 text-[10px] font-bold text-white bg-red-500 rounded-full border-2 border-white",children:St>9?"9+":St})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 sm:p-6 custom-scrollbar bg-gray-50/50 flex flex-col",children:[G==="patient"&&o==="doctor"&&e.jsx(sn,{appointment:Os}),G==="triage"&&o==="doctor"&&J&&e.jsxs("div",{className:"space-y-4 flex-1",children:[e.jsxs("div",{className:`p-4 rounded-xl border flex items-center gap-3 ${J.risk_level==="critical"||J.risk_level==="high"?"bg-red-50 border-red-200":J.risk_level==="medium"?"bg-orange-50 border-orange-200":"bg-green-50 border-green-200"}`,children:[e.jsx("div",{className:`p-2 rounded-full ${J.risk_level==="critical"||J.risk_level==="high"?"bg-red-100 text-red-600":J.risk_level==="medium"?"bg-orange-100 text-orange-600":"bg-green-100 text-green-600"}`,children:e.jsx(Ta,{size:20})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold uppercase opacity-70 mb-0.5",children:"NÃvel de Risco"}),e.jsx("p",{className:`font-bold text-lg ${J.risk_level==="critical"||J.risk_level==="high"?"text-red-700":J.risk_level==="medium"?"text-orange-700":"text-green-700"}`,children:J.risk_level==="critical"?"CrÃtico/Emergência":J.risk_level==="high"?"Alto":J.risk_level==="medium"?"Médio":"Baixo"})]})]}),e.jsxs("div",{className:"bg-white p-4 rounded-xl border border-gray-200 shadow-sm",children:[e.jsxs("h4",{className:"font-bold text-gray-800 mb
2-2 flex items-center gap-2 text-sm",children:[e.jsx(Lt,{size:16,className:"text-amber-600"})," Resumo da Queixa"]}),e.jsx("div",{className:"text-gray-700 text-sm leading-relaxed whitespace-pre-wrap",children:J.summary})]})]}),G==="chat"&&e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex-1 space-y-4 mb-4 overflow-y-auto custom-scrollbar pr-2",children:[sr.map(t=>e.jsx("div",{className:`flex ${t.isSelf?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[85%] p-3 text-sm shadow-sm border ${t.isSelf?"bg-blue-50 border-blue-100 text-blue-900 rounded-2xl rounded-tr-none":"bg-white border-gray-200 text-gray-700 rounded-2xl rounded-tl-none"}`,children:[e.jsx("p",{className:"text-[10px] font-bold mb-1 opacity-70",children:t.sender}),t.type==="file"?e.jsxs("a",{href:t.fileUrl,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-blue-600 hover:underline bg-white/50 p-2 rounded-lg",children:[e.jsx(Lt,{size:16}),t.fileName||t.text]}):t.text]})},t.id)),e.jsx("div",{ref:ar})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:_t,onChange:t=>Qs(t.target.value),onKeyPress:t=>t.key==="Enter"&&ra(),placeholder:"Digite sua mensagem...",className:"flex-1 px-4 py-2 bg-slate-100 border-0 rounded-xl focus:ring-2 focus:ring-blue-500 focus:bg-white transition-all"}),e.jsx("button",{onClick:()=>{var t;return(t=Tt.current)==null?void 0:t.click()},className:"p-3 text-gray-500 hover:bg-gray-100 rounded-xl transition-colors",title:"Anexar arquivo",children:e.jsx(Ur,{size:20})}),e.jsx("input",{type:"file",ref:Tt,className:"hidden",onChange:xr}),e.jsx("button",{onClick:ra,disabled:!_t.trim(),className:"p-2 bg-blue-600 text-white rounded-xl hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-lg shadow-blue-200",children:e.jsx(js,{size:20})})]})]}),G==="transcription"&&o==="doctor"&&e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx("div",{className:"mb-4",children:e.jsx("button",{onClick:fr,className:`w-full p-4 rounded-xl font-bold flex items-center justify-center gap-3 transition-all ${Zt?"bg-red-50 text-red-600 border-2 border-red-200 hover:bg-red-100":"bg-purple-600 text-white hover:bg-purple-700 shadow-lg"}`,children:Zt?e.jsxs(e.Fragment,{children:[e.jsx(pa,{size:20}),"Parar Transcrição",Ma&&e.jsx("span",{className:"w-2 h-2 bg-red-500 rounded-full animate-pulse"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ot,{size:20}),"Iniciar Transcrição"]})})}),e.jsxs("div",{className:"flex-1 space-y-3 overflow-y-auto custom-scrollbar pr-2",children:[Ae.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-400",children:[e.jsx(xa,{size:48,className:"mb-4 opacity-30"}),e.jsx("p",{className:"text-center",children:"Nenhuma transcrição disponÃvel."}),e.jsx("p",{className:"text-sm text-center mt-2",children:'Clique em "Iniciar Transcrição" para começar a transcrever a consulta.'})]}):Ae.map((t,s)=>e.jsxs(he.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`p-4 rounded-xl ${t.speaker_type==="professional"?"bg-purple-50 border border-purple-100":"bg-blue-50 border border-blue-100"}`,children:[e.jsx("span",{className:`text-xs font-bold uppercase ${t.speaker_type==="professional"?"text-purple-600":"text-blue-600"}`,children:t.speaker_type==="professional"?u!=null&&u.doctorName?`Dr(a). ${u.doctorName}`:"Dr(a). Profissional":"Paciente"}),e.jsx("p",{className:"text-gray-700 mt-1",children:t.text})]},s)),e.jsx("div",{ref:os})]}),Ae.length>0&&e.jsxs("button",{onClick:()=>as(!0),className:"mb-2 w-full py-2 text-xs font-bold text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors flex items-center justify-center gap-2",children:[e.jsx(qr,{size:14}),"Limpar Transcrição"]})]})]})]}),Le&&e.jsx("div",{className:"fixed inset-y-0 right-0 z-[60] flex w-full justify-end md:w-[42rem]",children:e.jsx(he.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"flex h-full w-full flex-col overflow-hidden bg-white shadow-2xl md:rounded-l-3xl md:border-l md:border-gray-200",children:Ia==="form"||!I?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 p-6 border-b border-gray-100",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-bold text-slate-800",children:"Evolução ClÃnica"}),e.jsx("p",{className:"text-sm text-gray-500",children:Ne?"Preencha a evolução e use Salvar e encerrar chamada para finalizar.":"Documento vinculado a esta consulta."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[I&&e.jsx(Vt,{variant:"outline",onClick:()=>oe("document"),icon:e.jsx(Ca,{size:18}),children:"Documento"}),e.jsx("button",{onClick:()=>{Ve(!1),oe("form"),Fe(!1)},className:"text-gray-400 hover:text-gray-600",children:e.jsx(Ge,{size:24})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-bold text-gray-700",children:"Modelo"}),e.jsx("select",{value:ie||"",onChange:t=>Ze(t.target.value),disabled:yt,className:"w-full p-3 bg-gray-50 border border-gray-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-60",children:xe.length===0?e.jsx("option",{value:"",children:yt?"Carregando modelos...":"Nenhum modelo disponÃvel â preenchimento manual"}):xe.map(t=>e.jsx("option",{value:t.id,children:t.title},t.id))}),Fa&&xe.length===0&&e.jsx("p",{className:"text-xs text-amber-700 bg-amber-50 border border-amber-100 rounded-lg px-3 py-2",children:"Nenhum modelo de sumarização encontrado. A evolução clÃnica será preenchida manualmente pelo médico, sem processamento por IA."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-bold text-gray-700",children:"Observações"}),e.jsx("textarea",{value:Se,onChange:t=>Ms(t.target.value),placeholder:"Escreva aqui as observações para gerar a evolução...",className:"w-full h-40 p-4 bg-gray-50 border border-gray-200 rounded-2xl text-sm text-gray-700 outline-none focus:ring-2 focus:ring-blue-100 resize-none"})]}),jt&&e.jsx("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800",children:jt}),e.jsxs("div",{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-3",children:[e.jsx("button",{onClick:()=>{Ve(!1),oe("form"),Fe(!1)},className:"px-6 py-3 rounded-xl border border-gray-200 text-gray-600 font-bold hover:bg-gray-50 transition-colors",children:"Fechar"}),e.jsx("button",{onClick:()=>ot({skipAi:!0}),disabled:ke||yt,className:"px-6 py-3 rounded-xl border border-gray-200 text-gray-700 font-bold hover:bg-gray-50 transition-colors flex items-center justify-center gap-2 disabled:opacity-60",children:ke&&xe.length===0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-gray-400/30 border-t-gray-600 rounded-full animate-spin"}),"Abrindo..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:18}),"Preencher manualmente"]})}),xe.length>0&&e.jsx("button",{onClick:()=>ot(),disabled:ke||yt||!ie,className:"px-6 py-3 rounded-xl bg-blue-600 text-white font-bold hover:bg-blue-700 transition-colors shadow-lg shadow-blue-200 flex items-center justify-center gap-2 disabled:opacity-60",children:ke?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),"Gerando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(bs,{size:18}),"Gerar arquivo"]})})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 p-6 border-b border-gray-100",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{onClick:()=>oe("form"),className:"mt-0.5 h-10 w-10 rounded-full border border-gray-200 text-gray-600 hover:text-gray-800 hover:bg-gray-50 flex items-center justify-center","aria-label":"Voltar",children:e.jsx(ka,{size:18})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-bold text-slate-800",children:"Documento gerado"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Visualização e revisão da evolução clÃnica."})]})]}),e.jsx("button",{onClick:()=>{Ve(!1),oe("form"),Fe(!1)},className:"text-gray-400 hover:text-gray-600",children:e.jsx(Ge,{size:24})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[e.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-slate-50 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-base font-bold text-slate-800",children:"Identificação da consulta"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Dados usados para a geração da evolução."})]}),e.jsx("span",{className:`px-3 py-1 rounded-full text-xs font-bold ${I.status==="completed"?"bg-green-100 text-green-700":I.status==="failed"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:I.status==="completed"?"ConcluÃdo":I.status==="failed"?"Falhou":"Processando"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 text-sm text-gray-700",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-bold text-gray-900",children:"Paciente:"})," ",nt.patientName]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-bold text-gray-900",children:"Nascimento:"})," ",nt.patientBirthDate]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-bold text-gray-900",children:"Médico:"})," ",nt.doctorName]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-bold text-gray-900",children:"Especialidade:"})," ",nt.specialtyName]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-bold text-gray-900",children:"Consulta:"})," ",nt.consultationDate]})]})]}),jt&&e.jsx("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800",children:jt}),I.status==="failed"?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700",children:"Não foi possÃvel gerar a evolução. Preencha manualmente para encerrar a consulta."}),e.jsx("button",{onClick:()=>ot({skipAi:!0}),disabled:ke,className:`px-4 py-2 rounded-xl font-bold transition-colors disabled:opacity-60 ${Ne?"bg-teal-600 text-white hover:bg-teal-700":"border border-gray-200 text-gray-700 hover:bg-gray-50"}`,children:ke?"Abrindo...":Ne?"Preencher manualmente e encerrar":"Preencher manualmente"})]}):I.status!=="completed"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-gray-200 bg-gray-50 p-4 text-sm text-gray-600",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-blue-600 border-t-transparent"}),xe.length===0?"Nenhum modelo de sumarização encontrado. A evolução será preenchida manualmente.":"A IA está processando a evolução clÃnica."]}),e.jsx("button",{onClick:()=>ot({skipAi:!0}),disabled:ke,className:`px-4 py-2 rounded-xl font-bold transition-colors disabled:opacity-60 ${Ne?"bg-teal-600 text-white hover:bg-teal-700":"border border-gray-200 text-gray-700 hover:bg-gray-50"}`,children:ke?"Abrindo...":Ne?"Preencher manualmente e encerrar":"Preencher manualmente"})]}):e.jsx("div",{className:"grid gap-4",children:(I.items||[]).map(t=>e.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white p-4 shadow-sm",children:[e.jsx("label",{className:"block text-xs font-bold uppercase text-blue-600 mb-2",children:t.item_title}),e.jsx("textarea",{value:t.item_content||"",onChange:s=>yr(t.id,s.target.value),className:"w-full min-h-28 rounded-xl border border-gray-200 bg-gray-50 p-3 text-sm text-gray-700 outline-none focus:ring-2 focus:ring-blue-100 resize-y"})]},t.id||t.item_title))})]}),e.jsxs("div",{className:"shrink-0 border-t border-gray-100 bg-white p-4 flex flex-col-reverse sm:flex-row sm:justify-end gap-3 shadow-[0_-4px_16px_rgba(0,0,0,0.04)]",children:[e.jsx("button",{onClick:br,disabled:!I||I.status!=="completed",className:"px-6 py-3 rounded-xl bg-slate-900 text-white font-bold hover:bg-slate-800 transition-colors shadow-lg shadow-slate-200 disabled:opacity-50 disabled:cursor-not-allowed",children:"Abrir PDF"}),e.jsx("button",{onClick:gr,disabled:Xt||!I||I.status!=="completed",className:`px-6 py-3 rounded-xl font-bold transition-colors disabled:opacity-60 disabled:cursor-not-allowed ${Ne?"bg-teal-600 text-white hover:bg-teal-700 shadow-lg shadow-teal-200":"border border-gray-200 text-gray-700 hover:bg-gray-50"}`,children:Xt?"Salvando...":Ne?"Salvar e encerrar chamada":"Salvar evolução"})]})]})})}),tr&&e.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4",children:e.jsxs(he.div,{initial:{opacity:0,scale:.9}
2,animate:{opacity:1,scale:1},className:"bg-white rounded-2xl shadow-2xl max-w-sm w-full p-6 text-center",children:[e.jsx(ge,{size:48,className:"mx-auto mb-4 text-red-500"}),e.jsx("h3",{className:"text-xl font-bold text-slate-800 mb-2",children:"Limpar Transcrição?"}),e.jsx("p",{className:"text-gray-600 mb-6 text-sm",children:"Tem certeza que deseja apagar todo o histórico desta transcrição? Esta ação não pode ser desfeita."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>as(!1),className:"flex-1 py-3 rounded-xl border border-gray-200 text-gray-600 font-bold hover:bg-gray-50 transition-colors",children:"Cancelar"}),e.jsx("button",{onClick:vr,className:"flex-1 py-3 rounded-xl bg-red-500 text-white font-bold hover:bg-red-600 transition-colors shadow-lg shadow-red-200",children:"Sim, Limpar"})]})]})}),za&&e.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4",children:e.jsxs(he.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"bg-white rounded-2xl shadow-2xl max-w-md w-full p-6",children:[e.jsx("h3",{className:"text-xl font-bold text-slate-800 mb-4",children:"Finalizar Consulta"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"Como deseja registrar esta consulta?"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>na("completed"),disabled:Yt,className:"w-full p-4 bg-green-50 text-green-700 border border-green-200 rounded-xl hover:bg-green-100 font-bold flex items-center justify-center gap-2 transition-colors disabled:opacity-60",children:[e.jsx(Mt,{size:20}),Yt?"Finalizando...":"Consulta Realizada com Sucesso"]}),e.jsxs("button",{onClick:()=>na("no_show"),className:"w-full p-4 bg-red-50 text-red-700 border border-red-200 rounded-xl hover:bg-red-100 font-bold flex items-center justify-center gap-2 transition-colors",children:[e.jsx(Ge,{size:20}),"Paciente Faltou (No-Show)"]})]}),e.jsx("button",{onClick:()=>gt(!1),className:"w-full mt-4 p-2 text-gray-500 hover:text-gray-700 font-medium",children:"Cancelar"})]})}),pe&&e.jsx("div",{className:"fixed inset-0 bg-black/80 backdrop-blur-md z-[60] flex items-center justify-center p-4",children:e.jsx(he.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"bg-white rounded-2xl shadow-2xl max-w-md w-full p-8 text-center",children:fe?e.jsxs("div",{className:"py-8",children:[e.jsx("div",{className:"w-20 h-20 bg-green-100 text-green-600 rounded-full flex items-center justify-center mx-auto mb-6 animate-bounce",children:e.jsx(Mt,{size:40})}),e.jsx("h3",{className:"text-2xl font-bold text-gray-800 mb-2",children:"Obrigado!"}),e.jsx("p",{className:"text-gray-500",children:"Sua avaliação foi registrada com sucesso."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 bg-blue-50 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(ha,{size:32,fill:"currentColor",className:"text-blue-600"})}),e.jsx("h3",{className:"text-2xl font-bold text-gray-800 mb-2",children:"Como foi sua consulta?"}),e.jsx("p",{className:"text-gray-500 mb-8",children:"Sua avaliação é muito importante para melhorarmos nosso atendimento."}),e.jsx("div",{className:"flex justify-center gap-2 mb-8",children:[1,2,3,4,5].map(t=>e.jsx("button",{onClick:()=>La(t),className:"p-2 transition-transform hover:scale-110 focus:outline-none",children:e.jsx(ha,{size:36,className:`${Ye>=t?"text-yellow-400 fill-yellow-400":"text-gray-200 fill-gray-100"}`})},t))}),e.jsx("textarea",{value:es,onChange:t=>Aa(t.target.value),placeholder:"Deixe um comentário (opcional)...",className:"w-full p-4 bg-gray-50 border border-gray-200 rounded-xl mb-6 text-sm focus:ring-2 focus:ring-blue-200 outline-none resize-none",rows:3}),e.jsx(Vt,{onClick:mr,disabled:Ye===0,className:"w-full py-4 text-lg shadow-xl shadow-blue-200",children:"Enviar Avaliação"}),(u==null?void 0:u.status)!=="completed"&&e.jsx("button",{onClick:sa,className:"mt-4 w-full py-3 text-blue-600 font-bold hover:bg-blue-50 rounded-xl transition-colors",children:"Voltar para a chamada"}),e.jsx("button",{onClick:()=>V(),className:"mt-2 text-sm text-gray-400 hover:text-gray-600",children:"Pular avaliação"})]})})}),qa&&e.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-[70] flex items-center justify-center p-4",children:e.jsxs(he.div,{initial:{opacity:0,scale:.9}
2,animate:{opacity:1,scale:1},className:"bg-white rounded-2xl shadow-2xl max-w-md w-full p-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-6",children:[e.jsxs("h3",{className:"text-xl font-bold text-slate-800 flex items-center gap-2",children:[e.jsx(fa,{size:22,className:"text-gray-600"}),"Configurações"]}),e.jsx("button",{onClick:()=>ts(!1),className:"text-gray-400 hover:text-gray-600",children:e.jsx(Ge,{size:24})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm font-bold text-slate-700 mb-2",children:[e.jsx(Ot,{size:16})," Microfone"]}),e.jsx("select",{className:"w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500",value:_e,onChange:t=>Ya(t.target.value),children:Wa.map(t=>e.jsx("option",{value:t.deviceId,children:t.label||`Microfone ${t.deviceId.slice(0,5)}...`},t.deviceId))}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx("div",{className:"text-xs text-gray-500 w-12",children:"NÃvel"}),e.jsx("div",{className:"flex-1 h-2 bg-gray-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-green-500 transition-all duration-75",style:{width:`${Math.min(100,ta*2)}%`}})})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm font-bold text-slate-700 mb-2",children:[e.jsx(gs,{size:16})," Câmera"]}),e.jsx("select",{className:"w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500",value:Te,onChange:t=>Za(t.target.value),children:Ja.map(t=>e.jsx("option",{value:t.deviceId,children:t.label||`Câmera ${t.deviceId.slice(0,5)}...`},t.deviceId))})]}),Vs.length>0&&e.jsxs("div",{children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm font-bold text-slate-700 mb-2",children:[e.jsx(Wr,{size:16})," SaÃda de Ãudio"]}),e.jsx("select",{className:"w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500",value:Ka,onChange:t=>{Xa(t.target.value);const s=document.querySelector("audio");s&&s.setSinkId&&s.setSinkId(t.target.value)},children:Vs.map(t=>e.jsx("option",{value:t.deviceId,children:t.label||`Alto-falante ${t.deviceId.slice(0,5)}...`},t.deviceId))})]}),e.jsxs("div",{className:"bg-blue-50 p-4 rounded-xl text-blue-800 text-xs leading-relaxed",children:[e.jsxs("p",{className:"font-bold flex items-center gap-2 mb-1",children:[e.jsx(ge,{size:14})," Dica de Ãudio"]}),"Caso o volume esteja baixo, tente selecionar outro microfone na lista acima ou aproxime-se do dispositivo. O sistema ajusta o volume automaticamente."]})]}),e.jsx("div",{className:"mt-8",children:e.jsx("button",{onClick:()=>ts(!1),className:"w-full py-3 bg-blue-600 text-white font-bold rounded-xl hover:bg-blue-700 transition-colors",children:"ConcluÃdo"})})]})}),e.jsx(en,{open:Ua,appointmentHash:c,onClose:()=>Fs(!1)}),o==="doctor"&&c&&e.jsx(Yr,{appointmentHash:c,transcript:Ae.map(t=>`${t.speaker_type==="professional"?"Médico":"Paciente"}: ${t.text}`).join(` 3`),className:G==="chat"&&us?"hidden":""})]})},_n=Object.freeze(Object.defineProperty({__proto__:null,VideoConsultation:un},Symbol.toStringTag,{value:"Module"}));export{Kr as M,un as V,_n as a,At as m,Ft as p};
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.