All files / components/Appointment AppointmentSelection.vue

87.68% Statements 477/544
78.55% Branches 304/387
89.2% Functions 124/139
88.75% Lines 442/498

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 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379                                            9x     3x   9x                         1x                                   2x                                                                                                                                     3x                                 8x     8x                                     1x                                 68x                       73x                                                                                                                             68x                         68x   68x       68x       68x                       68x 68x 68x 68x   68x   68x 68x   68x 68x 68x   68x 70x   68x 68x 68x 68x 68x 68x   68x 68x 68x   68x 68x 68x 68x   68x   68x               68x 68x   68x 449x 615x     68x 449x     68x 284x         284x 196x   162x   162x 583x 583x   583x 527x   583x     196x 158x             284x   53x 53x 53x         68x 269x   269x 152x 489x       269x     68x 269x   269x 152x 489x       269x     68x 116x     68x 280x         280x 189x   156x   156x 545x 545x 545x   545x 200x   545x     189x 152x             280x   51x 51x 51x         68x 269x 109x     191x     68x 269x 130x     212x     68x 164x         68x 98x 98x 98x 98x 98x 98x     68x 68x           68x   7x             7x   7x     7x 2x     5x 8x     7x     2x   2x   2x   2x     68x 31x   102x         68x 127x 62x 62x 62x       68x 127x     68x 80x 5x       75x 75x 326x       75x 149x 71x     68x 159x 69x     90x   99x 140x       68x                       68x 7x           7x 4x     3x 3x 3x 3x     3x   3x     3x 3x   3x 3x                                   68x 143x 143x     143x 75x     68x 77x     68x     68x   106x 104x       106x     93x   87x 172x     87x 100x           68x     68x 68x 68x       68x         68x 158x               68x 10x 9x 10x     2x 2x 4x     2x               68x 73x     68x               68x                 68x 325x     68x 68x     68x   6x 4x             2x               2x     68x 2x 2x       68x   98x 194x     98x                   98x               98x 98x         149x     96x 96x   96x 68x     96x         96x 96x 96x 96x     96x   2x 2x 2x       68x 146x 146x 146x     146x 289x   146x   1x 1x     145x   145x 145x                 145x 145x       145x 206x         145x 31x   114x       145x       3x   142x                                     145x 145x             58x   60x   129x 58x 14x 14x     60x 2x 2x 143x         2x   129x 129x 122x     7x 7x     7x 1x           6x     129x 4x     2x         2x     127x 127x         122x   10x 5x 5x     5x 5x 5x   5x     122x 7x     122x         143x 142x 284x 269x   142x   226x   309x     143x 137x 137x           137x 137x           137x     137x   142x           179x 179x 179x 197x     179x   7x   9x 9x         7x 1x     1x 1x       7x 7x 7x 7x 7x 7x 7x           47x 45x 45x 55x   47x   87x   47x         2x 2x 2x       13x       2x                 47x     47x         76x 76x 76x 47x       47x   47x       47x   47x 42x     47x     47x     47x       41x     47x 47x       68x 68x 58x 58x 2x   58x 58x   58x   58x 15x             58x 122x 9x 113x     113x         58x       58x   58x   55x   55x 116x     55x 55x   115x       58x 58x 58x 65x 65x 65x       58x 4x   6x 6x       4x     58x 119x           58x       68x 3x     68x 266x 133x       68x 81x 81x 80x           68x 59x 55x   115x 115x       55x       68x   279x 99x     150x 487x   99x 99x   180x                                 68x       76x 152x   76x 31x 38x   31x 45x 45x       76x 76x   76x       76x 21x 21x 1344x   55x       76x                                                                                                                                      
<template>
  <ProviderSelection
    :t="t"
    :selectableProviders="providerSelectionProviders"
    :providersWithAppointments="providersWithAppointments"
    :selectedProvider="selectedProvider"
    :selectedProviders="selectedProviders"
    @update:selectedProviders="onUpdateSelectedProviders"
    :providerSelectionError="providerSelectionError"
  />
  <div
    v-if="
      availableDaysFetched &&
      (noProviderSelected ||
        (selectedProvider && !providersWithAppointments.length)) &&
      !isSwitchingProvider
    "
    class="m-component"
  >
    <h2>{{ 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 ||
        !availableDaysFetched ||
        isSwitchingProvider)
    "
    class="m-component"
  >
    <CalendarListToggle
      :t="t"
      :isListView="isListView"
      @update:isListView="isListView = $event"
    />
    <div
      v-if="!availableDaysFetched || isSwitchingProvider"
      class="m-spinner-container"
    >
      <MucSpinner :text="t('spinnerText')" />
    </div>
    <CalendarView
      ref="calendarViewRef"
      v-else-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-else-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="showError && !isSwitchingProvider && !noProviderSelected"
    class="m-component"
  >
    <h2>{{ 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
    ref="buttons"
    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,
  MucSpinner,
} 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 { GlobalState } from "@/types/GlobalState";
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<{
  globalState: GlobalState;
  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 view is placed on the appointment summary, the focus on the 'next' button.
 */
const summary = ref<HTMLElement | null>(null);
const buttons = 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 fetchAvailableDaysForSelection();
};
 
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());
 
  Iif (!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]);
 
  Iif (!hasAppointments) return false;
 
  return true;
};
 
const hasAppointmentsForSelectedProviders = () => {
  return (
    availableDays?.value?.some((day) =>
      day.providerIDs.split(",").some((id) => selectedProviders.value[id])
    ) || false
  );
};
 
const providersWithAppointments = computed(() => {
  return (selectableProviders.value || []).sort((a, b) => {
    const aPriority = a.priority ?? -Infinity;
    const bPriority = b.priority ?? -Infinity;
    return bPriority - aPriority;
  });
});
 
const providerSelectionProviders = computed(() => {
  return providersWithAppointments.value.filter((p) => p.scope != null);
});
 
const providersWithAvailableDays = computed(() => {
  if (!availableDays.value?.length || !selectableProviders.value?.length) {
    return [];
  }
 
  // Collect all provider IDs that have at least one available day
  const idsWithDays = new Set<string>();
  availableDays.value.forEach((day) => {
    day.providerIDs.split(",").forEach((id) => idsWithDays.add(id.trim()));
  });
 
  // Filter to only providers with available days and sort by priority
  return selectableProviders.value
    .filter((p) => idsWithDays.has(String(p.id)))
    .sort((a, b) => (b.priority ?? -Infinity) - (a.priority ?? -Infinity));
});
 
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.scrollIntoView({ behavior: "smooth", block: "center" });
    (buttons.value?.lastChild as HTMLElement | null)?.focus({
      preventScroll: true,
    });
  }
};
 
const handleDaySelection = async (day: any) => {
  Iif (!(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);
    });
    Eif (allHours.length > 0) {
      selectedHour.value = Math.min(...(allHours as number[]));
    }
  E} 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(() => {
  const selectableIds = new Set(
    providerSelectionProviders.value.map((p) => String(p.id))
  );
 
  if (selectableIds.size === 0) {
    return "";
  }
 
  const hasSelection = Object.entries(selectedProviders.value).some(
    ([id, isSelected]) => isSelected && selectableIds.has(id)
  );
 
  return !hasSelection ? props.t("errorMessageProviderSelection") : "";
});
 
const noProviderSelected = computed(() => {
  // Check if any providers are selected at all
  const hasAnySelection = Object.values(selectedProviders.value).some(
    (selected) => selected
  );
 
  // If no providers are selected at all, return true
  if (!hasAnySelection) return true;
 
  // If there are no providers with available days, we can't determine selection
  if (!providersWithAvailableDays.value?.length) return false;
 
  const idsWithDays = new Set(
    providersWithAvailableDays.value.map((p) => String(p.id))
  );
 
  return !Object.keys(selectedProviders.value).some(
    (id) => selectedProviders.value[id] && idsWithDays.has(id)
  );
});
 
// 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) => {
    Eif (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
  Iif (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 fetchAvailableDaysForSelection = async (): Promise<void> => {
  // Always fetch available days for ALL providers to maintain the full list
  const allProviderIds = (selectableProviders.value || []).map((p) =>
    Number(p.id)
  );
 
  Iif (allProviderIds.length === 0) {
    // No providers available, clear available days
    availableDays.value = [];
    availableDaysFetched.value = true;
    error.value = false;
    isSwitchingProvider.value = false;
    updateDateRangeForSelectedProviders();
    return;
  }
 
  const data = await fetchAvailableDays(
    props.globalState,
    allProviderIds,
    Array.from(props.selectedServiceMap.keys()),
    Array.from(props.selectedServiceMap.values()),
    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);
    availableDaysFetched.value = true;
    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(
      props.globalState,
      date,
      providerIds.map(Number),
      Array.from(props.selectedServiceMap.keys()),
      Array.from(props.selectedServiceMap.values()),
      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 E{
      // 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(
  selectedServices: { providers: OfficeImpl[]; id: number }[]
): OfficeImpl[] {
  Iif (!selectedServices || selectedServices.length === 0) return [];
 
  const selectedServiceIds = selectedServices.map((s) => s.id);
 
  let allowedIds = new Set(selectedServices[0].providers.map((p) => p.id));
  for (let i = 1; i < selectedServices.length; i++) {
    const serviceIds = new Set(selectedServices[i].providers.map((p) => p.id));
    allowedIds = new Set([...allowedIds].filter((id) => serviceIds.has(id)));
  }
 
  const allProviders = selectedServices.flatMap((s) => s.providers);
  const filteredProvidersMap = new Map<number, OfficeImpl>();
  allProviders.forEach((p) => {
    Eif (allowedIds.has(p.id)) filteredProvidersMap.set(Number(p.id), p);
  });
 
  // Filter out providers where any selected service is in their disabledByServices.
  // Offices with allowDisabledServicesMix=true are kept and resolved later by grouping logic.
  const filteredProviders = Array.from(filteredProvidersMap.values()).filter(
    (p) => {
      const disabledServices = (p.disabledByServices ?? []).map(Number);
      if (disabledServices.length === 0) {
        return true;
      }
 
      const hasAnyDisabled = selectedServiceIds.some((serviceId) =>
        disabledServices.includes(Number(serviceId))
      );
 
      if (!hasAnyDisabled) {
        return true;
      }
 
      // Offices with allowDisabledServicesMix (array or legacy true) participate in
      // exclusive-vs-mixed logic in the grouping step and must not be filtered out.
      const participatesInMix =
        (Array.isArray(p.allowDisabledServicesMix) &&
          p.allowDisabledServicesMix.length > 0) ||
        p.allowDisabledServicesMix === true;
      if (participatesInMix) {
        return true;
      }
 
      return false;
    }
  );
 
  // Group by name and return unique providers
  return Object.values(
    filteredProviders.reduce<Record<string, OfficeImpl[]>>(
      (grouped, provider) => {
        (grouped[provider.name] ||= []).push(provider);
        return grouped;
      },
      {}
    )
  ).map((group) => {
    if (group.length === 1) return group[0];
 
    const clean = group.find((p) => (p.disabledByServices ?? []).length === 0);
    const restricted = group.find(
      (p) => (p.disabledByServices ?? []).length > 0
    );
 
    Iif (!clean && !restricted) return group[0];
    Iif (!restricted) return clean as OfficeImpl;
    Iif (!clean) return restricted as OfficeImpl;
 
    const restrictedDisabled = (restricted.disabledByServices ?? []).map(
      Number
    );
    const allDisabled = selectedServices.every((s) =>
      restrictedDisabled.includes(Number(s.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
    Eif (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[]
) {
  Iif (!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());
        });
    }
 
    Eif (nextAvailableDay) {
      const newDate = new Date(nextAvailableDay.time);
      selectedDay.value = newDate;
      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])
      );
    });
 
    Iif (nextAvailableDay) {
      selectedDay.value = new Date(nextAvailableDay.time);
      await nextTick();
      await getAppointmentsOfDay(nextAvailableDay.time);
    }
  }
}
 
async function snapToNearestForCurrentView() {
  Iif (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;
 
    isSwitchingProvider.value = false;
 
    Iif (selectionSnapshot !== JSON.stringify(selectedProviders.value)) {
      return;
    }
    const availableDaysForSelectedProviders =
      updateDateRangeForSelectedProviders();
 
    if (availableDaysForSelectedProviders.length > 0) {
      await validateAndUpdateSelectedDate(availableDaysForSelectedProviders);
    }
 
    const previousSelectedDateString = prevSelectedDay
      ? convertDateToString(prevSelectedDay)
      : null;
    const currentSelectedDateString = selectedDay.value
      ? convertDateToString(selectedDay.value)
      : null;
    if (
      currentSelectedDateString &&
      previousSelectedDateString === currentSelectedDateString
    ) {
      await getAppointmentsOfDay(currentSelectedDateString);
    }
 
    await validateCurrentDateHasAppointments();
    await snapToNearestForCurrentView();
  }, 150);
}
 
onMounted(() => {
  if (selectedService.value && selectedService.value.providers) {
    const mainService = selectedService.value;
    const chosenSubservices = (mainService.subServices || []).filter(
      (s) => s.count > 0
    );
    const allSelectedServices = [mainService, ...chosenSubservices];
    const availableProviders = getAvailableProviders(allSelectedServices);
 
    selectableProviders.value = [...availableProviders];
 
    const preselectedMatches = (office: OfficeImpl) =>
      props.preselectedOfficeId &&
      (Number(office.id) === Number(props.preselectedOfficeId) ||
        (Array.isArray(office.allowDisabledServicesMix) &&
          office.allowDisabledServicesMix.includes(
            Number(props.preselectedOfficeId)
          )));
 
    let offices = selectableProviders.value.filter((office) => {
      if (props.preselectedOfficeId) {
        return preselectedMatches(office);
      I} else if (selectedProvider.value) {
        return office.id == selectedProvider.value.id;
      } else {
        return false;
      }
    });
 
    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)),
      ];
    }
 
    const firstOfficeToShow = offices[0];
    Eif (selectableProviders.value) {
      selectableProviders.value = offices.sort((a, b) => {
        const aPriority = a.priority ?? -Infinity;
        const bPriority = b.priority ?? -Infinity;
        return bPriority - aPriority;
      });
    }
 
    if (props.preselectedOfficeId) {
      selectedProviders.value = selectableProviders.value.reduce(
        (acc, item) => {
          acc[item.id] = Boolean(preselectedMatches(item));
          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(() => {
  Eif (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);
    });
    Eif (allHours.length > 0) {
      selectedHour.value = Math.min(...(allHours as number[]));
    }
  I}
  // 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;
    E} else if (selectedIds.length !== 1) {
      selectedProvider.value = undefined;
    }
 
    const hasAvailableDays =
      availableDays.value && availableDays.value.length > 0;
    const daysWereFetched = availableDays.value !== undefined;
 
    Iif (daysWereFetched && !hasAvailableDays && !availableDaysFetched.value) {
      availableDaysFetched.value = true;
    }
 
    if (hasAvailableDays) {
      isSwitchingProvider.value = true;
      error.value = false;
      Object.values(errorStateMap.value).forEach((es) => (es.value = false));
    } else {
      isSwitchingProvider.value = false;
    }
 
    // Debounced pipeline
    scheduleRefreshAfterProviderChange();
  },
  { deep: true }
);
</script>
 
<style lang="scss" scoped>
@use "@/styles/breakpoints.scss" as *;
@use "@/styles/style.scss";
 
.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>