@mediquo/elements 0.11.0-rc.0 → 0.12.0

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 (140) hide show
  1. package/README.md +7 -18
  2. package/dist/chunks/api-chat-client-Dx-sFrf2.js +1 -0
  3. package/dist/chunks/{apple-pay-outcomes-SIvDJWN_.js → apple-pay-outcomes--uAwZeLE.js} +1 -1
  4. package/dist/chunks/appointment-details-BM8peAHH.js +1 -0
  5. package/dist/chunks/{appointment-details-CVEDe_k0.d.ts → appointment-details-KL9fK6vG.d.ts} +1 -2
  6. package/dist/chunks/ca_ES-DYhnenv6.js +1 -0
  7. package/dist/chunks/checkout-bridge-BFpVxNww.js +1 -0
  8. package/dist/chunks/{chunk-Y4EKUX25-Bix9r5ry.js → chunk-Y4EKUX25-Bdei04iw.js} +1 -1
  9. package/dist/chunks/{chunk-YTQUGGS3-DH0H7ld7.js → chunk-YTQUGGS3-sBILRfPo.js} +1 -1
  10. package/dist/chunks/de_DE-Dw0iVZNb.js +1 -0
  11. package/dist/chunks/{documentation-view-BSt0gtCR.js → documentation-view-BcA4Vbhp.js} +1 -1
  12. package/dist/chunks/en_US-DONnbI9l.js +1 -0
  13. package/dist/chunks/{external-JLtsAfi6.js → external-cM_kgYO_.js} +1 -1
  14. package/dist/chunks/{index-CUirgiWh.d.ts → index-BEPyJrJL.d.ts} +1 -1
  15. package/dist/chunks/{index-B3rs7SlM.d.ts → index-BKjqWyIs.d.ts} +1 -1
  16. package/dist/chunks/{index-B6OMnYjW.js → index-CGWd3FWG.js} +1 -1
  17. package/dist/chunks/index-Djkwyh_M.js +1 -0
  18. package/dist/chunks/{index-CCWMMqiq.js → index-Dw4Aeoyg.js} +1 -1
  19. package/dist/chunks/{appointment.model.d-BWwBLaEL.d.ts → index-DwlJg2um.d.ts} +13 -0
  20. package/dist/chunks/{index-D2yqKnpP.js → index-VQqG1eyA.js} +1 -1
  21. package/dist/chunks/{index-DFaKhE7Q.d.ts → index-fut7tm1R.d.ts} +1 -1
  22. package/dist/chunks/{index.d-ByhRBSb1.d.ts → index.d-DHMNq1lu.d.ts} +2 -7
  23. package/dist/chunks/{login-token-task-Yib__6a9.js → login-token-task-NQJ77O_q.js} +1 -1
  24. package/dist/chunks/mq-chat-room-BkXGHzrd.js +1 -0
  25. package/dist/chunks/{mq-chat-room-C8wCADp2.d.ts → mq-chat-room-C0dJCvpV.d.ts} +2 -2
  26. package/dist/chunks/{mq-next-appointments-CbjNpG1H.js → mq-next-appointments-BngkXupq.js} +1 -1
  27. package/dist/chunks/{mq-recent-documents-DNqh_8J0.js → mq-recent-documents-Ee-JRTdl.js} +1 -1
  28. package/dist/chunks/mq-schedule-DAKftQ3D.js +1 -0
  29. package/dist/chunks/{mq-support-chat-tdev5LC-.js → mq-support-chat-Bzj5LYHb.js} +1 -1
  30. package/dist/chunks/{mq-videocall-CwYtlPu6.js → mq-videocall-Cp7LSoDs.js} +1 -1
  31. package/dist/chunks/{next-appointment-card-DLU7-wIv.js → next-appointment-card-BE0KW2vv.js} +1 -1
  32. package/dist/chunks/{next-appointment-card-CPg9FuOI.d.ts → next-appointment-card-Z5G1jqtz.d.ts} +4 -4
  33. package/dist/chunks/professional-overview-Ck_SPivX.js +1 -0
  34. package/dist/chunks/{professional-overview-mO3tuMuH.d.ts → professional-overview-QVHl_ITk.d.ts} +1 -0
  35. package/dist/chunks/pt_PT-dELUeDqB.js +1 -0
  36. package/dist/chunks/task-CqjSKFwZ.js +1 -0
  37. package/dist/chunks/{telemetry-client-K37KMdy_.js → telemetry-client-DA2_SZBC.js} +1 -1
  38. package/dist/env.js +1 -1
  39. package/dist/events.d.ts +1 -22
  40. package/dist/events.js +1 -1
  41. package/dist/i18n.js +1 -1
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.js +1 -1
  44. package/dist/mq-api-client-provider.d.ts +1 -1
  45. package/dist/mq-api-client-provider.js +1 -1
  46. package/dist/mq-apple-pay-checkout.d.ts +1 -1
  47. package/dist/mq-apple-pay-checkout.js +1 -1
  48. package/dist/mq-appointment-checkout.d.ts +20 -14
  49. package/dist/mq-appointment-checkout.js +1 -1
  50. package/dist/mq-appointment-documentation.d.ts +4 -4
  51. package/dist/mq-appointment-documentation.js +1 -1
  52. package/dist/mq-chat-room.d.ts +3 -3
  53. package/dist/mq-chat-room.js +1 -1
  54. package/dist/mq-checkout.d.ts +44 -61
  55. package/dist/mq-checkout.js +1 -1
  56. package/dist/mq-dashboard.d.ts +7 -7
  57. package/dist/mq-dashboard.js +1 -1
  58. package/dist/mq-documents.d.ts +2 -2
  59. package/dist/mq-documents.js +1 -1
  60. package/dist/mq-google-pay-checkout.d.ts +1 -1
  61. package/dist/mq-google-pay-checkout.js +1 -1
  62. package/dist/mq-immediate-videocall-checkout.d.ts +10 -9
  63. package/dist/mq-immediate-videocall-checkout.js +1 -1
  64. package/dist/mq-my-appointments.d.ts +6 -6
  65. package/dist/mq-my-appointments.js +1 -1
  66. package/dist/mq-next-appointments.d.ts +5 -5
  67. package/dist/mq-next-appointments.js +1 -1
  68. package/dist/mq-payment-poller.d.ts +2 -2
  69. package/dist/mq-payment-poller.js +1 -1
  70. package/dist/mq-professional-presence-sync.js +1 -1
  71. package/dist/mq-recent-documents.d.ts +2 -2
  72. package/dist/mq-recent-documents.js +1 -1
  73. package/dist/mq-schedule-success.d.ts +5 -5
  74. package/dist/mq-schedule-success.js +2 -2
  75. package/dist/mq-schedule.d.ts +54 -100
  76. package/dist/mq-schedule.js +1 -1
  77. package/dist/mq-socket-provider.js +1 -1
  78. package/dist/mq-support-chat.d.ts +4 -4
  79. package/dist/mq-support-chat.js +1 -1
  80. package/dist/mq-terms-and-conditions.d.ts +2 -2
  81. package/dist/mq-terms-and-conditions.js +1 -1
  82. package/dist/mq-unread-count-sync.js +1 -1
  83. package/dist/mq-videocall.d.ts +5 -5
  84. package/dist/mq-videocall.js +1 -1
  85. package/dist/react/mq-api-client-provider.d.ts +1 -1
  86. package/dist/react/mq-api-client-provider.js +1 -1
  87. package/dist/react/mq-apple-pay-checkout.d.ts +1 -1
  88. package/dist/react/mq-apple-pay-checkout.js +1 -1
  89. package/dist/react/mq-appointment-checkout.d.ts +12 -8
  90. package/dist/react/mq-appointment-checkout.js +1 -1
  91. package/dist/react/mq-appointment-documentation.d.ts +4 -4
  92. package/dist/react/mq-appointment-documentation.js +1 -1
  93. package/dist/react/mq-chat-room.d.ts +3 -3
  94. package/dist/react/mq-chat-room.js +1 -1
  95. package/dist/react/mq-checkout.d.ts +11 -8
  96. package/dist/react/mq-checkout.js +1 -1
  97. package/dist/react/mq-dashboard.d.ts +6 -6
  98. package/dist/react/mq-dashboard.js +1 -1
  99. package/dist/react/mq-documents-page.d.ts +2 -2
  100. package/dist/react/mq-documents-page.js +1 -1
  101. package/dist/react/mq-documents.d.ts +2 -2
  102. package/dist/react/mq-documents.js +1 -1
  103. package/dist/react/mq-google-pay-checkout.d.ts +1 -1
  104. package/dist/react/mq-google-pay-checkout.js +1 -1
  105. package/dist/react/mq-immediate-videocall-checkout.d.ts +4 -2
  106. package/dist/react/mq-immediate-videocall-checkout.js +1 -1
  107. package/dist/react/mq-my-appointments.d.ts +6 -6
  108. package/dist/react/mq-my-appointments.js +1 -1
  109. package/dist/react/mq-next-appointments.d.ts +5 -5
  110. package/dist/react/mq-next-appointments.js +1 -1
  111. package/dist/react/mq-payment-poller.d.ts +1 -1
  112. package/dist/react/mq-payment-poller.js +1 -1
  113. package/dist/react/mq-professional-presence-sync.js +1 -1
  114. package/dist/react/mq-recent-documents.d.ts +2 -2
  115. package/dist/react/mq-recent-documents.js +1 -1
  116. package/dist/react/mq-schedule-success.d.ts +5 -5
  117. package/dist/react/mq-schedule-success.js +1 -1
  118. package/dist/react/mq-schedule.d.ts +4 -14
  119. package/dist/react/mq-schedule.js +1 -1
  120. package/dist/react/mq-socket-provider.js +1 -1
  121. package/dist/react/mq-support-chat.d.ts +3 -3
  122. package/dist/react/mq-support-chat.js +1 -1
  123. package/dist/react/mq-terms-and-conditions.d.ts +2 -2
  124. package/dist/react/mq-terms-and-conditions.js +1 -1
  125. package/dist/react/mq-unread-count-sync.js +1 -1
  126. package/dist/react/mq-videocall.d.ts +5 -5
  127. package/dist/react/mq-videocall.js +1 -1
  128. package/dist/ui/mq-calendar.js +1 -1
  129. package/dist/ui/mq-tabs.js +49 -22
  130. package/package.json +3 -3
  131. package/dist/chunks/api-chat-client-s45J7LKB.js +0 -1
  132. package/dist/chunks/appointment-details-BYGwLfww.js +0 -1
  133. package/dist/chunks/ca_ES-BOvS9ayb.js +0 -1
  134. package/dist/chunks/de_DE-B-4V4SgD.js +0 -1
  135. package/dist/chunks/en_US-CgxjeeCm.js +0 -1
  136. package/dist/chunks/mq-chat-room-B_WgeuXn.js +0 -1
  137. package/dist/chunks/mq-schedule-BfW7y8uG.js +0 -1
  138. package/dist/chunks/professional-overview-B4E05rLd.js +0 -1
  139. package/dist/chunks/pt_PT-Vb6hoo2l.js +0 -1
  140. package/dist/chunks/task-Bj8p7kJX.js +0 -1
@@ -0,0 +1 @@
1
+ import{_ as e,c as t}from"./custom-element-D2ziPxYE.js";import{e as s}from"./provide-BwI4DDGF.js";import{c as i}from"./consume-CovVqBjI.js";import{l as o}from"./localized-decorator-BlOuLhym.js";import{m as a,s as r}from"./runtime-Bg1WXVCx.js";import{A as n}from"./api-client-context-BXGqBAlO.js";import{i as l,a as d,x as c,E as m}from"./lit-element-DiWJYFwC.js";import{n as h}from"./property-scuRaFcM.js";import{r as p}from"./state-LQivXIgA.js";import{n as g}from"./create-context-DqP79qjF.js";import{tokens as u}from"../theme.js";import{xIcon as v}from"../ui/icons/x-icon.js";import"../ui/mq-avatar.js";import"../ui/mq-button.js";import"../ui/mq-skeleton.js";import{Q as y}from"./query-controller-B1byDHlF.js";import{g as b}from"./chunk-BUV4MGML-CkhBbfUu.js";import{o as f}from"./if-defined-BYeVdwgd.js";import{chevronLeftIcon as w}from"../ui/icons/chevron-left-icon.js";import{l as x}from"./chunk-S5RWG6G2-CQJ38pW6.js";import{r as k,c as $}from"./chunk-NIAGR3ZC-BDlNUZa1.js";import{e as C}from"./query-CeeutdfT.js";import{l as z}from"./chunk-FUCSYDW7-Duj5hy8S.js";import{DownloadFileEvent as I}from"../events.js";import{M as T,c as M,n as D}from"./api-chat-client-Dx-sFrf2.js";import{S,g as q}from"./chunk-Y4EKUX25-Bdei04iw.js";import{checkDoubleIcon as j}from"../ui/icons/check-double-icon.js";import{checkIcon as P}from"../ui/icons/check-icon.js";import{getLocale as A}from"../i18n.js";import{f as _,p as E}from"./parseISO-CEksKisk.js";import{a as R}from"./addDays-CdyO-PRI.js";import{S as U,E as B}from"./chunk-YTQUGGS3-sBILRfPo.js";import{s as N}from"./context-consumer-ESdICVAb.js";import{s as H}from"./chunk-6CCJWPGL-TiaqZaPV.js";import{Q as L}from"./chunk-RCFIJTXZ-C6Ir0-sM.js";import{e as K}from"./class-map-Co76I6aw.js";import"./index-Djkwyh_M.js";import{M as O}from"./mutation-controller-CR2qcqhH.js";const F=g("apiKey"),Q=g("token"),V=g("professionalHash"),G=g("roomId"),Z=g("consultationId"),J=g("consultationType");class MqChatRoomCloseEvent extends Event{static{this.eventName="mq-chat-room-close"}constructor(){super(MqChatRoomCloseEvent.eventName,{bubbles:!0,composed:!0})}}class MqChatRoomProfileEvent extends Event{static{this.eventName="mq-chat-room-profile"}constructor(){super(MqChatRoomProfileEvent.eventName,{bubbles:!0,composed:!0})}}const W=l`header{padding:var(--size-3) var(--size-4);background-color:var(--color-background-primary);display:flex;justify-content:space-between;gap:var(--size-1)}.left-side{display:flex;flex:1;min-width:0;align-items:center;gap:var(--size-3)}.left-side mq-avatar{flex-shrink:0}.info{min-width:0}.ghost-btn{text-align:left;background:0 0;border:none;padding:0;cursor:pointer}.right-side{display:flex;align-items:center}.name{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-bold);margin:0;color:var(--color-background);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.specialty{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);margin:0;color:var(--color-white);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.name-skeleton{margin-bottom:var(--size-1)}.profile-title{font-family:var(--font-body);font-size:var(--text-lg);line-height:var(--text-lg--line-height);font-weight:var(--font-weight-medium);margin:0;color:var(--color-white)}`;let Y=class ChatRoomHeader extends d{constructor(){super(...arguments),this.hideCloseButton=!1,this.getProfessionalQuery=new y(this,()=>b(this.apiClient,{hash:this.professionalHash}))}static{this.styles=W}handleClose(){this.dispatchEvent(new MqChatRoomCloseEvent)}handleClickProfile(){this.dispatchEvent(new MqChatRoomProfileEvent)}renderProfile(){return c`<div class="left-side"><mq-button type="button" size="icon-md" variant="ghost-inverted" @click="${()=>{this.dispatchEvent(new CustomEvent("goto-chat",{bubbles:!0,composed:!0}))}}">${w({size:24})}</mq-button><p class="profile-title">${a("Perfil de profesional")}</p></div>`}renderChat(){return c`${this.getProfessionalQuery.render({complete:e=>c`<button type="button" class="left-side ghost-btn" @click="${this.handleClickProfile}"><mq-avatar src="${f(e.avatar??void 0)}" alt="User Avatar" fallback="John Doe" size="sm"></mq-avatar><div class="info"><p class="name">${e.name}</p><p class="specialty">${e.title}</p></div></button>`,pending:()=>c`<div class="left-side"><mq-skeleton width="45px" height="45px" border-radius="full"></mq-skeleton><div><mq-skeleton class="name-skeleton" height="14px" width="120px"></mq-skeleton><mq-skeleton height="14px" width="100px"></mq-skeleton></div></div>`})}`}render(){return c`<header>${"profile"===this.view?this.renderProfile():this.renderChat()}<div class="right-side">${this.hideCloseButton?m:c`<mq-button type="button" size="icon-md" variant="ghost-inverted" @click="${this.handleClose}">${v({size:24})}</mq-button>`}</div></header>`}};e([i({context:n,subscribe:!0})],Y.prototype,"apiClient",void 0),e([h({type:String})],Y.prototype,"professionalHash",void 0),e([h({type:Boolean})],Y.prototype,"hideCloseButton",void 0),e([h({type:String})],Y.prototype,"view",void 0),Y=e([o(),t("chat-room-header")],Y);const X=/(https?:\/\/[^\s,;:!)\]}\]]+|www\.[^\s,;:!)\]}\]]+|[a-zA-Z0-9][-a-zA-Z0-9]*(?:\.[a-zA-Z0-9][-a-zA-Z0-9]*)+(?:\/[^\s,;:!)\]}\]]*|(?:\?|#|&)[^\s,;:!)\]}\]]*)?)/gi;function ee(e){return e.split(X).map((e,t)=>{if(t%2==1){const t=e.startsWith("http")?e:`https://${e}`;return c`<a href="${t}" target="_blank" rel="noopener noreferrer" class="message-link">${e}</a>`}return e})}let te=class TextMessageBubble extends d{static{this.styles=[l`:host{display:block}.message-bubble{padding:var(--size-2_5) var(--size-4);border-radius:var(--border-radius-lg);word-wrap:break-word;font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal)}.message-bubble.received{background-color:var(--chat-received-message-background);color:var(--chat-received-message-foreground);border-bottom-left-radius:0}.message-bubble.sent{background-color:var(--chat-sent-message-background);color:var(--chat-sent-message-foreground);border-bottom-right-radius:0}.message-content{white-space:pre-wrap}.message-paragraph{margin:0 0 var(--size-3) 0}.message-paragraph:last-child{margin-bottom:0}.message-bubble.received .message-content a.message-link,.message-bubble.sent .message-content a.message-link{color:var(--color-primary-link-default);text-decoration:underline}.message-bubble.received .message-content a.message-link:hover,.message-bubble.sent .message-content a.message-link:hover{opacity:.8}`]}formatMessageContent(e){const t=e.split("\n\n").filter(e=>e.trim());if(t.length<=1)return c`<div class="message-content">${ee(e)}</div>`;const s=t.map(e=>c`<div class="message-paragraph">${ee(e.trim())}</div>`);return c`<div class="message-content">${s}</div>`}render(){return c`<div class="message-bubble ${this.kind}">${this.formatMessageContent(this.message.string)}</div>`}};e([h({type:Object})],te.prototype,"message",void 0),e([h({type:String})],te.prototype,"kind",void 0),te=e([t("text-message-bubble")],te);const se=l`:host{display:block}.message-bubble{padding:var(--size-2);border-radius:var(--border-radius-lg);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);overflow:hidden}.message-bubble.received{background-color:var(--chat-received-message-background);border-bottom-left-radius:0}.message-bubble.sent{background-color:var(--chat-sent-message-background);border-bottom-right-radius:0}.image-content{display:block;width:229px;height:229px;object-fit:cover;border-radius:var(--border-radius-md)}.image-placeholder{display:flex;align-items:center;justify-content:center;width:100%;max-width:300px;height:200px;background-color:var(--color-gray-light);border-radius:var(--border-radius-md);color:var(--chat-sent-message-foreground);font-size:var(--text-sm)}.image-content{cursor:pointer;transition:opacity .2s ease}.image-content:hover{opacity:.9}.preview-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:var(--dialog-underlay);display:flex;align-items:center;justify-content:center;z-index:1000;cursor:pointer;opacity:0;transition:opacity var(--dialog-transition-duration) ease}.preview-overlay.open{opacity:1}.preview-image{position:fixed;z-index:1000;inset:var(--mq-safe-top,0) var(--mq-safe-right,0) var(--mq-safe-bottom,0) var(--mq-safe-left,0);max-width:calc(100% - var(--mq-safe-left,4px) - var(--mq-safe-right,4px));max-height:calc(100% - var(--mq-safe-top,4px) - var(--mq-safe-bottom,4px));margin:auto;object-fit:contain;cursor:default;box-shadow:var(--dialog-shadow);transform:scale(.95);transition:transform var(--dialog-transition-duration) ease}.preview-overlay.open .preview-image{transform:scale(1)}.preview-close{z-index:1001;display:inline-flex;align-items:center;justify-content:center;height:var(--size-10);width:var(--size-10);position:absolute;top:var(--mq-safe-top,4px);right:var(--mq-safe-right,4px);background:rgba(255,255,255,.3);border:none;color:var(--color-neutrals-text-default);font-size:var(--text-xl);padding:var(--size-2) var(--size-3);border-radius:var(--border-radius-md);cursor:pointer;transition:background var(--dialog-transition-duration) ease}.preview-close:hover{background:var(--dialog-close-hover-bg)}`;let ie=class ImageMessageBubble extends d{constructor(){super(...arguments),this.showPreview=!1,this.isPreviewRendered=!1,this.isPreviewActive=!1,this.closeTimer=null}static{this.styles=se}handleImageError(e){const t=e.target;t.style.display="none";const s=t.nextElementSibling;s&&(s.style.display="flex")}handleImageLoad(e){const t=e.target.nextElementSibling;t&&(t.style.display="none")}handleImageClick(){this.showPreview=!0,this.isPreviewRendered=!0,this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.isPreviewActive=!0})})}handleImageKeyDown(e){"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.handleImageClick())}handleClosePreview(e){e&&e.stopPropagation(),this.isPreviewActive=!1,this.closeTimer&&window.clearTimeout(this.closeTimer),this.closeTimer=window.setTimeout(()=>{this.isPreviewRendered=!1,this.showPreview=!1,this.closeTimer=null},200)}handleOverlayClick(e){e.target===e.currentTarget&&this.handleClosePreview()}handleOverlayKeyDown(e){"Enter"!==e.key&&" "!==e.key||e.target===e.currentTarget&&(e.preventDefault(),this.handleClosePreview())}handleKeyDown(e){"Escape"===e.key&&this.showPreview&&(e.preventDefault(),this.handleClosePreview())}handlePreviewImageKeyDown(e){e.stopPropagation()}connectedCallback(){super.connectedCallback(),document.addEventListener("keydown",this.handleKeyDown.bind(this))}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("keydown",this.handleKeyDown.bind(this)),this.closeTimer&&(window.clearTimeout(this.closeTimer),this.closeTimer=null)}render(){const e=this.message.attachment.signed_url??this.message.attachment.url;return c`<div class="message-bubble ${this.kind}"><img class="image-content" src="${e}" width="229" height="229" alt="Shared attachment" @error="${this.handleImageError}" @load="${this.handleImageLoad}" @click="${this.handleImageClick}" @keydown="${this.handleImageKeyDown}" tabindex="0"><div class="image-placeholder" style="display:none">Image unavailable</div></div>${this.showPreview&&this.isPreviewRendered?c`<div class="preview-overlay ${this.isPreviewActive?"open":""}" @click="${this.handleOverlayClick}" @keydown="${this.handleOverlayKeyDown}" tabindex="0"><button class="preview-close" @click="${this.handleClosePreview}" aria-label="Close preview">${v({size:24})}</button> <img class="preview-image" src="${e}" alt="Shared attachment preview" @click="${e=>e.stopPropagation()}" @keydown="${this.handlePreviewImageKeyDown}" tabindex="0"></div>`:""}`}};e([h({type:Object})],ie.prototype,"message",void 0),e([h({type:String})],ie.prototype,"kind",void 0),e([i({context:Q})],ie.prototype,"token",void 0),e([p()],ie.prototype,"showPreview",void 0),e([p()],ie.prototype,"isPreviewRendered",void 0),e([p()],ie.prototype,"isPreviewActive",void 0),ie=e([t("image-message-bubble")],ie);const oe=l`:host{background-color:var(--chat-system-message-background);color:var(--chat-system-message-foreground);display:block;padding:var(--size-2_5) var(--size-4);border-radius:var(--border-radius-lg);font-family:var(--font-body);font-size:var(--text-xs);line-height:var(--text-xs--line-height);font-weight:var(--font-weight-normal)}a.message-link{color:var(--color-primary-link-default);text-decoration:underline}a.message-link:hover{opacity:.8}`;let ae=class SystemMessageBubble extends d{static{this.styles=oe}render(){return c`<div class="system-message-bubble">${ee(this.message.string)}</div>`}};e([h({type:Object})],ae.prototype,"message",void 0),ae=e([t("system-message-bubble")],ae);const re=l`:host{display:block}.message-bubble{display:inline-block;padding:var(--size-2_5) var(--size-4);border-radius:var(--border-radius-lg);word-wrap:break-word;font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-normal);text-decoration:underline;color:var(--color-primary-link-default);border:none;cursor:pointer;text-align:left}.message-bubble:hover:not(:disabled){opacity:.8}.message-bubble:disabled{opacity:.5;cursor:not-allowed}.message-bubble.received{background-color:var(--chat-received-message-background);border-bottom-left-radius:0}.message-bubble.sent{background-color:var(--chat-sent-message-background);border-bottom-right-radius:0}.message-content{white-space:pre-wrap}.message-paragraph{margin:0 0 var(--size-3) 0}.message-paragraph:last-child{margin-bottom:0}`;let ne=class FileMessageBubble extends d{constructor(){super(...arguments),this.isDownloading=!1}static{this.styles=re}formatMessageContent(e){const t=e.split("\n\n").filter(e=>e.trim());if(t.length<=1)return c`<div class="message-content">${e}</div>`;const s=t.map(e=>c`<div class="message-paragraph">${e.trim()}</div>`);return c`<div class="message-content">${s}</div>`}async handleDownload(){if(this.isDownloading)return;const e=this.message.attachment.url;try{this.isDownloading=!0;const t=await fetch(e,{headers:{Authorization:`Bearer ${this.token}`}});if(!t.ok)throw new Error(`Failed to fetch file: ${t.statusText}`);const s=await t.blob(),i=new FileReader;i.onloadend=()=>{const e=i.result,t=new I({url:e,filename:this.message.attachment.file_name});this.dispatchEvent(t),this.isDownloading=!1},i.onerror=()=>{z.error("Error reading file as data URL"),this.isDownloading=!1},i.readAsDataURL(s)}catch(e){z.error("Error downloading file:",e),this.isDownloading=!1}}render(){return c`<button type="button" @click="${this.handleDownload}" class="message-bubble ${this.kind}" ?disabled="${this.isDownloading}">${this.formatMessageContent(this.message.attachment.file_name)}</button>`}};e([h({type:Object})],ne.prototype,"message",void 0),e([h({type:String})],ne.prototype,"kind",void 0),e([i({context:Q})],ne.prototype,"token",void 0),e([p()],ne.prototype,"isDownloading",void 0),ne=e([t("file-message-bubble")],ne);let le=class MessageBubble extends d{constructor(){super(...arguments),this.showTimestamp=!0}static{this.styles=[l`:host{display:block}.timestamp{font-family:var(--font-body);font-size:var(--text-xs);color:var(--color-gray-medium);font-weight:var(--font-weight-normal);text-align:left;display:flex;align-items:center;gap:var(--size-1)}.timestamp.sent{text-align:right;justify-content:flex-end}.status-icon{width:12px;height:12px}.status-icon.read{color:var(--color-primary)}`]}formatTimestamp(e){if(!e)return"";try{const t=new Date(e);return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1,timeZone:k(this.timezone)}).format(t)}catch{return e}}renderStatusIcon(){switch(this.message.status){case T.Sent:return P({size:12,color:"currentColor"});case T.Received:return j({size:12,color:"currentColor"});case T.Read:return j({size:12,color:"currentColor",className:"read"});default:return null}}renderBubbleContent(){switch(this.message.type){case"image":return c`<image-message-bubble .message="${this.message}" .kind="${this.kind}"></image-message-bubble>`;case"file":return c`<file-message-bubble .message="${this.message}" .kind="${this.kind}"></file-message-bubble>`;default:return c`<text-message-bubble .message="${this.message}" .kind="${this.kind}"></text-message-bubble>`}}render(){if(this.message.senderType===S.system)return c`<system-message-bubble .message="${this.message}"></system-message-bubble>`;const e=this.message.createdAt?new Date(this.message.createdAt):this.message.time?new Date(this.message.time):null;return c`${this.renderBubbleContent()} ${this.showTimestamp&&e?c`<div class="timestamp ${this.kind}">${this.formatTimestamp(e.toISOString())} ${"sent"===this.kind?c`<span class="status-icon ${this.message.status===T.Read?"read":""}">${this.renderStatusIcon()}</span>`:""}</div>`:""}`}};e([h({type:String})],le.prototype,"kind",void 0),e([h({type:Object})],le.prototype,"message",void 0),e([h({type:Boolean})],le.prototype,"showTimestamp",void 0),e([h({type:String})],le.prototype,"timezone",void 0),le=e([t("message-bubble")],le);let de=class DateBanner extends d{constructor(){super(...arguments),this.date=""}static{this.styles=[u,l`:host{display:block;margin-bottom:var(--size-2)}.date-banner{display:flex;align-items:center;justify-content:center;position:relative}.date-text{background-color:var(--color-gray-light);color:var(--color-gray-darker);font-family:var(--font-body);font-size:var(--text-xs);line-height:var(--text-xs--line-height);font-weight:var(--font-weight-medium);padding:var(--size-1) var(--size-2);border-radius:var(--border-radius-2xl);white-space:nowrap}`]}formatDate(e){const t=A().replace("_","-"),s=$(new Date,k(this.timezone)),i=_((o=E(s),R(o,-1,r)),"yyyy-MM-dd");var o,r;return e===s?a("Hoy"):e===i?a("Ayer"):E(e).toLocaleDateString(t,{dateStyle:"medium"})}render(){return c`<div class="date-banner"><span class="date-text">${this.formatDate(this.date)}</span></div>`}};function ce(e){return e.createdAt?new Date(e.createdAt):e.time?new Date(e.time):new Date}e([h({type:String})],de.prototype,"date",void 0),e([h({type:String})],de.prototype,"timezone",void 0),de=e([o(),t("date-banner")],de);let me=class MessagesList extends d{constructor(){super(...arguments),this.messages=[]}static{this.styles=[u,l`:host{display:block;width:100%;height:100%;overflow-y:auto;overflow-x:hidden}.messages-container{display:flex;flex-direction:column;padding:var(--size-4);gap:var(--size-1);background-color:var(--color-white);padding-bottom:var(--size-4)}.message-wrapper{display:flex;width:100%}.message-wrapper.received{justify-content:flex-start}.message-wrapper.sent{justify-content:flex-end}.message-wrapper.system{justify-content:center}message-bubble{max-width:70%}`]}get timezone(){return k(this.loginToken?.patient?.timezone)}scrollToBottom(){requestAnimationFrame(()=>{const e=this.messagesContainerEnd;e&&e.scrollIntoView({behavior:"instant",block:"end"})})}shouldShowMessageTimestamp(e,t){if(e.senderType===S.system)return!1;if(!t)return!0;if(t.senderType!==e.senderType)return!0;if(t.senderType===S.ordinary&&e.senderType===S.ordinary&&t.fromUserHash!==e.fromUserHash)return!0;return(ce(t).getTime()-ce(e).getTime())/6e4>1}groupMessagesByDate(e){const t=[];let s=null;const i=this.timezone;return e.forEach((o,a)=>{const r=$(ce(o),i);r!==s&&(t.push({type:"date",data:r}),s=r);const n=e[a+1],l=this.shouldShowMessageTimestamp(o,n);t.push({type:"message",data:o,showTimestamp:l})}),t}firstUpdated(){this.scrollToBottom()}willUpdate(e){e.has("messages")&&this.scrollToBottom()}render(){const e=this.groupMessagesByDate(this.messages),t=e.map((t,s)=>{if("date"===t.type)return c`<date-banner .date="${t.data}" .timezone="${this.timezone}"></date-banner>`;const i=this.professionalHash!==t.data.fromUserHash,o=t.data.senderType===S.system?"system":i?"sent":"received";return c`<div class="message-wrapper ${o}"><message-bubble .message="${t.data}" .kind="${o}" .timezone="${this.timezone}" .showTimestamp="${t.showTimestamp||"date"===e[s+1]?.type}"></message-bubble></div>`});return c`<div class="messages-container">${t}<div class="messages-container-end"></div></div>`}};e([h({type:Array})],me.prototype,"messages",void 0),e([h({type:String})],me.prototype,"professionalHash",void 0),e([i({context:x,subscribe:!0})],me.prototype,"loginToken",void 0),e([C(".messages-container-end")],me.prototype,"messagesContainerEnd",void 0),me=e([t("messages-list")],me);let he=class MessageBubbleSkeleton extends d{constructor(){super(...arguments),this.variant="patient",this.height="md",this.showTimestamp=!0}static{this.styles=[l`:host{display:block}.message-bubble{padding:var(--size-4);border-radius:var(--border-radius-lg);margin-bottom:var(--size-1);position:relative;overflow:hidden}.message-bubble.doctor{background-color:var(--color-gray-light);border-bottom-left-radius:0}.message-bubble.patient{background-color:var(--color-background-primary-light);border-bottom-right-radius:0}:host([height=sm]) .message-bubble{height:var(--size-8)}:host([height=md]) .message-bubble{height:var(--size-12)}`]}render(){return c`<div class="message-bubble ${this.variant}"></div>${this.showTimestamp?c`<div class="timestamp-skeleton ${this.variant}"></div>`:""}`}};e([h({type:String})],he.prototype,"variant",void 0),e([h({type:String})],he.prototype,"height",void 0),e([h({type:Boolean})],he.prototype,"showTimestamp",void 0),he=e([t("message-bubble-skeleton")],he);let pe=class MessagesSkeleton extends d{constructor(){super(...arguments),this.messageCount=6}static{this.styles=[u,l`:host{display:block;width:100%;height:100%;overflow:hidden}.messages-container{display:flex;flex-direction:column;padding:var(--size-4);gap:var(--size-3);max-width:100%;height:100%;background-color:var(--color-white)}.message-wrapper{display:flex;width:100%}.message-wrapper.doctor{justify-content:flex-start}.message-wrapper.patient{justify-content:flex-end}message-bubble-skeleton{max-width:85%;min-width:60%;width:100%}`]}getSkeletonHeight(e){const t=["sm","md","sm","md","sm","md"];return t[e%t.length]}getSkeletonVariant(e){const t=["doctor","patient","doctor","doctor","patient","doctor","patient"];return t[e%t.length]}renderSkeletonMessages(){return Array.from({length:this.messageCount},(e,t)=>{const s=this.getSkeletonVariant(t),i=this.getSkeletonHeight(t);return c`<div class="message-wrapper ${s}"><message-bubble-skeleton variant="${s}" height="${i}" ?showTimestamp="${t===this.messageCount-1||Math.random()>.7}"></message-bubble-skeleton></div>`})}render(){return c`<div class="messages-container">${this.renderSkeletonMessages()}</div>`}};e([h({type:Number})],pe.prototype,"messageCount",void 0),pe=e([t("messages-skeleton")],pe);var ge=class{constructor(e,t){this.host=e,this.listeners=[],this.host.addController(this),this.socketContext=new N(this.host,{context:U,subscribe:!0,callback:e=>{if(e&&(this.socket=e,t?.listeners)){this.listeners=t.listeners;for(const e of this.listeners)this.socket?.on(e.eventName,e.callback)}}})}hostConnected(){}hostDisconnected(){for(const e of this.listeners)this.socket?.off(e.eventName,e.callback)}};function ue(e,t){return{queryKey:H(e,"rooms",t.roomId),queryFn:()=>e.rooms.getRoomMessages(t),staleTime:0}}class OptimisticUpdatesController{constructor(e){this.host=e,this.apiClientContext=new N(this.host,{context:n,subscribe:!0,callback:e=>{this.apiClient=e}}),this.queryClientContext=new N(this.host,{context:L,subscribe:!0,callback:e=>{e&&(this.queryClient=e)}}),this.host.addController(this)}hostConnected(){}appendMessageToRoom(e,t){if(!this.apiClient)return;const s=ue(this.apiClient,{roomId:t}).queryKey;this.queryClient?.setQueriesData({queryKey:s,exact:!0},t=>[...t??[],e])}deleteMessage(e,t){if(!this.queryClient||!this.apiClient)return;const s=ue(this.apiClient,{roomId:t}).queryKey;this.queryClient.setQueryData(s,t=>(t??[]).map(t=>t.messageId===e?{...t,deletedAt:(new Date).toISOString(),string:a("Este mensaje fue eliminado")}:t))}updateMessageStatus({messageId:e,status:t,roomId:s}){if(!this.queryClient||!this.apiClient)return;const i=ue(this.apiClient,{roomId:s}).queryKey;this.queryClient.setQueryData(i,s=>(s??[]).map(s=>s.messageId===e?{...s,status:t}:s))}}let ve=class ChatRoomMessages extends d{constructor(){super(...arguments),this.getRoomMessagesQuery=new y(this,()=>ue(this.apiClient,{roomId:this.roomId})),this.optimisticUpdatesController=new OptimisticUpdatesController(this),this.onMessageReceived=e=>{if(e.roomId!==this.roomId)return;const t=function(e){const t={roomId:"string"==typeof e.roomId?Number.parseInt(e.roomId,10):e.roomId,messageId:e.messageId,status:e.status,senderType:e.senderType,fromUserHash:e.fromUserHash,time:e.time,createdAt:e.time?new Date(e.time).toISOString():null,deletedAt:null};switch(e.type){case"string":return{...t,type:"string",string:e.string,auto:e.auto?1:0,attachment:null};case"image":return{...t,type:"image",string:e.fileName||"",auto:0,attachment:{file_name:e.fileName,file_size:e.fileSize,url:e.imageUrl,type:"uncategorized",meta:{duration:0},signed_url:e.imageUrl}};case"file":return{...t,type:"file",string:e.fileName||"",auto:0,attachment:{file_name:e.fileName,file_size:e.fileSize,url:e.fileUrl,type:"uncategorized",meta:{duration:0},signed_url:e.fileUrl}};default:return{...t,type:"string",string:"",auto:0,attachment:null}}}(e);this.optimisticUpdatesController.appendMessageToRoom(t,t.roomId),t.roomId===this.roomId&&e.fromUserHash===this.professionalHash&&this._socketController.socket?.emit(B.messageStatus,e.messageId,this.roomId,T.Read)},this.onMessageDeleted=e=>{e.room_id===this.roomId&&this.optimisticUpdatesController.deleteMessage(e.message_id,e.room_id)},this.onMessageStatusUpdated=e=>{e.roomId===this.roomId&&this.optimisticUpdatesController.updateMessageStatus({messageId:e.messageId,status:e.status,roomId:e.roomId})},this._socketController=new ge(this,{listeners:[{eventName:B.message,callback:this.onMessageReceived},{eventName:B.message_deleted,callback:this.onMessageDeleted},{eventName:B.messageStatus,callback:this.onMessageStatusUpdated}]})}static{this.styles=[u,l`:host{display:block;width:100%;height:100%}`]}render(){return this.getRoomMessagesQuery.render({pending:()=>c`<messages-skeleton messageCount="8"></messages-skeleton>`,complete:e=>c`<messages-list .messages="${e}" .professionalHash="${this.professionalHash}"></messages-list>`})}};e([i({context:n,subscribe:!0})],ve.prototype,"apiClient",void 0),e([h({type:Number})],ve.prototype,"roomId",void 0),e([h({type:String})],ve.prototype,"professionalHash",void 0),ve=e([t("chat-room-messages")],ve);var ye=class{constructor(e){this.string=e.string,this.roomId=e.roomId,this.messageId=e.messageId,this.type=e.type,this.fileName=e.fileName,this.autoMessage=e.autoMessage,this.senderType=e.senderType,this.attachmentType=e.attachmentType,this.consultationId=e.consultationId,this.consultationType=e.consultationType}toSocketMessage(){return[B.message,this.string,this.roomId,this.messageId,this.type,this.fileName,this.autoMessage,this.senderType,this.attachmentType,this.consultationId,this.consultationType]}},be=class extends ye{constructor(e){super({roomId:e.roomId,messageId:e.messageId,string:e.string,type:"string",fileName:null,autoMessage:!1,senderType:S.ordinary,attachmentType:"uncategorized",consultationId:e.consultationId,consultationType:e.consultationType})}},fe=class extends ye{constructor(e){super({roomId:e.roomId,messageId:e.messageId,string:e.base64Attachment,fileName:e.fileName,type:e.type,autoMessage:!1,senderType:S.ordinary,attachmentType:"uncategorized",consultationId:e.consultationId,consultationType:e.consultationType})}};async function we(e){return await Promise.all(e.map(async e=>{const t=await function(e){return new Promise((t,s)=>{const i=new FileReader;i.onload=()=>{const o=i.result.split(",")[1];o?t(o):s(new Error(`Invalid data URL format for file: ${e.name}`))},i.onerror=()=>{s(new Error(`Failed to read file: ${e.name}`))},i.readAsDataURL(e)})}(e);return{name:e.name,size:e.size,type:e.type,base64:t}}))}const xe=l`:host{display:block;position:absolute;bottom:0;padding:var(--size-2) var(--size-2);background:#fff}.footer-container{display:flex;align-items:center;gap:var(--size-1);max-width:100%}.input-container{flex:1;position:relative;display:flex;align-items:center;border:1px solid var(--color-neutrals-border-disabled);border-radius:var(--border-radius-2xl);padding:0 var(--size-1);overflow:hidden}.input-container:focus-within{border-color:var(--color-primary)}.message-input{flex:1;border:none;outline:0;background:0 0;font-family:var(--font-body);font-size:var(--text-base);font-size:var(--text-sm);line-height:var(--text-sm--line-height);color:var(--color-neutrals-text-default);padding-left:var(--sp-2)}.message-input::placeholder{color:var(--color-neutrals-text-medium)}.attachment-icon{width:var(--size-5);height:var(--size-5);color:var(--color-primary)}.send-icon{width:var(--size-5);height:var(--size-5);color:var(--color-primary)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.send-button{color:var(--color-neutrals-link-disabled);background:0 0;border:none;padding:var(--size-2);border-radius:var(--border-radius-md);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background-color .2s ease}.send-button:hover:not(.disabled){background:var(--color-primary-light)}.send-button:active:not(.disabled){background-color:var(--color-neutrals-background-active)}.send-button.disabled{cursor:not-allowed;opacity:.4}.send-button.disabled .send-icon{color:var(--color-neutrals-text-disabled)}`;let ke=class ChatRoomFooter extends d{constructor(){super(...arguments),this.isTyping=!1,this.typingTimeoutId=null,this.inputValue="",this.socketController=new ge(this)}static{this.styles=[xe]}handleInputChange(e){const t=e.target;this.inputValue=t.value,this.isTyping||(this.socketController.socket?.emit(B.typing,this.roomId),this.isTyping=!0),this.typingTimeoutId&&clearTimeout(this.typingTimeoutId),this.typingTimeoutId=setTimeout(()=>{this.isTyping&&(this.socketController.socket?.emit(B.stop_typing,this.roomId),this.isTyping=!1)},1500)}handleKeyDown(e){"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.handleSendMessage())}async handleAttachment(e){const t=e.target.files;if(!t||0===t.length)return;const s=t.item(0);if(s)try{const e=(await we([s]))[0];if(!e)return void z.error("Error converting file to base64");const t=e?.type.includes("image")?"image":"file",i=crypto.randomUUID(),o=s.name,a=new fe({type:t,base64Attachment:e.base64,fileName:o,roomId:this.roomId,messageId:i,consultationId:this.consultationId,consultationType:this.consultationType});this.socketController.socket?.emit(...a.toSocketMessage())}catch(e){z.error("Error converting files to base64:",e)}}handleAttachmentClick(){this.attachmentInput.click()}handleSendMessage(){const e=this.inputValue.trim();if(!e)return;const t=crypto.randomUUID();this.isTyping&&(this.socketController.socket?.emit(B.stop_typing,this.roomId),this.isTyping=!1,this.typingTimeoutId&&clearTimeout(this.typingTimeoutId));const s=new be({messageId:t,string:e,roomId:this.roomId,consultationId:this.consultationId,consultationType:this.consultationType});this.socketController.socket?.emit(...s.toSocketMessage()),this.inputValue=""}disconnectedCallback(){this.isTyping&&(this.socketController.socket?.emit(B.stop_typing,this.roomId),this.typingTimeoutId&&clearTimeout(this.typingTimeoutId))}render(){const e=this.inputValue.trim().length>0;return c`<div class="footer-container"><div class="input-container"><input class="message-input" type="text" placeholder="${a("Escribe aquí...")}" .value="${this.inputValue}" @input="${this.handleInputChange}" @keydown="${this.handleKeyDown}"><div><input class="attachment-input sr-only" type="file" accept="image/jpeg,image/jpg,image/png,image/gif,image/bmp,image/tiff,application/pdf,text/*,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,audio/*,video/*" @change="${this.handleAttachment}"><mq-button variant="ghost" size="icon-sm" @click="${this.handleAttachmentClick}" title="${a("Adjuntar archivo")}">${c`<svg class="attachment-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>`}</mq-button></div></div><button class="send-button ${e?"":"disabled"}" @click="${this.handleSendMessage}" ?disabled="${!e}" title="${a("Enviar mensaje")}">${c`<svg class="send-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 2L11 13"/><path d="M22 2L15 22L11 13L2 9L22 2z"/></svg>`}</button></div>`}};e([i({context:Z})],ke.prototype,"consultationId",void 0),e([i({context:J})],ke.prototype,"consultationType",void 0),e([h({type:Number})],ke.prototype,"roomId",void 0),e([p()],ke.prototype,"inputValue",void 0),e([C(".attachment-input")],ke.prototype,"attachmentInput",void 0),ke=e([t("chat-room-footer")],ke);const $e=e=>({all_week:!0,monday:1===e,tuesday:2===e,wednesday:3===e,thursday:4===e,friday:5===e,saturday:6===e,sunday:7===e,working_week:e>=1&&e<=5,weekend:0===e||6===e});function Ce(e,t){const s=$e(6===e?0:e+1);return t.some(e=>{const t=e.days_of_week;return!0===s[t]})}let ze=class AvailabilitySection extends d{constructor(){super(...arguments),this.gaps=[],this.selectedDay=function(){const e=(new Date).getDay();return 0===e?6:e-1}()}static{this.styles=l`:host{display:flex;flex-direction:column;gap:var(--size-3)}.availability-header{font-family:var(--font-body);font-size:var(--text-lg);line-height:var(--text-lg--line-height);font-weight:var(--font-weight-normal);color:var(--color-primary);text-align:center;margin:0;margin-bottom:var(--size-4) 0}.availability-days{display:flex;flex-direction:row;justify-content:center;gap:var(--size-1);overflow-x:auto;padding-bottom:var(--size-4)}.availability-button{outline:0;border:1px solid var(--color-gray-medium);background:0 0;color:var(--color-gray-medium);cursor:pointer;height:var(--size-9);width:var(--size-10);border-radius:var(--border-radius-sm);text-transform:capitalize;font-size:var(--text-xs);line-height:var(--text-xs--line-height);font-weight:var(--font-weight-medium)}.availability-button:hover{background-color:color-mix(in srgb,var(--color-gray-light) 50%,transparent)}.availability-button:focus{background-color:color-mix(in srgb,var(--color-gray-light) 50%,transparent)}.availability-button.active{background:var(--color-primary);color:var(--color-white);border:none}.availability-button:disabled{opacity:.5;cursor:not-allowed;background-color:var(--color-gray-light)}.time-title{font-family:var(--font-body);font-size:var(--text-xs);line-height:var(--text-xs--line-height);font-weight:var(--font-weight-medium);color:var(--color-gray-dark);margin:0;margin-bottom:var(--size-1)}.time-entries{display:flex;flex-direction:column;gap:var(--size-1);margin-bottom:var(--size-6)}.time-entry{font-family:var(--font-body);font-size:var(--text-xs);line-height:var(--text-xs--line-height);font-weight:var(--font-weight-normal);color:var(--color-gray-medium);margin:0}`}updated(e){e.has("gaps")&&(void 0===this.selectedDay||Ce(this.selectedDay,this.gaps)||(this.selectedDay=void 0))}render(){const e=[{shortLabel:a("Lu"),label:a("Lunes"),key:"monday",disabled:!Ce(0,this.gaps)},{shortLabel:a("Ma"),label:a("Martes"),key:"tuesday",disabled:!Ce(1,this.gaps)},{shortLabel:a("Mi"),label:a("Miércoles"),key:"wednesday",disabled:!Ce(2,this.gaps)},{shortLabel:a("Ju"),label:a("Jueves"),key:"thursday",disabled:!Ce(3,this.gaps)},{shortLabel:a("Vi"),label:a("Viernes"),key:"friday",disabled:!Ce(4,this.gaps)},{shortLabel:a("Sa"),label:a("Sábado"),key:"saturday",disabled:!Ce(5,this.gaps)},{shortLabel:a("Do"),label:a("Domingo"),key:"sunday",disabled:!Ce(6,this.gaps)}];return c`<h2 class="availability-header">${a("Disponibilidad")}</h2><div class="availability-days">${e.map((e,t)=>c`<button type="button" class="availability-button ${K({active:this.selectedDay===t&&!e.disabled})}" ?disabled="${e.disabled}" @click="${()=>{e.disabled||(this.selectedDay=t)}}">${e.shortLabel}</button>`)}</div>${void 0===this.selectedDay||e[this.selectedDay]?.disabled?"":(()=>{const t=function(e,t){const s=$e(6===e?0:e+1);return t.filter(e=>{const t=e.days_of_week;return!0===s[t]}).map(e=>({from_time:e.from_time,to_time:e.to_time}))}(this.selectedDay,this.gaps);return c`<div class="availability-time"><p class="time-title">${e[this.selectedDay]?.label}</p><div class="time-entries">${t.length>0?t.map(e=>c`<p class="time-entry">${a("De")} ${e.from_time} ${a("a")} ${e.to_time}</p>`):c`<p class="time-entry">${a("No hay horarios disponibles")}</p>`}</div></div>`})()}`}};e([h({type:Array})],ze.prototype,"gaps",void 0),e([p()],ze.prototype,"selectedDay",void 0),ze=e([o(),t("availability-section")],ze);const Ie=l`:host{display:flex;flex-direction:column;height:100%;overflow-y:auto;background-color:var(--color-white)}.profile-container{padding:var(--size-6);display:flex;flex-direction:column}.profile-header{display:flex;flex-direction:column;align-items:center;text-align:center;padding-bottom:var(--size-6);border-bottom:1px solid var(--color-gray-medium);margin-bottom:var(--size-6)}.profile-avatar{margin-bottom:var(--size-2)}.profile-name{font-family:var(--font-body);font-size:var(--text-lg);line-height:var(--text-lg--line-height);font-weight:var(--font-weight-medium);color:var(--color-text-primary);margin:var(--size-4) 0}.profile-specialty{font-family:var(--font-body);font-size:var(--text-xs);line-height:var(--text-xs--line-height);font-weight:var(--font-weight-medium);color:var(--color-text-icons--secondary);margin:0;margin-bottom:var(--size-2);text-transform:uppercase}.profile-collegiate{font-family:var(--font-body);font-size:var(--text-xs);line-height:var(--text-xs--line-height);color:var(--color-gray-medium);text-transform:uppercase;margin:0}.description-header{font-family:var(--font-body);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-weight:var(--font-weight-medium);color:var(--color-primary);margin:0;margin-bottom:var(--size-3)}.description-text{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-foreground);margin:0}`;let Te=class ChatRoomProfile extends d{constructor(){super(...arguments),this.getProfessionalQuery=new y(this,()=>b(this.apiClient,{hash:this.professionalHash}))}static{this.styles=[u,Ie]}renderProfile(e){return c`<div class="profile-container"><div class="profile-header"><mq-avatar class="profile-avatar" src="${e.avatar||""}" fallback="${e.name}" alt="${e.name}'s profile picture" size="xl"></mq-avatar><div><h1 class="profile-name">${e.name}</h1>${e.title?c`<p class="profile-specialty">${e.title}</p>`:""} ${e.collegiate_number?c`<p class="profile-collegiate">${a(r`Nº COL. ${e.collegiate_number}`)}</p>`:""}</div></div>${e.chat_schedule&&e.chat_schedule.gaps.length>0?c`<availability-section .gaps="${e.chat_schedule.gaps}"></availability-section>`:m} ${e.description||e.overview?c`<div><h2 class="description-header">${a("Descripción")}</h2><p class="description-text"><professional-description .text="${e.description||e.overview||""}"></professional-description></p></div>`:""}</div>`}render(){return this.getProfessionalQuery.render({pending:()=>c``,complete:e=>this.renderProfile(e)})}};e([i({context:n,subscribe:!0})],Te.prototype,"apiClient",void 0),e([h({type:String})],Te.prototype,"professionalHash",void 0),Te=e([o(),t("chat-room-profile")],Te);const Me=l`.root{display:flex;flex-direction:column;height:100%;overflow:hidden}chat-room-header{flex-shrink:0}chat-room-messages{flex:1;overflow-y:auto;overflow-x:hidden}chat-room-footer{position:sticky;bottom:0;left:0;right:0;flex-shrink:0}`;let De=class MqChatRoom extends d{constructor(){super(...arguments),this.consultationId=void 0,this.consultationType=void 0,this.readonly=!1,this.hideCloseButton=!1,this.view="chat",this.socketController=new ge(this),this.readAllMessagesMutation=new O(this,{mutationFn:()=>this.apiClient.professionals.readAllMessages({roomId:this.roomId}),onSuccess:()=>{this.queryClientContext?.invalidateQueries({queryKey:q(this.apiClient,{roomId:this.roomId}).queryKey})}}),this.apiClient=M()}static{this.styles=[u,Me]}willUpdate(e){const t=D(e,{apiKey:this.apiKey,token:this.token},this.inheritedApiClient);t&&(this.apiClient=t),e.has("roomId")&&(this.socketController.socket?.emit(B.joinRoom,this.roomId),this.readAllMessagesMutation.run(void 0))}render(){return c`<div class="root"><chat-room-header .professionalHash="${this.professionalHash}" .view="${this.view}" .hideCloseButton="${this.hideCloseButton}" @mq-chat-room-profile="${()=>{this.view="profile"}}" @goto-chat="${()=>{this.view="chat"}}"></chat-room-header>${"chat"===this.view?c`<chat-room-messages .roomId="${this.roomId}" .professionalHash="${this.professionalHash}"></chat-room-messages>${this.readonly?m:c`<chat-room-footer .roomId="${this.roomId}"></chat-room-footer>`}`:c`<chat-room-profile .professionalHash="${this.professionalHash}" @mq-chat-room-chat="${()=>{this.view="chat"}}"></chat-room-profile>`}</div>`}};e([s({context:F}),h({type:String,attribute:"api-key"})],De.prototype,"apiKey",void 0),e([s({context:Q}),h({type:String,attribute:"token"})],De.prototype,"token",void 0),e([s({context:V}),h({type:String,attribute:"professional-hash"})],De.prototype,"professionalHash",void 0),e([s({context:G}),h({type:Number,attribute:"room-id"})],De.prototype,"roomId",void 0),e([s({context:Z}),h({type:String,attribute:"consultation-id"})],De.prototype,"consultationId",void 0),e([s({context:J}),h({type:String,attribute:"consultation-type"})],De.prototype,"consultationType",void 0),e([h({type:Boolean,reflect:!0})],De.prototype,"readonly",void 0),e([h({type:Boolean,attribute:"hide-close-button"})],De.prototype,"hideCloseButton",void 0),e([p()],De.prototype,"view",void 0),e([i({context:L,subscribe:!0})],De.prototype,"queryClientContext",void 0),e([i({context:n,subscribe:!0}),p()],De.prototype,"inheritedApiClient",void 0),e([s({context:n}),p()],De.prototype,"apiClient",void 0),De=e([o(),t("mq-chat-room")],De);export{De as M,MqChatRoomCloseEvent as a,MqChatRoomProfileEvent as b};
@@ -1,11 +1,11 @@
1
1
  import * as lit_html from 'lit-html';
2
2
  import * as lit from 'lit';
3
3
  import { LitElement, PropertyValues } from 'lit';
4
- import { M as MediquoApiChatClient, a as Message, I as ImageMessage, F as FileMessage } from './index.d-ByhRBSb1.js';
4
+ import { M as MediquoApiChatClient, a as Message, I as ImageMessage, F as FileMessage } from './index.d-DHMNq1lu.js';
5
5
  import '../ui/mq-avatar.js';
6
6
  import '../ui/mq-button.js';
7
7
  import '../ui/mq-skeleton.js';
8
- import { C as ConsultationType } from './appointment.model.d-BWwBLaEL.js';
8
+ import { C as ConsultationType } from './index-DwlJg2um.js';
9
9
  import { z } from 'zod';
10
10
  import { QueryClient } from '@tanstack/query-core';
11
11
 
@@ -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 o}from"./consume-CovVqBjI.js";import{m as n}from"./runtime-Bg1WXVCx.js";import{l as r}from"./localized-decorator-BlOuLhym.js";import{Q as s}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{A as l,c as m,n as c}from"./api-chat-client-s45J7LKB.js";import"./chunk-NIAGR3ZC-BDlNUZa1.js";import{g as d}from"./next-appointment-card-DLU7-wIv.js";import{g as h}from"./get-patient-profile-query-D9btgcxl.js";import{i as u,a as g,x as y}from"./lit-element-DiWJYFwC.js";import{n as f}from"./property-scuRaFcM.js";import{r as x}from"./state-LQivXIgA.js";import{setEnv as v}from"../env.js";import{MqViewAppointmentsEvent as b}from"../events.js";import{isValidLocale as j,setLocale as k}from"../i18n.js";import"./index-D3_2tkC3.js";import"./index-MfyXh-qX.js";import"../ui/mq-skeleton.js";const A=[l.pending,l.accepted],w=u`:host{display:flex;flex-direction:column;gap:var(--sp-4);width:100%;min-width:0;box-sizing:border-box}:host([empty]){align-self:start}:host([empty]) .card{flex:0 0 auto}.card{display:flex;flex-direction:column;flex:1;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-next-appointments-radius,12px);padding:var(--mq-next-appointments-padding,var(--sp-6))}`;let $=class MqNextAppointments extends g{constructor(){super(...arguments),this.apiClient=m(),this.getPatientProfileQuery=new s(this,()=>h(this.apiClient,{enabled:!this.loginToken})),this.getAppointmentsQuery=new s(this,()=>d(this.apiClient,{status:A,order:{field:"starts_at",direction:"asc"},page:1,per_page:1})),this.handleViewAll=()=>{this.dispatchEvent(new b({tab:"next"}))}}static{this.styles=w}willUpdate(t){t.has("env")&&this.env&&v(this.env),t.has("locale")&&this.locale&&j(this.locale)&&k(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??""}get accessToken(){return this.token||this.loginToken?.access_token||""}get patientTimezone(){return this.timezone??this.loginToken?.patient.timezone}get isEmpty(){const t=this.getAppointmentsQuery.result;return!0===t?.isSuccess&&!t.data?.data?.[0]}updated(){this.toggleAttribute("empty",this.isEmpty)}renderAppointment(){return this.getAppointmentsQuery.render({complete:t=>{const e=t.data?.[0];return e?y`<next-appointment-card .appointmentResource="${e}" .token="${this.accessToken}" .patientHash="${this.patientHash}" .timezone="${this.patientTimezone}"></next-appointment-card>`:y`<widget-empty-state icon="calendar" heading="${n("No tienes próximas citas")}" description="${n("Cuando agendes una cita, aparecerá aquí para que puedas consultarla, modificarla o cancelarla.")}"></widget-empty-state>`},pending:()=>y`<mq-skeleton height="257px"></mq-skeleton>`,error:()=>y`<widget-empty-state icon="calendar" heading="${n("No hemos podido cargar tu próxima cita")}" description="${n("Vuelve a intentarlo en unos minutos.")}"></widget-empty-state>`})}render(){return y`<section-header heading="${n("Próxima cita")}" action-label="${n("Ver todas")}" @section-action="${this.handleViewAll}"></section-header><div class="card">${this.renderAppointment()}</div>`}};t([f({type:String,attribute:"api-key"})],$.prototype,"apiKey",void 0),t([f({type:String,attribute:"token"})],$.prototype,"token",void 0),t([f({type:String,attribute:"locale"})],$.prototype,"locale",void 0),t([f({type:String,attribute:"env"})],$.prototype,"env",void 0),t([f({type:String,attribute:"timezone"})],$.prototype,"timezone",void 0),t([o({context:p,subscribe:!0})],$.prototype,"loginToken",void 0),t([o({context:a,subscribe:!0}),x()],$.prototype,"inheritedApiClient",void 0),t([i({context:a}),x()],$.prototype,"apiClient",void 0),$=t([r(),e("mq-next-appointments")],$);export{$ 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 o}from"./consume-CovVqBjI.js";import{m as n}from"./runtime-Bg1WXVCx.js";import{l as r}from"./localized-decorator-BlOuLhym.js";import{Q as s}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{A as l,c as m,n as c}from"./api-chat-client-Dx-sFrf2.js";import"./chunk-NIAGR3ZC-BDlNUZa1.js";import{g as d}from"./next-appointment-card-BE0KW2vv.js";import{g as h}from"./get-patient-profile-query-D9btgcxl.js";import{i as u,a as g,x as y}from"./lit-element-DiWJYFwC.js";import{n as f}from"./property-scuRaFcM.js";import{r as x}from"./state-LQivXIgA.js";import{setEnv as v}from"../env.js";import{MqViewAppointmentsEvent as b}from"../events.js";import{isValidLocale as j,setLocale as k}from"../i18n.js";import"./index-D3_2tkC3.js";import"./index-MfyXh-qX.js";import"../ui/mq-skeleton.js";const A=[l.pending,l.accepted],w=u`:host{display:flex;flex-direction:column;gap:var(--sp-4);width:100%;min-width:0;box-sizing:border-box}:host([empty]){align-self:start}:host([empty]) .card{flex:0 0 auto}.card{display:flex;flex-direction:column;flex:1;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-next-appointments-radius,12px);padding:var(--mq-next-appointments-padding,var(--sp-6))}`;let $=class MqNextAppointments extends g{constructor(){super(...arguments),this.apiClient=m(),this.getPatientProfileQuery=new s(this,()=>h(this.apiClient,{enabled:!this.loginToken})),this.getAppointmentsQuery=new s(this,()=>d(this.apiClient,{status:A,order:{field:"starts_at",direction:"asc"},page:1,per_page:1})),this.handleViewAll=()=>{this.dispatchEvent(new b({tab:"next"}))}}static{this.styles=w}willUpdate(t){t.has("env")&&this.env&&v(this.env),t.has("locale")&&this.locale&&j(this.locale)&&k(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??""}get accessToken(){return this.token||this.loginToken?.access_token||""}get patientTimezone(){return this.timezone??this.loginToken?.patient.timezone}get isEmpty(){const t=this.getAppointmentsQuery.result;return!0===t?.isSuccess&&!t.data?.data?.[0]}updated(){this.toggleAttribute("empty",this.isEmpty)}renderAppointment(){return this.getAppointmentsQuery.render({complete:t=>{const e=t.data?.[0];return e?y`<next-appointment-card .appointmentResource="${e}" .token="${this.accessToken}" .patientHash="${this.patientHash}" .timezone="${this.patientTimezone}"></next-appointment-card>`:y`<widget-empty-state icon="calendar" heading="${n("No tienes próximas citas")}" description="${n("Cuando agendes una cita, aparecerá aquí para que puedas consultarla, modificarla o cancelarla.")}"></widget-empty-state>`},pending:()=>y`<mq-skeleton height="257px"></mq-skeleton>`,error:()=>y`<widget-empty-state icon="calendar" heading="${n("No hemos podido cargar tu próxima cita")}" description="${n("Vuelve a intentarlo en unos minutos.")}"></widget-empty-state>`})}render(){return y`<section-header heading="${n("Próxima cita")}" action-label="${n("Ver todas")}" @section-action="${this.handleViewAll}"></section-header><div class="card">${this.renderAppointment()}</div>`}};t([f({type:String,attribute:"api-key"})],$.prototype,"apiKey",void 0),t([f({type:String,attribute:"token"})],$.prototype,"token",void 0),t([f({type:String,attribute:"locale"})],$.prototype,"locale",void 0),t([f({type:String,attribute:"env"})],$.prototype,"env",void 0),t([f({type:String,attribute:"timezone"})],$.prototype,"timezone",void 0),t([o({context:p,subscribe:!0})],$.prototype,"loginToken",void 0),t([o({context:a,subscribe:!0}),x()],$.prototype,"inheritedApiClient",void 0),t([i({context:a}),x()],$.prototype,"apiClient",void 0),$=t([r(),e("mq-next-appointments")],$);export{$ as M};
@@ -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-K37KMdy_.js";import{g as m,t as h}from"./index-CCWMMqiq.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-s45J7LKB.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};
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-DA2_SZBC.js";import{g as m,t as h}from"./index-Dw4Aeoyg.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-Dx-sFrf2.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 r}from"./get-appointment-query-DuHrjd8L.js";import{g as o}from"./get-organization-setup-query-De7eM6V3.js";import{S as n,z as l,g as d,a as c,A as h,t as p,B as u,C as m,D as v,E as f,F as g,G as y,H as b}from"./telemetry-client-DA2_SZBC.js";import{g as w}from"./get-patient-profile-query-D9btgcxl.js";import{s as S}from"./chunk-6CCJWPGL-TiaqZaPV.js";import{D as x}from"./chunk-5EJXDIGT-Bb4_pfDr.js";import{g as $}from"./get-schedule-services-query-Io2aQ_7G.js";import{b as _,g as C,a as k,c as M,d as E,e as I,f as A,r as F}from"./chunk-NIAGR3ZC-BDlNUZa1.js";import{c as D}from"./refund-cancel-policy-DoMzcLlL.js";import{MqBackEvent as q}from"../events.js";import{e as V,i as P,h as z,S as j,c as L,n as B,j as T,k as O}from"./api-chat-client-Dx-sFrf2.js";import"../ui/mq-button.js";import{i as N,e as Q}from"./provide-BwI4DDGF.js";import{c as R}from"./consume-CovVqBjI.js";import{m as U,s as W}from"./runtime-Bg1WXVCx.js";import{l as H}from"./localized-decorator-BlOuLhym.js";import{E as K,i as G,a as Z,x as J}from"./lit-element-DiWJYFwC.js";import{n as X}from"./property-scuRaFcM.js";import{r as Y}from"./state-LQivXIgA.js";import{e as ee,i as te,t as ie}from"./directive-2EDmOukv.js";import{m as se,f as ae}from"./index-C76yAope.js";import{setEnv as re}from"../env.js";import{getLocale as oe,initLocalization as ne,isValidLocale as le,setLocale as de}from"../i18n.js";import{n as ce}from"./create-context-DqP79qjF.js";import{M as he}from"./mutation-controller-CR2qcqhH.js";import{e as pe}from"./class-map-Co76I6aw.js";import{o as ue}from"./if-defined-BYeVdwgd.js";import{z as me}from"./external-cM_kgYO_.js";import"../ui/mq-input.js";import"../ui/mq-callout.js";import"../ui/mq-page-title.js";import"./professional-overview-Ck_SPivX.js";import"./appointment-details-BM8peAHH.js";import"../ui/mq-card.js";import{spinnerIcon as ve}from"../ui/icons/spinner-icon.js";import{tagIcon as fe}from"../ui/icons/tag-icon.js";import{h as ge,f as ye,c as be}from"./price-DU3YLTpk.js";import{toast as we}from"../ui/mq-toast.js";import{e as Se}from"./query-CeeutdfT.js";import{fileIcon as xe}from"../ui/icons/file-icon.js";import{uploadIcon as $e}from"../ui/icons/upload-icon.js";import{xIcon as _e}from"../ui/icons/x-icon.js";import"../ui/mq-textarea.js";import{l as Ce}from"./chunk-FUCSYDW7-Duj5hy8S.js";import{Q as ke}from"./chunk-RCFIJTXZ-C6Ir0-sM.js";import{i as Me,S as Ee,p as Ie,b as Ae}from"./checkout-bridge-BFpVxNww.js";import"../ui/mq-skeleton.js";import"../ui/mq-select.js";import"../ui/mq-badge.js";import{t as Fe,i as De,p as qe,f as Ve}from"./parseISO-CEksKisk.js";import{i as Pe,s as ze,e as je}from"./index-VQqG1eyA.js";import{calendarIcon as Le}from"../ui/icons/calendar-icon.js";import{skipToken as Be}from"@tanstack/query-core";import"../ui/mq-time-slot-picker.js";import{breakpoints as Te}from"../theme.js";import{a as Oe}from"./addDays-CdyO-PRI.js";function Ne(e,t){const i=+Fe(e)-+Fe(t);return i<0?-1:i>0?1:i}var Qe=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 Re=ee(class extends te{constructor(){super(...arguments),this.key=K}render(e,t){return this.key=e,t}update(e,[t,i]){return t!==this.key&&(se(e),this.key=t),i}}),Ue=ce(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 He(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 Ke(e){const t=We(e.defaultSpecialty,e.specialties),i=He(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,booking:void 0,appliedDiscount:void 0,profileComplete:e.profileComplete,requiresPayment:e.requiresPayment,error:!1}}const Ge=["status","session_id","reference","reason"];function Ze(e){const t=new URL(e);for(const e of Ge)t.searchParams.delete(e);return t.toString()}const Je={name:"completeProfile",skipIf:e=>e.profileComplete},Xe={name:"payment",skipIf:e=>!e.requiresPayment},Ye=[{name:"selectProfessional"},{name:"selectSlot"},Je,{name:"confirm"},Xe,{name:"done"}],et=[{name:"selectSlot"},Je,{name:"confirm"},Xe,{name:"done"}],tt=[{name:"selectSlot"},Je,{name:"confirm"},{name:"done"}];function it(e,t){t.stopPropagation(),e.dispatchEvent(new CustomEvent("back"))}const st=new WeakMap,at=new WeakMap,rt={current:[]};let ot=!1,nt=0;const lt=new Set,dt=new Map;function ct(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(rt.current.includes(e))continue;rt.current.push(e),e.recompute();const t=at.get(e);if(t)for(const e of t){const t=st.get(e);t&&ct(t)}}}function ht(e){const t={prevVal:e.prevState,currentVal:e.state};for(const i of e.listeners)i(t)}function pt(e){const t={prevVal:e.prevState,currentVal:e.state};for(const i of e.listeners)i(t)}function ut(e){if(nt>0&&!dt.has(e)&&dt.set(e,e.prevState),lt.add(e),!(nt>0||ot))try{for(ot=!0;lt.size>0;){const e=Array.from(lt);lt.clear();for(const t of e){const e=dt.get(t)??t.prevState;t.prevState=e,ht(t)}for(const t of e){const e=st.get(t);e&&(rt.current.push(t),ct(e))}for(const t of e){const e=st.get(t);if(e)for(const t of e)pt(t)}}}finally{ot=!1,rt.current=[],dt.clear()}}function mt(e){nt++;try{e()}finally{if(nt--,0===nt){const e=lt.values().next().value;e&&ut(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),ut(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=st.get(t);e||(e=new Set,st.set(t,e)),e.add(this);let i=at.get(this);i||(i=new Set,at.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=st.get(t);e&&e.delete(this);const i=at.get(this);i&&i.delete(t)}}}function vt(e,t){return"function"==typeof e?e(t):e}function ft(e,t){return Ct(t).reduce((e,t)=>null===e?null:void 0!==e?e[t]:void 0,e)}function gt(e,t,i){const s=Ct(t);return function e(t){if(!s.length)return vt(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 yt=/^(\d+)$/gm,bt=/\.(\d+)(?=\.)/gm,wt=/^(\d+)\./gm,St=/\.(\d+$)/gm,xt=/\.{2,}/gm,$t="__int__",_t=`${$t}$1`;function Ct(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(yt,_t).replace(bt,`.${_t}.`).replace(wt,`${_t}.`).replace(St,`.${_t}`).replace(xt,".").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 kt(e){return!(Array.isArray(e)&&0===e.length)}function Mt(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 Et(e,t){const{asyncDebounceMs:i}=t,{onBlurAsyncDebounceMs:s,onChangeAsyncDebounceMs:a,onDynamicAsyncDebounceMs:r}=t.validators||{},o=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=o;switch(i){case"change":n=a??o;break;case"blur":n=s??o;break;case"dynamic":n=r??o;break;case"submit":n=0}return"submit"===e&&(n=0),{cause:i,validate:t.fn,debounceMs:n}})})}const It=e=>!!e&&"object"==typeof e&&"fields"in e;function At(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)||!At(e[a],t[a]))return!1;return!0}const Ft=({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},Dt=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:"field"}:e?{newErrorValue:e,newSource:"form"}:{newErrorValue:void 0,newSource:void 0};function qt(e,t){return null==e?t:{...e,...t}}let Vt=256;const Pt=[];let zt;for(;Vt--;)Pt[Vt]=(Vt+256).toString(16).substring(1);const jt=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"},r={fn:t?e.validators.onSubmitAsync:e.validators.onSubmit,cause:"submit"},o=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,r,o],form:e.form});case"server":return e.runValidation({validators:[],form:e.form});case"blur":return e.runValidation({validators:[a,o],form:e.form});case"change":return e.runValidation({validators:[s,o],form:e.form});default:throw new Error(`Unknown validation event type: ${e.event.type}`)}};const Lt=(e,t)=>{const i=function(e,t){const i=new Map;for(const s of e){const e=s.path??[];let a=t,r="";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,o=Number(s);Array.isArray(a)&&!Number.isNaN(o)?r+=`[${o}]`:r+=(t>0?".":"")+String(s),a="object"==typeof a&&null!==a?a[s]:void 0}i.set(r,(i.get(r)??[]).concat(s))}return Object.fromEntries(i)}(e,t);return{form:i,fields:i}},Bt={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:Lt(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:Lt(s.issues,e)}},Tt=e=>!!e&&"~standard"in e,Ot={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{}};function Nt(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),r=e.getFieldMeta(a);r?e.setFieldMeta(t,r):e.setFieldMeta(t,s())})}const s=()=>Ot,a=(a,r,o)=>{i(a,"down"),a.forEach(i=>{i.toString().startsWith(t(r,o))&&e.setFieldMeta(i,s())})},r=e=>{i(e,"up")},o=(s,a,r,o)=>{const n=new Map(Object.keys(e.fieldInfo).filter(e=>e.startsWith(t(a,r))).map(t=>[t,e.getFieldMeta(t)]));i(s,r<o?"up":"down"),Object.keys(e.fieldInfo).filter(e=>e.startsWith(t(a,o))).forEach(i=>{const s=i.replace(t(a,o),t(a,r)),l=n.get(s);l&&e.setFieldMeta(i,l)})},n=(i,s,a,r)=>{i.forEach(i=>{if(!i.toString().startsWith(t(s,a)))return;const o=i.toString().replace(t(s,a),t(s,r)),[n,l]=[e.getFieldMeta(i),e.getFieldMeta(o)];n&&e.setFieldMeta(o,n),l&&e.setFieldMeta(i,l)})};return{handleArrayFieldMetaShift:function(i,s,l,d){const c=function(i,s,a,r){const o=[t(i,s)];if("swap"===a)o.push(t(i,r));else if("move"===a){const[e,a]=[Math.min(s,r),Math.max(s,r)];for(let s=e;s<=a;s++)o.push(t(i,s))}else{const a=e.getFieldValue(i),r=Array.isArray(a)?a.length:0;for(let e=s+1;e<r;e++)o.push(t(i,e))}return Object.keys(e.fieldInfo).filter(e=>o.some(t=>e.startsWith(t)))}(i,s,l,d);({insert:()=>a(c,i,s),remove:()=>r(c),swap:()=>void 0!==d&&n(c,i,s,d),move:()=>void 0!==d&&o(c,i,s,d)})[l]()}}}class EventClient{#e;#t;#i;#s;#a;#r;#o;#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.#r=null,this.#o=500}startConnectLoop(){null!==this.#r||this.#a||(this.debugLog(`Starting connect loop (every ${this.#o}ms)`),this.#r=setInterval(this.#c,this.#o))}stopConnectLoop(){null!==this.#r&&(clearInterval(this.#r),this.#r=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 Qt=new class FormEventClient extends EventClient{constructor(){super({pluginId:"form-devtools"})}};function Rt(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(),Qt.emit("form-unmounted",{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});const{onMount:s}=this.options.validators||{};return Qt.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&&!At(e.defaultValues,t.defaultValues)&&!this.state.isTouched,a=!At(e.defaultState,t.defaultState)&&!this.state.isTouched;(s||a||i)&&mt(()=>{this.baseStore.setState(()=>Rt(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(()=>Rt({...this.options.defaultState,values:e??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:s}))},this.validateAllFields=async e=>{const t=[];mt(()=>{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,r=[`${e}[${t}]`];for(let i=t+1;i<=(a??0);i++)r.push(`${e}[${i}]`);const o=Object.keys(this.fieldInfo).filter(e=>r.some(t=>e.startsWith(t))),n=[];mt(()=>{o.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=Mt(e,{...this.options,form:this,validationLogic:this.options.validationLogic||jt});let i=!1;const s={};return mt(()=>{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:r}=Ut(t),o=Wt(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=r?.[e],{newErrorValue:l,newSource:d}=Ft({newFormValidatorError:n,isPreviousErrorFromFormValidator:"form"===a?.[o],previousErrorValue:i?.[o]});"form"===d&&(s[e]={...s[e],[o]:n}),i?.[o]!==l&&this.setFieldMeta(e,e=>({...e,errorMap:{...e.errorMap,[o]:l},errorSourceMap:{...e.errorSourceMap,[o]:d}}))}this.state.errorMap?.[o]!==a&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:a}})),(a||r)&&(i=!0)}const a=Wt("submit");this.state.errorMap?.[a]&&"submit"!==e&&!i&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[a]:void 0}}));const r=Wt("server");this.state.errorMap?.[r]&&"server"!==e&&!i&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[r]:void 0}}))}),{hasErrored:i,fieldsErrorMap:s}},this.validateAsync=async e=>{const t=Et(e,{...this.options,form:this,validationLogic:this.options.validationLogic||jt});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=Wt(e.cause),a=this.state.validationMetaMap[t];a?.lastAbortController.abort();const r=new AbortController;this.state.validationMetaMap[t]={lastAbortController:r},i.push(new Promise(async t=>{let i;try{i=await new Promise((t,i)=>{setTimeout(async()=>{if(r.signal.aborted)return t(void 0);try{t(await this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:r.signal},type:"validateAsync"}))}catch(e){i(e)}},e.debounceMs)})}catch(e){i=e}const{formError:a,fieldErrors:o}=Ut(i);o&&(s=s?{...s,...o}:o);const n=Wt(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,r=s?.[e],{newErrorValue:o,newSource:l}=Ft({newFormValidatorError:r,isPreviousErrorFromFormValidator:"form"===a?.[n],previousErrorValue:i?.[n]});i?.[n]!==o&&this.setFieldMeta(e,e=>({...e,errorMap:{...e.errorMap,[n]:o},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 r={};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={...r[i]||{},[t]:s};r[i]=e}}}return this.baseStore.setState(e=>({...e,isFormValidating:!1})),r},this.validate=e=>{const{hasErrored:t,fieldsErrorMap:i}=this.validateSync(e);return t&&!this.options.asyncAlways?i:this.validateAsync(e)},this.getFieldValue=e=>ft(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]:vt(t,i.fieldMetaBase[e])}}))},this.resetFieldMeta=e=>Object.keys(e).reduce((e,t)=>(e[t]=Ot,e),{}),this.setFieldValue=(e,t,i)=>{const s=i?.dontUpdateMeta??!1,a=i?.dontRunListeners??!1,r=i?.dontValidate??!1;mt(()=>{s||this.setFieldMeta(e,e=>({...e,isTouched:!0,isDirty:!0,errorMap:{...e?.errorMap,onMount:void 0}})),this.baseStore.setState(i=>({...i,values:gt(i.values,e,t)}))}),a||this.getFieldInfo(e).instance?.triggerOnChangeListener(),r||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=Ct(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)],qt(s,{dontValidate:!0})),await this.validateField(e,"change"),Nt(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),qt(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),qt(i,{dontValidate:!0})),Nt(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 gt(gt(e,`${t}`,a),`${i}`,s)},qt(s,{dontValidate:!0})),Nt(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},qt(s,{dontValidate:!0})),Nt(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,[],qt(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]:Ot},values:this.options.defaultValues?gt(t.values,e,ft(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=>Bt.validate({value:this.state.values,validationSource:"form"},e),this.parseValuesWithSchemaAsync=e=>Bt.validateAsync({value:this.state.values,validationSource:"form"},e),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=e?.formId??function(){let e,t=0,i="";if(!zt||Vt+16>256){for(zt=new Array(256),t=256;t--;)zt[t]=256*Math.random()|0;t=0,Vt=0}for(;t<16;t++)e=zt[Vt+t],i+=6===t?Pt[15&e|64]:8===t?Pt[63&e|128]:Pt[e],1&t&&t>1&&t<11&&(i+="-");return Vt++,i}(),this._devtoolsSubmissionOverride=!1,this.baseStore=new Store(Rt({...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],r=t[0];let o=0;const n={};for(const e of Object.keys(r.fieldMetaBase)){const t=r.fieldMetaBase[e],i=a?.fieldMetaBase[e],l=s?.[e],d=ft(r.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 h=!kt(c??[]),p=!t.isDirty,u=At(d,ft(this.options.defaultValues,e))||At(d,this.getFieldInfo(e)?.instance?.options.defaultValue);l&&l.isPristine===p&&l.isValid===h&&l.isDefaultValue===u&&l.errors===c&&t===i?(n[e]=l,o++):n[e]={...t,errors:c,isPristine:p,isValid:h,isDefaultValue:u}}return Object.keys(r.fieldMetaBase).length&&s&&o===Object.keys(r.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],r=t[0],o=t[1],n=Object.values(o).filter(Boolean),l=n.some(e=>e.isValidating),d=n.every(e=>e.isValid),c=n.some(e=>e.isTouched),h=n.some(e=>e.isBlurred),p=n.every(e=>e.isDefaultValue),u=c&&r.errorMap?.onMount,m=n.some(e=>e.isDirty),v=!m,f=Boolean(r.errorMap?.onMount||n.some(e=>e?.errorMap?.onMount)),g=!!l;let y=s?.errors??[];a&&r.errorMap===a.errorMap||(y=Object.values(r.errorMap).reduce((e,t)=>void 0===t?e:t&&It(t)?(e.push(t.form),e):(e.push(t),e),[]));const b=0===y.length,w=d&&b,S=this.options.canSubmitWhenInvalid??!1,x=0===r.submissionAttempts&&!c&&!f||!g&&!r.isSubmitting&&w||S;let $=r.errorMap;if(u&&(y=y.filter(e=>e!==r.errorMap.onMount),$=Object.assign($,{onMount:void 0})),s&&a&&s.errorMap===$&&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===h&&s.isPristine===v&&s.isDefaultValue===p&&s.isDirty===m&&At(a,r))return s;let _={...r,errorMap:$,fieldMeta:this.fieldMetaDerived.state,errors:y,isFieldsValidating:l,isFieldsValid:d,isFormValid:b,isValid:w,canSubmit:x,isTouched:c,isBlurred:h,isPristine:v,isDefaultValue:p,isDirty:m};const C=this.options.transform?.deps??[],k=C.length!==this.prevTransformArray.length||C.some((e,t)=>e!==this.prevTransformArray[t]);if(k){const e=Object.assign({},this,{state:_});this.options.transform?.fn(e),_=e.state,this.prevTransformArray=C}return _}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(e||{}),this.store.subscribe(()=>{Qt.emit("form-state-change",{id:this._formId,state:this.store.state,options:this.options})}),Qt.on("request-form-state",e=>{e.payload.id===this._formId&&Qt.emit("form-state-change",{id:this._formId,state:this.store.state,options:this.options})}),Qt.on("request-form-reset",e=>{e.payload.id===this._formId&&this.reset()}),Qt.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 Tt(e.validate)?Bt[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})),mt(()=>{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 Qt.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 Qt.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"validate",errors:this.state.errors});mt(()=>{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})),mt(()=>{this.baseStore.setState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),Qt.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})),Qt.emit("form-submission-state-change",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"inflight",onError:e}),i(),e}}setErrorMap(e){mt(()=>{Object.entries(e).forEach(([e,t])=>{const i=e;if(It(t)){const{formError:e,fieldErrors:s}=Ut(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 Ut(e){if(e){if(It(e)){return{formError:Ut(e.form).formError,fieldErrors:e.fields}}return{formError:e}}return{formError:void 0}}function Wt(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=ft(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,qt(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,qt(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(e,t,i)=>{this.form.insertFieldValue(this.name,e,t,qt(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(e,t,i)=>{this.form.replaceFieldValue(this.name,e,t,qt(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(e,t)=>{this.form.removeFieldValue(this.name,e,qt(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(e,t,i)=>{this.form.swapFieldValues(this.name,e,t,qt(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(e,t,i)=>{this.form.moveFieldValues(this.name,e,t,qt(i,{dontRunListeners:!0})),i?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=e=>{this.form.clearFieldValues(this.name,qt(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=Mt(e,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||jt}),s=this.getLinkedFields(e).reduce((t,i)=>{const s=Mt(e,{...i.options,form:i.form,validationLogic:i.form.options.validationLogic||jt});return s.forEach(e=>{e.field=i}),t.concat(s)},[]);let a=!1;mt(()=>{const e=(e,i)=>{const s=Kt(i.cause),r=i.validate?Ht(e.runValidator({validate:i.validate,value:{value:e.store.state.value,validationSource:"field",fieldApi:e},type:"validate"})):void 0,o=t[s],{newErrorValue:n,newSource:l}=Dt({formLevelError:o,fieldLevelError:r});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 r=Kt("submit");return this.state.meta.errorMap?.[r]&&"submit"!==e&&!a&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[r]:void 0},errorSourceMap:{...e.errorSourceMap,[r]:void 0}})),{hasErrored:a}},this.validateAsync=async(e,t)=>{const i=Et(e,{...this.options,form:this.form,validationLogic:this.form.options.validationLogic||jt}),s=await t,a=this.getLinkedFields(e),r=a.reduce((t,i)=>{const s=Et(e,{...i.options,form:i.form,validationLogic:i.form.options.validationLogic||jt});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 o=[],n=[],l=(e,t,i)=>{const a=Kt(t.cause),r=e.getInfo().validationMetaMap[a];r?.lastAbortController.abort();const o=new AbortController;this.getInfo().validationMetaMap[a]={lastAbortController:o},i.push(new Promise(async i=>{let r;try{r=await new Promise((i,s)=>{this.timeoutIds.validations[t.cause]&&clearTimeout(this.timeoutIds.validations[t.cause]),this.timeoutIds.validations[t.cause]=setTimeout(async()=>{if(o.signal.aborted)return i(void 0);try{i(await this.runValidator({validate:t.validate,value:{value:e.store.state.value,fieldApi:e,signal:o.signal,validationSource:"field"},type:"validateAsync"}))}catch(e){s(e)}},t.debounceMs)})}catch(e){r=e}if(o.signal.aborted)return i(void 0);const n=Ht(r),l=s[this.name]?.[a],{newErrorValue:d,newSource:c}=Dt({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,o);for(const e of r)e.validate&&l(e.field,e,n);let d=[];(o.length||n.length)&&(d=await Promise.all(o),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[Kt(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=>Bt.validate({value:this.state.value,validationSource:"field"},e),this.parseValueWithSchemaAsync=e=>Bt.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)??{...Ot,...e.defaultMeta}})}),this.options=e}get state(){return this.store.state}runValidator(e){return Tt(e.validate)?Bt[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 Ht(e){if(e)return e}function Kt(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 Gt,Zt,Jt,Xt,Yt,ei=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},ti=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){Gt.set(this,void 0),Zt.set(this,void 0),this.api=new FormApi(t),ei(this,Gt,e,"f").addController(this)}hostConnected(){ei(this,Zt,this.api.store.subscribe(()=>{ti(this,Gt,"f").requestUpdate()}),"f")}hostDisconnected(){ti(this,Zt,"f")?.call(this)}field(e,t){return ii(this.api,e,t)}}Gt=new WeakMap,Zt=new WeakMap;Jt=new WeakMap,Xt=new WeakMap,Yt=new WeakMap;const ii=ee(class FieldDirective extends ae{constructor(e){if(super(e),Jt.set(this,!1),Xt.set(this,void 0),Yt.set(this,void 0),e.type!==ie.CHILD)throw new Error("The `field` directive must be used in the `child` attribute")}update(e,[t,i,s]){if(!ti(this,Jt,"f")){if(!ti(this,Xt,"f")){const e={...i,form:t};ei(this,Xt,new FieldApi(e),"f"),ei(this,Yt,ti(this,Xt,"f").mount(),"f")}ei(this,Jt,!0,"f")}return this.render(t,i,s)}disconnected(){super.disconnected(),ti(this,Yt,"f")?.call(this)}reconnected(){super.reconnected(),ti(this,Xt,"f")&&ei(this,Yt,ti(this,Xt,"f").mount(),"f")}render(e,t,i){return ti(this,Xt,"f")?i(ti(this,Xt,"f")):K}}),si=G`.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}`,ai=me.object({first_name:me.string({required_error:"required"}).min(1,"required"),last_name:me.string({required_error:"required"}).min(1,"required"),email:me.string({required_error:"required"}).email("email_invalid").min(1,"required"),phone:me.string({required_error:"required"}).min(9,"phone_invalid"),birth_date:me.string({required_error:"required"}).min(1,"required"),tax_id:me.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 ri=class CompleteProfileForm extends Z{constructor(){super(...arguments),this.isPending=!1,this.errorMap={required:U("Este campo es obligatorio"),email_invalid:U("El email no es válido"),phone_invalid:U("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:ai}}),this.getScheduleServicesQuery=new i(this,()=>$(this.apiClient))}static{this.styles=si}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===V.phonecall;return J`<div class="form-container"><form class="form-content" @submit="${e=>{e.preventDefault(),e.stopPropagation(),this.form.api.handleSubmit()}}"><div class="${pe({field:!0,hidden:!!this.defaultValues.first_name})}">${this.form.field({name:"first_name"},e=>J`<mq-input label="${U("Nombre")}" id="${ue(e.name)}" value="${ue(e.state.value)}" name="${ue(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?J`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:K}`)}</div><div class="${pe({field:!0,hidden:!!this.defaultValues.last_name})}">${this.form.field({name:"last_name"},e=>J`<mq-input label="${U("Apellidos")}" id="${ue(e.name)}" value="${ue(e.state.value)}" name="${ue(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?J`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:K}`)}</div><div class="${pe({field:!0,hidden:!!this.defaultValues.email})}">${this.form.field({name:"email"},e=>J`<mq-input type="email" label="${U("Email")}" id="${ue(e.name)}" value="${ue(e.state.value)}" name="${ue(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?J`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:K}`)}</div><div class="${pe({field:!0,hidden:!!this.defaultValues.phone})}">${this.form.field({name:"phone"},e=>J`<mq-input type="tel" label="${U("Teléfono")}" id="${ue(e.name)}" value="${ue(e.state.value)}" name="${ue(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?J`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:K}`)}</div><div class="${pe({field:!0,hidden:!!this.defaultValues.birth_date})}">${this.form.field({name:"birth_date"},e=>J`<mq-input type="date" label="${U("Fecha de nacimiento")}" id="${ue(e.name)}" value="${ue(e.state.value)}" name="${ue(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?J`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:K}`)}</div><div class="${pe({field:!0,hidden:!!this.defaultValues.tax_id})}">${this.form.field({name:"tax_id"},e=>J`<mq-input label="${U("DNI/NIE")}" id="${ue(e.name)}" value="${ue(e.state.value)}" name="${ue(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?J`<em class="field-error">${this.translateError(e.state.meta.errors[0]?.message||"")}</em>`:K}`)}</div>${t?J`<mq-callout background="default" variant="info" noPadding>${U("El profesional te llamará al número que indiques en este campo.")}</mq-callout>`:K}<mq-button type="submit" fullwidth size="xl" ?disabled="${this.isPending}">${U("Continuar")}</mq-button></form></div>`}};function oi(e){return e.totalAmount<=0}e([R({context:s,subscribe:!0})],ri.prototype,"apiClient",void 0),e([X({type:Boolean})],ri.prototype,"isPending",void 0),e([X({type:String})],ri.prototype,"serviceId",void 0),e([X({type:Object})],ri.prototype,"defaultValues",void 0),ri=e([H(),t("complete-profile-form")],ri);class InvalidDiscountCodeError extends Error{constructor(e="Invalid discount code"){super(e),this.name="InvalidDiscountCodeError"}}const ni=G`: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 li=class DiscountCodeField extends Z{constructor(){super(...arguments),this.basePrice=null,this.appliedDiscount=null,this.expanded=!1,this.form=new TanStackFormController(this,{defaultValues:{code:""}})}static{this.styles=ni}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,r=t.after_discount_amount??i.amount-Math.round(i.amount*a/100);return{code:s,percentage:a,discountAmount:i.amount-r,totalAmount:r,currency:i.currency}}catch(e){if(P(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 U(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 J`<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 J`<div class="row"><input class="input ${s?"input--error":""}" type="text" .value="${i.state.value}" ?disabled="${e}" placeholder="${U("Ingresa el código")}" @input="${e=>i.handleChange(e.target.value)}"> <button type="submit" class="btn" ?disabled="${!t.code.trim()||e}">${e?J`${ve({color:"currentColor",size:16})}`:U("Aplicar")}</button></div>${s?J`<p class="error">${s}</p>`:K}`})}</form>`}render(){return this.appliedDiscount&&!this.expanded?J`<div class="applied"><span class="applied__status" role="status">${J`<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>`} ${U("Código de promoción aplicado")} </span><button type="button" class="applied__change" @click="${this.onChangeCode}">${J`<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>`} ${U("Cambiar código")}</button></div>`:J`<button type="button" class="trigger" aria-expanded="${this.expanded}" @click="${this.toggle}">${fe({size:20})} <span class="trigger__label">${U("Añadir código de promoción")}</span> ${e=this.expanded,J`<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([R({context:s,subscribe:!0})],li.prototype,"apiClient",void 0),e([X({type:Object})],li.prototype,"basePrice",void 0),e([X({type:Object})],li.prototype,"appliedDiscount",void 0),e([Y()],li.prototype,"expanded",void 0),li=e([H(),t("discount-code-field")],li);const di=G`.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 ci=class NewAppointmentSummary extends Z{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,we.success(U("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,()=>o(this.apiClient))}static{this.styles=di}renderAppointmentDetails(){return J`${this.startsAt&&this.channel&&this.duration?J`<appointment-details .startsAt="${_(this.startsAt).toISOString()}" .duration="${this.duration}" .channel="${this.channel}" .timezone="${this.patient.timezone}"></appointment-details>`:K} ${this.previousStartsAt&&this.previousDuration?J`<hr><span class="previous-starts-at">${U("Cita previa:")}</span><appointment-details .startsAt="${_(this.previousStartsAt).toISOString()}" .duration="${this.previousDuration}" .timezone="${this.patient.timezone}" strike-through></appointment-details>`:K}`}render(){const e=oe(),t=this.getOrganizationSpecialtiesQuery.result?.data?.find(e=>e.id===this.professional?.speciality.id),i=c(t?.code??"",e,t?.name),s=this.serviceCode?h(this.serviceCode,e,this.serviceName):this.serviceName??"",a=this.getOrganizationSetupQuery.result?.data?.appointments,r=a?.reserve_conditions?.trim()??"",o=!0===a?.has_discount_coupons_show&&a?.payment_provider!==z.Stripe,n=this.servicePrice;return J`<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()} ${ge(n)?J`${this.showPrice?J`${o?J`<discount-code-field .basePrice="${{amount:n.amount,currency:n.currency}}" .appliedDiscount="${this.appliedDiscount}" @discount-applied="${this.onDiscountApplied}"></discount-code-field>`:K}<div class="payment-info">${s?J`<span class="payment-info__name">${s}</span>`:K} <span class="payment-info__price">${ye({amount:n.amount,currency:n.currency},e)}</span></div>${o&&this.appliedDiscount?J`<div class="discount-info"><span>${U("Promoción")} ${this.appliedDiscount.code} (-${this.appliedDiscount.percentage}%)</span> <span>${ye({amount:-this.appliedDiscount.discountAmount,currency:this.appliedDiscount.currency},e)}</span></div><hr><div class="total-info"><span>${U("Total")}</span> <span>${ye({amount:this.appliedDiscount.totalAmount,currency:this.appliedDiscount.currency},e)}</span></div>`:K}`:K} ${r.length>0?J`<hr><mq-clamped-text class="reservation-conditions" .lines="${2}" expand-label="${U("Ver más")}" collapse-label="${U("Ver menos")}"><span class="reservation-conditions__prefix">${U("Condiciones de reserva:")}</span> ${" "} <span class="reservation-conditions__body">${r}</span></mq-clamped-text>`:K}`:K}</mq-card>`}};e([R({context:s,subscribe:!0})],ci.prototype,"apiClient",void 0),e([X({type:Object})],ci.prototype,"professional",void 0),e([X({type:String})],ci.prototype,"startsAt",void 0),e([X({type:Number})],ci.prototype,"duration",void 0),e([X({type:String})],ci.prototype,"channel",void 0),e([X({type:String})],ci.prototype,"previousStartsAt",void 0),e([X({type:Number})],ci.prototype,"previousDuration",void 0),e([X({type:String})],ci.prototype,"serviceCode",void 0),e([X({type:String})],ci.prototype,"serviceName",void 0),e([X({type:Object})],ci.prototype,"servicePrice",void 0),e([X({type:Boolean,attribute:"fill-column",reflect:!0})],ci.prototype,"fillColumn",void 0),e([X({type:Object})],ci.prototype,"appliedDiscount",void 0),e([X({type:Boolean})],ci.prototype,"showPrice",void 0),e([R({context:Ue,subscribe:!0})],ci.prototype,"patient",void 0),ci=e([H(),t("new-appointment-summary")],ci);let hi=class CompleteProfileStep extends Z{constructor(){super(...arguments),this.showBack=!0,this.channel=void 0,this.getPatientProfileQuery=new i(this,()=>w(this.apiClient)),this.updatePatientProfileMutation=new he(this,{mutationFn:async e=>this.apiClient.flash.updatePatientProfile(e)})}static{this.styles=G`.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=>J`<mq-page-title .title="${U("Petición de cita")}" .showBack="${this.showBack}" @mq-back="${e=>it(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>${U("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([R({context:s,subscribe:!0})],hi.prototype,"apiClient",void 0),e([X({type:String})],hi.prototype,"serviceId",void 0),e([X({type:Boolean})],hi.prototype,"showBack",void 0),e([X({type:Object})],hi.prototype,"scheduleSlot",void 0),e([X({type:Object})],hi.prototype,"professional",void 0),e([X({type:String})],hi.prototype,"channel",void 0),hi=e([H(),t("complete-profile-step")],hi);const pi=G`: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 ui=class FileAttachments extends Z{constructor(){super(...arguments),this.uploadedFiles=[],this.uploadingFile=null,this.uploadFileMutation=new he(this,{mutationFn:e=>this.apiClient.documents.uploadFile({file:e}),throwOnError:!0})}static{this.styles=pi}handleClickUploadFile(){const e=this.shadowRoot?.querySelector("input[type='file']");e&&e.click()}getErrorMessageFromCode(e){switch(e){case 422:default:return U("Ha ocurrido un error en el envío del archivo");case 413:return U("El archivo supera el tamaño máximo permitido");case 415:return U("Formato de archivo no soportado")}}async handleUploadFile(e){const t=e.target.files?.[0];if(t){if(t.size>314572800)return we.error(U("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(!P(e))return;const t=this.getErrorMessageFromCode(e.response?.status??500);we.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 J`<div class="field"><input type="file" hidden @change="${this.handleUploadFile}"><p class="label">${U("Adjuntar archivos")}</p><p class="hint">${U("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}">${$e()} ${U("Subir archivo")}</mq-button><div class="files">${this.uploadedFiles.map((e,t)=>J`<div class="file"><div class="file-info">${xe()} <span class="file-name">${e.file_name}</span></div><div class="file-close"><mq-button size="icon-xs" variant="ghost" @click="${()=>this.handleRemoveFile(t)}">${_e({color:"var(--color-neutrals-text-default)",size:24})}</mq-button></div></div>`)} ${this.uploadingFile?J`<div class="file uploading"><div class="file-info">${J`<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 mi(e){const t=e.getApiClient();t&&await(e.getQueryClient()?.invalidateQueries({queryKey:S(t)}))}e([R({context:s,subscribe:!0})],ui.prototype,"apiClient",void 0),e([X({type:Array})],ui.prototype,"uploadedFiles",void 0),e([Y()],ui.prototype,"uploadingFile",void 0),e([Se("input[type='file']")],ui.prototype,"fileInput",void 0),ui=e([H(),t("file-attachments")],ui);class ScheduleAppointmentMutationController{constructor(e,t){this.mutation=new he(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 mi(t),await t.onSuccess(e.appointment.id)},onError:async()=>{await mi(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 vi=G`: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 fi=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 gi=class ConfirmStep extends Z{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 fi({appointmentId:e}))},onError:()=>{this.dispatchEvent(new CustomEvent("error"))}}),this.rescheduleAppointmentMutation=new he(this,{mutationFn:async e=>this.apiClient.appointments.rescheduleAppointment(e),onSuccess:async()=>{await(this.queryClientContext?.invalidateQueries({queryKey:S(this.apiClient)}));const e=this.appointment?.id;if(!e)return Ce.error("confirm-step: reschedule succeeded but appointment id is missing"),void this.dispatchEvent(new CustomEvent("error"));this.dispatchEvent(new fi({appointmentId:e}))},onError:async()=>{await(this.queryClientContext?.invalidateQueries({queryKey:S(this.apiClient)})),this.dispatchEvent(new CustomEvent("error"))}})}static{this.styles=vi}get isPaymentFlow(){return this.requiresPayment&&"schedule"===this.kind&&ge(this.service?.price)}get isFullyDiscounted(){return null!=this.appliedDiscount&&oi(this.appliedDiscount)}get ctaLabel(){return this.isFullyDiscounted?U("Confirmar cita"):this.isPaymentFlow?U("Continuar al pago"):U("Continuar")}async handleSubmit(){if(p.track(u(this.patient.hash,this.professional.id??"",this.startsAt??"",this.specialityId,this.serviceId??"")),this.isPaymentFlow&&!this.isFullyDiscounted)return this.scheduleSlot.payable_reference?void this.dispatchEvent(new PaymentStartedEvent({booking:{consultationReason:this.reason,preconsultationDocuments:this.attachedFiles}})):(Ce.error("confirm-step: slot has no payable_reference"),void this.dispatchEvent(new CustomEvent("error")));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})}}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 J`<mq-page-title .title="${"schedule"===this.kind?U("Petición de cita"):U("Modificar cita")}" .showBack="${this.showBack}" @mq-back="${e=>it(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">${U("Cuestionario preconsulta")}</p><div class="field"><p class="label">${U("Motivo de consulta")}</p><mq-textarea maxlength="${240}" label="${U("¿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}" @click="${this.handleSubmit}" fullwidth>${this.ctaLabel}</mq-button></mq-card></div>`}};e([R({context:s,subscribe:!0})],gi.prototype,"apiClient",void 0),e([R({context:Ue,subscribe:!0})],gi.prototype,"patient",void 0),e([X({type:String})],gi.prototype,"kind",void 0),e([X({type:Boolean})],gi.prototype,"showBack",void 0),e([X({type:Boolean})],gi.prototype,"requiresPayment",void 0),e([X({type:Object})],gi.prototype,"scheduleSlot",void 0),e([X({type:Object})],gi.prototype,"professional",void 0),e([X({type:String})],gi.prototype,"startsAt",void 0),e([X({type:Number})],gi.prototype,"duration",void 0),e([X({type:String})],gi.prototype,"channel",void 0),e([X({type:Object})],gi.prototype,"appointment",void 0),e([X({type:String})],gi.prototype,"serviceId",void 0),e([X({type:String})],gi.prototype,"specialityId",void 0),e([X({type:Object})],gi.prototype,"service",void 0),e([X({type:Object})],gi.prototype,"appliedDiscount",void 0),e([Y()],gi.prototype,"reason",void 0),e([Y()],gi.prototype,"attachedFiles",void 0),e([R({context:ke,subscribe:!0})],gi.prototype,"queryClientContext",void 0),gi=e([H(),t("confirm-step")],gi);class PaymentSuccessEvent extends Event{static{this.eventName="payment-success"}constructor(e){super(PaymentSuccessEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}const yi=G`: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 bi=class PaymentPendingStep extends Z{constructor(){super(...arguments),this._timedOut=!1,this._remaining=6e4}static{this.styles=yi}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?J`<p class="error-title">${U("No hemos podido confirmar tu pago")}</p><p class="message">${U("Ha ocurrido un problema al verificar el estado de tu pago. Por favor, contacta con soporte si el cargo se ha realizado.")}</p>`:J`${ve({size:40,color:"var(--color-primary-default)"})}<p class="message">${U("Verificando tu pago...")}</p>`}};e([R({context:s,subscribe:!0})],bi.prototype,"apiClient",void 0),e([X({type:String})],bi.prototype,"sessionId",void 0),e([Y()],bi.prototype,"_timedOut",void 0),bi=e([H(),t("payment-pending-step")],bi);const wi=G`: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;padding:var(--sp-4)}.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:400px}.payment-frame.payment-frame--bleed{padding:0}.panel{width:100%;box-sizing:border-box;padding:24px}.panel-message{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--sp-4);text-align:center;min-height:200px}.panel-message__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}.panel-message__text{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}@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}.payment-frame{padding:var(--sp-6)}}`;let Si=class PaymentStep extends Z{constructor(){super(...arguments),this.showBack=!0,this.channel=void 0,this.service=void 0,this.scheduleSlot=void 0,this.appliedDiscount=null,this.booking=null,this.env="production",this.locale="es_ES",this.countryCode="ES",this.checkoutMode="embed",this._iframeLoaded=!1,this._iframeHeight=null,this._fullBleed=!1,this._renderedUrl=null,this._redirected=!1,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",{detail:null}))}}),this._onPageShow=e=>{e.persisted&&this._redirected&&(this._redirected=!1,this.dispatchEvent(new CustomEvent("back")))},this._onMessage=e=>{if(!Me(e,this._iframe?.contentWindow))return;this._fullBleed=e.origin===Ee;const t=Ie(e.data);switch(t?.type){case"resize":return void(this._iframeHeight=t.height);case"success":return void this._onPaid(t.reference);case"error":return void this.dispatchEvent(new CustomEvent("error",{detail:{expired:"expired"===t.reason}}))}}}static{this.styles=wi}get isFullyDiscounted(){return null!=this.appliedDiscount&&oi(this.appliedDiscount)}confirmFree(){const e=this.scheduleSlot,t=this.service?.id;e&&t&&this.createScheduleAppointment.run({slotId:e.id,serviceId:t,consultationReason:this.booking?.consultationReason,preconsultationDocuments:this.booking?.preconsultationDocuments,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 be(this._paymentAmountCents()).toFixed(2)}_buildPayUrl(){const e="redirect"===this.checkoutMode?Ze(window.location.href):void 0,t=this.scheduleSlot?.payable_reference;return this.apiKey&&this.token&&t?Ae({apiKey:this.apiKey,token:this.token,payableReference:t,env:this.env,locale:this.locale,discountCode:this.appliedDiscount?.code,consultationReason:this.booking?.consultationReason,amount:this._paymentAmountLabel(),currency:this._paymentCurrency(),country:this.countryCode,label:this.service?.name??U("Consulta"),framedByHost:!0,mode:this.checkoutMode,successUrl:e,errorUrl:e}):null}willUpdate(e){super.willUpdate(e);const t=this._buildPayUrl();t!==this._renderedUrl&&(this._renderedUrl=t,this._iframeLoaded=!1,this._iframeHeight=null,this._fullBleed=!1)}connectedCallback(){super.connectedCallback(),window.addEventListener("message",this._onMessage),window.addEventListener("pageshow",this._onPageShow)}disconnectedCallback(){window.removeEventListener("message",this._onMessage),window.removeEventListener("pageshow",this._onPageShow),super.disconnectedCallback()}updated(){if("redirect"!==this.checkoutMode||this._redirected)return;if(this.isFullyDiscounted)return;const e=this._buildPayUrl();e&&(this._redirected=!0,window.location.assign(e))}_onIframeLoad(){this._iframeLoaded=!0}async _onPaid(e){const t=this.booking?.preconsultationDocuments??[];(await Promise.allSettled(t.map(({file_path:t,file_name:i})=>this.apiClient.appointments.addDocument({appointment_id:e,file_path:t,file_name:i})))).some(e=>"rejected"===e.status)&&Ce.error("payment-step: could not attach pre-consultation documents"),this.dispatchEvent(new PaymentSuccessEvent({appointmentId:e}))}_renderSummaryColumn(){return J`<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}">${U("Confirmar cita")}</mq-button></div></div></div>`}_renderPaymentColumn(){const e=this._buildPayUrl();return e?"redirect"===this.checkoutMode?J`<div class="payment-col__inner"><mq-card class="payment-frame" roundness="md"><mq-skeleton width="100%" height="400px" border-radius="md" role="status" aria-live="polite" aria-label="${U("Cargando portal de pago")}"></mq-skeleton></mq-card></div>`:J`<div class="payment-col__inner"><mq-card class="payment-frame ${this._fullBleed?"payment-frame--bleed":""}" roundness="md">${this._iframeLoaded?null:J`<mq-skeleton width="100%" height="400px" border-radius="md" role="status" aria-live="polite" aria-label="${U("Cargando portal de pago")}"></mq-skeleton>`}<iframe class="${this._iframeLoaded?"loaded":""}" src="${e}" title="${U("Portal de pago")}" allow="payment" style="${null!==this._iframeHeight?`height: ${this._iframeHeight}px;`:""}" @load="${this._onIframeLoad}"></iframe></mq-card></div>`:J`<div class="payment-col__inner"><mq-card class="panel" elevation="none" roundness="lg"><div class="panel-message"><p class="panel-message__title">${U("No se puede iniciar el pago")}</p><p class="panel-message__text">${U("Faltan credenciales de pago. Vuelve atrás e inténtalo de nuevo.")}</p></div></mq-card></div>`}render(){const e=J`<mq-page-title .title="${U("Petición de cita")}" .showBack="${this.showBack}" @mq-back="${e=>it(this,e)}"></mq-page-title>`;return this.isFullyDiscounted?J`${e}<div class="content content--free">${this._renderSummaryColumn()}<div class="payment-col" .inert="${!0}"></div></div>`:J`${e}<div class="content">${this._renderSummaryColumn()}<div class="payment-col">${this._renderPaymentColumn()}</div></div>`}};e([R({context:s,subscribe:!0})],Si.prototype,"apiClient",void 0),e([X({type:Boolean})],Si.prototype,"showBack",void 0),e([X({type:Object})],Si.prototype,"professional",void 0),e([X({type:String})],Si.prototype,"startsAt",void 0),e([X({type:Number})],Si.prototype,"duration",void 0),e([X({type:String})],Si.prototype,"channel",void 0),e([X({type:Object})],Si.prototype,"service",void 0),e([X({type:Object})],Si.prototype,"scheduleSlot",void 0),e([X({type:Object})],Si.prototype,"appliedDiscount",void 0),e([X({type:Object})],Si.prototype,"booking",void 0),e([X({type:String,attribute:!1})],Si.prototype,"apiKey",void 0),e([X({type:String,attribute:!1})],Si.prototype,"token",void 0),e([X({type:String,attribute:!1})],Si.prototype,"env",void 0),e([X({type:String,attribute:!1})],Si.prototype,"locale",void 0),e([X({type:String,attribute:!1})],Si.prototype,"countryCode",void 0),e([X({type:String,attribute:!1})],Si.prototype,"checkoutMode",void 0),e([R({context:ke,subscribe:!0})],Si.prototype,"queryClientContext",void 0),e([Se("iframe")],Si.prototype,"_iframe",void 0),e([Y()],Si.prototype,"_iframeLoaded",void 0),e([Y()],Si.prototype,"_iframeHeight",void 0),e([Y()],Si.prototype,"_fullBleed",void 0),Si=e([H(),t("payment-step")],Si);const xi=G`: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 $i=class ScheduleLoadingBanner extends Z{static{this.styles=xi}render(){return J`<div class="banner" role="status" aria-live="polite">${ve({size:24,color:"var(--color-primary-default, var(--color-primary))"})}<p class="label">${U("Cargando")}</p></div>`}};$i=e([H(),t("schedule-loading-banner")],$i);const _i=G`.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}}`,Ci=me.object({service:me.string().min(1),specialty:me.string().min(1)});class SearchProfessionalsFormSuccessEvent extends CustomEvent{static{this.eventName="success"}constructor(e){super(SearchProfessionalsFormSuccessEvent.eventName,{bubbles:!0,composed:!0,detail:e})}}let ki=class SearchProfessionalsForm extends Z{constructor(){super(...arguments),this.form=new TanStackFormController(this,{defaultValues:this.defaultValues,onSubmit:e=>{const t=e.value;p.track(m(this.patient.hash,t.specialty??"",t.service??"")),this.dispatchEvent(new SearchProfessionalsFormSuccessEvent(t))},validators:{onSubmit:Ci}}),this.getScheduleServicesQuery=new i(this,()=>$(this.apiClient)),this.getOrganizationSpecialtiesQuery=new i(this,()=>d(this.apiClient))}static{this.styles=_i}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 r=oe();return J`<mq-select label="${U("Modalidad de la cita")}" id="${ue(e)}" value="${ue(t)}" name="${ue(e)}" size="lg" ?error="${s}" @onvaluechange="${e=>{i(e.value)}}">${a.map(e=>J`<mq-option value="${e.id}">${h(e.code??"",r,e.name)}</mq-option>`)}</mq-select>`}renderOrganizationSpecialties({name:e,value:t,onValueChange:i,error:s},a){const r=oe();return J`<mq-select label="${U("Especialidad")}" id="${ue(e)}" value="${ue(t)}" name="${ue(e)}" size="lg" ?error="${s}" @onvaluechange="${e=>{i(e.value)}}">${a.map(e=>J`<mq-option value="${e.id}">${v[e.code]?.[r]??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 J`<div class="form-container"><form class="form-content" @submit="${e=>{e.preventDefault(),e.stopPropagation(),this.form.api.handleSubmit()}}">${this.filtersLoading?J`<schedule-loading-banner class="filters-loading-banner"></schedule-loading-banner>`:a?J`<div class="field">${this.form.field({name:"service"},e=>J`<p class="field-title">${U("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=>J`<p class="field-title">${U("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>${U("Buscar disponibilidad")}</mq-button>`:K}</form></div>`}};function Mi(e){if(!e)return new Date(Number.NaN);const t=_(e);if(De(t))return t;const i=qe(e);if(De(i))return i;const s=new Date(e);return Number.isNaN(s.getTime())?new Date(Number.NaN):s}function Ei(e,t){if(!De(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 Ve(e,"yyyy-MM-dd")}function Ii(e,t){const i=new Date;let s;for(const t of e){const e=Mi(t.starts_at);De(e)&&(Pe(e,i)&&(!s||Ne(e,s)<0)&&(s=e))}return s?Ei(s,t):void 0}e([R({context:s,subscribe:!0})],ki.prototype,"apiClient",void 0),e([R({context:Ue,subscribe:!0})],ki.prototype,"patient",void 0),e([X({type:Object})],ki.prototype,"defaultValues",void 0),ki=e([H(),t("search-professionals-form")],ki);const Ai=G`: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 Fi=class ShowFullScheduleEvent extends Event{static{this.eventName="show-full-schedule"}constructor(){super(ShowFullScheduleEvent.eventName,{bubbles:!0,composed:!0})}},Di=class ProfessionalCard extends Z{constructor(){super(...arguments),this.serviceId="",this.specialtyId="",this.showSlotUnavailableError=!1,this.getOrganizationSpecialtiesQuery=new i(this,()=>d(this.apiClient)),this.checkForSlotAvailabilityMutation=new he(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=Ai}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=Mi(i.starts_at);if(!De(s))return e;const a=Ei(s,t);if(!a)return e;const r={slot:i,parsedDate:s};if(!e.has(a))return e.set(a,[r]),e;const o=e.get(a);return o?.push(r),e},new Map);return 0===i.size?[]:Array.from(i.entries()).map(([e,t])=>({key:e,slots:t.sort((e,t)=>Ne(e.parsedDate,t.parsedDate)),date:t[0]?.parsedDate??new Date(Number.NaN)})).filter(({date:e})=>De(e)).sort((e,t)=>Ne(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=oe().replace("_","-"),i=C(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=oe().replace("_","-"),i=C(this.timezone),s=i?{timeZone:i}:{},a=new Intl.DateTimeFormat(t,{day:"numeric",...s}).format(e),r=new Intl.DateTimeFormat(t,{month:"short",...s}).format(e).replace(/\.$/,"");return`${a} ${`${r.charAt(0).toUpperCase()}${r.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,oe().replace("_","-"),this.timezone)}async handleSlotClick(e){const t=await this.checkForSlotAvailabilityMutation.run(e.id);t.status===j.available?(this.showSlotUnavailableError=!1,p.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:S(this.apiClient)}))}render(){const e=oe(),t=this.getOrganizationSpecialtiesQuery.result?.data?.find(e=>e.id===this.professional.speciality.id),i=c(t?.code??"",e,t?.name);return J`<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="${pe({"schedules-container":!0,"is-pending":this.checkForSlotAvailabilityMutation.isPending})}">${this.showSlotUnavailableError?J`<p class="error-message">${U("Este horario no está disponible. Por favor, seleccione otro.")}</p>`:K}<div class="schedules">${this.groupedSlots.length>0?this.groupedSlots.map(e=>J`<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})=>J`<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(()=>J`<div class="schedule-slot is-empty">-</div>`)}</div>`):J`<div class="no-slots">${U("Sin huecos disponibles actualmente")}</div>`}</div><mq-button fullwidth @click="${()=>{p.track(g(this.patient.hash,this.professional.id,this.specialtyId,this.serviceId)),this.dispatchEvent(new Fi)}}">${Le({size:24})} ${U("Ver agenda completa")}</mq-button></div></mq-card>`}};e([R({context:s,subscribe:!0})],Di.prototype,"apiClient",void 0),e([R({context:Ue,subscribe:!0})],Di.prototype,"patient",void 0),e([X({type:Object})],Di.prototype,"professional",void 0),e([X({type:String})],Di.prototype,"serviceId",void 0),e([X({type:String})],Di.prototype,"specialtyId",void 0),e([Y()],Di.prototype,"showSlotUnavailableError",void 0),e([R({context:ke,subscribe:!0})],Di.prototype,"queryClientContext",void 0),Di=e([H(),t("professional-card")],Di);const qi=G`:host{display:block;width:100%}mq-callout{--mq-callout-padding:var(--sp-2)}.message{font-family:var(--font-body);font-size:var(--text-sm);font-weight:var(--font-weight-bold);line-height:var(--text-sm--line-height);margin:0;overflow-wrap:anywhere}`;let Vi=class HighDemandCallout extends Z{constructor(){super(...arguments),this.specialtyName=void 0}static{this.styles=qi}render(){const e=this.specialtyName?.trim();return e?J`<mq-callout role="status" background="primary" variant="info"><p class="message">${U(W`La demanda de citas en ${e} es elevada en este momento, por lo que los tiempos de espera pueden ser mayores de lo habitual.`)}</p></mq-callout>`:K}};e([X({type:String})],Vi.prototype,"specialtyName",void 0),Vi=e([H(),t("high-demand-callout")],Vi);const Pi=G`: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)}#professionals-results high-demand-callout{display:block;margin-top:var(--sp-4)}`;class ShowFullScheduleEvent extends Event{static{this.eventName="show-full-schedule"}constructor(e){super(ShowFullScheduleEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}let zi=class ProfessionalsList extends Z{constructor(){super(...arguments),this.specialty_id=void 0,this.service_id=void 0,this.getScheduleServicesQuery=new i(this,()=>$(this.apiClient)),this.getOrganizationSpecialtiesQuery=new i(this,()=>d(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:S(e,"professionals-by-specialty-and-service",t),queryFn:t.speciality_id&&t.organization_schedule_service_id?()=>e.schedules.getProfessionalsBySpecialtyAndService(t):Be,staleTime:0};var e,t})}static{this.styles=Pi}render(){const e=oe(),t=this.getScheduleServicesQuery.result?.data?.find(e=>e.id===this.service_id);if(!this.specialty_id||!this.service_id)return K;const i=h(t?.code??"",e,t?.name),s=this.getOrganizationSpecialtiesQuery.result?.data?.find(e=>String(e.id)===this.specialty_id)?.name;return this.getProfessionalsBySpecialtyAndServiceQuery.render({pending:()=>J`<div id="professionals-results"><schedule-loading-banner></schedule-loading-banner></div>`,complete:e=>{const a=e?.data??[],r=!0===e?.meta?.high_demand?J`<high-demand-callout .specialtyName="${s}"></high-demand-callout>`:K;if(0===a.length)return J`${r}<mq-callout background="default" variant="info">${U("No hay profesionales disponibles para la especialidad seleccionada. Por favor, vuelve a intentarlo en otro momento o selecciona otra especialidad.")}</mq-callout>`;const o=a[0],n=o?.slots?.[0];p.track(y(this.patient.hash,this.specialty_id??"",this.service_id??"",n?.starts_at??"",o?.id??"",a.length,a.reduce((e,t)=>e+(t.slots?.length??0),0)));const l=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=k(i,new Date);return[t,void 0===s?void 0:U(W`${s} minutos`),a].filter(e=>Boolean(e))}({professionals:a,serviceName:i,timezone:this.patient?.timezone??""});return J`<div id="professionals-results"><p class="title">${U("Selecciona tu especialista")}</p><div class="applied-filters"><span class="applied-filters-label" id="applied-filters-label">${U("Resultados para:")}</span> <span class="applied-filters-values" role="group" aria-labelledby="applied-filters-label">${l.map(e=>J`<mq-badge variant="primary">${e}</mq-badge>`)}</span></div>${r}</div>${a.map(e=>J`<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:Ii(e.slots,this.patient?.timezone)}))}}"></professional-card>`)}`}})}};e([R({context:s,subscribe:!0})],zi.prototype,"apiClient",void 0),e([R({context:Ue,subscribe:!0})],zi.prototype,"patient",void 0),e([X({type:String})],zi.prototype,"specialty_id",void 0),e([X({type:String})],zi.prototype,"service_id",void 0),zi=e([H(),t("professionals-list")],zi);const ji=G`.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 Li=class SuccessEvent extends Event{static{this.eventName="success"}constructor(e){super(SuccessEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}},Bi=class SelectProfessionalStep extends Z{constructor(){super(...arguments),this.showBack=!0,this.defaultSpecialty=void 0,this.defaultService=void 0,this.errorMessage=void 0,this.formData=void 0,this.getScheduleServicesQuery=new i(this,()=>$(this.apiClient)),this.getOrganizationSpecialtiesQuery=new i(this,()=>d(this.apiClient))}static{this.styles=ji}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(),p.track(b(this.patient.hash))}scrollToProfessionalsList(){setTimeout(()=>{this.shadowRoot?.querySelector("professionals-list")?.scrollIntoView({behavior:"smooth"})},0)}render(){return J`<div class="container"><div class="page-container">${this.showBack?J`<mq-page-title .title="${U("Petición de cita")}" .showBack="${!0}" @mq-back="${e=>it(this,e)}"></mq-page-title>`:K} ${this.errorMessage?J`<mq-callout role="alert" background="default" variant="info">${this.errorMessage}</mq-callout>`:K} ${this.isScheduleFiltersReady?K:J`<schedule-loading-banner></schedule-loading-banner>`} ${this.isScheduleFiltersReady&&this.showSearchForm?J`<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>`:K} ${this.isScheduleFiltersReady?J`<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 Li({slot:e.detail.slot,serviceId:t.service_id,service:i,specialtyId:t.specialty_id,professional:e.detail.professional}))}}"></professionals-list>`:K}</div></div>`}};function Ti(e,t){return{queryKey:S(e,"schedule-service-professional-slots",t),queryFn:()=>e.schedules.getScheduleServiceProfessionalSlots(t),staleTime:x}}e([R({context:s,subscribe:!0})],Bi.prototype,"apiClient",void 0),e([R({context:Ue,subscribe:!0})],Bi.prototype,"patient",void 0),e([X({type:Boolean})],Bi.prototype,"showBack",void 0),e([X({type:String})],Bi.prototype,"defaultSpecialty",void 0),e([X({type:String})],Bi.prototype,"defaultService",void 0),e([X({type:String})],Bi.prototype,"errorMessage",void 0),e([Y()],Bi.prototype,"formData",void 0),Bi=e([H(),t("select-professional-step")],Bi);const Oi=()=>"undefined"!=typeof window&&window.innerWidth>=Te.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 Ni=G`:host{display:flex;flex-direction:column;gap:var(--sp-4)}.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 Qi=class DaysWindowView extends Z{constructor(){super(...arguments),this.specialityId=void 0,this.reschedulingAppointmentId=void 0,this.windowStartDate=void 0,this.errorMessage=void 0,this.specialtyName=void 0,this.checkForSlotAvailabilityMutation=new he(this,{mutationFn:e=>this.apiClient.schedules.getScheduleSlot({slot_id:e,service_id:this.serviceId||void 0,speciality_id:this.specialityId})}),this._visibleDays=Oi(),this.getScheduleServiceProfessionalSlotsQuery=new i(this,()=>{const e=this.patient.timezone,t=M(new Date,e),i=this.windowStartDay<t?t:this.windowStartDay,s=Ve(Oe(qe(i),this._visibleDays-1),"yyyy-MM-dd");return Ti(this.apiClient,{service_id:this.serviceId,professional_hash:this.professionalId,starts_at:E(A(i,e)),finishes_at:E(I(s,e)),rescheduling_appointment_id:this.reschedulingAppointmentId})})}static{this.styles=Ni}get windowStartDay(){return this.windowStartDate??M(new Date,this.patient.timezone)}connectedCallback(){super.connectedCallback(),this._resizeHandler=()=>{const e=Oi();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?.data,i=this.getScheduleServiceProfessionalSlotsQuery.result?.isPending,s=!0===t?.meta?.high_demand,a=t?.data?.filter(t=>Pe(_(t.starts_at),e)&&t.status===j.available),r=a?.map(e=>({key:e.id,date:_(e.starts_at).toISOString()})),o=oe().replace("_","-");return J`${s?J`<high-demand-callout .specialtyName="${this.specialtyName}"></high-demand-callout>`:K}<mq-card class="card" roundness="md"><mq-button @click="${()=>this.dispatchEvent(new CustomEvent("to-calendar-view"))}">${Le({size:24})} ${U("Elige otra fecha")}</mq-button>${this.errorMessage?J`<p class="error-message">${this.errorMessage}</p>`:K}<mq-time-slot-picker .locale="${o}" .timezone="${this.patient.timezone}" .visibleDays="${this._visibleDays}" .slots="${r??[]}" .windowStartDate="${this.windowStartDay}" ?is-loading="${i}" @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===j.available?this.dispatchEvent(new SlotSelectEvent({slot:i})):this.dispatchEvent(new SlotUnavailableEvent)}}"></mq-time-slot-picker></mq-card>`}};e([R({context:s,subscribe:!0})],Qi.prototype,"apiClient",void 0),e([X({type:String})],Qi.prototype,"professionalId",void 0),e([X({type:String})],Qi.prototype,"serviceId",void 0),e([X({type:Number})],Qi.prototype,"specialityId",void 0),e([X({type:String})],Qi.prototype,"reschedulingAppointmentId",void 0),e([X({type:String})],Qi.prototype,"windowStartDate",void 0),e([X({type:String,attribute:"error-message"})],Qi.prototype,"errorMessage",void 0),e([X({type:String})],Qi.prototype,"specialtyName",void 0),e([R({context:Ue,subscribe:!0})],Qi.prototype,"patient",void 0),Qi=e([H(),t("days-window-view")],Qi);const Ri=G`:host{display:flex;flex-direction:column;gap:var(--sp-4);max-width:var(--content-max-width);margin:0 auto}`;let Ui=class CalendarView extends Z{constructor(){super(...arguments),this.reschedulingAppointmentId=void 0,this.initialDate=void 0,this.specialtyName=void 0,this.currentMonth=void 0,this.getScheduleServiceProfessionalSlotsQuery=new i(this,()=>{const e=this.patient.timezone,t=M(new Date,e),i=Ve(ze(this.displayedMonth),"yyyy-MM-dd"),s=i<t?t:i,a=Ve(je(qe(s)),"yyyy-MM-dd");return Ti(this.apiClient,{service_id:this.serviceId,professional_hash:this.professionalId,starts_at:E(A(s,e)),finishes_at:E(I(a,e)),rescheduling_appointment_id:this.reschedulingAppointmentId})})}static{this.styles=Ri}get displayedMonth(){return this.currentMonth??qe(this.initialDate??M(new Date,this.patient.timezone))}render(){const e=new Date,t=this.getScheduleServiceProfessionalSlotsQuery.result?.data,i=this.getScheduleServiceProfessionalSlotsQuery.result?.isPending,s=!0===t?.meta?.high_demand,a=t?.data?.filter(t=>Pe(_(t.starts_at),e)&&t.status===j.available),r=a&&a.length>0?Array.from(new Set(a.map(e=>M(_(e.starts_at),this.patient.timezone)))):void 0,o=oe().replace("_","-");return J`${s?J`<high-demand-callout .specialtyName="${this.specialtyName}"></high-demand-callout>`:K}<mq-calendar locale="${o}" ?is-loading="${i}" .timezone="${this.patient.timezone}" .currentMonth="${this.displayedMonth.toISOString()}" .availableDays="${r}" @prev-month="${e=>{this.currentMonth=new Date(e.detail.currentMonth)}}" @next-month="${e=>{this.currentMonth=new Date(e.detail.currentMonth)}}"></mq-calendar>`}};e([R({context:s,subscribe:!0})],Ui.prototype,"apiClient",void 0),e([X({type:String})],Ui.prototype,"professionalId",void 0),e([X({type:String})],Ui.prototype,"serviceId",void 0),e([X({type:String})],Ui.prototype,"reschedulingAppointmentId",void 0),e([X({type:String})],Ui.prototype,"initialDate",void 0),e([X({type:String})],Ui.prototype,"specialtyName",void 0),e([R({context:Ue,subscribe:!0})],Ui.prototype,"patient",void 0),e([Y()],Ui.prototype,"currentMonth",void 0),Ui=e([t("calendar-view")],Ui);class SuccessEvent extends Event{static{this.eventName="success"}constructor(e){super(SuccessEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}const Wi=G`: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 Hi=class SelectSlotStep extends Z{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:S(e,"schedule-service-specialities",t),queryFn:()=>e.schedules.getScheduleServiceSpecialities(t),staleTime:x,...i};var e,t,i}),this.getOrganizationSpecialtiesQuery=new i(this,()=>d(this.apiClient)),this.view="days-window",this.windowStartDate=void 0}static{this.styles=Wi}get specialtyName(){const e=this.professional?.speciality?.id;if(e)return this.getOrganizationSpecialtiesQuery.result?.data?.find(t=>t.id===e)?.name}connectedCallback(){super.connectedCallback(),this.initialDate&&(this.windowStartDate=this.initialDate)}willUpdate(e){e.has("errorMessage")&&this.errorMessage&&this.queryClientContext?.invalidateQueries({queryKey:S(this.apiClient)})}renderView(){return"days-window"===this.view?J`<days-window-view .errorMessage="${this.errorMessage}" .professionalId="${this.professionalId}" .serviceId="${this.serviceId}" .specialityId="${this.professional?.speciality?.id}" .reschedulingAppointmentId="${this.reschedulingAppointmentId}" .specialtyName="${this.specialtyName}" .windowStartDate="${this.windowStartDate}" @to-calendar-view="${()=>{this.view="calendar"}}" @slot-select="${e=>{this.dispatchEvent(new SuccessEvent({slot:e.detail.slot}))}}" @slot-unavailable="${()=>{this.errorMessage=U("Este horario no está disponible. Por favor, seleccione otro.")}}"></days-window-view>`:J`<calendar-view .professionalId="${this.professionalId}" .serviceId="${this.serviceId}" .reschedulingAppointmentId="${this.reschedulingAppointmentId}" .specialtyName="${this.specialtyName}" .initialDate="${this.initialDate}" @date-select="${e=>{this.windowStartDate=Ve(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 J`<mq-page-title .title="${"schedule"===this.kind?U("Petición de cita"):U("Modificar cita")}" .showBack="${this.showBack}" @mq-back="${e=>it(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([R({context:s,subscribe:!0})],Hi.prototype,"apiClient",void 0),e([X({type:String})],Hi.prototype,"kind",void 0),e([X({type:Boolean})],Hi.prototype,"showBack",void 0),e([X({type:String})],Hi.prototype,"serviceId",void 0),e([X({type:String})],Hi.prototype,"professionalId",void 0),e([X({type:String})],Hi.prototype,"reschedulingAppointmentId",void 0),e([X({type:Object})],Hi.prototype,"professional",void 0),e([X({type:String})],Hi.prototype,"startsAt",void 0),e([X({type:Number})],Hi.prototype,"duration",void 0),e([X({type:String})],Hi.prototype,"channel",void 0),e([X({type:String,attribute:"error-message"})],Hi.prototype,"errorMessage",void 0),e([X({type:String})],Hi.prototype,"initialDate",void 0),e([X({type:Object})],Hi.prototype,"service",void 0),e([X({type:Object})],Hi.prototype,"appliedDiscount",void 0),e([R({context:ke,subscribe:!0})],Hi.prototype,"queryClientContext",void 0),e([Y()],Hi.prototype,"view",void 0),e([Y()],Hi.prototype,"windowStartDate",void 0),Hi=e([H(),t("select-slot-step")],Hi);let Ki=class SelectSlotStepSkeleton extends Z{constructor(){super(...arguments),this.showTitle=!0}static{this.styles=G`: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 J`${this.showTitle?J`<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>`:K}<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 Gi(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([X({type:Boolean,attribute:"show-title"})],Ki.prototype,"showTitle",void 0),Ki=e([t("select-slot-step-skeleton")],Ki),ne();class AppointmentCreatedEvent extends Event{static{this.eventName="appointment-created"}constructor(e){super(AppointmentCreatedEvent.eventName,{bubbles:!0,composed:!0}),this.detail=e}}let Zi=class MqSchedule extends Z{constructor(){super(...arguments),this.requiresPayment=!0,this.showBackButton=!0,this.checkoutMode="embed",this._patient=new N(this,{context:Ue,initialValue:{hash:"",name:"",timezone:"UTC"}}),this.apiClient=L(),this._emittedCreated=!1,this._organizationChanged=!1,this.getAppointmentQuery=new i(this,()=>r(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:S(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:He(this.defaultService,e)?.id,speciality_id:We(this.defaultSpecialty,t)},a={enabled:!!(this.defaultSlotId&&this.token&&e&&t)},{queryKey:S(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,()=>$(this.apiClient)),this.getOrganizationSetupQuery=new i(this,()=>o(this.apiClient,{enabled:"reschedule"===this.kind}))}static{this.styles=G`.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)}`}connectedCallback(){super.connectedCallback(),void 0===this._returned&&(this._returned=function(e){const t=new URLSearchParams(e),i=t.get("status");if("success"!==i&&"error"!==i)return null;const s=t.get("reference");return"success"===i&&s?{status:i,reference:s}:{status:"error",expired:"expired"===t.get("reason")}}(window.location.search),this._returned&&window.history.replaceState(window.history.state,"",Ze(window.location.href)))}firstUpdated(){"success"===this._returned?.status&&this._emitCreated(this._returned.reference)}willUpdate(e){e.has("env")&&this.env&&re(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._returned=null),this._organizationChanged=t,e.has("locale")&&this.locale&&le(this.locale)&&de(this.locale);const i=B(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:T(s),timezone:F(this.timezone,this.loginToken?.patient?.timezone)})}_returnError(){return"error"===this._returned?.status?{error:!0,expired:this._returned.expired}:{}}_current(e){return this._organizationChanged?void 0:e}_initWizard(e,t,i){return this._wizard||(this._wizard=new Qe(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 q({source:"mq-schedule"}))},update:t=>e.reconcile(t),onCreated:e=>this._emitCreated(e),onAuthRequired:e=>{this.dispatchEvent(new AuthRequiredEvent(e))}}}_emitCreated(e){this._emittedCreated||(this._emittedCreated=!0,this.dispatchEvent(new AppointmentCreatedEvent({appointmentId:e})))}_hostConfig(){const e=this.getPatientProfileQuery.result?.data;return{apiKey:this.apiKey??this.apiClient.getApiKey(),token:this.token,env:this.env,countryCode:e?.profile.billing.country_code??void 0,checkoutMode:this.checkoutMode}}_renderStep(e,t){const i=e.canGoBack||this.showBackButton;return Re(this.apiKey??"",function(e,t,i,s,a,r){const o=t.expired?U("La reserva de este horario ha caducado. Por favor, seleccione otro."):U("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 J`<select-professional-step .showBack="${d}" .defaultSpecialty="${t.specialty}" .defaultService="${t.service?.id}" .errorMessage="${t.error?o:void 0}" @show-full-schedule="${e=>{i.goTo("selectSlot",{service:e.detail.service,specialty:e.detail.specialtyId,professional:Gi(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:Gi(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?J`<select-slot-step kind="reschedule" .showBack="${d}" .errorMessage="${t.error?o: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>`:K}if(!l)return K;const e=t.service;return e?J`<select-slot-step kind="schedule" .showBack="${d}" .errorMessage="${t.error?o: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>`:J`<select-slot-step-skeleton></select-slot-step-skeleton>`}if("completeProfile"===e){const e=t.slot;return s?e&&s.service_id&&n?J`<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>`:K:e&&l&&t.service?J`<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>`:K}if("confirm"===e){const e=t.slot;return s?e&&s.service_id&&n?J`<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,expired:!1},{replace:!0})}"></confirm-step>`:K:e&&l&&t.service?J`<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}" @back="${i.back}" @success="${e=>i.onCreated(e.detail.appointmentId)}" @discount-applied="${e=>i.update({appliedDiscount:e.detail})}" @payment-started="${e=>i.next({booking:e.detail.booking})}" @error="${()=>i.goTo("selectSlot",{error:!0,expired:!1},{replace:!0})}"></confirm-step>`:K}if("payment"===e){const e=l,s=t.slot;return e&&s?J`<payment-step .showBack="${d}" .professional="${e}" .startsAt="${s.starts_at}" .duration="${s.duration}" .channel="${t.service?.channel??s.channel}" .service="${t.service}" .scheduleSlot="${s}" .appliedDiscount="${t.appliedDiscount??null}" .booking="${t.booking??null}" .apiKey="${r?.apiKey}" .token="${r?.token}" .env="${r?.env??"production"}" .locale="${oe()}" .countryCode="${r?.countryCode??"ES"}" .checkoutMode="${r?.checkoutMode??"embed"}" @back="${i.back}" @success="${e=>i.onCreated(e.detail.appointmentId)}" @discount-applied="${e=>i.update({appliedDiscount:e.detail})}" @payment-success="${e=>i.onCreated(e.detail.appointmentId)}" @error="${e=>{e.detail?.expired&&i.goTo("selectSlot",{error:!0,expired:!0},{replace:!0})}}"></payment-step>`:K}return K}(e.current,e.ctx,this._stepHandlers(e),t,{showBack:i,isAuthenticated:!!this.token},this._hostConfig()))}renderReschedulePolicyBlocked(){return J`<div class="reschedule-policy-blocked"><p>${U("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 q({source:"mq-schedule"}))}">${U("Volver")}</mq-button></div>`}render(){const e=J`<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&&O(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 r=s?.data?.appointments?.seconds_before_start_to_refund_on_cancel;if(!D({startsAtIso:a.start_date,refundPolicySeconds:r}))return this.renderReschedulePolicyBlocked();const o=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,booking:void 0,appliedDiscount:void 0,profileComplete:e.profileComplete,requiresPayment:!1,error:!1}}({appointment:a,profileComplete:t}),n=this._initWizard(tt,o);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 r=s?a?.data:void 0,o="available"===r?.status,n=s&&o,l=Ke({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(et,{...l,slot:o?r:void 0,error:s&&!o,...this._returnError()},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??(o?r:void 0)}),this._renderStep(d,void 0)}const i=Ke({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(Ye,{...i,...this._returnError()});return s.reconcile({profileComplete:t,service:i.service??s.ctx.service,specialty:s.ctx.specialty??i.specialty}),this._renderStep(s,void 0)}};e([X({type:String,attribute:"default-specialty"})],Zi.prototype,"defaultSpecialty",void 0),e([X({type:String,attribute:"default-service"})],Zi.prototype,"defaultService",void 0),e([X({type:String,attribute:"default-professional-hash"})],Zi.prototype,"defaultProfessionalHash",void 0),e([X({type:String,attribute:"default-slot-id"})],Zi.prototype,"defaultSlotId",void 0),e([X({type:String,attribute:"kind"})],Zi.prototype,"kind",void 0),e([X({type:Boolean,attribute:"requires-payment"})],Zi.prototype,"requiresPayment",void 0),e([X({type:String,attribute:"appointment-id"})],Zi.prototype,"appointmentId",void 0),e([X({type:Boolean,attribute:"show-back-button",converter:{fromAttribute:e=>null===e||"false"!==e&&"0"!==e,toAttribute:e=>e?"":"false"}})],Zi.prototype,"showBackButton",void 0),e([X({type:String,attribute:"checkout-mode"})],Zi.prototype,"checkoutMode",void 0),e([X({type:String,attribute:"api-key"})],Zi.prototype,"apiKey",void 0),e([X({type:String,attribute:"token"})],Zi.prototype,"token",void 0),e([X({type:String,attribute:"locale"})],Zi.prototype,"locale",void 0),e([X({type:String,attribute:"env"})],Zi.prototype,"env",void 0),e([X({type:String,attribute:"timezone"})],Zi.prototype,"timezone",void 0),e([R({context:a,subscribe:!0})],Zi.prototype,"loginToken",void 0),e([R({context:s,subscribe:!0}),Y()],Zi.prototype,"inheritedApiClient",void 0),e([Q({context:s}),Y()],Zi.prototype,"apiClient",void 0),Zi=e([H(),t("mq-schedule")],Zi);export{AppointmentCreatedEvent as A,Zi as M,AuthRequiredEvent as a};