introspectre 1.4.0

A GraphQL offensive-security engine: introspection-driven schema analysis, active vulnerability probing, and an interactive attack-surface report.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Introspectre - Actionable Schema Visualization</title>
    {{VENDOR_JS}}
    <style>
        :root {
            --bg: #0a0a0f;
            --bg-elev: #12121a;
            --panel: #0f1119;
            --border: #22253a;
            --text: #d7e0ea;
            --muted: #7a8296;
            --accent: #FCEE0A;
            --cyan: #00F0FF;
            --magenta: #FF2A6D;
            --high: #FF2A6D;
            --med: #FCEE0A;
            --low: #1BE7B5;
            --info: #00F0FF;
            --mono: ui-monospace, "Cascadia Code", "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", monospace;
            --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
        }

        body {
            margin: 0;
            padding: 0;
            font-family: var(--sans);
            background-color: var(--bg);
            color: var(--text);
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        h1, h2, h3, h4, h5, h6,
        button, .tag, .tab-btn, .toggle-btn, .graph-btn, .view-report-btn,
        .close-modal, .report-stat strong, .seed-group h4, .tree-label,
        #node-search, .instruction-toast b {
            font-family: var(--mono);
        }

        #cy {
            flex-grow: 1;
            height: 100%;
        }

        #sidebar {
            width: 450px;
            background-color: var(--panel);
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            padding: 20px;
            overflow-y: auto;
            box-shadow: 5px 0 15px rgba(0,0,0,0.6), 0 0 24px rgba(0,240,255,0.06);
        }

        .header {
            border-bottom: 1px solid var(--border);
            padding-bottom: 15px;
            margin-bottom: 20px;
        }

        .header h1 {
            font-size: 1.2rem;
            margin: 0;
            color: var(--accent);
            letter-spacing: 0.02em;
            text-shadow: 0 0 8px rgba(252,238,10,0.45), 0 0 20px rgba(252,238,10,0.15);
        }

        .header .meta {
            font-size: 0.8rem;
            color: var(--muted);
            margin-top: 5px;
        }

        .card {
            background-color: var(--bg-elev);
            border: 1px solid var(--border);
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .card h3 {
            margin-top: 0;
            font-size: 1rem;
        }

        .severity-high { border-left: 4px solid var(--high); box-shadow: inset 0 0 20px rgba(255,42,109,0.08); }
        .severity-medium { border-left: 4px solid var(--med); box-shadow: inset 0 0 20px rgba(252,238,10,0.06); }
        .severity-low { border-left: 4px solid var(--low); }
        .severity-info { border-left: 4px solid var(--info); }

        pre {
            background-color: var(--bg-elev);
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
            font-size: 0.85rem;
            border: 1px solid var(--border);
            font-family: var(--mono);
        }

        button {
            background-color: var(--bg-elev);
            border: 1px solid var(--border);
            color: var(--accent);
            padding: 5px 10px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.8rem;
            margin-right: 5px;
            margin-top: 5px;
        }

        button:hover {
            background-color: var(--border);
            border-color: var(--accent);
        }

        .finding-item {
            cursor: pointer;
            padding: 8px;
            border-radius: 4px;
            margin-bottom: 5px;
            border: 1px solid transparent;
        }

        .finding-item:hover {
            background-color: var(--bg-elev);
            border-color: var(--border);
        }

        .finding-item.active {
            background-color: rgba(0,240,255,0.12);
            border-color: var(--cyan);
        }

        .search-container {
            padding: 10px 0;
            position: relative;
        }
        #node-search {
            width: 100%;
            padding: 8px;
            border-radius: 4px;
            border: 1px solid var(--border);
            background: var(--bg-elev);
            color: var(--text);
            box-sizing: border-box;
        }
        #node-search:focus {
            outline: none;
            border-color: var(--cyan);
            box-shadow: 0 0 0 1px var(--cyan), 0 0 10px rgba(0,240,255,0.25);
        }
        #search-suggestions {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: var(--panel);
            border: 1px solid var(--border);
            max-height: 200px;
            overflow-y: auto;
            z-index: 10;
            box-shadow: 0 4px 12px rgba(0,0,0,0.5);
            border-radius: 4px;
        }
        .suggestion-item {
            padding: 8px;
            cursor: pointer;
            border-bottom: 1px solid var(--border);
        }
        .suggestion-item:hover {
            background-color: var(--border);
        }
        .semitransparent {
            opacity: 0.1 !important;
        }
        .toggle-group {
            display: inline-flex;
            margin-bottom: 10px;
            border-radius: 6px;
            overflow: hidden;
            border: 1px solid var(--border);
        }
        .toggle-btn {
            background-color: var(--bg-elev);
            color: var(--muted);
            border: none;
            padding: 5px 12px;
            cursor: pointer;
            font-size: 0.8rem;
            margin: 0;
            border-radius: 0;
        }
        .toggle-btn.active {
            background-color: var(--accent);
            color: var(--bg);
        }

        .highlighted-edge {
            line-color: var(--cyan) !important;
            target-arrow-color: var(--cyan) !important;
            width: 4px !important;
        }

        .tag {
            font-size: 0.7rem;
            padding: 2px 6px;
            border-radius: 10px;
            text-transform: uppercase;
            font-weight: bold;
            margin-right: 5px;
        }

        .tag-high { background-color: rgba(255,42,109,0.18); color: var(--high); }
        .tag-med { background-color: rgba(252,238,10,0.16); color: var(--med); }
        .tag-info { background-color: rgba(0,240,255,0.16); color: var(--info); }
        .tag-low { background-color: rgba(27,231,181,0.16); color: var(--low); }

        #details-pane {
            display: none;
        }

        .back-btn {
            margin-bottom: 15px;
            display: inline-block;
        }

        .graph-controls {
            position: absolute;
            bottom: 20px;
            right: 20px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            z-index: 100;
        }

        .graph-btn {
            background-color: var(--panel);
            border: 1px solid var(--border);
            color: var(--text);
            padding: 10px;
            border-radius: 8px;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0,0,0,0.5);
            font-size: 0.8rem;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .graph-btn:hover {
            background-color: var(--bg-elev);
            border-color: var(--accent);
        }

        .instruction-toast {
            position: absolute;
            top: 20px;
            right: 20px;
            max-width: 340px;
            background-color: rgba(15, 17, 25, 0.9);
            border: 1px solid var(--accent);
            padding: 10px 26px 10px 15px;
            border-radius: 8px;
            font-size: 0.8rem;
            color: var(--text);
            z-index: 100;
            pointer-events: none;
            box-shadow: 0 4px 15px rgba(0,0,0,0.5), 0 0 12px rgba(252,238,10,0.12);
        }

        .toast-close {
            position: absolute;
            top: 4px;
            right: 8px;
            cursor: pointer;
            pointer-events: auto;
            color: var(--muted);
            font-size: 1rem;
            line-height: 1;
        }

        .toast-close:hover {
            color: var(--accent);
        }

        #toast-reopen-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            display: none;
            font-weight: bold;
        }

        @media (max-width: 700px) {
            .instruction-toast {
                top: auto;
                bottom: 20px;
                left: 10px;
                right: 10px;
                max-width: none;
                font-size: 0.72rem;
            }
            #toast-reopen-btn {
                top: auto;
                bottom: 20px;
                right: 10px;
            }
        }

        .legend {
            position: absolute;
            top: auto;
            bottom: 20px;
            left: 20px;
            background-color: rgba(15, 17, 25, 0.9);
            border: 1px solid var(--border);
            border-radius: 8px;
            z-index: 100;
            box-shadow: 0 4px 15px rgba(0,0,0,0.5);
            font-size: 0.78rem;
            overflow: hidden;
            max-width: 220px;
        }

        .legend-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            padding: 8px 12px;
            cursor: pointer;
            color: var(--accent);
            font-family: var(--mono);
            font-weight: bold;
            user-select: none;
        }

        .legend-body {
            display: none;
            padding: 4px 12px 10px 12px;
            border-top: 1px solid var(--border);
        }

        .legend-body.expanded {
            display: block;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 3px 0;
            color: var(--text);
        }

        .legend-swatch {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            flex-shrink: 0;
            box-shadow: 0 0 4px rgba(0,0,0,0.6);
        }

        @media (max-width: 700px) {
            .legend {
                top: auto;
                bottom: 10px;
                left: 10px;
                max-width: 180px;
            }
        }

        /* Context Menu Styles */
        #ctx-menu {
            position: absolute;
            display: none;
            background-color: var(--panel);
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 5px 0;
            z-index: 2000;
            box-shadow: 0 8px 24px rgba(0,0,0,0.5);
            min-width: 160px;
        }

        .ctx-item {
            padding: 8px 15px;
            font-size: 0.85rem;
            color: var(--text);
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .ctx-item:hover {
            background-color: var(--accent);
            color: var(--bg);
        }

        .ctx-divider {
            height: 1px;
            background-color: var(--border);
            margin: 5px 0;
        }

        .btn-active {
            border-color: var(--accent) !important;
            color: var(--accent) !important;
        }

        /* Full Report Modal Styles */
        #report-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.85);
            z-index: 1000;
            overflow-y: auto;
            padding: 40px;
            box-sizing: border-box;
        }

        .modal-content {
            background-color: var(--panel);
            max-width: 1000px;
            margin: 40px auto;
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 40px;
            position: relative;
            box-shadow: 0 20px 50px rgba(0,0,0,0.5);
        }

        .close-modal {
            position: fixed;
            top: 25px;
            right: 25px;
            width: 44px;
            height: 44px;
            background-color: var(--accent);
            color: var(--bg);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.8rem;
            cursor: pointer;
            z-index: 2000;
            box-shadow: 0 4px 15px rgba(0,0,0,0.5), 0 0 16px rgba(252,238,10,0.35);
            transition: all 0.2s ease;
            line-height: 1;
        }

        .close-modal:hover {
            transform: scale(1.1);
            background-color: var(--cyan);
            box-shadow: 0 4px 15px rgba(0,0,0,0.5), 0 0 16px rgba(0,240,255,0.4);
        }

        .modal-footer {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid var(--border);
            display: flex;
            justify-content: center;
        }

        .report-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }

        .report-stat {
            background-color: var(--bg);
            padding: 15px;
            border-radius: 8px;
            border: 1px solid var(--border);
        }

        .report-stat strong {
            display: block;
            font-size: 0.8rem;
            color: var(--muted);
            margin-bottom: 5px;
        }

        .report-stat span {
            font-size: 1.2rem;
            font-weight: bold;
        }

        .view-report-btn {
            background-color: var(--accent);
            color: var(--bg);
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: bold;
            margin-top: 10px;
            width: 100%;
        }

        .view-report-btn:hover {
            opacity: 0.9;
            box-shadow: 0 0 14px rgba(252,238,10,0.35);
        }

        .seed-group {
            margin-bottom: 15px;
            padding: 10px;
            background: var(--bg-elev);
            border: 1px solid var(--border);
            border-radius: 6px;
        }

        .seed-group h4 {
            margin: 0 0 8px 0;
            font-size: 0.85rem;
            color: var(--accent);
        }

        .seed-item {
            font-size: 0.8rem;
            padding: 4px 8px;
            background: var(--bg);
            border-radius: 4px;
            margin-bottom: 4px;
            word-break: break-all;
            border: 1px solid transparent;
            font-family: var(--mono);
        }

        .seed-item:hover {
            border-color: var(--accent);
        }

        .swappable-value {
            color: var(--med);
            font-weight: bold;
            text-decoration: underline dotted;
            cursor: pointer;
            padding: 0 2px;
            border-radius: 2px;
        }

        .swappable-value:hover {
            background-color: rgba(252,238,10,0.18);
        }

        .value-dropdown {
            position: absolute;
            background: var(--panel);
            border: 1px solid var(--border);
            border-radius: 4px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.5);
            z-index: 2000;
            max-height: 150px;
            overflow-y: auto;
            min-width: 150px;
        }

        .dropdown-item {
            padding: 8px 12px;
            font-size: 0.8rem;
            cursor: pointer;
            border-bottom: 1px solid var(--border);
            font-family: var(--mono);
        }

        .dropdown-item:hover {
            background: var(--bg-elev);
            color: var(--accent);
        }

        /* Sidebar Tabs */
        .tab-header {
            display: flex;
            border-bottom: 1px solid var(--border);
            margin-bottom: 15px;
            gap: 5px;
        }

        .tab-btn {
            background: transparent;
            border: none;
            color: var(--muted);
            padding: 8px 12px;
            font-size: 0.8rem;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.2s;
        }

        .tab-btn:hover {
            color: var(--text);
        }

        .tab-btn.active {
            color: var(--accent);
            border-bottom-color: var(--accent);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        /* Tree View */
        .tree-container {
            font-family: var(--mono);
            font-size: 0.85rem;
        }

        .tree-node {
            margin-left: 15px;
            border-left: 1px solid var(--border);
        }

        .tree-item {
            padding: 4px 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            border-radius: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .tree-item:hover {
            background: var(--bg-elev);
        }

        .tree-item.selected {
            background: rgba(0,240,255,0.14);
            color: var(--cyan);
        }

        .tree-toggle {
            width: 16px;
            height: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.2s;
        }

        .tree-toggle.collapsed {
            transform: rotate(-90deg);
        }

        .tree-icon {
            font-size: 0.7rem;
            opacity: 0.7;
        }

        .tree-label {
            flex: 1;
        }

        .tree-type {
            color: var(--muted);
            font-size: 0.75rem;
            margin-left: auto;
        }
    </style>
</head>
<body>
    <div id="report-modal" onclick="if(event.target === this) closeReport()">
        <div class="close-modal" onclick="closeReport()">&times;</div>
        <div class="modal-content">
            <h2 style="margin-top:0">Full Security Analysis Report</h2>
            <div class="meta" id="report-meta-text"></div>
            <hr style="border: 0; border-top: 1px solid var(--border); margin: 20px 0;">
            
            <h3>Schema Statistics</h3>
            <div class="report-grid" id="report-stats-grid"></div>

            <h3>Vulnerability Details</h3>
            <div id="report-findings-content"></div>

            <div class="modal-footer">
                <button class="view-report-btn" style="width: auto; padding: 10px 30px;" onclick="closeReport()">Close Report</button>
            </div>
        </div>
    </div>

    <div id="sidebar">
        <div class="header">
            <h1>Introspectre Visual</h1>
            <div class="meta">Source: {{SOURCE}}</div>
            <button class="view-report-btn" onclick="openReport()">View Full Report Summary</button>
        </div>

        <div class="search-container">
            <input type="text" id="node-search" placeholder="Search types or fields..." autocomplete="off">
            <div id="search-suggestions"></div>
        </div>

        <div id="summary-pane">
            <div class="tab-header">
                <button class="tab-btn active" onclick="switchTab('findings')">Findings</button>
                <button class="tab-btn" onclick="switchTab('seeds')">Seeds</button>
                <button class="tab-btn" onclick="switchTab('schema')">Schema</button>
            </div>

            <div id="tab-findings" class="tab-content active">
                <div id="findings-list"></div>
            </div>

            <div id="tab-seeds" class="tab-content">
                <div id="seeds-list">
                    <div style="font-size: 0.8rem; color: var(--muted);">No seed data yet. Supply real values with <code>--seed-traffic &lt;burp.xml|.har&gt;</code> or <code>--seeds &lt;file.json&gt;</code> so active probes use realistic input instead of placeholders.</div>
                </div>
            </div>

            <div id="tab-schema" class="tab-content">
                <div id="schema-tree" class="tree-container"></div>
            </div>
        </div>

        <div id="details-pane">
            <button class="back-btn" onclick="showSummary()">← Back to list</button>
            <div id="details-content"></div>
        </div>
    </div>
    <div id="cy"></div>
    <div id="ctx-menu">
        <div class="ctx-item" onclick="ctxExpandNode()">Expand Relations</div>
        <div class="ctx-item" onclick="ctxExpandAll()">Expand All Children</div>
        <div class="ctx-divider"></div>
        <div class="ctx-item" onclick="ctxTraceRoot()">Trace Path to Root</div>
        <div class="ctx-item" onclick="ctxHideNode()">Hide Node</div>
    </div>
    <div class="graph-controls">
        <button class="graph-btn" id="filter-scalars-btn" onclick="toggleScalars()">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8z"/></svg>
            Scalars: SHOWN
        </button>
        <button class="graph-btn" id="isolate-mode-btn" onclick="toggleIsolateMode()">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 8a3 3 0 100-6 3 3 0 000 6zm6 5c0-2.21-3.13-4-7-4s-7 1.79-7 4v1h14v-1z"/></svg>
            Isolate Mode: OFF
        </button>
        <button class="graph-btn" onclick="resetGraph()">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 3.5a4.5 4.5 0 104.5 4.5H11l3 3.5 3-3.5h-1.5a6 6 0 11-6-6V3.5z"/></svg>
            Reset Graph
        </button>
        <button class="graph-btn" onclick="showAllNodes()">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0a8 8 0 100 16A8 8 0 008 0zM1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0z"/></svg>
            Show All
        </button>
        <button class="graph-btn" onclick="undoGraph()" title="Undo (Ctrl+Z)">
            ↶ Back
        </button>
        <button class="graph-btn" onclick="redoGraph()" title="Redo (Ctrl+Y)">
            ↷ Forward
        </button>
    </div>
    <div class="legend" id="legend-panel">
        <div class="legend-header" onclick="toggleLegend()">
            <span>Legend</span>
            <span id="legend-toggle-icon"></span>
        </div>
        <div class="legend-body" id="legend-body">
            <div class="legend-item"><span class="legend-swatch" style="background:#FF2A6D;"></span> High risk</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#FCEE0A;"></span> Medium risk</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#00F0FF;"></span> Info</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#B967FF;"></span> Mutation-type field</div>
            <div class="legend-item" style="margin-top:4px;opacity:.7;font-size:11px;">Ring color = type kind:</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#B7C3E8; border-radius:50%; border:2px solid #C9D2E8; box-sizing:border-box;"></span> grey ring = Object</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#B7C3E8; border-radius:50%; border:2px solid #F5A623; box-sizing:border-box;"></span> amber ring = Input object</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#B7C3E8; border-radius:50%; border:2px solid #58C97A; box-sizing:border-box;"></span> green ring = Interface</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#B7C3E8; border-radius:50%; border:2px solid #FF8AC4; box-sizing:border-box;"></span> pink ring = Union</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#B7C3E8; border-radius:50%; border:2px solid #FF8A3D; box-sizing:border-box;"></span> orange ring = Enum / Scalar</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#FFFFFF; border-radius:50%; border:2px solid #00F0FF; box-sizing:border-box;"></span> ◎ cyan ring = Root Query</div>
            <div class="legend-item"><span class="legend-swatch" style="background:#FFFFFF; border-radius:50%; border:2px solid #B967FF; box-sizing:border-box;"></span> ◎ purple ring = Root Mutation</div>
        </div>
    </div>
    <div class="instruction-toast" id="instruction-toast">
        <span class="toast-close" onclick="hideToastPermanently()" title="Dismiss">&times;</span>
        <b>Tip:</b> Double-click a node to expand · single-click to inspect · hover to highlight.<br>
        Nodes are <b>types</b> (shown once); edges are field names.<br>
        Scroll to zoom, drag to pan, drag a node to reposition it. Use <b>Isolate Mode</b> to focus one path.
        <br>Scalars &amp; enums (leaf value types) are <b>hidden by default</b> to cut clutter and keep the focus on the object/relationship attack surface — click <b>Scalars: HIDDEN</b> in the toolbar to reveal them.
    </div>
    <button class="graph-btn" id="toast-reopen-btn" onclick="showInstructionToast()" title="Show tips">?</button>

    <script>
        const graphData = {{GRAPH_DATA}};
        const findingsData = {{FINDINGS_DATA}};
        const statsData = {{STATS}};
        const metaData = {{META}};
        const seedsData = {{SEEDS_DATA}};

        // Master lists for quick lookup
        const masterNodes = graphData.nodes;
        const masterEdges = graphData.edges.map(e => ({
            ...e,
            id: `${e.source}-${e.target}-${e.label}`
        }));

        function openReport() {
            const modal = document.getElementById('report-modal');
            const statsGrid = document.getElementById('report-stats-grid');
            const findingsContent = document.getElementById('report-findings-content');
            const metaText = document.getElementById('report-meta-text');

            // Set meta info
            metaText.innerHTML = `Source: ${metaData.source} | Mode: ${metaData.offline ? 'Offline' : 'Live'}`;

            // Set stats
            statsGrid.innerHTML = `

                <div class="report-stat"><strong>Total Types</strong><span>${statsData.total_types}</span></div>

                <div class="report-stat"><strong>Queries</strong><span>${statsData.queries}</span></div>

                <div class="report-stat"><strong>Mutations</strong><span>${statsData.mutations}</span></div>

                <div class="report-stat"><strong>Total Fields</strong><span>${statsData.total_fields}</span></div>

            `;

            // Set findings
            let html = "";
            findingsData.forEach(f => {
                html += `

                    <div class="card severity-${f.severity.toLowerCase()}">

                        <h3>[${f.severity}] ${f.title} <span class="id">${f.id}</span></h3>

                        <p>${f.description}</p>

                        <h4>Affected</h4>

                        <ul>${f.affected.map(a => `<li>${a}</li>`).join('')}</ul>

                        <h4>Remediation</h4>

                        <p style="color: var(--low)">${f.remediation}</p>

                    </div>

                `;
            });
            findingsContent.innerHTML = html;

            modal.style.display = 'block';
        }

        function closeReport() {
            document.getElementById('report-modal').style.display = 'none';
        }

        // --- Graph engine state (graphology + Sigma) ---
        let graph = new graphology.Graph({ multi: true, type: "directed" });
        let renderer = null;
        let highlightedNodes = new Set();
        let hoveredNode = null;
        let draggedNode = null;
        let didDrag = false;

        function nodeSize(n) {
            let base = 9; // info / other (nudged up slightly for label legibility)
            if (n.risk === 'high') base = 15;
            else if (n.risk === 'medium') base = 12;
            else if (n.kind === 'SCALAR' || n.kind === 'ENUM') base = 7;
            if (n.isRoot) base += 6;
            return base;
        }

        // Precedence: root wins over risk/opType, so root nodes are always
        // visually distinct (white fill) — their role (Query vs Mutation) is
        // instead encoded via the ring color (see nodeRingColor / nodeAttrs below).
        function nodeColor(n) {
            if (n.isRoot) return '#FFFFFF';
            if (n.risk === 'high') return '#FF2A6D';
            if (n.risk === 'medium') return '#FCEE0A';
            if (n.opType === 'mutation') return '#B967FF';
            if (n.risk === 'info') return '#00F0FF';
            if (n.kind === 'SCALAR' || n.kind === 'ENUM') return '#8792AC';
            return '#B7C3E8';
        }

        // Every node renders through the bordered (circle+ring) program — it needs no
        // texture, so nothing can render invisible. Fill color encodes risk; the ring
        // color encodes the GraphQL kind (roots keep their cyan/purple role ring).
        function nodeRingColor(n) {
            if (n.isRoot) return n.opType === 'mutation' ? '#B967FF' : '#00F0FF';
            switch (n.kind) {
                case 'INPUT_OBJECT': return '#F5A623'; // amber
                case 'INTERFACE':    return '#58C97A'; // green
                case 'UNION':        return '#FF8AC4'; // pink
                case 'ENUM':
                case 'SCALAR':       return '#FF8A3D'; // orange
                default:             return '#C9D2E8'; // OBJECT + anything else: light grey
            }
        }

        function nodeAttrs(n, x, y) {
            const color = nodeColor(n);
            return {
                label: n.label || n.id,
                size: nodeSize(n),
                color: color,
                type: 'bordered',
                borderColor: nodeRingColor(n),
                x: x,
                y: y,
                kind: n.kind,
                risk: n.risk,
                isRoot: !!n.isRoot,
                isSensitive: !!n.isSensitive,
                authRequired: !!n.authRequired,
                opType: n.opType,
                hasHidden: false,
                // Root and high-risk nodes always show their label, even when
                // zoomed out past labelRenderedSizeThreshold.
                forceLabel: !!n.isRoot || n.risk === 'high'
            };
        }

        function edgeAttrs(e) {
            return {
                label: e.label,
                size: 3,
                color: e.isDeprecated ? '#555' : '#5A6580',
                isDeprecated: !!e.isDeprecated,
                args: e.args,
                weight: e.weight
            };
        }

        function addMasterNodeToGraph(id, nearPos, exact) {
            const n = masterNodes.find(m => m.id === id);
            if (!n) return false;
            let x, y;
            if (nearPos && exact) {
                x = nearPos.x;
                y = nearPos.y;
            } else if (nearPos) {
                x = nearPos.x + (Math.random() - 0.5) * 0.6;
                y = nearPos.y + (Math.random() - 0.5) * 0.6;
            } else {
                x = Math.random();
                y = Math.random();
            }
            graph.addNode(id, nodeAttrs(n, x, y));
            return true;
        }

        function addMasterEdgeToGraph(e) {
            graph.addEdgeWithKey(e.id, e.source, e.target, edgeAttrs(e));
        }

        function runForceAtlas(opts) {
            const n = graph.order;
            if (n === 0) return;
            const iterations = (opts && opts.iterations) ? opts.iterations : (n < 400 ? 200 : 100);
            // preserveExisting: keep already-placed nodes fixed so only newly-added
            // nodes get laid out (prevents reveal/expand from scattering manual drags).
            let snapshot = null;
            if (opts && opts.preserveExisting) {
                snapshot = {};
                graph.forEachNode((id, a) => { snapshot[id] = { x: a.x, y: a.y }; });
            }
            try {
                const settings = graphologyLibrary.layoutForceAtlas2.inferSettings(graph);
                graphologyLibrary.layoutForceAtlas2.assign(graph, { iterations, settings });
            } catch (err) {
                console.error('ForceAtlas2 layout failed:', err);
            }
            if (snapshot) {
                for (const id in snapshot) {
                    if (graph.hasNode(id)) {
                        graph.setNodeAttribute(id, 'x', snapshot[id].x);
                        graph.setNodeAttribute(id, 'y', snapshot[id].y);
                    }
                }
            }
        }

        // rebuildVisibleGraph: clears the visible graph and repopulates it from the
        // given master nodes/edges (only edges whose both endpoints are present are added),
        // then lays it out with ForceAtlas2.
        function rebuildVisibleGraph(nodes, edges) {
            graph.clear();
            nodes.forEach(n => {
                if (!graph.hasNode(n.id)) {
                    addMasterNodeToGraph(n.id, null);
                }
            });
            edges.forEach(e => {
                if (graph.hasNode(e.source) && graph.hasNode(e.target) && !graph.hasEdge(e.id)) {
                    addMasterEdgeToGraph(e);
                }
            });
            runForceAtlas();
            updateExpandableMarkers();
            if (renderer) renderer.refresh();
        }

        // --- Highlight helpers (used by reducers below) ---
        function clearHighlight() {
            highlightedNodes = new Set();
            if (renderer) renderer.refresh();
        }
        function setHighlight(ids) {
            highlightedNodes = new Set(ids);
            if (renderer) renderer.refresh();
        }
        function addHighlight(id) {
            highlightedNodes.add(id);
            if (renderer) renderer.refresh();
        }

        function nodeReducer(node, data) {
            const res = { ...data };
            if (highlightedNodes.size > 0) {
                if (highlightedNodes.has(node)) {
                    res.highlighted = true;
                    res.zIndex = 1;
                    res.size = data.size + 2;
                } else {
                    res.color = '#2a2f3f';
                    res.label = '';
                    res.zIndex = 0;
                }
            }
            if (data.hasHidden) {
                res.size = (res.size || data.size) + 2;
            }
            return res;
        }

        function edgeReducer(edge, data) {
            const res = { ...data };
            if (highlightedNodes.size > 0) {
                const extremities = graph.extremities(edge);
                const touches = extremities.every(n => highlightedNodes.has(n));
                if (touches) {
                    res.color = '#00F0FF';
                    res.size = 4;
                    res.zIndex = 1;
                } else {
                    res.color = '#33384a';
                    res.zIndex = 0;
                }
            }
            return res;
        }

        // Custom hover renderer: Sigma's built-in default hover box is drawn with a
        // light (#FFF) fill, which made our light labelColor text disappear on hover.
        // This mirrors Sigma's default hover drawing routine (rounded label box +
        // label text) but with a DARK box + cyan border so the light label text stays
        // readable against it.
        function defaultDrawNodeHover(context, data, settings) {
            const size = settings.labelSize;
            const font = settings.labelFont;
            const weight = settings.labelWeight;
            context.font = `${weight} ${size}px ${font}`;

            context.fillStyle = '#0a0a0f';
            context.strokeStyle = '#00F0FF';
            context.lineWidth = 1;
            context.shadowOffsetX = 0;
            context.shadowOffsetY = 0;
            context.shadowBlur = 8;
            context.shadowColor = '#000';

            const PADDING = 2;

            if (typeof data.label === 'string' && data.label.length > 0) {
                const textWidth = context.measureText(data.label).width;
                const boxWidth = Math.round(textWidth + 5);
                const boxHeight = Math.round(size + 2 * PADDING);
                const radius = Math.max(data.size, size / 2) + PADDING;
                const angleRadian = Math.asin(boxHeight / 2 / radius);
                const xDeltaCoord = Math.sqrt(Math.abs(Math.pow(radius, 2) - Math.pow(boxHeight / 2, 2)));

                context.beginPath();
                context.moveTo(data.x + xDeltaCoord, data.y + boxHeight / 2);
                context.lineTo(data.x + radius + boxWidth, data.y + boxHeight / 2);
                context.lineTo(data.x + radius + boxWidth, data.y - boxHeight / 2);
                context.lineTo(data.x + xDeltaCoord, data.y - boxHeight / 2);
                context.arc(data.x, data.y, radius, angleRadian, -angleRadian);
                context.closePath();
                context.fill();
                context.shadowOffsetX = 0;
                context.shadowOffsetY = 0;
                context.shadowBlur = 0;
                context.stroke();
            } else {
                context.beginPath();
                context.arc(data.x, data.y, data.size + PADDING, 0, Math.PI * 2);
                context.closePath();
                context.fill();
                context.shadowOffsetX = 0;
                context.shadowOffsetY = 0;
                context.shadowBlur = 0;
                context.stroke();
            }

            // Draw the label text (light color) on top of the dark box.
            if (data.label) {
                const labelColorAttr = settings.labelColor && settings.labelColor.attribute
                    ? (data[settings.labelColor.attribute] || settings.labelColor.color || '#d7e0ea')
                    : (settings.labelColor ? settings.labelColor.color : '#d7e0ea');
                context.fillStyle = labelColorAttr;
                context.font = `${weight} ${size}px ${font}`;
                context.fillText(data.label, data.x + data.size + 3, data.y + size / 3);
            }
        }

        // Every node uses the bordered (circle + ring) program: it needs no texture, so
        // nothing can render invisible. Fill color = risk; ring color = kind (nodeRingColor).
        // Ships inside the vendored sigma.min.js UMD bundle as Sigma.rendering.*.
        const R = Sigma.rendering;
        const BorderedProgram = R.createNodeBorderProgram({
            borders: [
                { size: { value: 0.18 }, color: { attribute: 'borderColor' } },
                { size: { fill: true },  color: { attribute: 'color' } }
            ]
        });

        const sigmaSettings = {
            defaultEdgeType: "arrow",
            renderLabels: true,
            labelColor: { color: "#d7e0ea" },
            labelFont: 'ui-monospace, "Cascadia Code", "JetBrains Mono", Consolas, monospace',
            labelRenderedSizeThreshold: 4,
            labelDensity: 0.8,
            labelGridCellSize: 60,
            defaultEdgeColor: "#5A6580",
            minCameraRatio: 0.05,
            maxCameraRatio: 12,
            allowInvalidContainer: true,
            nodeProgramClasses: { circle: R.NodeCircleProgram, bordered: BorderedProgram },
            nodeReducer,
            edgeReducer,
            defaultDrawNodeHover
        };

        try {
            renderer = new Sigma(graph, document.getElementById('cy'), sigmaSettings);
        } catch (err) {
            console.warn('Sigma failed to init with arrow edge type, retrying with line edges', err);
            sigmaSettings.defaultEdgeType = 'line';
            renderer = new Sigma(graph, document.getElementById('cy'), sigmaSettings);
        }

        function centerOnNode(nodeId, ratio) {
            if (!graph.hasNode(nodeId) || !renderer) return;
            const nd = renderer.getNodeDisplayData(nodeId);
            if (nd) {
                renderer.getCamera().animate({ x: nd.x, y: nd.y, ratio: ratio || 0.3 }, { duration: 500 });
            }
        }

        // Reuse the instruction toast to briefly show progressive-expansion notices.
        const instructionToastEl = document.getElementById('instruction-toast');
        const toastReopenBtnEl = document.getElementById('toast-reopen-btn');
        const defaultToastHTML = instructionToastEl ? instructionToastEl.innerHTML : '';
        let toastTimer = null;

        function armAutoHide() {
            clearTimeout(toastTimer);
            toastTimer = setTimeout(hideToastPermanently, 8000);
        }

        function hideToastPermanently() {
            clearTimeout(toastTimer);
            if (instructionToastEl) instructionToastEl.style.display = 'none';
            if (toastReopenBtnEl) toastReopenBtnEl.style.display = 'flex';
        }

        function showInstructionToast() {
            if (!instructionToastEl) return;
            instructionToastEl.innerHTML = defaultToastHTML;
            instructionToastEl.style.display = 'block';
            if (toastReopenBtnEl) toastReopenBtnEl.style.display = 'none';
            armAutoHide();
        }

        function showToast(msg, duration) {
            if (!instructionToastEl) return;
            instructionToastEl.style.display = 'block';
            if (toastReopenBtnEl) toastReopenBtnEl.style.display = 'none';
            instructionToastEl.innerHTML = `<span class="toast-close" onclick="hideToastPermanently()" title="Dismiss">&times;</span><b>Note:</b> ${msg}`;
            clearTimeout(toastTimer);
            toastTimer = setTimeout(() => {
                instructionToastEl.innerHTML = defaultToastHTML;
                armAutoHide();
            }, duration || 3000);
        }

        // Auto-hide the tip toast a few seconds after load; the "?" button re-shows it.
        armAutoHide();

        function toggleLegend() {
            const body = document.getElementById('legend-body');
            const icon = document.getElementById('legend-toggle-icon');
            if (!body) return;
            const expanded = body.classList.toggle('expanded');
            if (icon) icon.textContent = expanded ? '' : '';
        }

        // Shims exposing the old cytoscape node/edge wrapper API (.id()/.data()) so callers written against it keep working unchanged.
        function makeNodeShim(nodeObj) {
            return { id: () => nodeObj.id, data: (key) => nodeObj[key] };
        }
        function makeEdgeShim(edgeData) {
            return {
                data: () => edgeData,
                source: () => ({ id: () => edgeData.source }),
                target: () => ({ id: () => edgeData.target })
            };
        }

        // --- Undo / redo history for visible-graph mutations ---
        let historyStack = [];
        let redoStack = [];
        const HISTORY_MAX = 50;

        function snapshotGraph() {
            return { nodeIds: graph.nodes(), edgeIds: graph.edges() };
        }

        function pushHistory() {
            historyStack.push(snapshotGraph());
            if (historyStack.length > HISTORY_MAX) historyStack.shift();
            redoStack = [];
        }

        function restoreSnapshot(snap) {
            const nodes = snap.nodeIds.map(id => masterNodes.find(n => n.id === id)).filter(Boolean);
            const edges = snap.edgeIds.map(id => masterEdges.find(e => e.id === id)).filter(Boolean);
            rebuildVisibleGraph(nodes, edges);
        }

        function undoGraph() {
            if (!historyStack.length) return;
            redoStack.push(snapshotGraph());
            restoreSnapshot(historyStack.pop());
        }

        function redoGraph() {
            if (!redoStack.length) return;
            historyStack.push(snapshotGraph());
            restoreSnapshot(redoStack.pop());
        }

        function resetGraph() {
            pushHistory();
            const rootNodes = masterNodes.filter(n => n.isRoot);
            const nodesToAdd = hideScalars
                ? rootNodes.filter(n => n.kind !== 'SCALAR' && n.kind !== 'ENUM')
                : rootNodes;
            rebuildVisibleGraph(nodesToAdd, []);
        }

        function showAllNodes() {
            if (masterNodes.length > 150 && !confirm(`This schema has ${masterNodes.length} types and ${masterEdges.length} relations. Rendering everything at once may be heavy. Continue?`)) return;

            pushHistory();

            let nodesToAdd = masterNodes;
            let edgesToAdd = masterEdges;

            if (hideScalars) {
                nodesToAdd = masterNodes.filter(n => n.kind !== 'SCALAR' && n.kind !== 'ENUM');
                edgesToAdd = masterEdges.filter(e => {
                    const target = masterNodes.find(n => n.id === e.target);
                    return target && target.kind !== 'SCALAR' && target.kind !== 'ENUM';
                });
            }

            rebuildVisibleGraph(nodesToAdd, edgesToAdd);
        }

        let hideScalars = true; // Default to true to reduce clutter
        function toggleScalars() {
            hideScalars = !hideScalars;
            const btn = document.getElementById('filter-scalars-btn');
            btn.innerHTML = hideScalars ?
                `<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8z"/></svg> Scalars: HIDDEN` :
                `<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8z"/></svg> Scalars: SHOWN`;
            btn.classList.toggle('btn-active', hideScalars);

            if (hideScalars) {
                pushHistory();
                const toRemove = [];
                graph.forEachNode((id, attrs) => {
                    if (attrs.kind === 'SCALAR' || attrs.kind === 'ENUM') toRemove.push(id);
                });
                toRemove.forEach(id => graph.dropNode(id));
                updateExpandableMarkers();
                if (renderer) renderer.refresh();
            }
        }

        // Initialize Scalar button state
        document.getElementById('filter-scalars-btn').classList.add('btn-active');
        document.getElementById('filter-scalars-btn').innerHTML = `<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8z"/></svg> Scalars: HIDDEN`;

        const EXPAND_CAP = 15;

        function rankByRisk(edges) {
            const riskRank = r => r === 'high' ? 3 : r === 'medium' ? 2 : r === 'info' ? 1 : 0;
            return edges.slice().sort((a, b) => {
                const an = masterNodes.find(n => n.id === a.target);
                const bn = masterNodes.find(n => n.id === b.target);
                const ar = an ? riskRank(an.risk) : 0;
                const br = bn ? riskRank(bn.risk) : 0;
                if (br !== ar) return br - ar;
                return a.target.localeCompare(b.target);
            });
        }

        // Reveals outgoing edges/nodes from nodeId. If capLimit is finite and there are
        // more newly-revealable edges than that, only the top capLimit (by target risk,
        // then name) are added.
        function revealFromNode(nodeId, capLimit) {
            let outgoing = masterEdges.filter(e => e.source === nodeId);

            if (hideScalars) {
                outgoing = outgoing.filter(e => {
                    const target = masterNodes.find(n => n.id === e.target);
                    return target && target.kind !== 'SCALAR' && target.kind !== 'ENUM';
                });
            }

            const newOutgoing = outgoing.filter(e => !graph.hasNode(e.target) || !graph.hasEdge(e.id));
            let toReveal = newOutgoing;
            let capped = false;
            if (isFinite(capLimit) && newOutgoing.length > capLimit) {
                capped = true;
                toReveal = rankByRisk(newOutgoing).slice(0, capLimit);
            }

            if (toReveal.length === 0) return { added: 0, capped: false, total: newOutgoing.length };

            const parentPos = graph.hasNode(nodeId)
                ? { x: graph.getNodeAttribute(nodeId, 'x'), y: graph.getNodeAttribute(nodeId, 'y') }
                : null;

            // New (not-yet-present) targets get placed on an angle-spaced ring around
            // the parent so a large batch (e.g. a root's children) fans out instead of
            // stacking on the parent and staying compressed under the pinned relax pass.
            const newTargets = toReveal.filter(e => !graph.hasNode(e.target));
            const k = newTargets.length;

            // Estimate a layout spacing unit from the current graph extent.
            let unit = 8;
            if (parentPos && graph.order > 1) {
                let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
                graph.forEachNode((id, a) => {
                    if (a.x < minX) minX = a.x; if (a.x > maxX) maxX = a.x;
                    if (a.y < minY) minY = a.y; if (a.y > maxY) maxY = a.y;
                });
                const diag = Math.hypot(maxX - minX, maxY - minY);
                unit = diag > 1e-3 ? diag / Math.sqrt(graph.order) : 8;
            }
            const R = unit * Math.min(1.7 + k * 0.22, 5.5);
            // Deterministic-ish angular offset per parent so repeated expands don't all
            // start at angle 0.
            let parentHash = 0;
            for (let i = 0; i < nodeId.length; i++) parentHash = (parentHash + nodeId.charCodeAt(i)) % 360;
            const angOffset = (parentHash / 360) * 2 * Math.PI;

            let added = 0;
            let ringIdx = 0;
            toReveal.forEach(e => {
                if (!graph.hasNode(e.target)) {
                    let pos = parentPos;
                    if (parentPos && k > 0) {
                        const ang = (ringIdx / k) * 2 * Math.PI + angOffset;
                        pos = {
                            x: parentPos.x + R * Math.cos(ang) + (Math.random() - 0.5) * 0.3,
                            y: parentPos.y + R * Math.sin(ang) + (Math.random() - 0.5) * 0.3
                        };
                        ringIdx++;
                    }
                    if (addMasterNodeToGraph(e.target, pos, true)) added++;
                }
                if (!graph.hasEdge(e.id) && graph.hasNode(e.source) && graph.hasNode(e.target)) {
                    addMasterEdgeToGraph(e);
                    added++;
                }
            });

            return { added, capped, total: newOutgoing.length };
        }

        function expandNode(nodeId) {
            pushHistory();

            const result = revealFromNode(nodeId, EXPAND_CAP);

            if (result.added > 0) {
                runForceAtlas({ iterations: Math.min(120, 40 + result.added * 2), preserveExisting: true });
                updateExpandableMarkers();
                if (renderer) renderer.refresh();
            }

            if (result.capped) {
                showToast(`Showing ${EXPAND_CAP} of ${result.total}  right-click  Expand all`);
            }
        }

        // Context Menu Logic
        let selectedNodeId = null;

        window.addEventListener('click', function() {
            document.getElementById('ctx-menu').style.display = 'none';
        });

        function ctxExpandNode() {
            if (selectedNodeId) expandNode(selectedNodeId);
        }

        function ctxExpandAll() {
            if (!selectedNodeId) return;

            let totalAdded = 0;
            const expandRecursive = (id, depth) => {
                if (depth > 3) return;
                const r = revealFromNode(id, Infinity);
                totalAdded += r.added;
                const children = masterEdges.filter(e => e.source === id).map(e => e.target);
                children.forEach(c => expandRecursive(c, depth + 1));
            };

            expandRecursive(selectedNodeId, 0);

            if (totalAdded > 0) {
                runForceAtlas({ iterations: 100 });
                updateExpandableMarkers();
                if (renderer) renderer.refresh();
            }
        }

        function ctxTraceRoot() {
            if (selectedNodeId) ensurePathVisible(selectedNodeId);
        }

        function ctxHideNode() {
            if (selectedNodeId && graph.hasNode(selectedNodeId)) {
                graph.dropNode(selectedNodeId);
                updateExpandableMarkers();
                if (renderer) renderer.refresh();
            }
        }

        function updateExpandableMarkers() {
            graph.forEachNode((id) => {
                const hasOutgoingInMaster = masterEdges.some(e => e.source === id);
                const allOutgoingShown = masterEdges
                    .filter(e => e.source === id)
                    .every(e => graph.hasEdge(e.id));
                graph.setNodeAttribute(id, 'hasHidden', hasOutgoingInMaster && !allOutgoingShown);
            });
        }

        let isolateMode = false;
        function toggleIsolateMode() {
            isolateMode = !isolateMode;
            const btn = document.getElementById('isolate-mode-btn');
            btn.innerHTML = isolateMode ? 
                `<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 8a3 3 0 100-6 3 3 0 000 6zm6 5c0-2.21-3.13-4-7-4s-7 1.79-7 4v1h14v-1z"/></svg> Isolate Mode: ON` : 
                `<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 8a3 3 0 100-6 3 3 0 000 6zm6 5c0-2.21-3.13-4-7-4s-7 1.79-7 4v1h14v-1z"/></svg> Isolate Mode: OFF`;
            btn.style.borderColor = isolateMode ? 'var(--accent)' : 'var(--border)';
        }

        function getFullPathDiscovery(targetId) {
            const rootIds = masterNodes.filter(n => n.isRoot).map(n => n.id);
            
            // 1. Find the shortest path from any root to the target
            let shortestPath = null;
            let queue = rootIds.map(id => [id]);
            let visited = new Set(rootIds);

            while (queue.length > 0) {
                let path = queue.shift();
                let last = path[path.length - 1];

                if (last === targetId) {
                    shortestPath = path;
                    break;
                }

                masterEdges.filter(e => e.source === last).forEach(e => {
                    if (!visited.has(e.target)) {
                        visited.add(e.target);
                        queue.push([...path, e.target]);
                    }
                });
            }

            // 2. Find ALL downstream successors recursively
            let successors = new Set();
            let succEdges = new Set();
            const stack = [targetId];
            const seen = new Set();

            while (stack.length > 0) {
                const current = stack.pop();
                if (seen.has(current)) continue;
                seen.add(current);
                successors.add(current);

                let outgoing = masterEdges.filter(e => e.source === current);
                if (hideScalars) {
                    outgoing = outgoing.filter(e => {
                        const tNode = masterNodes.find(n => n.id === e.target);
                        return tNode && tNode.kind !== 'SCALAR' && tNode.kind !== 'ENUM';
                    });
                }

                outgoing.forEach(e => {
                    succEdges.add(e.id);
                    stack.push(e.target);
                });
            }

            // 3. Collect final set of nodes and edges
            const nodesSet = new Set(shortestPath || [targetId]);
            successors.forEach(s => nodesSet.add(s));

            const edgesSet = new Set(succEdges);
            if (shortestPath) {
                for (let i = 0; i < shortestPath.length - 1; i++) {
                    // Collect ALL edges between these two nodes to show full context
                    masterEdges.filter(e => e.source === shortestPath[i] && e.target === shortestPath[i+1])
                        .forEach(e => edgesSet.add(e.id));
                }
            }

            return {
                nodes: Array.from(nodesSet).map(id => masterNodes.find(n => n.id === id)).filter(Boolean),
                edges: Array.from(edgesSet).map(id => masterEdges.find(e => e.id === id)).filter(Boolean)
            };
        }

        function performIsolation(targetNodeId) {
            pushHistory();
            const discovery = getFullPathDiscovery(targetNodeId);
            rebuildVisibleGraph(discovery.nodes, discovery.edges);
        }

        function ensurePathVisible(targetNodeId) {
            if (isolateMode) {
                performIsolation(targetNodeId);
                return;
            }

            // Find path from any root in master data
            const rootIds = masterNodes.filter(n => n.isRoot).map(n => n.id);
            if (rootIds.includes(targetNodeId)) {
                if (!graph.hasNode(targetNodeId)) {
                    addMasterNodeToGraph(targetNodeId, null);
                    runForceAtlas({ preserveExisting: true });
                    updateExpandableMarkers();
                    if (renderer) renderer.refresh();
                }
                return;
            }

            // Simple BFS to find path in master data
            const queue = rootIds.map(r => [r]);
            const visited = new Set(rootIds);
            let path = null;

            while (queue.length > 0) {
                const currentPath = queue.shift();
                const lastNode = currentPath[currentPath.length - 1];

                if (lastNode === targetNodeId) {
                    path = currentPath;
                    break;
                }

                masterEdges
                    .filter(e => e.source === lastNode)
                    .forEach(e => {
                        if (!visited.has(e.target)) {
                            visited.add(e.target);
                            queue.push([...currentPath, e.target]);
                        }
                    });
            }

            if (path) {
                path.forEach((nodeId, i) => {
                    if (!graph.hasNode(nodeId)) {
                        addMasterNodeToGraph(nodeId, null);
                    }
                    if (i > 0) {
                        const prevNodeId = path[i-1];
                        const edge = masterEdges.find(e => e.source === prevNodeId && e.target === nodeId);
                        if (edge && !graph.hasEdge(edge.id) && graph.hasNode(edge.source) && graph.hasNode(edge.target)) {
                            addMasterEdgeToGraph(edge);
                        }
                    }
                });
                updateExpandableMarkers();
                runForceAtlas({ preserveExisting: true });
                if (renderer) renderer.refresh();
            } else {
                // Root node case or unreachable
                if (!graph.hasNode(targetNodeId)) {
                    const node = masterNodes.find(n => n.id === targetNodeId);
                    if (node) {
                        addMasterNodeToGraph(targetNodeId, null);
                        runForceAtlas({ preserveExisting: true });
                        updateExpandableMarkers();
                        if (renderer) renderer.refresh();
                    }
                }
            }
        }

        function showSummary() {
            document.getElementById('summary-pane').style.display = 'block';
            document.getElementById('details-pane').style.display = 'none';
            clearHighlight();
        }

        function processQueryForSeeds(query) {
            let result = query;
            seedsData.forEach(s => {
                const escapedVal = s.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                const fieldName = s.field_name;
                const regex = new RegExp(`(${fieldName}:\\s+)("?${escapedVal}"?)(\\s+#\\s+\\[Source: [^\\]]+\\])`, 'g');
                result = result.replace(regex, (match, p1, p2, p3) => {
                    return `${p1}<span class="swappable-value" data-field="${fieldName}" onclick="openValueDropdown(this, event)">${p2}</span>${p3}`;
                });
            });
            return result;
        }

        function showDetails(findingId) {
            const finding = findingsData.find(f => f.id === findingId);
            if (!finding) return;

            document.getElementById('summary-pane').style.display = 'none';
            document.getElementById('details-pane').style.display = 'block';

            // Resolve which affected types actually exist in the master graph data
            // before rendering, so we can show explicit feedback either way instead
            // of silently no-oping when a type isn't present/visible.
            const affectedTypes = [...new Set(finding.affected.map(a => String(a).split('.')[0]))];
            const missingTypes = affectedTypes.filter(t => !masterNodes.some(n => n.id === t));
            const shownTypes = affectedTypes.filter(t => !missingTypes.includes(t));

            let html = `

                <div class="card severity-${finding.severity.toLowerCase()}">

                    <button class="back-btn" onclick="showSummary()"> Back to list</button>

                    <h3>[${finding.id}] ${finding.title}</h3>

                    <p style="font-size:0.8rem;">Highlighted in graph: <b>${shownTypes.join(', ') || ''}</b></p>

                    ${missingTypes.length ? `<div style="color:var(--med)"> Not present in the current graph view: ${missingTypes.join(', ')}</div>` : ''}

                    <p>${finding.description}</p>

                    <strong>Remediation:</strong>

                    <p style="color: var(--low)">${finding.remediation}</p>

                </div>

                <h4>Affected Fields & Exploits</h4>

            `;

            finding.affected.forEach((aff, index) => {
                const tplObj = finding.templates[index];
                let literalStr = typeof tplObj === 'object' && tplObj.literal ? tplObj.literal : String(tplObj);
                const varStr = typeof tplObj === 'object' && tplObj.variable ? tplObj.variable : literalStr;

                literalStr = processQueryForSeeds(literalStr);

                html += `

                    <div class="card">

                        <strong onclick="focusAffected('${aff.split('.')[0]}')" style="cursor:pointer;text-decoration:underline dotted;">${aff}</strong>

                        <div class="toggle-group" id="finding-toggle-${index}">

                            <button class="toggle-btn active" onclick="toggleFindingQuery(${index}, 'literal')">Literal</button>

                            <button class="toggle-btn" onclick="toggleFindingQuery(${index}, 'variable')">Variables</button>

                        </div>

                        <pre id="tpl-lit-${index}">${literalStr}</pre>

                        <pre id="tpl-var-${index}" style="display:none;">${varStr}</pre>

                        

                        <div id="btn-group-lit-${index}" style="margin-top: 10px;">

                            <button onclick="copyToClipboard('tpl-lit-${index}')">Copy GraphQL</button>

                            <button onclick="copyAsCurlGeneric('tpl-lit-${index}')">Copy as cURL</button>

                            <button onclick="copyAsPythonGeneric('tpl-lit-${index}')">Copy as Python</button>

                        </div>

                        <div id="btn-group-var-${index}" style="display:none; margin-top: 10px;">

                            <button onclick="copyToClipboard('tpl-var-${index}')">Copy GraphQL</button>

                            <button onclick="copyAsCurlGeneric('tpl-var-${index}')">Copy as cURL</button>

                            <button onclick="copyAsPythonGeneric('tpl-var-${index}')">Copy as Python</button>

                        </div>

                    </div>

                `;
            });

            document.getElementById('details-content').innerHTML = html;

            // Highlight path in graph: resolve each affected type against the master
            // node list, reveal + highlight the ones that exist, and center the view
            // on the first one shown. Types not present in the schema/current view
            // are reported above instead of silently producing no visible highlight.
            clearHighlight();
            let firstShown = null;
            affectedTypes.forEach(t => {
                if (masterNodes.some(n => n.id === t)) {
                    ensurePathVisible(t);
                    addHighlight(t);
                    if (!firstShown) firstShown = t;
                }
            });
            renderer && renderer.refresh();
            if (firstShown) centerOnNode(firstShown, 0.4);
        }

        // focusAffected: called from the clickable "Affected" labels in the details
        // pane to jump the graph to a specific affected type.
        window.focusAffected = function(typeName) {
            if (!masterNodes.some(n => n.id === typeName)) return;
            ensurePathVisible(typeName);
            clearHighlight();
            addHighlight(typeName);
            renderer && renderer.refresh();
            centerOnNode(typeName, 0.4);
        };

        function getQueryForEdge(edgeData) {
            const sourceId = edgeData.source;
            const targetId = edgeData.target;
            const fieldName = edgeData.label;

            // Find shortest weighted path from any root node using MASTER data
            const rootIds = masterNodes.filter(n => n.isRoot).map(n => n.id);
            let bestPath = null;
            let bestRootId = null;
            let minWeight = Infinity;

            // BFS for shortest path in master data
            rootIds.forEach(rootId => {
                const queue = [[rootId]];
                const visited = new Set([rootId]);
                
                while (queue.length > 0) {
                    const path = queue.shift();
                    const lastId = path[path.length - 1];

                    if (lastId === sourceId) {
                        const weight = path.length; 
                        if (weight < minWeight) {
                            minWeight = weight;
                            bestPath = path;
                            bestRootId = rootId;
                        }
                        break;
                    }

                    masterEdges.filter(e => e.source === lastId).forEach(e => {
                        if (!visited.has(e.target)) {
                            visited.add(e.target);
                            queue.push([...path, e.target]);
                        }
                    });
                }
            });

            let queryPath = []; 
            if (bestPath) {
                for (let i = 0; i < bestPath.length - 1; i++) {
                    const s = bestPath[i];
                    const t = bestPath[i+1];
                    const edge = masterEdges.find(e => e.source === s && e.target === t);
                    if (edge) {
                        queryPath.push({ label: edge.label, args: edge.args || [] });
                    }
                }
            }
            queryPath.push({ label: fieldName, args: edgeData.args || [] });

            // Construct Query
            let indent = "  ";
            let literalQuery = "";
            let varQueryBody = "";
            let varDefs = [];
            
            const bestRootNode = masterNodes.find(n => n.id === bestRootId);
            let rootOp = "query";
            let opBadgeClass = "tag-info";
            if (bestRootNode && bestRootNode.opType) {
                rootOp = bestRootNode.opType;
                if (rootOp === 'mutation') opBadgeClass = "tag-high";
                if (rootOp === 'subscription') opBadgeClass = "tag-med";
            }

            literalQuery += `${rootOp} {\n`;
            queryPath.forEach((seg, i) => {
                literalQuery += `${indent}${seg.label}`;
                varQueryBody += `${indent}${seg.label}`;
                
                if (seg.args && seg.args.length > 0) {
                    const litArgs = [];
                    const varArgs = [];
                    seg.args.forEach(a => {
                        const fieldSeeds = seedsData.filter(s => s.field_name === a.name);
                        let val = a.sampleValue;
                        let displayVal = val;
                        let annotation = "";
                        
                        if (fieldSeeds.length > 0) {
                            val = fieldSeeds[0].value;
                            if (a.typeName === 'String' || a.typeName === 'ID') {
                                val = `"${val}"`;
                            }
                            annotation = ` # [Source: ${fieldSeeds[0].source}]`;
                            displayVal = `<span class="swappable-value" data-field="${a.name}" onclick="openValueDropdown(this, event)">${val}</span>`;
                        }
                        
                        litArgs.push(`${a.name}: ${displayVal}${annotation}`);
                        varArgs.push(`${a.name}: $${a.name}`);
                        varDefs.push(`$${a.name}: ${a.typeName || 'String'}`);
                    });
                    literalQuery += `(${litArgs.join(", ")})`;
                    varQueryBody += `(${varArgs.join(", ")})`;
                }

                if (i < queryPath.length - 1) {
                    literalQuery += " {\n";
                    varQueryBody += " {\n";
                    indent += "  ";
                }
            });
            
            const targetNode = masterNodes.find(n => n.id === targetId);
            const targetKind = targetNode ? targetNode.kind : 'UNKNOWN';
            if (targetKind === 'OBJECT' || targetKind === 'INTERFACE' || targetKind === 'UNION') {
                const typeSelect = " {\n" + `${indent}  __typename\n` + `${indent}}`;
                literalQuery += typeSelect;
                varQueryBody += typeSelect;
            }

            for (let i = 0; i < queryPath.length - 1; i++) {
                indent = indent.substring(0, indent.length - 2);
                literalQuery += `\n${indent}}`;
                varQueryBody += `\n${indent}}`;
            }
            literalQuery += "\n}";
            
            let varQuery = "";
            if (varDefs.length > 0) {
                const uniqueDefs = [...new Set(varDefs)];
                varQuery = `${rootOp} Explore(${uniqueDefs.join(", ")}) {\n${varQueryBody}\n}`;
            } else {
                varQuery = `${rootOp} Explore {\n${varQueryBody}\n}`;
            }

            return {
                literalQuery,
                varQuery,
                rootOp,
                opBadgeClass,
                queryPathStr: bestRootId ? `${bestRootId}  ${queryPath.map(p => p.label).join('')}` : 'None',
                sourceId: sourceId,
                targetId: targetId,
                targetKind: targetKind,
                fieldName: fieldName
            };
        }

        function renderQueryCard(q, index) {
            const litId = `path-query-literal-${index}`;
            const varId = `path-query-variable-${index}`;
            
            return `

                <div class="card" style="margin-top: 15px;">

                    <div style="margin-bottom: 10px; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid var(--border); padding-bottom: 10px;">

                        <span class="tag ${q.opBadgeClass}" style="font-size: 0.7rem; padding: 2px 6px; border-radius: 4px;">${q.rootOp.toUpperCase()}</span>

                        <strong style="font-size: 0.9rem;">${q.sourceId}.${q.fieldName}</strong>

                    </div>

                    <div class="meta" style="margin-bottom: 10px; font-size: 0.75rem;">

                        <strong>Path:</strong> ${q.queryPathStr}

                    </div>

                    <div class="toggle-group" style="margin-bottom: 10px;">

                        <button class="toggle-btn active" onclick="toggleQuerySet('${litId}', '${varId}', this)">Literal</button>

                        <button class="toggle-btn" onclick="toggleQuerySet('${varId}', '${litId}', this)">Variables</button>

                    </div>

                    <pre id="${litId}">${q.literalQuery}</pre>

                    <pre id="${varId}" style="display:none;">${q.varQuery}</pre>

                    

                    <div style="margin-top: 10px; display: flex; gap: 8px;">

                        <button class="btn-sm" onclick="copyToClipboard('${litId}')">Copy GraphQL</button>

                        <button class="btn-sm" onclick="copyAsCurlGeneric('${litId}')">cURL</button>

                    </div>

                </div>

            `;
        }

        window.toggleQuerySet = function(showId, hideId, btn) {
            document.getElementById(showId).style.display = 'block';
            document.getElementById(hideId).style.display = 'none';
            btn.parentElement.querySelectorAll('.toggle-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
        };

        function showPathDetails(edge) {
            try {
                const q = getQueryForEdge(edge.data());

                clearHighlight();
                setHighlight([edge.source().id(), edge.target().id()]);

                document.getElementById('summary-pane').style.display = 'none';
                document.getElementById('details-pane').style.display = 'block';

                let html = `

                    <div class="card">

                        <button class="back-btn" onclick="showSummary()"> Back to list</button>

                        <h3>Traversal Details</h3>

                        <p>Field: <strong>${q.fieldName}</strong> on <strong>${q.sourceId}</strong></p>

                        <p>Returns: <strong>${q.targetId}</strong> (${q.targetKind})</p>

                    </div>

                    ${renderQueryCard(q, 0)}

                `;

                const fieldId = `${q.sourceId}.${q.fieldName}`;
                const relevantFindings = findingsData.filter(f => f.affected.some(aff => aff.startsWith(fieldId) || aff === fieldId));
                
                if (relevantFindings.length > 0) {
                    html += `<h4 style="margin-top: 20px;">Related Security Findings</h4>`;
                    relevantFindings.forEach(f => {
                        html += `

                            <div class="finding-item" onclick="showDetails('${f.id}')">

                                <span class="tag tag-${f.severity.toLowerCase()}">${f.severity}</span>

                                <strong>${f.title}</strong>

                            </div>

                        `;
                    });
                }

                document.getElementById('details-content').innerHTML = html;
            } catch (err) {
                console.error("Error in showPathDetails:", err);
            }
        }

        function copyToClipboard(id) {
            const text = document.getElementById(id).innerText;
            navigator.clipboard.writeText(text);
        }

        function copyAsCurlGeneric(id) {
            const queryText = document.getElementById(id).innerText;
            const query = queryText.replace(/\n/g, ' ').replace(/"/g, '\\"');
            const curl = `curl -X POST -H "Content-Type: application/json" -d '{"query": "${query}"}' {{SOURCE}}`;
            navigator.clipboard.writeText(curl);
            alert('Copied as cURL!');
        }

        function copyAsPythonGeneric(id) {
            const queryText = document.getElementById(id).innerText;
            const python = `import requests\n\nurl = "{{SOURCE}}"\nquery = """${queryText}"""\n\nresponse = requests.post(url, json={"query": query})\nprint(response.json())`;
            navigator.clipboard.writeText(python);
            alert('Copied as Python snippet!');
        }

        // Search functionality
        const searchInput = document.getElementById('node-search');
        const searchSuggestions = document.getElementById('search-suggestions');
        
        searchInput.addEventListener('input', function(e) {
            const val = e.target.value.toLowerCase();
            if (!val) {
                searchSuggestions.style.display = 'none';
                return;
            }
            
            let suggestions = [];
            masterNodes.forEach(n => {
                if (n.id.toLowerCase().includes(val)) {
                    suggestions.push({ type: 'node', id: n.id, label: n.id });
                }
            });
            masterEdges.forEach(e => {
                const label = `${e.source}.${e.label}`;
                if (label.toLowerCase().includes(val)) {
                    suggestions.push({ type: 'edge', id: e.id, label: label, source: e.source, target: e.target });
                }
            });
            
            if (suggestions.length > 0) {
                searchSuggestions.innerHTML = suggestions.slice(0, 10).map(s => `

                    <div class="suggestion-item" onclick="selectSearchResult('${s.type}', '${s.id}')">

                        ${s.label}

                    </div>

                `).join('');
                searchSuggestions.style.display = 'block';
            } else {
                searchSuggestions.style.display = 'none';
            }
        });

        window.selectSearchResult = function(type, id) {
            searchSuggestions.style.display = 'none';
            searchInput.value = '';

            if (type === 'node') {
                ensurePathVisible(id);
                clearHighlight();
                addHighlight(id);
                centerOnNode(id, 0.3);
                handleNodeClick(id);
            } else if (type === 'edge') {
                const edgeData = masterEdges.find(e => e.id === id);
                if (edgeData) {
                    ensurePathVisible(edgeData.target);
                    clearHighlight();
                    setHighlight([edgeData.source, edgeData.target]);
                    centerOnNode(edgeData.target, 0.3);
                    showPathDetails(makeEdgeShim(edgeData));
                }
            }
        };

        window.toggleFindingQuery = function(index, type) {
            const btns = document.querySelectorAll('#finding-toggle-' + index + ' .toggle-btn');
            btns.forEach(b => b.classList.remove('active'));
            if (type === 'literal') {
                btns[0].classList.add('active');
                document.getElementById('tpl-lit-' + index).style.display = 'block';
                document.getElementById('tpl-var-' + index).style.display = 'none';
                document.getElementById('btn-group-lit-' + index).style.display = 'block';
                document.getElementById('btn-group-var-' + index).style.display = 'none';
            } else {
                btns[1].classList.add('active');
                document.getElementById('tpl-lit-' + index).style.display = 'none';
                document.getElementById('tpl-var-' + index).style.display = 'block';
                document.getElementById('btn-group-lit-' + index).style.display = 'none';
                document.getElementById('btn-group-var-' + index).style.display = 'block';
            }
        };

        window.toggleQuery = function(type) {
            const btns = document.querySelectorAll('#query-toggle .toggle-btn');
            btns.forEach(b => b.classList.remove('active'));
            if (type === 'literal') {
                btns[0].classList.add('active');
                document.getElementById('path-query-literal').style.display = 'block';
                document.getElementById('path-query-variable').style.display = 'none';
                document.getElementById('btn-group-literal').style.display = 'block';
                document.getElementById('btn-group-variable').style.display = 'none';
            } else {
                btns[1].classList.add('active');
                document.getElementById('path-query-literal').style.display = 'none';
                document.getElementById('path-query-variable').style.display = 'block';
                document.getElementById('btn-group-literal').style.display = 'none';
                document.getElementById('btn-group-variable').style.display = 'block';
            }
        };

        function switchTab(tabId) {
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            
            document.querySelector(`.tab-btn[onclick="switchTab('${tabId}')"]`).classList.add('active');
            document.getElementById(`tab-${tabId}`).classList.add('active');

            if (tabId === 'schema' && !document.getElementById('schema-tree').innerHTML) {
                buildSchemaTree();
            }
        }

        function buildSchemaTree() {
            const container = document.getElementById('schema-tree');
            const roots = masterNodes.filter(n => n.isRoot);
            
            roots.forEach(root => {
                // Auto-expand root nodes by default
                container.appendChild(createTreeNode(root.id, 'OBJECT', true));
            });
        }

        function createTreeNode(nodeId, kind, isExpanded = false) {
            const nodeEl = document.createElement('div');
            nodeEl.className = 'tree-node-wrapper';
            
            const item = document.createElement('div');
            item.className = 'tree-item';
            item.setAttribute('data-id', nodeId);
            
            const children = masterEdges.filter(e => e.source === nodeId);
            const hasChildren = children.length > 0;
            
            let icon = '📦';
            if (nodeId === 'Query') icon = '🔍';
            if (nodeId === 'Mutation') icon = '';
            if (nodeId === 'Subscription') icon = '📡';
            if (kind === 'SCALAR') icon = '📝';
            if (kind === 'ENUM') icon = '🔢';

            item.innerHTML = `

                <div class="tree-toggle ${hasChildren ? '' : 'hidden'} ${isExpanded ? '' : 'collapsed'}">

                    ${hasChildren ? '' : ''}

                </div>

                <span class="tree-icon">${icon}</span>

                <span class="tree-label">${nodeId}</span>

            `;

            const toggle = item.querySelector('.tree-toggle');
            const childrenContainer = document.createElement('div');
            childrenContainer.className = 'tree-node';
            
            // Fix double-click bug: Ensure display state matches the toggle class
            childrenContainer.style.display = isExpanded ? 'block' : 'none';

            const populateChildren = () => {
                if (childrenContainer.innerHTML) return; // Already populated
                
                children.forEach(edge => {
                    const targetNode = masterNodes.find(n => n.id === edge.target);
                    const targetKind = targetNode ? targetNode.kind : 'UNKNOWN';
                    
                    // Recursively create children
                    const childNodeWrapper = createTreeNode(edge.target, targetKind, false);
                    
                    // Customize the child item to show the field label
                    const childItem = childNodeWrapper.querySelector('.tree-item');
                    const isScalar = targetKind === 'SCALAR' || targetKind === 'ENUM';
                    const childIcon = isScalar ? '📝' : '🔗';
                    
                    childItem.querySelector('.tree-icon').innerText = childIcon;
                    const labelSpan = childItem.querySelector('.tree-label');
                    labelSpan.innerHTML = `${edge.label} <span class="tree-type" style="margin-left:8px; opacity:0.5; font-size:0.75rem;">${edge.target}</span>`;
                    
                    // Override child click for edge traversal
                    childItem.onclick = (ev) => {
                        ev.stopPropagation();
                        ensurePathVisible(edge.target);
                        if (graph.hasEdge(edge.id)) {
                            clearHighlight();
                            setHighlight([edge.source, edge.target]);
                            centerOnNode(edge.target, 0.3);
                            showPathDetails(makeEdgeShim(edge));
                        } else {
                            handleNodeClick(edge.target);
                        }
                        document.querySelectorAll('.tree-item').forEach(i => i.classList.remove('selected'));
                        childItem.classList.add('selected');
                    };
                    
                    childrenContainer.appendChild(childNodeWrapper);
                });
            };

            if (isExpanded) populateChildren();

            item.onclick = (e) => {
                e.stopPropagation();
                ensurePathVisible(nodeId);
                clearHighlight();
                addHighlight(nodeId);
                centerOnNode(nodeId, 1.2);
                handleNodeClick(nodeId);
                document.querySelectorAll('.tree-item').forEach(i => i.classList.remove('selected'));
                item.classList.add('selected');
            };

            if (hasChildren) {
                toggle.onclick = (e) => {
                    e.stopPropagation();
                    const nowCollapsed = toggle.classList.toggle('collapsed');
                    childrenContainer.style.display = nowCollapsed ? 'none' : 'block';
                    if (!nowCollapsed) populateChildren();
                };
            }

            nodeEl.appendChild(item);
            nodeEl.appendChild(childrenContainer);
            return nodeEl;
        }

        function renderFindingsList() {
            const findingsList = document.getElementById('findings-list');
            findingsList.innerHTML = '';
            findingsData.forEach(f => {
                const item = document.createElement('div');
                item.className = 'finding-item';
                item.innerHTML = `

                    <span class="tag tag-${f.severity.toLowerCase()}">${f.severity}</span>

                    <strong>${f.title}</strong>

                    <div style="font-size: 0.8rem; color: var(--muted); margin-top: 3px;">${f.id} - ${f.affected.length} affected</div>

                `;
                item.onclick = () => showDetails(f.id);
                findingsList.appendChild(item);
            });
        }

        // Initialize tabs
        switchTab('findings');
        renderFindingsList();

        if (renderer) {
            renderer.on('clickStage', function(){
                showSummary();
            });
        }

        function showNodeQueries(node) {
            const typeName = node.id();
            const kind = node.data('kind');

            // Search through MASTER edges but FILTER by those that are ACTUALLY RENDERED in the graph
            // This ensures we only show "what the user sees connected to it"
            const incomingEdges = masterEdges.filter(e => {
                return e.target === typeName && graph.hasEdge(e.id);
            });

            document.getElementById('summary-pane').style.display = 'none';
            document.getElementById('details-pane').style.display = 'block';

            let html = `

                <div class="card">

                    <button class="back-btn" onclick="showSummary()"> Back to list</button>

                    <h3>Type Details: ${typeName}</h3>

                    <div style="display: flex; gap: 8px; margin-top: 10px;">

                        <span class="tag tag-info">${kind}</span>

                        <span class="tag tag-low">${incomingEdges.length} Visible Connections</span>

                    </div>

                </div>

            `;

            if (incomingEdges.length > 0) {
                html += `<h4 style="margin-top: 20px;">Reproduction Queries (Visible Context)</h4>`;
                incomingEdges.forEach((edgeData, i) => {
                    try {
                        const q = getQueryForEdge(edgeData);
                        html += renderQueryCard(q, i);
                    } catch (e) {
                        console.error("Failed to generate query for edge:", e);
                    }
                });
            } else {
                html += `<p style="color: var(--muted); margin-top: 20px; font-style: italic;">No active discovery paths lead to this node in the current view.</p>`;
            }

            const relevantFindings = findingsData.filter(f => f.affected.some(aff => aff.startsWith(typeName)));
            if (relevantFindings.length > 0) {
                html += `<h4 style="margin-top: 20px;">Related Security Findings</h4>`;
                relevantFindings.forEach(f => {
                    html += `

                        <div class="finding-item" onclick="showDetails('${f.id}')">

                            <span class="tag tag-${f.severity.toLowerCase()}">${f.severity}</span>

                            <strong>${f.title}</strong>

                        </div>

                    `;
                });
            }

            document.getElementById('details-content').innerHTML = html;
        }

        // --- Click / hover / drag / context-menu wiring (Sigma events) ---

        // selectNode: the "inspect" half of node interaction — highlights the
        // neighborhood, syncs the schema tree, and shows details/queries. Does NOT
        // expand or isolate the graph (that's handled separately, see expandNode /
        // performIsolation and the doubleClickNode wiring below).
        function selectNode(nodeId) {
            const nodeObj = masterNodes.find(n => n.id === nodeId);
            if (!nodeObj) return;

            const neighborhood = [nodeId];
            if (graph.hasNode(nodeId)) {
                graph.forEachNeighbor(nodeId, (neighbor) => neighborhood.push(neighbor));
            }
            setHighlight(neighborhood);

            // --- Graph-to-Tree Interaction ---
            const treeItem = document.querySelector(`.tree-item[data-id="${nodeId}"]`);
            if (treeItem) {
                switchTab('schema');
                document.querySelectorAll('.tree-item').forEach(i => i.classList.remove('selected'));
                treeItem.classList.add('selected');
                treeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }

            if (nodeObj.kind === 'SCALAR' || nodeObj.kind === 'ENUM') {
                showNodeQueries(makeNodeShim(nodeObj));
            } else {
                const relevantFindings = findingsData.filter(f => f.affected.some(aff => aff.startsWith(nodeId)));
                if (relevantFindings.length > 0) {
                    showDetails(relevantFindings[0].id);
                }
            }
        }

        // handleNodeClick: used by non-graph entry points (search results, schema
        // tree clicks) where a single activation is expected to both reveal/expand
        // the node AND select it. The Sigma canvas itself no longer wires this to a
        // single click — see the clickNode/doubleClickNode wiring below.
        function handleNodeClick(nodeId) {
            const nodeObj = masterNodes.find(n => n.id === nodeId);
            if (!nodeObj) return;

            if (isolateMode) {
                performIsolation(nodeId);
            } else {
                expandNode(nodeId);
            }

            selectNode(nodeId);
        }

        if (renderer) {
            // Single click only selects/inspects; expansion happens on double-click
            // (see doubleClickNode below) so a stray click doesn't blow up the graph.
            renderer.on('clickNode', ({ node }) => {
                // A node drag ends with a synthetic click; don't let it select/relayout/zoom.
                if (didDrag) { didDrag = false; return; }
                selectNode(node);
            });

            renderer.on('doubleClickNode', (e) => {
                if (e.preventSigmaDefault) e.preventSigmaDefault();
                if (isolateMode) {
                    performIsolation(e.node);
                } else {
                    expandNode(e.node);
                }
                selectNode(e.node);
            });

            renderer.on('clickEdge', ({ edge }) => {
                const edgeData = masterEdges.find(e => e.id === edge);
                if (edgeData) showPathDetails(makeEdgeShim(edgeData));
            });

            renderer.on('enterNode', ({ node }) => {
                hoveredNode = node;
                const set = new Set([node]);
                graph.forEachNeighbor(node, (n) => set.add(n));
                highlightedNodes = set;
                renderer.refresh();
            });

            renderer.on('leaveNode', () => {
                hoveredNode = null;
                highlightedNodes = new Set();
                renderer.refresh();
            });

            renderer.on('rightClickNode', (e) => {
                if (e.preventSigmaDefault) e.preventSigmaDefault();
                if (e.event && e.event.original) e.event.original.preventDefault();

                selectedNodeId = e.node;

                const menu = document.getElementById('ctx-menu');
                menu.style.display = 'block';
                const nativeEvt = e.event && e.event.original;
                if (nativeEvt) {
                    menu.style.left = nativeEvt.clientX + 'px';
                    menu.style.top = nativeEvt.clientY + 'px';
                }
            });

            // Node dragging: reposition on drag. A drag ends with a synthetic clickNode,
            // so `didDrag` is tracked here and checked in the clickNode handler above to
            // stop a drag from selecting the node (which would relayout + zoom).
            renderer.on('downNode', (e) => {
                didDrag = false;
                draggedNode = e.node;
                graph.setNodeAttribute(draggedNode, 'highlighted', true);
            });

            // Pin the camera's bounding box while dragging so Sigma doesn't rescale
            // the whole view (auto-fit to content) as the dragged node moves — that
            // was the "drag flings the viewport" bug.
            renderer.getMouseCaptor().on('mousedown', () => {
                if (!renderer.getCustomBBox()) renderer.setCustomBBox(renderer.getBBox());
            });

            renderer.getMouseCaptor().on('mousemovebody', (e) => {
                if (!draggedNode) return;
                didDrag = true;
                const pos = renderer.viewportToGraph(e);
                graph.setNodeAttribute(draggedNode, 'x', pos.x);
                graph.setNodeAttribute(draggedNode, 'y', pos.y);
                if (e.preventSigmaDefault) e.preventSigmaDefault();
                if (e.original) {
                    e.original.preventDefault();
                    e.original.stopPropagation();
                }
            });

            renderer.getMouseCaptor().on('mouseup', () => {
                if (draggedNode) {
                    graph.removeNodeAttribute(draggedNode, 'highlighted');
                }
                draggedNode = null;
                renderer.setCustomBBox(null);
            });
        }

        // Undo/redo keybindings. Guarded so Ctrl/Cmd+Z doesn't fire while the user is
        // typing in the search box (or any other text input) on the page.
        window.addEventListener('keydown', (e) => {
            const active = document.activeElement;
            const isTyping = active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable);
            if (isTyping) return;

            if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z' && !e.shiftKey) {
                e.preventDefault();
                undoGraph();
            } else if ((e.ctrlKey || e.metaKey) && (e.key.toLowerCase() === 'y' || (e.key.toLowerCase() === 'z' && e.shiftKey))) {
                e.preventDefault();
                redoGraph();
            }
        });

        // --- Seed Value Swapping Logic ---
        window.openValueDropdown = function(element, event) {
            event.stopPropagation();
            const field = element.getAttribute('data-field');
            const fieldSeeds = seedsData.filter(s => s.field_name === field);
            if (fieldSeeds.length <= 1) return;

            // Remove existing dropdowns
            document.querySelectorAll('.value-dropdown').forEach(d => d.remove());

            const dropdown = document.createElement('div');
            dropdown.className = 'value-dropdown';
            fieldSeeds.forEach(s => {
                const item = document.createElement('div');
                item.className = 'dropdown-item';
                let val = s.value;
                // Simple heuristic for quote wrapping
                if (element.innerText.startsWith('"')) val = `"${val}"`;
                item.innerText = val;
                item.onclick = () => {
                    element.innerText = val;
                    dropdown.remove();
                };
                dropdown.appendChild(item);
            });

            document.body.appendChild(dropdown);
            const rect = element.getBoundingClientRect();
            dropdown.style.top = `${rect.bottom + window.scrollY}px`;
            dropdown.style.left = `${rect.left + window.scrollX}px`;

            // Close on click outside
            const closer = () => {
                dropdown.remove();
                document.removeEventListener('click', closer);
            };
            setTimeout(() => document.addEventListener('click', closer), 10);
        };

        // Populate seeds list
        const seedsList = document.getElementById('seeds-list');
        if (seedsData.length > 0) {
            seedsList.innerHTML = '';
            const groups = {};
            seedsData.forEach(s => {
                if (!groups[s.field_name]) groups[s.field_name] = [];
                groups[s.field_name].push(s);
            });
            
            Object.entries(groups).forEach(([field, seeds]) => {
                const group = document.createElement('div');
                group.className = 'seed-group';
                group.innerHTML = `<h4>${field}</h4>`;
                seeds.forEach(s => {
                    const item = document.createElement('div');
                    item.className = 'seed-item';
                    item.innerText = s.value;
                    item.title = `Source: ${s.source}`;
                    group.appendChild(item);
                });
                seedsList.appendChild(group);
            });
        }

        // Initialize
        resetGraph();

    </script>
</body>
</html>