All files / components/Appointment AppointmentSelection.vue

86.78% Statements 893/1029
73.27% Branches 540/737
85.97% Functions 190/221
87.68% Lines 847/966

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 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352                                              28x     3x   28x                           5x                                                                                                                                                                                           3x                                         13x     3x   13x                                       1x                                   80x                       85x                                                                                                                         80x                         80x   80x       80x       80x                       80x 80x   80x 80x         80x 80x 80x 80x 80x   80x   80x 80x 80x       80x 80x 80x   80x 101x     80x   80x           80x             80x 81x 1x   80x 4x   76x             80x 1x 1x     80x   402x       402x   402x 25728x     402x     80x 213x   213x 47x       80x 8x     80x 80x 80x 80x 80x 80x   80x     80x 49x 49x 92x 85x         49x   80x 80x   80x   80x   80x   80x   80x 80x 80x 80x   80x     80x   80x 162x   80x         162x               80x 1742x 491x     80x 80x           80x     293x           80x 69x 69x   67x         80x 129x     129x                   80x       162x     162x             80x 80x   80x 279x 279x 377x   279x             279x               80x 668x 668x 185x 267x 209x             80x 278x 278x     80x 278x       80x 1721x   3442x     6565x       1721x 1721x     1721x           1721x 1721x                     1721x                 80x           283x 283x   283x 322x 322x       322x                                                   322x 1390x 1390x 1390x   1390x 1390x 1390x   1390x       283x 322x   1068x       283x       80x     80x 2x 2x 4x   2x     80x 100x             100x 108x   100x   100x 108x   108x 458x 458x   458x 138x   458x     108x 108x             100x   37x 37x 37x         80x 67x   67x 75x 95x       67x     80x 67x   67x 75x 95x       67x     80x 51x     80x 79x         79x 75x   79x   79x 75x   75x 319x 319x 319x   319x 79x   319x     75x 75x             79x   25x 25x 25x         80x 67x 70x     45x     80x 67x 53x     35x     80x 41x         80x 106x 106x 106x 106x 106x 106x     80x   18x             18x   18x   18x 39x     18x       11x   13x 11x 1x   10x       8x   2x     80x               80x 146x 64x 64x 64x       80x 146x     80x 263x 194x       69x 69x 190x     69x 128x 7x             69x 128x 52x     80x     272x 83x       80x       1106x 1106x 1106x   16x 1106x 15x 15x 15x       15x         1x       80x     1105x   80x 1x 1x 1x 1x 1x 1x 1x 1x           80x 80x 80x 80x   80x             80x 13x 10x     12x 14x   10x 10x   10x   3x                             80x 20x       20x   20x   20x   20x 15x 15x 15x 15x     20x 20x 20x 20x   20x     20x     20x 3x     17x 17x       17x 13x     20x 19x 19x 19x         80x 161x 152x     161x 85x     76x 82x     76x     80x   150x 156x       150x     134x   82x 147x     82x 95x           80x             80x 2x 2x 1x     1x 1x           1x   1x 1x         80x 80x 80x       80x         80x 181x               80x 13x 13x 13x     4x 4x 9x     4x                 80x 25x 13x   12x     80x 86x     80x               80x               80x                 80x 221x 221x                 80x 80x 1x 1x 1x       80x   17x 4x             13x               13x     80x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     80x 1x 1x 1x 1x 1x       80x 15x 15x               80x 104x 104x       175x             104x   104x   104x 104x 104x 104x     104x 104x 104x     104x       104x 104x 104x   104x 175x 175x 175x     175x 170x     175x       175x   233x       175x 166x   166x 74x   9x   1x         1x 1x           100x 175x 154x 154x   175x       175x           104x 104x       104x 104x 36x 36x 9x     104x 100x   104x 45x     104x 104x 104x     80x               80x   80x         80x   80x 1x 2x     80x 4x 4x     4x 8x 4x         80x 3x 3x 2x   1x     1x             80x 1x       1x 1x   1x         1x       1x       1x 1x 1x               1x                 80x 165x 310x 165x   165x   302x 276x 276x 8x         165x   3x   165x 6x 8x 11x       165x 165x 284x   467x 284x 3x 6x 6x 5x         165x     80x                             149x   149x 149x   149x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     147x 147x 149x 149x             149x         18x       129x         24x       105x     149x 67x 67x   105x 80x     105x 105x 105x 105x   105x   105x 105x                                           105x       105x 1x 1x     104x 104x         104x 104x 104x   104x   104x           32x   33x     32x 33x   32x 33x     32x         32x         104x         6x           98x 58x             98x 105x     105x 105x 99x 99x     105x     80x 106x                 106x   106x       106x 38x     106x 106x     80x 102x 102x 102x   102x 181x   102x 2x 2x 2x     100x 102x 172x     102x 102x 102x   102x 131x       102x 15x   85x     100x 100x           66x   69x   143x 66x 15x 16x     69x 3x 3x 158x         3x   142x 142x 135x     7x 7x     7x 1x       6x     142x 4x     2x           3x 140x       5x   5x     135x     3x     140x 140x         138x 2x         3x 138x       10x   10x     128x     3x     138x 138x         133x   10x 5x 5x     5x 5x 5x   5x     133x 7x     133x                       173x 173x   173x 232x 232x 13x   232x 14x         173x   173x   173x 173x   173x 173x   173x     173x     173x 166x   173x     173x 162x     173x 173x       111x 111x 204x 184x   111x   123x   126x     111x 69x   69x 60x           69x     69x 28x     111x           28x   28x 22x   28x 28x   28x 27x       1x       11x     11x         18x       18x 18x 18x 18x 16x     16x     16x             16x 16x 1x 1x   1x       15x 15x         15x 2x 2x   2x       13x   13x     13x       13x     13x       13x   13x 13x 2x     11x 9x   11x 11x     16x 6x 5x 5x     11x       11x     13x 13x           80x 80x 66x 66x 3x   66x 66x   66x   66x 17x                       66x 133x 10x 123x     123x         66x       66x   66x   62x   62x 126x     62x 62x   125x       66x 66x 66x 68x 68x 68x           66x 66x   130x     130x       66x   66x 130x           66x   66x           80x 3x 3x     80x 38x 19x       80x 48x 34x 34x 33x       80x 68x 2x   3x 3x       2x       80x   89x 70x     106x 136x   70x 70x       19x                             80x     85x       85x 162x   85x 34x 38x   34x 51x 51x       85x 85x   85x       85x 81x   4x       85x 67x       18x                                                                                                                                      
<template>
  <ProviderSelection
    v-if="!isCaptchaSessionExpired"
    :t="t"
    :selectableProviders="providerSelectionProviders"
    :providersWithAppointments="providersWithAppointments"
    :selectedProvider="selectedProvider"
    :selectedProviders="selectedProviders"
    @update:selectedProviders="onUpdateSelectedProviders"
    :providerSelectionError="providerSelectionError"
  />
  <div
    v-if="
      !isCaptchaSessionExpired &&
      availableDaysFetched &&
      (noProviderSelected || !hasSelectedProviderWithAppointments) &&
      !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">
          <p>{{ t("apiErrorNoAppointmentForThisScopeText") }}</p>
        </div>
        <div
          class="m-content"
          style="margin-top: 8px"
          v-if="emptyStateAvailabilityInfoHtml"
        >
          <p>
            <muc-button
              variant="ghost"
              icon="information"
              icon-shown-left
              class="no-bottom-margin"
              @click="openEmptyStateInfoModal"
            >
              <template #default>{{ t("newAppointmentsInfoLink") }}</template>
            </muc-button>
          </p>
        </div>
      </template>
    </muc-callout>
  </div>
  <div
    v-else-if="
      !isCaptchaSessionExpired &&
      (!error || isNoAppointmentForThisDayError) &&
      (hasSelectedProviderWithAppointments ||
        !availableDaysFetched ||
        isSwitchingProvider)
    "
    class="m-component"
  >
    <CalendarListToggle
      :t="t"
      :isListView="isListView"
      @update:isListView="onListViewToggle"
    />
    <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"
      :prevBookableDate="prevBookableDate"
      :nextBookableDate="nextBookableDate"
      :timeSlotsInHoursByOffice="timeSlotsInHoursByOffice"
      :timeSlotsInDayPartByOffice="timeSlotsInDayPartByOffice"
      :currentHour="currentHour"
      :firstHour="firstHour"
      :lastHour="lastHour"
      :currentDayPart="currentDayPart"
      :firstDayPart="firstDayPart"
      :lastDayPart="lastDayPart"
      :selectableProviders="selectableProviders"
      :selectedProviders="selectedProvidersForCalendar"
      :providersWithAppointments="providersWithAppointments"
      :appointmentsCount="appointmentsCount"
      :isLoadingAppointments="isLoadingAppointments"
      :isLoadingComplete="isLoadingComplete"
      :availabilityInfoHtml="availabilityInfoHtml"
      :officeNameById="officeNameById"
      :isSlotSelected="isSlotSelected"
      :officeIdForTime="officeIdForTime"
      @update:selectedDay="handleDaySelection"
      @jumpToBookableDate="jumpToBookableDate"
      @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="selectedProvidersForCalendar"
      :providersWithAppointments="providersWithAppointments"
      :officeNameById="officeNameById"
      :isSlotSelected="isSlotSelected"
      :officeIdForTime="officeIdForTime"
      :availableDays="availableDays"
      :appointmentsByDay="appointmentsByDayForDisplay"
      :officeOrder="officeOrder"
      :hasMoreDaysAhead="hasMoreListDaysAhead"
      :isLoadingMoreDays="isLoadingMoreListDays"
      @update:selectedDay="handleDaySelection"
      @requestMoreDays="loadMoreListViewDays"
      @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 &&
      (isCaptchaSessionExpired || !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">
          <p>{{ t(apiErrorTranslation.textKey) }}</p>
        </div>
        <div
          class="m-content"
          style="margin-top: 8px"
          v-if="
            (apiErrorTranslation.textKey ===
              'apiErrorNoAppointmentForThisScopeText' ||
              apiErrorTranslation.textKey ===
                'apiErrorNoAppointmentForThisDayText') &&
            availabilityInfoHtml
          "
        >
          <p>
            <muc-button
              variant="ghost"
              icon="information"
              icon-shown-left
              class="no-bottom-margin"
              @click="openAvailabilityInfoModal"
            >
              <template #default>{{ t("newAppointmentsInfoLink") }}</template>
            </muc-button>
          </p>
        </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
    v-model:open="showAvailabilityInfoModal"
    :html="availabilityInfoHtmlForModal"
    :closeAriaLabel="t('closeDialog')"
    :t="t"
  />
</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 { AvailableCalendarDTO } from "@/api/models/AvailableCalendarDTO";
import { ErrorDTO } from "@/api/models/ErrorDTO";
import { OfficeAvailableTimeSlotsDTO } from "@/api/models/OfficeAvailableTimeSlotsDTO";
import { fetchAvailableCalendar } 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,
  handleApiError,
  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" | "clearBookingError") => 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<{ date: string; providerIDs: string }>>();
/** YYYY-MM-DD bounds of the last loaded appointment-slots window */
const loadedSlotsStartDate = ref<string | null>(null);
const loadedSlotsEndDate = ref<string | null>(null);
/**
 * Days for which free-slot SQL has already run. Empty results stay non-selectable
 * even after the free-slot window moves to another day (daylist may still return providerIDs).
 */
const freeSlotCheckedDates = ref<Set<string>>(new Set());
const prevBookableDate = ref<string | null>(null);
const nextBookableDate = ref<string | null>(null);
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 appointmentsByDay = ref<Map<string, OfficeAvailableTimeSlotsDTO[]>>(
  new Map()
);
 
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);
 
/** Sticky until back: available-calendar captcha session expired — hide providers/calendar. */
const captchaSessionExpired = ref(false);
 
const CAPTCHA_SESSION_ERROR_CODES = new Set([
  "captchaExpired",
  "captchaInvalid",
  "captchaMissing",
]);
 
const CAPTCHA_SESSION_BOOKING_KEYS = new Set([
  "apiErrorCaptchaExpired",
  "apiErrorCaptchaInvalid",
  "apiErrorCaptchaMissing",
  "altcha.invalidCaptcha",
]);
 
const isCaptchaSessionExpired = computed(() => {
  if (captchaSessionExpired.value) {
    return true;
  }
  if (props.bookingError && props.bookingErrorKey) {
    return CAPTCHA_SESSION_BOOKING_KEYS.has(props.bookingErrorKey);
  }
  return (
    !!errorStateMap.value.apiErrorCaptchaExpired?.value ||
    !!errorStateMap.value.apiErrorCaptchaInvalid?.value ||
    !!errorStateMap.value.apiErrorCaptchaMissing?.value
  );
});
 
const getFirstErrorCode = (data: any): string | null => {
  const code = data?.errors?.[0]?.errorCode;
  return typeof code === "string" ? code : null;
};
 
const clearLocalApiErrors = (): void => {
  // Keep captcha-expired lock until the user goes back.
  Iif (captchaSessionExpired.value) {
    return;
  }
 
  error.value = false;
 
  Object.values(errorStateMap.value).forEach((errorState) => {
    errorState.value = false;
  });
 
  errorStates.currentErrorData.value = null;
};
 
const clearVisibleErrors = (notifyParent = true): void => {
  clearLocalApiErrors();
 
  if (notifyParent && !captchaSessionExpired.value) {
    emit("clearBookingError");
  }
};
 
const isNoAppointmentForThisDayError = computed(
  () => errorStateMap.value.apiErrorNoAppointmentForThisDay?.value ?? false
);
 
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 }>({});
 
/** Checkbox state plus shared-booking peer IDs so calendar/list show round-robin-chosen offices. */
const selectedProvidersForCalendar = computed(() => {
  const result: { [id: string]: boolean } = { ...selectedProviders.value };
  for (const provider of selectableProviders.value || []) {
    if (!result[String(provider.id)]) continue;
    Eif (!Array.isArray(provider.sharedBookingOfficeIds)) continue;
    for (const peerId of provider.sharedBookingOfficeIds) {
      result[String(peerId)] = true;
    }
  }
  return result;
});
const listViewRef = ref<any>();
const calendarViewRef = ref<any>();
 
let initialized = false;
/** True while onMounted owns the first calendar fetch — skip provider-refresh races. */
let initialCalendarLoadPending = false;
/** Full request key of the last successful available-calendar response. */
let lastFetchedRequestKey: string | null = null;
/** Full request key of the in-flight available-calendar call (if any). */
let inFlightRequestKey: string | null = null;
/** Shared promise for the in-flight available-calendar call (same-key callers join). */
let inFlightCalendarPromise: Promise<boolean> | null = null;
const availableDaysFetched = ref(false);
const isLoadingAppointments = ref(false);
const isSwitchingProvider = ref(false);
 
const isLoadingComplete = ref(false);
 
let refetchTimer: ReturnType<typeof setTimeout> | undefined;
let providerRefreshGeneration = 0;
 
const officeIdsRequestKey = (ids: number[]): string =>
  [...ids].sort((a, b) => a - b).join(",");
 
const buildCalendarRequestKey = (
  officeIds: number[],
  slotsStartDate: string,
  slotsEndDate: string
): string =>
  [
    officeIdsRequestKey(officeIds),
    Array.from(props.selectedServiceMap.keys()).join(","),
    Array.from(props.selectedServiceMap.values()).join(","),
    slotsStartDate,
    slotsEndDate,
  ].join("|");
 
const toDayKey = (value: Date | string): string => {
  if (typeof value === "string") return value.slice(0, 10);
  return convertDateToString(value);
};
 
const TODAY = new Date();
const MAXDATE = new Date(
  TODAY.getFullYear(),
  TODAY.getMonth() + 6,
  TODAY.getDate()
);
 
const normalizeCalendarOffices = (
  offices: Array<{ officeId: number | string; appointments?: number[] }>
): OfficeAvailableTimeSlotsDTO[] => {
  return offices.map((office) => ({
    officeId: Number(office.officeId),
    appointments: office.appointments ?? [],
  }));
};
 
const dayHasSlotsForSelectedProviders = (dateKey: string): boolean => {
  const offices = appointmentsByDay.value.get(dateKey) ?? [];
  return offices.some(
    (office) =>
      isOfficeIdSelectedForCalendar(office.officeId) &&
      (office.appointments?.length ?? 0) > 0
  );
};
 
const isDateInLoadedSlotsWindow = (dateKey: string): boolean => {
  Iif (!loadedSlotsStartDate.value || !loadedSlotsEndDate.value) {
    return false;
  }
  return (
    dateKey >= loadedSlotsStartDate.value && dateKey <= loadedSlotsEndDate.value
  );
};
 
/**
 * Free-slot SQL window hint: selected day (otherwise today).
 * Backend loads appointment timestamps only for that window; other painted-month
 * days keep daylist providerIDs with empty offices until that day is free-slot-checked.
 */
const getFreeSlotsWindow = (): {
  slotsStartDate: string;
  slotsEndDate: string;
} => {
  const dayKey = selectedDay.value
    ? toDayKey(selectedDay.value)
    : convertDateToString(TODAY);
  return { slotsStartDate: dayKey, slotsEndDate: dayKey };
};
 
/**
 * 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);
  const fromSelectable = (selectableProviders.value || []).find(
    (p) => String(p.id) === idStr
  );
  Eif (fromSelectable) return fromSelectable;
 
  // Peers collapsed out of the Ort list may still own a reserved/free slot.
  const services = [
    selectedService.value,
    ...(selectedService.value?.subServices || []).filter((s) => s.count > 0),
  ].filter(Boolean) as Array<{ providers?: OfficeImpl[] }>;
  for (const service of services) {
    const found = (service.providers || []).find((p) => String(p.id) === idStr);
    if (found) return found as OfficeImpl;
  }
  return undefined;
};
 
/** True when the Ort checkbox for this office (or a shared-booking peer) is checked. */
const isOfficeIdSelectedForCalendar = (officeId: number | string): boolean => {
  const idStr = String(officeId);
  if (selectedProviders.value[idStr]) return true;
  return (selectableProviders.value || []).some((p) => {
    if (!selectedProviders.value[String(p.id)]) return false;
    return (
      Array.isArray(p.sharedBookingOfficeIds) &&
      p.sharedBookingOfficeIds.map(Number).includes(Number(officeId))
    );
  });
};
 
const displayOfficeNameForId = (id: number | string): string | null => {
  const displayId = displayOfficeIdFor(Number(id));
  return getOfficeById(displayId)?.name ?? getOfficeById(id)?.name ?? null;
};
 
const officeNameById = (id: number | string): string | null => {
  return displayOfficeNameForId(id);
};
 
/** Map a peer OfficeID to the Ort checkbox office that represents the shared group. */
const displayOfficeIdFor = (officeId: number): number => {
  const id = Number(officeId);
 
  const findOwner = (providers: OfficeImpl[] | undefined) =>
    (providers || []).find(
      (p) =>
        Array.isArray(p.sharedBookingOfficeIds) &&
        p.sharedBookingOfficeIds.map(Number).includes(id)
    );
 
  const selectableOwner = findOwner(selectableProviders.value);
  Iif (selectableOwner) return Number(selectableOwner.id);
 
  // Peers collapsed out of the Ort list still carry the group on the service.
  const serviceProviders = [
    ...(selectedService.value?.providers || []),
    ...((selectedService.value?.subServices || [])
      .filter((s) => (s.count ?? 0) > 0)
      .flatMap((s) => s.providers || []) as OfficeImpl[]),
  ] as OfficeImpl[];
  const serviceOwner = findOwner(serviceProviders);
  Iif (serviceOwner && Array.isArray(serviceOwner.sharedBookingOfficeIds)) {
    const group = serviceOwner.sharedBookingOfficeIds.map(Number);
    const selectableInGroup = (selectableProviders.value || [])
      .map((p) => Number(p.id))
      .filter((selectableId) => group.includes(selectableId));
    if (selectableInGroup.length > 0) {
      return Math.min(...selectableInGroup);
    }
    return Math.min(...group);
  }
 
  return id;
};
 
/**
 * Merge shared-booking peer offices into one timeslot section (display Ort).
 * slotOwnerByTimestamp keeps the real officeId for reserve/book, keyed by
 * display section + timestamp so unrelated Orte with the same wall-clock
 * slot do not collide.
 */
const aggregateSharedBookingOffices = (
  offices: OfficeAvailableTimeSlotsDTO[]
): {
  aggregated: OfficeAvailableTimeSlotsDTO[];
  slotOwnerByTimestamp: Map<string, number>;
} => {
  const slotOwnerByTimestamp = new Map<string, number>();
  const byDisplay = new Map<number, number[]>();
 
  for (const office of offices) {
    const realId = Number(office.officeId);
    let displayId = displayOfficeIdFor(realId);
 
    // Fallback: peer expanded into calendar (not an Ort checkbox) → fold into
    // the checked Ort that lists it, or the checked Ort with the same label.
    Iif (
      displayId === realId &&
      !selectedProviders.value[String(realId)] &&
      selectedProvidersForCalendar.value[String(realId)]
    ) {
      const peerOwner = (selectableProviders.value || []).find(
        (p) =>
          !!selectedProviders.value[String(p.id)] &&
          Array.isArray(p.sharedBookingOfficeIds) &&
          p.sharedBookingOfficeIds.map(Number).includes(realId)
      );
      if (peerOwner) {
        displayId = Number(peerOwner.id);
      } else {
        const peerName = officeNameById(realId);
        const sameNameOwner = (selectableProviders.value || []).find(
          (p) =>
            !!selectedProviders.value[String(p.id)] &&
            officeNameById(p.id) === peerName
        );
        if (sameNameOwner) {
          displayId = Number(sameNameOwner.id);
        }
      }
    }
 
    for (const time of office.appointments ?? []) {
      const ownerKey = `${displayId}_${time}`;
      Eif (!slotOwnerByTimestamp.has(ownerKey)) {
        slotOwnerByTimestamp.set(ownerKey, realId);
      }
      const list = byDisplay.get(displayId) ?? [];
      Eif (!list.includes(time)) {
        list.push(time);
      }
      byDisplay.set(displayId, list);
    }
  }
 
  const aggregated = [...byDisplay.entries()].map(
    ([mergedOfficeId, appointments]) => ({
      officeId: mergedOfficeId,
      appointments: [...appointments].sort((a, b) => a - b),
    })
  );
 
  return { aggregated, slotOwnerByTimestamp };
};
 
/** displayId_timestamp → real officeId (peer) for the currently shown day slots */
const slotOwnerByTimestamp = ref<Map<string, number>>(new Map());
 
/** appointmentsByDay with shared-booking peers merged for list/calendar display */
const appointmentsByDayForDisplay = computed(() => {
  const result = new Map<string, OfficeAvailableTimeSlotsDTO[]>();
  for (const [dateKey, offices] of appointmentsByDay.value.entries()) {
    result.set(dateKey, aggregateSharedBookingOffices(offices).aggregated);
  }
  return result;
});
 
const timeSlotsInHoursByOffice = computed(() => {
  const offices = new Map<
    number,
    { officeId: number; appointments: Map<number, number[]> }
  >();
 
  // Always re-aggregate here so peer offices never render as duplicate sections
  // even if appointmentTimestampsByOffice still has raw API office buckets.
  const selectedOffices = appointmentTimestampsByOffice.value.filter((office) =>
    isOfficeIdSelectedForCalendar(office.officeId)
  );
  const { aggregated } = aggregateSharedBookingOffices(selectedOffices);
 
  aggregated.forEach((office) => {
    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);
    });
 
    Eif (timesByHours.size > 0) {
      offices.set(Number(office.officeId), {
        officeId: Number(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[]> }
  >();
 
  const selectedOffices = appointmentTimestampsByOffice.value.filter((office) =>
    isOfficeIdSelectedForCalendar(office.officeId)
  );
  const { aggregated } = aggregateSharedBookingOffices(selectedOffices);
 
  aggregated.forEach((office) => {
    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);
    });
 
    Eif (timesByPartOfDay.size > 0) {
      offices.set(Number(office.officeId), {
        officeId: Number(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;
  clearVisibleErrors(false);
  selectedProvider.value = provider;
  selectedDay.value = undefined;
  selectedTimeslot.value = 0;
  await fetchAvailableDaysForSelection();
};
 
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 = toDayKey(date);
 
  const dayEntry = availableDays.value?.find(
    (day) => toDayKey(day.date) === dateString
  );
 
  if (!dayEntry) return false;
 
  // Bookable-day status (+ providerIDs) enables days not yet free-slot-checked.
  // Once checked, require real appointments (persists after the slots window moves).
  const hasProvider = dayEntry.providerIDs
    .split(",")
    .some((id) => isOfficeIdSelectedForCalendar(id.trim()));
  if (!hasProvider) {
    return false;
  }
  if (
    freeSlotCheckedDates.value.has(dateString) ||
    isDateInLoadedSlotsWindow(dateString)
  ) {
    return dayHasSlotsForSelectedProviders(dateString);
  }
  return true;
};
 
const hasAppointmentsForSelectedProviders = () => {
  return (
    availableDays?.value?.some((day) =>
      day.providerIDs.split(",").some((id) => isOfficeIdSelectedForCalendar(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()));
  });
 
  const officeHasAvailableDay = (p: OfficeImpl): boolean => {
    if (idsWithDays.has(String(p.id))) return true;
    Eif (!Array.isArray(p.sharedBookingOfficeIds)) return false;
    return p.sharedBookingOfficeIds.some((peerId) =>
      idsWithDays.has(String(peerId))
    );
  };
 
  // Filter to only providers with available days and sort by priority
  return selectableProviders.value
    .filter((p) => officeHasAvailableDay(p))
    .sort((a, b) => (b.priority ?? -Infinity) - (a.priority ?? -Infinity));
});
 
const hasSelectedProviderWithAppointments = computed(() => {
  // True only when a selected office appears in availableDays.providerIDs
  // (not merely because it is selectable).
  return (providersWithAvailableDays.value || []).some(
    (p) => !!selectedProviders.value[String(p.id)]
  );
});
 
const resolveRealOfficeIdForSlot = (
  displayOrAnyId: number,
  timeSlot: number
): number => {
  const displayId = displayOfficeIdFor(Number(displayOrAnyId));
  const fromDay = slotOwnerByTimestamp.value.get(`${displayId}_${timeSlot}`);
  if (fromDay !== undefined) return fromDay;
 
  const dayKey = selectedDay.value ? toDayKey(selectedDay.value) : null;
  if (dayKey) {
    const offices = appointmentsByDay.value.get(dayKey) ?? [];
    for (const office of offices) {
      Eif (
        displayOfficeIdFor(Number(office.officeId)) === displayId &&
        (office.appointments ?? []).includes(timeSlot)
      ) {
        return Number(office.officeId);
      }
    }
  }
 
  return Number(displayOrAnyId);
};
 
/** Real booking OfficeID for DOM / emit (shared-booking peers). */
const officeIdForTime = (
  timeSlot: number,
  displayOfficeId: number | string
): number => resolveRealOfficeIdForSlot(Number(displayOfficeId), timeSlot);
 
const handleTimeSlotSelection = async (officeId: number, timeSlot: number) => {
  clearVisibleErrors();
  selectedTimeslot.value = timeSlot;
  const realOfficeId = resolveRealOfficeIdForSlot(officeId, timeSlot);
  selectedProvider.value = getOfficeById(realOfficeId);
  Eif (summary.value) {
    await nextTick();
    summary.value.scrollIntoView({ behavior: "smooth", block: "center" });
    (buttons.value?.lastChild as HTMLElement | null)?.focus({
      preventScroll: true,
    });
  }
};
 
let skipSelectedDayWatch = false;
let daySelectionGeneration = 0;
let calendarFetchAbort: AbortController | null = null;
let calendarFetchGeneration = 0;
 
const isAbortError = (error: unknown): boolean =>
  (error instanceof DOMException && error.name === "AbortError") ||
  (typeof error === "object" &&
    error !== null &&
    "name" in error &&
    (error as { name: string }).name === "AbortError");
 
const snapHourOrDayPartAfterDayLoad = () => {
  if (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[]));
    }
    return;
  }
  Iif (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";
    }
  }
};
 
const handleDaySelection = async (day: any) => {
  Iif (!(day instanceof Date) || captchaSessionExpired.value) {
    return;
  }
 
  const dateKey = toDayKey(day);
  const isSameDay =
    !!selectedDay.value && toDayKey(selectedDay.value) === dateKey;
 
  clearVisibleErrors();
 
  if (!isSameDay) {
    selectedDay.value = day;
    selectedTimeslot.value = 0;
    selectedHour.value = null;
    selectedDayPart.value = null;
  }
 
  const generation = ++daySelectionGeneration;
  skipSelectedDayWatch = true;
  isLoadingAppointments.value = true;
  isLoadingComplete.value = false;
 
  try {
    // reloadCalendarAvailability no-ops (cache / in-flight join) when muc-calendar
    // re-emits the current day after calendarKey remounts.
    const reloaded = await reloadCalendarAvailability({
      preserveSelectedDay: true,
    });
    if (generation !== daySelectionGeneration || !reloaded) {
      return;
    }
 
    await getAppointmentsOfDay(dateKey);
    Iif (generation !== daySelectionGeneration) {
      return;
    }
 
    if (!isSameDay) {
      snapHourOrDayPartAfterDayLoad();
    }
  } finally {
    if (generation === daySelectionGeneration) {
      skipSelectedDayWatch = false;
      isLoadingAppointments.value = false;
      isLoadingComplete.value = true;
    }
  }
};
 
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);
 
/**
 * Switching back to calendar remounts MucCalendar; sync month + refresh the
 * selected day so chevrons/slots are live (list-view paging can leave markers
 * / slot window pointing at another month).
 */
const onListViewToggle = async (nextIsListView: boolean) => {
  isListView.value = nextIsListView;
  if (nextIsListView) {
    return;
  }
 
  Eif (selectedDay.value) {
    viewMonth.value = new Date(
      selectedDay.value.getFullYear(),
      selectedDay.value.getMonth(),
      1
    );
  }
  calendarKey.value++;
 
  Eif (selectedDay.value) {
    await handleDaySelection(selectedDay.value);
  }
};
 
// 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(() => {
  Iif (!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
  );
});
 
// Empty-days callout: all locations when none selected, otherwise the current selection.
const emptyStateAvailabilityInfoHtml = computed(() => {
  if (noProviderSelected.value) {
    return noneSelectedAvailabilityInfoHtml.value;
  }
  return availabilityInfoHtml.value;
});
 
const availabilityInfoHtmlForModal = computed(() => {
  return availabilityInfoHtmlOverride.value || availabilityInfoHtml.value;
});
 
const openNoneSelectedInfoModal = () => {
  const html = noneSelectedAvailabilityInfoHtml.value;
  if (html) {
    availabilityInfoHtmlOverride.value = html;
    showAvailabilityInfoModal.value = true;
  }
};
 
const openEmptyStateInfoModal = () => {
  if (noProviderSelected.value) {
    openNoneSelectedInfoModal();
    return;
  }
  openAvailabilityInfoModal();
};
 
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) => {
  Eif (selectedTimeslot.value !== time || !selectedProvider.value) {
    return false;
  }
  const selectedId = Number(selectedProvider.value.id);
  const sectionId = Number(officeId);
  return (
    selectedId === sectionId || displayOfficeIdFor(selectedId) === sectionId
  );
};
 
const nextStep = () => emit("next");
const previousStep = () => {
  captchaSessionExpired.value = false;
  clearVisibleErrors();
  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 && !captchaSessionExpired.value) {
    return {
      headerKey: "",
      textKey: "",
      errorType: "error", // Default
    };
  }
  // Otherwise, use our own error states
  return getApiErrorTranslation(errorStateMap.value, currentErrorData.value);
});
 
const lockUiForCaptchaSessionExpiry = (): void => {
  captchaSessionExpired.value = true;
  availableDays.value = [];
  appointmentsByDay.value = new Map();
  appointmentTimestampsByOffice.value = [];
  appointmentTimestamps.value = [];
  appointmentsCount.value = 0;
  selectedDay.value = undefined;
  selectedTimeslot.value = 0;
  selectedHour.value = null;
  selectedDayPart.value = null;
  loadedSlotsStartDate.value = null;
  loadedSlotsEndDate.value = null;
  freeSlotCheckedDates.value = new Set();
  prevBookableDate.value = null;
  nextBookableDate.value = null;
  availableDaysFetched.value = true;
  isSwitchingProvider.value = false;
  isLoadingAppointments.value = false;
  isLoadingComplete.value = true;
};
 
const handleError = (data: any): void => {
  error.value = true;
  handleApiResponse(data, errorStateMap.value, currentErrorData.value);
  const errorCode = getFirstErrorCode(data);
  Eif (errorCode && CAPTCHA_SESSION_ERROR_CODES.has(errorCode)) {
    lockUiForCaptchaSessionExpiry();
  }
};
 
const setNoAppointmentForThisDayError = (): void => {
  error.value = true;
  handleApiError(
    "noAppointmentForThisDay",
    errorStateMap.value,
    currentErrorData.value
  );
};
 
// API calls
const applyCalendarResponse = (calendar: AvailableCalendarDTO): boolean => {
  const days = calendar?.availableDays;
  Iif (
    !Array.isArray(days) ||
    !days.every(
      (d) =>
        typeof d === "object" && d !== null && "date" in d && "providerIDs" in d
    )
  ) {
    return false;
  }
 
  const slotsStart =
    calendar.slotsStartDate ?? calendar.startDate ?? convertDateToString(TODAY);
  const slotsEnd =
    calendar.slotsEndDate ?? calendar.endDate ?? convertDateToString(MAXDATE);
  // Free-slot SQL window from the API (usually a single day), not the painted month.
  loadedSlotsStartDate.value = slotsStart;
  loadedSlotsEndDate.value = slotsEnd;
  prevBookableDate.value = calendar.prevBookableDate ?? null;
  nextBookableDate.value = calendar.nextBookableDate ?? null;
 
  // Backend daylist covers the painted month(s) of the free-slot window only.
  const slotsStartLocal = new Date(`${toDayKey(slotsStart)}T12:00:00`);
  const slotsEndLocal = new Date(`${toDayKey(slotsEnd)}T12:00:00`);
  const paintedMonthStart = toDayKey(
    new Date(slotsStartLocal.getFullYear(), slotsStartLocal.getMonth(), 1)
  );
  const paintedMonthEnd = toDayKey(
    new Date(slotsEndLocal.getFullYear(), slotsEndLocal.getMonth() + 1, 0)
  );
 
  const nextByDay = new Map(appointmentsByDay.value);
  const nextCheckedDates = new Set(freeSlotCheckedDates.value);
  const normalizedDays: Array<{ date: string; providerIDs: string }> = [];
 
  for (const day of days) {
    const dateKey = toDayKey(day.date);
    const offices = normalizeCalendarOffices(day.offices ?? []);
    const inFreeSlotWindow = dateKey >= slotsStart && dateKey <= slotsEnd;
 
    // Overwrite appointments only for the free-slot SQL window.
    if (inFreeSlotWindow || !nextByDay.has(dateKey)) {
      nextByDay.set(dateKey, offices);
    }
 
    Iif (!day.providerIDs) {
      continue;
    }
 
    const hasAppointments = offices.some(
      (office) =>
        isOfficeIdSelectedForCalendar(office.officeId) &&
        (office.appointments?.length ?? 0) > 0
    );
 
    if (inFreeSlotWindow) {
      nextCheckedDates.add(dateKey);
      // Persist empty results: do not re-enable from daylist providerIDs later.
      if (!hasAppointments) {
        continue;
      }
    } else if (nextCheckedDates.has(dateKey)) {
      // Previously free-slot-checked; keep using cached appointment map.
      const cachedHasSlots = (nextByDay.get(dateKey) ?? []).some(
        (office) =>
          isOfficeIdSelectedForCalendar(office.officeId) &&
          (office.appointments?.length ?? 0) > 0
      );
      Eif (!cachedHasSlots) {
        continue;
      }
    }
 
    // When free-slot office data is present, only keep offices that actually
    // have appointments — daylist providerIDs can list offices with zero slots.
    const officesForProviderIds = nextByDay.get(dateKey) ?? offices;
    const providerIdsWithSlots = officesForProviderIds
      .filter((office) => (office.appointments?.length ?? 0) > 0)
      .map((office) => String(office.officeId));
    const providerIDs =
      providerIdsWithSlots.length > 0
        ? providerIdsWithSlots.join(",")
        : day.providerIDs;
 
    normalizedDays.push({
      date: day.date,
      providerIDs,
    });
  }
 
  appointmentsByDay.value = nextByDay;
  freeSlotCheckedDates.value = nextCheckedDates;
 
  // Merge daylists across months: replace only the painted month from this response
  // so ListView / calendar can accumulate the full bookable horizon.
  const mergedByDate = new Map<string, { date: string; providerIDs: string }>();
  for (const day of availableDays.value ?? []) {
    const key = toDayKey(day.date);
    if (key < paintedMonthStart || key > paintedMonthEnd) {
      mergedByDate.set(key, day);
    }
  }
  for (const day of normalizedDays) {
    mergedByDate.set(toDayKey(day.date), day);
  }
  availableDays.value = Array.from(mergedByDate.values()).sort((a, b) =>
    toDayKey(a.date).localeCompare(toDayKey(b.date))
  );
 
  updateCalendarNavigationBounds(availableDays.value);
  calendarKey.value++;
  return true;
};
 
const jumpToBookableDate = async (isoDate: string) => {
  const day = new Date(`${isoDate}T12:00:00`);
  if (Number.isNaN(day.getTime())) {
    return;
  }
  await handleDaySelection(day);
};
 
const isLoadingMoreListDays = ref(false);
 
const firstOfNextMonth = (isoDate: string): string => {
  const d = new Date(`${toDayKey(isoDate)}T12:00:00`);
  return convertDateToString(new Date(d.getFullYear(), d.getMonth() + 1, 1));
};
 
const monthKey = (isoDate: string): string => toDayKey(isoDate).slice(0, 7);
 
const hasDaysInMonth = (isoDate: string): boolean => {
  const key = monthKey(isoDate);
  return (availableDays.value ?? []).some((day) => monthKey(day.date) === key);
};
 
const lastLoadedListDayKey = computed(() => {
  const days = availableDays.value ?? [];
  Iif (days.length === 0) {
    return null;
  }
  return days
    .map((day) => toDayKey(day.date))
    .sort((a, b) => a.localeCompare(b))
    .at(-1)!;
});
 
/** Later months may still exist beyond the currently merged daylist. */
const hasMoreListDaysAhead = computed(() => {
  const lastKey = lastLoadedListDayKey.value;
  if (!nextBookableDate.value) {
    return false;
  }
  Iif (!lastKey) {
    return true;
  }
  return nextBookableDate.value > lastKey;
});
 
/**
 * ListView "Mehr laden": fetch the next month's daylist and merge it into availableDays.
 * Does not change the open accordion / selected day.
 */
const loadMoreListViewDays = async () => {
  Iif (isLoadingMoreListDays.value || captchaSessionExpired.value) {
    return;
  }
 
  const maxKey = convertDateToString(MAXDATE);
  const lastKey = lastLoadedListDayKey.value ?? convertDateToString(TODAY);
  let fetchDate =
    nextBookableDate.value && nextBookableDate.value > lastKey
      ? nextBookableDate.value
      : firstOfNextMonth(lastKey);
 
  // Skip months already present in the merged daylist.
  while (fetchDate <= maxKey && hasDaysInMonth(fetchDate)) {
    fetchDate = firstOfNextMonth(fetchDate);
  }
 
  Iif (fetchDate > maxKey) {
    return;
  }
 
  isLoadingMoreListDays.value = true;
  try {
    await reloadCalendarAvailability({
      preserveSelectedDay: true,
      replaceAvailableDays: false,
      allowSlotsFollowUp: false,
      slotsStartDate: fetchDate,
      slotsEndDate: fetchDate,
    });
  } finally {
    isLoadingMoreListDays.value = false;
  }
};
 
/**
 * Office IDs for available-calendar. Once checkboxes exist, only
 * checked offices are sent so next/prevBookableDate match the selection.
 * Shared-booking peers expand so both OfficeIDs participate in capacity.
 */
const getOfficeIdsForCalendarRequest = (): number[] => {
  const selectable = selectableProviders.value || [];
  const selectableIds = new Set(selectable.map((p) => Number(p.id)));
  const hasCheckboxState = Object.keys(selectedProviders.value).length > 0;
 
  const baseIds = hasCheckboxState
    ? Object.entries(selectedProviders.value)
        .filter(([, isSelected]) => isSelected)
        .map(([id]) => Number(id))
        .filter((id) => selectableIds.has(id))
    : selectable.map((p) => Number(p.id));
 
  // Peers must be offered by every selected service — available-calendar
  // validates each officeId against all serviceIds. A union (any service)
  // wrongly expands Ausbildung 10503 when only the main service exists there.
  const services = [
    selectedService.value,
    ...(selectedService.value?.subServices || []).filter((s) => s.count > 0),
  ].filter(Boolean) as Array<{ providers?: Array<{ id: string | number }> }>;
  const peerOfferedByAllSelectedServices = (peer: number): boolean => {
    Iif (services.length === 0) return true;
    return services.every((service) =>
      (service.providers || []).some((p) => Number(p.id) === peer)
    );
  };
 
  const expanded = new Set<number>();
  for (const id of baseIds) {
    expanded.add(id);
    const office =
      selectable.find((p) => Number(p.id) === id) || getOfficeById(id);
    if (!Array.isArray(office?.sharedBookingOfficeIds)) continue;
    for (const peerId of office.sharedBookingOfficeIds) {
      const peer = Number(peerId);
      if (peerOfferedByAllSelectedServices(peer)) {
        expanded.add(peer);
      }
    }
  }
 
  return [...expanded];
};
 
const reloadCalendarAvailability = async (options?: {
  preserveSelectedDay?: boolean;
  /** Prevent infinite reload when API/mocks return a slots window that still excludes selectedDay */
  allowSlotsFollowUp?: boolean;
  /** Override free-slot window (e.g. ListView paging into later months). */
  slotsStartDate?: string;
  slotsEndDate?: string;
  /**
   * When true, drop accumulated daylist before applying the response.
   * Defaults to true for fresh loads; false when preserving selection (merge months).
   */
  replaceAvailableDays?: boolean;
  /** Bypass same-key cache / in-flight join (tests or forced refresh). */
  force?: boolean;
}): Promise<boolean> => {
  const allowSlotsFollowUp = options?.allowSlotsFollowUp !== false;
  const replaceAvailableDays =
    options?.replaceAvailableDays ?? !options?.preserveSelectedDay;
  const officeIds = getOfficeIdsForCalendarRequest();
 
  if (officeIds.length === 0) {
    availableDays.value = [];
    appointmentsByDay.value = new Map();
    loadedSlotsStartDate.value = null;
    loadedSlotsEndDate.value = null;
    freeSlotCheckedDates.value = new Set();
    prevBookableDate.value = null;
    nextBookableDate.value = null;
    availableDaysFetched.value = true;
    lastFetchedRequestKey = null;
    return false;
  }
 
  const defaultSlots = getFreeSlotsWindow();
  const slotsStartDate = options?.slotsStartDate ?? defaultSlots.slotsStartDate;
  const slotsEndDate = options?.slotsEndDate ?? defaultSlots.slotsEndDate;
  const requestKey = buildCalendarRequestKey(
    officeIds,
    slotsStartDate,
    slotsEndDate
  );
 
  // Identical request already applied — muc-calendar remounts must not refetch.
  if (
    !options?.force &&
    lastFetchedRequestKey === requestKey &&
    availableDaysFetched.value
  ) {
    return true;
  }
 
  // Identical request already in flight — join it (do not abort + restart).
  if (
    !options?.force &&
    inFlightRequestKey === requestKey &&
    inFlightCalendarPromise !== null
  ) {
    return inFlightCalendarPromise;
  }
 
  // Different params supersede any older in-flight call.
  calendarFetchAbort?.abort();
 
  // Fresh calendar load (not a day re-click): drop prior free-slot verdicts.
  if (!options?.preserveSelectedDay) {
    freeSlotCheckedDates.value = new Set();
    appointmentsByDay.value = new Map();
  }
  if (replaceAvailableDays) {
    availableDays.value = [];
  }
 
  const abortController = new AbortController();
  calendarFetchAbort = abortController;
  const generation = ++calendarFetchGeneration;
  inFlightRequestKey = requestKey;
 
  const run = async (): Promise<boolean> => {
    let data: AvailableCalendarDTO | ErrorDTO;
    try {
      data = await fetchAvailableCalendar(
        props.globalState,
        officeIds,
        Array.from(props.selectedServiceMap.keys()),
        Array.from(props.selectedServiceMap.values()),
        props.captchaToken ?? undefined,
        slotsStartDate,
        slotsEndDate,
        abortController.signal
      );
    } catch (error) {
      if (isAbortError(error) || abortController.signal.aborted) {
        return false;
      }
      if (generation === calendarFetchGeneration) {
        handleError({ errors: [{ errorCode: "networkError" }] });
        availableDaysFetched.value = true;
        isSwitchingProvider.value = false;
      }
      return false;
    }
 
    Iif (generation !== calendarFetchGeneration) {
      return false;
    }
 
    if (data && typeof data === "object" && "errors" in data) {
      handleError(data);
      return false;
    }
 
    const calendar = data as AvailableCalendarDTO;
    Iif (!applyCalendarResponse(calendar)) {
      handleError(data);
      return false;
    }
 
    lastFetchedRequestKey = requestKey;
    availableDaysFetched.value = true;
    clearLocalApiErrors();
 
    const hadSelectedDay = !!selectedDay.value;
 
    if (
      !options?.preserveSelectedDay &&
      !hadSelectedDay &&
      availableDays.value.length > 0
    ) {
      // Prefer a day that already has times loaded to avoid an immediate follow-up.
      const firstWithSlotsInWindow = availableDays.value.find(
        (day) =>
          isDateInLoadedSlotsWindow(toDayKey(day.date)) &&
          dayHasSlotsForSelectedProviders(toDayKey(day.date))
      );
      const firstInWindow = availableDays.value.find((day) =>
        isDateInLoadedSlotsWindow(toDayKey(day.date))
      );
      const firstWithSlots = availableDays.value.find((day) =>
        dayHasSlotsForSelectedProviders(toDayKey(day.date))
      );
      const picked =
        firstWithSlotsInWindow ??
        firstInWindow ??
        firstWithSlots ??
        availableDays.value[0];
      // Noon avoids UTC date-only parsing shifting the calendar day.
      selectedDay.value = new Date(`${toDayKey(picked.date)}T12:00:00`);
    }
 
    // Auto-selected (or preserved) day may fall outside the month we just loaded.
    // Follow up at most once — mocks that ignore slots params must not recurse forever.
    if (
      allowSlotsFollowUp &&
      selectedDay.value &&
      !isDateInLoadedSlotsWindow(toDayKey(selectedDay.value))
    ) {
      return reloadCalendarAvailability({
        preserveSelectedDay: true,
        allowSlotsFollowUp: false,
      });
    }
 
    if (selectedDay.value) {
      viewMonth.value = new Date(
        selectedDay.value.getFullYear(),
        selectedDay.value.getMonth(),
        1
      );
    }
 
    updateDateRangeForSelectedProviders(options?.preserveSelectedDay === true);
    return true;
  };
 
  inFlightCalendarPromise = run().finally(() => {
    if (generation === calendarFetchGeneration) {
      inFlightRequestKey = null;
      inFlightCalendarPromise = null;
    }
  });
  return inFlightCalendarPromise;
};
 
const fetchAvailableDaysForSelection = async (): Promise<void> => {
  Iif (!(selectableProviders.value || []).length) {
    availableDays.value = [];
    availableDaysFetched.value = true;
    clearLocalApiErrors();
    isSwitchingProvider.value = false;
    updateDateRangeForSelectedProviders();
    return;
  }
 
  const reloaded = await reloadCalendarAvailability();
  // Aborted/superseded by another calendar fetch — leave spinner flags to that request.
  Iif (!reloaded) {
    return;
  }
 
  if (selectedDay.value) {
    await getAppointmentsOfDay(toDayKey(selectedDay.value));
  }
 
  availableDaysFetched.value = true;
  isSwitchingProvider.value = false;
};
 
const getAppointmentsOfDay = async (date: string): Promise<void> => {
  isLoadingAppointments.value = true;
  appointmentTimestamps.value = [];
  appointmentTimestampsByOffice.value = [];
 
  const selectedProviderIds = Object.keys(selectedProviders.value).filter(
    (id) => selectedProviders.value[id]
  );
  if (selectedProviderIds.length === 0) {
    isLoadingAppointments.value = false;
    isLoadingComplete.value = true;
    return;
  }
 
  const officesForDay = appointmentsByDay.value.get(toDayKey(date)) ?? [];
  const selectedOffices = officesForDay.filter((office) =>
    isOfficeIdSelectedForCalendar(office.officeId)
  );
  const { aggregated, slotOwnerByTimestamp: owners } =
    aggregateSharedBookingOffices(selectedOffices);
  appointmentTimestampsByOffice.value = aggregated;
  slotOwnerByTimestamp.value = owners;
 
  appointmentsCount.value = appointmentTimestampsByOffice.value.reduce(
    (sum, office) => sum + (office.appointments?.length ?? 0),
    0
  );
 
  if (appointmentsCount.value === 0) {
    setNoAppointmentForThisDayError();
  } else {
    clearLocalApiErrors();
  }
 
  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) => {
    if (allowedIds.has(p.id)) filteredProvidersMap.set(Number(p.id), p);
  });
 
  // Filter out providers where any selected service is in their disabledByServices.
  // Mix-group peers are kept here, then collapsed to one Ort below.
  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;
      }
 
      const participatesInMix =
        (Array.isArray(p.allowDisabledServicesMix) &&
          p.allowDisabledServicesMix.length > 0) ||
        p.allowDisabledServicesMix === true;
      if (participatesInMix) {
        return true;
      }
 
      return false;
    }
  );
 
  // Collapse shared-booking peers to one Ort (lowest id as stable display).
  // Distinct from allowDisabledServicesMix (exclusive vs mixed survivor).
  const sharedGroupKey = (p: OfficeImpl): string => {
    if (
      Array.isArray(p.sharedBookingOfficeIds) &&
      p.sharedBookingOfficeIds.length > 0
    ) {
      return [...p.sharedBookingOfficeIds]
        .map(Number)
        .sort((a, b) => a - b)
        .join(",");
    }
    return `id:${p.id}`;
  };
 
  const afterSharedCollapse = Object.values(
    filteredProviders.reduce<Record<string, OfficeImpl[]>>(
      (grouped, provider) => {
        (grouped[sharedGroupKey(provider)] ||= []).push(provider);
        return grouped;
      },
      {}
    )
  ).map((group) => {
    if (group.length === 1) return group[0];
    return [...group].sort((a, b) => Number(a.id) - Number(b.id))[0];
  });
 
  // Collapse allowDisabledServicesMix peers to one Ort (exclusive vs mixed).
  // Pair by mix group ids — not by display name.
  const mixGroupKey = (p: OfficeImpl): string => {
    if (
      Array.isArray(p.allowDisabledServicesMix) &&
      p.allowDisabledServicesMix.length > 0
    ) {
      return [...p.allowDisabledServicesMix]
        .map(Number)
        .sort((a, b) => a - b)
        .join(",");
    }
    return `id:${p.id}`;
  };
 
  return Object.values(
    afterSharedCollapse.reduce<Record<string, OfficeImpl[]>>(
      (grouped, provider) => {
        (grouped[mixGroupKey(provider)] ||= []).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);
  });
}
 
/**
 * MucCalendar enables/disables month chevrons from min/max.
 * Use adjacent bookable markers when present so empty months stay skippable;
 * otherwise clamp to the loaded bookable range so the last/first month disables next/prev.
 */
function updateCalendarNavigationBounds(
  daysForBounds: Array<{ date: string }> = availableDays.value ?? []
) {
  let earliest: string | null = loadedSlotsStartDate.value;
  let latest: string | null = loadedSlotsEndDate.value;
 
  for (const day of daysForBounds) {
    const key = toDayKey(day.date);
    if (earliest === null || key < earliest) {
      earliest = key;
    }
    if (latest === null || key > latest) {
      latest = key;
    }
  }
 
  const minIso =
    prevBookableDate.value ?? earliest ?? convertDateToString(TODAY);
  const maxIso =
    nextBookableDate.value ?? latest ?? convertDateToString(MAXDATE);
 
  let min = new Date(`${minIso}T12:00:00`);
  let max = new Date(`${maxIso}T12:00:00`);
  // Noon-normalized "today" so wall-clock time cannot push min past same-day max.
  const todayNoon = new Date(TODAY);
  todayNoon.setHours(12, 0, 0, 0);
 
  Iif (Number.isNaN(min.getTime())) {
    min = new Date(todayNoon);
  }
  Iif (Number.isNaN(max.getTime())) {
    max = new Date(MAXDATE);
  }
  if (min < todayNoon) {
    min = new Date(todayNoon);
  }
  Iif (max > MAXDATE) {
    max = new Date(MAXDATE);
  }
  if (min > max) {
    max = new Date(min);
  }
 
  minDate.value = min;
  maxDate.value = max;
}
 
function updateDateRangeForSelectedProviders(skipDateValidation = false) {
  Iif (!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) {
    updateCalendarNavigationBounds(availableDaysForSelectedProviders);
    // 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
    if (!skipDateValidation) {
      validateAndUpdateSelectedDate(availableDaysForSelectedProviders);
    }
  }
  return availableDaysForSelectedProviders;
}
 
async function validateAndUpdateSelectedDate(
  availableDaysForSelectedProviders: any[]
) {
  Iif (availableDaysForSelectedProviders.length === 0) return;
 
  const sortedDays = [...availableDaysForSelectedProviders].sort((a, b) =>
    toDayKey(a.date).localeCompare(toDayKey(b.date))
  );
  const earliestKey = toDayKey(sortedDays[0].date);
  const currentKey = selectedDay.value ? toDayKey(selectedDay.value) : null;
 
  if (currentKey === earliestKey) {
    return;
  }
 
  // Noon avoids UTC date-only parsing shifting the calendar day.
  await handleDaySelection(new Date(`${earliestKey}T12:00:00`));
}
 
async function snapToNearestForCurrentView() {
  Iif (isListView.value) {
    await listViewRef.value?.snapToNearest?.();
  } else {
    await calendarViewRef.value?.snapToNearest?.();
  }
}
 
function scheduleRefreshAfterProviderChange() {
  Iif (captchaSessionExpired.value || initialCalendarLoadPending) {
    return;
  }
  // Bump generation so only the latest toggle owns the spinner / finally-clear.
  const generation = ++providerRefreshGeneration;
  const selectionSnapshot = JSON.stringify(selectedProviders.value);
  if (refetchTimer) clearTimeout(refetchTimer);
  refetchTimer = setTimeout(async () => {
    Iif (generation !== providerRefreshGeneration) {
      return;
    }
    Iif (selectionSnapshot !== JSON.stringify(selectedProviders.value)) {
      return;
    }
    Iif (initialCalendarLoadPending) {
      if (generation === providerRefreshGeneration) {
        isSwitchingProvider.value = false;
      }
      return;
    }
 
    const checkedIds = getOfficeIdsForCalendarRequest();
    if (checkedIds.length === 0) {
      Eif (generation === providerRefreshGeneration) {
        isSwitchingProvider.value = false;
      }
      return;
    }
 
    // Same offices/services/slots as the last successful fetch — skip API.
    const slots = getFreeSlotsWindow();
    const nextKey = buildCalendarRequestKey(
      checkedIds,
      slots.slotsStartDate,
      slots.slotsEndDate
    );
    if (availableDaysFetched.value && nextKey === lastFetchedRequestKey) {
      Eif (generation === providerRefreshGeneration) {
        isSwitchingProvider.value = false;
      }
      return;
    }
 
    // Ensure spinner is visible for the whole in-flight refetch (incl. initial races).
    isSwitchingProvider.value = true;
 
    try {
      // Refetch with only checked offices so next/prevBookableDate match selection.
      // Replace daylist: office set changed, do not keep prior offices' months.
      const reloaded = await reloadCalendarAvailability({
        preserveSelectedDay: true,
        replaceAvailableDays: true,
      });
      Iif (generation !== providerRefreshGeneration) {
        return;
      }
      Iif (!reloaded) {
        return;
      }
 
      availableDaysFetched.value = true;
 
      const daysForSelection = updateDateRangeForSelectedProviders(true);
      if (daysForSelection.length === 0) {
        return;
      }
 
      const sortedDays = [...daysForSelection].sort((a, b) =>
        toDayKey(a.date).localeCompare(toDayKey(b.date))
      );
      const earliestKey = toDayKey(sortedDays[0].date);
      const currentKey = selectedDay.value ? toDayKey(selectedDay.value) : null;
 
      // One deterministic rule: earliest day across checked offices, then fetch.
      if (currentKey !== earliestKey) {
        await handleDaySelection(new Date(`${earliestKey}T12:00:00`));
      } else Eif (currentKey) {
        await getAppointmentsOfDay(currentKey);
      }
 
      Iif (generation !== providerRefreshGeneration) {
        return;
      }
 
      await snapToNearestForCurrentView();
    } finally {
      // Keep spinner up if a newer checkbox toggle already started another refresh.
      Eif (generation === providerRefreshGeneration) {
        isSwitchingProvider.value = false;
      }
    }
  }, 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) ||
        Number(office.parentId) === Number(props.preselectedOfficeId) ||
        (Array.isArray(office.allowDisabledServicesMix) &&
          office.allowDisabledServicesMix.includes(
            Number(props.preselectedOfficeId)
          )) ||
        (Array.isArray(office.sharedBookingOfficeIds) &&
          office.sharedBookingOfficeIds.includes(
            Number(props.preselectedOfficeId)
          )));
 
    let offices = selectableProviders.value.filter((office) => {
      if (props.preselectedOfficeId) {
        return preselectedMatches(office);
      } else Iif (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;
      });
    }
 
    // Claim the initial fetch before checkbox init so the selectedProviders watch
    // cannot schedule a parallel refresh while onMounted loads the calendar.
    initialCalendarLoadPending = true;
    selectedProviders.value = selectableProviders.value.reduce(
      (acc, item) => {
        acc[item.id] = props.preselectedOfficeId
          ? Boolean(preselectedMatches(item))
          : true;
        return acc;
      },
      {} as { [id: string]: boolean }
    );
    initialized = true;
 
    officeOrder.value = new Map(
      selectableProviders.value.map((office, index) => [
        Number(office.id),
        index,
      ])
    );
 
    void showSelectionForProvider(firstOfficeToShow ?? offices[0]).finally(
      () => {
        initialCalendarLoadPending = false;
      }
    );
  }
});
 
onUnmounted(() => {
  Iif (refetchTimer) clearTimeout(refetchTimer);
  calendarFetchAbort?.abort();
});
 
watch(isLoadingAppointments, (loading) => {
  if (loading) {
    isLoadingComplete.value = false;
  }
});
 
watch(selectedDay, async (newDate) => {
  if (skipSelectedDayWatch) return;
  selectedTimeslot.value = 0;
  if (newDate) {
    await getAppointmentsOfDay(toDayKey(selectedDay.value || newDate));
  }
});
 
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[]));
    }
  }
  // For am/pm view
  else Iif (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 () => {
    Iif (captchaSessionExpired.value) {
      return;
    }
    // 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 Eif (selectedIds.length !== 1) {
      selectedProvider.value = undefined;
    }
 
    const hasAvailableDays =
      availableDays.value && availableDays.value.length > 0;
    const daysWereFetched = availableDaysFetched.value;
 
    clearVisibleErrors(daysWereFetched || hasAvailableDays);
 
    // Keep the calendar spinner up for any checked-office refetch — do not flash
    // the empty-state callout while availableDays still reflect the old office set.
    if (selectedIds.length > 0) {
      isSwitchingProvider.value = true;
    } else {
      isSwitchingProvider.value = false;
    }
 
    // Initial load owns the first fetch; checkbox init must not abort/refetch it.
    if (initialCalendarLoadPending || !availableDaysFetched.value) {
      return;
    }
 
    // 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>