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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Monetization Toolkit JavaScript
// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    setupEventListeners();
    initializeCharts();
    updateDashboardData();
    
    // Handle hash-based navigation
    window.addEventListener('hashchange', function() {
        const section = window.location.hash.substring(1);
        if (section) {
            showSection(section);
        }
    });

    // Initial section based on hash
    if (window.location.hash) {
        showSection(window.location.hash.substring(1));
    }
});
// Global variables
let currentSection = 'dashboard';
let charts = {};
let timeRange = '7d';

// Initialize the application
function initializeApp() {
    // Set default section
    showSection('dashboard');
    
    // Initialize with sample data
    updateKPIs();
    updateCharts();
    
    // Set up periodic updates
    setInterval(updateKPIs, 30000); // Update every 30 seconds
}

// Setup event listeners
function setupEventListeners() {
    // Navigation
    document.getElementById('region-select').addEventListener('change', function() {
        updateRegionData(this.value);
    });
    
    // A/B Test Form
    document.getElementById('ab-test-form').addEventListener('submit', function(e) {
        e.preventDefault();
        createNewTest();
    });
    
    // Modal buttons
    document.getElementById('watch-ad-btn').addEventListener('click', function() {
        simulateAdWatching();
    });
    
    document.getElementById('complete-purchase-btn').addEventListener('click', function() {
        completePurchase();
    });
    
    // Ad modal close on backdrop click
    document.getElementById('ad-modal').addEventListener('click', function(e) {
        if (e.target === this) closeAdModal();
    });
    
    document.getElementById('purchase-modal').addEventListener('click', function(e) {
        if (e.target === this) closePurchaseModal();
    });
}

// Section navigation
function showSection(sectionName) {
    // Hide all sections
    const sections = document.querySelectorAll('.content-section');
    sections.forEach(section => {
        section.classList.add('hidden');
    });
    
    // Show selected section
    document.getElementById(sectionName).classList.remove('hidden');
    
    // Update navigation
    const navButtons = document.querySelectorAll('.nav-btn');
    navButtons.forEach(btn => {
        btn.classList.remove('active');
    });
    
    event.target.classList.add('active');
    currentSection = sectionName;
    
    // Update charts if needed
    if (sectionName === 'analytics') {
        updateAnalyticsCharts();
    }
}

// Update KPIs
function updateKPIs() {
    const kpis = {
        'daily-revenue': generateRandomValue(2500, 3200, '$'),
        'active-users': generateRandomValue(14500, 15800, ''),
        'conversion-rate': generateRandomValue(2.8, 3.6, '%'),
        'arpu': generateRandomValue(0.15, 0.22, '$')
    };
    
    Object.keys(kpis).forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            animateValue(element, element.textContent, kpis[id]);
        }
    });
}

// Generate random values for simulation
function generateRandomValue(min, max, prefix = '') {
    const value = (Math.random() * (max - min) + min).toFixed(max < 10 ? 2 : 0);
    return prefix + value;
}

// Animate value changes
function animateValue(element, start, end) {
    const startTime = performance.now();
    const duration = 1000;
    
    function updateValue(currentTime) {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);
        
        // Simple interpolation
        const startNum = parseFloat(start.replace(/[^\d.-]/g, '')) || 0;
        const endNum = parseFloat(end.replace(/[^\d.-]/g, '')) || 0;
        const current = startNum + (endNum - startNum) * progress;
        
        const prefix = start.match(/^[^\d]*/)?.[0] || '';
        const suffix = start.match(/[^\d]*$/)?.[0] || '';
        
        element.textContent = prefix + current.toFixed(start.includes('%') ? 2 : start.includes('$') && startNum < 1 ? 3 : 0) + suffix;
        
        if (progress < 1) {
            requestAnimationFrame(updateValue);
        }
    }
    
    requestAnimationFrame(updateValue);
}

// Initialize Charts
function initializeCharts() {
    // Revenue Chart
    const revenueCtx = document.getElementById('revenue-chart');
    if (revenueCtx) {
        charts.revenue = new Chart(revenueCtx, {
            type: 'line',
            data: {
                labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                datasets: [{
                    label: 'Revenue',
                    data: generateChartData(7, 2000, 3000),
                    borderColor: '#ec4899',
                    backgroundColor: 'rgba(236, 72, 153, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: false,
                        ticks: {
                            callback: function(value) {
                                return '$' + value;
                            }
                        }
                    }
                }
            }
        });
    }
    
    // User Chart
    const userCtx = document.getElementById('user-chart');
    if (userCtx) {
        charts.user = new Chart(userCtx, {
            type: 'bar',
            data: {
                labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                datasets: [{
                    label: 'New Users',
                    data: generateChartData(7, 500, 1000),
                    backgroundColor: '#14b8a6',
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
    
    // Ads Performance Chart
    const adsCtx = document.getElementById('ads-performance-chart');
    if (adsCtx) {
        charts.ads = new Chart(adsCtx, {
            type: 'doughnut',
            data: {
                labels: ['Completed', 'Skipped', 'Failed'],
                datasets: [{
                    data: [75, 20, 5],
                    backgroundColor: ['#14b8a6', '#ec4899', '#f3f4f6'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }
    
    // Purchase Chart
    const purchaseCtx = document.getElementById('purchase-chart');
    if (purchaseCtx) {
        charts.purchase = new Chart(purchaseCtx, {
            type: 'pie',
            data: {
                labels: ['Starter Pack', 'Value Pack', 'Mega Pack'],
                datasets: [{
                    data: [25, 45, 30],
                    backgroundColor: ['#ec4899', '#14b8a6', '#f3f4f6'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }
    
    // Analytics Charts
    initializeAnalyticsCharts();
}

// Initialize Analytics Charts
function initializeAnalyticsCharts() {
    // Revenue Source Chart
    const revenueSourceCtx = document.getElementById('revenue-source-chart');
    if (revenueSourceCtx) {
        charts.revenueSource = new Chart(revenueSourceCtx, {
            type: 'bar',
            data: {
                labels: ['Rewarded Ads', 'In-App Purchases', 'Subscriptions'],
                datasets: [{
                    label: 'Revenue ($)',
                    data: [15000, 25000, 8000],
                    backgroundColor: ['#ec4899', '#14b8a6', '#f3f4f6'],
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                indexAxis: 'y',
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }
    
    // Retention Chart
    const retentionCtx = document.getElementById('retention-chart');
    if (retentionCtx) {
        charts.retention = new Chart(retentionCtx, {
            type: 'line',
            data: {
                labels: ['Day 1', 'Day 3', 'Day 7', 'Day 14', 'Day 30'],
                datasets: [{
                    label: 'Retention Rate',
                    data: [100, 65, 45, 35, 28],
                    borderColor: '#14b8a6',
                    backgroundColor: 'rgba(20, 184, 166, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        ticks: {
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    }
                }
            }
        });
    }
}

// Generate chart data
function generateChartData(days, min, max) {
    const data = [];
    for (let i = 0; i < days; i++) {
        data.push(Math.floor(Math.random() * (max - min) + min));
    }
    return data;
}

// Update charts
function updateCharts() {
    Object.keys(charts).forEach(chartKey => {
        if (charts[chartKey]) {
            // Update with new data
            if (chartKey === 'revenue') {
                charts[chartKey].data.datasets[0].data = generateChartData(7, 2000, 3000);
            } else if (chartKey === 'user') {
                charts[chartKey].data.datasets[0].data = generateChartData(7, 500, 1000);
            }
            charts[chartKey].update('none');
        }
    });
}

// Update analytics charts
function updateAnalyticsCharts() {
    // Add some animation to charts when section is shown
    Object.keys(charts).forEach(chartKey => {
        if (charts[chartKey] && charts[chartKey].canvas.closest('#analytics')) {
            charts[chartKey].update('active');
        }
    });
}

// Time range update
function updateTimeRange(range) {
    timeRange = range;
    
    // Update button states
    const buttons = document.querySelectorAll('.time-range-btn');
    buttons.forEach(btn => {
        btn.classList.remove('bg-pink-500', 'text-white');
        btn.classList.add('bg-gray-200', 'text-gray-700');
    });
    
    event.target.classList.remove('bg-gray-200', 'text-gray-700');
    event.target.classList.add('bg-pink-500', 'text-white');
    
    // Update charts with new time range
    updateChartsForTimeRange(range);
}

// Update charts for specific time range
function updateChartsForTimeRange(range) {
    let days, min, max;
    
    switch(range) {
        case '7d':
            days = 7;
            min = 2000;
            max = 3000;
            break;
        case '30d':
            days = 30;
            min = 1800;
            max = 3200;
            break;
        case '90d':
            days = 90;
            min = 1600;
            max = 3400;
            break;
    }
    
    if (charts.revenue) {
        charts.revenue.data.labels = generateTimeLabels(days);
        charts.revenue.data.datasets[0].data = generateChartData(days, min, max);
        charts.revenue.update('active');
    }
}

// Generate time labels
function generateTimeLabels(days) {
    const labels = [];
    const today = new Date();
    
    for (let i = days - 1; i >= 0; i--) {
        const date = new Date(today);
        date.setDate(date.getDate() - i);
        labels.push(date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }));
    }
    
    return labels;
}

// Create new A/B test
function createNewTest() {
    const form = document.getElementById('ab-test-form');
    const formData = new FormData(form);
    
    // Simulate test creation
    showNotification('A/B Test created successfully!', 'success');
    form.reset();
    
    // Add to active tests list (simulation)
    setTimeout(() => {
        updateActiveTests();
    }, 1000);
}

// Update active tests list
function updateActiveTests() {
    // This would typically fetch from an API
    console.log('Updating active tests...');
}

// Region data update
function updateRegionData(region) {
    // Simulate region-specific data updates
    showNotification(`Region changed to ${region.toUpperCase()}`, 'info');
    
    // Update KPIs based on region
    updateKPIsForRegion(region);
}

// Update KPIs for specific region
function updateKPIsForRegion(region) {
    const regionMultipliers = {
        'global': 1.0,
        'us': 1.2,
        'eu': 1.1,
        'asia': 0.8,
        'latam': 0.6
    };
    
    const multiplier = regionMultipliers[region] || 1.0;
    
    // Update with regional data
    const baseValues = {
        'daily-revenue': 2847,
        'active-users': 15234,
        'conversion-rate': 3.24,
        'arpu': 0.187
    };
    
    Object.keys(baseValues).forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            const baseValue = baseValues[id];
            const newValue = baseValue * multiplier * (0.9 + Math.random() * 0.2);
            
            let formattedValue;
            if (id === 'daily-revenue') {
                formattedValue = '$' + newValue.toFixed(0);
            } else if (id === 'active-users') {
                formattedValue = Math.round(newValue).toLocaleString();
            } else if (id === 'conversion-rate') {
                formattedValue = newValue.toFixed(2) + '%';
            } else if (id === 'arpu') {
                formattedValue = '$' + newValue.toFixed(3);
            }
            
            animateValue(element, element.textContent, formattedValue);
        }
    });
}

// Simulate ad watching
function simulateAdWatching() {
    const button = document.getElementById('watch-ad-btn');
    const originalText = button.textContent;
    
    button.disabled = true;
    button.innerHTML = '<div class="spinner mx-auto"></div>';
    
    // Simulate ad duration
    setTimeout(() => {
        button.textContent = 'Ad Complete!';
        button.classList.remove('bg-pink-500', 'hover:bg-pink-600');
        button.classList.add('bg-green-500', 'hover:bg-green-600');
        
        setTimeout(() => {
            closeAdModal();
            showNotification('Ad watched successfully! +3 extra lives', 'success');
            button.textContent = originalText;
            button.disabled = false;
            button.classList.remove('bg-green-500', 'hover:bg-green-600');
            button.classList.add('bg-pink-500', 'hover:bg-pink-600');
        }, 1500);
    }, 3000);
}

// Complete purchase
function completePurchase() {
    const button = document.getElementById('complete-purchase-btn');
    const originalText = button.textContent;
    
    button.disabled = true;
    button.innerHTML = '<div class="spinner mx-auto"></div>';
    
    // Simulate purchase processing
    setTimeout(() => {
        button.textContent = 'Purchase Complete!';
        button.classList.remove('bg-teal-500', 'hover:bg-teal-600');
        button.classList.add('bg-green-500', 'hover:bg-green-600');
        
        setTimeout(() => {
            closePurchaseModal();
            showNotification('Purchase successful! 2,500 coins added to your account', 'success');
            button.textContent = originalText;
            button.disabled = false;
            button.classList.remove('bg-green-500', 'hover:bg-green-600');
            button.classList.add('bg-teal-500', 'hover:bg-teal-600');
        }, 1500);
    }, 2000);
}

// Modal functions
function closeAdModal() {
    document.getElementById('ad-modal').classList.add('hidden');
}

function closePurchaseModal() {
    document.getElementById('purchase-modal').classList.add('hidden');
}

// Show notification
function showNotification(message, type = 'info') {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg max-w-sm transform transition-all duration-300 translate-x-full`;
    
    // Set colors based on type
    switch(type) {
        case 'success':
            notification.classList.add('bg-green-500', 'text-white');
            break;
        case 'error':
            notification.classList.add('bg-red-500', 'text-white');
            break;
        case 'warning':
            notification.classList.add('bg-yellow-500', 'text-white');
            break;
        default:
            notification.classList.add('bg-blue-500', 'text-white');
    }
    
    notification.innerHTML = `
        <div class="flex items-center">
            <div class="flex-1">${message}</div>
            <button onclick="this.parentElement.parentElement.remove()" class="ml-3 text-white hover:text-gray-200">
                <i data-feather="x"></i>
            </button>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // Animate in
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 100);
    
    // Auto remove after 5 seconds
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 300);
    }, 5000);
    
    // Refresh feather icons
    if (typeof feather !== 'undefined') {
        feather.replace();
    }
}

// Dashboard data updates
function updateDashboardData() {
    // Simulate real-time data updates
    setInterval(() => {
        if (currentSection === 'dashboard') {
            updateKPIs();
            updateCharts();
        }
    }, 10000); // Update every 10 seconds
}

// Export functions for testing (if needed)
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        generateRandomValue,
        animateValue,
        showNotification
    };
}