@clara.care/react 1.0.6 → 1.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/clara-widget.cjs.js +1 -1
- package/clara-widget.es.js +1 -1
- package/package.json +2 -2
package/clara-widget.cjs.js
CHANGED
|
@@ -404,7 +404,7 @@ INSTRUCCIONES:
|
|
|
404
404
|
|
|
405
405
|
GENERA EL JSON:`;n({phase:"generating",percentage:50,message:"Generando template completo con IA..."});const d=(await o.models.generateContent({model:"gemini-2.5-pro",contents:l+`
|
|
406
406
|
|
|
407
|
-
`+u,config:{temperature:.2,maxOutputTokens:16384}})).text||"";console.log("[TemplateGenerator] AI Response length:",d.length),console.log("[TemplateGenerator] AI Response:",d),n({phase:"generating",percentage:70,message:"Procesando respuesta..."});let p=null;if(p=(g=>{try{return JSON.parse(g)}catch{}const C=g.match(/```(?:json)?\s*([\s\S]*?)\s*```/);if(C&&C[1])try{return JSON.parse(C[1].trim())}catch{}const E=g.indexOf("{");if(E!==-1){let B=g.slice(E),_=0,M=0,D=!1,L=!1;for(let N=0;N<B.length;N++){const F=B[N];if(L){L=!1;continue}if(F==="\\"){L=!0;continue}if(F==='"'){D=!D;continue}D||(F==="{"&&_++,F==="}"&&_--,F==="["&&M++,F==="]"&&M--)}D&&(B+='"'),B=B.replace(/,\s*"[^"]*":\s*"[^"]*$/,"").replace(/,\s*"[^"]*":\s*$/,"").replace(/,\s*"[^"]*$/,"").replace(/,\s*\{[^}]*$/,"").replace(/,\s*$/,""),B+="]".repeat(Math.max(0,M)),B+="}".repeat(Math.max(0,_)),B=B.replace(/,\s*}/g,"}").replace(/,\s*]/g,"]");try{return JSON.parse(B)}catch(N){console.warn("[TemplateGenerator] JSON repair failed:",N)}}return null})(d),!p)throw console.error("[TemplateGenerator] All JSON extraction strategies failed"),new Error("No se pudo parsear la respuesta de la IA. El JSON estaba incompleto o malformado.");console.log("[TemplateGenerator] Parsed response:",p);const m=((e=p.structure)==null?void 0:e.sections)||p.sections||[],P=p.name||p.templateName||p.formName||"Template Generado",T=p.description||p.templateDescription||"Generado automáticamente",x=m.map(g=>{var C;return{key:g.key||((C=g.label)==null?void 0:C.toLowerCase().replace(/\s+/g,"_"))||"section",label:g.label||"Sección",enabled:g.enabled!==!1,fields:(g.fields||[]).map(E=>({id:E.id||E.htmlFieldId,htmlFieldId:E.htmlFieldId||E.id,label:E.label||E.id||"Campo",type:E.type||"text",...E.options&&{options:E.options}}))}}),y=x.reduce((g,C)=>{var E;return g+(((E=C.fields)==null?void 0:E.length)||0)},0),S={name:P,description:T,structure:{sections:x}};return console.log("[TemplateGenerator] Final template:",{name:S.name,sectionsCount:S.structure.sections.length,fieldsCount:y}),n({phase:"complete",percentage:100,message:`Template generado: ${S.structure.sections.length} secciones, ${y} campos`}),S}catch(i){return console.error("[TemplateGenerator] Error:",i),n({phase:"error",percentage:0,message:i instanceof Error?i.message:"Error desconocido"}),null}}const DEMO_TEMPLATE_IDS={audiometria:"a0785251-eb3a-4d6c-8224-10a8c6acfd12",odontologia:"fe2085fd-5f19-44e9-b04c-92e0f0ab7769"},API_BASE_URL="https://ncifcjxnmyjfracfzwrl.supabase.co/functions/v1/api";let demoTemplatesCache={};function isValidApiKey(n){return!!n&&n.length>=20}function getAuthHeaders(n,e){const i={"Content-Type":"application/json"};if(isValidApiKey(n))i["X-API-Key"]=n;else if(e&&e.length>20)i.Authorization=`Bearer ${e}`;else if(isValidApiKey(claraApi.getApiKey()))i["X-API-Key"]=claraApi.getApiKey();else if(claraApi.getAccessToken()&&claraApi.getAccessToken().length>20)i.Authorization=`Bearer ${claraApi.getAccessToken()}`;else return null;return i}async function fetchTemplateById(n,e,i){try{const a=getAuthHeaders(e,i);if(!a)return console.log("[DemoTemplates] No valid authentication available, skipping fetch"),null;const s=`${API_BASE_URL}/templates`;console.log("[DemoTemplates] Fetching templates to find:",n);const r=await fetch(s,{method:"GET",headers:a});if(!r.ok)return console.error("[DemoTemplates] Failed to fetch templates:",r.status),null;const o=await r.json(),u=(o.data||o).find(c=>c.id===n);return u?(console.log("[DemoTemplates] Found template:",u.name),u):(console.warn("[DemoTemplates] Template not found:",n),null)}catch(a){return console.error("[DemoTemplates] Error fetching template:",a),null}}async function getDemoTemplate(n,e,i){if(demoTemplatesCache[n])return console.log("[DemoTemplates] Returning cached template:",n),demoTemplatesCache[n];const a=DEMO_TEMPLATE_IDS[n],s=await fetchTemplateById(a,e,i);return s&&(demoTemplatesCache[n]=s,console.log("[DemoTemplates] Cached template:",n,s.name)),s}function dispatchClaraEvent(n,e){console.log(`[Clara Event] ${n}`,e),window.dispatchEvent(new CustomEvent(n,{detail:e}))}function emitFieldFilled(n,e,i){dispatchClaraEvent("clara:field-filled",{fieldName:n,value:e,sectionKey:i,timestamp:new Date().toISOString()})}function emitFormDataUpdated(n,e,i){dispatchClaraEvent("clara:formdata-updated",{formData:{...n},changedField:e,changedFields:i,timestamp:new Date().toISOString()})}function emitTranscriptUpdated(n,e,i){dispatchClaraEvent("clara:transcript-updated",{role:n,content:e,messages:i,timestamp:new Date().toISOString()})}function emitTitleUpdated(n,e){dispatchClaraEvent("clara:title-updated",{title:n,analysisId:e,timestamp:new Date().toISOString()})}function emitTemplateChanged(n,e,i){dispatchClaraEvent("clara:template-changed",{templateId:n,templateName:e,sections:i,timestamp:new Date().toISOString()})}function emitSessionStarted(n){dispatchClaraEvent("clara:session-started",{analysisId:n,timestamp:new Date().toISOString()})}function emitOdontogramCleared(n,e){dispatchClaraEvent("clara:odontogram-cleared",{fieldId:n,teeth:e,timestamp:new Date().toISOString()})}function emitOdontogramUpdated(n,e){dispatchClaraEvent("clara:odontogram-updated",{fieldId:n,teeth:e,timestamp:new Date().toISOString()})}function emitSessionStopped(n){dispatchClaraEvent("clara:session-stopped",{analysisId:n,timestamp:new Date().toISOString()})}const ClaraDashboard=({onStartSession:n,onLogout:e,primaryColor:i})=>{const{config:a,accessToken:s,templates:r,currentTemplate:o,formData:l,userProfile:u,remoteSessionActive:c,remoteSessionInfo:d,setTemplates:p,setCurrentTemplate:f,setUserProfile:m}=useClaraStore(),P=a.lang||"es",T=!!a.templateId,[x,y]=React.useState("consulta"),[S,g]=React.useState(!1),[C,E]=React.useState(!1),[B,_]=React.useState(!1),[M,D]=React.useState(!1),[L,N]=React.useState(!1),[F,H]=React.useState(null),[$,O]=React.useState(null);o!=null&&o.name||a.templateId||t("dashboard.selectTemplate",P),React.useEffect(()=>{(async()=>{var R,G,z,q;if(!claraApi.hasAuth())if(a.apiKey)claraApi.setApiKey(a.apiKey);else if(s)claraApi.setAccessToken(s);else{console.log("[Dashboard] No auth available, loading demo template from API"),_(!0);try{const U=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);U&&(f(U),console.log("[Dashboard] Loaded demo template:",U.name))}catch(U){console.error("[Dashboard] Error loading demo template:",U)}finally{_(!1)}return}_(!0);try{const U=await claraApi.fetchUserProfile();console.log("[Dashboard] Raw profile response:",JSON.stringify(U,null,2)),U&&(m(U),console.log("[Dashboard] User profile settings:",U.settings));const K=await claraApi.fetchTemplates();if(K&&K.length>0){p(K),console.log("[Dashboard] Templates loaded:",K.length);const Q=a.templateId||((R=U==null?void 0:U.settings)==null?void 0:R.selectedTemplateId);if(console.log("[Dashboard] Template selection - config:",a.templateId,"settings:",(G=U==null?void 0:U.settings)==null?void 0:G.selectedTemplateId,"using:",Q),Q){const ne=K.find(Ee=>Ee.id===Q);if(ne)f(ne),console.log("[Dashboard] Selected template:",ne.name);else{console.log("[Dashboard] Template not found:",Q,"loading demo template from API");const Ee=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);Ee&&f(Ee)}}else{const ne=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);ne&&(f(ne),console.log("[Dashboard] No template configured, using demo:",ne.name))}}else{console.log("[Dashboard] No templates from API, loading demo template");const Q=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);Q&&f(Q)}}catch(U){console.error("[Dashboard] Error loading data:",U),((z=U==null?void 0:U.message)!=null&&z.includes("401")||(q=U==null?void 0:U.message)!=null&&q.toLowerCase().includes("invalid api key"))&&D(!0),console.log("[Dashboard] Falling back to demo template due to error");try{const K=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);K&&f(K)}catch(K){console.error("[Dashboard] Failed to load fallback demo template:",K)}}finally{_(!1)}})()},[a.apiKey,a.templateId,a.demoTemplate,s,p,f,m]),React.useEffect(()=>{!a.templateId&&!a.apiKey&&(async()=>{_(!0);try{const R=await getDemoTemplate(a.demoTemplate);R&&(f(R),console.log("[Dashboard] Demo template changed to:",R.name))}catch(R){console.error("[Dashboard] Error loading demo template:",R)}finally{_(!1)}})()},[a.demoTemplate]);const b=async()=>{N(!0),O(null),H({phase:"analyzing",percentage:0,message:"Iniciando..."});const k=await generateTemplateFromPage(R=>{H(R)});k&&(O(k),await I(k))},I=async k=>{console.log("[Dashboard] Saving generated template:",k),H({phase:"saving",percentage:90,message:"Guardando template..."});try{const R={name:k.name||"Template Generado",description:k.description||"Generado automáticamente desde la página",structure:k.structure};console.log("[Dashboard] Template payload:",R);const G=await claraApi.createTemplate(R);if(console.log("[Dashboard] Saved template response:",G),G)p([...r,G]),f(G),H({phase:"complete",percentage:100,message:"Template guardado exitosamente"}),setTimeout(()=>{N(!1),H(null),O(null)},1500);else throw new Error("No se pudo guardar el template")}catch(R){console.error("[Dashboard] Error saving template:",R),H({phase:"error",percentage:0,message:R instanceof Error?R.message:"Error al guardar"})}},V=()=>{switch(x){case"consulta":const k=B,R=!k&&!!o&&!c;return jsxRuntime.jsxs(motion.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:[c&&d&&jsxRuntime.jsxs(motion.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"mb-4 p-3 rounded-lg bg-amber-500/10 border border-amber-500/30 w-full max-w-xs",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2 text-amber-600",children:[jsxRuntime.jsx(Radio,{className:"w-4 h-4 animate-pulse"}),jsxRuntime.jsx("span",{className:"text-xs font-medium",children:"Consulta en proceso"})]}),jsxRuntime.jsx("p",{className:"text-[10px] text-amber-600/80 mt-1",children:d.templateName||"Otra sesión está activa"})]}),jsxRuntime.jsx("div",{className:"mb-5 relative",children:jsxRuntime.jsxs("div",{className:"w-24 h-24 rounded-full bg-secondary flex items-center justify-center shadow-inner relative",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center z-10 opacity-10",style:{backgroundColor:i}}),jsxRuntime.jsx("div",{className:"absolute z-20",children:jsxRuntime.jsx(Mic,{className:"w-8 h-8",style:{color:c?"#d97706":i}})}),jsxRuntime.jsx("div",{className:"absolute inset-0 rounded-full animate-pulse-ring opacity-20",style:{backgroundColor:c?"#d97706":i}})]})}),jsxRuntime.jsx("h3",{className:"text-foreground text-base font-semibold mb-1",children:t(c?"session.recording":"dashboard.newConsultation",P)}),jsxRuntime.jsx("p",{className:"text-muted-foreground text-xs mb-6 px-4",children:k?t("common.loading",P):c?t("session.recording",P):""}),jsxRuntime.jsxs("button",{onClick:n,disabled:!R,className:`w-full max-w-xs font-medium py-3 px-5 rounded-xl shadow-button flex items-center justify-center gap-2.5 transition-all mb-5 text-sm ${R?"text-white bg-clara-dark hover:brightness-110 active:scale-95":"bg-clara-dark/60 text-white/80 cursor-not-allowed"}`,children:[k?jsxRuntime.jsx(LoaderCircle,{className:"w-4 h-4 animate-spin"}):c?jsxRuntime.jsx(Radio,{className:"w-4 h-4"}):jsxRuntime.jsx(Mic,{className:"w-4 h-4"}),t(c?"session.recording":"dashboard.startSession",P)]}),!T&&jsxRuntime.jsx("div",{className:"flex items-center gap-2",children:jsxRuntime.jsxs("button",{onClick:()=>!k&&E(!0),disabled:k,className:`group flex items-center gap-2.5 bg-card border border-border px-3 py-2 rounded-lg shadow-sm transition-all ${k?"opacity-50 cursor-not-allowed":"cursor-pointer hover:border-accent"}`,children:[jsxRuntime.jsx("div",{className:"p-1 rounded-md",style:{backgroundColor:`${i}1A`,color:i},children:k?jsxRuntime.jsx(LoaderCircle,{className:"w-3.5 h-3.5 animate-spin"}):jsxRuntime.jsx(FileText,{className:"w-3.5 h-3.5"})}),jsxRuntime.jsxs("div",{className:"text-left",children:[jsxRuntime.jsx("p",{className:"text-[9px] uppercase text-muted-foreground font-bold tracking-wider",children:t("dashboard.templates",P)}),jsxRuntime.jsx("p",{className:"text-xs font-medium text-foreground truncate max-w-[100px]",children:k?t("common.loading",P):(o==null?void 0:o.name)||t("dashboard.selectTemplate",P)})]}),!k&&jsxRuntime.jsx(ChevronDown,{className:"w-3.5 h-3.5 text-muted-foreground"})]})})]});case"chat":return jsxRuntime.jsx(ClaraChat,{primaryColor:i})}},A=[{id:"consulta",label:t("dashboard.newConsultation",P),icon:Mic},{id:"chat",label:t("tabs.chat",P),icon:MessageSquare}];return jsxRuntime.jsxs("div",{className:"flex flex-col h-full bg-card relative",children:[jsxRuntime.jsxs("div",{className:"px-4 py-4 border-b border-border flex items-center justify-between bg-card z-10",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("img",{src:claraLogo,alt:"Clara",className:"h-5 w-auto"}),jsxRuntime.jsx("span",{className:"text-[9px] text-muted-foreground font-medium uppercase tracking-wider ml-1",children:"WIDGET"})]}),jsxRuntime.jsxs("div",{className:"relative",children:[jsxRuntime.jsx("button",{onClick:()=>g(!S),className:"text-muted-foreground hover:text-foreground p-1 rounded-full hover:bg-secondary transition-colors",children:jsxRuntime.jsx(Settings,{className:"w-4 h-4"})}),jsxRuntime.jsx(AnimatePresence,{children:S&&jsxRuntime.jsxs(motion.div,{initial:{opacity:0,scale:.95,y:-10},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:-10},className:"absolute right-0 mt-2 w-44 bg-card rounded-lg shadow-widget border border-border py-1 z-50",children:[!T&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("button",{onClick:()=>{E(!0),g(!1)},className:"w-full text-left px-3 py-2 text-xs text-foreground hover:bg-secondary flex items-center gap-2 transition-colors",children:[jsxRuntime.jsx(FileText,{className:"w-3.5 h-3.5"}),t("dashboard.templates",P)]}),jsxRuntime.jsxs("button",{onClick:()=>{b(),g(!1)},className:"w-full text-left px-3 py-2 text-xs text-foreground hover:bg-secondary flex items-center gap-2 transition-colors",children:[jsxRuntime.jsx(Sparkles,{className:"w-3.5 h-3.5"}),t("dashboard.generate",P)]})]}),jsxRuntime.jsxs("a",{href:"https://clara.care",target:"_blank",rel:"noreferrer",className:"w-full text-left px-3 py-2 text-xs text-foreground hover:bg-secondary flex items-center gap-2 transition-colors",children:[jsxRuntime.jsx(ExternalLink,{className:"w-3.5 h-3.5"}),"Ir a Clara.care"]}),jsxRuntime.jsx("div",{className:"border-t border-border my-1"}),jsxRuntime.jsxs("button",{onClick:e,className:"w-full text-left px-3 py-2 text-xs text-destructive hover:bg-destructive/10 flex items-center gap-2 transition-colors",children:[jsxRuntime.jsx(LogOut,{className:"w-3.5 h-3.5"}),t("dashboard.logout",P)]})]})})]})]}),x!=="consulta"&&jsxRuntime.jsx("div",{className:"px-3 mt-4 mb-2",children:jsxRuntime.jsx("div",{className:"bg-clara-dark text-white p-0.5 rounded-lg flex items-center justify-between shadow-lg",children:A.map(k=>jsxRuntime.jsxs("button",{onClick:()=>y(k.id),className:`flex-1 py-1.5 text-xs font-medium rounded-md flex items-center justify-center gap-1.5 transition-all ${x===k.id?"bg-card text-foreground shadow-sm":"text-gray-400 hover:text-white"}`,children:[jsxRuntime.jsx(k.icon,{className:"w-3.5 h-3.5"}),k.label]},k.id))})}),jsxRuntime.jsx("div",{className:"flex-1 overflow-hidden flex flex-col",children:V()}),jsxRuntime.jsx(AnimatePresence,{children:C&&jsxRuntime.jsx(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-50 flex items-center justify-center bg-foreground/50 p-3",children:jsxRuntime.jsxs(motion.div,{initial:{scale:.95,y:20},animate:{scale:1,y:0},exit:{scale:.95,y:20},className:"bg-card rounded-xl w-full h-[80%] flex flex-col shadow-widget overflow-hidden",children:[jsxRuntime.jsxs("div",{className:"p-3 border-b border-border flex justify-between items-center bg-secondary",children:[jsxRuntime.jsx("h3",{className:"font-bold text-sm text-foreground",children:t("dashboard.templates",P)}),jsxRuntime.jsx("button",{onClick:()=>E(!1),className:"p-1 rounded-full hover:bg-muted text-muted-foreground transition-colors",children:jsxRuntime.jsx(X,{className:"w-4 h-4"})})]}),jsxRuntime.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:B?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8",children:jsxRuntime.jsx(LoaderCircle,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):r.length===0?jsxRuntime.jsx("div",{className:"text-center py-8 text-muted-foreground text-sm",children:"No hay plantillas disponibles"}):r.map(k=>{const R=(o==null?void 0:o.id)===k.id;return jsxRuntime.jsxs("button",{onClick:async()=>{var G;f(k),emitTemplateChanged(k.id,k.name,((G=k.structure)==null?void 0:G.sections)||[]),E(!1),await claraApi.updateUserSettings({selectedTemplateId:k.id})},className:`w-full p-3 border rounded-lg cursor-pointer transition-all flex justify-between items-center ${R?"shadow-sm":"border-border hover:bg-secondary"}`,style:R?{borderColor:i,backgroundColor:`${i}0D`}:{},children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2.5",children:[jsxRuntime.jsx("div",{className:`w-7 h-7 rounded-full flex items-center justify-center ${R?"text-white":"bg-secondary text-muted-foreground"}`,style:R?{backgroundColor:i}:{},children:jsxRuntime.jsx(FileText,{className:"w-3.5 h-3.5"})}),jsxRuntime.jsxs("div",{className:"text-left",children:[jsxRuntime.jsx("span",{className:`font-medium text-xs block ${R?"":"text-foreground"}`,style:R?{color:i}:{},children:k.name}),k.description&&jsxRuntime.jsx("span",{className:"text-[10px] text-muted-foreground line-clamp-1",children:k.description})]})]}),R&&jsxRuntime.jsx(Check,{className:"w-4 h-4",style:{color:i}})]},k.id)})})]})})}),jsxRuntime.jsx(AnimatePresence,{children:M&&jsxRuntime.jsx(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-50 flex items-center justify-center bg-foreground/50 p-4",children:jsxRuntime.jsx(motion.div,{initial:{scale:.95,y:20},animate:{scale:1,y:0},exit:{scale:.95,y:20},className:"bg-card rounded-xl w-full max-w-xs shadow-widget overflow-hidden",children:jsxRuntime.jsxs("div",{className:"p-5 flex flex-col items-center text-center",children:[jsxRuntime.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center mb-4",children:jsxRuntime.jsx(TriangleAlert,{className:"w-6 h-6 text-destructive"})}),jsxRuntime.jsx("h3",{className:"font-bold text-base text-foreground mb-2",children:"API Key Inválida"}),jsxRuntime.jsx("p",{className:"text-muted-foreground text-sm mb-5",children:"La API Key proporcionada no es válida o ha expirado. Por favor verifica tu configuración."}),jsxRuntime.jsx("button",{onClick:()=>{D(!1),e()},className:"w-full py-2.5 px-4 rounded-lg bg-destructive text-white font-medium text-sm hover:brightness-110 transition-all",children:"Cerrar y Reintentar"})]})})})}),jsxRuntime.jsx(AnimatePresence,{children:L&&jsxRuntime.jsx(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-50 flex items-center justify-center bg-foreground/50 p-4",children:jsxRuntime.jsxs(motion.div,{initial:{scale:.95,y:20},animate:{scale:1,y:0},exit:{scale:.95,y:20},className:"bg-card rounded-xl w-full max-w-xs shadow-widget overflow-hidden relative",children:[jsxRuntime.jsx("button",{onClick:()=>{N(!1),H(null),O(null)},className:"absolute top-3 right-3 p-1 rounded-full hover:bg-secondary text-muted-foreground transition-colors z-10",children:jsxRuntime.jsx(X,{className:"w-4 h-4"})}),jsxRuntime.jsxs("div",{className:"p-5 flex flex-col items-center text-center",children:[(F==null?void 0:F.phase)==="complete"?jsxRuntime.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mb-4",style:{backgroundColor:`${i}20`},children:jsxRuntime.jsx(Check,{className:"w-8 h-8",style:{color:i}})}):(F==null?void 0:F.phase)==="error"?jsxRuntime.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mb-4 bg-destructive/20",children:jsxRuntime.jsx(TriangleAlert,{className:"w-8 h-8 text-destructive"})}):jsxRuntime.jsx("div",{className:"w-24 h-24 mb-2",children:jsxRuntime.jsx(Lottie,{animationData:aiGeneratingAnimation,loop:!0,style:{width:"100%",height:"100%"}})}),jsxRuntime.jsx("h3",{className:"font-bold text-base text-foreground mb-2",children:(F==null?void 0:F.phase)==="complete"?t("generate.complete",P):(F==null?void 0:F.phase)==="error"?t("common.error",P):t("generate.title",P)}),F&&F.phase!=="error"&&jsxRuntime.jsxs("div",{className:"w-full mb-3",children:[jsxRuntime.jsx("div",{className:"h-2 bg-secondary rounded-full overflow-hidden",children:jsxRuntime.jsx(motion.div,{className:"h-full rounded-full",style:{backgroundColor:i},initial:{width:0},animate:{width:`${F.percentage}%`},transition:{duration:.3}})}),jsxRuntime.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[F.percentage,"%"]})]}),jsxRuntime.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:(F==null?void 0:F.message)||t("generate.analyzing",P)}),$&&(F==null?void 0:F.phase)!=="saving"&&(F==null?void 0:F.phase)!=="complete"&&jsxRuntime.jsxs("div",{className:"w-full text-left mb-4 p-3 bg-secondary rounded-lg",children:[jsxRuntime.jsx("p",{className:"text-xs font-semibold text-foreground mb-1",children:$.name}),jsxRuntime.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[$.structure.sections.length," ",t("generate.sections",P),", "," ",$.structure.sections.reduce((k,R)=>k+R.fields.length,0)," ",t("generate.fields",P)]})]}),jsxRuntime.jsx("div",{className:"flex gap-2 w-full",children:(F==null?void 0:F.phase)==="error"?jsxRuntime.jsx("button",{onClick:()=>{N(!1),H(null),O(null)},className:"w-full py-2.5 px-4 rounded-lg bg-secondary text-foreground font-medium text-sm hover:bg-muted transition-all",children:t("common.close",P)}):(F==null?void 0:F.phase)==="complete"||(F==null?void 0:F.phase)==="saving"?null:jsxRuntime.jsx("button",{onClick:()=>{N(!1),H(null),O(null)},className:"w-full py-2.5 px-4 rounded-lg bg-secondary text-foreground font-medium text-sm hover:bg-muted transition-all",children:t("common.cancel",P)})})]})]})})})]})};var ViewState=(n=>(n.LOGIN="login",n.DASHBOARD="dashboard",n.SESSION="session",n))(ViewState||{}),SessionStatus=(n=>(n.CONNECTING="connecting",n.ACTIVE="active",n.PAUSED="paused",n.DISCONNECTED="disconnected",n.ERROR="error",n))(SessionStatus||{});function floatTo16BitPCM(n){const e=new ArrayBuffer(n.length*2),i=new DataView(e);let a=0;for(let s=0;s<n.length;s++,a+=2){let r=Math.max(-1,Math.min(1,n[s]));i.setInt16(a,r<0?r*32768:r*32767,!0)}return e}function arrayBufferToBase64(n){let e="";const i=new Uint8Array(n),a=i.byteLength;for(let s=0;s<a;s++)e+=String.fromCharCode(i[s]);return btoa(e)}function float32To16BitPCMBase64(n){return arrayBufferToBase64(floatTo16BitPCM(n))}function downsampleBuffer(n,e,i=16e3){if(e===i||e<i)return n;const a=e/i,s=Math.floor(n.length/a),r=new Float32Array(s);let o=0,l=0;for(;o<r.length;){const u=Math.round((o+1)*a);let c=0,d=0;for(let p=Math.round(l);p<u&&p<n.length;p++)c+=n[p],d++;r[o]=d>0?c/d:0,o++,l=u}return r}const surfaceToArea=n=>{if(!n)return 0;switch(n.toLowerCase()){case"whole":case"completo":return 0;case"vestibular":case"bucal":case"top":return 1;case"lingual":case"palatal":case"palatino":case"bottom":return 2;case"mesial":case"left":return 4;case"distal":case"right":return 6;case"oclusal":case"incisal":case"center":return 7;default:return 7}},extractJson=n=>{if(n!==null&&typeof n=="object")return n;if(typeof n!="string"||!n.trim())return null;const e=n.trim();try{return JSON.parse(e)}catch{}try{const i=e.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,"").trim();if(i!==e)return JSON.parse(i)}catch{}try{const i=e.match(/\{[\s\S]*\}/);if(i)return JSON.parse(i[0])}catch{}try{const i=e.match(/\[[\s\S]*\]/);if(i)return JSON.parse(i[0])}catch{}try{const i=e.replace(/\\"/g,'"').replace(/\\n/g,`
|
|
407
|
+
`+u,config:{temperature:.2,maxOutputTokens:16384}})).text||"";console.log("[TemplateGenerator] AI Response length:",d.length),console.log("[TemplateGenerator] AI Response:",d),n({phase:"generating",percentage:70,message:"Procesando respuesta..."});let p=null;if(p=(g=>{try{return JSON.parse(g)}catch{}const C=g.match(/```(?:json)?\s*([\s\S]*?)\s*```/);if(C&&C[1])try{return JSON.parse(C[1].trim())}catch{}const E=g.indexOf("{");if(E!==-1){let B=g.slice(E),_=0,M=0,D=!1,L=!1;for(let N=0;N<B.length;N++){const F=B[N];if(L){L=!1;continue}if(F==="\\"){L=!0;continue}if(F==='"'){D=!D;continue}D||(F==="{"&&_++,F==="}"&&_--,F==="["&&M++,F==="]"&&M--)}D&&(B+='"'),B=B.replace(/,\s*"[^"]*":\s*"[^"]*$/,"").replace(/,\s*"[^"]*":\s*$/,"").replace(/,\s*"[^"]*$/,"").replace(/,\s*\{[^}]*$/,"").replace(/,\s*$/,""),B+="]".repeat(Math.max(0,M)),B+="}".repeat(Math.max(0,_)),B=B.replace(/,\s*}/g,"}").replace(/,\s*]/g,"]");try{return JSON.parse(B)}catch(N){console.warn("[TemplateGenerator] JSON repair failed:",N)}}return null})(d),!p)throw console.error("[TemplateGenerator] All JSON extraction strategies failed"),new Error("No se pudo parsear la respuesta de la IA. El JSON estaba incompleto o malformado.");console.log("[TemplateGenerator] Parsed response:",p);const m=((e=p.structure)==null?void 0:e.sections)||p.sections||[],P=p.name||p.templateName||p.formName||"Template Generado",T=p.description||p.templateDescription||"Generado automáticamente",x=m.map(g=>{var C;return{key:g.key||((C=g.label)==null?void 0:C.toLowerCase().replace(/\s+/g,"_"))||"section",label:g.label||"Sección",enabled:g.enabled!==!1,fields:(g.fields||[]).map(E=>({id:E.id||E.htmlFieldId,htmlFieldId:E.htmlFieldId||E.id,label:E.label||E.id||"Campo",type:E.type||"text",...E.options&&{options:E.options}}))}}),y=x.reduce((g,C)=>{var E;return g+(((E=C.fields)==null?void 0:E.length)||0)},0),S={name:P,description:T,structure:{sections:x}};return console.log("[TemplateGenerator] Final template:",{name:S.name,sectionsCount:S.structure.sections.length,fieldsCount:y}),n({phase:"complete",percentage:100,message:`Template generado: ${S.structure.sections.length} secciones, ${y} campos`}),S}catch(i){return console.error("[TemplateGenerator] Error:",i),n({phase:"error",percentage:0,message:i instanceof Error?i.message:"Error desconocido"}),null}}const DEMO_TEMPLATE_IDS={audiometria:"a0785251-eb3a-4d6c-8224-10a8c6acfd12",odontologia:"fe2085fd-5f19-44e9-b04c-92e0f0ab7769"},API_BASE_URL="https://mahjxdopacmbyqewgxpx.supabase.co/functions/v1/api";let demoTemplatesCache={};function isValidApiKey(n){return!!n&&n.length>=20}function getAuthHeaders(n,e){const i={"Content-Type":"application/json"};if(isValidApiKey(n))i["X-API-Key"]=n;else if(e&&e.length>20)i.Authorization=`Bearer ${e}`;else if(isValidApiKey(claraApi.getApiKey()))i["X-API-Key"]=claraApi.getApiKey();else if(claraApi.getAccessToken()&&claraApi.getAccessToken().length>20)i.Authorization=`Bearer ${claraApi.getAccessToken()}`;else return null;return i}async function fetchTemplateById(n,e,i){try{const a=getAuthHeaders(e,i);if(!a)return console.log("[DemoTemplates] No valid authentication available, skipping fetch"),null;const s=`${API_BASE_URL}/templates`;console.log("[DemoTemplates] Fetching templates to find:",n);const r=await fetch(s,{method:"GET",headers:a});if(!r.ok)return console.error("[DemoTemplates] Failed to fetch templates:",r.status),null;const o=await r.json(),u=(o.data||o).find(c=>c.id===n);return u?(console.log("[DemoTemplates] Found template:",u.name),u):(console.warn("[DemoTemplates] Template not found:",n),null)}catch(a){return console.error("[DemoTemplates] Error fetching template:",a),null}}async function getDemoTemplate(n,e,i){if(demoTemplatesCache[n])return console.log("[DemoTemplates] Returning cached template:",n),demoTemplatesCache[n];const a=DEMO_TEMPLATE_IDS[n],s=await fetchTemplateById(a,e,i);return s&&(demoTemplatesCache[n]=s,console.log("[DemoTemplates] Cached template:",n,s.name)),s}function dispatchClaraEvent(n,e){console.log(`[Clara Event] ${n}`,e),window.dispatchEvent(new CustomEvent(n,{detail:e}))}function emitFieldFilled(n,e,i){dispatchClaraEvent("clara:field-filled",{fieldName:n,value:e,sectionKey:i,timestamp:new Date().toISOString()})}function emitFormDataUpdated(n,e,i){dispatchClaraEvent("clara:formdata-updated",{formData:{...n},changedField:e,changedFields:i,timestamp:new Date().toISOString()})}function emitTranscriptUpdated(n,e,i){dispatchClaraEvent("clara:transcript-updated",{role:n,content:e,messages:i,timestamp:new Date().toISOString()})}function emitTitleUpdated(n,e){dispatchClaraEvent("clara:title-updated",{title:n,analysisId:e,timestamp:new Date().toISOString()})}function emitTemplateChanged(n,e,i){dispatchClaraEvent("clara:template-changed",{templateId:n,templateName:e,sections:i,timestamp:new Date().toISOString()})}function emitSessionStarted(n){dispatchClaraEvent("clara:session-started",{analysisId:n,timestamp:new Date().toISOString()})}function emitOdontogramCleared(n,e){dispatchClaraEvent("clara:odontogram-cleared",{fieldId:n,teeth:e,timestamp:new Date().toISOString()})}function emitOdontogramUpdated(n,e){dispatchClaraEvent("clara:odontogram-updated",{fieldId:n,teeth:e,timestamp:new Date().toISOString()})}function emitSessionStopped(n){dispatchClaraEvent("clara:session-stopped",{analysisId:n,timestamp:new Date().toISOString()})}const ClaraDashboard=({onStartSession:n,onLogout:e,primaryColor:i})=>{const{config:a,accessToken:s,templates:r,currentTemplate:o,formData:l,userProfile:u,remoteSessionActive:c,remoteSessionInfo:d,setTemplates:p,setCurrentTemplate:f,setUserProfile:m}=useClaraStore(),P=a.lang||"es",T=!!a.templateId,[x,y]=React.useState("consulta"),[S,g]=React.useState(!1),[C,E]=React.useState(!1),[B,_]=React.useState(!1),[M,D]=React.useState(!1),[L,N]=React.useState(!1),[F,H]=React.useState(null),[$,O]=React.useState(null);o!=null&&o.name||a.templateId||t("dashboard.selectTemplate",P),React.useEffect(()=>{(async()=>{var R,G,z,q;if(!claraApi.hasAuth())if(a.apiKey)claraApi.setApiKey(a.apiKey);else if(s)claraApi.setAccessToken(s);else{console.log("[Dashboard] No auth available, loading demo template from API"),_(!0);try{const U=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);U&&(f(U),console.log("[Dashboard] Loaded demo template:",U.name))}catch(U){console.error("[Dashboard] Error loading demo template:",U)}finally{_(!1)}return}_(!0);try{const U=await claraApi.fetchUserProfile();console.log("[Dashboard] Raw profile response:",JSON.stringify(U,null,2)),U&&(m(U),console.log("[Dashboard] User profile settings:",U.settings));const K=await claraApi.fetchTemplates();if(K&&K.length>0){p(K),console.log("[Dashboard] Templates loaded:",K.length);const Q=a.templateId||((R=U==null?void 0:U.settings)==null?void 0:R.selectedTemplateId);if(console.log("[Dashboard] Template selection - config:",a.templateId,"settings:",(G=U==null?void 0:U.settings)==null?void 0:G.selectedTemplateId,"using:",Q),Q){const ne=K.find(Ee=>Ee.id===Q);if(ne)f(ne),console.log("[Dashboard] Selected template:",ne.name);else{console.log("[Dashboard] Template not found:",Q,"loading demo template from API");const Ee=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);Ee&&f(Ee)}}else{const ne=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);ne&&(f(ne),console.log("[Dashboard] No template configured, using demo:",ne.name))}}else{console.log("[Dashboard] No templates from API, loading demo template");const Q=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);Q&&f(Q)}}catch(U){console.error("[Dashboard] Error loading data:",U),((z=U==null?void 0:U.message)!=null&&z.includes("401")||(q=U==null?void 0:U.message)!=null&&q.toLowerCase().includes("invalid api key"))&&D(!0),console.log("[Dashboard] Falling back to demo template due to error");try{const K=await getDemoTemplate(a.demoTemplate,a.apiKey||void 0,s||void 0);K&&f(K)}catch(K){console.error("[Dashboard] Failed to load fallback demo template:",K)}}finally{_(!1)}})()},[a.apiKey,a.templateId,a.demoTemplate,s,p,f,m]),React.useEffect(()=>{!a.templateId&&!a.apiKey&&(async()=>{_(!0);try{const R=await getDemoTemplate(a.demoTemplate);R&&(f(R),console.log("[Dashboard] Demo template changed to:",R.name))}catch(R){console.error("[Dashboard] Error loading demo template:",R)}finally{_(!1)}})()},[a.demoTemplate]);const b=async()=>{N(!0),O(null),H({phase:"analyzing",percentage:0,message:"Iniciando..."});const k=await generateTemplateFromPage(R=>{H(R)});k&&(O(k),await I(k))},I=async k=>{console.log("[Dashboard] Saving generated template:",k),H({phase:"saving",percentage:90,message:"Guardando template..."});try{const R={name:k.name||"Template Generado",description:k.description||"Generado automáticamente desde la página",structure:k.structure};console.log("[Dashboard] Template payload:",R);const G=await claraApi.createTemplate(R);if(console.log("[Dashboard] Saved template response:",G),G)p([...r,G]),f(G),H({phase:"complete",percentage:100,message:"Template guardado exitosamente"}),setTimeout(()=>{N(!1),H(null),O(null)},1500);else throw new Error("No se pudo guardar el template")}catch(R){console.error("[Dashboard] Error saving template:",R),H({phase:"error",percentage:0,message:R instanceof Error?R.message:"Error al guardar"})}},V=()=>{switch(x){case"consulta":const k=B,R=!k&&!!o&&!c;return jsxRuntime.jsxs(motion.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:[c&&d&&jsxRuntime.jsxs(motion.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"mb-4 p-3 rounded-lg bg-amber-500/10 border border-amber-500/30 w-full max-w-xs",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2 text-amber-600",children:[jsxRuntime.jsx(Radio,{className:"w-4 h-4 animate-pulse"}),jsxRuntime.jsx("span",{className:"text-xs font-medium",children:"Consulta en proceso"})]}),jsxRuntime.jsx("p",{className:"text-[10px] text-amber-600/80 mt-1",children:d.templateName||"Otra sesión está activa"})]}),jsxRuntime.jsx("div",{className:"mb-5 relative",children:jsxRuntime.jsxs("div",{className:"w-24 h-24 rounded-full bg-secondary flex items-center justify-center shadow-inner relative",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center z-10 opacity-10",style:{backgroundColor:i}}),jsxRuntime.jsx("div",{className:"absolute z-20",children:jsxRuntime.jsx(Mic,{className:"w-8 h-8",style:{color:c?"#d97706":i}})}),jsxRuntime.jsx("div",{className:"absolute inset-0 rounded-full animate-pulse-ring opacity-20",style:{backgroundColor:c?"#d97706":i}})]})}),jsxRuntime.jsx("h3",{className:"text-foreground text-base font-semibold mb-1",children:t(c?"session.recording":"dashboard.newConsultation",P)}),jsxRuntime.jsx("p",{className:"text-muted-foreground text-xs mb-6 px-4",children:k?t("common.loading",P):c?t("session.recording",P):""}),jsxRuntime.jsxs("button",{onClick:n,disabled:!R,className:`w-full max-w-xs font-medium py-3 px-5 rounded-xl shadow-button flex items-center justify-center gap-2.5 transition-all mb-5 text-sm ${R?"text-white bg-clara-dark hover:brightness-110 active:scale-95":"bg-clara-dark/60 text-white/80 cursor-not-allowed"}`,children:[k?jsxRuntime.jsx(LoaderCircle,{className:"w-4 h-4 animate-spin"}):c?jsxRuntime.jsx(Radio,{className:"w-4 h-4"}):jsxRuntime.jsx(Mic,{className:"w-4 h-4"}),t(c?"session.recording":"dashboard.startSession",P)]}),!T&&jsxRuntime.jsx("div",{className:"flex items-center gap-2",children:jsxRuntime.jsxs("button",{onClick:()=>!k&&E(!0),disabled:k,className:`group flex items-center gap-2.5 bg-card border border-border px-3 py-2 rounded-lg shadow-sm transition-all ${k?"opacity-50 cursor-not-allowed":"cursor-pointer hover:border-accent"}`,children:[jsxRuntime.jsx("div",{className:"p-1 rounded-md",style:{backgroundColor:`${i}1A`,color:i},children:k?jsxRuntime.jsx(LoaderCircle,{className:"w-3.5 h-3.5 animate-spin"}):jsxRuntime.jsx(FileText,{className:"w-3.5 h-3.5"})}),jsxRuntime.jsxs("div",{className:"text-left",children:[jsxRuntime.jsx("p",{className:"text-[9px] uppercase text-muted-foreground font-bold tracking-wider",children:t("dashboard.templates",P)}),jsxRuntime.jsx("p",{className:"text-xs font-medium text-foreground truncate max-w-[100px]",children:k?t("common.loading",P):(o==null?void 0:o.name)||t("dashboard.selectTemplate",P)})]}),!k&&jsxRuntime.jsx(ChevronDown,{className:"w-3.5 h-3.5 text-muted-foreground"})]})})]});case"chat":return jsxRuntime.jsx(ClaraChat,{primaryColor:i})}},A=[{id:"consulta",label:t("dashboard.newConsultation",P),icon:Mic},{id:"chat",label:t("tabs.chat",P),icon:MessageSquare}];return jsxRuntime.jsxs("div",{className:"flex flex-col h-full bg-card relative",children:[jsxRuntime.jsxs("div",{className:"px-4 py-4 border-b border-border flex items-center justify-between bg-card z-10",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("img",{src:claraLogo,alt:"Clara",className:"h-5 w-auto"}),jsxRuntime.jsx("span",{className:"text-[9px] text-muted-foreground font-medium uppercase tracking-wider ml-1",children:"WIDGET"})]}),jsxRuntime.jsxs("div",{className:"relative",children:[jsxRuntime.jsx("button",{onClick:()=>g(!S),className:"text-muted-foreground hover:text-foreground p-1 rounded-full hover:bg-secondary transition-colors",children:jsxRuntime.jsx(Settings,{className:"w-4 h-4"})}),jsxRuntime.jsx(AnimatePresence,{children:S&&jsxRuntime.jsxs(motion.div,{initial:{opacity:0,scale:.95,y:-10},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:-10},className:"absolute right-0 mt-2 w-44 bg-card rounded-lg shadow-widget border border-border py-1 z-50",children:[!T&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("button",{onClick:()=>{E(!0),g(!1)},className:"w-full text-left px-3 py-2 text-xs text-foreground hover:bg-secondary flex items-center gap-2 transition-colors",children:[jsxRuntime.jsx(FileText,{className:"w-3.5 h-3.5"}),t("dashboard.templates",P)]}),jsxRuntime.jsxs("button",{onClick:()=>{b(),g(!1)},className:"w-full text-left px-3 py-2 text-xs text-foreground hover:bg-secondary flex items-center gap-2 transition-colors",children:[jsxRuntime.jsx(Sparkles,{className:"w-3.5 h-3.5"}),t("dashboard.generate",P)]})]}),jsxRuntime.jsxs("a",{href:"https://clara.care",target:"_blank",rel:"noreferrer",className:"w-full text-left px-3 py-2 text-xs text-foreground hover:bg-secondary flex items-center gap-2 transition-colors",children:[jsxRuntime.jsx(ExternalLink,{className:"w-3.5 h-3.5"}),"Ir a Clara.care"]}),jsxRuntime.jsx("div",{className:"border-t border-border my-1"}),jsxRuntime.jsxs("button",{onClick:e,className:"w-full text-left px-3 py-2 text-xs text-destructive hover:bg-destructive/10 flex items-center gap-2 transition-colors",children:[jsxRuntime.jsx(LogOut,{className:"w-3.5 h-3.5"}),t("dashboard.logout",P)]})]})})]})]}),x!=="consulta"&&jsxRuntime.jsx("div",{className:"px-3 mt-4 mb-2",children:jsxRuntime.jsx("div",{className:"bg-clara-dark text-white p-0.5 rounded-lg flex items-center justify-between shadow-lg",children:A.map(k=>jsxRuntime.jsxs("button",{onClick:()=>y(k.id),className:`flex-1 py-1.5 text-xs font-medium rounded-md flex items-center justify-center gap-1.5 transition-all ${x===k.id?"bg-card text-foreground shadow-sm":"text-gray-400 hover:text-white"}`,children:[jsxRuntime.jsx(k.icon,{className:"w-3.5 h-3.5"}),k.label]},k.id))})}),jsxRuntime.jsx("div",{className:"flex-1 overflow-hidden flex flex-col",children:V()}),jsxRuntime.jsx(AnimatePresence,{children:C&&jsxRuntime.jsx(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-50 flex items-center justify-center bg-foreground/50 p-3",children:jsxRuntime.jsxs(motion.div,{initial:{scale:.95,y:20},animate:{scale:1,y:0},exit:{scale:.95,y:20},className:"bg-card rounded-xl w-full h-[80%] flex flex-col shadow-widget overflow-hidden",children:[jsxRuntime.jsxs("div",{className:"p-3 border-b border-border flex justify-between items-center bg-secondary",children:[jsxRuntime.jsx("h3",{className:"font-bold text-sm text-foreground",children:t("dashboard.templates",P)}),jsxRuntime.jsx("button",{onClick:()=>E(!1),className:"p-1 rounded-full hover:bg-muted text-muted-foreground transition-colors",children:jsxRuntime.jsx(X,{className:"w-4 h-4"})})]}),jsxRuntime.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:B?jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8",children:jsxRuntime.jsx(LoaderCircle,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):r.length===0?jsxRuntime.jsx("div",{className:"text-center py-8 text-muted-foreground text-sm",children:"No hay plantillas disponibles"}):r.map(k=>{const R=(o==null?void 0:o.id)===k.id;return jsxRuntime.jsxs("button",{onClick:async()=>{var G;f(k),emitTemplateChanged(k.id,k.name,((G=k.structure)==null?void 0:G.sections)||[]),E(!1),await claraApi.updateUserSettings({selectedTemplateId:k.id})},className:`w-full p-3 border rounded-lg cursor-pointer transition-all flex justify-between items-center ${R?"shadow-sm":"border-border hover:bg-secondary"}`,style:R?{borderColor:i,backgroundColor:`${i}0D`}:{},children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2.5",children:[jsxRuntime.jsx("div",{className:`w-7 h-7 rounded-full flex items-center justify-center ${R?"text-white":"bg-secondary text-muted-foreground"}`,style:R?{backgroundColor:i}:{},children:jsxRuntime.jsx(FileText,{className:"w-3.5 h-3.5"})}),jsxRuntime.jsxs("div",{className:"text-left",children:[jsxRuntime.jsx("span",{className:`font-medium text-xs block ${R?"":"text-foreground"}`,style:R?{color:i}:{},children:k.name}),k.description&&jsxRuntime.jsx("span",{className:"text-[10px] text-muted-foreground line-clamp-1",children:k.description})]})]}),R&&jsxRuntime.jsx(Check,{className:"w-4 h-4",style:{color:i}})]},k.id)})})]})})}),jsxRuntime.jsx(AnimatePresence,{children:M&&jsxRuntime.jsx(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-50 flex items-center justify-center bg-foreground/50 p-4",children:jsxRuntime.jsx(motion.div,{initial:{scale:.95,y:20},animate:{scale:1,y:0},exit:{scale:.95,y:20},className:"bg-card rounded-xl w-full max-w-xs shadow-widget overflow-hidden",children:jsxRuntime.jsxs("div",{className:"p-5 flex flex-col items-center text-center",children:[jsxRuntime.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center mb-4",children:jsxRuntime.jsx(TriangleAlert,{className:"w-6 h-6 text-destructive"})}),jsxRuntime.jsx("h3",{className:"font-bold text-base text-foreground mb-2",children:"API Key Inválida"}),jsxRuntime.jsx("p",{className:"text-muted-foreground text-sm mb-5",children:"La API Key proporcionada no es válida o ha expirado. Por favor verifica tu configuración."}),jsxRuntime.jsx("button",{onClick:()=>{D(!1),e()},className:"w-full py-2.5 px-4 rounded-lg bg-destructive text-white font-medium text-sm hover:brightness-110 transition-all",children:"Cerrar y Reintentar"})]})})})}),jsxRuntime.jsx(AnimatePresence,{children:L&&jsxRuntime.jsx(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-50 flex items-center justify-center bg-foreground/50 p-4",children:jsxRuntime.jsxs(motion.div,{initial:{scale:.95,y:20},animate:{scale:1,y:0},exit:{scale:.95,y:20},className:"bg-card rounded-xl w-full max-w-xs shadow-widget overflow-hidden relative",children:[jsxRuntime.jsx("button",{onClick:()=>{N(!1),H(null),O(null)},className:"absolute top-3 right-3 p-1 rounded-full hover:bg-secondary text-muted-foreground transition-colors z-10",children:jsxRuntime.jsx(X,{className:"w-4 h-4"})}),jsxRuntime.jsxs("div",{className:"p-5 flex flex-col items-center text-center",children:[(F==null?void 0:F.phase)==="complete"?jsxRuntime.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mb-4",style:{backgroundColor:`${i}20`},children:jsxRuntime.jsx(Check,{className:"w-8 h-8",style:{color:i}})}):(F==null?void 0:F.phase)==="error"?jsxRuntime.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mb-4 bg-destructive/20",children:jsxRuntime.jsx(TriangleAlert,{className:"w-8 h-8 text-destructive"})}):jsxRuntime.jsx("div",{className:"w-24 h-24 mb-2",children:jsxRuntime.jsx(Lottie,{animationData:aiGeneratingAnimation,loop:!0,style:{width:"100%",height:"100%"}})}),jsxRuntime.jsx("h3",{className:"font-bold text-base text-foreground mb-2",children:(F==null?void 0:F.phase)==="complete"?t("generate.complete",P):(F==null?void 0:F.phase)==="error"?t("common.error",P):t("generate.title",P)}),F&&F.phase!=="error"&&jsxRuntime.jsxs("div",{className:"w-full mb-3",children:[jsxRuntime.jsx("div",{className:"h-2 bg-secondary rounded-full overflow-hidden",children:jsxRuntime.jsx(motion.div,{className:"h-full rounded-full",style:{backgroundColor:i},initial:{width:0},animate:{width:`${F.percentage}%`},transition:{duration:.3}})}),jsxRuntime.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[F.percentage,"%"]})]}),jsxRuntime.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:(F==null?void 0:F.message)||t("generate.analyzing",P)}),$&&(F==null?void 0:F.phase)!=="saving"&&(F==null?void 0:F.phase)!=="complete"&&jsxRuntime.jsxs("div",{className:"w-full text-left mb-4 p-3 bg-secondary rounded-lg",children:[jsxRuntime.jsx("p",{className:"text-xs font-semibold text-foreground mb-1",children:$.name}),jsxRuntime.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[$.structure.sections.length," ",t("generate.sections",P),", "," ",$.structure.sections.reduce((k,R)=>k+R.fields.length,0)," ",t("generate.fields",P)]})]}),jsxRuntime.jsx("div",{className:"flex gap-2 w-full",children:(F==null?void 0:F.phase)==="error"?jsxRuntime.jsx("button",{onClick:()=>{N(!1),H(null),O(null)},className:"w-full py-2.5 px-4 rounded-lg bg-secondary text-foreground font-medium text-sm hover:bg-muted transition-all",children:t("common.close",P)}):(F==null?void 0:F.phase)==="complete"||(F==null?void 0:F.phase)==="saving"?null:jsxRuntime.jsx("button",{onClick:()=>{N(!1),H(null),O(null)},className:"w-full py-2.5 px-4 rounded-lg bg-secondary text-foreground font-medium text-sm hover:bg-muted transition-all",children:t("common.cancel",P)})})]})]})})})]})};var ViewState=(n=>(n.LOGIN="login",n.DASHBOARD="dashboard",n.SESSION="session",n))(ViewState||{}),SessionStatus=(n=>(n.CONNECTING="connecting",n.ACTIVE="active",n.PAUSED="paused",n.DISCONNECTED="disconnected",n.ERROR="error",n))(SessionStatus||{});function floatTo16BitPCM(n){const e=new ArrayBuffer(n.length*2),i=new DataView(e);let a=0;for(let s=0;s<n.length;s++,a+=2){let r=Math.max(-1,Math.min(1,n[s]));i.setInt16(a,r<0?r*32768:r*32767,!0)}return e}function arrayBufferToBase64(n){let e="";const i=new Uint8Array(n),a=i.byteLength;for(let s=0;s<a;s++)e+=String.fromCharCode(i[s]);return btoa(e)}function float32To16BitPCMBase64(n){return arrayBufferToBase64(floatTo16BitPCM(n))}function downsampleBuffer(n,e,i=16e3){if(e===i||e<i)return n;const a=e/i,s=Math.floor(n.length/a),r=new Float32Array(s);let o=0,l=0;for(;o<r.length;){const u=Math.round((o+1)*a);let c=0,d=0;for(let p=Math.round(l);p<u&&p<n.length;p++)c+=n[p],d++;r[o]=d>0?c/d:0,o++,l=u}return r}const surfaceToArea=n=>{if(!n)return 0;switch(n.toLowerCase()){case"whole":case"completo":return 0;case"vestibular":case"bucal":case"top":return 1;case"lingual":case"palatal":case"palatino":case"bottom":return 2;case"mesial":case"left":return 4;case"distal":case"right":return 6;case"oclusal":case"incisal":case"center":return 7;default:return 7}},extractJson=n=>{if(n!==null&&typeof n=="object")return n;if(typeof n!="string"||!n.trim())return null;const e=n.trim();try{return JSON.parse(e)}catch{}try{const i=e.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,"").trim();if(i!==e)return JSON.parse(i)}catch{}try{const i=e.match(/\{[\s\S]*\}/);if(i)return JSON.parse(i[0])}catch{}try{const i=e.match(/\[[\s\S]*\]/);if(i)return JSON.parse(i[0])}catch{}try{const i=e.replace(/\\"/g,'"').replace(/\\n/g,`
|
|
408
408
|
`);if(i!==e)return JSON.parse(i)}catch{}try{const i=e.match(/(?:updates\s*:\s*)(\[[\s\S]*\])/i);if(i&&i[1])return JSON.parse(i[1])}catch{}return null},WORKLET_CODE=`
|
|
409
409
|
class PCMProcessor extends AudioWorkletProcessor {
|
|
410
410
|
process(inputs, outputs, parameters) {
|
package/clara-widget.es.js
CHANGED
|
@@ -26791,7 +26791,7 @@ GENERA EL JSON:`;
|
|
|
26791
26791
|
const DEMO_TEMPLATE_IDS = {
|
|
26792
26792
|
audiometria: "a0785251-eb3a-4d6c-8224-10a8c6acfd12",
|
|
26793
26793
|
odontologia: "fe2085fd-5f19-44e9-b04c-92e0f0ab7769"
|
|
26794
|
-
}, API_BASE_URL = "https://
|
|
26794
|
+
}, API_BASE_URL = "https://mahjxdopacmbyqewgxpx.supabase.co/functions/v1/api";
|
|
26795
26795
|
let demoTemplatesCache = {};
|
|
26796
26796
|
function isValidApiKey(n) {
|
|
26797
26797
|
return !!n && n.length >= 20;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clara.care/react",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.7",
|
|
4
4
|
"description": "Clara AI Medical Documentation Widget - React component with TypeScript support",
|
|
5
5
|
"main": "clara-widget.cjs.js",
|
|
6
6
|
"module": "clara-widget.es.js",
|
|
@@ -61,4 +61,4 @@
|
|
|
61
61
|
"sideEffects": [
|
|
62
62
|
"*.css"
|
|
63
63
|
]
|
|
64
|
-
}
|
|
64
|
+
}
|