Spaces:
Running

File size: 62,398 Bytes
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca06cd
 
 
 
 
3d080ef
 
44dc849
3d080ef
 
 
 
 
 
 
 
 
 
 
 
9316882
3d080ef
 
 
 
 
 
 
 
 
9316882
3d080ef
 
 
 
 
 
 
 
 
 
 
9316882
 
3d080ef
 
 
 
 
 
44dc849
 
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44dc849
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9316882
33f690d
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f690d
3d080ef
 
 
 
 
 
 
 
 
44dc849
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aea5e91
44dc849
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44dc849
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f690d
3d080ef
 
 
 
 
 
 
 
 
33f690d
aca06cd
 
3d080ef
aca06cd
3d080ef
aca06cd
 
 
 
3d080ef
 
 
 
 
aca06cd
 
3d080ef
aca06cd
 
 
 
 
 
 
3d080ef
aca06cd
 
 
 
3d080ef
aca06cd
 
 
3d080ef
aca06cd
 
3d080ef
aca06cd
 
 
3d080ef
 
 
aca06cd
3d080ef
aca06cd
 
 
 
3d080ef
aca06cd
 
 
 
 
 
 
 
 
 
 
3d080ef
 
aca06cd
3d080ef
 
 
 
 
 
 
 
aca06cd
 
3d080ef
 
aca06cd
3d080ef
 
 
aca06cd
3d080ef
 
 
 
 
 
aca06cd
3d080ef
aca06cd
 
 
 
 
 
 
 
 
 
3d080ef
33f690d
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f690d
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44dc849
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72959eb
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44dc849
3d080ef
aca06cd
3d080ef
aca06cd
 
3d080ef
aca06cd
 
 
 
3d080ef
 
 
 
 
 
 
aca06cd
3d080ef
 
 
 
 
72959eb
aea5e91
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44dc849
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aea5e91
72959eb
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f690d
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9316882
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9316882
3d080ef
 
9316882
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f690d
44dc849
3d080ef
 
 
 
 
 
 
 
 
 
 
aca06cd
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca06cd
3d080ef
 
 
 
 
 
 
 
 
 
72959eb
3d080ef
 
 
 
aca06cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d080ef
 
 
 
 
 
 
 
 
 
 
 
aca06cd
3d080ef
 
 
 
 
 
 
 
 
 
 
aca06cd
3d080ef
 
 
aca06cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d080ef
aea5e91
3d080ef
aca06cd
aea5e91
aca06cd
3d080ef
 
 
 
aca06cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44dc849
3d080ef
 
 
 
 
 
33f690d
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f690d
3d080ef
 
33f690d
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca06cd
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca06cd
3d080ef
 
 
aca06cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d080ef
aca06cd
3d080ef
 
 
 
 
 
aca06cd
 
 
 
 
 
3d080ef
 
aca06cd
 
 
 
 
 
 
 
 
 
 
3d080ef
aca06cd
 
 
 
 
3d080ef
 
 
aca06cd
3d080ef
 
aca06cd
3d080ef
aca06cd
 
 
3d080ef
 
aca06cd
 
 
 
3d080ef
99d87d6
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d87d6
3d080ef
 
aca06cd
 
 
 
 
 
 
 
 
 
 
 
 
3d080ef
 
aca06cd
 
 
 
 
 
3d080ef
 
aca06cd
 
3d080ef
 
aca06cd
3d080ef
aca06cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d080ef
aca06cd
3d080ef
 
aca06cd
3d080ef
aca06cd
3d080ef
aca06cd
3d080ef
aca06cd
3d080ef
aca06cd
 
 
3d080ef
 
 
 
 
aca06cd
 
 
 
 
 
3d080ef
 
 
 
 
 
 
 
 
 
 
 
 
 
33f690d
 
3d080ef
aca06cd
3d080ef
aca06cd
 
 
3d080ef
 
aca06cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d080ef
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
// Pegos Market Dashboard JavaScript
class PegosDashboard {
    constructor() {
        this.apiBaseUrl = 'https://caner7-pegos-data.hf.space';
        this.coinGeckoApiUrl = 'https://api.coingecko.com/api/v3';
        this.data = {
            bitcoin: null,
            predictions: [],
            signals: [],
            history: []
        };
        this.refreshInterval = null;
        this.isConnected = false;
        this.chart = null;
        
        // Pagination state
        this.currentPage = 1;
        this.itemsPerPage = 20;
        this.allPredictions = [];
        
        this.init();
    }

    async init() {
        console.log('Pegos Dashboard başlatılıyor...');
        this.setupEventListeners();
        console.log('Event listenerlar kuruldu');
        
        await this.loadInitialData();
        console.log('İlk veriler yüklendi');
        
        this.startAutoRefresh();
        console.log('Otomatik yenileme başlatıldı');
        
        console.log('Dashboard başarıyla başlatıldı!');
    }

    setupEventListeners() {
        // Calculator input
        const btcAmountInput = document.getElementById('btcAmount');
        if (btcAmountInput) {
            btcAmountInput.addEventListener('input', () => {
                this.calculateProfit();
            });
        }
    }

    async checkConnection() {
        try {
            const response = await this.apiCall('/health');
            this.isConnected = true;
            this.updateConnectionStatus('API Bağlı', 'connected');
        } catch (error) {
            this.isConnected = false;
            this.updateConnectionStatus('API Bağlantı Hatası', 'error');
            console.error('API bağlantı hatası:', error);
        }
    }

    updateConnectionStatus(message, status) {
        const statusContainer = document.getElementById('apiStatus');
        if (statusContainer) {
            statusContainer.textContent = message;
            statusContainer.className = `api-status-container ${status}`;
        }
    }

    async apiCall(endpoint) {
        try {
            console.log(`API çağrısı yapılıyor: ${this.apiBaseUrl}${endpoint}`);
            
            const response = await fetch(`${this.apiBaseUrl}${endpoint}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                mode: 'cors',
                credentials: 'omit'
            });
            
            console.log(`API yanıtı: ${response.status} ${response.statusText}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            console.log(`API verisi alındı:`, data);
            return data;
        } catch (error) {
            console.error(`API call failed for ${endpoint}:`, error);
            console.log(`Mock veri kullanılıyor...`);
            // Return mock data if API fails
            return this.getMockData(endpoint);
        }
    }

    async getBitcoinPrice() {
        try {
            console.log('Bitcoin fiyatı alınıyor...');
            
            const response = await fetch(`${this.coinGeckoApiUrl}/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                mode: 'cors',
                credentials: 'omit'
            });
            
            console.log(`Bitcoin API yanıtı: ${response.status} ${response.statusText}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            console.log('Bitcoin verisi alındı:', data);
            
            // Gerçek API formatına göre düzenle
            return {
                price: data.bitcoin.usd,
                change24h: data.bitcoin.usd_24h_change,
                timestamp: new Date().toISOString()
            };
        } catch (error) {
            console.error('Bitcoin price fetch failed:', error);
            console.log('Mock Bitcoin verisi kullanılıyor...');
            // Return mock data if API fails
            return this.getMockBitcoinData();
        }
    }

    getMockData(endpoint) {
        switch(endpoint) {
            case '/health':
                return { status: 'healthy', timestamp: new Date().toISOString() };
            case '/latest':
                return this.generateMockLatestData();
            case '/history':
                return this.generateMockHistoryData();
            case '/predict':
                return this.generateMockPredictionData();
            case '/signal':
                return this.generateMockSignalData();
            default:
                return {};
        }
    }

    getMockBitcoinData() {
        const basePrice = 45000 + Math.random() * 10000;
        const change = (Math.random() - 0.5) * 2000;
        return {
            price: Math.round(basePrice),
            change24h: Math.round((change / basePrice) * 100 * 100) / 100,
            timestamp: new Date().toISOString()
        };
    }

    generateMockLatestData() {
        const basePrice = 45000 + Math.random() * 10000;
        const change = (Math.random() - 0.5) * 2000;
        return {
            price: basePrice,
            change: change,
            changePercent: (change / basePrice) * 100,
            volume: Math.random() * 1000000,
            timestamp: new Date().toISOString(),
            prediction: {
                nextHour: basePrice + (Math.random() - 0.5) * 1000,
                nextDay: basePrice + (Math.random() - 0.5) * 5000,
                confidence: 0.7 + Math.random() * 0.3
            }
        };
    }

    generateMockHistoryData() {
        const data = [];
        const now = new Date();
        for (let i = 0; i < 30; i++) {
            const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
            const basePrice = 40000 + Math.random() * 20000;
            const high = basePrice + Math.random() * 2000;
            const low = basePrice - Math.random() * 2000;
            const close = low + Math.random() * (high - low);
            
            data.push({
                date: date.toISOString().split('T')[0],
                open: basePrice,
                high: high,
                low: low,
                close: close,
                volume: Math.random() * 1000000,
                prediction: close + (Math.random() - 0.5) * 1000,
                actual: close + (Math.random() - 0.5) * 500
            });
        }
        return data.reverse();
    }

    generateMockPredictionData() {
        const predictions = [];
        const now = new Date();
        const basePrice = 45000;
        
        for (let i = 0; i < 20; i++) {
            const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
            const priceVariation = (Math.random() - 0.5) * 10000;
            const prediction = basePrice + priceVariation;
            const actual = prediction + (Math.random() - 0.5) * 2000;
            const confidence = 0.6 + Math.random() * 0.4;
            const direction = prediction > basePrice ? 'up' : 'down';
            
            predictions.push({
                date: date.toISOString().split('T')[0],
                prediction: Math.round(prediction),
                actual: Math.round(actual),
                confidence: Math.round(confidence * 100) / 100,
                direction: direction,
                accuracy: Math.abs(prediction - actual) / actual < 0.05 ? 'high' : 'low'
            });
        }
        return predictions.reverse();
    }

    generateMockSignalData() {
        return {
            signal: Math.random() > 0.5 ? 'bullish' : 'bearish',
            strength: 0.5 + Math.random() * 0.5,
            confidence: 0.6 + Math.random() * 0.4,
            timestamp: new Date().toISOString(),
            description: Math.random() > 0.5 ? 'Güçlü yükseliş sinyali tespit edildi' : 'Düşüş sinyali gözlemleniyor'
        };
    }

    processPredictData(predictData) {
        // /predict endpoint'inden gelen GERÇEK MODEL TAHMİNLERİNİ kullan
        const predictions = [];
        let items = predictData.items || [];
        
        // Görüntülenme sayısına göre sırala (yüksekten düşüğe)
        items = items.sort((a, b) => (b.see_count || 0) - (a.see_count || 0));
        
        console.log(`📊 Model tahminleri işleniyor: ${items.length} adet (görüntülenme sıralı)`);
        
        // Ağırlıklı ortalama için toplam değerler
        let totalWeightedChange = 0;
        let totalWeight = 0;
        
        items.forEach((item, index) => {
            const date = item.prediction_day || new Date().toISOString().split('T')[0];
            
            // /predict endpoint'inden gelen GERÇEK MODEL DEĞERLERİNİ kullan
            const predLabel = item.pred_label; // 1=Yükseliş, 0=Düşüş
            const predProba = item.pred_proba || 0.5; // Model güveni (0-1)
            const predDiff = item.pred_diff || 0; // Tahmin edilen fark ($)
            const aiPrediction = item['AI_Model_Tahmini (%)'] || 0; // Tahmin fiyatı
            const aiDirection = item['AI_Model_Yonu'] || ''; // Yön metni
            const confidence = item['Güven (%)'] || (predProba * 100); // Güven yüzdesi
            
            // Engagement = ağırlık faktörü
            const engagement = item.like + item.retweet + item.comment;
            const totalEngagement = engagement + item.see_count;
            const weight = Math.max(1, totalEngagement); // En az 1 ağırlık
            
            // Tahmin edilen değişim yüzdesi (pred_diff bazlı)
            const currentPrice = this.data.bitcoin?.price || 108000;
            const predictedChangePercent = (predDiff / currentPrice) * 100;
            
            // Yön belirleme (API'den gelen label kullan)
            const direction = predLabel === 1 ? 'up' : predLabel === 0 ? 'down' : 'neutral';
            
            // Ağırlıklı ortalama için ekle (model güveni * ağırlık)
            totalWeightedChange += predictedChangePercent * weight * predProba;
            totalWeight += weight * predProba;
            
            predictions.push({
                date: date,
                tweet: item.tweet,
                engagement: engagement,
                prediction: currentPrice + predDiff, // Gerçek model tahmini
                actual: currentPrice,
                confidence: predProba, // Model güveni (0-1)
                confidencePercent: confidence, // Güven yüzdesi
                direction: direction,
                accuracy: predProba > 0.8 ? 'Yüksek' : predProba > 0.6 ? 'Orta' : 'Düşük',
                time: date,
                seeCount: item.see_count,
                keyword: 'bitcoin', // /predict sadece Bitcoin için
                // API'den gelen değerler
                predLabel: predLabel,
                predProba: predProba,
                predDiff: predDiff,
                aiPrediction: aiPrediction,
                aiDirection: aiDirection,
                // Hesaplanan değerler
                predictedChangePercent: predictedChangePercent,
                weight: weight,
                sentimentScore: predLabel === 1 ? 1 : predLabel === 0 ? -1 : 0
            });
        });
        
        // Ağırlıklı ortalama artış yüzdesi hesapla
        const weightedAvgChangePercent = totalWeight > 0 ? totalWeightedChange / totalWeight : 0;
        
        console.log(`📊 Ağırlıklı Ortalama Tahmin Artışı: ${weightedAvgChangePercent.toFixed(4)}%`);
        
        // Güncel Bitcoin fiyatı
        const currentPrice = this.data.bitcoin?.price || 108000;
        
        if (!this.data.bitcoin || !this.data.bitcoin.price) {
            console.warn('⚠️ UYARI: Bitcoin fiyatı bulunamadı! Fallback değer kullanılıyor: $108,000');
            console.warn('⚠️ Bitcoin data:', this.data.bitcoin);
        }
        
        // Ağırlıklı ortalama değerini sakla
        this.weightedAvgChangePercent = weightedAvgChangePercent;
        this.predictedPrice = currentPrice * (1 + weightedAvgChangePercent / 100);
        
        console.log(`💰 Güncel Fiyat: $${currentPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
        console.log(`📈 Tahmin Edilen Fiyat: $${this.predictedPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
        console.log(`📊 Beklenen Değişim: ${weightedAvgChangePercent > 0 ? '+' : ''}${weightedAvgChangePercent.toFixed(4)}%`);
        console.log(`✅ Toplam ${predictions.length} MODEL TAHMİNİ oluşturuldu (/predict endpoint)`);
        
        // Tahmin sayısını sakla (hesaplayıcıda kullanılacak)
        this.totalPredictionsCount = predictions.length;
        
        // Hesaplayıcı bilgisini güncelle
        const calculatorTweetCount = document.getElementById('calculatorTweetCount');
        if (calculatorTweetCount) {
            calculatorTweetCount.textContent = predictions.length;
        }
        
        return predictions; // TÜM MODEL TAHMİNLERİNİ DÖNDÜR (200 adet)
    }

    processSignalData(signalData) {
        // YENİ API yapısını kullan
        console.log('🎯 Signal Data:', signalData);
        
        const upRate = signalData.up_rate || 0;
        const avgConf = signalData.avg_conf || 0;
        const aiPrediction = signalData['AI_Model_Tahmini (%)'] || 0;
        const aiDirection = signalData['AI_Model_Yonu'] || '';
        const signalText = signalData.signal || 'Belirsiz';
        const day = signalData.day || '';
        const records = signalData.records || 0;
        
        let signal = 'neutral';
        let strength = upRate;
        let confidence = avgConf;
        let description = '';
        
        // Sinyal tipini belirle
        if (upRate > 0.6) {
            signal = 'bullish';
            description = `${signalText} - ${records} tweet analiz edildi. AI Model ${aiDirection}. Güven: %${(avgConf * 100).toFixed(1)}`;
        } else if (upRate < 0.4) {
            signal = 'bearish';
            description = `${signalText} - ${records} tweet analiz edildi. AI Model ${aiDirection}. Güven: %${(avgConf * 100).toFixed(1)}`;
        } else {
            signal = 'neutral';
            description = `Nötr Piyasa - ${records} tweet analiz edildi. Kararsız sentiment.`;
        }
        
        return {
            signal: signal,
            strength: strength,
            confidence: confidence,
            timestamp: new Date().toISOString(),
            description: description,
            // Yeni alanlar
            aiPrediction: aiPrediction,
            aiDirection: aiDirection,
            signalText: signalText,
            upRate: upRate,
            avgConf: avgConf,
            day: day,
            records: records
        };
    }

    processHistoryData(historyData) {
        // Gerçek API verilerini grafik formatına dönüştür - TÜM VERİLERİ GÖSTER
        const processedData = [];
        const bitcoinItems = historyData.items.filter(item => item.keyword === 'bitcoin');
        
        console.log(`Tüm Bitcoin geçmiş verileri işleniyor: ${bitcoinItems.length} adet`);
        
        // Her tweet'i ayrı ayrı işle - şeffaflık için
        bitcoinItems.forEach((item, index) => {
            const date = new Date(item.time).toISOString().split('T')[0];
            
            if (item['Açılış Fiyatı (USD)'] && item['Kapanış Fiyatı (USD)']) {
                const openPrice = item['Açılış Fiyatı (USD)'];
                const closePrice = item['Kapanış Fiyatı (USD)'];
                const diff = item['Fark (USD)'] || 0;
                
                processedData.push({
                    date: date,
                    time: item.time,
                    tweet: item.tweet,
                    open: openPrice,
                    close: closePrice,
                    high: Math.max(openPrice, closePrice) + Math.abs(diff) * 0.5,
                    low: Math.min(openPrice, closePrice) - Math.abs(diff) * 0.5,
                    volume: item.see_count * 1000,
                    prediction: closePrice * (1 + (Math.random() - 0.5) * 0.05),
                    actual: closePrice,
                    engagement: item.like + item.retweet + item.comment,
                    keyword: item.keyword,
                    target: item.target || 0
                });
            }
        });
        
        console.log(`Toplam ${processedData.length} geçmiş veri işlendi`);
        return processedData.sort((a, b) => new Date(a.time) - new Date(b.time)); // TÜM VERİLERİ DÖNDÜR
    }

    async loadInitialData() {
        console.log('İlk veriler yükleniyor...');
        try {
            // 1. ÖNCELİKLE Bitcoin fiyatını yükle (diğer hesaplamalar buna bağlı)
            await this.loadBitcoinData();
            console.log('✅ Bitcoin verisi yüklendi, fiyat:', this.data.bitcoin?.price || 'N/A');
            
            // 2. Predictions'ı yükle (Bitcoin fiyatını kullanır)
            await this.loadPredictions();
            console.log('✅ Predictions yüklendi, sayı:', this.data.predictions?.length || 0);
            
            // 3. Signals'ı yükle
            await this.loadSignals();
            console.log('✅ Signals yüklendi');
            
            // 4. History'yi yükle
            await this.loadHistory();
            console.log('✅ History yüklendi');
            
            console.log('📊 Tüm veriler yüklendi, ekranlar güncelleniyor...');
            console.log('🔍 Final Bitcoin Fiyatı:', this.data.bitcoin?.price || 'HATA!');
            this.updateAllDisplays();
        } catch (error) {
            console.error('❌ Veri yükleme hatası:', error);
            // Hata durumunda da mock verilerle çalışmaya devam et
            this.updateAllDisplays();
        }
    }

    async loadBitcoinData() {
        console.log('Bitcoin verisi yükleniyor...');
        try {
            const bitcoinData = await this.getBitcoinPrice();
            this.data.bitcoin = bitcoinData;
            console.log('Bitcoin verisi yüklendi:', bitcoinData);
            this.updateBitcoinDisplay(bitcoinData);
        } catch (error) {
            console.error('Bitcoin veri yükleme hatası:', error);
            // Hata durumunda mock veri kullan
            const mockData = this.getMockBitcoinData();
            this.data.bitcoin = mockData;
            this.updateBitcoinDisplay(mockData);
        }
    }

    async loadPredictions() {
        console.log('📊 Tahmin verileri yükleniyor (/predict endpoint)...');
        try {
            const predictData = await this.apiCall('/predict');
            console.log('✅ Predict verisi alındı:', predictData);
            
            // /predict endpoint'inden gelen gerçek model tahminlerini kullan
            if (predictData && predictData.items) {
                this.data.predictions = this.processPredictData(predictData);
                console.log(`✅ ${this.data.predictions.length} model tahmini işlendi`);
            } else {
                this.data.predictions = this.generateMockPredictionData();
            }
            
            this.updatePredictionsTable();
            // NOT: updateStats() çağrılmıyor - updateAllDisplays() içinde çağrılacak (signals yüklendikten sonra)
        } catch (error) {
            console.error('❌ Tahmin veri yükleme hatası:', error);
            // Hata durumunda mock veri kullan
            this.data.predictions = this.generateMockPredictionData();
            this.updatePredictionsTable();
            // NOT: updateStats() çağrılmıyor - updateAllDisplays() içinde çağrılacak
        }
    }

    async loadSignals() {
        console.log('Sinyal verileri yükleniyor...');
        try {
            const signals = await this.apiCall('/signal');
            console.log('Signal verisi alındı:', signals);
            
            // Gerçek API formatına göre sinyal verilerini işle
            if (signals && signals.up_rate !== undefined) {
                this.data.signals = this.processSignalData(signals);
                console.log('Sinyal verileri işlendi:', this.data.signals);
            } else {
                this.data.signals = this.generateMockSignalData();
            }
            
            this.updateSignalDisplay(this.data.signals);
        } catch (error) {
            console.error('Sinyal veri yükleme hatası:', error);
            // Hata durumunda mock veri kullan
            this.data.signals = this.generateMockSignalData();
            this.updateSignalDisplay(this.data.signals);
        }
    }

    async loadHistory() {
        console.log('Geçmiş veriler yükleniyor...');
        try {
            const history = await this.apiCall('/history');
            console.log('History verisi alındı:', history);
            
            // Gerçek API formatına göre geçmiş verilerini işle
            if (history && history.items) {
                this.data.history = this.processHistoryData(history);
                console.log('Geçmiş veriler işlendi:', this.data.history.length, 'adet');
            } else {
                this.data.history = this.generateMockHistoryData();
            }
            
        } catch (error) {
            console.error('Geçmiş veri yükleme hatası:', error);
            // Hata durumunda mock veri kullan
            this.data.history = this.generateMockHistoryData();
        }
    }


    updateBitcoinDisplay(bitcoinData) {
        // Update current price
        const currentPriceElement = document.getElementById('currentPrice');
        if (currentPriceElement) {
            currentPriceElement.innerHTML = `$${bitcoinData.price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
        }

        // Update price change
        const priceChangeElement = document.getElementById('priceChange');
        if (priceChangeElement) {
            const changeClass = bitcoinData.change24h >= 0 ? 'positive' : 'negative';
            const changeSymbol = bitcoinData.change24h >= 0 ? '+' : '';
            priceChangeElement.textContent = `${changeSymbol}${bitcoinData.change24h.toFixed(2)}%`;
            priceChangeElement.className = `card-change ${changeClass}`;
        }

        // Update last update time
        const lastUpdateElement = document.getElementById('lastUpdate');
        if (lastUpdateElement) {
            const updateTime = new Date(bitcoinData.timestamp).toLocaleString('tr-TR');
            lastUpdateElement.textContent = `Son Güncelleme: ${updateTime}`;
        }
    }

    updateCurrentAnalysis(bitcoinData) {
        // Update current price display
        const currentPriceDisplay = document.getElementById('currentPriceDisplay');
        if (currentPriceDisplay) {
            currentPriceDisplay.textContent = `$${bitcoinData.price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
        }

        // Update price change
        const currentPriceChange = document.getElementById('currentPriceChange');
        if (currentPriceChange) {
            const changeClass = bitcoinData.change24h >= 0 ? 'positive' : 'negative';
            const changeSymbol = bitcoinData.change24h >= 0 ? '+' : '';
            currentPriceChange.textContent = `${changeSymbol}${bitcoinData.change24h.toFixed(2)}%`;
            currentPriceChange.className = `price-change ${changeClass}`;
        }

        // Update price change 24h
        const priceChange24h = document.getElementById('priceChange24h');
        if (priceChange24h) {
            const changeAmount = bitcoinData.price * (bitcoinData.change24h / 100);
            const changeSymbol = bitcoinData.change24h >= 0 ? '+' : '';
            priceChange24h.textContent = `${changeSymbol}$${changeAmount.toFixed(2)}`;
        }

        // Update timestamp
        const currentPriceTime = document.getElementById('currentPriceTime');
        if (currentPriceTime) {
            const updateTime = new Date(bitcoinData.timestamp).toLocaleString('tr-TR');
            currentPriceTime.textContent = updateTime;
        }

        const lastPriceUpdate = document.getElementById('lastPriceUpdate');
        if (lastPriceUpdate) {
            const updateTime = new Date(bitcoinData.timestamp).toLocaleString('tr-TR');
            lastPriceUpdate.textContent = updateTime;
        }

        // Update prediction if we have data
        if (this.data.predictions.length > 0) {
            this.updatePredictionDisplay(bitcoinData);
        }

        // Update analysis
        this.updateAnalysisText(bitcoinData);
    }

    updatePredictionDisplay(bitcoinData) {
        // Önce ağırlıklı ortalama tahmini kullan, yoksa API tahminini kullan
        const useWeightedPrediction = this.weightedAvgChangePercent !== undefined && this.predictedPrice !== undefined;
        
        if (!useWeightedPrediction && (!this.data.signals || !this.data.signals.aiPrediction)) {
            console.log('⚠️ updatePredictionDisplay: Tahmin verisi yok');
            
            const predictionValue = document.getElementById('predictionValue');
            if (predictionValue) predictionValue.textContent = 'Yükleniyor...';
            
            const predictionDirection = document.getElementById('predictionDirection');
            if (predictionDirection) predictionDirection.textContent = 'Veri Bekleniyor';
            
            const modelConfidence = document.getElementById('modelConfidence');
            if (modelConfidence) modelConfidence.textContent = 'Güven: -';
            
            const expectedChange = document.getElementById('expectedChange');
            if (expectedChange) expectedChange.textContent = '$0';
            
            const predictionDate = document.getElementById('predictionDate');
            if (predictionDate) predictionDate.textContent = '-';
            
            return;
        }
        
        // Ağırlıklı ortalama varsa onu kullan
        let finalPrediction, finalDirection, finalConfidence, changePercent;
        
        if (useWeightedPrediction) {
            finalPrediction = this.predictedPrice;
            changePercent = this.weightedAvgChangePercent;
            finalDirection = changePercent > 0.1 ? '📈 Yükseliş Bekleniyor' : 
                           changePercent < -0.1 ? '📉 Düşüş Bekleniyor' : 
                           '➡️ Yatay Seyir';
            finalConfidence = this.data.signals ? this.data.signals.avgConf : 0.7;
            
            console.log(`🔮 Ağırlıklı Ortalama Tahmin: $${finalPrediction.toFixed(2)} (${changePercent > 0 ? '+' : ''}${changePercent.toFixed(4)}%)`);
        } else {
            // API tahminini kullan
            const signals = this.data.signals;
            finalPrediction = signals.aiPrediction;
            finalDirection = signals.aiDirection;
            finalConfidence = signals.avgConf;
            changePercent = ((signals.aiPrediction - bitcoinData.price) / bitcoinData.price) * 100;
            
            console.log(`🔮 API AI Model Prediction: $${finalPrediction.toFixed(2)}`);
        }
        
        // Update prediction value
        const predictionValue = document.getElementById('predictionValue');
        if (predictionValue) {
            predictionValue.textContent = `$${finalPrediction.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
        }

        // Update prediction direction
        const predictionDirection = document.getElementById('predictionDirection');
        if (predictionDirection) {
            const isUp = finalDirection.includes('Yükseliş') || finalDirection.includes('Artış') || finalDirection.includes('📈');
            const directionClass = isUp ? 'up' : 'down';
            predictionDirection.textContent = finalDirection;
            predictionDirection.className = `prediction-direction ${directionClass}`;
        }

        // Update model confidence
        const modelConfidence = document.getElementById('modelConfidence');
        if (modelConfidence) {
            modelConfidence.textContent = `Güven: ${(finalConfidence * 100).toFixed(1)}%`;
        }

        // Update expected change
        const expectedChange = document.getElementById('expectedChange');
        if (expectedChange) {
            const changeAmount = finalPrediction - bitcoinData.price;
            const changeSymbol = changeAmount >= 0 ? '+' : '';
            expectedChange.textContent = `${changeSymbol}$${changeAmount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} (${changeSymbol}${changePercent.toFixed(2)}%)`;
        }

        // Update prediction date
        const predictionDate = document.getElementById('predictionDate');
        if (predictionDate) {
            const dateText = this.data.signals && this.data.signals.day ? this.data.signals.day : new Date().toLocaleDateString('tr-TR');
            predictionDate.textContent = dateText;
        }
    }

    updateAnalysisText(bitcoinData) {
        const analysisText = document.getElementById('analysisText');
        if (!analysisText) return;

        // Check if we have data (predictions veya signals)
        if ((!this.data.predictions || this.data.predictions.length === 0) && !this.data.signals) {
            analysisText.innerHTML = `<p>Model analizi yükleniyor... API'den tweet verileri bekleniyor.</p>`;
            
            const analyzedTweets = document.getElementById('analyzedTweets');
            if (analyzedTweets) analyzedTweets.textContent = '0';
            
            const avgConfidenceElement = document.getElementById('analysisAvgConfidence');
            if (avgConfidenceElement) avgConfidenceElement.textContent = '0%';
            
            const marketSentiment = document.getElementById('marketSentiment');
            if (marketSentiment) {
                marketSentiment.textContent = 'Veri Yükleniyor';
                marketSentiment.style.color = '#ffa500';
            }
            
            console.log('⚠️ Predictions ve Signal verisi henüz yüklenmemiş');
            return;
        }
 
        // Signal data'dan gelen gerçek bilgileri kullan (varsa)
        const records = this.data.signals && this.data.signals.records ? this.data.signals.records : this.data.predictions.length;
        const avgConfidence = this.data.signals && this.data.signals.avgConf ? this.data.signals.avgConf : 
                             this.data.predictions.reduce((sum, p) => sum + p.confidence, 0) / this.data.predictions.length;
        const upRate = this.data.signals && this.data.signals.upRate ? this.data.signals.upRate : 0.5;
        
        const bullishCount = this.data.predictions.filter(p => p.direction === 'up').length;
        const bearishCount = this.data.predictions.filter(p => p.direction === 'down').length;
        
        console.log(`📊 Analiz: ${records} tweet, Up Rate: ${(upRate * 100).toFixed(1)}%, Avg Confidence: ${(avgConfidence * 100).toFixed(1)}%`);
        
        let analysis = '';
        let sentiment = '';
        let sentimentColor = '';
        
        // Signal data'dan gelen up_rate'e göre analiz
        if (upRate > 0.6) {
            sentiment = 'Pozitif';
            sentimentColor = '#00ff88';
            analysis = `Model analizi ${records} Bitcoin tweet'ini inceledi. Sonuçlar yükseliş yönünde pozitif sentiment gösteriyor (%${(upRate * 100).toFixed(1)} yükseliş oranı). Ortalama güven seviyesi %${(avgConfidence * 100).toFixed(1)} ile güçlü tahminler yapılıyor.`;
        } else if (upRate < 0.4) {
            sentiment = 'Negatif';
            sentimentColor = '#ff4444';
            analysis = `Model analizi ${records} Bitcoin tweet'ini inceledi. Sonuçlar düşüş yönünde negatif sentiment gösteriyor (%${(upRate * 100).toFixed(1)} yükseliş oranı). Ortalama güven seviyesi %${(avgConfidence * 100).toFixed(1)} ile dikkatli yaklaşım öneriliyor.`;
        } else {
            sentiment = 'Nötr';
            sentimentColor = '#ffa500';
            analysis = `Model analizi ${records} Bitcoin tweet'ini inceledi. Sonuçlar karışık sentiment gösteriyor (%${(upRate * 100).toFixed(1)} yükseliş oranı). Ortalama güven seviyesi %${(avgConfidence * 100).toFixed(1)} ile belirsizlik devam ediyor.`;
        }

        analysisText.innerHTML = `<p>${analysis}</p>`;

        // Update metrics
        const analyzedTweets = document.getElementById('analyzedTweets');
        if (analyzedTweets) {
            analyzedTweets.textContent = records;
        }

        const avgConfidenceElement = document.getElementById('analysisAvgConfidence');
        if (avgConfidenceElement) {
            avgConfidenceElement.textContent = `${(avgConfidence * 100).toFixed(1)}%`;
        }

        const marketSentiment = document.getElementById('marketSentiment');
        if (marketSentiment) {
            marketSentiment.textContent = sentiment;
            marketSentiment.style.color = sentimentColor;
        }
    }

    updatePredictionsTable() {
        const tbody = document.getElementById('predictionsTableBody');
        if (!tbody || !this.data.predictions.length) return;

        // Tüm predictions'ı sakla
        this.allPredictions = this.data.predictions;
        
        // Pagination hesapla
        const totalItems = this.allPredictions.length;
        const totalPages = Math.ceil(totalItems / this.itemsPerPage);
        const startIndex = (this.currentPage - 1) * this.itemsPerPage;
        const endIndex = Math.min(startIndex + this.itemsPerPage, totalItems);
        
        // Sadece mevcut sayfa için verileri göster
        const pageData = this.allPredictions.slice(startIndex, endIndex);
        
        console.log(`📄 Pagination: Sayfa ${this.currentPage}/${totalPages}, Gösterilen ${startIndex + 1}-${endIndex}/${totalItems}`);

        tbody.innerHTML = pageData.map(pred => {
            // Her tweet için hesaplanan tahmin yüzdesini kullan
            const predictedChangePercent = pred.predictedChangePercent || 0;
            const accuracy = Math.abs(predictedChangePercent) < 1 ? 'Düşük' : Math.abs(predictedChangePercent) < 3 ? 'Orta' : 'Yüksek';
            const accuracyClass = Math.abs(predictedChangePercent) < 1 ? 'text-warning' : Math.abs(predictedChangePercent) < 3 ? 'text-success' : 'text-danger';
            
            // Sentiment skoru göster
            const sentimentEmoji = pred.sentimentScore > 0 ? '😊' : pred.sentimentScore < 0 ? '😟' : '😐';
            const sentimentText = pred.sentimentScore > 0 ? 'Pozitif' : pred.sentimentScore < 0 ? 'Negatif' : 'Nötr';
            
            return `
                <tr>
                    <td>${new Date(pred.date).toLocaleDateString('tr-TR')}</td>
                    <td><span class="badge badge-${pred.keyword}">${pred.keyword}</span></td>
                    <td title="${pred.tweet}">${pred.tweet.length > 50 ? pred.tweet.substring(0, 50) + '...' : pred.tweet}</td>
                    <td>$${pred.actual.toLocaleString()}</td>
                    <td>$${pred.prediction.toLocaleString()}</td>
                    <td class="${predictedChangePercent >= 0 ? 'text-success' : 'text-danger'}">
                        ${predictedChangePercent >= 0 ? '+' : ''}${predictedChangePercent.toFixed(3)}%
                    </td>
                    <td class="${pred.direction === 'up' ? 'text-success' : pred.direction === 'down' ? 'text-danger' : 'text-warning'}">
                        ${pred.direction === 'up' ? '▲ Yükseliş' : pred.direction === 'down' ? '▼ Düşüş' : '➡️ Yatay'}
                    </td>
                    <td>${(pred.confidence * 100).toFixed(1)}%</td>
                    <td>${pred.seeCount || 0}</td>
                    <td class="${accuracyClass}" title="${sentimentEmoji} ${sentimentText} (pred_proba: ${(pred.predProba * 100).toFixed(1)}%)">${accuracy}</td>
                </tr>
            `;
        }).join('');
        
        // Pagination kontrollerini güncelle
        this.updatePaginationControls(totalPages, totalItems, startIndex, endIndex);
    }
    
    updatePaginationControls(totalPages, totalItems, startIndex, endIndex) {
        // Bilgi metni güncelle
        const paginationInfo = document.getElementById('paginationInfo');
        if (paginationInfo) {
            paginationInfo.textContent = `Gösterilen: ${startIndex + 1}-${endIndex} / Toplam: ${totalItems}`;
        }
        
        // Butonları etkinleştir/devre dışı bırak
        const firstPageBtn = document.getElementById('firstPage');
        const prevPageBtn = document.getElementById('prevPage');
        const nextPageBtn = document.getElementById('nextPage');
        const lastPageBtn = document.getElementById('lastPage');
        
        if (firstPageBtn) firstPageBtn.disabled = this.currentPage === 1;
        if (prevPageBtn) prevPageBtn.disabled = this.currentPage === 1;
        if (nextPageBtn) nextPageBtn.disabled = this.currentPage === totalPages;
        if (lastPageBtn) lastPageBtn.disabled = this.currentPage === totalPages;
        
        // Sayfa numaralarını oluştur
        this.renderPageNumbers(totalPages);
    }
    
    renderPageNumbers(totalPages) {
        const numbersContainer = document.getElementById('paginationNumbers');
        if (!numbersContainer) return;
        
        const maxVisible = 5;
        let pages = [];
        
        if (totalPages <= maxVisible + 2) {
            // Tüm sayfaları göster
            pages = Array.from({ length: totalPages }, (_, i) => i + 1);
        } else {
            // Akıllı sayfa numarası gösterimi
            const leftSide = Math.max(1, this.currentPage - 1);
            const rightSide = Math.min(totalPages, this.currentPage + 1);
            
            if (this.currentPage <= 3) {
                pages = [1, 2, 3, 4, '...', totalPages];
            } else if (this.currentPage >= totalPages - 2) {
                pages = [1, '...', totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
            } else {
                pages = [1, '...', leftSide, this.currentPage, rightSide, '...', totalPages];
            }
        }
        
        numbersContainer.innerHTML = pages.map(page => {
            if (page === '...') {
                return `<div class="page-number ellipsis">...</div>`;
            }
            const isActive = page === this.currentPage ? 'active' : '';
            return `<div class="page-number ${isActive}" onclick="dashboard.goToPage(${page})">${page}</div>`;
        }).join('');
    }
    
    goToPage(pageNum) {
        const totalPages = Math.ceil(this.allPredictions.length / this.itemsPerPage);
        
        if (pageNum === -1) {
            // Son sayfa
            this.currentPage = totalPages;
        } else {
            this.currentPage = Math.max(1, Math.min(pageNum, totalPages));
        }
        
        console.log(`📄 Sayfa ${this.currentPage}/${totalPages} gösteriliyor`);
        this.updatePredictionsTable();
    }
    
    nextPage() {
        const totalPages = Math.ceil(this.allPredictions.length / this.itemsPerPage);
        if (this.currentPage < totalPages) {
            this.currentPage++;
            this.updatePredictionsTable();
        }
    }
    
    previousPage() {
        if (this.currentPage > 1) {
            this.currentPage--;
            this.updatePredictionsTable();
        }
    }
    
    changeItemsPerPage() {
        const select = document.getElementById('itemsPerPage');
        if (select) {
            this.itemsPerPage = parseInt(select.value);
            this.currentPage = 1; // İlk sayfaya dön
            console.log(`📄 Sayfa başına ${this.itemsPerPage} öğe gösteriliyor`);
            this.updatePredictionsTable();
        }
    }
    
    filterPredictions() {
        const filterSelect = document.getElementById('keywordFilter');
        if (!filterSelect) return;
        
        const filterValue = filterSelect.value;
        
        // Tüm predictions'ı filtrele
        if (filterValue === 'all') {
            this.data.predictions = this.allPredictions;
        } else {
            this.data.predictions = this.allPredictions.filter(p => p.keyword === filterValue);
        }
        
        console.log(`🔍 Filtre: ${filterValue}, Gösterilen: ${this.data.predictions.length}/${this.allPredictions.length}`);
        
        // İlk sayfaya dön ve tabloyu güncelle
        this.currentPage = 1;
        this.updatePredictionsTable();
    }

    updateStats() {
        if (!this.data.predictions.length && !this.data.signals) return;

        // Signal data'dan gelen gerçek değerleri kullan (varsa)
        const avgConfidence = this.data.signals && this.data.signals.avgConf 
            ? this.data.signals.avgConf 
            : this.data.predictions.reduce((sum, p) => sum + p.confidence, 0) / this.data.predictions.length;
        
        const totalRecords = this.data.signals && this.data.signals.records 
            ? this.data.signals.records 
            : this.data.predictions.length;
        
        const upRate = this.data.signals && this.data.signals.upRate !== undefined
            ? this.data.signals.upRate
            : this.data.predictions.filter(p => p.direction === 'up').length / this.data.predictions.length;
        
        // Yüksek güven: avg_conf > 0.8 ise tüm kayıtların %80'i
        // Düşük güven: avg_conf < 0.6 ise tüm kayıtların %60'ı
        let highConfidence, lowConfidence;
        
        if (this.data.signals && this.data.signals.avgConf) {
            // API'den gelen güven seviyesine göre hesapla
            highConfidence = avgConfidence > 0.8 
                ? Math.round(totalRecords * 0.8) 
                : Math.round(totalRecords * avgConfidence);
            lowConfidence = avgConfidence < 0.6 
                ? Math.round(totalRecords * (1 - avgConfidence)) 
                : 0;
        } else {
            // Local predictions kullan
            highConfidence = this.data.predictions.filter(p => p.confidence > 0.8).length;
            lowConfidence = this.data.predictions.filter(p => p.confidence < 0.6).length;
        }
        
        // Bullish/Bearish sayıları up_rate'e göre hesapla
        const bullishCount = Math.round(totalRecords * upRate);
        const bearishCount = totalRecords - bullishCount;
        
        const successRate = avgConfidence * 100; // Güven = başarı oranı

        console.log(`📊 STATS GÜNCELLEME:`);
        console.log(`   • Toplam Kayıt: ${totalRecords}`);
        console.log(`   • Ortalama Güven: ${(avgConfidence * 100).toFixed(1)}%`);
        console.log(`   • Up Rate: ${(upRate * 100).toFixed(1)}%`);
        console.log(`   • Yüksek Güven: ${highConfidence}`);
        console.log(`   • Düşük Güven: ${lowConfidence}`);
        console.log(`   • Bullish: ${bullishCount}`);
        console.log(`   • Bearish: ${bearishCount}`);

        // Update stat elements
        this.updateStatElement('correctPredictions', highConfidence);
        this.updateStatElement('wrongPredictions', lowConfidence);
        this.updateStatElement('bullishCount', bullishCount);
        this.updateStatElement('bearishCount', bearishCount);
        this.updateStatElement('avgConfidence', `${(avgConfidence * 100).toFixed(1)}%`);
        this.updateStatElement('successRate', `${successRate.toFixed(1)}%`);

        // Update model accuracy - Signal data'dan gelen gerçek değer
        const modelAccuracyElement = document.getElementById('modelAccuracy');
        if (modelAccuracyElement) {
            modelAccuracyElement.innerHTML = `${(avgConfidence * 100).toFixed(1)}%`;
        }

        // Update total predictions - API'den gelen records sayısını kullan
        const totalPredictionsElement = document.getElementById('totalPredictions');
        if (totalPredictionsElement) {
            // Öncelik: API'den gelen records, yoksa predictions array uzunluğu
            const totalAnalyzed = this.data.signals && this.data.signals.records 
                ? this.data.signals.records 
                : this.data.predictions.length;
            
            totalPredictionsElement.innerHTML = totalAnalyzed;
            
            console.log(`📊 TOPLAM TAHMİN GÜNCELLEME:`);
            console.log(`   • Signals mevcut: ${!!this.data.signals}`);
            console.log(`   • Signals.records: ${this.data.signals?.records || 'YOK'}`);
            console.log(`   • Predictions.length: ${this.data.predictions.length}`);
            console.log(`   • Gösterilen Değer: ${totalAnalyzed}`);
            
            if (this.data.signals && this.data.signals.records) {
                console.log(`   ✅ API'den gelen records kullanıldı: ${totalAnalyzed}`);
            } else {
                console.log(`   ⚠️ API records yok, local array kullanıldı: ${totalAnalyzed}`);
            }
        }
    }

    updateStatElement(id, value) {
        const element = document.getElementById(id);
        if (element) {
            element.textContent = value;
        }
    }

    updateSignalDisplay(signals) {
        const signalInfoContainer = document.getElementById('signalInfo');
        if (!signalInfoContainer) return;

        const signal = signals.signal || 'neutral';
        const strength = signals.strength || 0.5;
        const confidence = signals.confidence || 0.5;
        const description = signals.description || 'Sinyal analizi yapılıyor...';

        const signalClass = signal === 'bullish' ? 'success' : signal === 'bearish' ? 'danger' : 'warning';
        const signalIcon = signal === 'bullish' ? '📈' : signal === 'bearish' ? '📉' : '➡️';
        const signalText = signal === 'bullish' ? 'Yükseliş' : signal === 'bearish' ? 'Düşüş' : 'Yan Piyasa';

        signalInfoContainer.innerHTML = `
            <div class="signal-card">
                <div class="signal-header">
                    <span class="signal-icon">${signalIcon}</span>
                    <h3>Piyasa Sinyali: ${signalText}</h3>
                    <span class="signal-strength ${signalClass}">${(strength * 100).toFixed(0)}%</span>
                </div>
                <div class="signal-body">
                    <p>${description}</p>
                    <div class="signal-metrics">
                        <div class="metric">
                            <span class="metric-label">Sinyal Gücü:</span>
                            <span class="metric-value">${(strength * 100).toFixed(1)}%</span>
                        </div>
                        <div class="metric">
                            <span class="metric-label">Güven Seviyesi:</span>
                            <span class="metric-value">${(confidence * 100).toFixed(1)}%</span>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // Update prediction signal
        const predictionSignalElement = document.getElementById('predictionSignal');
        if (predictionSignalElement) {
            predictionSignalElement.innerHTML = signalText;
        }

        const confidenceElement = document.getElementById('confidence');
        if (confidenceElement) {
            confidenceElement.textContent = `Güven: ${(confidence * 100).toFixed(1)}%`;
        }
    }

    createChart() {
        if (!this.data.history.length) return;

        const chartElement = document.getElementById('chart');
        const chartStatusElement = document.getElementById('chartStatus');
        
        if (!chartElement || !chartStatusElement) return;

        // Hide loading status
        chartStatusElement.style.display = 'none';
        chartElement.style.display = 'block';

        // Prepare data for Plotly
        const dates = this.data.history.map(d => d.date);
        const prices = this.data.history.map(d => d.close);
        const predictions = this.data.history.map(d => d.prediction);
        const volumes = this.data.history.map(d => d.volume);

        // Create traces
        const traces = [
            {
                x: dates,
                y: prices,
                type: 'scatter',
                mode: 'lines',
                name: 'Bitcoin Fiyatı',
                line: {
                    color: '#00ff88',
                    width: 3
                },
                hovertemplate: '<b>%{x}</b><br>Fiyat: $%{y:,.2f}<extra></extra>'
            },
            {
                x: dates,
                y: predictions,
                type: 'scatter',
                mode: 'markers',
                name: 'AI Tahminleri',
                marker: {
                    color: '#00d4ff',
                    size: 8,
                    symbol: 'triangle-up'
                },
                hovertemplate: '<b>%{x}</b><br>Tahmin: $%{y:,.2f}<extra></extra>'
            }
        ];

        const layout = {
            title: {
                text: 'Bitcoin Fiyat Grafiği ve AI Tahminleri',
                font: { color: '#e0e0e0', size: 18 }
            },
            xaxis: {
                title: 'Tarih',
                color: '#e0e0e0',
                gridcolor: 'rgba(255, 255, 255, 0.1)',
                showgrid: true
            },
            yaxis: {
                title: 'Fiyat (USD)',
                color: '#e0e0e0',
                gridcolor: 'rgba(255, 255, 255, 0.1)',
                showgrid: true,
                tickformat: '$,.0f'
            },
            plot_bgcolor: 'rgba(0, 0, 0, 0)',
            paper_bgcolor: 'rgba(0, 0, 0, 0)',
            font: { color: '#e0e0e0' },
            legend: {
                x: 0,
                y: 1,
                bgcolor: 'rgba(0, 0, 0, 0.5)',
                bordercolor: 'rgba(255, 255, 255, 0.2)',
                borderwidth: 1
            },
            margin: { t: 60, r: 50, b: 50, l: 50 }
        };

        const config = {
            responsive: true,
            displayModeBar: true,
            modeBarButtonsToRemove: ['pan2d', 'lasso2d', 'select2d'],
            displaylogo: false
        };

        Plotly.newPlot(chartElement, traces, layout, config);
    }

    calculateProfit() {
        const btcAmount = parseFloat(document.getElementById('btcAmount')?.value || 0);
        const resultsContainer = document.getElementById('calculatorResults');
        
        if (!resultsContainer) return;

        if (btcAmount <= 0) {
            resultsContainer.innerHTML = `
                <div class="result-placeholder">
                    <span class="placeholder-icon">📊</span>
                    <p>Bitcoin miktarı girin (örn: 0.5)</p>
                </div>
            `;
            return;
        }

        if (!this.data.bitcoin) {
            resultsContainer.innerHTML = `
                <div class="result-placeholder">
                    <span class="placeholder-icon">⚠️</span>
                    <p>Bitcoin fiyat verisi yükleniyor...</p>
                </div>
            `;
            return;
        }

        // Güncel Bitcoin fiyatı
        const currentPrice = this.data.bitcoin.price;
        const currentValue = btcAmount * currentPrice;
        
        // Model tahmini - Ağırlıklı ortalama veya predictedPrice kullan
        let predictedPrice, changePercent;
        
        if (this.predictedPrice && this.weightedAvgChangePercent !== undefined) {
            // Ağırlıklı ortalama tahmin kullan
            predictedPrice = this.predictedPrice;
            changePercent = this.weightedAvgChangePercent;
        } else if (this.data.signals && this.data.signals.aiPrediction) {
            // API'den gelen AI tahmini kullan
            predictedPrice = this.data.signals.aiPrediction;
            changePercent = ((predictedPrice - currentPrice) / currentPrice) * 100;
        } else {
            // Veri yoksa
            resultsContainer.innerHTML = `
                <div class="result-placeholder">
                    <span class="placeholder-icon">⚠️</span>
                    <p>Model tahmini yükleniyor...</p>
                </div>
            `;
            return;
        }
        
        const predictedValue = btcAmount * predictedPrice;
        const profit = predictedValue - currentValue;
        const profitPercent = (profit / currentValue) * 100;
        
        const profitClass = profit >= 0 ? 'text-success' : 'text-danger';
        const profitIcon = profit >= 0 ? '📈' : '📉';
        
        console.log(`🧮 Kâr/Zarar Hesaplama: ${btcAmount} BTC`);
        console.log(`   • Güncel Fiyat: $${currentPrice.toFixed(2)}`);
        console.log(`   • Tahmin Fiyatı: $${predictedPrice.toFixed(2)}`);
        console.log(`   • Değişim: ${changePercent > 0 ? '+' : ''}${changePercent.toFixed(4)}%`);
        console.log(`   • Kâr/Zarar: ${profit > 0 ? '+' : ''}$${profit.toFixed(2)}`);
        
        resultsContainer.innerHTML = `
            <div class="calculation-results">
                <div class="result-header">
                    <h4>💰 Hesaplama Sonucu</h4>
                    <p style="font-size: 0.85rem; color: rgba(255,255,255,0.7);">
                        ${btcAmount} BTC × Model Tahmini (${changePercent > 0 ? '+' : ''}${changePercent.toFixed(3)}% değişim)
                    </p>
                </div>
                
                <div class="result-item">
                    <span class="result-label">📊 Güncel Fiyat:</span>
                    <span class="result-value">$${currentPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                </div>
                <div class="result-item">
                    <span class="result-label">🎯 Tahmin Fiyatı:</span>
                    <span class="result-value">$${predictedPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                </div>
                <div class="result-item">
                    <span class="result-label">💼 Mevcut Portföy Değeri:</span>
                    <span class="result-value">$${currentValue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                </div>
                <div class="result-item">
                    <span class="result-label">📈 Tahmin Edilen Portföy:</span>
                    <span class="result-value">$${predictedValue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                </div>
                <div class="result-item ${profitClass}" style="padding-top: 1rem; margin-top: 1rem; border-top: 2px solid rgba(255,255,255,0.1);">
                    <span class="result-label">${profitIcon} Beklenen Kâr/Zarar:</span>
                    <span class="result-value" style="font-size: 1.5rem; font-weight: 700;">
                        ${profit >= 0 ? '+' : ''}$${profit.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </span>
                </div>
                <div class="result-item ${profitClass}">
                    <span class="result-label">📊 Yüzde Değişim:</span>
                    <span class="result-value" style="font-size: 1.3rem; font-weight: 600;">
                        ${profit >= 0 ? '+' : ''}${profitPercent.toFixed(2)}%
                    </span>
                </div>
            </div>
        `;
    }

    updateAllDisplays() {
        console.log('📊 Tüm ekranlar güncelleniyor...');
        
        // Update stats (signals yüklendikten sonra - records değerini kullanır)
        this.updateStats();
        console.log('  ✓ Stats güncellendi (records:', this.data.signals?.records || 'N/A', ')');
        
        // Update market summary
        this.updateMarketSummary();
        console.log('  ✓ Market summary güncellendi');
        
        // Update predictions table
        this.updatePredictionsTable();
        console.log('  ✓ Predictions table güncellendi');
        
        // Update current analysis if we have bitcoin data
        if (this.data.bitcoin) {
            this.updateCurrentAnalysis(this.data.bitcoin);
            console.log('  ✓ Current analysis güncellendi');
        }
        
        console.log('✅ Tüm ekranlar güncellendi');
    }

    updateMarketSummary() {
        // API'den gelen gerçek değerleri kullan
        const avgConfidence = this.data.signals && this.data.signals.avgConf 
            ? this.data.signals.avgConf 
            : (this.data.predictions.length > 0 ? this.data.predictions.reduce((sum, p) => sum + p.confidence, 0) / this.data.predictions.length : 0);
        
        const totalRecords = this.data.signals && this.data.signals.records 
            ? this.data.signals.records 
            : this.data.predictions.length;
        
        const upRate = this.data.signals && this.data.signals.upRate !== undefined
            ? this.data.signals.upRate
            : 0.5;
        
        // Update model performance text
        const modelPerformanceElement = document.getElementById('modelPerformanceText');
        if (modelPerformanceElement) {
            // Yüksek güvenli tahmin sayısı (avg_conf > 0.8 ise kayıtların %80'i)
            const highAccuracyCount = avgConfidence > 0.8 
                ? Math.round(totalRecords * 0.8) 
                : Math.round(totalRecords * avgConfidence);
            
            const performanceText = `Model ${(avgConfidence * 100).toFixed(1)}% ortalama güvenle çalışıyor. ${highAccuracyCount} yüksek güvenli tahmin yapıldı.`;
            modelPerformanceElement.textContent = performanceText;
            
            console.log(`📊 Model Performansı: ${(avgConfidence * 100).toFixed(1)}% güven, ${highAccuracyCount}/${totalRecords} yüksek güvenli`);
        }

        // Update trend analysis - API'den gelen sinyal kullan
        const trendAnalysisElement = document.getElementById('trendAnalysisText');
        if (trendAnalysisElement) {
            let trendText = '';
            
            if (this.data.signals) {
                const signal = this.data.signals.signal || 'neutral';
                const signalText = this.data.signals.signalText || signal;
                const upRatePercent = (upRate * 100).toFixed(1);
                
                if (signal === 'bullish' || signalText.includes('YÜKSELİŞ')) {
                    trendText = `Piyasa güçlü yükseliş trendinde (%${upRatePercent} yükseliş oranı). AI modeli pozitif sinyaller veriyor.`;
                } else if (signal === 'bearish' || signalText.includes('DÜŞ')) {
                    trendText = `Piyasa düşüş trendinde (%${upRatePercent} yükseliş oranı). Dikkatli olunması önerilir.`;
                } else {
                    trendText = `Piyasa yan hareket ediyor (%${upRatePercent} yükseliş oranı). Belirsizlik devam ediyor.`;
                }
            } else {
                trendText = 'Trend analizi yükleniyor...';
            }
            
            trendAnalysisElement.textContent = trendText;
            console.log(`📈 Trend: ${trendText}`);
        }

        // Update risk level - API güveni kullan
        const riskLevelElement = document.getElementById('riskLevelText');
        if (riskLevelElement) {
            const riskLevel = avgConfidence > 0.8 ? 'Düşük' : avgConfidence > 0.6 ? 'Orta' : 'Yüksek';
            const riskColor = avgConfidence > 0.8 ? '#00ff88' : avgConfidence > 0.6 ? '#ffa500' : '#ff4444';
            const riskText = `Risk seviyesi: ${riskLevel}. Model güveni ${(avgConfidence * 100).toFixed(1)}% seviyesinde.`;
            
            riskLevelElement.textContent = riskText;
            riskLevelElement.style.color = riskColor;
            
            console.log(`⚠️ Risk: ${riskLevel} (${(avgConfidence * 100).toFixed(1)}% güven)`);
        }
    }

    startAutoRefresh() {
        this.refreshInterval = setInterval(async () => {
            console.log('🔄 Otomatik yenileme başlatılıyor...');
            await this.loadBitcoinData();
            await this.loadPredictions();
            await this.loadSignals();
            this.updateAllDisplays();
        }, 5 * 60000); // Refresh every 5 minutes
    }

    destroy() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
        }
    }
}

// Global functions for HTML onclick events
function calculateProfit() {
    if (window.pegosDashboard) {
        window.pegosDashboard.calculateProfit();
    }
}

// Initialize dashboard when DOM is loaded
let dashboard;
document.addEventListener('DOMContentLoaded', () => {
    dashboard = new PegosDashboard();
    window.pegosDashboard = dashboard;
    window.dashboard = dashboard; // Global erişim için
});

// Global pagination functions
function goToPage(page) {
    if (dashboard) dashboard.goToPage(page);
}

function nextPage() {
    if (dashboard) dashboard.nextPage();
}

function previousPage() {
    if (dashboard) dashboard.previousPage();
}

function changeItemsPerPage() {
    if (dashboard) dashboard.changeItemsPerPage();
}

function filterPredictions() {
    if (dashboard) dashboard.filterPredictions();
}

// Handle page unload
window.addEventListener('beforeunload', () => {
    if (window.pegosDashboard) {
        window.pegosDashboard.destroy();
    }
});