/**
 * KSO Chandigarh Dashboard Widgets
 * Enhanced dashboard components with charts and analytics
 */

class KSODashboardWidgets {
    constructor() {
        this.charts = {};
        this.widgets = {};
        this.colors = {
            primary: '#007bff',
            success: '#28a745',
            warning: '#ffc107',
            danger: '#dc3545',
            info: '#17a2b8',
            secondary: '#6c757d'
        };
        this.init();
    }

    init() {
        this.addStyles();
        this.loadChartJS();
    }

    addStyles() {
        const style = document.createElement('style');
        style.textContent = `
            .kso-widget {
                background: #fff;
                border-radius: 8px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                padding: 20px;
                margin-bottom: 20px;
                position: relative;
                overflow: hidden;
                transition: transform 0.3s ease, box-shadow 0.3s ease;
            }

            .kso-widget:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            }

            .kso-widget-header {
                display: flex;
                justify-content: between;
                align-items: center;
                margin-bottom: 20px;
                padding-bottom: 15px;
                border-bottom: 1px solid #e9ecef;
            }

            .kso-widget-title {
                font-size: 18px;
                font-weight: 600;
                color: #333;
                margin: 0;
                flex: 1;
            }

            .kso-widget-actions {
                display: flex;
                gap: 10px;
            }

            .kso-widget-action {
                background: none;
                border: none;
                color: #6c757d;
                cursor: pointer;
                font-size: 14px;
                padding: 5px;
                border-radius: 3px;
                transition: color 0.2s ease;
            }

            .kso-widget-action:hover {
                color: #007bff;
            }

            .kso-widget-body {
                position: relative;
            }

            .kso-stat-card {
                text-align: center;
                padding: 20px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border-radius: 8px;
                margin-bottom: 20px;
                position: relative;
                overflow: hidden;
            }

            .kso-stat-card::before {
                content: '';
                position: absolute;
                top: -50%;
                right: -50%;
                width: 100%;
                height: 100%;
                background: rgba(255, 255, 255, 0.1);
                transform: rotate(45deg);
                transition: all 0.3s ease;
            }

            .kso-stat-card:hover::before {
                top: -60%;
                right: -60%;
            }

            .kso-stat-value {
                font-size: 32px;
                font-weight: 700;
                margin-bottom: 8px;
                position: relative;
                z-index: 2;
            }

            .kso-stat-label {
                font-size: 14px;
                opacity: 0.9;
                position: relative;
                z-index: 2;
            }

            .kso-stat-change {
                font-size: 12px;
                margin-top: 8px;
                position: relative;
                z-index: 2;
            }

            .kso-stat-change.positive {
                color: #4caf50;
            }

            .kso-stat-change.negative {
                color: #f44336;
            }

            .kso-chart-container {
                position: relative;
                height: 300px;
                margin: 20px 0;
            }

            .kso-chart-container canvas {
                max-height: 100%;
            }

            .kso-progress-widget {
                padding: 15px;
            }

            .kso-progress-item {
                margin-bottom: 20px;
            }

            .kso-progress-label {
                display: flex;
                justify-content: space-between;
                margin-bottom: 8px;
                font-size: 14px;
                font-weight: 500;
            }

            .kso-progress-bar {
                height: 8px;
                background: #e9ecef;
                border-radius: 4px;
                overflow: hidden;
                position: relative;
            }

            .kso-progress-fill {
                height: 100%;
                background: linear-gradient(90deg, #007bff, #0056b3);
                transition: width 0.8s ease;
                position: relative;
            }

            .kso-progress-fill::after {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
                animation: shimmer 2s infinite;
            }

            @keyframes shimmer {
                0% { transform: translateX(-100%); }
                100% { transform: translateX(100%); }
            }

            .kso-activity-feed {
                max-height: 400px;
                overflow-y: auto;
            }

            .kso-activity-item {
                display: flex;
                align-items: flex-start;
                padding: 15px;
                border-bottom: 1px solid #e9ecef;
                transition: background-color 0.2s ease;
            }

            .kso-activity-item:hover {
                background-color: #f8f9fa;
            }

            .kso-activity-icon {
                width: 36px;
                height: 36px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 15px;
                flex-shrink: 0;
            }

            .kso-activity-content {
                flex: 1;
            }

            .kso-activity-title {
                font-weight: 500;
                font-size: 14px;
                color: #333;
                margin-bottom: 4px;
            }

            .kso-activity-description {
                font-size: 12px;
                color: #6c757d;
                margin-bottom: 8px;
            }

            .kso-activity-time {
                font-size: 11px;
                color: #999;
            }

            .kso-quick-actions {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                gap: 15px;
                margin-top: 20px;
            }

            .kso-quick-action {
                background: #f8f9fa;
                border: 1px solid #e9ecef;
                border-radius: 8px;
                padding: 20px;
                text-align: center;
                cursor: pointer;
                transition: all 0.3s ease;
                text-decoration: none;
                color: #333;
            }

            .kso-quick-action:hover {
                background: #e9ecef;
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
                text-decoration: none;
                color: #007bff;
            }

            .kso-quick-action-icon {
                font-size: 24px;
                margin-bottom: 10px;
                display: block;
            }

            .kso-quick-action-label {
                font-size: 14px;
                font-weight: 500;
            }

            .kso-loading {
                display: flex;
                justify-content: center;
                align-items: center;
                height: 200px;
                color: #6c757d;
            }

            .kso-loading i {
                margin-right: 10px;
            }

            /* Dark mode */
            .dark-mode .kso-widget {
                background: #343a40;
                color: #fff;
            }

            .dark-mode .kso-widget-header {
                border-bottom-color: #495057;
            }

            .dark-mode .kso-widget-title {
                color: #fff;
            }

            .dark-mode .kso-activity-item {
                border-bottom-color: #495057;
            }

            .dark-mode .kso-activity-item:hover {
                background-color: #495057;
            }

            .dark-mode .kso-activity-title {
                color: #fff;
            }

            .dark-mode .kso-activity-description {
                color: #adb5bd;
            }

            .dark-mode .kso-quick-action {
                background: #495057;
                border-color: #6c757d;
                color: #fff;
            }

            .dark-mode .kso-quick-action:hover {
                background: #6c757d;
                color: #fff;
            }

            .dark-mode .kso-progress-bar {
                background: #495057;
            }

            /* Responsive */
            @media (max-width: 768px) {
                .kso-widget {
                    padding: 15px;
                }

                .kso-quick-actions {
                    grid-template-columns: repeat(2, 1fr);
                }

                .kso-stat-value {
                    font-size: 24px;
                }
            }
        `;
        document.head.appendChild(style);
    }

    loadChartJS() {
        if (!window.Chart) {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js';
            script.onload = () => {
                console.log('Chart.js loaded successfully');
            };
            document.head.appendChild(script);
        }
    }

    createStatCard(id, options = {}) {
        const container = document.getElementById(id);
        if (!container) return;

        const widget = document.createElement('div');
        widget.className = 'kso-widget';
        widget.innerHTML = `
            <div class="kso-stat-card" style="background: ${options.gradient || 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'}">
                <div class="kso-stat-value" id="${id}-value">${options.value || '0'}</div>
                <div class="kso-stat-label">${options.label || 'Statistic'}</div>
                <div class="kso-stat-change ${options.changeType || 'positive'}" id="${id}-change">
                    <i class="fas fa-arrow-${options.changeType === 'negative' ? 'down' : 'up'}"></i>
                    ${options.change || '0%'}
                </div>
            </div>
        `;

        container.appendChild(widget);
        this.widgets[id] = widget;
    }

    createChartWidget(id, type, data, options = {}) {
        const container = document.getElementById(id);
        if (!container) return;

        const widget = document.createElement('div');
        widget.className = 'kso-widget';
        widget.innerHTML = `
            <div class="kso-widget-header">
                <h3 class="kso-widget-title">${options.title || 'Chart'}</h3>
                <div class="kso-widget-actions">
                    <button class="kso-widget-action" onclick="window.ksoWidgets.refreshChart('${id}')">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>
            <div class="kso-widget-body">
                <div class="kso-chart-container">
                    <canvas id="${id}-chart"></canvas>
                </div>
            </div>
        `;

        container.appendChild(widget);
        this.widgets[id] = widget;

        // Create chart after Chart.js is loaded
        const createChart = () => {
            if (window.Chart) {
                const ctx = document.getElementById(`${id}-chart`).getContext('2d');
                this.charts[id] = new Chart(ctx, {
                    type: type,
                    data: data,
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        ...options.chartOptions
                    }
                });
            } else {
                setTimeout(createChart, 100);
            }
        };

        createChart();
    }

    createProgressWidget(id, items, options = {}) {
        const container = document.getElementById(id);
        if (!container) return;

        const widget = document.createElement('div');
        widget.className = 'kso-widget';
        widget.innerHTML = `
            <div class="kso-widget-header">
                <h3 class="kso-widget-title">${options.title || 'Progress'}</h3>
            </div>
            <div class="kso-widget-body">
                <div class="kso-progress-widget">
                    ${items.map(item => `
                        <div class="kso-progress-item">
                            <div class="kso-progress-label">
                                <span>${item.label}</span>
                                <span>${item.value}%</span>
                            </div>
                            <div class="kso-progress-bar">
                                <div class="kso-progress-fill" style="width: ${item.value}%; background: ${item.color || '#007bff'}"></div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;

        container.appendChild(widget);
        this.widgets[id] = widget;
    }

    createActivityFeed(id, activities, options = {}) {
        const container = document.getElementById(id);
        if (!container) return;

        const widget = document.createElement('div');
        widget.className = 'kso-widget';
        widget.innerHTML = `
            <div class="kso-widget-header">
                <h3 class="kso-widget-title">${options.title || 'Recent Activity'}</h3>
                <div class="kso-widget-actions">
                    <button class="kso-widget-action" onclick="window.ksoWidgets.refreshActivity('${id}')">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>
            <div class="kso-widget-body">
                <div class="kso-activity-feed">
                    ${activities.map(activity => `
                        <div class="kso-activity-item">
                            <div class="kso-activity-icon" style="background: ${activity.color || '#007bff'}">
                                <i class="${activity.icon || 'fas fa-info'}" style="color: white; font-size: 14px;"></i>
                            </div>
                            <div class="kso-activity-content">
                                <div class="kso-activity-title">${activity.title}</div>
                                <div class="kso-activity-description">${activity.description}</div>
                                <div class="kso-activity-time">${activity.time}</div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;

        container.appendChild(widget);
        this.widgets[id] = widget;
    }

    createQuickActions(id, actions, options = {}) {
        const container = document.getElementById(id);
        if (!container) return;

        const widget = document.createElement('div');
        widget.className = 'kso-widget';
        widget.innerHTML = `
            <div class="kso-widget-header">
                <h3 class="kso-widget-title">${options.title || 'Quick Actions'}</h3>
            </div>
            <div class="kso-widget-body">
                <div class="kso-quick-actions">
                    ${actions.map(action => `
                        <a href="${action.href || '#'}" class="kso-quick-action" onclick="${action.onClick || ''}">
                            <i class="${action.icon || 'fas fa-cog'} kso-quick-action-icon"></i>
                            <div class="kso-quick-action-label">${action.label}</div>
                        </a>
                    `).join('')}
                </div>
            </div>
        `;

        container.appendChild(widget);
        this.widgets[id] = widget;
    }

    updateStatCard(id, value, change = null, changeType = 'positive') {
        const valueElement = document.getElementById(`${id}-value`);
        const changeElement = document.getElementById(`${id}-change`);
        
        if (valueElement) {
            valueElement.textContent = value;
        }
        
        if (changeElement && change !== null) {
            changeElement.innerHTML = `
                <i class="fas fa-arrow-${changeType === 'negative' ? 'down' : 'up'}"></i>
                ${change}
            `;
            changeElement.className = `kso-stat-change ${changeType}`;
        }
    }

    refreshChart(id) {
        if (this.charts[id]) {
            // Add loading state
            const chartContainer = document.querySelector(`#${id} .kso-chart-container`);
            if (chartContainer) {
                chartContainer.innerHTML = '<div class="kso-loading"><i class="fas fa-spinner fa-spin"></i>Refreshing...</div>';
            }
            
            // Simulate data refresh
            setTimeout(() => {
                // Restore canvas
                chartContainer.innerHTML = `<canvas id="${id}-chart"></canvas>`;
                
                // You would typically fetch new data here
                // For demo, we'll just update the existing chart
                this.charts[id].update();
            }, 1000);
        }
    }

    refreshActivity(id) {
        const activityFeed = document.querySelector(`#${id} .kso-activity-feed`);
        if (activityFeed) {
            activityFeed.innerHTML = '<div class="kso-loading"><i class="fas fa-spinner fa-spin"></i>Loading activities...</div>';
            
            // Simulate activity refresh
            setTimeout(() => {
                // You would typically fetch new activities here
                location.reload(); // For demo purposes
            }, 1000);
        }
    }

    removeWidget(id) {
        if (this.widgets[id]) {
            this.widgets[id].remove();
            delete this.widgets[id];
        }
        
        if (this.charts[id]) {
            this.charts[id].destroy();
            delete this.charts[id];
        }
    }

    getChart(id) {
        return this.charts[id];
    }

    getWidget(id) {
        return this.widgets[id];
    }
}

// Initialize dashboard widgets
document.addEventListener('DOMContentLoaded', () => {
    window.ksoWidgets = new KSODashboardWidgets();
});
