// PerformanceView - Detailed team performance analytics (Admin only)
function PerformanceView() {
    const { user } = useAuth();
    const [projects, setProjects] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [dateRange, setDateRange] = React.useState('all'); // 'all', '30d', '90d', '1y'
    const [selectedUser, setSelectedUser] = React.useState(null); // For user detail modal

    // Load all projects including archived
    React.useEffect(() => {
        const loadData = async () => {
            setLoading(true);
            try {
                const [activeProjects, archivedProjects] = await Promise.all([
                    ApiUtils.fetchProjects(),
                    window.ApiProjects.fetchArchivedProjects()
                ]);
                setProjects([...activeProjects, ...archivedProjects]);
            } catch (err) {
                console.error('Failed to load projects:', err);
            } finally {
                setLoading(false);
            }
        };
        loadData();
    }, []);

    // Filter projects by date range
    const filteredProjects = React.useMemo(() => {
        if (dateRange === 'all') return projects;

        const now = new Date();
        let cutoffDate = new Date();

        switch (dateRange) {
            case '30d':
                cutoffDate.setDate(now.getDate() - 30);
                break;
            case '90d':
                cutoffDate.setDate(now.getDate() - 90);
                break;
            case '1y':
                cutoffDate.setFullYear(now.getFullYear() - 1);
                break;
            default:
                return projects;
        }

        return projects.filter(p => {
            const projectDate = p.archived_at ? new Date(p.archived_at) : new Date(p.created_at);
            return projectDate >= cutoffDate;
        });
    }, [projects, dateRange]);

    // Compute all analytics data
    const analytics = React.useMemo(() => {
        const userMap = new Map();
        const reasonsMap = new Map();
        const monthlyData = new Map();
        const totals = { completed: 0, cancelled: 0, active: 0, onTime: 0, late: 0 };

        filteredProjects.forEach(project => {
            const isCompleted = project.status === 'completed' || (project.is_archived && !project.is_cancelled);
            const isActive = !project.is_archived && !project.is_cancelled;

            // Project totals
            if (project.is_cancelled) {
                totals.cancelled++;
            } else if (isCompleted) {
                totals.completed++;
                if (project.due_date) {
                    const dueDate = new Date(project.due_date);
                    const completedDate = project.archived_at
                        ? new Date(project.archived_at)
                        : (project.updated_at ? new Date(project.updated_at) : new Date());
                    dueDate.setHours(23, 59, 59, 999);
                    if (completedDate <= dueDate) {
                        totals.onTime++;
                    } else {
                        totals.late++;
                    }
                } else {
                    totals.onTime++;
                }
            } else if (isActive) {
                totals.active++;
            }

            // Monthly trends (based on created_at or archived_at)
            const trendDate = project.is_archived && project.archived_at
                ? new Date(project.archived_at)
                : new Date(project.created_at);
            const monthKey = `${trendDate.getFullYear()}-${String(trendDate.getMonth() + 1).padStart(2, '0')}`;

            if (!monthlyData.has(monthKey)) {
                monthlyData.set(monthKey, { completed: 0, cancelled: 0, created: 0 });
            }
            const monthData = monthlyData.get(monthKey);

            if (project.is_cancelled) {
                monthData.cancelled++;
            } else if (isCompleted) {
                monthData.completed++;
            }
            // Count created projects
            const createdMonth = new Date(project.created_at);
            const createdKey = `${createdMonth.getFullYear()}-${String(createdMonth.getMonth() + 1).padStart(2, '0')}`;
            if (!monthlyData.has(createdKey)) {
                monthlyData.set(createdKey, { completed: 0, cancelled: 0, created: 0 });
            }
            monthlyData.get(createdKey).created++;

            // Track cancellation reasons
            if (project.is_cancelled && project.cancellation_reason) {
                const reason = project.cancellation_reason.trim();
                if (reason) {
                    reasonsMap.set(reason, (reasonsMap.get(reason) || 0) + 1);
                }
            }

            // User performance
            const assignments = project.assignments || [];
            assignments.forEach(assignment => {
                const userId = assignment.user_id;
                if (!userId) return;

                if (!userMap.has(userId)) {
                    userMap.set(userId, {
                        id: userId,
                        name: assignment.user_name || assignment.user_email || 'Utente',
                        email: assignment.user_email,
                        avatar: assignment.user_avatar,
                        totalProjects: 0,
                        activeProjects: 0,
                        completedProjects: 0,
                        cancelledProjects: 0,
                        completedOnTime: 0,
                        completedLate: 0,
                        avgCompletionDays: [],
                    });
                }

                const userData = userMap.get(userId);
                userData.totalProjects++;

                if (project.is_cancelled) {
                    userData.cancelledProjects++;
                } else if (isCompleted) {
                    userData.completedProjects++;
                    if (project.due_date) {
                        const dueDate = new Date(project.due_date);
                        const completedDate = project.archived_at
                            ? new Date(project.archived_at)
                            : (project.updated_at ? new Date(project.updated_at) : new Date());
                        dueDate.setHours(23, 59, 59, 999);
                        if (completedDate <= dueDate) {
                            userData.completedOnTime++;
                        } else {
                            userData.completedLate++;
                        }
                        // Track completion time
                        if (project.start_date) {
                            const startDate = new Date(project.start_date);
                            const days = Math.ceil((completedDate - startDate) / (1000 * 60 * 60 * 24));
                            if (days > 0) userData.avgCompletionDays.push(days);
                        }
                    } else {
                        userData.completedOnTime++;
                    }
                } else {
                    userData.activeProjects++;
                }
            });
        });

        // Calculate averages and sort users
        const users = Array.from(userMap.values()).map(u => ({
            ...u,
            avgCompletionDays: u.avgCompletionDays.length > 0
                ? Math.round(u.avgCompletionDays.reduce((a, b) => a + b, 0) / u.avgCompletionDays.length)
                : null,
            successRate: u.completedProjects > 0
                ? Math.round((u.completedOnTime / u.completedProjects) * 100)
                : 0,
        })).sort((a, b) => {
            if (b.completedOnTime !== a.completedOnTime) return b.completedOnTime - a.completedOnTime;
            if (b.completedProjects !== a.completedProjects) return b.completedProjects - a.completedProjects;
            return a.cancelledProjects - b.cancelledProjects;
        });

        // Sort monthly data
        const months = Array.from(monthlyData.entries())
            .sort((a, b) => a[0].localeCompare(b[0]))
            .slice(-12); // Last 12 months

        // Sort cancellation reasons
        const reasons = Array.from(reasonsMap.entries())
            .map(([reason, count]) => ({ reason, count }))
            .sort((a, b) => b.count - a.count);

        return { users, totals, months, reasons };
    }, [filteredProjects]);

    // Get initials from name
    const getInitials = (name) => {
        if (!name) return '?';
        const parts = name.split(' ').filter(Boolean);
        if (parts.length >= 2) {
            return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
        }
        return name.substring(0, 2).toUpperCase();
    };

    // Get avatar color based on name
    const getAvatarColor = (name) => {
        const colors = [
            'bg-blue-500', 'bg-green-500', 'bg-amber-500', 'bg-red-500',
            'bg-purple-500', 'bg-pink-500', 'bg-indigo-500', 'bg-teal-500'
        ];
        const hash = name?.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0) || 0;
        return colors[hash % colors.length];
    };


    // Format month label
    const formatMonth = (monthKey) => {
        const [year, month] = monthKey.split('-');
        const date = new Date(year, parseInt(month) - 1);
        return date.toLocaleDateString('it-IT', { month: 'short', year: '2-digit' });
    };

    if (loading) {
        return (
            <div className="p-6">
                <div className="flex items-center justify-center py-20">
                    <Spinner size="lg" />
                </div>
            </div>
        );
    }

    const totalClosed = analytics.totals.completed + analytics.totals.cancelled;
    const completionRate = totalClosed > 0 ? Math.round((analytics.totals.completed / totalClosed) * 100) : 0;
    const punctualityRate = analytics.totals.completed > 0
        ? Math.round((analytics.totals.onTime / analytics.totals.completed) * 100)
        : 0;

    return (
        <div className="p-6 space-y-6">
            {/* Header with filters */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-2xl font-bold text-slate-900">Performance Team</h1>
                    <p className="text-slate-500 mt-1">Analisi dettagliata delle prestazioni del team</p>
                </div>
                <div className="flex items-center gap-2">
                    <span className="text-sm text-slate-500">Periodo:</span>
                    <select
                        value={dateRange}
                        onChange={(e) => setDateRange(e.target.value)}
                        className="px-3 py-2 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                    >
                        <option value="all">Tutto il tempo</option>
                        <option value="30d">Ultimi 30 giorni</option>
                        <option value="90d">Ultimi 90 giorni</option>
                        <option value="1y">Ultimo anno</option>
                    </select>
                </div>
            </div>

            {/* KPI Cards */}
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                <Card className="p-4">
                    <div className="text-sm text-slate-500">Totale Pratiche</div>
                    <div className="text-3xl font-bold text-slate-900 mt-1">{filteredProjects.length}</div>
                </Card>
                <Card className="p-4">
                    <div className="text-sm text-slate-500">Completate</div>
                    <div className="text-3xl font-bold text-green-600 mt-1">{analytics.totals.completed}</div>
                </Card>
                <Card className="p-4">
                    <div className="text-sm text-slate-500">Annullate</div>
                    <div className="text-3xl font-bold text-red-600 mt-1">{analytics.totals.cancelled}</div>
                </Card>
                <Card className="p-4">
                    <div className="text-sm text-slate-500">In Corso</div>
                    <div className="text-3xl font-bold text-blue-600 mt-1">{analytics.totals.active}</div>
                </Card>
                <Card className="p-4">
                    <div className="text-sm text-slate-500">Tasso Completamento</div>
                    <div className="text-3xl font-bold text-slate-900 mt-1">{completionRate}%</div>
                    <div className="w-full bg-slate-200 rounded-full h-1.5 mt-2">
                        <div className="bg-green-500 h-1.5 rounded-full" style={{ width: `${completionRate}%` }}></div>
                    </div>
                </Card>
                <Card className="p-4">
                    <div className="text-sm text-slate-500">Puntualita</div>
                    <div className="text-3xl font-bold text-slate-900 mt-1">{punctualityRate}%</div>
                    <div className="w-full bg-slate-200 rounded-full h-1.5 mt-2">
                        <div className="bg-blue-500 h-1.5 rounded-full" style={{ width: `${punctualityRate}%` }}></div>
                    </div>
                </Card>
            </div>

            {/* Monthly Trends Chart - Full width under KPIs */}
            {analytics.months.length > 0 && (
                <Card className="p-6">
                    <h2 className="text-lg font-semibold text-slate-900 mb-4">Andamento Mensile</h2>
                    <div className="h-56">
                        <div className="flex items-end justify-between h-40 gap-2">
                            {analytics.months.map(([monthKey, data]) => {
                                const maxVal = Math.max(
                                    ...analytics.months.map(([_, d]) => Math.max(d.completed, d.cancelled, d.created))
                                );
                                const completedHeight = maxVal > 0 ? (data.completed / maxVal) * 100 : 0;
                                const cancelledHeight = maxVal > 0 ? (data.cancelled / maxVal) * 100 : 0;

                                return (
                                    <div key={monthKey} className="flex-1 flex flex-col items-center gap-1">
                                        <div className="flex gap-1 items-end h-32 w-full justify-center">
                                            <div
                                                className="w-4 bg-green-500 rounded-t transition-all"
                                                style={{ height: `${completedHeight}%`, minHeight: data.completed > 0 ? '4px' : '0' }}
                                                title={`Completate: ${data.completed}`}
                                            ></div>
                                            <div
                                                className="w-4 bg-red-400 rounded-t transition-all"
                                                style={{ height: `${cancelledHeight}%`, minHeight: data.cancelled > 0 ? '4px' : '0' }}
                                                title={`Annullate: ${data.cancelled}`}
                                            ></div>
                                        </div>
                                        <span className="text-xs text-slate-500 mt-2">{formatMonth(monthKey)}</span>
                                    </div>
                                );
                            })}
                        </div>
                        <div className="flex items-center justify-center gap-6 mt-4">
                            <div className="flex items-center gap-2">
                                <div className="w-3 h-3 rounded bg-green-500"></div>
                                <span className="text-sm text-slate-600">Completate</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <div className="w-3 h-3 rounded bg-red-400"></div>
                                <span className="text-sm text-slate-600">Annullate</span>
                            </div>
                        </div>
                    </div>
                </Card>
            )}

            {/* Team Ranking - Full Width */}
            <Card className="p-6">
                <h2 className="text-lg font-semibold text-slate-900 mb-4 flex items-center gap-2">
                    <svg className="w-5 h-5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                    </svg>
                    Classifica Team
                </h2>

                        {analytics.users.length === 0 ? (
                            <p className="text-slate-500 text-center py-8">Nessun dato disponibile</p>
                        ) : (
                            <div className="overflow-x-auto">
                                <table className="w-full">
                                    <thead>
                                        <tr className="text-left text-xs font-medium text-slate-500 uppercase tracking-wider border-b border-slate-100">
                                            <th className="pb-3 pl-2">Pos.</th>
                                            <th className="pb-3">Utente</th>
                                            <th className="pb-3 text-center">Completate</th>
                                            <th className="pb-3 text-center">Annullate</th>
                                            <th className="pb-3 text-center">In Tempo</th>
                                            <th className="pb-3 text-center">In Ritardo</th>
                                            <th className="pb-3 text-center">Puntualita</th>
                                            <th className="pb-3 text-center">Tempo Medio</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-slate-100">
                                        {analytics.users.map((member, index) => (
                                                <tr
                                                    key={member.id}
                                                    className="hover:bg-slate-50 cursor-pointer transition-colors"
                                                    onClick={() => setSelectedUser(member)}
                                                >
                                                    <td className="py-3 pl-2">
                                                        <span className="text-sm text-slate-500 font-medium">#{index + 1}</span>
                                                    </td>
                                                    <td className="py-3">
                                                        <div className="flex items-center gap-3">
                                                            {member.avatar ? (
                                                                <img
                                                                    src={window.ApiUsers?.getAvatarUrl(member.avatar)}
                                                                    alt={member.name}
                                                                    className="w-8 h-8 rounded-full object-cover"
                                                                />
                                                            ) : (
                                                                <div className={`w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-medium ${getAvatarColor(member.name)}`}>
                                                                    {getInitials(member.name)}
                                                                </div>
                                                            )}
                                                            <div>
                                                                <div className="font-medium text-slate-900">{member.name}</div>
                                                                <div className="text-xs text-slate-500">{member.email}</div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td className="py-3 text-center">
                                                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-700">
                                                            {member.completedProjects}
                                                        </span>
                                                    </td>
                                                    <td className="py-3 text-center">
                                                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-700">
                                                            {member.cancelledProjects}
                                                        </span>
                                                    </td>
                                                    <td className="py-3 text-center">
                                                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-700">
                                                            {member.completedOnTime}
                                                        </span>
                                                    </td>
                                                    <td className="py-3 text-center">
                                                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-amber-100 text-amber-700">
                                                            {member.completedLate}
                                                        </span>
                                                    </td>
                                                    <td className="py-3 text-center">
                                                        <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-bold ${
                                                            member.successRate >= 80 ? 'bg-green-100 text-green-700' :
                                                            member.successRate >= 50 ? 'bg-amber-100 text-amber-700' : 'bg-red-100 text-red-700'
                                                        }`}>
                                                            {member.successRate}%
                                                        </span>
                                                    </td>
                                                    <td className="py-3 text-center text-sm text-slate-600">
                                                        {member.avgCompletionDays !== null ? `${member.avgCompletionDays}g` : '-'}
                                                    </td>
                                                </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        )}
            </Card>

            {/* Bottom Row - Esito Pratiche and Motivi Annullamento side by side */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Completion vs Cancellation Donut */}
                <Card className="p-6">
                    <h2 className="text-lg font-semibold text-slate-900 mb-4">Esito Pratiche</h2>
                    <div className="flex items-center justify-center">
                        <div className="relative w-40 h-40">
                            <svg className="w-full h-full transform -rotate-90" viewBox="0 0 100 100">
                                {/* Background circle */}
                                <circle
                                    cx="50"
                                    cy="50"
                                    r="40"
                                    fill="none"
                                    stroke="#e2e8f0"
                                    strokeWidth="12"
                                />
                                {/* Completed arc */}
                                {totalClosed > 0 && (
                                    <circle
                                        cx="50"
                                        cy="50"
                                        r="40"
                                        fill="none"
                                        stroke="#22c55e"
                                        strokeWidth="12"
                                        strokeDasharray={`${(analytics.totals.completed / totalClosed) * 251.2} 251.2`}
                                        strokeLinecap="round"
                                    />
                                )}
                            </svg>
                            <div className="absolute inset-0 flex flex-col items-center justify-center">
                                <span className="text-2xl font-bold text-slate-900">{completionRate}%</span>
                                <span className="text-xs text-slate-500">successo</span>
                            </div>
                        </div>
                    </div>
                    <div className="mt-4 flex items-center justify-center gap-6">
                        <div className="flex items-center gap-2">
                            <div className="w-3 h-3 rounded-full bg-green-500"></div>
                            <span className="text-sm text-slate-600">Completate ({analytics.totals.completed})</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <div className="w-3 h-3 rounded-full bg-slate-200"></div>
                            <span className="text-sm text-slate-600">Annullate ({analytics.totals.cancelled})</span>
                        </div>
                    </div>
                </Card>

                {/* Cancellation Reasons - Horizontal Bar Chart */}
                <Card className="p-6">
                    <h2 className="text-lg font-semibold text-slate-900 mb-4">Motivi Annullamento</h2>
                    {analytics.reasons.length === 0 ? (
                        <p className="text-sm text-slate-500 text-center py-4">
                            Nessuna pratica annullata con motivo specificato
                        </p>
                    ) : (
                        <div className="space-y-3">
                            {(() => {
                                const maxCount = Math.max(...analytics.reasons.slice(0, 6).map(r => r.count));
                                return analytics.reasons.slice(0, 6).map((item, index) => {
                                    const barWidth = maxCount > 0 ? (item.count / maxCount) * 100 : 0;
                                    return (
                                        <div key={index} className="group">
                                            <div className="flex items-center justify-between mb-1">
                                                <p className="text-sm text-slate-700 truncate flex-1 pr-2" title={item.reason}>
                                                    {item.reason.length > 30 ? item.reason.substring(0, 30) + '...' : item.reason}
                                                </p>
                                                <span className="text-sm font-semibold text-red-600 flex-shrink-0">{item.count}</span>
                                            </div>
                                            <div className="w-full bg-slate-100 rounded-full h-2.5">
                                                <div
                                                    className="bg-red-500 h-2.5 rounded-full transition-all duration-300"
                                                    style={{ width: `${barWidth}%` }}
                                                ></div>
                                            </div>
                                        </div>
                                    );
                                });
                            })()}
                            {analytics.reasons.length > 6 && (
                                <p className="text-xs text-slate-400 text-center pt-2">
                                    +{analytics.reasons.length - 6} altri motivi
                                </p>
                            )}
                        </div>
                    )}
                </Card>
            </div>

            {/* User Detail Modal */}
            {selectedUser && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
                    <div className="bg-white rounded-xl shadow-xl max-w-lg w-full max-h-[90vh] overflow-y-auto">
                        <div className="p-6 border-b border-slate-100">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-4">
                                    {selectedUser.avatar ? (
                                        <img
                                            src={window.ApiUsers?.getAvatarUrl(selectedUser.avatar)}
                                            alt={selectedUser.name}
                                            className="w-14 h-14 rounded-full object-cover"
                                        />
                                    ) : (
                                        <div className={`w-14 h-14 rounded-full flex items-center justify-center text-white text-lg font-medium ${getAvatarColor(selectedUser.name)}`}>
                                            {getInitials(selectedUser.name)}
                                        </div>
                                    )}
                                    <div>
                                        <h3 className="text-xl font-semibold text-slate-900">{selectedUser.name}</h3>
                                        <p className="text-sm text-slate-500">{selectedUser.email}</p>
                                    </div>
                                </div>
                                <button
                                    onClick={() => setSelectedUser(null)}
                                    className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg"
                                >
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                        <div className="p-6 space-y-6">
                            {/* Stats Grid */}
                            <div className="grid grid-cols-2 gap-4">
                                <div className="bg-slate-50 rounded-lg p-4 text-center">
                                    <div className="text-2xl font-bold text-slate-900">{selectedUser.totalProjects}</div>
                                    <div className="text-sm text-slate-500">Totale Pratiche</div>
                                </div>
                                <div className="bg-green-50 rounded-lg p-4 text-center">
                                    <div className="text-2xl font-bold text-green-600">{selectedUser.completedProjects}</div>
                                    <div className="text-sm text-green-700">Completate</div>
                                </div>
                                <div className="bg-red-50 rounded-lg p-4 text-center">
                                    <div className="text-2xl font-bold text-red-600">{selectedUser.cancelledProjects}</div>
                                    <div className="text-sm text-red-700">Annullate</div>
                                </div>
                                <div className="bg-blue-50 rounded-lg p-4 text-center">
                                    <div className="text-2xl font-bold text-blue-600">{selectedUser.activeProjects}</div>
                                    <div className="text-sm text-blue-700">In Corso</div>
                                </div>
                            </div>

                            {/* Performance Metrics */}
                            <div className="space-y-4">
                                <h4 className="font-medium text-slate-900">Metriche di Performance</h4>

                                <div>
                                    <div className="flex justify-between text-sm mb-1">
                                        <span className="text-slate-600">Puntualita</span>
                                        <span className="font-medium text-slate-900">{selectedUser.successRate}%</span>
                                    </div>
                                    <div className="w-full bg-slate-200 rounded-full h-2">
                                        <div
                                            className={`h-2 rounded-full ${
                                                selectedUser.successRate >= 80 ? 'bg-green-500' :
                                                selectedUser.successRate >= 50 ? 'bg-amber-500' : 'bg-red-500'
                                            }`}
                                            style={{ width: `${selectedUser.successRate}%` }}
                                        ></div>
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4 pt-2">
                                    <div className="flex items-center justify-between p-3 bg-slate-50 rounded-lg">
                                        <span className="text-sm text-slate-600">In Tempo</span>
                                        <span className="font-semibold text-blue-600">{selectedUser.completedOnTime}</span>
                                    </div>
                                    <div className="flex items-center justify-between p-3 bg-slate-50 rounded-lg">
                                        <span className="text-sm text-slate-600">In Ritardo</span>
                                        <span className="font-semibold text-amber-600">{selectedUser.completedLate}</span>
                                    </div>
                                </div>

                                {selectedUser.avgCompletionDays !== null && (
                                    <div className="flex items-center justify-between p-3 bg-slate-50 rounded-lg">
                                        <span className="text-sm text-slate-600">Tempo Medio Completamento</span>
                                        <span className="font-semibold text-slate-900">{selectedUser.avgCompletionDays} giorni</span>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

window.PerformanceView = PerformanceView;
