@mediquo/elements 0.10.5 → 0.10.6

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.
Files changed (144) hide show
  1. package/dist/chunks/addDays-CdyO-PRI.js +1 -0
  2. package/dist/chunks/addSeconds-fO5orJrt.js +1 -0
  3. package/dist/chunks/api-chat-client-DgSWD5IP.js +1 -0
  4. package/dist/chunks/{apple-pay-outcomes-DJDSt0US.js → apple-pay-outcomes-Bm2QZwZx.js} +1 -1
  5. package/dist/chunks/appointment-details-BYGwLfww.js +1 -0
  6. package/dist/chunks/ca_ES-mW7NQKWA.js +1 -0
  7. package/dist/chunks/chunk-NIAGR3ZC-BDlNUZa1.js +1 -0
  8. package/dist/chunks/{chunk-Y4EKUX25-Bdei04iw.js → chunk-Y4EKUX25-Bix9r5ry.js} +1 -1
  9. package/dist/chunks/{chunk-YTQUGGS3-sBILRfPo.js → chunk-YTQUGGS3-DH0H7ld7.js} +1 -1
  10. package/dist/chunks/custom-element-CiOhPWP1-DPpsGZrV.js +1 -0
  11. package/dist/chunks/de_DE-Bz01AZ5g.js +1 -0
  12. package/dist/chunks/documentation-view-DbtlEQSG.js +1 -0
  13. package/dist/chunks/en_US-CV2TVb45.js +1 -0
  14. package/dist/chunks/{external-cM_kgYO_.js → external-JLtsAfi6.js} +1 -1
  15. package/dist/chunks/format-tMwfQwDf.js +1 -0
  16. package/dist/chunks/{index-C1325SFM.d.ts → index-CsFUct9e.d.ts} +1 -0
  17. package/dist/chunks/index-D2yqKnpP.js +1 -0
  18. package/dist/chunks/{index-DYDUC2Va.js → index-DOkZ23_U.js} +1 -1
  19. package/dist/chunks/index-Detg0o-C.js +1 -0
  20. package/dist/chunks/{index-pnQMnaEN.d.ts → index-MVR2p_EX.d.ts} +1 -0
  21. package/dist/chunks/isBefore-DBi1CiNR.js +1 -0
  22. package/dist/chunks/mq-chat-room-82OqHZDt.js +1 -0
  23. package/dist/chunks/{mq-chat-room-CWIDQUxq.d.ts → mq-chat-room-ZNKKjO5n.d.ts} +4 -0
  24. package/dist/chunks/mq-next-appointments-D4w-LJmF.js +1 -0
  25. package/dist/chunks/{mq-professional-presence-sync-cmg6CXhz.d.ts → mq-professional-presence-sync-BPb8GjLT.d.ts} +0 -1
  26. package/dist/chunks/mq-professional-presence-sync-CnwOuX68.js +1 -0
  27. package/dist/chunks/{mq-recent-documents-DzxYuYy6.js → mq-recent-documents-Cr6u6xRi.js} +1 -1
  28. package/dist/chunks/mq-schedule-D7axS8UJ.js +1 -0
  29. package/dist/chunks/mq-support-chat-C-dyTXms.js +1 -0
  30. package/dist/chunks/{mq-unread-count-sync-DTn9dfR4.d.ts → mq-unread-count-sync-D3KUuLPV.d.ts} +0 -1
  31. package/dist/chunks/mq-unread-count-sync-Dqf98Tn_.js +1 -0
  32. package/dist/chunks/mq-videocall-RE4mE__m.js +1 -0
  33. package/dist/chunks/next-appointment-card-CQxPBnp_.js +1 -0
  34. package/dist/chunks/{next-appointment-card-Cd6GXAne.d.ts → next-appointment-card-CrXZEw8L.d.ts} +18 -4
  35. package/dist/chunks/parseISO-CEksKisk.js +1 -0
  36. package/dist/chunks/pt_PT-9EoQbEa0.js +1 -0
  37. package/dist/chunks/{refund-cancel-policy-C_9LyN_y.js → refund-cancel-policy-DoMzcLlL.js} +1 -1
  38. package/dist/chunks/{telemetry-client-dwDzxn9N.js → telemetry-client-K37KMdy_.js} +1 -1
  39. package/dist/env.js +1 -1
  40. package/dist/i18n.js +1 -1
  41. package/dist/mq-api-client-provider.js +1 -1
  42. package/dist/mq-apple-pay-checkout.js +1 -1
  43. package/dist/mq-appointment-checkout.js +1 -1
  44. package/dist/mq-appointment-documentation.d.ts +2 -2
  45. package/dist/mq-appointment-documentation.js +1 -1
  46. package/dist/mq-chat-room.d.ts +1 -1
  47. package/dist/mq-chat-room.js +1 -1
  48. package/dist/mq-checkout.js +1 -1
  49. package/dist/mq-dashboard.d.ts +3 -3
  50. package/dist/mq-dashboard.js +1 -1
  51. package/dist/mq-documents.d.ts +1 -1
  52. package/dist/mq-documents.js +1 -1
  53. package/dist/mq-google-pay-checkout.js +1 -1
  54. package/dist/mq-immediate-videocall-checkout.js +1 -1
  55. package/dist/mq-my-appointments.d.ts +2 -4
  56. package/dist/mq-my-appointments.js +1 -1
  57. package/dist/mq-next-appointments.d.ts +2 -2
  58. package/dist/mq-next-appointments.js +1 -1
  59. package/dist/mq-payment-poller.js +1 -1
  60. package/dist/mq-professional-presence-sync.d.ts +1 -1
  61. package/dist/mq-professional-presence-sync.js +1 -1
  62. package/dist/mq-recent-documents.d.ts +1 -1
  63. package/dist/mq-recent-documents.js +1 -1
  64. package/dist/mq-schedule-success.d.ts +1 -3
  65. package/dist/mq-schedule-success.js +2 -2
  66. package/dist/mq-schedule.d.ts +8 -7
  67. package/dist/mq-schedule.js +1 -1
  68. package/dist/mq-socket-provider.js +1 -1
  69. package/dist/mq-support-chat.d.ts +1 -1
  70. package/dist/mq-support-chat.js +1 -1
  71. package/dist/mq-terms-and-conditions.js +1 -1
  72. package/dist/mq-unread-count-sync.d.ts +1 -1
  73. package/dist/mq-unread-count-sync.js +1 -1
  74. package/dist/mq-videocall.d.ts +2 -2
  75. package/dist/mq-videocall.js +1 -1
  76. package/dist/react/mq-api-client-provider.js +1 -1
  77. package/dist/react/mq-apple-pay-checkout.js +1 -1
  78. package/dist/react/mq-appointment-checkout.js +1 -1
  79. package/dist/react/mq-appointment-documentation.d.ts +2 -2
  80. package/dist/react/mq-appointment-documentation.js +1 -1
  81. package/dist/react/mq-chat-room.d.ts +1 -1
  82. package/dist/react/mq-chat-room.js +1 -1
  83. package/dist/react/mq-checkout.js +1 -1
  84. package/dist/react/mq-dashboard.d.ts +3 -3
  85. package/dist/react/mq-dashboard.js +1 -1
  86. package/dist/react/mq-documents-page.d.ts +1 -1
  87. package/dist/react/mq-documents-page.js +1 -1
  88. package/dist/react/mq-documents.d.ts +1 -1
  89. package/dist/react/mq-documents.js +1 -1
  90. package/dist/react/mq-google-pay-checkout.js +1 -1
  91. package/dist/react/mq-immediate-videocall-checkout.js +1 -1
  92. package/dist/react/mq-my-appointments.d.ts +2 -3
  93. package/dist/react/mq-my-appointments.js +1 -1
  94. package/dist/react/mq-next-appointments.d.ts +2 -2
  95. package/dist/react/mq-next-appointments.js +1 -1
  96. package/dist/react/mq-payment-poller.js +1 -1
  97. package/dist/react/mq-professional-presence-sync.d.ts +1 -1
  98. package/dist/react/mq-professional-presence-sync.js +1 -1
  99. package/dist/react/mq-recent-documents.d.ts +1 -1
  100. package/dist/react/mq-recent-documents.js +1 -1
  101. package/dist/react/mq-schedule-success.d.ts +1 -2
  102. package/dist/react/mq-schedule-success.js +1 -1
  103. package/dist/react/mq-schedule.d.ts +0 -1
  104. package/dist/react/mq-schedule.js +1 -1
  105. package/dist/react/mq-socket-provider.js +1 -1
  106. package/dist/react/mq-support-chat.d.ts +1 -1
  107. package/dist/react/mq-support-chat.js +1 -1
  108. package/dist/react/mq-terms-and-conditions.js +1 -1
  109. package/dist/react/mq-unread-count-sync.d.ts +1 -1
  110. package/dist/react/mq-unread-count-sync.js +1 -1
  111. package/dist/react/mq-videocall.d.ts +2 -2
  112. package/dist/react/mq-videocall.js +1 -1
  113. package/dist/theme.d.ts +9 -0
  114. package/dist/theme.js +1 -1
  115. package/dist/ui/mq-calendar.d.ts +2 -0
  116. package/dist/ui/mq-calendar.js +1 -1
  117. package/dist/ui/mq-dialog.d.ts +62 -13
  118. package/dist/ui/mq-dialog.js +341 -1
  119. package/dist/ui/mq-tabs.js +5 -5
  120. package/dist/ui/mq-time-slot-picker.d.ts +1 -0
  121. package/dist/ui/mq-time-slot-picker.js +1 -1
  122. package/package.json +2 -1
  123. package/dist/chunks/addSeconds-CXt0dUch.js +0 -1
  124. package/dist/chunks/api-chat-client-D5BosjTp.js +0 -1
  125. package/dist/chunks/appointment-details-DpawC6lW.js +0 -1
  126. package/dist/chunks/ca_ES-DMretbb7.js +0 -1
  127. package/dist/chunks/chunk-2TKJJNS7-DzhxHWWb.js +0 -1
  128. package/dist/chunks/de_DE-DUtzXD1z.js +0 -1
  129. package/dist/chunks/documentation-view-BnKC8xEu.js +0 -1
  130. package/dist/chunks/en_US-mxYf5Jqv.js +0 -1
  131. package/dist/chunks/format-CRFiCNHw.js +0 -1
  132. package/dist/chunks/index-2xVO6z8H.js +0 -1
  133. package/dist/chunks/index-D13HvA4a.js +0 -1
  134. package/dist/chunks/index-D54b6IW6.js +0 -1
  135. package/dist/chunks/isBefore-Dfww5192.js +0 -1
  136. package/dist/chunks/isSameDay-CuhZMy1T.js +0 -1
  137. package/dist/chunks/mq-chat-room-C7FB_wOo.js +0 -1
  138. package/dist/chunks/mq-next-appointments-DMMeL0DC.js +0 -1
  139. package/dist/chunks/mq-schedule-JZyPjgBT.js +0 -1
  140. package/dist/chunks/mq-support-chat-HYSmf_ud.js +0 -1
  141. package/dist/chunks/mq-videocall-CgU0vUQJ.js +0 -1
  142. package/dist/chunks/next-appointment-card-BFBmWPYB.js +0 -1
  143. package/dist/chunks/parseISO-Dj3qSTG8.js +0 -1
  144. package/dist/chunks/pt_PT-g8meEZVV.js +0 -1
@@ -1 +1 @@
1
- import{_ as t,c as e}from"./custom-element-D2ziPxYE.js";import{e as i}from"./provide-BwI4DDGF.js";import{c as r}from"./consume-CovVqBjI.js";import{m as o}from"./runtime-Bg1WXVCx.js";import{l as s}from"./localized-decorator-BlOuLhym.js";import{Q as n}from"./query-controller-B1byDHlF.js";import{A as a}from"./api-client-context-BXGqBAlO.js";import{l as p}from"./chunk-S5RWG6G2-CQJ38pW6.js";import{g as d,t as l,r as c}from"./telemetry-client-dwDzxn9N.js";import{g as m,t as h}from"./index-D54b6IW6.js";import{g as u}from"./get-patient-profile-query-D9btgcxl.js";import{i as g,a as y,x as f}from"./lit-element-DiWJYFwC.js";import{n as v}from"./property-scuRaFcM.js";import{r as b}from"./state-LQivXIgA.js";import{setEnv as j}from"../env.js";import{MqViewDocumentsEvent as x}from"../events.js";import{isValidLocale as k,setLocale as w,getLocale as S}from"../i18n.js";import{c as $,n as C}from"./api-chat-client-D5BosjTp.js";import"./index-MfyXh-qX.js";import"./index-D3_2tkC3.js";const P=g`:host{display:flex;flex-direction:column;align-self:start;gap:var(--sp-4);width:100%;min-width:0;box-sizing:border-box}.card{display:flex;flex-direction:column;gap:var(--sp-3);min-width:0;box-sizing:border-box;background-color:var(--color-card,#fff);border:1px solid var(--color-border-subtle,#edecf1);border-radius:var(--mq-recent-documents-radius,12px);padding:var(--mq-recent-documents-padding,var(--sp-6))}`;let Q=class MqRecentDocuments extends y{constructor(){super(...arguments),this.apiClient=$(),this.getPatientProfileQuery=new n(this,()=>u(this.apiClient,{enabled:!this.loginToken})),this.getPatientDocumentsQuery=new n(this,()=>({...m(this.apiClient,{patient_hash:this.patientHash,page:1,per_page:3}),enabled:!!this.patientHash})),this.getOrganizationSpecialtiesQuery=new n(this,()=>d(this.apiClient)),this.handleViewAll=()=>{l.track(c(this.patientHash)),this.dispatchEvent(new x)}}static{this.styles=P}willUpdate(t){t.has("env")&&this.env&&j(this.env),t.has("locale")&&this.locale&&k(this.locale)&&w(this.locale);const e=C(t,{env:this.env,apiKey:this.apiKey,token:this.token,locale:this.locale},this.inheritedApiClient);e&&(this.apiClient=e)}get patientHash(){return this.loginToken?.patient.hash??this.getPatientProfileQuery.result?.data?.hash??""}renderEmptyState(){return f`<widget-empty-state icon="document" heading="${o("No tienes documentación")}" description="${o("Aquí se mostrarán tus recetas e informes médicos.")}"></widget-empty-state>`}renderSkeleton(){return f`<document-list placeholders="${3}"></document-list>`}renderError(){return f`<widget-empty-state icon="document" heading="${o("No hemos podido cargar tu documentación")}" description="${o("Vuelve a intentarlo en unos minutos.")}"></widget-empty-state>`}renderDocuments(){return this.getPatientDocumentsQuery.render({complete:t=>0===t.data.length?this.renderEmptyState():f`<document-list .documents="${h(t.data,this.getOrganizationSpecialtiesQuery.result?.data,S())}" patientHash="${this.patientHash}"></document-list>`,initial:()=>this.getPatientProfileQuery.result?.isError?this.renderError():this.renderSkeleton(),pending:()=>this.renderSkeleton(),error:()=>this.renderError()})}render(){return f`<section-header heading="${o("Documentos recientes")}" action-label="${o("Ver todas")}" @section-action="${this.handleViewAll}"></section-header><div class="card">${this.renderDocuments()}</div>`}};t([v({type:String,attribute:"api-key"})],Q.prototype,"apiKey",void 0),t([v({type:String,attribute:"token"})],Q.prototype,"token",void 0),t([v({type:String,attribute:"locale"})],Q.prototype,"locale",void 0),t([v({type:String,attribute:"env"})],Q.prototype,"env",void 0),t([r({context:a,subscribe:!0}),b()],Q.prototype,"inheritedApiClient",void 0),t([i({context:a}),b()],Q.prototype,"apiClient",void 0),t([r({context:p,subscribe:!0})],Q.prototype,"loginToken",void 0),Q=t([s(),e("mq-recent-documents")],Q);export{Q as M};
1
+ import{_ as t,c as e}from"./custom-element-D2ziPxYE.js";import{e as i}from"./provide-BwI4DDGF.js";import{c as r}from"./consume-CovVqBjI.js";import{m as o}from"./runtime-Bg1WXVCx.js";import{l as s}from"./localized-decorator-BlOuLhym.js";import{Q as n}from"./query-controller-B1byDHlF.js";import{A as a}from"./api-client-context-BXGqBAlO.js";import{l as p}from"./chunk-S5RWG6G2-CQJ38pW6.js";import{g as d,t as l,r as c}from"./telemetry-client-K37KMdy_.js";import{g as m,t as h}from"./index-Detg0o-C.js";import{g as u}from"./get-patient-profile-query-D9btgcxl.js";import{i as g,a as y,x as f}from"./lit-element-DiWJYFwC.js";import{n as v}from"./property-scuRaFcM.js";import{r as b}from"./state-LQivXIgA.js";import{setEnv as j}from"../env.js";import{MqViewDocumentsEvent as x}from"../events.js";import{isValidLocale as k,setLocale as w,getLocale as S}from"../i18n.js";import{c as $,n as C}from"./api-chat-client-DgSWD5IP.js";import"./index-MfyXh-qX.js";import"./index-D3_2tkC3.js";const E=g`:host{display:flex;flex-direction:column;align-self:start;gap:var(--sp-4);width:100%;min-width:0;box-sizing:border-box}.card{display:flex;flex-direction:column;gap:var(--sp-3);min-width:0;box-sizing:border-box;background-color:var(--color-card,#fff);border:1px solid var(--color-border-subtle,#edecf1);border-radius:var(--mq-recent-documents-radius,12px);padding:var(--mq-recent-documents-padding,var(--sp-6))}`;let P=class MqRecentDocuments extends y{constructor(){super(...arguments),this.apiClient=$(),this.getPatientProfileQuery=new n(this,()=>u(this.apiClient,{enabled:!this.loginToken})),this.getPatientDocumentsQuery=new n(this,()=>({...m(this.apiClient,{patient_hash:this.patientHash,page:1,per_page:3}),enabled:!!this.patientHash})),this.getOrganizationSpecialtiesQuery=new n(this,()=>d(this.apiClient)),this.handleViewAll=()=>{l.track(c(this.patientHash)),this.dispatchEvent(new x)}}static{this.styles=E}willUpdate(t){t.has("env")&&this.env&&j(this.env),t.has("locale")&&this.locale&&k(this.locale)&&w(this.locale);const e=C(t,{env:this.env,apiKey:this.apiKey,token:this.token,locale:this.locale},this.inheritedApiClient);e&&(this.apiClient=e)}get patientHash(){return this.loginToken?.patient.hash??this.getPatientProfileQuery.result?.data?.hash??""}renderEmptyState(){return f`<widget-empty-state icon="document" heading="${o("No tienes documentación")}" description="${o("Aquí se mostrarán tus recetas e informes médicos.")}"></widget-empty-state>`}renderSkeleton(){return f`<document-list placeholders="${3}"></document-list>`}renderError(){return f`<widget-empty-state icon="document" heading="${o("No hemos podido cargar tu documentación")}" description="${o("Vuelve a intentarlo en unos minutos.")}"></widget-empty-state>`}renderDocuments(){return this.getPatientDocumentsQuery.render({complete:t=>0===t.data.length?this.renderEmptyState():f`<document-list .documents="${h(t.data,this.getOrganizationSpecialtiesQuery.result?.data,S())}" patientHash="${this.patientHash}"></document-list>`,initial:()=>this.getPatientProfileQuery.result?.isError?this.renderError():this.renderSkeleton(),pending:()=>this.renderSkeleton(),error:()=>this.renderError()})}render(){return f`<section-header heading="${o("Documentos recientes")}" action-label="${o("Ver todas")}" @section-action="${this.handleViewAll}"></section-header><div class="card">${this.renderDocuments()}</div>`}};t([v({type:String,attribute:"api-key"})],P.prototype,"apiKey",void 0),t([v({type:String,attribute:"token"})],P.prototype,"token",void 0),t([v({type:String,attribute:"locale"})],P.prototype,"locale",void 0),t([v({type:String,attribute:"env"})],P.prototype,"env",void 0),t([r({context:a,subscribe:!0}),b()],P.prototype,"inheritedApiClient",void 0),t([i({context:a}),b()],P.prototype,"apiClient",void 0),t([r({context:p,subscribe:!0})],P.prototype,"loginToken",void 0),P=t([s(),e("mq-recent-documents")],P);export{P as M};
@@ -0,0 +1 @@
1
+ import{_ as e,c as t}from"./custom-element-D2ziPxYE.js";import{Q as i}from"./query-controller-B1byDHlF.js";import{A as s}from"./api-client-context-BXGqBAlO.js";import{l as a}from"./chunk-S5RWG6G2-CQJ38pW6.js";import{g as o}from"./get-appointment-query-DuHrjd8L.js";import{g as r}from"./get-organization-setup-query-De7eM6V3.js";import{S as n,z as l,g as d,a as c,A as p,t as h,B as u,C as m,D as v,E as f,F as g,G as y,H as b}from"./telemetry-client-K37KMdy_.js";import{g as w}from"./get-patient-profile-query-D9btgcxl.js";import{s as _}from"./chunk-6CCJWPGL-TiaqZaPV.js";import{D as x}from"./chunk-5EJXDIGT-Bb4_pfDr.js";import{g as S}from"./get-schedule-services-query-Io2aQ_7G.js";import{b as $,g as k,a as C,c as P,d as E,e as M,f as I,r as A}from"./chunk-NIAGR3ZC-BDlNUZa1.js";import{c as F}from"./refund-cancel-policy-DoMzcLlL.js";import{MqPaymentRedirectEvent as q,MqBackEvent as V}from"../events.js";import{i as D,e as z,h as L,P as j,S as B,c as T,n as O,j as U,k as N}from"./api-chat-client-DgSWD5IP.js";import"../ui/mq-button.js";import{i as R,e as W}from"./provide-BwI4DDGF.js";import{c as Q}from"./consume-CovVqBjI.js";import{m as H,s as K}from"./runtime-Bg1WXVCx.js";import{l as G}from"./localized-decorator-BlOuLhym.js";import{E as Z,i as J,a as X,x as Y}from"./lit-element-DiWJYFwC.js";import{n as ee}from"./property-scuRaFcM.js";import{r as te}from"./state-LQivXIgA.js";import{e as ie,i as se,t as ae}from"./directive-2EDmOukv.js";import{m as oe,f as re}from"./index-C76yAope.js";import{setEnv as ne}from"../env.js";import{getLocale as le,initLocalization as de,isValidLocale as ce,setLocale as pe}from"../i18n.js";import{n as he}from"./create-context-DqP79qjF.js";import{M as ue}from"./mutation-controller-CR2qcqhH.js";import{e as me}from"./class-map-Co76I6aw.js";import{o as ve}from"./if-defined-BYeVdwgd.js";import{z as fe}from"./external-JLtsAfi6.js";import"../ui/mq-input.js";import"../ui/mq-callout.js";import"../ui/mq-page-title.js";import"./professional-overview-B4E05rLd.js";import"./appointment-details-BYGwLfww.js";import"../ui/mq-card.js";import{spinnerIcon as ge}from"../ui/icons/spinner-icon.js";import{tagIcon as ye}from"../ui/icons/tag-icon.js";import{h as be,f as we,c as _e}from"./price-DU3YLTpk.js";import{toast as xe}from"../ui/mq-toast.js";import{e as Se}from"./query-CeeutdfT.js";import{fileIcon as $e}from"../ui/icons/file-icon.js";import{uploadIcon as ke}from"../ui/icons/upload-icon.js";import{xIcon as Ce}from"../ui/icons/x-icon.js";import"../ui/mq-textarea.js";import{l as Pe}from"./chunk-FUCSYDW7-Duj5hy8S.js";import{Q as Ee}from"./chunk-RCFIJTXZ-C6Ir0-sM.js";import"../ui/mq-skeleton.js";import"../ui/mq-text-button.js";import{ICON_STROKE_WIDTH as Me}from"../ui/icons/types.js";import"../ui/mq-select.js";import"../ui/mq-badge.js";import{t as Ie,i as Ae,p as Fe,f as qe}from"./parseISO-CEksKisk.js";import{i as Ve,s as De,e as ze}from"./index-D2yqKnpP.js";import{calendarIcon as Le}from"../ui/icons/calendar-icon.js";import{skipToken as je}from"@tanstack/query-core";import"../ui/mq-time-slot-picker.js";import{breakpoints as Be}from"../theme.js";import{a as Te}from"./addDays-CdyO-PRI.js";function Oe(e,t){const i=+Ie(e)-+Ie(t);return i<0?-1:i>0?1:i}var Ue=class{constructor(e,t,i){this.host=e,this.steps=t,this._history=[],this._ctx=i,this._index=this._skipForward(0),this.host.addController(this)}hostConnected(){}hostDisconnected(){}get current(){const e=this.steps[this._index];if(!e)throw new Error(`WizardController: invalid index ${this._index} for ${this.steps.length}-step wizard`);return e.name}get ctx(){return this._ctx}get canGoBack(){return this._history.length>0}next(e){if(e&&(this._ctx={...this._ctx,...e}),this._index>=this.steps.length-1)return void this.host.requestUpdate();const t=this._skipForward(this._index+1);t!==this._index&&(this._history.push(this._index),this._index=t),this.host.requestUpdate()}goTo(e,t,i={}){t&&(this._ctx={...this._ctx,...t});const s=this.steps.findIndex(t=>t.name===e);if(s<0)throw new Error(`WizardController: unknown step "${e}"`);const a=this._skipForward(s);i.replace?(this._history[this._history.length-1]===a&&this._history.pop(),this._index=a):a!==this._index&&(this._history.push(this._index),this._index=a),this.host.requestUpdate()}back(){const e=this._history.pop();return void 0!==e&&(this._index=e,this.host.requestUpdate(),!0)}reconcile(e){const t={...this._ctx,...e},i=!function(e,t){if(e===t)return!0;const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(const s of i)if(e[s]!==t[s])return!1;return!0}(this._ctx,t);this._ctx=t;const s=this._skipForward(this._index),a=s!==this._index;a&&(this._history.push(this._index),this._index=s),(i||a)&&this.host.requestUpdate()}_skipForward(e){let t=e;for(;t<this.steps.length-1;){const e=this.steps[t];if(!e?.skipIf?.(this._ctx))return t;t++}return t}};const Ne=ie(class extends se{constructor(){super(...arguments),this.key=Z}render(e,t){return this.key=e,t}update(e,[t,i]){return t!==this.key&&(oe(e),this.key=t),i}}),Re=he(Symbol.for("mq-schedule:patient"));class DiscountAppliedEvent extends Event{static{this.eventName="discount-applied"}constructor(e){super(DiscountAppliedEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}class AuthRequiredEvent extends Event{static{this.eventName="auth-required"}constructor(e){super(AuthRequiredEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}function We(e,t){if(!e)return;const i=function(e){if(e)return l[e]??e}(e);return t?.find(t=>t.code===i||String(t.id)===e)?.id}function Qe(e,t){if(!e)return;const i=n[e];return i?t?.find(e=>e.channel===i):t?.find(t=>t.code===e||t.id===e)}function He(e){const t=We(e.defaultSpecialty,e.specialties),i=Qe(e.defaultService,e.services),s=e.defaultProfessionalHash?{avatar:e.professional?.avatar??null,collegiate_number:e.professional?.collegiate_number??null,description:e.professional?.description??null,languages:e.professional?.languages??[],name:e.professional?.name??"",id:e.professional?.hash??"",speciality:{id:t??0}}:void 0;return{service:i,specialty:t?.toString(),slot:void 0,professional:s,firstAvailableSlotDay:void 0,paymentSessionId:void 0,paymentUrl:void 0,paymentProvider:void 0,paymentRequest:void 0,appliedDiscount:void 0,profileComplete:e.profileComplete,requiresPayment:e.requiresPayment,error:!1}}const Ke={name:"completeProfile",skipIf:e=>e.profileComplete},Ge={name:"payment",skipIf:e=>!e.requiresPayment},Ze=[{name:"selectProfessional"},{name:"selectSlot"},Ke,{name:"confirm"},Ge,{name:"done"}],Je=[{name:"selectSlot"},Ke,{name:"confirm"},Ge,{name:"done"}],Xe=[{name:"selectSlot"},Ke,{name:"confirm"},{name:"done"}];function Ye(e){return e.totalAmount<=0}class InvalidDiscountCodeError extends Error{constructor(e="Invalid discount code"){super(e),this.name="InvalidDiscountCodeError"}}function et(e,t){t.stopPropagation(),e.dispatchEvent(new CustomEvent("back"))}const tt=new WeakMap,it=new WeakMap,st={current:[]};let at=!1,ot=0;const rt=new Set,nt=new Map;function lt(e){const t=Array.from(e).sort((e,t)=>e instanceof Derived&&e.options.deps.includes(t)?1:t instanceof Derived&&t.options.deps.includes(e)?-1:0);for(const e of t){if(st.current.includes(e))continue;st.current.push(e),e.recompute();const t=it.get(e);if(t)for(const e of t){const t=tt.get(e);t&&lt(t)}}}function dt(e){const t={prevVal:e.prevState,currentVal:e.state};for(const i of e.listeners)i(t)}function ct(e){const t={prevVal:e.prevState,currentVal:e.state};for(const i of e.listeners)i(t)}function pt(e){if(ot>0&&!nt.has(e)&&nt.set(e,e.prevState),rt.add(e),!(ot>0||at))try{for(at=!0;rt.size>0;){const e=Array.from(rt);rt.clear();for(const t of e){const e=nt.get(t)??t.prevState;t.prevState=e,dt(t)}for(const t of e){const e=tt.get(t);e&&(st.current.push(t),lt(e))}for(const t of e){const e=tt.get(t);if(e)for(const t of e)ct(t)}}}finally{at=!1,st.current=[],nt.clear()}}function ht(e){ot++;try{e()}finally{if(ot--,0===ot){const e=rt.values().next().value;e&&pt(e)}}}class Store{constructor(e,t){this.listeners=new Set,this.subscribe=e=>{var t,i;this.listeners.add(e);const s=null==(i=null==(t=this.options)?void 0:t.onSubscribe)?void 0:i.call(t,e,this);return()=>{this.listeners.delete(e),null==s||s()}},this.prevState=e,this.state=e,this.options=t}setState(e){var t,i,s;this.prevState=this.state,(null==(t=this.options)?void 0:t.updateFn)?this.state=this.options.updateFn(this.prevState)(e):!function(e){return"function"==typeof e}(e)?this.state=e:this.state=e(this.prevState),null==(s=null==(i=this.options)?void 0:i.onUpdate)||s.call(i),pt(this)}}class Derived{constructor(e){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{const e=this.options.deps.length,t=new Array(e),i=new Array(e);for(let s=0;s<e;s++){const e=this.options.deps[s];t[s]=e.prevState,i[s]=e.state}return this.lastSeenDepValues=i,{prevDepVals:t,currDepVals:i,prevVal:this.prevState??void 0}},this.recompute=()=>{var e,t;this.prevState=this.state;const i=this.getDepVals();this.state=this.options.fn(i),null==(t=(e=this.options).onUpdate)||t.call(e)},this.checkIfRecalculationNeededDeeply=()=>{for(const e of this.options.deps)e instanceof Derived&&e.checkIfRecalculationNeededDeeply();let e=!1;const t=this.lastSeenDepValues,{currDepVals:i}=this.getDepVals();for(let s=0;s<i.length;s++)if(i[s]!==t[s]){e=!0;break}e&&this.recompute()},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(const e of this._subscriptions)e()}),this.subscribe=e=>{var t,i;this.listeners.add(e);const s=null==(i=(t=this.options).onSubscribe)?void 0:i.call(t,e,this);return()=>{this.listeners.delete(e),null==s||s()}},this.options=e,this.state=e.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals})}registerOnGraph(e=this.options.deps){for(const t of e)if(t instanceof Derived)t.registerOnGraph(),this.registerOnGraph(t.options.deps);else if(t instanceof Store){let e=tt.get(t);e||(e=new Set,tt.set(t,e)),e.add(this);let i=it.get(this);i||(i=new Set,it.set(this,i)),i.add(t)}}unregisterFromGraph(e=this.options.deps){for(const t of e)if(t instanceof Derived)this.unregisterFromGraph(t.options.deps);else if(t instanceof Store){const e=tt.get(t);e&&e.delete(this);const i=it.get(this);i&&i.delete(t)}}}function ut(e,t){return"function"==typeof e?e(t):e}function mt(e,t){return St(t).reduce((e,t)=>null===e?null:void 0!==e?e[t]:void 0,e)}function vt(e,t,i){const s=St(t);return function e(t){if(!s.length)return ut(i,t);const a=s.shift();if("string"==typeof a||"number"==typeof a&&!Array.isArray(t))return"object"==typeof t?(null===t&&(t={}),{...t,[a]:e(t[a])}):{[a]:e()};if(Array.isArray(t)&&"number"==typeof a){const i=t.slice(0,a);return[...i.length?i:new Array(a),e(t[a]),...t.slice(a+1)]}return[...new Array(a),e()]}(e)}const ft=/^(\d+)$/gm,gt=/\.(\d+)(?=\.)/gm,yt=/^(\d+)\./gm,bt=/\.(\d+$)/gm,wt=/\.{2,}/gm,_t="__int__",xt=`${_t}$1`;function St(e){if(Array.isArray(e))return[...e];if("string"!=typeof e)throw new Error("Path must be a string.");return e.replace(/(^\[)|]/gm,"").replace(/\[/g,".").replace(ft,xt).replace(gt,`.${xt}.`).replace(yt,`${xt}.`).replace(bt,`.${xt}`).replace(wt,".").split(".").map(e=>{if(e.startsWith(_t)){const t=e.substring(_t.length),i=parseInt(t,10);return String(i)===t?i:t}return e})}function $t(e){return!(Array.isArray(e)&&0===e.length)}function kt(e,t){return t.validationLogic({form:t.form,validators:t.validators,event:{type:e,async:!1},runValidation:e=>e.validators.filter(Boolean).map(e=>({cause:e.cause,validate:e.fn}))})}function Ct(e,t){const{asyncDebounceMs:i}=t,{onBlurAsyncDebounceMs:s,onChangeAsyncDebounceMs:a,onDynamicAsyncDebounceMs:o}=t.validators||{},r=i??0;return t.validationLogic({form:t.form,validators:t.validators,event:{type:e,async:!0},runValidation:t=>t.validators.filter(Boolean).map(t=>{const i=t?.cause||e;let n=r;switch(i){case"change":n=a??r;break;case"blur":n=s??r;break;case"dynamic":n=o??r;break;case"submit":n=0}return"submit"===e&&(n=0),{cause:i,validate:t.fn,debounceMs:n}})})}const Pt=e=>!!e&&"object"==typeof e&&"fields"in e;function Et(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,s]of e)if(!t.has(i)||!Object.is(s,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(const a of i)if(!s.includes(a)||!Et(e[a],t[a]))return!1;return!0}const Mt=({newFormValidatorError:e,isPreviousErrorFromFormValidator:t,previousErrorValue:i})=>e?{newErrorValue:e,newSource:"form"}:t?{newErrorValue:void 0,newSource:void 0}:i?{newErrorValue:i,newSource:"field"}:{newErrorValue:void 0,newSource:void 0},It=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function At(e,t){return null==e?t:{...e,...t}}let Ft=256;const qt=[];let Vt;for(;Ft--;)qt[Ft]=(Ft+256).toString(16).substring(1);const Dt=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});const t=e.event.async,i=t?void 0:{fn:e.validators.onMount,cause:"mount"},s={fn:t?e.validators.onChangeAsync:e.validators.onChange,cause:"change"},a={fn:t?e.validators.onBlurAsync:e.validators.onBlur,cause:"blur"},o={fn:t?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},r=t?void 0:{fn:()=>{},cause:"server"};switch(e.event.type){case"mount":return e.runValidation({validators:[i],form:e.form});case"submit":return e.runValidation({validators:[s,a,o,r],form:e.form});case"server":return e.runValidation({validators:[],form:e.form});case"blur":return e.runValidation({validators:[a,r],form:e.form});case"change":return e.runValidation({validators:[s,r],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};const zt=(e,t)=>{const i=function(e,t){const i=new Map;for(const s of e){const e=s.path??[];let a=t,o="";for(let t=0;t<e.length;t++){const i=e[t];if(void 0===i)continue;const s="object"==typeof i?i.key:i,r=Number(s);Array.isArray(a)&&!Number.isNaN(r)?o+=`[${r}]`:o+=(t>0?".":"")+String(s),a="object"==typeof a&&null!==a?a[s]:void 0}i.set(o,(i.get(o)??[]).concat(s))}return Object.fromEntries(i)}(e,t);return{form:i,fields:i}},Lt={validate({value:e,validationSource:t},i){const s=i["~standard"].validate(e);if(s instanceof Promise)throw new Error("async function passed to sync validator");if(s.issues)return"field"===t?s.issues:zt(s.issues,e)},async validateAsync({value:e,validationSource:t},i){const s=await i["~standard"].validate(e);if(s.issues)return"field"===t?s.issues:zt(s.issues,e)}},jt=e=>!!e&&"~standard"in e,Bt={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{}};function Tt(e){function t(e,t){return`${e}[${t}]`}function i(t,i){("up"===i?t:[...t].reverse()).forEach(t=>{const a=function(e,t){return e.replace(/\[(\d+)\]/,(e,i)=>{const s=parseInt(i,10);return`[${"up"===t?s+1:Math.max(0,s-1)}]`})}(t.toString(),i),o=e.getFieldMeta(a);o?e.setFieldMeta(t,o):e.setFieldMeta(t,s())})}const s=()=>Bt,a=(a,o,r)=>{i(a,"down"),a.forEach(i=>{i.toString().startsWith(t(o,r))&&e.setFieldMeta(i,s())})},o=e=>{i(e,"up")},r=(s,a,o,r)=>{const n=new Map(Object.keys(e.fieldInfo).filter(e=>e.startsWith(t(a,o))).map(t=>[t,e.getFieldMeta(t)]));i(s,o<r?"up":"down"),Object.keys(e.fieldInfo).filter(e=>e.startsWith(t(a,r))).forEach(i=>{const s=i.replace(t(a,r),t(a,o)),l=n.get(s);l&&e.setFieldMeta(i,l)})},n=(i,s,a,o)=>{i.forEach(i=>{if(!i.toString().startsWith(t(s,a)))return;const r=i.toString().replace(t(s,a),t(s,o)),[n,l]=[e.getFieldMeta(i),e.getFieldMeta(r)];n&&e.setFieldMeta(r,n),l&&e.setFieldMeta(i,l)})};return{handleArrayFieldMetaShift:function(i,s,l,d){const c=function(i,s,a,o){const r=[t(i,s)];if("swap"===a)r.push(t(i,o));else if("move"===a){const[e,a]=[Math.min(s,o),Math.max(s,o)];for(let s=e;s<=a;s++)r.push(t(i,s))}else{const a=e.getFieldValue(i),o=Array.isArray(a)?a.length:0;for(let e=s+1;e<o;e++)r.push(t(i,e))}return Object.keys(e.fieldInfo).filter(e=>r.some(t=>e.startsWith(t)))}(i,s,l,d);({insert:()=>a(c,i,s),remove:()=>o(c),swap:()=>void 0!==d&&n(c,i,s,d),move:()=>void 0!==d&&r(c,i,s,d)})[l]()}}}class EventClient{#e;#t;#i;#s;#a;#o;#r;#n=0;#l=5;#d=()=>{this.debugLog("Connected to event bus"),this.#a=!0,this.debugLog("Emitting queued events",this.#s),this.#s.forEach(e=>this.emitEventToBus(e)),this.#s=[],this.stopConnectLoop(),this.#t().removeEventListener("tanstack-connect-success",this.#d)};#c=()=>{if(this.#t().addEventListener("tanstack-connect-success",this.#d),this.#n<this.#l)return this.#n++,void this.dispatchCustomEvent("tanstack-connect",{});this.#t().removeEventListener("tanstack-connect",this.#c),this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};constructor({pluginId:e,debug:t=!1}){this.#e=e,this.#t=this.getGlobalTarget,this.#i=t,this.debugLog(" Initializing event subscription for plugin",this.#e),this.#s=[],this.#a=!1,this.#o=null,this.#r=500}startConnectLoop(){null!==this.#o||this.#a||(this.debugLog(`Starting connect loop (every ${this.#r}ms)`),this.#o=setInterval(this.#c,this.#r))}stopConnectLoop(){null!==this.#o&&(clearInterval(this.#o),this.#o=null,this.debugLog("Stopped connect loop"))}debugLog(...e){this.#i&&console.log(`🌴 [tanstack-devtools:${this.#e}-plugin]`,...e)}getGlobalTarget(){if("undefined"!=typeof globalThis&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if("undefined"!=typeof window&&void 0!==window.addEventListener)return this.debugLog("Using window as event target"),window;const e="undefined"!=typeof EventTarget?new EventTarget:void 0;return void 0===e||void 0===e.addEventListener?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog("Using new EventTarget as fallback"),e)}getPluginId(){return this.#e}dispatchCustomEventShim(e,t){try{const i=new Event(e,{detail:t});this.#t().dispatchEvent(i)}catch(e){this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(e,t){try{this.#t().dispatchEvent(new CustomEvent(e,{detail:t}))}catch(i){this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog("Emitting event to client bus",e),this.dispatchCustomEvent("tanstack-dispatch-event",e)}emit(e,t){return this.#a?this.emitEventToBus({type:`${this.#e}:${e}`,payload:t,pluginId:this.#e}):(this.debugLog("Bus not available, will be pushed as soon as connected"),this.#s.push({type:`${this.#e}:${e}`,payload:t,pluginId:this.#e}),void("undefined"!=typeof CustomEvent&&(this.#c(),this.startConnectLoop())))}on(e,t){const i=`${this.#e}:${e}`,s=e=>{this.debugLog("Received event from bus",e.detail),t(e.detail)};return this.#t().addEventListener(i,s),this.debugLog("Registered event to bus",i),()=>{this.#t().removeEventListener(i,s)}}onAll(e){const t=t=>{const i=t.detail;e(i)};return this.#t().addEventListener("tanstack-devtools-global",t),()=>this.#t().removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(e){const t=t=>{const i=t.detail;this.#e&&i.pluginId!==this.#e||e(i)};return this.#t().addEventListener("tanstack-devtools-global",t),()=>this.#t().removeEventListener("tanstack-devtools-global",t)}}const Ot=new class FormEventClient extends EventClient{constructor(){super({pluginId:"form-devtools"})}};function Ut(e){return{values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}class FormApi{constructor(e){this.options={},this.fieldInfo={},this.prevTransformArray=[],this.mount=()=>{const e=this.fieldMetaDerived.mount(),t=this.store.mount(),i=()=>{e(),t(),Ot.emit("form-unmounted",{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});const{onMount:s}=this.options.validators||{};return Ot.emit("form-state-change",{id:this._formId,state:this.store.state,options:this.options}),s?(this.validateSync("mount"),i):i},this.update=e=>{if(!e)return;const t=this.options;this.options=e;const i=!!e.transform?.deps?.some((e,t)=>e!==this.prevTransformArray[t]),s=e.defaultValues&&!Et(e.defaultValues,t.defaultValues)&&!this.state.isTouched,a=!Et(e.defaultState,t.defaultState)&&!this.state.isTouched;(s||a||i)&&ht(()=>{this.baseStore.setState(()=>Ut(Object.assign({},this.state,a?e.defaultState:{},s?{values:e.defaultValues}:{},i?{_force_re_eval:!this.state._force_re_eval}:{})))})},this.reset=(e,t)=>{const{fieldMeta:i}=this.state,s=this.resetFieldMeta(i);e&&!t?.keepDefaultValues&&(this.options={...this.options,defaultValues:e}),this.baseStore.setState(()=>Ut({...this.options.defaultState,values:e??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}))},this.validateAllFields=async e=>{const t=[];ht(()=>{Object.values(this.fieldInfo).forEach(i=>{if(!i.instance)return;const s=i.instance;t.push(Promise.resolve().then(()=>s.validate(e,{skipFormValidation:!0}))),i.instance.state.meta.isTouched||i.instance.setMeta(e=>({...e,isTouched:!0}))})});return(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=async(e,t,i)=>{const s=this.getFieldValue(e),a=Array.isArray(s)?Math.max(s.length-1,0):null,o=[`${e}[${t}]`];for(let i=t+1;i<=(a??0);i++)o.push(`${e}[${i}]`);const r=Object.keys(this.fieldInfo).filter(e=>o.some(t=>e.startsWith(t))),n=[];ht(()=>{r.forEach(e=>{n.push(Promise.resolve().then(()=>this.validateField(e,i)))})});return(await Promise.all(n)).flat()},this.validateField=(e,t)=>{const i=this.fieldInfo[e]?.instance;return i?(i.state.meta.isTouched||i.setMeta(e=>({...e,isTouched:!0})),i.validate(t)):[]},this.validateSync=e=>{const t=kt(e,{...this.options,form:this,validationLogic:this.options.validationLogic||Dt});let i=!1;const s={};return ht(()=>{for(const e of t){if(!e.validate)continue;const t=this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:a,fieldErrors:o}=Nt(t),r=Rt(e.cause);for(const e of Object.keys(this.state.fieldMeta)){const t=this.getFieldMeta(e);if(!t)continue;const{errorMap:i,errorSourceMap:a}=t,n=o?.[e],{newErrorValue:l,newSource:d}=Mt({newFormValidatorError:n,isPreviousErrorFromFormValidator:"form"===a?.[r],previousErrorValue:i?.[r]});"form"===d&&(s[e]={...s[e],[r]:n}),i?.[r]!==l&&this.setFieldMeta(e,e=>({...e,errorMap:{...e.errorMap,[r]:l},errorSourceMap:{...e.errorSourceMap,[r]:d}}))}this.state.errorMap?.[r]!==a&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[r]:a}})),(a||o)&&(i=!0)}const a=Rt("submit");this.state.errorMap?.[a]&&"submit"!==e&&!i&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[a]:void 0}}));const o=Rt("server");this.state.errorMap?.[o]&&"server"!==e&&!i&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:void 0}}))}),{hasErrored:i,fieldsErrorMap:s}},this.validateAsync=async e=>{const t=Ct(e,{...this.options,form:this,validationLogic:this.options.validationLogic||Dt});this.state.isFormValidating||this.baseStore.setState(e=>({...e,isFormValidating:!0}));const i=[];let s;for(const e of t){if(!e.validate)continue;const t=Rt(e.cause),a=this.state.validationMetaMap[t];a?.lastAbortController.abort();const o=new AbortController;this.state.validationMetaMap[t]={lastAbortController:o},i.push(new Promise(async t=>{let i;try{i=await new Promise((t,i)=>{setTimeout(async()=>{if(o.signal.aborted)return t(void 0);try{t(await this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:o.signal},type:"validateAsync"}))}catch(e){i(e)}},e.debounceMs)})}catch(e){i=e}const{formError:a,fieldErrors:r}=Nt(i);r&&(s=s?{...s,...r}:r);const n=Rt(e.cause);for(const e of Object.keys(this.state.fieldMeta)){const t=this.getFieldMeta(e);if(!t)continue;const{errorMap:i,errorSourceMap:a}=t,o=s?.[e],{newErrorValue:r,newSource:l}=Mt({newFormValidatorError:o,isPreviousErrorFromFormValidator:"form"===a?.[n],previousErrorValue:i?.[n]});i?.[n]!==r&&this.setFieldMeta(e,e=>({...e,errorMap:{...e.errorMap,[n]:r},errorSourceMap:{...e.errorSourceMap,[n]:l}}))}this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[n]:a}})),t(s?{fieldErrors:s,errorMapKey:n}:void 0)}))}let a=[];const o={};if(i.length){a=await Promise.all(i);for(const e of a)if(e?.fieldErrors){const{errorMapKey:t}=e;for(const[i,s]of Object.entries(e.fieldErrors)){const e={...o[i]||{},[t]:s};o[i]=e}}}return this.baseStore.setState(e=>({...e,isFormValidating:!1})),o},this.validate=e=>{const{hasErrored:t,fieldsErrorMap:i}=this.validateSync(e);return t&&!this.options.asyncAlways?i:this.validateAsync(e)},this.getFieldValue=e=>mt(this.state.values,e),this.getFieldMeta=e=>this.state.fieldMeta[e],this.getFieldInfo=e=>this.fieldInfo[e]||={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.setFieldMeta=(e,t)=>{this.baseStore.setState(i=>({...i,fieldMetaBase:{...i.fieldMetaBase,[e]:ut(t,i.fieldMetaBase[e])}}))},this.resetFieldMeta=e=>Object.keys(e).reduce((e,t)=>(e[t]=Bt,e),{}),this.setFieldValue=(e,t,i)=>{const s=i?.dontUpdateMeta??!1,a=i?.dontRunListeners??!1,o=i?.dontValidate??!1;ht(()=>{s||this.setFieldMeta(e,e=>({...e,isTouched:!0,isDirty:!0,errorMap:{...e?.errorMap,onMount:void 0}})),this.baseStore.setState(i=>({...i,values:vt(i.values,e,t)}))}),a||this.getFieldInfo(e).instance?.triggerOnChangeListener(),o||this.validateField(e,"change")},this.deleteField=e=>{const t=Object.keys(this.fieldInfo).filter(t=>{const i=e.toString();return t!==i&&t.startsWith(i)}),i=[...t,e];this.baseStore.setState(e=>{const t={...e};return i.forEach(e=>{t.values=function(e,t){const i=St(t);return function e(t){if(!t)return;if(1===i.length){const e=i[0];if(Array.isArray(t)&&"number"==typeof e)return t.filter((t,i)=>i!==e);const{[e]:s,...a}=t;return a}const s=i.shift();if("string"==typeof s&&"object"==typeof t)return{...t,[s]:e(t[s])};if("number"==typeof s&&Array.isArray(t)){if(s>=t.length)return t;const i=t.slice(0,s);return[...i.length?i:new Array(s),e(t[s]),...t.slice(s+1)]}throw new Error("It seems we have created an infinite loop in deleteBy. ")}(e)}(t.values,e),delete this.fieldInfo[e],delete t.fieldMetaBase[e]}),t})},this.pushFieldValue=(e,t,i)=>{this.setFieldValue(e,e=>[...Array.isArray(e)?e:[],t],i)},this.insertFieldValue=async(e,t,i,s)=>{this.setFieldValue(e,e=>[...e.slice(0,t),i,...e.slice(t)],At(s,{dontValidate:!0})),await this.validateField(e,"change"),Tt(this).handleArrayFieldMetaShift(e,t,"insert"),await this.validateArrayFieldsStartingFrom(e,t,"change")},this.replaceFieldValue=async(e,t,i,s)=>{this.setFieldValue(e,e=>e.map((e,s)=>s===t?i:e),At(s,{dontValidate:!0})),await this.validateField(e,"change"),await this.validateArrayFieldsStartingFrom(e,t,"change")},this.removeFieldValue=async(e,t,i)=>{const s=this.getFieldValue(e),a=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(e,e=>e.filter((e,i)=>i!==t),At(i,{dontValidate:!0})),Tt(this).handleArrayFieldMetaShift(e,t,"remove"),null!==a){const t=`${e}[${a}]`;this.deleteField(t)}await this.validateField(e,"change"),await this.validateArrayFieldsStartingFrom(e,t,"change")},this.swapFieldValues=(e,t,i,s)=>{this.setFieldValue(e,e=>{const s=e[t],a=e[i];return vt(vt(e,`${t}`,a),`${i}`,s)},At(s,{dontValidate:!0})),Tt(this).handleArrayFieldMetaShift(e,t,"swap",i),this.validateField(e,"change"),this.validateField(`${e}[${t}]`,"change"),this.validateField(`${e}[${i}]`,"change")},this.moveFieldValues=(e,t,i,s)=>{this.setFieldValue(e,e=>{const s=[...e];return s.splice(i,0,s.splice(t,1)[0]),s},At(s,{dontValidate:!0})),Tt(this).handleArrayFieldMetaShift(e,t,"move",i),this.validateField(e,"change"),this.validateField(`${e}[${t}]`,"change"),this.validateField(`${e}[${i}]`,"change")},this.clearFieldValues=(e,t)=>{const i=this.getFieldValue(e),s=Array.isArray(i)?Math.max(i.length-1,0):null;if(this.setFieldValue(e,[],At(t,{dontValidate:!0})),null!==s)for(let t=0;t<=s;t++){const i=`${e}[${t}]`;this.deleteField(i)}this.validateField(e,"change")},this.resetField=e=>{this.baseStore.setState(t=>({...t,fieldMetaBase:{...t.fieldMetaBase,[e]:Bt},values:this.options.defaultValues?vt(t.values,e,mt(this.options.defaultValues,e)):t.values}))},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((e,[t,i])=>(Object.keys(i).length&&i.errors.length&&(e[t]={errors:i.errors,errorMap:i.errorMap}),e),{})}),this.parseValuesWithSchema=e=>Lt.validate({value:this.state.values,validationSource:"form"},e),this.parseValuesWithSchemaAsync=e=>Lt.validateAsync({value:this.state.values,validationSource:"form"},e),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=e?.formId??function(){let e,t=0,i="";if(!Vt||Ft+16>256){for(Vt=new Array(256),t=256;t--;)Vt[t]=256*Math.random()|0;t=0,Ft=0}for(;t<16;t++)e=Vt[Ft+t],i+=6===t?qt[15&e|64]:8===t?qt[63&e|128]:qt[e],1&t&&t>1&&t<11&&(i+="-");return Ft++,i}(),this._devtoolsSubmissionOverride=!1,this.baseStore=new Store(Ut({...e?.defaultState,values:e?.defaultValues??e?.defaultState?.values})),this.fieldMetaDerived=new Derived({deps:[this.baseStore],fn:({prevDepVals:e,currDepVals:t,prevVal:i})=>{const s=i,a=e?.[0],o=t[0];let r=0;const n={};for(const e of Object.keys(o.fieldMetaBase)){const t=o.fieldMetaBase[e],i=a?.fieldMetaBase[e],l=s?.[e],d=mt(o.values,e);let c=l?.errors;if(!i||t.errorMap!==i.errorMap){c=Object.values(t.errorMap??{}).filter(e=>void 0!==e);const i=this.getFieldInfo(e)?.instance;i&&!i.options.disableErrorFlat&&(c=c?.flat(1))}const p=!$t(c??[]),h=!t.isDirty,u=Et(d,mt(this.options.defaultValues,e))||Et(d,this.getFieldInfo(e)?.instance?.options.defaultValue);l&&l.isPristine===h&&l.isValid===p&&l.isDefaultValue===u&&l.errors===c&&t===i?(n[e]=l,r++):n[e]={...t,errors:c,isPristine:h,isValid:p,isDefaultValue:u}}return Object.keys(o.fieldMetaBase).length&&s&&r===Object.keys(o.fieldMetaBase).length?s:n}}),this.store=new Derived({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:e,currDepVals:t,prevVal:i})=>{const s=i,a=e?.[0],o=t[0],r=t[1],n=Object.values(r).filter(Boolean),l=n.some(e=>e.isValidating),d=n.every(e=>e.isValid),c=n.some(e=>e.isTouched),p=n.some(e=>e.isBlurred),h=n.every(e=>e.isDefaultValue),u=c&&o.errorMap?.onMount,m=n.some(e=>e.isDirty),v=!m,f=Boolean(o.errorMap?.onMount||n.some(e=>e?.errorMap?.onMount)),g=!!l;let y=s?.errors??[];a&&o.errorMap===a.errorMap||(y=Object.values(o.errorMap).reduce((e,t)=>void 0===t?e:t&&Pt(t)?(e.push(t.form),e):(e.push(t),e),[]));const b=0===y.length,w=d&&b,_=this.options.canSubmitWhenInvalid??!1,x=0===o.submissionAttempts&&!c&&!f||!g&&!o.isSubmitting&&w||_;let S=o.errorMap;if(u&&(y=y.filter(e=>e!==o.errorMap.onMount),S=Object.assign(S,{onMount:void 0})),s&&a&&s.errorMap===S&&s.fieldMeta===this.fieldMetaDerived.state&&s.errors===y&&s.isFieldsValidating===l&&s.isFieldsValid===d&&s.isFormValid===b&&s.isValid===w&&s.canSubmit===x&&s.isTouched===c&&s.isBlurred===p&&s.isPristine===v&&s.isDefaultValue===h&&s.isDirty===m&&Et(a,o))return s;let $={...o,errorMap:S,fieldMeta:this.fieldMetaDerived.state,errors:y,isFieldsValidating:l,isFieldsValid:d,isFormValid:b,isValid:w,canSubmit:x,isTouched:c,isBlurred:p,isPristine:v,isDefaultValue:h,isDirty:m};const k=this.options.transform?.deps??[],C=k.length!==this.prevTransformArray.length||k.some((e,t)=>e!==this.prevTransformArray[t]);if(C){const e=Object.assign({},this,{state:$});this.options.transform?.fn(e),$=e.state,this.prevTransformArray=k}return $}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(e||{}),this.store.subscribe(()=>{Ot.emit("form-state-change",{id:this._formId,state:this.store.state,options:this.options})}),Ot.on("request-form-state",e=>{e.payload.id===this._formId&&Ot.emit("form-state-change",{id:this._formId,state:this.store.state,options:this.options})}),Ot.on("request-form-reset",e=>{e.payload.id===this._formId&&this.reset()}),Ot.on("request-form-force-submit",e=>{e.payload.id===this._formId&&(this._devtoolsSubmissionOverride=!0,this.handleSubmit(),this._devtoolsSubmissionOverride=!1)})}get state(){return this.store.state}get formId(){return this._formId}runValidator(e){return jt(e.validate)?Lt[e.type](e.value,e.validate):e.validate(e.value)}async handleSubmit(e){if(this.baseStore.setState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),ht(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance&&(e.instance.state.meta.isTouched||e.instance.setMeta(e=>({...e,isTouched:!0})))})}),!this.state.canSubmit&&!this._devtoolsSubmissionOverride)return;const t=e??this.options.onSubmitMeta;this.baseStore.setState(e=>({...e,isSubmitting:!0}));const i=()=>{this.baseStore.setState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields("submit"),!this.state.isFieldsValid)return i(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),void Ot.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(e=>e.errors).flat()});if(await this.validate("submit"),!this.state.isValid)return i(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),void Ot.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"validate",errors:this.state.errors});ht(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance?.options.listeners?.onSubmit?.({value:e.instance.state.value,fieldApi:e.instance})})}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await(this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t})),ht(()=>{this.baseStore.setState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),Ot.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),i()})}catch(e){throw this.baseStore.setState(e=>({...e,isSubmitSuccessful:!1})),Ot.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"inflight",onError:e}),i(),e}}setErrorMap(e){ht(()=>{Object.entries(e).forEach(([e,t])=>{const i=e;if(Pt(t)){const{formError:e,fieldErrors:s}=Nt(t);for(const e of Object.keys(this.fieldInfo)){this.getFieldMeta(e)&&this.setFieldMeta(e,t=>({...t,errorMap:{...t.errorMap,[i]:s?.[e]},errorSourceMap:{...t.errorSourceMap,[i]:"form"}}))}this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[i]:e}}))}else this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[i]:t}}))})})}}function Nt(e){if(e){if(Pt(e)){return{formError:Nt(e.form).formError,fieldErrors:e.fields}}return{formError:e}}return{formError:void 0}}function Rt(e){switch(e){case"submit":return"onSubmit";case"blur":return"onBlur";case"mount":return"onMount";case"server":return"onServer";case"dynamic":return"onDynamic";default:return"onChange"}}class FieldApi{constructor(e){this.options={},this.mount=()=>{const e=this.store.mount();void 0!==this.options.defaultValue&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:!0});this.getInfo().instance=this,this.update(this.options);const{onMount:t}=this.options.validators||{};if(t){const e=this.runValidator({validate:t,value:{value:this.state.value,fieldApi:this,validationSource:"field"},type:"validate"});e&&this.setMeta(t=>({...t,errorMap:{...t?.errorMap,onMount:e},errorSourceMap:{...t?.errorSourceMap,onMount:"field"}}))}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),e},this.update=e=>{this.options=e;const t=this.name!==e.name;if(this.name=e.name,void 0===this.state.value){const i=mt(e.form.options.defaultValues,e.name),s=e.defaultValue??i;t?this.setValue(e=>e||s,{dontUpdateMeta:!0}):void 0!==s&&this.setValue(s,{dontUpdateMeta:!0})}void 0===this.form.getFieldMeta(this.name)&&this.setMeta(this.state.meta)},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,At(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate("change")},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(e,t)=>{this.form.pushFieldValue(this.name,e,At(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(e,t,i)=>{this.form.insertFieldValue(this.name,e,t,At(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(e,t,i)=>{this.form.replaceFieldValue(this.name,e,t,At(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(e,t)=>{this.form.removeFieldValue(this.name,e,At(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(e,t,i)=>{this.form.swapFieldValues(this.name,e,t,At(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(e,t,i)=>{this.form.moveFieldValues(this.name,e,t,At(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=e=>{this.form.clearFieldValues(this.name,At(e,{dontRunListeners:!0})),e?.dontRunListeners||this.triggerOnChangeListener()},this.getLinkedFields=e=>{const t=Object.values(this.form.fieldInfo),i=[];for(const s of t){if(!s.instance)continue;const{onChangeListenTo:t,onBlurListenTo:a}=s.instance.options.validators||{};"change"===e&&t?.includes(this.name)&&i.push(s.instance),"blur"===e&&a?.includes(this.name)&&i.push(s.instance)}return i},this.validateSync=(e,t)=>{const i=kt(e,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Dt}),s=this.getLinkedFields(e).reduce((t,i)=>{const s=kt(e,{...i.options,form:i.form,validationLogic:i.form.options.validationLogic||Dt});return s.forEach(e=>{e.field=i}),t.concat(s)},[]);let a=!1;ht(()=>{const e=(e,i)=>{const s=Qt(i.cause),o=i.validate?Wt(e.runValidator({validate:i.validate,value:{value:e.store.state.value,validationSource:"field",fieldApi:e},type:"validate"})):void 0,r=t[s],{newErrorValue:n,newSource:l}=It({formLevelError:r,fieldLevelError:o});e.state.meta.errorMap?.[s]!==n&&e.setMeta(e=>({...e,errorMap:{...e.errorMap,[s]:n},errorSourceMap:{...e.errorSourceMap,[s]:l}})),n&&(a=!0)};for(const t of i)e(this,t);for(const t of s)t.validate&&e(t.field,t)});const o=Qt("submit");return this.state.meta.errorMap?.[o]&&"submit"!==e&&!a&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[o]:void 0},errorSourceMap:{...e.errorSourceMap,[o]:void 0}})),{hasErrored:a}},this.validateAsync=async(e,t)=>{const i=Ct(e,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||Dt}),s=await t,a=this.getLinkedFields(e),o=a.reduce((t,i)=>{const s=Ct(e,{...i.options,form:i.form,validationLogic:i.form.options.validationLogic||Dt});return s.forEach(e=>{e.field=i}),t.concat(s)},[]);this.state.meta.isValidating||this.setMeta(e=>({...e,isValidating:!0}));for(const e of a)e.setMeta(e=>({...e,isValidating:!0}));const r=[],n=[],l=(e,t,i)=>{const a=Qt(t.cause),o=e.getInfo().validationMetaMap[a];o?.lastAbortController.abort();const r=new AbortController;this.getInfo().validationMetaMap[a]={lastAbortController:r},i.push(new Promise(async i=>{let o;try{o=await new Promise((i,s)=>{this.timeoutIds.validations[t.cause]&&clearTimeout(this.timeoutIds.validations[t.cause]),this.timeoutIds.validations[t.cause]=setTimeout(async()=>{if(r.signal.aborted)return i(void 0);try{i(await this.runValidator({validate:t.validate,value:{value:e.store.state.value,fieldApi:e,signal:r.signal,validationSource:"field"},type:"validateAsync"}))}catch(e){s(e)}},t.debounceMs)})}catch(e){o=e}if(r.signal.aborted)return i(void 0);const n=Wt(o),l=s[this.name]?.[a],{newErrorValue:d,newSource:c}=It({formLevelError:l,fieldLevelError:n});e.setMeta(e=>({...e,errorMap:{...e?.errorMap,[a]:d},errorSourceMap:{...e.errorSourceMap,[a]:c}})),i(d)}))};for(const e of i)e.validate&&l(this,e,r);for(const e of o)e.validate&&l(e.field,e,n);let d=[];(r.length||n.length)&&(d=await Promise.all(r),await Promise.all(n)),this.setMeta(e=>({...e,isValidating:!1}));for(const e of a)e.setMeta(e=>({...e,isValidating:!1}));return d.filter(Boolean)},this.validate=(e,t)=>{if(!this.state.meta.isTouched)return[];const{fieldsErrorMap:i}=t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e),{hasErrored:s}=this.validateSync(e,i[this.name]??{});if(s&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Qt(e)]?.lastAbortController.abort(),this.state.meta.errors;const a=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e);return this.validateAsync(e,a)},this.handleChange=e=>{this.setValue(e)},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(e=>({...e,isTouched:!0})),this.state.meta.isBlurred||this.setMeta(e=>({...e,isBlurred:!0})),this.validate("blur"),this.triggerOnBlurListener()},this.parseValueWithSchema=e=>Lt.validate({value:this.state.value,validationSource:"field"},e),this.parseValueWithSchemaAsync=e=>Lt.validateAsync({value:this.state.value,validationSource:"field"},e),this.form=e.form,this.name=e.name,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=new Derived({deps:[this.form.store],fn:()=>({value:this.form.getFieldValue(this.name),meta:this.form.getFieldMeta(this.name)??{...Bt,...e.defaultMeta}})}),this.options=e}get state(){return this.store.state}runValidator(e){return jt(e.validate)?Lt[e.type](e.value,e.validate):e.validate(e.value)}setErrorMap(e){this.setMeta(t=>({...t,errorMap:{...t.errorMap,...e}}))}triggerOnBlurListener(){const e=this.form.options.listeners?.onBlurDebounceMs;e&&e>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});const t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})}triggerOnChangeListener(){const e=this.form.options.listeners?.onChangeDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});const t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this})}}function Wt(e){if(e)return e}function Qt(e){switch(e){case"submit":return"onSubmit";case"blur":return"onBlur";case"mount":return"onMount";case"server":return"onServer";case"dynamic":return"onDynamic";default:return"onChange"}}var Ht,Kt,Gt,Zt,Jt,Xt=function(e,t,i,s,a){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?a.call(e,i):a?a.value=i:t.set(e,i),i},Yt=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class TanStackFormController{constructor(e,t){Ht.set(this,void 0),Kt.set(this,void 0),this.api=new FormApi(t),Xt(this,Ht,e,"f").addController(this)}hostConnected(){Xt(this,Kt,this.api.store.subscribe(()=>{Yt(this,Ht,"f").requestUpdate()}),"f")}hostDisconnected(){Yt(this,Kt,"f")?.call(this)}field(e,t){return ei(this.api,e,t)}}Ht=new WeakMap,Kt=new WeakMap;Gt=new WeakMap,Zt=new WeakMap,Jt=new WeakMap;const ei=ie(class FieldDirective extends re{constructor(e){if(super(e),Gt.set(this,!1),Zt.set(this,void 0),Jt.set(this,void 0),e.type!==ae.CHILD)throw new Error("The `field` directive must be used in the `child` attribute")}update(e,[t,i,s]){if(!Yt(this,Gt,"f")){if(!Yt(this,Zt,"f")){const e={...i,form:t};Xt(this,Zt,new FieldApi(e),"f"),Xt(this,Jt,Yt(this,Zt,"f").mount(),"f")}Xt(this,Gt,!0,"f")}return this.render(t,i,s)}disconnected(){super.disconnected(),Yt(this,Jt,"f")?.call(this)}reconnected(){super.reconnected(),Yt(this,Zt,"f")&&Xt(this,Jt,Yt(this,Zt,"f").mount(),"f")}render(e,t,i){return Yt(this,Zt,"f")?i(Yt(this,Zt,"f")):Z}}),ti=J`.form-container{display:flex;flex-direction:column;gap:var(--size-4)}.form-content{display:flex;flex-direction:column;gap:var(--size-4);width:100%}.field{display:flex;flex-direction:column;gap:var(--size-2);width:100%}.field-title{font-family:var(--font-body);font-size:var(--text-base);font-weight:var(--font-weight-bold);line-height:22px;color:var(--color-neutrals-text-default);margin:0}.field-error{font-style:normal;color:var(--color-error-text-default);font-size:var(--text-base);line-height:var(--text-base--line-height);font-weight:var(--font-weight-normal)}.field.hidden{display:none}`,ii=fe.object({first_name:fe.string({required_error:"required"}).min(1,"required"),last_name:fe.string({required_error:"required"}).min(1,"required"),email:fe.string({required_error:"required"}).email("email_invalid").min(1,"required"),phone:fe.string({required_error:"required"}).min(9,"phone_invalid"),birth_date:fe.string({required_error:"required"}).min(1,"required"),tax_id:fe.string({required_error:"required"}).min(1,"required")});class CompleteProfileFormSuccessEvent extends CustomEvent{static{this.eventName="success"}constructor(e){super(CompleteProfileFormSuccessEvent.eventName,{bubbles:!0,composed:!0,detail:e})}}let si=class CompleteProfileForm extends X{constructor(){super(...arguments),this.isPending=!1,this.errorMap={required:H("Este campo es obligatorio"),email_invalid:H("El email no es válido"),phone_invalid:H("El teléfono no es válido")},this.form=new TanStackFormController(this,{defaultValues:this.defaultValues,onSubmit:e=>{this.dispatchEvent(new CompleteProfileFormSuccessEvent(e.value))},validators:{onSubmit:ii}}),this.getScheduleServicesQuery=new i(this,()=>S(this.apiClient))}static{this.styles=ti}translateError(e){return this.errorMap[e]||e}willUpdate(e){e.has("defaultValues")&&(this.form.api.setFieldValue("first_name",this.defaultValues.first_name),this.form.api.setFieldValue("last_name",this.defaultValues.last_name),this.form.api.setFieldValue("email",this.defaultValues.email),this.form.api.setFieldValue("phone",this.defaultValues.phone),this.form.api.setFieldValue("birth_date",this.defaultValues.birth_date),this.form.api.setFieldValue("tax_id",this.defaultValues.tax_id))}render(){const e=this.getScheduleServicesQuery.result?.data?.find(e=>e.id===this.serviceId),t=e?.channel===z.phonecall;return Y`<div class="form-container"><form class="form-content" @submit="${e=>{e.preventDefault(),e.stopPropagation(),this.form.api.handleSubmit()}}"><div class="${me({field:!0,hidden:!!this.defaultValues.first_name})}">${this.form.field({name:"first_name"},e=>Y`<mq-input label="${H("Nombre")}" id="${ve(e.name)}" value="${ve(e.state.value)}" name="${ve(e.name)}" required ?error="${!e.state.meta.isValid}" @onvaluechange="${t=>{e.handleChange(t.value)}}"></mq-input>${!e.state.meta.isValid&&e.state.meta.errors.length>0?Y`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:Z}`)}</div><div class="${me({field:!0,hidden:!!this.defaultValues.last_name})}">${this.form.field({name:"last_name"},e=>Y`<mq-input label="${H("Apellidos")}" id="${ve(e.name)}" value="${ve(e.state.value)}" name="${ve(e.name)}" required ?error="${!e.state.meta.isValid}" @onvaluechange="${t=>{e.handleChange(t.value)}}"></mq-input>${!e.state.meta.isValid&&e.state.meta.errors.length>0?Y`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:Z}`)}</div><div class="${me({field:!0,hidden:!!this.defaultValues.email})}">${this.form.field({name:"email"},e=>Y`<mq-input type="email" label="${H("Email")}" id="${ve(e.name)}" value="${ve(e.state.value)}" name="${ve(e.name)}" required ?error="${!e.state.meta.isValid}" @onvaluechange="${t=>{e.handleChange(t.value)}}"></mq-input>${!e.state.meta.isValid&&e.state.meta.errors.length>0?Y`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:Z}`)}</div><div class="${me({field:!0,hidden:!!this.defaultValues.phone})}">${this.form.field({name:"phone"},e=>Y`<mq-input type="tel" label="${H("Teléfono")}" id="${ve(e.name)}" value="${ve(e.state.value)}" name="${ve(e.name)}" required ?error="${!e.state.meta.isValid}" @onvaluechange="${t=>{e.handleChange(t.value)}}"></mq-input>${!e.state.meta.isValid&&e.state.meta.errors.length>0?Y`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:Z}`)}</div><div class="${me({field:!0,hidden:!!this.defaultValues.birth_date})}">${this.form.field({name:"birth_date"},e=>Y`<mq-input type="date" label="${H("Fecha de nacimiento")}" id="${ve(e.name)}" value="${ve(e.state.value)}" name="${ve(e.name)}" required ?error="${!e.state.meta.isValid}" @onvaluechange="${t=>{e.handleChange(t.value)}}"></mq-input>${!e.state.meta.isValid&&e.state.meta.errors.length>0?Y`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:Z}`)}</div><div class="${me({field:!0,hidden:!!this.defaultValues.tax_id})}">${this.form.field({name:"tax_id"},e=>Y`<mq-input label="${H("DNI/NIE")}" id="${ve(e.name)}" value="${ve(e.state.value)}" name="${ve(e.name)}" required ?error="${!e.state.meta.isValid}" @onvaluechange="${t=>{e.handleChange(t.value)}}"></mq-input>${!e.state.meta.isValid&&e.state.meta.errors.length>0?Y`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:Z}`)}</div>${t?Y`<mq-callout background="default" variant="info" noPadding>${H("El profesional te llamará al número que indiques en este campo.")}</mq-callout>`:Z}<mq-button type="submit" fullwidth size="xl" ?disabled="${this.isPending}">${H("Continuar")}</mq-button></form></div>`}};e([Q({context:s,subscribe:!0})],si.prototype,"apiClient",void 0),e([ee({type:Boolean})],si.prototype,"isPending",void 0),e([ee({type:String})],si.prototype,"serviceId",void 0),e([ee({type:Object})],si.prototype,"defaultValues",void 0),si=e([G(),t("complete-profile-form")],si);const ai=J`:host{display:block}.trigger{width:100%;display:flex;align-items:center;gap:var(--sp-1);padding:0;border:none;background:0 0;cursor:pointer;font-family:var(--font-titles);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);color:var(--color-primary)}.trigger:focus-visible{outline:2px solid var(--color-primary);outline-offset:2px;border-radius:var(--border-radius-sm)}.trigger__label{flex:1;text-align:left}.chevron{transition:transform .2s ease}.chevron--open{transform:rotate(180deg)}.reveal{display:grid;grid-template-rows:0fr;overflow:hidden;transition:grid-template-rows .2s ease-out}.reveal[data-expanded=true]{grid-template-rows:1fr}.reveal__content{min-height:0;overflow:hidden}.field{display:flex;flex-direction:column;gap:var(--sp-2);margin-top:var(--sp-3)}.row{display:flex;gap:var(--sp-2)}.input{box-sizing:border-box;flex:1;min-width:0;height:var(--size-9);padding:var(--sp-1) var(--sp-3);border:1px solid var(--color-neutrals-border-disabled);border-radius:var(--border-radius-md);background:var(--color-neutrals-background-extraWeak,var(--color-white));font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);color:var(--color-neutrals-text-default);outline:0;transition:border-color .2s ease}.input::placeholder{color:var(--color-text-icons--secondary)}.input:focus{border-color:var(--color-primary)}.input--error{border-color:var(--color-error-text-default)}.error{margin:0;font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);color:var(--color-error-text-default)}.btn{box-sizing:border-box;flex:0 0 auto;height:var(--size-9);display:flex;align-items:center;justify-content:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-6);border:1px solid var(--color-primary);border-radius:var(--border-radius-md);background:var(--color-primary);color:var(--color-white);font-family:var(--font-titles);font-size:var(--text-xs);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-medium);cursor:pointer;transition:background-color .2s ease,opacity .2s ease}.btn:hover:not(:disabled){background:var(--color-primary-dark);border-color:var(--color-primary-dark)}.btn:focus-visible{outline:2px solid var(--color-primary);outline-offset:2px}.btn:disabled{opacity:.5;cursor:default}.applied{display:flex;flex-direction:column;gap:var(--sp-3)}.applied__status{display:flex;align-items:center;gap:var(--sp-1);font-family:var(--font-titles);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);color:var(--color-text-icons--success-dark,#105b5b)}.applied__change{display:inline-flex;align-items:center;gap:var(--sp-1);align-self:flex-start;padding:0;border:none;background:0 0;cursor:pointer;font-family:var(--font-titles);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);text-decoration:underline;color:var(--color-text-icons--secondary)}.applied__change:focus-visible{outline:2px solid var(--color-primary);outline-offset:2px;border-radius:var(--border-radius-sm)}`;let oi=class DiscountCodeField extends X{constructor(){super(...arguments),this.basePrice=null,this.appliedDiscount=null,this.expanded=!1,this.form=new TanStackFormController(this,{defaultValues:{code:""}})}static{this.styles=ai}async validateCode(e){const t=e.trim();if(this.basePrice&&""!==t)try{const e=await async function(e,t){const{basePrice:i}=t,s=t.code.trim();try{const t=await e.payments.getConsultationCoupon(s,i.amount),a=t.percent_off,o=t.after_discount_amount??i.amount-Math.round(i.amount*a/100);return{code:s,percentage:a,discountAmount:i.amount-o,totalAmount:o,currency:i.currency}}catch(e){if(D(e)&&404===e.response?.status)throw new InvalidDiscountCodeError;throw e}}(this.apiClient,{code:t,basePrice:this.basePrice});return this.dispatchEvent(new DiscountAppliedEvent(e)),this.expanded=!1,void this.form.api.reset()}catch(e){return H(e instanceof InvalidDiscountCodeError?"Este código no es válido.":"No hemos podido validar el código. Inténtalo de nuevo.")}}toggle(){this.expanded=!this.expanded}onChangeCode(){this.form.api.reset(),this.expanded=!0}renderInputForm(){const{isSubmitting:e,values:t}=this.form.api.state;return Y`<form class="field" @submit="${e=>{e.preventDefault(),e.stopPropagation(),this.form.api.handleSubmit()}}">${this.form.field({name:"code",validators:{onSubmitAsync:({value:e})=>this.validateCode(e)}},i=>{const s=i.state.meta.errors[0];return Y`<div class="row"><input class="input ${s?"input--error":""}" type="text" .value="${i.state.value}" ?disabled="${e}" placeholder="${H("Ingresa el código")}" @input="${e=>i.handleChange(e.target.value)}"> <button type="submit" class="btn" ?disabled="${!t.code.trim()||e}">${e?Y`${ge({color:"currentColor",size:16})}`:H("Aplicar")}</button></div>${s?Y`<p class="error">${s}</p>`:Z}`})}</form>`}render(){return this.appliedDiscount&&!this.expanded?Y`<div class="applied"><span class="applied__status" role="status">${Y`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M20 6L9 17L4 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`} ${H("Código de promoción aplicado")} </span><button type="button" class="applied__change" @click="${this.onChangeCode}">${Y`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 8H20M20 8L16 4M20 8L16 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M20 16H4M4 16L8 12M4 16L8 20" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`} ${H("Cambiar código")}</button></div>`:Y`<button type="button" class="trigger" aria-expanded="${this.expanded}" @click="${this.toggle}">${ye({size:20})} <span class="trigger__label">${H("Añadir código de promoción")}</span> ${e=this.expanded,Y`<svg class="chevron ${e?"chevron--open":""}" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 9L12 15L18 9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`}</button><div class="reveal" data-expanded="${this.expanded}" .inert="${!this.expanded}"><div class="reveal__content">${this.renderInputForm()}</div></div>`;var e}};e([Q({context:s,subscribe:!0})],oi.prototype,"apiClient",void 0),e([ee({type:Object})],oi.prototype,"basePrice",void 0),e([ee({type:Object})],oi.prototype,"appliedDiscount",void 0),e([te()],oi.prototype,"expanded",void 0),oi=e([G(),t("discount-code-field")],oi);const ri=J`.summary{box-sizing:border-box;max-width:var(--content-max-width);margin:0 auto;padding:var(--sp-4);display:flex;flex-direction:column;gap:var(--sp-4)}hr{width:100%;border:none;border-top:1px solid var(--color-neutrals-border-disabled);margin:0}.payment-info{display:flex;justify-content:space-between;color:var(--color-neutrals-text-default);font-size:16px}.payment-info__name{font-weight:600}.payment-info__price{font-weight:500}.discount-info{display:flex;justify-content:space-between;gap:var(--sp-4);color:var(--color-neutrals-text-default);font-size:var(--text-base)}.total-info{display:flex;justify-content:space-between;gap:var(--sp-4);color:var(--color-neutrals-text-default);font-size:var(--text-base);font-weight:600}.previous-starts-at{font-family:var(--font-body);font-size:var(--text-base);line-height:var(--text-base--line-height);color:var(--color-neutrals-text-default)}.reservation-conditions{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);color:var(--color-text-icons--secondary)}.reservation-conditions__prefix{font-weight:var(--font-weight-semibold)}.reservation-conditions__body{font-weight:var(--font-weight-normal)}:host([fill-column]){width:100%;min-width:0;align-self:flex-start}:host([fill-column]) .summary{max-width:none;margin:0}@media (min-width:768px){.summary{padding:var(--sp-6)}}`;let ni=class NewAppointmentSummary extends X{constructor(){super(...arguments),this.startsAt=void 0,this.duration=void 0,this.channel=void 0,this.previousStartsAt=void 0,this.previousDuration=void 0,this.serviceCode=void 0,this.serviceName=void 0,this.servicePrice=null,this.fillColumn=!1,this.appliedDiscount=null,this.showPrice=!0,this.onDiscountApplied=e=>{this.appliedDiscount=e.detail,xe.success(H("Código de promoción validado correctamente"))},this.getOrganizationSpecialtiesQuery=new i(this,()=>d(this.apiClient,{enabled:!!this.professional?.speciality.id})),this.getOrganizationSetupQuery=new i(this,()=>r(this.apiClient))}static{this.styles=ri}renderAppointmentDetails(){return Y`${this.startsAt&&this.channel&&this.duration?Y`<appointment-details .startsAt="${$(this.startsAt).toISOString()}" .duration="${this.duration}" .channel="${this.channel}" .timezone="${this.patient.timezone}" variant="wide"></appointment-details>`:Z} ${this.previousStartsAt&&this.previousDuration?Y`<hr><span class="previous-starts-at">${H("Cita previa:")}</span><appointment-details .startsAt="${$(this.previousStartsAt).toISOString()}" .duration="${this.previousDuration}" .timezone="${this.patient.timezone}" strike-through variant="wide"></appointment-details>`:Z}`}render(){const e=le(),t=this.getOrganizationSpecialtiesQuery.result?.data?.find(e=>e.id===this.professional?.speciality.id),i=c(t?.code??"",e,t?.name),s=this.serviceCode?p(this.serviceCode,e,this.serviceName):this.serviceName??"",a=this.getOrganizationSetupQuery.result?.data?.appointments,o=a?.reserve_conditions?.trim()??"",r=!0===a?.has_discount_coupons_show&&a?.payment_provider!==L.Stripe,n=this.servicePrice;return Y`<mq-card class="summary" roundness="md"><professional-overview .name="${this.professional.name??""}" .specialtyName="${i??""}" .collegiateNumber="${this.professional.collegiate_number??void 0}" .description="${this.professional.description??""}" .languages="${this.professional.languages}" .avatar="${this.professional.avatar??""}" always-expanded-on-desktop></professional-overview>${this.renderAppointmentDetails()} ${be(n)?Y`${this.showPrice?Y`${r?Y`<discount-code-field .basePrice="${{amount:n.amount,currency:n.currency}}" .appliedDiscount="${this.appliedDiscount}" @discount-applied="${this.onDiscountApplied}"></discount-code-field>`:Z}<div class="payment-info">${s?Y`<span class="payment-info__name">${s}</span>`:Z} <span class="payment-info__price">${we({amount:n.amount,currency:n.currency},e)}</span></div>${r&&this.appliedDiscount?Y`<div class="discount-info"><span>${H("Promoción")} ${this.appliedDiscount.code} (-${this.appliedDiscount.percentage}%)</span> <span>${we({amount:-this.appliedDiscount.discountAmount,currency:this.appliedDiscount.currency},e)}</span></div><hr><div class="total-info"><span>${H("Total")}</span> <span>${we({amount:this.appliedDiscount.totalAmount,currency:this.appliedDiscount.currency},e)}</span></div>`:Z}`:Z} ${o.length>0?Y`<hr><mq-clamped-text class="reservation-conditions" .lines="${2}" expand-label="${H("Ver más")}" collapse-label="${H("Ver menos")}"><span class="reservation-conditions__prefix">${H("Condiciones de reserva:")}</span> ${" "} <span class="reservation-conditions__body">${o}</span></mq-clamped-text>`:Z}`:Z}</mq-card>`}};e([Q({context:s,subscribe:!0})],ni.prototype,"apiClient",void 0),e([ee({type:Object})],ni.prototype,"professional",void 0),e([ee({type:String})],ni.prototype,"startsAt",void 0),e([ee({type:Number})],ni.prototype,"duration",void 0),e([ee({type:String})],ni.prototype,"channel",void 0),e([ee({type:String})],ni.prototype,"previousStartsAt",void 0),e([ee({type:Number})],ni.prototype,"previousDuration",void 0),e([ee({type:String})],ni.prototype,"serviceCode",void 0),e([ee({type:String})],ni.prototype,"serviceName",void 0),e([ee({type:Object})],ni.prototype,"servicePrice",void 0),e([ee({type:Boolean,attribute:"fill-column",reflect:!0})],ni.prototype,"fillColumn",void 0),e([ee({type:Object})],ni.prototype,"appliedDiscount",void 0),e([ee({type:Boolean})],ni.prototype,"showPrice",void 0),e([Q({context:Re,subscribe:!0})],ni.prototype,"patient",void 0),ni=e([G(),t("new-appointment-summary")],ni);let li=class CompleteProfileStep extends X{constructor(){super(...arguments),this.showBack=!0,this.channel=void 0,this.getPatientProfileQuery=new i(this,()=>w(this.apiClient)),this.updatePatientProfileMutation=new ue(this,{mutationFn:async e=>this.apiClient.flash.updatePatientProfile(e)})}static{this.styles=J`.content{box-sizing:border-box;display:flex;flex-direction:column;gap:var(--sp-6)}.right-side{padding:var(--sp-4);background-color:var(--color-neutrals-background-weak)}h2{font-family:var(--font-titles);font-size:var(--text-2xl);line-height:var(--text-2xl--line-height);font-weight:var(--font-weight-bold);margin:0;margin-bottom:var(--sp-4)}@media (min-width:768px){.content{flex-direction:row;align-items:start;gap:var(--sp-6)}.right-side{width:50%;padding:var(--sp-6)}new-appointment-summary{width:50%}}`}handleSubmit(e){const t=e.detail;this.updatePatientProfileMutation.run({first_name:t.first_name,last_name:t.last_name,email:t.email,phone:t.phone,birth_date:t.birth_date,phone_prefix:"+34",tax_id:t.tax_id,privacy_accepted:!0,terms_accepted:!0}),this.dispatchEvent(new CustomEvent("success"))}render(){return this.getPatientProfileQuery.render({complete:e=>Y`<mq-page-title .title="${H("Petición de cita")}" .showBack="${this.showBack}" @mq-back="${e=>et(this,e)}"></mq-page-title><div class="content"><new-appointment-summary .professional="${this.professional}" .startsAt="${this.scheduleSlot.starts_at}" .duration="${this.scheduleSlot.duration}" .channel="${this.channel??this.scheduleSlot.channel}"></new-appointment-summary><div class="right-side"><h2>${H("Completa tu perfil")}</h2><complete-profile-form .serviceId="${this.serviceId}" @success="${this.handleSubmit}" .defaultValues="${{first_name:e?.profile.first_name,last_name:e?.profile.last_name,email:e?.profile.email,phone_prefix:e?.profile.phone_prefix,phone:e?.profile.phone,birth_date:e?.profile.birth_date,gender:e?.profile.gender,tax_id:e?.profile.billing.tax_id}}" .isPending="${this.updatePatientProfileMutation.isPending}"></complete-profile-form></div></div>`})}};e([Q({context:s,subscribe:!0})],li.prototype,"apiClient",void 0),e([ee({type:String})],li.prototype,"serviceId",void 0),e([ee({type:Boolean})],li.prototype,"showBack",void 0),e([ee({type:Object})],li.prototype,"scheduleSlot",void 0),e([ee({type:Object})],li.prototype,"professional",void 0),e([ee({type:String})],li.prototype,"channel",void 0),li=e([G(),t("complete-profile-step")],li);const di=J`:host{display:block}.field{display:flex;flex-direction:column;gap:var(--sp-4)}.label{font-family:var(--font-body);font-size:var(--text-base);line-height:var(--text-base--line-height);font-weight:var(--font-weight-bold);color:var(--color-neutrals-text-default);margin:0}.hint{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);color:var(--color-neutrals-text-default);margin:0}.files{display:flex;flex-direction:column;gap:var(--sp-2)}.file{font-family:var(--font-body);border-radius:var(--border-radius-md);padding:var(--sp-2);display:flex;align-items:center;justify-content:space-between;gap:var(--sp-1);background-color:var(--color-white)}.file.uploading{opacity:.5;pointer-events:none}.file-info{flex:1;display:flex;align-items:center;gap:var(--sp-2);font-size:var(--text-xs);line-height:var(--text-xs--line-height);font-weight:var(--font-weight-bold);color:var(--color-neutrals-text-default);margin:0;min-width:0}.file-info svg{flex-shrink:0}.file-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.file-close{line-height:0;flex-shrink:0}@keyframes animate-spin{from{transform:rotate(0)}to{transform:rotate(360deg)}}.animate-spin{animation:animate-spin 750ms linear infinite}@media (min-width:768px){mq-button{max-width:323px;margin:0 auto}}`;class FileAttachmentsChangeEvent extends CustomEvent{static{this.eventName="onfileschange"}constructor(e){super(FileAttachmentsChangeEvent.eventName,{bubbles:!0,composed:!0,detail:{files:e}})}}let ci=class FileAttachments extends X{constructor(){super(...arguments),this.uploadedFiles=[],this.uploadingFile=null,this.uploadFileMutation=new ue(this,{mutationFn:e=>this.apiClient.documents.uploadFile({file:e}),throwOnError:!0})}static{this.styles=di}handleClickUploadFile(){const e=this.shadowRoot?.querySelector("input[type='file']");e&&e.click()}getErrorMessageFromCode(e){switch(e){case 422:default:return H("Ha ocurrido un error en el envío del archivo");case 413:return H("El archivo supera el tamaño máximo permitido");case 415:return H("Formato de archivo no soportado")}}async handleUploadFile(e){const t=e.target.files?.[0];if(t){if(t.size>314572800)return xe.error(H("El archivo supera el tamaño máximo permitido"),{duration:3e3}),void(this.fileInput.value="");this.uploadingFile=t;try{const e=await this.uploadFileMutation.run(t),i={id:crypto.randomUUID(),file_path:e.url,file_name:t.name},s=[...this.uploadedFiles,i];this.dispatchEvent(new CustomEvent("onfileschange",{bubbles:!0,composed:!0,detail:{files:s,newFile:i}})),this.uploadingFile=null}catch(e){if(!D(e))return;const t=this.getErrorMessageFromCode(e.response?.status??500);xe.error(t,{duration:3e3}),this.uploadingFile=null}finally{this.fileInput.value=""}}}handleRemoveFile(e){const t=this.uploadedFiles.filter((t,i)=>i!==e);this.dispatchEvent(new CustomEvent("onfileschange",{bubbles:!0,composed:!0,detail:{files:t}}))}render(){return Y`<div class="field"><input type="file" hidden @change="${this.handleUploadFile}"><p class="label">${H("Adjuntar archivos")}</p><p class="hint">${H("Puedes adjuntar imágenes o documentación adicional (analíticas, resultados de pruebas, etc.) para que los evalúe el médico")}</p><mq-button size="md" variant="outline" fullwidth @click="${this.handleClickUploadFile}">${ke()} ${H("Subir archivo")}</mq-button><div class="files">${this.uploadedFiles.map((e,t)=>Y`<div class="file"><div class="file-info">${$e()} <span class="file-name">${e.file_name}</span></div><div class="file-close"><mq-button size="icon-xs" variant="ghost" @click="${()=>this.handleRemoveFile(t)}">${Ce({color:"var(--color-neutrals-text-default)",size:24})}</mq-button></div></div>`)} ${this.uploadingFile?Y`<div class="file uploading"><div class="file-info">${Y`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="animate-spin"><path opacity="0.12" fill-rule="evenodd" clip-rule="evenodd" d="M12 4C9.87827 4 7.84344 4.84285 6.34315 6.34315C4.84285 7.84344 4 9.87827 4 12C4 14.1217 4.84285 16.1566 6.34315 17.6569C7.84344 19.1571 9.87827 20 12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12C20 9.87827 19.1571 7.84344 17.6569 6.34315C16.1566 4.84285 14.1217 4 12 4ZM2 12C2 6.477 6.477 2 12 2C17.523 2 22 6.477 22 12C22 17.523 17.523 22 12 22C6.477 22 2 17.523 2 12Z" fill="#333333"/><path fill-rule="evenodd" clip-rule="evenodd" d="M11.9985 4.00001C9.93591 3.99566 7.9522 4.7923 6.46551 6.22201C6.3707 6.31289 6.25891 6.3842 6.13654 6.43187C6.01417 6.47955 5.8836 6.50265 5.7523 6.49986C5.621 6.49708 5.49153 6.46846 5.37129 6.41564C5.25105 6.36282 5.14239 6.28683 5.05151 6.19201C4.96064 6.0972 4.88933 5.98541 4.84165 5.86304C4.79398 5.74067 4.77088 5.6101 4.77366 5.4788C4.77645 5.3475 4.80507 5.21803 4.85789 5.09779C4.91071 4.97755 4.9867 4.86889 5.08151 4.77801C6.94058 2.99145 9.42015 1.9956 11.9985 2.00001C12.2637 2.00001 12.5181 2.10537 12.7056 2.29291C12.8932 2.48044 12.9985 2.7348 12.9985 3.00001C12.9985 3.26523 12.8932 3.51959 12.7056 3.70712C12.5181 3.89466 12.2637 4.00001 11.9985 4.00001Z" fill="#333333"/></svg>`} <span class="file-name">${this.uploadingFile.name}</span></div></div>`:""}</div></div>`}};async function pi(e){const t=e.getApiClient();t&&await(e.getQueryClient()?.invalidateQueries({queryKey:_(t)}))}e([Q({context:s,subscribe:!0})],ci.prototype,"apiClient",void 0),e([ee({type:Array})],ci.prototype,"uploadedFiles",void 0),e([te()],ci.prototype,"uploadingFile",void 0),e([Se("input[type='file']")],ci.prototype,"fileInput",void 0),ci=e([G(),t("file-attachments")],ci);class ScheduleAppointmentMutationController{constructor(e,t){this.mutation=new ue(e,{mutationFn:e=>{const i=t.getApiClient();return i?function(e,t){return e.appointments.createAppointment(t)}(i,e):Promise.reject(new Error("No api client available"))},onSuccess:async e=>{await pi(t),await t.onSuccess(e.appointment.id)},onError:async()=>{await pi(t),await t.onError()}})}run(e){return this.mutation.run(function(e){return{slot_id:e.slotId,service_id:e.serviceId,consultation_reason:e.consultationReason,preconsultation_documents:e.preconsultationDocuments,discount_code:e.discountCode}}(e))}get isPending(){return this.mutation.isPending}get isError(){return this.mutation.isError}get isSuccess(){return this.mutation.isSuccess}get isIdle(){return this.mutation.isIdle}get data(){return this.mutation.data}get error(){return this.mutation.error}reset(){this.mutation.reset()}}const hi=J`:host{height:100%;display:flex;flex-direction:column;gap:var(--sp-4)}.content{display:flex;flex-direction:column;gap:var(--sp-4)}.questionnaire{width:100%;padding:var(--sp-4)}.questionnaire>:not(:last-child){margin-bottom:var(--sp-4)}.questionnaire-title{font-family:var(--font-titles);font-size:var(--text-2xl);line-height:var(--text-2xl--line-height);font-weight:var(--font-weight-bold);color:var(--color-neutrals-text-default);margin:0;margin-bottom:var(--sp-4)}.field{display:flex;flex-direction:column;gap:var(--sp-4)}.label{font-family:var(--font-body);font-size:var(--text-base);line-height:var(--text-base--line-height);font-weight:var(--font-weight-bold);color:var(--color-neutrals-text-default);margin:0}@media (min-width:768px){.content{flex-direction:row;gap:var(--sp-6)}new-appointment-summary{width:50%}.questionnaire{width:50%;padding:var(--sp-6)}}`;let ui=class SuccessEvent extends Event{static{this.eventName="success"}constructor(e){super(SuccessEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}};class PaymentStartedEvent extends Event{static{this.eventName="payment-started"}constructor(e){super(PaymentStartedEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}let mi=class ConfirmStep extends X{constructor(){super(...arguments),this.kind="schedule",this.showBack=!0,this.requiresPayment=!0,this.channel=void 0,this.appointment=void 0,this.specialityId="",this.service=void 0,this.appliedDiscount=null,this.reason="",this.attachedFiles=[],this.createScheduleAppointment=new ScheduleAppointmentMutationController(this,{getApiClient:()=>this.apiClient,getQueryClient:()=>this.queryClientContext,onSuccess:e=>{this.dispatchEvent(new ui({appointmentId:e}))},onError:()=>{this.dispatchEvent(new CustomEvent("error"))}}),this.rescheduleAppointmentMutation=new ue(this,{mutationFn:async e=>this.apiClient.appointments.rescheduleAppointment(e),onSuccess:async()=>{await(this.queryClientContext?.invalidateQueries({queryKey:_(this.apiClient)}));const e=this.appointment?.id;if(!e)return Pe.error("confirm-step: reschedule succeeded but appointment id is missing"),void this.dispatchEvent(new CustomEvent("error"));this.dispatchEvent(new ui({appointmentId:e}))},onError:async()=>{await(this.queryClientContext?.invalidateQueries({queryKey:_(this.apiClient)})),this.dispatchEvent(new CustomEvent("error"))}}),this.createPaymentLinkMutation=new ue(this,{mutationFn:async e=>({result:await this.apiClient.payments.createPaymentLink(e),request:e}),onSuccess:({result:e,request:t})=>{this.dispatchEvent(new PaymentStartedEvent({sessionId:e.session_id,paymentUrl:e.payment_link,request:t,provider:e.provider}))},onError:async()=>{await(this.queryClientContext?.invalidateQueries({queryKey:_(this.apiClient)})),this.dispatchEvent(new CustomEvent("error"))}})}static{this.styles=hi}get isPaymentFlow(){return this.requiresPayment&&"schedule"===this.kind&&be(this.service?.price)}get isFullyDiscounted(){return null!=this.appliedDiscount&&Ye(this.appliedDiscount)}get ctaLabel(){return this.isFullyDiscounted?H("Confirmar cita"):this.isPaymentFlow?H("Continuar al pago"):H("Continuar")}async handleSubmit(){if(h.track(u(this.patient.hash,this.professional.id??"",this.startsAt??"",this.specialityId,this.serviceId??"")),!this.isPaymentFlow||this.isFullyDiscounted)if("schedule"===this.kind)this.createScheduleAppointment.run({slotId:this.scheduleSlot.id,serviceId:this.serviceId,consultationReason:this.reason,preconsultationDocuments:this.attachedFiles,discountCode:this.isFullyDiscounted?this.appliedDiscount?.code:void 0});else{const e=this.appointment?.id;if(!e)return void this.dispatchEvent(new CustomEvent("error"));this.rescheduleAppointmentMutation.run({id:e,slot_id:this.scheduleSlot.id,consultation_reason:this.reason,preconsultation_documents:this.attachedFiles})}else this.createPaymentLinkMutation.run({slot_id:this.scheduleSlot.id,service_id:this.serviceId,specialty_id:this.specialityId,consultation_reason:this.reason,preconsultation_documents:this.attachedFiles,discount_code:this.appliedDiscount?.code,return_url:this.returnUrl,payable_reference:this.scheduleSlot.payable_reference??void 0})}handleFilesChange(e){this.attachedFiles=e.detail.files}firstUpdated(){!this.reason&&this.appointment&&(this.reason=this.appointment.consultation_reason??""),!this.attachedFiles.length&&this.appointment&&(this.attachedFiles=this.appointment.preconsultation_documents?.map(e=>({id:e.id,file_path:e.file_path,file_name:e.file_name}))??[])}render(){return Y`<mq-page-title .title="${"schedule"===this.kind?H("Petición de cita"):H("Modificar cita")}" .showBack="${this.showBack}" @mq-back="${e=>et(this,e)}"></mq-page-title><div class="content"><new-appointment-summary .professional="${this.professional}" .startsAt="${this.startsAt}" .duration="${this.duration}" .previousStartsAt="${this.appointment?.start_date}" .previousDuration="${this.appointment?.duration}" .channel="${this.channel??this.appointment?.channel}" .serviceCode="${this.service?.code}" .serviceName="${this.service?.name}" .servicePrice="${this.scheduleSlot?.speciality?.price??null}" .appliedDiscount="${this.appliedDiscount}" .showPrice="${"reschedule"!==this.kind}" @discount-applied="${e=>{this.appliedDiscount=e.detail}}"></new-appointment-summary><mq-card class="questionnaire" roundness="md"><p class="questionnaire-title">${H("Cuestionario preconsulta")}</p><div class="field"><p class="label">${H("Motivo de consulta")}</p><mq-textarea maxlength="${240}" label="${H("¿Por qué necesitas la consulta?")}" rows="${4}" .value="${this.reason}" @onvaluechange="${e=>{this.reason=e.value}}"></mq-textarea></div><file-attachments .uploadedFiles="${this.attachedFiles}" @onfileschange="${this.handleFilesChange}"></file-attachments><mq-button size="xl" type="button" ?disabled="${this.createScheduleAppointment.isPending||this.rescheduleAppointmentMutation.isPending||this.createPaymentLinkMutation.isPending}" @click="${this.handleSubmit}" fullwidth>${this.ctaLabel}</mq-button></mq-card></div>`}};e([Q({context:s,subscribe:!0})],mi.prototype,"apiClient",void 0),e([Q({context:Re,subscribe:!0})],mi.prototype,"patient",void 0),e([ee({type:String})],mi.prototype,"kind",void 0),e([ee({type:Boolean})],mi.prototype,"showBack",void 0),e([ee({type:Boolean})],mi.prototype,"requiresPayment",void 0),e([ee({type:Object})],mi.prototype,"scheduleSlot",void 0),e([ee({type:Object})],mi.prototype,"professional",void 0),e([ee({type:String})],mi.prototype,"startsAt",void 0),e([ee({type:Number})],mi.prototype,"duration",void 0),e([ee({type:String})],mi.prototype,"channel",void 0),e([ee({type:Object})],mi.prototype,"appointment",void 0),e([ee({type:String})],mi.prototype,"serviceId",void 0),e([ee({type:String})],mi.prototype,"specialityId",void 0),e([ee({type:Object})],mi.prototype,"service",void 0),e([ee({type:Object})],mi.prototype,"appliedDiscount",void 0),e([ee({type:String})],mi.prototype,"returnUrl",void 0),e([te()],mi.prototype,"reason",void 0),e([te()],mi.prototype,"attachedFiles",void 0),e([Q({context:Ee,subscribe:!0})],mi.prototype,"queryClientContext",void 0),mi=e([G(),t("confirm-step")],mi);class PaymentSuccessEvent extends Event{static{this.eventName="payment-success"}constructor(e){super(PaymentSuccessEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}const vi=J`:host{display:flex;flex-direction:column;align-items:center;justify-content:center;flex:1;gap:var(--sp-4);padding:var(--sp-8);text-align:center}.message{font-family:var(--font-body);font-size:var(--text-base);line-height:var(--text-base--line-height);color:var(--color-neutrals-text-default);margin:0}.error-title{font-family:var(--font-titles);font-size:var(--text-2xl);line-height:var(--text-2xl--line-height);font-weight:var(--font-weight-bold);color:var(--color-neutrals-text-default);margin:0}`;let fi=class PaymentPendingStep extends X{constructor(){super(...arguments),this._timedOut=!1,this._remaining=6e4}static{this.styles=vi}connectedCallback(){super.connectedCallback(),this._intervalId=setInterval(async()=>{if(this._remaining-=1e3,this._remaining<=0)return clearInterval(this._intervalId),this._timedOut=!0,void this.dispatchEvent(new CustomEvent("error"));try{const e=await this.apiClient.payments.getPaymentSession(this.sessionId);"paid"===e.status&&(clearInterval(this._intervalId),this.dispatchEvent(new PaymentSuccessEvent({appointmentId:e.consultation_id})))}catch{}},1e3)}disconnectedCallback(){super.disconnectedCallback(),clearInterval(this._intervalId)}render(){return this._timedOut?Y`<p class="error-title">${H("No hemos podido confirmar tu pago")}</p><p class="message">${H("Ha ocurrido un problema al verificar el estado de tu pago. Por favor, contacta con soporte si el cargo se ha realizado.")}</p>`:Y`${ge({size:40,color:"var(--color-primary-default)"})}<p class="message">${H("Verificando tu pago...")}</p>`}};e([Q({context:s,subscribe:!0})],fi.prototype,"apiClient",void 0),e([ee({type:String})],fi.prototype,"sessionId",void 0),e([te()],fi.prototype,"_timedOut",void 0),fi=e([G(),t("payment-pending-step")],fi);const gi="https://checkout.mediquo.com";function yi(){return Y`<svg viewBox="0 0 9 9" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M8.69821 4.46496C8.69821 4.14585 8.66917 3.8405 8.61524 3.54688H4.44141V5.2291L6.8452 5.22961C6.7477 5.78933 6.43393 6.26646 5.95317 6.58456V7.67596H7.38404C8.21953 6.9159 8.69821 5.79239 8.69821 4.46496Z" fill="#4285F4"/><path d="M5.95444 6.58518C5.55614 6.84924 5.04323 7.0037 4.44319 7.0037C3.28408 7.0037 2.30078 6.23599 1.94864 5.20117H0.472656V6.32673C1.20391 7.75305 2.70686 8.7318 4.44319 8.7318C5.64327 8.7318 6.65146 8.34387 7.3853 7.67608L5.95444 6.58518Z" fill="#34A853"/><path d="M1.80945 4.36536C1.80945 4.07479 1.85872 3.79391 1.94844 3.52986V2.4043H0.472459C0.170106 2.99409 0 3.65985 0 4.36536C0 5.07087 0.170624 5.73662 0.472459 6.32642L1.94844 5.20086C1.85872 4.9368 1.80945 4.65592 1.80945 4.36536Z" fill="#FABB05"/><path d="M4.44319 1.7281C5.0982 1.7281 5.68476 1.94985 6.14788 2.38315L7.4159 1.13779C6.64576 0.43279 5.64171 0 4.44319 0C2.70738 0 1.20391 0.978746 0.472656 2.40506L1.94864 3.53062C2.30078 2.4958 3.28408 1.7281 4.44319 1.7281Z" fill="#E94235"/></svg>`}function bi(){return Y`<svg viewBox="0 0 7 8" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M4.39647 1.24287C4.67047 0.908299 4.8564 0.459064 4.80736 0C4.40627 0.0194706 3.91682 0.258332 3.63345 0.593169C3.37902 0.879905 3.15383 1.34795 3.21253 1.78777C3.66277 1.8259 4.1126 1.56806 4.39647 1.24287Z" fill="currentColor"/><path d="M4.80415 1.87364C4.15029 1.83562 3.59435 2.23593 3.2821 2.23593C2.96968 2.23593 2.49152 1.8928 1.97435 1.90205C1.30122 1.9117 0.676641 2.28326 0.335058 2.87422C-0.36752 4.05642 0.149648 5.81003 0.832868 6.77287C1.16466 7.24922 1.56452 7.77371 2.09139 7.75487C2.5892 7.7358 2.78432 7.44017 3.38943 7.44017C3.9941 7.44017 4.16986 7.75487 4.69682 7.74533C5.2433 7.73579 5.58494 7.26875 5.91672 6.79194C6.29735 6.24893 6.45316 5.72461 6.46296 5.69583C6.45316 5.6863 5.4092 5.29531 5.39952 4.12294C5.38967 3.14129 6.21914 2.67437 6.25818 2.64541C5.78977 1.96906 5.05789 1.8928 4.80415 1.87364Z" fill="currentColor"/></svg>`}class PaymentMethodSelectedEvent extends Event{static{this.eventName="payment-method-selected"}constructor(e){super(PaymentMethodSelectedEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}const wi=J`:host{display:block;width:100%}.panel{width:100%;box-sizing:border-box;padding:24px}.header{display:flex;flex-direction:column;gap:6px;margin-bottom:10px}.title{font-family:var(--font-titles);font-size:var(--text-base);line-height:var(--text-base--line-height);font-weight:var(--font-weight-semibold);letter-spacing:-.025em;color:var(--color-neutrals-text-default);margin:0}.subtitle{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);color:var(--color-neutrals-text-medium);margin:0}.body{display:flex;flex-direction:column;gap:var(--sp-4)}.options{display:flex;flex-direction:column;gap:var(--sp-4)}.option{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;min-height:52px;padding:16px;border:1px solid var(--color-border,#edecf1);border-radius:var(--border-radius-md);background:var(--color-card,#fff);cursor:pointer;text-align:left;font:inherit;color:var(--color-neutrals-text-default);box-sizing:border-box;transition:border-color .15s ease}.option:active:not(:disabled):not(.option--selected),.option:hover:not(:disabled):not(.option--selected){border-color:var(--color-neutrals-border-default)}.option:focus-visible{outline:2px solid var(--color-primary);outline-offset:2px}.option--selected{border-color:var(--color-primary)}.lead{display:inline-flex;align-items:center;gap:12px;min-width:0}.lead__icon{display:flex;align-items:center;justify-content:center;width:16px;height:16px;color:var(--color-neutrals-text-default);flex-shrink:0}.lead__icon svg{display:block;width:100%;height:100%}.option__label{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);color:var(--color-neutrals-text-default);margin:0;white-space:nowrap}.mark{display:inline-flex;align-items:center;gap:3px;height:20px;padding:0 6px;border:1px solid #dadce0;border-radius:4px;background:#fff;box-sizing:border-box;flex-shrink:0}.mark__glyph{display:flex;align-items:center}.mark__glyph svg{display:block;width:auto;height:11px}.mark--apple{color:#000;gap:2px;padding:0 5px}.mark__pay{font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;font-size:11px;line-height:1}.mark--google .mark__pay{color:#5f6368;font-weight:500}.mark--apple .mark__pay{color:#000;font-weight:600}.radio{position:relative;width:16px;height:16px;border-radius:50%;border:2px solid var(--color-neutrals-border-default,#c9c6d4);box-sizing:border-box;flex-shrink:0;transition:border-color .15s ease}.radio--checked{border-color:var(--color-primary)}.radio--checked::after{content:"";position:absolute;inset:2px;border-radius:50%;background:var(--color-primary)}.action{display:block;width:100%}.confirm{display:block;width:100%}.wallet{display:flex;align-items:center;justify-content:center;gap:6px;width:100%;height:var(--button-height-md);padding:0 var(--size-4,16px);border:none;border-radius:var(--border-radius-md);background:#000;color:#fff;cursor:pointer;font:inherit;box-sizing:border-box;transition:background-color .15s ease}.wallet:hover{background-color:#1f1f1f}.wallet:active{background-color:#2e2e2e}.wallet:focus-visible{outline:2px solid var(--color-primary);outline-offset:2px}.wallet__glyph{display:flex;align-items:center}.wallet__glyph svg{display:block;width:auto}.wallet--google .wallet__glyph svg{height:22px}.wallet--apple .wallet__glyph{color:#fff}.wallet--apple .wallet__glyph svg{height:20px}.wallet__pay{font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;font-size:20px;line-height:1;color:#fff}.wallet--google .wallet__pay{font-weight:500}.wallet--apple .wallet__pay{font-weight:600}`;let _i=class PaymentMethodSelector extends X{constructor(){super(...arguments),this.showWallets=!0,this.showGooglePay=!1,this.showApplePay=!1,this._selected=null,this._confirm=()=>{this._selected&&this.dispatchEvent(new PaymentMethodSelectedEvent({method:this._selected}))}}static{this.styles=wi}get _googlePayVisible(){return this.showWallets&&this.showGooglePay&&"undefined"!=typeof window&&window.isSecureContext}get _applePayVisible(){return this.showWallets&&this.showApplePay&&"undefined"!=typeof window&&window.isSecureContext}willUpdate(e){(e.has("showWallets")||e.has("showGooglePay")||e.has("showApplePay"))&&(this._googlePayVisible||this._applePayVisible||(this._selected="card"))}_select(e){this._selected=e}_renderRow(e,t,i){const s=this._selected===e;return Y`<button type="button" class="${me({option:!0,"option--selected":s})}" role="radio" aria-checked="${s}" @click="${()=>this._select(e)}"><span class="lead">${i} <span class="option__label">${t}</span> </span><span class="${me({radio:!0,"radio--checked":s})}"></span></button>`}_renderAction(){return"google-pay"===this._selected?Y`<button type="button" class="wallet wallet--google" aria-label="${H("Pagar con Google Pay")}" @click="${this._confirm}"><span class="wallet__glyph">${yi()}</span> <span class="wallet__pay">Pay</span></button>`:"apple-pay"===this._selected?Y`<button type="button" class="wallet wallet--apple" aria-label="${H("Pagar con Apple Pay")}" @click="${this._confirm}"><span class="wallet__glyph">${bi()}</span> <span class="wallet__pay">Pay</span></button>`:Y`<mq-button class="confirm" variant="primary" size="md" fullwidth type="button" ?disabled="${null===this._selected}" @click="${this._confirm}">${H("Confirmar y pagar")}</mq-button>`}render(){return Y`<mq-card class="panel" elevation="none" roundness="lg"><div class="header"><h2 class="title">${H("Método de pago")}</h2><p class="subtitle">${H("Selecciona un método para realizar el pago de la cita")}</p></div><div class="body"><div class="options" role="radiogroup" aria-label="${H("Método de pago")}">${this._renderRow("card",H("Tarjeta"),Y`<span class="lead__icon">${Y`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${Me}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2.5" y="5" width="19" height="14" rx="2.5"/><path d="M2.5 10h19"/></svg>`}</span>`)} ${this._googlePayVisible?this._renderRow("google-pay",H("Google pay"),Y`<span class="mark mark--google"><span class="mark__glyph">${yi()}</span> <span class="mark__pay">Pay</span></span>`):null} ${this._applePayVisible?this._renderRow("apple-pay",H("Apple pay"),Y`<span class="mark mark--apple"><span class="mark__glyph">${bi()}</span> <span class="mark__pay">Pay</span></span>`):null}</div><div class="action">${this._renderAction()}</div></div></mq-card>`}};e([ee({type:Boolean,attribute:"show-wallets"})],_i.prototype,"showWallets",void 0),e([ee({type:Boolean,attribute:"show-google-pay"})],_i.prototype,"showGooglePay",void 0),e([ee({type:Boolean,attribute:"show-apple-pay"})],_i.prototype,"showApplePay",void 0),e([te()],_i.prototype,"_selected",void 0),_i=e([G(),t("payment-method-selector")],_i);const xi=J`:host{height:100%;min-height:0;display:flex;flex-direction:column;gap:var(--sp-6);flex:1}.content{display:flex;flex-direction:column;flex:1;min-height:0;gap:var(--sp-4)}.summary-col{display:flex;flex-direction:column;gap:var(--sp-4);min-width:0}.confirm-reveal{display:grid;grid-template-rows:0fr;transition:grid-template-rows .25s ease-out}.content--free .confirm-reveal{grid-template-rows:1fr}.confirm-reveal__inner{min-height:0;overflow:hidden}.payment-col{display:grid;grid-template-rows:1fr;overflow:hidden;transition:grid-template-rows .3s ease,opacity .25s ease}.content--free .payment-col{grid-template-rows:0fr;opacity:0}.payment-col__inner{min-height:0;overflow:hidden}.payment-frame{position:relative;width:100%;min-width:0;display:flex;flex-direction:column;flex:0 0 auto;min-height:0;border-radius:var(--border-radius-md);overflow:hidden}.payment-frame iframe:not(.loaded){position:absolute;width:1px;height:1px;opacity:0;pointer-events:none;border:none}.payment-frame iframe.loaded{flex:none;display:block;width:100%;border:none;min-height:1050px}.panel{width:100%;box-sizing:border-box;padding:24px}.wallet-waiting{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--sp-4);text-align:center;min-height:200px}.wallet-waiting__title{font-family:var(--font-titles);font-size:var(--text-lg);line-height:var(--text-lg--line-height);font-weight:var(--font-weight-semibold);color:var(--color-neutrals-text-default);margin:0}.wallet-waiting__message{font-family:var(--font-body);font-size:var(--text-base);line-height:var(--text-base--line-height);color:var(--color-neutrals-text-subtle);margin:0}.error{display:flex;flex-direction:column;align-items:center;justify-content:center;flex:1;gap:var(--sp-4);padding:var(--sp-8);text-align:center}.error-title{font-family:var(--font-titles);font-size:var(--text-2xl);line-height:var(--text-2xl--line-height);font-weight:var(--font-weight-bold);color:var(--color-neutrals-text-default);margin:0}.error-message{font-family:var(--font-body);font-size:var(--text-base);line-height:var(--text-base--line-height);color:var(--color-neutrals-text-default);margin:0}@media (min-width:768px){.content{display:grid;grid-template-columns:1fr 1fr;align-items:start;gap:var(--sp-6);transition:grid-template-columns .3s ease}.content--free{grid-template-columns:1fr 0fr}.summary-col{max-width:calc((var(--content-max-width) - var(--sp-6))/ 2)}.content--free .summary-col{margin-inline:auto}.payment-col,.payment-frame{min-width:0}}`,Si="mediquo:payment:retry",$i="mediquo:payment:resize";class PaymentRetryEvent extends Event{static{this.eventName="payment-retry"}constructor(){super(PaymentRetryEvent.eventName,{bubbles:!0,composed:!0})}}class ApplePayOpenedEvent extends Event{static{this.eventName="apple-pay-opened"}constructor(e){super(ApplePayOpenedEvent.eventName,{bubbles:!0,composed:!0,cancelable:!0}),this.detail=e}}class GooglePayOpenedEvent extends Event{static{this.eventName="google-pay-opened"}constructor(e){super(GooglePayOpenedEvent.eventName,{bubbles:!0,composed:!0,cancelable:!0}),this.detail=e}}let ki=class PaymentStep extends X{constructor(){super(...arguments),this.showBack=!0,this.paymentUrl="",this.channel=void 0,this.service=void 0,this.scheduleSlot=void 0,this.appliedDiscount=null,this.bookingRequest=null,this.env="production",this.locale="es_ES",this.countryCode="ES",this.googlePayEnabled=!1,this.applePayEnabled=!1,this.stripeRedirect=!1,this._view="select",this._walletWaiting=null,this._walletUrl=null,this._walletPopupBlocked=!1,this._walletConfigError=!1,this._timedOut=!1,this._iframeLoaded=!1,this._iframeHeight=null,this._walletPopup=null,this._pollDeadline=0,this.createScheduleAppointment=new ScheduleAppointmentMutationController(this,{getApiClient:()=>this.apiClient,getQueryClient:()=>this.queryClientContext,onSuccess:e=>{this.dispatchEvent(new CustomEvent("success",{detail:{appointmentId:e}}))},onError:()=>{this.dispatchEvent(new CustomEvent("error"))}}),this._onPaymentMethodSelected=e=>{const t=e.detail.method;if(this.provider===L.Stripe&&this.stripeRedirect){const e=new q({url:this.paymentUrl,sessionId:this.sessionId});return this.dispatchEvent(e),void(e.defaultPrevented||window.location.assign(this.paymentUrl))}if("card"===t)return this._view="card",this._walletWaiting=null,this._walletConfigError=!1,void this._startPaymentPolling();const i=t,s=this._buildWalletCheckoutUrl(i);if(!s)return this._walletConfigError=!0,this._walletWaiting=i,this._walletUrl=null,void(this._walletPopupBlocked=!1);this._walletUrl=s,this._walletConfigError=!1,this._walletPopupBlocked=!1,this._walletWaiting=i;const a=this._dispatchWalletOpenedEvent(i,s);if(this.dispatchEvent(a),a.defaultPrevented)this._walletPopup=null;else{const e=this._openWalletPopup(i,s);this._walletPopup=e,e||(this._walletPopupBlocked=!0)}this._startPaymentPolling()},this._onHeaderBack=e=>(e.stopPropagation(),this.embedsHostedCheckout?(this._stopPaymentPolling(),void this.dispatchEvent(new CustomEvent("back"))):"card"===this._view?(this._stopPaymentPolling(),this._view="select",this._iframeLoaded=!1,void(this._iframeHeight=null)):this._walletWaiting?(this._stopPaymentPolling(),this._walletWaiting=null,this._walletConfigError=!1,this._walletPopup?.close(),void(this._walletPopup=null)):void this.dispatchEvent(new CustomEvent("back"))),this._onMessage=e=>{if("card"===this._view)switch(e.data?.type){case Si:return void this.dispatchEvent(new PaymentRetryEvent);case $i:return void("number"==typeof e.data.height&&(this._iframeHeight=e.data.height))}}}static{this.styles=xi}get isFullyDiscounted(){return null!=this.appliedDiscount&&Ye(this.appliedDiscount)}get embedsHostedCheckout(){return this.provider===L.Stripe&&!this.stripeRedirect}confirmFree(){const e=this.bookingRequest;e&&this.createScheduleAppointment.run({slotId:e.slot_id,serviceId:e.service_id,consultationReason:e.consultation_reason,preconsultationDocuments:e.preconsultation_documents,discountCode:this.appliedDiscount?.code})}_paymentAmountCents(){return this.appliedDiscount?this.appliedDiscount.totalAmount:this.scheduleSlot?.speciality?.price?.amount??0}_paymentCurrency(){return this.appliedDiscount?.currency??this.scheduleSlot?.speciality?.price?.currency??"EUR"}_paymentAmountLabel(){return _e(this._paymentAmountCents()).toFixed(2)}_buildApplePayUrl(){return this.apiKey&&this.token?function(e){const t=new URL(`${gi}/apple-pay`);return t.searchParams.set("api_key",e.apiKey),t.searchParams.set("session_id",e.sessionId),t.searchParams.set("amount",e.amount),t.searchParams.set("currency",e.currency),t.searchParams.set("country",e.country),t.searchParams.set("label",e.label),t.searchParams.set("env",e.env),t.searchParams.set("locale",e.locale),e.successUrl&&t.searchParams.set("success_url",e.successUrl),t.hash=`token=${encodeURIComponent(e.token)}`,t.toString()}({apiKey:this.apiKey,token:this.token,sessionId:this.sessionId,amount:this._paymentAmountLabel(),currency:this._paymentCurrency(),country:this.countryCode,label:this.service?.name??H("Consulta"),env:this.env,locale:this.locale,successUrl:this.successUrl}):null}_buildGooglePayUrl(){return this.apiKey&&this.token?function(e){const t=new URL(`${gi}/google-pay`);return t.searchParams.set("api_key",e.apiKey),t.searchParams.set("session_id",e.sessionId),t.searchParams.set("amount",e.amount),t.searchParams.set("currency",e.currency),t.searchParams.set("country",e.country),t.searchParams.set("label",e.label),t.searchParams.set("env",e.env),t.searchParams.set("locale",e.locale),e.successUrl&&t.searchParams.set("success_url",e.successUrl),t.hash=`token=${encodeURIComponent(e.token)}`,t.toString()}({apiKey:this.apiKey,token:this.token,sessionId:this.sessionId,amount:this._paymentAmountLabel(),currency:this._paymentCurrency(),country:this.countryCode,label:this.service?.name??H("Consulta"),env:this.env,locale:this.locale,successUrl:this.successUrl}):null}_buildPayUrl(){return this.apiKey&&this.token?function(e){const t=new URL(`${gi}/pay`);t.searchParams.set("api_key",e.apiKey),t.searchParams.set("session_id",e.sessionId),t.searchParams.set("amount",e.amount),t.searchParams.set("currency",e.currency),t.searchParams.set("country",e.country),t.searchParams.set("label",e.label),t.searchParams.set("env",e.env),t.searchParams.set("locale",e.locale);const i=e.payableReference?.trim();return i&&t.searchParams.set("payable_reference",i),t.hash=`token=${encodeURIComponent(e.token)}`,t.toString()}({apiKey:this.apiKey,token:this.token,sessionId:this.sessionId,amount:this._paymentAmountLabel(),currency:this._paymentCurrency(),country:this.countryCode,label:this.service?.name??H("Consulta"),env:this.env,locale:this.locale,payableReference:this.scheduleSlot?.payable_reference??void 0}):null}_buildWalletCheckoutUrl(e){return"apple-pay"===e?this._buildApplePayUrl():this._buildGooglePayUrl()}_stopPaymentPolling(){void 0!==this._pollIntervalId&&(clearInterval(this._pollIntervalId),this._pollIntervalId=void 0),void 0!==this._pollStartTimeoutId&&(clearTimeout(this._pollStartTimeoutId),this._pollStartTimeoutId=void 0)}_startPaymentPolling(){this._stopPaymentPolling(),this._timedOut=!1,this._pollDeadline=Date.now()+6e5,this._pollStartTimeoutId=setTimeout(()=>{this._pollStartTimeoutId=void 0,this._pollOnce(),this._pollIntervalId=setInterval(()=>{this._pollOnce()},3e3)},5e3)}async _pollOnce(){if(Date.now()>=this._pollDeadline)return this._stopPaymentPolling(),this._timedOut=!0,this.requestUpdate(),void this.dispatchEvent(new CustomEvent("error"));try{const e=await this.apiClient.payments.getPaymentSession(this.sessionId);if(e.status===j.Paid)return this._stopPaymentPolling(),this._walletPopup?.close(),this._walletPopup=null,void this.dispatchEvent(new PaymentSuccessEvent({appointmentId:e.consultation_id}));e.status===j.Denied&&(this._stopPaymentPolling(),this._walletPopup?.close(),this._walletPopup=null,this._walletWaiting=null,this.dispatchEvent(new PaymentRetryEvent))}catch{}}_dispatchWalletOpenedEvent(e,t){return"apple-pay"===e?new ApplePayOpenedEvent({url:t,sessionId:this.sessionId}):new GooglePayOpenedEvent({url:t,sessionId:this.sessionId})}_openWalletPopup(e,t){const i="apple-pay"===e?"mediquo-apple-pay":"mediquo-google-pay";return window.open(t,i,["width=480","height=720",`left=${Math.max(0,Math.round((window.screen.availWidth-480)/2))}`,`top=${Math.max(0,Math.round((window.screen.availHeight-720)/2))}`,"menubar=no","toolbar=no","location=yes","status=no","scrollbars=yes","resizable=yes"].join(","))}_reopenWalletPopup(){if(!this._walletUrl||!this._walletWaiting)return;const e=this._openWalletPopup(this._walletWaiting,this._walletUrl);this._walletPopup=e,this._walletPopupBlocked=!e}_walletWaitingTitle(){return this._walletConfigError?"google-pay"===this._walletWaiting?H("No se puede iniciar Google Pay"):H("No se puede iniciar Apple Pay"):"google-pay"===this._walletWaiting?H("Esperando confirmación de Google Pay"):H("Esperando confirmación de Apple Pay")}_walletReopenLabel(){return"google-pay"===this._walletWaiting?H("Abrir Google Pay"):H("Abrir Apple Pay")}_walletReopenLinkLabel(){return"google-pay"===this._walletWaiting?H("Abrir ventana de Google Pay"):H("Abrir ventana de Apple Pay")}_walletReopenAgainLabel(){return"google-pay"===this._walletWaiting?H("Volver a abrir Google Pay"):H("Volver a abrir Apple Pay")}willUpdate(e){super.willUpdate(e),this.embedsHostedCheckout&&"select"===this._view&&(this._view="card")}updated(e){super.updated(e),e.has("paymentUrl")&&(this._iframeLoaded=!1,this._iframeHeight=null),this.embedsHostedCheckout&&"card"===this._view&&this.sessionId&&(e.has("sessionId")||e.has("provider")||e.has("paymentUrl"))&&this._startPaymentPolling()}connectedCallback(){super.connectedCallback(),window.addEventListener("message",this._onMessage)}disconnectedCallback(){window.removeEventListener("message",this._onMessage),this._stopPaymentPolling(),this._walletPopup?.close(),this._walletPopup=null,super.disconnectedCallback()}_onIframeLoad(){this._iframeLoaded=!0}_renderSummaryColumn(){return Y`<div class="summary-col"><new-appointment-summary .professional="${this.professional}" .startsAt="${this.startsAt}" .duration="${this.duration}" .channel="${this.channel}" .serviceCode="${this.service?.code}" .serviceName="${this.service?.name}" .servicePrice="${this.scheduleSlot?.speciality?.price??null}" .appliedDiscount="${this.appliedDiscount}" .fillColumn="${!0}"></new-appointment-summary><div class="confirm-reveal" .inert="${!this.isFullyDiscounted}"><div class="confirm-reveal__inner"><mq-button size="xl" type="button" fullwidth ?disabled="${this.createScheduleAppointment.isPending}" @click="${this.confirmFree}">${H("Confirmar cita")}</mq-button></div></div></div>`}_renderPaymentColumn(){if(this._walletWaiting)return this._walletConfigError?Y`<div class="payment-col__inner"><mq-card class="panel" elevation="none" roundness="lg"><div class="wallet-waiting"><p class="wallet-waiting__title">${this._walletWaitingTitle()}</p><p class="wallet-waiting__message">${H("Faltan credenciales de pago. Vuelve atrás e inténtalo de nuevo, o paga con tarjeta.")}</p><mq-text-button type="button" @click="${()=>{this._walletWaiting=null,this._walletConfigError=!1}}">${H("Elegir otro método")}</mq-text-button></div></mq-card></div>`:Y`<div class="payment-col__inner"><mq-card class="panel" elevation="none" roundness="lg"><div class="wallet-waiting"><p class="wallet-waiting__title">${this._walletWaitingTitle()}</p><p class="wallet-waiting__message">${H("No cierres esta página.")}</p>${this._walletPopupBlocked&&this._walletUrl?Y`<mq-text-button type="button" @click="${this._reopenWalletPopup}">${this._walletReopenLabel()}</mq-text-button><a href="${this._walletUrl}" target="_blank" rel="noopener noreferrer">${this._walletReopenLinkLabel()}</a>`:Y`<mq-text-button type="button" @click="${this._reopenWalletPopup}">${this._walletReopenAgainLabel()}</mq-text-button>`}</div></mq-card></div>`;if("select"===this._view)return Y`<div class="payment-col__inner"><payment-method-selector .showWallets="${this.provider!==L.Stripe}" .showGooglePay="${this.googlePayEnabled}" .showApplePay="${this.applePayEnabled}" @payment-method-selected="${this._onPaymentMethodSelected}"></payment-method-selector></div>`;const e=this.embedsHostedCheckout?this._buildPayUrl():this.paymentUrl;return this.embedsHostedCheckout&&!e?Y`<div class="payment-col__inner"><mq-card class="panel" elevation="none" roundness="lg"><div class="wallet-waiting"><p class="wallet-waiting__title">${H("No se puede iniciar el pago")}</p><p class="wallet-waiting__message">${H("Faltan credenciales de pago. Vuelve atrás e inténtalo de nuevo.")}</p></div></mq-card></div>`:Y`<div class="payment-col__inner"><div class="payment-frame">${this._iframeLoaded?null:Y`<mq-skeleton width="100%" height="600px" border-radius="md" role="status" aria-live="polite" aria-label="${H("Cargando portal de pago")}"></mq-skeleton>`}<iframe class="${this._iframeLoaded?"loaded":""}" src="${e??""}" title="${H("Portal de pago")}" allow="payment" style="${null!==this._iframeHeight?`min-height: ${this._iframeHeight}px; height: ${this._iframeHeight}px;`:""}" @load="${this._onIframeLoad}"></iframe></div></div>`}render(){if(this._timedOut)return Y`<div class="error"><p class="error-title">${H("No hemos podido confirmar tu pago")}</p><p class="error-message">${H("Ha ocurrido un problema al verificar el estado de tu pago. Por favor, contacta con soporte si el cargo se ha realizado.")}</p></div>`;const e=Y`<mq-page-title .title="${H("Petición de cita")}" .showBack="${this.showBack}" @mq-back="${this._onHeaderBack}"></mq-page-title>`;return this.isFullyDiscounted?Y`${e}<div class="content content--free">${this._renderSummaryColumn()}<div class="payment-col" .inert="${!0}"></div></div>`:Y`${e}<div class="content">${this._renderSummaryColumn()}<div class="payment-col">${this._renderPaymentColumn()}</div></div>`}};e([Q({context:s,subscribe:!0})],ki.prototype,"apiClient",void 0),e([ee({type:String})],ki.prototype,"sessionId",void 0),e([ee({type:Boolean})],ki.prototype,"showBack",void 0),e([ee({type:String})],ki.prototype,"paymentUrl",void 0),e([ee({type:Object})],ki.prototype,"professional",void 0),e([ee({type:String})],ki.prototype,"startsAt",void 0),e([ee({type:Number})],ki.prototype,"duration",void 0),e([ee({type:String})],ki.prototype,"channel",void 0),e([ee({type:Object})],ki.prototype,"service",void 0),e([ee({type:Object})],ki.prototype,"scheduleSlot",void 0),e([ee({type:Object})],ki.prototype,"appliedDiscount",void 0),e([ee({type:Object})],ki.prototype,"bookingRequest",void 0),e([ee({type:String,attribute:!1})],ki.prototype,"apiKey",void 0),e([ee({type:String,attribute:!1})],ki.prototype,"token",void 0),e([ee({type:String,attribute:!1})],ki.prototype,"env",void 0),e([ee({type:String,attribute:!1})],ki.prototype,"locale",void 0),e([ee({type:String,attribute:!1})],ki.prototype,"countryCode",void 0),e([ee({type:String,attribute:!1})],ki.prototype,"successUrl",void 0),e([ee({type:String,attribute:!1})],ki.prototype,"provider",void 0),e([ee({type:Boolean,attribute:!1})],ki.prototype,"googlePayEnabled",void 0),e([ee({type:Boolean,attribute:!1})],ki.prototype,"applePayEnabled",void 0),e([ee({type:Boolean,attribute:!1})],ki.prototype,"stripeRedirect",void 0),e([Q({context:Ee,subscribe:!0})],ki.prototype,"queryClientContext",void 0),e([te()],ki.prototype,"_view",void 0),e([te()],ki.prototype,"_walletWaiting",void 0),e([te()],ki.prototype,"_walletUrl",void 0),e([te()],ki.prototype,"_walletPopupBlocked",void 0),e([te()],ki.prototype,"_walletConfigError",void 0),e([te()],ki.prototype,"_timedOut",void 0),e([te()],ki.prototype,"_iframeLoaded",void 0),e([te()],ki.prototype,"_iframeHeight",void 0),ki=e([G(),t("payment-step")],ki);const Ci=J`:host{display:block;width:100%;box-sizing:border-box}.banner{align-items:center;background-color:var(--color-primary-background-extraWeak);border-radius:var(--border-radius-sm);box-sizing:border-box;color:var(--color-primary-default,var(--color-primary));display:flex;gap:10px;font-family:var(--font-body);font-size:var(--text-sm);font-weight:var(--font-weight-normal);line-height:var(--text-sm--line-height);padding:var(--size-2) var(--size-4);width:100%}.label{margin:0}`;let Pi=class ScheduleLoadingBanner extends X{static{this.styles=Ci}render(){return Y`<div class="banner" role="status" aria-live="polite">${ge({size:24,color:"var(--color-primary-default, var(--color-primary))"})}<p class="label">${H("Cargando")}</p></div>`}};Pi=e([G(),t("schedule-loading-banner")],Pi);const Ei=J`.form-container{display:flex;flex-direction:column;gap:var(--size-4)}.form-content{display:flex;flex-direction:column;gap:var(--size-4);width:100%}.field{display:flex;flex-direction:column;gap:var(--size-2);width:100%}.field-title{font-family:var(--font-body, "Roboto");font-size:var(--text-base,16px);font-weight:var(--font-weight-bold,700);line-height:22px;color:var(--color-neutrals-text-default,#333);margin:0}.action-button{flex-shrink:0;width:100%}.filters-loading-banner{flex-basis:100%;width:100%}@media (min-width:768px){.form-content{flex-direction:row;gap:var(--size-6);align-items:end}.action-button{--button-height-md:var(--button-height-lg);min-width:254px;width:auto}}`,Mi=fe.object({service:fe.string().min(1),specialty:fe.string().min(1)});class SearchProfessionalsFormSuccessEvent extends CustomEvent{static{this.eventName="success"}constructor(e){super(SearchProfessionalsFormSuccessEvent.eventName,{bubbles:!0,composed:!0,detail:e})}}let Ii=class SearchProfessionalsForm extends X{constructor(){super(...arguments),this.form=new TanStackFormController(this,{defaultValues:this.defaultValues,onSubmit:e=>{const t=e.value;h.track(m(this.patient.hash,t.specialty??"",t.service??"")),this.dispatchEvent(new SearchProfessionalsFormSuccessEvent(t))},validators:{onSubmit:Mi}}),this.getScheduleServicesQuery=new i(this,()=>S(this.apiClient)),this.getOrganizationSpecialtiesQuery=new i(this,()=>d(this.apiClient))}static{this.styles=Ei}get filtersLoading(){const e=this.getScheduleServicesQuery.result,t=this.getOrganizationSpecialtiesQuery.result;return(e?.isPending??!0)||(t?.isPending??!0)}willUpdate(e){e.has("defaultValues")&&(this.form.api.setFieldValue("service",this.defaultValues.service),this.form.api.setFieldValue("specialty",this.defaultValues.specialty))}renderScheduleServices({name:e,value:t,onValueChange:i,error:s},a){const o=le();return Y`<mq-select label="${H("Modalidad de la cita")}" id="${ve(e)}" value="${ve(t)}" name="${ve(e)}" size="lg" ?error="${s}" @onvaluechange="${e=>{i(e.value)}}">${a.map(e=>Y`<mq-option value="${e.id}">${p(e.code??"",o,e.name)}</mq-option>`)}</mq-select>`}renderOrganizationSpecialties({name:e,value:t,onValueChange:i,error:s},a){const o=le();return Y`<mq-select label="${H("Especialidad")}" id="${ve(e)}" value="${ve(t)}" name="${ve(e)}" size="lg" ?error="${s}" @onvaluechange="${e=>{i(e.value)}}">${a.map(e=>Y`<mq-option value="${e.id}">${v[e.code]?.[o]??e.name}</mq-option>`)}</mq-select>`}render(){const e=this.getScheduleServicesQuery.result,t=this.getOrganizationSpecialtiesQuery.result,i=e?.data,s=t?.data,a=!0===e?.isSuccess&&!0===t?.isSuccess&&null!=i&&null!=s;return Y`<div class="form-container"><form class="form-content" @submit="${e=>{e.preventDefault(),e.stopPropagation(),this.form.api.handleSubmit()}}">${this.filtersLoading?Y`<schedule-loading-banner class="filters-loading-banner"></schedule-loading-banner>`:a?Y`<div class="field">${this.form.field({name:"service"},e=>Y`<p class="field-title">${H("Modalidad de la cita*")}</p>${this.renderScheduleServices({name:e.name,value:e.state.value,onValueChange:e.handleChange,error:!e.state.meta.isValid},i)}`)}</div><div class="field">${this.form.field({name:"specialty"},e=>Y`<p class="field-title">${H("Especialidad*")}</p>${this.renderOrganizationSpecialties({name:e.name,value:e.state.value,onValueChange:e.handleChange,error:!e.state.meta.isValid},s)}`)}</div><mq-button type="submit" class="action-button" fullwidth>${H("Buscar disponibilidad")}</mq-button>`:Z}</form></div>`}};function Ai(e){if(!e)return new Date(Number.NaN);const t=$(e);if(Ae(t))return t;const i=Fe(e);if(Ae(i))return i;const s=new Date(e);return Number.isNaN(s.getTime())?new Date(Number.NaN):s}function Fi(e,t){if(!Ae(e))return"";if(t)try{const i=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),s=e=>i.find(t=>t.type===e)?.value??"";return`${s("year")}-${s("month")}-${s("day")}`}catch{}return qe(e,"yyyy-MM-dd")}function qi(e,t){const i=new Date;let s;for(const t of e){const e=Ai(t.starts_at);Ae(e)&&(Ve(e,i)&&(!s||Oe(e,s)<0)&&(s=e))}return s?Fi(s,t):void 0}e([Q({context:s,subscribe:!0})],Ii.prototype,"apiClient",void 0),e([Q({context:Re,subscribe:!0})],Ii.prototype,"patient",void 0),e([ee({type:Object})],Ii.prototype,"defaultValues",void 0),Ii=e([G(),t("search-professionals-form")],Ii);const Vi=J`:host{display:block}.card{padding:var(--sp-6) var(--sp-4);display:flex;flex-direction:column;gap:var(--sp-4)}.schedules{display:flex;flex-direction:column;gap:var(--sp-2)}.schedule{align-self:stretch;display:flex;align-items:center;column-gap:var(--sp-2_5);flex-wrap:nowrap;min-width:0;overflow:hidden}.day-slot{box-sizing:border-box;padding:var(--sp-2);width:var(--size-15);height:var(--size-15);display:flex;flex-direction:column;gap:var(--sp-1);align-items:center;justify-content:center}.day-slot-day{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal)}.day-slot-date{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-medium);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.schedules-container{flex:1;display:flex;flex-direction:column;gap:var(--sp-4);transition:opacity .2s}.schedules-container.is-pending{opacity:.5;pointer-events:none}.schedule-slot{box-sizing:border-box;padding:var(--sp-2) var(--sp-1);background:var(--color-primary-background-extraWeak);flex:1 1 0;min-width:0;height:var(--sp-11);display:flex;align-items:center;justify-content:center;border:1px solid color-mix(in srgb,var(--color-primary) 12%,transparent);border-radius:var(--border-radius-md);cursor:pointer;transition:all .2s;font-family:var(--font-body);font-size:var(--text-sm);font-weight:var(--font-weight-medium);color:var(--color-primary-text-link);text-align:center;white-space:nowrap;outline:0;position:relative;--mq-slot-ring-color:var(--color-primary)}.schedule-slot:hover:not(.is-empty){background-color:color-mix(in srgb,var(--color-primary) 12%,var(--color-primary-background-extraWeak));border-color:color-mix(in srgb,var(--color-primary) 24%,transparent)}.schedule-slot:focus-visible{box-shadow:0 0 0 1.5px var(--color-background,#fff),0 0 0 3.5px var(--mq-slot-ring-color,var(--color-primary));z-index:1}.schedule-slot.is-empty{cursor:default;background-color:transparent;border-color:var(--color-border);color:var(--color-neutrals-text-medium)}.schedule-slot.is-empty:focus-visible{box-shadow:none}.schedule-slot:nth-child(n + 5){display:none}.no-slots{font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);color:var(--color-neutrals-text-default);text-align:center}.error-message{color:var(--color-error-text-default);font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);margin:0;text-align:center}@media (min-width:768px){.card{flex-direction:row;justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-8)}professional-overview{width:100%;max-width:327px;flex-shrink:0}.schedules-container{gap:var(--sp-3)}mq-button{margin:0 auto;max-width:323px}.schedule-slot:nth-child(n + 5){display:flex}.schedule-slot:nth-child(n + 9){display:none}}`;class SelectedSlotEvent extends Event{static{this.eventName="selected-slot"}constructor(e){super(SelectedSlotEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}let Di=class ShowFullScheduleEvent extends Event{static{this.eventName="show-full-schedule"}constructor(){super(ShowFullScheduleEvent.eventName,{bubbles:!0,composed:!0})}},zi=class ProfessionalCard extends X{constructor(){super(...arguments),this.serviceId="",this.specialtyId="",this.showSlotUnavailableError=!1,this.getOrganizationSpecialtiesQuery=new i(this,()=>d(this.apiClient)),this.checkForSlotAvailabilityMutation=new ue(this,{mutationFn:e=>this.apiClient.schedules.getScheduleSlot({slot_id:e,service_id:this.serviceId||void 0,speciality_id:this.specialtyId?Number(this.specialtyId):void 0})})}static{this.styles=Vi}get groupedSlots(){const e=this.professional?.slots??[];return 0===e.length?[]:function(e,t){if(!e.length)return[];const i=e.reduce((e,i)=>{const s=Ai(i.starts_at);if(!Ae(s))return e;const a=Fi(s,t);if(!a)return e;const o={slot:i,parsedDate:s};if(!e.has(a))return e.set(a,[o]),e;const r=e.get(a);return r?.push(o),e},new Map);return 0===i.size?[]:Array.from(i.entries()).map(([e,t])=>({key:e,slots:t.sort((e,t)=>Oe(e.parsedDate,t.parsedDate)),date:t[0]?.parsedDate??new Date(Number.NaN)})).filter(({date:e})=>Ae(e)).sort((e,t)=>Oe(e.date,t.date))}(e,this.patient.timezone).map(e=>({key:e.key,dayLabel:this.formatDay(e.date),dateLabel:this.formatDate(e.date),slots:e.slots,date:e.date}))}get timezone(){return this.patient.timezone}formatDay(e){const t=le().replace("_","-"),i=k(this.timezone),s=new Intl.DateTimeFormat(t,{weekday:"short",...i?{timeZone:i}:{}}).format(e).replace(/\.$/,"");return`${s.charAt(0).toUpperCase()}${s.slice(1)}`}formatDate(e){const t=le().replace("_","-"),i=k(this.timezone),s=i?{timeZone:i}:{},a=new Intl.DateTimeFormat(t,{day:"numeric",...s}).format(e),o=new Intl.DateTimeFormat(t,{month:"short",...s}).format(e).replace(/\.$/,"");return`${a} ${`${o.charAt(0).toUpperCase()}${o.slice(1)}`}`}formatTime(e){return function(e,t,i){return new Intl.DateTimeFormat(t,{hour:"2-digit",minute:"2-digit",hour12:!1,...i?{timeZone:i}:{}}).format(e)}(e,le().replace("_","-"),this.timezone)}async handleSlotClick(e){const t=await this.checkForSlotAvailabilityMutation.run(e.id);t.status===B.available?(this.showSlotUnavailableError=!1,h.track(f(this.patient.hash,this.professional.id,e.starts_at,this.specialtyId,this.serviceId)),this.dispatchEvent(new SelectedSlotEvent({slot:t,professional:this.professional}))):(this.showSlotUnavailableError=!0,this.queryClientContext?.invalidateQueries({queryKey:_(this.apiClient)}))}render(){const e=le(),t=this.getOrganizationSpecialtiesQuery.result?.data?.find(e=>e.id===this.professional.speciality.id),i=c(t?.code??"",e,t?.name);return Y`<mq-card class="card" elevation="md" roundness="lg"><professional-overview .name="${this.professional.name}" .specialtyName="${i??""}" .collegiateNumber="${this.professional.collegiate_number??void 0}" .description="${this.professional.description??""}" .languages="${this.professional.languages}" .avatar="${this.professional.avatar??""}"></professional-overview><div class="${me({"schedules-container":!0,"is-pending":this.checkForSlotAvailabilityMutation.isPending})}">${this.showSlotUnavailableError?Y`<p class="error-message">${H("Este horario no está disponible. Por favor, seleccione otro.")}</p>`:Z}<div class="schedules">${this.groupedSlots.length>0?this.groupedSlots.map(e=>Y`<div class="schedule"><div class="day-slot"><span class="day-slot-day">${e.dayLabel}</span> <span class="day-slot-date">${e.dateLabel}</span></div>${e.slots.map(({slot:e,parsedDate:t})=>Y`<button class="schedule-slot" data-slot-id="${e.id}" @click="${()=>this.handleSlotClick(e)}">${this.formatTime(t)}</button>`)} ${Array.from({length:Math.max(0,7-e.slots.length)}).map(()=>Y`<div class="schedule-slot is-empty">-</div>`)}</div>`):Y`<div class="no-slots">${H("Sin huecos disponibles actualmente")}</div>`}</div><mq-button fullwidth @click="${()=>{h.track(g(this.patient.hash,this.professional.id,this.specialtyId,this.serviceId)),this.dispatchEvent(new Di)}}">${Le({size:24})} ${H("Ver agenda completa")}</mq-button></div></mq-card>`}};e([Q({context:s,subscribe:!0})],zi.prototype,"apiClient",void 0),e([Q({context:Re,subscribe:!0})],zi.prototype,"patient",void 0),e([ee({type:Object})],zi.prototype,"professional",void 0),e([ee({type:String})],zi.prototype,"serviceId",void 0),e([ee({type:String})],zi.prototype,"specialtyId",void 0),e([te()],zi.prototype,"showSlotUnavailableError",void 0),e([Q({context:Ee,subscribe:!0})],zi.prototype,"queryClientContext",void 0),zi=e([G(),t("professional-card")],zi);const Li=J`:host{display:flex;flex-direction:column;gap:var(--sp-4)}.title{font-family:var(--font-titles);font-size:var(--text-2xl);line-height:var(--text-2xl--line-height);font-weight:var(--font-weight-bold);margin:0;margin-bottom:var(--sp-2)}.applied-filters{align-items:center;display:flex;flex-wrap:wrap;gap:var(--sp-2)}.applied-filters-label{color:var(--color-neutrals-text-default);font-family:var(--font-body);font-size:var(--text-sm);font-weight:var(--font-weight-normal);line-height:var(--text-sm--line-height);margin:0}.applied-filters-values{align-items:center;display:flex;flex-wrap:wrap;gap:var(--sp-2)}`;class ShowFullScheduleEvent extends Event{static{this.eventName="show-full-schedule"}constructor(e){super(ShowFullScheduleEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}let ji=class ProfessionalsList extends X{constructor(){super(...arguments),this.specialty_id=void 0,this.service_id=void 0,this.getScheduleServicesQuery=new i(this,()=>S(this.apiClient)),this.getProfessionalsBySpecialtyAndServiceQuery=new i(this,()=>{return e=this.apiClient,t={closest_slots_days:2,slots_per_day:7,speciality_id:this.specialty_id?Number(this.specialty_id):void 0,organization_schedule_service_id:this.service_id?this.service_id:void 0},{queryKey:_(e,"professionals-by-specialty-and-service",t),queryFn:t.speciality_id&&t.organization_schedule_service_id?()=>e.schedules.getProfessionalsBySpecialtyAndService(t):je,staleTime:0};var e,t})}static{this.styles=Li}render(){const e=le(),t=this.getScheduleServicesQuery.result?.data?.find(e=>e.id===this.service_id);if(!this.specialty_id||!this.service_id)return Z;const i=p(t?.code??"",e,t?.name);return this.getProfessionalsBySpecialtyAndServiceQuery.render({pending:()=>Y`<div id="professionals-results"><schedule-loading-banner></schedule-loading-banner></div>`,complete:e=>{if(0===e.length)return Y`<mq-callout background="default" variant="info">${H("No hay profesionales disponibles para la especialidad seleccionada. Por favor, vuelve a intentarlo en otro momento o selecciona otra especialidad.")}</mq-callout>`;const s=e[0],a=s?.slots?.[0];h.track(y(this.patient.hash,this.specialty_id??"",this.service_id??"",a?.starts_at??"",s?.id??"",e.length,e.reduce((e,t)=>e+(t.slots?.length??0),0)));const o=function({professionals:e,serviceName:t,timezone:i}){const s=function(e,t){const[i]=e;if(void 0===i)return;const s=t(i);return e.every(e=>t(e)===s)?i:void 0}(e.flatMap(e=>e.slots??[]).filter(e=>e.duration>0).map(e=>Math.round(e.duration/60)),e=>String(e)),a=C(i,new Date);return[t,void 0===s?void 0:H(K`${s} minutos`),a].filter(e=>Boolean(e))}({professionals:e,serviceName:i,timezone:this.patient?.timezone??""});return Y`<div id="professionals-results"><p class="title">${H("Selecciona tu especialista")}</p><div class="applied-filters"><span class="applied-filters-label" id="applied-filters-label">${H("Resultados para:")}</span> <span class="applied-filters-values" role="group" aria-labelledby="applied-filters-label">${o.map(e=>Y`<mq-badge variant="primary">${e}</mq-badge>`)}</span></div></div>${e.map(e=>Y`<professional-card .professional="${e}" .serviceId="${this.service_id??""}" .specialtyId="${this.specialty_id??""}" @show-full-schedule="${i=>{i.stopPropagation();const s=this.service_id,a=this.specialty_id;void 0!==t&&void 0!==s&&void 0!==a&&this.dispatchEvent(new ShowFullScheduleEvent({professional:e,serviceId:s,service:t,specialtyId:a,firstAvailableSlotDay:qi(e.slots,this.patient?.timezone)}))}}"></professional-card>`)}`}})}};e([Q({context:s,subscribe:!0})],ji.prototype,"apiClient",void 0),e([Q({context:Re,subscribe:!0})],ji.prototype,"patient",void 0),e([ee({type:String})],ji.prototype,"specialty_id",void 0),e([ee({type:String})],ji.prototype,"service_id",void 0),ji=e([G(),t("professionals-list")],ji);const Bi=J`.container{display:flex;flex-direction:column;gap:var(--sp-6)}.page-container{width:100%;box-sizing:border-box;display:flex;flex-direction:column;gap:var(--size-4)}.header-background{background-color:var(--color-neutrals-background-weak);display:flex;justify-content:center;width:100%}.header-container{max-width:var(--content-max-width);margin:0 auto;display:flex;flex-direction:column;gap:var(--size-4);width:100%;box-sizing:border-box}.header-nav{display:flex;align-items:center;justify-content:space-between;width:100%}.title-section{display:flex;flex-direction:column;gap:var(--size-1);align-items:center;width:100%}.title-content{display:flex;flex-direction:column;gap:var(--size-1);align-items:flex-start;padding-bottom:var(--size-2);width:100%;box-sizing:border-box}.main-title{font-family:var(--font-titles);font-size:31px;font-weight:var(--font-weight-bold);line-height:normal;color:var(--color-neutrals-text-default);margin:0;white-space:nowrap}.subtitle{font-family:var(--font-body);font-size:var(--text-base);font-weight:var(--font-weight-normal);line-height:22px;color:var(--color-neutrals-text-default);margin:0;white-space:pre-wrap;min-width:100%;width:min-content}.empty-space{height:32px;width:auto}.banner-container{align-items:flex-start;box-sizing:border-box;display:flex;gap:var(--size-2);padding:var(--size-4) var(--size-2);width:100%;background-color:var(--color-neutrals-background-disabled);color:var(--color-neutrals-text-default);font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);border-radius:var(--border-radius-sm)}.banner-icon{flex-shrink:0;display:flex;align-items:center;justify-content:center}.banner-message{margin:0;white-space:pre-wrap}@media (min-width:768px){.page-container{gap:var(--sp-8)}}`;let Ti=class SuccessEvent extends Event{static{this.eventName="success"}constructor(e){super(SuccessEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}},Oi=class SelectProfessionalStep extends X{constructor(){super(...arguments),this.showBack=!0,this.defaultSpecialty=void 0,this.defaultService=void 0,this.formData=void 0,this.getScheduleServicesQuery=new i(this,()=>S(this.apiClient)),this.getOrganizationSpecialtiesQuery=new i(this,()=>d(this.apiClient))}static{this.styles=Bi}get isScheduleFiltersReady(){const e=this.getScheduleServicesQuery.result?.isSuccess,t=this.getOrganizationSpecialtiesQuery.result?.isSuccess;return!!e&&!!t}get showSearchForm(){const e=this.getScheduleServicesQuery.result?.data,t=this.getOrganizationSpecialtiesQuery.result?.data;if(!e||!t)return!1;const i=e.length>1||t.length>1;return!(1===e.length&&1===t.length&&!this.formData)&&(i||!this.formData)}updated(){if(this.formData)return;if(this.defaultService&&this.defaultSpecialty)return void(this.formData={service_id:this.defaultService,specialty_id:this.defaultSpecialty});const e=this.getScheduleServicesQuery.result?.data,t=this.getOrganizationSpecialtiesQuery.result?.data;if(e?.length&&t?.length&&1===e.length&&1===t.length){const i=e[0],s=t[0];if(!i||!s)return;this.formData={service_id:i.id,specialty_id:String(s.id)}}}connectedCallback(){super.connectedCallback(),h.track(b(this.patient.hash))}scrollToProfessionalsList(){setTimeout(()=>{this.shadowRoot?.querySelector("professionals-list")?.scrollIntoView({behavior:"smooth"})},0)}render(){return Y`<div class="container"><div class="page-container">${this.showBack?Y`<mq-page-title .title="${H("Petición de cita")}" .showBack="${!0}" @mq-back="${e=>et(this,e)}"></mq-page-title>`:Z} ${this.isScheduleFiltersReady?Z:Y`<schedule-loading-banner></schedule-loading-banner>`} ${this.isScheduleFiltersReady&&this.showSearchForm?Y`<search-professionals-form .defaultValues="${{service:this.formData?.service_id??this.defaultService??"",specialty:this.formData?.specialty_id??this.defaultSpecialty??""}}" @success="${e=>{e.stopPropagation(),this.formData={service_id:e.detail.service,specialty_id:e.detail.specialty},this.scrollToProfessionalsList()}}"></search-professionals-form>`:Z} ${this.isScheduleFiltersReady?Y`<professionals-list .specialty_id="${this.formData?.specialty_id}" .service_id="${this.formData?.service_id}" @selected-slot="${e=>{e.stopPropagation();const t=this.formData;if(!t?.service_id||!t.specialty_id)return;const i=this.getScheduleServicesQuery.result?.data?.find(e=>e.id===t.service_id);this.dispatchEvent(new Ti({slot:e.detail.slot,serviceId:t.service_id,service:i,specialtyId:t.specialty_id,professional:e.detail.professional}))}}"></professionals-list>`:Z}</div></div>`}};function Ui(e,t){return{queryKey:_(e,"schedule-service-professional-slots",t),queryFn:()=>e.schedules.getScheduleServiceProfessionalSlots(t),staleTime:x}}e([Q({context:s,subscribe:!0})],Oi.prototype,"apiClient",void 0),e([Q({context:Re,subscribe:!0})],Oi.prototype,"patient",void 0),e([ee({type:Boolean})],Oi.prototype,"showBack",void 0),e([ee({type:String})],Oi.prototype,"defaultSpecialty",void 0),e([ee({type:String})],Oi.prototype,"defaultService",void 0),e([te()],Oi.prototype,"formData",void 0),Oi=e([G(),t("select-professional-step")],Oi);const Ni=()=>"undefined"!=typeof window&&window.innerWidth>=Be.mobile?6:4;class SlotSelectEvent extends Event{static{this.eventName="slot-select"}constructor(e){super(SlotSelectEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}class SlotUnavailableEvent extends Event{static{this.eventName="slot-unavailable"}constructor(){super(SlotUnavailableEvent.eventName,{bubbles:!0,composed:!0})}}const Ri=J`:host{display:block}.card{overflow-x:auto;padding:var(--sp-4);display:flex;flex-direction:column;gap:var(--sp-4)}.error-message{color:var(--color-error-text-default);font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);margin:0;text-align:center}@media (min-width:768px){.card{padding:var(--sp-8) var(--sp-4)}}`;let Wi=class DaysWindowView extends X{constructor(){super(...arguments),this.specialityId=void 0,this.reschedulingAppointmentId=void 0,this.windowStartDate=void 0,this.errorMessage=void 0,this.checkForSlotAvailabilityMutation=new ue(this,{mutationFn:e=>this.apiClient.schedules.getScheduleSlot({slot_id:e,service_id:this.serviceId||void 0,speciality_id:this.specialityId})}),this._visibleDays=Ni(),this.getScheduleServiceProfessionalSlotsQuery=new i(this,()=>{const e=this.patient.timezone,t=P(new Date,e),i=this.windowStartDay<t?t:this.windowStartDay,s=qe(Te(Fe(i),this._visibleDays-1),"yyyy-MM-dd");return Ui(this.apiClient,{service_id:this.serviceId,professional_hash:this.professionalId,starts_at:E(I(i,e)),finishes_at:E(M(s,e)),rescheduling_appointment_id:this.reschedulingAppointmentId})})}static{this.styles=Ri}get windowStartDay(){return this.windowStartDate??P(new Date,this.patient.timezone)}connectedCallback(){super.connectedCallback(),this._resizeHandler=()=>{const e=Ni();e!==this._visibleDays&&(this._visibleDays=e,this.requestUpdate())},window.addEventListener("resize",this._resizeHandler)}disconnectedCallback(){super.disconnectedCallback(),this._resizeHandler&&window.removeEventListener("resize",this._resizeHandler)}render(){const e=new Date,t=this.getScheduleServiceProfessionalSlotsQuery.result?.isPending,i=this.getScheduleServiceProfessionalSlotsQuery.result?.data?.filter(t=>Ve($(t.starts_at),e)&&t.status===B.available),s=i?.map(e=>({key:e.id,date:$(e.starts_at).toISOString()})),a=le().replace("_","-");return Y`<mq-card class="card" roundness="md"><mq-button @click="${()=>this.dispatchEvent(new CustomEvent("to-calendar-view"))}">${Le({size:24})} ${H("Elige otra fecha")}</mq-button>${this.errorMessage?Y`<p class="error-message">${this.errorMessage}</p>`:Z}<mq-time-slot-picker .locale="${a}" .timezone="${this.patient.timezone}" .visibleDays="${this._visibleDays}" .slots="${s??[]}" .windowStartDate="${this.windowStartDay}" ?is-loading="${t}" @window-change="${e=>{this.windowStartDate=e.detail.windowStartDate}}" .isLoading="${this.checkForSlotAvailabilityMutation.isPending}" @slot-select="${async e=>{e.stopPropagation();const t=e.detail.slot.key,i=await this.checkForSlotAvailabilityMutation.run(t);i.status===B.available?this.dispatchEvent(new SlotSelectEvent({slot:i})):this.dispatchEvent(new SlotUnavailableEvent)}}"></mq-time-slot-picker></mq-card>`}};e([Q({context:s,subscribe:!0})],Wi.prototype,"apiClient",void 0),e([ee({type:String})],Wi.prototype,"professionalId",void 0),e([ee({type:String})],Wi.prototype,"serviceId",void 0),e([ee({type:Number})],Wi.prototype,"specialityId",void 0),e([ee({type:String})],Wi.prototype,"reschedulingAppointmentId",void 0),e([ee({type:String})],Wi.prototype,"windowStartDate",void 0),e([ee({type:String,attribute:"error-message"})],Wi.prototype,"errorMessage",void 0),e([Q({context:Re,subscribe:!0})],Wi.prototype,"patient",void 0),Wi=e([G(),t("days-window-view")],Wi);const Qi=J`:host{display:block;max-width:var(--content-max-width);margin:0 auto}`;let Hi=class CalendarView extends X{constructor(){super(...arguments),this.reschedulingAppointmentId=void 0,this.initialDate=void 0,this.currentMonth=void 0,this.getScheduleServiceProfessionalSlotsQuery=new i(this,()=>{const e=this.patient.timezone,t=P(new Date,e),i=qe(De(this.displayedMonth),"yyyy-MM-dd"),s=i<t?t:i,a=qe(ze(Fe(s)),"yyyy-MM-dd");return Ui(this.apiClient,{service_id:this.serviceId,professional_hash:this.professionalId,starts_at:E(I(s,e)),finishes_at:E(M(a,e)),rescheduling_appointment_id:this.reschedulingAppointmentId})})}static{this.styles=Qi}get displayedMonth(){return this.currentMonth??Fe(this.initialDate??P(new Date,this.patient.timezone))}render(){const e=new Date,t=this.getScheduleServiceProfessionalSlotsQuery.result?.isPending,i=this.getScheduleServiceProfessionalSlotsQuery.result?.data?.filter(t=>Ve($(t.starts_at),e)&&t.status===B.available),s=i&&i.length>0?Array.from(new Set(i.map(e=>P($(e.starts_at),this.patient.timezone)))):void 0,a=le().replace("_","-");return Y`<mq-calendar locale="${a}" ?is-loading="${t}" .timezone="${this.patient.timezone}" .currentMonth="${this.displayedMonth.toISOString()}" .availableDays="${s}" @prev-month="${e=>{this.currentMonth=new Date(e.detail.currentMonth)}}" @next-month="${e=>{this.currentMonth=new Date(e.detail.currentMonth)}}"></mq-calendar>`}};e([Q({context:s,subscribe:!0})],Hi.prototype,"apiClient",void 0),e([ee({type:String})],Hi.prototype,"professionalId",void 0),e([ee({type:String})],Hi.prototype,"serviceId",void 0),e([ee({type:String})],Hi.prototype,"reschedulingAppointmentId",void 0),e([ee({type:String})],Hi.prototype,"initialDate",void 0),e([Q({context:Re,subscribe:!0})],Hi.prototype,"patient",void 0),e([te()],Hi.prototype,"currentMonth",void 0),Hi=e([t("calendar-view")],Hi);class SuccessEvent extends Event{static{this.eventName="success"}constructor(e){super(SuccessEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}const Ki=J`:host{display:flex;flex-direction:column;gap:var(--sp-6)}.content{display:flex;flex-direction:column;gap:var(--sp-4)}calendar-view{width:100%}days-window-view{width:100%}@media (min-width:768px){.content{flex-direction:row;gap:var(--sp-6)}new-appointment-summary{width:50%}days-window-view{width:50%}calendar-view{width:50%}}`;let Gi=class SelectSlotStep extends X{constructor(){super(...arguments),this.kind="schedule",this.showBack=!0,this.reschedulingAppointmentId=void 0,this.startsAt=void 0,this.duration=void 0,this.channel=void 0,this.errorMessage=void 0,this.initialDate=void 0,this.service=void 0,this.appliedDiscount=null,this.getScheduleServiceSpecialitiesQuery=new i(this,()=>{return e=this.apiClient,t=this.serviceId,i={enabled:!!this.serviceId},{queryKey:_(e,"schedule-service-specialities",t),queryFn:()=>e.schedules.getScheduleServiceSpecialities(t),staleTime:x,...i};var e,t,i}),this.view="days-window",this.windowStartDate=void 0}static{this.styles=Ki}connectedCallback(){super.connectedCallback(),this.initialDate&&(this.windowStartDate=this.initialDate)}renderView(){return"days-window"===this.view?Y`<days-window-view .errorMessage="${this.errorMessage}" .professionalId="${this.professionalId}" .serviceId="${this.serviceId}" .specialityId="${this.professional?.speciality?.id}" .reschedulingAppointmentId="${this.reschedulingAppointmentId}" .windowStartDate="${this.windowStartDate}" @to-calendar-view="${()=>{this.view="calendar"}}" @slot-select="${e=>{this.dispatchEvent(new SuccessEvent({slot:e.detail.slot}))}}" @slot-unavailable="${()=>{this.errorMessage=H("Este horario no está disponible. Por favor, seleccione otro."),this.queryClientContext?.invalidateQueries({queryKey:_(this.apiClient)})}}"></days-window-view>`:Y`<calendar-view .professionalId="${this.professionalId}" .serviceId="${this.serviceId}" .reschedulingAppointmentId="${this.reschedulingAppointmentId}" .initialDate="${this.initialDate}" @date-select="${e=>{this.windowStartDate=qe(new Date(e.detail.date),"yyyy-MM-dd"),this.view="days-window"}}"></calendar-view>`}render(){const e=this.getScheduleServiceSpecialitiesQuery.result?.data?.find(e=>e.id===this.professional?.speciality?.id)?.price??null;return Y`<mq-page-title .title="${"schedule"===this.kind?H("Petición de cita"):H("Modificar cita")}" .showBack="${this.showBack}" @mq-back="${e=>et(this,e)}"></mq-page-title><div class="content"><new-appointment-summary .professional="${this.professional}" .channel="${this.channel}" .startsAt="${this.startsAt}" .duration="${this.duration}" .serviceCode="${this.service?.code}" .serviceName="${this.service?.name}" .servicePrice="${e}" .appliedDiscount="${this.appliedDiscount}" .showPrice="${"reschedule"!==this.kind}"></new-appointment-summary>${this.renderView()}</div>`}};e([Q({context:s,subscribe:!0})],Gi.prototype,"apiClient",void 0),e([ee({type:String})],Gi.prototype,"kind",void 0),e([ee({type:Boolean})],Gi.prototype,"showBack",void 0),e([ee({type:String})],Gi.prototype,"serviceId",void 0),e([ee({type:String})],Gi.prototype,"professionalId",void 0),e([ee({type:String})],Gi.prototype,"reschedulingAppointmentId",void 0),e([ee({type:Object})],Gi.prototype,"professional",void 0),e([ee({type:String})],Gi.prototype,"startsAt",void 0),e([ee({type:Number})],Gi.prototype,"duration",void 0),e([ee({type:String})],Gi.prototype,"channel",void 0),e([ee({type:String,attribute:"error-message"})],Gi.prototype,"errorMessage",void 0),e([ee({type:String})],Gi.prototype,"initialDate",void 0),e([ee({type:Object})],Gi.prototype,"service",void 0),e([ee({type:Object})],Gi.prototype,"appliedDiscount",void 0),e([Q({context:Ee,subscribe:!0})],Gi.prototype,"queryClientContext",void 0),e([te()],Gi.prototype,"view",void 0),e([te()],Gi.prototype,"windowStartDate",void 0),Gi=e([G(),t("select-slot-step")],Gi);let Zi=class SelectSlotStepSkeleton extends X{constructor(){super(...arguments),this.showTitle=!0}static{this.styles=J`:host{display:flex;flex-direction:column;gap:var(--sp-6)}.page-title-skeleton{display:flex;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4)}.content{display:flex;flex-direction:column;gap:var(--sp-4)}.block{width:100%;display:flex;flex-direction:column;gap:var(--sp-4)}@media (min-width:768px){.page-title-skeleton{gap:var(--sp-6)}.content{flex-direction:row;gap:var(--sp-6)}.block{width:50%}}`}render(){return Y`${this.showTitle?Y`<div class="page-title-skeleton"><mq-skeleton width="var(--size-10)" height="var(--size-10)"></mq-skeleton><mq-skeleton width="120px" height="var(--size-6)"></mq-skeleton></div>`:Z}<div class="content"><div class="block"><mq-skeleton width="100%" height="190px"></mq-skeleton></div><div class="block"><mq-skeleton width="100%" height="317px"></mq-skeleton></div></div>`}};function Ji(e){return{id:e.id,name:e.name,avatar:e.avatar,description:e.description,collegiate_number:e.collegiate_number,languages:e.languages,speciality:e.speciality}}e([ee({type:Boolean,attribute:"show-title"})],Zi.prototype,"showTitle",void 0),Zi=e([t("select-slot-step-skeleton")],Zi),de();class AppointmentCreatedEvent extends Event{static{this.eventName="appointment-created"}constructor(e){super(AppointmentCreatedEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}let Xi=class MqSchedule extends X{constructor(){super(...arguments),this.requiresPayment=!0,this.showBackButton=!0,this.googlePayEnabled=!1,this.applePayEnabled=!1,this.stripeRedirect=!1,this._patient=new R(this,{context:Re,initialValue:{hash:"",name:"",timezone:"UTC"}}),this.apiClient=T(),this._emittedCreated=!1,this._organizationChanged=!1,this.getAppointmentQuery=new i(this,()=>o(this.apiClient,{id:this.appointmentId??""},{enabled:!!this.appointmentId})),this.getProfessionalQuery=new i(this,()=>{return e=this.apiClient,t={hash:this.defaultProfessionalHash??""},i={enabled:!!this.defaultProfessionalHash},{queryKey:_(e,"professional-public-profile",t.hash),queryFn:()=>e.profile.getProfessionalPublicProfile(t),staleTime:x,...i};var e,t,i}),this.getScheduleSlotQuery=new i(this,()=>{const e=this._current(this.getScheduleServicesQuery.result)?.data,t=this._current(this.getOrganizationSpecialtiesQuery.result)?.data;return i=this.apiClient,s={slot_id:this.defaultSlotId??"",service_id:Qe(this.defaultService,e)?.id,speciality_id:We(this.defaultSpecialty,t)},a={enabled:!!(this.defaultSlotId&&this.token&&e&&t)},{queryKey:_(i,"schedules","slot",s.slot_id,s.service_id,s.speciality_id),queryFn:()=>i.schedules.getScheduleSlot(s),staleTime:x,...a};var i,s,a}),this.getPatientProfileQuery=new i(this,()=>w(this.apiClient,{enabled:!!this.token})),this.getOrganizationSpecialtiesQuery=new i(this,()=>d(this.apiClient)),this.getScheduleServicesQuery=new i(this,()=>S(this.apiClient)),this.getOrganizationSetupQuery=new i(this,()=>r(this.apiClient,{enabled:"reschedule"===this.kind}))}static{this.styles=J`.reschedule-policy-blocked{padding:var(--sp-6);display:flex;flex-direction:column;gap:var(--sp-4);max-width:36rem;margin:0 auto}.reschedule-policy-blocked p{margin:0;font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height)}`}willUpdate(e){e.has("env")&&this.env&&ne(this.env);const t=e.has("apiKey")&&void 0!==e.get("apiKey");t&&(this._wizard&&this.removeController(this._wizard),this._wizard=void 0,this._emittedCreated=!1),this._organizationChanged=t,e.has("locale")&&this.locale&&ce(this.locale)&&pe(this.locale);const i=O(e,{env:this.env,apiKey:this.apiKey,token:this.token,locale:this.locale},this.inheritedApiClient);i&&(this.apiClient=i);const s=this.getPatientProfileQuery.result?.data;this._patient.setValue({hash:s?.hash??"",name:U(s),timezone:A(this.timezone,this.loginToken?.patient?.timezone)})}_current(e){return this._organizationChanged?void 0:e}_initWizard(e,t,i){return this._wizard||(this._wizard=new Ue(this,e,t),i&&this._wizard.goTo(i)),this._wizard}_stepHandlers(e){return{next:t=>e.next(t),goTo:(t,i,s)=>e.goTo(t,i,s),back:()=>{e.back()||this.dispatchEvent(new V({source:"mq-schedule"}))},update:t=>e.reconcile(t),onCreated:e=>{this._emittedCreated||(this._emittedCreated=!0,this.dispatchEvent(new AppointmentCreatedEvent({appointmentId:e})))},onAuthRequired:e=>{this.dispatchEvent(new AuthRequiredEvent(e))}}}_hostConfig(){const e=this.getPatientProfileQuery.result?.data;return{apiKey:this.apiKey,token:this.token,env:this.env,locale:this.locale,countryCode:e?.profile.billing.country_code??void 0,successUrl:this.applePaySuccessUrl,returnUrl:this.returnUrl,googlePayEnabled:this.googlePayEnabled,applePayEnabled:this.applePayEnabled,stripeRedirect:this.stripeRedirect}}_renderStep(e,t){const i=e.canGoBack||this.showBackButton;return Ne(this.apiKey??"",function(e,t,i,s,a,o){const r=H("No se ha podido reservar este horario. Por favor, seleccione otro."),n=s?{id:s.from.hash,name:s.from.name??"",avatar:s.from.avatar,description:s.from.description,collegiate_number:s.from.collegiate_number,languages:s.from.languages,speciality:{id:s.speciality_id??0}}:void 0,l=t.professional??n,{showBack:d,isAuthenticated:c}=a;if("selectProfessional"===e)return Y`<select-professional-step .showBack="${d}" .defaultSpecialty="${t.specialty}" .defaultService="${t.service?.id}" @show-full-schedule="${e=>{i.goTo("selectSlot",{service:e.detail.service,specialty:e.detail.specialtyId,professional:Ji(e.detail.professional),firstAvailableSlotDay:e.detail.firstAvailableSlotDay,appliedDiscount:void 0,error:!1})}}" @back="${i.back}" @success="${e=>{const t=e.detail.service;t&&(c?i.goTo("completeProfile",{slot:e.detail.slot,service:t,specialty:e.detail.specialtyId,professional:Ji(e.detail.professional),appliedDiscount:void 0,error:!1}):i.onAuthRequired({professionalHash:e.detail.professional.id,slotId:e.detail.slot.id,serviceId:t.id,specialtyId:e.detail.specialtyId}))}}"></select-professional-step>`;if("selectSlot"===e){if(s){const e=s.service_id;return e&&n?Y`<select-slot-step kind="reschedule" .showBack="${d}" .errorMessage="${t.error?r:void 0}" .serviceId="${e}" .reschedulingAppointmentId="${s.id}" .professionalId="${s.from.hash}" .professional="${n}" .startsAt="${s.start_date}" .duration="${s.duration}" .channel="${s.channel}" @back="${i.back}" @success="${e=>{i.next({slot:e.detail.slot,appliedDiscount:void 0,error:!1})}}"></select-slot-step>`:Z}if(!l)return Z;const e=t.service;return e?Y`<select-slot-step kind="schedule" .showBack="${d}" .errorMessage="${t.error?r:void 0}" .serviceId="${e.id}" .service="${e}" .professionalId="${l.id}" .professional="${l}" .initialDate="${t.firstAvailableSlotDay}" .appliedDiscount="${t.appliedDiscount??null}" @back="${i.back}" @discount-applied="${e=>i.update({appliedDiscount:e.detail})}" @success="${s=>{c?i.next({slot:s.detail.slot,error:!1}):i.onAuthRequired({professionalHash:l.id,slotId:s.detail.slot.id,serviceId:e.id,specialtyId:t.specialty})}}"></select-slot-step>`:Y`<select-slot-step-skeleton></select-slot-step-skeleton>`}if("completeProfile"===e){const e=t.slot;return s?e&&s.service_id&&n?Y`<complete-profile-step .showBack="${d}" .serviceId="${s.service_id}" .channel="${s.channel}" .scheduleSlot="${e}" .professional="${l??n}" @back="${i.back}" @success="${()=>i.next()}"></complete-profile-step>`:Z:e&&l&&t.service?Y`<complete-profile-step .showBack="${d}" .serviceId="${t.service.id}" .channel="${t.service.channel??t.slot?.channel}" .scheduleSlot="${e}" .professional="${l}" @back="${i.back}" @success="${()=>i.next()}"></complete-profile-step>`:Z}if("confirm"===e){const e=t.slot;return s?e&&s.service_id&&n?Y`<confirm-step kind="reschedule" .showBack="${d}" .scheduleSlot="${e}" .professional="${n}" .serviceId="${s.service_id}" .specialityId="${s.speciality_id?.toString()??""}" .startsAt="${e.starts_at}" .duration="${s.duration}" .appointment="${s}" .requiresPayment="${!1}" @back="${i.back}" @success="${e=>i.onCreated(e.detail.appointmentId)}" @error="${()=>i.goTo("selectSlot",{error:!0},{replace:!0})}"></confirm-step>`:Z:e&&l&&t.service?Y`<confirm-step kind="schedule" .showBack="${d}" .scheduleSlot="${e}" .professional="${l}" .serviceId="${t.service.id}" .specialityId="${t.specialty??""}" .service="${t.service}" .startsAt="${e.starts_at}" .duration="${e.duration}" .channel="${t.service.channel??t.slot?.channel}" .requiresPayment="${t.requiresPayment}" .appliedDiscount="${t.appliedDiscount??null}" .returnUrl="${o?.returnUrl}" @back="${i.back}" @success="${e=>i.onCreated(e.detail.appointmentId)}" @discount-applied="${e=>i.update({appliedDiscount:e.detail})}" @payment-started="${e=>{i.next({paymentSessionId:e.detail.sessionId,paymentUrl:e.detail.paymentUrl,paymentRequest:e.detail.request,paymentProvider:e.detail.provider})}}" @error="${()=>i.goTo("selectSlot",{error:!0},{replace:!0})}"></confirm-step>`:Z}if("payment"===e){const e=t.paymentSessionId,s=t.paymentUrl,r=l,n=t.slot;return e&&r&&n?Y`<payment-step .showBack="${d}" .sessionId="${e}" .paymentUrl="${s??""}" .professional="${r}" .startsAt="${n.starts_at}" .duration="${n.duration}" .channel="${t.service?.channel??n.channel}" .service="${t.service}" .scheduleSlot="${n}" .appliedDiscount="${t.appliedDiscount??null}" .bookingRequest="${t.paymentRequest??null}" .provider="${t.paymentProvider}" .apiKey="${o?.apiKey}" .token="${o?.token}" .env="${o?.env??"production"}" .locale="${o?.locale??"es_ES"}" .countryCode="${o?.countryCode??"ES"}" .successUrl="${o?.successUrl}" .googlePayEnabled="${o?.googlePayEnabled??!1}" .applePayEnabled="${o?.applePayEnabled??!1}" .stripeRedirect="${o?.stripeRedirect??!1}" @back="${i.back}" @success="${e=>i.onCreated(e.detail.appointmentId)}" @discount-applied="${async e=>{if(i.update({appliedDiscount:e.detail}),Ye(e.detail))return;const s=t.paymentRequest;if(!s)return;const o={...s,discount_code:e.detail.code};try{const e=await a.apiClient.payments.createPaymentLink(o);i.update({paymentSessionId:e.session_id,paymentUrl:e.payment_link,paymentRequest:o,paymentProvider:e.provider,error:!1})}catch{i.update({error:!0}),i.back()}}}" @payment-success="${e=>i.onCreated(e.detail.appointmentId)}" @payment-retry="${async e=>{const s=t.paymentRequest;if(!s)return i.update({error:!0}),void i.back();try{const e=await a.apiClient.payments.createPaymentLink(s);i.update({paymentSessionId:e.session_id,paymentUrl:e.payment_link,paymentProvider:e.provider,error:!1})}catch{i.update({error:!0}),i.back()}}}" @error="${()=>{i.update({error:!0}),i.back()}}"></payment-step>`:Z}return Z}(e.current,e.ctx,this._stepHandlers(e),t,{showBack:i,isAuthenticated:!!this.token,apiClient:this.apiClient},this._hostConfig()))}renderReschedulePolicyBlocked(){return Y`<div class="reschedule-policy-blocked"><p>${H("Esta cita ya no se puede modificar ni anular: no queda el tiempo mínimo requerido antes del inicio.")}</p><mq-button variant="primary" @click="${()=>this.dispatchEvent(new V({source:"mq-schedule"}))}">${H("Volver")}</mq-button></div>`}render(){const e=Y`<select-slot-step-skeleton .showTitle="${!1}"></select-slot-step-skeleton>`;if(this.token&&this.getPatientProfileQuery.result?.isPending)return e;const t=!!this.getPatientProfileQuery.result?.data&&N(this.getPatientProfileQuery.result.data);if("reschedule"===this.kind){const i=this._current(this.getAppointmentQuery.result),s=this._current(this.getOrganizationSetupQuery.result);if(i?.isPending||s?.isPending)return e;const a=i?.data;if(!a)return e;const o=s?.data?.appointments?.seconds_before_start_to_refund_on_cancel;if(!F({startsAtIso:a.start_date,refundPolicySeconds:o}))return this.renderReschedulePolicyBlocked();const r=function(e){const{appointment:t}=e,i={id:t.from.hash,name:t.from.name??"",avatar:t.from.avatar,description:t.from.description,collegiate_number:t.from.collegiate_number,languages:t.from.languages,speciality:{id:t.speciality_id??0}};return{service:void 0,specialty:t.speciality_id?.toString(),slot:void 0,professional:i,firstAvailableSlotDay:void 0,paymentSessionId:void 0,paymentUrl:void 0,paymentProvider:void 0,paymentRequest:void 0,appliedDiscount:void 0,profileComplete:e.profileComplete,requiresPayment:!1,error:!1}}({appointment:a,profileComplete:t}),n=this._initWizard(Xe,r);return n.reconcile({profileComplete:t}),this._renderStep(n,a)}if(this.defaultProfessionalHash){const i=this._current(this.getProfessionalQuery.result);if(!i||i.isPending)return e;const s=!!this.defaultSlotId&&!!this.token,a=this._current(this.getScheduleSlotQuery.result);if(s&&(!a||a.isPending))return e;const o=s?a?.data:void 0,r="available"===o?.status,n=s&&r,l=He({defaultSpecialty:this.defaultSpecialty,defaultService:this.defaultService,defaultProfessionalHash:this.defaultProfessionalHash,specialties:this._current(this.getOrganizationSpecialtiesQuery.result)?.data,services:this._current(this.getScheduleServicesQuery.result)?.data,professional:i.data,profileComplete:t,requiresPayment:this.requiresPayment}),d=this._initWizard(Je,{...l,slot:r?o:void 0,error:s&&!r},n?"completeProfile":void 0);return d.reconcile({profileComplete:t,service:l.service??d.ctx.service,professional:l.professional??d.ctx.professional,specialty:d.ctx.specialty??l.specialty,slot:d.ctx.slot??(r?o:void 0)}),this._renderStep(d,void 0)}const i=He({defaultSpecialty:this.defaultSpecialty,defaultService:this.defaultService,defaultProfessionalHash:void 0,specialties:this._current(this.getOrganizationSpecialtiesQuery.result)?.data,services:this._current(this.getScheduleServicesQuery.result)?.data,professional:void 0,profileComplete:t,requiresPayment:this.requiresPayment}),s=this._initWizard(Ze,i);return s.reconcile({profileComplete:t,service:i.service??s.ctx.service,specialty:s.ctx.specialty??i.specialty}),this._renderStep(s,void 0)}};e([ee({type:String,attribute:"default-specialty"})],Xi.prototype,"defaultSpecialty",void 0),e([ee({type:String,attribute:"default-service"})],Xi.prototype,"defaultService",void 0),e([ee({type:String,attribute:"default-professional-hash"})],Xi.prototype,"defaultProfessionalHash",void 0),e([ee({type:String,attribute:"default-slot-id"})],Xi.prototype,"defaultSlotId",void 0),e([ee({type:String,attribute:"kind"})],Xi.prototype,"kind",void 0),e([ee({type:Boolean,attribute:"requires-payment"})],Xi.prototype,"requiresPayment",void 0),e([ee({type:String,attribute:"appointment-id"})],Xi.prototype,"appointmentId",void 0),e([ee({type:Boolean,attribute:"show-back-button",converter:{fromAttribute:e=>null===e||"false"!==e&&"0"!==e,toAttribute:e=>e?"":"false"}})],Xi.prototype,"showBackButton",void 0),e([ee({type:String,attribute:"api-key"})],Xi.prototype,"apiKey",void 0),e([ee({type:String,attribute:"token"})],Xi.prototype,"token",void 0),e([ee({type:String,attribute:"locale"})],Xi.prototype,"locale",void 0),e([ee({type:String,attribute:"env"})],Xi.prototype,"env",void 0),e([ee({type:String,attribute:"apple-pay-success-url"})],Xi.prototype,"applePaySuccessUrl",void 0),e([ee({type:String,attribute:"return-url"})],Xi.prototype,"returnUrl",void 0),e([ee({type:Boolean,attribute:"google-pay-enabled"})],Xi.prototype,"googlePayEnabled",void 0),e([ee({type:Boolean,attribute:"apple-pay-enabled"})],Xi.prototype,"applePayEnabled",void 0),e([ee({type:Boolean,attribute:"stripe-redirect"})],Xi.prototype,"stripeRedirect",void 0),e([ee({type:String,attribute:"timezone"})],Xi.prototype,"timezone",void 0),e([Q({context:a,subscribe:!0})],Xi.prototype,"loginToken",void 0),e([Q({context:s,subscribe:!0}),te()],Xi.prototype,"inheritedApiClient",void 0),e([W({context:s}),te()],Xi.prototype,"apiClient",void 0),Xi=e([G(),t("mq-schedule")],Xi);export{AppointmentCreatedEvent as A,Xi as M,AuthRequiredEvent as a};
@@ -0,0 +1 @@
1
+ import{_ as t,c as o}from"./custom-element-D2ziPxYE.js";import{e}from"./provide-BwI4DDGF.js";import{c as i}from"./consume-CovVqBjI.js";import{m as a}from"./runtime-Bg1WXVCx.js";import{l as r}from"./localized-decorator-BlOuLhym.js";import{c as s,g as n,n as c}from"./api-chat-client-DgSWD5IP.js";import"./chunk-NIAGR3ZC-BDlNUZa1.js";import{Q as p}from"./query-controller-B1byDHlF.js";import{A as l}from"./api-client-context-BXGqBAlO.js";import{M as d}from"./mutation-controller-CR2qcqhH.js";import{g as h}from"./get-organization-setup-query-De7eM6V3.js";import{g as m}from"./chunk-BUV4MGML-CkhBbfUu.js";import{g as u}from"./chunk-Y4EKUX25-Bix9r5ry.js";import{a as v,i as g,E as f,x as y}from"./lit-element-DiWJYFwC.js";import{n as b}from"./property-scuRaFcM.js";import{r as _}from"./state-LQivXIgA.js";import{tokens as w}from"../theme.js";import{annotationQuestionIcon as k}from"../ui/icons/annotation-question-icon.js";import{spinnerIcon as q}from"../ui/icons/spinner-icon.js";import{xIcon as x}from"../ui/icons/x-icon.js";import"./mq-chat-room-82OqHZDt.js";import"../ui/mq-avatar.js";import{S as C,a as j,b as z,c as $,d as R}from"./index-BkDanNQg.js";import{toast as E}from"../ui/mq-toast.js";let I=class MqSupportChat extends v{constructor(){super(...arguments),this.variant="icon",this.open=!1,this._hasOpened=!1,this._lastEmittedUnread=0,this._orgSetupQuery=new p(this,()=>h(this.apiClient)),this._professionalQuery=new p(this,()=>m(this.apiClient,{hash:this._professionalHash??""},{enabled:Boolean(this._professionalHash)})),this._unreadQuery=new p(this,()=>u(this.apiClient,{roomId:this.roomId??0},{enabled:Boolean(this.roomId)})),this._supportRoomMutation=new d(this,{mutationFn:t=>this.apiClient.rooms.createSupportRoom(t),onSuccess:t=>{this.roomId=t.room_id,this.open&&this._markSupportRead()},onError:()=>{this.open&&(this.open=!1,E.error(a("No se ha podido abrir el chat con soporte")))}}),this._readAllMutation=new d(this,{mutationFn:()=>this.apiClient.professionals.readAllMessages({roomId:this.roomId??0}),onSuccess:()=>{const t=this.roomId;t&&this._unreadQuery.queryClient?.invalidateQueries({queryKey:u(this.apiClient,{roomId:t}).queryKey})}}),this.apiClient=s(),this._onUnreadRequest=()=>{this._emitUnreadChange()},this._onToggleRequest=()=>{this._toggle()},this._onKeydown=t=>{t.defaultPrevented||"Escape"===t.key&&this.open&&this._close()}}static{this.styles=[w,g`*{box-sizing:border-box}:host{position:fixed;bottom:calc(var(--mq-safe-bottom,0px) + var(--sp-1));right:calc(var(--sp-4) + var(--mq-safe-right,0px));z-index:1000}@keyframes widget-in{from{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}.widget{animation:widget-in .3s ease-out}.launcher{display:inline-flex;align-items:center;padding:0;border:none;background-color:var(--color-primary-light);border-radius:9999px;cursor:pointer;transition:transform .1s ease-out}.launcher:active{transform:scale(.95)}.launcher:focus-visible{outline:0}.icon-circle{position:relative;flex-shrink:0;width:var(--size-13);height:var(--size-13);--avatar-size:var(--size-13);border-radius:var(--border-radius-full);display:grid;place-items:center;background-color:var(--color-primary);color:var(--color-white);transition:background-color .1s ease-out,color .1s ease-out}.launcher.open .icon-circle{background-color:var(--color-primary-light);color:var(--color-primary-dark)}.icon{position:absolute;display:grid;place-items:center;transition:opacity .12s ease-out,transform .12s ease-out}.icon-chat{opacity:1;transform:rotate(0)}.launcher.open .icon-chat{opacity:0;transform:rotate(90deg)}.icon-close{opacity:0;transform:rotate(-90deg)}.launcher.open .icon-close{opacity:1;transform:rotate(0)}.icon-circle.with-avatar{background-color:var(--color-primary-light)}.launcher-avatar{width:var(--size-13);height:var(--size-13)}.icon-circle.with-avatar .icon-close,.launcher.open .icon-circle.with-avatar .icon-chat{transform:none}.icon-circle.with-avatar .online-dot{z-index:1}.online-dot{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%) translate(calc(var(--avatar-size) * .35355),calc(var(--avatar-size) * -.35355));width:var(--size-3);height:var(--size-3);border-radius:var(--border-radius-full);background-color:var(--color-gray-medium);border:2px solid var(--color-background);transition:opacity .2s ease-out}.online-dot[data-presence=online]{background-color:var(--color-text-icons--success)}.online-dot[data-presence=absent]{background-color:#ff014d}.launcher.has-unread .online-dot,.launcher.open .online-dot{opacity:0}@keyframes badge-in{from{transform:scale(0)}to{transform:scale(1)}}.badge{position:absolute;top:calc(-1 * var(--size-1));right:calc(-1 * var(--size-1));min-width:var(--size-5);height:var(--size-5);padding:0 var(--sp-1);display:grid;place-items:center;background-color:var(--color-negative);border:2px solid var(--color-background);border-radius:9999px;color:var(--color-white);font-family:var(--font-body);font-size:var(--text-xs);line-height:1;font-weight:var(--font-weight-bold);animation:badge-in .15s ease-out;z-index:2}.panel{position:fixed;z-index:1;inset:var(--mq-safe-top,0) var(--mq-safe-right,0) var(--mq-safe-bottom,0) var(--mq-safe-left,0);background-color:var(--color-white);overflow:hidden;transform:scale(.95);transform-origin:bottom right;opacity:0;visibility:hidden;pointer-events:none;transition:opacity .15s ease-out,transform .15s ease-out,visibility 0s linear .15s}.panel.open{opacity:1;transform:none;visibility:visible;pointer-events:auto;transition:opacity .15s ease-out,transform .15s ease-out}.panel-loading{width:100%;height:100%;display:grid;place-items:center}mq-chat-room{display:block;width:100%;height:100%}@media (min-width:768px){.panel{inset:auto;bottom:calc(var(--size-20) + var(--mq-safe-bottom,0px));right:calc(var(--sp-4) + var(--mq-safe-right,0px));width:400px;height:calc(100vh - 6rem - var(--mq-safe-top,0px) - var(--mq-safe-bottom,0px));max-height:560px;border-radius:var(--border-radius-lg)}}`]}get _professionalHash(){return this._orgSetupQuery.result?.data?.support_professional?.hash??void 0}get unreadCount(){return this._unreadQuery.result?.data?.unread_count??0}get _presence(){const t=this._professionalQuery.result?.data;return t?n(t):void 0}connectedCallback(){super.connectedCallback(),window.addEventListener("keydown",this._onKeydown),window.addEventListener(C.eventName,this._onToggleRequest),window.addEventListener(j.eventName,this._onUnreadRequest)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("keydown",this._onKeydown),window.removeEventListener(C.eventName,this._onToggleRequest),window.removeEventListener(j.eventName,this._onUnreadRequest)}willUpdate(t){const o=c(t,{apiKey:this.apiKey,token:this.token},this.inheritedApiClient);o&&(this.apiClient=o)}updated(){this._ensureRoom();const t=this.unreadCount;t!==this._lastEmittedUnread&&(this._lastEmittedUnread=t,this._emitUnreadChange())}_ensureRoom(){const t=this._professionalHash;!t||this.roomId||this._supportRoomMutation.isPending||this._supportRoomMutation.isError||this._supportRoomMutation.run({professional_hash:t})}_emitUnreadChange(){window.dispatchEvent(new z(this.unreadCount))}_markSupportRead(){const t=this.roomId,o=this._unreadQuery.queryClient;t&&o&&(o.setQueryData(u(this.apiClient,{roomId:t}).queryKey,t=>t?{...t,unread_count:0}:t),this._readAllMutation.run(void 0))}_toggle(){this.open?this._close():this._open()}_open(){this.open=!0,this._hasOpened=!0,this.dispatchEvent(new $),!this.roomId&&this._supportRoomMutation.isError&&this._supportRoomMutation.reset(),this._ensureRoom(),this._markSupportRead()}_close(){this.open=!1,this.dispatchEvent(new R)}render(){const t=this._professionalHash;if(!t||!this.token)return f;const o=this._professionalQuery.result?.data;if("avatar"===this.variant&&!o)return f;const e=this.unreadCount>0,i="avatar"===this.variant&&Boolean(o);return y`<div class="widget"><div class="panel ${this.open?"open":""}">${this._hasOpened?this.roomId?y`<mq-chat-room api-key="${this.apiKey}" token="${this.token}" professional-hash="${t}" .roomId="${this.roomId}" @mq-chat-room-close="${this._close}"></mq-chat-room>`:y`<div class="panel-loading">${q({color:"var(--color-primary)"})}</div>`:f}</div><button type="button" class="launcher ${this.open?"open":""} ${e?"has-unread":""}" aria-label="${this.label||a("Chat con soporte")}" aria-expanded="${this.open?"true":"false"}" @click="${this._toggle}"><span class="icon-circle ${i?"with-avatar":""}">${this._presence?y`<span class="online-dot" data-presence="${this._presence}"></span>`:f} ${e&&!this.open?y`<span class="badge">${this.unreadCount>99?"99+":this.unreadCount}</span>`:f} <span class="icon icon-chat">${i?y`<mq-avatar class="launcher-avatar" .src="${o?.avatar??void 0}" .fallback="${o?.name}" .alt="${o?.name}"></mq-avatar>`:k({size:24})} </span><span class="icon icon-close">${x({size:24})}</span></span></button></div>`}};t([b({type:String,attribute:"api-key"})],I.prototype,"apiKey",void 0),t([b({type:String,attribute:"token"})],I.prototype,"token",void 0),t([b({type:String,attribute:"label"})],I.prototype,"label",void 0),t([b({type:String,attribute:"variant"})],I.prototype,"variant",void 0),t([_()],I.prototype,"open",void 0),t([_()],I.prototype,"roomId",void 0),t([_()],I.prototype,"_hasOpened",void 0),t([i({context:l,subscribe:!0}),_()],I.prototype,"inheritedApiClient",void 0),t([e({context:l}),_()],I.prototype,"apiClient",void 0),I=t([r(),o("mq-support-chat")],I);export{I as M};
@@ -9,7 +9,6 @@ import { LitElement } from 'lit';
9
9
  * `@mediquo/elements/react/mq-unread-count-sync`).
10
10
  */
11
11
  declare class MqUnreadCountSync extends LitElement {
12
- private _controller;
13
12
  createRenderRoot(): this;
14
13
  render(): symbol;
15
14
  }
@@ -0,0 +1 @@
1
+ import{_ as e,c as t}from"./custom-element-D2ziPxYE.js";import{a as r,E as n}from"./lit-element-DiWJYFwC.js";let s=class MqUnreadCountSync extends r{createRenderRoot(){return this}render(){return n}};s=e([t("mq-unread-count-sync")],s);export{s as M};
@@ -0,0 +1 @@
1
+ import{_ as t,c as e}from"./custom-element-D2ziPxYE.js";import{a as i,i as o,E as s,x as n}from"./lit-element-DiWJYFwC.js";import{n as r}from"./property-scuRaFcM.js";import{spinnerIcon as a}from"../ui/icons/spinner-icon.js";import{e as l}from"./provide-BwI4DDGF.js";import{c as d}from"./consume-CovVqBjI.js";import{h as c}from"./task-Bj8p7kJX.js";import{A as p}from"./api-client-context-BXGqBAlO.js";import{f as h,A as m,C as u,c as v,n as g,i as b}from"./api-chat-client-DgSWD5IP.js";import{r as f}from"./state-LQivXIgA.js";import{n as y}from"./create-context-DqP79qjF.js";import{g as w,p as x,a as k}from"./chunk-NIAGR3ZC-BDlNUZa1.js";import{env as $}from"../env.js";import{m as C}from"./runtime-Bg1WXVCx.js";import{l as E}from"./localized-decorator-BlOuLhym.js";import{a as _}from"./addSeconds-fO5orJrt.js";import{getLocale as S}from"../i18n.js";import{calendarIcon as z}from"../ui/icons/calendar-icon.js";import"../ui/mq-page-title.js";import"./professional-overview-B4E05rLd.js";import{MqViewAppointmentsEvent as T}from"../events.js";import{clockIcon as O}from"../ui/icons/clock-icon.js";import"./documentation-view-DbtlEQSG.js";import{l as q}from"./chunk-S5RWG6G2-CQJ38pW6.js";import{t as I,u as j,w as R,x as V,y as A}from"./telemetry-client-K37KMdy_.js";import"./mq-chat-room-82OqHZDt.js";import{chatbubbleIcon as N}from"../ui/icons/chat-bubble-icon.js";import{micIcon as U}from"../ui/icons/mic-icon.js";import{micOffIcon as P}from"../ui/icons/mic-off-icon.js";import{videoIcon as W}from"../ui/icons/video-icon.js";import{videoOffIcon as M}from"../ui/icons/video-off-icon.js";import"../ui/mq-unread-badge.js";import{Q as D}from"./query-controller-B1byDHlF.js";import{g as K}from"./chunk-Y4EKUX25-Bix9r5ry.js";import{l as L}from"./chunk-FUCSYDW7-Duj5hy8S.js";import"../ui/mq-floating-bubble.js";import{e as F}from"./query-CeeutdfT.js";import{M as B}from"./mutation-controller-CR2qcqhH.js";import{alertCircleIcon as H}from"../ui/icons/alert-circle-icon.js";import"../ui/mq-rating.js";import{toast as G}from"../ui/mq-toast.js";import{heartBeatIcon as Q}from"../ui/icons/heartbeat-icon.js";import{timeLeftIcon as Y}from"../ui/icons/time-left-icon.js";import"./mq-layout-BndHxkbb.js";class PermissionController{constructor(t){this.state="prompt",this.host=t,t.addController(this)}async hostConnected(){await this.requestPermissions()}async requestPermissions(){try{const t=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});for(const e of t.getTracks())e.stop();this.state="granted"}catch{this.state="denied"}finally{this.host.requestUpdate()}}}class InvalidTokenError extends Error{}function Z(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(t){return decodeURIComponent(atob(t).replace(/(.)/g,(t,e)=>{let i=e.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}(e)}catch(t){return atob(e)}}InvalidTokenError.prototype.name="InvalidTokenError";const J=y(Symbol("opentok-service")),X=y(Symbol("params"));class OpenTokService{static{this.URL="https://static.opentok.com/v2/js/opentok.min.js"}_ensureLoaded(){if(!window.OT)throw new Error("OpenTok SDK is not loaded");return window.OT}load(){return new Promise((t,e)=>{if(window.OT)return void t();const i=document.createElement("script");i.src=OpenTokService.URL,i.onload=()=>{t()},i.onerror=e,document.head.appendChild(i)})}initSession(t,e){return this._ensureLoaded().initSession(t,e)}initPublisher(t,e,i){return this._ensureLoaded().initPublisher(t,e,i)}subscribe(t,e,i,o,s){return t.subscribe(e,i,o,s)}}const tt="waiting-room",et="videocall",it="documentation",ot="not-time-yet",st="review";class OpenTokController{constructor(t,e,i,o,s,n){this.isLoading=!0,this.isSessionReady=!1,this.isReconnecting=!1,this.errorMessage="",this.session=null,this.streams=[],this.destroyedStreamIds=new Set,this.openTokService=new OpenTokService,this.session_token=null,this.hasLeftWaitingRoom=!1,this.host=t,this.apiClient=e,t.addController(this),this.appointment=i,this.token=o,this.onCallStarted=s,this.onCallFinished=n,this._loadOpentok()}async _loadOpentok(){try{await this.openTokService.load(),this._initializeSession()}catch{this.isLoading=!1,this.errorMessage="Failed to load OpenTok script",this.host.requestUpdate()}}async _getSessionAndToken(){const t=await this.apiClient.flash.joinCall({callId:this.appointment.call_id});return this.session_token=t.session_token,[t.session_id,t.session_token]}async _initializeSession(){try{const[t,e]=await this._getSessionAndToken();this.session=this.openTokService.initSession($.OPENTOK_API_KEY,t),this.session.on("sessionConnected",()=>{this.isLoading=!1,this.isSessionReady=!0,this.host.requestUpdate()}),this.session.on("sessionDisconnected",()=>{this.isSessionReady=!1,this._leaveWaitingRoom(),setTimeout(()=>{this.onCallFinished(),this.host.requestUpdate()},1e3),this.host.requestUpdate()}),this.session.on("sessionReconnecting",()=>{this.isReconnecting=!0,this.host.requestUpdate()}),this.session.on("sessionReconnected",()=>{this.isReconnecting=!1;const t=this.streams.filter(t=>!this.destroyedStreamIds.has(t.streamId));this.streams=[],this.host.requestUpdate(),requestAnimationFrame(()=>{this.streams=t.filter(t=>!this.destroyedStreamIds.has(t.streamId)),this.host.requestUpdate()})}),this.session.on("streamCreated",t=>{this.streams=[...this.streams,t.stream],this.onCallStarted(),this.host.requestUpdate()}),this.session.on("streamDestroyed",t=>{t.stream?.streamId&&this.destroyedStreamIds.add(t.stream.streamId),setTimeout(()=>{this.streams=this.streams.filter(e=>e.streamId!==t.stream?.streamId),this._leaveWaitingRoom(),this.onCallFinished(),this.host.requestUpdate()},1e3)}),this.session.connect(e,t=>{t&&(this.isLoading=!1,this.errorMessage=`Failed to connect to session: ${t.message}`,this.host.requestUpdate())}),this.apiClient.flash.setReady({professional_hash:this.appointment.from.hash,consultation_id:this.appointment.id,consultation_type:"appointment"})}catch(t){this.isLoading=!1,this.errorMessage=`Error initializing session: ${t instanceof Error?t.message:"Unknown error"}`,this.host.requestUpdate()}}_leaveWaitingRoom(){this.hasLeftWaitingRoom||(this.hasLeftWaitingRoom=!0,this.apiClient.flash.leaveWaitingRoom({professional_hash:this.appointment.from.hash,consultation_id:this.appointment.id,consultation_type:"appointment"}))}hostDisconnected(){this._leaveWaitingRoom(),this.session&&(this.session.disconnect(),this.session.off("streamCreated"),this.session.off("streamDestroyed"),this.session.off("sessionConnected"),this.session.off("sessionDisconnected"),this.session.off("sessionReconnecting"),this.session.off("sessionReconnected"))}}let nt=class NotTimeYetView extends i{static{this.styles=[o`mq-page-title{margin-bottom:var(--size-3)}.description{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);color:var(--color-neutrals-text-default);font-weight:var(--font-weight-normal);margin:0;margin-bottom:var(--size-3)}.details-card{background-color:var(--color-background);border-radius:var(--border-radius-xl);padding:var(--size-6) var(--size-4);display:flex;min-width:0;flex-direction:column;gap:var(--size-6);margin-bottom:var(--size-6)}.details-card-title{padding:14px 0;font-size:var(--text-base);line-height:100%;font-weight:var(--font-weight-medium);color:var(--color-gray-darker);text-align:left}.details-rows{display:flex;flex-direction:column;gap:var(--size-3)}.details-row{display:flex;align-items:center;gap:var(--size-2);font-family:var(--font-body);font-size:var(--text-base);line-height:var(--text-base--line-height);color:var(--color-neutrals-text-default);font-weight:var(--font-weight-semibold)}.details-row span::first-letter{text-transform:uppercase}@media (min-width:768px){.description{font-size:var(--text-base);line-height:var(--text-base--line-height);margin-bottom:var(--sp-6)}}`]}firstUpdated(){I.track(j(this.loginToken.patient.hash,this.appointment.id??""))}render(){const t=S()?.replace("_","-")??"es-ES",e=w(this.loginToken.patient.timezone),i=new Intl.DateTimeFormat(t,{dateStyle:"full",...e?{timeZone:e}:{}}),o=new Intl.DateTimeFormat(t,{timeStyle:"short",...e?{timeZone:e}:{}}),r=x(this.appointment.start_date),a=_(r,this.appointment.duration),l=e?k(e,r):"";return n`<mq-page-title .title="${C("¡Aún no es la hora!")}" back-label="${C("Salir")}" @mq-back="${t=>{t.stopPropagation(),this.dispatchEvent(new T({tab:"next"}))}}"></mq-page-title><p class="description">${C("Cuando falten 10 minutos para tu consulta, podrás acceder a la videoconsulta")}</p><div class="details-card"><professional-overview .name="${this.appointment.from.name??""}" .specialtyName="${this.appointment.from.speciality??""}" .collegiateNumber="${this.appointment.from.collegiate_number??void 0}" .description="${this.appointment.from.description??""}" .languages="${this.appointment.from.languages}" .avatar="${this.appointment.from.avatar??""}"></professional-overview><div class="details-rows"><div class="details-row">${z({size:24})} <span>${i.format(r)}</span></div><div class="details-row">${O({size:24})} <span>${o.format(r)} - ${o.format(a)}${l?` (${l})`:""}</span></div></div></div>${!0===this.appointment.has_chat_in_appointment?n`<chat-cta .consultationId="${this.appointment.id}" .roomId="${Number(this.appointment.room_id)}" .professionalHash="${this.appointment.from.hash}" .text="${C("Utiliza el chat para enviar el motivo de consulta, documentos o imágenes")}" .onOpenChat="${()=>{I.track(R(this.loginToken.patient.hash,this.appointment.id??""))}}"></chat-cta>`:s}`}};t([r({type:Object})],nt.prototype,"appointment",void 0),t([d({context:q})],nt.prototype,"loginToken",void 0),nt=t([E(),e("not-time-yet-view")],nt);let rt=class PermissionStatusBanner extends i{static{this.styles=o`:host{display:block;padding:var(--size-5) var(--size-6);background-color:#ebf9ff;border-radius:var(--border-radius-lg);text-align:center}span{color:var(--color-neutrals-text-default);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal)}`}render(){return n`<span>${C("Espera a ser atendido sin salir de esta pantalla")}</span>`}};rt=t([E(),e("permission-status-banner")],rt);let at=class WaitingRoomLayout extends i{constructor(){super(...arguments),this.isWaitingRoom=!1}static{this.styles=o`.information-container{padding:var(--size-5) var(--size-4);background-color:var(--color-neutrals-background-disabled)}mq-page-title{margin-bottom:var(--size-4)}.content{max-width:560px;margin:0 auto}.information-container p{font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);color:var(--color-neutrals-text-default);margin:0}.video-container{margin-left:auto;margin-right:auto;margin-bottom:var(--size-6);position:relative;max-height:301px;aspect-ratio:9/16;border-radius:16px;overflow:hidden}@media (min-width:768px){.information-container{background-color:transparent;padding:var(--size-6) 0}.video-container{max-height:454px;aspect-ratio:16/9}.information-container p{font-size:var(--text-base);line-height:var(--text-base--line-height)}}`}firstUpdated(){this.isWaitingRoom&&I.track(V(this.loginToken.patient.hash,this.appointment.id??""))}render(){if(!this.isWaitingRoom)return n`<slot></slot>`;const t=S()?.replace("_","-")??"es-ES",e=w(this.loginToken.patient.timezone),i=e?{timeZone:e}:{},o=new Intl.DateTimeFormat(t,{dateStyle:"short",...i}),r=new Intl.DateTimeFormat(t,{timeStyle:"short",...i}),a=x(this.appointment.start_date),l=_(a,this.appointment.duration),d=e?k(e,a):"",c=o.format(a),p=`${r.format(a)} - ${r.format(l)}${d?` (${d})`:""}`;return n`<permission-status-banner></permission-status-banner><div class="content"><div class="information-container"><mq-page-title .title="${C("Sala de espera")}" back-label="${C("Salir")}" @mq-back="${t=>{t.stopPropagation(),this.dispatchEvent(new T({tab:"next"}))}}"></mq-page-title><div class="doctor-info"><p>${this.appointment.from.name}</p><p>${c}</p><p>${p}</p></div></div><div class="video-container"><slot></slot></div>${!0===this.appointment.has_chat_in_appointment?n`<chat-cta .consultationId="${this.appointment.id}" .roomId="${Number(this.appointment.room_id)}" .professionalHash="${this.appointment.from.hash}" .text="${C("Utiliza el chat para enviar el motivo de consulta, documentos o imágenes")}" .onOpenChat="${()=>{I.track(R(this.loginToken.patient.hash,this.appointment.id??""))}}"></chat-cta>`:s}</div>`}};t([r({type:Object})],at.prototype,"appointment",void 0),t([r({type:Boolean,attribute:"is-waiting-room"})],at.prototype,"isWaitingRoom",void 0),t([d({context:q})],at.prototype,"loginToken",void 0),at=t([e("waiting-room-layout")],at);class AppointmentCounterController{constructor(t,e){this.startsAtGetter=e,this.formattedTime="--:--",this.interval=null,this.host=t,t.addController(this)}async hostConnected(){this.interval=setInterval(()=>{const t=new Date,e=this.startsAtGetter(),i=t.getTime()-e.getTime(),o=Math.floor(i/1e3),s=Math.floor(o/60),n=o%60;this.formattedTime=`${s.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`,this.host.requestUpdate()},1e3)}hostDisconnected(){this.interval&&clearInterval(this.interval)}}class ToggleAudioEvent extends Event{static{this.eventName="toggle-audio"}constructor(t){super(ToggleAudioEvent.eventName,{bubbles:!0,composed:!0}),this.isAudioOn=t}}class ToggleVideoEvent extends Event{static{this.eventName="toggle-video"}constructor(t){super(ToggleVideoEvent.eventName,{bubbles:!0,composed:!0}),this.isVideoOn=t}}class ToggleChatEvent extends Event{static{this.eventName="toggle-chat"}constructor(t){super(ToggleChatEvent.eventName,{bubbles:!0,composed:!0}),this.isChatOpen=t}}class ViewDocumentationEvent extends Event{static{this.eventName="view-documentation"}constructor(){super(ViewDocumentationEvent.eventName,{bubbles:!0,composed:!0})}}class DownloadFileEvent extends Event{static{this.eventName="download-file"}constructor(t,e){super(DownloadFileEvent.eventName,{bubbles:!0,composed:!0}),this.url=t,this.filename=e}}let lt=class PublisherControls extends i{constructor(){super(...arguments),this.isAudioOn=!1,this.isVideoOn=!0,this.isChatOpen=!1,this.chatEnabled=!1,this.isWaitingRoom=!1,this.unreadQuery=new D(this,()=>K(this.apiClient,{roomId:this.roomId}))}static{this.styles=o`:host{display:flex;justify-content:space-between;gap:var(--size-4)}:host([is-waiting-room]){justify-content:center}.left-controls{display:flex;gap:var(--size-4)}.control-button{border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;width:var(--size-10);height:var(--size-10);padding:var(--size-2);border-radius:12.5px;transition:all .2s ease-in-out}@media (min-width:768px){.control-button{width:var(--size-11);height:var(--size-11);padding:var(--size-2);border-radius:16px}}.control-button:hover{background-color:var(--color-gray-light)}.control-button:focus-visible{outline:0;box-shadow:0 0 0 2px var(--color-primary-light)}.control-button--on{background-color:var(--color-white);color:var(--color-primary)}.control-button--off{background-color:var(--color-white);color:var(--color-negative)}`}toggleAudio(){this.dispatchEvent(new ToggleAudioEvent(!this.isAudioOn))}toggleVideo(){this.dispatchEvent(new ToggleVideoEvent(!this.isVideoOn))}toggleChat(){this.dispatchEvent(new ToggleChatEvent(!this.isChatOpen))}render(){return n`<div class="left-controls">${this.isWaitingRoom||!this.chatEnabled?s:n`<button type="button" class="control-button control-button--on" @click="${this.toggleChat}">${N({size:20})} ${(this.unreadQuery.result?.data?.unread_count??0)>0?n`<mq-unread-badge></mq-unread-badge>`:s}</button>`} <button type="button" class="control-button ${this.isAudioOn?"control-button--on":"control-button--off"}" @click="${this.toggleAudio}">${this.isAudioOn?U({size:20}):P({size:20})}</button> <button type="button" class="control-button ${this.isVideoOn?"control-button--on":"control-button--off"}" @click="${this.toggleVideo}">${this.isVideoOn?W({size:20}):M({size:20})}</button></div>`}};t([d({context:p,subscribe:!0})],lt.prototype,"apiClient",void 0),t([r({type:Boolean})],lt.prototype,"isAudioOn",void 0),t([r({type:Boolean})],lt.prototype,"isVideoOn",void 0),t([r({type:Boolean})],lt.prototype,"isChatOpen",void 0),t([r({type:Boolean})],lt.prototype,"chatEnabled",void 0),t([r({type:Boolean,reflect:!0,attribute:"is-waiting-room"})],lt.prototype,"isWaitingRoom",void 0),t([r({type:Number})],lt.prototype,"roomId",void 0),lt=t([e("publisher-controls")],lt);let dt=class VideoPublisher extends i{constructor(){super(...arguments),this.isWaitingRoom=!1,this.hasChatInAppointment=!1,this.appointmentCounterController=new AppointmentCounterController(this,()=>x(this.startsAt)),this.isAudioOn=!0,this.isVideoOn=!0,this.isChatOpen=!1,this._handleVisibilityChange=()=>{"visible"===document.visibilityState&&this.publisher&&(this.publisher.publishAudio(!1),this.publisher.publishVideo(!1),setTimeout(()=>{this.publisher?.publishAudio(this.isAudioOn),this.publisher?.publishVideo(this.isVideoOn)},500))}}static{this.styles=o`:host{width:100%;height:100%;display:block}.OT_video-element{width:100%;height:100%;background:var(--color-black)}.OT_mute{display:none}video{border-radius:var(--border-radius-lg)}#video-publisher{width:100%;height:100%;transition:width .5s ease-in-out,height .5s ease-in-out;border-radius:var(--border-radius-lg)}:host(:not([is-waiting-room])) #video-publisher{width:121px;height:200px;z-index:50;border-radius:12px;overflow:hidden}:host([is-waiting-room]) .top-items{position:absolute;inset:0}:host(:not([is-waiting-room])) .top-items{position:absolute;z-index:50;top:var(--size-4);left:var(--size-4);right:var(--size-4);display:flex;justify-content:space-between;gap:var(--size-1)}.meta-container{display:flex;align-items:flex-start;gap:var(--size-1);min-width:0}.meta-item{background-color:var(--color-neutrals-text-default);padding:var(--size-2) var(--size-3);color:var(--color-white);font-size:var(--text-xs);line-height:var(--text-xs--line-height);flex-shrink:0}.meta-item:first-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0}publisher-controls{position:absolute;z-index:50;bottom:var(--size-4);left:var(--size-4);right:var(--size-4)}mq-chat-room{height:100%}@media (min-width:768px){:host(:not([is-waiting-room])) #video-publisher{width:250px;height:auto;aspect-ratio:16/9}:host(:not([is-waiting-room])) .top-items{top:var(--size-6);left:var(--size-6);right:var(--size-6)}}`}firstUpdated(t){super.firstUpdated(t),this.publisher=this.openTokService.initPublisher(this.publisherEl,{fitMode:"contain",width:"100%",height:"100%",audioFallbackEnabled:!1,insertMode:"append",mirror:!1,publishAudio:this.isAudioOn,publishVideo:this.isVideoOn},t=>{t&&L.error("error initializing publisher",t),this.session.publish(this.publisher)}),document.addEventListener("visibilitychange",this._handleVisibilityChange)}disconnectedCallback(){document.removeEventListener("visibilitychange",this._handleVisibilityChange),super.disconnectedCallback(),this.publisher?.destroy()}async _handleToggleAudioEvent(t){this.isAudioOn=t.isAudioOn,this.publisher.publishAudio(t.isAudioOn)}async _handleToggleVideoEvent(t){this.isVideoOn=t.isVideoOn,this.publisher.publishVideo(t.isVideoOn)}async _handleToggleChatEvent(t){this.isChatOpen=t.isChatOpen}render(){return n`<div class="top-items">${this.isWaitingRoom?n`<div></div>`:n`<div class="meta-container"><span class="meta-item">${this.professionalName}</span> <span class="meta-item">${this.appointmentCounterController.formattedTime}</span></div>`}<div id="video-publisher"></div></div><publisher-controls .isAudioOn="${this.isAudioOn}" .isVideoOn="${this.isVideoOn}" .isChatOpen="${this.isChatOpen}" .chatEnabled="${this.hasChatInAppointment}" .roomId="${Number.parseInt(this.roomId,10)}" ?is-waiting-room="${this.isWaitingRoom}" @toggle-audio="${this._handleToggleAudioEvent}" @toggle-video="${this._handleToggleVideoEvent}" @toggle-chat="${this._handleToggleChatEvent}"></publisher-controls>${this.hasChatInAppointment?n`<mq-floating-bubble ?dismissable="${!1}" .open="${this.isChatOpen}" @mq-close="${()=>{this.isChatOpen=!1}}" hideCloseButton>${this.isChatOpen?n`<mq-chat-room slot="content" .consultationId="${this.consultationId}" .consultationType="${u.appointment}" token="${this.loginToken.access_token}" .roomId="${Number.parseInt(this.roomId,10)}" .professionalHash="${this.professionalHash}" @mq-chat-room-close="${()=>{this.isChatOpen=!1}}"></mq-chat-room>`:s}</mq-floating-bubble>`:s}`}};t([r({type:String})],dt.prototype,"consultationId",void 0),t([r({type:String})],dt.prototype,"apiKey",void 0),t([r({type:String})],dt.prototype,"token",void 0),t([r({type:String})],dt.prototype,"roomId",void 0),t([r({type:String})],dt.prototype,"professionalHash",void 0),t([r({type:Object})],dt.prototype,"session",void 0),t([r({type:String})],dt.prototype,"professionalName",void 0),t([r({type:String})],dt.prototype,"startsAt",void 0),t([r({type:Boolean,reflect:!0,attribute:"is-waiting-room"})],dt.prototype,"isWaitingRoom",void 0),t([r({type:Boolean})],dt.prototype,"hasChatInAppointment",void 0),t([d({context:J})],dt.prototype,"openTokService",void 0),t([d({context:q})],dt.prototype,"loginToken",void 0),t([F("#video-publisher")],dt.prototype,"publisherEl",void 0),t([f()],dt.prototype,"isAudioOn",void 0),t([f()],dt.prototype,"isVideoOn",void 0),t([f()],dt.prototype,"isChatOpen",void 0),dt=t([e("video-publisher")],dt);let ct=class VideoSubscriber extends i{constructor(){super(...arguments),this.isVideoOn=!0,this._subscriberProperties={fitMode:"contain",insertMode:"append",width:"100%",height:"100%"},this._handleVisibilityChange=()=>{"visible"===document.visibilityState&&this.subscriber&&(this.subscriber.subscribeToAudio(!1),this.subscriber.subscribeToVideo(!1),setTimeout(()=>{this.subscriber?.subscribeToAudio(!0),this.subscriber?.subscribeToVideo(!0)},500),setTimeout(()=>this._resubscribe(),600))}}static{this.styles=o`:host{position:absolute;inset:0}.OT_subscriber{width:100%;height:100%;position:absolute;inset:0;background:var(--color-neutrals-background-default)}video{width:100%;height:100%}.video-disabled{position:absolute;inset:0;background:var(--color-gray-dark)}.hidden{display:none}`}firstUpdated(){this._subscribe(),document.addEventListener("visibilitychange",this._handleVisibilityChange)}_subscribe(){this.subscriber=this.openTokService.subscribe(this.session,this.stream,this.subscriberEl,this._subscriberProperties,t=>{}),this._attachSubscriberEvents()}_attachSubscriberEvents(){this.subscriber.on("connected",t=>{this.isVideoOn=t.target.stream?.hasVideo??!0}),this.subscriber.on("videoDisabled",()=>{this.isVideoOn=!1}),this.subscriber.on("videoEnabled",()=>{this.isVideoOn=!0}),this.subscriber.on("disconnected",()=>{this.isVideoOn=!1})}_resubscribe(){if(this.subscriber&&this.session&&this.subscriberEl){try{this.session.unsubscribe(this.subscriber)}catch{}this.subscriberEl.innerHTML="",this._subscribe()}}disconnectedCallback(){if(document.removeEventListener("visibilitychange",this._handleVisibilityChange),this.subscriber&&this.session)try{this.session.unsubscribe(this.subscriber)}catch{}super.disconnectedCallback()}render(){return n`<div id="video-subscriber" class="${this.isVideoOn?"":"hidden"}"></div>${this.isVideoOn?n``:n`<div class="video-disabled"></div>`}`}};t([r({type:Object})],ct.prototype,"session",void 0),t([r({type:Object})],ct.prototype,"stream",void 0),t([f()],ct.prototype,"isVideoOn",void 0),t([d({context:J})],ct.prototype,"openTokService",void 0),t([F("#video-subscriber")],ct.prototype,"subscriberEl",void 0),ct=t([e("video-subscriber")],ct);let pt=class VideocallContent extends i{constructor(){super(...arguments),this.streams=[],this.isWaitingRoom=!1,this.isReconnecting=!1}static{this.styles=o`:host{display:block;position:relative;width:100%;height:100%;background:var(--color-gray-darkest);aspect-ratio:16/9}.reconnecting-overlay{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--size-3);background:rgba(0,0,0,.6);z-index:100}.reconnecting-overlay__text{color:var(--color-white);font-size:var(--text-sm);line-height:var(--text-sm--line-height)}.reconnecting-overlay__subtitle{color:var(--color-white);font-size:var(--text-xs);line-height:var(--text-xs--line-height);opacity:.85}`}firstUpdated(){this.isWaitingRoom||I.track(A(this.loginToken.patient.hash,this.appointment.id??""))}updated(t){t.has("isWaitingRoom")&&!0===t.get("isWaitingRoom")&&!this.isWaitingRoom&&I.track(A(this.loginToken.patient.hash,this.appointment.id??""))}render(){return n`<video-publisher .consultationId="${this.appointment.id}" .session="${this.session}" ?is-waiting-room="${this.isWaitingRoom}" .professionalName="${this.appointment.from.name??""}" .professionalHash="${this.appointment.from.hash}" .startsAt="${this.appointment.started_at??(new Date).toISOString()}" .apiKey="${this.apiKey}" .token="${this.token}" .roomId="${this.appointment.room_id}" .hasChatInAppointment="${!0===this.appointment.has_chat_in_appointment}"></video-publisher>${0===this.streams.length?n``:this.streams.map(t=>n`<video-subscriber .session="${this.session}" .stream="${t}"></video-subscriber>`)} ${this.isReconnecting?n`<div class="reconnecting-overlay">${a({color:"var(--color-white)"})} <span class="reconnecting-overlay__text">${C("Reconectando...")} </span><span class="reconnecting-overlay__subtitle">${C("Espere mientras se restablece la conexión")}</span></div>`:""}`}};t([r({type:Object})],pt.prototype,"session",void 0),t([r({type:Array})],pt.prototype,"streams",void 0),t([r({type:String})],pt.prototype,"apiKey",void 0),t([r({type:String})],pt.prototype,"token",void 0),t([r({type:Object})],pt.prototype,"appointment",void 0),t([r({type:Boolean,reflect:!0,attribute:"is-waiting-room"})],pt.prototype,"isWaitingRoom",void 0),t([r({type:Boolean,reflect:!0,attribute:"is-reconnecting"})],pt.prototype,"isReconnecting",void 0),t([d({context:q})],pt.prototype,"loginToken",void 0),pt=t([E(),e("mq-videocall-content")],pt);class ReviewSubmittedEvent extends Event{static{this.eventName="review-submitted"}constructor(){super(ReviewSubmittedEvent.eventName,{bubbles:!0,composed:!0})}}class ReviewSkippedEvent extends Event{static{this.eventName="review-skipped"}constructor(){super(ReviewSkippedEvent.eventName,{bubbles:!0,composed:!0})}}let ht=class ReviewView extends i{constructor(){super(...arguments),this.rating=0,this.comment="",this._reviewMutation=new B(this,{mutationFn:({rating:t,comment:e})=>this.apiClient.consultations.postReview({consultation_id:this.appointment.id??"",consultation_type:u.appointment,rating:t,comment:e.trim()?e.trim():null}),onSuccess:()=>{this.dispatchEvent(new ReviewSubmittedEvent)},onError:t=>{!function(t){const e=t,i=e?.response?.status;return 400===i&&/already exists/i.test(e?.response?.data?.message??"")}(t)?G.error(C("No se ha podido enviar el cuestionario")):this.dispatchEvent(new ReviewSubmittedEvent)}}),this._reconnectMutation=new B(this,{mutationFn:t=>this.apiClient.appointments.reconnectAppointment(t),onSuccess:()=>{this.dispatchEvent(new CustomEvent("review-reconnect",{bubbles:!0,composed:!0}))},onError:()=>{G.error(C("No se ha podido volver a la sala de espera"))}}),this.handleSkip=()=>{this.dispatchEvent(new ReviewSkippedEvent)},this.handleSubmit=()=>{this.rating<1||this.rating>5||this._reviewMutation.isPending||this._reviewMutation.run({rating:this.rating,comment:this.comment})}}static{this.styles=o`:host{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100%;background-color:var(--color-background);box-sizing:border-box}.container{width:100%;max-width:500px;padding:var(--sp-6);display:flex;flex-direction:column;gap:var(--sp-5);box-sizing:border-box}.title{margin:0;padding:0 var(--sp-6);font-family:var(--font-titles);font-size:var(--text-2xl);line-height:var(--text-2xl--line-height);font-weight:var(--font-weight-normal);color:var(--color-primary);text-align:center}.rating{display:flex;flex-direction:column;align-items:center;gap:var(--sp-2);padding:var(--sp-1) var(--sp-6)}.subtitle{margin:0;font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);color:var(--color-text-icons--secondary);text-align:center}.comment-card{background-color:var(--color-white);border:var(--action-border-width) solid var(--color-border);border-radius:var(--border-radius-lg);box-shadow:0 4px 4px rgba(0,0,0,.05);padding:var(--sp-5);display:flex;flex-direction:column;gap:var(--sp-5)}.comment-header{display:flex;justify-content:space-between;align-items:flex-start;gap:var(--sp-3)}.comment-label{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm);font-weight:var(--font-weight-medium);color:var(--color-neutrals-text-default)}.comment-counter{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);color:var(--color-text-icons--secondary);white-space:nowrap}.textarea{width:100%;box-sizing:border-box;height:var(--size-44);padding:var(--sp-3) var(--sp-4);background-color:var(--color-gray-lighter);border:var(--action-border-width) solid var(--color-border);border-radius:var(--border-radius-md);font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);color:var(--color-neutrals-text-default);resize:none}.textarea::placeholder{color:var(--color-text-icons--secondary);opacity:.6}.textarea:focus{outline:0;border-color:var(--color-primary)}.actions{display:flex;gap:var(--sp-4)}.btn{flex:1;height:var(--button-height-md);padding:var(--sp-2) var(--sp-4);border-radius:var(--border-radius-md);font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-medium);cursor:pointer;transition:opacity .15s ease-in-out}.btn:focus-visible{outline:2px solid var(--color-primary);outline-offset:2px}.btn:disabled{cursor:not-allowed}.btn-skip{background:var(--color-white);border:var(--action-border-width) solid var(--color-primary);color:var(--color-primary)}.btn-skip:hover:not(:disabled){background:var(--color-primary-background-extraWeak)}.btn-submit{background:var(--color-primary);border:var(--action-border-width) solid var(--color-primary);color:var(--color-white)}.btn-submit:hover:not(:disabled){background:var(--color-primary-dark)}.btn-submit:disabled{opacity:.5}.waiting-card{background-color:var(--color-background-primary-light);border-radius:var(--border-radius-lg);padding:var(--sp-4);display:flex;flex-direction:column;gap:var(--sp-2)}.waiting-header{display:flex;align-items:center;gap:var(--sp-2);color:var(--color-neutrals-text-default)}.waiting-title{font-family:var(--font-body);font-size:var(--text-xs);line-height:1;font-weight:var(--font-weight-medium);color:var(--color-neutrals-text-default)}.waiting-body{margin:0;font-family:var(--font-body);font-size:var(--text-xs);line-height:var(--text-xs--line-height);color:var(--color-text-icons--secondary)}.waiting-link{background:0 0;border:0;padding:0;cursor:pointer;color:#3c50ec;font:inherit;text-decoration:none}.waiting-link:hover{text-decoration:none}.waiting-link:disabled{cursor:not-allowed;opacity:.6}`}render(){return n`<div class="container"><h1 class="title">${C("¿Qué tal ha ido tu cita?")}</h1><div class="rating"><mq-rating .value="${this.rating}" .label="${C("Valoración de la consulta")}" @mq-rating-change="${t=>{this.rating=t.value}}"></mq-rating><p class="subtitle">${C("(1 es muy malo, 5 es excelente)")}</p></div><div class="comment-card"><div class="comment-header"><span class="comment-label">${C("¿Tienes comentarios sobre la consulta?")}</span> <span class="comment-counter">${this.comment.length}/${240}</span></div><textarea class="textarea" maxlength="${240}" placeholder="${C("Comparte cómo fue la atención o si tuviste algún problema con la videollamada…")}" .value="${this.comment}" @input="${t=>{this.comment=t.target.value}}"></textarea><div class="actions"><button type="button" class="btn btn-skip" ?disabled="${this._reviewMutation.isPending}" @click="${this.handleSkip}">${C("Omitir")}</button> <button type="button" class="btn btn-submit" ?disabled="${this.rating<1||this._reviewMutation.isPending}" @click="${this.handleSubmit}">${C("Enviar")}</button></div></div><div class="waiting-card"><div class="waiting-header">${H({color:"currentColor",size:18})} <span class="waiting-title">${C("¿Ocurrió algún problema?")}</span></div><p class="waiting-body">${C("Si la cita no se ha podido realizar, puedes")} <button type="button" class="waiting-link" ?disabled="${this._reconnectMutation.isPending}" @click="${()=>this._reconnectMutation.run({appointmentId:this.appointment.id})}">${C("volver a la sala de espera.")}</button></p></div></div>`}};t([d({context:p,subscribe:!0})],ht.prototype,"apiClient",void 0),t([r({type:Object})],ht.prototype,"appointment",void 0),t([f()],ht.prototype,"rating",void 0),t([f()],ht.prototype,"comment",void 0),ht=t([E(),e("review-view")],ht);let mt=class ErrorView extends i{static{this.styles=o`.container{display:grid;place-items:center;width:100%;max-width:447px;margin:0 auto}.card>:not(:first-child){margin-top:var(--size-8)}.title{font-family:var(--font-titles);color:var(--color-neutrals-text-default);font-size:var(--text-2xl);line-height:var(--text-2xl--line-height);font-weight:var(--font-weight-bold);margin:0;margin-bottom:var(--size-3)}.description{color:var(--color-neutrals-text-default);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:400}`}render(){return n`<div class="container"><div class="card"><slot name="icon"></slot><div class="content"><h1 class="title">${this.title}</h1><p class="description">${this.message}</p></div></div></div>`}};t([r({type:String})],mt.prototype,"title",void 0),t([r({type:String})],mt.prototype,"message",void 0),mt=t([e("error-view")],mt);let ut=class UnexpectedErrorView extends i{render(){return n`<error-view .title="${C("Error desconocido")}" .message="${C("Ha ocurrido un error al cargar la página. Por favor, intenta nuevamente o contacta al soporte.")}"><div slot="icon">${Q()}</div></error-view>`}};ut=t([E(),e("unexpected-error-view")],ut);let vt=class ExpiredAppointmentErrorView extends i{render(){return n`<error-view .title="${C("Consulta caducada")}" .message="${C("Parece que no te hemos encontrado a la hora de tu cita. Puedes programar otra consulta para resolver tus dudas.")}"><div slot="icon">${Y()}</div></error-view>`}};vt=t([E(),e("expired-appointment-error-view")],vt);let gt=class NotFoundErrorView extends i{static{this.styles=o`div{display:flex;flex-direction:column;gap:2px}span{font-size:var(--text-xs);line-height:var(--text-xs--line-height);font-weight:400;color:var(--color-gray-medium)}`}render(){return n`<error-view .title="${C("Página no encontrada")}" .message="${C("La página que estás buscando fue removida, renombrada o puede que no exista.")}"><div slot="icon"><span>404</span> ${Q()}</div></error-view>`}};function bt(t){try{return function(t,e){if("string"!=typeof t)throw new InvalidTokenError("Invalid token specified: must be a string");e||(e={});const i=!0===e.header?0:1,o=t.split(".")[i];if("string"!=typeof o)throw new InvalidTokenError(`Invalid token specified: missing part #${i+1}`);let s;try{s=Z(o)}catch(t){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${i+1} (${t.message})`)}try{return JSON.parse(s)}catch(t){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${i+1} (${t.message})`)}}(t)}catch{return null}}gt=t([E(),e("not-found-error-view")],gt);let ft=class MqVideocallProvider extends i{static{this.styles=o`*{box-sizing:border-box}:host{display:block;margin:0 auto;width:100%;height:100%}.centered{display:grid;place-items:center;height:100%;min-height:var(--mq-container-min-height)}documentation-view{display:block;padding:var(--sp-4)}`}constructor(){super(),this.apiClient=v(),this.opentokService=new OpenTokService,this.params={appointmentId:this.appointmentId,token:this.token,apiKey:this.apiKey},this.appointmentTask=new c(this,{task:async([t,,])=>{const[e,i,o]=await Promise.all([this.apiClient.flash.getAppointment({appointmentId:t}),this.apiClient.consultations.getReview(t).then(()=>!0).catch(()=>!1),this.apiClient.organizations.getOrganizationSetup().catch(()=>{})]);return{appointment:e,hasReview:i,hasNps:!0===o?.appointments?.has_nps}},args:()=>[this.appointmentId,this.apiKey,this.token]})}willUpdate(t){const e=g(t,{apiKey:this.apiKey,token:this.token},this.inheritedApiClient);if(e&&(this.apiClient=e),this.appointmentTask.value&&!this.opentokController){const{appointment:t,hasReview:e,hasNps:i}=this.appointmentTask.value,o=function(t,e){return h(t)?t.status===m.finished||t.status===m.reporting?e?st:it:tt:ot}(t,i);this.screen=o===st&&e?it:o,this.params={appointmentId:this.appointmentId,token:this.token,apiKey:this.apiKey},this.opentokController=new OpenTokController(this,this.apiClient,t,this.token,()=>{this.screen=et},()=>{this.screen=!i||e?it:st})}}render(){const t=n`<div class="centered">${a({color:"var(--color-primary)"})}</div>`,e=n`<mq-layout background="transparent"><not-found-error-view></not-found-error-view></mq-layout>`;return this.appointmentTask.render({pending:()=>t,error:t=>{const i=bt(this.token);return i?.exp&&i.exp<Date.now()/1e3?n`<mq-layout background="transparent"><expired-appointment-error-view></expired-appointment-error-view></mq-layout>`:b(t)&&t.response?.status&&t.response.status<500?e:n`<mq-layout background="transparent"><unexpected-error-view></unexpected-error-view></mq-layout>`},complete:({appointment:i,hasNps:o})=>{if(this.opentokController?.isLoading)return t;if(this.opentokController?.errorMessage||!this.opentokController)return e;if(this.screen===ot)return n`<mq-layout background="transparent"><not-time-yet-view .appointment="${i}"></not-time-yet-view></mq-layout>`;if(this.screen===st)return n`<mq-layout background="transparent"><review-view .appointment="${i}" @review-submitted="${()=>{this.screen=it}}" @review-skipped="${()=>{this.screen=it}}" @review-reconnect="${()=>{this.screen=tt}}"></review-view></mq-layout>`;if(this.screen===it)return n`<mq-layout background="transparent"><documentation-view .appointment="${i}" .token="${this.token}" ?can-reconnect="${!o}" @reconnect="${()=>{this.screen=tt}}"></documentation-view></mq-layout>`;if(this.screen===tt||this.screen===et){const e=this.opentokController.session;return e?n`<waiting-room-layout .appointment="${i}" ?is-waiting-room="${this.screen===tt}"><mq-videocall-content .apiKey="${this.apiKey}" .token="${this.token}" .session="${e}" .streams="${this.opentokController?.streams??[]}" ?is-waiting-room="${this.screen===tt}" ?is-reconnecting="${this.opentokController.isReconnecting}" .appointment="${i}"></mq-videocall-content></waiting-room-layout>`:t}return n`<mq-layout background="transparent"><unexpected-error-view></unexpected-error-view></mq-layout>`}})}};t([r({type:String,attribute:"appointment-id"})],ft.prototype,"appointmentId",void 0),t([r({type:String,attribute:"api-key"})],ft.prototype,"apiKey",void 0),t([r({type:String})],ft.prototype,"token",void 0),t([d({context:p,subscribe:!0}),f()],ft.prototype,"inheritedApiClient",void 0),t([l({context:p}),f()],ft.prototype,"apiClient",void 0),t([f()],ft.prototype,"screen",void 0),t([l({context:J})],ft.prototype,"opentokService",void 0),t([l({context:X})],ft.prototype,"params",void 0),ft=t([e("mq-videocall-provider")],ft);let yt=class PermissionsRequiredErrorView extends i{static{this.styles=o`.img-container{display:flex;justify-content:center}img{width:100%;height:auto;max-width:229px}`}render(){return n`<error-view .title="${C("Acepta los permisos de cámara y micrófono")}" .message="${C("Parece que has denegado los permisos necesarios para entrar a la videollamada. Edita los permisos en tu navegador para entrar. Una vez concedidos, debes refrescar esta pantalla.")}"><div class="img-container" slot="icon"><img src="${`${$.ASSETS_BASE_URL}/wc-videocall/Miccam_asset.png`}" alt="Miccam_asset" width="229" height="166.44"></div></error-view>`}};yt=t([E(),e("permissions-required-error-view")],yt);let wt=class MqVideocall extends i{constructor(){super(...arguments),this._permissionController=new PermissionController(this)}static{this.styles=o`:host{display:block;width:100%;height:100%}.loading-spinner-container{height:100%;display:flex;flex-direction:column;justify-content:center;align-items:center}.permissions-required-error-view-container{height:100%;padding-left:var(--size-4);padding-right:var(--size-4);display:grid;place-items:center}`}render(){return"prompt"===this._permissionController.state?n`<div class="loading-spinner-container">${a({color:"var(--color-primary)"})}</div>`:"denied"===this._permissionController.state?n`<div class="permissions-required-error-view-container"><permissions-required-error-view></permissions-required-error-view></div>`:n`<mq-videocall-provider .appointmentId="${this.appointmentId}" .token="${this.token}" .apiKey="${this.apiKey}"></mq-videocall-provider>`}};t([r({type:String,attribute:"appointment-id"})],wt.prototype,"appointmentId",void 0),t([r({type:String,attribute:"api-key"})],wt.prototype,"apiKey",void 0),t([r({type:String})],wt.prototype,"token",void 0),wt=t([e("mq-videocall")],wt);export{DownloadFileEvent as D,wt as M,ReviewSkippedEvent as R,ToggleAudioEvent as T,ViewDocumentationEvent as V,ReviewSubmittedEvent as a,ToggleChatEvent as b,ToggleVideoEvent as c};