
    document.addEventListener('DOMContentLoaded', function() {

        const isArabic = tsAdminData.isArabic;

        const API_BASE = tsAdminData.apiBaseUrl;

        const HEADERS = {

            'Authorization': 'Bearer ' + tsAdminData.token,

            'X-Api-Key': tsAdminData.apiKey

        };



        // UI Translation Helpers

        const trans = (key) => {

            const dict = {
                'totalTickets': isArabic ? 'إجمالي التذاكر' : 'Total Tickets',
                'open': isArabic ? 'مفتوح' : 'Open',
                'inProgress': isArabic ? 'جاري العمل' : 'In Progress',
                'pending': isArabic ? 'قيد الانتظار' : 'Pending',
                'closed': isArabic ? 'مغلق' : 'Closed',
                'avgResolution': isArabic ? 'متوسط وقت الحل' : 'Avg. Resolution Time',
                'hours': isArabic ? 'ساعة' : 'h',
                'days': isArabic ? 'يوم' : 'days',
                'assigned': isArabic ? 'المعينة' : 'Assigned',
                'resolved': isArabic ? 'المحلولة' : 'Resolved',
                'low': isArabic ? 'منخفض' : 'Low',
                'medium': isArabic ? 'متوسط' : 'Medium',
                'high': isArabic ? 'عالي' : 'High',
                'volume': isArabic ? 'حجم التذاكر' : 'Ticket Volume',
                'general': isArabic ? 'عام' : 'General',
                'technical': isArabic ? 'الدعم الفني' : 'Technical Support',
                'billing': isArabic ? 'الحسابات' : 'Billing',
                'sales': isArabic ? 'المبيعات' : 'Sales',
                'unassigned': isArabic ? 'غير معين' : 'Unassigned'
            };

            return dict[key] || key;

        };



        // Theme and Grid settings

        Chart.defaults.font.family = isArabic ? "'Cairo', sans-serif" : "'Inter', sans-serif";

        Chart.defaults.color = "#94a3b8";

        Chart.defaults.font.weight = 600;

        

        // Instances container

        const charts = {

            trend: null,

            status: null,

            agent: null,

            category: null

        };



        // Setup filter button listeners

        const filterBtns = document.querySelectorAll('.sd-filter-btn');

        filterBtns.forEach(btn => {

            btn.addEventListener('click', function() {

                filterBtns.forEach(b => b.classList.remove('active'));

                this.classList.add('active');

                const days = this.getAttribute('data-days');

                fetchDashboardData(days);

            });

        });



        // Initialize with default 30 days filter
        const wrapper = document.querySelector('.sahl-dashboard-wrapper');
        if (wrapper) {
            fetchDashboardData(30);
        }



        // Core data retrieval and layout renderer

        function fetchDashboardData(days) {

            const wrapper = document.querySelector('.sahl-dashboard-wrapper');

            wrapper.classList.add('loading');



            fetch(`${API_BASE}/reports/dashboard?days=${days}`, { headers: HEADERS })

                .then(res => {

                    if (!res.ok) throw new Error('API failed');

                    return res.json();

                })

                .then(data => {

                    wrapper.classList.remove('loading');

                    

                    if (!data || data.totalTickets === 0) {

                        // Display clean Empty State

                        document.getElementById('dashboard-charts-wrapper').style.display = 'none';

                        document.getElementById('dashboard-empty-state').style.display = 'block';

                        

                        // Set KPIs to 0

                        animateValue('kpi-total', 0);

                        animateValue('kpi-open', 0);

                        animateValue('kpi-progress', 0);

                        animateValue('kpi-closed', 0);

                        document.getElementById('kpi-avg').innerText = '0 ' + trans('hours');

                        return;

                    }



                    // Hide empty state, reveal charts

                    document.getElementById('dashboard-empty-state').style.display = 'none';

                    document.getElementById('dashboard-charts-wrapper').style.display = 'block';



                    // Animate KPIs

                    animateValue('kpi-total', data.totalTickets);

                    animateValue('kpi-open', data.openTickets);

                    animateValue('kpi-progress', data.inProgressTickets);

                    animateValue('kpi-pending', data.pendingTickets);

                    animateValue('kpi-closed', data.closedTickets);

                    animateValue('kpi-avg', Math.round(data.averageResolutionTimeHrs), ' ' + trans('hours'));



                    // Load Charts

                    renderVolumeTrendChart(data.volumeTrend);

                    renderStatusDoughnut(data.statusSummary);

                    renderAgentPerformanceChart(data.agentPerformance);

                    renderCategoryPie(data.categoryDistribution);

                    renderPriorityProgress(data.priorityDistribution, data.totalTickets);

                })

                .catch(err => {

                    wrapper.classList.remove('loading');

                    console.error("âŒ SahlDesk Analytics Error:", err);

                });

        }



        // Count-Up Animation interpolator (Double-precision quadratic ease-out)

        function animateValue(id, end, suffix = '') {

            const obj = document.getElementById(id);

            if (!obj) return;

            let start = 0;

            const duration = 800; 

            const startTime = performance.now();

            

            function update(now) {

                const elapsed = now - startTime;

                const progress = Math.min(elapsed / duration, 1);

                const ease = progress * (2 - progress);

                const val = Math.floor(start + ease * (end - start));

                obj.innerText = val + suffix;

                

                if (progress < 1) {

                    requestAnimationFrame(update);

                } else {

                    obj.innerText = end + suffix;

                }

            }

            requestAnimationFrame(update);

        }



        // CHART 1: VOLUME TREND (Line Chart with smooth area fills)

        function renderVolumeTrendChart(trendData) {

            const ctx = document.getElementById('trendChart').getContext('2d');

            

            // Generate canvas linear gradient

            const gradient = ctx.createLinearGradient(0, 0, 0, 300);

            gradient.addColorStop(0, 'rgba(37, 99, 235, 0.35)');

            gradient.addColorStop(1, 'rgba(37, 99, 235, 0.00)');



            const labels = trendData.map(t => {

                // Return styled dates

                const dateObj = new Date(t.date);

                return dateObj.toLocaleDateString(isArabic ? 'ar-EG' : 'en-US', { month: 'short', day: 'numeric' });

            });

            const counts = trendData.map(t => t.count);



            if (charts.trend) {

                charts.trend.data.labels = labels;

                charts.trend.data.datasets[0].data = counts;

                charts.trend.update();

            } else {

                charts.trend = new Chart(ctx, {

                    type: 'line',

                    data: {

                        labels: labels,

                        datasets: [{

                            label: trans('volume'),

                            data: counts,

                            borderColor: '#2563eb',

                            borderWidth: 3,

                            backgroundColor: gradient,

                            fill: true,

                            tension: 0.4,

                            pointBackgroundColor: '#2563eb',

                            pointBorderColor: '#ffffff',

                            pointBorderWidth: 2,

                            pointHoverRadius: 6

                        }]

                    },

                    options: {

                        responsive: true,

                        maintainAspectRatio: false,

                        plugins: {

                            legend: { display: false },

                            tooltip: {

                                padding: 12,

                                borderRadius: 10,

                                titleFont: { size: 14, weight: 'bold' },

                                bodyFont: { size: 13 }

                            }

                        },

                        scales: {

                            y: {

                                beginAtZero: true,

                                grid: { color: '#f1f5f9', drawBorder: false },

                                ticks: { stepSize: 1 }

                            },

                            x: {

                                grid: { display: false }

                            }

                        }

                    }

                });

            }

        }



        // CHART 2: STATUS SUMMARY (Doughnut Chart)

        function renderStatusDoughnut(statusData) {

            const ctx = document.getElementById('statusChart').getContext('2d');

            

            const labels = statusData.map(s => {

                const lower = s.status.toLowerCase();

                if (lower === 'progress') return trans('inProgress');

                return trans(lower);

            });

            const counts = statusData.map(s => s.count);



            const colors = {

                'open': '#f59e0b',

                'in progress': '#3b82f6',

                'progress': '#3b82f6',

                'pending': '#eab308',

                'closed': '#10b981'

            };

            const backgroundColors = statusData.map(s => colors[s.status.toLowerCase()] || '#64748b');



            if (charts.status) {

                charts.status.data.labels = labels;

                charts.status.data.datasets[0].data = counts;

                charts.status.data.datasets[0].backgroundColor = backgroundColors;

                charts.status.update();

            } else {

                charts.status = new Chart(ctx, {

                    type: 'doughnut',

                    data: {

                        labels: labels,

                        datasets: [{

                            data: counts,

                            backgroundColor: backgroundColors,

                            borderWidth: 0,

                            hoverOffset: 4

                        }]

                    },

                    options: {

                        responsive: true,

                        maintainAspectRatio: false,

                        cutout: '65%',

                        plugins: {

                            legend: { position: 'bottom', labels: { usePointStyle: true, padding: 20 } }

                        }

                    }

                });

            }

        }



        // CHART 3: AGENT PERFORMANCE (Bar Chart)

        function renderAgentPerformanceChart(agentData) {

            const ctx = document.getElementById('agentChart').getContext('2d');

            

            const labels = agentData.map(a => a.agentName === 'Unassigned' ? trans('unassigned') : a.agentName);

            const assigned = agentData.map(a => a.assignedCount);

            const resolved = agentData.map(a => a.resolvedCount);



            if (charts.agent) {

                charts.agent.data.labels = labels;

                charts.agent.data.datasets[0].data = assigned;

                charts.agent.data.datasets[1].data = resolved;

                charts.agent.update();

            } else {

                charts.agent = new Chart(ctx, {

                    type: 'bar',

                    data: {

                        labels: labels,

                        datasets: [

                            {

                                label: trans('assigned'),

                                data: assigned,

                                backgroundColor: '#94a3b8',

                                borderRadius: 4,

                                barPercentage: 0.6

                            },

                            {

                                label: trans('resolved'),

                                data: resolved,

                                backgroundColor: '#10b981',

                                borderRadius: 4,

                                barPercentage: 0.6

                            }

                        ]

                    },

                    options: {

                        responsive: true,

                        maintainAspectRatio: false,

                        plugins: {

                            legend: { position: 'top', align: 'end', labels: { usePointStyle: true, boxWidth: 8 } }

                        },

                        scales: { 

                            y: { beginAtZero: true, grid: { color: '#f1f5f9', borderDash: [5, 5] }, ticks: { stepSize: 1 } },

                            x: { grid: { display: false } }

                        }

                    }

                });

            }

        }



        // CHART 4: CATEGORY DISTRIBUTION (Pie Chart)

        function renderCategoryPie(categoryData) {

            const ctx = document.getElementById('categoryChart').getContext('2d');

            

            const labels = categoryData.map(c => trans(c.category.toLowerCase()));

            const counts = categoryData.map(c => c.count);

            

            const bgColors = ['#3b82f6', '#8b5cf6', '#ec4899', '#f43f5e', '#f59e0b', '#10b981', '#14b8a6', '#06b6d4'];



            if (charts.category) {

                charts.category.data.labels = labels;

                charts.category.data.datasets[0].data = counts;

                charts.category.update();

            } else {

                charts.category = new Chart(ctx, {

                    type: 'pie',

                    data: {

                        labels: labels,

                        datasets: [{

                            data: counts,

                            backgroundColor: bgColors.slice(0, counts.length),

                            borderWidth: 0,

                            hoverOffset: 4

                        }]

                    },

                    options: {

                        responsive: true,

                        maintainAspectRatio: false,

                        plugins: {

                            legend: { position: 'right', labels: { usePointStyle: true, boxWidth: 8, font: { size: 11 } } }

                        }

                    }

                });

            }

        }



        // PRIORITY PROGRESS BARS

        function renderPriorityProgress(priorityData, total) {

            let high = 0, medium = 0, low = 0;

            priorityData.forEach(p => {

                const lower = p.priority.toLowerCase();

                if (lower === 'high') high = p.count;

                if (lower === 'medium') medium = p.count;

                if (lower === 'low') low = p.count;

            });



            const highPct = total > 0 ? (high / total) * 100 : 0;

            const medPct = total > 0 ? (medium / total) * 100 : 0;

            const lowPct = total > 0 ? (low / total) * 100 : 0;



            document.getElementById('priority-high-bar').style.width = highPct + '%';

            document.getElementById('priority-high-count').innerText = high;

            

            document.getElementById('priority-medium-bar').style.width = medPct + '%';

            document.getElementById('priority-medium-count').innerText = medium;

            

            document.getElementById('priority-low-bar').style.width = lowPct + '%';

            document.getElementById('priority-low-count').innerText = low;

        }

        // Custom Upgrade Page: Billing Toggle Logic
        var toggle = document.getElementById('billing-toggle');
        var priceAmount = document.getElementById('pro-price-amount');
        var pricePeriod = document.getElementById('pro-price-period');
        var monthlyLabel = document.getElementById('billing-monthly-label');
        var yearlyLabel = document.getElementById('billing-yearly-label');

        if(toggle && priceAmount && pricePeriod) {
            var monthlyPrice = priceAmount.getAttribute('data-monthly');
            var yearlyPrice = priceAmount.getAttribute('data-yearly');
            var moText = pricePeriod.getAttribute('data-mo');
            var yrText = pricePeriod.getAttribute('data-yr');

            toggle.addEventListener('change', function() {
                if(this.checked) {
                    priceAmount.innerText = yearlyPrice;
                    pricePeriod.innerText = yrText;
                    yearlyLabel.style.color = '#1e293b';
                    monthlyLabel.style.color = '#64748b';
                } else {
                    priceAmount.innerText = monthlyPrice;
                    pricePeriod.innerText = moText;
                    monthlyLabel.style.color = '#1e293b';
                    yearlyLabel.style.color = '#64748b';
                }
            });
        }
    });
