All files / src/flow Editor.ts

85.55% Statements 3529/4125
82.79% Branches 255/308
85.71% Functions 84/98
85.55% Lines 3529/4125

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 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 412696x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x                                                                                           249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 96x 96x 96x 96x 9x 9x 9x 9x 9x 3x 3x 3x 3x 3x 3x 3x 9x 9x 9x 9x 8x 96x 96x 96x 96x 96x 96x 96x 96x 96x 1x 1x 96x 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 6x 6x 6x 6x 6x 6x 6x 6x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 249x 249x 249x 249x 249x 96x 96x 96x 203x 203x 203x 203x 207x 207x 203x 494x 494x 494x 494x 494x 494x 67x 67x 67x 67x 67x 67x 67x 67x 494x 494x 494x 494x 67x 67x 67x 67x 67x 67x 494x 494x 494x 494x 494x 494x 494x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 94x 94x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 427x     427x     427x         427x 427x 427x 427x 427x 427x 427x 427x         28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x                                           585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 585x 96x 209x 209x 209x 209x 209x 209x 209x 209x 209x 68x 209x 209x 209x 209x 209x 209x                 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x           209x                       209x 209x 209x 209x 96x 1x 1x                         1x                                                                                                                                         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 96x 493x 493x 493x 493x 493x 341x 341x 341x 341x 341x 86x 341x 493x 493x 25x 25x       25x 25x 25x 25x 1x 1x 1x 1x 25x 24x 25x 232x 232x 96x 211x 211x 211x 211x 211x 211x 211x 211x 211x       211x     96x 490x 490x 490x 490x 209x 490x 490x 211x 211x 211x 490x 490x 490x 490x 490x 490x 490x 209x 203x 203x 203x 203x 203x 203x 203x 203x 209x 209x 490x 209x 490x 490x 329x 329x 329x 209x 209x 209x 209x 209x 209x 209x 1x 209x 208x 208x 490x 490x 490x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 490x 490x 490x 230x 23x 23x 23x 1x 23x 22x 22x 490x 490x 490x 240x 28x 28x 28x 28x 28x 15x 15x 240x 212x 212x 212x 212x 212x 212x 212x 72x 56x 56x 56x 56x 490x 490x 3x 3x 3x 3x 3x 96x 96x 96x 96x 96x 96x 96x 96x 96x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 96x 22x 22x 22x 2x 22x 22x                         22x 96x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 3x 3x 3x 1x 1x 3x 2x 2x 2x 2x 2x   2x     3x 2x 2x 2x 2x 3x   5x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 5x 5x 5x 5x 5x 96x 5x 5x 5x 2x 2x 2x 2x 5x 1x 5x 2x 2x 1x 5x 5x 1x 1x 96x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 96x         294x 294x 294x 96x 1x 1x 1x 1x 1x 96x 294x 294x 294x 294x 294x 147x 147x 147x 147x 187x 147x 147x 147x 147x 147x 187x 131x 131x 131x 131x 131x 131x 16x 16x 16x 16x 16x 8x 8x 130x 16x 16x 16x   131x 96x 25x 96x 795x 344x 795x 344x 344x 344x 1032x 344x 795x 795x 795x 38x 795x           451x 451x 96x 488x 488x 307x 307x 307x 307x 307x 307x 307x 307x 307x 96x 832x 832x 832x 832x 832x 832x 832x 96x 101x 101x 101x 101x 76x 76x 76x 76x 135x 135x 135x 135x 135x 76x 6x         6x 96x 179x 179x 179x 179x 179x 179x 179x 179x 179x 96x 209x 209x 209x 209x 209x 209x 68x 68x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 8x 8x 8x 8x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x   209x 209x 209x 96x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x                 209x 209x                     209x 209x 209x                   209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x 209x         209x 209x           209x 96x                                         96x               96x 96x 96x 96x 96x 1x 1x 1x                           1x 1x       1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 96x 96x 96x                                       96x 96x 96x                             96x 11x 11x 96x 19x 19x 3x 3x 3x 3x 3x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 96x 175x 8x 96x                                                                                                   96x 96x                                                                                                                                                                                                           96x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 85x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 488x 488x 488x 488x 488x 488x           96x                                         488x 488x 488x 488x 488x                                                             488x 488x 488x 488x 488x 488x 488x     488x 488x 488x     96x 488x   488x 488x 488x 488x   488x 488x 488x                                       96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x  
import { html, TemplateResult } from 'lit-html';
import { css, PropertyValueMap, PropertyValues, unsafeCSS } from 'lit';
import { property, state } from 'lit/decorators.js';
import {
  FlowDefinition,
  FlowPosition,
  Action,
  Node,
  NodeUI
} from '../store/flow-definition';
import { getStore, Store } from '../store/Store';
import { AppState, FlowIssue, fromStore, zustand } from '../store/AppState';
import { RapidElement } from '../RapidElement';
import { repeat } from 'lit-html/directives/repeat.js';
import { CustomEventType, DirtyTrackable, Workspace } from '../interfaces';
import {
  generateUUID,
  getClasses,
  getCookie,
  setCookie,
  WebResponse
} from '../utils';
import { TEMBA_COMPONENTS_VERSION } from '../version';
import {
  getLanguageDisplayName,
  getNodeBounds,
  calculateReflowPositions,
  NodeBounds,
  snapToGrid
} from './utils';
import { ACTION_CONFIG, NODE_CONFIG } from './config';
import { PRIMARY_LANGUAGE_OPTION_VALUE } from './EditorToolbar';
import {
  buildTranslationBundles,
  getTranslationCounts
} from './flow-translations';
import { calculateLayeredLayout, placeStickyNotes } from './reflow';
import type { RevisionsWindow } from './RevisionsWindow';
 
import {
  ACTION_GROUP_METADATA,
  CONTEXT_MENU_SHORTCUTS,
  FlowType,
  FlowTypes
} from './types';
 
import {
  Plumber,
  calculateFlowchartPath,
  ARROW_LENGTH,
  ARROW_HALF_WIDTH
} from './Plumber';
import { CanvasNode } from './CanvasNode';
import { DragManager } from './DragManager';
import { ZoomManager } from './ZoomManager';
import { Dialog } from '../layout/Dialog';
 
import { CanvasMenu, CanvasMenuSelection } from './CanvasMenu';
import { NodeTypeSelector, NodeTypeSelection } from './NodeTypeSelector';
import { FlowSearch, SearchResult } from './FlowSearch';
 
export function findNodeForExit(
  definition: FlowDefinition,
  exitUuid: string
): string | null {
  for (const node of definition.nodes) {
    const exit = node.exits.find((e) => e.uuid === exitUuid);
    if (exit) {
      return node.uuid;
    }
  }
  return null;
}
 
const SAVE_QUIET_TIME = 2000;

export interface DraggableItem {
  uuid: string;
  position: FlowPosition;
  element: HTMLElement;
  type: 'node' | 'sticky';
}

export interface SelectionBox {
  startX: number;
  startY: number;
  endX: number;
  endY: number;
}

export type ToolbarAction =
  | { action: 'view-change'; view: 'flow' | 'table' }
  | { action: 'zoom-in' }
  | { action: 'zoom-out' }
  | { action: 'zoom-to-fit' }
  | { action: 'zoom-to-full' }
  | { action: 'revisions' }
  | { action: 'search' }
  | { action: 'language-change'; isPrimary?: boolean; languageCode?: string }
  | { action: 'auto-translate' };
const EMPTY_FLOW_ISSUES: FlowIssue[] = [];

// How long the pending-changes auto-save countdown runs (in ms).
// Used in both the CSS animation and the JS setTimeout.
const PENDING_SAVE_DELAY = 5000;

/**
 * Manages a timed "pending changes" card that lets users discard or auto-save
 * after a delay.  Used for both auto-layout and shift+drag copy.
 */
class PendingChangesTimer {
  /** Whether the card is visible. */
  unsaved = false;

  /**
   * Flag consumed once per willUpdate cycle to suppress the debounced save
   * that would otherwise fire when dirtyDate changes.
   */
  pending = false;
 
  /** Counter incremented on every start/reset – used as a Lit template key
   *  so the CSS countdown animation restarts. */
  resetCount = 0;
 
  private timer: ReturnType<typeof setTimeout> | null = null;
 
  constructor(
    public readonly label: string,
    private readonly delay: number,
    private readonly host: { requestUpdate(): void },
    private readonly onExpire: () => void
  ) {}
 
  /** Show the card and start (or restart) the countdown timer. */
  start(requestRender = true): void {
    this.clearTimer();
    this.resetCount++;
    this.unsaved = true;
    this.timer = setTimeout(() => {
      this.timer = null;
      if (this.unsaved) {
        this.unsaved = false;
        this.host.requestUpdate();
        this.onExpire();
      }
    }, this.delay);
    if (requestRender) {
      this.host.requestUpdate();
    }
  }
 
  /** Hide the card and cancel the timer without calling any callback. */
  dismiss(): void {
    this.unsaved = false;
    this.clearTimer();
    this.host.requestUpdate();
  }
 
  clearTimer(): void {
    if (this.timer !== null) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  }
}
 
// Offset for positioning dropped action node relative to mouse cursor
// Keep small to make drop location close to cursor position
const DROP_PREVIEW_OFFSET_X = 20;
const DROP_PREVIEW_OFFSET_Y = 20;
 
export class Editor extends RapidElement {
  // connection SVGs are appended directly to the canvas, so we need light DOM
  createRenderRoot() {
    return this;
  }
 
  // this is the master plumber
  public plumber: Plumber;
 
  // drag/selection manager
  public dragManager: DragManager;
 
  // zoom/pan/loupe manager
  public zoomManager: ZoomManager;
 
  // timer for debounced saving
  private saveTimer: number | null = null;
 
  @property({ type: String })
  public flow: string;
 
  @property({ type: String })
  public version: string;
 
  @property({ type: String })
  public flowType: FlowType = FlowTypes.MESSAGE;
 
  @property({ type: Array })
  public features: string[] = [];
 
  private activityTimer: number | null = null;
  private activityInterval = 100; // Start with 100ms interval for fast initial load
 
  @fromStore(zustand, (state: AppState) => state.flowDefinition)
  public definition!: FlowDefinition;
 
  @fromStore(zustand, (state: AppState) => state.simulatorActive)
  private simulatorActive!: boolean;
 
  @fromStore(zustand, (state: AppState) => state.canvasSize)
  private canvasSize!: { width: number; height: number };
 
  @fromStore(zustand, (state: AppState) => state.dirtyDate)
  private dirtyDate!: Date;
 
  @fromStore(zustand, (state: AppState) => state.languageCode)
  private languageCode!: string;
 
  @fromStore(zustand, (state: AppState) => state.isTranslating)
  private isTranslating!: boolean;
 
  @fromStore(zustand, (state: AppState) => state.workspace)
  private workspace!: Workspace;
 
  @fromStore(zustand, (state: AppState) => state.getCurrentActivity())
  private activityData!: any;
 
  @fromStore(
    zustand,
    (state: AppState) => state.flowInfo?.issues ?? EMPTY_FLOW_ISSUES
  )
  private flowIssues!: FlowIssue[];
 
  // Drag state (managed by DragManager, kept on Editor for Lit reactivity)
  @state()
  public isDragging = false;
 
  // Public getter for drag state
  public get dragging(): boolean {
    return this.isDragging;
  }
 
  @state()
  public currentDragItem: DraggableItem | null = null;
 
  // Selection state
  @state()
  public selectedItems: Set<string> = new Set();
 
  @state()
  public isSelecting = false;
 
  @state()
  public selectionBox: SelectionBox | null = null;
 
  @state()
  public targetId: string | null = null;
 
  @state()
  public sourceId: string | null = null;
 
  @state()
  public dragFromNodeId: string | null = null;
 
  @state()
  public originalConnectionTargetId: string | null = null;
 
  @state()
  public isValidTarget = true;
 
  // Canvas-relative source exit position (set at drag start)
  public connectionSourceX: number | null = null;
  public connectionSourceY: number | null = null;
 
  @state()
  private issuesWindowHidden = true;
 
  @state()
  private revisionsWindowHidden = true;
 
  @state()
  private viewingRevision = false;
 
  @state()
  public isSaving = false;
 
  @state()
  private saveError: string | null = null;
 
  @state()
  public zoom = 1.0;
 
  @state()
  private autoTranslating = false;
 
  // Non-reactive flag set in willUpdate to suppress the debouncedSave
  // call in updated() when the dirtyDate change comes from a reflow/copy
  private _suppressDirtySave = false;
 
  // Tracks the in-flight save so disconnectedCallback can defer cleanup
  private savePromise: Promise<void> | null = null;
 
  // --- Pending-changes timer (shared by reflow + copy) ---
 
  public pendingTimer = new PendingChangesTimer(
    'Unsaved Changes',
    PENDING_SAVE_DELAY,
    this,
    () => {
      this.pendingPositions = null;
      this.copiedItemUuids = [];
      this.saveChanges();
    }
  );
 
  /** Positions of all items captured before the first pending operation. */
  private pendingPositions: Record<string, FlowPosition> | null = null;
 
  /** UUIDs of items created by shift+drag copy during the pending window. */
  public copiedItemUuids: string[] = [];
 
  /** Save all current canvas positions if not already saved. */
  public capturePositionsOnce(): void {
    if (this.pendingPositions) return;
    const saved: Record<string, FlowPosition> = {};
    for (const node of this.definition.nodes) {
      const ui = this.definition._ui?.nodes[node.uuid];
      if (ui?.position) {
        saved[node.uuid] = { ...ui.position };
      }
    }
    const stickies = this.definition._ui?.stickies || {};
    for (const [uuid, sticky] of Object.entries(stickies)) {
      if (sticky.position) {
        saved[uuid] = { ...sticky.position };
      }
    }
    this.pendingPositions = saved;
  }
 
  public deleteDialog: Dialog | null = null;
 
  private dirtyAdapter: DirtyTrackable = {
    dirtyMessage:
      'Your flow is still saving. If you leave now, your latest changes may be lost.',
    markClean: () => {
      // no-op — the editor manages its own save lifecycle
    }
  };
 
  private boundBeforeUnload = (e: BeforeUnloadEvent) => {
    e.preventDefault();
  };
 
  // NodeEditor state - handles both node and action editing
  @state()
  public editingNode: Node | null = null;
 
  @state()
  public editingNodeUI: NodeUI | null = null;
 
  @state()
  public editingAction: Action | null = null;
 
  private dialogOrigin: { x: number; y: number } | null = null;
 
  // Message table view toggle
  @property({ type: Boolean, reflect: true, attribute: 'message-view' })
  showMessageTable = false;

  @state()
  private isCreatingNewNode = false;

  @state()
  private pendingNodePosition: FlowPosition | null = null;

  // Canvas drop state for dragging actions to canvas
  @state()
  private canvasDropPreview: {
    action: Action;
    nodeUuid: string;
    actionIndex: number;
    position: FlowPosition;
    actionHeight: number;
  } | null = null;
  @state()
  private addActionToNodeUuid: string | null = null;

  // Track target node for action drag
  @state()
  private actionDragTargetNodeUuid: string | null = null;
 
  // Track previous target node to clear placeholder when moving between nodes
  private previousActionDragTargetNodeUuid: string | null = null;
 
  // Track action external drag state for shift-copy support
  private isActionExternalDrag = false;
  private actionDragIsCopy = false;
  private actionDragLastDetail: {
    action: Action;
    nodeUuid: string;
    actionIndex: number;
    mouseX: number;
    mouseY: number;
    actionHeight: number;
    isLastAction: boolean;
  } | null = null;
 
  // Connection placeholder state for dropping connections on empty canvas
  @state()
  public connectionPlaceholder: {
    position: FlowPosition;
    visible: boolean;
    dragUp?: boolean;
  } | null = null;

  // Track pending connection when dropping on canvas
  private pendingCanvasConnection: {
    fromNodeId: string;
    exitId: string;
    position: FlowPosition;
  } | null = null;

  // Bound event handlers to maintain proper 'this' context
  private boundCanvasContextMenu = this.handleCanvasContextMenu.bind(this);
  private boundWheel = (e: WheelEvent) => this.zoomManager.handleWheel(e);
  private boundWindowResize = () =>
    this.zoomManager.updateZoomControlPositioning();

  static get styles() {
    return css`
      #editor-container {
        position: relative;
        flex: 1;
        display: flex;
        flex-direction: column;
        min-height: 0;
      }
 
      #editor {
        overflow: scroll;
        flex: 1;
        -webkit-font-smoothing: antialiased;
      }
 
      /* On touch devices, disable native scroll-by-touch so canvas
         drag draws a selection rectangle. Users scroll via scrollbars. */
      #editor.touch-device {
        touch-action: none;
      }
 
      #editor.touch-device::-webkit-scrollbar {
        -webkit-appearance: none;
        width: 12px;
        height: 12px;
      }
 
      #editor.touch-device::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.3);
        border-radius: 6px;
        border: 2px solid transparent;
        background-clip: padding-box;
      }
 
      #editor.touch-device::-webkit-scrollbar-track {
        background: rgba(0, 0, 0, 0.05);
      }
 
      #grid {
        position: relative;
        background-color: #f9f9f9;
        background-image: radial-gradient(
          circle,
          rgba(61, 177, 255, 0.3) 1px,
          transparent 1px
        );
        background-size: 20px 20px;
        background-position: 10px 10px;
        width: 100%;
        display: flex;
        padding-top: 20px;
        transform-origin: 0 0;
      }
 
      #canvas {
        position: relative;
        padding: 0px;
        flex-grow: 1;
        margin: 20px;
      }
 
      #canvas > .draggable {
        position: absolute;
        z-index: 100;
        touch-action: none;
      }
 
      #canvas > .draggable:hover {
        z-index: 200;
      }
 
      #canvas > .dragging {
        z-index: 99999 !important;
        transition: none !important;
      }
 
      #canvas.shift-held {
        --shift-held-cursor: copy;
        cursor: copy;
      }
 
      #canvas.viewing-revision {
        pointer-events: none;
      }
 
      #canvas.read-only svg {
        pointer-events: none;
      }
 
      #grid.viewing-revision {
        background-color: #fff9fc;
        background-image: radial-gradient(
          circle,
          rgba(166, 38, 164, 0.2) 1px,
          transparent 1px
        );
      }
 
      #grid.viewing-revision temba-flow-node,
      #grid.viewing-revision svg.plumb-connector {
        opacity: 0.5;
      }
 
      svg.plumb-connector {
        z-index: 10;
      }
 
      svg.plumb-connector path {
        stroke: var(--color-connectors);
        stroke-width: 3px;
      }
 
      svg.plumb-connector .plumb-arrow {
        fill: var(--color-connectors);
        stroke: none;
      }
 
      svg.plumb-connector.hover path {
        stroke: var(--color-success);
      }
 
      svg.plumb-connector.hover .plumb-arrow {
        fill: var(--color-success);
      }
 
      #canvas.read-only-connections svg.plumb-connector.hover path {
        stroke: var(--color-connectors);
      }
 
      #canvas.read-only-connections svg.plumb-connector.hover .plumb-arrow {
        fill: var(--color-connectors);
      }
 
      #canvas.read-only-connections svg.plumb-connector,
      #canvas.read-only-connections svg.plumb-connector * {
        pointer-events: none !important;
        cursor: default !important;
      }
 
      #canvas.read-only-connections svg.plumb-connector path {
        stroke: #e0e0e0;
      }
 
      #canvas.read-only-connections svg.plumb-connector .plumb-arrow {
        fill: #e0e0e0;
      }
 
      svg.plumb-connector.removing path {
        stroke: var(--color-error);
      }
 
      svg.plumb-connector.removing .plumb-arrow {
        fill: var(--color-error);
      }
 
      svg.plumb-connector.dragging {
        z-index: 99999;
      }
 
      /* Active contact count on nodes */
      .active-count {
        position: absolute;
        background: #3498db;
        border: 1px solid #2980b9;
        border-radius: 12px;
        padding: 3px 6px;
        color: #fff;
        font-weight: 500;
        top: -10px;
        left: -10px;
        font-size: 13px;
 
        text-align: center;
        z-index: 600;
        line-height: 1;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
      }
 
      /* Activity overlay badges on connection exit stubs */
      .activity-overlay {
        position: absolute;
        background: #f3f3f3;
        border: 1px solid #d9d9d9;
        color: #333;
        border-radius: 4px;
        padding: 2px 4px;
        font-size: 10px;
        font-weight: 600;
        line-height: 0.9;
        cursor: pointer;
        z-index: 10;
        pointer-events: auto;
        white-space: nowrap;
        user-select: none;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
      }
 
      #grid.viewing-revision .activity-overlay {
        opacity: 0.5;
        pointer-events: none;
      }
 
      /* Recent contacts popup */
      @keyframes popupBounceIn {
        0% {
          transform: scale(0.8);
          opacity: 0;
        }
        50% {
          transform: scale(1.05);
        }
        100% {
          transform: scale(1);
          opacity: 1;
        }
      }
 
      .recent-contacts-popup {
        display: none;
        position: absolute;
        width: 200px;
        background: #f3f3f3;
        border-radius: 10px;
        box-shadow: 0 1px 3px 1px rgba(130, 130, 130, 0.2);
        z-index: 1015;
        transform-origin: top center;
      }
 
      .recent-contacts-popup.show {
        display: block;
        animation: popupBounceIn 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
      }
 
      .recent-contacts-popup .popup-title {
        background: #999;
        color: #fff;
        padding: 6px 0;
        text-align: center;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        font-size: 12px;
      }
 
      .recent-contacts-popup .no-contacts-message {
        padding: 15px;
        text-align: center;
        color: #999;
        font-size: 12px;
      }
 
      .recent-contacts-popup .contact-row {
        padding: 8px 10px;
        border-top: 1px solid #e0e0e0;
        text-align: left;
      }
 
      .recent-contacts-popup .contact-row:last-child {
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
      }
 
      .recent-contacts-popup .contact-name {
        display: block;
        font-weight: 500;
        font-size: 12px;
        color: var(--color-link-primary, #1d4ed8);
        cursor: pointer;
      }
 
      .recent-contacts-popup .contact-name:hover {
        text-decoration: underline;
      }
 
      .recent-contacts-popup .contact-operand {
        padding-top: 3px;
        font-size: 11px;
        color: #666;
        word-wrap: break-word;
      }
 
      .recent-contacts-popup .contact-time {
        padding-top: 3px;
        font-size: 10px;
        color: #999;
      }
 
      /* Connection target feedback */
      temba-flow-node.connection-target-valid {
        outline: 3px solid var(--color-success, #22c55e) !important;
        outline-offset: 2px;
        border-radius: var(--curvature);
      }
 
      temba-flow-node.connection-target-invalid {
        outline: 3px solid var(--color-error, #ef4444) !important;
        outline-offset: 2px;
        border-radius: var(--curvature);
      }
 
      /* Selection box styles */
      .selection-box {
        position: absolute;
        border: 2px dashed #6298f0ff;
        background-color: rgba(59, 130, 246, 0.1);
        z-index: 9999;
        pointer-events: none;
      }
 
      /* Selected item styles */
      .draggable.selected {
        outline: 3px solid #6298f0ff;
        outline-offset: 0px;
        border-radius: var(--curvature);
      }
 
      .draggable.selected.drag-copy {
        outline: none;
      }
 
      /* Language banner replaced by toolbar language selector */
 
      .localization-window-content {
        display: flex;
        flex-direction: column;
        gap: 16px;
        height: 100%;
      }
 
      .localization-header {
        font-size: 13px;
        color: #4b5563;
        line-height: 1.4;
      }
 
      .localization-language-select {
        --color-widget-border: #d1d5db;
        --color-widget-background: #fff;
      }
 
      .localization-language-row {
        display: flex;
        align-items: flex-end;
        gap: 12px;
      }
 
      .localization-language-row temba-select {
        flex: 1;
      }
 
      .localization-progress {
        margin-top: auto;
        display: flex;
        flex-direction: column;
        gap: 8px;
      }
 
      .localization-progress.disabled {
        opacity: 0.4;
        pointer-events: none;
      }
 
      .localization-progress-bar-row {
        display: flex;
        align-items: center;
        gap: 8px;
      }
 
      .localization-progress-trigger {
        flex: 1;
        border-radius: 6px;
        cursor: pointer;
        display: flex;
        align-items: center;
      }
 
      .localization-progress-trigger:focus-visible {
        outline: 2px solid #94a3b8;
        outline-offset: 2px;
      }
 
      .localization-progress-trigger temba-progress {
        flex: 1;
      }
 
      .localization-progress h5 {
        margin: 0;
        font-size: 13px;
        font-weight: 600;
        color: #374151;
      }
 
      .localization-progress-summary {
        font-size: 12px;
        color: #6b7280;
        display: flex;
        align-items: center;
        gap: 6px;
        min-height: 20px;
      }
 
      .translation-settings-toggle {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        background: transparent;
        border: none;
        outline: none;
        color: #6b7280;
        font-size: 12px;
        font-weight: 600;
        cursor: pointer;
        padding: 4px;
        border-radius: 4px;
      }
 
      .translation-settings-label {
        font-size: 12px;
        color: #6b7280;
      }
 
      .translation-settings-arrow {
        width: 8px;
        height: 8px;
        border-right: 2px solid currentColor;
        border-bottom: 2px solid currentColor;
        transform: rotate(-45deg);
        transition: transform 0.2s ease;
        margin-left: 2px;
      }
 
      .translation-settings-arrow.expanded {
        transform: rotate(45deg);
      }
 
      .translation-settings {
      }
 
      .translation-settings-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
 
      .translation-settings-row temba-checkbox {
        width: 100%;
      }
 
      .revert-button {
        background: var(--color-primary-dark);
        border: none;
        color: #fff;
        padding: 6px 10px;
        border-radius: var(--curvature);
        font-size: 11px;
        font-weight: 600;
        cursor: pointer;
        transition: opacity 0.2s ease;
      }
 
      .localization-empty {
        font-size: 13px;
        color: #9ca3af;
        white-space: nowrap;
      }
 
      .issue-list-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 13px;
        color: #333;
      }
 
      .issue-list-item:hover {
        background: #fff5f5;
      }
 
      .issue-list-item temba-icon {
        color: tomato;
        flex-shrink: 0;
      }
 
      .empty-flow {
        position: sticky;
        top: 80px;
        left: 0;
        right: 0;
        height: 0;
        display: flex;
        justify-content: center;
        pointer-events: none;
        z-index: 50;
      }
 
      .empty-flow-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 16px;
        text-align: center;
        pointer-events: auto;
      }
 
      .empty-flow-title {
        font-size: 18px;
        font-weight: 600;
        color: #374151;
      }
 
      .empty-flow-description {
        font-size: 14px;
        color: #6b7280;
        max-width: 320px;
        line-height: 1.5;
      }
 
      .empty-flow-button {
        background: var(--color-primary-dark);
        border: none;
        color: #fff;
        padding: 10px 20px;
        border-radius: var(--curvature);
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: opacity 0.2s ease;
      }
 
      .empty-flow-button:hover {
        opacity: 0.9;
      }
 
      /* Legacy zoom-controls kept for compat — now in toolbar */
 
      .loupe,
      .loupe * {
        pointer-events: none !important;
      }
 
      .loupe {
        position: fixed;
        width: 280px;
        height: 280px;
        border-radius: 50%;
        overflow: hidden;
        z-index: 10000;
        border: 2px solid rgba(0, 0, 0, 0.25);
        box-shadow:
          0 4px 16px rgba(0, 0, 0, 0.35),
          0 1px 4px rgba(0, 0, 0, 0.2),
          inset 0 0 0 2px rgba(255, 255, 255, 0.3),
          inset 0 0 20px rgba(0, 0, 0, 0.08);
        transform: translate(-50%, -50%) scale(0);
        opacity: 0;
        transition:
          transform 0.15s ease-out,
          opacity 0.15s ease-out;
      }
 
      .loupe.visible {
        transform: translate(-50%, -50%) scale(1);
        opacity: 1;
      }
 
      .loupe-content {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: #f9f9f9;
        background-image: radial-gradient(
          circle,
          rgba(61, 177, 255, 0.3) 1px,
          transparent 1px
        );
      }
 
      .loupe::after {
        content: '';
        position: absolute;
        inset: 0;
        border-radius: 50%;
        background: radial-gradient(
          circle,
          transparent 45%,
          rgba(0, 0, 0, 0.03) 58%,
          rgba(0, 0, 0, 0.08) 68%,
          rgba(0, 0, 0, 0.18) 80%,
          rgba(0, 0, 0, 0.35) 90%,
          rgba(0, 0, 0, 0.55) 100%
        );
        z-index: 1;
      }
 
      .loupe-crosshair-h,
      .loupe-crosshair-v {
        position: absolute;
        background: rgba(0, 0, 0, 0.15);
      }
 
      .loupe-crosshair-h {
        width: 12px;
        height: 1px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
 
      .loupe-crosshair-v {
        width: 1px;
        height: 12px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
 
      .loupe-clone {
        position: absolute;
        transform-origin: 0 0;
        pointer-events: none;
      }
 
      .loupe-clone > .draggable {
        position: absolute;
        z-index: 100;
      }
 
      .loupe-clone > svg.plumb-connector {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: visible;
      }
 
      /* Force hovered appearance inside the loupe since :hover can't fire
         through pointer-events:none */
      .loupe-clone .action .cn-title .remove-button,
      .loupe-clone .router .remove-button {
        visibility: visible;
        opacity: 0.7;
      }
 
      .loupe-clone .action .drag-handle {
        visibility: visible;
        opacity: 0.7;
      }
 
      .loupe-clone .exit.connected {
        background-color: var(--color-connectors, #e6e6e6);
      }
 
      .loupe-clone .node.execute-actions .add-action-button {
        opacity: 0.8;
      }
 
      .drag-hint {
        position: absolute;
        bottom: 40px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 100000;
        pointer-events: none;
        background: rgba(255, 255, 255, 0.5);
        backdrop-filter: blur(6px);
        color: #555;
        font-size: 18px;
        font-weight: 300;
        padding: 10px 32px;
        border-radius: 10px;
        border: 1px solid rgba(0, 0, 0, 0.08);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        white-space: nowrap;
        display: none;
      }
 
      .drag-hint.visible {
        display: block;
        animation: drag-hint-in 0.15s ease forwards;
      }
 
      @keyframes drag-hint-in {
        from {
          opacity: 0;
        }
        to {
          opacity: 1;
        }
      }
 
      .reflow-card {
        position: absolute;
        top: 16px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 10000;
        background: rgba(0, 0, 0, 0.65);
        backdrop-filter: blur(8px);
        border-radius: 10px;
        padding: 12px 16px 8px;
        display: flex;
        flex-direction: column;
        gap: 8px;
        color: white;
        font-size: 13px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
 
      .reflow-card .reflow-top {
        display: flex;
        align-items: center;
        gap: 10px;
      }
 
      .reflow-card .reflow-label {
        white-space: nowrap;
      }
 
      .reflow-card button {
        border: none;
        border-radius: 6px;
        padding: 6px 14px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        white-space: nowrap;
        transition: opacity 0.15s ease;
      }
 
      .reflow-card button:hover {
        opacity: 0.85;
      }
 
      .reflow-card .reflow-discard {
        background: rgba(255, 255, 255, 0.2);
        color: white;
      }
 
      .reflow-meter {
        height: 3px;
        border-radius: 2px;
        background: rgba(255, 255, 255, 0.15);
        overflow: hidden;
      }
 
      .reflow-meter-fill {
        height: 100%;
        background: rgba(255, 255, 255, 0.5);
        border-radius: 2px;
        /* animation-name is set dynamically via style attribute */
        animation-duration: ${unsafeCSS(PENDING_SAVE_DELAY / 1000)}s;
        animation-timing-function: linear;
        animation-fill-mode: forwards;
      }
    `;
  }
 
  constructor() {
    super();
    this.dragManager = new DragManager(this);
    this.zoomManager = new ZoomManager(this);
  }
 
  protected firstUpdated(
    changes: PropertyValueMap<any> | Map<PropertyKey, unknown>
  ): void {
    super.firstUpdated(changes);
    this.plumber = new Plumber(this.querySelector('#canvas'), this);
    this.plumber.zoom = this.zoom;
    this.setupGlobalEventListeners();
    getStore()?.getState().setFlushSave(this.flushSave);
    zustand.getState().setFeatures(this.features);
 
    // Eagerly detect touch capability so hover-only controls are visible
    // from the start and scrollbar/touch-action CSS is applied immediately.
    if (navigator.maxTouchPoints > 0) {
      this.querySelector('#canvas')?.classList.add('touch-device');
      this.querySelector('#editor')?.classList.add('touch-device');
    }
    this.zoomManager.updateZoomControlPositioning();
    this.zoomManager.setLoupeElements(
      this.querySelector('#loupe') as HTMLElement,
      this.querySelector('#loupe-content') as HTMLElement
    );
    this.zoomManager.initLoupe();
    if (changes.has('flow') && this.flow) {
      // Defer revision fetch so reactive state changes in fetchRevisions()
      // don't run inside firstUpdated().
      setTimeout(() => {
        if (!this.isConnected || !this.flow) {
          return;
        }
        getStore().getState().fetchRevision(`/flow/revisions/${this.flow}`);
      }, 0);
    }
 
    this.plumber.on('connection:drag', (connection: any) => {
      this.dragFromNodeId = connection.data.nodeId;
      this.sourceId = connection.sourceId;
      this.connectionSourceX = connection.sourceX;
      this.connectionSourceY = connection.sourceY;
      this.originalConnectionTargetId = connection.target.id;
    });
 
    this.plumber.on('connection:abort', (info) => {
      this.makeConnection(info);
    });
 
    this.plumber.on('connection:detach', (info) => {
      // console.log('Connection detached', info);
      this.makeConnection(info);
    });
  }
 
  private makeConnection(info) {
    if (this.sourceId && this.targetId && this.isValidTarget) {
      // going to the same target, just put it back
      if (info.target.id === this.targetId) {
        this.plumber.connectIds(
          this.dragFromNodeId,
          this.sourceId,
          this.targetId
        );
      }
      // otherwise update the connection
      else {
        getStore()
          .getState()
          .updateConnection(this.dragFromNodeId, this.sourceId, this.targetId);
      }
    } else if (
      this.connectionPlaceholder &&
      this.connectionPlaceholder.visible &&
      this.sourceId
    ) {
      // Snap the placeholder position to grid
      const snappedPosition = {
        left: snapToGrid(this.connectionPlaceholder.position.left),
        top: snapToGrid(this.connectionPlaceholder.position.top)
      };
      const isDragUp = !!this.connectionPlaceholder.dragUp;

      // Update the placeholder to the snapped position
      this.connectionPlaceholder.position = snappedPosition;

      // Store the pending connection info
      this.pendingCanvasConnection = {
        fromNodeId: this.dragFromNodeId,
        exitId: this.sourceId,
        position: snappedPosition
      };

      // Show the context menu near the placeholder
      const canvas = this.querySelector('#canvas');
      if (canvas) {
        const canvasRect = canvas.getBoundingClientRect();
        const menuX = canvasRect.left + snappedPosition.left * this.zoom - 40;
        const menuY = isDragUp
          ? canvasRect.top + snappedPosition.top * this.zoom + 74 // just below placeholder bottom
          : canvasRect.top + snappedPosition.top * this.zoom + 80; // just below placeholder
 
        const canvasMenu = this.querySelector(
          'temba-canvas-menu'
        ) as CanvasMenu;
        if (canvasMenu) {
          canvasMenu.show(
            menuX,
            menuY,
            {
              x: snappedPosition.left,
              y: snappedPosition.top
            },
            false, // Don't show sticky note option for connection drops
            false,
            CONTEXT_MENU_SHORTCUTS[this.flowType]
          );
        }
      }

      // Request update to render the connection line
      this.requestUpdate();

      // Don't clear placeholder or connection info yet - keep them for menu interaction
      return;
    }

    // Clean up visual feedback
    document.querySelectorAll('temba-flow-node').forEach((node) => {
      node.classList.remove(
        'connection-target-valid',
        'connection-target-invalid'
      );
    });

    // Clear connection state (but keep sourceId/dragFromNodeId if we have a pending connection)
    if (!this.pendingCanvasConnection) {
      this.sourceId = null;
      this.connectionSourceX = null;
      this.connectionSourceY = null;
      this.dragFromNodeId = null;
    }
    this.targetId = null;
    this.isValidTarget = true;
  }

  protected willUpdate(changes: PropertyValues): void {
    super.willUpdate(changes);

    if (changes.has('definition')) {
      // Set flowType from the loaded definition
      if (this.definition?.type) {
        this.flowType = this.getFlowTypeFromDefinition(this.definition.type);
      }

      // Pre-sync zoom state so we don't mutate reactive state in updated().
      this.zoomManager.restoreInitialZoomFromSettings();
    }

    if (changes.has('dirtyDate')) {
      if (this.dirtyDate) {
        if (this.pendingTimer.pending) {
          // This dirtyDate is from a reflow/copy operation — consume the
          // flag and suppress the save in updated().
          this.pendingTimer.pending = false;
          this._suppressDirtySave = true;
        } else if (this.pendingTimer.unsaved) {
          // Additional change while the pending-changes card is showing —
          // reset the timer so all accumulated changes can be discarded.
          this.pendingTimer.start(false);
          this._suppressDirtySave = true;
        } else {
          this.isSaving = true;
        }
      }
    }
  }

  private setSimulatorTabHidden(hidden: boolean): void {
    const simulator = document.querySelector(
      'temba-simulator'
    ) as HTMLElement & {
      shadowRoot?: ShadowRoot;
    };
    const phoneTab = simulator?.shadowRoot?.querySelector('#phone-tab') as any;
    if (phoneTab) {
      phoneTab.hidden = hidden;
    }
  }
 
  protected updated(
    changes: PropertyValueMap<any> | Map<PropertyKey, unknown>
  ): void {
    super.updated(changes);
    if (changes.has('features')) {
      zustand.getState().setFeatures(this.features);
    }
    if (changes.has('revisionsWindowHidden')) {
      this.setSimulatorTabHidden(!this.revisionsWindowHidden);
    }
    if (changes.has('canvasSize')) {
      this.zoomManager.updateZoomControlPositioning();
    }
 
    if (
      changes.has('showMessageTable') &&
      !this.showMessageTable &&
      this.plumber
    ) {
      // Canvas was re-added to the DOM; rebind the plumber, listeners, and repaint
      requestAnimationFrame(() => {
        const canvas = this.querySelector('#canvas');
        if (canvas) {
          this.plumber.setContainer(canvas as HTMLElement);
          this.plumber.repaintEverything();
          canvas.addEventListener('contextmenu', this.boundCanvasContextMenu);
        }
      });
    }

    if (changes.has('showMessageTable')) {
      this.zoomManager.updateZoomControlPositioning();
    }
 
    if (changes.has('definition')) {
      // defer to avoid triggering a reactive canvasSize update during this cycle
      setTimeout(() => this.updateCanvasSize(), 0);
 
      // Start fetching activity data when definition is loaded
      if (this.definition?.uuid) {
        this.startActivityFetching();
      }
    }
 
    if (changes.has('simulatorActive')) {
      if (this.simulatorActive) {
        // Close any open floating windows when simulator opens
        this.closeFloatingWindows();
        // Stop polling when simulator becomes active
        this.stopActivityFetching();
      } else {
        // Resume polling and refresh activity when simulator closes
        this.activityInterval = 100; // Reset to fast initial interval
        this.startActivityFetching();
      }
    }

    if (changes.has('activityData')) {
      // Update plumber with new activity data
      if (this.plumber) {
        this.plumber.setActivityData(this.activityData);
      }
    }
 
    if (changes.has('dirtyDate')) {
      if (this.dirtyDate) {
        if (this._suppressDirtySave) {
          this._suppressDirtySave = false;
        } else {
          this.debouncedSave();
        }
      }
    }
 
    if (changes.has('isSaving')) {
      const store = document.querySelector('temba-store') as Store;
      if (this.isSaving) {
        window.addEventListener('beforeunload', this.boundBeforeUnload);
        if (store?.markDirty) {
          store.markDirty(this.dirtyAdapter);
        }
      } else {
        window.removeEventListener('beforeunload', this.boundBeforeUnload);
        if (store?.markClean) {
          store.markClean(this.dirtyAdapter);
        }
      }
    }
 
    if (changes.has('saveError') && this.saveError) {
      this.showSaveErrorDialog(this.saveError);
      setTimeout(() => {
        this.saveError = null;
      }, 0);
    }
  }
 
  /**
   * Map FlowDefinition type to Editor flowType
   * FlowDefinition uses: 'messaging', 'messaging_background', 'messaging_offline', 'voice'
   * Editor uses: 'message', 'voice', 'background'
   */
  private getFlowTypeFromDefinition(definitionType: string): FlowType {
    if (definitionType === 'voice') {
      return FlowTypes.VOICE;
    } else if (
      definitionType === 'messaging_background' ||
      definitionType === 'messaging_offline'
    ) {
      return FlowTypes.BACKGROUND;
    } else {
      // 'messaging' or any other messaging type defaults to 'message'
      return FlowTypes.MESSAGE;
    }
  }
 
  /**
   * If there's a pending debounced save, cancel the timer and save immediately.
   * Called by the simulator to ensure the latest definition is persisted before
   * starting a simulation run.
   */
  private flushSave = async (): Promise<void> => {
    // Capture the definition eagerly before any async gap so it
    // survives even if the component unmounts and clearFlowData runs.
    const snapshot = this.definition ? { ...this.definition } : null;
 
    // Flush pending-changes timer (reflow/copy operations) if active
    if (this.pendingTimer.unsaved) {
      this.pendingPositions = null;
      this.copiedItemUuids = [];
      this.pendingTimer.dismiss();
    }
 
    // Cancel any pending debounce timer
    if (this.saveTimer !== null) {
      clearTimeout(this.saveTimer);
      this.saveTimer = null;
    }
 
    // Wait for any in-flight POST to finish first
    if (this.savePromise) {
      await this.savePromise;
    }
 
    // Save if there are unsaved changes
    if (snapshot && this.dirtyDate) {
      await this.saveChanges(snapshot);
    }
  };
 
  private debouncedSave(): void {
    // Clear any existing timer
    if (this.saveTimer !== null) {
      clearTimeout(this.saveTimer);
    }
 
    this.saveTimer = window.setTimeout(() => {
      // Don't auto-save while the pending-changes card is showing
      if (this.pendingTimer.unsaved) {
        this.saveTimer = null;
        return;
      }
 
      const now = new Date();
      const timeSinceLastChange = now.getTime() - this.dirtyDate.getTime();
 
      if (timeSinceLastChange >= SAVE_QUIET_TIME) {
        this.saveChanges();
        this.saveTimer = null;
      } else {
        this.debouncedSave();
      }
    }, SAVE_QUIET_TIME);
  }
 
  private definitionForSave(definition: FlowDefinition): FlowDefinition {
    return {
      ...definition,
      _ui: {
        ...definition._ui,
        editor: TEMBA_COMPONENTS_VERSION
      }
    };
  }
 
  private saveChanges(definitionOverride?: FlowDefinition): Promise<void> {
    const definition = this.definitionForSave(
      definitionOverride || this.definition
    );
    this.isSaving = true;
 
    const promise = getStore()
      .postJSON(`/flow/revisions/${this.flow}/`, definition)
      .then((response) => {
        if (response.status < 200 || response.status >= 300) {
          this.saveError = this.extractErrorMessage(response);
          return;
        }
 
        // Update flow info and revision with the response data
        if (response.json) {
          const state = getStore().getState();
 
          if (response.json.info) {
            state.setFlowInfo(response.json.info);
          }
 
          if (response.json.revision?.revision !== undefined) {
            state.setRevision(response.json.revision.revision);
          }
        }
 
        getStore().getState().setDirtyDate(null);
 
        // Refresh the revisions list if it's currently open.
        this.getRevisionsWindow()?.refresh();
      })
      .catch((error) => {
        console.error('Failed to save flow:', error);
        if (error instanceof Response) {
          this.saveError = `Server error (${error.status}). Your changes have not been saved.`;
        } else {
          this.saveError =
            'Unable to reach the server. Please check your connection and try again.';
        }
      })
      .finally(() => {
        this.isSaving = false;
        this.savePromise = null;
      });

    this.savePromise = promise;
    return promise;
  }
 
  private extractErrorMessage(response: WebResponse): string {
    if (response.json) {
      if (typeof response.json.detail === 'string') {
        return response.json.detail;
      }
      if (typeof response.json.error === 'string') {
        return response.json.error;
      }
      if (typeof response.json.description === 'string') {
        return response.json.description;
      }
    }
    return `Save failed with status ${response.status}.`;
  }
 
  private showSaveErrorDialog(message: string): void {
    const dialog = document.createElement('temba-dialog') as Dialog;
    dialog.header = 'Save Failed';
    dialog.primaryButtonName = '';
    dialog.cancelButtonName = 'Dismiss';
 
    const content = document.createElement('div');
    content.style.cssText = 'padding: 20px; font-size: 14px; line-height: 1.5;';
    content.textContent = message;
    dialog.appendChild(content);

    document.body.appendChild(dialog);
    dialog.open = true;

    dialog.addEventListener('temba-dialog-hidden', () => {
      document.body.removeChild(dialog);
    });
  }
 
  private startActivityFetching(): void {
    // Don't start if simulator is active
    if (this.simulatorActive) {
      return;
    }
    // Fetch immediately
    this.fetchActivityData();
  }
 
  private stopActivityFetching(): void {
    if (this.activityTimer !== null) {
      clearTimeout(this.activityTimer);
      this.activityTimer = null;
    }
  }
 
  private fetchActivityData(): void {
    if (!this.definition?.uuid) {
      return;
    }
 
    // Don't fetch if simulator is active
    if (this.simulatorActive) {
      return;
    }
 
    const activityEndpoint = `/flow/activity/${this.definition.uuid}/`;
    const store = getStore();
    if (!store) {
      return;
    }
    const state = store.getState();
    state.fetchActivity(activityEndpoint).then(() => {
      // Guard against responses arriving after the editor is disconnected
      if (!this.isConnected) {
        return;
      }
 
      // Schedule next fetch with exponential backoff (max 5 minutes)
      this.activityInterval = Math.min(60000 * 5, this.activityInterval + 100);
 
      if (this.activityTimer !== null) {
        clearTimeout(this.activityTimer);
      }
 
      this.activityTimer = window.setTimeout(() => {
        this.fetchActivityData();
      }, this.activityInterval);
    });
  }
 
  private handleLanguageChange(languageCode: string): void {
    zustand.getState().setLanguageCode(languageCode);
  }
 
  private getAvailableLanguages(): Array<{ code: string; name: string }> {
    // Use languages from workspace if available
    if (this.workspace?.languages && this.workspace.languages.length > 0) {
      return this.workspace.languages
        .map((code) => ({ code, name: getLanguageDisplayName(code) }))
        .filter((lang) => lang.code && lang.name);
    }
 
    // Fall back to flow definition languages if available
    if (
      this.definition?._ui?.languages &&
      this.definition._ui.languages.length > 0
    ) {
      return this.definition._ui.languages.map((lang: any) => {
        const code = typeof lang === 'string' ? lang : lang.iso || lang.code;
        return { code, name: getLanguageDisplayName(code) };
      });
    }

    // No languages available
    return [];
  }
 
  private getLocalizationLanguages(): Array<{ code: string; name: string }> {
    if (!this.definition) {
      return [];
    }
 
    const baseLanguage = this.definition.language;
    return this.getAvailableLanguages().filter(
      (lang) => lang.code !== baseLanguage
    );
  }
 
  private getLocalizationProgress(languageCode: string): {
    total: number;
    localized: number;
  } {
    return getTranslationCounts(
      buildTranslationBundles(this.definition, languageCode)
    );
  }
 
  private hasAnyNodeWithLocalizeCategories(): boolean {
    if (!this.definition?._ui?.nodes) return false;
    return Object.values(this.definition._ui.nodes).some(
      (nodeUI: any) => nodeUI?.config?.localizeCategories
    );
  }
 
  private handleAutoTranslateClick(): void {
    if (this.viewingRevision) {
      return;
    }
    const at = this.querySelector('temba-auto-translate') as any;
    at?.start();
  }
 
  private handleAutoTranslateChanged(e: CustomEvent): void {
    this.autoTranslating = !!e.detail?.running;
  }
 
  disconnectedCallback(): void {
    super.disconnectedCallback();
    this.zoomManager.teardownLoupe();
    getStore()?.getState().setFlushSave(null);
    this.dragManager.teardownListeners();
    window.removeEventListener('beforeunload', this.boundBeforeUnload);
    const store = document.querySelector('temba-store') as Store;
    if (store?.markClean) {
      store.markClean(this.dirtyAdapter);
    }
    if (this.saveTimer !== null) {
      clearTimeout(this.saveTimer);
      this.saveTimer = null;
    }
    if (this.activityTimer !== null) {
      clearTimeout(this.activityTimer);
      this.activityTimer = null;
    }
    this.pendingTimer.clearTimer();
    window.removeEventListener('resize', this.boundWindowResize);

    const canvas = this.querySelector('#canvas');
    if (canvas) {
      canvas.removeEventListener('contextmenu', this.boundCanvasContextMenu);
    }
 
    const editor = this.querySelector('#editor');
    if (editor) {
      editor.removeEventListener('wheel', this.boundWheel);
    }
 
    // Clear all flow-specific data from the store so stale data
    // isn't briefly visible when a different flow is opened.
    // If a save is in-flight, wait for it to complete first so the
    // definition isn't nulled out from under the POST.
    if (this.savePromise) {
      this.savePromise.then(() => zustand.getState().clearFlowData());
    } else {
      zustand.getState().clearFlowData();
    }
  }
 
  private setupGlobalEventListeners(): void {
    // Drag/selection listeners managed by DragManager
    this.dragManager.setupListeners();
 
    window.addEventListener('resize', this.boundWindowResize);
 
    const canvas = this.querySelector('#canvas');
    if (canvas) {
      canvas.addEventListener('contextmenu', this.boundCanvasContextMenu);
    }
 
    const editor = this.querySelector('#editor');
    if (editor) {
      editor.addEventListener('wheel', this.boundWheel, { passive: false });
    }
 
    // Listen for action edit requests from flow nodes
    this.addEventListener(
      CustomEventType.ActionEditRequested,
      this.handleActionEditRequested.bind(this)
    );

    // Listen for add action requests from flow nodes
    this.addEventListener(
      CustomEventType.AddActionRequested,
      this.handleAddActionRequested.bind(this)
    );
 
    // Listen for node edit requests from flow nodes
    this.addEventListener(
      CustomEventType.NodeEditRequested,
      this.handleNodeEditRequested.bind(this)
    );
 
    // Listen for node deletion events
    this.addEventListener(
      CustomEventType.NodeDeleted,
      this.handleNodeDeleted.bind(this)
    );
 
    // Listen for sticky note deletion events
    this.addEventListener(CustomEventType.StickyNoteDeleted, ((
      event: CustomEvent
    ) => {
      const uuid = event.detail?.uuid;
      if (uuid) {
        getStore().getState().removeStickyNotes([uuid]);
      }
    }) as EventListener);
 
    // Listen for canvas menu selections
    this.addEventListener(CustomEventType.Selection, (event: CustomEvent) => {
      const target = event.target as HTMLElement;
      if (target.tagName === 'TEMBA-CANVAS-MENU') {
        this.handleCanvasMenuSelection(event);
      } else if (target.tagName === 'TEMBA-NODE-TYPE-SELECTOR') {
        this.handleNodeTypeSelection(event);
      }
    });
 
    // Listen for canvas menu cancel (close without selection)
    this.addEventListener(CustomEventType.Canceled, (event: CustomEvent) => {
      const target = event.target as HTMLElement;
      if (target.tagName === 'TEMBA-CANVAS-MENU') {
        this.handleCanvasMenuClosed();
      } else if (target.tagName === 'TEMBA-NODE-TYPE-SELECTOR') {
        this.handleNodeTypeSelectorClosed();
      }
    });
 
    // Listen for action drag events from nodes
    this.addEventListener(
      CustomEventType.DragExternal,
      this.handleActionDragExternal.bind(this)
    );
 
    this.addEventListener(
      CustomEventType.DragInternal,
      this.handleActionDragInternal.bind(this)
    );
 
    this.addEventListener(CustomEventType.DragStop, (event: CustomEvent) => {
      if (event.detail.isExternal) {
        this.handleActionDropExternal(event);
      }
    });
 
    this.addEventListener(CustomEventType.SizeChanged, (event: CustomEvent) => {
      const { uuid } = event.detail;
      if (uuid) {
        requestAnimationFrame(() => {
          this.checkCollisionsAndReflow([uuid]);
        });
      }
    });
  }
 
  private openFlowSearch(): void {
    if (this.viewingRevision) {
      return;
    }
 
    if (this.zoomManager.isDialogOrMenuOpen()) {
      return;
    }
 
    const search = this.querySelector('temba-flow-search') as FlowSearch;
    if (!search) {
      return;
    }
 
    search.definition = this.definition;
    search.languageCode = this.languageCode || '';
    search.scope = this.showMessageTable ? 'table' : 'flow';
    search.includeCategories =
      this.isTranslating && this.hasAnyNodeWithLocalizeCategories();
    search.show();
  }
 
  private closeFlowSearch(): void {
    const search = this.querySelector('temba-flow-search') as FlowSearch;
    if (search?.open) {
      search.hide();
    }
  }

  // Called by DragManager for non-drag keyboard handling
  public handleKeyDown(event: KeyboardEvent): void {
    if (event.key === 'Shift') {
      // Toggle to copy mode mid-drag (actions)
      if (this.isActionExternalDrag && !this.actionDragIsCopy) {
        this.actionDragIsCopy = true;
        this.showActionOriginal(true);
        if (this.actionDragLastDetail?.isLastAction) {
          this.reprocessActionDrag();
        }
        this.requestUpdate();
      }
    }

    // Cmd/Ctrl+F opens flow search (unless a dialog is already open)
    if ((event.metaKey || event.ctrlKey) && event.key === 'f') {
      event.preventDefault();
      this.openFlowSearch();
      return;
    }

    // Don't handle other keys while search overlay is open
    const search = this.querySelector('temba-flow-search') as FlowSearch;
    if (search?.open) return;

    if (event.key === 'Delete' || event.key === 'Backspace') {
      if (this.deleteDialog?.open) {
        this.deleteSelectedItems();
        this.deleteDialog.open = false;
        return;
      }
 
      if (this.selectedItems.size > 0) {
        this.showDeleteConfirmation();
      }
    }
    if (event.key === 'Escape') {
      this.selectedItems.clear();
      this.requestUpdate();
    }
  }

  // Called by DragManager for action drag shift-copy
  public handleKeyUp(event: KeyboardEvent): void {
    if (event.key === 'Shift') {
      if (this.isActionExternalDrag && this.actionDragIsCopy) {
        this.actionDragIsCopy = false;
        this.showActionOriginal(false);
        if (this.actionDragLastDetail?.isLastAction) {
          this.reprocessActionDrag();
        }
        this.requestUpdate();
      }
    }
  }

  // Called by DragManager on window blur
  public handleWindowBlur(): void {
    if (this.isActionExternalDrag && this.actionDragIsCopy) {
      this.actionDragIsCopy = false;
      this.showActionOriginal(false);
      if (this.actionDragLastDetail?.isLastAction) {
        this.reprocessActionDrag();
      }
      this.requestUpdate();
    }
  }

  // --- Flow settings cookie (LRU, max 50 flows) ---

  static MAX_FLOW_SETTINGS = 50;

  public getFlowSettings(): Record<string, any> {
    try {
      return JSON.parse(getCookie('flow-settings') || '{}');
    } catch {
      return {};
    }
  }

  public saveFlowSetting(key: string, value: any): void {
    if (!this.flow) return;
    const settings = this.getFlowSettings();
 
    // Remove existing entry so re-inserting moves it to the end (most recent)
    delete settings[this.flow];
    settings[this.flow] = { ...(settings[this.flow] || {}), [key]: value };
 
    // Evict oldest entries if over the limit
    const keys = Object.keys(settings);
    if (keys.length > Editor.MAX_FLOW_SETTINGS) {
      for (const oldKey of keys.slice(
        0,
        keys.length - Editor.MAX_FLOW_SETTINGS
      )) {
        delete settings[oldKey];
      }
    }

    setCookie('flow-settings', JSON.stringify(settings));
  }

  public getFlowSetting<T>(key: string): T | undefined {
    if (!this.flow) return undefined;
    return this.getFlowSettings()[this.flow]?.[key];
  }

  private showDeleteConfirmation(): void {
    const itemCount = this.selectedItems.size;
    const itemType = itemCount === 1 ? 'item' : 'items';
 
    // Create and show confirmation dialog
    // Don't open a second dialog if one is already showing
    if (this.deleteDialog?.open) return;
 
    const dialog = document.createElement('temba-dialog') as Dialog;
    dialog.header = 'Delete Items';
    dialog.primaryButtonName = 'Delete';
    dialog.cancelButtonName = 'Cancel';
    dialog.destructive = true;
    dialog.innerHTML = `<div style="padding: 20px;">Are you sure you want to delete ${itemCount} ${itemType}?</div>`;
 
    dialog.addEventListener('temba-button-clicked', (event: any) => {
      if (event.detail.button.name === 'Delete') {
        this.deleteSelectedItems();
        dialog.open = false;
      }
    });

    // Add to document and show
    document.body.appendChild(dialog);
    dialog.open = true;
    this.deleteDialog = dialog;

    // Clean up dialog when closed
    dialog.addEventListener('temba-dialog-hidden', () => {
      document.body.removeChild(dialog);
      this.deleteDialog = null;
    });
  }

  private performReflow(): void {
    if (!this.definition || this.definition.nodes.length === 0) return;

    // Save current positions for discard (only on first pending operation)
    this.capturePositionsOnce();
 
    const stickies = this.definition._ui?.stickies || {};

    // Save old node positions before reflow for sticky proximity calculation
    const oldNodePositions: Record<string, FlowPosition> = {};
    for (const node of this.definition.nodes) {
      const ui = this.definition._ui?.nodes[node.uuid];
      if (ui?.position) {
        oldNodePositions[node.uuid] = { ...ui.position };
      }
    }

    // Identify start node (first in sorted array)
    const startNodeUuid = this.definition.nodes[0].uuid;

    // Gather node sizes from DOM
    const nodeSizes = new Map<string, { width: number; height: number }>();
    const getNodeSize = (uuid: string): { width: number; height: number } => {
      const element = this.querySelector(`[id="${uuid}"]`) as HTMLElement;
      if (element) {
        const size = {
          width: element.offsetWidth,
          height: element.offsetHeight
        };
        nodeSizes.set(uuid, size);
        return size;
      }
      const fallback = { width: 200, height: 100 };
      nodeSizes.set(uuid, fallback);
      return fallback;
    };
 
    // Compute new layout
    const newPositions = calculateLayeredLayout(
      this.definition.nodes,
      this.definition._ui.nodes,
      startNodeUuid,
      getNodeSize
    );
 
    // Place sticky notes next to their closest nodes
    if (Object.keys(stickies).length > 0) {
      const stickySizes = new Map<string, { width: number; height: number }>();
      for (const uuid of Object.keys(stickies)) {
        const el = this.querySelector(
          `temba-sticky-note[uuid="${uuid}"]`
        ) as HTMLElement;
        if (el) {
          stickySizes.set(uuid, {
            width: el.offsetWidth,
            height: el.offsetHeight
          });
        } else {
          const sticky = stickies[uuid];
          stickySizes.set(uuid, {
            width: sticky.width || 200,
            height: sticky.height || 100
          });
        }
      }

      const stickyPositions = placeStickyNotes(
        stickies,
        oldNodePositions,
        newPositions,
        nodeSizes,
        stickySizes,
        startNodeUuid
      );

      // Merge sticky positions into newPositions
      Object.assign(newPositions, stickyPositions);
    }

    // Cancel any in-flight save timer so it doesn't persist the reflowed
    // layout before the user has a chance to Save or Discard.
    if (this.saveTimer !== null) {
      clearTimeout(this.saveTimer);
      this.saveTimer = null;
    }

    // Suppress the auto-save from this updateCanvasPositions call
    this.pendingTimer.pending = true;

    // Apply new positions
    getStore().getState().updateCanvasPositions(newPositions);

    // Update canvas size and repaint connections
    this.updateCanvasSize();
    requestAnimationFrame(() => {
      this.plumber.repaintEverything();
    });

    // Scroll to top-left so the start node is visible
    const editor = this.querySelector('#editor') as HTMLElement;
    if (editor) {
      editor.scrollTo({ left: 0, top: 0, behavior: 'smooth' });
    }

    // Start/reset auto-save countdown
    this.pendingTimer.start();
  }

  private handlePendingDiscard(): void {
    this.pendingTimer.dismiss();

    const hasChanges = this.copiedItemUuids.length > 0 || this.pendingPositions;
    if (!hasChanges) return;

    // Cancel any pending save timer before reverting
    if (this.saveTimer !== null) {
      clearTimeout(this.saveTimer);
      this.saveTimer = null;
    }

    // Remove any copied items first
    if (this.copiedItemUuids.length > 0) {
      const nodeUuids = this.copiedItemUuids.filter((uuid) =>
        this.definition.nodes.some((n) => n.uuid === uuid)
      );
      const stickyUuids = this.copiedItemUuids.filter(
        (uuid) => this.definition._ui?.stickies?.[uuid]
      );

      this.pendingTimer.pending = true;
      if (nodeUuids.length > 0) {
        getStore().getState().removeNodes(nodeUuids);
      }
      if (stickyUuids.length > 0) {
        this.pendingTimer.pending = true;
        getStore().getState().removeStickyNotes(stickyUuids);
      }
      this.copiedItemUuids = [];
    }

    // Restore all positions to pre-pending state
    if (this.pendingPositions) {
      this.pendingTimer.pending = true;
      getStore().getState().updateCanvasPositions(this.pendingPositions);
      this.pendingPositions = null;
    }

    // Clear dirty state since we reverted
    setTimeout(() => {
      getStore().getState().setDirtyDate(null);
      this.isSaving = false;
    }, 0);

    requestAnimationFrame(() => {
      this.plumber.repaintEverything();
    });
  }

  private renderPendingCard(): TemplateResult | string {
    if (!this.pendingTimer.unsaved) return '';
    // Each resetCount value produces a unique animation-name so the
    // CSS countdown restarts when the timer is reset.
    const anim = `pc-${this.pendingTimer.resetCount}`;
    return html`<div class="reflow-card">
      <div class="reflow-top">
        <span class="reflow-label">${this.pendingTimer.label}</span>
        <button class="reflow-discard" @click=${this.handlePendingDiscard}>
          Discard
        </button>
      </div>
      <div class="reflow-meter">
        <div class="reflow-meter-fill" style="animation-name: ${anim}"></div>
      </div>
      <style>
        @keyframes ${anim} {
          from {
            width: 100%;
          }
          to {
            width: 0%;
          }
        }
      </style>
    </div>`;
  }

  private deleteNodes(uuids: string[]): void {
    // Remove nodes from the definition - CanvasNode will handle plumber cleanup
    if (uuids.length > 0) {
      getStore().getState().removeNodes(uuids);
    }
  }

  private deleteSelectedItems(): void {
    const nodes = Array.from(this.selectedItems).filter((uuid) =>
      this.definition.nodes.some((node) => node.uuid === uuid)
    );
    this.deleteNodes(Array.from(nodes));

    const stickies = Array.from(this.selectedItems).filter(
      (uuid) => this.definition._ui?.stickies?.[uuid]
    );

    getStore().getState().removeStickyNotes(stickies);
 
    // Clear selection
    this.selectedItems.clear();
  }
 
  private renderCanvasDropPreview(): TemplateResult | string {
    if (!this.canvasDropPreview) return '';
 
    const { action, position } = this.canvasDropPreview;
    const actionConfig = ACTION_CONFIG[action.type];

    if (!actionConfig) return '';

    return html`<div
      class="canvas-drop-preview"
      style="position: absolute; left: ${position.left}px; top: ${position.top}px; opacity: 0.6; pointer-events: none; z-index: 10000;"
    >
      <div
        class="node execute-actions"
        style="outline: 3px dashed var(--color-primary, #3b82f6); outline-offset: 2px; border-radius: var(--curvature);"
      >
        <div class="action sortable ${action.type}">
          <div class="action-content">
            <div
              class="cn-title"
              style="background: ${actionConfig.group
                ? ACTION_GROUP_METADATA[actionConfig.group]?.color
                : '#aaaaaa'}"
            >
              <div class="title-spacer"></div>
              <div class="name">${actionConfig.name}</div>
              <div class="title-spacer"></div>
            </div>
            <div class="body">
              ${actionConfig.render
                ? actionConfig.render({ actions: [action] } as any, action)
                : html`<pre>${action.type}</pre>`}
            </div>
          </div>
        </div>
        <div class="action-exits">
          <div class="exit-wrapper">
            <div class="exit"></div>
          </div>
        </div>
      </div>
    </div>`;
  }
 
  private renderConnectionPlaceholder(): TemplateResult | string {
    if (!this.connectionPlaceholder || !this.connectionPlaceholder.visible)
      return '';
 
    const { position, dragUp } = this.connectionPlaceholder;
 
    // Render connection line when we have a pending connection (after drop)
    let svgPath = null;
    if (
      this.sourceId &&
      this.dragFromNodeId &&
      this.pendingCanvasConnection &&
      this.connectionSourceX != null &&
      this.connectionSourceY != null
    ) {
      const sourceX = this.connectionSourceX;
      const sourceY = this.connectionSourceY;
      const targetX = position.left + 100;
      // When dragging up, connect to the placeholder bottom; otherwise to the top
      const targetY = dragUp ? position.top + 64 : position.top;
 
      const routeFace: 'top' | 'left' | 'right' = dragUp
        ? targetX < sourceX
          ? 'left'
          : 'right'
        : 'top';
 
      const pathData = calculateFlowchartPath(
        sourceX,
        sourceY,
        targetX,
        targetY,
        20,
        dragUp ? 0 : 10,
        5,
        routeFace
      );

      const aw = ARROW_HALF_WIDTH;
      const al = ARROW_LENGTH;
      let arrowPoints: string;
      if (dragUp) {
        // Arrow tip pointing up, base at placeholder bottom
        arrowPoints = `${targetX},${targetY - al} ${targetX - aw},${targetY} ${
          targetX + aw
        },${targetY}`;
      } else {
        // Arrow pointing down into top of placeholder
        arrowPoints = `${targetX},${targetY} ${targetX - aw},${targetY - al} ${
          targetX + aw
        },${targetY - al}`;
      }

      svgPath = html`
        <svg
          style="position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 9999;"
        >
          <path
            d="${pathData}"
            fill="none"
            stroke="var(--color-connectors, #ccc)"
            stroke-width="3"
          />
          <polygon
            points="${arrowPoints}"
            fill="var(--color-connectors, #ccc)"
          />
        </svg>
      `;
    }

    return html`${svgPath}
      <div
        class="connection-placeholder"
        style="position: absolute; left: ${position.left}px; top: ${position.top}px; opacity: 0.6; pointer-events: none; z-index: 10000;"
      >
        <div
          class="node execute-actions"
          style="outline: 3px dashed var(--color-primary, #3b82f6); outline-offset: 2px; border-radius: var(--curvature); min-width: 200px;"
        >
          <div class="empty-node-placeholder" style="height: 60px;"></div>
          <div class="action-exits">
            <div class="exit-wrapper">
              <div class="exit" style="pointer-events: none;"></div>
            </div>
          </div>
        </div>
      </div>`;
  }
 
  /**
   * Checks for collisions between nodes and sticky notes, and reflows
   * as needed. Sacred items (just moved/dropped/resized) keep their
   * positions while other items are moved in the least-disruptive direction.
   */
  public checkCollisionsAndReflow(sacredUuids: string[] = []): void {
    if (!this.definition) return;

    const allBounds: NodeBounds[] = [];
    for (const node of this.definition.nodes) {
      const nodeUI = this.definition._ui?.nodes[node.uuid];
      if (!nodeUI?.position) continue;

      const bounds = getNodeBounds(node.uuid, nodeUI.position);
      if (bounds) {
        allBounds.push(bounds);
      }
    }
 
    const stickies = this.definition._ui?.stickies || {};
    for (const [uuid, sticky] of Object.entries(stickies)) {
      if (!sticky.position) continue;
      const el = this.querySelector(
        `temba-sticky-note[uuid="${uuid}"]`
      ) as HTMLElement;
      if (!el) continue;
      const bounds = getNodeBounds(uuid, sticky.position, el);
      if (bounds) {
        allBounds.push(bounds);
      }
    }

    const reflowPositions = calculateReflowPositions(sacredUuids, allBounds);

    if (reflowPositions.size > 0) {
      const positions: { [uuid: string]: FlowPosition } = {};
      for (const [uuid, position] of reflowPositions.entries()) {
        positions[uuid] = position;
      }
      getStore().getState().updateCanvasPositions(positions);
    }
  }

  /* c8 ignore start -- touch-only handlers */
 
  /**
   * Find the temba-flow-node element at the given viewport coordinates.
   * Uses elementFromPoint which works for both mouse and touch input.
   */
  public findTargetNodeAt(clientX: number, clientY: number): Element | null {
    const el = document.elementFromPoint(clientX, clientY);
    return el?.closest('temba-flow-node') ?? null;
  }
 
  private updateCanvasSize(): void {
    if (!this.definition) return;
 
    const store = getStore();
    if (!store) return;
 
    // Calculate required canvas size based on all elements
    let maxWidth = 0;
    let maxHeight = 0;
 
    // Check node positions
    this.definition.nodes.forEach((node) => {
      const ui = this.definition._ui.nodes[node.uuid];
      if (ui && ui.position) {
        const nodeElement = this.querySelector(
          `[id="${node.uuid}"]`
        ) as HTMLElement;
        if (nodeElement) {
          // Use offsetWidth/offsetHeight (unaffected by ancestor transforms)
          maxWidth = Math.max(
            maxWidth,
            ui.position.left + nodeElement.offsetWidth
          );
          maxHeight = Math.max(
            maxHeight,
            ui.position.top + nodeElement.offsetHeight
          );
        }
      }
    });
 
    // Check sticky note positions
    const stickies = this.definition._ui?.stickies || {};
    Object.entries(stickies).forEach(([uuid, sticky]) => {
      if (sticky.position) {
        const stickyElement = this.querySelector(
          `temba-sticky-note[uuid="${uuid}"]`
        ) as HTMLElement;
        if (stickyElement) {
          // Use clientWidth/clientHeight instead of getBoundingClientRect() to get element dimensions
          // This avoids the coordinate system mismatch between viewport and canvas coordinates
          const width = stickyElement.clientWidth;
          const height = stickyElement.clientHeight;
 
          // Both sticky.position and width/height are now in the same coordinate system
          maxWidth = Math.max(maxWidth, sticky.position.left + width);
          maxHeight = Math.max(maxHeight, sticky.position.top + height);
        } else {
          // Fallback to default sizes if element not found
          maxWidth = Math.max(
            maxWidth,
            sticky.position.left + (sticky.width || 200)
          );
          maxHeight = Math.max(
            maxHeight,
            sticky.position.top + (sticky.height || 100)
          );
        }
      }
    });
 
    // Update canvas size in store
    store.getState().expandCanvas(maxWidth, maxHeight);
  }
 
  private handleCanvasContextMenu(event: MouseEvent): void {
    if (this.isReadOnly()) {
      event.preventDefault();
      return;
    }
 
    // Check if we right-clicked on empty canvas space
    const target = event.target as HTMLElement;
    if (target.id !== 'canvas') {
      return;
    }
 
    // Prevent the default browser context menu
    event.preventDefault();
    event.stopPropagation();
 
    // Ensure no sticky note contenteditable retains focus
    this.dragManager.blurActiveContentEditable();
 
    this.showContextMenuAt(event.clientX, event.clientY);
  }
 
  /**
   * Show the canvas context menu at the given viewport coordinates.
   * Shared by right-click (mouse) and double-tap (touch).
   */
  public showContextMenuAt(clientX: number, clientY: number): void {
    if (this.isReadOnly()) return;
 
    const canvas = this.querySelector('#canvas');
    if (!canvas) return;
 
    const canvasRect = canvas.getBoundingClientRect();
    const relativeX = (clientX - canvasRect.left) / this.zoom - 10;
    const relativeY = (clientY - canvasRect.top) / this.zoom - 10;
 
    const snappedLeft = snapToGrid(relativeX);
    const snappedTop = snapToGrid(relativeY);
 
    const canvasMenu = this.querySelector('temba-canvas-menu') as CanvasMenu;
    if (canvasMenu) {
      const hasNodes = this.definition && this.definition.nodes.length > 0;
      canvasMenu.show(
        clientX,
        clientY,
        {
          x: snappedLeft,
          y: snappedTop
        },
        true,
        hasNodes,
        CONTEXT_MENU_SHORTCUTS[this.flowType]
      );
    }
  }
 
  private handleEmptyFlowClick(event: MouseEvent): void {
    const editor = this.querySelector('#editor') as HTMLElement;
    if (!editor) return;
 
    // Scroll to top-left
    editor.scrollTo({ left: 0, top: 0, behavior: 'smooth' });
 
    // Place node at top-left of the canvas
    const nodeLeft = 0;
    const nodeTop = 0;
 
    const canvasMenu = this.querySelector('temba-canvas-menu') as CanvasMenu;
    if (canvasMenu) {
      const button = event.currentTarget as HTMLElement;
      const rect = button.getBoundingClientRect();
      const menuWidth = 265;
      const menuX = rect.left + rect.width / 2 - menuWidth / 2;
      const menuY = rect.bottom + 8;
      canvasMenu.show(
        menuX,
        menuY,
        { x: nodeLeft, y: nodeTop },
        false,
        false,
        CONTEXT_MENU_SHORTCUTS[this.flowType]
      );
    }
  }
 
  private handleCanvasMenuSelection(event: CustomEvent): void {
    const selection = event.detail as CanvasMenuSelection;
    const store = getStore();
 
    if (selection.action === 'reflow') {
      this.performReflow();
      return;
    }
 
    if (selection.action === 'sticky') {
      // Create new sticky note
      const stickyUuid = store.getState().createStickyNote({
        left: selection.position.x,
        top: selection.position.y
      });
 
      // Check for collisions with the new sticky as sacred
      requestAnimationFrame(() => {
        this.checkCollisionsAndReflow([stickyUuid]);
      });
 
      // Clear all pending connection state and placeholder
      this.pendingCanvasConnection = null;
      this.connectionPlaceholder = null;
      this.sourceId = null;
      this.connectionSourceX = null;
      this.connectionSourceY = null;
      this.dragFromNodeId = null;
    } else if (selection.action === 'other') {
      // Show unified node type selector
      const selector = this.querySelector(
        'temba-node-type-selector'
      ) as NodeTypeSelector;
      if (selector) {
        selector.show('all', selection.position);
      }
      // Note: we don't clear pendingCanvasConnection or placeholder here,
      // they will be used in handleNodeTypeSelection
    } else {
      // Configured shortcut — go directly to the node editor with the
      // action/node type carried in selection.action.
      this.handleNodeTypeSelection(
        new CustomEvent(CustomEventType.Selection, {
          detail: {
            nodeType: selection.action,
            position: selection.position
          } as NodeTypeSelection
        })
      );
    }
  }
 
  private cleanUpConnection(): void {
    if (this.isCreatingNewNode) {
      this.isCreatingNewNode = false;
      this.pendingNodePosition = null;
    }
 
    // see if we need to put our connection back
    if (this.originalConnectionTargetId) {
      this.plumber.connectIds(
        this.dragFromNodeId,
        this.sourceId,
        this.originalConnectionTargetId
      );
      this.originalConnectionTargetId = null;
    }
 
    // Menu closed without selection - clear placeholder and pending connection
    if (this.pendingCanvasConnection) {
      this.pendingCanvasConnection = null;
      this.connectionPlaceholder = null;
      this.sourceId = null;
      this.connectionSourceX = null;
      this.connectionSourceY = null;
      this.dragFromNodeId = null;
      this.originalConnectionTargetId = null;
    }
  }
 
  private handleCanvasMenuClosed(): void {
    this.cleanUpConnection();
  }
 
  private handleNodeTypeSelectorClosed(): void {
    this.addActionToNodeUuid = null;
    this.cleanUpConnection();
  }
 
  private handleNodeTypeSelection(event: CustomEvent): void {
    const selection = event.detail as NodeTypeSelection;
 
    // Check if we have a pending canvas connection (from dropping on empty canvas)
    if (this.pendingCanvasConnection) {
      // Don't clear the placeholder yet - keep it visible while editing
      // The position is already stored in pendingCanvasConnection
      // Fall through to normal node creation flow below
    }
 
    // Check if we're adding an action to an existing node
    if (this.addActionToNodeUuid) {
      // Find the existing node
      const node = this.definition.nodes.find(
        (n) => n.uuid === this.addActionToNodeUuid
      );
      const nodeUI = this.definition._ui.nodes[this.addActionToNodeUuid];
 
      if (node && nodeUI) {
        // Create a new action to add to the existing node
        const actionUuid = generateUUID();
        this.editingAction = {
          uuid: actionUuid,
          type: selection.nodeType as any
        } as Action;
 
        // Set the editing node to the existing node (not creating new)
        this.editingNode = node;
        this.editingNodeUI = nodeUI;
        this.isCreatingNewNode = false;
 
        // Clear the addActionToNodeUuid flag
        this.addActionToNodeUuid = null;
 
        return;
      }
 
      // If we couldn't find the node, clear the flag and continue with normal flow
      this.addActionToNodeUuid = null;
    }
 
    // Create a temporary node structure for editing (not added to store yet)
    const nodeUuid = generateUUID();
 
    // Determine if this is an action type or a node type
    // Actions need to be wrapped in an execute_actions node
    const isActionType = selection.nodeType in ACTION_CONFIG;
    const nodeType = isActionType ? 'execute_actions' : selection.nodeType;
 
    // For nodes with routers, initialize an empty router to ensure fromFormData works correctly
    const nodeConfig = NODE_CONFIG[nodeType];
    const hasRouter =
      nodeConfig?.form &&
      Object.keys(nodeConfig.form).some(
        (key) =>
          ['rules', 'categories', 'cases'].includes(key) ||
          nodeConfig.form[key]?.type === 'array'
      );
 
    const tempNode: Node = {
      uuid: nodeUuid,
      actions: [],
      exits: hasRouter
        ? [] // Router-based nodes will generate their own exits
        : [
            {
              uuid: generateUUID(),
              destination_uuid: null
            }
          ]
    };
 
    if (hasRouter) {
      // This node uses a router - initialize it with empty structure
      tempNode.router = {
        type: 'switch',
        categories: [],
        cases: [],
        operand: '@input.text',
        default_category_uuid: undefined
      };
    }
 
    const tempNodeUI: NodeUI = {
      position: this.pendingCanvasConnection
        ? this.pendingCanvasConnection.position
        : {
            left: selection.position.x,
            top: selection.position.y
          },
      type: nodeType as any,
      config: {}
    };
 
    // Mark that we're creating a new node and store the position
    this.isCreatingNewNode = true;
    this.pendingNodePosition = this.pendingCanvasConnection
      ? this.pendingCanvasConnection.position
      : {
          left: selection.position.x,
          top: selection.position.y
        };
 
    // Open the node editor with the temporary node
    this.editingNode = tempNode;
    this.editingNodeUI = tempNodeUI;
 
    // If this is an action type, we also need to set up an editing action
    if (isActionType) {
      const actionUuid = generateUUID();
      this.editingAction = {
        uuid: actionUuid,
        type: selection.nodeType as any
      } as Action;
    }
  }
 
  private editForceBase = false;
 
  private handleActionEditRequested(event: CustomEvent): void {
    // For action editing, we set the action and find the corresponding node
    this.editingAction = event.detail.action;
    this.editForceBase = !!event.detail.forceBase;
    this.dialogOrigin =
      event.detail.originX != null
        ? { x: event.detail.originX, y: event.detail.originY }
        : null;
 
    // Find the node that contains this action
    const nodeUuid = event.detail.nodeUuid;
    const node = this.definition.nodes.find((n) => n.uuid === nodeUuid);
 
    if (node) {
      this.editingNode = node;
      this.editingNodeUI = this.definition._ui.nodes[nodeUuid];
    }
  }
 
  private handleAddActionRequested(event: CustomEvent): void {
    // Get the node where we want to add the action
    const nodeUuid = event.detail.nodeUuid;
    const node = this.definition.nodes.find((n) => n.uuid === nodeUuid);
 
    if (!node) {
      return;
    }
 
    // Get the node's position to place the selector near it
    const nodeUI = this.definition._ui.nodes[nodeUuid];
    if (!nodeUI) {
      return;
    }
 
    // Show the node type selector in action mode, excluding branching actions
    const selector = this.querySelector(
      'temba-node-type-selector'
    ) as NodeTypeSelector;
    if (selector) {
      // Show the selector near the node, using a mode that excludes branching actions
      selector.show('action-no-branching', {
        x: nodeUI.position.left,
        y: nodeUI.position.top
      });
 
      // Store the node UUID so we know which node to add the action to
      this.addActionToNodeUuid = nodeUuid;
    }
  }
 
  private handleNodeEditRequested(event: CustomEvent): void {
    this.editForceBase = !!event.detail.forceBase;
    this.editingAction = null;
    this.editingNode = event.detail.node;
    this.editingNodeUI = event.detail.nodeUI;
    this.dialogOrigin =
      event.detail.originX != null
        ? { x: event.detail.originX, y: event.detail.originY }
        : null;
  }
 
  private handleNodeDeleted(event: CustomEvent): void {
    const nodeUuid = event.detail.uuid;
    if (nodeUuid) {
      this.deleteNodes([nodeUuid]);
    }
  }
 
  private handleActionSaved(updatedAction: Action): void {
    if (this.editingNode && this.editingAction) {
      let updatedActions: Action[];
 
      // Check if this action already exists in the node
      const existingActionIndex = this.editingNode.actions.findIndex(
        (action) => action.uuid === this.editingAction.uuid
      );
 
      if (existingActionIndex >= 0) {
        // Update existing action
        updatedActions = this.editingNode.actions.map((action) =>
          action.uuid === this.editingAction.uuid ? updatedAction : action
        );
      } else {
        // Add new action
        updatedActions = [...this.editingNode.actions, updatedAction];
      }
 
      const updatedNode = { ...this.editingNode, actions: updatedActions };
 
      // Check if we're creating a new node or updating an existing one
      if (this.isCreatingNewNode) {
        // This is a new node with a new action - add it to the store
        const store = getStore();
 
        const nodeUI: NodeUI = {
          position: this.pendingNodePosition || { left: 0, top: 0 },
          type: this.editingNodeUI?.type,
          config: {}
        };
 
        // Add the node to the store
        store.getState().addNode(updatedNode, nodeUI);
 
        // If we have a pending canvas connection, connect it to this new node
        if (this.pendingCanvasConnection) {
          store
            .getState()
            .updateConnection(
              this.pendingCanvasConnection.fromNodeId,
              this.pendingCanvasConnection.exitId,
              updatedNode.uuid
            );
 
          // Clear the pending connection and placeholder
          this.pendingCanvasConnection = null;
          this.connectionPlaceholder = null;
          this.sourceId = null;
          this.connectionSourceX = null;
          this.connectionSourceY = null;
          this.dragFromNodeId = null;
        }
 
        // Reset the creation flags
        this.isCreatingNewNode = false;
        this.pendingNodePosition = null;
 
        // Check for collisions and reflow
        requestAnimationFrame(() => {
          this.checkCollisionsAndReflow([updatedNode.uuid]);
        });
      } else {
        const uuid = this.editingNode.uuid;
        // Update existing node in the store
        getStore()?.getState().updateNode(uuid, updatedNode);
 
        // Check for collisions and reflow in case node size changed
        requestAnimationFrame(() => {
          this.checkCollisionsAndReflow([uuid]);
        });
      }
    }
    this.closeNodeEditor();
  }
 
  private closeNodeEditor(): void {
    this.editingNode = null;
    this.editingNodeUI = null;
    this.editingAction = null;
    this.dialogOrigin = null;
    this.editForceBase = false;
  }
 
  private handleActionEditCanceled(): void {
    // If we were creating a new node, just discard it
    this.cleanUpConnection();
    this.closeNodeEditor();
  }
 
  private handleNodeSaved(
    updatedNode: Node,
    uiConfig?: Record<string, any>
  ): void {
    if (this.editingNode) {
      if (this.isCreatingNewNode) {
        // This is a new node - add it to the store for the first time
        const store = getStore();
 
        const nodeUI: NodeUI = {
          position: this.pendingNodePosition || { left: 0, top: 0 },
          type: this.editingNodeUI?.type,
          config: uiConfig || {}
        };
 
        // Add the node to the store
        store.getState().addNode(updatedNode, nodeUI);
 
        // If we have a pending canvas connection, connect it to this new node
        if (this.pendingCanvasConnection) {
          store
            .getState()
            .updateConnection(
              this.pendingCanvasConnection.fromNodeId,
              this.pendingCanvasConnection.exitId,
              updatedNode.uuid
            );
 
          // Clear the pending connection and placeholder
          this.pendingCanvasConnection = null;
          this.connectionPlaceholder = null;
          this.sourceId = null;
          this.connectionSourceX = null;
          this.connectionSourceY = null;
          this.dragFromNodeId = null;
        }
 
        // Reset the creation flags
        this.isCreatingNewNode = false;
        this.pendingNodePosition = null;
 
        // Check for collisions and reflow
        requestAnimationFrame(() => {
          this.checkCollisionsAndReflow([updatedNode.uuid]);
        });
      } else {
        // This is an existing node - update it
        // Clean up jsPlumb connections for removed exits before updating the node
        if (this.plumber) {
          const oldExits = this.editingNode.exits || [];
          const newExits = updatedNode.exits || [];
 
          // Find exits that were removed
          const removedExits = oldExits.filter(
            (oldExit) =>
              !newExits.find((newExit) => newExit.uuid === oldExit.uuid)
          );
 
          // Remove jsPlumb connections for removed exits
          removedExits.forEach((exit) => {
            this.plumber.removeExitConnection(exit.uuid);
          });
        }
 
        this.plumber.revalidate([updatedNode.uuid]);
 
        // Update the node in the store
        getStore()?.getState().updateNode(this.editingNode.uuid, updatedNode);
 
        // Update the UI config if provided
        if (uiConfig) {
          getStore()?.getState().updateNodeUIConfig(updatedNode.uuid, uiConfig);
        }
 
        // Check for collisions and reflow in case node size changed
        const nodeUuid = updatedNode.uuid;
        requestAnimationFrame(() => {
          this.checkCollisionsAndReflow([nodeUuid]);
        });
      }
    }
    this.closeNodeEditor();
  }
 
  private handleNodeEditCanceled(): void {
    this.cleanUpConnection();
    this.closeNodeEditor();
  }
 
  private getNodeAtPosition(mouseX: number, mouseY: number): string | null {
    // Get all node elements
    const nodeElements = this.querySelectorAll('temba-flow-node');
 
    for (const nodeElement of Array.from(nodeElements)) {
      const rect = nodeElement.getBoundingClientRect();
 
      if (
        mouseX >= rect.left &&
        mouseX <= rect.right &&
        mouseY >= rect.top &&
        mouseY <= rect.bottom
      ) {
        return nodeElement.getAttribute('data-node-uuid');
      }
    }
 
    return null;
  }
 
  private calculateCanvasDropPosition(
    mouseX: number,
    mouseY: number,
    applyGridSnapping: boolean = true
  ): FlowPosition {
    // calculate the position on the canvas
    const canvas = this.querySelector('#canvas');
    if (!canvas) return { left: 0, top: 0 };
 
    const canvasRect = canvas.getBoundingClientRect();
 
    // Convert viewport coordinates to canvas coordinates, accounting for zoom
    const left = (mouseX - canvasRect.left) / this.zoom - DROP_PREVIEW_OFFSET_X;
    const top = (mouseY - canvasRect.top) / this.zoom - DROP_PREVIEW_OFFSET_Y;
 
    // Apply grid snapping only if requested (for final drop position)
    if (applyGridSnapping) {
      return {
        left: snapToGrid(left),
        top: snapToGrid(top)
      };
    }
 
    return { left, top };
  }
 
  private handleActionDragExternal(event: CustomEvent): void {
    const {
      action,
      nodeUuid,
      actionIndex,
      mouseX,
      mouseY,
      actionHeight = 60,
      isLastAction = false
    } = event.detail;
 
    // Track action external drag state for shift-copy support
    const isFirstExternalEvent = !this.isActionExternalDrag;
    this.isActionExternalDrag = true;
    this.actionDragLastDetail = {
      action,
      nodeUuid,
      actionIndex,
      mouseX,
      mouseY,
      actionHeight,
      isLastAction
    };
 
    // Initialize copy mode from current shift state (handles shift held before drag)
    if (isFirstExternalEvent) {
      const shiftHeld =
        this.querySelector('#canvas')?.classList.contains('shift-held') ??
        false;
      if (shiftHeld) {
        this.actionDragIsCopy = true;
        this.showActionOriginal(true);
      } else {
        (this.querySelector('#drag-hint') as HTMLElement)?.classList.add(
          'visible'
        );
      }
    }
 
    // Check if mouse is over another execute_actions node
    const targetNode = this.getNodeAtPosition(mouseX, mouseY);
 
    if (targetNode && targetNode !== nodeUuid) {
      const targetNodeUI = this.definition._ui.nodes[targetNode];
      const targetNodeDef = this.definition.nodes.find(
        (n) => n.uuid === targetNode
      );
 
      // Only allow dropping on execute_actions nodes, and not the source node
      if (targetNodeUI?.type === 'execute_actions' && targetNodeDef) {
        // If we moved to a different target node, clear the previous one's placeholder
        if (
          this.previousActionDragTargetNodeUuid &&
          this.previousActionDragTargetNodeUuid !== targetNode
        ) {
          const previousElement = this.querySelector(
            `temba-flow-node[data-node-uuid="${this.previousActionDragTargetNodeUuid}"]`
          );
          if (previousElement) {
            previousElement.dispatchEvent(
              new CustomEvent('action-drag-leave', {
                detail: {},
                bubbles: false
              })
            );
          }
        }
 
        // Update target node for drop handling
        this.actionDragTargetNodeUuid = targetNode;
        this.previousActionDragTargetNodeUuid = targetNode;
 
        // Hide canvas preview when over a valid target
        this.canvasDropPreview = null;
 
        // Tell source node to show ghost (we're over a valid target)
        const sourceElement = this.querySelector(
          `temba-flow-node[data-node-uuid="${nodeUuid}"]`
        );
        if (sourceElement) {
          sourceElement.dispatchEvent(
            new CustomEvent('action-show-ghost', {
              detail: {},
              bubbles: false
            })
          );
        }
 
        // Notify the target node about the drag
        const targetElement = this.querySelector(
          `temba-flow-node[data-node-uuid="${targetNode}"]`
        );
        if (targetElement) {
          targetElement.dispatchEvent(
            new CustomEvent('action-drag-over', {
              detail: {
                action,
                sourceNodeUuid: nodeUuid,
                actionIndex,
                mouseX,
                mouseY,
                actionHeight
              },
              bubbles: false
            })
          );
        }
 
        this.requestUpdate();
        return;
      }
    }
 
    // Not over a valid target node, clear any previous target's placeholder
    if (this.previousActionDragTargetNodeUuid) {
      const previousElement = this.querySelector(
        `temba-flow-node[data-node-uuid="${this.previousActionDragTargetNodeUuid}"]`
      );
      if (previousElement) {
        previousElement.dispatchEvent(
          new CustomEvent('action-drag-leave', {
            detail: {},
            bubbles: false
          })
        );
      }
      this.previousActionDragTargetNodeUuid = null;
    }
 
    this.actionDragTargetNodeUuid = null;
 
    const sourceElement = this.querySelector(
      `temba-flow-node[data-node-uuid="${nodeUuid}"]`
    );
 
    // Show canvas drop preview if this is not the last action,
    // or if shift-copy is active (copying allows canvas drop for last action too)
    if (!isLastAction || this.actionDragIsCopy) {
      // Hide ghost when showing canvas preview (for canvas drops)
      if (sourceElement) {
        sourceElement.dispatchEvent(
          new CustomEvent('action-hide-ghost', {
            detail: {},
            bubbles: false
          })
        );
      }
 
      // Don't snap to grid for preview - let it follow cursor smoothly
      const position = this.calculateCanvasDropPosition(mouseX, mouseY, false);
 
      this.canvasDropPreview = {
        action,
        nodeUuid,
        actionIndex,
        position,
        actionHeight
      };
    } else {
      // For last action without copy, keep ghost visible (can't drop on canvas)
      if (sourceElement) {
        sourceElement.dispatchEvent(
          new CustomEvent('action-show-ghost', {
            detail: {},
            bubbles: false
          })
        );
      }
 
      // Clear any existing preview for last action
      this.canvasDropPreview = null;
    }
 
    // Force re-render to update preview position
    this.requestUpdate();
  }
 
  private handleActionDragInternal(_event: CustomEvent): void {
    // Clear any previous target's placeholder when returning to internal drag
    if (this.previousActionDragTargetNodeUuid) {
      const previousElement = this.querySelector(
        `temba-flow-node[data-node-uuid="${this.previousActionDragTargetNodeUuid}"]`
      );
      if (previousElement) {
        previousElement.dispatchEvent(
          new CustomEvent('action-drag-leave', {
            detail: {},
            bubbles: false
          })
        );
      }
      this.previousActionDragTargetNodeUuid = null;
    }
 
    this.canvasDropPreview = null;
    this.actionDragTargetNodeUuid = null;
    this.isActionExternalDrag = false;
    this.actionDragIsCopy = false;
    (this.querySelector('#drag-hint') as HTMLElement)?.classList.remove(
      'visible'
    );
    this.actionDragLastDetail = null;
  }
 
  /** Show or hide the original action element in the source node. */
  private showActionOriginal(visible: boolean): void {
    if (!this.actionDragLastDetail) return;
    const sourceElement = this.querySelector(
      `temba-flow-node[data-node-uuid="${this.actionDragLastDetail.nodeUuid}"]`
    );
    if (sourceElement) {
      sourceElement.dispatchEvent(
        new CustomEvent(
          visible ? 'action-show-original' : 'action-hide-original',
          { detail: {}, bubbles: false }
        )
      );
    }
  }
 
  /**
   * Reprocess the last action drag event with the current shift-copy state.
   * Used when shift is toggled mid-drag to show/hide the canvas preview
   * for last-action drags.
   */
  private reprocessActionDrag(): void {
    if (!this.actionDragLastDetail) return;
    const { action, nodeUuid, actionIndex, mouseX, mouseY, actionHeight } =
      this.actionDragLastDetail;
 
    const sourceElement = this.querySelector(
      `temba-flow-node[data-node-uuid="${nodeUuid}"]`
    );
 
    // Only relevant when not hovering a target node
    if (this.actionDragTargetNodeUuid) return;
 
    if (this.actionDragIsCopy) {
      // Shift pressed: show canvas preview
      if (sourceElement) {
        sourceElement.dispatchEvent(
          new CustomEvent('action-hide-ghost', {
            detail: {},
            bubbles: false
          })
        );
      }
      const position = this.calculateCanvasDropPosition(mouseX, mouseY, false);
      this.canvasDropPreview = {
        action,
        nodeUuid,
        actionIndex,
        position,
        actionHeight
      };
    } else {
      // Shift released: hide canvas preview, show ghost
      if (sourceElement) {
        sourceElement.dispatchEvent(
          new CustomEvent('action-show-ghost', {
            detail: {},
            bubbles: false
          })
        );
      }
      this.canvasDropPreview = null;
    }
  }
 
  private handleActionDropExternal(event: CustomEvent): void {
    const {
      action,
      nodeUuid,
      actionIndex,
      mouseX,
      mouseY,
      isLastAction = false
    } = event.detail;
 
    const isCopy = this.actionDragIsCopy;
 
    // Reset action drag state
    this.isActionExternalDrag = false;
    this.actionDragIsCopy = false;
    this.actionDragLastDetail = null;
    this.previousActionDragTargetNodeUuid = null;
    (this.querySelector('#drag-hint') as HTMLElement)?.classList.remove(
      'visible'
    );
 
    // Check if we're dropping on an existing execute_actions node
    const targetNodeUuid = this.actionDragTargetNodeUuid;
 
    if (targetNodeUuid && targetNodeUuid !== nodeUuid) {
      // Dropping on another node - notify the target node to handle the drop
      const targetElement = this.querySelector(
        `temba-flow-node[data-node-uuid="${targetNodeUuid}"]`
      );
      if (targetElement) {
        targetElement.dispatchEvent(
          new CustomEvent('action-drop', {
            detail: {
              action,
              sourceNodeUuid: nodeUuid,
              actionIndex,
              mouseX,
              mouseY,
              isCopy
            },
            bubbles: false
          })
        );
      }
 
      // Clear state
      this.canvasDropPreview = null;
      this.actionDragTargetNodeUuid = null;
      return;
    }
 
    // If this is the last action and not copying, do nothing
    // Last actions can only be moved to other nodes, not dropped on canvas
    if (isLastAction && !isCopy) {
      this.canvasDropPreview = null;
      this.actionDragTargetNodeUuid = null;
      return;
    }
 
    // Not dropping on another node, create a new one on canvas
    // Snap to grid for the final drop position
    const position = this.calculateCanvasDropPosition(mouseX, mouseY, true);
 
    if (!isCopy) {
      // remove the action from the original node
      const originalNode = this.definition.nodes.find(
        (n) => n.uuid === nodeUuid
      );
      if (!originalNode) return;
 
      const updatedActions = originalNode.actions.filter(
        (_a, idx) => idx !== actionIndex
      );
 
      // if no actions remain, delete the node
      if (updatedActions.length === 0) {
        // Use deleteNodes to properly clean up Plumber connections before removing
        this.deleteNodes([nodeUuid]);
      } else {
        // update the node
        const updatedNode = { ...originalNode, actions: updatedActions };
        getStore()?.getState().updateNode(nodeUuid, updatedNode);
      }
    }
 
    // create a new execute_actions node with the dropped action
    // When copying, generate a fresh UUID so the clone doesn't share the original's
    const droppedAction = isCopy ? { ...action, uuid: generateUUID() } : action;
    const newNode: Node = {
      uuid: generateUUID(),
      actions: [droppedAction],
      exits: [
        {
          uuid: generateUUID(),
          destination_uuid: null
        }
      ]
    };
 
    const newNodeUI: NodeUI = {
      position,
      type: 'execute_actions',
      config: {}
    };
 
    // add the new node
    getStore()?.getState().addNode(newNode, newNodeUI);
 
    // Copy localizations from the original action to the new one
    if (isCopy) {
      this.copyActionLocalizations(action.uuid, droppedAction.uuid);
    }
 
    // clear the preview
    this.canvasDropPreview = null;
    this.actionDragTargetNodeUuid = null;
 
    // Check for collisions and reflow after adding new node
    requestAnimationFrame(() => {
      this.checkCollisionsAndReflow([newNode.uuid]);
    });
  }
 
  /** Copy all localization entries from one action UUID to another. */
  private copyActionLocalizations(
    sourceUuid: string,
    targetUuid: string
  ): void {
    const localization = this.definition?.localization;
    if (!localization) return;
    const store = getStore()?.getState();
    if (!store) return;
    for (const langCode of Object.keys(localization)) {
      const entry = localization[langCode]?.[sourceUuid];
      if (entry) {
        store.updateLocalization(
          langCode,
          targetUuid,
          JSON.parse(JSON.stringify(entry))
        );
      }
    }
  }
 
  private closeOpenWindows(): void {
    if (!this.issuesWindowHidden) {
      this.issuesWindowHidden = true;
    }
    if (!this.revisionsWindowHidden) {
      this.getRevisionsWindow()?.close();
      this.revisionsWindowHidden = true;
    }
    if (this.simulatorActive) {
      const simulator = document.querySelector('temba-simulator') as any;
      simulator?.handleClose();
    }
  }
 
  private closeFloatingWindows(): void {
    if (!this.issuesWindowHidden) {
      this.issuesWindowHidden = true;
    }
    if (!this.revisionsWindowHidden) {
      this.getRevisionsWindow()?.close();
      this.revisionsWindowHidden = true;
    }
  }
 
  private getRevisionsWindow(): RevisionsWindow | null {
    return this.querySelector(
      'temba-revisions-window'
    ) as RevisionsWindow | null;
  }
 
  // --- Issues window event handlers ---
 
  private handleIssuesTabClick(): void {
    if (!this.issuesWindowHidden) {
      this.issuesWindowHidden = true;
      return;
    }
    this.closeOpenWindows();
    this.issuesWindowHidden = false;
  }
 
  private handleIssueSelected(e: CustomEvent): void {
    const { issue } = e.detail;
    this.issuesWindowHidden = true;
 
    this.focusNode(issue.node_uuid);
 
    const node = this.definition.nodes.find((n) => n.uuid === issue.node_uuid);
    if (!node) return;
 
    if (issue.action_uuid) {
      const action = node.actions?.find((a) => a.uuid === issue.action_uuid);
      if (action) {
        this.editingAction = action;
        this.editingNode = node;
        this.editingNodeUI = this.definition._ui.nodes[issue.node_uuid];
      }
    } else {
      this.editingNode = node;
      this.editingNodeUI = this.definition._ui.nodes[issue.node_uuid];
    }
  }
 
  // --- Revisions window event handlers ---
 
  private handleRevisionViewed(): void {
    this.viewingRevision = true;
    this.closeFlowSearch();
    this.plumber?.reset();
  }
 
  private handleRevisionCancelled(): void {
    this.viewingRevision = false;
    this.plumber?.reset();
  }
 
  private handleRevisionsClosed(): void {
    this.viewingRevision = false;
    this.revisionsWindowHidden = true;
  }
 
  private async handleRevisionReverted(e: CustomEvent): Promise<void> {
    const { definition, languageCode } = e.detail;
    this.viewingRevision = false;
    this.revisionsWindowHidden = true;
    this.plumber?.reset();
 
    await this.saveChanges(definition);
 
    getStore()
      .getState()
      .fetchRevision(`/flow/revisions/${this.flow}`)
      .finally(() => {
        if (languageCode) {
          this.handleLanguageChange(languageCode);
        }
      });
  }
 
  private renderToolbarElement(): TemplateResult {
    const languages = this.getLocalizationLanguages();
    const availableLanguages = this.getAvailableLanguages();
    const baseLanguage = this.definition?.language;
    const baseLanguageName =
      availableLanguages.find((lang) => lang.code === baseLanguage)?.name ||
      (baseLanguage ? getLanguageDisplayName(baseLanguage) : '') ||
      'Primary language';
    const isBaseSelected =
      !this.languageCode ||
      this.languageCode === baseLanguage ||
      !languages.some((lang) => lang.code === this.languageCode);
    const activeLanguage = !isBaseSelected
      ? languages.find((lang) => lang.code === this.languageCode)
      : null;
    const currentLanguage = activeLanguage || {
      code: baseLanguage || '',
      name: baseLanguageName
    };
    const progress = this.getLocalizationProgress(
      isBaseSelected ? '' : this.languageCode
    );
    const percent = Math.round(
      (progress.localized / Math.max(progress.total, 1)) * 100
    );
    const isEmptyFlow = !this.definition || this.definition.nodes.length === 0;
    const languageOptions = isEmptyFlow
      ? []
      : [
          {
            name: baseLanguageName,
            value: PRIMARY_LANGUAGE_OPTION_VALUE
          },
          ...languages.map((lang) => {
            const localizationProgress = this.getLocalizationProgress(
              lang.code
            );
            const localizationPercent = Math.round(
              (localizationProgress.localized /
                Math.max(localizationProgress.total, 1)) *
                100
            );
            return {
              name: lang.name,
              value: lang.code,
              percent: localizationPercent
            };
          })
        ];
 
    // shown whenever the active language has any localizable content, even
    // at 100% — the dialog's "update existing" option lets users re-run
    // translation on already-translated entries.
    const hasPendingTranslations =
      Boolean(activeLanguage) && progress.total > 0;
 
    return html`
      <temba-editor-toolbar
        ?message-view=${this.showMessageTable}
        .zoom=${this.zoom}
        ?zoom-initialized=${this.zoomManager.isZoomInitialized}
        ?zoom-fitted=${this.zoomManager.isZoomFitted}
        ?revisions-active=${!this.revisionsWindowHidden}
        ?is-saving=${this.isSaving}
        ?search-disabled=${this.getRevisionsWindow()?.isViewingRevision ??
        false}
        .languageOptions=${languageOptions}
        current-language-name=${currentLanguage.name}
        ?is-base-language=${isBaseSelected}
        .languagePercent=${percent}
        ?show-localization-tools=${Boolean(activeLanguage)}
        ?has-pending-translations=${hasPendingTranslations ||
        this.autoTranslating}
        ?auto-translate-disabled=${this.viewingRevision}
        ?auto-translating=${this.autoTranslating}
        @temba-button-clicked=${this.handleToolbarAction}
      ></temba-editor-toolbar>
    `;
  }
 
  private handleToolbarAction(e: CustomEvent): void {
    const detail = e.detail as ToolbarAction;
    switch (detail.action) {
      case 'view-change':
        this.showMessageTable = detail.view === 'table';
        break;
      case 'zoom-in':
        this.zoomManager.zoomIn();
        break;
      case 'zoom-out':
        this.zoomManager.zoomOut();
        break;
      case 'zoom-to-fit':
        this.zoomManager.zoomToFit();
        break;
      case 'zoom-to-full':
        this.zoomManager.zoomToFull();
        break;
      case 'revisions':
        if (!this.revisionsWindowHidden) {
          this.getRevisionsWindow()?.close();
          this.revisionsWindowHidden = true;
        } else {
          this.closeOpenWindows();
          this.revisionsWindowHidden = false;
        }
        break;
      case 'search':
        this.openFlowSearch();
        break;
      case 'auto-translate':
        this.handleAutoTranslateClick();
        break;
      case 'language-change':
        if (detail.isPrimary) {
          this.handleLanguageChange(this.definition?.language || '');
        } else if (detail.languageCode) {
          this.handleLanguageChange(detail.languageCode);
        }
        break;
    }
  }
 
  /**
   * Focus on a specific node by smoothly scrolling it to the center of the canvas
   */
  public focusNode(nodeUuid: string) {
    const nodeElement = this.querySelector(
      `temba-flow-node[uuid="${nodeUuid}"]`
    ) as HTMLElement;
    if (!nodeElement) {
      return;
    }
 
    const editor = this.querySelector('#editor') as HTMLElement;
    if (!editor) {
      return;
    }
 
    // Get the editor's dimensions and scroll position
    const editorRect = editor.getBoundingClientRect();
    const editorCenterX = editorRect.width / 2;
    const editorCenterY = editorRect.height / 2;
 
    // Use offsetWidth/offsetHeight (unaffected by ancestor transforms)
    const nodeCenterX = nodeElement.offsetLeft + nodeElement.offsetWidth / 2;
    const nodeCenterY = nodeElement.offsetTop + nodeElement.offsetHeight / 2;
 
    // Calculate the scroll position needed to center the node.
    // Multiply by zoom because scroll operates in visual (transformed) space
    // while offsetLeft/offsetTop are in layout space.
    const targetScrollX = nodeCenterX * this.zoom - editorCenterX;
    const targetScrollY = nodeCenterY * this.zoom - editorCenterY;
 
    // Smooth scroll the editor container to the target position
    editor.scrollTo({
      left: Math.max(0, targetScrollX),
      top: Math.max(0, targetScrollY),
      behavior: 'smooth'
    });
  }
 
  private handleSearchResultSelected(event: CustomEvent): void {
    const result = event.detail as SearchResult;
 
    // Handle sticky note results
    if (result.stickyField) {
      this.focusCanvasElement(
        `temba-sticky-note[uuid="${result.nodeUuid}"]`,
        result.stickyField
      );
      return;
    }
 
    const node = this.definition.nodes.find((n) => n.uuid === result.nodeUuid);
    if (!node) return;
 
    const nodeUI = this.definition._ui?.nodes[result.nodeUuid];
 
    if (this.showMessageTable) {
      const messageTable = this.querySelector('temba-message-table') as
        | (HTMLElement & {
            focusSearchResult?: (
              nodeUuid: string,
              actionUuid: string | null
            ) => void;
          })
        | null;
      messageTable?.focusSearchResult?.(
        result.nodeUuid,
        result.action?.uuid || null
      );
    } else {
      // Scroll to the node on canvas
      this.focusNode(result.nodeUuid);
    }
 
    // Open editor after a short delay so scroll can start
    setTimeout(() => {
      if (result.action) {
        // Open the action editor
        this.editingAction = result.action;
        this.editingNode = node;
        this.editingNodeUI = nodeUI;
        this.dialogOrigin = null;
      } else {
        // Open the node editor (for splits, webhooks, etc.)
        this.editingNode = node;
        this.editingNodeUI = nodeUI;
        this.dialogOrigin = null;
      }
    }, 200);
  }
 
  /**
   * Scroll a canvas element into view and optionally focus a field inside it.
   */
  private focusCanvasElement(
    selector: string,
    stickyField?: 'title' | 'body'
  ): void {
    const el = this.querySelector(selector) as HTMLElement;
    if (!el) return;
 
    const editor = this.querySelector('#editor') as HTMLElement;
    if (!editor) return;
 
    const editorRect = editor.getBoundingClientRect();
    const centerX = el.offsetLeft + el.offsetWidth / 2;
    const centerY = el.offsetTop + el.offsetHeight / 2;
    const targetScrollX = centerX * this.zoom - editorRect.width / 2;
    const targetScrollY = centerY * this.zoom - editorRect.height / 2;
 
    editor.scrollTo({
      left: Math.max(0, targetScrollX),
      top: Math.max(0, targetScrollY),
      behavior: 'smooth'
    });
 
    if (stickyField) {
      setTimeout(() => {
        const fieldEl = el.shadowRoot?.querySelector(
          `.sticky-${stickyField}`
        ) as HTMLElement;
        if (fieldEl) {
          fieldEl.focus();
        }
      }, 300);
    }
  }
 
  public isReadOnly(): boolean {
    return this.viewingRevision || this.isTranslating;
  }
 
  public render(): TemplateResult {
    // we have to embed our own style since we are in light DOM
    const style = html`<style>
      ${unsafeCSS(Editor.styles.cssText)}
      ${unsafeCSS(CanvasNode.styles.cssText)}
    </style>`;
 
    const stickies = this.definition?._ui?.stickies || {};
 
    // Detect flows with missing UI metadata (e.g. stale _ui after UUID
    // regeneration during export/import). Flag as corrupted if any node
    // is missing a _ui entry, not just when all are.
    const hasCorruptedUI =
      this.definition &&
      this.definition.nodes.length > 0 &&
      this.definition.nodes.some((n) => !this.definition._ui?.nodes[n.uuid]);
 
    return html`${style}
      <temba-issues-window
        .issues=${this.flowIssues}
        ?hidden=${this.issuesWindowHidden}
        @temba-issue-selected=${this.handleIssueSelected}
        @temba-issues-closed=${() => (this.issuesWindowHidden = true)}
      ></temba-issues-window>
      <temba-revisions-window
        .flow=${this.flow}
        ?hidden=${this.revisionsWindowHidden}
        ?saving=${this.isSaving}
        @temba-revision-viewed=${this.handleRevisionViewed}
        @temba-revision-cancelled=${this.handleRevisionCancelled}
        @temba-revision-reverted=${this.handleRevisionReverted}
        @temba-revisions-closed=${this.handleRevisionsClosed}
      ></temba-revisions-window>
      <temba-auto-translate
        .definition=${this.definition}
        language-code=${this.languageCode}
        ?disabled=${this.viewingRevision}
        @temba-auto-translate-changed=${this.handleAutoTranslateChanged}
      ></temba-auto-translate>
      <div id="editor-container">
        ${this.renderToolbarElement()}
        <div id="editor">
          ${this.showMessageTable
            ? html`<temba-message-table></temba-message-table>`
            : html`
                ${hasCorruptedUI
                  ? html`<div class="empty-flow">
                      <div class="empty-flow-content">
                        <div class="empty-flow-title">
                          Unable to display this flow
                        </div>
                        <div class="empty-flow-description">
                          This flow's layout data does not match its nodes. It
                          may have been corrupted during an export or migration.
                          Please re-export the flow from the original workspace
                          and try importing it again.
                        </div>
                      </div>
                    </div>`
                  : this.definition &&
                      this.definition.nodes.length === 0 &&
                      !this.isReadOnly()
                    ? html`<div class="empty-flow">
                        <div class="empty-flow-content">
                          <div class="empty-flow-title">This flow is empty</div>
                          <div class="empty-flow-description">
                            Get started by adding your first action or split to
                            define how this flow will work.
                          </div>
                          <button
                            class="empty-flow-button"
                            @click=${this.handleEmptyFlowClick}
                          >
                            Add first step
                          </button>
                        </div>
                      </div>`
                    : ''}
                <div
                  id="grid"
                  class="${this.viewingRevision ? 'viewing-revision' : ''}"
                  style="min-width:${100 / this.zoom}%;min-height:${100 /
                  this.zoom}%;width:${this.canvasSize.width}px; height:${this
                    .canvasSize.height}px;transform:scale(${this.zoom})"
                >
                  <div
                    id="canvas"
                    class="${getClasses({
                      'viewing-revision': this.viewingRevision,
                      'read-only-connections':
                        this.viewingRevision || this.isTranslating
                    })}"
                  >
                    ${this.definition && !hasCorruptedUI
                      ? repeat(
                          [...this.definition.nodes].sort((a, b) =>
                            a.uuid.localeCompare(b.uuid)
                          ),
                          (node) => node.uuid,
                          (node) => {
                            const nodeUI = this.definition._ui?.nodes[
                              node.uuid
                            ] || {
                              position: { left: 0, top: 0 },
                              type: node.router?.wait
                                ? 'wait_for_response'
                                : 'execute_actions'
                            };
                            const position = nodeUI.position;
 
                            const dragging =
                              this.isDragging &&
                              this.currentDragItem?.uuid === node.uuid;
 
                            const selected = this.selectedItems.has(node.uuid);
 
                            // first node is the flow start (nodes are sorted by position)
                            const isFlowStart =
                              this.definition.nodes.length > 0 &&
                              this.definition.nodes[0].uuid === node.uuid;
 
                            return html`<temba-flow-node
                              class="draggable ${dragging
                                ? 'dragging'
                                : ''} ${selected
                                ? 'selected'
                                : ''} ${isFlowStart ? 'flow-start' : ''}"
                              @mousedown=${(e: MouseEvent) =>
                                this.dragManager.handleMouseDown(e)}
                              @touchstart=${(e: TouchEvent) =>
                                this.dragManager.handleItemTouchStart(e)}
                              uuid=${node.uuid}
                              data-node-uuid=${node.uuid}
                              style="left:${position.left}px; top:${position.top}px;transition: all 0.2s ease-in-out;"
                              .plumber=${this.plumber}
                              .node=${node}
                              .ui=${nodeUI}
                              @temba-node-deleted=${(event) => {
                                this.deleteNodes([event.detail.uuid]);
                              }}
                            ></temba-flow-node>`;
                          }
                        )
                      : hasCorruptedUI
                        ? ''
                        : html`<temba-loading></temba-loading>`}
                    ${repeat(
                      Object.entries(stickies),
                      ([uuid]) => uuid,
                      ([uuid, sticky]) => {
                        const position = sticky.position || { left: 0, top: 0 };
                        const dragging =
                          this.isDragging &&
                          this.currentDragItem?.uuid === uuid;
                        const selected = this.selectedItems.has(uuid);
                        return html`<temba-sticky-note
                          class="draggable ${dragging
                            ? 'dragging'
                            : ''} ${selected ? 'selected' : ''}"
                          @mousedown=${(e: MouseEvent) =>
                            this.dragManager.handleMouseDown(e)}
                          @touchstart=${(e: TouchEvent) =>
                            this.dragManager.handleItemTouchStart(e)}
                          style="left:${position.left}px; top:${position.top}px;"
                          uuid=${uuid}
                          .data=${sticky}
                          .dragging=${dragging}
                          .selected=${selected}
                        ></temba-sticky-note>`;
                      }
                    )}
                    ${this.dragManager.renderSelectionBox()}
                    ${this.renderCanvasDropPreview()}
                    ${this.renderConnectionPlaceholder()}
                  </div>
                </div>
              `}
        </div>
        ${this.renderPendingCard()}
        <div class="drag-hint" id="drag-hint">Hold ⇧ to duplicate</div>
      </div>
      <div class="loupe" id="loupe">
        <div class="loupe-content" id="loupe-content"></div>
        <div class="loupe-crosshair-h"></div>
        <div class="loupe-crosshair-v"></div>
      </div>
 
      ${this.editingNode || this.editingAction
        ? html`<temba-node-editor
            .node=${this.editingNode}
            .nodeUI=${this.editingNodeUI}
            .action=${this.editingAction}
            .dialogOrigin=${this.dialogOrigin}
            ?force-base=${this.editForceBase}
            @temba-node-saved=${(e: CustomEvent) =>
              this.handleNodeSaved(e.detail.node, e.detail.uiConfig)}
            @temba-action-saved=${(e: CustomEvent) =>
              this.handleActionSaved(e.detail.action)}
            @temba-node-edit-cancelled=${this.handleNodeEditCanceled}
          ></temba-node-editor>`
        : ''}
 
      <temba-canvas-menu></temba-canvas-menu>
      ${!this.viewingRevision
        ? html`<temba-node-type-selector
            .flowType=${this.flowType}
            .features=${this.features}
          ></temba-node-type-selector>`
        : ''}
      <temba-flow-search
        .scope=${this.showMessageTable ? 'table' : 'flow'}
        .includeCategories=${this.isTranslating &&
        this.hasAnyNodeWithLocalizeCategories()}
        @temba-search-result-selected=${this.handleSearchResultSelected}
      ></temba-flow-search>
      ${!this.showMessageTable && this.flowIssues?.length
        ? html`
            <temba-floating-tab
              id="issues-tab"
              icon="alert_warning"
              label="Flow Issues"
              color="tomato"
              order="2"
              .active=${!this.issuesWindowHidden}
              @temba-button-clicked=${() => this.handleIssuesTabClick()}
            ></temba-floating-tab>
          `
        : ''} `;
  }
}