All files / src/components/Appointment AppointmentSelection.vue

91.07% Statements 837/919
84.69% Branches 249/294
62.06% Functions 18/29
91.07% Lines 837/919

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279  1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           9x   9x 9x 9x 9x   9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x 9x   9x 9x 9x   9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x 148x       148x 148x 148x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x         1x 1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x             1x 1x                         1x                 1x 1x         1x       1x 1x 1x 1x 1x 1x 1x 1x   1x                         1x   1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x 1x             1x 1x 1x 1x   1x   1x 1x   1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x   1x   1x   1x           1x   1x 69x 69x 69x   1x 69x 69x   1x 166x     166x   166x 121x   98x   98x 373x 373x   373x 334x 334x 373x 98x   121x 97x 97x 97x 97x 97x 166x   166x 166x 31x 31x 31x 166x 166x 1x   1x 131x   131x 84x 266x 266x 84x   131x 1x   1x 131x   131x 84x 266x 266x 84x   131x 1x   1x 75x 1x   1x 154x     154x   154x 105x   85x   85x 297x 297x 297x   297x 110x 110x 297x 85x   105x 84x 84x 84x 84x 84x 154x   154x 154x 30x 30x 30x 154x 154x 1x   1x 131x 56x 56x   86x 1x   1x 131x 74x 74x   104x 1x   1x 90x 3x 87x 1x   1x 95x 95x 95x 95x 95x 95x 95x   1x 1x 1x 1x 1x 1x   1x 7x 7x             7x   7x     7x 1x 1x   6x 7x 7x   7x     2x 2x 2x   7x   2x 7x   1x 9x 9x 6x 9x   9x   1x     121x 62x 62x 62x 121x 1x   1x 187x 116x 116x   71x 71x 82x 70x 71x 1x   1x                   1x 7x           7x 1x 1x   6x 6x 6x 6x     7x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                           7x   1x   207x 207x 207x     207x 207x 74x 207x 2x 2x     207x 135x 135x   70x 70x 82x 70x 70x   207x 1x   1x   138x 138x 138x   138x 1x       1x     1x 1x 1x       1x         1x 152x 152x 152x 152x 152x 152x 1x   1x 10x 10x 10x     2x 2x 4x 2x   2x 2x 2x 2x 2x 2x 1x   1x 70x 1x   1x               1x                 1x 159x     1x 1x     1x   12x 4x 4x 4x 4x 4x 4x   12x               8x 1x   1x 9x 9x 9x     1x   140x 140x 140x   140x   79x 79x 79x 79x 79x 79x 79x   61x   61x 61x 61x 61x 140x 140x 140x   61x 140x 140x 61x 52x 52x 119x 52x 140x 52x 52x   52x 31x 31x   52x 52x 52x 52x 52x 52x 52x 52x 52x     52x 140x 9x 9x 9x 140x   1x 98x 98x 98x     98x 98x 98x 98x           98x   98x 98x 98x 98x 98x 98x 98x 98x 98x   98x 98x 98x 98x   98x 98x 98x 98x     98x 9x 98x 89x 89x     98x 98x 9x 98x 5x 98x 93x     93x 98x                       98x   98x 98x 98x 98x 98x   55x 55x 55x 55x 55x 55x 122x 122x 55x 55x 118x       4x 4x 4x 4x     118x 42x 42x   118x 118x 118x 118x 6x 118x   118x 55x 55x   176x 176x 176x 176x 176x   176x 176x 205x 205x 205x 176x   176x 84x 84x 84x 84x 84x 84x   84x 84x 84x 84x 84x 84x 84x 84x     84x 84x 176x 176x   119x 119x 119x 119x 119x 119x 119x 119x   119x   14x 14x 18x 18x 18x 14x     14x 7x 7x 7x 7x 7x 7x 7x   14x 14x 14x   14x 14x 14x 14x 14x 14x 119x   45x 45x 38x 38x 45x 45x 45x 45x 45x   45x 45x 3x 3x 45x 3x 4x 4x 4x 4x 4x 4x   3x   3x         3x 45x   45x 45x   45x 45x 45x 45x   73x 73x 73x 73x 45x 21x 24x 45x   45x     45x 45x     45x 35x 35x     45x 45x 73x 73x   1x 65x   55x 55x 55x 55x 55x 55x 55x 55x     55x     55x 4x 24x 12x 12x 12x 24x 4x 55x 51x 51x     55x 118x 6x 118x   112x 112x 112x 55x     55x 55x 2x 2x   55x   55x 54x 54x   54x 54x 54x   54x 54x 54x 54x 54x 54x     55x 55x 55x 65x 65x 65x 55x 55x     55x 2x 2x 4x 4x 4x 2x 2x 2x 2x   55x 55x 116x 116x 55x 55x   55x 55x 1x   1x 3x 1x   1x 164x 82x 82x 1x   1x 67x 67x 66x 66x 66x 66x 1x   1x 56x 54x 54x 114x 114x 114x 54x 54x 54x 54x 1x   1x   180x 61x 61x 61x 89x 89x 61x 61x 61x 61x 61x   119x                         1x   1x 1x 1x   73x 73x 73x 73x 29x 29x 29x 29x 73x 44x 44x     73x 73x 73x     73x 73x 1x 1x                                                                                                                              
<template>
  <ProviderSelection
    :t="t"
    :selectableProviders="selectableProviders"
    :providersWithAppointments="providersWithAppointments"
    :selectedProvider="selectedProvider"
    :selectedProviders="selectedProviders"
    @update:selectedProviders="onUpdateSelectedProviders"
    :providerSelectionError="providerSelectionError"
  />
  <div
    v-if="
      availableDaysFetched &&
      (noProviderSelected ||
        (selectedProvider && !providersWithAppointments.length)) &&
      !isSwitchingProvider
    "
    class="m-component"
  >
    <h2 tabindex="0">{{ t("time") }}</h2>
    <muc-callout type="info">
      <template #header>
        <h3>{{ t("apiErrorNoAppointmentForThisScopeHeader") }}</h3>
      </template>
      <template #content>
        <div class="m-content">
          {{ t("apiErrorNoAppointmentForThisScopeText") }}
        </div>
        <div
          class="m-content"
          style="margin-top: 8px"
          v-if="noneSelectedAvailabilityInfoHtml"
        >
          <muc-button
            variant="ghost"
            icon="information"
            icon-shown-left
            class="no-bottom-margin"
            @click="openNoneSelectedInfoModal"
          >
            <template #default>{{ t("newAppointmentsInfoLink") }}</template>
          </muc-button>
        </div>
      </template>
    </muc-callout>
  </div>
  <div v-else-if="!error && hasSelectedProviderWithAppointments">
    <CalendarListToggle
      :t="t"
      :isListView="isListView"
      @update:isListView="isListView = $event"
    />
    <CalendarView
      ref="calendarViewRef"
      v-if="!isListView"
      :t="t"
      :selectedDay="selectedDay"
      :calendarKey="calendarKey"
      :allowedDates="allowedDates"
      :minDate="minDate"
      :maxDate="maxDate"
      :viewMonth="viewMonth"
      :timeSlotsInHoursByOffice="timeSlotsInHoursByOffice"
      :timeSlotsInDayPartByOffice="timeSlotsInDayPartByOffice"
      :currentHour="currentHour"
      :firstHour="firstHour"
      :lastHour="lastHour"
      :currentDayPart="currentDayPart"
      :firstDayPart="firstDayPart"
      :lastDayPart="lastDayPart"
      :selectableProviders="selectableProviders"
      :selectedProviders="selectedProviders"
      :providersWithAppointments="providersWithAppointments"
      :appointmentsCount="appointmentsCount"
      :isLoadingAppointments="isLoadingAppointments"
      :isLoadingComplete="isLoadingComplete"
      :availabilityInfoHtml="availabilityInfoHtml"
      :officeNameById="officeNameById"
      :isSlotSelected="isSlotSelected"
      @update:selectedDay="handleDaySelection"
      @selectTimeSlot="
        ({ officeId, time }) =>
          handleTimeSlotSelection(officeId as number, time)
      "
      @setSelectedHour="(h) => (selectedHour = h as number | null)"
      @setSelectedDayPart="(p) => (selectedDayPart = p as any)"
      @openInfo="openAvailabilityInfoModal"
    />
 
    <ListView
      ref="listViewRef"
      v-if="isListView"
      :t="t"
      :isLoadingAppointments="isLoadingAppointments"
      :availabilityInfoHtml="availabilityInfoHtml"
      :selectableProviders="selectableProviders"
      :selectedProviders="selectedProviders"
      :providersWithAppointments="providersWithAppointments"
      :officeNameById="officeNameById"
      :isSlotSelected="isSlotSelected"
      :availableDays="availableDays"
      :datesWithoutAppointments="datesWithoutAppointments"
      :appointmentTimestampsByOffice="appointmentTimestampsByOffice"
      :officeOrder="officeOrder"
      @update:selectedDay="handleDaySelection"
      @selectTimeSlot="
        ({ officeId, time }) =>
          handleTimeSlotSelection(officeId as number, time)
      "
      @openInfo="openAvailabilityInfoModal"
    />
    <div ref="summary">
      <AppointmentPreview
        :t="t"
        :selectedProvider="selectedProvider"
        :selectedDay="selectedDay"
        :selectedTimeslot="selectedTimeslot"
        :selectedService="selectedService"
      />
    </div>
  </div>
  <div
    v-if="!noProviderSelected && showError && !isSwitchingProvider"
    class="m-component"
  >
    <h2 tabindex="0">{{ t("time") }}</h2>
    <muc-callout :type="toCalloutType(apiErrorTranslation.errorType)">
      <template #header>
        <h3>{{ t(apiErrorTranslation.headerKey) }}</h3>
      </template>
      <template #content>
        <div class="m-content">{{ t(apiErrorTranslation.textKey) }}</div>
        <div
          class="m-content"
          style="margin-top: 8px"
          v-if="
            (apiErrorTranslation.textKey ===
              'apiErrorNoAppointmentForThisScopeText' ||
              apiErrorTranslation.textKey ===
                'apiErrorNoAppointmentForThisDayText') &&
            availabilityInfoHtml
          "
        >
          <muc-button
            variant="ghost"
            icon="information"
            icon-shown-left
            class="no-bottom-margin"
            @click="openAvailabilityInfoModal"
          >
            <template #default>{{ t("newAppointmentsInfoLink") }}</template>
          </muc-button>
        </div>
      </template>
    </muc-callout>
  </div>
  <div class="m-button-group">
    <muc-button
      v-if="!isRebooking"
      icon="arrow-left"
      icon-shown-left
      variant="secondary"
      @click="previousStep"
    >
      <template #default>{{ t("back") }}</template>
    </muc-button>
    <muc-button
      :disabled="
        selectedTimeslot === 0 ||
        !selectedDay ||
        loadingStates.isReservingAppointment.value
      "
      :icon="'arrow-right'"
      @click="nextStep"
    >
      <template #default>
        <span>{{ t("next") }}</span>
      </template>
    </muc-button>
  </div>
  <AvailabilityInfoModal
    :show="showAvailabilityInfoModal"
    :html="availabilityInfoHtmlForModal"
    :closeAriaLabel="t('closeDialog')"
    @close="closeAvailabilityInfoModal"
  />
</template>
<script setup lang="ts">
import type { CalloutType } from "@/utils/callout";
import type { ApiErrorTranslation } from "@/utils/errorHandler";
import type { Ref } from "vue";
 
import { MucButton, MucCallout } from "@muenchen/muc-patternlab-vue";
import {
  computed,
  inject,
  nextTick,
  onMounted,
  onUnmounted,
  ref,
  watch,
} from "vue";
 
import { AvailableDaysDTO } from "@/api/models/AvailableDaysDTO";
import { AvailableTimeSlotsByOfficeDTO } from "@/api/models/AvailableTimeSlotsByOfficeDTO";
import { OfficeAvailableTimeSlotsDTO } from "@/api/models/OfficeAvailableTimeSlotsDTO";
import {
  fetchAvailableDays,
  fetchAvailableTimeSlots,
} from "@/api/ZMSAppointmentAPI";
import { OfficeImpl } from "@/types/OfficeImpl";
import {
  SelectedServiceProvider,
  SelectedTimeslotProvider,
} from "@/types/ProvideInjectTypes";
import { toCalloutType } from "@/utils/callout";
import {
  createErrorStates,
  getApiErrorTranslation,
  handleApiResponse,
} from "@/utils/errorHandler";
import {
  berlinHourFormatter,
  convertDateToString,
} from "@/utils/formatAppointmentDateTime";
import { generateAvailabilityInfoHtml } from "@/utils/infoForAllAppointments";
import { sanitizeHtml } from "@/utils/sanitizeHtml";
import AppointmentPreview from "./AppointmentSelection/AppointmentPreview.vue";
import AvailabilityInfoModal from "./AppointmentSelection/AvailabilityInfoModal.vue";
import CalendarListToggle from "./AppointmentSelection/CalendarListToggle.vue";
import CalendarView from "./AppointmentSelection/CalendarView.vue";
import ListView from "./AppointmentSelection/ListView.vue";
import ProviderSelection from "./AppointmentSelection/ProviderSelection.vue";
 
const props = defineProps<{
  baseUrl: string | undefined;
  isRebooking: boolean;
  exclusiveLocation: string | undefined;
  preselectedOfficeId: string | undefined;
  selectedServiceMap: Map<string, number>;
  captchaToken: string | null;
  bookingError: boolean;
  bookingErrorKey: string;
  errorType?: CalloutType;
  t: (key: string) => string;
}>();
 
const emit = defineEmits<(e: "next" | "back") => void>();
 
const { selectedService } = inject<SelectedServiceProvider>(
  "selectedServiceProvider"
) as SelectedServiceProvider;
 
const { selectedProvider, selectedTimeslot } = inject<SelectedTimeslotProvider>(
  "selectedTimeslot"
) as SelectedTimeslotProvider;
 
const loadingStates = inject("loadingStates", {
  isReservingAppointment: ref(false),
  isUpdatingAppointment: ref(false),
  isBookingAppointment: ref(false),
  isCancelingAppointment: ref(false),
}) as {
  isReservingAppointment: Ref<boolean>;
  isUpdatingAppointment: Ref<boolean>;
  isBookingAppointment: Ref<boolean>;
  isCancelingAppointment: Ref<boolean>;
};
 
const selectableProviders = ref<OfficeImpl[]>();
const availableDays = ref<Array<{ time: string; providerIDs: string }>>();
const selectedHour = ref<number | null>(null);
const selectedDayPart = ref<"am" | "pm" | null>(null);
 
const appointmentsCount = ref<number>(0);
 
const appointmentTimestampsByOffice = ref<OfficeAvailableTimeSlotsDTO[]>([]);
const appointmentTimestamps = ref<number[]>([]);
 
const errorStates = createErrorStates();
const errorStateMap = computed(() => errorStates.errorStateMap);
const currentErrorData = computed(() => errorStates.currentErrorData);
 
const error = ref<boolean>(false);
const showError = computed(() => error.value || props.bookingError);
 
const selectedDay = ref<Date>();
const minDate = ref<Date>();
const maxDate = ref<Date>();
const viewMonth = ref<Date>(new Date());
const officeOrder = ref<Map<number, number>>(new Map());
const calendarKey = ref(0);
 
const selectedProviders = ref<{ [id: string]: boolean }>({});
const listViewRef = ref<any>();
const calendarViewRef = ref<any>();
 
let initialized = false;
const availableDaysFetched = ref(false);
const isLoadingAppointments = ref(false);
const isSwitchingProvider = ref(false);
 
const datesWithoutAppointments = ref(new Set<string>());
 
const isLoadingComplete = ref(false);
 
let refetchTimer: ReturnType<typeof setTimeout> | undefined;
 
/**
 * Reference to the appointment summary.
 * After selecting a time slot, the focus is placed on the appointment summary.
 */
const summary = ref<HTMLElement | null>(null);
 
const getOfficeById = (id: number | string): OfficeImpl | undefined => {
  const idStr = String(id);
  return (selectableProviders.value || []).find((p) => String(p.id) === idStr);
};
 
const officeNameById = (id: number | string): string | null => {
  return getOfficeById(id)?.name ?? null;
};
 
const timeSlotsInHoursByOffice = computed(() => {
  const offices = new Map<
    number,
    { officeId: number; appointments: Map<number, number[]> }
  >();
 
  appointmentTimestampsByOffice.value.forEach((office) => {
    if (!selectedProviders.value[office.officeId]) return;
 
    const timesByHours = new Map<number, number[]>();
 
    office.appointments?.forEach?.((time) => {
      const berlinDate = new Date(time * 1000);
      const hour = parseInt(berlinHourFormatter.format(berlinDate));
 
      if (!timesByHours.has(hour)) {
        timesByHours.set(hour, []);
      }
      timesByHours.get(hour)?.push(time);
    });
 
    if (timesByHours.size > 0) {
      offices.set(office.officeId, {
        officeId: office.officeId,
        appointments: timesByHours,
      });
    }
  });
 
  return new Map(
    [...offices.entries()].sort((a, b) => {
      const indexA = officeOrder.value.get(a[0]) ?? Infinity;
      const indexB = officeOrder.value.get(b[0]) ?? Infinity;
      return indexA - indexB;
    })
  );
});
 
const firstHour = computed(() => {
  let min = Infinity;
 
  for (const [, office] of timeSlotsInHoursByOffice.value) {
    for (const hour of office.appointments.keys()) {
      min = Math.min(min, hour);
    }
  }
 
  return min === Infinity ? null : min;
});
 
const lastHour = computed(() => {
  let max = -Infinity;
 
  for (const [, office] of timeSlotsInHoursByOffice.value) {
    for (const hour of office.appointments.keys()) {
      max = Math.max(max, hour);
    }
  }
 
  return max === -Infinity ? null : max;
});
 
const currentHour = computed(() => {
  return selectedHour.value !== null ? selectedHour.value : firstHour.value;
});
 
const timeSlotsInDayPartByOffice = computed(() => {
  const offices = new Map<
    number,
    { officeId: number; appointments: Map<string, number[]> }
  >();
 
  appointmentTimestampsByOffice.value.forEach((office) => {
    if (!selectedProviders.value[office.officeId]) return;
 
    const timesByPartOfDay = new Map<string, number[]>();
 
    office.appointments?.forEach?.((time) => {
      const berlinDate = new Date(time * 1000);
      const hour = parseInt(berlinHourFormatter.format(berlinDate));
      const dayPart = hour >= 12 ? "pm" : "am";
 
      if (!timesByPartOfDay.has(dayPart)) {
        timesByPartOfDay.set(dayPart, []);
      }
      timesByPartOfDay.get(dayPart)?.push(time);
    });
 
    if (timesByPartOfDay.size > 0) {
      offices.set(office.officeId, {
        officeId: office.officeId,
        appointments: timesByPartOfDay,
      });
    }
  });
 
  return new Map(
    [...offices.entries()].sort((a, b) => {
      const indexA = officeOrder.value.get(a[0]) ?? Infinity;
      const indexB = officeOrder.value.get(b[0]) ?? Infinity;
      return indexA - indexB;
    })
  );
});
 
const firstDayPart = computed(() => {
  for (const [, office] of timeSlotsInDayPartByOffice.value) {
    if (office.appointments.has("am")) return "am";
  }
 
  return "pm";
});
 
const lastDayPart = computed(() => {
  for (const [, office] of timeSlotsInDayPartByOffice.value) {
    if (office.appointments.has("pm")) return "pm";
  }
 
  return "am";
});
 
const currentDayPart = computed(() => {
  return selectedDayPart.value !== null
    ? selectedDayPart.value
    : firstDayPart.value;
});
 
const showSelectionForProvider = async (provider: OfficeImpl) => {
  isSwitchingProvider.value = true;
  selectedProvider.value = provider;
  error.value = false;
  selectedDay.value = undefined;
  selectedTimeslot.value = 0;
  await refetchAvailableDaysForSelection();
};
 
const TODAY = new Date();
const MAXDATE = new Date(
  TODAY.getFullYear(),
  TODAY.getMonth() + 6,
  TODAY.getDate()
);
 
const allowedDates = (date: Date) => {
  const beforeMaxDate =
    date.getFullYear() < MAXDATE.getFullYear() ||
    (date.getFullYear() === MAXDATE.getFullYear() &&
      date.getMonth() < MAXDATE.getMonth()) ||
    (date.getFullYear() === MAXDATE.getFullYear() &&
      date.getMonth() === MAXDATE.getMonth() &&
      date.getDate() < MAXDATE.getDate());
 
  if (!beforeMaxDate) return false;
 
  const dateString = convertDateToString(date);
 
  // Check if this date is known to have no appointments
  if (datesWithoutAppointments.value.has(dateString)) {
    return false;
  }
 
  const dayEntry = availableDays.value?.find(
    (day) => convertDateToString(new Date(day.time)) === dateString
  );
 
  if (!dayEntry) return false;
 
  // Check if the date has appointments for the selected providers
  const hasAppointments = dayEntry.providerIDs
    .split(",")
    .some((id) => selectedProviders.value[id]);
 
  if (!hasAppointments) return false;
 
  return true;
};
 
const hasAppointmentsForSelectedProviders = () => {
  return (
    availableDays?.value?.some((day) =>
      day.providerIDs.split(",").some((id) => selectedProviders.value[id])
    ) || false
  );
};
 
const providersWithAppointments = computed(() => {
  // Always return all selectable providers to maintain UI state
  // The filtering for calendar display happens in updateDateRangeForSelectedProviders
  return (selectableProviders.value || []).sort((a, b) => {
    const aPriority = a.priority ?? -Infinity;
    const bPriority = b.priority ?? -Infinity;
    return bPriority - aPriority;
  });
});
 
const hasSelectedProviderWithAppointments = computed(() => {
  if (!availableDays?.value || availableDays.value.length === 0) {
    return false;
  }
 
  return Object.entries(selectedProviders.value).some(
    ([id, isSelected]) =>
      isSelected &&
      providersWithAppointments.value.some((p) => p.id.toString() === id)
  );
});
 
const handleTimeSlotSelection = async (officeId: number, timeSlot: number) => {
  selectedTimeslot.value = timeSlot;
  selectedProvider.value = getOfficeById(officeId);
  if (summary.value) {
    await nextTick();
    summary.value.focus();
    summary.value.scrollIntoView({ behavior: "smooth", block: "center" });
  }
};
 
const handleDaySelection = async (day: any) => {
  if (!(day instanceof Date)) {
    // Don't allow deselection - if day is not a Date, ignore the selection
    return;
  }
 
  // If the same date is already selected, don't do anything
  if (selectedDay.value && selectedDay.value.getTime() === day.getTime()) {
    return;
  }
 
  selectedDay.value = day;
  selectedTimeslot.value = 0;
  selectedHour.value = null;
  selectedDayPart.value = null;
 
  // Reset to earliest available appointment
  if (timeSlotsInHoursByOffice.value.size > 0) {
    // For hourly view
    const allHours = Array.from(
      timeSlotsInHoursByOffice.value.values()
    ).flatMap((office) => {
      const hours = Array.from((office as any).appointments.keys());
      return hours.filter((hour) => typeof hour === "number" && hour >= 0);
    });
    if (allHours.length > 0) {
      selectedHour.value = Math.min(...(allHours as number[]));
    }
  } else if (timeSlotsInDayPartByOffice.value.size > 0) {
    // For am/pm view
    const allDayParts = Array.from(
      timeSlotsInDayPartByOffice.value.values()
    ).flatMap((office) => {
      const dayParts = Array.from((office as any).appointments.keys());
      return dayParts.filter((part) => part === "am" || part === "pm");
    });
    if (allDayParts.includes("am")) {
      selectedDayPart.value = "am";
    } else if (allDayParts.includes("pm")) {
      selectedDayPart.value = "pm";
    }
  }
};
 
const providerSelectionError = computed(() => {
  // Check if any providers are selected
  const selectedProviderIds = Object.keys(selectedProviders.value).filter(
    (id) => selectedProviders.value[id]
  );
 
  // If no providers are selected at all, show error
  if (
    selectedProviderIds.length === 0 &&
    providersWithAppointments.value.length > 0
  ) {
    return props.t("errorMessageProviderSelection");
  }
 
  // If available days is empty (no data fetched), don't show error yet
  if (!availableDays?.value || availableDays.value.length === 0) {
    return "";
  }
 
  const hasSelection = Object.entries(selectedProviders.value).some(
    ([id, isSelected]) =>
      isSelected &&
      providersWithAppointments.value.some((p) => p.id.toString() === id)
  );
 
  return hasSelection ? "" : props.t("errorMessageProviderSelection");
});
 
const noProviderSelected = computed(() => {
  // Check if any providers are selected
  const selectedProviderIds = Object.keys(selectedProviders.value).filter(
    (id) => selectedProviders.value[id]
  );
 
  return selectedProviderIds.length === 0;
});
 
// Threshold moved to constants
 
const isListView = ref(false);
 
// Modal state and handlers
const showAvailabilityInfoModal = ref(false);
const availabilityInfoHtmlOverride = ref("");
const openAvailabilityInfoModal = () => {
  availabilityInfoHtmlOverride.value = "";
  showAvailabilityInfoModal.value = true;
};
const closeAvailabilityInfoModal = () => {
  showAvailabilityInfoModal.value = false;
  availabilityInfoHtmlOverride.value = "";
};
 
const availabilityInfoHtml = computed(() => {
  return generateAvailabilityInfoHtml(
    selectedProviders.value,
    selectableProviders.value,
    selectedProvider.value,
    sanitizeHtml
  );
});
 
const noneSelectedAvailabilityInfoHtml = computed(() => {
  if (!noProviderSelected.value) return "";
  const providers = selectableProviders.value || [];
  if (providers.length === 0) return "";
 
  // Build a synthetic selection that includes all selectable providers
  const allSelectedMap: Record<string, boolean> = {};
  providers.forEach((p: any) => {
    if (p?.id != null) allSelectedMap[String(p.id)] = true;
  });
 
  return generateAvailabilityInfoHtml(
    allSelectedMap,
    selectableProviders.value,
    undefined,
    sanitizeHtml
  );
});
 
const availabilityInfoHtmlForModal = computed(() => {
  return availabilityInfoHtmlOverride.value || availabilityInfoHtml.value;
});
 
const openNoneSelectedInfoModal = () => {
  const html = noneSelectedAvailabilityInfoHtml.value;
  if (html) {
    availabilityInfoHtmlOverride.value = html;
    showAvailabilityInfoModal.value = true;
  }
};
 
const onUpdateSelectedProviders = (val: { [id: string]: boolean }) => {
  // Avoid unnecessary triggers when value is identical
  const current = JSON.stringify(selectedProviders.value);
  const next = JSON.stringify(val);
  if (current !== next) {
    selectedProviders.value = { ...val };
  }
};
 
const isSlotSelected = (officeId: number | string, time: number) =>
  selectedTimeslot.value === time &&
  selectedProvider.value?.id?.toString() === officeId.toString();
 
const nextStep = () => emit("next");
const previousStep = () => emit("back");
 
// API error handling
const apiErrorTranslation = computed<ApiErrorTranslation>(() => {
  // If we have a booking error from props, use that instead of our own error states
  if (props.bookingError && props.bookingErrorKey) {
    return {
      headerKey: `${props.bookingErrorKey}Header`,
      textKey: `${props.bookingErrorKey}Text`,
      errorType: props.errorType || "error", // Use prop if provided, otherwise default to "error"
    };
  }
  // If we're switching providers, don't show any error messages
  if (isSwitchingProvider.value) {
    return {
      headerKey: "",
      textKey: "",
      errorType: "error", // Default
    };
  }
  // Otherwise, use our own error states
  return getApiErrorTranslation(errorStateMap.value, currentErrorData.value);
});
 
const handleError = (data: any): void => {
  error.value = true;
  handleApiResponse(data, errorStateMap.value, currentErrorData.value);
};
 
// API calls
const refetchAvailableDaysForSelection = async (): Promise<void> => {
  // Only fetch available days for currently selected providers
  const selectedProviderIds = Object.keys(selectedProviders.value).filter(
    (id) => selectedProviders.value[id]
  );
 
  if (selectedProviderIds.length === 0) {
    // No providers selected, clear available days but keep providers visible
    availableDays.value = [];
    availableDaysFetched.value = true;
    error.value = false;
    isSwitchingProvider.value = false;
    updateDateRangeForSelectedProviders();
    return;
  }
 
  const providerIdsToQuery = selectedProviderIds.map(Number);
 
  const data = await fetchAvailableDays(
    providerIdsToQuery,
    Array.from(props.selectedServiceMap.keys()),
    Array.from(props.selectedServiceMap.values()),
    props.baseUrl ?? undefined,
    props.captchaToken ?? undefined
  );
 
  const days = (data as AvailableDaysDTO)?.availableDays;
  if (
    Array.isArray(days) &&
    days.length > 0 &&
    days.every(
      (d) =>
        typeof d === "object" && d !== null && "time" in d && "providerIDs" in d
    )
  ) {
    datesWithoutAppointments.value.clear();
    availableDays.value = days as { time: string; providerIDs: string }[];
    // Only set selectedDay on first load; otherwise preserve current selection
    if (!selectedDay.value) {
      selectedDay.value = new Date((days[0] as any).time);
    }
    // Keep viewMonth in sync with selectedDay and force calendar to re-render
    viewMonth.value = new Date(
      selectedDay.value.getFullYear(),
      selectedDay.value.getMonth(),
      1
    );
    calendarKey.value++;
    availableDaysFetched.value = true;
    error.value = false;
    isSwitchingProvider.value = false;
 
    // Update date range based on selected providers
    updateDateRangeForSelectedProviders();
  } else {
    handleError(data);
    isSwitchingProvider.value = false;
  }
};
 
const getAppointmentsOfDay = async (date: string): Promise<void> => {
  isLoadingAppointments.value = true;
  appointmentTimestamps.value = [];
  appointmentTimestampsByOffice.value = [];
 
  // Only fetch appointments for selected providers
  const selectedProviderIds = Object.keys(selectedProviders.value).filter(
    (id) => selectedProviders.value[id]
  );
  if (selectedProviderIds.length === 0) {
    // No providers selected, clear appointments
    isLoadingAppointments.value = false;
    return;
  }
 
  const providerIds = selectedProviderIds.map(Number);
 
  try {
    const data = await fetchAvailableTimeSlots(
      date,
      providerIds.map(Number),
      Array.from(props.selectedServiceMap.keys()),
      Array.from(props.selectedServiceMap.values()),
      props.baseUrl ?? undefined,
      props.captchaToken ?? undefined
    );
 
    if (data && "offices" in data && Array.isArray((data as any).offices)) {
      appointmentTimestampsByOffice.value = (
        data as AvailableTimeSlotsByOfficeDTO
      ).offices;
 
      appointmentsCount.value = (data as any).offices.reduce(
        (sum: number, office: any) => sum + (office.appointments?.length ?? 0),
        0
      );
 
      // Track dates without appointments
      if (appointmentsCount.value === 0) {
        datesWithoutAppointments.value.add(date);
      } else {
        datesWithoutAppointments.value.delete(date);
      }
 
      // Only show error if there are no appointments on any day
      if (
        appointmentsCount.value === 0 &&
        !hasAppointmentsForSelectedProviders()
      ) {
        error.value = true;
      } else {
        error.value = false;
 
        // Keep selectedDay; provider-change pipeline decides nearest available date
      }
    } else {
      // Track dates without appointments
      datesWithoutAppointments.value.add(date);
 
      // Only show error if there are no appointments on any day
      if (!hasAppointmentsForSelectedProviders()) {
        error.value = true;
      } else {
        error.value = false;
        // Keep selectedDay; provider-change pipeline decides nearest available date
      }
    }
  } catch (error) {
    // Handle any errors from fetchAvailableTimeSlots
  } finally {
    isLoadingAppointments.value = false;
    isLoadingComplete.value = true;
  }
};
 
function getAvailableProviders(
  providers: OfficeImpl[],
  selectedIds: number[]
): OfficeImpl[] {
  return Object.values(
    providers.reduce<Record<string, OfficeImpl[]>>((grouped, provider) => {
      (grouped[provider.name] ||= []).push(provider);
      return grouped;
    }, {})
  ).map((group) => {
    if (group.length === 1) return group[0];
 
    // clean = passport provider
    // restricted = default provider (hidden by passport related services)
    const clean = group.find((p) => (p.disabledByServices ?? []).length === 0);
    const restricted = group.find(
      (p) => (p.disabledByServices ?? []).length > 0
    );
 
    // Fallbacks if one type is missing
    if (!clean && !restricted) return group[0];
    if (!restricted) return clean as OfficeImpl;
    if (!clean) return restricted as OfficeImpl;
 
    const restrictedDisabled = (restricted.disabledByServices ?? []).map(
      Number
    );
    const allDisabled = selectedIds.every((id) =>
      restrictedDisabled.includes(id)
    );
 
    return allDisabled ? (clean as OfficeImpl) : (restricted as OfficeImpl);
  });
}
 
function updateDateRangeForSelectedProviders() {
  if (!availableDays.value) return [];
  const selectedProviderIds = Object.entries(selectedProviders.value)
    .filter(([_, isSelected]) => isSelected)
    .map(([id]) => Number(id));
 
  const availableDaysForSelectedProviders = (availableDays.value || []).filter(
    (day) =>
      day.providerIDs
        .split(",")
        .some((providerId) => selectedProviderIds.includes(Number(providerId)))
  );
 
  if (availableDaysForSelectedProviders.length > 0) {
    minDate.value = new Date(availableDaysForSelectedProviders[0].time);
    maxDate.value = new Date(
      availableDaysForSelectedProviders[
        availableDaysForSelectedProviders.length - 1
      ].time
    );
    // Ensure calendar updates min/max immediately
    if (selectedDay.value) {
      viewMonth.value = new Date(
        selectedDay.value.getFullYear(),
        selectedDay.value.getMonth(),
        1
      );
    }
    calendarKey.value++;
 
    // Validate that the currently selected date is still available for selected providers
    validateAndUpdateSelectedDate(availableDaysForSelectedProviders);
  }
  return availableDaysForSelectedProviders;
}
 
async function validateAndUpdateSelectedDate(
  availableDaysForSelectedProviders: any[]
) {
  if (!selectedDay.value) return;
  const currentDate = convertDateToString(selectedDay.value);
  const isCurrentDateAvailable = availableDaysForSelectedProviders.some(
    (day: any) => convertDateToString(new Date(day.time)) === currentDate
  );
 
  if (!isCurrentDateAvailable) {
    // First try to find a date after the current date
    let nextAvailableDay = availableDaysForSelectedProviders.find(
      (day: any) => {
        const dayDate = new Date(day.time);
        return dayDate >= (selectedDay.value ?? new Date());
      }
    );
 
    // If no future date is available, find the closest date before the current date
    if (!nextAvailableDay) {
      nextAvailableDay = [...availableDaysForSelectedProviders]
        .reverse()
        .find((day: any) => {
          const dayDate = new Date(day.time);
          return dayDate <= (selectedDay.value ?? new Date());
        });
    }
 
    if (nextAvailableDay) {
      const newDate = new Date(nextAvailableDay.time);
      selectedDay.value = newDate;
      // Set viewMonth to the first day of the month containing the new date
      viewMonth.value = new Date(newDate.getFullYear(), newDate.getMonth(), 1);
      calendarKey.value++;
      await nextTick();
      await getAppointmentsOfDay(nextAvailableDay.time);
    }
  }
}
 
async function validateCurrentDateHasAppointments() {
  if (!selectedDay.value) return;
  const currentDate = convertDateToString(selectedDay.value);
  const dayEntry = availableDays.value?.find(
    (day) => convertDateToString(new Date(day.time)) === currentDate
  );
  const hasAppointments = dayEntry?.providerIDs
    .split(",")
    .some((providerId) => selectedProviders.value[providerId]);
 
  if (
    !hasAppointments &&
    availableDays.value &&
    availableDays.value.length > 0
  ) {
    const nextAvailableDay = availableDays.value.find((day) => {
      const dayDate = new Date(day.time);
      return (
        dayDate >= (selectedDay.value ?? new Date()) &&
        day.providerIDs
          .split(",")
          .some((providerId) => selectedProviders.value[providerId])
      );
    });
 
    if (nextAvailableDay) {
      selectedDay.value = new Date(nextAvailableDay.time);
      await nextTick();
      await getAppointmentsOfDay(nextAvailableDay.time);
    }
  }
}
 
async function snapToNearestForCurrentView() {
  if (isListView.value) {
    await listViewRef.value?.snapToNearest?.();
  } else {
    await calendarViewRef.value?.snapToNearest?.();
  }
}
 
function scheduleRefreshAfterProviderChange() {
  const selectionSnapshot = JSON.stringify(selectedProviders.value);
  if (refetchTimer) clearTimeout(refetchTimer);
  refetchTimer = setTimeout(async () => {
    const prevSelectedDay = selectedDay.value
      ? new Date(selectedDay.value)
      : undefined;
    await refetchAvailableDaysForSelection();
    // Selection changed while awaiting? Abort this cycle.
    if (selectionSnapshot !== JSON.stringify(selectedProviders.value)) {
      return;
    }
    const availableDaysForSelectedProviders =
      updateDateRangeForSelectedProviders();
 
    // Validate and update selected date to ensure it's available for selected providers
    if (availableDaysForSelectedProviders.length > 0) {
      await validateAndUpdateSelectedDate(availableDaysForSelectedProviders);
    }
 
    // Snap inside day
    await validateCurrentDateHasAppointments();
    await snapToNearestForCurrentView();
  }, 150);
}
 
onMounted(() => {
  if (selectedService.value && selectedService.value.providers) {
    // Gather all selected service IDs (main + any chosen subservices)
    const mainId = selectedService.value.id;
    const chosenSubservices = (selectedService.value.subServices || []).filter(
      (subservice) => subservice.count > 0
    );
    const selectedIds = [mainId, ...chosenSubservices.map((s) => s.id)].map(
      Number
    );
    const providers: OfficeImpl[] = selectedService.value.providers;
 
    // Passport calendar functionality
    const availableProviders = getAvailableProviders(providers, selectedIds);
 
    // Checks whether there are restrictions on the providers due to the subservices.
    if (selectedService.value.subServices) {
      selectableProviders.value = availableProviders.filter((provider) => {
        return chosenSubservices.every((subservice) =>
          subservice.providers.some(
            (subserviceProvider) => subserviceProvider.id == provider.id
          )
        );
      });
    } else {
      selectableProviders.value = availableProviders;
    }
 
    // Checks whether a provider is already selected so that it is displayed first in the slider.
    let offices = selectableProviders.value.filter((office) => {
      if (props.preselectedOfficeId) {
        return office.id == props.preselectedOfficeId;
      } else if (selectedProvider.value) {
        return office.id == selectedProvider.value.id;
      } else {
        return false;
      }
    });
 
    // Add alternative locations to the slider if allowed
    const allowAlternativeLocations =
      offices.length === 0 ||
      offices[0].showAlternativeLocations === null ||
      offices[0].showAlternativeLocations;
 
    const allowNonExclusive = offices.length === 0 || !props.exclusiveLocation;
 
    if (allowAlternativeLocations && allowNonExclusive) {
      const excludedId =
        props.preselectedOfficeId ?? selectedProvider.value?.id;
 
      const otherOffices = availableProviders.filter(
        (office) => office.id !== excludedId
      );
 
      const officeIds = new Set(offices.map((office) => office.id));
      offices = [
        ...offices,
        ...otherOffices.filter((office) => !officeIds.has(office.id)),
      ];
    }
 
    // Remember first office before sorting (preselected/selected stays first)
    const firstOfficeToShow = offices[0];
    if (selectableProviders.value) {
      selectableProviders.value = offices.sort((a, b) => {
        const aPriority = a.priority ?? -Infinity;
        const bPriority = b.priority ?? -Infinity;
        return bPriority - aPriority;
      });
    }
 
    // If a preselected office ID is provided, only check the corresponding provider's checkbox
    if (props.preselectedOfficeId) {
      selectedProviders.value = selectableProviders.value.reduce(
        (acc, item) => {
          acc[item.id] = String(item.id) === String(props.preselectedOfficeId);
          return acc;
        },
        {} as { [id: string]: boolean }
      );
      initialized = true;
    }
 
    officeOrder.value = new Map(
      selectableProviders.value.map((office, index) => [
        Number(office.id),
        index,
      ])
    );
 
    showSelectionForProvider(firstOfficeToShow ?? offices[0]);
  }
});
 
onUnmounted(() => {
  if (refetchTimer) clearTimeout(refetchTimer);
});
 
watch(isLoadingAppointments, (loading) => {
  if (loading) {
    isLoadingComplete.value = false;
  }
});
 
watch(selectedDay, async (newDate) => {
  selectedTimeslot.value = 0;
  if (newDate) {
    await getAppointmentsOfDay(
      convertDateToString(selectedDay.value || new Date())
    );
  }
});
 
watch(selectableProviders, (newVal) => {
  if (!initialized && newVal && newVal.length) {
    selectedProviders.value = newVal.reduce(
      (acc, item) => {
        acc[item.id] = true;
        return acc;
      },
      {} as { [id: string]: boolean }
    );
    initialized = true;
  }
});
 
watch(appointmentTimestampsByOffice, () => {
  // Only reset if we are in hourly view and a day is selected
  if (selectedDay.value && timeSlotsInHoursByOffice.value.size > 0) {
    const allHours = Array.from(
      timeSlotsInHoursByOffice.value.values()
    ).flatMap((office) => {
      const hours = Array.from((office as any).appointments.keys());
      return hours.filter((hour) => typeof hour === "number" && hour >= 0);
    });
    if (allHours.length > 0) {
      selectedHour.value = Math.min(...(allHours as number[]));
    }
  }
  // For am/pm view
  else if (selectedDay.value && timeSlotsInDayPartByOffice.value.size > 0) {
    const allDayParts = Array.from(
      timeSlotsInDayPartByOffice.value.values()
    ).flatMap((office) => {
      const dayParts = Array.from((office as any).appointments.keys());
      return dayParts.filter((part) => part === "am" || part === "pm");
    });
    if (allDayParts.includes("am")) {
      selectedDayPart.value = "am";
    } else if (allDayParts.includes("pm")) {
      selectedDayPart.value = "pm";
    }
  }
});
 
watch(
  selectedProviders,
  async () => {
    // Sync single-selection provider immediately
    const selectedIds = Object.keys(selectedProviders.value).filter(
      (id) => selectedProviders.value[id]
    );
    if (selectedIds.length === 1 && selectableProviders.value) {
      const provider = selectableProviders.value.find(
        (p) => p.id.toString() === selectedIds[0]
      );
      selectedProvider.value = provider ?? undefined;
    } else if (selectedIds.length !== 1) {
      selectedProvider.value = undefined;
    }
 
    // Pre-hook: set switching state and clear errors immediately
    isSwitchingProvider.value = true;
    error.value = false;
    Object.values(errorStateMap.value).forEach((es) => (es.value = false));
 
    // Debounced pipeline
    scheduleRefreshAfterProviderChange();
  },
  { deep: true }
);
</script>
 
<style lang="scss" scoped>
@use "@/styles/breakpoints.scss" as *;
 
.m-button-group {
  margin-bottom: 20px;
  padding-bottom: 0;
  padding-top: 30px;
}
 
.no-bottom-margin,
.no-bottom-margin.m-button,
.no-bottom-margin .m-button {
  margin-bottom: 0 !important;
}
 
.no-top-margin,
.no-top-margin h3 {
  margin-top: 0 !important;
}
 
.m-button--ghost.disabled,
.m-button--ghost:disabled {
  background: #fff;
  border-color: #fff;
}
 
.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
 
<style>
.slider-no-margin .m-component__column {
  margin: 0 !important;
}
 
.slider-no-margin .m-checkbox-group__heading:empty {
  margin: 0 !important;
  padding: 0 !important;
}
 
.float-right .m-button__icon {
  margin-left: 12px !important;
}
 
.muc-calendar-view-full-size .muc-calendar-item,
.muc-calendar-container .muc-calendar-item {
  font-size: 1.125rem !important; /* 18px - default for desktop */
}
 
.muc-calendar-view-full-size,
.muc-calendar-container {
  font-size: 1.125rem !important; /* Desktop size */
}
 
#listViewAccordion .m-accordion__section-button {
  font-size: 1.125rem !important;
}
</style>