All files / web/src/app/flowchart page.tsx

0% Statements 0/2420
0% Branches 0/1
0% Functions 0/1
0% Lines 0/2420

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client'

import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
import { createSocket } from '@/lib/socket'
import { useRouter, useSearchParams } from 'next/navigation'
import * as Dialog from '@radix-ui/react-dialog'
import { loadFlowchart, type GeneratedExample } from '@/lib/flowcharts/loader'
import type { FlowchartDefinition } from '@/lib/flowcharts/schema'
import { downloadFlowchartPDF } from '@/lib/flowcharts/pdf-export'
import type { ExecutableFlowchart, ProblemValue } from '@/lib/flowcharts/schema'
import { generateExamplesAsync } from '@/lib/flowcharts/example-generator-client'
import { diagnoseFlowchart, type DiagnosticReport } from '@/lib/flowcharts/doctor'
import {
  FlowchartModal,
  FlowchartCard,
  DeleteToastContainer,
  type PendingDeletion,
} from '@/components/flowchart'
import { Tooltip } from '@/components/ui/Tooltip'
import { useCreateWorkshopSession } from '@/hooks/useWorkshopSession'
import {
  agglomerativeClustering,
  subsetDistanceMatrix,
  distIndex,
} from '@/lib/flowcharts/clustering'
import { css } from '../../../styled-system/css'
import { vstack, hstack } from '../../../styled-system/patterns'

type ModalState =
  | { type: 'closed' }
  | { type: 'loading'; flowchartId: string }
  | { type: 'inputting'; flowchartId: string; flowchart: ExecutableFlowchart }
  | { type: 'error'; flowchartId: string; message: string }

type FilterType = 'all' | 'published' | 'drafts'

interface WorkshopSession {
  id: string
  state: string
  topicDescription: string | null
  draftTitle: string | null
  draftEmoji: string | null
  draftDefinitionJson: string | null
  draftMermaidContent: string | null
  createdAt: string
  updatedAt: string
}

interface EmbeddingSearchResult {
  id: string
  title: string
  description: string
  emoji: string
  difficulty: string
  similarity: number
  source: 'hardcoded' | 'database'
}

interface KeywordSearchResult {
  id: string
  title: string
  description: string
  emoji: string
  type: 'draft' | 'published'
  sessionId?: string // For drafts, to navigate to workshop
}

interface PublishedFlowchart {
  id: string
  title: string
  description: string
  emoji: string
  difficulty: string
  source: 'hardcoded' | 'database'
  authorId?: string // Only for database flowcharts
  publishedAt: string | null
  hasEmbedding?: boolean
}

const CLUSTER_COLORS = [
  {
    border: { base: 'purple.400', _dark: 'purple.500' },
    bg: { base: 'purple.50', _dark: 'purple.950' },
    text: { base: 'purple.600', _dark: 'purple.400' },
    line: { base: 'purple.200', _dark: 'purple.800' },
  },
  {
    border: { base: 'teal.400', _dark: 'teal.500' },
    bg: { base: 'teal.50', _dark: 'teal.950' },
    text: { base: 'teal.600', _dark: 'teal.400' },
    line: { base: 'teal.200', _dark: 'teal.800' },
  },
  {
    border: { base: 'orange.400', _dark: 'orange.500' },
    bg: { base: 'orange.50', _dark: 'orange.950' },
    text: { base: 'orange.600', _dark: 'orange.400' },
    line: { base: 'orange.200', _dark: 'orange.800' },
  },
  {
    border: { base: 'pink.400', _dark: 'pink.500' },
    bg: { base: 'pink.50', _dark: 'pink.950' },
    text: { base: 'pink.600', _dark: 'pink.400' },
    line: { base: 'pink.200', _dark: 'pink.800' },
  },
]

export default function FlowchartPickerPage() {
  const router = useRouter()
  const searchParams = useSearchParams()

  // The selected flowchart ID from URL query param
  const selectedId = searchParams.get('select')

  // Internal modal state (loading/inputting/error) - derived from URL + async loading
  const [modalState, setModalState] = useState<ModalState>({ type: 'closed' })

  // Create workshop session mutation
  const { mutate: createSession, isPending: isCreatingFromSearch } = useCreateWorkshopSession()

  // Filter state
  const [filter, setFilter] = useState<FilterType>('all')

  // Published flowcharts state (both hardcoded and user-created)
  const [publishedFlowcharts, setPublishedFlowcharts] = useState<PublishedFlowchart[]>([])
  const [isLoadingPublished, setIsLoadingPublished] = useState(true)
  const [currentUserId, setCurrentUserId] = useState<string | null>(null)

  // Draft sessions state
  const [draftSessions, setDraftSessions] = useState<WorkshopSession[]>([])
  const [isLoadingDrafts, setIsLoadingDrafts] = useState(true)

  // Distance matrix for clustering (from browse API)
  const [distanceData, setDistanceData] = useState<{ ids: string[]; matrix: number[] } | null>(null)

  // Label breadth scores for diversity-aware label assignment
  const [labelBreadths, setLabelBreadths] = useState<Record<string, number> | null>(null)

  // Pending deletions for undo functionality
  const [pendingDeletions, setPendingDeletions] = useState<PendingDeletion[]>([])

  // PDF download state (tracks which flowchart is currently being exported)
  const [exportingPdfId, setExportingPdfId] = useState<string | null>(null)

  // Embedding generation state
  const [isGeneratingEmbeddings, setIsGeneratingEmbeddings] = useState(false)
  const [generatingEmbeddingIds, setGeneratingEmbeddingIds] = useState<Set<string>>(new Set())

  // Search state
  const [searchQuery, setSearchQuery] = useState('')
  const [embeddingResults, setEmbeddingResults] = useState<EmbeddingSearchResult[]>([])
  const [keywordResults, setKeywordResults] = useState<KeywordSearchResult[]>([])
  const [isSearching, setIsSearching] = useState(false)
  const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  // Taxonomy navigation path - supports full breadcrumb trail
  // Stored in URL as JSON-encoded array of {label, ids} objects
  type ScopeLevel = { label: string; ids: string[] }
  const scopePath = useMemo<ScopeLevel[]>(() => {
    const encoded = searchParams.get('scopePath')
    if (!encoded) return []
    try {
      return JSON.parse(decodeURIComponent(encoded))
    } catch {
      return []
    }
  }, [searchParams])

  // Current scope is the deepest level in the path
  const scopedFlowchartIds = scopePath.length > 0 ? scopePath[scopePath.length - 1].ids : null
  const scopeLabel = scopePath.length > 0 ? scopePath[scopePath.length - 1].label : null

  // Helper to navigate deeper into a scope
  const navigateToScope = useCallback(
    (ids: string[], label: string) => {
      const newPath = [...scopePath, { label, ids }]
      const params = new URLSearchParams(searchParams.toString())
      params.set('scopePath', encodeURIComponent(JSON.stringify(newPath)))
      router.push(`?${params.toString()}`, { scroll: false })
    },
    [router, searchParams, scopePath]
  )

  // Navigate to a specific level in the breadcrumb (0 = root/all)
  const navigateToLevel = useCallback(
    (level: number) => {
      const params = new URLSearchParams(searchParams.toString())
      if (level === 0) {
        params.delete('scopePath')
      } else {
        const newPath = scopePath.slice(0, level)
        params.set('scopePath', encodeURIComponent(JSON.stringify(newPath)))
      }
      const queryString = params.toString()
      router.push(queryString ? `?${queryString}` : '/flowchart', { scroll: false })
    },
    [router, searchParams, scopePath]
  )

  // Examples for animated card backgrounds (generated client-side)
  // Unified map for both published flowcharts (keyed by flowchart ID) and drafts (keyed by session ID)
  const [cardExamples, setCardExamples] = useState<
    Map<
      string,
      {
        flowchart: ExecutableFlowchart
        examples: GeneratedExample[]
        diagnosticReport: DiagnosticReport
      }
    >
  >(new Map())

  // Track IDs currently being generated to prevent duplicate work
  const generatingIdsRef = useRef<Set<string>>(new Set())

  // Grid ref and column count for responsive "Explore" button visibility
  const gridRef = useRef<HTMLDivElement>(null)
  const [gridColumnCount, setGridColumnCount] = useState(4) // Default to 4 columns

  // Measure grid column count on resize
  useEffect(() => {
    const grid = gridRef.current
    if (!grid) return

    const measureColumns = () => {
      const style = window.getComputedStyle(grid)
      const columns = style.gridTemplateColumns.split(' ').length
      setGridColumnCount(columns)
    }

    measureColumns()
    const observer = new ResizeObserver(measureColumns)
    observer.observe(grid)
    return () => observer.disconnect()
  }, [])

  // Compute diagnostics for draft sessions (memoized)
  const draftDiagnostics = useMemo(() => {
    const diagnosticsMap = new Map<string, DiagnosticReport>()
    for (const session of draftSessions) {
      if (session.draftDefinitionJson) {
        try {
          const definition: FlowchartDefinition = JSON.parse(session.draftDefinitionJson)
          const report = diagnoseFlowchart(definition, session.draftMermaidContent || undefined)
          diagnosticsMap.set(session.id, report)
        } catch {
          // Invalid JSON, skip
        }
      }
    }
    return diagnosticsMap
  }, [draftSessions])

  // Memoized clustering: recompute when filter or distance data changes
  const clusterAssignments = useMemo(() => {
    if (!distanceData) return null

    // Partition IDs into flowchart IDs and label IDs
    const LABEL_PREFIX = 'label:'
    const flowchartDistIds = distanceData.ids.filter((id) => !id.startsWith(LABEL_PREFIX))
    const labelDistIds = distanceData.ids.filter((id) => id.startsWith(LABEL_PREFIX))

    // Only cluster published flowcharts (drafts don't have embeddings)
    // When scoped, only include flowcharts in the scope
    const baseIds = filter === 'drafts' ? [] : publishedFlowcharts.map((fc) => fc.id)
    const visibleIds = scopedFlowchartIds
      ? baseIds.filter((id) => scopedFlowchartIds.includes(id))
      : baseIds

    // Subset distance matrix to visible flowchart IDs that have embeddings
    const subset = subsetDistanceMatrix(distanceData.ids, distanceData.matrix, visibleIds)
    if (subset.ids.length < 2) return null

    const result = agglomerativeClustering(subset.ids.length, subset.matrix)

    // Build Map<flowchartId, clusterIndex> for O(1) lookup
    const map = new Map<string, number>()
    subset.ids.forEach((id, i) => map.set(id, result.assignments[i]))

    // Collect unique emojis per cluster (max 5)
    const clusterEmojis: string[][] = Array.from({ length: result.k }, () => [])
    subset.ids.forEach((id, i) => {
      const ci = result.assignments[i]
      const fc = publishedFlowcharts.find((f) => f.id === id)
      const emoji = fc?.emoji || '📊'
      if (!clusterEmojis[ci].includes(emoji) && clusterEmojis[ci].length < 5) {
        clusterEmojis[ci].push(emoji)
      }
    })

    // Assign topic labels to clusters using the full distance matrix
    const clusterLabels: (string | null)[] = Array.from({ length: result.k }, () => null)
    const clusterRunnerUps: { label: string; score: number }[][] = Array.from(
      { length: result.k },
      () => []
    )
    const clusterDiversityScores: number[] = Array.from({ length: result.k }, () => 0)
    const flowchartMatchStrengths = new Map<string, number>() // flowchartId -> 0-100 match strength

    if (labelDistIds.length > 0) {
      const fullN = distanceData.ids.length
      const fullIdxMap = new Map<string, number>()
      distanceData.ids.forEach((id, i) => fullIdxMap.set(id, i))

      // Compute cluster diversity (avg pairwise distance within cluster)
      // Used to bias toward broader labels for diverse clusters
      const clusterDiversities: number[] = []
      for (let ci = 0; ci < result.k; ci++) {
        const members = subset.ids.filter((_, i) => result.assignments[i] === ci)
        if (members.length < 2) {
          clusterDiversities.push(0)
          continue
        }
        let totalDist = 0
        let pairCount = 0
        for (let i = 0; i < members.length; i++) {
          for (let j = i + 1; j < members.length; j++) {
            const idxI = fullIdxMap.get(members[i])!
            const idxJ = fullIdxMap.get(members[j])!
            totalDist += distanceData.matrix[distIndex(idxI, idxJ, fullN)]
            pairCount++
          }
        }
        const diversity = pairCount > 0 ? totalDist / pairCount : 0
        clusterDiversities.push(diversity)
        clusterDiversityScores[ci] = diversity
      }

      // Find max breadth for normalization
      const maxBreadth = labelBreadths ? Math.max(1, ...Object.values(labelBreadths)) : 1

      // For each label, compute MAX distance to cluster members (worst match).
      // For diverse clusters, give a bonus to broad labels.
      type LabelScore = { label: string; clusterIdx: number; maxDist: number; adjustedDist: number }
      const scores: LabelScore[] = []
      const DIVERSITY_THRESHOLD = 0.35 // Clusters more diverse than this get breadth bonus

      for (const lid of labelDistIds) {
        const labelIdx = fullIdxMap.get(lid)!
        const labelName = lid.slice(LABEL_PREFIX.length)
        const breadth = labelBreadths?.[labelName] ?? 0
        const normalizedBreadth = breadth / maxBreadth // 0 to 1

        for (let ci = 0; ci < result.k; ci++) {
          const members = subset.ids.filter((_, i) => result.assignments[i] === ci)
          if (members.length === 0) continue

          let maxDist = 0
          for (const mid of members) {
            const memberIdx = fullIdxMap.get(mid)!
            const dist = distanceData.matrix[distIndex(labelIdx, memberIdx, fullN)]
            if (dist > maxDist) maxDist = dist
          }

          // For diverse clusters, give bonus to broad labels
          const isDiverse = clusterDiversities[ci] > DIVERSITY_THRESHOLD
          const breadthBonus = isDiverse ? normalizedBreadth * 0.15 : 0
          const adjustedDist = maxDist - breadthBonus

          scores.push({ label: labelName, clusterIdx: ci, maxDist, adjustedDist })
        }
      }

      // Sort by adjusted distance (best matches first = lowest adjusted distance)
      scores.sort((a, b) => a.adjustedDist - b.adjustedDist)

      // Collect top 3 labels per cluster (before greedy assignment removes options)
      const clusterTopLabels: Map<number, { label: string; score: number }[]> = new Map()
      for (const score of scores) {
        if (score.maxDist > 0.75) continue // Skip poor matches
        const existing = clusterTopLabels.get(score.clusterIdx) || []
        if (existing.length < 4) {
          existing.push({ label: score.label, score: Math.round((1 - score.adjustedDist) * 100) })
          clusterTopLabels.set(score.clusterIdx, existing)
        }
      }

      // Greedy assignment: best label first, no label reuse
      const usedLabels = new Set<string>()
      const assignedClusters = new Set<number>()
      for (const score of scores) {
        if (usedLabels.has(score.label) || assignedClusters.has(score.clusterIdx)) continue
        // Only assign if the worst match is still reasonable (threshold 0.75)
        if (score.maxDist > 0.75) continue
        clusterLabels[score.clusterIdx] = score.label
        usedLabels.add(score.label)
        assignedClusters.add(score.clusterIdx)
        if (assignedClusters.size === result.k) break
      }

      // Set runner-ups (exclude the assigned label)
      for (let ci = 0; ci < result.k; ci++) {
        const topLabels = clusterTopLabels.get(ci) || []
        const assignedLabel = clusterLabels[ci]
        clusterRunnerUps[ci] = topLabels.filter((l) => l.label !== assignedLabel).slice(0, 3)
      }

      // Compute match strength per flowchart (how well it fits its assigned label)
      for (let ci = 0; ci < result.k; ci++) {
        const assignedLabel = clusterLabels[ci]
        if (!assignedLabel) continue
        const labelIdx = fullIdxMap.get(`${LABEL_PREFIX}${assignedLabel}`)
        if (labelIdx === undefined) continue

        const members = subset.ids.filter((_, i) => result.assignments[i] === ci)
        for (const mid of members) {
          const memberIdx = fullIdxMap.get(mid)!
          const dist = distanceData.matrix[distIndex(labelIdx, memberIdx, fullN)]
          // Convert distance (0-1) to match strength (100-0), clamped
          const strength = Math.round(Math.max(0, Math.min(100, (1 - dist) * 125 - 10)))
          flowchartMatchStrengths.set(mid, strength)
        }
      }
    }

    return {
      map,
      k: result.k,
      centroids: result.centroids,
      ids: subset.ids,
      clusterEmojis,
      clusterLabels,
      clusterRunnerUps,
      clusterDiversityScores,
      flowchartMatchStrengths,
    }
  }, [distanceData, publishedFlowcharts, filter, scopedFlowchartIds, labelBreadths])

  // Memoized clustering for semantic search results
  const semanticClusterAssignments = useMemo(() => {
    if (!distanceData || embeddingResults.length < 2) return null

    const LABEL_PREFIX = 'label:'
    const labelDistIds = distanceData.ids.filter((id) => id.startsWith(LABEL_PREFIX))

    // Get IDs from embedding results that exist in the distance data
    const resultIds = embeddingResults.map((r) => r.id)

    // Subset distance matrix to search result IDs
    const subset = subsetDistanceMatrix(distanceData.ids, distanceData.matrix, resultIds)
    if (subset.ids.length < 2) return null

    const result = agglomerativeClustering(subset.ids.length, subset.matrix)

    // Build Map<flowchartId, clusterIndex> for O(1) lookup
    const map = new Map<string, number>()
    subset.ids.forEach((id, i) => map.set(id, result.assignments[i]))

    // Collect unique emojis per cluster (max 5)
    const clusterEmojis: string[][] = Array.from({ length: result.k }, () => [])
    subset.ids.forEach((id, i) => {
      const ci = result.assignments[i]
      const sr = embeddingResults.find((r) => r.id === id)
      const emoji = sr?.emoji || '📊'
      if (!clusterEmojis[ci].includes(emoji) && clusterEmojis[ci].length < 5) {
        clusterEmojis[ci].push(emoji)
      }
    })

    // Assign topic labels to clusters using diversity-aware scoring
    const clusterLabels: (string | null)[] = Array.from({ length: result.k }, () => null)
    if (labelDistIds.length > 0) {
      const fullN = distanceData.ids.length
      const fullIdxMap = new Map<string, number>()
      distanceData.ids.forEach((id, i) => fullIdxMap.set(id, i))

      // Compute cluster diversity
      const clusterDiversities: number[] = []
      for (let ci = 0; ci < result.k; ci++) {
        const members = subset.ids.filter((_, i) => result.assignments[i] === ci)
        if (members.length < 2) {
          clusterDiversities.push(0)
          continue
        }
        let totalDist = 0
        let pairCount = 0
        for (let i = 0; i < members.length; i++) {
          for (let j = i + 1; j < members.length; j++) {
            const idxI = fullIdxMap.get(members[i])
            const idxJ = fullIdxMap.get(members[j])
            if (idxI !== undefined && idxJ !== undefined) {
              totalDist += distanceData.matrix[distIndex(idxI, idxJ, fullN)]
              pairCount++
            }
          }
        }
        clusterDiversities.push(pairCount > 0 ? totalDist / pairCount : 0)
      }

      const maxBreadth = labelBreadths ? Math.max(1, ...Object.values(labelBreadths)) : 1
      const DIVERSITY_THRESHOLD = 0.35

      type LabelScore = { label: string; clusterIdx: number; maxDist: number; adjustedDist: number }
      const scores: LabelScore[] = []

      for (const lid of labelDistIds) {
        const labelIdx = fullIdxMap.get(lid)!
        const labelName = lid.slice(LABEL_PREFIX.length)
        const breadth = labelBreadths?.[labelName] ?? 0
        const normalizedBreadth = breadth / maxBreadth

        for (let ci = 0; ci < result.k; ci++) {
          const members = subset.ids.filter((_, i) => result.assignments[i] === ci)
          if (members.length === 0) continue

          let maxDist = 0
          for (const mid of members) {
            const memberIdx = fullIdxMap.get(mid)
            if (memberIdx === undefined) continue
            const dist = distanceData.matrix[distIndex(labelIdx, memberIdx, fullN)]
            if (dist > maxDist) maxDist = dist
          }

          const isDiverse = clusterDiversities[ci] > DIVERSITY_THRESHOLD
          const breadthBonus = isDiverse ? normalizedBreadth * 0.15 : 0
          const adjustedDist = maxDist - breadthBonus

          scores.push({ label: labelName, clusterIdx: ci, maxDist, adjustedDist })
        }
      }

      scores.sort((a, b) => a.adjustedDist - b.adjustedDist)

      const usedLabels = new Set<string>()
      const assignedClusters = new Set<number>()
      for (const score of scores) {
        if (usedLabels.has(score.label) || assignedClusters.has(score.clusterIdx)) continue
        if (score.maxDist > 0.75) continue
        clusterLabels[score.clusterIdx] = score.label
        usedLabels.add(score.label)
        assignedClusters.add(score.clusterIdx)
        if (assignedClusters.size === result.k) break
      }
    }

    return { map, k: result.k, ids: subset.ids, clusterEmojis, clusterLabels }
  }, [distanceData, embeddingResults, labelBreadths])

  // Load published flowcharts (hardcoded + user-created)
  const loadPublished = useCallback(async () => {
    try {
      const response = await fetch('/api/flowcharts/browse')
      if (response.ok) {
        const data = await response.json()
        setPublishedFlowcharts(data.flowcharts || [])
        setCurrentUserId(data.currentUserId || null)
        setDistanceData(data.distances ?? null)
        setLabelBreadths(data.labelBreadths ?? null)
      }
    } catch (err) {
      console.error('Failed to load published flowcharts:', err)
    } finally {
      setIsLoadingPublished(false)
    }
  }, [])

  const handleGenerateEmbeddings = useCallback(async () => {
    setIsGeneratingEmbeddings(true)
    try {
      const res = await fetch('/api/flowcharts/seed-embeddings/task', { method: 'POST' })
      if (!res.ok) {
        console.error('Failed to start embedding task')
        setIsGeneratingEmbeddings(false)
        return
      }

      const { taskId } = await res.json()
      const socket = createSocket()

      socket.on('connect', () => {
        socket.emit('task:subscribe', taskId)
      })

      // Handle task already completed/failed before socket connected
      socket.on('task:state', (state: { id: string; status: string }) => {
        if (state.id !== taskId) return
        if (
          state.status === 'completed' ||
          state.status === 'failed' ||
          state.status === 'cancelled'
        ) {
          setIsGeneratingEmbeddings(false)
          socket.disconnect()
          if (state.status === 'completed') {
            loadPublished()
          }
        }
      })

      socket.on(
        'task:event',
        (event: { taskId: string; eventType: string; payload: Record<string, unknown> }) => {
          if (event.taskId !== taskId) return

          if (
            event.eventType === 'embed_complete' ||
            event.eventType === 'completed' ||
            event.eventType === 'failed' ||
            event.eventType === 'cancelled'
          ) {
            setIsGeneratingEmbeddings(false)
            socket.emit('task:unsubscribe', taskId)
            socket.disconnect()
            if (event.eventType === 'embed_complete' || event.eventType === 'completed') {
              loadPublished()
            }
          }
        }
      )
    } catch (err) {
      console.error('Failed to generate embeddings:', err)
      setIsGeneratingEmbeddings(false)
    }
  }, [loadPublished])

  const handleGenerateCardEmbedding = useCallback(
    async (id: string) => {
      setGeneratingEmbeddingIds((prev) => new Set(prev).add(id))
      try {
        const res = await fetch(`/api/flowcharts/${id}/embedding`, { method: 'POST' })
        if (res.ok) {
          await loadPublished()
        }
      } catch (err) {
        console.error('Failed to generate embedding for', id, err)
      } finally {
        setGeneratingEmbeddingIds((prev) => {
          const next = new Set(prev)
          next.delete(id)
          return next
        })
      }
    },
    [loadPublished]
  )

  useEffect(() => {
    loadPublished()
  }, [loadPublished])

  // Load draft sessions
  useEffect(() => {
    async function loadDrafts() {
      try {
        const response = await fetch('/api/flowchart-workshop/sessions')
        if (response.ok) {
          const data = await response.json()
          setDraftSessions(data.sessions || [])
        }
      } catch (err) {
        console.error('Failed to load draft sessions:', err)
      } finally {
        setIsLoadingDrafts(false)
      }
    }
    loadDrafts()
  }, [])

  // Generate examples for ALL flowcharts (published + drafts) in a single unified effect
  // Uses concurrent generation - the worker pool properly queues requests via request IDs
  useEffect(() => {
    if (isLoadingPublished || isLoadingDrafts) return

    // Collect all items that need examples generated
    type ItemToGenerate = {
      id: string
      title: string
      type: 'published' | 'draft'
      // For drafts only:
      definitionJson?: string
      mermaidContent?: string
    }

    const itemsToGenerate: ItemToGenerate[] = []

    // Add published flowcharts (all from database now)
    for (const fc of publishedFlowcharts) {
      if (cardExamples.has(fc.id) || generatingIdsRef.current.has(fc.id)) continue
      itemsToGenerate.push({
        id: fc.id,
        title: fc.title,
        type: 'published',
      })
    }

    // Add healthy drafts with valid definitions
    for (const session of draftSessions) {
      if (cardExamples.has(session.id) || generatingIdsRef.current.has(session.id)) continue
      if (!session.draftDefinitionJson || !session.draftMermaidContent) continue

      // Only include healthy drafts
      const report = draftDiagnostics.get(session.id)
      if (report && !report.isHealthy) continue

      itemsToGenerate.push({
        id: session.id,
        title: session.draftTitle || 'Untitled Draft',
        type: 'draft',
        definitionJson: session.draftDefinitionJson,
        mermaidContent: session.draftMermaidContent,
      })
    }

    if (itemsToGenerate.length === 0) return

    // Mark all as generating before starting
    for (const item of itemsToGenerate) {
      generatingIdsRef.current.add(item.id)
    }

    // Generate examples for a single item
    async function generateForItem(item: ItemToGenerate): Promise<void> {
      try {
        let executable: ExecutableFlowchart
        let mermaidContent: string | undefined

        if (item.type === 'published') {
          // All published flowcharts are loaded from database via API
          const response = await fetch(`/api/flowcharts/${item.id}`)
          if (!response.ok) return
          const data = await response.json()
          const { definition, mermaid } = data.flowchart as {
            definition: FlowchartDefinition
            mermaid: string
          }
          executable = await loadFlowchart(definition, mermaid)
          mermaidContent = mermaid
        } else {
          // Draft - use local JSON from session
          const definition: FlowchartDefinition = JSON.parse(item.definitionJson!)
          executable = await loadFlowchart(definition, item.mermaidContent!)
          mermaidContent = item.mermaidContent
        }

        const diagnosticReport = diagnoseFlowchart(executable.definition, mermaidContent)
        const examples = await generateExamplesAsync(executable, 10, {})

        setCardExamples((prev) =>
          new Map(prev).set(item.id, { flowchart: executable, examples, diagnosticReport })
        )
      } catch (err) {
        console.error(`[Examples] Failed to generate for ${item.title}:`, err)
      } finally {
        generatingIdsRef.current.delete(item.id)
      }
    }

    // Generate all examples concurrently - the worker pool handles queuing
    Promise.all(itemsToGenerate.map(generateForItem))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isLoadingPublished, isLoadingDrafts, publishedFlowcharts, draftSessions, draftDiagnostics])

  // Debounced search for flowcharts
  useEffect(() => {
    // Clear previous timeout
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current)
    }

    // Don't search if query is too short
    if (searchQuery.trim().length < 3) {
      setEmbeddingResults([])
      setKeywordResults([])
      setIsSearching(false)
      return
    }

    setIsSearching(true)

    // Debounce the search by 500ms
    searchTimeoutRef.current = setTimeout(async () => {
      try {
        // 1. Embedding search via API (semantic matching)
        const response = await fetch('/api/flowcharts/suggest', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ query: searchQuery, limit: 10 }),
        })

        let embeddingMatches: EmbeddingSearchResult[] = []
        if (response.ok) {
          const data = await response.json()
          embeddingMatches = data.suggestions || []
        }
        setEmbeddingResults(embeddingMatches)

        // 2. Keyword search on drafts (local matching)
        const queryLower = searchQuery.toLowerCase()
        const embeddingIds = new Set(embeddingMatches.map((r) => r.id))

        const keywordMatches: KeywordSearchResult[] = []

        // Search drafts by keyword
        for (const draft of draftSessions) {
          const title = draft.draftTitle || draft.topicDescription || ''
          if (title.toLowerCase().includes(queryLower)) {
            keywordMatches.push({
              id: draft.id,
              title: title || 'Untitled',
              description: draft.topicDescription || '',
              emoji: draft.draftEmoji || '📝',
              type: 'draft',
              sessionId: draft.id,
            })
          }
        }

        // Search published flowcharts that weren't in embedding results
        for (const fc of publishedFlowcharts) {
          if (embeddingIds.has(fc.id)) continue // Already matched by embedding
          const inTitle = fc.title.toLowerCase().includes(queryLower)
          const inDescription = fc.description?.toLowerCase().includes(queryLower)
          if (inTitle || inDescription) {
            keywordMatches.push({
              id: fc.id,
              title: fc.title,
              description: fc.description,
              emoji: fc.emoji,
              type: 'published',
            })
          }
        }

        setKeywordResults(keywordMatches)
      } catch (err) {
        console.error('Failed to search flowcharts:', err)
      } finally {
        setIsSearching(false)
      }
    }, 500)

    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current)
      }
    }
  }, [searchQuery, draftSessions, publishedFlowcharts])

  // Handle draft session actions
  const handleResumeDraft = useCallback(
    (sessionId: string) => {
      router.push(`/flowchart/workshop/${sessionId}`)
    },
    [router]
  )

  // Handle remixing a built-in flowchart
  const handleRemix = useCallback(
    async (flowchartId: string) => {
      try {
        const response = await fetch('/api/flowchart-workshop/sessions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ remixFromId: flowchartId }),
        })

        if (!response.ok) {
          throw new Error('Failed to create remix session')
        }

        const { session } = await response.json()
        router.push(`/flowchart/workshop/${session.id}`)
      } catch (err) {
        console.error('Failed to remix flowchart:', err)
      }
    },
    [router]
  )

  // Handle editing user's own published flowchart
  const handleEditPublished = useCallback(
    async (flowchartId: string) => {
      try {
        const response = await fetch('/api/flowchart-workshop/sessions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ editPublishedId: flowchartId }),
        })

        if (!response.ok) {
          throw new Error('Failed to create edit session')
        }

        const { session } = await response.json()
        router.push(`/flowchart/workshop/${session.id}`)
      } catch (err) {
        console.error('Failed to start editing flowchart:', err)
      }
    },
    [router]
  )

  // Handle creating a new flowchart from the search bar query
  const handleCreateFromSearch = useCallback(() => {
    if (!searchQuery.trim()) return
    createSession({ topicDescription: searchQuery.trim() })
  }, [searchQuery, createSession])

  // Handle PDF download for a built-in flowchart
  const handleDownloadPDF = useCallback(async (flowchartId: string) => {
    setExportingPdfId(flowchartId)
    try {
      // Fetch flowchart from API (all flowcharts are in database now)
      const response = await fetch(`/api/flowcharts/${flowchartId}`)
      if (!response.ok) {
        console.error('Flowchart not found:', flowchartId)
        return
      }
      const data = await response.json()
      const { mermaid, meta } = data.flowchart as {
        mermaid: string
        meta: { title: string; description: string }
      }

      await downloadFlowchartPDF(mermaid, {
        title: meta.title,
        description: meta.description,
        flowchartId,
      })
    } catch (err) {
      console.error('Failed to export PDF:', err)
    } finally {
      setExportingPdfId(null)
    }
  }, [])

  // Start deletion with undo option
  const handleDeleteDraft = useCallback(
    (sessionId: string) => {
      const session = draftSessions.find((s) => s.id === sessionId)
      if (!session) return

      // Add to pending deletions
      setPendingDeletions((prev) => [
        ...prev,
        {
          id: sessionId,
          title: session.draftTitle || session.topicDescription || 'Untitled',
          createdAt: Date.now(),
        },
      ])

      // Hide from list immediately
      setDraftSessions((prev) => prev.filter((s) => s.id !== sessionId))
    },
    [draftSessions]
  )

  // Undo deletion
  const handleUndoDelete = useCallback((deletion: PendingDeletion) => {
    // Remove from pending
    setPendingDeletions((prev) => prev.filter((d) => d.id !== deletion.id))

    // Re-fetch sessions to restore the item
    fetch('/api/flowchart-workshop/sessions')
      .then((res) => res.json())
      .then((data) => setDraftSessions(data.sessions || []))
      .catch(console.error)
  }, [])

  // Confirm deletion (actually delete)
  const handleConfirmDelete = useCallback(async (deletion: PendingDeletion) => {
    // Remove from pending
    setPendingDeletions((prev) => prev.filter((d) => d.id !== deletion.id))

    // Actually delete
    try {
      await fetch(`/api/flowchart-workshop/sessions/${deletion.id}`, {
        method: 'DELETE',
      })
    } catch (err) {
      console.error('Failed to delete session:', err)
    }
  }, [])

  // Sync modal state with URL query param
  useEffect(() => {
    if (!selectedId) {
      // URL has no selection - close modal
      setModalState({ type: 'closed' })
      return
    }

    // URL has a selection - check if we need to load it
    const needsLoad = modalState.type === 'closed' || modalState.flowchartId !== selectedId
    if (needsLoad) {
      // Start loading the newly selected flowchart
      setModalState({ type: 'loading', flowchartId: selectedId })
    }
  }, [selectedId]) // eslint-disable-line react-hooks/exhaustive-deps

  // Load flowchart when modal enters loading state
  useEffect(() => {
    if (modalState.type !== 'loading') return

    const flowchartId = modalState.flowchartId

    async function load() {
      try {
        // Fetch from API (supports both hardcoded and database flowcharts)
        const response = await fetch(`/api/flowcharts/${flowchartId}`)
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}))
          setModalState({
            type: 'error',
            flowchartId,
            message: errorData.error || 'Flowchart not found',
          })
          return
        }

        const data = await response.json()
        const { definition, mermaid } = data.flowchart as {
          definition: FlowchartDefinition
          mermaid: string
        }

        const flowchart = await loadFlowchart(definition, mermaid)
        setModalState({ type: 'inputting', flowchartId, flowchart })
      } catch (error) {
        console.error('Error loading flowchart:', error)
        setModalState({ type: 'error', flowchartId, message: 'Failed to load flowchart' })
      }
    }

    load()
  }, [modalState])

  // Open modal by updating URL (adds to browser history)
  const handleCardClick = useCallback(
    (flowchartId: string) => {
      router.push(`/flowchart?select=${flowchartId}`, { scroll: false })
    },
    [router]
  )

  const handleProblemSubmit = useCallback(
    (values: Record<string, ProblemValue>) => {
      if (modalState.type !== 'inputting') return

      // Store problem values in sessionStorage for the walker page to pick up
      const storageKey = `flowchart-problem-${modalState.flowchartId}`
      sessionStorage.setItem(storageKey, JSON.stringify(values))

      // Navigate to the walker page
      router.push(`/flowchart/${modalState.flowchartId}`)
    },
    [modalState, router]
  )

  // Close modal by updating URL (replaces current history entry to avoid back-to-modal loop)
  const handleClose = useCallback(() => {
    router.replace('/flowchart', { scroll: false })
  }, [router])

  const isModalOpen = modalState.type !== 'closed'

  return (
    <div
      className={css({
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        minHeight: '100vh',
      })}
    >
      {/* Outer wrapper: full-width edge-to-edge */}
      <div
        className={css({
          width: '100%',
        })}
      >
        {/* Sticky search/filter bar — top "lid" of the container */}
        <header
          className={css({
            position: 'sticky',
            top: 0,
            zIndex: 10,
            display: 'flex',
            justifyContent: 'center',
            width: '100%',
            borderBottom: '2px solid',
            borderBottomColor: { base: 'gray.200', _dark: 'gray.700' },
            backgroundColor: { base: 'white', _dark: 'gray.800' },
            transition: 'border-color 0.15s, box-shadow 0.15s',
            _focusWithin: {
              borderColor: { base: 'blue.500', _dark: 'blue.400' },
              boxShadow: '0 0 0 3px rgba(59, 130, 246, 0.2)',
            },
          })}
        >
          <div
            className={css({
              display: 'flex',
              flexDirection: { base: 'column', md: 'row' },
              alignItems: { base: 'stretch', md: 'center' },
              width: '100%',
              maxWidth: '1200px',
              paddingX: '4',
              overflow: 'hidden',
            })}
          >
            {/* Search input area */}
            <div
              className={css({
                position: 'relative',
                flex: 1,
                display: 'flex',
                alignItems: 'center',
              })}
            >
              <span
                className={css({
                  position: 'absolute',
                  left: '3',
                  top: '50%',
                  transform: 'translateY(-50%)',
                  color: { base: 'gray.400', _dark: 'gray.500' },
                  pointerEvents: 'none',
                })}
              >
                🔍
              </span>
              {(() => {
                // Check if we should show inline create UI (no results, query >= 3 chars, not searching)
                const hasNoResults =
                  searchQuery.trim().length >= 3 &&
                  !isSearching &&
                  embeddingResults.length === 0 &&
                  keywordResults.length === 0
                return (
                  <>
                    <input
                      type="text"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' && hasNoResults && !isCreatingFromSearch) {
                          e.preventDefault()
                          handleCreateFromSearch()
                        }
                      }}
                      placeholder="What do you want to learn?"
                      className={css({
                        width: '100%',
                        paddingY: '3',
                        paddingLeft: '10',
                        paddingRight: hasNoResults ? '120px' : searchQuery ? '9' : '3',
                        border: 'none',
                        backgroundColor: 'transparent',
                        color: { base: 'gray.900', _dark: 'gray.100' },
                        fontSize: 'md',
                        _focus: {
                          outline: 'none',
                        },
                        _placeholder: {
                          color: { base: 'gray.400', _dark: 'gray.500' },
                        },
                      })}
                    />
                    {hasNoResults ? (
                      <div
                        className={css({
                          position: 'absolute',
                          right: '2',
                          top: '50%',
                          transform: 'translateY(-50%)',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '2',
                        })}
                      >
                        <button
                          onClick={() => setSearchQuery('')}
                          className={css({
                            padding: '1',
                            borderRadius: 'full',
                            border: 'none',
                            backgroundColor: { base: 'gray.200', _dark: 'gray.600' },
                            color: { base: 'gray.600', _dark: 'gray.300' },
                            cursor: 'pointer',
                            fontSize: 'xs',
                            lineHeight: 1,
                            _hover: {
                              backgroundColor: { base: 'gray.300', _dark: 'gray.500' },
                            },
                          })}
                        >

                        </button>
                        <button
                          onClick={handleCreateFromSearch}
                          disabled={isCreatingFromSearch}
                          className={css({
                            paddingY: '1.5',
                            paddingX: '3',
                            borderRadius: 'md',
                            backgroundColor: { base: 'blue.600', _dark: 'blue.500' },
                            color: 'white',
                            fontWeight: 'semibold',
                            fontSize: 'sm',
                            border: 'none',
                            cursor: 'pointer',
                            transition: 'all 0.2s',
                            _hover: {
                              backgroundColor: { base: 'blue.700', _dark: 'blue.600' },
                            },
                            _disabled: {
                              opacity: 0.5,
                              cursor: 'not-allowed',
                            },
                          })}
                        >
                          {isCreatingFromSearch ? 'Creating...' : 'Create'}
                        </button>
                      </div>
                    ) : searchQuery ? (
                      <button
                        onClick={() => setSearchQuery('')}
                        className={css({
                          position: 'absolute',
                          right: '2',
                          top: '50%',
                          transform: 'translateY(-50%)',
                          padding: '1',
                          borderRadius: 'full',
                          border: 'none',
                          backgroundColor: { base: 'gray.200', _dark: 'gray.600' },
                          color: { base: 'gray.600', _dark: 'gray.300' },
                          cursor: 'pointer',
                          fontSize: 'xs',
                          lineHeight: 1,
                          _hover: {
                            backgroundColor: { base: 'gray.300', _dark: 'gray.500' },
                          },
                        })}
                      >

                      </button>
                    ) : null}
                  </>
                )
              })()}
            </div>

            {/* Divider: vertical on md+, horizontal on mobile */}
            <div
              className={css({
                width: { base: '100%', md: '1px' },
                height: { base: '1px', md: '60%' },
                alignSelf: { base: 'stretch', md: 'center' },
                backgroundColor: { base: 'gray.300', _dark: 'gray.600' },
                flexShrink: 0,
              })}
            />

            {/* Filter buttons */}
            <div
              className={css({
                display: 'flex',
                alignItems: 'center',
                justifyContent: { base: 'stretch', md: 'flex-start' },
                gap: '1',
                padding: '1',
                flexShrink: 0,
              })}
            >
              {[
                { value: 'all' as const, label: 'All' },
                {
                  value: 'published' as const,
                  label: `Published${publishedFlowcharts.length > 0 ? ` (${publishedFlowcharts.length})` : ''}`,
                },
                {
                  value: 'drafts' as const,
                  label: `Drafts${draftSessions.length > 0 ? ` (${draftSessions.length})` : ''}`,
                },
              ].map((option) => (
                <button
                  key={option.value}
                  onClick={() => setFilter(option.value)}
                  className={css({
                    flex: { base: 1, md: 'initial' },
                    paddingY: '1.5',
                    paddingX: '3',
                    borderRadius: 'md',
                    fontSize: 'sm',
                    fontWeight: 'medium',
                    border: 'none',
                    cursor: 'pointer',
                    transition: 'all 0.15s',
                    whiteSpace: 'nowrap',
                    backgroundColor:
                      filter === option.value
                        ? { base: 'gray.100', _dark: 'gray.700' }
                        : 'transparent',
                    color:
                      filter === option.value
                        ? { base: 'gray.900', _dark: 'gray.100' }
                        : { base: 'gray.600', _dark: 'gray.400' },
                    boxShadow: filter === option.value ? 'sm' : 'none',
                    _hover: {
                      color: { base: 'gray.900', _dark: 'gray.100' },
                    },
                  })}
                >
                  {option.label}
                </button>
              ))}
            </div>
          </div>
        </header>

        {/* Recessed card well — cards sit in this subtle "well" below the sticky header */}
        <div
          className={css({
            backgroundColor: { base: 'gray.50', _dark: 'gray.900' },
            paddingX: '4',
            paddingY: '6',
            display: 'flex',
            justifyContent: 'center',
            minHeight: 0,
            flex: 1,
          })}
        >
          <div
            ref={gridRef}
            className={css({
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
              gap: '4',
              width: '100%',
              maxWidth: '1200px',
            })}
          >
            {/* Search results header */}
            {searchQuery.trim().length >= 3 &&
              (embeddingResults.length > 0 || keywordResults.length > 0 || isSearching) && (
                <div
                  className={css({
                    gridColumn: '1 / -1',
                    textAlign: 'center',
                    color: { base: 'gray.600', _dark: 'gray.400' },
                    fontSize: 'sm',
                  })}
                >
                  {isSearching ? (
                    'Searching...'
                  ) : (
                    <>
                      Found <strong>{embeddingResults.length + keywordResults.length}</strong>{' '}
                      result
                      {embeddingResults.length + keywordResults.length !== 1 ? 's' : ''} for &ldquo;
                      {searchQuery}&rdquo;
                    </>
                  )}
                </div>
              )}
            {/* Show search results when search is active */}
            {searchQuery.trim().length >= 3 ? (
              <>
                {/* Prominent create card when there ARE results but best match < 0.55 */}
                {/* (When there are NO results, the create button is in the search bar) */}
                {(() => {
                  const hasResults = embeddingResults.length > 0 || keywordResults.length > 0
                  if (!hasResults) return null // Create is in search bar when no results
                  const bestSimilarity =
                    embeddingResults.length > 0
                      ? Math.max(...embeddingResults.map((r) => r.similarity))
                      : 0
                  return bestSimilarity < 0.55 ? (
                    <div
                      className={css({
                        gridColumn: '1 / -1',
                        paddingY: '3',
                        paddingX: '4',
                        borderRadius: 'lg',
                        border: '2px dashed',
                        borderColor: { base: 'blue.300', _dark: 'blue.600' },
                        backgroundColor: { base: 'blue.50', _dark: 'blue.950' },
                        display: 'flex',
                        alignItems: 'center',
                        gap: '3',
                      })}
                    >
                      <span className={css({ fontSize: 'lg', flexShrink: 0 })}>&#10024;</span>
                      <span
                        className={css({
                          fontSize: 'sm',
                          color: { base: 'gray.700', _dark: 'gray.300' },
                          flex: 1,
                          minWidth: 0,
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap',
                        })}
                      >
                        Create &ldquo;{searchQuery}&rdquo;
                      </span>
                      <button
                        onClick={handleCreateFromSearch}
                        disabled={isCreatingFromSearch}
                        className={css({
                          paddingY: '1.5',
                          paddingX: '4',
                          borderRadius: 'md',
                          backgroundColor: { base: 'blue.600', _dark: 'blue.500' },
                          color: 'white',
                          fontWeight: 'semibold',
                          fontSize: 'sm',
                          border: 'none',
                          cursor: 'pointer',
                          flexShrink: 0,
                          transition: 'all 0.2s',
                          _hover: {
                            backgroundColor: { base: 'blue.700', _dark: 'blue.600' },
                          },
                          _disabled: {
                            opacity: 0.5,
                            cursor: 'not-allowed',
                          },
                        })}
                      >
                        {isCreatingFromSearch ? 'Creating...' : 'Create'}
                      </button>
                    </div>
                  ) : null
                })()}

                {/* Semantic matches (embedding-based) */}
                {embeddingResults.length > 0 &&
                  (() => {
                    const renderSemanticCard = (
                      result: EmbeddingSearchResult,
                      clusterColorIndex?: number
                    ) => {
                      const publishedMatch = publishedFlowcharts.find((fc) => fc.id === result.id)
                      const isOwnFlowchart =
                        result.source === 'database' &&
                        currentUserId &&
                        publishedMatch?.authorId === currentUserId

                      return (
                        <FlowchartCard
                          key={result.id}
                          title={result.title}
                          description={result.description}
                          emoji={result.emoji}
                          difficulty={result.difficulty}
                          subtitle={`${Math.round(result.similarity * 100)}% match`}
                          clusterColorIndex={clusterColorIndex}
                          onClick={() => handleCardClick(result.id)}
                          actions={
                            result.source === 'hardcoded'
                              ? [
                                  {
                                    label: exportingPdfId === result.id ? 'Exporting...' : 'PDF',
                                    onClick: () => handleDownloadPDF(result.id),
                                    variant: 'secondary' as const,
                                    disabled: exportingPdfId === result.id,
                                  },
                                  {
                                    label: 'Remix',
                                    onClick: () => handleRemix(result.id),
                                    variant: 'secondary' as const,
                                  },
                                ]
                              : isOwnFlowchart
                                ? [
                                    {
                                      label: 'Edit',
                                      onClick: () => handleEditPublished(result.id),
                                      variant: 'primary' as const,
                                    },
                                    {
                                      label: 'Remix',
                                      onClick: () => handleRemix(result.id),
                                      variant: 'secondary' as const,
                                    },
                                  ]
                                : [
                                    {
                                      label: 'Remix',
                                      onClick: () => handleRemix(result.id),
                                      variant: 'secondary' as const,
                                    },
                                  ]
                          }
                        />
                      )
                    }

                    // If we have clustering data, render by clusters
                    if (semanticClusterAssignments && semanticClusterAssignments.k > 1) {
                      const elements: React.ReactNode[] = []
                      const clusteredIds = new Set(semanticClusterAssignments.ids)

                      for (let ci = 0; ci < semanticClusterAssignments.k; ci++) {
                        const color = CLUSTER_COLORS[ci % CLUSTER_COLORS.length]
                        const emojis = semanticClusterAssignments.clusterEmojis[ci]
                        const topicLabel = semanticClusterAssignments.clusterLabels[ci]
                        const clusterResults = embeddingResults.filter(
                          (r) => semanticClusterAssignments.map.get(r.id) === ci
                        )
                        if (clusterResults.length === 0) continue

                        elements.push(
                          <div
                            key={`semantic-header-${ci}`}
                            className={css({
                              gridColumn: '1 / -1',
                              display: 'flex',
                              alignItems: 'center',
                              gap: '3',
                              color: color.text,
                              fontSize: 'sm',
                              marginTop: ci > 0 ? '4' : '0',
                              marginBottom: '2',
                            })}
                          >
                            <span>{emojis.join(' ')}</span>
                            {topicLabel && (
                              <span className={css({ fontWeight: 'medium' })}>{topicLabel}</span>
                            )}
                            <div
                              className={css({
                                flex: 1,
                                height: '1px',
                                backgroundColor: color.line,
                              })}
                            />
                          </div>
                        )

                        for (const result of clusterResults) {
                          elements.push(renderSemanticCard(result, ci))
                        }
                      }

                      // Render unclustered results (if any)
                      const unclustered = embeddingResults.filter((r) => !clusteredIds.has(r.id))
                      if (unclustered.length > 0) {
                        elements.push(
                          <div
                            key="semantic-header-unclustered"
                            className={css({
                              gridColumn: '1 / -1',
                              display: 'flex',
                              alignItems: 'center',
                              gap: '3',
                              color: { base: 'gray.500', _dark: 'gray.400' },
                              fontSize: 'sm',
                              marginTop: '4',
                              marginBottom: '2',
                            })}
                          >
                            <span>More</span>
                            <div
                              className={css({
                                flex: 1,
                                height: '1px',
                                backgroundColor: { base: 'gray.200', _dark: 'gray.700' },
                              })}
                            />
                          </div>
                        )
                        for (const result of unclustered) {
                          elements.push(renderSemanticCard(result))
                        }
                      }

                      return elements
                    }

                    // Fallback: flat list with header
                    return (
                      <>
                        <div
                          className={css({
                            gridColumn: '1 / -1',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '3',
                            color: { base: 'gray.500', _dark: 'gray.400' },
                            fontSize: 'sm',
                            marginBottom: '2',
                          })}
                        >
                          <span>🧠</span>
                          <span>Semantic matches</span>
                          <div
                            className={css({
                              flex: 1,
                              height: '1px',
                              backgroundColor: { base: 'gray.200', _dark: 'gray.700' },
                            })}
                          />
                        </div>
                        {embeddingResults.map((result) => renderSemanticCard(result))}
                      </>
                    )
                  })()}

                {/* Keyword matches */}
                {keywordResults.length > 0 && (
                  <>
                    <div
                      className={css({
                        gridColumn: '1 / -1',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '3',
                        color: { base: 'gray.500', _dark: 'gray.400' },
                        fontSize: 'sm',
                        marginTop: embeddingResults.length > 0 ? '4' : '0',
                        marginBottom: '2',
                      })}
                    >
                      <span>🔤</span>
                      <span>Keyword matches</span>
                      <div
                        className={css({
                          flex: 1,
                          height: '1px',
                          backgroundColor: { base: 'gray.200', _dark: 'gray.700' },
                        })}
                      />
                    </div>
                    {keywordResults.map((result) => {
                      // For published keyword matches, check if user owns this flowchart
                      const publishedMatch =
                        result.type === 'published'
                          ? publishedFlowcharts.find((fc) => fc.id === result.id)
                          : null
                      const isOwnFlowchart =
                        result.type === 'published' &&
                        currentUserId &&
                        publishedMatch?.authorId === currentUserId

                      return (
                        <FlowchartCard
                          key={`keyword-${result.id}`}
                          title={result.title}
                          description={result.description}
                          emoji={result.emoji}
                          status={result.type === 'draft' ? 'Draft' : undefined}
                          onClick={() =>
                            result.type === 'draft' && result.sessionId
                              ? handleResumeDraft(result.sessionId)
                              : handleCardClick(result.id)
                          }
                          actions={
                            result.type === 'draft' && result.sessionId
                              ? [
                                  {
                                    label: 'Edit',
                                    href: `/flowchart/workshop/${result.sessionId}`,
                                    variant: 'primary' as const,
                                  },
                                ]
                              : isOwnFlowchart
                                ? [
                                    {
                                      label: 'Edit',
                                      onClick: () => handleEditPublished(result.id),
                                      variant: 'primary' as const,
                                    },
                                    {
                                      label: 'Remix',
                                      onClick: () => handleRemix(result.id),
                                      variant: 'secondary' as const,
                                    },
                                  ]
                                : [
                                    {
                                      label: 'Remix',
                                      onClick: () => handleRemix(result.id),
                                      variant: 'secondary' as const,
                                    },
                                  ]
                          }
                        />
                      )
                    })}
                  </>
                )}

                {/* Create link when good matches exist */}
                {embeddingResults.length > 0 &&
                  Math.max(...embeddingResults.map((r) => r.similarity)) >= 0.55 && (
                    <div
                      className={css({
                        gridColumn: '1 / -1',
                        textAlign: 'center',
                        paddingY: '5',
                        marginTop: '2',
                      })}
                    >
                      <button
                        onClick={handleCreateFromSearch}
                        disabled={isCreatingFromSearch}
                        className={css({
                          backgroundColor: { base: 'gray.100', _dark: 'gray.800' },
                          border: '1px solid',
                          borderColor: { base: 'gray.300', _dark: 'gray.600' },
                          borderRadius: 'lg',
                          cursor: 'pointer',
                          color: { base: 'gray.700', _dark: 'gray.300' },
                          fontSize: 'sm',
                          fontWeight: 'medium',
                          paddingY: '3',
                          paddingX: '5',
                          transition: 'all 0.15s',
                          _hover: {
                            backgroundColor: { base: 'blue.50', _dark: 'blue.950' },
                            borderColor: { base: 'blue.300', _dark: 'blue.600' },
                            color: { base: 'blue.700', _dark: 'blue.300' },
                          },
                          _disabled: {
                            opacity: 0.5,
                            cursor: 'not-allowed',
                          },
                        })}
                      >
                        {isCreatingFromSearch
                          ? 'Creating...'
                          : `Don\u2019t see what you need? Create \u201C${searchQuery}\u201D \u2192`}
                      </button>
                    </div>
                  )}
              </>
            ) : (
              <>
                {/* Published flowcharts (hardcoded + user-created) */}
                {filter !== 'drafts' &&
                  (() => {
                    const renderPublishedCard = (
                      flowchart: PublishedFlowchart,
                      clusterColorIndex?: number
                    ) => {
                      const isOwnFlowchart =
                        flowchart.source === 'database' &&
                        currentUserId &&
                        flowchart.authorId === currentUserId

                      const cardData = cardExamples.get(flowchart.id)

                      const actions =
                        flowchart.source === 'hardcoded'
                          ? [
                              {
                                label: exportingPdfId === flowchart.id ? 'Exporting...' : 'PDF',
                                onClick: () => handleDownloadPDF(flowchart.id),
                                variant: 'secondary' as const,
                                disabled: exportingPdfId === flowchart.id,
                              },
                              {
                                label: 'Remix',
                                onClick: () => handleRemix(flowchart.id),
                                variant: 'secondary' as const,
                              },
                            ]
                          : isOwnFlowchart
                            ? [
                                {
                                  label: 'Edit',
                                  onClick: () => handleEditPublished(flowchart.id),
                                  variant: 'primary' as const,
                                },
                                {
                                  label: 'Remix',
                                  onClick: () => handleRemix(flowchart.id),
                                  variant: 'secondary' as const,
                                },
                              ]
                            : [
                                {
                                  label: 'Remix',
                                  onClick: () => handleRemix(flowchart.id),
                                  variant: 'secondary' as const,
                                },
                              ]

                      if (flowchart.hasEmbedding === false) {
                        const isGenerating = generatingEmbeddingIds.has(flowchart.id)
                        actions.push({
                          label: isGenerating ? 'Generating...' : 'Generate Embedding',
                          onClick: () => handleGenerateCardEmbedding(flowchart.id),
                          variant: 'secondary' as const,
                          disabled: isGenerating,
                        })
                      }

                      return (
                        <FlowchartCard
                          key={flowchart.id}
                          title={flowchart.title}
                          description={flowchart.description}
                          emoji={flowchart.emoji}
                          difficulty={flowchart.difficulty}
                          flowchart={cardData?.flowchart}
                          examples={cardData?.examples}
                          diagnosticReport={cardData?.diagnosticReport}
                          clusterColorIndex={clusterColorIndex}
                          onClick={() => handleCardClick(flowchart.id)}
                          actions={actions}
                        />
                      )
                    }

                    if (clusterAssignments) {
                      const clusteredIds = new Set(clusterAssignments.ids)
                      const elements: React.ReactNode[] = []

                      // Breadcrumb navigation (shows full path when drilled in)
                      if (scopePath.length > 0) {
                        elements.push(
                          <div
                            key="scope-nav"
                            className={css({
                              gridColumn: '1 / -1',
                              display: 'flex',
                              alignItems: 'center',
                              gap: '2',
                              marginBottom: '3',
                              flexWrap: 'wrap',
                            })}
                          >
                            {/* Root "All" link */}
                            <button
                              onClick={() => navigateToLevel(0)}
                              className={css({
                                display: 'flex',
                                alignItems: 'center',
                                gap: '1.5',
                                paddingX: '3',
                                paddingY: '1.5',
                                borderRadius: 'lg',
                                fontSize: 'sm',
                                fontWeight: 'medium',
                                color: { base: 'gray.600', _dark: 'gray.300' },
                                backgroundColor: { base: 'gray.100', _dark: 'gray.800' },
                                cursor: 'pointer',
                                transition: 'all 0.15s',
                                _hover: {
                                  backgroundColor: { base: 'gray.200', _dark: 'gray.700' },
                                },
                              })}
                            >
                              <span className={css({ fontSize: '12px' })}>←</span>
                              All
                            </button>
                            {/* Breadcrumb trail */}
                            {scopePath.map((level, index) => (
                              <div
                                key={index}
                                className={css({ display: 'flex', alignItems: 'center', gap: '2' })}
                              >
                                <span
                                  className={css({
                                    fontSize: 'sm',
                                    color: { base: 'gray.400', _dark: 'gray.500' },
                                  })}
                                >
                                  /
                                </span>
                                {index < scopePath.length - 1 ? (
                                  // Clickable intermediate breadcrumb
                                  <button
                                    onClick={() => navigateToLevel(index + 1)}
                                    className={css({
                                      fontSize: 'sm',
                                      fontWeight: 'medium',
                                      color: { base: 'gray.500', _dark: 'gray.400' },
                                      cursor: 'pointer',
                                      transition: 'color 0.15s',
                                      _hover: {
                                        color: { base: 'gray.700', _dark: 'gray.200' },
                                      },
                                    })}
                                  >
                                    {level.label}
                                  </button>
                                ) : (
                                  // Current level (not clickable)
                                  <span
                                    className={css({
                                      fontSize: 'sm',
                                      fontWeight: 'medium',
                                      color: { base: 'gray.700', _dark: 'gray.200' },
                                    })}
                                  >
                                    {level.label}
                                  </span>
                                )}
                              </div>
                            ))}
                          </div>
                        )
                      }

                      // First pass: separate singleton clusters from multi-item clusters
                      const singletonFlowcharts: PublishedFlowchart[] = []
                      const multiItemClusters: { ci: number; flowcharts: PublishedFlowchart[] }[] =
                        []

                      for (let ci = 0; ci < clusterAssignments.k; ci++) {
                        const clusterFlowcharts = publishedFlowcharts.filter(
                          (fc) => clusterAssignments.map.get(fc.id) === ci
                        )
                        if (clusterFlowcharts.length === 0) continue

                        if (clusterFlowcharts.length === 1) {
                          singletonFlowcharts.push(clusterFlowcharts[0])
                        } else {
                          multiItemClusters.push({ ci, flowcharts: clusterFlowcharts })
                        }
                      }

                      // Render multi-item clusters with headers
                      for (const { ci, flowcharts: clusterFlowcharts } of multiItemClusters) {
                        const color = CLUSTER_COLORS[ci % CLUSTER_COLORS.length]
                        const emojis = clusterAssignments.clusterEmojis[ci]

                        // Section header with insights
                        const topicLabel = clusterAssignments.clusterLabels[ci]
                        const runnerUps = clusterAssignments.clusterRunnerUps[ci]
                        const diversity = clusterAssignments.clusterDiversityScores[ci]
                        const isDiverse = diversity > 0.35
                        const clusterIds = clusterFlowcharts.map((fc) => fc.id)

                        // Build tooltip content
                        const tooltipContent = (
                          <div
                            className={css({
                              display: 'flex',
                              flexDirection: 'column',
                              gap: '2.5',
                            })}
                          >
                            {/* Diversity indicator */}
                            <div
                              className={css({ display: 'flex', alignItems: 'center', gap: '2' })}
                            >
                              <span className={css({ fontSize: 'xs', opacity: 0.7 })}>
                                {isDiverse ? '🌐' : '🎯'}
                              </span>
                              <span className={css({ fontSize: 'xs', color: 'gray.300' })}>
                                {isDiverse
                                  ? 'Diverse topics grouped together'
                                  : 'Focused on a specific topic'}
                              </span>
                            </div>

                            {/* Runner-up labels */}
                            {runnerUps.length > 0 && (
                              <div
                                className={css({
                                  display: 'flex',
                                  flexDirection: 'column',
                                  gap: '1',
                                })}
                              >
                                <span
                                  className={css({
                                    fontSize: 'xs',
                                    opacity: 0.5,
                                    textTransform: 'uppercase',
                                    letterSpacing: '0.05em',
                                  })}
                                >
                                  Also related to
                                </span>
                                <div
                                  className={css({ display: 'flex', flexWrap: 'wrap', gap: '1.5' })}
                                >
                                  {runnerUps.map((ru, i) => (
                                    <span
                                      key={i}
                                      className={css({
                                        fontSize: 'xs',
                                        paddingX: '2',
                                        paddingY: '0.5',
                                        borderRadius: 'full',
                                        backgroundColor: 'rgba(255,255,255,0.1)',
                                        color: 'gray.300',
                                      })}
                                    >
                                      {ru.label}
                                    </span>
                                  ))}
                                </div>
                              </div>
                            )}

                            {/* Cluster stats */}
                            <div
                              className={css({
                                fontSize: 'xs',
                                opacity: 0.5,
                                paddingTop: '1',
                                borderTop: '1px solid rgba(255,255,255,0.1)',
                              })}
                            >
                              {clusterFlowcharts.length} flowchart
                              {clusterFlowcharts.length !== 1 ? 's' : ''} in this group
                            </div>
                          </div>
                        )

                        elements.push(
                          <div
                            key={`cluster-header-${ci}`}
                            className={css({
                              gridColumn: '1 / -1',
                              display: 'flex',
                              alignItems: 'center',
                              gap: '3',
                              color: color.text,
                              fontSize: 'sm',
                              marginTop: ci > 0 ? '4' : '0',
                              marginBottom: '2',
                            })}
                          >
                            <span>{emojis.join(' ')}</span>
                            {topicLabel && (
                              <Tooltip
                                content={tooltipContent}
                                side="bottom"
                                align="start"
                                delayDuration={300}
                              >
                                <button
                                  className={css({
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '1.5',
                                    fontWeight: 'medium',
                                    cursor: 'help',
                                    background: 'none',
                                    border: 'none',
                                    padding: 0,
                                    color: 'inherit',
                                    transition: 'opacity 0.15s',
                                    _hover: { opacity: 0.8 },
                                  })}
                                >
                                  {topicLabel}
                                  <span
                                    className={css({
                                      fontSize: '10px',
                                      opacity: 0.5,
                                      transition: 'opacity 0.15s',
                                    })}
                                  >
                                    {isDiverse ? '🌐' : '🎯'}
                                  </span>
                                </button>
                              </Tooltip>
                            )}
                            <div
                              className={css({
                                flex: 1,
                                height: '1px',
                                backgroundColor: color.line,
                              })}
                            />
                            {clusterFlowcharts.length > gridColumnCount && (
                              <button
                                onClick={() => {
                                  navigateToScope(
                                    clusterIds,
                                    topicLabel || `${emojis[0] || ''} Cluster`
                                  )
                                }}
                                className={css({
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: '1',
                                  paddingX: '2',
                                  paddingY: '1',
                                  borderRadius: 'md',
                                  fontSize: 'xs',
                                  fontWeight: 'medium',
                                  color: color.text,
                                  backgroundColor: 'transparent',
                                  cursor: 'pointer',
                                  transition: 'all 0.15s',
                                  _hover: {
                                    backgroundColor: color.bg,
                                  },
                                })}
                              >
                                Explore
                                <span className={css({ fontSize: '10px' })}>→</span>
                              </button>
                            )}
                          </div>
                        )

                        // Cards in this cluster, sorted by match strength (best matches first)
                        const sortedClusterFlowcharts = [...clusterFlowcharts].sort((a, b) => {
                          const strengthA =
                            clusterAssignments.flowchartMatchStrengths.get(a.id) ?? 0
                          const strengthB =
                            clusterAssignments.flowchartMatchStrengths.get(b.id) ?? 0
                          return strengthB - strengthA // Descending order
                        })
                        for (const fc of sortedClusterFlowcharts) {
                          elements.push(renderPublishedCard(fc, ci))
                        }
                      }

                      // Render singletons under "Other topics" section
                      if (singletonFlowcharts.length > 0) {
                        elements.push(
                          <div
                            key="cluster-header-singletons"
                            className={css({
                              gridColumn: '1 / -1',
                              display: 'flex',
                              alignItems: 'center',
                              gap: '3',
                              color: { base: 'gray.500', _dark: 'gray.400' },
                              fontSize: 'sm',
                              marginTop: multiItemClusters.length > 0 ? '4' : '0',
                              marginBottom: '2',
                            })}
                          >
                            <span>Other topics</span>
                            <div
                              className={css({
                                flex: 1,
                                height: '1px',
                                backgroundColor: { base: 'gray.200', _dark: 'gray.700' },
                              })}
                            />
                          </div>
                        )
                        for (const fc of singletonFlowcharts) {
                          elements.push(renderPublishedCard(fc))
                        }
                      }

                      // Unclustered flowcharts (no embedding)
                      // When scoped, only show unclustered items within the scope
                      const scopeSet = scopedFlowchartIds ? new Set(scopedFlowchartIds) : null
                      const unclustered = publishedFlowcharts.filter(
                        (fc) => !clusteredIds.has(fc.id) && (!scopeSet || scopeSet.has(fc.id))
                      )
                      if (unclustered.length > 0) {
                        const missingEmbeddings = unclustered.some((fc) => !fc.hasEmbedding)
                        elements.push(
                          <div
                            key="cluster-header-unclustered"
                            className={css({
                              gridColumn: '1 / -1',
                              display: 'flex',
                              alignItems: 'center',
                              gap: '3',
                              color: { base: 'gray.500', _dark: 'gray.400' },
                              fontSize: 'sm',
                              marginTop: '4',
                              marginBottom: '2',
                            })}
                          >
                            <span>
                              {missingEmbeddings ? 'Unclustered \u2014 missing embeddings' : 'More'}
                            </span>
                            <div
                              className={css({
                                flex: 1,
                                height: '1px',
                                backgroundColor: { base: 'gray.200', _dark: 'gray.700' },
                              })}
                            />
                            {missingEmbeddings && (
                              <button
                                onClick={handleGenerateEmbeddings}
                                disabled={isGeneratingEmbeddings}
                                className={css({
                                  paddingY: '1',
                                  paddingX: '3',
                                  borderRadius: 'md',
                                  fontSize: 'xs',
                                  fontWeight: 'medium',
                                  border: '1px solid',
                                  borderColor: { base: 'gray.300', _dark: 'gray.600' },
                                  backgroundColor: { base: 'white', _dark: 'gray.800' },
                                  color: { base: 'gray.700', _dark: 'gray.300' },
                                  cursor: 'pointer',
                                  whiteSpace: 'nowrap',
                                  transition: 'all 0.15s',
                                  _hover: {
                                    backgroundColor: { base: 'gray.100', _dark: 'gray.700' },
                                  },
                                  _disabled: {
                                    opacity: 0.5,
                                    cursor: 'not-allowed',
                                  },
                                })}
                              >
                                {isGeneratingEmbeddings ? 'Generating...' : 'Generate Embeddings'}
                              </button>
                            )}
                          </div>
                        )
                        for (const fc of unclustered) {
                          elements.push(renderPublishedCard(fc))
                        }
                      }

                      return elements
                    }

                    // Fallback: no clustering data, render flat
                    return publishedFlowcharts.map((fc) => renderPublishedCard(fc))
                  })()}

                {/* Draft flowcharts */}
                {filter !== 'published' && draftSessions.length > 0 && (
                  <div
                    className={css({
                      gridColumn: '1 / -1',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '3',
                      color: { base: 'gray.500', _dark: 'gray.400' },
                      fontSize: 'sm',
                      marginTop: filter !== 'drafts' && publishedFlowcharts.length > 0 ? '4' : '0',
                      marginBottom: '2',
                    })}
                  >
                    <span>Drafts</span>
                    <div
                      className={css({
                        flex: 1,
                        height: '1px',
                        backgroundColor: { base: 'gray.200', _dark: 'gray.700' },
                      })}
                    />
                  </div>
                )}
                {filter !== 'published' &&
                  draftSessions.map((session) => {
                    const cardData = cardExamples.get(session.id)

                    return (
                      <FlowchartCard
                        key={session.id}
                        title={session.draftTitle || session.topicDescription || 'Untitled'}
                        emoji={session.draftEmoji || '📝'}
                        status={session.state === 'refining' ? 'In Progress' : 'Draft'}
                        subtitle={`Updated ${new Date(session.updatedAt).toLocaleDateString()}`}
                        onClick={() => handleResumeDraft(session.id)}
                        flowchart={cardData?.flowchart}
                        examples={cardData?.examples}
                        diagnosticReport={
                          cardData?.diagnosticReport ?? draftDiagnostics.get(session.id)
                        }
                        actions={[
                          {
                            label: 'Edit',
                            href: `/flowchart/workshop/${session.id}`,
                            variant: 'primary',
                          },
                          {
                            label: 'Delete',
                            onClick: () => handleDeleteDraft(session.id),
                            variant: 'danger',
                          },
                        ]}
                      />
                    )
                  })}

                {/* Empty state for drafts filter */}
                {filter === 'drafts' && !isLoadingDrafts && draftSessions.length === 0 && (
                  <div
                    className={css({
                      gridColumn: '1 / -1',
                      padding: '8',
                      textAlign: 'center',
                      color: { base: 'gray.500', _dark: 'gray.400' },
                    })}
                  >
                    <p>No drafts yet. Search for a topic above to create your first flowchart!</p>
                  </div>
                )}
              </>
            )}
          </div>
          {/* Close grid */}
        </div>
        {/* Close recessed well */}
      </div>
      {/* Close outer wrapper */}

      {/* Delete toast for undo functionality */}
      <DeleteToastContainer
        deletions={pendingDeletions}
        onUndo={handleUndoDelete}
        onConfirm={handleConfirmDelete}
      />

      {/* Modal for problem selection - state driven by URL query param */}
      <Dialog.Root
        open={isModalOpen}
        onOpenChange={(open) => {
          if (!open) handleClose()
        }}
      >
        <Dialog.Portal>
          <Dialog.Overlay
            className={css({
              backgroundColor: 'rgba(0, 0, 0, 0.6)',
              position: 'fixed',
              inset: 0,
              zIndex: 100,
            })}
          />

          {modalState.type === 'loading' && (
            <Dialog.Content
              className={css({
                position: 'fixed',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                backgroundColor: { base: 'white', _dark: 'gray.800' },
                borderRadius: '2xl',
                padding: '8',
                zIndex: 101,
                _focus: { outline: 'none' },
              })}
            >
              <Dialog.Title className={css({ srOnly: true })}>Loading Flowchart</Dialog.Title>
              <Dialog.Description className={css({ srOnly: true })}>
                Please wait while the flowchart loads
              </Dialog.Description>
              <div
                className={css({
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: { base: 'gray.500', _dark: 'gray.400' },
                })}
              >
                Loading...
              </div>
            </Dialog.Content>
          )}

          {modalState.type === 'error' && (
            <Dialog.Content
              className={css({
                position: 'fixed',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                backgroundColor: { base: 'white', _dark: 'gray.800' },
                borderRadius: '2xl',
                padding: '8',
                zIndex: 101,
                _focus: { outline: 'none' },
              })}
            >
              <Dialog.Title className={css({ srOnly: true })}>Error Loading Flowchart</Dialog.Title>
              <Dialog.Description className={css({ srOnly: true })}>
                An error occurred while loading the flowchart
              </Dialog.Description>
              <div className={vstack({ gap: '4', alignItems: 'center' })}>
                <p className={css({ color: { base: 'red.600', _dark: 'red.400' } })}>
                  {modalState.message}
                </p>
                <button
                  onClick={handleClose}
                  className={css({
                    paddingX: '4',
                    paddingY: '2',
                    borderRadius: 'md',
                    backgroundColor: { base: 'gray.200', _dark: 'gray.700' },
                    color: { base: 'gray.800', _dark: 'gray.200' },
                    border: 'none',
                    cursor: 'pointer',
                  })}
                >
                  Close
                </button>
              </div>
            </Dialog.Content>
          )}

          {modalState.type === 'inputting' &&
            (() => {
              const flowchartInfo = publishedFlowcharts.find(
                (fc) => fc.id === modalState.flowchartId
              )
              return (
                <FlowchartModal
                  flowchart={modalState.flowchart}
                  onSubmit={handleProblemSubmit}
                  onClose={handleClose}
                  shareUrl={
                    // Show share button for published flowcharts (hardcoded or database)
                    flowchartInfo
                      ? `${typeof window !== 'undefined' ? window.location.origin : ''}/flowchart?select=${modalState.flowchartId}`
                      : undefined
                  }
                  diagnosticReport={cardExamples.get(modalState.flowchartId)?.diagnosticReport}
                  flowchartId={modalState.flowchartId}
                  source={flowchartInfo?.source}
                  isOwnedByUser={flowchartInfo?.authorId === currentUserId}
                />
              )
            })()}
        </Dialog.Portal>
      </Dialog.Root>
    </div>
  )
}