// DueDateAlertsWidget - Shows projects with approaching/overdue deadlines
function DueDateAlertsWidget({ projects, onViewChange }) {
    // Categorize projects by deadline urgency
    const categorizedProjects = React.useMemo(() => {
        const now = new Date();
        now.setHours(0, 0, 0, 0);

        const overdue = [];
        const urgent = [];
        const upcoming = [];

        projects.forEach(p => {
            if (!p.due_date || p.status === 'completato' || p.is_archived) return;

            const due = new Date(p.due_date);
            due.setHours(0, 0, 0, 0);
            const daysUntil = Math.ceil((due - now) / (1000 * 60 * 60 * 24));

            const projectWithDays = { ...p, daysUntil };

            if (daysUntil < 0) {
                overdue.push(projectWithDays);
            } else if (daysUntil <= 3) {
                urgent.push(projectWithDays);
            } else if (daysUntil <= 7) {
                upcoming.push(projectWithDays);
            }
        });

        // Sort each category by urgency
        overdue.sort((a, b) => a.daysUntil - b.daysUntil);
        urgent.sort((a, b) => a.daysUntil - b.daysUntil);
        upcoming.sort((a, b) => a.daysUntil - b.daysUntil);

        return { overdue, urgent, upcoming };
    }, [projects]);

    const totalAlerts = categorizedProjects.overdue.length +
                       categorizedProjects.urgent.length +
                       categorizedProjects.upcoming.length;

    // Get badge style based on category
    const getBadgeStyle = (category) => {
        switch (category) {
            case 'overdue':
                return 'bg-red-100 text-red-700 border-red-200';
            case 'urgent':
                return 'bg-amber-100 text-amber-700 border-amber-200';
            case 'upcoming':
                return 'bg-blue-100 text-blue-700 border-blue-200';
            default:
                return 'bg-slate-100 text-slate-700 border-slate-200';
        }
    };

    // Get label based on days
    const getDaysLabel = (daysUntil) => {
        if (daysUntil < 0) {
            const days = Math.abs(daysUntil);
            return days === 1 ? 'Scaduto ieri' : `Scaduto da ${days} giorni`;
        } else if (daysUntil === 0) {
            return 'Scade oggi';
        } else if (daysUntil === 1) {
            return 'Scade domani';
        } else {
            return `Scade tra ${daysUntil} giorni`;
        }
    };

    // Get priority badge
    const getPriorityBadge = (priority) => {
        const styles = {
            high: 'bg-red-50 text-red-600',
            medium: 'bg-amber-50 text-amber-600',
            low: 'bg-slate-50 text-slate-600'
        };
        const labels = {
            high: 'Alta',
            medium: 'Media',
            low: 'Bassa'
        };
        return (
            <span className={`text-xs px-1.5 py-0.5 rounded ${styles[priority] || styles.low}`}>
                {labels[priority] || priority}
            </span>
        );
    };

    // Render a project item
    const renderProjectItem = (project, category) => (
        <div
            key={project.id}
            className={`flex items-center gap-3 px-4 py-3 rounded-lg border cursor-pointer
                       transition-all hover:shadow-sm ${getBadgeStyle(category)}`}
            onClick={() => onViewChange('projects')}
        >
            <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                    <span className="font-medium text-sm truncate">{project.name}</span>
                    {getPriorityBadge(project.priority)}
                </div>
                <div className="text-xs mt-0.5 opacity-80">
                    {getDaysLabel(project.daysUntil)}
                    {project.due_date && (
                        <span className="ml-2">
                            ({Formatters.formatDate(project.due_date)})
                        </span>
                    )}
                </div>
            </div>
            <svg className="w-4 h-4 opacity-50 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
        </div>
    );

    if (totalAlerts === 0) {
        return null; // Don't render if no alerts
    }

    // Combine all items, limited to 5
    const allItems = [
        ...categorizedProjects.overdue.map(p => ({ ...p, category: 'overdue' })),
        ...categorizedProjects.urgent.map(p => ({ ...p, category: 'urgent' })),
        ...categorizedProjects.upcoming.map(p => ({ ...p, category: 'upcoming' }))
    ].slice(0, 5);

    const hasMore = totalAlerts > 5;

    return (
        <Card className="p-4">
            <div className="flex items-center justify-between mb-3">
                <h3 className="font-semibold text-slate-900 flex items-center gap-2">
                    <svg className="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                              d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    Scadenze
                    {totalAlerts > 0 && (
                        <span className="text-xs font-normal px-2 py-0.5 rounded-full bg-red-100 text-red-600">
                            {totalAlerts}
                        </span>
                    )}
                </h3>
                {hasMore && (
                    <button
                        onClick={() => onViewChange('projects')}
                        className="text-sm text-brand-600 hover:text-brand-700 font-medium"
                    >
                        Vedi tutti
                    </button>
                )}
            </div>

            {/* Summary badges */}
            <div className="flex gap-2 mb-3 flex-wrap">
                {categorizedProjects.overdue.length > 0 && (
                    <span className="text-xs px-2 py-1 rounded-full bg-red-100 text-red-700">
                        {categorizedProjects.overdue.length} scaduti
                    </span>
                )}
                {categorizedProjects.urgent.length > 0 && (
                    <span className="text-xs px-2 py-1 rounded-full bg-amber-100 text-amber-700">
                        {categorizedProjects.urgent.length} urgenti
                    </span>
                )}
                {categorizedProjects.upcoming.length > 0 && (
                    <span className="text-xs px-2 py-1 rounded-full bg-blue-100 text-blue-700">
                        {categorizedProjects.upcoming.length} in arrivo
                    </span>
                )}
            </div>

            {/* Project list */}
            <div className="space-y-2">
                {allItems.map(project => renderProjectItem(project, project.category))}
            </div>
        </Card>
    );
}

window.DueDateAlertsWidget = DueDateAlertsWidget;
