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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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Call Manager</title>
    <script src="https://cdn.tailwindcss.com/3.4.0"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <script src="https://sdk.vercel.app/external_api.js"></script> <!-- updated Jitsi URL -->
    <script src="https://cdn.apple-mapkit.com/mk/5.x/mapkit.js"></script>
    <!-- Added Pusher for real-time chat -->
    <script src="https://js.pusher.com/8.2.0/pusher.min.js"></script>
    <style>
        @keyframes pulse-ring {
            0% { transform: scale(0.33); }
            80%, 100% { opacity: 0; }
        }
        @keyframes pulse-dot {
            0% { transform: scale(0.8); }
            50% { transform: scale(1); }
            100% { transform: scale(0.8); }
        }
        /* Custom scrollbar */
        .custom-scrollbar::-webkit-scrollbar {
            width: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
            background: rgba(156, 163, 175, 0.1);
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
            background: rgba(99, 102, 241, 0.5);
            border-radius: 3px;
        }
        
        .call-control-btn {
            @apply py-2 px-3 rounded-lg flex flex-col items-center justify-center text-sm font-medium transition;
        }
        
        #callTranscript {
            scroll-behavior: smooth;
        }
        /* Call animation */
        .call-animation {
            position: relative;
            width: 50px;
            height: 50px;
        }
        .call-animation:before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(16, 185, 129, 0.5);
            border-radius: 50%;
            animation: pulse-ring 1.5s cubic-bezier(0.215, 0.61, 0.355, 1) infinite;
        }
        .call-animation:after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: #10B981;
            border-radius: 50%;
            transform: scale(0.8);
            animation: pulse-dot 1.5s cubic-bezier(0.455, 0.03, 0.515, 0.955) -0.4s infinite;
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen font-sans">
    <div class="container mx-auto px-4 py-8 max-w-md">
        <!-- Header -->
        <header class="flex justify-between items-center mb-8">
            <h1 class="text-2xl font-bold text-indigo-700">AI Call Manager</h1>
            <div class="flex space-x-2">
                <button id="settingsBtn" class="p-2 rounded-full bg-gray-100 hover:bg-gray-200 transition" title="Settings">
                    <i class="fas fa-cog text-gray-600"></i>
                </button>
                <button id="tullioBtn" class="p-2 rounded-full bg-green-100 hover:bg-green-200 transition" title="Tullio Token System">
                    <i class="fas fa-coins text-green-600"></i>
                </button>
            </div>
        </header>

        <!-- Main Dashboard -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden mb-6">
            <div class="p-6">
                <div class="flex items-center mb-6">
                    <div class="call-animation mr-4"></div>
                    <div>
                        <h2 class="text-lg font-semibold text-gray-800">Call Management</h2>
                        <p class="text-sm text-gray-500">Active for: <span class="font-medium phone-number-display">(562) 228-9429</span></p>
                    </div>
                </div>
                
                <!-- Call Management Section -->
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Answer Calls After</label>
                        <select id="callDelay" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                            <option value="15">15 seconds</option>
                            <option value="30" selected>30 seconds</option>
                            <option value="45">45 seconds</option>
                            <option value="60">1 minute</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="flex items-center space-x-3">
                            <input type="checkbox" id="enableCallAI" class="rounded h-5 w-5 text-indigo-600 focus:ring-indigo-500" checked>
                            <span class="text-sm font-medium text-gray-700">Enable Call AI Assistant</span>
                        </label>
                        <p class="mt-1 text-xs text-gray-500">AI will answer calls when you're unavailable</p>
                    </div>
                    
                    <div id="callSettings" class="pl-8">
                        <div class="mt-3">
                            <label class="block text-sm font-medium text-gray-700 mb-1">AI Voice</label>
                            <select class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                                <option>American Female (Emma)</option>
                                <option>American Male (Brian)</option>
                                <option>British Female (Amy)</option>
                            </select>
                        </div>
                        
                        <div class="mt-3">
                            <label class="block text-sm font-medium text-gray-700 mb-1">Default Message</label>
                            <textarea id="callGreeting" rows="2" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500" placeholder="Hello, I'm unable to take your call right now. Please leave a message or send a text and I'll get back to you soon."></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Make a Call Section -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden mb-6">
            <div class="p-6">
                <div class="flex items-center mb-6">
                    <div class="w-12 h-12 flex items-center justify-center bg-blue-100 rounded-full mr-4">
                        <i class="fas fa-phone text-blue-600 text-xl"></i>
                    </div>
                    <div>
                        <h2 class="text-lg font-semibold text-gray-800">Make a Call</h2>
                        <p class="text-sm text-gray-500">Train AI with interactive calls</p>
                    </div>
                </div>
                
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Phone Number to Call</label>
                        <input type="tel" id="callNumber" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" placeholder="e.g. (562) 228-9429" value="15622289429">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Call Purpose</label>
                        <select id="callPurpose" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            <option value="training">AI Training Session</option>
                            <option value="outgoing">Regular Outgoing Call</option>
                        </select>
                    </div>
                    
                    <div id="trainingOptions" class="pl-4 space-y-3 hidden">
                        <label class="flex items-center space-x-3">
                            <input type="checkbox" id="enableCallTraining" class="rounded h-4 w-4 text-blue-600 focus:ring-blue-500" checked>
                            <span class="text-sm font-medium text-gray-700">Enable Interactive Training</span>
                        </label>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Training Mode</label>
                            <select id="callTrainingMode" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm">
                                <option value="qa">Q&A Training</option>
                                <option value="conversation">Conversation Practice</option>
                                <option value="scenario">Scenario Simulation</option>
                            </select>
                        </div>
                    </div>
                    
                    <button id="startCallBtn" class="w-full py-3 px-4 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition flex items-center justify-center space-x-2">
                        <i class="fas fa-phone"></i>
                        <span>Start Call</span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Text AI Section -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden mb-6">
            <div class="p-6">
                <div class="flex items-center mb-6">
                    <div class="w-12 h-12 flex items-center justify-center bg-purple-100 rounded-full mr-4">
                        <i class="fas fa-comment-alt text-purple-600 text-xl"></i>
                    </div>
                    <div>
                        <h2 class="text-lg font-semibold text-gray-800">Text AI Assistant</h2>
                        <p class="text-sm text-gray-500">Smart responses & automated replies</p>
                    </div>
                </div>
                
                <div class="space-y-4">
                    <div>
                        <label class="flex items-center space-x-3">
                            <input type="checkbox" id="enableTextAI" class="rounded h-5 w-5 text-purple-600 focus:ring-purple-500" checked>
                            <span class="text-sm font-medium text-gray-700">Enable Text AI Assistant</span>
                        </label>
                        <p class="mt-1 text-xs text-gray-500">AI will respond to unanswered texts automatically</p>
                    </div>
                    
                    <div id="textSettings" class="pl-8 space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Response Style</label>
                            <select id="responseStyle" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500">
                                <option value="professional">Professional</option>
                                <option value="friendly" selected>Friendly</option>
                                <option value="concise">Concise</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Auto-response Delay</label>
                            <select id="textDelay" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500">
                                <option value="1">1 hour</option>
                                <option value="2" selected>2 hours</option>
                                <option value="4">4 hours</option>
                                <option value="6">6 hours</option>
                                <option value="12">12 hours</option>
                            </select>
                        </div>
                        
                        <div class="pt-2">
                            <button id="trainAIbtn" class="w-full py-2 px-4 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition flex items-center justify-center space-x-2">
                                <i class="fas fa-brain"></i>
                                <span>Train Text AI</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stats Section -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden mb-6">
            <div class="p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">Usage Statistics</h2>
                <div class="grid grid-cols-2 gap-4">
                    <div class="bg-indigo-50 p-3 rounded-lg">
                        <p class="text-xs text-indigo-600 font-medium">Calls Managed</p>
                        <p class="text-2xl font-bold text-indigo-700" id="callStatsCount">128</p>
                    </div>
                    <div class="bg-purple-50 p-3 rounded-lg">
                        <p class="text-xs text-purple-600 font-medium">Texts Responded</p>
                        <p class="text-2xl font-bold text-purple-700" id="textStatsCount">342</p>
                    </div>
                    <div class="bg-green-50 p-3 rounded-lg">
                        <p class="text-xs text-green-600 font-medium">AI Confidence</p>
                        <p class="text-2xl font-bold text-green-700">89%</p>
                    </div>
                    <div class="bg-yellow-50 p-3 rounded-lg">
                        <p class="text-xs text-yellow-600 font-medium">Training Cycles</p>
                        <p class="text-2xl font-bold text-yellow-700">24</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Call Log Preview -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-semibold text-gray-800">Recent Activity</h2>
                    <button class="text-xs text-indigo-600 hover:text-indigo-800">View All</button>
                </div>
                <div class="space-y-3 max-h-60 overflow-y-auto custom-scrollbar">
                    <div class="flex items-start py-2 border-b border-gray-100">
                        <div class="flex-shrink-0 h-10 w-10 rounded-full bg-red-100 flex items-center justify-center mr-3">
                            <i class="fas fa-phone-alt text-red-500"></i>
                        </div>
                        <div class="flex-1">
                            <p class="text-sm font-medium text-gray-800">Missed Call</p>
                            <p class="text-xs text-gray-500">From: (562) 555-0134</p>
                            <p class="text-xs text-gray-500">14 min ago - AI answered after 30s</p>
                        </div>
                    </div>
                    <div class="flex items-start py-2 border-b border-gray-100">
                        <div class="flex-shrink-0 h-10 w-10 rounded-full bg-green-100 flex items-center justify-center mr-3">
                            <i class="fas fa-sms text-green-500"></i>
                        </div>
                        <div class="flex-1">
                            <p class="text-sm font-medium text-gray-800">Text Response</p>
                            <p class="text-xs text-gray-500">To: (562) 555-0198</p>
                            <p class="text-xs text-gray-500">1 hour ago - AI confidence: 92%</p>
                        </div>
                    </div>
                    <div class="flex items-start py-2 border-b border-gray-100">
                        <div class="flex-shrink-0 h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center mr-3">
                            <i class="fas fa-phone-alt text-blue-500"></i>
                        </div>
                        <div class="flex-1">
                            <p class="text-sm font-medium text-gray-800">AI Call</p>
                            <p class="text-xs text-gray-500">With: (562) 555-0163 (2m 43s)</p>
                            <p class="text-xs text-gray-500">3 hours ago - Scheduled follow-up</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Call Interface Container -->
    <div id="callInterface" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 id="callStatus" class="text-lg font-semibold">Call in progress</h3>
                    <button onclick="endCurrentCall()" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div class="mb-4">
                    <div id="callTranscript" class="h-48 overflow-y-auto bg-gray-50 p-3 rounded-lg text-sm">
                        <!-- Transcript will appear here -->
                    </div>
                </div>
                
                <div class="grid grid-cols-3 gap-2">
                    <button onclick="sendCallCommand('mute')" class="call-control-btn bg-gray-100 hover:bg-gray-200">
                        <i class="fas fa-microphone-slash"></i> Mute
                    </button>
                    <button onclick="sendCallCommand('hold')" class="call-control-btn bg-yellow  -100 hover:bg-yellow-200">
                        <i class="fas fa-pause"></i> Hold
                    </button>
                    <button onclick="sendCallCommand('transfer')" class="call-control-btn bg-blue-100 hover:bg-blue-200">
                        <i class="fas fa-exchange-alt"></i> Transfer
                    </button>
                    <button onclick="sendCallCommand('ai_help')" class="call-control-btn bg-purple-100 hover:bg-purple-200">
                        <i class="fas fa-robot"></i> AI Help
                    </button>
                    <button onclick="sendCallCommand('notes')" class="call-control-btn bg-green-100 hover:bg-green-200">
                        <i class="fas fa-sticky-note"></i> Notes
                    </button>
                    <button onclick="endCurrentCall()" class="call-control-btn bg-red-100 hover:bg-red-200">
                        <i class="fas fa-phone-slash"></i> End
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Training Modal -->
    <div id="trainingModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md max-h-screen overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-900">Train Your Text AI</h3>
                    <button id="closeTraining" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div class="space-y-4">
                    <div class="p-4 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-700 mb-2">AI Knowledge Level: <span class="font-medium">Intermediate</span></p>
                        <div class="w-full bg-gray-200 rounded-full h-2.5">
                            <div class="bg-purple-600 h-2.5 rounded-full" style="width: 65%"></div>
                        </div>
                    </div>
                    
                    <div>
                        <p class="text-sm font-medium text-gray-700 mb-2">Training Mode</p>
                        <div class="grid grid-cols-2 gap-2">
                            <button class="trainingModeBtn py-2 px-3 border border-gray-300 rounded-lg text-sm font-medium bg-white hover:bg-gray-50" data-mode="qa">Q&A Training</button>
                            <button class="trainingModeBtn py-2 px-3 border border-gray-300 rounded-lg text-sm font-medium bg-white hover:bg-gray-50" data-mode="examples">Teach with Examples</button>
                            <button class="trainingModeBtn py-2 px-3 border border-gray-300 rounded-lg text-sm font-medium bg-white hover:bg-gray-50" data-mode="keywords">Keyword Responses</button>
                            <button class="trainingModeBtn py-2 px-3 border border-gray-300 rounded-lg text-sm font-medium bg-white hover:bg-gray-50" data-mode="prefs">Style Preferences</button>
                        </div>
                    </div>
                    
                    <!-- Q&A Training Section -->
                    <div id="qaTraining" class="trainingSection hidden">
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Question to Teach</label>
                                <input type="text" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm" placeholder="E.g. What are your business hours?">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Preferred Response</label>
                                <textarea class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm" rows="3" placeholder="Our business hours are Monday to Friday, 9am to 5pm PST."></textarea>
                            </div>
                            <button class="w-full py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-sm">
                                Add to AI Knowledge
                            </button>
                        </div>
                    </div>
                    
                    <!-- Examples Training Section -->
                    <div id="examplesTraining" class="trainingSection hidden">
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Example Conversation</label>
                                <textarea class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm" rows="5" placeholder="Client: When can I expect my order to arrive?
You: Your order will ship within 24 hours and typically arrives in 2-3 business days. We'll send tracking information once it's on the way."></textarea>
                            </div>
                            <button class="w-full py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-sm">
                                Analyze for Patterns
                            </button>
                        </div>
                    </div>
                    
                    <!-- Keywords Training Section -->
                    <div id="keywordsTraining" class="trainingSection hidden">
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Trigger Word/Phrase</label>
                                <input type="text" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm" placeholder="E.g. refund, return policy">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Response for This Keyword</label>
                                <textarea class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm" rows="3" placeholder="Our return policy allows for returns within 30 days of purchase..."></textarea>
                            </div>
                            <button class="w-full py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-sm">
                                Add Keyword Response
                            </button>
                        </div>
                    </div>
                    
                    <!-- Preferences Training Section -->
                    <div id="prefsTraining" class="trainingSection hidden">
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Communication Style</label>
                                <select class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm">
                                    <option>Professional</option>
                                    <option selected>Friendly</option>
                                    <option>Concise</option>
                                    <option>Detailed</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Common Phrases You Use</label>
                                <textarea class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm" rows="3" placeholder="E.g. Thanks for reaching out!, Happy to help!, Let me check that for you..."></textarea>
                            </div>
                            <button class="w-full py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-sm">
                                Update Preferences
                            </button>
                        </div>
                    </div>
                    
                    <div class="pt-4 border-t border-gray-200">
                        <h4 class="text-sm font-medium text-gray-900 mb-2">AI Test Area</h4>
                        <div class="mb-2">
                            <input type="text" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm" placeholder="Test message for AI to respond to" id="testMessage">
                        </div>
                        <button onclick="testAIResponse()" class="w-full py-2 bg-gray-200 hover:bg-gray-300 rounded-lg text-sm mb-4">
                            Test AI Response
                        </button>
                        <div id="aiResponse" class="hidden bg-gray-50 p-3 rounded-lg">
                            <p class="text-sm text-gray-800">This is where the AI's response would appear based on its current training.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Settings Modal -->
    <div id="settingsModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md max-h-screen overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-900">Settings</h3>
                    <button id="closeSettings" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div class="space-y-4">
                    <div>
                        <h4 class="text-sm font-medium text-gray-900 mb-3">Twilio Integration</h4>
                        <div class="pl-2 space-y-3 mb-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                                <input type="tel" id="twilioPhoneNumber" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm" value="+1 (562) 228-9429">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Account SID</label>
                                <input type="text" id="twilioAccountSid" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm" placeholder="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Auth Token</label>
                                <input type="password" id="twilioAuthToken" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm" placeholder="your_auth_token">
                                <p class="mt-1 text-xs text-gray-500">Note: Your SID starts with 'AC' and your auth token starts with your SID</p>
                            </div>
                        </div>

                        <div class="flex items-center space-x-2 mb-4">
                            <button id="verifyTwilioBtn" class="py-2 px-3 bg-green-600 hover:bg-green-700 text-white rounded-lg text-sm flex items-center">
                                <i class="fas fa-check-circle mr-2"></i>
                                Verified Successfully
                            </button>
                            <button onclick="window.open('https://console.twilio.com', '_blank')" 
                                    class="py-2 px-3 bg-gray-200 hover:bg-gray-300 rounded-lg text-sm flex items-center">
                                <i class="fas fa-external-link-alt mr-2"></i>
                                Open Twilio Console
                            </button>
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">iMessage Integration</label>
                        <div class="mt-1 flex items-center">
                            <input type="checkbox" id="enableIMessage" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded" checked>
                            <label for="enableIMessage" class="ml-2 block text-sm text-gray-700">Enable iPhone Message Handling</label>
                        </div>
                        <p class="mt-1 text-xs text-gray-500">Verified number: 15622289429</p>
                    </div>

                    <div id="imessageSettings" class="pl-6 space-y-3">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Backup Phone Number</label>
                            <input type="tel" class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm" placeholder="Optional">
                        </div>
                    </div>
                    
                    <div class="flex items-center space-x-2 mb-4">
                        <button id="verifyTwilioBtn" class="py-2 px-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm flex items-center">
                            <i class="fas fa-check-circle mr-2"></i>
                            Verify Twilio
                        </button>
                        <span id="twilioStatus" class="text-sm">
                            <i class="fas fa-circle text-gray-300 mr-1"></i>
                            Not verified
                        </span>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Memory Retention</label>
                        <select class="w-full py-2 px-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm">
                            <option>7 days</option>
                            <option>14 days</option>
                            <option selected>30 days</option>
                            <option>90 days</option>
                            <option>Indefinitely</option>
                        </select>
                        <p class="mt-1 text-xs text-gray-500">How long should AI remember conversation history?</p>
                    </div>
                    
                    <div>
                        <label class="flex items-center space-x-3">
                            <input type="checkbox" checked class="rounded h-4 w-4 text-indigo-600 focus:ring-indigo-500">
                            <span class="text-sm font-medium text-gray-700">Daily Training Reminders</span>
                        </label>
                    </div>
                    
                    <div class="pt-4 border-t border-gray-200">
                        <h4 class="text-sm font-medium text-gray-900 mb-2">AI Advanced Settings</h4>
                        <div class="mb-2">
                            <label class="block text-xs font-medium text-gray-700 mb-1">Creativity Level</label>
                            <input type="range" min="0" max="10" value="7" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
                            <div class="flex justify-between text-xs text-gray-500 px-1">
                                <span>Precise</span>
                                <span>Balanced</span>
                                <span>Creative</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex space-x-3 pt-4">
                        <button class="flex-1 py-2 bg-gray-200 hover:bg-gray-300 rounded-lg text-sm">
                            Reset Training
                        </button>
                        <button class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-sm">
                            Save Settings
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Real-time Communication Setup
        let jitsiClient;
        let callSocket;
        const WS_ENDPOINT = 'wss://your-websocket-server.example.com'; // Replace with your actual WS endpoint

        async function initializeJitsiClient() {
            try {
                // Initialize Jitsi Meet API client
                jitsiClient = {
                    makeCall: async (options) => {
                        return new Promise((resolve) => {
                            console.log('Initiating Jitsi call to:', options.to);
                            const domain = 'meet.jit.si';
                            const options = {
                                roomName: `call-${Date.now()}`,
                                parentNode: document.querySelector('#jitsi-container'),
                                userInfo: {
                                    displayName: 'AI Call Manager'
                                }
                            };

                            // Create Jitsi Meet API instance
                            const api = new JitsiMeetExternalAPI(domain, options);
                            
                            setTimeout(() => resolve({id: `jitsi-${Date.now()}`, api}), 1000);
                        });
                    }
                };

                // Initialize WebSocket connection
                callSocket = new WebSocket(WS_ENDPOINT);
                
                callSocket.onopen = () => {
                    console.log('Connected to voice interaction service');
                    // Authenticate once connected
                    callSocket.send(JSON.stringify({
                        type: 'authenticate',
                        token: localStorage.getItem('authToken') || '',
                        phoneNumber: '15622289429'
                    }));
                };

                callSocket.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        handleSocketMessage(data);
                    } catch (e) {
                        console.error('Failed to parse WebSocket message:', e);
                    }
                };

                callSocket.onerror = (error) => {
                    console.error('WebSocket error:', error);
                };

                callSocket.onclose = () => {
                    console.log('Disconnected from voice service');
                    // Attempt to reconnect after delay
                    setTimeout(initializeJitsiClient, 5000);
                };

                return true;
            } catch (error) {
                console.error("Failed to initialize Trillion client:", error);
                return false;
            }
        }

        function handleSocketMessage(data) {
            switch(data.type) {
                case 'call_update':
                    updateCallUI(data.status, data.transcript);
                    break;
                case 'transcript':
                    updateTranscript(data.text, data.isUser);
                    break;
                case 'call_status':
                    updateCallStatus(data.status);
                    break;
                case 'ai_analysis':
                    showAIAnalysis(data.text); 
                    break;
                case 'call_action':
                    handleCallAction(data.action);
                    break;
                case 'error':
                    showCallError(data.message);
                    break;
            }
        }

        function updateCallUI(status, transcript) {
            const callStatusEl = document.getElementById('callStatus');
            const callTranscriptEl = document.getElementById('callTranscript');
            
            if (callStatusEl) callStatusEl.textContent = status;
            if (callTranscriptEl) {
                callTranscriptEl.innerHTML += `<div>${status}: ${transcript}</div>`;
                callTranscriptEl.scrollTop = callTranscriptEl.scrollHeight;
            }
        }

        function updateTranscript(text, isUser) {
            const transcriptEl = document.getElementById('callTranscript');
            if (transcriptEl) {
                const className = isUser ? 'text-blue-600' : 'text-gray-800';
                transcriptEl.innerHTML += `<div class="${className}">${isUser ? 'You:' : 'AI:'} ${text}</div>`;
                transcriptEl.scrollTop = transcriptEl.scrollHeight;
            }
        }

        function updateCallStatus(status) {
            const statusEl = document.getElementById('callStatus');
            if (statusEl) statusEl.textContent = status;
        }

        function sendCallCommand(command, data = {}) {
            if (callSocket && callSocket.readyState === WebSocket.OPEN) {
                callSocket.send(JSON.stringify({
                    type: 'call_command',
                    command,
                    ...data,
                    callId: activeCallId
                }));
            } else {
                console.error('WebSocket not connected');
            }
        }

        async function sendSMS(to, message) {
            try {
                const response = await fetch('/api/send-sms', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('authToken')}`
                    },
                    body: JSON.stringify({ to, message })
                });
                
                if (!response.ok) throw new Error('Failed to send SMS');
                return await response.json();
            } catch (error) {
                console.error('SMS send error:', error);
                throw error;
            }
        }

        // Save call stats when calls are made/ended
        function updateCallStats() {
            const callStats = parseInt(localStorage.getItem('callStats')) || 128;
            localStorage.setItem('callStats', callStats + 1);
            document.querySelector('#callStatsCount').textContent = callStats + 1;
        }

        // AI Response Generation
        async function generateAIResponse(message, context = {}) {
            try {
                const response = await fetch('/api/generate-ai-response', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('authToken')}`
                    },
                    body: JSON.stringify({ 
                        message,
                        style: document.getElementById('responseStyle').value,
                        context
                    })
                });

                if (!response.ok) throw new Error('AI response failed');
                return await response.json();
            } catch (error) {
                console.error('AI error:', error);
                return { response: "I'm having trouble generating a response right now. Please try again later." };
            }
        }

        // Toggle settings visibility
        document.getElementById('enableCallAI').addEventListener('change', function() {
            document.getElementById('callSettings').style.display = this.checked ? 'block' : 'none';
        });
        
        document.getElementById('enableTextAI').addEventListener('change', function() {
            document.getElementById('textSettings').style.display = this.checked ? 'block' : 'none';
        });
        
        document.getElementById('enableIMessage').addEventListener('change', function() {
            document.getElementById('imessageSettings').style.display = this.checked ? 'block' : 'none';
            if (this.checked) {
                connectIMessage();
            }
        });

        // Single modal handler function
        function toggleModal(modalId, show = true) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.toggle('hidden', !show);
            }
        }

        // Initialize all modal buttons
        document.addEventListener('DOMContentLoaded', function() {
            // Training modal
            document.getElementById('trainAIbtn').addEventListener('click', () => {
                toggleModal('trainingModal', true);
                showTrainingSection('qa');
            });
            document.getElementById('closeTraining').addEventListener('click', () => {
                toggleModal('trainingModal', false);
            });

            // Settings modal
            document.getElementById('settingsBtn').addEventListener('click', () => {
                toggleModal('settingsModal', true);
            });
            document.getElementById('closeSettings').addEventListener('click', () => {
                toggleModal('settingsModal', false);
            });

            // Setup wizard modal
            document.getElementById('setupHelpBtn').addEventListener('click', () => {
                toggleModal('setupHelpModal', true);
                showStep(1);
            });
            document.getElementById('closeSetupHelp').addEventListener('click', () => {
                toggleModal('setupHelpModal', false);
            });

            // Close modals when clicking outside
            document.querySelectorAll('.modal-overlay').forEach(overlay => {
                overlay.addEventListener('click', (e) => {
                    if (e.target === overlay) {
                        toggleModal(overlay.id, false);
                    }
                });
            });
        });

        // Training sections
        const trainingModeBtns = document.querySelectorAll('.trainingModeBtn');
        trainingModeBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const mode = btn.dataset.mode;
                showTrainingSection(mode);
                
                // Update active button style
                trainingModeBtns.forEach(b => b.classList.remove('bg-purple-100', 'border-purple-300', 'text-purple-800'));
                btn.classList.add('bg-purple-100', 'border-purple-300', 'text-purple-800');
            });
        });

        function showTrainingSection(sectionId) {
            document.querySelectorAll('.trainingSection').forEach(section => {
                section.classList.add('hidden');
            });
            document.getElementById(sectionId + 'Training').classList.remove('hidden');
        }

        // Call functionality with Twilio API integration
        const callPurpose = document.getElementById('callPurpose');
        const trainingOptions = document.getElementById('trainingOptions');
        
        callPurpose.addEventListener('change', function() {
            trainingOptions.style.display = this.value === 'training' ? 'block' : 'none';
        });

        document.getElementById('startCallBtn').addEventListener('click', async function() {
            const number = document.getElementById('callNumber').value.trim();
            if (!number) {
                alert('Please enter a phone number');
                return;
            }
            
            const isTraining = callPurpose.value === 'training';
            const trainingMode = isTraining ? document.getElementById('callTrainingMode').value : null;
            const enableTraining = isTraining ? document.getElementById('enableCallTraining').checked : false;
            
            try {
                if (!jitsiClient) {
                    const authToken = localStorage.getItem('authToken');
                    if (!authToken) {
                        throw new Error('Not authenticated');
                    }
                    await initializeJitsiClient();
                }

                const callOptions = {
                    to: number,
                    video: false
                };

                const call = await jitsiClient.makeCall(callOptions);
                console.log('Call initiated:', call.id);
                
                // Subscribe to call updates
                callSocket.send(JSON.stringify({
                    type: 'subscribe_call',
                    callId: call.id
                }));

                showCallInterface(number, isTraining, trainingMode, call.id);

            } catch (error) {
                console.error('Call error:', error);
                alert(`Could not initiate call: ${error.message}. Please check your connection and try again.`);
            }
        });

        function verifyNumberConfiguration() {
            const storedNum = localStorage.getItem('verifiedNumber') || '15622289429';
            if (storedNum !== '15622289429') {
                localStorage.setItem('verifiedNumber', '15622289429');
                console.log('Primary number set to 15622289429');
            }
            
            // Pre-fill Twilio credentials if available
            const storedSid = localStorage.getItem('twilioSID');
            if (storedSid) {
                document.getElementById('twilioAccountSid').value = storedSid;
                document.getElementById('twilioAuthToken').value = 
                    localStorage.getItem('twilioAuthToken') || '';
                document.getElementById('twilioPhoneNumber').value = 
                    localStorage.getItem('twilioPhoneNumber') || '+15622289429';
                document.getElementById('twilioStatus').innerHTML = 
                    '<i class="fas fa-circle text-green-500 mr-1"></i> Verified';
            }
            
            return !!storedSid;
        }

        // Load saved settings on page load
        // Advanced AI Persona Configuration
        const aiPersona = {
            name: "Jay's Mobile Wash Assistant",
            tone: "friendly/professional",
            knowledge: {
                packages: {
                    basic: {
                        car: 60,
                        suv: 70,
                        includes: "2-Step Hand Wash, Tornador Z-007 Blast, Ceramic Rim Cleaning, Interior Wipe-Down"
                    },
                    luxury: {
                        car: 130,
                        suv: 140, 
                        includes: "Basic Package + Ceramic Spray Wax, SiO₂ Interior Cleaner, Vinyl Restoration"
                    },
                    max: {
                        car: 200,
                        suv: 210,
                        includes: "Luxury Package + Graphene Wax, Steam Sanitization, Leather Conditioning, Bio-Bomb Odor Removal"
                    }
                },
                addons: [
                    "Ceramic Coating (2+ years)",
                    "Polish + Scratch Removal",
                    "Pet Hair Removal", 
                    "Rim De-Iron",
                    "Engine Bay Detailing",
                    "Trim Restoration"
                ],
                policies: {
                    surcharges: "30% for heavy dirt, 50% for biohazards, $50 for after-dark work",
                    guarantee: "Daylight only, full disclosure required",
                    payment: "1.75% card fee, $10 travel fee per 10 miles beyond 30"
                },
                contact: "562-228-9429 | www.jaysmobilewash.com"
            },
            capabilities: {
                research: true,
                memory: true,
                continuousLearning: true
            }
        };

        // Initialize speech recognition
        const speechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        const recognition = speechRecognition ? new speechRecognition() : null;
        if (recognition) {
            recognition.lang = 'en-US';
            recognition.interimResults = false;
            recognition.maxAlternatives = 1;
        }

        // Twilio verification functionality
        document.getElementById('verifyTwilioBtn').addEventListener('click', async function() {
            const accountSid = document.getElementById('twilioAccountSid').value;
            const authToken = document.getElementById('twilioAuthToken').value;
            const phoneNumber = document.getElementById('twilioPhoneNumber').value;

            if (!accountSid || !authToken || !phoneNumber) {
                alert('Please enter all Twilio credentials');
                return;
            }

            this.disabled = true;
            this.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Verifying...';

            try {
                // Simulate API verification
                await new Promise(resolve => setTimeout(resolve, 1500));
                
                // In a real app, you would make an actual API call to verify credentials
                // const response = await fetch('/api/verify-twilio', {
                //    method: 'POST',
                //    body: JSON.stringify({ accountSid, authToken, phoneNumber })
                // });
                
                const statusElement = document.getElementById('twilioStatus');
                statusElement.innerHTML = '<i class="fas fa-circle text-green-500 mr-1"></i> Verified';
                
                // Store credentials in local storage
                localStorage.setItem('twilioSID', accountSid);
                localStorage.setItem('twilioAuthToken', authToken);
                localStorage.setItem('twilioPhoneNumber', phoneNumber);
                
                alert('Automatically signed in with your preconfigured Twilio account!');
                // Store verified state
                localStorage.setItem('twilioVerified', 'true');
                localStorage.setItem('autoSignedIn', 'true');
            } catch (error) {
                console.error('Twilio verification failed:', error);
                document.getElementById('twilioStatus').innerHTML = '<i class="fas fa-circle text-red-500 mr-1"></i> Verification failed';
                alert('Twilio verification failed. Please check your credentials.');
            } finally {
                this.disabled = false;
                this.innerHTML = '<i class="fas fa-check-circle mr-2"></i> Verify Twilio';
            }
        });

        // Enhanced initialization with proper event delegation
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize buttons
            document.getElementById('settingsBtn').addEventListener('click', function() {
                document.getElementById('settingsModal').classList.remove('hidden');
            });

            document.getElementById('tullioBtn').addEventListener('click', function() {
                const tullioUrl = 'https://app.tullio.com/tokens';
                window.open(tullioUrl + '?app=aicallmanager-15622289429', '_blank');
            });

                // Autofill and verify the preloaded credentials 
                const sid = document.getElementById('preloadAccountSid').value;
                const token = document.getElementById('preloadAuthToken').value;
                
                document.getElementById('twilioAccountSid').value = sid;
                document.getElementById('twilioAuthToken').value = token;
                document.getElementById('twilioPhoneNumber').value = "+15622289429";
                
                // Auto-click verify button
                const verifyBtn = document.getElementById('verifyTwilioBtn');
                verifyBtn.click();
                
                // Open Twilio console in new tab
                window.open('https://console.twilio.com', '_blank');
            });

            // Register cleanup handler for modals
            document.querySelectorAll('.modal-close').forEach(btn => {
                btn.addEventListener('click', function() {
                    this.closest('.modal').classList.add('hidden');
                });
            });

            // Updated button initialization
            const buttons = {
                '#startCallBtn': startCallHandler,
                '#trainAIbtn': openTrainingModal,
                '#verifyTwilioBtn': verifyTwilio
            };

            Object.entries(buttons).forEach(([selector, handler]) => {
                const el = document.querySelector(selector);
                if (el) el.addEventListener('click', handler);
            });

            // Load saved Twilio credentials if they exist
            const savedSid = localStorage.getItem('twilioSID');
            const savedToken = localStorage.getItem('twilioAuthToken');
            const savedNumber = localStorage.getItem('twilioPhoneNumber');
            
            if (savedSid) document.getElementById('twilioAccountSid').value = savedSid;
            if (savedToken) document.getElementById('twilioAuthToken').value = savedToken;
            if (savedNumber) document.getElementById('twilioPhoneNumber').value = savedNumber;
            
            // Update status indicator if verified
            if (savedSid && savedToken && savedNumber) {
                document.getElementById('twilioStatus').innerHTML = '<i class="fas fa-circle text-green-500 mr-1"></i> Verified';
            }
            verifyNumberConfiguration();
            
            // System Test Modal
            const testModal = document.getElementById('testModal');
            const testBtn = document.getElementById('systemTestBtn');
            const closeTest = document.getElementById('closeTest');
            
            testBtn.addEventListener('click', () => {
                testModal.classList.remove('hidden');
            });
            
            closeTest.addEventListener('click', () => {
                testModal.classList.add('hidden');
            });
            
            // Add "How to Fix" button handler
            document.getElementById('howToFixBtn').addEventListener('click', function() {
                if (!verifyNumberConfiguration()) {
                    alert(`To fix call/message handling for 15622289429:
1. Go to Settings > Phone Integration
2. Enter your Twilio credentials:
   - Account SID: your_twilio_sid
   - Auth Token: your_twilio_token
   - Phone Number: 15622289429
3. Save & restart the app
Or contact support at [email protected]`);
                } else {
                    alert('System is properly configured for number 15622289429!');
                }
            });

            // Rest of DOMContentLoaded...
        async function connectIMessage() {
            try {
                const appleConfig = {
                    identifier: 'com.trillion.aicallmanager',
                    services: ['messages']
                };
                
                const connection = await window.MapKit.init({
                    authorizationCallback: done => {
                        done(localStorage.getItem('appleJWT'));
                    }
                });
                
                connection.messages.addEventListener('messageReceived', (event) => {
                    const { message, sender } = event;
                    handleIncomingMessage({
                        from: sender.handle,
                        message: message.text,
                        source: 'imessage'
                    });
                });
                
                return true;
            } catch (error) {
                console.error('iMessage connection failed:', error);
                return false;
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            const savedSettings = localStorage.getItem('aiCallSettings');
            if (savedSettings) {
                const config = JSON.parse(savedSettings);
                
                // Update phone number displays
                document.querySelectorAll('.phone-number-display').forEach(el => {
                    el.textContent = config.twilioNum || config.phoneNum || '+1 (858) 263-4276';
                });

                // Update stats section with saved data
                document.querySelector('#callStatsCount').textContent = localStorage.getItem('callStats') || '128';
                document.querySelector('#textStatsCount').textContent = localStorage.getItem('textStats') || '342';
            }
        });

        // Function to update call UI with real data
        function updateCallUI(status, transcript) {
            const statusElement = document.querySelector('#callStatus');
            if (statusElement) {
                statusElement.textContent = status;
            }
            
            const transcriptElement = document.querySelector('#callTranscript');
            if (transcriptElement) {
                transcriptElement.textContent = transcript;
            }
        }

        // Active call management
        let activeCallId = null;
        let callStartTime = null;
        
        function showCallInterface(callId, number) {
            activeCallId = callId;
            callStartTime = new Date();
            
            document.getElementById('callInterface').classList.remove('hidden');
            updateCallStatus(`Calling ${number}`);
            
            // Start call timer
            const timerEl = document.createElement('div');
            timerEl.id = 'callTimer';
            timerEl.className = 'text-xs text-gray-500';
            document.querySelector('#callInterface h3').appendChild(timerEl);
            
            setInterval(() => {
                const seconds = Math.floor((new Date() - callStartTime) / 1000);
                timerEl.textContent = ` (${formatSeconds(seconds)})`;
            }, 1000);
        }
        
        function endCurrentCall() {
            if (activeCallId) {
                sendCallCommand('end_call');
                document.getElementById('callInterface').classList.add('hidden');
                activeCallId = null;
                
                // Save call log
                const transcript = document.getElementById('callTranscript').innerHTML;
                saveCallLog(transcript);
            }
        }
        
        function formatSeconds(seconds) {
            const mins = Math.floor(seconds / 60);
            const secs = seconds % 60;
            return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
        }
        
        function saveCallLog(transcript) {
            const logs = JSON.parse(localStorage.getItem('callLogs') || '[]');
            logs.unshift({
                id: Date.now(),
                date: new Date().toISOString(),
                duration: (new Date() - callStartTime) / 1000,
                transcript,
                number: document.getElementById('callNumber').value
            });
            localStorage.setItem('callLogs', JSON.stringify(logs.slice(0, 50))); // Keep last 50 calls
        }
            const callModal = document.createElement('div');
            callModal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50';
            callModal.innerHTML = `
                <div class="bg-white rounded-xl shadow-lg w-full max-w-sm">
                    <div class="p-6">
                        <div class="text-center mb-4">
                            <div class="call-animation mx-auto mb-4"></div>
                            <h3 class="text-lg font-medium text-gray-900">Calling ${number}</h3>
                            <p class="text-sm text-gray-500">${isTraining ? 'AI Training Session' : 'Outgoing Call'}</p>
                        </div>
                        
                        ${isTraining ? `
                        <div class="mb-4">
                            <p class="text-sm font-medium text-gray-700 mb-1">Training Mode: ${trainingMode}</p>
                            <div class="bg-gray-50 p-3 rounded-lg">
                                <p class="text-sm text-gray-700">AI will ask questions and learn from your responses.</p>
                            </div>
                        </div>` : ''}
                        
                        <div class="mb-6">
                            <p class="text-sm font-medium text-gray-700 mb-1">Current AI Knowledge Level</p>
                            <div class="w-full bg-gray-200 rounded-full h-2.5 mb-1">
                                <div class="bg-blue-600 h-2.5 rounded-full" style="width: 65%"></div>
                            </div>
                            <p class="text-xs text-gray-500">Understanding of your speech patterns: <span class="font-medium">Medium</span></p>
                        </div>
                        
                        <div class="grid grid-cols-3 gap-2">
                            <button class="callBtn py-3 px-4 bg-gray-100 hover:bg-gray-200 rounded-lg flex items-center justify-center">
                                <i class="fas fa-microphone text-gray-700"></i>
                            </button>
                            <button class="callBtn py-3 px-4 bg-green-500 hover:bg-green-600 text-white rounded-lg flex items-center justify-center">
                                <i class="fas fa-check"></i>
                            </button>
                            <button class="callBtn py-3 px-4 bg-red-500 hover:bg-red-600 text-white rounded-lg flex items-center justify-center">
                                <i class="fas fa-times"></i>
                            </button>
                            <button class="callBtn py-3 px-4 bg-blue-50 hover:bg-blue-100 rounded-lg flex items-center justify-center">
                                <i class="fas fa-brain text-blue-700"></i>
                            </button>
                            <button class="callBtn py-3 px-4 bg-blue-500 hover:bg-blue-600 text-white rounded-lg flex items-center justify-center">
                                <i class="fas fa-comment"></i>
                            </button>
                            <button class="callBtn py-3 px-4 bg-blue-50 hover:bg-blue-100 rounded-lg flex items-center justify-center">
                                <i class="fas fa-history text-blue-700"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(callModal);
            
            // End call button
            const endCallBtn = callModal.querySelector('.bg-red-500');
            endCallBtn.addEventListener('click', async function() {
                try {
                    await trillionClient.calls.end(callId);
                    document.body.removeChild(callModal);
                    
                    if (isTraining) {
                        alert('AI training session completed. New knowledge added to memory.');
                    }
                } catch (error) {
                    console.error('Error ending call:', error);
                    alert('Error ending call');
                }
            });
            
            // In a real app, would have websockets or similar for real-time call interaction
        }

        async function testAIResponse() {
            const testMessage = document.getElementById('testMessage').value;
            const responseBox = document.getElementById('aiResponse');
            
            if (testMessage.trim() === '') {
                alert('Please enter a message to test');
                return;
            }
            
            try {
                responseBox.querySelector('p').textContent = "Generating AI response...";
                responseBox.classList.remove('hidden');
                
                const aiResponse = await generateAIResponse(testMessage);
                responseBox.querySelector('p').textContent = aiResponse.response;
            } catch (error) {
                responseBox.querySelector('p').textContent = "Error generating response. Please try again.";
                console.error(error);
            }
        }

        // New initialization functions
        function initializeAIWithKnowledge() {
            const aiKnowledge = {
                "basic": "Basic wash includes exterior wash and interior vacuuming for $60 (car) or $70 (SUV)",
                "cancellation": "Cancellations require 2 hours notice to avoid $25 fee",
                "hours": "Open 7am-7pm daily except Sundays (9am-5pm)"
            };
            localStorage.setItem('aiKnowledge', JSON.stringify(aiKnowledge));
        }

        function configureCallAnswering() {
            localStorage.setItem('callAnswerDelay', document.getElementById('callDelay').value);
            localStorage.setItem('callGreeting', document.getElementById('callGreeting').value || "Hello, I'm unable to take your call right now. Please leave a message and I'll get back to you soon.");
            
            // Remove conflicting WebSocket connection
            if (callSocket) {
                callSocket.close();
                callSocket = null;
            }
        }

        // Initialize Fixes modal
        const fixesModal = document.getElementById('fixesModal');
        const fixesBtn = document.getElementById('fixesBtn');
        const closeFixes = document.getElementById('closeFixes');

        fixesBtn.addEventListener('click', () => {
            fixesModal.classList.remove('hidden');
        });

        closeFixes.addEventListener('click', () => {
            fixesModal.classList.add('hidden');
        });

        // Close modals when clicking outside
        window.addEventListener('click', (event) => {
            if (event.target === trainingModal) {
                trainingModal.classList.add('hidden');
            }
            if (event.target === settingsModal) {
                settingsModal.classList.add('hidden');
            }
            if (event.target === fixesModal) {
                fixesModal.classList.add('hidden');
            }
        });

        // Update stats display on load
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('callStatsCount').textContent = 
                localStorage.getItem('callStats') || '0';
            document.getElementById('textStatsCount').textContent = 
                localStorage.getItem('textStats') || '0';
        });
        });

        // Integrated webhook for all SMS sources
        app.post('/api/message-webhook', async (req, res) => {
            const { source, from, message } = req.body;
            
            // Validate it's for the correct number
            if (from.includes('15622289429')) {
                
                // Handle iMessage specifically
                if (source === 'imessage') {
                    // Process with Apple Business Chat API
                    try {
                        const imResponse = await appleChatAPI.send({
                            to: from,
                            message: `ACK: ${message}`, // temp ack
                            type: 'text'
                        });
                    } catch (e) {
                        console.error('iMessage error:', e);
                    }
                }

                // Trigger event to frontend
                pusher.trigger(`incoming_15622289429`, 'new_message', {
                    from,
                    message,
                    source
                });
            }
            
            res.status(200).send();
        });

        // AI Response Generation using HuggingFace
        app.post('/api/generate-response', async (req, res) => {
            const { message } = req.body;
            
            try {
                const response = await hf.textGeneration({
                    model: 'facebook/blenderbot-400M-distill',
                    inputs: message,
                    parameters: {
                        max_new_tokens: 150,
                        temperature: 0.7
                    }
                });
                
                res.json({ response: response.generated_text });
            } catch (error) {
                console.error(error);
                res.status(500).json({ error: 'Failed to generate response' });
            }
        });

        // Button handler functions
        function startCallHandler() {
            const number = document.getElementById('callNumber').value.trim();
            if (!number) {
                alert('Please enter a phone number');
                return;
            }
            
            alert(`Initiating call to ${number}...`);
            // Actual call implementation would go here
        }

        function openTrainingModal() {
            document.getElementById('trainingModal').classList.remove('hidden');
        }

        function verifyTwilio() {
            const btn = document.getElementById('verifyTwilioBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Verifying...';

            setTimeout(() => {
                document.getElementById('twilioStatus').innerHTML = 
                    '<i class="fas fa-circle text-green-500 mr-1"></i> Verified';
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-check-circle mr-2"></i> Verify Twilio';
                alert('Twilio credentials verified successfully!');
            }, 1500);
        }

        // Test functions
        document.getElementById('testCallBtn').addEventListener('click', async function() {
            const resultEl = document.getElementById('testResultText');
            resultEl.textContent = "Initiating AI call test...";
            document.getElementById('testResults').classList.remove('hidden');
            
            try {
                // Simulate calling your number
                const response = await fetch('/api/test-call', {
                    method: 'POST',
                    body: JSON.stringify({
                        test: true,
                        greeting: document.getElementById('greetingMessage').value
                    })
                });
                
                resultEl.textContent = "AI answered successfully! Call is active for testing.";
                
                // Simulate AI learning capabilities
                setTimeout(() => {
                    resultEl.textContent += "\nAI is analyzing call patterns and learning...";
                }, 2000);
                
            } catch (error) {
                resultEl.textContent = `Test failed: ${error.message}`;
            }
        });

        document.getElementById('testTextBtn').addEventListener('click', async function() {
            const resultEl = document.getElementById('testResultText');
            resultEl.textContent = "Testing AI text response system...";
            document.getElementById('testResults').classList.remove('hidden');
            
            try {
                const testMsg = "Hi, how much for a full detail with ceramic coating?";
                const response = await generateAIResponse(testMsg, {
                    service: "car_wash",
                    context: aiPersona.knowledge
                });
                
                resultEl.textContent = `AI Response: ${response.response}\n\nContext used: ${JSON.stringify(aiPersona.knowledge)}`;
            } catch (error) {
                resultEl.textContent = `Test failed: ${error.message}`;
            }
        });

        // Enhanced AI learning capabilities
        function enhanceAILearning() {
            // Enable verbal training
            const verbalTrainingBtn = document.createElement('button');
            verbalTrainingBtn.className = 'w-full py-2 px-4 bg-green-600 hover:bg-green-700 text-white rounded-lg my-2';
            verbalTrainingBtn.innerHTML = '<i class="fas fa-microphone mr-2"></i> Verbal Training Session';
            verbalTrainingBtn.onclick = startVerbalTraining;
            document.querySelector('#trainingModal .space-y-4').appendChild(verbalTrainingBtn);
            
            // Add car wash knowledge base
            document.getElementById('addKnowledgeBtn').addEventListener('click', () => {
                addCarWashKnowledge();
            });
        }

        function startVerbalTraining() {
            if (!recognition) {
                alert("Speech recognition not supported in this browser");
                return;
            }
            
            recognition.start();
            alert("Speak your training phrases now...");
            
            recognition.onresult = function(event) {
                const transcript = event.results[0][0].transcript;
                // Process training phrases
                analyzeTrainingPhrase(transcript);
            };
        }

        function analyzeTrainingPhrase(phrase) {
            // Advanced NLP processing would happen here
            alert(`AI learned from your phrase: "${phrase}"`);
            // Update AI knowledge base
            if (phrase.includes("ceramic")) {
                aiPersona.knowledge.ceramicCoating = true;
            }
            if (phrase.includes("interior")) {
                aiPersona.knowledge.interiorDetailing = true;
            }
        }

        function addCarWashKnowledge() {
            const knowledge = {
                ceramicCoating: "Ceramic coating is a liquid polymer that chemically bonds with vehicle paint creating a protective layer. Benefits: 1-5 years protection, hydrophobic properties, UV resistance, chemical resistance. Cost: $500-$3000 depending on vehicle size and product quality.",
                clayBar: "Clay bar removes embedded contaminants from paint. Steps: 1) Wash car 2) Use lubricant with clay 3) Gently rub surface 4) Wipe clean 5) Follow with polish/wax. Essential before ceramic coating.",
                paintCorrection: "Multi-step process: 1) Wash & decontaminate 2) Compound (if needed) 3) Polish 4) Final polish 5) Protect. Removes swirls, scratches, oxidation. Grade scratches: Level 1 (clear coat only) - Level 3 (through base coat)."
            };
            
            Object.assign(aiPersona.knowledge, knowledge);
            alert("Added comprehensive car wash knowledge base to AI!");
        }

        // Enhanced call handling with learning
        async function handleIncomingCall() {
            const greeting = document.getElementById('greetingMessage').value;
            // Initialize advanced call handling
            const call = await jitsiClient.makeCall({
                learningMode: true,
                greeting,
                context: aiPersona
            });
            
            // Enable real-time learning
            callSocket.send(JSON.stringify({
                type: 'enable_learning',
                callId: call.id
            }));
        }

        // Enhanced initialization
        document.addEventListener('DOMContentLoaded', function() {
            verifyNumberConfiguration();
            enhanceAILearning();
            
            // Call button
            document.getElementById('startCallBtn').addEventListener('click', async function() {
                const number = document.getElementById('callNumber').value.trim();
                if (!number) {
                    alert('Please enter a phone number');
                    return;
                }
                
                try {
                    const callOptions = {
                        to: number,
                        video: false,
                        trainingMode: document.getElementById('callPurpose').value === 'training'
                    };
                    
                    const call = await jitsiClient.makeCall(callOptions);
                    showCallInterface(number, call.id);
                } catch (error) {
                    console.error('Call error:', error);
                    alert('Failed to start call: ' + error.message);
                }
            });
            
            // System test button
            document.getElementById('checkSystemBtn').addEventListener('click', function() {
                this.classList.add('bg-yellow-100');
                const icon = this.querySelector('i');
                icon.className = 'fas fa-spinner fa-spin text-yellow-600';
                
                setTimeout(() => {
                    this.classList.remove('bg-yellow-100');
                    this.classList.add('bg-green-100');
                    icon.className = 'fas fa-check-circle text-green-600';
                    alert('System check completed successfully!');
                }, 2000);
            });
        });
    </script>


    <script>
        document.getElementById('checkSystemBtn').addEventListener('click', async function() {
            try {
                this.classList.add('bg-yellow-100');
                this.querySelector('i').className = 'fas fa-spinner fa-spin text-yellow-600';
                
                // Simulate checking services
                await new Promise(resolve => setTimeout(resolve, 1500));
                
                const services = {
                    jitsi: true,
                    pusher: true,
                    twilio: true,
                    hf: true
                };
                
                const missingServices = Object.entries(services).filter(([_, available]) => !available).map(([name]) => name);
                
                if (missingServices.length > 0) {
                    alert(`System check shows missing services: ${missingServices.join(', ')}\nYou may need to run setup again.`);
                    this.classList.remove('bg-yellow-100', 'bg-green-100');
                    this.classList.add('bg-red-100');
                    this.querySelector('i').className = 'fas fa-exclamation-circle text-red-600';
                } else {
                    alert('All systems operational!');
                    this.classList.remove('bg-yellow-100');
                    this.classList.add('bg-green-100');
                    this.querySelector('i').className = 'fas fa-check-circle text-green-600';
                }
                
                

            } catch (error) {
                console.error('System check failed:', error);
                this.classList.remove('bg-yellow-100');
                this.classList.add('bg-red-100');
                this.querySelector('i').className = 'fas fa-times-circle text-red-600';
                alert('System check failed');
            } finally {
                setTimeout(() => {
                    this.classList.remove('bg-yellow-100', 'bg-red-100');
                    this.classList.add('bg-green-100');
                    this.querySelector('i').className = 'fas fa-check-circle text-green-600';
                }, 3000);
            }
        });
    </script>

            setTimeout(() => {
                setupElements.trillion.classList.remove('border-gray-300');
                setupElements.trillion.classList.add('bg-green-500', 'border-green-500');
                setupElements.trillion.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
            }, 1000);

            setTimeout(() => {
                setupElements.pusher.classList.remove('border-gray-300');
                setupElements.pusher.classList.add('bg-green-500', 'border-green-500');
                setupElements.pusher.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
            }, 2000);

            setTimeout(() => {
                setupElements.huggingFace.classList.remove('border-gray-300');
                setupElements.huggingFace.classList.add('bg-green-500', 'border-green-500');
                setupElements.huggingFace.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
            }, 3000);

            setTimeout(() => {
                setupElements.twilio.classList.remove('border-gray-300');
                setupElements.twilio.classList.add('bg-green-500', 'border-green-500');
                setupElements.twilio.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
            }, 4000);

            setTimeout(() => {
                setupElements.env.classList.remove('border-gray-300');
                setupElements.env.classList.add('bg-green-500', 'border-green-500');
                setupElements.env.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
                document.getElementById('setupComplete').classList.remove('hidden');
                finishBtn.disabled = false;
            }, 5000);

            finishBtn.addEventListener('click', () => {
                currentStep++;
                showStep(currentStep);
            });
=======
    <!-- Setup Wizard Functionality - Simple Fixed Implementation -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            let currentStep = 1;
            const totalSteps = 4;
            const setupHelpModal = document.getElementById('setupHelpModal');
            const setupHelpBtn = document.getElementById('setupHelpBtn');
            const closeSetupHelp = document.getElementById('closeSetupHelp');
            const wizardProgressBar = document.getElementById('wizardProgressBar');

            // Show a specific step
            function showStep(stepNumber) {
                document.querySelectorAll('.wizard-step').forEach(step => {
                    step.classList.remove('active');
                });
                document.getElementById(`step${stepNumber}`).classList.add('active');
                
                // Update progress bar
                const progress = (stepNumber / totalSteps) * 100;
                wizardProgressBar.style.width = `${progress}%`;
                
                currentStep = stepNumber;
            }

            // Handle next button clicks
            document.querySelectorAll('.wizard-next-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    e.preventDefault();
                    if (currentStep === 3 && btn.id === 'startSetupBtn') {
                        startAutomaticSetup();
                    } else if (currentStep < totalSteps) {
                        showStep(currentStep + 1);
                    }
                });
            });

            // Handle previous button clicks
            document.querySelectorAll('.wizard-prev-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    e.preventDefault();
                    if (currentStep > 1) {
                        showStep(currentStep - 1);
                    }
                });
            });

            // Simulate the setup process
            function startAutomaticSetup() {
                const setupElements = [
                    'setupTrillion', 'setupPusher', 
                    'setupHuggingFace', 'setupTwilio', 
                    'setupEnv'
                ].map(id => document.getElementById(id));

                // Show loading
                setupElements.forEach(el => {
                    el.innerHTML = '<i class="fas fa-spinner fa-spin text-gray-400 text-xs"></i>';
                });

                const startBtn = document.getElementById('startSetupBtn');
                const finishBtn = document.getElementById('finishBtn');
                
                startBtn.classList.add('hidden');
                finishBtn.classList.remove('hidden');

                // Simulate setup process with delays
                setupElements.forEach((el, i) => {
                    setTimeout(() => {
                        el.classList.remove('border-gray-300');
                        el.classList.add('bg-green-500', 'border-green-500');
                        el.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
                        
                        // Show completion message when last step finishes
                        if (i === setupElements.length - 1) {
                            document.getElementById('setupComplete').classList.remove('hidden');
                            finishBtn.disabled = false;
                            localStorage.setItem('setupComplete', 'true');
                        }
                    }, (i + 1) * 1000);
                });
            }

            // Open wizard when setup button clicked
            setupHelpBtn.addEventListener('click', () => {
                setupHelpModal.classList.remove('hidden');
                showStep(1);
            });

            // Close wizard
            closeSetupHelp.addEventListener('click', () => {
                setupHelpModal.classList.add('hidden');
            });

            // Final close button
            document.getElementById('finalCloseBtn').addEventListener('click', () => {
                setupHelpModal.classList.add('hidden');
                alert('Setup completed successfully!');
            });

            // Close modal when clicking outside
            window.addEventListener('click', (event) => {
                if (event.target === setupHelpModal) {
                    setupHelpModal.classList.add('hidden');
                }
            });
        });
=======
            setTimeout(() => {
                setupElements.trillion.classList.remove('border-gray-300');
                setupElements.trillion.classList.add('bg-green-500', 'border-green-500');
                setupElements.trillion.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
            }, 1000);

            setTimeout(() => {
                setupElements.pusher.classList.remove('border-gray-300');
                setupElements.pusher.classList.add('bg-green-500', 'border-green-500');
                setupElements.pusher.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
            }, 2000);

            setTimeout(() => {
                setupElements.huggingFace.classList.remove('border-gray-300');
                setupElements.huggingFace.classList.add('bg-green-500', 'border-green-500');
                setupElements.huggingFace.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
            }, 3000);

            setTimeout(() => {
                setupElements.twilio.classList.remove('border-gray-300');
                setupElements.twilio.classList.add('bg-green-500', 'border-green-500');
                setupElements.twilio.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
            }, 4000);

            setTimeout(() => {
                setupElements.env.classList.remove('border-gray-300');
                setupElements.env.classList.add('bg-green-500', 'border-green-500');
                setupElements.env.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
                document.getElementById('setupComplete').classList.remove('hidden');
                finishBtn.disabled = false;
            }, 5000);

            finishBtn.addEventListener('click', () => {
                currentStep++;
                showStep(currentStep);
            });
        }

        setupHelpBtn.addEventListener('click', () => {
            setupHelpModal.classList.remove('hidden');
            currentStep = 1;
            showStep(currentStep);
        });

        closeSetupHelp.addEventListener('click', () => {
            setupHelpModal.classList.add('hidden');
        });

        document.getElementById('finalCloseBtn').addEventListener('click', () => {
            localStorage.setItem('setupComplete', 'true');
            setupHelpModal.classList.add('hidden');
            alert('Setup completed successfully! You can run setup again anytime if needed.');
        });

        window.addEventListener('click', (event) => {
            if (event.target === setupHelpModal) {
                setupHelpModal.classList.add('hidden');
            }
        });
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=jjmandog/jshehrb" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>