/* ============================================
   Business Dashboard Template - Custom Scripts
   Description: Dashboard functionality and interactions
   ============================================ */

(function() {
    'use strict';

    // ============================================
    // Dashboard Module
    // ============================================
    const Dashboard = {

        // Initialize dashboard
        init: function() {
            this.updateDateTime();
            this.initGreeting();
            this.initCountUp();
            this.initChartPeriodSelect();
            this.initTableFilters();

            // Update time every second
            setInterval(() => this.updateDateTime(), 1000);

            // Show welcome toast only on home page (index.html)
            const isHomePage = window.location.pathname.endsWith('index.html') ||
                               window.location.pathname.endsWith('/');
            if (isHomePage) {
                setTimeout(() => this.showWelcomeToast(), 1500);
            }
        },

        // Update date and time display
        updateDateTime: function() {
            const dateEl = document.getElementById('currentDate');
            const timeEl = document.getElementById('currentTime');

            if (dateEl && timeEl) {
                const now = new Date();

                // Format date: "Wednesday, December 4, 2025"
                const dateOptions = {
                    weekday: 'long',
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                };
                dateEl.textContent = now.toLocaleDateString('en-US', dateOptions);

                // Format time: "2:30 PM"
                const timeOptions = {
                    hour: 'numeric',
                    minute: '2-digit',
                    hour12: true
                };
                timeEl.textContent = now.toLocaleTimeString('en-US', timeOptions);
            }
        },

        // Set greeting based on time of day
        initGreeting: function() {
            const greetingEl = document.querySelector('.rsl-hero-eyebrow');
            if (!greetingEl) return;

            const hour = new Date().getHours();
            let greeting = 'Good morning';
            let icon = 'fa-sun';

            if (hour >= 12 && hour < 17) {
                greeting = 'Good afternoon';
                icon = 'fa-sun';
            } else if (hour >= 17 && hour < 21) {
                greeting = 'Good evening';
                icon = 'fa-cloud-sun';
            } else if (hour >= 21 || hour < 5) {
                greeting = 'Good night';
                icon = 'fa-moon';
            }

            greetingEl.innerHTML = `<i class="fas ${icon}"></i> ${greeting}`;
        },

        // Initialize count-up animations for KPI values
        initCountUp: function() {
            const kpiValues = document.querySelectorAll('[data-count-to]');

            kpiValues.forEach(el => {
                const target = parseFloat(el.getAttribute('data-count-to'));
                const prefix = el.getAttribute('data-count-prefix') || '';
                const suffix = el.getAttribute('data-count-suffix') || '';
                const decimals = parseInt(el.getAttribute('data-count-decimals')) || 0;
                const duration = parseInt(el.getAttribute('data-count-duration')) || 2000;

                // Check if user prefers reduced motion
                if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
                    el.textContent = prefix + this.formatNumber(target, decimals) + suffix;
                    return;
                }

                // Animate count
                this.animateValue(el, 0, target, duration, prefix, suffix, decimals);
            });
        },

        // Animate a value from start to end
        animateValue: function(el, start, end, duration, prefix, suffix, decimals) {
            const startTime = performance.now();
            const self = this;

            function update(currentTime) {
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);

                // Easing function (ease-out-cubic)
                const easeOut = 1 - Math.pow(1 - progress, 3);
                const current = start + (end - start) * easeOut;

                el.textContent = prefix + self.formatNumber(current, decimals) + suffix;

                if (progress < 1) {
                    requestAnimationFrame(update);
                }
            }

            requestAnimationFrame(update);
        },

        // Format number with commas and decimals
        formatNumber: function(num, decimals) {
            return num.toLocaleString('en-US', {
                minimumFractionDigits: decimals,
                maximumFractionDigits: decimals
            });
        },

        // Initialize chart period selector
        initChartPeriodSelect: function() {
            const periodSelect = document.querySelector('.chart-period-select');
            if (!periodSelect) return;

            // Listen for RSL Select custom event (used when data-rsl-select is present)
            periodSelect.addEventListener('rsl-select-change', (e) => {
                const period = e.detail.values[0]; // Get first selected value
                this.updateChartData(period);

                // Show toast notification
                this.showToast('Chart updated', `Showing data for ${this.getPeriodLabel(period)}`, 'info');
            });

            // Also listen for native change event (fallback for non-RSL selects)
            periodSelect.addEventListener('change', (e) => {
                const period = e.target.value;
                this.updateChartData(period);

                // Show toast notification
                this.showToast('Chart updated', `Showing data for ${this.getPeriodLabel(period)}`, 'info');
            });
        },

        // Get human-readable period label
        getPeriodLabel: function(period) {
            const labels = {
                '7d': 'last 7 days',
                '30d': 'last 30 days',
                '90d': 'last 90 days',
                '1y': 'last year'
            };
            return labels[period] || period;
        },

        // Sample data for different time periods
        chartData: {
            '7d': {
                labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                datasets: [
                    { label: 'Revenue', values: [18500, 22100, 19800, 24200, 21500, 15200, 12800] },
                    { label: 'Expenses', values: [12000, 14500, 13200, 15800, 14200, 9800, 8500] }
                ]
            },
            '30d': {
                labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
                datasets: [
                    { label: 'Revenue', values: [92000, 98000, 105000, 115000] },
                    { label: 'Expenses', values: [58000, 62000, 65000, 72000] }
                ]
            },
            '90d': {
                labels: ['Jan', 'Feb', 'Mar'],
                datasets: [
                    { label: 'Revenue', values: [285000, 312000, 345000] },
                    { label: 'Expenses', values: [182000, 195000, 215000] }
                ]
            },
            '1y': {
                labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                datasets: [
                    { label: 'Revenue', values: [65000, 72000, 68000, 85000, 92000, 88000, 95000, 102000, 98000, 115000, 108000, 124500] },
                    { label: 'Expenses', values: [45000, 48000, 46000, 52000, 55000, 53000, 58000, 62000, 59000, 68000, 65000, 72000] }
                ]
            }
        },

        // Update chart data based on selected period
        updateChartData: function(period) {
            const chartElement = document.querySelector('[data-rsl-chart]');
            if (!chartElement || !window.RSL || !window.RSL.Charts) {
                console.log('Chart not available');
                return;
            }

            const data = this.chartData[period];
            if (!data) {
                console.log('No data for period:', period);
                return;
            }

            // Update the chart using RSL.Charts API
            // First update the data attributes
            chartElement.setAttribute('data-labels', JSON.stringify(data.labels));
            chartElement.setAttribute('data-datasets', JSON.stringify(data.datasets));

            // Destroy and recreate the chart with new data
            RSL.Charts.destroy(chartElement);
            RSL.Charts.create(chartElement);

            console.log('Chart updated for period:', period);
        },

        // Initialize table filters
        initTableFilters: function() {
            const searchInput = document.querySelector('[data-filter-key="search"]');
            const statusSelect = document.querySelector('[data-filter-key="status"]');
            const table = document.getElementById('activity-table');

            if (!table) return;

            // Search filter
            if (searchInput) {
                let debounceTimer;
                searchInput.addEventListener('input', (e) => {
                    clearTimeout(debounceTimer);
                    debounceTimer = setTimeout(() => {
                        this.filterTable(table, e.target.value, 'search');
                    }, 300);
                });
            }

            // Status filter
            if (statusSelect) {
                statusSelect.addEventListener('change', (e) => {
                    this.filterTable(table, e.target.value, 'status');
                });
            }
        },

        // Filter table rows
        filterTable: function(table, value, filterType) {
            const rows = table.querySelectorAll('tbody tr');
            let visibleCount = 0;

            rows.forEach(row => {
                let show = true;

                if (filterType === 'search' && value) {
                    const text = row.textContent.toLowerCase();
                    show = text.includes(value.toLowerCase());
                }

                if (filterType === 'status' && value) {
                    const rowStatus = row.getAttribute('data-status');
                    show = rowStatus === value;
                }

                row.style.display = show ? '' : 'none';
                if (show) visibleCount++;
            });

            // Announce to screen readers
            this.announceFilterResults(visibleCount);
        },

        // Announce filter results for accessibility
        announceFilterResults: function(count) {
            const announcement = document.createElement('div');
            announcement.setAttribute('role', 'status');
            announcement.setAttribute('aria-live', 'polite');
            announcement.setAttribute('aria-atomic', 'true');
            announcement.className = 'sr-only';
            announcement.textContent = `${count} ${count === 1 ? 'result' : 'results'} found`;

            document.body.appendChild(announcement);
            setTimeout(() => announcement.remove(), 1000);
        },

        // Show welcome toast
        showWelcomeToast: function() {
            this.showToast(
                'Welcome back!',
                'You have 3 new notifications and 2 pending tasks.',
                'success'
            );
        },

        // Show toast notification
        // type parameter is for visual styling: 'success' (green), 'info' (blue), 'warning' (yellow), 'error' (red)
        showToast: function(header, body, type) {
            if (window.RSL && window.RSL.Toast) {
                // Map semantic type to background colors
                const typeColors = {
                    'success': '#28a745',
                    'info': '#007bff',
                    'warning': '#ffc107',
                    'error': '#dc3545'
                };

                window.RSL.Toast.show({
                    header: header,
                    body: body,
                    position: 'top-right',
                    timeout: 5000,
                    bgColor: typeColors[type] || typeColors.info
                    // Note: 'type' in RSL.Toast is for positioning (fixed/absolute), not styling
                });
            }
        }
    };

    // ============================================
    // Initialize on DOM ready
    // ============================================
    document.addEventListener('DOMContentLoaded', function() {
        Dashboard.init();

        // Initialize RSL components
        if (window.RSL) {
            // Initialize Select components
            if (window.RSL.Select) {
                window.RSL.Select.init();
            }

            // Initialize Charts
            if (window.RSL.Charts) {
                window.RSL.Charts.init();
            }

            // Initialize Smart Table
            if (window.RSL.SmartTable) {
                window.RSL.SmartTable.init();
            }

            // Initialize KPI Cards
            if (window.RSL.KPICards) {
                window.RSL.KPICards.init();
            }

            // Initialize Progress Bars
            if (window.RSL.ProgressBar) {
                window.RSL.ProgressBar.init();
            }

            // Initialize Date Picker
            if (window.RSL.DatePicker) {
                window.RSL.DatePicker.init();
            }
        }
    });

    // Expose Dashboard for external use
    window.Dashboard = Dashboard;

})();
