File size: 70,057 Bytes
d940355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2a66d3
 
1b2e6b0
 
8f352ef
 
 
 
aab7e66
 
 
 
1b2e6b0
 
8f352ef
 
 
 
 
 
 
 
 
1b2e6b0
 
 
 
 
 
 
d940355
 
4cce8d1
d940355
4cce8d1
d940355
4cce8d1
 
 
 
 
 
 
 
98ba7e7
4cce8d1
d940355
 
 
4cce8d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
98ba7e7
 
 
 
 
 
 
d940355
 
 
 
 
 
 
 
 
0158489
d940355
 
 
 
 
 
 
0158489
 
 
 
d940355
 
 
0158489
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96e1f74
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
96e1f74
d940355
 
0158489
 
 
 
 
 
 
 
 
 
 
 
d940355
0158489
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
0158489
d940355
0158489
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
 
 
0158489
d940355
 
4cce8d1
d940355
0158489
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
4cce8d1
 
 
 
d940355
4cce8d1
 
 
d940355
 
4cce8d1
 
 
 
 
 
 
 
 
 
0158489
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
aab7e66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ba7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
98ba7e7
 
 
 
 
 
 
 
aab7e66
 
96e1f74
 
 
 
 
 
 
 
98ba7e7
d940355
 
 
 
 
 
96e1f74
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
 
 
 
 
 
 
0158489
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aab7e66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0158489
 
 
 
 
aab7e66
 
 
 
 
 
 
 
0158489
aab7e66
0158489
98ba7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0158489
 
 
 
 
 
98ba7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0158489
 
4cce8d1
 
 
 
 
 
 
 
 
98ba7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96e1f74
 
 
 
 
 
 
 
 
 
 
4cce8d1
 
 
 
 
 
 
aab7e66
 
d940355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f352ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aab7e66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
 
 
8f352ef
 
 
 
a2a66d3
 
 
 
d940355
 
 
 
 
 
 
1b2e6b0
 
 
d940355
 
 
 
a2a66d3
d940355
 
 
1b2e6b0
 
 
 
 
 
 
 
0158489
 
 
 
 
 
 
 
aab7e66
0158489
 
aab7e66
 
0158489
aab7e66
 
 
 
 
 
 
 
 
 
0158489
d940355
 
56db2ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b2e6b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
aab7e66
 
 
 
 
 
 
 
 
1b2e6b0
 
 
0158489
 
 
 
8f352ef
 
 
 
1b2e6b0
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
 
 
 
 
 
a2a66d3
 
d940355
 
 
a2a66d3
d940355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2a66d3
 
 
 
 
98ba7e7
a2a66d3
 
 
 
 
 
 
 
 
d940355
 
 
 
e47ebf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f352ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
8f352ef
 
 
d940355
 
 
 
 
 
 
 
 
 
 
a2a66d3
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
8f352ef
 
 
 
 
 
 
 
 
 
56db2ce
1b2e6b0
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
 
 
 
 
 
 
 
 
 
8f352ef
d940355
 
 
 
 
8f352ef
 
 
 
1b2e6b0
 
 
d940355
 
 
 
 
 
8f352ef
 
 
 
 
 
1b2e6b0
 
 
 
 
d940355
 
 
 
a2a66d3
 
 
 
 
 
 
d940355
 
 
a2a66d3
 
d940355
 
8f352ef
56db2ce
1b2e6b0
d940355
 
 
 
 
8f352ef
d940355
 
aab7e66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e47ebf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
 
 
 
e47ebf0
 
 
 
 
 
 
 
 
 
 
 
 
d940355
 
 
 
 
 
 
 
 
 
 
 
8ff9916
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
"""
Evolution Aurora - WORKING DEMO with Real Visual Effects
"""

import json
import os
import random
import time
from datetime import datetime
import gradio as gr
import plotly.graph_objects as go
import numpy as np

# Global state
state = {
    "fitness_history": [0.9333],
    "events": [],
    "particles": [],
    "iteration": 0,
    "running": False,
    "variants_evaluated": 0,
    "start_time": None,
    "achievements": [],
    "high_score": 0.9333,
    "player_name": f"Player_{random.randint(1000, 9999)}",
    "multiplayer_active": False,
    "other_players": {},
    "global_best": 0.9333,
    "boss_active": False,
    "boss_health": 0,
    "boss_defeated": False
}

# Simulated multiplayer data
FAKE_PLAYERS = [
    {"name": "NeuralNinja_JP", "country": "πŸ‡―πŸ‡΅", "fitness": 0.9455, "status": "evolving"},
    {"name": "CodeEvolver_US", "country": "πŸ‡ΊπŸ‡Έ", "fitness": 0.9523, "status": "evolving"},
    {"name": "AIWizard_UK", "country": "πŸ‡¬πŸ‡§", "fitness": 0.9812, "status": "leading"},
    {"name": "QuantumCoder_DE", "country": "πŸ‡©πŸ‡ͺ", "fitness": 0.9234, "status": "struggling"},
    {"name": "MatrixMaster_FR", "country": "πŸ‡«πŸ‡·", "fitness": 0.9667, "status": "evolving"}
]

# Achievement definitions
ACHIEVEMENTS = {
    "first_evolution": {"name": "🎯 First Evolution!", "desc": "Started your first evolution", "threshold": 1},
    "fast_learner": {"name": "⚑ Fast Learner", "desc": "Reached 95% fitness", "threshold": 0.95},
    "perfectionist": {"name": "πŸ’Ž Perfectionist", "desc": "Reached 99% fitness", "threshold": 0.99},
    "speed_demon": {"name": "🏎️ Speed Demon", "desc": "Process 10+ variants/sec", "threshold": 10},
    "marathon": {"name": "πŸƒ Marathon Runner", "desc": "Run 10+ generations", "threshold": 10}
}

# HTML for aurora effect with epic intro
AURORA_HTML = """
<div id="aurora-container" style="position: relative; width: 100%; height: 400px; background: linear-gradient(to bottom, #000428, #004e92); overflow: hidden; border-radius: 10px;">
    <canvas id="aurora-canvas" style="width: 100%; height: 100%;"></canvas>
    <div id="title-container" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 10;">
        <h1 id="main-title" style="color: #00FF88; font-size: 64px; margin: 0; text-shadow: 0 0 30px #00FF88, 0 0 60px #00FF88; animation: pulse 2s ease-in-out infinite;">
            Evolution Aurora
        </h1>
        <p style="color: #FFD700; font-size: 28px; text-shadow: 0 0 20px #FFD700; margin-top: 10px; opacity: 0; animation: fadeIn 2s ease-in 1s forwards;">
            Watch AI Learn to Code in Real-Time
        </p>
        <p id="welcome-msg" style="color: #00AAFF; font-size: 20px; margin-top: 20px; opacity: 0; animation: fadeIn 2s ease-in 2s forwards;">
            🧠 Neural Network Visualization | πŸš€ Synapses Fire with Each Improvement
        </p>
    </div>
</div>

<style>
@keyframes pulse {
    0% { transform: scale(1); opacity: 0.8; }
    50% { transform: scale(1.05); opacity: 1; }
    100% { transform: scale(1); opacity: 0.8; }
}

@keyframes fadeIn {
    to { opacity: 1; }
}

@keyframes float {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-10px); }
}

#aurora-container {
    box-shadow: 0 10px 40px rgba(123, 63, 242, 0.5);
}
</style>

<script>
const canvas = document.getElementById('aurora-canvas');
const ctx = canvas.getContext('2d');
let particles = [];
let weatherSystem = {
    raindrops: [],
    lightning: false,
    lightningTimer: 0,
    rainbow: false,
    rainbowOpacity: 0
};

function resizeCanvas() {
    canvas.width = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);

class Particle {
    constructor(x, y, color, type = 'normal') {
        this.x = x;
        this.y = y;
        this.vx = (Math.random() - 0.5) * 10;
        this.vy = (Math.random() - 0.5) * 10 - 5;
        this.life = 100;
        this.color = color;
        this.size = Math.random() * 4 + 2;
        this.type = type;
        this.angle = Math.random() * Math.PI * 2;
        this.splitCount = 0;
        this.trail = [];
    }
    
    update() {
        // Store trail for quantum particles
        if (this.type === 'quantum' && this.trail.length < 20) {
            this.trail.push({x: this.x, y: this.y, alpha: this.life / 100});
        }
        
        // Quantum behavior
        if (this.type === 'quantum') {
            // Quantum tunneling
            if (Math.random() < 0.02) {
                this.x += (Math.random() - 0.5) * 100;
                this.y += (Math.random() - 0.5) * 100;
            }
            
            // Wave function collapse
            this.angle += 0.1;
            this.vx += Math.sin(this.angle) * 0.5;
            this.vy += Math.cos(this.angle) * 0.5;
            
            // Particle splitting
            if (this.life === 50 && this.splitCount === 0) {
                this.split();
            }
        }
        
        // Mouse attraction
        const dx = mouseX - this.x;
        const dy = mouseY - this.y;
        const dist = Math.sqrt(dx * dx + dy * dy);
        
        if (dist < 200 && dist > 0) {
            const force = 0.5 * (1 - dist / 200);
            this.vx += (dx / dist) * force;
            this.vy += (dy / dist) * force;
        }
        
        this.x += this.vx;
        this.y += this.vy;
        this.vy += 0.2;
        this.life--;
        this.vx *= 0.98;
        this.vy *= 0.98;
    }
    
    split() {
        this.splitCount++;
        for (let i = 0; i < 3; i++) {
            const newParticle = new Particle(this.x, this.y, this.color, 'quantum');
            newParticle.vx = (Math.random() - 0.5) * 15;
            newParticle.vy = (Math.random() - 0.5) * 15;
            newParticle.life = 50;
            newParticle.size = this.size * 0.7;
            particles.push(newParticle);
        }
    }
    
    draw() {
        // Draw trail for quantum particles
        if (this.type === 'quantum' && this.trail.length > 1) {
            ctx.save();
            ctx.strokeStyle = this.color;
            ctx.lineWidth = this.size * 0.5;
            for (let i = 1; i < this.trail.length; i++) {
                ctx.globalAlpha = this.trail[i].alpha * 0.3;
                ctx.beginPath();
                ctx.moveTo(this.trail[i-1].x, this.trail[i-1].y);
                ctx.lineTo(this.trail[i].x, this.trail[i].y);
                ctx.stroke();
            }
            ctx.restore();
        }
        
        ctx.save();
        ctx.globalAlpha = this.life / 100;
        ctx.fillStyle = this.color;
        ctx.shadowBlur = this.type === 'quantum' ? 30 : 20;
        ctx.shadowColor = this.color;
        
        // Draw quantum particles with special effect
        if (this.type === 'quantum') {
            // Outer glow
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size * 2, 0, Math.PI * 2);
            ctx.globalAlpha = (this.life / 100) * 0.3;
            ctx.fill();
            
            // Inner core
            ctx.globalAlpha = this.life / 100;
            ctx.fillStyle = '#FFFFFF';
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size * 0.5, 0, Math.PI * 2);
            ctx.fill();
        }
        
        // Normal particle
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();
    }
}

function createBurst(intensity, type = 'normal') {
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const colors = ['#00FF88', '#7B3FF2', '#00AAFF', '#FFD700', '#FF6B6B', '#4ECDC4', '#45B7D1'];
    
    if (type === 'quantum' || intensity > 4) {
        // Create quantum particles for high intensity
        for (let i = 0; i < 30 * intensity; i++) {
            const angle = (Math.PI * 2 * i) / (30 * intensity);
            const speed = Math.random() * 20 + 10;
            const color = colors[Math.floor(Math.random() * colors.length)];
            
            const quantum = new Particle(
                centerX + Math.cos(angle) * 30,
                centerY + Math.sin(angle) * 30,
                color,
                'quantum'
            );
            quantum.vx = Math.cos(angle) * speed;
            quantum.vy = Math.sin(angle) * speed;
            quantum.size = Math.random() * 6 + 3;
            particles.push(quantum);
        }
    }
    
    // Create normal burst
    for (let i = 0; i < 100 * intensity; i++) {
        const angle = (Math.PI * 2 * i) / (100 * intensity);
        const speed = Math.random() * 15 + 5;
        const color = colors[Math.floor(Math.random() * colors.length)];
        
        particles.push(new Particle(
            centerX + Math.cos(angle) * 20,
            centerY + Math.sin(angle) * 20,
            color
        ));
    }
    
    // Add some special lightning particles
    if (intensity > 3) {
        for (let j = 0; j < 20; j++) {
            const lightningParticle = new Particle(centerX, centerY, '#FFFFFF');
            lightningParticle.size = Math.random() * 8 + 4;
            lightningParticle.life = 150;
            particles.push(lightningParticle);
        }
    }
    
    // Add wormhole effect at 99%
    if (intensity > 5) {
        createWormhole();
    }
}

function createWormhole() {
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    
    // Create spiral of quantum particles
    for (let i = 0; i < 100; i++) {
        const angle = (i / 100) * Math.PI * 8;
        const radius = i * 2;
        
        const wormhole = new Particle(
            centerX + Math.cos(angle) * radius,
            centerY + Math.sin(angle) * radius,
            '#FF00FF',
            'quantum'
        );
        wormhole.vx = -Math.cos(angle) * 5;
        wormhole.vy = -Math.sin(angle) * 5;
        wormhole.life = 200;
        particles.push(wormhole);
    }
}

// Click to damage boss
canvas.addEventListener('click', (e) => {
    const rect = canvas.getBoundingClientRect();
    const x = (e.clientX - rect.left) * (canvas.width / rect.width);
    const y = (e.clientY - rect.top) * (canvas.height / rect.height);
    
    // Create burst at click location
    for (let i = 0; i < 50; i++) {
        const angle = (Math.PI * 2 * i) / 50;
        const speed = Math.random() * 10 + 5;
        particles.push(new Particle(
            x + Math.cos(angle) * 10,
            y + Math.sin(angle) * 10,
            ['#00FF88', '#7B3FF2', '#00AAFF', '#FFD700'][Math.floor(Math.random() * 4)]
        ));
    }
    
    // Damage boss if active and clicked on it
    if (bossActive && bossHealth > 0) {
        const bossX = canvas.width / 2;
        const bossY = canvas.height / 3;
        const dist = Math.sqrt((x - bossX) ** 2 + (y - bossY) ** 2);
        
        if (dist < 80) {
            bossHealth = Math.max(0, bossHealth - 10);
            createBurst(3, 'quantum');
            
            if (bossHealth <= 0 && bossActive) {
                // Boss defeated!
                bossActive = false;
                window.bossDamageCallback && window.bossDamageCallback();
                
                // Victory effects
                for (let i = 0; i < 5; i++) {
                    setTimeout(() => {
                        createBurst(10, 'quantum');
                        triggerGlitch();
                    }, i * 200);
                }
            }
        }
    }
});

// Track current fitness for neural network
let currentFitness = 0.9333;

// Weather System
class Raindrop {
    constructor() {
        this.x = Math.random() * canvas.width;
        this.y = -10;
        this.speed = Math.random() * 5 + 10;
        this.length = Math.random() * 20 + 10;
        this.opacity = Math.random() * 0.5 + 0.3;
    }
    
    update() {
        this.y += this.speed;
        if (this.y > canvas.height) {
            this.y = -10;
            this.x = Math.random() * canvas.width;
        }
    }
    
    draw() {
        ctx.save();
        ctx.strokeStyle = `rgba(100, 150, 255, ${this.opacity})`;
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(this.x, this.y);
        ctx.lineTo(this.x, this.y + this.length);
        ctx.stroke();
        ctx.restore();
    }
}

function drawWeather() {
    // Rain effect
    weatherSystem.raindrops.forEach(drop => {
        drop.update();
        drop.draw();
    });
    
    // Lightning effect
    if (weatherSystem.lightning && weatherSystem.lightningTimer > 0) {
        ctx.save();
        ctx.fillStyle = `rgba(255, 255, 255, ${weatherSystem.lightningTimer / 10})`;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // Draw lightning bolt
        if (weatherSystem.lightningTimer > 5) {
            ctx.strokeStyle = '#FFFFFF';
            ctx.lineWidth = 3;
            ctx.shadowBlur = 20;
            ctx.shadowColor = '#00AAFF';
            
            const startX = Math.random() * canvas.width;
            const segments = 5;
            let x = startX;
            let y = 0;
            
            ctx.beginPath();
            ctx.moveTo(x, y);
            
            for (let i = 0; i < segments; i++) {
                x += (Math.random() - 0.5) * 100;
                y += canvas.height / segments;
                ctx.lineTo(x, y);
            }
            
            ctx.stroke();
        }
        
        ctx.restore();
        weatherSystem.lightningTimer--;
    }
    
    // Rainbow effect
    if (weatherSystem.rainbow && weatherSystem.rainbowOpacity > 0) {
        ctx.save();
        const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height / 2);
        const colors = ['#FF0000', '#FF7F00', '#FFFF00', '#00FF00', '#0000FF', '#4B0082', '#9400D3'];
        
        colors.forEach((color, i) => {
            gradient.addColorStop(i / (colors.length - 1), color);
        });
        
        ctx.fillStyle = gradient;
        ctx.globalAlpha = weatherSystem.rainbowOpacity;
        ctx.beginPath();
        ctx.arc(canvas.width / 2, canvas.height, canvas.width, 0, Math.PI, true);
        ctx.fill();
        ctx.restore();
    }
}

function triggerLightning() {
    weatherSystem.lightning = true;
    weatherSystem.lightningTimer = 10;
    
    // Create burst at lightning strike point
    createBurst(3);
}

function startRain() {
    // Create raindrops
    for (let i = 0; i < 50; i++) {
        weatherSystem.raindrops.push(new Raindrop());
    }
}

function stopRain() {
    weatherSystem.raindrops = [];
}

function showRainbow() {
    weatherSystem.rainbow = true;
    // Fade in
    const fadeIn = setInterval(() => {
        weatherSystem.rainbowOpacity += 0.02;
        if (weatherSystem.rainbowOpacity >= 0.3) {
            clearInterval(fadeIn);
            // Fade out after 3 seconds
            setTimeout(() => {
                const fadeOut = setInterval(() => {
                    weatherSystem.rainbowOpacity -= 0.02;
                    if (weatherSystem.rainbowOpacity <= 0) {
                        weatherSystem.rainbow = false;
                        weatherSystem.rainbowOpacity = 0;
                        clearInterval(fadeOut);
                    }
                }, 50);
            }, 3000);
        }
    }, 50);
}

function animate() {
    ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // Draw weather effects first (background)
    drawWeather();
    
    // Draw neural network (middle layer)
    neuralNetwork.update(currentFitness);
    neuralNetwork.draw(ctx);
    
    // Draw boss (above neural network)
    drawBoss();
    
    // Mouse glow effect
    const gradient = ctx.createRadialGradient(mouseX, mouseY, 0, mouseX, mouseY, 100);
    gradient.addColorStop(0, 'rgba(123, 63, 242, 0.3)');
    gradient.addColorStop(0.5, 'rgba(0, 170, 255, 0.1)');
    gradient.addColorStop(1, 'rgba(0, 255, 136, 0)');
    ctx.fillStyle = gradient;
    ctx.fillRect(mouseX - 100, mouseY - 100, 200, 200);
    
    // Draw particles (foreground layer)
    particles = particles.filter(p => {
        p.update();
        p.draw();
        return p.life > 0;
    });
    
    // Draw cursor sparkle
    ctx.save();
    ctx.fillStyle = '#FFFFFF';
    ctx.shadowBlur = 20;
    ctx.shadowColor = '#00FF88';
    ctx.beginPath();
    ctx.arc(mouseX, mouseY, 3, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
    
    requestAnimationFrame(animate);
}
animate();

// Trigger burst every 2 seconds
setInterval(() => {
    if (Math.random() > 0.3) {
        createBurst(Math.random() * 2 + 1);
    }
}, 2000);

// Reality glitch effect
let glitchActive = false;
function triggerGlitch() {
    glitchActive = true;
    document.body.style.filter = 'hue-rotate(180deg) invert(100%)';
    
    setTimeout(() => {
        document.body.style.filter = 'hue-rotate(90deg)';
    }, 100);
    
    setTimeout(() => {
        document.body.style.filter = 'none';
        glitchActive = false;
    }, 300);
    
    // Create massive quantum burst
    createBurst(10, 'quantum');
}

// Boss battle system
let bossActive = false;
let bossHealth = 100;

function drawBoss() {
    if (!bossActive) return;
    
    const bossX = canvas.width / 2;
    const bossY = canvas.height / 3;
    
    // Boss body (menacing eye)
    ctx.save();
    ctx.fillStyle = '#FF0000';
    ctx.strokeStyle = '#000000';
    ctx.lineWidth = 3;
    
    // Outer eye
    ctx.beginPath();
    ctx.ellipse(bossX, bossY, 80, 40, 0, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    
    // Inner eye
    ctx.fillStyle = '#000000';
    ctx.beginPath();
    ctx.arc(bossX, bossY, 20, 0, Math.PI * 2);
    ctx.fill();
    
    // Pupil that follows mouse
    const dx = mouseX - bossX;
    const dy = mouseY - bossY;
    const angle = Math.atan2(dy, dx);
    const pupilX = bossX + Math.cos(angle) * 10;
    const pupilY = bossY + Math.sin(angle) * 10;
    
    ctx.fillStyle = '#FFFFFF';
    ctx.beginPath();
    ctx.arc(pupilX, pupilY, 5, 0, Math.PI * 2);
    ctx.fill();
    
    // Health bar
    ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';
    ctx.fillRect(bossX - 50, bossY - 70, 100, 10);
    ctx.fillStyle = 'rgba(0, 255, 0, 0.8)';
    ctx.fillRect(bossX - 50, bossY - 70, bossHealth, 10);
    ctx.strokeRect(bossX - 50, bossY - 70, 100, 10);
    
    // Boss title
    ctx.fillStyle = '#FFFFFF';
    ctx.font = 'bold 20px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('THE LOCAL OPTIMUM', bossX, bossY - 80);
    
    ctx.restore();
    
    // Boss attacks
    if (Math.random() < 0.02 && bossHealth > 0) {
        // Laser beam attack
        for (let i = 0; i < 20; i++) {
            const attackParticle = new Particle(
                bossX + (Math.random() - 0.5) * 50,
                bossY,
                '#FF0000'
            );
            attackParticle.vy = 10;
            attackParticle.vx = (Math.random() - 0.5) * 5;
            particles.push(attackParticle);
        }
    }
}

// Watch for quantum and boss events
const watchQuantum = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        const text = mutation.target.textContent || '';
        if (text.includes('QUANTUM REALM ENTERED')) {
            createBurst(5, 'quantum');
        } else if (text.includes('BOSS APPEARED')) {
            bossActive = true;
            bossHealth = 100;
            speak("Warning! Final boss detected. The Local Optimum blocks your path to perfection!", 1.1, 0.8);
        } else if (text.includes('BOSS DEFEATED')) {
            bossActive = false;
            bossHealth = 0;
            createBurst(20, 'quantum'); // Massive victory explosion
            triggerGlitch();
            speak("Victory! You have achieved perfection! 100 percent fitness!", 1.2, 1.2);
        }
        
        // Check for fitness updates
        const fitnessMatch = text.match(/Fitness (\d+\.\d+)/);
        if (fitnessMatch) {
            const newFitness = parseFloat(fitnessMatch[1]);
            if (newFitness > currentFitness) {
                const improvement = newFitness - currentFitness;
                currentFitness = newFitness;
                // Trigger neural network firing
                neuralNetwork.triggerFitnessImprovement(improvement);
                
                // Weather effects based on improvement
                if (improvement > 0.005) {
                    triggerLightning(); // Lightning for major improvements
                }
                
                // Rainbow at 95%
                if (newFitness >= 0.95 && currentFitness < 0.96) {
                    showRainbow();
                    stopRain();
                }
                
                // Rain when plateauing
                if (improvement < 0.002 && weatherSystem.raindrops.length === 0) {
                    startRain();
                }
            }
        }
    });
});

setTimeout(() => {
    const eventLog = document.querySelector('[id*="event_log"]');
    if (eventLog) watchQuantum.observe(eventLog, { childList: true, subtree: true });
    
    // Also watch fitness display directly
    const fitnessDisplay = document.querySelector('[id*="fitness_display"]');
    if (fitnessDisplay) {
        const fitnessObserver = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                const input = mutation.target.querySelector('input');
                if (input && input.value) {
                    const newFitness = parseFloat(input.value);
                    if (!isNaN(newFitness) && newFitness !== currentFitness) {
                        currentFitness = newFitness;
                    }
                }
            });
        });
        fitnessObserver.observe(fitnessDisplay, { childList: true, subtree: true, attributes: true });
    }
}, 2000);

// Epic initial burst sequence
setTimeout(() => {
    createBurst(5); // Massive initial burst
    document.getElementById('welcome-msg').style.fontSize = '24px';
}, 500);

setTimeout(() => createBurst(3), 1500);
setTimeout(() => createBurst(4), 2500);

// Neural Network Visualization
class NeuralNetwork {
    constructor() {
        this.neurons = [];
        this.synapses = [];
        this.layers = [5, 8, 6, 4, 1]; // Network architecture
        this.setupNetwork();
        this.pulsePhase = 0;
        this.lastFitness = 0.9333;
        this.firingNeurons = new Set();
        this.brainWavePhase = 0;
    }
    
    setupNetwork() {
        const centerX = canvas.width / 2;
        const centerY = canvas.height / 2;
        const networkWidth = 400;
        const networkHeight = 300;
        
        // Create neurons for each layer
        for (let layer = 0; layer < this.layers.length; layer++) {
            const layerNeurons = [];
            const x = centerX - networkWidth/2 + (layer / (this.layers.length - 1)) * networkWidth;
            
            for (let i = 0; i < this.layers[layer]; i++) {
                const y = centerY - networkHeight/2 + ((i + 0.5) / this.layers[layer]) * networkHeight;
                layerNeurons.push({
                    x: x,
                    y: y,
                    layer: layer,
                    index: i,
                    activation: Math.random() * 0.3,
                    pulseOffset: Math.random() * Math.PI * 2,
                    size: layer === this.layers.length - 1 ? 15 : 8 - layer // Output neuron is bigger
                });
            }
            this.neurons.push(layerNeurons);
        }
        
        // Create synapses between layers
        for (let layer = 0; layer < this.layers.length - 1; layer++) {
            for (let i = 0; i < this.neurons[layer].length; i++) {
                for (let j = 0; j < this.neurons[layer + 1].length; j++) {
                    this.synapses.push({
                        from: this.neurons[layer][i],
                        to: this.neurons[layer + 1][j],
                        weight: Math.random() * 0.5 + 0.1,
                        active: false,
                        pulseProgress: 0
                    });
                }
            }
        }
    }
    
    update(currentFitness) {
        this.pulsePhase += 0.02;
        this.brainWavePhase += 0.015;
        
        // Check if fitness improved
        const fitnessImproved = currentFitness > this.lastFitness + 0.0001;
        
        if (fitnessImproved) {
            // Activate firing sequence
            this.triggerFitnessImprovement(currentFitness - this.lastFitness);
        }
        
        this.lastFitness = currentFitness;
        
        // Update neuron activations with brain wave effect
        for (let layer of this.neurons) {
            for (let neuron of layer) {
                // Base pulsing
                neuron.activation = 0.3 + 0.2 * Math.sin(this.pulsePhase + neuron.pulseOffset);
                
                // Add brain wave effect
                const waveInfluence = Math.sin(this.brainWavePhase + neuron.x * 0.01 + neuron.y * 0.01) * 0.2;
                neuron.activation += waveInfluence;
                
                // Firing neurons glow brighter
                if (this.firingNeurons.has(neuron)) {
                    neuron.activation = Math.min(1, neuron.activation + 0.5);
                }
            }
        }
        
        // Update synapses
        for (let synapse of this.synapses) {
            if (synapse.active) {
                synapse.pulseProgress += 0.05;
                if (synapse.pulseProgress >= 1) {
                    synapse.active = false;
                    synapse.pulseProgress = 0;
                    // Activate the target neuron
                    this.firingNeurons.add(synapse.to);
                    setTimeout(() => this.firingNeurons.delete(synapse.to), 500);
                }
            }
        }
    }
    
    triggerFitnessImprovement(improvement) {
        // Fire neurons based on improvement magnitude
        const fireCount = Math.min(20, Math.floor(improvement * 1000));
        
        // Major milestone effects
        if (this.lastFitness >= 0.95 && this.lastFitness < 0.95 + improvement) {
            // 95% milestone - neural storm
            this.triggerNeuralStorm();
        }
        if (this.lastFitness >= 0.99 && this.lastFitness < 0.99 + improvement) {
            // 99% milestone - neural overload
            this.triggerNeuralOverload();
        }
        
        // Start with random input neurons
        for (let i = 0; i < fireCount; i++) {
            const neuron = this.neurons[0][Math.floor(Math.random() * this.neurons[0].length)];
            this.firingNeurons.add(neuron);
            
            // Propagate through network
            setTimeout(() => {
                this.propagateActivation(neuron);
            }, i * 50);
        }
        
        // Create synapse firing wave
        const synapsesToFire = this.synapses.filter(s => Math.random() < improvement * 50);
        synapsesToFire.forEach((synapse, i) => {
            setTimeout(() => {
                synapse.active = true;
                synapse.pulseProgress = 0;
            }, i * 20);
        });
    }
    
    triggerNeuralStorm() {
        // Fire all neurons in waves
        for (let layer = 0; layer < this.neurons.length; layer++) {
            setTimeout(() => {
                this.neurons[layer].forEach(neuron => {
                    this.firingNeurons.add(neuron);
                    setTimeout(() => this.firingNeurons.delete(neuron), 1000);
                });
            }, layer * 200);
        }
        
        // Activate many synapses
        this.synapses.forEach((synapse, i) => {
            if (Math.random() < 0.7) {
                setTimeout(() => {
                    synapse.active = true;
                    synapse.pulseProgress = 0;
                }, Math.random() * 1000);
            }
        });
    }
    
    triggerNeuralOverload() {
        // Extreme effect - all neurons and synapses fire rapidly
        const overloadDuration = 3000;
        const overloadInterval = setInterval(() => {
            // Random neurons fire
            for (let i = 0; i < 10; i++) {
                const layer = Math.floor(Math.random() * this.neurons.length);
                const index = Math.floor(Math.random() * this.neurons[layer].length);
                const neuron = this.neurons[layer][index];
                this.firingNeurons.add(neuron);
                setTimeout(() => this.firingNeurons.delete(neuron), 200);
            }
            
            // Random synapses fire
            for (let i = 0; i < 20; i++) {
                const synapse = this.synapses[Math.floor(Math.random() * this.synapses.length)];
                synapse.active = true;
                synapse.pulseProgress = 0;
            }
        }, 100);
        
        setTimeout(() => clearInterval(overloadInterval), overloadDuration);
    }
    
    propagateActivation(neuron) {
        // Find synapses from this neuron
        const outgoingSynapses = this.synapses.filter(s => s.from === neuron);
        
        outgoingSynapses.forEach((synapse, i) => {
            setTimeout(() => {
                synapse.active = true;
                synapse.pulseProgress = 0;
            }, i * 100);
        });
    }
    
    draw(ctx) {
        ctx.save();
        
        // Set overall neural network opacity
        ctx.globalAlpha = 0.7;
        
        // Draw brain scan background effect
        this.drawBrainScan(ctx);
        
        // Draw synapses
        for (let synapse of this.synapses) {
            ctx.save();
            
            const baseAlpha = 0.2 + synapse.weight * 0.3;
            ctx.globalAlpha = synapse.active ? Math.min(1, baseAlpha + 0.6) : baseAlpha;
            
            // Draw synapse line
            ctx.beginPath();
            ctx.moveTo(synapse.from.x, synapse.from.y);
            ctx.lineTo(synapse.to.x, synapse.to.y);
            
            const gradient = ctx.createLinearGradient(
                synapse.from.x, synapse.from.y,
                synapse.to.x, synapse.to.y
            );
            
            if (synapse.active) {
                // Firing synapse - animated pulse
                const pulsePos = synapse.pulseProgress;
                gradient.addColorStop(0, 'rgba(0, 255, 136, 0.1)');
                gradient.addColorStop(Math.max(0, pulsePos - 0.1), 'rgba(0, 255, 136, 0.1)');
                gradient.addColorStop(pulsePos, 'rgba(255, 255, 255, 1)');
                gradient.addColorStop(Math.min(1, pulsePos + 0.1), 'rgba(0, 255, 136, 0.1)');
                gradient.addColorStop(1, 'rgba(123, 63, 242, 0.1)');
                
                ctx.lineWidth = 3;
                ctx.shadowBlur = 20;
                ctx.shadowColor = '#00FF88';
            } else {
                gradient.addColorStop(0, 'rgba(0, 170, 255, 0.2)');
                gradient.addColorStop(1, 'rgba(123, 63, 242, 0.2)');
                ctx.lineWidth = 1;
            }
            
            ctx.strokeStyle = gradient;
            ctx.stroke();
            ctx.restore();
        }
        
        // Draw neurons
        for (let layer of this.neurons) {
            for (let neuron of layer) {
                ctx.save();
                
                const isFiring = this.firingNeurons.has(neuron);
                const isOutput = neuron.layer === this.layers.length - 1;
                
                // Neuron glow
                if (isFiring || isOutput) {
                    const glowGradient = ctx.createRadialGradient(
                        neuron.x, neuron.y, 0,
                        neuron.x, neuron.y, neuron.size * 3
                    );
                    glowGradient.addColorStop(0, isFiring ? 'rgba(255, 255, 255, 0.5)' : 'rgba(255, 215, 0, 0.3)');
                    glowGradient.addColorStop(0.5, isFiring ? 'rgba(0, 255, 136, 0.3)' : 'rgba(255, 215, 0, 0.1)');
                    glowGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
                    
                    ctx.fillStyle = glowGradient;
                    ctx.fillRect(neuron.x - neuron.size * 3, neuron.y - neuron.size * 3, 
                                neuron.size * 6, neuron.size * 6);
                }
                
                // Neuron body
                ctx.beginPath();
                ctx.arc(neuron.x, neuron.y, neuron.size, 0, Math.PI * 2);
                
                const neuronGradient = ctx.createRadialGradient(
                    neuron.x - neuron.size/3, neuron.y - neuron.size/3, 0,
                    neuron.x, neuron.y, neuron.size
                );
                
                if (isOutput) {
                    // Output neuron - golden
                    neuronGradient.addColorStop(0, '#FFD700');
                    neuronGradient.addColorStop(1, '#FFA500');
                } else if (isFiring) {
                    // Firing neuron - bright white/green
                    neuronGradient.addColorStop(0, '#FFFFFF');
                    neuronGradient.addColorStop(1, '#00FF88');
                } else {
                    // Normal neuron - blue/purple gradient
                    const brightness = neuron.activation;
                    neuronGradient.addColorStop(0, `rgba(0, 170, 255, ${brightness})`);
                    neuronGradient.addColorStop(1, `rgba(123, 63, 242, ${brightness * 0.7})`);
                }
                
                ctx.fillStyle = neuronGradient;
                ctx.fill();
                
                // Neuron outline
                ctx.strokeStyle = isFiring ? '#FFFFFF' : 'rgba(255, 255, 255, 0.2)';
                ctx.lineWidth = isFiring ? 2 : 1;
                ctx.stroke();
                
                ctx.restore();
            }
        }
        
        ctx.restore();
    }
    
    drawBrainScan(ctx) {
        // Brain scan effect - concentric circles emanating from center
        const centerX = canvas.width / 2;
        const centerY = canvas.height / 2;
        
        ctx.save();
        
        // Draw multiple scan waves
        for (let i = 0; i < 5; i++) {
            const radius = (this.brainWavePhase * 100 + i * 100) % 500;
            const alpha = Math.max(0, 1 - radius / 500) * 0.3;
            
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
            
            // Create gradient stroke
            const gradient = ctx.createRadialGradient(centerX, centerY, radius - 10, centerX, centerY, radius + 10);
            gradient.addColorStop(0, `rgba(0, 255, 136, 0)`);
            gradient.addColorStop(0.5, `rgba(0, 255, 136, ${alpha})`);
            gradient.addColorStop(1, `rgba(123, 63, 242, 0)`);
            
            ctx.strokeStyle = gradient;
            ctx.lineWidth = 3;
            ctx.stroke();
        }
        
        // Add "thinking" pulses randomly
        if (Math.random() < 0.05) {
            // Random thinking pulse
            const pulseX = centerX + (Math.random() - 0.5) * 300;
            const pulseY = centerY + (Math.random() - 0.5) * 200;
            
            const pulseGradient = ctx.createRadialGradient(pulseX, pulseY, 0, pulseX, pulseY, 50);
            pulseGradient.addColorStop(0, 'rgba(255, 255, 255, 0.4)');
            pulseGradient.addColorStop(0.5, 'rgba(0, 170, 255, 0.2)');
            pulseGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
            
            ctx.fillStyle = pulseGradient;
            ctx.fillRect(pulseX - 50, pulseY - 50, 100, 100);
        }
        
        ctx.restore();
    }
}

// Initialize neural network
const neuralNetwork = new NeuralNetwork();

// Mouse interaction
let mouseX = canvas.width / 2;
let mouseY = canvas.height / 2;

canvas.addEventListener('mousemove', (e) => {
    const rect = canvas.getBoundingClientRect();
    mouseX = (e.clientX - rect.left) * (canvas.width / rect.width);
    mouseY = (e.clientY - rect.top) * (canvas.height / rect.height);
});


// Auto-start evolution after intro
setTimeout(() => {
    const startBtn = document.querySelector('.gr-button-primary');
    if (startBtn && startBtn.textContent.includes('Start')) {
        startBtn.click();
    }
}, 4000);

// Boss defeat callback is now defined in the main app
</script>
"""

def create_3d_landscape():
    """Create an animated 3D fitness landscape."""
    # Create mesh grid
    x = np.linspace(-5, 5, 50)
    y = np.linspace(-5, 5, 50)
    X, Y = np.meshgrid(x, y)
    
    # Create landscape with multiple peaks
    Z = np.sin(np.sqrt(X**2 + Y**2)) / np.sqrt(X**2 + Y**2 + 1)
    Z += 0.5 * np.exp(-((X-2)**2 + (Y-2)**2) / 3)
    Z += 0.8 * np.exp(-((X+2)**2 + (Y-1)**2) / 2)
    
    fig = go.Figure(data=[go.Surface(
        x=X, y=Y, z=Z,
        colorscale=[
            [0, '#0A0A2A'],
            [0.5, '#7B3FF2'],
            [1, '#00FF88']
        ],
        opacity=0.9,
        lighting=dict(
            ambient=0.4,
            diffuse=0.5,
            specular=0.2,
            roughness=0.5,
            fresnel=0.2
        ),
        lightposition=dict(x=-100, y=-100, z=50)
    )])
    
    # Add moving points representing evolving programs
    if state["fitness_history"]:
        n_points = min(len(state["fitness_history"]), 10)
        for i in range(n_points):
            t = i / max(n_points - 1, 1)
            fitness = state["fitness_history"][-(n_points-i)]
            
            # Spiral path
            angle = t * 4 * np.pi
            radius = 3 * (1 - t)
            x_pos = radius * np.cos(angle)
            y_pos = radius * np.sin(angle)
            z_pos = fitness - 0.9
            
            fig.add_trace(go.Scatter3d(
                x=[x_pos], y=[y_pos], z=[z_pos],
                mode='markers',
                marker=dict(
                    size=10,
                    color='#FFD700' if i == n_points - 1 else '#00FF88',
                    symbol='diamond'
                ),
                showlegend=False
            ))
    
    fig.update_layout(
        scene=dict(
            xaxis=dict(showgrid=False, showticklabels=False, title=''),
            yaxis=dict(showgrid=False, showticklabels=False, title=''),
            zaxis=dict(showgrid=True, title='Fitness'),
            camera=dict(
                eye=dict(x=1.5, y=1.5, z=1.5),
                up=dict(x=0, y=0, z=1)
            ),
            aspectmode='cube'
        ),
        paper_bgcolor='#0A0A2A',
        plot_bgcolor='#0A0A2A',
        height=500,
        margin=dict(l=0, r=0, t=0, b=0)
    )
    
    return fig

def create_fitness_chart():
    """Create animated fitness progress chart."""
    fig = go.Figure()
    
    if state["fitness_history"]:
        x = list(range(len(state["fitness_history"])))
        y = state["fitness_history"]
        
        # Main line
        fig.add_trace(go.Scatter(
            x=x, y=y,
            mode='lines+markers',
            name='Fitness',
            line=dict(color='#00FF88', width=4),
            marker=dict(size=8, color='#7B3FF2', line=dict(color='#00FF88', width=2))
        ))
        
        # Add glow effect
        fig.add_trace(go.Scatter(
            x=x, y=y,
            mode='lines',
            line=dict(color='#00FF88', width=12),
            opacity=0.3,
            showlegend=False
        ))
    
    fig.update_layout(
        xaxis=dict(
            title='Generation',
            gridcolor='#333',
            zerolinecolor='#333'
        ),
        yaxis=dict(
            title='Fitness Score',
            gridcolor='#333',
            zerolinecolor='#333',
            range=[0.9, 1.0]
        ),
        paper_bgcolor='#0A0A2A',
        plot_bgcolor='#0A0A2A',
        font=dict(color='#FFF'),
        height=400,
        showlegend=False
    )
    
    return fig

def update_multiplayer():
    """Update multiplayer state with other players' progress."""
    if not state["multiplayer_active"]:
        return
    
    # Simulate other players making progress
    for player in FAKE_PLAYERS:
        if random.random() < 0.3:  # 30% chance of improvement
            improvement = random.uniform(0.001, 0.01)
            player["fitness"] = min(player["fitness"] + improvement, 0.9999)
            
            # Check if someone beat us
            current_fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
            if player["fitness"] > current_fitness and player["fitness"] > state["global_best"]:
                state["global_best"] = player["fitness"]
                state["events"].append({
                    "time": datetime.now().strftime("%H:%M:%S"),
                    "type": "multiplayer",
                    "message": f"⚑ {player['name']} {player['country']} TOOK THE LEAD! ({player['fitness']:.4f})"
                })

def format_multiplayer_leaderboard():
    """Format live multiplayer leaderboard."""
    current_fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
    
    # Combine all players
    all_players = [{"name": state["player_name"], "country": "🏴", "fitness": current_fitness, "status": "you"}]
    all_players.extend(FAKE_PLAYERS)
    
    # Sort by fitness
    all_players.sort(key=lambda x: x["fitness"], reverse=True)
    
    html = '''
    <div style="background: linear-gradient(135deg, #1a1a3a, #0a0a2a); padding: 20px; border-radius: 10px; border: 2px solid #7B3FF2;">
        <h3 style="color: #FFD700; margin-top: 0; text-align: center;">πŸ† LIVE GLOBAL LEADERBOARD</h3>
        <div style="max-height: 400px; overflow-y: auto;">
    '''
    
    for i, player in enumerate(all_players):
        rank = i + 1
        medal = "πŸ₯‡" if rank == 1 else "πŸ₯ˆ" if rank == 2 else "πŸ₯‰" if rank == 3 else f"#{rank}"
        
        is_you = player["status"] == "you"
        bg_color = "linear-gradient(45deg, #FFD700, #FFA500)" if is_you else "rgba(123, 63, 242, 0.2)"
        border = "2px solid #FFD700" if rank == 1 else "1px solid rgba(255, 255, 255, 0.1)"
        
        html += f'''
        <div style="background: {bg_color}; margin: 10px 0; padding: 15px; border-radius: 8px; border: {border}; 
                    {'animation: pulse 2s infinite;' if is_you else ''} transition: all 0.3s;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div style="font-size: 20px; color: {'#000' if is_you else '#FFF'};">
                    {medal} {player['country']} <strong>{player['name']}</strong>
                    {' (YOU)' if is_you else ''}
                </div>
                <div style="font-size: 24px; color: {'#000' if is_you else '#00FF88'}; font-weight: bold;">
                    {player['fitness']:.4f}
                </div>
            </div>
            {'<div style="color: #FFD700; font-size: 14px; margin-top: 5px;">πŸ”₯ YOUR POSITION</div>' if is_you else ''}
        </div>
        '''
    
    html += '''
        </div>
        <div style="text-align: center; margin-top: 20px;">
            <button style="background: linear-gradient(45deg, #FF6B6B, #4ECDC4); color: white; border: none; 
                          padding: 10px 30px; border-radius: 25px; font-size: 18px; cursor: pointer;"
                    onclick="alert('Multiplayer Battle Mode: Coming Soon!')">
                βš”οΈ CHALLENGE TOP PLAYER
            </button>
        </div>
    </div>
    '''
    
    return html

def handle_boss_defeat():
    """Handle boss defeat and reach 100% fitness."""
    if state["boss_active"] and state["boss_health"] <= 0:
        state["boss_defeated"] = True
        state["boss_active"] = False
        state["fitness_history"].append(1.0)  # 100% fitness!
        
        state["events"].append({
            "time": datetime.now().strftime("%H:%M:%S"),
            "type": "victory",
            "message": "πŸŽ‰ BOSS DEFEATED! You've achieved 100% FITNESS! PERFECTION ATTAINED!"
        })
        
        # Unlock special achievement
        if "perfection_plus" not in state["achievements"]:
            state["achievements"].append("perfection_plus")
            state["events"].append({
                "time": datetime.now().strftime("%H:%M:%S"),
                "type": "achievement",
                "message": "πŸ† LEGENDARY ACHIEVEMENT: Perfection Plus Ultra!"
            })
        
        return True
    return False

def simulate_evolution():
    """Simulate one evolution step."""
    if not state["running"]:
        return
    
    state["iteration"] += 1
    
    # Update multiplayer if active
    if state["multiplayer_active"]:
        update_multiplayer()
    
    # Simulate evaluating multiple variants (Modal parallel execution)
    variants_this_gen = random.randint(4, 8)  # Simulating parallel evaluation
    state["variants_evaluated"] += variants_this_gen
    
    # Simulate fitness improvement
    current_fitness = state["fitness_history"][-1]
    improvement = random.uniform(0.001, 0.015) * (1 - current_fitness)
    new_fitness = min(current_fitness + improvement, 0.9999)
    
    state["fitness_history"].append(new_fitness)
    
    # Check for new achievements
    new_achievements = check_achievements()
    
    # Add event
    event = {
        "time": datetime.now().strftime("%H:%M:%S"),
        "type": "improvement" if improvement > 0.005 else "minor",
        "message": f"Generation {state['iteration']}: Fitness {new_fitness:.4f} (+{improvement:.4f}) - {variants_this_gen} variants evaluated"
    }
    state["events"].append(event)
    
    # Add achievement events
    for ach in new_achievements:
        state["events"].append({
            "time": datetime.now().strftime("%H:%M:%S"),
            "type": "achievement",
            "message": f"πŸ† ACHIEVEMENT UNLOCKED: {ach['name']}"
        })
    
    # Trigger quantum effects at high fitness levels
    if new_fitness >= 0.95 and current_fitness < 0.95:
        state["events"].append({
            "time": datetime.now().strftime("%H:%M:%S"),
            "type": "quantum",
            "message": "βš›οΈ QUANTUM REALM ENTERED! Reality is bending..."
        })
    
    if new_fitness >= 0.99 and current_fitness < 0.99:
        state["events"].append({
            "time": datetime.now().strftime("%H:%M:%S"),
            "type": "boss",
            "message": "πŸ‘Ύ FINAL BOSS APPEARED: The Local Optimum! Click on it to attack!"
        })
        # Trigger boss battle
        state["boss_active"] = True
        state["boss_health"] = 100
    
    # Boss battle progress
    if state["boss_active"] and state["boss_health"] > 0:
        # Boss slowly damages our fitness
        damage = random.uniform(0.0001, 0.0005)
        new_fitness = max(0.98, new_fitness - damage)
        state["fitness_history"][-1] = new_fitness
    
    return event

def get_evolved_code():
    """Generate example of evolved code with improvements."""
    iteration = state.get("iteration", 0)
    fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
    
    # Base code
    base_code = '''def create_model(X_train, y_train):
    """Create and train a DecisionTree model."""
    model = DecisionTreeClassifier(
        max_depth=3,
        min_samples_split=2,
        random_state=42
    )
    model.fit(X_train, y_train)
    return model'''
    
    # Evolved improvements based on iteration
    if iteration == 0:
        return base_code, base_code, []
    
    improvements = []
    evolved_code = base_code
    
    if iteration >= 1:
        evolved_code = evolved_code.replace("max_depth=3", "max_depth=5")
        improvements.append("↑ Increased max_depth: 3 β†’ 5")
    
    if iteration >= 2:
        evolved_code = evolved_code.replace("min_samples_split=2", "min_samples_split=5")
        improvements.append("↑ Optimized min_samples_split: 2 β†’ 5")
    
    if iteration >= 3:
        evolved_code = evolved_code.replace(
            "model = DecisionTreeClassifier(",
            "model = DecisionTreeClassifier(\n        criterion='entropy',"
        )
        improvements.append("+ Added entropy criterion")
    
    if iteration >= 4:
        evolved_code = evolved_code.replace("random_state=42", "random_state=42,\n        min_samples_leaf=2")
        improvements.append("+ Added min_samples_leaf constraint")
        
    return base_code, evolved_code, improvements

def format_code_display():
    """Format code evolution display with syntax highlighting."""
    original, evolved, improvements = get_evolved_code()
    
    html = f'''
    <div style="background: #0A0A2A; padding: 20px; border-radius: 10px;">
        <h3 style="color: #00FF88; margin-top: 0;">🧬 Code Evolution</h3>
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
            <div>
                <h4 style="color: #7B3FF2;">Original Code</h4>
                <pre style="background: #1a1a3a; padding: 15px; border-radius: 5px; color: #fff; overflow-x: auto;"><code>{original}</code></pre>
            </div>
            <div>
                <h4 style="color: #00FF88;">Evolved Code (Gen {state.get("iteration", 0)})</h4>
                <pre style="background: #1a1a3a; padding: 15px; border-radius: 5px; color: #fff; overflow-x: auto; border: 2px solid #00FF88;"><code>{evolved}</code></pre>
            </div>
        </div>
        <div style="margin-top: 20px;">
            <h4 style="color: #FFD700;">✨ Improvements Applied:</h4>
            <ul style="color: #00AAFF; list-style: none; padding: 0;">
                {"".join(f'<li style="margin: 5px 0;">β€’ {imp}</li>' for imp in improvements) if improvements else '<li>β€’ Analyzing code patterns...</li>'}
            </ul>
        </div>
    </div>
    '''
    return html

def check_achievements():
    """Check and award achievements."""
    new_achievements = []
    
    # First evolution
    if state["iteration"] >= 1 and "first_evolution" not in state["achievements"]:
        state["achievements"].append("first_evolution")
        new_achievements.append(ACHIEVEMENTS["first_evolution"])
    
    # Fitness achievements
    current_fitness = state["fitness_history"][-1] if state["fitness_history"] else 0
    
    if current_fitness >= 0.95 and "fast_learner" not in state["achievements"]:
        state["achievements"].append("fast_learner")
        new_achievements.append(ACHIEVEMENTS["fast_learner"])
    
    if current_fitness >= 0.99 and "perfectionist" not in state["achievements"]:
        state["achievements"].append("perfectionist")
        new_achievements.append(ACHIEVEMENTS["perfectionist"])
    
    # Speed achievement
    if state["start_time"] and state["variants_evaluated"] > 0:
        elapsed = time.time() - state["start_time"]
        if elapsed > 0:
            speed = state["variants_evaluated"] / elapsed
            if speed >= 10 and "speed_demon" not in state["achievements"]:
                state["achievements"].append("speed_demon")
                new_achievements.append(ACHIEVEMENTS["speed_demon"])
    
    # Marathon achievement
    if state["iteration"] >= 10 and "marathon" not in state["achievements"]:
        state["achievements"].append("marathon")
        new_achievements.append(ACHIEVEMENTS["marathon"])
    
    # Update high score
    if current_fitness > state["high_score"]:
        state["high_score"] = current_fitness
    
    return new_achievements

def format_achievements():
    """Format achievements display."""
    html = '<div style="background: #0A0A2A; padding: 20px; border-radius: 10px;">'
    html += '<h3 style="color: #FFD700; margin-top: 0;">πŸ† Achievements</h3>'
    html += '<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px;">'
    
    for ach_id in state["achievements"]:
        ach = ACHIEVEMENTS.get(ach_id, {})
        html += f'''
        <div style="background: linear-gradient(45deg, #7B3FF2, #00AAFF); padding: 10px; border-radius: 8px; text-align: center;">
            <div style="font-size: 24px;">{ach.get("name", "")}</div>
            <div style="font-size: 12px; color: #FFD700;">{ach.get("desc", "")}</div>
        </div>
        '''
    
    if not state["achievements"]:
        html += '<div style="color: #666; text-align: center; width: 100%;">Start evolving to unlock achievements!</div>'
    
    html += '</div>'
    html += f'<div style="margin-top: 20px; text-align: center; color: #00FF88; font-size: 20px;">High Score: {state["high_score"]:.4f}</div>'
    html += '</div>'
    return html

def get_share_text():
    """Generate share text for social media."""
    fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
    achievements_count = len(state["achievements"])
    
    text = f"🌟 Evolution Aurora: I evolved AI to {fitness:.2%} fitness with {achievements_count} achievements unlocked! Can you beat my score?\n\n"
    text += "Try it yourself: https://huggingface.co/spaces/Agents-MCP-Hackathon/Evolution\n"
    text += "#EvolutionAurora #AIEvolution #HuggingFace"
    
    return text

def format_events():
    """Format events for display."""
    html = '<div style="background: #0A0A2A; padding: 15px; border-radius: 10px; height: 300px; overflow-y: auto; font-family: monospace;">'
    
    for event in state["events"][-20:][::-1]:
        if event["type"] == "victory":
            color = "#FFD700"
            icon = "πŸŽ‰"
            style = "font-size: 20px; font-weight: bold; background: linear-gradient(45deg, #FFD700, #FF6B6B); padding: 15px; border-radius: 10px; margin: 10px 0; animation: pulse 0.5s infinite; text-shadow: 0 0 20px #FFD700; border: 3px solid #FFD700;"
        elif event["type"] == "boss":
            color = "#FF0000"
            icon = "πŸ‘Ύ"
            style = "font-size: 18px; font-weight: bold; background: rgba(255, 0, 0, 0.3); padding: 12px; border-radius: 8px; margin: 8px 0; border: 2px solid #FF0000; animation: pulse 2s infinite;"
        elif event["type"] == "achievement":
            color = "#FFD700"
            icon = "πŸ†"
            style = "font-size: 16px; font-weight: bold; background: linear-gradient(45deg, #7B3FF2, #00AAFF); padding: 10px; border-radius: 5px; margin: 5px 0;"
        elif event["type"] == "quantum":
            color = "#FF00FF"
            icon = "βš›οΈ"
            style = "font-size: 18px; font-weight: bold; background: linear-gradient(45deg, #FF00FF, #00FFFF); padding: 12px; border-radius: 8px; margin: 8px 0; animation: pulse 1s infinite; text-shadow: 0 0 10px #FF00FF;"
        elif event["type"] == "multiplayer":
            color = "#FF6B6B"
            icon = "βš”οΈ"
            style = "font-size: 14px; font-weight: bold; background: rgba(255, 107, 107, 0.2); padding: 8px; border-radius: 5px; margin: 5px 0; border: 1px solid #FF6B6B;"
        elif event["type"] == "improvement":
            color = "#00FF88"
            icon = "✨"
            style = "padding: 5px;"
        else:
            color = "#00AAFF"
            icon = "πŸ“Š"
            style = "padding: 5px;"
        
        html += f'<div style="color: {color}; {style}">{icon} [{event["time"]}] {event["message"]}</div>'
    
    html += '</div>'
    return html

def toggle_evolution(running):
    """Start or stop evolution."""
    state["running"] = running
    if running:
        state["iteration"] = 0
        state["fitness_history"] = [0.9333]
        state["variants_evaluated"] = 0
        state["start_time"] = time.time()
        state["events"] = [{
            "time": datetime.now().strftime("%H:%M:%S"),
            "type": "improvement",
            "message": "πŸš€ Evolution started! Initial fitness: 0.9333 | Modal containers spinning up..."
        }]
    return "πŸ›‘ Stop Evolution" if running else "πŸš€ Start Evolution"

# Create Gradio interface
with gr.Blocks(
    theme=gr.themes.Base(
        primary_hue="purple",
        secondary_hue="green",
        neutral_hue="slate"
    ),
    css="""
    .gradio-container {
        background: linear-gradient(135deg, #0A0A2A 0%, #1A1A3A 100%);
        color: white;
    }
    .gr-button-primary {
        background: linear-gradient(45deg, #7B3FF2, #00AAFF) !important;
        border: none !important;
    }
    .gr-box {
        background: rgba(255, 255, 255, 0.05) !important;
        border: 1px solid rgba(255, 255, 255, 0.1) !important;
    }
    """
) as demo:
    
    # Header with Modal branding
    with gr.Row():
        gr.Markdown("""
        # 🌟 Evolution Aurora - AI Learning to Code
        
        Watch as AI evolves code in real-time with neural network visualization! See synapses fire and neurons activate as the AI discovers improvements. The neural network shows the AI's "thoughts" as it learns.
        """)
        gr.HTML('''
        <div style="text-align: right; padding: 10px;">
            <div style="background: linear-gradient(45deg, #FF6B6B, #4ECDC4); padding: 10px 20px; border-radius: 25px; display: inline-block;">
                <span style="color: white; font-weight: bold; font-size: 18px;">⚑ Powered by Modal</span>
            </div>
            <p style="color: #00AAFF; margin-top: 5px; font-size: 14px;">Cloud execution for parallel evolution</p>
        </div>
        ''')
    
    # Aurora effect at the top
    gr.HTML(AURORA_HTML)
    
    # Sound effects (Web Audio API)
    gr.HTML('''
    <script>
    // Sound system for achievements and improvements
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    let soundEnabled = true;
    
    function playSound(type) {
        if (!soundEnabled) return;
        
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        if (type === 'achievement') {
            // Achievement sound - ascending arpeggio
            oscillator.frequency.setValueAtTime(523.25, audioContext.currentTime); // C5
            oscillator.frequency.setValueAtTime(659.25, audioContext.currentTime + 0.1); // E5
            oscillator.frequency.setValueAtTime(783.99, audioContext.currentTime + 0.2); // G5
            oscillator.frequency.setValueAtTime(1046.50, audioContext.currentTime + 0.3); // C6
            gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.5);
        } else if (type === 'improvement') {
            // Improvement sound - gentle ping
            oscillator.frequency.setValueAtTime(880, audioContext.currentTime); // A5
            gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.2);
        }
    }
    
    // Watch for achievement messages
    const observeAchievements = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            if (mutation.type === 'childList') {
                const text = mutation.target.textContent || '';
                if (text.includes('ACHIEVEMENT UNLOCKED')) {
                    playSound('achievement');
                } else if (text.includes('✨') && text.includes('+0.0')) {
                    playSound('improvement');
                }
            }
        });
    });
    
    // Start observing when ready
    setTimeout(() => {
        const eventLog = document.querySelector('[id*="event_log"]');
        if (eventLog) {
            observeAchievements.observe(eventLog, { childList: true, subtree: true });
        }
    }, 1000);
    
    // Keyboard shortcuts
    document.addEventListener('keydown', (e) => {
        if (e.key === ' ' && e.target.tagName !== 'INPUT') {
            e.preventDefault();
            const startBtn = document.querySelector('.gr-button-primary');
            if (startBtn) startBtn.click();
        } else if (e.key === 's' && e.ctrlKey) {
            e.preventDefault();
            const shareBtn = document.querySelector('[id*="share_btn"]');
            if (shareBtn) shareBtn.click();
        } else if (e.key === 'm') {
            soundEnabled = !soundEnabled;
            console.log('Sound', soundEnabled ? 'enabled' : 'disabled');
        }
    });
    </script>
    ''')
    
    # Epic Voice Narration System
    gr.HTML('''
    <script>
    // Text-to-speech narration
    const speak = (text, rate = 1, pitch = 1) => {
        if (!window.speechSynthesis) return;
        
        const utterance = new SpeechSynthesisUtterance(text);
        utterance.rate = rate;
        utterance.pitch = pitch;
        utterance.volume = 0.8;
        
        // Try to use a dramatic voice
        const voices = speechSynthesis.getVoices();
        const dramaticVoice = voices.find(v => v.name.includes('Daniel') || v.name.includes('Alex')) || voices[0];
        if (dramaticVoice) utterance.voice = dramaticVoice;
        
        speechSynthesis.speak(utterance);
    };
    
    // Epic intro narration
    setTimeout(() => {
        speak("Welcome to Evolution Aurora. Where artificial intelligence learns to code before your very eyes.", 0.9, 0.8);
    }, 1000);
    
    // Watch for achievements and milestones
    const narrateProgress = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            const text = mutation.target.textContent || '';
            
            if (text.includes('ACHIEVEMENT UNLOCKED')) {
                speak("Achievement unlocked!", 1.2, 1.2);
            } else if (text.includes('0.95') && text.includes('Fitness')) {
                speak("Incredible! 95 percent fitness achieved. The AI is learning fast.", 1, 0.9);
            } else if (text.includes('0.99') && text.includes('Fitness')) {
                speak("Approaching perfection! 99 percent fitness. This is extraordinary!", 1.1, 1.1);
            } else if (text.includes('TOOK THE LEAD')) {
                speak("Alert! Another player has taken the lead! You must evolve faster!", 1.2, 1);
            }
        });
    });
    
    setTimeout(() => {
        const containers = document.querySelectorAll('[id*="display"], [id*="event_log"]');
        containers.forEach(c => narrateProgress.observe(c, { childList: true, subtree: true }));
    }, 2000);
    </script>
    ''')
    
    with gr.Row():
        with gr.Column(scale=1):
            toggle_btn = gr.Button("πŸš€ Start Evolution", variant="primary", size="lg")
            
            # Multiplayer toggle
            multiplayer_btn = gr.Button("🌍 Join Global Battle", variant="secondary", size="lg")
            
            gr.Markdown("### πŸ“Š Statistics")
            with gr.Row():
                fitness_display = gr.Number(
                    value=0.9333,
                    label="Current Fitness",
                    precision=4
                )
                generation_display = gr.Number(
                    value=0,
                    label="Generation"
                )
            
            gr.Markdown("### ⚑ Modal Performance")
            with gr.Row():
                variants_display = gr.Number(
                    value=0,
                    label="Variants Evaluated"
                )
                speed_display = gr.Textbox(
                    value="0 variants/sec",
                    label="Processing Speed"
                )
        
        with gr.Column(scale=2):
            gr.Markdown("### πŸ“ˆ Fitness Evolution")
            fitness_chart = gr.Plot(value=create_fitness_chart())
    
    # Multiplayer Leaderboard
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### 🌍 Global Competition")
            multiplayer_display = gr.HTML(value=format_multiplayer_leaderboard())
        
        with gr.Column(scale=2):
            # Code Evolution Display
            gr.Markdown("### 🧬 Live Code Evolution")
            code_display = gr.HTML(value=format_code_display())
    
    # Achievements Display
    gr.Markdown("### πŸ† Achievements & Leaderboard")
    achievements_display = gr.HTML(value=format_achievements())
    
    with gr.Row():
        share_btn = gr.Button("πŸ“± Share Your Score", variant="secondary")
        share_text = gr.Textbox(
            value=get_share_text(),
            label="Copy & Share:",
            interactive=True,
            visible=False
        )
    
    with gr.Row():
        with gr.Column():
            gr.Markdown("### πŸ”οΈ Fitness Landscape")
            landscape_3d = gr.Plot(value=create_3d_landscape())
        
        with gr.Column():
            gr.Markdown("### πŸ“œ Evolution Log")
            event_log = gr.HTML(value=format_events())
    
    # Timer for updates
    timer = gr.Timer(1.0)
    
    # Toggle state
    running_state = gr.State(False)
    multiplayer_state = gr.State(False)
    
    def on_toggle(running):
        new_state = not running
        return new_state, toggle_evolution(new_state)
    
    def on_multiplayer(active):
        state["multiplayer_active"] = not active
        return not active, "🚫 Leave Battle" if not active else "🌍 Join Global Battle"
    
    def on_share():
        return gr.update(visible=True, value=get_share_text())
    
    toggle_btn.click(
        fn=on_toggle,
        inputs=[running_state],
        outputs=[running_state, toggle_btn]
    )
    
    multiplayer_btn.click(
        fn=on_multiplayer,
        inputs=[multiplayer_state],
        outputs=[multiplayer_state, multiplayer_btn]
    )
    
    share_btn.click(
        fn=on_share,
        outputs=[share_text]
    )
    
    def update_all():
        if state["running"]:
            simulate_evolution()
        
        # Calculate speed
        speed = "0 variants/sec"
        if state["start_time"] and state["variants_evaluated"] > 0:
            elapsed = time.time() - state["start_time"]
            if elapsed > 0:
                speed = f"{state['variants_evaluated'] / elapsed:.2f} variants/sec"
        
        return {
            fitness_display: state["fitness_history"][-1] if state["fitness_history"] else 0.9333,
            generation_display: state["iteration"],
            variants_display: state["variants_evaluated"],
            speed_display: speed,
            fitness_chart: create_fitness_chart(),
            landscape_3d: create_3d_landscape(),
            multiplayer_display: format_multiplayer_leaderboard(),
            code_display: format_code_display(),
            achievements_display: format_achievements(),
            event_log: format_events()
        }
    
    timer.tick(
        fn=update_all,
        outputs=[fitness_display, generation_display, variants_display, speed_display, fitness_chart, landscape_3d, multiplayer_display, code_display, achievements_display, event_log]
    )
    
    # Hidden boss defeat button
    boss_defeat_btn = gr.Button("Boss Defeat Trigger", visible=False, elem_id="boss_defeat_btn")
    
    def on_boss_defeat():
        """Handle boss defeat from JavaScript."""
        if handle_boss_defeat():
            return {}
        return {}
    
    boss_defeat_btn.click(
        fn=on_boss_defeat,
        outputs=[]
    )
    
    # JavaScript to handle boss defeat callback
    gr.HTML('''
    <script>
    // Connect boss defeat callback to Gradio
    window.bossDamageCallback = () => {
        const btn = document.getElementById('boss_defeat_btn');
        if (btn) {
            btn.click();
        }
    };
    </script>
    ''')
    
    # Challenge Mode
    with gr.Row():
        gr.Markdown("""
        ### 🎯 Challenge Mode
        
        **Today's Challenge**: Reach 99% fitness in under 10 generations!
        
        πŸ₯‡ **Gold**: < 5 generations  
        πŸ₯ˆ **Silver**: < 7 generations  
        πŸ₯‰ **Bronze**: < 10 generations
        """)
        
        gr.HTML('''
        <div style="text-align: center; padding: 20px;">
            <div style="display: inline-block; background: linear-gradient(45deg, #FFD700, #FFA500); padding: 15px 30px; border-radius: 10px;">
                <h3 style="margin: 0; color: #000;">πŸ… Your Best: Not Set</h3>
                <p style="margin: 5px 0 0 0; color: #333;">Complete a run to set your record!</p>
            </div>
        </div>
        ''')
    
    gr.Markdown("""
    ---
    ### πŸ† HuggingFace Agents-MCP Hackathon 2025
    
    **Track 3**: Agentic Demo Showcase | **Integration**: Evolve Framework | **Sponsor**: Modal
    
    This demo showcases AI-driven code evolution with real-time visualization. The aurora effects 
    intensify with fitness improvements, creating a stunning visual representation of machine learning.
    
    ### ⌨️ Keyboard Shortcuts
    
    - **Space**: Start/Stop Evolution
    - **Ctrl+S**: Share Your Score
    - **M**: Toggle Sound Effects
    
    ### πŸ’‘ Pro Tips
    
    - Watch for achievement unlocks - they come with special sound effects!
    - The aurora intensifies with larger fitness improvements
    - Modal's parallel execution evaluates 4-8 variants simultaneously
    - Try to unlock all 5 achievements in a single run!
    """)

if __name__ == "__main__":
    print("\n🌟 Evolution Aurora - Final Demo")
    print("=" * 50)
    print("This version has:")
    print("βœ“ Working aurora particle effects")
    print("βœ“ Animated 3D fitness landscape")
    print("βœ“ Real-time evolution simulation")
    print("βœ“ Beautiful UI with gradients")
    print("=" * 50 + "\n")
    
    demo.launch()