All files / src/flow NodeEditor.ts

66.1% Statements 1779/2691
71.69% Branches 309/431
78.33% Functions 47/60
66.1% Lines 1779/2691

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 269293x 297x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 76x 76x 222x 222x 222x 222x 64x 64x 222x 222x 222x 222x 222x 222x 77x 77x 77x 93x 64x 64x 64x 64x 64x 64x 64x 64x 93x 389x 389x 16x 373x 373x 326x     389x 16x 16x 16x 16x 16x 16x 16x 389x 389x 389x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 5684x 5684x 93x 129x 129x 129x 129x 129x 129x 129x 129x 93x 93x 129x 129x 129x 93x 2x 2x 2x 2x 2x 390x 390x 390x 390x 390x 390x 390x 390x 390x 390x 130x 130x 130x 130x 92x 89x 89x 89x 89x 130x 41x 41x 41x 41x 41x 41x     93x 390x 390x 390x 390x 390x 390x 89x 130x 41x 41x 41x 41x 41x 41x 93x 259x 259x 259x 259x 259x 259x 259x 80x 80x 79x 259x 177x 177x 177x 177x 177x 177x 177x 2x 177x 2x 2x 2x 2x   2x 2x 2x 2x 2x 175x 175x 175x 155x 175x 177x 177x 177x 82x 82x 79x 79x 79x 79x 79x 79x 79x 79x 4x 4x 79x 79x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x 8x 4x 4x 4x       4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x             4x 4x 4x 4x 4x 79x 75x 75x 75x 75x 75x 75x 79x 79x 10x 79x 8x 8x 8x 8x 8x 8x 12x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 10x 10x 10x 8x 8x 79x 79x 79x 259x 259x 259x 1131x 424x 424x 424x 424x 981x 707x 707x 707x 707x 93x 130x 130x 130x 130x 130x 130x 130x 1x 1x 1x 1x 130x                                                               130x 93x 256x 256x 256x 256x 256x 256x 1131x 1131x 1131x 1131x 1131x 930x 1131x 30x 30x 30x 2x 2x 2x 2x 2x           256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 93x 338x 338x 873x 873x 873x 873x 873x 873x 254x 254x 873x 873x 873x 90x 90x 90x 90x 90x 90x 82x 82x 82x 82x 82x 93x 254x 254x 218x 218x 218x 24x 24x 218x 218x 218x 218x 254x 36x 36x 36x 36x 93x 33x 33x 33x 33x 33x 2x 33x 2097x 2097x 2097x 2097x 443x 443x 443x 427x 427x 427x 443x 16x   16x 16x 16x 443x 443x 1654x 1786x 1814x 8x 93x 1177x 379x 379x 379x 379x 379x 379x 377x 377x 377x 41x 93x 4x 4x 4x 4x 4x 1x 93x 5x 5x 5x 5x 3x 3x           5x 2x                                                 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 4x 3x 3x 3x 2x 4x 4x 4x 2x 2x 2x                                       2x 2x 2x 2x 2x 2x 2x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                             93x 93x 93x 93x 93x 93x 93x 93x 2x 2x                         2x 2x 2x 2x 2x                             93x 3x 3x 3x 3x 3x 3x 3x 3x 3x 93x 5x 5x 5x 5x 5x 21x 21x 21x 21x 21x 3x 21x                   21x 21x 21x 21x 3x 3x 3x 3x 3x 3x 3x 21x 21x 5x 93x 1x 1x 93x 3x 3x 3x 3x 3x 3x 3x 14x 14x 14x 14x 14x 14x 14x 14x                             14x 14x 3x 3x 14x   14x 14x 14x 14x 14x                 14x 14x 14x 14x           3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 3x 2x 2x 2x 3x 3x 3x 3x 3x 3x 93x 3x 3x 3x 3x 3x 3x 3x 19x 19x                                       19x 93x 3x 3x 3x 3x 93x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                             3x 3x 3x                                                                                                                                                                                                                                                                                       93x 1x 1x 1x 1x 1x 1x 1x 1x       1x                                                                     93x 129x 129x 129x 129x 129x 129x 129x 129x 93x 228x 366x 35x 366x                                                                 35x 35x 366x     366x 366x 366x 35x 35x 35x 35x 35x 35x 99x 366x                                             93x 93x 93x 101x 101x 101x 101x     32x 32x 32x 32x 1068x 1068x 1068x 8x 1068x 1068x 8x 8x 1068x 1068x 1068x 1068x 1068x 1068x 1068x 1068x 1068x 1068x 1068x 1068x 29x 8x 8x 1x 100x 100x 100x 96x 96x 96x 96x 1x 1x 1x 1x 1x                                   93x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x           6x 6x 1x 1x 6x 6x 6x 6x                                                                                                                             6x 6x 6x 1x 1x 1x 6x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 7x 12x 2x 2x 2x 2x 93x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x   2x 2x 2x 93x                                     8x 8x 8x 8x 8x 8x 4x 4x 8x 4x 4x 4x 8x   4x 8x 1x 1x 8x 1036x 1036x 1036x 8x 8x 8x 8x 1028x 1028x 1036x 1036x 1036x 1036x 1036x 1036x 1036x 174x 174x 174x                   174x 174x 174x 34x 34x 160x 140x 140x 95x 95x 95x 94x 94x 94x 94x 94x 94x 94x 94x 1x 1x 1x 1x 1x 1x     1036x 1036x 1036x 1036x 1036x 1036x 1036x 1036x 1036x 1036x                                           93x         93x                   93x                                                                                                                             93x 917x 917x 1640x 917x 917x 917x 12x 12x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 913x 917x 913x 913x 913x 913x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 813x 813x 813x 813x 813x 813x 813x 813x 917x       1994x 28x 28x 1994x   1994x 128x 128x         1994x 4x 1x 1x 1x 1x 1x 1994x   93x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 60x 60x 60x 28x 28x 28x 60x 60x 60x 28x 28x 28x 28x 28x 28x 52x 52x 52x 52x 8x 8x 44x 44x 44x 44x 44x 28x 28x 4x 4x 4x 4x 6x 6x 28x 64x 64x 4x 4x 1x 1x 60x 64x   52x 52x 52x 52x 52x 64x 20x 20x 20x 64x 64x 64x 64x 52x 52x 52x 52x 52x   1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 52x 32x 32x 8x             28x       28x             28x                                                                                                                                                                                                                                                                                                                                                                                                   93x 128x 128x 128x 128x 128x 128x 128x 128x 128x 128x 297x 297x 297x 297x 297x 297x 297x 297x 12x 12x 297x 4x 4x 4x 293x 293x 293x 293x 293x 293x 293x 293x 293x 293x 293x 293x 293x 293x 128x 128x 1x 1x 128x 7x 7x 128x 128x 128x 128x 292x 292x 292x 94x 94x 94x 17x 94x 94x 94x 94x 94x 94x 94x 292x 292x 292x 292x 292x 292x 292x 292x 292x 319x 319x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 150x 150x 142x 142x 142x 292x   292x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 93x                       93x 649x 649x 649x 649x 755x 755x 755x 755x 20x 20x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x               649x 649x 649x       93x             93x 128x 128x 128x 128x 128x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 93x 45x 45x 45x 45x 45x 45x 45x 45x 45x             45x 65x 65x 65x 143x 143x 143x 93x 93x 65x 65x 65x 93x 70x 70x 93x 93x 93x 93x 93x 93x 82x 82x 82x 82x 82x 93x 93x 93x 93x 93x 93x 93x 746x 93x 93x 93x 93x 93x 93x 92x 92x 92x 92x 92x 93x 93x 93x 93x 93x 93x 93x 93x 93x  
import { html, TemplateResult, css, PropertyValues } from 'lit';
import { property, state } from 'lit/decorators.js';
import { RapidElement } from '../RapidElement';
import { Node, NodeUI, Action, FlowDefinition } from '../store/flow-definition';
import {
  ValidationResult,
  NodeConfig,
  NODE_CONFIG,
  ACTION_CONFIG,
  FieldConfig,
  ActionConfig
} from './config';
import {
  LayoutItem,
  RowLayoutConfig,
  GroupLayoutConfig,
  AccordionLayoutConfig,
  FormData,
  ACTION_GROUP_METADATA,
  SPLIT_GROUP_METADATA
} from './types';
import { CustomEventType } from '../interfaces';
import { generateUUID } from '../utils';
import {
  formatIssueMessage,
  resolveToLocalizationFormData,
  resolveFromLocalizationFormData
} from './utils';
import { getTranslatableCategoriesForNode } from './categoryLocalization';
import { collectReservedCategoryErrors } from './categoryUtils';
import { FieldRenderer } from '../form/FieldRenderer';
import { renderMarkdownInline } from '../markdown';
import {
  AppState,
  FlowInfo,
  FlowIssue,
  fromStore,
  zustand
} from '../store/AppState';
import { getStore } from '../store/Store';
 
export class NodeEditor extends RapidElement {
  static get styles() {
    return css`
      .node-editor-form {
        padding: 20px;
        display: flex;
        flex-direction: column;
        gap: 15px;
        min-width: 400px;
 
        --color-bubble-bg: rgba(var(--primary-rgb), 0.7);
        --color-bubble-border: rgba(0, 0, 0, 0.2);
        --color-bubble-text: #fff;
      }
 
      .form-field {
        display: flex;
        flex-direction: column;
      }
 
      .form-field label {
      }
 
      .field-errors {
        color: var(--color-error, tomato);
        font-size: 12px;
        margin-left: 5px;
        margin-top: 15px;
      }
 
      .issue-warning {
        display: flex;
        align-items: center;
        gap: 8px;
        color: var(--color-error, tomato);
        font-size: 13px;
        cursor: pointer;
      }
 
      .issue-warning:hover .issue-text {
        text-decoration: underline;
      }
 
      .form-actions {
        display: flex;
        gap: 10px;
        justify-content: flex-end;
        margin-top: 20px;
      }
 
      .action-section {
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        padding: 15px;
        margin: 10px 0;
      }
 
      .action-section h3 {
        margin: 0 0 10px 0;
        color: #333;
        font-size: 14px;
        font-weight: 600;
      }
 
      .router-section {
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        padding: 15px;
        margin: 10px 0;
      }
 
      .router-section h3 {
        margin: 0 0 10px 0;
        color: #333;
        font-size: 14px;
        font-weight: 600;
      }
 
      .form-row {
        display: grid;
        gap: 1rem;
        align-items: center;
      }
 
      .form-row-wrapper {
        display: flex;
        flex-direction: column;
      }
 
      .form-row-label {
        margin-bottom: 5px;
        margin-left: 4px;
        display: block;
        font-weight: 400;
        font-size: var(--label-size);
        letter-spacing: 0.05em;
        line-height: normal;
        color: var(--color-label, #777);
      }
 
      .form-row-inline-label {
        font-size: 20px;
        font-weight: 300;
        color: #ccc;
        min-width: 20px;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
        user-select: none;
      }
 
      .form-row-help {
        font-size: 12px;
        color: #666;
        margin-top: 6px;
      }
 
      .form-text {
        color: #666;
        font-size: 13px;
      }
 
      .form-group {
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        overflow: hidden;
      }
 
      .form-group.no-border {
        border: none;
      }
 
      .form-group.no-border > .form-group-header {
        background: none;
        border-bottom: none;
        padding-left: 11px; /* 1px border + 10px padding to align with bordered groups */
      }
 
      .form-group.no-border > .form-group-header:hover {
        background: none;
      }
 
      .form-group.no-border > .form-group-content {
        padding-left: 0;
        padding-right: 0;
      }
 
      .form-group.has-errors {
        border-color: var(--color-error, tomato);
      }
 
      .form-group.has-bubble {
        border-width: 2px;
        border-color: rgba(var(--primary-rgb), 0.5);
      }
 
      .form-group-header {
        background: #f8f9fa;
        padding: 8px 10px;
        border-bottom: 1px solid #e0e0e0;
 
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;
        user-select: none;
      }
 
      .form-group.has-bubble .form-group-header {
        background: rgba(var(--primary-rgb), 0.1);
      }
 
      .collapsed .form-group-header {
        border: none;
      }
 
      .form-group-header:hover {
        background: rgba(0, 0, 0, 0.05);
      }
 
      .form-group-header.collapsible:hover {
        background: #f1f3f4;
      }
 
      .form-group-info {
        flex: 1;
      }
 
      .form-group-title {
        font-weight: 500;
        color: var(--color-label, #777);
        font-size: 14px;
        display: flex;
        align-items: center;
      }
 
      .form-group-help {
        font-size: 12px;
        color: #666;
        margin-top: 2px;
      }
 
      .form-group-toggle {
        color: #666;
        transition: transform 0.3s ease;
        display: flex;
        align-items: center;
      }
 
      .form-group-toggle.collapsed {
        transform: rotate(-90deg);
      }
 
      .form-group-content {
        padding: var(--group-content-padding, 6px);
        display: flex;
        flex-direction: column;
        gap: 15px;
        overflow: hidden;
        transition: all 0.2s ease-in-out;
 
        opacity: 1;
      }
 
      .form-group-content.collapsed {
        max-height: 0;
        padding-top: 0 !important;
        padding-bottom: 0 !important;
        opacity: 0;
      }
 
      .group-toggle-icon {
        color: #666;
        transition:
          transform 0.3s ease,
          opacity 0.3s ease;
        cursor: pointer;
        transform: rotate(0deg);
        opacity: 1;
      }
 
      .group-toggle-icon.faded {
        opacity: 0;
      }
 
      .group-toggle-icon.expanded {
        transform: rotate(90deg);
      }
 
      .group-toggle-icon.collapsed {
        transform: rotate(0deg);
      }
 
      .group-toggle-icon:hover {
        color: #333;
      }
 
      .group-error-icon {
        color: var(--color-error, tomato);
        margin-right: 8px;
      }
 
      .group-count-bubble {
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 11px;
        font-weight: 600;
        padding: 4px;
        min-width: 12px;
        min-height: 12px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        line-height: 0px;
        opacity: 1;
        transition: opacity 0.3s ease;
        background: var(--color-bubble-bg, #fff);
        border: 1px solid var(--color-bubble-border, #777);
        color: var(--color-bubble-text, #000);
      }
 
      .group-count-bubble.hidden {
        opacity: 0;
        pointer-events: none;
      }
 
      .group-checkmark-icon {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 1;
        transition: opacity 0.3s ease;
        border-radius: 50%;
        color: var(--color-bubble-text, #000);
        background: var(--color-bubble-bg, #fff);
        border: 1px solid var(--color-bubble-border, #777);
        padding: 0.2em;
      }
 
      .group-checkmark-icon.hidden {
        opacity: 0;
        pointer-events: none;
      }
 
      .group-toggle-container {
        position: relative;
        display: flex;
        align-items: center;
      }
 
      /* Accordion styles are now in temba-accordion-section component */
 
      .gutter-fields {
        display: flex;
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
      }
 
      .gutter-fields .form-row {
        margin: 0;
      }
 
      .gutter-fields temba-checkbox {
        align-self: flex-start;
      }
 
      .gutter-fields temba-select {
        min-width: 150px;
      }
 
      .optional-field-link {
        margin: 10px 0;
      }
 
      .optional-field-link a {
        color: var(--color-link-primary, #0066cc);
        text-decoration: none;
        font-size: 13px;
        cursor: pointer;
      }
 
      .optional-field-link a:hover {
        text-decoration: underline;
      }
 
      .original-value {
        background: #fff8dc;
        padding: 10px;
        border-radius: 4px;
        font-size: 13px;
        color: #666;
      }
 
      .original-value-content {
        color: #333;
        white-space: pre-wrap;
        word-break: break-word;
      }
 
      .category-localization-table {
        width: 100%;
        display: flex;
        flex-direction: column;
      }
 
      .category-localization-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 8px;
        align-items: center;
        padding: 4px 0;
      }
 
      .original-name {
        font-size: 13px;
        color: #333;
        padding: 10px 12px;
        background: #fff8dc;
        border-radius: var(--curvature);
        display: flex;
        flex-direction: column;
        justify-content: center;
        min-height: 38px;
        box-sizing: border-box;
      }
 
      .localized-name temba-textinput {
        width: 100%;
      }
 
      .localization-section-label {
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #aaa;
        padding: 10px 0 2px;
      }
 
      .localization-section-label:first-child {
        padding-top: 0;
      }
 
      .rule-operator {
        font-size: 11px;
        color: #b8a060;
        margin-right: 4px;
      }
    `;
  }
 
  @property({ type: Object })
  action?: Action;
 
  @property({ type: Object })
  node?: Node;
 
  @property({ type: Object })
  nodeUI?: NodeUI;
 
  @property({ attribute: false })
  dialogOrigin?: { x: number; y: number };
 
  @property({ type: Boolean })
  isOpen: boolean = false;
 
  @state()
  private formData: FormData = {};
 
  @state()
  private originalFormData: FormData = {};
 
  @state()
  private errors: { [key: string]: string } = {};
 
  @state()
  private groupCollapseState: { [key: string]: boolean } = {};
 
  @state()
  private groupHoverState: { [key: string]: boolean } = {};
 
  @state()
  private revealedOptionalFields: Set<string> = new Set();
 
  @fromStore(zustand, (state: AppState) => state.languageCode)
  private languageCode!: string;
 
  @fromStore(zustand, (state: AppState) => state.isTranslating)
  private _isTranslating!: boolean;

  @property({ type: Boolean, attribute: 'force-base' })
  forceBase = false;
 
  private get isTranslating(): boolean {
    return this.forceBase ? false : this._isTranslating;
  }
 
  @fromStore(zustand, (state: AppState) => state.flowDefinition)
  private flowDefinition!: FlowDefinition;
 
  @fromStore(zustand, (state: AppState) => state.flowInfo)
  private flowInfo!: FlowInfo;
 
  @fromStore(zustand, (state: AppState) => state.issuesByNode)
  private issuesByNode!: Map<string, FlowIssue[]>;
 
  @fromStore(zustand, (state: AppState) => state.issuesByAction)
  private issuesByAction!: Map<string, FlowIssue[]>;
 
  private boundHandleEscape = this.handleEscapeKey.bind(this);
 
  connectedCallback(): void {
    super.connectedCallback();
    this.initializeFormData();
    document.addEventListener('keydown', this.boundHandleEscape);
  }
 
  disconnectedCallback(): void {
    super.disconnectedCallback();
    document.removeEventListener('keydown', this.boundHandleEscape);
  }
 
  private handleEscapeKey(event: KeyboardEvent): void {
    if (event.key === 'Escape' && this.isOpen) {
      this.handleCancel();
    }
  }
 
  willUpdate(changedProperties: PropertyValues): void {
    super.willUpdate(changedProperties);
    if (
      changedProperties.has('node') ||
      changedProperties.has('action') ||
      changedProperties.has('nodeUI')
    ) {
      // For action editing, we only need the action
      if (this.action && (!this.node || !this.nodeUI)) {
        this.isOpen = true;
        this.initializeFormData();
        this.errors = {};
      }
      // For node editing, we need both node and nodeUI
      else if (this.node && this.nodeUI) {
        this.isOpen = true;
        this.initializeFormData();
        this.errors = {};
      }
      // If we don't have the required data, close the dialog
      else if (!this.action && (!this.node || !this.nodeUI)) {
        this.isOpen = false;
      }
    }
  }
 
  updated(changedProperties: Map<string | number | symbol, unknown>): void {
    super.updated(changedProperties);
    if (
      changedProperties.has('node') ||
      changedProperties.has('action') ||
      changedProperties.has('nodeUI')
    ) {
      // For action editing, we only need the action
      if (this.action && (!this.node || !this.nodeUI)) {
        this.resolveFormData();
      }
      // For node editing, we need both node and nodeUI
      else if (this.node && this.nodeUI) {
        this.resolveFormData();
      }
    }
  }
 
  private initializeFormData(): void {
    this.groupCollapseState = {};
    const nodeConfig = this.getNodeConfig();
 
    // Temporary: terminal nodes defer to action configs, same as execute_actions
    if (
      (!nodeConfig ||
        nodeConfig.type === 'execute_actions' ||
        nodeConfig.type === 'terminal') &&
      this.action
    ) {
      // Action editing mode - use action config
      const actionConfig = ACTION_CONFIG[this.action.type];
 
      // Check if we're in localization mode
      const actionToLocalization = actionConfig
        ? resolveToLocalizationFormData(actionConfig)
        : undefined;
      if (this.isTranslating && actionToLocalization) {
        // Get localized values for this action
        const localization =
          this.flowDefinition?.localization?.[this.languageCode]?.[
            this.action.uuid
          ] || {};
 
        this.formData = actionToLocalization(this.action, localization);
      } else if (actionConfig?.toFormData) {
        this.formData = actionConfig.toFormData(this.action);
      } else {
        this.formData = { ...this.action };
      }
 
      // Convert Record objects to array format for key-value editors
      this.processFormDataForEditing();
 
      // Store a copy of the original form data for computed field comparisons
      this.originalFormData = JSON.parse(JSON.stringify(this.formData));
    } else if (this.node) {
      // Node editing mode - use node config
      const nodeConfig = this.getNodeConfig();
 
      // Check if we're in localization mode for a node with localizable categories
      const nodeToLocalization = nodeConfig
        ? resolveToLocalizationFormData(nodeConfig)
        : undefined;
      if (
        this.isTranslating &&
        nodeConfig?.localizable === 'categories' &&
        nodeToLocalization
      ) {
        // Get localized values for this node's categories
        const localization =
          this.flowDefinition?.localization?.[this.languageCode] || {};
 
        this.formData = nodeToLocalization(this.node, localization);
 
        const translatableCategoryUuids = new Set(
          getTranslatableCategoriesForNode(
            this.nodeUI?.type,
            this.node.router?.categories
          ).map((category) => category.uuid)
        );
 
        // Filter categories to translatable ones
        if (
          this.formData.categories &&
          typeof this.formData.categories === 'object' &&
          !Array.isArray(this.formData.categories)
        ) {
          this.formData = {
            ...this.formData,
            categories: Object.fromEntries(
              Object.entries(this.formData.categories).filter(
                ([categoryUuid]) => translatableCategoryUuids.has(categoryUuid)
              )
            )
          };
        }
 
        // Determine visibility based on per-node config or existing values
        const nodeConfig2 = this.nodeUI?.config || {};
        const showCategories =
          nodeConfig2.localizeCategories ||
          (this.formData.categories &&
            Object.values(this.formData.categories).some(
              (c: any) => c.localizedName
            ));
        const showRules =
          nodeConfig2.localizeRules ||
          (this.formData.rules &&
            Object.values(this.formData.rules).some((r: any) =>
              r.localizedArguments?.some((a: string) => a)
            ));
 
        // Remove sections that shouldn't be shown
        if (!showCategories) {
          delete this.formData.categories;
        }
        if (!showRules) {
          delete this.formData.rules;
        }
      } else if (nodeConfig?.toFormData) {
        this.formData = nodeConfig.toFormData(this.node, this.nodeUI);
      } else {
        this.formData = { ...this.node };
      }
 
      // For new wait_for_response nodes, default the result name
      if (
        this.nodeUI?.type === 'wait_for_response' &&
        !this.formData.result_name &&
        this.flowInfo?.results &&
        !this.flowDefinition?._ui?.nodes?.[this.node.uuid]
      ) {
        const existingNames = new Set(this.flowInfo.results.map((r) => r.name));
        let candidate = 'Result';
        let i = 2;
        while (existingNames.has(candidate)) {
          candidate = `Result ${i}`;
          i++;
        }
        this.formData.result_name = candidate;
        this.formData._isNew = true;
      }

      // Convert Record objects to array format for key-value editors
      this.processFormDataForEditing();
 
      // Store a copy of the original form data for computed field comparisons
      this.originalFormData = JSON.parse(JSON.stringify(this.formData));
    }
 
    // enforce immutability of formData
    Object.keys(this.formData).forEach((key) => {
      const value = this.formData[key];
      if (Array.isArray(value)) {
        this.formData[key] = [...value];
      } else if (value && typeof value === 'object') {
        // If it's an object, ensure we don't mutate the original
        this.formData[key] = { ...value };
      }
    });
  }

  private async resolveFormData(): Promise<void> {
    const config = this.getConfig();
    if (!config?.resolveFormData) return;
 
    try {
      const resolved = await config.resolveFormData(this.formData);
      if (resolved && resolved !== this.formData) {
        this.formData = resolved;
        this.processFormDataForEditing();
 
        // Run computed fields for all dependencies that may have changed
        const form = config.form;
        if (form) {
          Object.entries(form).forEach(([fieldName, fieldConfig]) => {
            if (fieldConfig.dependsOn && fieldConfig.computeValue) {
              const computedValue = fieldConfig.computeValue(
                this.formData,
                this.formData[fieldName],
                this.originalFormData
              );
              this.formData = {
                ...this.formData,
                [fieldName]: computedValue
              };
            }
          });
        }
 
        this.requestUpdate();
      }
    } catch (error) {
      // Resolve failures are non-fatal; form still works with initial data
    }
  }
 
  private processFormDataForEditing(): void {
    const processed = { ...this.formData };
 
    // Convert Record objects to key-value arrays for key-value editors
    Object.keys(processed).forEach((key) => {
      const value = processed[key];
      if (value && typeof value === 'object' && !Array.isArray(value)) {
        // Check if this field should be a key-value editor
        const isKeyValueField = this.isKeyValueField(key);
        if (isKeyValueField) {
          // Convert Record to array format
          processed[key] = Object.entries(value).map(([k, v]) => ({
            key: k,
            value: v
          }));
        }
      }
    });
 
    // Convert select fields to array format
    const config = this.getConfig();
    if (config?.form) {
      this.processSelectFields(processed, config.form);
    }
 
    this.formData = processed;
  }
 
  private processSelectFields(data: any, formConfig: any): void {
    Object.entries(formConfig).forEach(
      ([fieldName, fieldConfig]: [string, any]) => {
        const value = data[fieldName];
 
        // Handle top-level select fields
        if (fieldConfig.type === 'select' && value) {
          data[fieldName] = this.convertToSelectArray(value);
        }

        // Handle select fields within array items
        if (
          fieldConfig.type === 'array' &&
          Array.isArray(value) &&
          fieldConfig.itemConfig
        ) {
          value.forEach((item: any) => {
            this.processSelectFields(item, fieldConfig.itemConfig);
          });
        }
      }
    );
  }

  private convertToSelectArray(value: any): any[] {
    if (Array.isArray(value)) {
      return value.map((v) =>
        typeof v === 'string' ? { name: v, value: v } : v
      );
    } else if (typeof value === 'string') {
      return [{ name: value, value: value }];
    } else {
      return [value];
    }
  }

  private isKeyValueField(fieldName: string): boolean {
    // Check if this field is configured as a key-value type
    const config = this.getConfig();
    const fields = config?.form;
    return fields?.[fieldName]?.type === 'key-value';
  }
 
  private getConfig(): ActionConfig | NodeConfig | null {
    // If we have a node and nodeUI, check if we should use node config
    if (this.node && this.nodeUI) {
      const nodeConfig = this.getNodeConfig();
 
      // Temporary: terminal nodes defer to action configs for editing, same as execute_actions
      // For execute_actions/terminal nodes, defer to action editing if an action is selected
      if (
        (this.nodeUI.type === 'execute_actions' ||
          this.nodeUI.type === ('terminal' as any)) &&
        this.action
      ) {
        return ACTION_CONFIG[this.action.type] || null;
      }
 
      // For all other nodes with a config, use the node config
      if (nodeConfig) {
        return nodeConfig;
      }
    }

    // Fall back to action config if no node config or for pure action editing
    if (this.action) {
      return ACTION_CONFIG[this.action.type] || null;
    }
 
    return null;
  }
 
  private getNodeConfig(): NodeConfig | null {
    if (!this.nodeUI) return null;
    // Get node config based on the nodeUI's type
    return this.nodeUI.type ? NODE_CONFIG[this.nodeUI.type] : null;
  }
 
  private getHeaderColor(): string {
    const config = this.getConfig();
    return config?.group
      ? ACTION_GROUP_METADATA[config.group]?.color ||
          SPLIT_GROUP_METADATA[config.group]?.color
      : '#aaaaaa';
  }
 
  private handleDialogButtonClick(event: CustomEvent): void {
    const button = event.detail.button;
 
    if (button.name === 'Save') {
      this.handleSave();
    } else if (button.name === 'Cancel') {
      this.handleCancel();
    }
  }
 
  private handleSave(): void {
    // Process form data first
    const processedFormData = this.processFormDataForSave();
 
    // Skip validation if we're in localization mode
    // (localization only deals with translating text, not changing structure)
    if (!this.isTranslating) {
      // Validate the form
      const validation = this.validateForm();
      if (!validation.valid) {
        this.errors = validation.errors;
 
        // Expand any groups that contain validation errors
        this.expandGroupsWithErrors(validation.errors);
 
        return;
      }
    }
 
    // Check if we're in localization mode
    if (this.isTranslating) {
      // Handle action localization
      if (this.action) {
        const actionConfig = ACTION_CONFIG[this.action.type];
 
        const actionFromLocalization = actionConfig
          ? resolveFromLocalizationFormData(actionConfig)
          : undefined;
        if (actionFromLocalization) {
          // Save to localization structure
          const localizationData = actionFromLocalization(
            processedFormData,
            this.action
          );
 
          // Update the flow definition's localization
          this.updateLocalization(
            this.languageCode,
            this.action.uuid,
            localizationData
          );
 
          // Close the dialog
          this.fireCustomEvent(CustomEventType.NodeEditCancelled, {});
          return;
        }
      }
 
      // Handle node localization (for router categories and rules)
      if (this.node) {
        const nodeConfig = this.getNodeConfig();
 
        const nodeFromLocalization = nodeConfig
          ? resolveFromLocalizationFormData(nodeConfig)
          : undefined;
        if (nodeConfig?.localizable === 'categories' && nodeFromLocalization) {
          const localizationData = nodeFromLocalization(
            processedFormData,
            this.node
          );
 
          const languageLocalization =
            this.flowDefinition?.localization?.[this.languageCode] || {};
 
          // Save category localizations
          const categories = getTranslatableCategoriesForNode(
            this.nodeUI?.type,
            this.node?.router?.categories
          );
 
          categories.forEach((category) => {
            const categoryUuid = category.uuid;
            const nextLocalization = localizationData[categoryUuid];
 
            if (nextLocalization) {
              this.updateLocalization(
                this.languageCode,
                categoryUuid,
                nextLocalization
              );
            } else if (languageLocalization[categoryUuid]) {
              this.updateLocalization(this.languageCode, categoryUuid, {});
            }
          });

          // Save rule localizations
          const cases = this.node.router?.cases || [];
          cases.forEach((c) => {
            const nextLocalization = localizationData[c.uuid];
            if (nextLocalization) {
              this.updateLocalization(
                this.languageCode,
                c.uuid,
                nextLocalization
              );
            } else if (languageLocalization[c.uuid]) {
              this.updateLocalization(this.languageCode, c.uuid, {});
            }
          });

          // Close the dialog
          this.fireCustomEvent(CustomEventType.NodeEditCancelled, {});
          return;
        }
      }
    }

    // Determine whether to use node or action saving based on context
    // If we have a node with a router, always use node saving (even if action is set)
    // because router configuration is handled at the node level
    if (this.node && this.node.router) {
      // Node editing mode with router - use formDataToNode
      const updatedNode = this.formDataToNode(processedFormData);
 
      // Eagerly update flowInfo results so subsequent node creation
      // sees the new result name before the server round-trip
      this.updateFlowInfoResult(updatedNode);
 
      // Generate UI config if the node config provides a toUIConfig function
      const nodeConfig = this.getNodeConfig();
      const uiConfig = nodeConfig?.toUIConfig
        ? nodeConfig.toUIConfig(processedFormData)
        : undefined;
 
      this.fireCustomEvent(CustomEventType.NodeSaved, {
        node: updatedNode,
        uiConfig
      });
    } else if (this.action) {
      // Pure action editing mode (no router)
      const updatedAction = this.formDataToAction(processedFormData);
      this.fireCustomEvent(CustomEventType.ActionSaved, {
        action: updatedAction
      });
    } else if (this.node) {
      // Node editing mode without router
      const updatedNode = this.formDataToNode(processedFormData);
 
      // Generate UI config if the node config provides a toUIConfig function
      const nodeConfig = this.getNodeConfig();
      const uiConfig = nodeConfig?.toUIConfig
        ? nodeConfig.toUIConfig(processedFormData)
        : undefined;
 
      this.fireCustomEvent(CustomEventType.NodeSaved, {
        node: updatedNode,
        uiConfig
      });
    }
  }
 
  // Updates flowInfo.results eagerly so that new nodes created before the
  // server responds with updated info will see the result name and avoid
  // generating a duplicate default name.
  private updateFlowInfoResult(node: Node): void {
    if (!this.flowInfo?.results) return;
 
    const state = zustand.getState();
 
    // Remove any existing entry for this node
    const filtered = this.flowInfo.results.filter(
      (r) => !r.node_uuids.includes(node.uuid)
    );
 
    // Add new entry only if result_name is set
    const resultName = node.router?.result_name;
    if (resultName) {
      const categories = (node.router?.categories || []).map((c) => c.name);
      filtered.push({
        key: resultName.toLowerCase().replace(/\s+/g, '_'),
        name: resultName,
        categories,
        node_uuids: [node.uuid]
      });
    }

    state.setFlowInfo({ ...this.flowInfo, results: filtered });
  }

  private updateLocalization(
    languageCode: string,
    actionUuid: string,
    localizationData: Record<string, any>
  ): void {
    // Use the store method to properly update localization with immer
    zustand
      .getState()
      .updateLocalization(languageCode, actionUuid, localizationData);
  }
 
  private processFormDataForSave(): FormData {
    const processed = { ...this.formData };
 
    // Convert key-value arrays to Records
    Object.keys(processed).forEach((key) => {
      const value = processed[key];
      if (
        Array.isArray(value) &&
        value.length > 0 &&
        typeof value[0] === 'object' &&
        'key' in value[0] &&
        'value' in value[0]
      ) {
        // This is a key-value array, convert to Record
        const record: Record<string, string> = {};
        value.forEach(({ key: k, value: v }) => {
          if (k.trim() !== '' || v.trim() !== '') {
            record[k] = v;
          }
        });
        processed[key] = record;
      } else if (Array.isArray(value) && value.length === 0) {
        // Empty key-value array should become empty object
        const isKeyValueField = this.isKeyValueField(key);
        if (isKeyValueField) {
          processed[key] = {};
        }
      }
    });
 
    return processed;
  }

  private handleCancel(): void {
    this.fireCustomEvent(CustomEventType.NodeEditCancelled, {});
  }

  private validateForm(): ValidationResult {
    const errors: { [key: string]: string } = {};
    const config = this.getConfig();

    if (config) {
      // Check if new field configuration system is available
      if (config.form) {
        Object.entries(config.form).forEach(([fieldName, fieldConfig]) => {
          const value = this.formData[fieldName];
          if (fieldConfig.type === 'select' && fieldConfig.allowCreate) {
            // check our values to see if any have arbitrary set
            let selected = this.formData[fieldName];
            selected = Array.isArray(selected)
              ? selected.find((v: any) => v.arbitrary)
              : null;
 
            if (selected && selected.arbitrary) {
              errors[fieldName] =
                'There was an error creating' + ' "' + selected.name + '"';
            }
          }

          // Check required fields (skip in localization mode since all fields are optional)
          if (
            !this.isTranslating &&
            (fieldConfig as any).required &&
            (!value || (Array.isArray(value) && value.length === 0))
          ) {
            errors[fieldName] = `${
              (fieldConfig as any).label || fieldName
            } is required.`;
          }
 
          // Check minLength for text fields
          if (
            typeof value === 'string' &&
            (fieldConfig as any).minLength &&
            value.length < (fieldConfig as any).minLength
          ) {
            errors[fieldName] = `${
              (fieldConfig as any).label || fieldName
            } must be at least ${(fieldConfig as any).minLength} characters`;
          }

          // Check maxLength for text fields
          if (
            typeof value === 'string' &&
            (fieldConfig as any).maxLength &&
            value.length > (fieldConfig as any).maxLength
          ) {
            errors[fieldName] = `${
              (fieldConfig as any).label || fieldName
            } must be no more than ${
              (fieldConfig as any).maxLength
            } characters`;
          }
        });
      }
 
      // Universal validation for category arrays to check for reserved names
      this.validateCategoryNames(errors);
 
      // Run custom validation if available
      if (config.validate) {
        if (config.sanitize) {
          config.sanitize(this.formData);
        }
 
        let customValidation;
        if (this.action) {
          customValidation = config.validate({
            ...this.action,
            ...this.formData
          });
        } else {
          customValidation = config.validate(this.formData);
        }
        Object.assign(errors, customValidation.errors);
      }
    }

    // Validate key-value fields for unique keys
    this.validateKeyValueUniqueness(errors);
 
    return {
      valid: Object.keys(errors).length === 0,
      errors
    };
  }
 
  private validateKeyValueUniqueness(errors: { [key: string]: string }): void {
    // The individual key-value editors will show validation errors on duplicate keys and empty keys with values
    // We just need to prevent form submission when there are validation issues
    Object.entries(this.formData).forEach(([fieldName, value]) => {
      if (
        Array.isArray(value) &&
        value.length > 0 &&
        typeof value[0] === 'object' &&
        'key' in value[0] &&
        'value' in value[0]
      ) {
        // This is a key-value array
        let hasValidationErrors = false;
 
        // Check for empty keys with values
        value.forEach(({ key, value: itemValue }: any) => {
          if (key.trim() === '' && itemValue.trim() !== '') {
            hasValidationErrors = true;
          }
        });
 
        // Check for duplicate keys (only non-empty ones)
        const keys = value
          .filter(({ key }: any) => key.trim() !== '') // Only check non-empty keys
          .map(({ key }: any) => key.trim());

        const uniqueKeys = new Set(keys);

        if (keys.length !== uniqueKeys.size) {
          hasValidationErrors = true;
        }

        if (hasValidationErrors) {
          errors[fieldName] = `Please resolve validation errors to continue`;
        }
      }
    });
  }

  private validateCategoryNames(errors: { [key: string]: string }): void {
    Object.assign(errors, collectReservedCategoryErrors(this.formData));
  }
 
  private formDataToNode(formData: FormData = this.formData): Node {
    if (!this.node) throw new Error('No node to update');
    let updatedNode: Node = { ...this.node };
 
    // Check if node config has fromFormData - if so, it handles the entire transformation
    const nodeConfig = this.getNodeConfig();
    const nodeHasFromFormData = nodeConfig?.fromFormData !== undefined;

    // Handle actions using action config transformations if available
    // Skip this if the node has its own fromFormData (which handles actions itself)
    if (
      !nodeHasFromFormData &&
      this.node.actions &&
      this.node.actions.length > 0
    ) {
      updatedNode.actions = this.node.actions.map((action) => {
        // If we're editing a specific action, only transform that one
        if (this.action && action.uuid === this.action.uuid) {
          const actionConfig = ACTION_CONFIG[action.type];
          if (actionConfig?.fromFormData) {
            // Use action-specific form data transformation
            return actionConfig.fromFormData(formData);
          } else {
            // Default transformation - merge form data with original action
            return { ...action, ...formData };
          }
        } else {
          // Keep other actions unchanged
          return action;
        }
      });
    }
 
    // Handle router configuration using node config
    if (nodeHasFromFormData) {
      // Use node-specific form data transformation
      // When a node has fromFormData, it's responsible for creating the entire
      // node structure including actions and router (regardless of whether router exists yet)
      updatedNode = nodeConfig.fromFormData!(formData, updatedNode);
    } else if (this.node.router) {
      // Default router handling when no nodeConfig.fromFormData
      updatedNode.router = { ...this.node.router };
 
      // Apply form data to router fields if they exist
      if (formData.result_name !== undefined) {
        updatedNode.router.result_name = formData.result_name;
      }
 
      // Handle preconfigured rules from node config
      if (nodeConfig?.router?.rules) {
        // Build a complete new set of categories and exits based on node config
        const existingCategories = updatedNode.router.categories || [];
        const existingExits = updatedNode.exits || [];
 
        const newCategories: any[] = [];
        const newExits: any[] = [];
 
        // Group rules by category name to handle multiple rules pointing to the same category
        const categoryNameToRules = new Map<
          string,
          typeof nodeConfig.router.rules
        >();
        nodeConfig.router.rules.forEach((rule) => {
          if (!categoryNameToRules.has(rule.categoryName)) {
            categoryNameToRules.set(rule.categoryName, []);
          }
          categoryNameToRules.get(rule.categoryName)!.push(rule);
        });

        // Create categories for all unique category names
        categoryNameToRules.forEach((rules, categoryName) => {
          // Check if category already exists to preserve its UUID and exit_uuid
          const existingCategory = existingCategories.find(
            (cat) => cat.name === categoryName
          );

          if (existingCategory) {
            // Preserve existing category and its associated exit
            newCategories.push(existingCategory);
            const associatedExit = existingExits.find(
              (exit) => exit.uuid === existingCategory.exit_uuid
            );
            if (associatedExit) {
              newExits.push(associatedExit);
            }
          } else {
            // Create new category and exit
            const categoryUuid = generateUUID();
            const exitUuid = generateUUID();
 
            newCategories.push({
              uuid: categoryUuid,
              name: categoryName,
              exit_uuid: exitUuid
            });
 
            newExits.push({
              uuid: exitUuid,
              destination_uuid: null
            });
          }
        });
 
        // Add default category if specified
        if (nodeConfig.router.defaultCategory) {
          // Check if default category already exists in our new list
          const existingDefault = newCategories.find(
            (cat) => cat.name === nodeConfig.router.defaultCategory
          );

          if (!existingDefault) {
            // Check if it exists in the original categories
            const originalDefault = existingCategories.find(
              (cat) => cat.name === nodeConfig.router.defaultCategory
            );

            if (originalDefault) {
              // Preserve existing default category and its exit
              newCategories.push(originalDefault);
              const associatedExit = existingExits.find(
                (exit) => exit.uuid === originalDefault.exit_uuid
              );
              if (associatedExit) {
                newExits.push(associatedExit);
              }
            } else {
              // Create new default category and exit
              const categoryUuid = generateUUID();
              const exitUuid = generateUUID();

              newCategories.push({
                uuid: categoryUuid,
                name: nodeConfig.router.defaultCategory,
                exit_uuid: exitUuid
              });

              newExits.push({
                uuid: exitUuid,
                destination_uuid: null
              });
            }
          }
        }

        // Replace the entire categories and exits lists with our complete new sets
        updatedNode.router.categories = newCategories;
        updatedNode.exits = newExits;
      }
    } else {
      // If no router, just apply form data to node properties
      Object.keys(formData).forEach((key) => {
        if (
          key !== 'uuid' &&
          key !== 'actions' &&
          key !== 'exits' &&
          key !== 'router'
        ) {
          (updatedNode as any)[key] = formData[key];
        }
      });
    }

    return updatedNode;
  }

  private formDataToAction(formData: FormData = this.formData): Action {
    if (!this.action) throw new Error('No action to update');

    // Use action config transformation if available
    const actionConfig = ACTION_CONFIG[this.action.type];
    if (actionConfig?.fromFormData) {
      return actionConfig.fromFormData(formData);
    } else {
      // Default 1:1 mapping
      return { ...this.action, ...formData };
    }
  }

  private handleFormFieldChange(propertyName: string, event: Event): void {
    const target = event.target as any;
    let value: any;

    // Handle different component types like ActionEditor does
    if (target.tagName === 'TEMBA-CHECKBOX') {
      value = target.checked;
    } else if (target.values !== undefined) {
      value = target.values;
    } else {
      value = target.value;
    }

    this.formData = {
      ...this.formData,
      [propertyName]: value
    };

    // Clear any existing error for this field
    if (this.errors[propertyName]) {
      const newErrors = { ...this.errors };
      delete newErrors[propertyName];
      this.errors = newErrors;
    }

    // Check for computed values in dependent fields
    this.updateComputedFields(propertyName);

    // Re-evaluate group collapse states that depend on form data
    this.updateGroupCollapseStates();

    // Trigger re-render to handle conditional field visibility
    this.requestUpdate();
  }

  private updateGroupCollapseStates(): void {
    const config = this.getConfig();
    if (!config?.layout) return;

    this.updateGroupCollapseStatesRecursive(config.layout);
  }

  private updateGroupCollapseStatesRecursive(items: LayoutItem[]): void {
    items.forEach((item) => {
      if (typeof item === 'object' && item.type === 'group') {
        const { label, collapsed, collapsible } = item;

        // Only update if the group is collapsible and has a function-based collapsed property
        // Skip reveal groups that have been expanded — they are one-way
        if (collapsible && typeof collapsed === 'function') {
          if (item.reveal && this.groupCollapseState[label] === false) {
            // Reveal group was manually expanded — don't re-collapse
          } else {
            const newCollapsedState = collapsed(this.formData);

            // Only update if the state has changed to avoid unnecessary re-renders
            if (this.groupCollapseState[label] !== newCollapsedState) {
              this.groupCollapseState = {
                ...this.groupCollapseState,
                [label]: newCollapsedState
              };
            }
          }
        }

        // Recursively check nested items
        this.updateGroupCollapseStatesRecursive(item.items);
      } else if (typeof item === 'object' && item.type === 'row') {
        // Recursively check items in rows
        this.updateGroupCollapseStatesRecursive(item.items);
      } else if (typeof item === 'object' && item.type === 'accordion') {
        // Accordion sections use their collapsed function only for initial state;
        // after that, user toggles control them.
        item.sections.forEach((section) => {
          this.updateGroupCollapseStatesRecursive(section.items);
        });
      }
    });
  }

  private updateComputedFields(changedFieldName: string): void {
    const config = this.getConfig();
    if (!config?.form) return;

    // Check all fields to see if any depend on the changed field
    Object.entries(config.form).forEach(([fieldName, fieldConfig]) => {
      if (fieldConfig.dependsOn?.includes(changedFieldName)) {
        if (fieldConfig.computeValue) {
          const currentValue = this.formData[fieldName];
 
          const computedValue = fieldConfig.computeValue(
            this.formData,
            currentValue,
            this.originalFormData
          );

          // Update the form data with the computed value
          this.formData = {
            ...this.formData,
            [fieldName]: computedValue
          };
        }
      }
    });
  }

  /**
   * Helper method to check if a field is visible based on its conditions
   */
  private isFieldVisible(fieldName: string, config: FieldConfig): boolean {
    if (config.conditions?.visible) {
      try {
        return config.conditions.visible(this.formData);
      } catch (error) {
        console.error(`Error checking visibility for ${fieldName}:`, error);
        // If there's an error, show the field by default
        return true;
      }
    }
    return true;
  }

  private renderNewField(
    fieldName: string,
    config: FieldConfig,
    value: any
  ): TemplateResult {
    // Check visibility condition
    if (!this.isFieldVisible(fieldName, config)) {
      return html``;
    }

    const errors = this.errors[fieldName] ? [this.errors[fieldName]] : [];
 
    // Build container style with maxWidth if specified
    const containerStyle = config.maxWidth
      ? `max-width: ${config.maxWidth};`
      : '';
 
    // Render original value if in localization mode and action has the field
    const originalValueDisplay =
      this.isTranslating && this.action && fieldName in this.action
        ? this.renderOriginalValue(fieldName, this.action[fieldName])
        : html``;
 
    const fieldContent = this.renderFieldContent(
      fieldName,
      config,
      value,
      errors
    );

    const content = html` ${originalValueDisplay} ${fieldContent} `;

    // Wrap in container with style if maxWidth is specified
    if (containerStyle) {
      return html`<div style="${containerStyle}">${content}</div>`;
    }

    return content;
  }

  private renderOptionalField(
    fieldName: string,
    config: FieldConfig,
    value: any
  ): TemplateResult {
    // If the field has a value or has been revealed, show it
    const hasValue = value && value.toString().trim() !== '';
    const isRevealed = this.revealedOptionalFields.has(fieldName);

    if (hasValue || isRevealed) {
      // Render the field normally
      return this.renderNewField(fieldName, config, value);
    }

    // Show the "Save as..." link
    return html`
      <div class="optional-field-link">
        <a
          @click="${(e: Event) => {
            e.preventDefault();
            this.revealOptionalField(fieldName);
          }}"
        >
          ${config.optionalLink}
        </a>
      </div>
    `;
  }
 
  private revealOptionalField(fieldName: string): void {
    this.revealedOptionalFields = new Set([
      ...this.revealedOptionalFields,
      fieldName
    ]);
  }

  private renderLocalizationTable(): TemplateResult {
    const rules = this.formData.rules || {};
    const ruleEntries = Object.entries(rules);
    const categories = this.formData.categories || {};
    const categoryEntries = Object.entries(categories);

    if (ruleEntries.length === 0 && categoryEntries.length === 0) {
      return html`<div>No content to localize</div>`;
    }

    return html`
      <div class="category-localization-table">
        ${ruleEntries.length > 0
          ? html`
              <div class="localization-section-label">Rules</div>
              ${ruleEntries.map(
                ([caseUuid, ruleData]: [string, any]) => html`
                  ${(ruleData.originalArguments || []).map(
                    (arg: string, i: number) =>
                      arg
                        ? html`
                            <div class="category-localization-row">
                              <div class="original-name">
                                <span class="rule-operator"
                                  >${ruleData.operatorName}</span
                                >
                                <span>${arg}</span>
                              </div>
                              <div class="localized-name">
                                <temba-textinput
                                  name="rule-${caseUuid}-${i}"
                                  placeholder=""
                                  value="${ruleData.localizedArguments?.[i] ||
                                  ''}"
                                  @change=${(e: Event) =>
                                    this.handleRuleLocalizationChange(
                                      caseUuid,
                                      i,
                                      (e.target as any).value
                                    )}
                                ></temba-textinput>
                              </div>
                            </div>
                          `
                        : ''
                  )}
                `
              )}
            `
          : ''}
        ${categoryEntries.length > 0
          ? html`
              <div class="localization-section-label">Categories</div>
              ${categoryEntries.map(
                ([categoryUuid, categoryData]: [string, any]) => html`
                  <div class="category-localization-row">
                    <div class="original-name">
                      ${categoryData.originalName}
                    </div>
                    <div class="localized-name">
                      <temba-textinput
                        name="${categoryUuid}"
                        placeholder=""
                        value="${categoryData.localizedName || ''}"
                        @change=${(e: Event) =>
                          this.handleCategoryLocalizationChange(
                            categoryUuid,
                            (e.target as any).value
                          )}
                      ></temba-textinput>
                    </div>
                  </div>
                `
              )}
            `
          : ''}
      </div>
    `;
  }

  private handleCategoryLocalizationChange(
    categoryUuid: string,
    value: string
  ): void {
    if (!this.formData.categories) {
      this.formData.categories = {};
    }
    if (!this.formData.categories[categoryUuid]) {
      this.formData.categories[categoryUuid] = {};
    }
    this.formData.categories[categoryUuid].localizedName = value;
    this.requestUpdate();
  }
 
  private handleRuleLocalizationChange(
    caseUuid: string,
    argIndex: number,
    value: string
  ): void {
    if (!this.formData.rules) {
      this.formData.rules = {};
    }
    if (!this.formData.rules[caseUuid]) {
      this.formData.rules[caseUuid] = {
        originalArguments: [],
        localizedArguments: []
      };
    }
    if (!this.formData.rules[caseUuid].localizedArguments) {
      this.formData.rules[caseUuid].localizedArguments = [];
    }
    this.formData.rules[caseUuid].localizedArguments[argIndex] = value;
    this.requestUpdate();
  }

  private renderOriginalValue(
    fieldName: string,
    originalValue: any
  ): TemplateResult {
    // Format the original value for display
    let displayValue = '';

    if (Array.isArray(originalValue)) {
      if (originalValue.length === 0) {
        return html``; // Don't show anything for empty arrays
      }
      // For arrays, join with commas
      displayValue = originalValue.join(', ');
    } else if (typeof originalValue === 'string') {
      displayValue = originalValue;
    } else if (originalValue) {
      displayValue = String(originalValue);
    }

    // Don't show if empty
    if (!displayValue || displayValue.trim() === '') {
      return html``;
    }

    return html`
      <div class="original-value">
        <div class="original-value-content">${displayValue}</div>
      </div>
    `;
  }

  private renderFieldContent(
    fieldName: string,
    config: FieldConfig,
    value: any,
    errors: string[]
  ): TemplateResult {
    // In localization mode, make all fields optional (not required)
    const fieldConfig = this.isTranslating
      ? { ...config, required: false }
      : config;

    // Use FieldRenderer for consistent field rendering
    return FieldRenderer.renderField(fieldName, fieldConfig, value, {
      errors,
      onChange: (e: Event) => {
        // Handle different change event types
        if (fieldName && config.type === 'key-value') {
          // Special handling for key-value editor
          const customEvent = e as CustomEvent;
          if (customEvent.detail) {
            this.handleNewFieldChange(fieldName, customEvent.detail.value);
          }
        } else if (fieldName && config.type === 'array') {
          // Special handling for array editor
          this.handleNewFieldChange(fieldName, (e.target as any).value);
        } else if (fieldName && config.type === 'message-editor') {
          // Special handling for message editor
          this.handleMessageEditorChange(fieldName, e);
        } else if (fieldName && config.type === 'media') {
          // Extract URL from media picker's attachment
          const picker = e.target as any;
          const url = picker.attachments?.[0]?.url || '';
          this.handleNewFieldChange(fieldName, url);
        } else if (fieldName && config.type === 'template-editor') {
          // Special handling for template editor (manages template + template_variables)
          this.handleTemplateEditorChange(fieldName, e);
        } else {
          // Default handling for most field types
          this.handleFormFieldChange(fieldName, e);
        }
      },
      showLabel: true,
      formData: this.formData,
      additionalData: {
        attachments: this.formData.attachments || [],
        template_variables: this.formData.template_variables || []
      }
    });
  }
 
  private handleGroupToggle(groupLabel: string): void {
    this.groupCollapseState = {
      ...this.groupCollapseState,
      [groupLabel]: !this.groupCollapseState[groupLabel]
    };
  }
 
  private handleGroupMouseEnter(groupLabel: string): void {
    this.groupHoverState = {
      ...this.groupHoverState,
      [groupLabel]: true
    };
  }
 
  private handleGroupMouseLeave(groupLabel: string): void {
    this.groupHoverState = {
      ...this.groupHoverState,
      [groupLabel]: false
    };
  }
 
  private expandGroupsWithErrors(errors: { [key: string]: string }): void {
    const config = this.getConfig();
    if (!config?.layout) return;
 
    const errorFields = new Set(Object.keys(errors));
    this.expandGroupsWithErrorsRecursive(config.layout, errorFields);
  }

  private expandGroupsWithErrorsRecursive(
    items: LayoutItem[],
    errorFields: Set<string>
  ): void {
    items.forEach((item) => {
      if (typeof item === 'object' && item.type === 'group') {
        const fieldsInGroup = this.collectFieldsFromItems(item.items);
        const groupHasErrors = fieldsInGroup.some((fieldName) =>
          errorFields.has(fieldName)
        );

        if (groupHasErrors) {
          // Expand this group
          this.groupCollapseState = {
            ...this.groupCollapseState,
            [item.label]: false
          };
        }
 
        // Recursively check nested items
        this.expandGroupsWithErrorsRecursive(item.items, errorFields);
      } else if (typeof item === 'object' && item.type === 'row') {
        // Recursively check items in rows
        this.expandGroupsWithErrorsRecursive(item.items, errorFields);
      } else if (typeof item === 'object' && item.type === 'accordion') {
        // Check each accordion section for errors
        item.sections.forEach((section) => {
          const fieldsInSection = this.collectFieldsFromItems(section.items);
          const sectionHasErrors = fieldsInSection.some((fieldName) =>
            errorFields.has(fieldName)
          );
          if (sectionHasErrors) {
            this.groupCollapseState = {
              ...this.groupCollapseState,
              [`accordion:${section.label}`]: false
            };
          }
          this.expandGroupsWithErrorsRecursive(section.items, errorFields);
        });
      }
    });
  }
 
  private renderLayoutItem(
    item: LayoutItem,
    config: ActionConfig | NodeConfig,
    renderedFields: Set<string>
  ): TemplateResult {
    if (typeof item === 'string') {
      // String shorthand for field
      return this.renderLayoutItem(
        { type: 'field', field: item },
        config,
        renderedFields
      );
    }

    switch (item.type) {
      case 'field':
        // In translation mode, skip fields not in the localizable list
        if (
          this.isTranslating &&
          Array.isArray((config as ActionConfig).localizable) &&
          !(config as ActionConfig).localizable!.includes(item.field)
        ) {
          renderedFields.add(item.field);
          return html``;
        }
        if (config.form![item.field] && !renderedFields.has(item.field)) {
          renderedFields.add(item.field);
          const fieldConfig = config.form![item.field] as FieldConfig;
 
          // Handle optional link fields
          if (fieldConfig.optionalLink) {
            return this.renderOptionalField(
              item.field,
              fieldConfig,
              this.formData[item.field]
            );
          }
 
          return this.renderNewField(
            item.field,
            fieldConfig,
            this.formData[item.field]
          );
        }
        return html``;

      case 'row':
        return this.renderRow(item, config, renderedFields);
 
      case 'group':
        return this.renderGroup(item, config, renderedFields);
 
      case 'accordion':
        return this.renderAccordion(item, config, renderedFields);
 
      case 'spacer':
        return html``;

      case 'text':
        return html`<div class="form-text">${item.text}</div>`;

      default:
        return html``;
    }
  }

  private renderRow(
    rowConfig: RowLayoutConfig,
    config: ActionConfig | NodeConfig,
    renderedFields: Set<string>
  ): TemplateResult {
    const {
      items,
      gap = '1rem',
      label,
      helpText,
      inlineLabels,
      marginBottom
    } = rowConfig;

    // Collect all fields from this row for width calculations
    const fieldsInRow = this.collectFieldsFromItems(items);
    const validFields = fieldsInRow.filter(
      (fieldName) => config.form?.[fieldName]
    );

    // Filter for visible fields only to handle conditional visibility
    const visibleFields = validFields.filter((fieldName) => {
      const fieldConfig = config.form![fieldName];
      return this.isFieldVisible(fieldName, fieldConfig);
    });

    if (visibleFields.length === 0) {
      return html``;
    }

    // Build a map of field flex styles
    // Fields with maxWidth get flex: 0 0 {maxWidth} (fixed)
    // Fields without maxWidth get flex: 1 1 0 (grow to fill space)
    const fieldFlexStyles = new Map<string, string>();
    visibleFields.forEach((fieldName) => {
      const fieldConfig = config.form![fieldName];
      if (fieldConfig.maxWidth) {
        // Fixed width field: no grow, no shrink, basis = maxWidth
        fieldFlexStyles.set(fieldName, `flex: 0 0 ${fieldConfig.maxWidth};`);
      } else {
        // Flexible field: grow to fill remaining space
        fieldFlexStyles.set(fieldName, `flex: 1 1 0;`);
      }
    });

    const rowContent = html`
      <div
        class="form-row"
        style="display: flex; gap: ${gap};${marginBottom
          ? ` margin-bottom: ${marginBottom};`
          : ''}"
      >
        ${items.map((item) => {
          // Spacer items render as empty flex children
          if (typeof item !== 'string' && item.type === 'spacer') {
            return html`<div style="flex: 1 1 0;"></div>`;
          }

          // Get the field name from the item
          const fieldName =
            typeof item === 'string'
              ? item
              : item.type === 'field'
                ? item.field
                : null;

          // Get flex style for this field if it's a visible field
          const flexStyle =
            fieldName && fieldFlexStyles.has(fieldName)
              ? fieldFlexStyles.get(fieldName)
              : '';

          const itemContent = this.renderLayoutItem(
            item,
            config,
            renderedFields
          );

          // When inlineLabels is provided, render the label inline to the left
          const inlineLabel =
            inlineLabels && fieldName ? inlineLabels[fieldName] : null;

          // Wrap in a div with flex style if we have a flex style
          if (flexStyle) {
            // Evaluated fields use temba-rich-edit which needs min-width: 0
            // on its flex item wrapper to prevent overflow in flex rows
            const fieldConfig = fieldName ? config.form?.[fieldName] : null;
            const minWidth = fieldConfig?.evaluated ? ' min-width: 0;' : '';
            return inlineLabel
              ? html`<div
                  style="${flexStyle} display: flex; align-items: center; gap: 0.35rem;"
                >
                  <span class="form-row-inline-label">${inlineLabel}</span>
                  <div style="flex: 1 1 0; min-width: 0;">${itemContent}</div>
                </div>`
              : html`<div style="${flexStyle}${minWidth}">${itemContent}</div>`;
          }
          return itemContent;
        })}
      </div>
    `;
 
    // If no label or helpText, return just the row content
    if (!label && !helpText) {
      return rowContent;
    }
 
    // Otherwise, wrap with label on top, content, then helpText below (matching field pattern)
    return html`
      <div class="form-row-wrapper">
        ${label ? html`<label class="form-row-label">${label}</label>` : ''}
        ${rowContent}
        ${helpText
          ? html`<div class="form-row-help">
              ${renderMarkdownInline(helpText)}
            </div>`
          : ''}
      </div>
    `;
  }
 
  private renderGroup(
    groupConfig: GroupLayoutConfig,
    config: ActionConfig | NodeConfig,
    renderedFields: Set<string>
  ): TemplateResult {
    const {
      label,
      items,
      collapsible = false,
      collapsed = false,
      helpText,
      icon,
      contentPadding,
      gap,
      bordered = true,
      reveal = false,
      getGroupValueCount
    } = groupConfig;

    // Initialize collapse state if not set
    if (collapsible && !(label in this.groupCollapseState)) {
      // Evaluate collapsed property - can be boolean or function
      const initialCollapsed =
        typeof collapsed === 'function' ? collapsed(this.formData) : collapsed;

      this.groupCollapseState = {
        ...this.groupCollapseState,
        [label]: initialCollapsed
      };
    }

    const isCollapsed = collapsible
      ? (this.groupCollapseState[label] ??
        (typeof collapsed === 'function'
          ? collapsed(this.formData)
          : collapsed))
      : false;
 
    // Reveal mode: once expanded, render items directly without any group wrapper
    if (reveal && !isCollapsed) {
      return html`${items.map((item) =>
        this.renderLayoutItem(item, config, renderedFields)
      )}`;
    }
 
    // Check if any field in this group has errors
    const fieldsInGroup = this.collectFieldsFromItems(items);
    const groupHasErrors = fieldsInGroup.some(
      (fieldName) => this.errors[fieldName]
    );
 
    // Calculate count for bubble display
    let valueCount = 0;
    let showBubble = false;
    let showCheckmark = false;
    let hasValue = false;
    const isHovered = this.groupHoverState[label] ?? false;
 
    if (getGroupValueCount && collapsible) {
      try {
        const result = getGroupValueCount(this.formData);
 
        if (typeof result === 'boolean') {
          // Boolean result - show checkmark when true
          showCheckmark = result && isCollapsed && !isHovered;
          hasValue = result;
        } else if (typeof result === 'number') {
          // Numeric result - show count bubble
          valueCount = result;
          showBubble = valueCount > 0 && isCollapsed && !isHovered;
          hasValue = valueCount > 0;
        }
      } catch (error) {
        console.error(
          `Error calculating group value count for ${label}:`,
          error
        );
      }
    }
 
    return html`
      <div
        class="form-group ${collapsible ? 'collapsible' : ''} ${groupHasErrors
          ? 'has-errors'
          : ''} ${isCollapsed ? 'collapsed' : 'expanded'} ${hasValue
          ? 'has-bubble'
          : ''} ${!bordered ? 'no-border' : ''}"
      >
        <div
          class="form-group-header ${collapsible ? 'clickable' : ''}"
          @click=${collapsible
            ? () => this.handleGroupToggle(label)
            : undefined}
          @mouseenter=${collapsible
            ? () => this.handleGroupMouseEnter(label)
            : undefined}
          @mouseleave=${collapsible
            ? () => this.handleGroupMouseLeave(label)
            : undefined}
        >
          <div class="form-group-info">
            <div class="form-group-title">
              ${icon
                ? html`<temba-icon
                    name=${icon}
                    size="1"
                    style="margin-right:6px;color:#999;"
                  ></temba-icon>`
                : ''}${label}
            </div>
            ${helpText
              ? html`<div class="form-group-help">
                  ${renderMarkdownInline(helpText)}
                </div>`
              : ''}
          </div>
          ${groupHasErrors
            ? html`<temba-icon
                name="alert_warning"
                class="group-error-icon"
                size="1.5"
              ></temba-icon>`
            : ''}
          ${collapsible && !groupHasErrors
            ? html`<div class="group-toggle-container">
                <temba-icon
                  name="arrow_right"
                  size="1.5"
                  class="group-toggle-icon ${isCollapsed
                    ? 'collapsed'
                    : 'expanded'} ${showBubble || showCheckmark ? 'faded' : ''}"
                ></temba-icon>
                ${showCheckmark
                  ? html`<temba-icon
                      name="check"
                      size="1"
                      class="group-checkmark-icon"
                    ></temba-icon>`
                  : showBubble
                    ? html`<div
                        class="group-count-bubble ${!showBubble
                          ? 'hidden'
                          : ''}"
                      >
                        ${valueCount}
                      </div>`
                    : ''}
              </div>`
            : ''}
        </div>
        <div
          class="form-group-content ${isCollapsed ? 'collapsed' : 'expanded'}"
          style="${[
            contentPadding ? `--group-content-padding: ${contentPadding}` : '',
            gap ? `gap: ${gap}` : ''
          ]
            .filter(Boolean)
            .join(';')}"
        >
          ${items.map((item) =>
            this.renderLayoutItem(item, config, renderedFields)
          )}
        </div>
      </div>
    `;
  }

  private renderAccordion(
    accordionConfig: AccordionLayoutConfig,
    config: ActionConfig | NodeConfig,
    renderedFields: Set<string>
  ): TemplateResult {
    const { sections, multi = false } = accordionConfig;

    // Filter out sections where all fields are invisible
    const visibleSections = sections.filter((section) => {
      const fieldsInSection = this.collectFieldsFromItems(section.items);
      if (fieldsInSection.length === 0) return true;

      // When translating, hide sections marked as not localizable
      if (this.isTranslating && section.localizable === false) {
        // Mark fields as rendered so they don't appear at top level
        fieldsInSection.forEach((f) => renderedFields.add(f));
        return false;
      }

      return fieldsInSection.some((fieldName) => {
        const fieldConfig = config.form?.[fieldName];
        return fieldConfig ? this.isFieldVisible(fieldName, fieldConfig) : true;
      });
    });

    if (visibleSections.length === 0) {
      return html``;
    }

    return html`
      <temba-accordion
        ?multi=${multi}
        @toggle=${this.handleAccordionSectionToggle}
      >
        ${visibleSections.map((section) => {
          const { label, collapsed = true, getValueCount } = section;
          const stateKey = `accordion:${label}`;

          // Initialize collapse state if not set
          if (!(stateKey in this.groupCollapseState)) {
            const initialCollapsed =
              typeof collapsed === 'function'
                ? collapsed(this.formData)
                : collapsed;
            this.groupCollapseState = {
              ...this.groupCollapseState,
              [stateKey]: initialCollapsed
            };
          }

          const isCollapsed = this.groupCollapseState[stateKey] ?? true;

          // Check for errors in this section
          const fieldsInSection = this.collectFieldsFromItems(section.items);
          const sectionHasErrors = fieldsInSection.some(
            (fieldName) => this.errors[fieldName]
          );

          // Value count / checkmark display
          let valueCount = 0;
          let isChecked = false;

          if (getValueCount) {
            try {
              const result = getValueCount(this.formData);
              if (typeof result === 'boolean') {
                isChecked = result;
              } else if (typeof result === 'number') {
                valueCount = result;
              }
            } catch (error) {
              // ignore
            }
          }

          return html`
            <temba-accordion-section
              label=${label}
              icon=${section.icon || ''}
              .count=${valueCount}
              ?checked=${isChecked}
              .collapsed=${isCollapsed}
              ?hasError=${sectionHasErrors}
            >
              ${section.items.map((item) =>
                this.renderLayoutItem(item, config, renderedFields)
              )}
            </temba-accordion-section>
          `;
        })}
      </temba-accordion>
    `;
  }

  private handleAccordionSectionToggle(evt: CustomEvent): void {
    const label = evt.detail.label;
    const collapsed = evt.detail.collapsed;
    const stateKey = `accordion:${label}`;
    this.groupCollapseState = {
      ...this.groupCollapseState,
      [stateKey]: collapsed
    };
  }

  private collectFieldsFromItems(items: LayoutItem[]): string[] {
    const fields: string[] = [];

    items.forEach((item) => {
      if (typeof item === 'string') {
        fields.push(item);
      } else if (item.type === 'field') {
        fields.push(item.field);
      } else if (item.type === 'row') {
        fields.push(...this.collectFieldsFromItems(item.items));
      } else if (item.type === 'group') {
        fields.push(...this.collectFieldsFromItems(item.items));
      } else if (item.type === 'accordion') {
        item.sections.forEach((section) => {
          fields.push(...this.collectFieldsFromItems(section.items));
        });
      }
    });

    return fields;
  }

  private renderFieldRow(
    rowConfig: RowLayoutConfig,
    config: ActionConfig | NodeConfig
  ): TemplateResult {
    // This method is deprecated - use renderRow instead
    return this.renderRow(rowConfig, config, new Set());
  }

  private renderFieldGroup(
    groupConfig: GroupLayoutConfig,
    config: ActionConfig | NodeConfig
  ): TemplateResult {
    // This method is deprecated - use renderGroup instead
    return this.renderGroup(groupConfig, config, new Set());
  }

  private handleNewFieldChange(fieldName: string, value: any) {
    this.formData = {
      ...this.formData,
      [fieldName]: value
    };

    // Clear any existing error for this field
    if (this.errors[fieldName]) {
      const newErrors = { ...this.errors };
      delete newErrors[fieldName];
      this.errors = newErrors;
    }

    // Re-evaluate group collapse states that depend on form data
    this.updateGroupCollapseStates();

    // Trigger re-render
    this.requestUpdate();
  }
  private handleTemplateEditorChange(fieldName: string, event: Event): void {
    const customEvent = event as CustomEvent;
    const detail = customEvent.detail;

    this.formData = {
      ...this.formData,
      [fieldName]: detail.template
        ? { uuid: detail.template.uuid, name: detail.template.name }
        : null,
      template_variables: detail.variables || []
    };

    this.updateGroupCollapseStates();
    this.requestUpdate();
  }

  private handleMessageEditorChange(fieldName: string, event: Event): void {
    const target = event.target as any;
 
    // Update both text and attachments from the message editor
    this.formData = {
      ...this.formData,
      [fieldName]: target.value,
      attachments: target.attachments || []
    };
 
    // Clear any existing errors for both fields
    if (this.errors[fieldName]) {
      const newErrors = { ...this.errors };
      delete newErrors[fieldName];
      delete newErrors.attachments;
      this.errors = newErrors;
    }
 
    // Trigger re-render
    this.requestUpdate();
  }
 
  private renderFields(): TemplateResult {
    const config = this.getConfig();
    if (!config) {
      return html` <div>No configuration available</div> `;
    }
 
    // Special rendering for category/rule localization
    if (
      this.isTranslating &&
      config.localizable === 'categories' &&
      (this.formData.categories || this.formData.rules)
    ) {
      return this.renderLocalizationTable();
    }
 
    // Use the new fields configuration system
    if (config.form) {
      // If layout is specified, use it
      if (config.layout) {
        const renderedFields = new Set<string>();
 
        // Also collect fields from gutter to avoid rendering them in main form
        const gutterFields = new Set<string>();
        if (config.gutter) {
          const gutterFieldNames = this.collectFieldsFromItems(config.gutter);
          gutterFieldNames.forEach((field) => gutterFields.add(field));
        }
 
        return html`
          ${config.layout.map((item) =>
            this.renderLayoutItem(item, config, renderedFields)
          )}
          ${
            /* Render any fields not explicitly placed in layout or gutter */
            Object.entries(config.form).map(([fieldName, fieldConfig]) => {
              if (
                !renderedFields.has(fieldName) &&
                !gutterFields.has(fieldName)
              ) {
                // In translation mode, skip fields not in the localizable list
                if (
                  this.isTranslating &&
                  Array.isArray((config as ActionConfig).localizable) &&
                  !(config as ActionConfig).localizable!.includes(fieldName)
                ) {
                  return html``;
                }
                return this.renderNewField(
                  fieldName,
                  fieldConfig as FieldConfig,
                  this.formData[fieldName]
                );
              }
              return html``;
            })
          }
        `;
      } else {
        // Default rendering without layout
        return html`
          ${Object.entries(config.form).map(([fieldName, fieldConfig]) => {
            // In translation mode, skip fields not in the localizable list
            if (
              this.isTranslating &&
              Array.isArray((config as ActionConfig).localizable) &&
              !(config as ActionConfig).localizable!.includes(fieldName)
            ) {
              return html``;
            }
            return this.renderNewField(
              fieldName,
              fieldConfig as FieldConfig,
              this.formData[fieldName]
            );
          })}
        `;
      }
    }
 
    // Fallback for configs without form configuration
    if (this.action) {
      return html` <div>No form configuration available for this action</div> `;
    } else {
      return html` <div>No form configuration available for this node</div> `;
    }
  }
 
  private renderGutter(): TemplateResult {
    const config = this.getConfig();
    if (!config?.gutter || config.gutter.length === 0) {
      return html``;
    }
 
    // Don't show gutter when localizing categories
    if (this.isTranslating && config.localizable === 'categories') {
      return html``;
    }
 
    // Use the same layout rendering system for gutter fields
    const renderedFields = new Set<string>();

    return html`
      <div class="gutter-fields">
        ${config.gutter.map((item) =>
          this.renderLayoutItem(item, config, renderedFields)
        )}
      </div>
    `;
  }

  private renderActionSection(): TemplateResult {
    if (!this.node || this.node.actions.length === 0) {
      return html``;
    }
 
    const nodeConfig = this.getNodeConfig();
 
    // If node has an action config, defer to ActionEditor
    if (nodeConfig?.action) {
      const action = this.node.actions[0]; // Assume single action for now
 
      return html`
        <div class="action-section">
          <h3>Action Configuration</h3>
          <div class="action-preview">
            <p><strong>Type:</strong> ${action.type}</p>
            <p><em>Action details will be editable here</em></p>
          </div>
        </div>
      `;
    }
 
    return html``;
  }

  private renderRouterSection(): TemplateResult {
    if (!this.node?.router) {
      return html``;
    }

    const nodeConfig = this.getNodeConfig();
 
    return html`
      <div class="router-section">
        <h3>Router Configuration</h3>
        ${nodeConfig?.router
          ? this.renderRouterConfig()
          : html`<p>Basic router (no advanced configuration)</p>`}
      </div>
    `;
  }

  private renderRouterConfig(): TemplateResult {
    const nodeConfig = this.getNodeConfig();
    if (!nodeConfig?.router) return html``;
 
    // Render router configuration based on node config
    // This is where you'd render rule and category editors
    return html`
      <div class="router-config">
        <p><strong>Type:</strong> ${nodeConfig.router.type}</p>
        ${nodeConfig.router.rules
          ? html`
              <div class="rules-section">
                <h4>Rules</h4>
                <!-- Future: Render rule editor based on nodeConfig.router.rules -->
                <p><em>Rule editing will be implemented here</em></p>
              </div>
            `
          : ''}
      </div>
    `;
  }
 
  private handleIssueClick(issue: FlowIssue): void {
    this.fireCustomEvent(CustomEventType.ShowIssue, { issue });
  }
 
  private renderIssueWarnings(): TemplateResult | string {
    const issues: FlowIssue[] = [];
 
    // Check for action-level issues
    if (this.action && this.issuesByAction?.has(this.action.uuid)) {
      issues.push(...this.issuesByAction.get(this.action.uuid));
    }
 
    // Check for node-level issues (issues without action_uuid)
    if (this.node && this.issuesByNode?.has(this.node.uuid)) {
      issues.push(...this.issuesByNode.get(this.node.uuid));
    }
 
    if (issues.length === 0) return '';

    return html`
      ${issues.map(
        (issue) => html`
          <div
            class="issue-warning"
            @click=${() => this.handleIssueClick(issue)}
          >
            <temba-icon name="alert_warning" size="1.2"></temba-icon>
            <span class="issue-text">${formatIssueMessage(issue)}</span>
          </div>
        `
      )}
    `;
  }
 
  render(): TemplateResult {
    if (!this.isOpen) {
      return html``;
    }
 
    const headerColor = this.isTranslating ? '#505050' : this.getHeaderColor();
    const headerTextColor = this.isTranslating ? '#fff' : '#fff';
    const config = this.getConfig();
    const dialogSize = config?.dialogSize || 'medium'; // Default to 'large' if not specified
 
    const languageName = this.isTranslating
      ? getStore().getLanguageName(this.languageCode)
      : '';
 
    let header = config?.name || 'Edit';
    if (this.isTranslating) {
      header = languageName ? `${languageName} - ${header}` : header;
    }
 
    return html`
      <temba-dialog
        header="${header}"
        .open="${this.isOpen}"
        .originX=${this.dialogOrigin?.x ?? null}
        .originY=${this.dialogOrigin?.y ?? null}
        @temba-button-clicked=${this.handleDialogButtonClick}
        primaryButtonName="Save"
        cancelButtonName="Cancel"
        style="--header-bg: ${headerColor}; --header-text: ${headerTextColor};"
        size="${dialogSize}"
      >
        <div class="node-editor-form">
          ${this.renderFields()}
          ${this.getNodeConfig()?.router?.configurable
            ? this.renderRouterSection()
            : null}
          ${this.renderIssueWarnings()}
        </div>
 
        <div slot="gutter">${this.renderGutter()}</div>
      </temba-dialog>
    `;
  }
}