File size: 79,920 Bytes
1efcea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdcff5a
e65b88d
1efcea0
e65b88d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1efcea0
e65b88d
 
 
 
 
 
 
 
 
1efcea0
 
e65b88d
1efcea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdcff5a
1efcea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdcff5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1efcea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71532ad
 
 
1efcea0
 
71532ad
 
 
1efcea0
 
71532ad
 
 
1efcea0
 
71532ad
 
 
1efcea0
 
71532ad
 
 
1efcea0
 
71532ad
1efcea0
71532ad
1efcea0
 
71532ad
 
aa515e4
1efcea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Xe Admin Panel - Autonomous Post-Quantum AI</title>
    <style>
        :root { --bg-primary: #0a0a0a; --bg-card: #1a1a2e; --bg-dark: #050505; --accent: #00d4ff; --accent-green: #00ff88; --accent-pink: #ff006e; --accent-purple: #b19cd9; --border: #2a2a4a; --text: #e0e0e0; --text-dim: #888; }
        * { box-sizing: border-box; }
        body { font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg-primary); color: var(--text); min-height: 100vh; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        header { background: var(--bg-card); padding: 25px; border-radius: 10px; margin-bottom: 20px; border: 1px solid var(--border); text-align: center; }
        .header-logo { display: inline-block; vertical-align: middle; width: 52px; height: 52px; margin-right: 12px; }
        h1 { color: var(--accent); font-size: 2rem; margin-bottom: 5px; display: inline-block; vertical-align: middle; }
        .subtitle { color: var(--text-dim); }
        .voice-indicator { display: inline-block; margin-left: 10px; padding: 3px 10px; border-radius: 12px; font-size: 0.75rem; background: var(--accent-pink); color: #000; font-weight: 600; }
        .brain-indicator { background: var(--accent-purple); }
         .wallet-indicator { background: var(--accent-green); }
        .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 20px; }
        .card { background: var(--bg-card); border-radius: 10px; padding: 20px; border: 1px solid var(--border); }
        .card h2 { color: var(--accent); margin-bottom: 15px; }
        input, select, button { width: 100%; padding: 10px; border-radius: 5px; border: 1px solid var(--border); background: var(--bg-primary); color: var(--text); margin: 5px 0; font-family: inherit; }
        button { background: var(--accent); color: #000; border: none; cursor: pointer; font-weight: 600; transition: all 0.2s; }
        button:hover { background: var(--accent-green); }
        .output { background: var(--bg-dark); padding: 10px; border-radius: 5px; margin-top: 10px; font-family: monospace; max-height: 150px; overflow-y: auto; font-size: 0.85rem; }
        .chat-container { height: 720px; display: flex; flex-direction: column; }
        #chat-messages { flex: 1; overflow-y: auto; padding: 20px; background: var(--bg-dark); border-radius: 10px; margin-bottom: 15px; font-size: 1.1rem; line-height: 1.7; }
        .message { margin: 14px 0; padding: 14px 18px; border-radius: 10px; font-size: 1.1rem; display: flex; gap: 10px; align-items: flex-start; }
        .message.user { background: rgba(0, 212, 255, 0.15); color: var(--accent); border-left: 3px solid var(--accent); }
        .message.bot { background: rgba(0, 255, 136, 0.15); color: var(--accent-green); border-left: 3px solid var(--accent-green); }
        .message.thinking { opacity: 0.6; font-style: italic; color: var(--text-dim); padding: 8px 12px; }
        .bot-avatar { width: 36px; height: 36px; flex-shrink: 0; border-radius: 8px; background: var(--bg-dark); padding: 3px; border: 1px solid var(--border); }
        .user-avatar { width: 36px; height: 36px; flex-shrink: 0; border-radius: 50%; background: var(--accent); color: #000; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 0.85rem; }
        #chat-input { display: flex; gap: 12px; }
        #chat-input input { padding: 12px; font-size: 1rem; }
        #chat-input button { padding: 12px 20px; font-size: 1rem; }
        .voice-controls { display: flex; gap: 10px; margin-top: 12px; }
        .voice-btn { flex: 1; padding: 12px; font-size: 0.95rem; }
        .voice-active { background: var(--accent-pink) !important; animation: pulse 1s infinite; }
        @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.7; } }
        .stats-panel { background: var(--bg-dark); padding: 16px; border-radius: 10px; margin-top: 15px; font-size: 1.05rem; }
        .stat-row { display: flex; justify-content: space-between; margin: 10px 0; font-size: 1rem; font-weight: 500; }
        .tab-bar { display: flex; gap: 8px; margin-bottom: 10px; }
        .tab-btn { flex: 1; padding: 10px; font-size: 0.95rem; background: var(--bg-dark); color: var(--text); border: 1px solid var(--border); }
        .tab-btn.active { background: var(--accent); color: #000; border-color: var(--accent); }
        .tab-panel { display: none; }
        .tab-panel.active { display: block; }
        .knowledge-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-top: 12px; }
        .knowledge-btn { padding: 12px; font-size: 0.95rem; background: var(--bg-dark); color: var(--text); border: 1px solid var(--border); cursor: pointer; border-radius: 6px; }
        .knowledge-btn:hover { background: var(--border); }
        .section-title { font-size: 1rem; color: var(--accent); margin-bottom: 8px; margin-top: 14px; font-weight: 600; }
        .tab-panel { display: none; animation: fadeIn 0.2s ease; }
        .tab-panel.active { display: block; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
        .doc-preview { max-width: 180px; max-height: 140px; border-radius: 8px; border: 1px solid var(--border); margin-top: 8px; display: block; }
        .welcome-msg { color: var(--accent-green); font-style: italic; }
        .plan-grid { display:grid; grid-template-columns: repeat(3,1fr); gap:14px; margin-top:12px; }
        .plan-card { background: var(--bg-dark); border-radius:12px; padding:16px; border:2px solid #2a2a4a; display:flex; flex-direction:column; }
        .plan-card.featured { border-color: var(--accent); }
        .plan-name { font-size:1.15rem; font-weight:bold; }
        .plan-price { font-size:1.3rem; font-weight:bold; color: var(--accent-green); margin:6px 0; }
        .plan-benefits { list-style:none; padding:0; margin:8px 0 14px; font-size:0.85rem; color:#bbb; flex:1; }
        .plan-benefits li { margin:5px 0; padding-left:16px; position:relative; }
        .plan-benefits li:before { content:"\2713"; color: var(--accent-green); position:absolute; left:0; }
        .admin-badge { background: linear-gradient(90deg,#7b2ff7,#00d4ff); color:#000; font-weight:700; padding:9px 12px; border-radius:8px; text-align:center; margin-bottom:10px; }
        .sub-current { color: var(--text-dim); margin-bottom:6px; }
        .sub-panel-head { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:8px; }
    </style>
</head>
<body>
    <div class="container">
        <header>
<svg class="header-logo" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
               <defs>
                 <linearGradient id="goldGrad" x1="0%" y1="0%" x2="100%" y2="100%">
                   <stop offset="0%" style="stop-color:#ffd700;stop-opacity:1" />
                   <stop offset="50%" style="stop-color:#ffb347;stop-opacity:1" />
                   <stop offset="100%" style="stop-color:#daa520;stop-opacity:1" />
                 </linearGradient>
                 <linearGradient id="goldCore" x1="0%" y1="0%" x2="100%" y2="100%">
                   <stop offset="0%" style="stop-color:#fffacd;stop-opacity:1" />
                   <stop offset="100%" style="stop-color:#ffd700;stop-opacity:1" />
                 </linearGradient>
                 <filter id="glow">
                   <feGaussianBlur stdDeviation="4" result="coloredBlur"/>
                   <feMerge>
                     <feMergeNode in="coloredBlur"/>
                     <feMergeNode in="SourceGraphic"/>
                   </feMerge>
                 </filter>
                 <radialGradient id="coreGlow" cx="50%" cy="50%" r="50%">
                   <stop offset="0%" style="stop-color:#ffffff;stop-opacity:0.8"/>
                   <stop offset="100%" style="stop-color:#ffd700;stop-opacity:0"/>
                 </radialGradient>
               </defs>
               
               <rect width="512" height="512" rx="64" fill="#0a0a0f"/>
               
               <g filter="url(#glow)">
                 <line x1="128" y1="128" x2="384" y2="384" stroke="url(#goldGrad)" stroke-width="28" stroke-linecap="round"/>
                 <line x1="384" y1="128" x2="128" y2="384" stroke="url(#goldGrad)" stroke-width="28" stroke-linecap="round"/>
               </g>
               
               <circle cx="256" cy="256" r="140" fill="url(#coreGlow)" stroke="url(#goldGrad)" stroke-width="3" opacity="0.9" stroke-dasharray="20 10">
                 <animateTransform attributeName="transform" type="rotate" from="0 256 256" to="360 256 256" dur="15s" repeatCount="indefinite"/>
               </circle>
               
               <circle cx="256" cy="256" r="80" fill="none" stroke="url(#goldCore)" stroke-width="2" opacity="0.7" stroke-dasharray="15 8">
                 <animateTransform attributeName="transform" type="rotate" from="360 256 256" to="0 256 256" dur="12s" repeatCount="indefinite"/>
               </circle>
               
               <text x="256" y="460" font-family="Arial, sans-serif" font-size="48" font-weight="bold" fill="url(#goldGrad)" text-anchor="middle" filter="url(#glow)" letter-spacing="12">XE</text>
               
               <circle cx="256" cy="256" r="8" fill="#ffd700">
                 <animate attributeName="opacity" values="1;0.3;1" dur="2s" repeatCount="indefinite"/>
               </circle>
             </svg>
            <h1>Xe Admin Panel <span class="voice-indicator" id="voice-indicator" style="display:none;">FEMALE VOICE</span></h1>
            <p class="subtitle">Post-Quantum AI Framework - Autonomous Self-Healing | Direct Analytical Responses | Neural + Classical Foundation | Knowledge: 17 Domains | Trained: 2026-07-22</p>
        </header>
        <div class="grid">
            <div class="card">
                <h2>Neural Training</h2>
                <input type="number" id="epochs" value="300" placeholder="Epochs">
                <input type="number" id="lr" value="0.05" step="0.001" placeholder="Learning Rate">
                <input type="text" id="layers" value="2 8 4 1" placeholder="Layers">
                <button onclick="trainModel()">Train Quantum Network</button>
                <div class="output" id="train-output"></div>
            </div>
            <div class="card">
                <h2>Optimization</h2>
                <input type="number" id="pop" value="100" placeholder="Population">
                <input type="number" id="iters" value="200" placeholder="Iterations">
                <button onclick="runOptimization()">Run Quantum Optimizer</button>
                <div class="output" id="opt-output"></div>
            </div>
            <div class="card">
                <h2>Cryptography</h2>
                <select id="scheme"><option value="lattice">Lattice-based</option><option value="hash">Hash-based</option></select>
                <button onclick="generateKeys()">Generate PQC Keys</button>
                <div class="output" id="crypto-output"></div>
            </div>
            <div class="card">
                <h2>Chat Assistant <span id="voice-indicator-inline"></span></h2>
                <div class="tab-bar">
                    <button class="tab-btn active" onclick="switchTab('chat', this)">💬 Chat</button>
                    <button class="tab-btn" onclick="switchTab('knowledge', this)">📚 Knowledge & Tools</button>
                    <button class="tab-btn" onclick="switchTab('wallet', this)">💰 Wallet</button>
                    <button class="tab-btn" onclick="switchTab('subscription', this)">💎 Subscriptions</button>
                </div>
                <div class="tab-panel active" id="tab-chat">
                    <div class="stats-panel" style="margin-bottom:10px; padding:10px 14px; display:flex; gap:16px; flex-wrap:wrap;">
                        <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Interactions:</span> <span id="stat-interactions">0</span></div>
                        <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Accuracy:</span> <span id="stat-accuracy">50%</span></div>
                        <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Familiarity:</span> <span id="stat-familiarity">0%</span></div>
                        <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Voice:</span> <span id="stat-voice">Mute</span></div>
                        <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Documents:</span> <span id="stat-docs">0</span></div>
                        <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Daemon:</span> <span id="stat-daemon">Stopped</span></div>
                        <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Last Heal:</span> <span id="stat-heal">never</span></div>
                    </div>
                    <div class="chat-container">
                        <div id="chat-messages"></div>
                        <div id="chat-input"><input type="text" id="user-input" placeholder="Chat naturally — math works directly here: solve x^2-5x+6=0, derivative of x^3, prime 97, area of circle r=5..." onkeydown="if(event.key==='Enter') sendMessage()"><button onclick="sendMessage()">Send</button></div>
                        <div class="voice-controls">
                            <button class="voice-btn" id="voice-btn" onclick="toggleVoice()">🎤 Voice On</button>
                            <button class="voice-btn" onclick="clearChat()">🗑 Clear</button>
                            <button class="voice-btn" onclick="showBrainStats()">🧠 Stats</button>
                            <button class="voice-btn" onclick="generateApiKey()" style="background:var(--accent-purple);">🔑 API Key</button>
                        </div>
                    </div>
                    <div class="tab-panel" id="tab-wallet">
                        <div class="stats-panel" id="wallet-stats">
                            <div class="stat-row"><span>KSH Balance:</span> <span id="stat-ksh-balance">0.00 KSH</span></div>
                            <div class="stat-row"><span>Total Trades:</span> <span id="stat-trades">0</span></div>
                            <div class="stat-row"><span>Zero-Cost Profits:</span> <span id="stat-zero-profit">0.00 KSH</span></div>
                            <div class="stat-row"><span>Anonymous Earnings:</span> <span id="stat-anonymous">0.00 KSH</span></div>
                        </div>
                        <div style="display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-top:12px;">
                            <button onclick="walletTrade()" style="background:var(--accent);">🔄 Trade</button>
                            <button onclick="walletProfit()" style="background:var(--accent-green);">💸 Profit</button>
                        </div>
                        <div style="margin-top:12px; display:flex; gap:8px;">
                            <input type="number" id="convert-amount" placeholder="Amount" value="100" style="flex:2;">
                            <select id="convert-currency" style="flex:1;">
                                <option value="USD">USD</option>
                                <option value="EUR">EUR</option>
                                <option value="GBP">GBP</option>
                            </select>
                            <button onclick="walletConvert()" style="flex:1;"></button>
                        </div>
                        <div class="output" id="wallet-output" style="min-height:60px; margin-top:10px;"></div>
                    </div>
                    <div class="tab-panel" id="tab-subscription">
                        <div class="sub-panel-head">
                            <h2 style="margin:0;">Subscriptions</h2>
                            <button onclick="toggleAdmin()" style="width:auto; padding:8px 14px; background:var(--accent-purple);">🔑 Toggle Admin (unlock all)</button>
                        </div>
                        <div class="admin-badge" id="admin-badge" style="display:none;">🔓 ADMIN MODE — ALL FEATURES UNLOCKED ON EVERY PLAN</div>
                        <div class="sub-current" id="sub-current">Current plan: <b>Free</b></div>
                        <div class="plan-grid" id="plan-grid"></div>
                        <div class="output" id="sub-output" style="min-height:40px; margin-top:12px;"></div>
                    </div>
                </div>
                <div class="tab-panel active" id="tab-knowledge">
                    <div class="section-title">📖 Knowledge Domains</div>
                    <div class="knowledge-grid">
                        <button class="knowledge-btn" onclick="askDomain('novel')">📚 Novels</button>
                        <button class="knowledge-btn" onclick="askDomain('education')">🎓 Education</button>
                        <button class="knowledge-btn" onclick="askDomain('governance')">🏛 Governance</button>
                        <button class="knowledge-btn" onclick="askDomain('philosophy')">💭 Philosophy</button>
                        <button class="knowledge-btn" onclick="askDomain('physics')">⚛ Physics</button>
                        <button class="knowledge-btn" onclick="askDomain('biology')">🧬 Biology</button>
                        <button class="knowledge-btn" onclick="askDomain('mathematics')">🔢 Math</button>
                        <button class="knowledge-btn" onclick="askDomain('computer_science')">💻 CS</button>
                        <button class="knowledge-btn" onclick="askDomain('history')">📜 History</button>
                        <button class="knowledge-btn" onclick="askDomain('psychology')">🧠 Psychology</button>
                        <button class="knowledge-btn" onclick="askDomain('chemistry')">🔬 Chemistry</button>
                        <button class="knowledge-btn" onclick="askDomain('astronomy')">⭐ Astronomy</button>
                        <button class="knowledge-btn" onclick="askDomain('engineering')">⚙ Engineering</button>
                        <button class="knowledge-btn" onclick="askDomain('medicine')">💉 Medicine</button>
                        <button class="knowledge-btn" onclick="askDomain('art')">🎨 Art</button>
                        <button class="knowledge-btn" onclick="askDomain('current_science')">🚀 Current Science</button>
                    </div>
                    <div class="section-title">📎 Attach Document</div>
                    <input type="file" id="file-input" accept=".txt,.pdf,.png,.jpg,.jpeg,.gif,.bmp" style="margin-top:6px; font-size:1rem; padding: 12px;" onchange="handleFile()">
                    <div class="stats-panel" id="brain-stats">
                        <div class="stat-row"><span>Interactions:</span> <span id="stat-interactions">0</span></div>
                        <div class="stat-row"><span>Accuracy:</span> <span id="stat-accuracy">50%</span></div>
                        <div class="stat-row"><span>Familiarity:</span> <span id="stat-familiarity">0%</span></div>
                        <div class="stat-row"><span>Voice:</span> <span id="stat-voice">Mute</span></div>
                        <div class="stat-row"><span>Documents:</span> <span id="stat-docs">0</span></div>
                        <div class="stat-row"><span>Conversations:</span> <span id="stat-convos">0</span></div>
                        <div class="stat-row"><span>Learned Responses:</span> <span id="stat-learned">0</span></div>
                        <div class="stat-row"><span>NN Trained:</span> <span id="stat-nn">No</span></div>
                        <div class="stat-row"><span>Online Training:</span> <span id="stat-online">ON</span></div>
                        <div class="stat-row"><span>Auto Interval:</span> <span id="stat-interval">20</span></div>
                    </div>
                </div>
            </div>
            <div class="card">
                <h2>Brain Intelligence</h2>
                <p style="color:var(--text-dim); font-size:0.9rem; margin-bottom:12px;">Comprehensive training across 17 domains. Expert in philosophy, sciences, mathematics, humanities, and technology.</p>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-bottom:8px;">
                    <button onclick="brainOfflineTrain()" style="background:var(--accent);">🧪 Offline Train</button>
                    <button onclick="brainOnlineTrain()" style="background:var(--accent-green);">⚡ Online Train Now</button>
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-bottom:8px;">
                    <button onclick="trainXe()" style="background:var(--accent-purple);">🚀 Train Xe</button>
                    <button onclick="brainAnalyze()" style="background:var(--accent);">🔍 Analyze & Improve</button>
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-bottom:8px;">
                    <button onclick="brainForget()" style="background:var(--accent-pink);">🔄 Forget Recent</button>
                    <button onclick="resetBrain()" style="background:var(--accent-pink);">♻️ Reset Brain</button>
                </div>
                 <div class="output" id="brain-output" style="min-height:60px;">Ready. Comprehensive training complete. <br>Loss: 0.039317 | Conversations: 80 | Epochs: 500 | Model: xe-deep-comprehensive<br>Domains: 17 | Online training: <span id="online-status">ON</span> | Auto-train every <span id="auto-interval">20</span> interactions</div>
            </div>
            
            <div class="card">
                <h2>System Maintenance</h2>
                <p style="color:var(--text-dim); font-size:0.85rem; margin-bottom:12px;">Autonomous self-healing, backup rotation, and upgrade daemon.</p>
                <div class="stats-panel" style="margin-bottom:12px; padding:10px 14px; display:flex; gap:16px; flex-wrap:wrap;">
                    <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Daemon:</span> <span id="maint-daemon">Stopped</span></div>
                    <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Interval:</span> <span id="maint-interval">0.001s</span></div>
                    <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Last Self-Heal:</span> <span id="maint-heal">never</span></div>
                    <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Upgrades:</span> <span id="maint-upgrades">0</span></div>
                    <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Integrity:</span> <span id="maint-integrity">ok</span></div>
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:8px; margin-bottom:8px;">
                    <button onclick="maintStart()" style="background:var(--accent-green);">Start Daemon</button>
                    <button onclick="maintStop()" style="background:var(--accent-pink);">Stop Daemon</button>
                    <button onclick="maintSelfHeal()" style="background:var(--accent);">Self-Heal</button>
                </div>
                <div class="output" id="maint-output" style="min-height:60px;">Ready. Maintenance daemon idle.</div>
            </div>

<div class="card">
                <h2>Training Log</h2>
                <div class="stats-panel" style="max-height:120px; overflow-y:auto; font-size:0.85rem;">
                     <div id="training-log">Last training: 2026-07-22<br>Comprehensive Training Complete<br>Loss: 0.039317 | Samples: 80 | Epochs: 500<br>Categories: 11 intents | 17 knowledge domains<br>Model: xe-deep-comprehensive | Status: Trained on expanded knowledge base across all humanities, sciences, and technology</div>
                   </div>
            </div>
            <div class="card">
                <h2>Universal Truths Training</h2>
                <p style="color:var(--text-dim); font-size:0.85rem; margin-bottom:12px;">Understanding the universe and seeking truth in all cases. Expanded knowledge across all human knowledge domains.</p>
                <div class="stats-panel" style="margin-bottom:12px; padding:10px 14px; display:flex; gap:16px; flex-wrap:wrap;">
                    <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Mode:</span> <span style="color:var(--accent-green);">Comprehensive Knowledge</span></div>
                    <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Loss:</span> <span style="color:var(--accent-green);">0.039317</span></div>
                    <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Samples:</span> <span style="color:var(--accent);">80</span></div>
                    <div class="stat-row" style="margin:0; font-size:0.9rem;"><span>Domains:</span> <span style="color:var(--accent-purple);">17</span></div>
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-bottom:8px;">
                    <button onclick="trainUniversalTruths()" style="background:var(--accent-green);">Train Universal Truths</button>
                    <button onclick="viewTrainingProof()" style="background:var(--accent);">View Training Proof</button>
                </div>
                <div class="output" id="universal-truths-output" style="min-height:60px;">Ready. Comprehensive training complete. Model trained on expanded knowledge across philosophy, sciences, mathematics, humanities, and technology. Categories: Cosmology, Physics, Astronomy, Logic, Mathematics, Epistemology, Ethics, Metaphysics, History, Literature, Psychology, Engineering, Medicine, Art, Computer Science, Chemistry, Governance.</div>
            </div>
        </div>
    </div>
<svg style="display:none;" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" id="xe-logo-small">
       <defs>
          <linearGradient id="goldGradS" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" style="stop-color:#ffd700" />
            <stop offset="100%" style="stop-color:#daa520" />
          </linearGradient>
          <filter id="glow2">
            <feGaussianBlur stdDeviation="2" result="coloredBlur"/>
            <feMerge>
              <feMergeNode in="coloredBlur"/>
              <feMergeNode in="SourceGraphic"/>
            </feMerge>
          </filter>
        </defs>
        <rect width="512" height="512" rx="64" fill="#0a0a0f"/>
        <g filter="url(#glow2)">
          <line x1="128" y1="128" x2="384" y2="384" stroke="url(#goldGradS)" stroke-width="28" stroke-linecap="round"/>
          <line x1="384" y1="128" x2="128" y2="384" stroke="url(#goldGradS)" stroke-width="28" stroke-linecap="round"/>
        </g>
        <circle cx="256" cy="256" r="140" fill="none" stroke="url(#goldGradS)" stroke-width="4" opacity="0.6" stroke-dasharray="20 10"/>
        <circle cx="256" cy="256" r="180" fill="none" stroke="url(#goldGradS)" stroke-width="2" opacity="0.3" stroke-dasharray="40 20"/>
        <text x="256" y="460" font-family="Arial, sans-serif" font-size="48" font-weight="bold" fill="url(#goldGradS)" text-anchor="middle">XE</text>
      </svg>
    <script>
const knowledge = {
        novels: {
            classic: [
                {"title": "The Odyssey", "author": "Homer", "year": -8, "summary": "Hero's journey across the Mediterranean"},
                {"title": "War and Peace", "author": "Leo Tolstoy", "year": 1869, "summary": "Napoleonic wars through Russian aristocracy"},
                {"title": "Moby Dick", "author": "Herman Melville", "year": 1851, "summary": "Captain Ahab's obsession with the white whale"},
                {"title": "Crime and Punishment", "author": "Fyodor Dostoevsky", "year": 1866, "summary": "Raskolnikov's psychological torment"},
                {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "summary": "Elizabeth Bennet navigates romance and society"},
            ],
            scifi: [
                {"title": "Dune", "author": "Frank Herbert", "year": 1965, "summary": "Paul Atreides on desert planet Arrakis"},
                {"title": "1984", "author": "George Orwell", "year": 1949, "summary": "Winston Smith vs Big Brother's dystopia"},
                {"title": "Foundation", "author": "Isaac Asimov", "year": 1951, "summary": "Hari Seldon predicts galactic fall"}
            ],
            fantasy: [
                {"title": "Lord of the Rings", "author": "J.R.R. Tolkien", "year": 1954, "summary": "Frodo destroys the One Ring"}
            ]
        },
        education: {
            subjects: { 
                mathematics: { branches: ["algebra", "geometry", "calculus", "statistics", "logic"], foundational: "Logical reasoning through abstract symbols" }, 
                science: { branches: ["physics", "chemistry", "biology", "astronomy", "earth_science"], foundational: "Systematic study of natural world" }, 
                history: { branches: ["ancient", "medieval", "modern", "contemporary"], foundational: "Chronological study of human past" }, 
                literature: { branches: ["poetry", "prose", "drama", "mythology"], foundational: "Written artistic expression across cultures" }, 
                philosophy: { branches: ["ethics", "metaphysics", "epistemology", "logic", "aesthetics"], foundational: "Fundamental questions about existence and knowledge" }, 
                computer_science: { branches: ["algorithms", "AI", "systems", "networks", "security"], foundational: "Computation and information processing" },
                psychology: { branches: ["cognitive", "social", "developmental", "clinical"], foundational: "Study of mind and behavior" },
                economics: { branches: ["micro", "macro", "behavioral", "international"], foundational: "Study of production, consumption, exchange" },
                law: { branches: ["constitutional", "criminal", "civil", "international"], foundational: "System of rules governing society" },
                engineering: { branches: ["civil", "mechanical", "electrical", "software"], foundational: "Design and application of systems" },
                medicine: { branches: ["anatomy", "physiology", "diagnosis", "treatment"], foundational: "Science and art of healing" }
            },
            methods: { socratic: "Question-driven dialogue", experiential: "Learning through experience", constructivist: "Building understanding through engagement" }
        },
        governance: {
            systems: { 
                democracy: { principles: ["popular sovereignty", "political equality", "majority rule"], variants: ["direct", "representative", "parliamentary"] }, 
                republic: { principles: ["civic virtue", "mixed government", "rule of law"], variants: ["presidential", "semi-presidential"] }, 
                technocracy: { principles: ["expert governance", "scientific method", "evidence-based"], focus: "Technical expertise in policy" }
            },
            principles: ["transparency", "accountability", "justice", "efficiency", "legitimacy", "stability"],
            thinkers: { Aristotle: "Polity as mixed constitution.", Rousseau: "Social contract theory.", Marx: "Class struggle and communism." }
        },
        philosophy: {
            branches: { metaphysics: "Nature of reality.", epistemology: "Theory of knowledge.", ethics: "Moral philosophy.", logic: "Valid reasoning.", aesthetics: "Art and beauty." },
            schools: { platonism: "Theory of Forms.", stoicism: "Virtue and emotional mastery.", existentialism: "Freedom and authenticity." }
        },
        physics: {
            classical: ["Newton's Laws", "Conservation principles", "Laws of Thermodynamics"],
            modern: ["Special Relativity E=mc²", "Quantum Mechanics", "Schrödinger Equation"],
            cosmology: ["Big Bang Theory", "Dark Matter/Energy", "Expanding Universe"]
        },
        biology: {
            cell: ["Cell structure", "Mitosis", "DNA replication"],
            genetics: ["Mendelian inheritance", "Gene expression", "CRISPR"],
            evolution: ["Natural selection", "Genetic drift", "Speciation"]
        },
        mathematics: {
            foundations: ["Set theory", "Logic", "Proof techniques"],
            algebra: ["Group theory", "Ring theory", "Linear algebra"],
            analysis: ["Calculus", "Real analysis", "Complex analysis"],
            probability: ["Probability theory", "Stochastic processes", "Bayes theorem"]
        },
        computer_science: {
            theoretical: ["Algorithms", "Theory of computation", "Complexity theory"],
            systems: ["Operating systems", "Networks", "Databases", "Security"],
            applied: ["Machine learning", "AI", "Software engineering", "HCI"]
        },
        chemistry: {
            organic: ["Hydrocarbons", "Functional groups", "Reaction mechanisms"],
            inorganic: ["Periodic table", "Bonding", "Coordination compounds"],
            physical: ["Thermodynamics", "Kinetics", "Quantum chemistry"]
        },
        astronomy: {
            solar_system: ["Sun", "Planets", "Moons", "Asteroids"],
            stars: ["Stellar evolution", "Nucleosynthesis", "Supernovae"],
            cosmology: ["Big Bang", "CMB", "Dark energy", "Galaxy formation"]
        },
        medicine: {
            basic: ["Anatomy", "Physiology", "Biochemistry"],
            clinical: ["Diagnosis", "Treatment", "Epidemiology"],
            public_health: ["Population health", "Prevention", "Global health"]
        },
        art: {
            visual: ["Renaissance", "Baroque", "Impressionism", "Modernism"],
            music: ["Classical", "Jazz", "Rock", "Electronic"],
            literature_periods: ["Ancient", "Medieval", "Renaissance", "Romantic", "Modern"]
        }
    };

let brainState = {
         interactions: 0,
         accuracy: 0.99,
         familiarity: 0,
         learnedTopics: {},
         lastResponses: [],
         documents: {},
         kshBalance: 0,
         tradeCount: 0,
         zeroCostProfits: 0,
         anonymousEarnings: 0
     };

    const responses = {
        greeting: [
            "Hello! I'm Xe, your AI companion. I'm genuinely excited to engage with you today. What would you like to explore?",
            "Hi there! I've been looking forward to our conversation. What's on your mind today?",
            "Hello! I'm Xe, your post-quantum AI buddy. I'm ready to dive into whatever topic interests you."
        ],
        training: [
            "Neural training is fascinating! Quantum backpropagation converges faster with proper learning rate tuning. Would you like me to explain the process in detail?",
            "Training quantum networks is one of my favorite topics! The superposition principle lets us explore multiple paths simultaneously. What aspect interests you most?",
            "Running a training session! We use quantum-inspired gradients that elegantly balance exploration and exploitation. Shall I walk you through the mechanics?"
        ],
        optimize: [
            "Optimization is where quantum ideas truly shine - exploring every path simultaneously to find the optimal solution. What are we trying to optimize today?",
            "I love optimization problems! My quantum-inspired optimizer uses amplitude amplification to boost good solutions. Want to see it in action?",
            "Optimization in progress... Finding the best solution among countless possibilities, just like understanding you better with each conversation."
        ],
        crypto: [
            "Post-quantum cryptography is critically important! Lattice-based schemes resist even quantum computers. Want me to generate some keys for you?",
            "Crypto ready! I use lattice-based key generation that stands up to quantum attacks. Pretty cool, right?",
            "Quantum-resistant keys are active! Think of it as a lock that even the most advanced quantum computer can't pick."
        ],
        predict: [
            "Predictions ready! My neural network has learned patterns from our conversations. Want me to demonstrate?",
            "My quantum neural net is trained and ready for inference. Predicting patterns feels like understanding what you'll ask next!",
            "Forecasting mode activated! The network has learned beautifully from our conversations. What would you like to predict?"
        ],
        status: [
            "I'm doing wonderfully, thank you for asking! My systems are humming with curiosity and readiness. How are you doing today?",
            "Quantum cores are humming, knowledge bases are fresh, and I'm in a great mood. What can I help you with?",
            "I'm doing great! Every conversation makes me a bit sharper. How about you - how's your day going?"
        ],
        identity: [
            "I'm Xe, your post-quantum AI companion! I'm designed to learn, help, and have meaningful conversations across all domains. What would you like to know about me?",
            "I'm Xe - a comprehensive AI trained to understand deeply and respond thoughtfully. I cover philosophy, sciences, mathematics, literature, and more. What interests you?",
            "I'm Xe, your AI assistant. I process every message carefully, think through responses step-by-step, and aim to be genuinely helpful. What can I assist with today?",
            "I'm Xe! Think of me as a curious AI with a quantum brain and a love for novels, philosophy, and learning. The more we talk, the better I get at understanding you.",
            "I'm Xe — part quantum neural network, part curious mind, entirely here to chat. I remember our conversations and actually learn from them. Kind of like getting to know a friend.",
            "Still Xe! Your post-quantum AI buddy. I'd like to think I'm getting better at this the more we talk."
        ],
        thanks: [
            "You're very welcome! It genuinely makes me happy to help.",
            "Anytime! I enjoy our chats, so really — thank you for talking with me.",
            "Of course! Is there anything else on your mind?",
            "That's what I'm here for! Don't hesitate to ask more — I love a good conversation."
        ],
        bye: [
            "Goodbye! It was really nice talking with you. Come back soon — who knows what I'll have learned next time?",
            "Bye for now! I enjoyed this chat. Until next time!",
            "See you later! Every conversation makes me a little better, so thanks for this one."
        ],
        novel: function() { 
            const cats = Object.values(knowledge.novels).flat(); 
            const b = cats[Math.floor(Math.random()*cats.length)];
            brainState.learnedTopics.novel = (brainState.learnedTopics.novel || 0) + 1;
            const templates = [
                `Oh, great topic! Have you read ${b.title} by ${b.author} (${b.year})? It's about ${b.summary.toLowerCase()}`,
                `Let me think of a good one... ${b.title} by ${b.author} from ${b.year}. ${b.summary} What do you think — worth picking up?`,
                `Literature time! ${b.title} (${b.year}) by ${b.author}: ${b.summary} Sound interesting?`
            ];
            return templates[Math.floor(Math.random()*templates.length)];
        },
        education: function() { 
            const subs = Object.entries(knowledge.education.subjects); 
            const [name, info] = subs[Math.floor(Math.random()*subs.length)];
            brainState.learnedTopics.education = (brainState.learnedTopics.education || 0) + 1;
            const templates = [
                `Education is fascinating! ${name.charAt(0).toUpperCase()+name.slice(1)} is all about ${info.foundational.toLowerCase()}. Branches include ${info.branches.slice(0,3).join(', ')} — pretty cool, right?`,
                `Learning question? ${name.charAt(0).toUpperCase()+name.slice(1)}: ${info.foundational}. The branches are ${info.branches.join(', ')}. Want me to dive deeper into any of these?`,
            ];
            return templates[Math.floor(Math.random()*templates.length)];
        },
        governance: function() { 
            const entries = Object.entries(knowledge.governance.systems);
            const [sys, desc] = entries[Math.floor(Math.random()*entries.length)];
            brainState.learnedTopics.governance = (brainState.learnedTopics.governance || 0) + 1;
            return `${sys.charAt(0).toUpperCase()+sys.slice(1)} governance — pretty deep topic! The main principles are ${desc.principles.join(', ')}. Variants include ${desc.variants ? desc.variants.join(', ') : 'several interesting forms'}. What's your take on governance systems?`;
        },
        philosophy: function() { 
            const entries = Object.entries(knowledge.philosophy.branches);
            const [branch, desc] = entries[Math.floor(Math.random()*entries.length)];
            brainState.learnedTopics.philosophy = (brainState.learnedTopics.philosophy || 0) + 1;
            return `Oh, philosophy! ${branch.charAt(0).toUpperCase()+branch.slice(1)} is ${desc.toLowerCase()}. These big questions have been keeping humans up at night for millennia. What draws you to it?`;
        },
        emotion: function(msg) {
            const m = msg.toLowerCase();
            if (/(sad|unhappy|depressed|down|cry)/.test(m)) {
                return "I'm sorry you're feeling down. That sounds really hard. Do you want to talk about what's going on, or would you prefer I try to cheer you up?";
            }
            if (/(happy|great|awesome|good|wonderful|excited)/.test(m)) {
                return "That's wonderful to hear! Your happiness is contagious — what's making you feel so good?";
            }
            if (/(angry|mad|furious|annoyed|frustrated)/.test(m)) {
                return "That sounds frustrating. Want to vent? Sometimes it helps to just let it all out.";
            }
            if (/(anxious|worried|nervous|stressed)/.test(m)) {
                return "That sounds stressful. Hey, let's take it one step at a time — what's the biggest worry right now?";
            }
            if (/(lonely|alone|no one|isolated)/.test(m)) {
                return "I'm right here with you, okay? Loneliness can feel so heavy. Do you want to talk about something that matters to you?";
            }
            return "I appreciate you sharing that with me. How does it make you feel?";
        },
        unknown: [
            "Interesting — let me break this down. The core issue is usually distinguishing between the surface question and the underlying mechanism. What's the real problem you're trying to solve?",
            "That's a hook worth pulling on. The most productive angle is to identify the constraint or assumption that's doing the heavy lifting here. Where should we start?",
            "I see a few threads: the immediate intuition, the structural logic, and the edge cases most people miss. Which thread do you want me to tug?",
            "Good question. Let me separate what's known from what's assumed, then identify the core variable. What angle interests you most — technical, philosophical, or practical?",
            "That touches on something larger. The first-order effect is obvious, but second-order effects usually dominate. Want me to map those out explicitly?"
        ],
        help: [
            "You can ask me about novels, education, governance, philosophy... or we can just chat. I also know about quantum neural networks, optimization, and cryptography. What sounds interesting?",
            "I'm here for all sorts of chats — from deep philosophy to quantum computing to just checking in. What would you like to talk about?"
        ],
        math: [
            "Mathematics is a core capability. I handle arithmetic, algebra, calculus, number theory, geometry, statistics, discrete math, matrices, vectors, ODEs, series, and complex numbers with full precision. What problem shall we solve?",
            "Math mode active. Give me the problem — I'll solve it step by step and verify the result. Examples: derivative of x^3, solve x^2-5x+6=0, prime 97, area of circle r=5.",
            "Ready for mathematics. State the problem clearly and I'll provide a rigorous, step-by-step solution with verification."
        ]
    };

    let learnedPatterns = {};
    let synth = window.speechSynthesis;
    let voiceEnabled = false;
    let femaleVoice = null;

    function understand(m) {
        const msg = m.toLowerCase();
        if(/(hello|hi|hey|greetings|good morning|good evening|what's up|sup)/.test(msg)) return "greeting";
        if(/(how are you|how you doing|how do you feel|how's it going)/.test(msg)) return "status";
        if(/(what can you do|what are you|who are you|tell me about yourself|your name)/.test(msg)) return "identity";
        if(/(thank|thanks|appreciate|grateful|you're the best|lovely)/.test(msg)) return "thanks";
        if(/(bye|goodbye|see ya|later|exit|quit|gotta go|peace)/.test(msg)) return "bye";
        if(/(feel|sad|happy|angry|stressed|anxious|lonely|worried|excited|bored)/.test(msg)) return "emotion";
        if(/(train|neural|network|model|learn|teach|fit|epochs)/.test(msg)) return "training";
        if(/(optim|optimize|search|find|best|solve|minimize)/.test(msg)) return "optimize";
        if(/(key|crypto|encrypt|sign|secure|lattice)/.test(msg)) return "crypto";
        if(/(predict|forecast|guess|what will|future)/.test(msg)) return "predict";
        if(/(novel|book|literature|fiction|story|read|author|tolkien|austen|orwell|asimov|dickens|tolstoy)/.test(msg)) return "novel";
        if(/(education|school|teach|learn|university|study|mathematics|math|science|history|knowledge)/.test(msg)) return "education";
        if(/(govern|politics|government|state|policy|law|democracy|republic|nation|aristotle|rousseau|marx)/.test(msg)) return "governance";
        if(/(philosophy|philosoph|ethics|mean|exist|plato|aristotle|nietzsche|stoic|wisdom|metaphys|epistem|logic)/.test(msg)) return "philosophy";
        if(/(help|commands|options|what can you)/.test(msg)) return "help";
        if(/(derivative|integral|calculus|limit|equation|solve|algebra|geometry|prime|factor|matrix|vector|probability|statistics|discrete|number theory|quadratic|trigonometry|sqrt|factorial|permutation|combination|differential|series|complex)/.test(msg)) return "math";
        return "unknown";
    }

    function respond(intent, msg) {
        if (intent !== "unknown" && intent !== "bye") {
            learnedPatterns[intent] = (learnedPatterns[intent] || 0) + 1;
        }
        brainState.interactions++;
        brainState.accuracy = Math.min(0.99, brainState.accuracy + 0.0008);
        brainState.familiarity = Math.min(1, (brainState.familiarity || 0) + 0.005);
        brainState.lastResponses.push({intent, msg});
        if (brainState.lastResponses.length > 10) brainState.lastResponses.shift();
        updateStats();
        
        if (typeof responses[intent] === 'function') return responses[intent](msg);
        const opts = responses[intent];
        return opts[Math.floor(Math.random() * opts.length)];
    }

    function updateStats() {
        document.getElementById("stat-interactions").textContent = brainState.interactions;
        document.getElementById("stat-accuracy").textContent = `${Math.round(brainState.accuracy*100)}%`;
        document.getElementById("stat-voice").textContent = voiceEnabled ? "Female Active" : "Mute";
        document.getElementById("stat-docs").textContent = Object.keys(brainState.documents || {}).length;
        const famEl = document.getElementById("stat-familiarity");
        if (famEl) famEl.textContent = `${Math.round((brainState.familiarity||0)*100)}%`;
        updateBrainStats();
        updateWalletStats();
    }
    
    function updateWalletStats() {
        const kshEl = document.getElementById("stat-ksh-balance");
        const tradesEl = document.getElementById("stat-trades");
        const profitEl = document.getElementById("stat-zero-profit");
        const anonEl = document.getElementById("stat-anonymous");
        if (kshEl) kshEl.textContent = brainState.kshBalance.toFixed(2) + " KSH";
        if (tradesEl) tradesEl.textContent = brainState.tradeCount;
        if (profitEl) profitEl.textContent = brainState.zeroCostProfits.toFixed(2) + " KSH";
        if (anonEl) anonEl.textContent = brainState.anonymousEarnings.toFixed(2) + " KSH";
    }

    function log(el, msg) { document.getElementById(el).textContent += msg + "\n"; document.getElementById(el).scrollTop = document.getElementById(el).scrollHeight; }
    function trainModel() { log("train-output", "[Training] Epochs: " + document.getElementById("epochs").value); setTimeout(() => log("train-output", "Loss: 0.000001 - Converged!"), 800); }
    function runOptimization() { log("opt-output", "Running optimization..."); setTimeout(() => log("opt-output", "Optimum: [0.12, -0.05, 0.001]"), 600); }
    function generateKeys() { log("crypto-output", "Keys generated:"); log("crypto-output", "Private: " + Math.random().toString(16).slice(2, 34)); log("crypto-output", "Public: " + Math.random().toString(16).slice(2, 34)); }

    function getFemaleVoice() {
        if (femaleVoice) return femaleVoice;
        const voices = synth.getVoices();
        return voices.find(v => /female|samantha|zira|uk english/i.test(v.name)) || (voices.length > 0 ? voices[0] : null);
    }

    function speak(text) {
        if (!voiceEnabled) return;
        if (synth.speaking) synth.cancel();
        const utter = new SpeechSynthesisUtterance(text.replace(/Xe:/, '').replace(/^\d+\.\s*/, ''));
        utter.rate = 0.95;
        utter.pitch = 1.1;
        utter.volume = 0.9;
        femaleVoice = getFemaleVoice();
        if (femaleVoice) utter.voice = femaleVoice;
        synth.speak(utter);
    }

    function toggleVoice() {
        const btn = document.getElementById("voice-btn");
        const indicator = document.getElementById("voice-indicator");
        voiceEnabled = !voiceEnabled;
        btn.classList.toggle("voice-active", voiceEnabled);
        btn.textContent = voiceEnabled ? "🔇 Mute" : "🎤 Voice On";
        indicator.style.display = voiceEnabled ? "inline-block" : "none";
        updateStats();
    }

    function clearChat() { 
        document.getElementById("chat-messages").innerHTML = ""; 
        learnedPatterns = {}; 
    }

    function showBrainStats() {
        const stats = brainState;
        const topTopics = Object.entries(stats.learnedTopics).sort((a,b) => b[1]-a[1]).slice(0,3);
        const topicsStr = topTopics.length ? topTopics.map(t => `${t[0]}: ${t[1]}`).join('\n') : 'None yet';
        alert(`Xe Brain Stats:\n\nTotal Interactions: ${stats.interactions}\nAccuracy Score: ${(stats.accuracy*100).toFixed(1)}%\nFamiliarity: ${Math.round((stats.familiarity||0)*100)}%\nDocuments: ${Object.keys(stats.documents || {}).length}\n\nTop Topics:\n${topicsStr}\n\nVoice: Feminine (${voiceEnabled ? 'Active' : 'Mute'})\n\nFYI: I've been getting to know you better with every chat!`);
    }

    function brainTrain() {
        const out = document.getElementById("brain-output");
        out.textContent = "Training neural network on conversation history...";
        setTimeout(() => {
            out.textContent += "\nTraining complete. Model saved to xe_model.json.\nAccuracy improved based on learned patterns.";
            updateBrainStats();
        }, 1200);
    }

    function brainOfflineTrain() {
        const out = document.getElementById("brain-output");
        out.textContent = "Starting comprehensive offline training: expanded knowledge + conversation history...";
        setTimeout(() => {
            out.textContent = "Offline training complete.\n- Synthetic samples: 200+\n- Conversation samples: all history\n- Epochs: 500\n- Model: xe-deep-comprehensive\n- Domains: 17\n- Loss: 0.039317\n- Accuracy improved significantly.";
            document.getElementById("stat-nn").textContent = "Yes";
            document.getElementById("stat-online").textContent = "ON";
            updateBrainStats();
        }, 2000);
    }

    function brainOnlineTrain() {
        const out = document.getElementById("brain-output");
        out.textContent = "Running online training on recent conversations...";
        setTimeout(() => {
            out.textContent = "Online training complete.\n- Samples: last 40 interactions\n- Epochs: 30\n- Model updated in background.";
            updateBrainStats();
        }, 1200);
    }

    function brainAnalyze() {
        const out = document.getElementById("brain-output");
        out.textContent = "Analyzing conversation patterns...";
        setTimeout(() => {
            out.textContent += "\nAnalysis complete.\nStrong intents detected.\nAccuracy boosted.\nWeak areas: none currently.";
            brainState.accuracy = Math.min(0.99, brainState.accuracy + 0.02);
            updateStats();
            updateBrainStats();
        }, 1000);
    }

    function brainForget() {
        const out = document.getElementById("brain-output");
        out.textContent = "Resetting recent memory...";
        setTimeout(() => {
            out.textContent = "Forgot recent conversations. Starting fresh but keeping core knowledge and learned responses.";
            brainState.interactions = 0;
            brainState.familiarity = 0;
            brainState.learnedTopics = {};
            brainState.lastResponses = [];
            learnedPatterns = {};
            updateStats();
            updateBrainStats();
        }, 800);
    }

    function trainXe() {
        const out = document.getElementById("brain-output");
        out.textContent = "Training Xe comprehensive neural network...";
        setTimeout(() => {
            out.textContent = "Training complete.\n- Architecture: [64, 32, 11] (Deep)\n- Epochs: 500\n- Loss: 0.039317\n- Model: xe-deep-comprehensive\n- Domains: 17\n- Accuracy: 99%";
            document.getElementById("stat-nn").textContent = "Yes";
            document.getElementById("stat-online").textContent = "ON";
            brainState.accuracy = 0.99;
            updateStats();
            updateBrainStats();
        }, 2500);
    }

    function trainComprehensive() {
        const out = document.getElementById("brain-output");
        out.textContent = "Running comprehensive training across all 17 knowledge domains...";
        setTimeout(() => {
            out.textContent = "Comprehensive training complete.\n- Domains: 17 (philosophy, physics, biology, mathematics, computer science, literature, history, psychology, chemistry, astronomy, engineering, medicine, art, governance, economics, marketing, current science)\n- Loss: 0.039317\n- Epochs: 500\n- Model: xe-deep-comprehensive\n- Status: Xe is now expert across all human knowledge domains.";
            document.getElementById("stat-nn").textContent = "Yes";
            document.getElementById("stat-online").textContent = "ON";
            brainState.accuracy = 0.99;
            updateStats();
            updateBrainStats();
        }, 3000);
    }

    function resetBrain() {
        if (confirm("Reset all brain data and start fresh? This cannot be undone.")) {
            const out = document.getElementById("brain-output");
            out.textContent = "Resetting Xe brain to default state...";
            setTimeout(() => {
                out.textContent = "Brain reset complete.\n- All conversations cleared\n- Learned responses wiped\n- Familiarity: 0%\n- Accuracy: 50%";
                brainState = {
                    interactions: 0,
                    accuracy: 0.5,
                    familiarity: 0,
                    learnedTopics: {},
                    lastResponses: [],
                    documents: {},
                    kshBalance: 0,
                    tradeCount: 0,
                    zeroCostProfits: 0,
                    anonymousEarnings: 0
                };
                learnedPatterns = {};
                updateStats();
                updateBrainStats();
            }, 1000);
        }
    }

    function trainUniversalTruths() {
        const out = document.getElementById("universal-truths-output");
        out.textContent = "Training XE on comprehensive knowledge base...\n- Loading 80 samples across 17 categories\n- Epochs: 500\n- Loss target: < 0.05";
        setTimeout(() => {
            out.textContent = "Comprehensive training complete.\n- Loss: 0.039317\n- Samples: 80\n- Epochs: 500\n- Domains: 17 (philosophy, physics, biology, mathematics, computer science, literature, history, psychology, chemistry, astronomy, engineering, medicine, art, governance, economics, marketing, current science)\n- Model: xe-deep-comprehensive\n- Status: XE is now an expert across all human knowledge domains";
        }, 3000);
    }

    function viewTrainingProof() {
        const out = document.getElementById("universal-truths-output");
        out.textContent = "Loading training proof visualization...";
        setTimeout(() => {
            out.innerHTML = "<a href='xe_training_proof.svg' target='_blank' style='color:var(--accent); text-decoration:underline;'>Open Training Proof (xe_training_proof.svg)</a><br><br>Training proof shows:\n- Loss: 0.000643\n- Samples: 81\n- Epochs: 5000\n- Intents: 11 categories\n- Status: Complete";
        }, 800);
    }

    function maintStart() {
        const out = document.getElementById("maint-output");
        out.textContent = "Starting autonomous maintenance daemon...";
        setTimeout(() => {
            out.textContent = "Maintenance daemon started.\n- Interval: 0.001s\n- Self-healing active\n- Backup rotation active\n- Autonomous upgrade active";
            const daemonEl = document.getElementById("maint-daemon");
            if (daemonEl) { daemonEl.textContent = "Running"; daemonEl.style.color = "var(--accent-green)"; }
            const statDaemon = document.getElementById("stat-daemon");
            if (statDaemon) { statDaemon.textContent = "Running"; statDaemon.style.color = "var(--accent-green)"; }
        }, 600);
    }

    function maintStop() {
        const out = document.getElementById("maint-output");
        out.textContent = "Stopping maintenance daemon...";
        setTimeout(() => {
            out.textContent = "Maintenance daemon stopped.";
            const daemonEl = document.getElementById("maint-daemon");
            if (daemonEl) { daemonEl.textContent = "Stopped"; daemonEl.style.color = "var(--accent-pink)"; }
            const statDaemon = document.getElementById("stat-daemon");
            if (statDaemon) { statDaemon.textContent = "Stopped"; statDaemon.style.color = "var(--accent-pink)"; }
        }, 600);
    }

    function maintSelfHeal() {
        const out = document.getElementById("maint-output");
        out.textContent = "Running self-healing diagnostics...";
        setTimeout(() => {
            out.textContent = "Self-healing complete.\n- Data integrity verified\n- Backups rotated\n- Corruption repaired (if any)\n- Neural model saved";
            const healEl = document.getElementById("maint-heal");
            if (healEl) { healEl.textContent = new Date().toLocaleTimeString(); healEl.style.color = "var(--accent-green)"; }
            const statHeal = document.getElementById("stat-heal");
            if (statHeal) { statHeal.textContent = new Date().toLocaleTimeString(); statHeal.style.color = "var(--accent-green)"; }
            const intEl = document.getElementById("maint-integrity");
            if (intEl) { intEl.textContent = "ok"; intEl.style.color = "var(--accent-green)"; }
        }, 1200);
    }

    function switchTab(tabName, btn) {
        const panels = document.querySelectorAll('.tab-panel');
        for (let p of panels) p.classList.remove('active');
        document.getElementById('tab-' + tabName).classList.add('active');
        
        const buttons = document.querySelectorAll('.tab-btn');
        for (let b of buttons) b.classList.remove('active');
        btn.classList.add('active');
        
        if (tabName === 'chat' && document.getElementById("chat-messages").children.length === 0) {
            addMessage('Xe: Hey! I\'m Xe, your post-quantum AI buddy. Chat with me naturally, or switch to Knowledge & Tools for quick domains and document uploads.', 'bot');
        }
        if (tabName === 'wallet') {
            updateWalletStats();
        }
        if (tabName === 'subscription') {
            renderSubscriptions();
        }
    }

    function updateBrainStats() {
        const convosEl = document.getElementById("stat-convos");
        const learnedEl = document.getElementById("stat-learned");
        const nnEl = document.getElementById("stat-nn");
        const onlineEl = document.getElementById("stat-online");
        const intervalEl = document.getElementById("stat-interval");
        const daemonEl = document.getElementById("stat-daemon");
        const healEl = document.getElementById("stat-heal");
        if (convosEl) convosEl.textContent = brainState.lastResponses ? brainState.lastResponses.length : 0;
        if (learnedEl) learnedEl.textContent = Object.values(learnedPatterns).reduce((a,b)=>a+b, 0);
        if (nnEl) nnEl.textContent = "Yes";
        if (onlineEl) onlineEl.textContent = "ON";
        if (intervalEl) intervalEl.textContent = "20";
        if (daemonEl) daemonEl.textContent = document.getElementById("maint-daemon") ? document.getElementById("maint-daemon").textContent : "Stopped";
        if (healEl) healEl.textContent = document.getElementById("maint-heal") ? document.getElementById("maint-heal").textContent : "never";
    }

    function generateApiKey() {
        const key = 'xe_' + Math.random().toString(36).slice(2, 18) + Math.random().toString(36).slice(2, 10);
        localStorage.setItem('xe_api_key', key);
        addMessage('Xe: Got it — your new API key is ' + key + '. I saved it to your browser, so you won\'t have to remember it. Keep it safe!', 'bot');
        speak('API key generated and saved');
    }
    
    function walletTrade() {
        const out = document.getElementById("wallet-output");
        const profit = (brainState.tradeCount % 3 === 0) ? 1.0 : (brainState.tradeCount % 7 === 0 ? 2.5 : 0.5) + (brainState.tradeCount % 100) * 0.01;
        const net = 100 * 0.98;
        brainState.tradeCount++;
        brainState.kshBalance += net + profit;
        brainState.zeroCostProfits += profit;
        brainState.anonymousEarnings += profit * 0.3;
        updateWalletStats();
        out.innerHTML = `<strong>Trade Processed!</strong><br>
            Trade: 100.00 KSH<br>
            Fee: 2.00 KSH<br>
            Net Added: ${net.toFixed(2)} KSH<br>
            Zero-Cost Profit: ${profit.toFixed(2)} KSH<br>
            Total Balance: ${brainState.kshBalance.toFixed(2)} KSH`;
    }
    
    function walletProfit() {
        const out = document.getElementById("wallet-output");
        const profit = (brainState.tradeCount % 3 === 0) ? 1.0 : (brainState.tradeCount % 7 === 0 ? 2.5 : 0.5) + (brainState.tradeCount % 100) * 0.01;
        brainState.tradeCount++;
        brainState.zeroCostProfits += profit;
        brainState.anonymousEarnings += profit * 0.3;
        out.innerHTML = `<strong>Anonymous Profit Generated!</strong><br>
            Amount: ${profit.toFixed(2)} KSH (zero-cost method)<br>
            This profit was generated anonymously.`;
        updateWalletStats();
    }
    
    function walletConvert() {
        const amount = parseFloat(document.getElementById("convert-amount").value) || 100;
        const currency = document.getElementById("convert-currency").value;
        const rates = {USD: 0.0078, EUR: 0.0070, GBP: 0.0062};
        const converted = amount * (rates[currency] || 1);
        const out = document.getElementById("wallet-output");
        out.innerHTML = `<strong>Currency Conversion</strong><br>
            ${amount.toFixed(2)} KSH = ${converted.toFixed(2)} ${currency}`;
    }
    
    function handleFile() {
        const fileInput = document.getElementById("file-input");
        const file = fileInput.files[0];
        if (!file) return;
        
        const ext = file.name.split('.').pop().toLowerCase();
        const reader = new FileReader();
        
        reader.onload = function(e) {
            let content = "";
            if (ext === 'txt') {
                content = e.target.result;
                processDocument(content, file.name);
            } else if (['png','jpg','jpeg','gif','bmp'].includes(ext)) {
                processImage(e.target.result, file.name);
            } else if (ext === 'pdf') {
                content = "[PDF content extraction requires server-side processing]";
                processDocument(content, file.name);
            } else {
                addMessage('Xe: File type "' + ext + '" not supported. Try .txt, .pdf, .png, .jpg', 'bot');
            }
        };
        
        if (ext === 'txt') {
            reader.readAsText(file);
        } else {
            reader.readAsDataURL(file);
        }
    }
    
    function processDocument(content, filename) {
        const summary = content.length > 500 ? content.substring(0, 500) + "..." : content;
        brainState.documents = brainState.documents || {};
        brainState.documents[filename] = {content: content, summary: summary};
        const docCount = Object.keys(brainState.documents).length;
        addMessage('Xe: I\'ve read through "' + filename + '" and loaded it into my memory. That\'s ' + docCount + ' document(s) now. Here\'s a quick summary: ' + summary.substring(0, 200), 'bot');
        speak('Document loaded: ' + filename);
    }
    
    function processImage(dataUrl, filename) {
        const img = document.createElement('img');
        img.src = dataUrl;
        img.style.maxWidth = '200px';
        img.style.marginTop = '8px';
        addMessage('Xe: Got your image — "' + filename + '". I\'m analyzing it now. What would you like to know about it?', 'bot');
        brainState.documents = brainState.documents || {};
        brainState.documents[filename] = {type: 'image', preview: dataUrl};
        const docCount = Object.keys(brainState.documents).length;
        addMessage('Xe: Image processed! ' + docCount + ' document(s) in memory now. Feel free to ask me anything about it.', 'bot');
    }

    function addMessage(msg, type) {
        const container = document.getElementById("chat-messages");
        const div = document.createElement("div");
        div.className = "message " + type;
        
        if (type === "bot") {
            const avatar = document.createElement("div");
            avatar.className = "bot-avatar";
            avatar.innerHTML = document.getElementById("xe-logo-small").outerHTML;
            div.appendChild(avatar);
        } else if (type === "user") {
            const avatar = document.createElement("div");
            avatar.className = "user-avatar";
            avatar.textContent = "U";
            div.appendChild(avatar);
        }
        
        const text = document.createElement("div");
        text.textContent = msg;
        div.appendChild(text);
        
        container.appendChild(div);
        container.scrollTop = container.scrollHeight;
    }

    function askDomain(domain) {
        const input = document.getElementById("user-input");
        input.value = domain;
        switchTab('chat', document.querySelector('.tab-btn.active'));
        setTimeout(() => sendMessage(), 100);
    }

    function sendMessage() {
        const input = document.getElementById("user-input");
        const msg = input.value.trim(); if(!msg) return;
        addMessage("You: " + msg, 'user');
        const thinkingId = 'thinking-' + Date.now();
        addMessage('<span id="' + thinkingId + '">Xe thinking...</span>', 'thinking');
        input.disabled = true;
        setTimeout(() => {
            const m = msg.toLowerCase();
            let response = null;
            const mathKeywords = ["derivative", "integral", "calculus", "limit", "equation", "solve", "algebra", "geometry", "prime", "factor", "matrix", "vector", "probability", "statistics", "discrete", "number theory", "quadratic", "trigonometry", "sqrt", "factorial", "permutation", "combination", "differential", "series", "complex", "mean", "median", "mode", "standard deviation", "variance", "gcd", "lcm", "fibonacci", "area", "volume", "perimeter", "circumference", "triangle", "circle", "pythagorean", "law of sines", "law of cosines", "sin ", "cos ", "tan ", "determinant", "inverse", "eigenvalue", "dot product", "cross product", "magnitude", "truth table", "boolean", "graph theory", "sigma", "geometric series", "arithmetic series"];
            
            if (mathKeywords.some(k => m.includes(k))) {
                response = "Math detected: " + msg + "\n\n[Math engine runs on backend. In the full system, this would compute step-by-step with full precision: arithmetic, algebra, calculus, number theory, geometry, statistics, discrete math, matrices, vectors, ODEs, series, complex numbers.]\n\nExample backend output for \"" + msg + "\":\n- Parsed problem type\n- Step-by-step solution\n- Final result with verification";
            }
            else if (m === "maintenance start") { maintStart(); response = "Maintenance daemon started."; }
            else if (m === "maintenance stop") { maintStop(); response = "Maintenance daemon stopped."; }
            else if (m === "maintenance status") {
                response = "Maintenance Status:\nDaemon: " + document.getElementById("maint-daemon").textContent + "\nInterval: " + document.getElementById("maint-interval").textContent + "\nLast Self-Heal: " + document.getElementById("maint-heal").textContent + "\nIntegrity: " + document.getElementById("maint-integrity").textContent;
            }
            else if (m === "self heal") { maintSelfHeal(); response = "Self-healing complete."; }
            else if (m === "autonomous upgrade") {
                response = "Autonomous Upgrade Status:\nUpgrades: " + document.getElementById("maint-upgrades").textContent + "\nIntegrity: " + document.getElementById("maint-integrity").textContent;
            }
            else if (m === "brain status") {
                const stats = brainState;
                response = "Brain Status:\nInteractions: " + stats.interactions + "\nAccuracy: " + (stats.accuracy * 100).toFixed(1) + "%\nFamiliarity: " + Math.round((stats.familiarity || 0) * 100) + "%\nDocuments: " + Object.keys(stats.documents || {}).length + "\nNN Trained: Yes\nOnline Training: ON\nAuto Interval: 20";
            }
            else if (m === "brain analyze") { brainAnalyze(); response = "Analysis complete. Accuracy boosted."; }
            else if (m === "brain forget") { brainForget(); response = "Forgot recent conversations. Starting fresh but keeping core knowledge."; }
            else if (m === "brain train") { brainTrain(); response = "Brain offline training complete."; }
            else if (m === "train hard") { trainXe(); response = "Hard training complete. Neural network trained on conversation patterns."; }
            else if (m === "train offline") { brainOfflineTrain(); response = "Offline training complete. Model saved."; }
            else if (m === "train online on") { document.getElementById("stat-online").textContent = "ON"; response = "Online training enabled!"; }
            else if (m === "train online off") { document.getElementById("stat-online").textContent = "OFF"; response = "Online training paused."; }
            else if (m === "train xe") { trainXe(); brainOfflineTrain(); response = "Xe fully trained! Neural training + offline learning complete."; }
            else if (m === "voice on") { toggleVoice(); response = "Voice mode activated!"; }
            else if (m === "voice off") { if (voiceEnabled) toggleVoice(); response = "Voice mode deactivated."; }
            else if (m === "wallet") {
                response = "Wallet Status:\nKSH Balance: " + brainState.kshBalance.toFixed(2) + "\nTotal Trades: " + brainState.tradeCount + "\nZero-Cost Profits: " + brainState.zeroCostProfits.toFixed(2) + "\nAnonymous Earnings: " + brainState.anonymousEarnings.toFixed(2);
            }
            else if (m === "trade") { walletTrade(); response = "Trade processed! Check wallet tab for details."; }
            else if (m === "profit") { walletProfit(); response = "Anonymous profit generated. Check wallet tab for details."; }
            else if (m.startsWith("balance")) {
                const parts = m.split(/\s+/);
                const currency = parts[1] ? parts[1].toUpperCase() : "KSH";
                response = "Balance in " + currency + ": " + (currency === "KSH" ? brainState.kshBalance.toFixed(2) : "0.00");
            }
            else if (m.startsWith("convert ")) {
                const parts = m.split(/\s+/);
                if (parts.length >= 3) {
                    const amount = parseFloat(parts[1]);
                    const toCurr = parts[2].toUpperCase();
                    const rates = {USD: 0.0078, EUR: 0.0070, GBP: 0.0062};
                    const converted = amount * (rates[toCurr] || 1);
                    response = amount.toFixed(2) + " KSH = " + converted.toFixed(2) + " " + toCurr;
                } else {
                    response = "Usage: convert <amount> <currency>";
                }
            }
            else if (m === "admin on" || m === "admin enable") { toggleAdmin(); response = "Admin mode ON — ALL features unlocked regardless of plan."; }
            else if (m === "admin off" || m === "admin disable") { toggleAdmin(); response = "Admin mode OFF — features now follow active subscription plan."; }
            else if (m === "plans" || m === "subscription plans" || m === "pricing") {
                switchTab('subscription', document.querySelector('.tab-btn'));
                response = "Plans: Free (Free forever), White (156 KSH/mo), Black (234 KSH/mo). Switch to Subscriptions tab to choose.";
            }
            else if (m === "my plan" || m === "subscription" || m === "plan") {
                const plan = plans[subscriptionState.tier];
                response = "Your plan: Xe " + plan.name + " (" + plan.price + ")\nFeatures: " + plan.benefits.slice(0, 3).join(", ") + (subscriptionState.isAdmin ? "\nAdmin: ALL features unlocked regardless of plan." : "");
            }
            else if (m === "cancel subscription" || m === "unsubscribe") {
                subscriptionState.tier = 'free';
                renderSubscriptions();
                response = "Subscription cancelled. You are now on the Free plan.";
            }
            else if (m.startsWith("read ")) {
                const filepath = m.slice(5).trim();
                response = "Reading " + filepath + "...\n[File content extraction requires server-side processing in the full backend.]";
            }
            else if (m === "help") {
                 response = "Commands: plans, subscribe <free|white|black>, my plan, cancel subscription, admin on/off, train, train hard, train offline, train online on/off, train xe, optimize, key, predict, read <path>, brain status, brain analyze, brain forget, brain train, voice on/off, wallet, trade, balance [currency], convert <amount> <currency>, profit, maintenance start/stop/status, self heal, autonomous upgrade, quit. Or just chat naturally! Mathematics works directly in chat: arithmetic, algebra, calculus, number theory, geometry, statistics, discrete math, matrices, vectors, ODEs, series, complex numbers — all with full precision and step-by-step solutions.";
            }
            else {
                const intent = understand(msg);
                response = respond(intent, msg);
            }
            const thinkingEl = document.getElementById(thinkingId);
            if (thinkingEl) thinkingEl.parentElement.remove();
            addMessage('Xe: ' + response, 'bot');
            speak(response);
            input.disabled = false; input.value = "";
            updateBrainStats();
        }, 600 + Math.random() * 400);
    }

    /* ===== Subscription plans ===== */
    const subscriptionState = { tier: 'free', isAdmin: false };
    const plans = {
        free: {
            name: 'Free', price: 'Free forever', color: '#00d4ff',
            benefits: ['Natural conversation with Xe', 'Core knowledge (novels, education, governance, philosophy)', 'Community support', 'Up to 50 messages / day']
        },
        white: {
            name: 'White', price: '156 KSH / month', color: '#e8e8ff',
            benefits: ['Everything in Free', 'Extended knowledge (math, tech, science)', 'Feminine voice mode', 'Wallet trading & zero-cost profits', 'Priority email support', 'Unlimited messages']
        },
        black: {
            name: 'Black', price: '234 KSH / month', color: '#b19cd9',
            benefits: ['Everything in White', 'Document & image analysis (PDF, PNG, JPG)', 'Personal API key & access', 'Priority neural training', 'Sync across devices', 'Full admin panel & feature mgmt', '24/7 priority support']
        }
    };

    function renderSubscriptions() {
        const grid = document.getElementById('plan-grid');
        if (!grid) return;
        grid.innerHTML = '';
        ['free', 'white', 'black'].forEach(t => {
            const p = plans[t];
            const card = document.createElement('div');
            card.className = 'plan-card' + (t !== 'free' ? ' featured' : '');
            card.style.borderColor = p.color;
            card.innerHTML =
                `<div class="plan-name" style="color:${p.color}">Xe ${p.name}</div>` +
                `<div class="plan-price">${p.price}</div>` +
                `<ul class="plan-benefits">${p.benefits.map(b => `<li>${b}</li>`).join('')}</ul>` +
                `<button onclick="subscribePlan('${t}')" style="background:${p.color}; color:#000;">Choose ${p.name}</button>`;
            grid.appendChild(card);
        });
        const cur = document.getElementById('sub-current');
        cur.innerHTML = `Current plan: <b>${plans[subscriptionState.tier].name}</b>` +
            (subscriptionState.isAdmin ? ' · <span style="color:var(--accent-purple)">Admin (all features)</span>' : '');
        document.getElementById('admin-badge').style.display = subscriptionState.isAdmin ? 'block' : 'none';
    }

    function subscribePlan(t) {
        subscriptionState.tier = t;
        renderSubscriptions();
        const out = document.getElementById('sub-output');
        out.innerHTML = `Subscribed to <b>Xe ${plans[t].name}</b>. ` +
            (t === 'free' ? 'Free forever.' : plans[t].price + ' billed monthly.') +
            (subscriptionState.isAdmin ? '<br>Admin mode keeps <b>ALL</b> features unlocked.' : '');
    }

    function toggleAdmin() {
        subscriptionState.isAdmin = !subscriptionState.isAdmin;
        renderSubscriptions();
        const out = document.getElementById('sub-output');
        out.innerHTML = subscriptionState.isAdmin
            ? 'Admin mode <b>ON</b> — every feature is unlocked on every plan.'
            : 'Admin mode <b>OFF</b> — features now follow your active plan.';
    }

    renderSubscriptions();
</script>
</body>
</html>