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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TIMELINK v1.0 - by webXOS</title>
    
    <!-- Libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Courier New', monospace;
            background: #000000;
            color: #00ff00;
            overflow: hidden;
            height: 100vh;
            width: 100vw;
        }
        
        /* Main Canvas */
        #threeCanvas {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            z-index: 1;
        }
        
        /* UI Overlay */
        #ui-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            z-index: 2;
            pointer-events: none;
        }
        
        /* Minimal Header */
        #minimal-header {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            background: rgba(0, 20, 0, 0.85);
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #00ff00;
            backdrop-filter: blur(5px);
            pointer-events: auto;
            height: 50px;
        }
        
        .minimal-logo {
            font-size: 16px;
            font-weight: bold;
            color: #00ff00;
            text-shadow: 0 0 10px #00ff00;
        }
        
        .minimal-stats {
            display: flex;
            gap: 20px;
            font-size: 12px;
        }
        
        .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .stat-label {
            color: #00cc00;
            font-size: 10px;
        }
        
        .stat-value {
            color: #00ff00;
            font-weight: bold;
        }
        
        /* Control Panel */
        #control-panel {
            position: absolute;
            top: 60px;
            left: 20px;
            width: 200px;
            background: rgba(0, 30, 0, 0.95);
            border: 2px solid #00ff00;
            border-radius: 8px;
            padding: 15px;
            backdrop-filter: blur(5px);
            pointer-events: auto;
        }
        
        .control-title {
            color: #00ff00;
            font-size: 14px;
            margin-bottom: 15px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 255, 0, 0.3);
            padding-bottom: 5px;
        }
        
        .shape-selector {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-bottom: 15px;
        }
        
        .shape-btn {
            background: rgba(0, 40, 0, 0.7);
            border: 1px solid #00ff00;
            color: #00ff00;
            padding: 8px;
            font-size: 12px;
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.3s;
            text-align: center;
        }
        
        .shape-btn:hover {
            background: rgba(0, 255, 0, 0.1);
            box-shadow: 0 0 10px #00ff00;
        }
        
        .shape-btn.active {
            background: rgba(0, 255, 0, 0.2);
            box-shadow: 0 0 15px #00ff00;
            border-color: #00ffff;
        }
        
        /* Central Generate Button */
        #central-generate-btn {
            position: fixed;
            bottom: 40px;
            left: 50%;
            transform: translateX(-50%);
            width: 280px;
            background: linear-gradient(45deg, #006600, #00cc00);
            border: none;
            color: white;
            padding: 20px 40px;
            font-family: 'Courier New', monospace;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            border-radius: 12px;
            text-transform: uppercase;
            letter-spacing: 2px;
            transition: all 0.3s;
            z-index: 10;
            pointer-events: auto;
            box-shadow: 0 0 30px rgba(0, 255, 0, 0.5);
            text-align: center;
        }
        
        #central-generate-btn:hover {
            background: linear-gradient(45deg, #00cc00, #00ff00);
            box-shadow: 0 0 40px rgba(0, 255, 0, 0.8);
            transform: translateX(-50%) scale(1.05);
        }
        
        #central-generate-btn.generating {
            background: linear-gradient(45deg, #cc0000, #ff0000);
            animation: pulse 2s infinite;
            box-shadow: 0 0 40px rgba(255, 0, 0, 0.6);
        }
        
        #central-generate-btn.paused {
            background: linear-gradient(45deg, #666600, #cccc00);
            box-shadow: 0 0 30px rgba(204, 204, 0, 0.6);
        }
        
        /* Time Scale Control */
        .time-control {
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid rgba(0, 255, 0, 0.3);
        }
        
        .time-slider {
            width: 100%;
            margin: 10px 0;
        }
        
        .time-value {
            text-align: center;
            font-size: 12px;
            color: #00cc00;
            margin-top: 5px;
        }
        
        /* Export Panel */
        #export-panel {
            position: absolute;
            bottom: 20px;
            right: 20px;
            width: 200px;
            background: rgba(0, 30, 0, 0.95);
            border: 2px solid #00ff00;
            border-radius: 8px;
            padding: 15px;
            backdrop-filter: blur(5px);
            pointer-events: auto;
        }
        
        .export-btn {
            width: 100%;
            background: rgba(0, 60, 0, 0.8);
            border: 1px solid #00ff00;
            color: #00ff00;
            padding: 10px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            cursor: pointer;
            border-radius: 4px;
            margin: 5px 0;
            transition: all 0.3s;
        }
        
        .export-btn:hover {
            background: rgba(0, 255, 0, 0.1);
            box-shadow: 0 0 10px #00ff00;
        }
        
        .export-btn.ready {
            background: linear-gradient(45deg, #006600, #00cc00);
            color: white;
            font-weight: bold;
        }
        
        /* Full Screen Button */
        #fullscreen-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(0, 40, 0, 0.8);
            border: 1px solid #00ff00;
            color: #00ff00;
            padding: 6px 12px;
            font-family: 'Courier New', monospace;
            font-size: 11px;
            cursor: pointer;
            border-radius: 4px;
            z-index: 3;
            pointer-events: auto;
            transition: all 0.3s;
        }
        
        #fullscreen-btn:hover {
            background: rgba(0, 255, 0, 0.1);
            box-shadow: 0 0 10px #00ff00;
        }
        
        /* Emergency Stop Button */
        #emergency-btn {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background: rgba(60, 0, 0, 0.8);
            border: 1px solid #ff0000;
            color: #ff0000;
            padding: 10px 15px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            cursor: pointer;
            border-radius: 4px;
            pointer-events: auto;
            transition: all 0.3s;
        }
        
        #emergency-btn:hover {
            background: rgba(255, 0, 0, 0.1);
            box-shadow: 0 0 15px #ff0000;
        }
        
        /* Progress Display */
        #progress-display {
            position: absolute;
            top: 60px;
            right: 20px;
            width: 200px;
            background: rgba(0, 30, 0, 0.95);
            border: 2px solid #00ff00;
            border-radius: 8px;
            padding: 15px;
            backdrop-filter: blur(5px);
            pointer-events: auto;
        }
        
        .progress-item {
            margin: 8px 0;
        }
        
        .progress-label {
            display: flex;
            justify-content: space-between;
            font-size: 11px;
            color: #00cc00;
            margin-bottom: 3px;
        }
        
        .progress-bar {
            width: 100%;
            height: 6px;
            background: rgba(0, 0, 0, 0.5);
            border: 1px solid #00ff00;
            border-radius: 3px;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #00ff00, #00cc00);
            width: 0%;
            transition: width 0.5s ease;
        }
        
        /* Crystal Info */
        .crystal-info {
            font-size: 10px;
            color: #00ff00;
            text-align: center;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid rgba(0, 255, 0, 0.3);
        }
        
        /* Image Capture Panel */
        #capture-panel {
            position: absolute;
            top: 280px;
            left: 20px;
            width: 200px;
            background: rgba(0, 30, 0, 0.95);
            border: 2px solid #00ff00;
            border-radius: 8px;
            padding: 15px;
            backdrop-filter: blur(5px);
            pointer-events: auto;
        }
        
        .capture-controls {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .capture-btn {
            flex: 1;
            background: rgba(0, 60, 0, 0.8);
            border: 1px solid #00ff00;
            color: #00ff00;
            padding: 8px;
            font-size: 11px;
            cursor: pointer;
            border-radius: 4px;
            text-align: center;
        }
        
        .capture-btn:hover {
            background: rgba(0, 255, 0, 0.1);
            box-shadow: 0 0 10px #00ff00;
        }
        
        /* System Warning */
        #system-warning {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 20, 0, 0.95);
            border: 2px solid #ff0000;
            padding: 30px;
            color: #ff0000;
            text-align: center;
            display: none;
            z-index: 100;
            max-width: 400px;
            border-radius: 8px;
            backdrop-filter: blur(10px);
            pointer-events: auto;
        }
        
        /* Notification */
        #notification {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 30, 0, 0.95);
            border: 2px solid #00ff00;
            padding: 30px;
            color: #00ff00;
            text-align: center;
            display: none;
            z-index: 100;
            max-width: 400px;
            border-radius: 8px;
            backdrop-filter: blur(10px);
            pointer-events: auto;
        }
        
        /* Animations */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        
        @keyframes glow {
            0%, 100% { box-shadow: 0 0 10px #00ff00; }
            50% { box-shadow: 0 0 20px #00ff00, 0 0 30px #00ff00; }
        }
        
        @keyframes float {
            0%, 100% { transform: translateX(-50%) translateY(0px); }
            50% { transform: translateX(-50%) translateY(-10px); }
        }
        
        .glow {
            animation: glow 2s infinite;
        }
        
        .float {
            animation: float 3s ease-in-out infinite;
        }
        
        /* Time Display */
        #time-display {
            position: absolute;
            top: 120px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 30, 0, 0.9);
            border: 2px solid #00ff00;
            padding: 10px 20px;
            border-radius: 8px;
            min-width: 200px;
            backdrop-filter: blur(5px);
            pointer-events: auto;
            text-align: center;
        }
        
        .time-scale-value {
            font-size: 24px;
            color: #00ff00;
            font-weight: bold;
            font-family: monospace;
            margin: 5px 0;
            text-shadow: 0 0 10px #00ff00;
        }
        
        .time-label {
            color: #00cc00;
            font-size: 10px;
            letter-spacing: 1px;
        }
    </style>
</head>
<body>
    <canvas id="threeCanvas"></canvas>
    
    <div id="ui-overlay">
        <!-- Minimal Header -->
        <div id="minimal-header">
            <div class="minimal-logo">TIMELINK // by webXOS</div>
            <div class="minimal-stats">
                <div class="stat-item">
                    <div class="stat-label">CRYSTALS</div>
                    <div class="stat-value" id="crystalCount">0</div>
                </div>
                <div class="stat-item">
                    <div class="stat-label">IMAGES</div>
                    <div class="stat-value" id="imageCount">0</div>
                </div>
                <div class="stat-item">
                    <div class="stat-label">FPS</div>
                    <div class="stat-value" id="fpsCounter">60</div>
                </div>
            </div>
        </div>
        
        <!-- Control Panel -->
        <div id="control-panel">
            <div class="control-title">CRYSTAL SHAPES</div>
            
            <div class="shape-selector">
                <button class="shape-btn active" onclick="selectShape('quantum_spiral')">🌀 QUANTUM SPIRAL</button>
                <button class="shape-btn" onclick="selectShape('fractal_matrix')">⬢ FRACTAL MATRIX</button>
                <button class="shape-btn" onclick="selectShape('neural_lattice')">⊞ NEURAL LATTICE</button>
                <button class="shape-btn" onclick="selectShape('temporal_ring')">⭕ TEMPORAL RING</button>
            </div>
            
            <div class="time-control">
                <div class="time-label">TIME SCALE</div>
                <input type="range" id="timeScale" class="time-slider" min="0.1" max="5.0" value="1.0" step="0.1">
                <div class="time-value" id="timeScaleValue">1.0x</div>
            </div>
        </div>
        
        <!-- Capture Panel -->
        <div id="capture-panel">
            <div class="control-title">IMAGE CAPTURE</div>
            
            <div class="progress-item">
                <div class="progress-label">
                    <span>CAPTURED</span>
                    <span id="captureCount">0</span>
                </div>
                <div class="progress-bar">
                    <div id="captureProgress" class="progress-fill"></div>
                </div>
            </div>
            
            <div class="capture-controls">
                <button class="capture-btn" onclick="captureImage()">📸 CAPTURE</button>
                <button class="capture-btn" onclick="toggleAutoCapture()" id="autoCaptureBtn">⚙ AUTO: OFF</button>
            </div>
            
            <div class="crystal-info">
                <div>Quality: HD (1280x720)</div>
                <div>Format: PNG + JSON</div>
            </div>
        </div>
        
        <!-- Progress Display -->
        <div id="progress-display">
            <div class="control-title">GENERATION PROGRESS</div>
            
            <div class="progress-item">
                <div class="progress-label">
                    <span>CURRENT CRYSTAL</span>
                    <span id="crystalProgressText">0%</span>
                </div>
                <div class="progress-bar">
                    <div id="crystalProgress" class="progress-fill"></div>
                </div>
            </div>
            
            <div class="progress-item">
                <div class="progress-label">
                    <span>DATASET SIZE</span>
                    <span id="datasetSize">0 MB</span>
                </div>
                <div class="progress-bar">
                    <div id="datasetProgress" class="progress-fill"></div>
                </div>
            </div>
            
            <div class="crystal-info">
                <div id="currentCrystalInfo">READY TO START</div>
                <div id="vertexCount">0 vertices / 0 edges</div>
            </div>
        </div>
        
        <!-- Export Panel -->
        <div id="export-panel">
            <div class="control-title">DATASET EXPORT</div>
            
            <button class="export-btn" onclick="exportCurrentCrystal()">
                💾 EXPORT CURRENT
            </button>
            
            <button class="export-btn" onclick="exportCompleteDataset()">
                📦 EXPORT COMPLETE
            </button>
            
            <button class="export-btn" onclick="exportHuggingFace()">
                🤗 HUGGING FACE
            </button>
            
            <div class="crystal-info" style="margin-top: 10px;">
                <div>Includes: Images + Data</div>
                <div>Ready: <span id="exportReady">NO</span></div>
            </div>
        </div>
        
        <!-- Central Generate Button -->
        <button id="central-generate-btn" onclick="toggleAutomatedGeneration()" class="float">
            ⚡ GENERATE CRYSTALS
        </button>
        
        <!-- Full Screen Button -->
        <button id="fullscreen-btn" onclick="toggleFullscreen()">⛶ FULLSCREEN</button>
        
        <!-- Emergency Stop -->
        <button id="emergency-btn" onclick="emergencyStop()">🛑 EMERGENCY STOP</button>
        
        <!-- Time Display -->
        <div id="time-display">
            <div class="time-label">AUTOMATED GENERATOR</div>
            <div class="time-scale-value" id="timeDisplay">00:00:00</div>
            <div class="time-label">TOTAL TIME: <span id="totalTime">0s</span></div>
        </div>
        
        <!-- System Warning -->
        <div id="system-warning">
            <h3>⚠️ SYSTEM LIMIT REACHED</h3>
            <p>Memory usage approaching browser limits.</p>
            <p>Auto-exporting current dataset...</p>
            <div style="margin-top: 20px;">
                <button onclick="continueGeneration()" style="background: rgba(0,60,0,0.8); border: 1px solid #00ff00; color: #00ff00; padding: 10px 20px; cursor: pointer; margin: 5px;">
                    CONTINUE
                </button>
                <button onclick="emergencyStop()" style="background: rgba(60,0,0,0.8); border: 1px solid #ff0000; color: #ff0000; padding: 10px 20px; cursor: pointer; margin: 5px;">
                    STOP
                </button>
            </div>
        </div>
        
        <!-- Notification -->
        <div id="notification">
            <h3 id="notificationTitle">EXPORTING</h3>
            <p id="notificationMessage">Preparing dataset...</p>
            <div class="progress-bar" style="margin: 20px auto; width: 80%;">
                <div id="notificationProgress" class="progress-fill"></div>
            </div>
        </div>
    </div>

    <script>
        // ==================== GLOBAL STATE ====================
        let scene, camera, renderer, controls;
        let currentCrystal = null;
        let isGenerating = false;
        let generationInterval = null;
        let animationId = null;
        let isFullscreen = false;
        let autoCaptureEnabled = false;
        
        // Crystal generation state
        let generationState = {
            active: false,
            crystalCount: 0,
            currentShape: 'quantum_spiral',
            timeScale: 1.0,
            startTime: 0,
            totalGenerationTime: 0,
            currentCrystal: {
                vertices: [],
                edges: [],
                size: 0,
                targetSize: 200,
                currentStep: 0,
                maxSteps: 300,
                color: new THREE.Color(0x00ff00),
                shape: 'quantum_spiral'
            }
        };
        
        // Dataset collection
        let dataset = {
            crystals: [],
            currentCrystalData: [],
            capturedImages: [],
            autoCaptureCount: 0,
            manualCaptureCount: 0,
            totalImages: 0,
            isExporting: false,
            lastExportTime: 0
        };
        
        // System monitoring
        let systemMonitor = {
            fps: 60,
            memoryUsage: 0,
            performanceLevel: 'high',
            frameCount: 0,
            lastFrameTime: performance.now(),
            lastCleanup: 0,
            warningShown: false
        };
        
        // Color palettes for each shape
        const SHAPE_COLORS = {
            quantum_spiral: [0x00ff00, 0x00cc00, 0x009900], // Greens
            fractal_matrix: [0x00ffff, 0x00cccc, 0x009999], // Cyans
            neural_lattice: [0xff00ff, 0xcc00cc, 0x990099], // Magentas
            temporal_ring: [0xffff00, 0xcccc00, 0x999900]  // Yellows
        };
        
        // ==================== THREE.JS INITIALIZATION ====================
        function initThreeJS() {
            try {
                const canvas = document.getElementById('threeCanvas');
                
                // Scene
                scene = new THREE.Scene();
                scene.background = new THREE.Color(0x000000);
                
                // Camera
                const width = window.innerWidth;
                const height = window.innerHeight;
                camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 5000);
                camera.position.set(0, 150, 300);
                
                // Renderer with better quality for image capture
                renderer = new THREE.WebGLRenderer({ 
                    canvas: canvas,
                    antialias: true,
                    alpha: true,
                    preserveDrawingBuffer: true // Required for image capture
                });
                renderer.setSize(width, height);
                renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
                
                // Controls
                controls = new THREE.OrbitControls(camera, renderer.domElement);
                controls.enableDamping = true;
                controls.dampingFactor = 0.05;
                controls.minDistance = 50;
                controls.maxDistance = 1000;
                
                // Enhanced lighting for better visuals
                const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
                scene.add(ambientLight);
                
                const directionalLight1 = new THREE.DirectionalLight(0xffffff, 0.8);
                directionalLight1.position.set(100, 200, 100);
                scene.add(directionalLight1);
                
                const directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.4);
                directionalLight2.position.set(-100, -200, -100);
                scene.add(directionalLight2);
                
                // Create enhanced background
                createEnhancedBackground();
                
                console.log("TIMELINK: Three.js initialized with enhanced visuals");
                return true;
                
            } catch (error) {
                console.error("TIMELINK: Three.js error:", error);
                showNotification("ERROR", "Graphics system initialization failed");
                return false;
            }
        }
        
        function createEnhancedBackground() {
            // Create multiple layers of particles for depth
            createParticleLayer(5000, 500, 1000, 0x00ff00, 0.3); // Near layer
            createParticleLayer(3000, 1000, 2000, 0x00ffff, 0.2); // Middle layer
            createParticleLayer(2000, 2000, 4000, 0xff00ff, 0.1); // Far layer
            
            // Add central glow effect
            const glowGeometry = new THREE.SphereGeometry(10, 32, 32);
            const glowMaterial = new THREE.MeshBasicMaterial({
                color: 0x00ff00,
                transparent: true,
                opacity: 0.2,
                wireframe: true
            });
            const centralGlow = new THREE.Mesh(glowGeometry, glowMaterial);
            scene.add(centralGlow);
        }
        
        function createParticleLayer(count, minRadius, maxRadius, baseColor, opacity) {
            const geometry = new THREE.BufferGeometry();
            const positions = new Float32Array(count * 3);
            const colors = new Float32Array(count * 3);
            const sizes = new Float32Array(count);
            
            const color = new THREE.Color(baseColor);
            
            for (let i = 0; i < count * 3; i += 3) {
                const radius = minRadius + Math.random() * (maxRadius - minRadius);
                const theta = Math.random() * Math.PI * 2;
                const phi = Math.acos(2 * Math.random() - 1);
                
                positions[i] = radius * Math.sin(phi) * Math.cos(theta);
                positions[i + 1] = radius * Math.sin(phi) * Math.sin(theta);
                positions[i + 2] = radius * Math.cos(phi);
                
                // Color variation
                const colorVariation = Math.random() * 0.3;
                colors[i] = color.r + colorVariation;
                colors[i + 1] = color.g + colorVariation;
                colors[i + 2] = color.b + colorVariation;
                
                sizes[i/3] = 0.5 + Math.random() * 2;
            }
            
            geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
            geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
            geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
            
            const material = new THREE.PointsMaterial({
                size: 1.5,
                vertexColors: true,
                transparent: true,
                opacity: opacity,
                sizeAttenuation: true
            });
            
            const particles = new THREE.Points(geometry, material);
            scene.add(particles);
            
            // Store for animation
            if (!window.particleLayers) window.particleLayers = [];
            window.particleLayers.push(particles);
        }
        
        // ==================== CENTRAL GENERATE BUTTON ====================
        function toggleAutomatedGeneration() {
            if (generationState.active) {
                pauseGeneration();
            } else {
                startGeneration();
            }
        }
        
        function selectShape(shape) {
            generationState.currentShape = shape;
            updateShapeButtons();
            
            if (generationState.active) {
                showNotification("SHAPE CHANGED", `Next crystal will be ${formatShapeName(shape)}`);
            } else {
                showNotification("SHAPE SELECTED", `${formatShapeName(shape)} ready for generation`);
            }
        }
        
        function formatShapeName(shape) {
            return shape.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
        }
        
        // ==================== CRYSTAL GENERATION SYSTEM ====================
        function startGeneration() {
            if (generationState.active) return;
            
            console.log("TIMELINK: Starting automated crystal generation...");
            
            generationState.active = true;
            generationState.startTime = Date.now();
            generationState.crystalCount = 0;
            
            // Update central generate button
            const centralBtn = document.getElementById('central-generate-btn');
            centralBtn.textContent = '⏸ STOP GENERATION';
            centralBtn.classList.add('generating');
            centralBtn.classList.remove('paused');
            centralBtn.classList.remove('float'); // Remove floating animation when active
            
            // Start first crystal
            initializeCrystal();
            
            // Start generation loop
            generationInterval = setInterval(growCrystalStep, 50); // 20 FPS
            
            // Start floating animation for button
            centralBtn.style.animation = 'none';
            setTimeout(() => {
                centralBtn.style.animation = 'pulse 2s infinite';
            }, 100);
            
            showNotification("GENERATION STARTED", `Automated ${formatShapeName(generationState.currentShape)} crystal generation active`);
        }
        
        function pauseGeneration() {
            if (!generationState.active) return;
            
            console.log("TIMELINK: Pausing generation");
            
            generationState.active = false;
            clearInterval(generationInterval);
            generationInterval = null;
            
            // Update central generate button
            const centralBtn = document.getElementById('central-generate-btn');
            centralBtn.textContent = '▶ RESUME GENERATION';
            centralBtn.classList.remove('generating');
            centralBtn.classList.add('paused');
            centralBtn.classList.add('float'); // Add floating animation when paused
            
            // Restore floating animation
            centralBtn.style.animation = 'float 3s ease-in-out infinite';
            
            showNotification("GENERATION PAUSED", "Click RESUME to continue automated generation");
        }
        
        function initializeCrystal() {
            // Clean up previous crystal
            if (currentCrystal) {
                scene.remove(currentCrystal);
                currentCrystal = null;
            }
            
            // Reset crystal data
            generationState.currentCrystal = {
                vertices: [],
                edges: [],
                size: 0,
                targetSize: 200,
                currentStep: 0,
                maxSteps: 300,
                color: new THREE.Color(SHAPE_COLORS[generationState.currentShape][0]),
                shape: generationState.currentShape
            };
            
            dataset.currentCrystalData = [];
            
            // Create initial vertex at center
            generationState.currentCrystal.vertices.push({
                x: 0, y: 0, z: 0,
                connections: [],
                generation: 0,
                energy: 1.0,
                color: generationState.currentCrystal.color.getHex(),
                shape: generationState.currentShape,
                temporalPhase: null  // Initialize all vertices with temporalPhase
            });
            
            // Set color based on shape
            const colors = SHAPE_COLORS[generationState.currentShape];
            generationState.currentCrystal.color = new THREE.Color(colors[Math.floor(Math.random() * colors.length)]);
            
            updateCrystalInfo();
            updateCrystalProgress(0);
            
            console.log(`TIMELINK: Initialized ${generationState.currentShape} crystal`);
        }
        
        function growCrystalStep() {
            if (!generationState.active) return;
            
            const crystal = generationState.currentCrystal;
            
            // Check if crystal is complete
            if (crystal.currentStep >= crystal.maxSteps || crystal.vertices.length >= crystal.targetSize) {
                completeCurrentCrystal();
                startNewCrystal();
                return;
            }
            
            crystal.currentStep++;
            crystal.size = (crystal.currentStep / crystal.maxSteps) * crystal.targetSize;
            
            // Grow based on selected shape
            switch(crystal.shape) {
                case 'quantum_spiral':
                    growQuantumSpiral();
                    break;
                case 'fractal_matrix':
                    growFractalMatrix();
                    break;
                case 'neural_lattice':
                    growNeuralLattice();
                    break;
                case 'temporal_ring':
                    growTemporalRing();
                    break;
            }
            
            // Update visualization
            updateCrystalVisualization();
            
            // Auto-capture images
            if (autoCaptureEnabled && crystal.currentStep % 10 === 0) {
                captureImage();
            }
            
            // Update UI
            updateUI();
        }
        
        // ==================== SHAPE ALGORITHMS ====================
        function growQuantumSpiral() {
            const crystal = generationState.currentCrystal;
            const time = generationState.totalGenerationTime;
            
            const layers = Math.max(3, Math.floor(crystal.size / 20));
            const currentLayer = Math.floor(crystal.vertices.length / 4);
            
            for (let i = 0; i < 3 && crystal.vertices.length < crystal.targetSize; i++) {
                // Calculate spiral position with time-based animation
                const timeWarp = Math.sin(time * 0.5 + i * 0.5) * 0.3;
                const radius = 15 + (currentLayer * 4) + timeWarp * 8;
                const height = currentLayer * 12;
                const angle = (currentLayer / layers) * Math.PI * 6 + (i / 3) * Math.PI * 2;
                
                const x = Math.cos(angle + time * 0.2) * radius;
                const y = height + Math.sin(time * 0.3 + i) * 4;
                const z = Math.sin(angle + time * 0.2) * radius;
                
                // Find nearest vertex for connection
                let nearestIndex = 0;
                let minDistance = Infinity;
                
                for (let j = 0; j < crystal.vertices.length; j++) {
                    const v = crystal.vertices[j];
                    const dx = x - v.x;
                    const dy = y - v.y;
                    const dz = z - v.z;
                    const distance = Math.sqrt(dx*dx + dy*dy + dz*dz);
                    
                    if (distance < minDistance && distance < 30) {
                        minDistance = distance;
                        nearestIndex = j;
                    }
                }
                
                // Create new vertex
                const newVertex = {
                    x: x,
                    y: y,
                    z: z,
                    connections: [nearestIndex],
                    generation: currentLayer,
                    energy: 0.7 + Math.random() * 0.3,
                    color: crystal.color.getHex(),
                    shape: crystal.shape,
                    temporalPhase: null  // Add temporalPhase for consistency
                };
                
                crystal.vertices.push(newVertex);
                
                // Create reciprocal connection
                if (nearestIndex < crystal.vertices.length) {
                    crystal.vertices[nearestIndex].connections.push(crystal.vertices.length - 1);
                    crystal.edges.push([nearestIndex, crystal.vertices.length - 1]);
                }
            }
        }
        
        function growFractalMatrix() {
            const crystal = generationState.currentCrystal;
            
            // Start with central connections
            if (crystal.vertices.length === 1) {
                // Create initial fractal arms
                for (let i = 0; i < 6; i++) {
                    const angle = (i / 6) * Math.PI * 2;
                    const length = 20;
                    
                    crystal.vertices.push({
                        x: Math.cos(angle) * length,
                        y: Math.sin(angle) * length,
                        z: 0,
                        connections: [0],
                        generation: 1,
                        energy: 0.9,
                        color: crystal.color.getHex(),
                        shape: crystal.shape,
                        temporalPhase: null  // Add temporalPhase for consistency
                    });
                    crystal.vertices[0].connections.push(crystal.vertices.length - 1);
                    crystal.edges.push([0, crystal.vertices.length - 1]);
                }
            } else {
                // Fractal branching from existing vertices
                const verticesToBranch = [];
                
                // Select vertices with few connections
                for (let i = 0; i < crystal.vertices.length; i++) {
                    const vertex = crystal.vertices[i];
                    if (vertex.connections.length < 4 && vertex.generation < 5) {
                        verticesToBranch.push(i);
                    }
                }
                
                // Branch from selected vertices
                verticesToBranch.forEach(vertexIndex => {
                    const vertex = crystal.vertices[vertexIndex];
                    const branches = 1 + Math.floor(Math.random() * 3);
                    
                    for (let b = 0; b < branches && crystal.vertices.length < crystal.targetSize; b++) {
                        // Calculate branch direction
                        const baseAngle = vertex.generation * Math.PI / 2;
                        const branchAngle = baseAngle + (b / branches) * Math.PI * 2;
                        const pitch = Math.random() * Math.PI;
                        
                        // Fractal scaling
                        const scale = Math.pow(0.6, vertex.generation);
                        const length = 12 + Math.random() * 10;
                        
                        const x = vertex.x + Math.sin(pitch) * Math.cos(branchAngle) * length * scale;
                        const y = vertex.y + Math.cos(pitch) * length * scale;
                        const z = vertex.z + Math.sin(pitch) * Math.sin(branchAngle) * length * scale;
                        
                        const newVertex = {
                            x: x,
                            y: y,
                            z: z,
                            connections: [vertexIndex],
                            generation: vertex.generation + 1,
                            energy: vertex.energy * (0.6 + Math.random() * 0.4),
                            color: crystal.color.getHex(),
                            shape: crystal.shape,
                            temporalPhase: null  // Add temporalPhase for consistency
                        };
                        
                        crystal.vertices.push(newVertex);
                        vertex.connections.push(crystal.vertices.length - 1);
                        crystal.edges.push([vertexIndex, crystal.vertices.length - 1]);
                    }
                });
            }
        }
        
        function growNeuralLattice() {
            const crystal = generationState.currentCrystal;
            const time = generationState.totalGenerationTime;
            
            if (crystal.vertices.length < 15) {
                // Initial random points for neural network
                for (let i = 0; i < 4 && crystal.vertices.length < crystal.targetSize; i++) {
                    const radius = 25 + crystal.size;
                    const theta = Math.random() * Math.PI * 2;
                    const phi = Math.acos(2 * Math.random() - 1);
                    
                    const x = radius * Math.sin(phi) * Math.cos(theta);
                    const y = radius * Math.sin(phi) * Math.sin(theta);
                    const z = radius * Math.cos(phi);
                    
                    const newVertex = {
                        x: x,
                        y: y,
                        z: z,
                        connections: [],
                        generation: Math.floor(crystal.vertices.length / 5),
                        energy: 0.8 + Math.random() * 0.2,
                        color: crystal.color.getHex(),
                        shape: crystal.shape,
                        temporalPhase: null  // Add temporalPhase for consistency
                    };
                    
                    // Connect to 3 nearest neighbors
                    const neighbors = [];
                    for (let j = 0; j < crystal.vertices.length; j++) {
                        const v = crystal.vertices[j];
                        const dx = x - v.x;
                        const dy = y - v.y;
                        const dz = z - v.z;
                        const distance = Math.sqrt(dx*dx + dy*dy + dz*dz);
                        neighbors.push({index: j, distance: distance});
                    }
                    
                    neighbors.sort((a, b) => a.distance - b.distance);
                    
                    const maxConnections = Math.min(3, neighbors.length);
                    for (let n = 0; n < maxConnections; n++) {
                        if (neighbors[n].distance < 40) {
                            newVertex.connections.push(neighbors[n].index);
                            crystal.vertices[neighbors[n].index].connections.push(crystal.vertices.length);
                            crystal.edges.push([neighbors[n].index, crystal.vertices.length]);
                        }
                    }
                    
                    crystal.vertices.push(newVertex);
                }
            } else {
                // Neural network style connections
                // Add new connections between existing vertices
                const newConnections = Math.min(8, Math.floor(crystal.vertices.length / 20));
                
                for (let c = 0; c < newConnections; c++) {
                    const i = Math.floor(Math.random() * crystal.vertices.length);
                    const j = Math.floor(Math.random() * crystal.vertices.length);
                    
                    if (i !== j && !crystal.vertices[i].connections.includes(j)) {
                        const v1 = crystal.vertices[i];
                        const v2 = crystal.vertices[j];
                        const dx = v1.x - v2.x;
                        const dy = v1.y - v2.y;
                        const dz = v1.z - v2.z;
                        const distance = Math.sqrt(dx*dx + dy*dy + dz*dz);
                        
                        // Connection probability based on distance
                        const connectionProbability = Math.exp(-distance / 30) * (0.5 + 0.5 * Math.sin(time * 0.5));
                        
                        if (distance < 50 && Math.random() < connectionProbability) {
                            crystal.vertices[i].connections.push(j);
                            crystal.vertices[j].connections.push(i);
                            crystal.edges.push([i, j]);
                        }
                    }
                }
                
                // Add new neurons occasionally
                if (Math.random() > 0.8 && crystal.vertices.length < crystal.targetSize) {
                    const radius = 40 + crystal.size / 2;
                    const theta = Math.random() * Math.PI * 2;
                    const phi = Math.acos(2 * Math.random() - 1);
                    
                    const x = radius * Math.sin(phi) * Math.cos(theta);
                    const y = radius * Math.sin(phi) * Math.sin(theta);
                    const z = radius * Math.cos(phi);
                    
                    const newVertex = {
                        x: x,
                        y: y,
                        z: z,
                        connections: [],
                        generation: Math.floor(crystal.vertices.length / 25),
                        energy: 0.7 + Math.random() * 0.3,
                        color: crystal.color.getHex(),
                        shape: crystal.shape,
                        temporalPhase: null  // Add temporalPhase for consistency
                    };
                    
                    crystal.vertices.push(newVertex);
                }
            }
        }
        
        function growTemporalRing() {
            const crystal = generationState.currentCrystal;
            const time = generationState.totalGenerationTime;
            
            const segments = Math.min(120, 30 + Math.floor(crystal.size / 2));
            const currentSegment = crystal.vertices.length;
            
            if (currentSegment >= segments) return;
            
            const radius = 30 + crystal.size / 3;
            const angle = (currentSegment / segments) * Math.PI * 2;
            
            // Time-based distortion effects
            const timeDistortion = Math.sin(time * 0.5 + currentSegment * 0.1) * 0.5;
            const phaseShift = time * 0.3;
            const verticalWave = Math.sin(angle * 3 + time * 0.4) * 10;
            
            const x = Math.cos(angle + phaseShift) * radius * (1 + timeDistortion * 0.2);
            const z = Math.sin(angle + phaseShift) * radius * (1 + timeDistortion * 0.2);
            const y = verticalWave;
            
            const newVertex = {
                x: x,
                y: y,
                z: z,
                connections: [],
                generation: currentSegment,
                energy: 0.8 + Math.abs(Math.sin(angle)) * 0.2,
                color: crystal.color.getHex(),
                shape: crystal.shape,
                temporalPhase: angle
            };
            
            // Connect to previous vertex
            if (currentSegment > 0) {
                newVertex.connections.push(currentSegment - 1);
                crystal.vertices[currentSegment - 1].connections.push(currentSegment);
                crystal.edges.push([currentSegment - 1, currentSegment]);
            }
            
            // Connect to opposite side
            if (currentSegment > segments / 4 && currentSegment % (segments/8) === 0) {
                const oppositeIndex = Math.floor((currentSegment + segments/2) % segments);
                if (oppositeIndex < crystal.vertices.length) {
                    newVertex.connections.push(oppositeIndex);
                    crystal.vertices[oppositeIndex].connections.push(currentSegment);
                    crystal.edges.push([oppositeIndex, currentSegment]);
                }
            }
            
            // Connect to center
            if (currentSegment % (segments/12) === 0) {
                newVertex.connections.push(0);
                crystal.vertices[0].connections.push(currentSegment);
                crystal.edges.push([0, currentSegment]);
            }
            
            crystal.vertices.push(newVertex);
        }
        
        function updateCrystalVisualization() {
            const crystal = generationState.currentCrystal;
            
            if (crystal.vertices.length === 0) return;
            
            // Create or update crystal geometry
            if (!currentCrystal) {
                const geometry = new THREE.BufferGeometry();
                const material = new THREE.LineBasicMaterial({
                    color: crystal.color,
                    linewidth: 2,
                    transparent: true,
                    opacity: 0.9
                });
                
                currentCrystal = new THREE.LineSegments(geometry, material);
                scene.add(currentCrystal);
                
                // Add vertex points for better visualization
                const pointGeometry = new THREE.BufferGeometry();
                const pointMaterial = new THREE.PointsMaterial({
                    color: crystal.color,
                    size: 3,
                    transparent: true,
                    opacity: 0.7
                });
                
                currentCrystal.points = new THREE.Points(pointGeometry, pointMaterial);
                scene.add(currentCrystal.points);
            }
            
            // Update line geometry
            const positions = new Float32Array(crystal.vertices.length * 3);
            const indices = [];
            
            for (let i = 0; i < crystal.vertices.length; i++) {
                const v = crystal.vertices[i];
                positions[i * 3] = v.x;
                positions[i * 3 + 1] = v.y;
                positions[i * 3 + 2] = v.z;
            }
            
            for (const [a, b] of crystal.edges) {
                indices.push(a, b);
            }
            
            // Update line geometry
            currentCrystal.geometry.dispose();
            currentCrystal.geometry = new THREE.BufferGeometry();
            currentCrystal.geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
            currentCrystal.geometry.setIndex(indices);
            
            // Update point geometry
            currentCrystal.points.geometry.dispose();
            currentCrystal.points.geometry = new THREE.BufferGeometry();
            currentCrystal.points.geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
            
            // Update material with time-based effects
            const pulse = 0.8 + 0.2 * Math.sin(generationState.totalGenerationTime * 2);
            currentCrystal.material.opacity = pulse * 0.9;
            currentCrystal.material.color = crystal.color;
            currentCrystal.points.material.color = crystal.color;
            currentCrystal.points.material.opacity = pulse * 0.7;
            
            // Add subtle rotation
            currentCrystal.rotation.y += 0.001 * generationState.timeScale;
            currentCrystal.points.rotation.y = currentCrystal.rotation.y;
        }
        
        function completeCurrentCrystal() {
            const crystal = generationState.currentCrystal;
            
            // Final image capture
            captureImage();
            
            // Normalize vertex data for consistency (ensure all vertices have temporalPhase)
            const normalizedVertices = crystal.vertices.map(v => ({
                ...v,
                temporalPhase: v.temporalPhase !== undefined ? v.temporalPhase : null
            }));
            
            // Store crystal data
            const crystalData = {
                id: generationState.crystalCount,
                shape: crystal.shape,
                vertices: crystal.vertices.length,
                edges: crystal.edges.length,
                size: crystal.size,
                generationSteps: crystal.currentStep,
                generationTime: crystal.currentStep * 0.05,
                color: crystal.color.getHex(),
                vertexData: normalizedVertices,
                edgeData: crystal.edges,
                images: dataset.capturedImages.filter(img => img.metadata.crystalId === generationState.crystalCount)
            };
            
            dataset.crystals.push(crystalData);
            generationState.crystalCount++;
            
            console.log(`TIMELINK: Completed crystal #${generationState.crystalCount} with ${crystal.vertices.length} vertices`);
        }
        
        function startNewCrystal() {
            if (!generationState.active) return;
            
            // Reset for new crystal
            initializeCrystal();
        }
        
        // ==================== IMAGE CAPTURE SYSTEM ====================
        function captureImage() {
            try {
                const canvas = document.getElementById('threeCanvas');
                
                // Ensure canvas is ready
                if (!canvas || canvas.width === 0) {
                    console.warn("Canvas not ready for capture");
                    return;
                }
                
                // Capture at high quality
                const imageData = canvas.toDataURL('image/png', 1.0);
                
                // Create metadata for the image
                const imageMetadata = {
                    timestamp: Date.now(),
                    crystalId: generationState.crystalCount,
                    crystalShape: generationState.currentShape,
                    step: generationState.currentCrystal.currentStep,
                    vertices: generationState.currentCrystal.vertices.length,
                    edges: generationState.currentCrystal.edges.length,
                    size: generationState.currentCrystal.size,
                    timeScale: generationState.timeScale,
                    generationTime: generationState.totalGenerationTime
                };
                
                // Store image with metadata
                dataset.capturedImages.push({
                    data: imageData,
                    metadata: imageMetadata,
                    type: 'manual'
                });
                
                dataset.totalImages++;
                dataset.manualCaptureCount++;
                
                // Update UI
                document.getElementById('imageCount').textContent = dataset.totalImages;
                document.getElementById('captureCount').textContent = dataset.totalImages;
                
                const captureProgress = Math.min((dataset.totalImages / 100) * 100, 100);
                document.getElementById('captureProgress').style.width = captureProgress + '%';
                
                // Flash effect for visual feedback
                if (dataset.totalImages % 5 === 0) {
                    showNotification("IMAGE CAPTURED", `Saved image #${dataset.totalImages} for dataset`);
                }
                
            } catch (error) {
                console.error("TIMELINK: Image capture error:", error);
            }
        }
        
        function toggleAutoCapture() {
            autoCaptureEnabled = !autoCaptureEnabled;
            const btn = document.getElementById('autoCaptureBtn');
            
            if (autoCaptureEnabled) {
                btn.textContent = '⚙ AUTO: ON';
                btn.classList.add('ready');
                showNotification("AUTO CAPTURE", "Auto-capture enabled (every 10 steps)");
            } else {
                btn.textContent = '⚙ AUTO: OFF';
                btn.classList.remove('ready');
                showNotification("AUTO CAPTURE", "Auto-capture disabled");
            }
        }
        
        // ==================== EXPORT FUNCTIONS ====================
        async function exportCurrentCrystal() {
            if (generationState.currentCrystal.vertices.length === 0) {
                showNotification("ERROR", "No crystal data to export");
                return;
            }
            
            showNotification("EXPORTING", "Exporting current crystal dataset...");
            
            try {
                const zip = new JSZip();
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                const crystalId = generationState.crystalCount;
                const shapeName = formatShapeName(generationState.currentShape).toLowerCase().replace(' ', '_');
                
                // Create metadata
                const metadata = {
                    crystal_id: crystalId,
                    shape: generationState.currentShape,
                    shape_name: formatShapeName(generationState.currentShape),
                    vertices: generationState.currentCrystal.vertices.length,
                    edges: generationState.currentCrystal.edges.length,
                    generation_time: generationState.totalGenerationTime,
                    export_time: new Date().toISOString(),
                    time_scale: generationState.timeScale,
                    images_captured: dataset.capturedImages.filter(img => img.metadata.crystalId === crystalId).length
                };
                
                zip.file("metadata.json", JSON.stringify(metadata, null, 2));
                
                // Export crystal data
                const crystalData = {
                    vertices: generationState.currentCrystal.vertices,
                    edges: generationState.currentCrystal.edges,
                    parameters: {
                        target_size: generationState.currentCrystal.targetSize,
                        color: generationState.currentCrystal.color.getHex(),
                        time_scale: generationState.timeScale
                    }
                };
                
                zip.file("crystal_data.json", JSON.stringify(crystalData, null, 2));
                
                // Export images
                const imgFolder = zip.folder("images");
                const crystalImages = dataset.capturedImages.filter(img => img.metadata.crystalId === crystalId);
                
                crystalImages.forEach((image, index) => {
                    const base64Data = image.data.replace(/^data:image\/png;base64,/, "");
                    imgFolder.file(`step_${index.toString().padStart(4, '0')}.png`, base64Data, {base64: true});
                });
                
                // Create README
                const readme = generateCrystalReadme(metadata, crystalImages.length);
                zip.file("README.md", readme);
                
                // Generate and download
                const content = await zip.generateAsync({type: "blob"});
                const filename = `timelink_${shapeName}_crystal_${timestamp}.zip`;
                
                saveAs(content, filename);
                
                showNotification("SUCCESS", `Exported ${shapeName} crystal dataset`);
                
            } catch (error) {
                console.error("TIMELINK: Export error:", error);
                showNotification("ERROR", `Export failed: ${error.message}`);
            }
        }
        
        async function exportCompleteDataset() {
            if (dataset.crystals.length === 0 && generationState.currentCrystal.vertices.length === 0) {
                showNotification("ERROR", "No dataset to export");
                return;
            }
            
            showNotification("EXPORTING", "Preparing complete dataset package...");
            
            try {
                const zip = new JSZip();
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                
                // Create dataset structure with proper row-oriented format
                const datasetRows = [];
                
                dataset.crystals.forEach((crystal, index) => {
                    // Normalize vertex data to ensure consistency
                    const normalizedVertexData = crystal.vertexData.map(vertex => ({
                        ...vertex,
                        temporalPhase: vertex.temporalPhase !== undefined ? vertex.temporalPhase : null
                    }));
                    
                    // Create a row for each crystal
                    const row = {
                        id: crystal.id,
                        shape: crystal.shape,
                        vertices: crystal.vertices,
                        edges: crystal.edges,
                        size: crystal.size,
                        generationSteps: crystal.generationSteps,
                        generationTime: parseFloat(crystal.generationTime),
                        color: crystal.color,
                        vertexData: normalizedVertexData,
                        edgeData: crystal.edgeData,
                        // Note: images are not included in JSON to avoid large files
                        images_count: crystal.images ? crystal.images.length : 0
                    };
                    
                    datasetRows.push(row);
                    
                    // Export images for this crystal
                    const crystalFolder = zip.folder(`crystal_${crystal.id}_${crystal.shape}`);
                    
                    // Export crystal metadata
                    crystalFolder.file("metadata.json", JSON.stringify({
                        id: crystal.id,
                        shape: crystal.shape,
                        vertices: crystal.vertices,
                        edges: crystal.edges,
                        generationTime: parseFloat(crystal.generationTime),
                        export_time: new Date().toISOString()
                    }, null, 2));
                    
                    // Export images if available
                    if (crystal.images && crystal.images.length > 0) {
                        const imgFolder = crystalFolder.folder("images");
                        crystal.images.forEach((image, imgIndex) => {
                            const base64Data = image.data.replace(/^data:image\/png;base64,/, "");
                            imgFolder.file(`step_${imgIndex.toString().padStart(4, '0')}.png`, base64Data, {base64: true});
                        });
                    }
                });
                
                // Comprehensive metadata
                const metadata = {
                    total_crystals: dataset.crystals.length,
                    total_images: dataset.totalImages,
                    total_generation_time: generationState.totalGenerationTime,
                    start_time: new Date(generationState.startTime).toISOString(),
                    export_time: new Date().toISOString(),
                    shapes_generated: [...new Set(dataset.crystals.map(c => c.shape))],
                    system_info: {
                        memory_usage: `${systemMonitor.memoryUsage} MB`,
                        performance_level: systemMonitor.performanceLevel
                    },
                    // Dataset structure information
                    data_format: "row-oriented JSON (list of objects)",
                    features: {
                        id: "int64 - Crystal ID",
                        shape: "string - Crystal shape type",
                        vertices: "int64 - Number of vertices",
                        edges: "int64 - Number of edges",
                        size: "float64 - Crystal size metric",
                        generationSteps: "int64 - Steps to generate",
                        generationTime: "float64 - Time to generate (seconds)",
                        color: "int64 - Hex color code",
                        vertexData: "list of structs - Vertex information",
                        edgeData: "list of lists - Edge connections",
                        images_count: "int64 - Number of images captured"
                    }
                };
                
                // Main dataset file - row-oriented JSON
                zip.file("dataset.json", JSON.stringify(datasetRows, null, 2));
                zip.file("dataset_metadata.json", JSON.stringify(metadata, null, 2));
                
                // Export summary and README
                const summary = generateDatasetSummary(metadata);
                zip.file("summary.txt", summary);
                
                const readme = generateCompleteReadme(metadata);
                zip.file("README.md", readme);
                
                // Generate and download
                const content = await zip.generateAsync({type: "blob"});
                const filename = `timelink_complete_dataset_${timestamp}.zip`;
                
                saveAs(content, filename);
                
                showNotification("SUCCESS", `Exported complete dataset (${metadata.total_crystals} crystals, ${metadata.total_images} images)`);
                
            } catch (error) {
                console.error("TIMELINK: Export error:", error);
                showNotification("ERROR", `Export failed: ${error.message}`);
            }
        }
        
        async function exportHuggingFace() {
            if (dataset.crystals.length === 0) {
                showNotification("ERROR", "No dataset to export for Hugging Face");
                return;
            }
            
            showNotification("EXPORTING", "Preparing Hugging Face dataset...");
            
            try {
                const zip = new JSZip();
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                
                // Prepare the data in Hugging Face format: a list of crystal objects
                const hfData = dataset.crystals.map(crystal => {
                    // Normalize vertex data: ensure every vertex has temporalPhase (set to null if missing)
                    const normalizedVertexData = crystal.vertexData.map(vertex => {
                        // Ensure all vertices have the same fields
                        const normalizedVertex = { ...vertex };
                        
                        // Ensure temporalPhase exists (null for non-temporal shapes)
                        if (!('temporalPhase' in normalizedVertex)) {
                            normalizedVertex.temporalPhase = null;
                        }
                        
                        // Return standardized vertex structure
                        return {
                            x: parseFloat(normalizedVertex.x) || 0.0,
                            y: parseFloat(normalizedVertex.y) || 0.0,
                            z: parseFloat(normalizedVertex.z) || 0.0,
                            connections: normalizedVertex.connections || [],
                            generation: parseInt(normalizedVertex.generation) || 0,
                            energy: parseFloat(normalizedVertex.energy) || 0.0,
                            color: parseInt(normalizedVertex.color) || 0x00ff00,
                            shape: normalizedVertex.shape || crystal.shape,
                            temporalPhase: normalizedVertex.temporalPhase !== null ? 
                                          parseFloat(normalizedVertex.temporalPhase) : null
                        };
                    });
                    
                    // Normalize edgeData: ensure it's a list of [int, int]
                    const normalizedEdgeData = crystal.edgeData.map(edge => {
                        if (Array.isArray(edge) && edge.length === 2) {
                            return [parseInt(edge[0]) || 0, parseInt(edge[1]) || 0];
                        } else {
                            return [0, 0];
                        }
                    });
                    
                    // Create standardized row for Hugging Face
                    return {
                        id: crystal.id,
                        shape: crystal.shape,
                        vertices: parseInt(crystal.vertices) || 0,
                        edges: parseInt(crystal.edges) || 0,
                        size: parseFloat(crystal.size) || 0.0,
                        generationSteps: parseInt(crystal.generationSteps) || 0,
                        generationTime: parseFloat(crystal.generationTime) || 0.0,
                        color: parseInt(crystal.color) || 0x00ff00,
                        vertexData: normalizedVertexData,
                        edgeData: normalizedEdgeData
                        // Note: we are not including base64 images in the JSON
                    };
                });
                
                // Hugging Face specific metadata
                const hfMetadata = {
                    "description": `TIMELINK Time Crystal Dataset - ${dataset.crystals.length} crystals`,
                    "citation": "@misc{timelink2025,\n  title={TIMELINK: Quantum Time Crystal Generation},\n  author={WebXOS Research},\n  year={2025},\n  note={Dataset of algorithmically generated time crystal structures}\n}",
                    "license": "mit",
                    "language": "en",
                    "size_categories": ["n<1K", "1K<n<10K"],
                    "task_categories": ["graph-generation", "image-generation"],
                    "task_ids": ["graph-generation", "image-generation", "time-series-generation"],
                    "pretty_name": "TIMELINK Time Crystal Dataset",
                    "tags": ["quantum", "crystal", "graph", "3d", "generation", "time-series"],
                    "dataset_info": {
                        "features": {
                            "id": {"dtype": "int64", "nullable": false},
                            "shape": {"dtype": "string", "nullable": false},
                            "vertices": {"dtype": "int64", "nullable": false},
                            "edges": {"dtype": "int64", "nullable": false},
                            "size": {"dtype": "float64", "nullable": false},
                            "generationSteps": {"dtype": "int64", "nullable": false},
                            "generationTime": {"dtype": "float64", "nullable": false},
                            "color": {"dtype": "int64", "nullable": false},
                            "vertexData": {
                                "feature": {
                                    "x": {"dtype": "float64", "nullable": false},
                                    "y": {"dtype": "float64", "nullable": false},
                                    "z": {"dtype": "float64", "nullable": false},
                                    "connections": {"dtype": "int64", "list": true, "nullable": false},
                                    "generation": {"dtype": "int64", "nullable": false},
                                    "energy": {"dtype": "float64", "nullable": false},
                                    "color": {"dtype": "int64", "nullable": false},
                                    "shape": {"dtype": "string", "nullable": false},
                                    "temporalPhase": {"dtype": "float64", "nullable": true}
                                },
                                "list": true,
                                "nullable": false
                            },
                            "edgeData": {
                                "feature": {
                                    "dtype": "int64",
                                    "list": true,
                                    "nullable": false
                                },
                                "list": true,
                                "nullable": false
                            }
                        },
                        "splits": {
                            "train": {
                                "name": "train",
                                "num_bytes": Math.round(systemMonitor.memoryUsage * 1024 * 1024),
                                "num_examples": dataset.crystals.length
                            }
                        }
                    }
                };
                
                zip.file("dataset_info.json", JSON.stringify(hfMetadata, null, 2));
                zip.file("data.json", JSON.stringify(hfData, null, 2));
                
                // Export images in organized folders (separate from JSON to avoid large files)
                dataset.crystals.forEach((crystal, index) => {
                    const crystalImages = dataset.capturedImages.filter(img => img.metadata.crystalId === crystal.id);
                    if (crystalImages.length > 0) {
                        const imgFolder = zip.folder(`images/crystal_${crystal.id}`);
                        crystalImages.forEach((image, imgIndex) => {
                            const base64Data = image.data.replace(/^data:image\/png;base64,/, "");
                            imgFolder.file(`${crystal.shape}_${imgIndex}.png`, base64Data, {base64: true});
                        });
                    }
                });
                
                // Create dataset card for Hugging Face
                const datasetCard = generateHuggingFaceDatasetCard(hfMetadata, dataset.crystals.length);
                zip.file("README.md", datasetCard);
                
                // Add dataset_infos.json for Hugging Face
                const datasetInfos = {
                    "default": hfMetadata
                };
                zip.file("dataset_infos.json", JSON.stringify(datasetInfos, null, 2));
                
                // Generate and download
                const content = await zip.generateAsync({type: "blob"});
                const filename = `timelink_huggingface_dataset_${timestamp}.zip`;
                
                saveAs(content, filename);
                
                showNotification("SUCCESS", "Hugging Face dataset exported! Upload data.json and images folder to HF");
                
            } catch (error) {
                console.error("TIMELINK: Export error:", error);
                showNotification("ERROR", `Export failed: ${error.message}`);
            }
        }
        
        function generateCrystalReadme(metadata, imageCount) {
            return `# TIMELINK Crystal Dataset

## Crystal Information
- **ID**: ${metadata.crystal_id}
- **Shape**: ${metadata.shape_name}
- **Vertices**: ${metadata.vertices}
- **Edges**: ${metadata.edges}
- **Generation Time**: ${metadata.generation_time.toFixed(2)} seconds
- **Images Captured**: ${imageCount}
- **Export Time**: ${metadata.export_time}

## Contents
- \`metadata.json\` - Crystal metadata
- \`crystal_data.json\` - Complete crystal structure data
- \`images/\` - Captured PNG images of growth steps
- \`README.md\` - This file

## Usage
This dataset can be used for:
1. Graph neural network training
2. 3D structure analysis
3. Time series generation studies
4. Quantum crystal simulation

## License
MIT License - Free for academic and research use.
`;
        }
        
        function generateCompleteReadme(metadata) {
            return `# TIMELINK Complete Dataset

## Dataset Overview
Total Crystals: ${metadata.total_crystals}
Total Images: ${metadata.total_images}
Generation Time: ${metadata.total_generation_time.toFixed(2)} seconds
Shapes Generated: ${metadata.shapes_generated.join(', ')}

## File Structure
\`\`\`
dataset.zip/
├── dataset.json              # Main dataset file (row-oriented)
├── dataset_metadata.json     # Complete dataset metadata
├── summary.txt              # Statistical summary
├── README.md                # This file
└── crystal_*/               # Individual crystal folders
    ├── images/              # Crystal growth images
    └── metadata.json        # Crystal-specific metadata
\`\`\`

## Data Format
Each crystal in dataset.json includes:
- 3D vertex positions (x, y, z)
- Edge connections between vertices
- Growth time series data
- Comprehensive metadata

Note: Images are stored separately in crystal folders to avoid large JSON files.

## Applications
- Machine learning training data
- 3D graph generation research
- Quantum system simulation
- Time series analysis
- Computer graphics research

## Citation
@misc{timelink2025,
  title={TIMELINK: Hybrid Time Scaling Crystal Generator},
  author={WebXOS Research},
  year={2025},
  note={Complete time crystal growth dataset}
}

## License
MIT License
`;
        }
        
        function generateHuggingFaceDatasetCard(metadata, crystalCount) {
            return `# TIMELINK Time Crystal Dataset

## Dataset Description
This dataset contains ${crystalCount} algorithmically generated time crystal structures with corresponding growth images.

### Dataset Summary
Time crystals are quantum systems that exhibit periodic motion in their ground state. This dataset captures complete growth trajectories of algorithmically generated time crystals.

### Supported Tasks
- Graph generation and completion
- Image generation from 3D structures
- Time series forecasting
- 3D structure prediction

### Languages
English

## Dataset Structure
### Data Instances
Each instance represents a complete time crystal with:
- 3D vertex positions in vertexData
- Edge connections in edgeData
- Growth images in the images folder
- Metadata including generation parameters

### Data Fields
- \`id\`: Unique crystal identifier
- \`shape\`: Crystal shape type (quantum_spiral, fractal_matrix, neural_lattice, temporal_ring)
- \`vertices\`: Number of vertices
- \`edges\`: Number of edges
- \`size\`: Crystal size metric
- \`generationSteps\`: Steps taken to generate the crystal
- \`generationTime\`: Time taken to generate (seconds)
- \`color\`: Hex color code
- \`vertexData\`: List of vertex objects with x, y, z coordinates and properties
- \`edgeData\`: List of edge connections between vertices

## Usage
\`\`\`python
from datasets import load_dataset

# Load the dataset
dataset = load_dataset("json", data_files="data.json")

# Access the first crystal
first_crystal = dataset['train'][0]
print(f"Crystal ID: {first_crystal['id']}")
print(f"Shape: {first_crystal['shape']}")
print(f"Vertices: {first_crystal['vertices']}")
\`\`\`

## Citation
${metadata.citation}

## License
${metadata.license.toUpperCase()} License

## Dataset Creation
This dataset was generated using TIMELINK v1.0 - Central Control Crystal Generator.
`;
        }
        
        function generateDatasetSummary(metadata) {
            return `TIMELINK DATASET SUMMARY
============================
Total Crystals: ${metadata.total_crystals}
Total Images: ${metadata.total_images}
Total Generation Time: ${metadata.total_generation_time.toFixed(2)} seconds
Shapes Generated: ${metadata.shapes_generated.join(', ')}
Export Time: ${metadata.export_time}
Memory Usage: ${metadata.system_info.memory_usage}
Performance Level: ${metadata.system_info.performance_level}
`;
        }
        
        // ==================== UI FUNCTIONS ====================
        function updateUI() {
            // Update crystal count
            document.getElementById('crystalCount').textContent = generationState.crystalCount;
            
            // Update crystal info
            updateCrystalInfo();
            
            // Update progress
            const crystalProgress = (generationState.currentCrystal.currentStep / generationState.currentCrystal.maxSteps) * 100;
            updateCrystalProgress(crystalProgress);
            
            // Update time display
            updateTimeDisplay();
            
            // Update dataset size
            updateDatasetSize();
        }
        
        function updateCrystalInfo() {
            const crystal = generationState.currentCrystal;
            document.getElementById('currentCrystalInfo').textContent = 
                `${formatShapeName(crystal.shape)} #${generationState.crystalCount + 1}`;
            document.getElementById('vertexCount').textContent = 
                `${crystal.vertices.length} vertices / ${crystal.edges.length} edges`;
        }
        
        function updateCrystalProgress(percent) {
            document.getElementById('crystalProgress').style.width = percent + '%';
            document.getElementById('crystalProgressText').textContent = Math.round(percent) + '%';
        }
        
        function updateTimeDisplay() {
            generationState.totalGenerationTime = (Date.now() - generationState.startTime) / 1000;
            
            const totalSeconds = Math.floor(generationState.totalGenerationTime);
            const hours = Math.floor(totalSeconds / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const seconds = totalSeconds % 60;
            
            const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            document.getElementById('timeDisplay').textContent = timeString;
            document.getElementById('totalTime').textContent = totalSeconds + 's';
        }
        
        function updateDatasetSize() {
            // Estimate dataset size
            const dataSize = JSON.stringify(dataset.crystals).length / (1024 * 1024);
            const imageSize = dataset.totalImages * 0.5; // ~0.5MB per image
            systemMonitor.memoryUsage = Math.round(dataSize + imageSize);
            
            document.getElementById('datasetSize').textContent = `${systemMonitor.memoryUsage} MB`;
            
            const datasetProgress = Math.min((systemMonitor.memoryUsage / 500) * 100, 100);
            document.getElementById('datasetProgress').style.width = datasetProgress + '%';
            
            // Update export ready status
            document.getElementById('exportReady').textContent = 
                dataset.crystals.length > 0 ? 'YES' : 'NO';
        }
        
        function updateShapeButtons() {
            document.querySelectorAll('.shape-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.textContent.includes(formatShapeName(generationState.currentShape).toUpperCase())) {
                    btn.classList.add('active');
                }
            });
        }
        
        function toggleFullscreen() {
            const elem = document.documentElement;
            
            if (!document.fullscreenElement) {
                if (elem.requestFullscreen) elem.requestFullscreen();
                else if (elem.webkitRequestFullscreen) elem.webkitRequestFullscreen();
                else if (elem.msRequestFullscreen) elem.msRequestFullscreen();
                
                document.getElementById('fullscreen-btn').textContent = '🗗 EXIT FULLSCREEN';
                isFullscreen = true;
            } else {
                if (document.exitFullscreen) document.exitFullscreen();
                else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
                else if (document.msExitFullscreen) document.msExitFullscreen();
                
                document.getElementById('fullscreen-btn').textContent = '⛶ FULLSCREEN';
                isFullscreen = false;
            }
        }
        
        function emergencyStop() {
            console.log("TIMELINK: Emergency stop activated");
            
            generationState.active = false;
            if (generationInterval) {
                clearInterval(generationInterval);
                generationInterval = null;
            }
            
            const centralBtn = document.getElementById('central-generate-btn');
            centralBtn.textContent = '⚡ GENERATE CRYSTALS';
            centralBtn.classList.remove('generating', 'paused');
            centralBtn.classList.add('float');
            centralBtn.style.animation = 'float 3s ease-in-out infinite';
            
            if (generationState.currentCrystal.vertices.length > 0) {
                exportCompleteDataset();
            }
            
            showNotification("EMERGENCY STOP", "Generation stopped. Dataset exported.");
        }
        
        function continueGeneration() {
            hideSystemWarning();
            systemMonitor.warningShown = false;
        }
        
        function showSystemWarning() {
            document.getElementById('system-warning').style.display = 'block';
        }
        
        function hideSystemWarning() {
            document.getElementById('system-warning').style.display = 'none';
        }
        
        function showNotification(title, message) {
            const notification = document.getElementById('notification');
            document.getElementById('notificationTitle').textContent = title;
            document.getElementById('notificationMessage').textContent = message;
            notification.style.display = 'block';
            
            setTimeout(() => {
                notification.style.display = 'none';
            }, 3000);
        }
        
        // ==================== ANIMATION LOOP ====================
        function animate(currentTime) {
            animationId = requestAnimationFrame(animate);
            
            // Calculate FPS
            if (!systemMonitor.lastFrameTime) {
                systemMonitor.lastFrameTime = currentTime;
                systemMonitor.frameCount = 0;
            }
            
            systemMonitor.frameCount++;
            const deltaTime = currentTime - systemMonitor.lastFrameTime;
            
            if (deltaTime >= 1000) {
                systemMonitor.fps = Math.round((systemMonitor.frameCount * 1000) / deltaTime);
                document.getElementById('fpsCounter').textContent = systemMonitor.fps;
                systemMonitor.frameCount = 0;
                systemMonitor.lastFrameTime = currentTime;
            }
            
            // Animate background particles
            if (window.particleLayers) {
                window.particleLayers.forEach((particles, index) => {
                    const positions = particles.geometry.attributes.position.array;
                    for (let i = 0; i < positions.length; i += 3) {
                        const speed = 0.05 * (index + 1);
                        positions[i] += (Math.random() - 0.5) * speed;
                        positions[i + 1] += (Math.random() - 0.5) * speed;
                        positions[i + 2] += (Math.random() - 0.5) * speed;
                    }
                    particles.geometry.attributes.position.needsUpdate = true;
                });
            }
            
            // Animate crystal rotation
            if (currentCrystal && generationState.active) {
                currentCrystal.rotation.y += 0.002 * generationState.timeScale;
                if (currentCrystal.points) {
                    currentCrystal.points.rotation.y = currentCrystal.rotation.y;
                }
            }
            
            // Update controls
            if (controls) {
                controls.update();
            }
            
            // Render
            if (renderer && scene && camera) {
                renderer.render(scene, camera);
            }
        }
        
        // ==================== INITIALIZATION ====================
        function init() {
            console.log("TIMELINK v1.0 - Central Control Generator - Initializing...");
            
            if (initThreeJS()) {
                // Setup event listeners
                document.getElementById('timeScale').addEventListener('input', function() {
                    generationState.timeScale = parseFloat(this.value);
                    document.getElementById('timeScaleValue').textContent = this.value + 'x';
                });
                
                document.addEventListener('fullscreenchange', updateFullscreenButton);
                document.addEventListener('webkitfullscreenchange', updateFullscreenButton);
                document.addEventListener('msfullscreenchange', updateFullscreenButton);
                
                window.addEventListener('resize', onWindowResize);
                
                // Start animation loop
                animate(0);
                
                console.log("TIMELINK: System ready with central generate button");
                showNotification("SYSTEM READY", "Click the central GENERATE CRYSTALS button to start");
            }
        }
        
        function updateFullscreenButton() {
            const btn = document.getElementById('fullscreen-btn');
            if (document.fullscreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
                btn.textContent = '🗗 EXIT FULLSCREEN';
                isFullscreen = true;
            } else {
                btn.textContent = '⛶ FULLSCREEN';
                isFullscreen = false;
            }
        }
        
        function onWindowResize() {
            if (camera && renderer) {
                const width = window.innerWidth;
                const height = window.innerHeight;
                
                camera.aspect = width / height;
                camera.updateProjectionMatrix();
                renderer.setSize(width, height);
            }
        }
        
        // Cleanup on page unload
        window.addEventListener('beforeunload', (e) => {
            if (generationState.active) {
                e.preventDefault();
                e.returnValue = 'Crystal generation in progress. Are you sure you want to leave?';
                emergencyStop();
            }
        });
        
        // Start when page loads
        window.addEventListener('load', init);
        
        // Global functions
        window.toggleAutomatedGeneration = toggleAutomatedGeneration;
        window.selectShape = selectShape;
        window.captureImage = captureImage;
        window.toggleAutoCapture = toggleAutoCapture;
        window.exportCurrentCrystal = exportCurrentCrystal;
        window.exportCompleteDataset = exportCompleteDataset;
        window.exportHuggingFace = exportHuggingFace;
        window.toggleFullscreen = toggleFullscreen;
        window.emergencyStop = emergencyStop;
        window.continueGeneration = continueGeneration;
    </script>
</body>
</html>