File size: 33,032 Bytes
37d6cb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gaming Dashboard - EDUrocks 3.0</title>
    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
    <style type="text/tailwindcss">
        @theme {
            --color-edu-dark: #011627;
            --color-edu-dark-secondary: #3C1642;
            --color-edu-dark-accent: #58355E;
            --color-edu-text: #e8d5e0;
            --color-edu-text-secondary: #c4a5b8;
            --color-edu-pink: #F4154D;
            --color-edu-pink-light: #FA0F71;
            --color-edu-rose: #FF1F84;
        }
    </style>
    <style>
        body {
            background: linear-gradient(135deg, #011627 0%, #3C1642 50%, #011627 100%);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }

        .glass-effect {
            background: rgba(60, 22, 66, 0.7);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(244, 21, 77, 0.1);
        }

        .stat-card {
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(255, 105, 180, 0.2);
        }

        .game-card {
            transition: all 0.2s ease;
        }

        .game-card:hover {
            transform: translateX(5px);
            border-color: rgba(255, 105, 180, 0.5);
        }

        .gradient-text {
            background: linear-gradient(45deg, #F4154D, #FA0F71, #e8d5e0, #FA0F71, #F4154D);
            background-size: 200% 200%;
            -webkit-background-clip: text;
            background-clip: text;
            -webkit-text-fill-color: transparent;
            animation: gradient 6s ease infinite;
        }
    </style>
</head>
<body class="bg-edu-dark text-edu-text min-h-screen">

    
    <nav class="glass-effect sticky top-0 z-50 border-b border-edu-pink/20">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
            <div class="flex items-center justify-between">
                
                <a href="index.html" class="text-2xl md:text-3xl font-black">
                    <span class="gradient-text">
                        EDUrocks
                    </span>
                    <span class="text-edu-text-secondary text-xl ml-2">/ Dashboard</span>
                </a>

                
                <div class="flex items-center gap-3 md:gap-4">
                    <span id="usernameDisplay" class="hidden sm:inline text-edu-text-secondary text-sm">Loading...</span>
                    <a href="page1.html" class="px-4 py-2 bg-gradient-to-r from-edu-pink to-edu-pink-light text-edu-text rounded-full text-sm font-medium transition-all hover:shadow-lg hover:scale-105">
                        Browse Gxmes
                    </a>
                </div>
            </div>
        </div>
    </nav>

    
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

        
        <section class="mb-8">
            <h1 class="text-3xl md:text-4xl font-bold mb-2">
                Welcome back, <span id="usernameWelcome" class="gradient-text">Player</span>!
            </h1>
            <p class="text-edu-text-secondary">Here's your gaming activity and stats</p>
        </section>

        
        <section class="mb-10">
            <h2 class="text-2xl font-bold mb-6 flex items-center gap-2">
                <span>๐Ÿ“Š</span>
                <span>Your Stats</span>
            </h2>
            <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">
                
                <div class="stat-card glass-effect rounded-2xl p-6 text-center">
                    <div class="text-5xl mb-3">โฑ๏ธ</div>
                    <div class="text-3xl md:text-4xl font-bold gradient-text" id="totalPlaytime">
                        <div class="animate-pulse">-</div>
                    </div>
                    <div class="text-sm text-edu-text-secondary mt-2">Total Playtime</div>
                </div>

                
                <div class="stat-card glass-effect rounded-2xl p-6 text-center">
                    <div class="text-5xl mb-3">๐ŸŽฎ</div>
                    <div class="text-3xl md:text-4xl font-bold gradient-text" id="gamesPlayed">
                        <div class="animate-pulse">-</div>
                    </div>
                    <div class="text-sm text-edu-text-secondary mt-2">Gxmes Played</div>
                </div>

                
                <div class="stat-card glass-effect rounded-2xl p-6 text-center">
                    <div class="text-5xl mb-3">โญ</div>
                    <div class="text-3xl md:text-4xl font-bold gradient-text" id="favorites">
                        <div class="animate-pulse">-</div>
                    </div>
                    <div class="text-sm text-edu-text-secondary mt-2">Favorites</div>
                </div>

                
                <div class="stat-card glass-effect rounded-2xl p-6 text-center">
                    <div class="text-5xl mb-3">๐Ÿ’พ</div>
                    <div class="text-3xl md:text-4xl font-bold gradient-text" id="cloudSaves">
                        <div class="animate-pulse">-</div>
                    </div>
                    <div class="text-sm text-edu-text-secondary mt-2">Cloud Saves</div>
                </div>
            </div>
        </section>

        
        <section class="mb-10">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-2xl font-bold flex items-center gap-2">
                    <span>๐Ÿ•</span>
                    <span>Recent Gxmes</span>
                </h2>
                <a href="page1.html" class="text-edu-pink hover:text-edu-pink-light transition-colors text-sm font-medium flex items-center gap-1">
                    Play More <span>โ†’</span>
                </a>
            </div>
            <div id="recentGxmes" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                
                <div class="col-span-2 text-center py-12">
                    <div class="animate-pulse text-edu-text-secondary">Loading recent games...</div>
                </div>
            </div>
        </section>

        
        <section class="mb-10">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-2xl font-bold flex items-center gap-2">
                    <span>๐Ÿ’พ</span>
                    <span>Your Saved Gxmes</span>
                </h2>
                <button onclick="forceSyncAllGxmes()" class="text-edu-pink hover:text-edu-pink-light transition-colors text-sm font-medium flex items-center gap-1">
                    <span>๐Ÿ”„</span> Force Sync
                </button>
            </div>
            <div id="savedGxmes" class="space-y-3">
                
                <div class="text-center py-12">
                    <div class="animate-pulse text-edu-text-secondary">Loading saved games...</div>
                </div>
            </div>
        </section>

    </main>

    
    <footer class="border-t border-edu-pink/20 py-6 mt-16">
        <div class="container mx-auto px-4 md:px-6 text-center text-edu-text-secondary text-sm">
            <p>ยฉ 2025 EDUrocks Group - Your data is synced across all devices</p>
        </div>
    </footer>

    
    <script src="./assets/js/aws-detection.js"></script>
    <script type="module">
        import { Auth } from './assets/js/auth.js';
        window.Auth = Auth;

        // Get API URL with domain detection
        function getGameApiUrl() {
            if (window.eduBackendOverride) {
                // Override is userauth/api.php, but we need userauth/game-api.php
                return window.eduBackendOverride.replace('api.php', 'game-api.php');
            }

            const hostname = window.location.hostname;
            const isIP = /^(\d{1,3}\.){3}\d{1,3}$/.test(hostname) || /^[0-9a-fA-F:]+$/.test(hostname);
            const isLocal = hostname === 'localhost' ||
                           hostname.endsWith('.local') ||
                           hostname === '127.0.0.1' ||
                           hostname === '::1';

            if (hostname === 'devbuild.edurocks.org' || isIP || isLocal) {
                return 'https://backendapi.edurocks.org/userauth/game-api.php';
            }

            const domain = hostname.replace(/^www\./, "");
            return `https://backendapi.${domain}/userauth/game-api.php`;
        }

        const GAME_API_URL = getGameApiUrl();

        // Format helpers
        function formatPlaytime(seconds) {
            if (!seconds || seconds === 0) return '0s';
            if (seconds < 60) return Math.floor(seconds) + 's';
            if (seconds < 3600) return Math.floor(seconds / 60) + 'm';
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            return minutes > 0 ? hours + 'h ' + minutes + 'm' : hours + 'h';
        }

        function formatDate(dateString) {
            if (!dateString) return 'Unknown';

            // Parse date - handle both UTC and local timestamps
            let date;
            if (dateString.includes('Z') || dateString.includes('+') || dateString.includes('-')) {
                // ISO format with timezone
                date = new Date(dateString);
            } else {
                // Assume UTC if no timezone specified (MySQL TIMESTAMP format)
                date = new Date(dateString + ' UTC');
            }

            // Check if date is valid
            if (isNaN(date.getTime())) return 'Unknown';

            // Get current time in user's timezone
            const now = new Date();

            // Calculate difference in milliseconds
            const diffMs = now - date;

            // If date is in the future (clock skew tolerance: 5 seconds)
            if (diffMs < -5000) return 'Just now';
            if (diffMs < 0) return 'Just now';

            // Calculate time units
            const diffSeconds = Math.floor(diffMs / 1000);
            const diffMinutes = Math.floor(diffMs / (1000 * 60));
            const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
            const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
            const diffWeeks = Math.floor(diffDays / 7);
            const diffMonths = Math.floor(diffDays / 30);
            const diffYears = Math.floor(diffDays / 365);

            // Return appropriate format based on time elapsed
            if (diffSeconds < 10) return 'Just now';
            if (diffSeconds < 60) return diffSeconds + 's ago';
            if (diffMinutes === 1) return '1 min ago';
            if (diffMinutes < 60) return diffMinutes + ' min ago';
            if (diffHours === 1) return '1 hour ago';
            if (diffHours < 24) return diffHours + ' hours ago';
            if (diffDays === 1) return 'Yesterday';
            if (diffDays < 7) return diffDays + ' days ago';
            if (diffWeeks === 1) return '1 week ago';
            if (diffWeeks < 4) return diffWeeks + ' weeks ago';
            if (diffMonths === 1) return '1 month ago';
            if (diffMonths < 12) return diffMonths + ' months ago';
            if (diffYears === 1) return '1 year ago';
            return diffYears + ' years ago';
        }

        function formatBytes(bytes) {
            if (!bytes) return '0 B';
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
            return (bytes / 1024 / 1024).toFixed(1) + ' MB';
        }

        // Check authentication
        async function init() {
            console.log('[Dashboard] Initializing...');

            if (!Auth.isLoggedIn()) {
                console.log('[Dashboard] Not logged in, redirecting...');
                window.location.href = 'login.html';
                return;
            }

            const username = Auth.getUsername();
            console.log('[Dashboard] Logged in as:', username);

            document.getElementById('usernameDisplay').textContent = username;
            document.getElementById('usernameWelcome').textContent = username;

            // Load all data
            await Promise.all([
                loadStats(),
                loadRecentGxmes(),
                loadSavedGxmes()
            ]);

            console.log('[Dashboard] All data loaded');
        }

        // Load user stats
        async function loadStats() {
            try {
                console.log('[Dashboard] Loading stats...');
                const stats = await Auth.getUserStats();
                console.log('[Dashboard] Stats received:', stats);

                // Total playtime
                const playtime = stats.totalPlayTime || stats.total_play_time || 0;
                document.getElementById('totalPlaytime').textContent = formatPlaytime(parseInt(playtime));

                // Gxmes played
                const gamesPlayed = stats.totalGxmesPlayed || stats.unique_games || 0;
                document.getElementById('gamesPlayed').textContent = parseInt(gamesPlayed).toLocaleString();

                // Favorites count
                const favCount = stats.favoritesCount || stats.favorites_count || 0;
                document.getElementById('favorites').textContent = parseInt(favCount).toLocaleString();

                // Get cloud saves count
                const token = Auth.getToken();
                const response = await fetch(GAME_API_URL + '?action=listAllSaves&token=' + token, {
                    credentials: 'include'
                });
                const data = await response.json();

                let saveCount = 0;
                if (data.success && data.games) {
                    saveCount = data.games.reduce((acc, game) => acc + parseInt(game.save_count || 0), 0);
                }

                document.getElementById('cloudSaves').textContent = saveCount.toLocaleString();
                console.log('[Dashboard] Stats loaded successfully');
            } catch (error) {
                console.error('[Dashboard] Failed to load stats:', error);
                document.getElementById('totalPlaytime').textContent = '0h';
                document.getElementById('gamesPlayed').textContent = '0';
                document.getElementById('favorites').textContent = '0';
                document.getElementById('cloudSaves').textContent = '0';
            }
        }

        // Load recent games
        async function loadRecentGxmes() {
            try {
                console.log('[Dashboard] Loading recent games...');
                const stats = await Auth.getUserStats();
                const recentGxmesEl = document.getElementById('recentGxmes');

                console.log('[Dashboard] Recent games data:', stats.recentGxmes);

                if (stats.recentGxmes && stats.recentGxmes.length > 0) {
                    recentGxmesEl.innerHTML = stats.recentGxmes.slice(0, 6).map(game => {
                        const gameUrl = './filestorage/gd/' + encodeURIComponent(game.game_id) + '/index.html';
                        const gameIcon = game.game_image || './filestorage/gd/' + encodeURIComponent(game.game_id) + '/icon.png';
                        return '<a href="' + gameUrl + '" class="game-card glass-effect rounded-xl p-5 border border-edu-pink/10 block hover:bg-edu-rose transition-all">' +
                            '<div class="flex items-center justify-between">' +
                                '<div class="flex items-center gap-4">' +
                                    '<div class="w-14 h-14 rounded-xl overflow-hidden flex-shrink-0 bg-edu-dark-secondary">' +
                                        '<img src="' + gameIcon + '" alt="' + (game.game_name || game.game_id) + '" class="w-full h-full object-contain" onerror="var p=this.parentElement; p.innerHTML=\'๐ŸŽฎ\'; p.classList.add(\'flex\', \'items-center\', \'justify-center\', \'text-2xl\');">' +
                                    '</div>' +
                                    '<div>' +
                                        '<div class="text-edu-text font-semibold text-lg">' + (game.game_name || game.game_id) + '</div>' +
                                        '<div class="text-sm text-edu-text-secondary">' + formatDate(game.last_played) + '</div>' +
                                    '</div>' +
                                '</div>' +
                                '<div class="text-right">' +
                                    '<div class="text-edu-pink font-bold text-lg">' + formatPlaytime(parseInt(game.total_time || 0)) + '</div>' +
                                    '<div class="text-xs text-edu-text-secondary">played</div>' +
                                '</div>' +
                            '</div>' +
                        '</a>';
                    }).join('');
                } else {
                    recentGxmesEl.innerHTML = '<div class="col-span-2 glass-effect rounded-xl p-12 text-center border border-edu-pink/10">' +
                            '<div class="text-6xl mb-4">๐ŸŽฎ</div>' +
                            '<div class="text-edu-text-secondary text-lg">No games played yet</div>' +
                            '<a href="page1.html" class="inline-block mt-4 px-6 py-3 bg-gradient-to-r from-edu-pink to-edu-pink-light text-edu-text rounded-full font-medium hover:shadow-lg transition-all">' +
                                'Browse Gxmes' +
                            '</a>' +
                        '</div>';
                }
                console.log('[Dashboard] Recent games loaded');
            } catch (error) {
                console.error('[Dashboard] Failed to load recent games:', error);
                document.getElementById('recentGxmes').innerHTML = '<div class="col-span-2 glass-effect rounded-xl p-8 text-center border border-red-500/20">' +
                        '<div class="text-red-400">Failed to load recent games</div>' +
                        '<div class="text-sm text-edu-text-secondary mt-2">' + error.message + '</div>' +
                    '</div>';
            }
        }

        // Load all saved games
        async function loadSavedGxmes() {
            try {
                console.log('[Dashboard] Loading saved games...');
                const token = Auth.getToken();
                const response = await fetch(GAME_API_URL + '?action=listAllSaves&token=' + token, {
                    credentials: 'include'
                });
                const data = await response.json();
                const savedGxmesEl = document.getElementById('savedGxmes');

                console.log('[Dashboard] Saved games data:', data);

                if (data.success && data.games && data.games.length > 0) {
                    savedGxmesEl.innerHTML = data.games.map(game => '<div class="game-card glass-effect rounded-xl p-5 border border-edu-pink/10">' +
                            '<div class="flex items-center justify-between">' +
                                '<div class="flex items-center gap-4 flex-1">' +
                                    '<div class="w-12 h-12 bg-gradient-to-br from-edu-pink to-edu-pink-light rounded-xl flex items-center justify-center text-xl flex-shrink-0">๐Ÿ’พ</div>' +
                                    '<div class="flex-1">' +
                                        '<div class="text-edu-text font-semibold text-lg">' + game.game_id + '</div>' +
                                        '<div class="text-sm text-edu-text-secondary">' +
                                            game.save_count + ' save' + (parseInt(game.save_count) !== 1 ? 's' : '') + ' โ€ข ' +
                                            formatBytes(parseInt(game.total_size || 0)) + ' โ€ข ' +
                                            'Updated ' + formatDate(game.last_modified) +
                                        '</div>' +
                                    '</div>' +
                                '</div>' +
                                '<button onclick="viewGameSaves(\'' + game.game_id + '\')" class="px-5 py-2.5 bg-edu-pink/20 text-edu-pink hover:bg-edu-pink hover:text-edu-text rounded-lg transition-all font-medium flex-shrink-0">' +
                                    'View Saves' +
                                '</button>' +
                            '</div>' +
                        '</div>').join('');
                } else {
                    savedGxmesEl.innerHTML = '<div class="glass-effect rounded-xl p-12 text-center border border-edu-pink/10">' +
                            '<div class="text-6xl mb-4">๐Ÿ’พ</div>' +
                            '<div class="text-edu-text-secondary text-lg mb-2">No saved games yet</div>' +
                            '<div class="text-sm text-edu-text-secondary">Play some games to sync your saves automatically!</div>' +
                        '</div>';
                }
                console.log('[Dashboard] Saved games loaded');
            } catch (error) {
                console.error('[Dashboard] Failed to load saved games:', error);
                document.getElementById('savedGxmes').innerHTML = '<div class="glass-effect rounded-xl p-8 text-center border border-red-500/20">' +
                        '<div class="text-red-400">Failed to load saved games</div>' +
                        '<div class="text-sm text-edu-text-secondary mt-2">' + error.message + '</div>' +
                    '</div>';
            }
        }

        // View individual game saves
        window.viewGameSaves = async function(gameId) {
            try {
                console.log('[Dashboard] Loading saves for game:', gameId);
                const token = Auth.getToken();
                const response = await fetch(GAME_API_URL + '?action=getGameSaves&gameId=' + encodeURIComponent(gameId) + '&token=' + token, {
                    credentials: 'include'
                });
                const data = await response.json();

                console.log('[Dashboard] Game saves data:', data);

                if (data.success && data.saves && data.saves.length > 0) {
                    const savesHtml = data.saves.map(save => {
                        let deviceInfo = '';
                        try {
                            const device = JSON.parse(save.device_info || '{}');
                            deviceInfo = device.browser ? '<span>๐Ÿ’ป ' + device.browser + '</span>' : '';
                        } catch (e) {}

                        return '<div class="bg-edu-dark/50 rounded-lg p-4 border border-edu-pink/10 hover:border-edu-pink/30 transition-all">' +
                            '<div class="flex items-center justify-between">' +
                                '<div class="flex-1">' +
                                    '<div class="text-edu-text font-medium mb-1">' + save.save_key.replace(/^(localStorage:|indexedDB:)/, '') + '</div>' +
                                    '<div class="text-xs text-edu-text-secondary flex items-center gap-3">' +
                                        '<span>๐Ÿ“ฆ ' + formatBytes(parseInt(save.size || 0)) + '</span>' +
                                        '<span>๐Ÿ• ' + formatDate(save.last_modified) + '</span>' +
                                        deviceInfo +
                                    '</div>' +
                                '</div>' +
                                '<button onclick="viewSaveHistoryDashboard(\'' + gameId + '\', \'' + save.save_key + '\')" class="ml-3 px-4 py-2 bg-edu-pink/20 text-edu-pink hover:bg-edu-pink hover:text-edu-text rounded-lg transition-all text-sm font-medium">' +
                                    '๐Ÿ“œ History' +
                                '</button>' +
                            '</div>' +
                        '</div>';
                    }).join('');

                    // Show modal
                    const modal = document.createElement('div');
                    modal.className = 'fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4';
                    modal.innerHTML = '<div class="glass-effect rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-hidden flex flex-col">' +
                            '<div class="bg-gradient-to-r from-edu-pink to-edu-pink-light p-5 flex items-center justify-between">' +
                                '<h3 class="text-2xl font-bold text-edu-text">' + gameId + ' - Saved Data</h3>' +
                                '<button onclick="this.closest(\'.fixed\').remove()" class="text-edu-text hover:text-white text-3xl leading-none transition-colors">&times;</button>' +
                            '</div>' +
                            '<div class="p-6 space-y-3 overflow-y-auto">' +
                                '<div class="text-edu-text-secondary text-sm mb-4">' +
                                    data.saves.length + ' save' + (data.saves.length !== 1 ? 's' : '') + ' found' +
                                '</div>' +
                                savesHtml +
                            '</div>' +
                        '</div>';
                    modal.onclick = (e) => { if (e.target === modal) modal.remove(); };
                    document.body.appendChild(modal);
                } else {
                    alert('No saves found for this game');
                }
            } catch (error) {
                console.error('[Dashboard] Failed to load game saves:', error);
                alert('Failed to load saves for this game: ' + error.message);
            }
        };

        window.refreshSaves = loadSavedGxmes;

        // Force sync all games
        window.forceSyncAllGxmes = async function() {
            try {
                console.log('[Dashboard] Force sync requested');
                const btn = event.target.closest('button');
                const originalText = btn.innerHTML;
                btn.innerHTML = '<span>โณ</span> Syncing...';
                btn.disabled = true;

                // Just reload the saves - the sync happens automatically in games
                await loadSavedGxmes();

                btn.innerHTML = '<span>โœ…</span> Synced!';
                setTimeout(() => {
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }, 2000);

                console.log('[Dashboard] Force sync complete');
            } catch (error) {
                console.error('[Dashboard] Force sync error:', error);
                alert('Force sync failed: ' + error.message);
            }
        };

        // View save history from dashboard
        window.viewSaveHistoryDashboard = async function(gameId, saveKey) {
            try {
                console.log('[Dashboard] Loading history for:', gameId, saveKey);
                const token = Auth.getToken();
                const response = await fetch(GAME_API_URL + '?action=getHistory&gameId=' + encodeURIComponent(gameId) + '&saveKey=' + encodeURIComponent(saveKey) + '&token=' + token, {
                    credentials: 'include'
                });
                const data = await response.json();

                console.log('[Dashboard] History data:', data);

                if (!data.success || !data.history || data.history.length === 0) {
                    alert('No history found for this save slot. History is created when you modify existing saves.');
                    return;
                }

                const saveKeyDisplay = saveKey.replace(/^(localStorage:|indexedDB:)/, '');

                // Build history list HTML
                const historyHtml = data.history.map(entry => {
                    const timestamp = new Date(entry.saved_at).toLocaleString();
                    const clientTimestamp = entry.client_timestamp ? new Date(entry.client_timestamp).toLocaleString() : 'N/A';

                    return '<div class="bg-edu-dark/50 rounded-lg p-4 border border-edu-pink/10 hover:border-edu-pink/30 transition-all">' +
                        '<div class="flex items-center justify-between">' +
                            '<div class="flex-1">' +
                                '<div class="text-edu-text font-semibold mb-1">Version #' + entry.id + '</div>' +
                                '<div class="text-xs text-edu-text-secondary">' +
                                    '<div>๐Ÿ• Server: ' + timestamp + '</div>' +
                                    '<div>๐Ÿ’ป Client: ' + clientTimestamp + '</div>' +
                                '</div>' +
                            '</div>' +
                            '<button onclick="restoreFromHistoryDashboard(' + entry.id + ', \'' + gameId + '\', \'' + saveKey + '\')" class="ml-3 px-4 py-2 bg-green-500/20 text-green-400 hover:bg-green-500 hover:text-white rounded-lg transition-all text-sm font-bold">' +
                                'โ†ป Restore' +
                            '</button>' +
                        '</div>' +
                    '</div>';
                }).join('');

                // Show modal
                const modal = document.createElement('div');
                modal.className = 'fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4';
                modal.id = 'history-modal-dashboard';
                modal.innerHTML = '<div class="glass-effect rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-hidden flex flex-col">' +
                        '<div class="bg-gradient-to-r from-edu-pink to-edu-pink-light p-5 flex items-center justify-between">' +
                            '<div>' +
                                '<h3 class="text-2xl font-bold text-edu-text">๐Ÿ“œ History: ' + saveKeyDisplay + '</h3>' +
                                '<div class="text-edu-text-secondary text-sm mt-1">' + gameId + '</div>' +
                            '</div>' +
                            '<button onclick="this.closest(\'.fixed\').remove()" class="text-edu-text hover:text-white text-3xl leading-none transition-colors">&times;</button>' +
                        '</div>' +
                        '<div class="p-6 space-y-3 overflow-y-auto">' +
                            '<div class="text-edu-text-secondary text-sm mb-4">' +
                                'Found ' + data.history.length + ' previous version(s). Click "Restore" to load an older save.' +
                            '</div>' +
                            historyHtml +
                        '</div>' +
                    '</div>';
                modal.onclick = (e) => { if (e.target === modal) modal.remove(); };
                document.body.appendChild(modal);

            } catch (error) {
                console.error('[Dashboard] Failed to load history:', error);
                alert('Failed to load history: ' + error.message);
            }
        };

        // Restore from history in dashboard
        window.restoreFromHistoryDashboard = async function(historyId, gameId, saveKey) {
            if (!confirm('This will replace the current save with this older version. The game will need to be reloaded. Continue?')) {
                return;
            }

            try {
                console.log('[Dashboard] Restoring history ID:', historyId);
                const token = Auth.getToken();
                const response = await fetch(GAME_API_URL + '?action=restoreHistory', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    },
                    credentials: 'include',
                    body: JSON.stringify({ historyId })
                });

                const data = await response.json();

                if (!data.success) {
                    throw new Error(data.error || 'Failed to restore');
                }

                console.log('[Dashboard] Restore successful:', data);

                // Close modal
                const modal = document.getElementById('history-modal-dashboard');
                if (modal) modal.remove();

                // Show success message
                alert('Save restored successfully! When you next load ' + gameId + ', it will use this restored save.');

                // Refresh the saves list
                await loadSavedGxmes();

            } catch (error) {
                console.error('[Dashboard] Failed to restore:', error);
                alert('Failed to restore save: ' + error.message);
            }
        };

        // Initialize on load
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>