// ProjectsView - Gestione progetti per tutti gli utenti

function ProjectsView({ pendingProjectId, onPendingHandled, onViewProject }) {
    const { user: currentUser, isAdmin } = useAuth();
    const toast = useToast();

    // Permission checks for specific actions
    const canCreate = isAdmin || currentUser?.can_create_projects;
    const canUpdate = isAdmin || currentUser?.can_update_projects;
    const canDelete = isAdmin || currentUser?.can_delete_projects;
    const [projects, setProjects] = React.useState([]);
    const [archivedProjects, setArchivedProjects] = React.useState([]);
    const [users, setUsers] = React.useState([]);
    const [referenti, setReferenti] = React.useState([]);
    const [timelines, setTimelines] = React.useState({});
    const [loading, setLoading] = React.useState(true);
    const [showCreateModal, setShowCreateModal] = React.useState(false);
    const [editingProject, setEditingProject] = React.useState(null);
    const [assigningProject, setAssigningProject] = React.useState(null);
    const [timelineProject, setTimelineProject] = React.useState(null);
    const [activeTab, setActiveTab] = React.useState('active'); // 'active' or 'archived'
    const [confirmModal, setConfirmModal] = React.useState(null); // { type, project }

    const loadData = async () => {
        setLoading(true);

        // Small delay to ensure backend has committed changes
        await new Promise(resolve => setTimeout(resolve, 100));

        // Check permissions at load time using current user state
        const hasDeletePermission = isAdmin || currentUser?.can_delete_projects;

        try {
            // Only fetch what the user has permission to see:
            // - archived projects: only if can delete
            // - users list: admin gets full list, users with can_update_projects get assignable users (excludes admins)
            const hasUpdatePermission = isAdmin || currentUser?.can_update_projects;
            const [projectsData, archivedData, usersData, referentiData] = await Promise.all([
                ApiUtils.fetchProjects(true),
                hasDeletePermission ? ApiUtils.fetchArchivedProjects() : Promise.resolve([]),
                isAdmin ? ApiUtils.fetchUsers(true) : (hasUpdatePermission ? ApiUtils.fetchUsersForAssignment() : Promise.resolve([])),
                ApiUtils.fetchReferenti(null, false),
            ]);
            // Sort by creation time (newest first) and force new array references for React to detect changes
            const sortByCreatedAt = (a, b) => new Date(b.created_at) - new Date(a.created_at);
            setProjects(projectsData.sort(sortByCreatedAt).map(p => ({ ...p, _key: Date.now() })));
            setArchivedProjects(archivedData.sort(sortByCreatedAt).map(p => ({ ...p, _key: Date.now() })));
            // For admin users, filter by is_active; for non-admin, the endpoint already returns only assignable users
            setUsers(isAdmin ? usersData.filter(u => u.is_active).map(u => ({ ...u, _key: Date.now() })) : usersData.map(u => ({ ...u, _key: Date.now() })));
            setReferenti(referentiData.filter(r => r.is_active).map(r => ({ ...r, _key: Date.now() })));
            
            // Fetch timeline data for all projects (active and archived)
            const allProjects = [...projectsData, ...archivedData];
            const timelinePromises = allProjects.map(async (project) => {
                try {
                    const timeline = await ApiUtils.getProjectTimeline(project.id, false);
                    return { projectId: project.id, timeline };
                } catch (err) {
                    console.error(`Failed to load timeline for project ${project.id}:`, err);
                    return { projectId: project.id, timeline: null };
                }
            });
            
            const timelineResults = await Promise.all(timelinePromises);
            const timelinesMap = {};
            timelineResults.forEach(({ projectId, timeline }) => {
                timelinesMap[projectId] = timeline;
            });
            setTimelines(timelinesMap);
        } catch (err) {
            toast('Errore nel caricamento dati: ' + err.message, 'error');
        } finally {
            setLoading(false);
        }
    };

    React.useEffect(() => {
        // Wait for user to be loaded before fetching data
        if (currentUser) {
            loadData();
        }
    }, [currentUser]);

    // Handle pending project from notification click
    React.useEffect(() => {
        if (pendingProjectId && !loading) {
            // Look in both active and archived projects
            const allProjects = [...projects, ...archivedProjects];
            const project = allProjects.find(p => p.id === pendingProjectId);
            if (project) {
                // Switch to correct tab if needed
                if (archivedProjects.find(p => p.id === pendingProjectId)) {
                    setActiveTab('archived');
                } else {
                    setActiveTab('active');
                }
                setTimelineProject(project);
            }
            // Clear the pending project
            if (onPendingHandled) {
                onPendingHandled();
            }
        }
    }, [pendingProjectId, projects, archivedProjects, loading, onPendingHandled]);

    const getProgressInfo = (projectId) => {
        const timeline = timelines[projectId];
        if (!timeline || !timeline.steps || timeline.steps.length === 0) {
            return { completed: 0, total: 0, percent: 0, lastUpdated: null };
        }
        
        const completed = timeline.steps.filter(s => s.status === 'completato').length;
        const total = timeline.steps.length;
        const percent = Math.round((completed / total) * 100);
        
        // Find the most recent update across all steps
        let lastUpdated = null;
        timeline.steps.forEach(step => {
            const stepDate = step.updated_at ? new Date(step.updated_at) : null;
            if (stepDate && (!lastUpdated || stepDate > lastUpdated)) {
                lastUpdated = stepDate;
            }
        });
        
        return { completed, total, percent, lastUpdated };
    };

    // Use shared utilities
    const formatRelativeTime = Formatters.formatRelativeTime;

    const getProjectReferenti = (projectId) => {
        return referenti.filter(r => r.project_ids && r.project_ids.includes(projectId));
    };

    const getProjectAssignees = (project) => {
        if (!project.assignments || project.assignments.length === 0) return [];
        return project.assignments.map(a => ({
            id: a.user_id,
            name: a.user_name || a.user_email,
            email: a.user_email,
            avatar: a.user_avatar
        }));
    };

    // Refresh timeline data for a specific project after step changes
    const refreshProjectTimeline = async (projectId) => {
        try {
            const timeline = await ApiUtils.getProjectTimeline(projectId, false);
            setTimelines(prev => ({
                ...prev,
                [projectId]: timeline
            }));
        } catch (err) {
            console.error(`Failed to refresh timeline for project ${projectId}:`, err);
        }
    };

    const handleArchive = (project) => {
        setConfirmModal({
            type: 'archive',
            project,
            title: 'Archivia Pratica',
            message: `Sei sicuro di voler archiviare la pratica "${project.name}"?\n\nLa pratica sarà nascosta dalla lista principale ma potrà essere ripristinata.`,
            confirmText: 'Archivia',
            variant: 'warning',
        });
    };

    const handleUnarchive = (project) => {
        setConfirmModal({
            type: 'unarchive',
            project,
            title: 'Ripristina Pratica',
            message: `Sei sicuro di voler ripristinare la pratica "${project.name}"?`,
            confirmText: 'Ripristina',
            variant: 'info',
        });
    };

    const handleCancel = (project) => {
        setConfirmModal({
            type: 'cancel',
            project,
            title: 'Annulla Pratica',
            message: `Sei sicuro di voler annullare la pratica "${project.name}"?\n\nIl workflow sara bloccato e non sara possibile modificare gli stati degli step.`,
            confirmText: 'Annulla Pratica',
            variant: 'danger',
        });
    };

    const handleUncancel = (project) => {
        setConfirmModal({
            type: 'uncancel',
            project,
            title: 'Ripristina Pratica',
            message: `Sei sicuro di voler ripristinare la pratica "${project.name}"?\n\nIl workflow sara sbloccato.`,
            confirmText: 'Ripristina',
            variant: 'info',
        });
    };

    const handlePermanentDelete = (project) => {
        setConfirmModal({
            type: 'permanent_delete',
            project,
            title: 'Elimina Definitivamente',
            message: `Sei sicuro di voler eliminare DEFINITIVAMENTE la pratica "${project.name}"?\n\nQuesta azione è IRREVERSIBILE. Tutti i dati associati (workflow, commenti, assegnazioni) verranno eliminati permanentemente.`,
            confirmText: 'Elimina Definitivamente',
            variant: 'danger',
        });
    };

    const executeConfirmedAction = async () => {
        if (!confirmModal) return;
        
        const { type, project } = confirmModal;
        setConfirmModal({ ...confirmModal, loading: true });
        
        try {
            if (type === 'archive') {
                await ApiUtils.archiveProject(project.id);
                toast('Pratica archiviata con successo', 'success');
            } else if (type === 'unarchive') {
                await ApiUtils.unarchiveProject(project.id);
                toast('Pratica ripristinata con successo', 'success');
            } else if (type === 'cancel') {
                await ApiUtils.cancelProject(project.id);
                toast('Pratica annullata', 'success');
            } else if (type === 'uncancel') {
                await ApiUtils.uncancelProject(project.id);
                toast('Pratica ripristinata', 'success');
            } else if (type === 'permanent_delete') {
                await ApiUtils.permanentlyDeleteProject(project.id);
                toast('Pratica eliminata definitivamente', 'success');
            }
            setConfirmModal(null);
            loadData();
        } catch (err) {
            const errorMsgs = {
                'archive': 'Errore nell\'archiviazione: ',
                'unarchive': 'Errore nel ripristino: ',
                'cancel': 'Errore nell\'annullamento: ',
                'uncancel': 'Errore nel ripristino: ',
                'permanent_delete': 'Errore nell\'eliminazione: ',
            };
            toast((errorMsgs[type] || 'Errore: ') + err.message, 'error');
            setConfirmModal(null);
        }
    };

    return (
        <div className="p-6 space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h2 className="text-2xl font-bold text-slate-800">Gestione Pratiche</h2>
                    <p className="text-slate-500 mt-1">Gestisci tutti i progetti e le assegnazioni utenti</p>
                </div>
                {canCreate && (
                    <button
                        onClick={() => setShowCreateModal(true)}
                        className="flex items-center gap-2 px-4 py-2 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-lg transition-colors"
                    >
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        Nuova Pratica
                    </button>
                )}
            </div>

            {/* Tabs - only show archive tab if user can delete */}
            {canDelete && (
                <div className="flex gap-4 border-b border-slate-200">
                    <button
                        onClick={() => setActiveTab('active')}
                        className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                            activeTab === 'active'
                                ? 'border-brand-500 text-brand-600'
                                : 'border-transparent text-slate-500 hover:text-slate-700'
                        }`}
                    >
                        Pratiche Attive
                        <span className="ml-2 px-2 py-0.5 text-xs rounded-full bg-slate-100 text-slate-600">
                            {projects.length}
                        </span>
                    </button>
                    <button
                        onClick={() => setActiveTab('archived')}
                        className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                            activeTab === 'archived'
                                ? 'border-brand-500 text-brand-600'
                                : 'border-transparent text-slate-500 hover:text-slate-700'
                        }`}
                    >
                        Archivio
                        <span className="ml-2 px-2 py-0.5 text-xs rounded-full bg-slate-100 text-slate-600">
                            {archivedProjects.length}
                        </span>
                    </button>
                </div>
            )}

            {/* Gantt Chart - Only show for active tab with projects */}
            {!loading && activeTab === 'active' && projects.length > 0 && (
                <ProjectGanttChart
                    projects={projects}
                    onProjectClick={onViewProject}
                />
            )}

            {/* Projects Content */}
            {loading ? (
                <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-12 text-center">
                    <Spinner size="lg" />
                    <p className="text-slate-500 mt-4">Caricamento progetti...</p>
                </div>
            ) : activeTab === 'active' && projects.length === 0 ? (
                <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-12 text-center">
                    <svg className="w-16 h-16 text-slate-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
                    </svg>
                    <p className="text-slate-500">Nessuna pratica trovata</p>
                    {canCreate && (
                        <button
                            onClick={() => setShowCreateModal(true)}
                            className="mt-4 text-brand-500 hover:text-brand-600 font-medium"
                        >
                            Crea la prima pratica
                        </button>
                    )}
                </div>
            ) : activeTab === 'archived' && archivedProjects.length === 0 ? (
                <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-12 text-center">
                    <svg className="w-16 h-16 text-slate-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
                    </svg>
                    <p className="text-slate-500">Nessuna pratica archiviata</p>
                </div>
            ) : activeTab === 'active' ? (
                /* Active Projects Grid - Compact Cards */
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                    {projects.map(project => {
                        const progressInfo = getProgressInfo(project.id);
                        const assignees = getProjectAssignees(project);

                        return (
                            <div
                                key={project.id}
                                className={`bg-white rounded-lg shadow-sm border overflow-hidden hover:shadow-md transition-shadow cursor-pointer relative ${
                                    project.is_cancelled
                                        ? 'border-red-200 opacity-75'
                                        : 'border-slate-200'
                                }`}
                                onClick={() => onViewProject && onViewProject(project.id)}
                            >
                                {/* Cancelled Banner */}
                                {project.is_cancelled && (
                                    <div className="absolute top-0 left-0 right-0 bg-red-500/90 text-white text-xs font-bold text-center py-1 uppercase tracking-wide z-10">
                                        Annullato
                                    </div>
                                )}

                                {/* Progress Bar */}
                                <div className={`h-1.5 bg-slate-100 ${project.is_cancelled ? 'mt-6' : ''}`}>
                                    <div
                                        className={`h-full transition-all duration-500 ${StatusBadge.getProgressColor(progressInfo.percent)}`}
                                        style={{ width: `${progressInfo.percent}%` }}
                                    />
                                </div>

                                <div className="p-4">
                                    {/* Header: Name & Priority */}
                                    <div className="flex items-start justify-between gap-2 mb-3">
                                        <h3 className={`font-semibold text-sm leading-tight line-clamp-2 ${project.is_cancelled ? 'text-slate-500' : 'text-slate-800'}`}>{project.name}</h3>
                                        <PriorityBadge priority={project.priority} size="sm" />
                                    </div>

                                    {/* Progress & Scadenza Row */}
                                    <div className="flex items-center justify-between text-xs mb-3">
                                        <span className={`px-2 py-0.5 rounded-full font-medium ${
                                            progressInfo.percent === 100
                                                ? 'bg-green-100 text-green-700'
                                                : progressInfo.percent >= 50
                                                    ? 'bg-blue-100 text-blue-700'
                                                    : progressInfo.percent > 0
                                                        ? 'bg-amber-100 text-amber-700'
                                                        : 'bg-slate-100 text-slate-500'
                                        }`}>
                                            {progressInfo.percent}%
                                        </span>
                                        <span className={`flex items-center gap-1 ${project.due_date ? 'text-slate-600' : 'text-slate-400'}`}>
                                            <svg className="w-3.5 h-3.5" 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>
                                            {project.due_date
                                                ? new Date(project.due_date).toLocaleDateString('it-IT', { day: '2-digit', month: 'short' })
                                                : '-'
                                            }
                                        </span>
                                    </div>

                                    {/* Assignees */}
                                    <div className="flex items-center justify-between">
                                        <div className="flex items-center -space-x-1.5">
                                            {assignees.length > 0 ? (
                                                <>
                                                    {assignees.slice(0, 3).map((user, i) => {
                                                        const initials = user.name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
                                                        const avatarUrl = user.avatar ? window.ApiUsers?.getAvatarUrl(user.avatar) : null;
                                                        return avatarUrl ? (
                                                            <img
                                                                key={user.id}
                                                                src={avatarUrl}
                                                                alt={user.name}
                                                                className="w-6 h-6 rounded-full border-2 border-white object-cover"
                                                                title={user.name}
                                                            />
                                                        ) : (
                                                            <div
                                                                key={user.id}
                                                                className="w-6 h-6 rounded-full bg-blue-100 border-2 border-white flex items-center justify-center"
                                                                title={user.name}
                                                            >
                                                                <span className="text-[10px] font-medium text-blue-700">{initials}</span>
                                                            </div>
                                                        );
                                                    })}
                                                    {assignees.length > 3 && (
                                                        <div
                                                            className="w-6 h-6 rounded-full bg-slate-200 border-2 border-white flex items-center justify-center"
                                                            title={assignees.slice(3).map(u => u.name).join(', ')}
                                                        >
                                                            <span className="text-[10px] font-medium text-slate-600">+{assignees.length - 3}</span>
                                                        </div>
                                                    )}
                                                </>
                                            ) : (
                                                <span className="text-xs text-slate-400">Nessuno</span>
                                            )}
                                        </div>

                                        {/* Action buttons */}
                                        <div className="flex items-center gap-1" onClick={e => e.stopPropagation()}>
                                            {canUpdate && (
                                                <button
                                                    onClick={() => setEditingProject(project)}
                                                    className="p-1.5 text-slate-400 hover:text-brand-600 hover:bg-brand-50 rounded transition-colors"
                                                    title="Modifica"
                                                >
                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                    </svg>
                                                </button>
                                            )}
                                            {canDelete && (
                                                <button
                                                    onClick={() => handleArchive(project)}
                                                    className="p-1.5 text-slate-400 hover:text-orange-600 hover:bg-orange-50 rounded transition-colors"
                                                    title="Archivia"
                                                >
                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
                                                    </svg>
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>
            ) : (
                /* Archived Projects Grid */
                <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
                    {archivedProjects.map(project => {
                        const progressInfo = getProgressInfo(project.id);
                        const projectRefs = getProjectReferenti(project.id);
                        const assignees = getProjectAssignees(project);

                        // Determine final status styling
                        const isCancelled = project.is_cancelled;
                        const isCompleted = project.status === 'completed';
                        const statusBadge = isCancelled
                            ? { bg: 'bg-red-100', text: 'text-red-700', label: 'Annullato' }
                            : isCompleted
                                ? { bg: 'bg-green-100', text: 'text-green-700', label: 'Completato' }
                                : { bg: 'bg-slate-200', text: 'text-slate-600', label: 'Archiviato' };

                        return (
                            <div key={project.id} className={`bg-white rounded-xl shadow-sm border overflow-hidden opacity-80 hover:opacity-100 transition-opacity flex flex-col h-full relative ${
                                isCancelled ? 'border-red-200' : isCompleted ? 'border-green-200' : 'border-slate-200'
                            }`}>
                                {/* Status Banner */}
                                {(isCancelled || isCompleted) && (
                                    <div className={`absolute top-0 left-0 right-0 text-white text-xs font-bold text-center py-1 uppercase tracking-wide z-10 ${
                                        isCancelled ? 'bg-red-500/90' : 'bg-green-500/90'
                                    }`}>
                                        {statusBadge.label}
                                    </div>
                                )}

                                {/* Progress Header - Clickable */}
                                <div
                                    className={`px-5 pt-4 pb-3 border-b border-slate-100 cursor-pointer hover:bg-slate-50 transition-colors ${(isCancelled || isCompleted) ? 'mt-6' : ''}`}
                                    onClick={() => onViewProject && onViewProject(project.id)}
                                >
                                    <div className="flex items-center justify-between mb-2">
                                        <div className="flex items-center gap-2">
                                            <span className={`px-2 py-0.5 text-xs font-semibold rounded-full ${statusBadge.bg} ${statusBadge.text}`}>
                                                {statusBadge.label}
                                            </span>
                                            <span className={`px-2 py-0.5 text-xs font-bold rounded-full ${
                                                progressInfo.percent === 100
                                                    ? 'bg-green-100 text-green-700'
                                                    : progressInfo.percent >= 50
                                                        ? 'bg-blue-100 text-blue-700'
                                                        : progressInfo.percent > 0
                                                            ? 'bg-amber-100 text-amber-700'
                                                            : 'bg-slate-100 text-slate-500'
                                            }`}>
                                                {progressInfo.completed}/{progressInfo.total}
                                            </span>
                                        </div>
                                        <span className="text-xs text-slate-400">
                                            {project.archived_at 
                                                ? new Date(project.archived_at).toLocaleDateString('it-IT', { day: '2-digit', month: 'short' })
                                                : '-'
                                            }
                                        </span>
                                    </div>
                                    <div className="w-full h-2 bg-slate-100 rounded-full overflow-hidden">
                                        <div 
                                            className={`h-full transition-all duration-500 ${StatusBadge.getProgressColor(progressInfo.percent)}`}
                                            style={{ width: `${progressInfo.percent}%` }}
                                        />
                                    </div>
                                    <div className="mt-1 text-right">
                                        <span className="text-xs font-medium text-slate-500">{progressInfo.percent}%</span>
                                    </div>
                                </div>

                                {/* Main Content - Clickable */}
                                <div
                                    className="p-5 flex-1 flex flex-col cursor-pointer hover:bg-slate-50/50 transition-colors"
                                    onClick={() => onViewProject && onViewProject(project.id)}
                                >
                                    {/* Title & Priority */}
                                    <div className="flex items-start justify-between gap-3 mb-3">
                                        <div>
                                            <h3 className="font-semibold text-slate-800 leading-tight">{project.name}</h3>
                                            <p className="text-xs text-slate-400 font-mono mt-0.5">{project.slug}</p>
                                        </div>
                                        <PriorityBadge priority={project.priority} />
                                    </div>

                                    {/* Meta Info */}
                                    <div className="space-y-2 text-sm mb-4">
                                        <div className="flex items-center gap-2 text-slate-600">
                                            <svg className="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                            </svg>
                                            <span>
                                                {project.start_date
                                                    ? new Date(project.start_date).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', year: 'numeric' })
                                                    : 'Data non impostata'
                                                }
                                            </span>
                                        </div>

                                        {/* Scadenza */}
                                        <div className="flex items-center gap-2 text-slate-600">
                                            <svg className="w-4 h-4 text-slate-400 flex-shrink-0" 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>
                                            <span className="text-slate-500">Scadenza:</span>
                                            <span className={project.due_date ? '' : 'text-slate-400'}>
                                                {project.due_date
                                                    ? new Date(project.due_date).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', year: 'numeric' })
                                                    : 'Non impostata'
                                                }
                                            </span>
                                        </div>

                                        {/* Creato da */}
                                        <div className="flex items-center gap-2 text-slate-600">
                                            <svg className="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                            </svg>
                                            <span className="text-slate-500">Creato da:</span>
                                            <span className="font-medium">{project.created_by_name || 'N/A'}</span>
                                        </div>

                                        {/* Referenti */}
                                        <div className="flex items-start gap-2">
                                            <svg className="w-4 h-4 text-slate-400 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                            </svg>
                                            <div className="flex flex-wrap gap-1">
                                                {projectRefs.length > 0 ? (
                                                    projectRefs.map(ref => (
                                                        <span 
                                                            key={ref.id}
                                                            className="inline-flex items-center gap-1 px-2 py-0.5 bg-teal-50 text-teal-700 rounded-full text-xs font-medium"
                                                            title={ref.email || ref.phone_number || ''}
                                                        >
                                                            <span className="w-3.5 h-3.5 bg-teal-500 rounded-full flex items-center justify-center text-white text-[9px]">
                                                                {ref.first_name?.charAt(0).toUpperCase()}
                                                            </span>
                                                            {ref.full_name}
                                                        </span>
                                                    ))
                                                ) : (
                                                    <span className="text-slate-400 text-xs">Nessun referente</span>
                                                )}
                                            </div>
                                        </div>

                                        {/* Assignees */}
                                        <div className="flex items-start gap-2">
                                            <svg className="w-4 h-4 text-slate-400 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                                            </svg>
                                            <div className="flex flex-wrap gap-1">
                                                {assignees.length > 0 ? (
                                                    assignees.map(user => (
                                                        <span 
                                                            key={user.id}
                                                            className="inline-flex items-center gap-1 px-2 py-0.5 bg-blue-50 text-blue-700 rounded-full text-xs font-medium"
                                                            title={user.email}
                                                        >
                                                            {user.name}
                                                        </span>
                                                    ))
                                                ) : (
                                                    <span className="text-slate-400 text-xs">Nessun utente assegnato</span>
                                                )}
                                            </div>
                                        </div>
                                    </div>

                                    {/* Description & Notes - flex grow */}
                                    <div className="flex-1 min-h-[40px]">
                                        {project.description && (
                                            <p className="text-sm text-slate-600 line-clamp-2 mb-2">{project.description}</p>
                                        )}
                                        {project.notes && (
                                            <div className="p-2.5 bg-slate-50 rounded-lg border border-slate-100">
                                                <p className="text-xs font-medium text-slate-500 mb-0.5">Note:</p>
                                                <p className="text-sm text-slate-600 line-clamp-2">{project.notes}</p>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Footer Actions */}
                                <div className="px-5 py-4 bg-slate-50 border-t border-slate-100 mt-auto">
                                    <div className="flex items-center gap-2">
                                        <button
                                            onClick={() => setTimelineProject(project)}
                                            className="flex-1 flex items-center justify-center gap-2 px-3 py-2 text-sm font-medium text-white bg-brand-500 hover:bg-brand-600 rounded-lg transition-colors"
                                        >
                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                                            </svg>
                                            Workflow
                                        </button>
                                        {/* Show restore button for all archived projects */}
                                        {canDelete && (
                                            <button
                                                onClick={() => handleUnarchive(project)}
                                                className="p-2 text-green-600 hover:text-green-700 hover:bg-green-50 rounded-lg transition-colors border border-green-200"
                                                title="Ripristina pratica"
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                                                </svg>
                                            </button>
                                        )}
                                        {/* Permanent delete button */}
                                        {canDelete && (
                                            <button
                                                onClick={() => handlePermanentDelete(project)}
                                                className="p-2 text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors border border-red-200"
                                                title="Elimina definitivamente"
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                </svg>
                                            </button>
                                        )}
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}

            {/* Create Project Modal */}
            {showCreateModal && (
                <CreateProjectModal
                    users={users}
                    referenti={referenti}
                    onClose={() => setShowCreateModal(false)}
                    onSuccess={() => {
                        setShowCreateModal(false);
                        loadData();
                        toast('Pratica creata con successo', 'success');
                    }}
                />
            )}

            {/* Edit Project Modal */}
            {editingProject && (
                <EditProjectModal
                    project={editingProject}
                    referenti={referenti}
                    users={users}
                    onClose={() => setEditingProject(null)}
                    onSuccess={() => {
                        setEditingProject(null);
                        loadData();
                        toast('Pratica aggiornata con successo', 'success');
                    }}
                />
            )}

            {/* Assign Users Modal */}
            {assigningProject && (
                <AssignUsersModal
                    project={assigningProject}
                    users={users}
                    onClose={() => setAssigningProject(null)}
                    onSuccess={() => {
                        loadData();
                        toast('Assegnazioni aggiornate con successo', 'success');
                    }}
                />
            )}

            {/* Timeline Modal */}
            {timelineProject && (
                <ProjectTimelineModal
                    project={timelineProject}
                    onClose={() => setTimelineProject(null)}
                    onStepChange={refreshProjectTimeline}
                    canEdit={true}
                    isAssigned={timelineProject.assignments?.some(a => a.user_id === currentUser?.id)}
                />
            )}

            {/* Confirmation Modal */}
            {confirmModal && (
                <ConfirmationModal
                    title={confirmModal.title}
                    message={confirmModal.message}
                    confirmText={confirmModal.confirmText}
                    variant={confirmModal.variant}
                    loading={confirmModal.loading}
                    onConfirm={executeConfirmedAction}
                    onCancel={() => setConfirmModal(null)}
                />
            )}
        </div>
    );
}

window.ProjectsView = ProjectsView;
