/**
 * Dashboard Manager
 */
class DashboardManager {
    constructor() {
        this.stats = null;
        this.init();
    }

    async init() {
        await this.loadStats();
        this.setupAutoRefresh();
        this.setupRealTimeUpdates();
    }

    async loadStats() {
        try {
            const data = await window.rcpFetch('stats.php');
            
            if (data.success) {
                this.stats = data;
                this.updateDashboard();
            } else {
                console.error('Failed to load stats:', data.message);
                this.showError('Failed to load dashboard data');
            }
        } catch (error) {
            console.error('Error loading dashboard:', error);
            this.showError('Network error loading dashboard');
        }
    }

    updateDashboard() {
        this.updateStatsCards();
        this.updateRecentActivity();
        this.updateQuickStats();
    }

    updateStatsCards() {
        const counts = this.stats.counts || {};
        
        document.getElementById('statIngredients').textContent = counts.ingredients || 0;
        document.getElementById('statRecipes').textContent = counts.recipes || 0;
        document.getElementById('statMeals').textContent = counts.meals || 0;
        document.getElementById('statUsers').textContent = counts.users || 0;
    }

    updateRecentActivity() {
        const container = document.getElementById('recentActivity');
        const activities = this.stats.recent || [];
        
        if (activities.length === 0) {
            container.innerHTML = `
                <div class="text-center py-4 text-muted">
                    <i class="fas fa-inbox display-6 mb-3"></i>
                    <p>No recent activity yet</p>
                </div>
            `;
            return;
        }
        
        container.innerHTML = activities.map(activity => `
            <div class="list-group-item border-0 px-0">
                <div class="d-flex align-items-start">
                    <div class="flex-shrink-0">
                        <span class="badge bg-light text-dark rounded-pill">
                            <i class="fas fa-${this.getActivityIcon(activity.type)}"></i>
                        </span>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <div class="d-flex justify-content-between align-items-start">
                            <h6 class="mb-1">${window.escapeHtml(activity.label)}</h6>
                            <small class="text-muted">${this.formatTimeAgo(activity.created_at)}</small>
                        </div>
                        <p class="mb-1 small text-muted">
                            ${window.escapeHtml(activity.description || '')}
                        </p>
                        <small class="text-muted">
                            By: ${window.escapeHtml(activity.creator_name || 'System')}
                        </small>
                    </div>
                </div>
            </div>
        `).join('');
    }

    updateQuickStats() {
        // Update any additional real-time stats
        const timestampEl = document.getElementById('lastUpdate');
        if (timestampEl) {
            timestampEl.textContent = new Date().toLocaleTimeString();
        }
    }

    getActivityIcon(type) {
        const icons = {
            'login': 'sign-in-alt',
            'logout': 'sign-out-alt',
            'ingredient': 'carrot',
            'recipe': 'utensils',
            'meal': 'clipboard-list',
            'user': 'user',
            'settings': 'cog',
            'security': 'shield-alt'
        };
        return icons[type] || 'circle';
    }

    formatTimeAgo(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);
        
        if (diffMins < 1) return 'Just now';
        if (diffMins < 60) return `${diffMins}m ago`;
        if (diffHours < 24) return `${diffHours}h ago`;
        if (diffDays < 7) return `${diffDays}d ago`;
        return date.toLocaleDateString();
    }

    setupAutoRefresh() {
        // Refresh every 2 minutes
        setInterval(() => {
            this.loadStats();
        }, 120000);
    }

    setupRealTimeUpdates() {
        // Listen for real-time events (WebSocket could be added later)
        document.addEventListener('dataUpdated', (e) => {
            this.loadStats(); // Reload when data changes
        });
    }

    showError(message) {
        window.showAlert(message, 'danger');
    }
}

// Initialize dashboard when page loads
document.addEventListener('DOMContentLoaded', () => {
    new DashboardManager();
});

// Export for global access
window.DashboardManager = DashboardManager;