// ProjectDetailView - Two-column view for project details and workflow

function ProjectDetailView({ projectId, onBack, focusCommentId, focusStepId, onFocusHandled, onTriggerRegistration, onViewJob }) {
    const { user: currentUser, isAdmin } = useAuth();
    const toast = useToast();
    const [project, setProject] = React.useState(null);
    const [referenti, setReferenti] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [saving, setSaving] = React.useState(false);
    const [description, setDescription] = React.useState('');
    const [hasChanges, setHasChanges] = React.useState(false);

    // Comments state
    const [comments, setComments] = React.useState([]);
    const [loadingComments, setLoadingComments] = React.useState(false);
    const [newComment, setNewComment] = React.useState('');
    const [addingComment, setAddingComment] = React.useState(false);
    const [confirmDelete, setConfirmDelete] = React.useState(null);
    const [actionModal, setActionModal] = React.useState(null); // { type: 'cancel' | 'complete', loading: false }
    const [showCancelForm, setShowCancelForm] = React.useState(false);
    const [selectedCancelReason, setSelectedCancelReason] = React.useState('');
    const [cancelNotes, setCancelNotes] = React.useState('');
    const [cancelLoading, setCancelLoading] = React.useState(false);

    const loadData = async (silent = false) => {
        if (!silent) setLoading(true);
        try {
            // Use getProject to fetch full project data including assignments
            const [projectData, referentiData] = await Promise.all([
                ApiUtils.getProject(projectId),
                ApiUtils.fetchReferenti(null, false),
            ]);

            if (projectData) {
                setProject(projectData);
                setDescription(projectData.description || '');
            }
            setReferenti(referentiData.filter(r => r.is_active));
        } catch (err) {
            if (!silent) toast('Errore nel caricamento dati: ' + err.message, 'error');
        } finally {
            if (!silent) setLoading(false);
        }
    };

    const loadComments = async () => {
        setLoadingComments(true);
        try {
            const commentsData = await ApiUtils.getProjectComments(projectId);
            setComments(commentsData || []);
        } catch (err) {
            toast('Errore nel caricamento commenti: ' + err.message, 'error');
        } finally {
            setLoadingComments(false);
        }
    };

    React.useEffect(() => {
        if (projectId) {
            loadData();
            loadComments();
        }
    }, [projectId]);

    // Handle scrolling to focused project comment (not step comment)
    React.useEffect(() => {
        if (focusCommentId && !focusStepId && !loadingComments && comments.length > 0) {
            // This is a project-level comment - scroll to it
            const commentElement = document.getElementById(`project-comment-${focusCommentId}`);
            if (commentElement) {
                // Scroll the comment into view
                commentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                // Add highlight animation
                commentElement.classList.add('ring-2', 'ring-brand-500', 'ring-offset-2', 'bg-brand-50');
                // Remove highlight after animation
                setTimeout(() => {
                    commentElement.classList.remove('ring-2', 'ring-brand-500', 'ring-offset-2', 'bg-brand-50');
                    if (onFocusHandled) onFocusHandled();
                }, 3000);
            } else if (onFocusHandled) {
                // Comment not found, clear focus state anyway
                onFocusHandled();
            }
        }
    }, [focusCommentId, focusStepId, loadingComments, comments, onFocusHandled]);

    // Track changes (only description now, notes removed)
    React.useEffect(() => {
        if (project) {
            const descChanged = description !== (project.description || '');
            setHasChanges(descChanged);
        }
    }, [description, project]);

    const handleSave = async () => {
        if (!hasChanges) return;

        setSaving(true);
        try {
            await ApiUtils.updateProject(projectId, { description });
            toast('Modifiche salvate con successo', 'success');
            setHasChanges(false);
            // Reload project data
            await loadData();
        } catch (err) {
            toast('Errore nel salvataggio: ' + err.message, 'error');
        } finally {
            setSaving(false);
        }
    };

    const handleAddComment = async () => {
        if (!newComment?.trim()) return;

        setAddingComment(true);
        try {
            await ApiUtils.addProjectComment(projectId, newComment.trim());
            setNewComment('');
            await loadComments();
            toast('Commento aggiunto', 'success');
        } catch (err) {
            toast('Errore nell\'aggiunta commento: ' + err.message, 'error');
        } finally {
            setAddingComment(false);
        }
    };

    const handleDeleteComment = (commentId) => {
        setConfirmDelete({ commentId });
    };

    const executeDelete = async () => {
        if (!confirmDelete) return;

        try {
            await ApiUtils.deleteProjectComment(projectId, confirmDelete.commentId);
            toast('Commento eliminato', 'success');
            setConfirmDelete(null);
            await loadComments();
        } catch (err) {
            toast('Errore nell\'eliminazione: ' + err.message, 'error');
            setConfirmDelete(null);
        }
    };

    const getProjectReferenti = () => {
        if (!project) return [];
        return referenti.filter(r => r.project_ids && r.project_ids.includes(project.id));
    };

    const getProjectAssignees = () => {
        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
        }));
    };

    const formatRelativeTime = Formatters.formatRelativeTime;

    // Check if user can perform project actions (admin or assigned)
    const canPerformActions = isAdmin || project?.assignments?.some(a => a.user_id === currentUser?.id);

    const handleCancelProject = () => {
        setShowCancelForm(true);
        setSelectedCancelReason('');
        setCancelNotes('');
    };

    const executeCancelProject = async () => {
        if (!selectedCancelReason) {
            toast('Seleziona un motivo per l\'annullamento', 'error');
            return;
        }

        // Combine reason and notes
        const fullReason = cancelNotes.trim()
            ? `${selectedCancelReason} - ${cancelNotes.trim()}`
            : selectedCancelReason;

        setCancelLoading(true);
        try {
            await ApiUtils.cancelProject(project.id, fullReason);
            await ApiUtils.archiveProject(project.id);
            toast('Pratica annullata e archiviata', 'success');
            onBack && onBack();
        } catch (err) {
            toast('Errore: ' + err.message, 'error');
        } finally {
            setCancelLoading(false);
            setShowCancelForm(false);
        }
    };

    const handleCompleteProject = () => {
        setActionModal({
            type: 'complete',
            title: 'Chiudi Pratica',
            message: `Sei sicuro di voler chiudere positivamente la pratica "${project?.name}"?\n\nLa pratica verrà marcata come completata.`,
            confirmText: 'Chiudi Pratica',
            variant: 'success',
            loading: false,
        });
    };

    const handleRestoreProject = async () => {
        try {
            // Unarchive also clears cancelled/completed status on the backend
            await ApiUtils.unarchiveProject(project.id);
            toast('Pratica ripristinata', 'success');
            await loadData();
        } catch (err) {
            toast('Errore nel ripristino: ' + err.message, 'error');
        }
    };

    const executeAction = async () => {
        if (!actionModal) return;

        setActionModal({ ...actionModal, loading: true });

        try {
            if (actionModal.type === 'complete') {
                // Set status to completed then archive it
                await ApiUtils.updateProject(project.id, { status: 'completed' });
                await ApiUtils.archiveProject(project.id);
                toast('Pratica chiusa e archiviata con successo', 'success');
                // Go back to list since project is now archived
                onBack && onBack();
            }
            setActionModal(null);
        } catch (err) {
            toast('Errore: ' + err.message, 'error');
            setActionModal(null);
        }
    };

    if (loading) {
        return (
            <div className="p-8">
                <div className="flex items-center gap-4 mb-6">
                    <button
                        onClick={onBack}
                        className="p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-100 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="M10 19l-7-7m0 0l7-7m-7 7h18" />
                        </svg>
                    </button>
                    <span className="text-slate-500">Caricamento...</span>
                </div>
                <div className="text-center py-12">
                    <Spinner size="lg" />
                    <p className="text-slate-500 mt-4">Caricamento pratica...</p>
                </div>
            </div>
        );
    }

    if (!project) {
        return (
            <div className="p-8">
                <div className="flex items-center gap-4 mb-6">
                    <button
                        onClick={onBack}
                        className="p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-100 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="M10 19l-7-7m0 0l7-7m-7 7h18" />
                        </svg>
                    </button>
                </div>
                <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="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <p className="text-slate-500">Pratica non trovata</p>
                    <button
                        onClick={onBack}
                        className="mt-4 text-brand-500 hover:text-brand-600 font-medium"
                    >
                        Torna alla lista pratiche
                    </button>
                </div>
            </div>
        );
    }

    const projectRefs = getProjectReferenti();
    const assignees = getProjectAssignees();
    const isAssigned = project?.assignments?.some(a => a.user_id === currentUser?.id);

    return (
        <div className="p-6 h-full">
            {/* Header with back button */}
            <div className="flex items-center justify-between mb-6">
                <div className="flex items-center gap-4">
                    <button
                        onClick={onBack}
                        className="p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors"
                        title="Torna alla lista"
                    >
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                        </svg>
                    </button>
                    <div>
                        <h1 className="text-2xl font-bold text-slate-800">{project.name}</h1>
                        <p className="text-slate-500 text-sm font-mono">{project.slug}</p>
                    </div>
                    <PriorityBadge priority={project.priority} />
                </div>

                {hasChanges && isAdmin && (
                    <button
                        onClick={handleSave}
                        disabled={saving}
                        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 disabled:opacity-50"
                    >
                        {saving ? (
                            <>
                                <Spinner size="sm" />
                                Salvataggio...
                            </>
                        ) : (
                            <>
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                </svg>
                                Salva Modifiche
                            </>
                        )}
                    </button>
                )}
            </div>

            {/* Cancelled Banner */}
            {project.is_cancelled && (
                <CancelledBanner
                    cancelledAt={project.cancelled_at}
                    cancelledByName={project.cancelled_by_name}
                    cancellationReason={project.cancellation_reason}
                    canUncancel={false}
                />
            )}

            {/* Completed Banner */}
            {!project.is_cancelled && project.status === 'completed' && (
                <CompletedBanner />
            )}

            {/* Two Column Layout - 30/70 ratio */}
            <div className="flex flex-col lg:flex-row gap-4 h-[calc(100vh-200px)]">
                {/* Left Column - Project Details and Comments (30%) */}
                <div className="lg:w-[30%] flex-shrink-0 bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden flex flex-col">
                    <div className="p-3 border-b border-slate-100 bg-slate-50">
                        <h2 className="text-sm font-semibold text-slate-800 flex items-center gap-2">
                            <svg className="w-4 h-4 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                            </svg>
                            Dettagli
                        </h2>
                    </div>

                    <div className="p-3 flex-1 overflow-y-auto scrollbar-thin space-y-3">
                        {/* Meta Info - Compact */}
                        <div className="space-y-2 text-xs">
                            {/* Date & Created By - inline */}
                            <div className="flex items-center gap-2 text-slate-600">
                                <svg className="w-3.5 h-3.5 text-slate-400" 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>
                                <span className="text-slate-300">•</span>
                                <span className="text-slate-500">da {project.created_by_name || 'N/A'}</span>
                            </div>

                            {/* Referenti */}
                            <div>
                                <span className="text-slate-500 text-[10px] uppercase tracking-wide">Referenti</span>
                                <div className="flex flex-wrap gap-1 mt-1">
                                    {projectRefs.length > 0 ? (
                                        projectRefs.map(ref => (
                                            <span
                                                key={ref.id}
                                                className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-teal-50 text-teal-700 rounded text-xs"
                                                title={ref.email || ref.phone_number || ''}
                                            >
                                                {ref.full_name}
                                            </span>
                                        ))
                                    ) : (
                                        <span className="text-slate-400 text-xs">—</span>
                                    )}
                                </div>
                            </div>

                            {/* Assignees */}
                            <div>
                                <span className="text-slate-500 text-[10px] uppercase tracking-wide">Assegnati</span>
                                <div className="flex flex-wrap gap-1 mt-1">
                                    {assignees.length > 0 ? (
                                        assignees.map(user => {
                                            const avatarUrl = user.avatar ? window.ApiUsers?.getAvatarUrl(user.avatar) : null;
                                            return (
                                                <span
                                                    key={user.id}
                                                    className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded text-xs"
                                                    title={user.email}
                                                >
                                                    {avatarUrl ? (
                                                        <img src={avatarUrl} alt={user.name} className="w-3.5 h-3.5 rounded-full object-cover" />
                                                    ) : null}
                                                    {user.name}
                                                </span>
                                            );
                                        })
                                    ) : (
                                        <span className="text-slate-400 text-xs">—</span>
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Description - Compact */}
                        <div className="pt-2 border-t border-slate-100">
                            <span className="text-slate-500 text-[10px] uppercase tracking-wide">Descrizione</span>
                            {isAdmin ? (
                                <MentionInput
                                    value={description}
                                    onChange={setDescription}
                                    placeholder="Aggiungi descrizione..."
                                    rows={2}
                                    className="mt-1"
                                />
                            ) : (
                                <div className="mt-1 text-xs text-slate-600">
                                    {project.description ? <MentionText text={project.description} /> : <span className="text-slate-400 italic">—</span>}
                                </div>
                            )}
                        </div>

                        {/* ID Card Section */}
                        <IDCardSection
                            projectId={projectId}
                            project={project}
                            onUpdate={() => loadData(true)}
                        />

                        {/* Email Registration Section */}
                        <EmailSection
                            project={project}
                            onTrigger={onTriggerRegistration}
                            onUpdate={() => loadData(true)}
                            onViewJob={onViewJob}
                        />

                        {/* Comments Section - Compact */}
                        <div className="flex-1 flex flex-col border border-slate-200 rounded-lg overflow-hidden">
                            <div className="p-2 bg-slate-50 border-b border-slate-100">
                                <h5 className="text-xs font-semibold text-slate-600 flex items-center gap-1.5">
                                    <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="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                                    </svg>
                                    Note ({comments.length})
                                </h5>
                            </div>

                            {/* Comments List */}
                            <div className="flex-1 overflow-y-auto">
                                {loadingComments ? (
                                    <div className="p-4 text-center">
                                        <Spinner size="sm" />
                                    </div>
                                ) : comments.length > 0 ? (
                                    <div className="divide-y divide-slate-100">
                                        {comments.map(comment => (
                                            <ProjectCommentItem
                                                key={comment.id}
                                                comment={comment}
                                                currentUser={currentUser}
                                                formatRelativeTime={formatRelativeTime}
                                                onDelete={handleDeleteComment}
                                            />
                                        ))}
                                    </div>
                                ) : (
                                    <div className="p-4 text-center text-slate-400 text-sm">
                                        Nessun commento. Inizia la conversazione!
                                    </div>
                                )}
                            </div>

                            {/* Add Comment */}
                            <div className="p-2 border-t border-slate-100 bg-slate-50">
                                <div className="flex gap-1.5">
                                    <MentionInput
                                        value={newComment}
                                        onChange={setNewComment}
                                        placeholder="Nota..."
                                        className="flex-1"
                                        rows={1}
                                        onKeyDown={(e) => {
                                            if (e.key === 'Enter' && !e.shiftKey) {
                                                e.preventDefault();
                                                handleAddComment();
                                            }
                                        }}
                                    />
                                    <button
                                        onClick={handleAddComment}
                                        disabled={addingComment || !newComment?.trim()}
                                        className="px-2.5 py-1.5 bg-brand-500 text-white text-xs font-medium rounded hover:bg-brand-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        {addingComment ? '...' : '+'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Right Column - Workflow Timeline (70%) */}
                <div className="lg:flex-1 bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden flex flex-col">
                    <div className="p-3 border-b border-slate-100 bg-slate-50">
                        <h2 className="text-sm font-semibold text-slate-800 flex items-center gap-2">
                            <svg className="w-4 h-4 text-slate-500" 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
                        </h2>
                    </div>

                    <div className="flex-1 overflow-hidden p-4">
                        <ProjectTimeline
                            projectId={projectId}
                            canEdit={true}
                            isAssigned={isAssigned}
                            isCancelled={project.is_cancelled || project.status === 'completed'}
                            onStepChange={() => {
                                // Optionally reload project data after step changes
                            }}
                            focusCommentId={focusStepId ? focusCommentId : null}
                            focusStepId={focusStepId}
                            onFocusHandled={onFocusHandled}
                        />
                    </div>

                    {/* Action Buttons Footer - Compact */}
                    {canPerformActions && !project.is_cancelled && project.status !== 'completed' && (
                        <div className="p-3 border-t border-slate-200 bg-slate-50">
                            {!showCancelForm ? (
                                <div className="flex gap-2">
                                    <button
                                        onClick={handleCompleteProject}
                                        className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 bg-green-500 text-white text-sm font-medium rounded-lg hover:bg-green-600 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="M5 13l4 4L19 7" />
                                        </svg>
                                        Chiudi
                                    </button>
                                    <button
                                        onClick={handleCancelProject}
                                        className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 bg-red-500 text-white text-sm font-medium rounded-lg hover:bg-red-600 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="M6 18L18 6M6 6l12 12" />
                                        </svg>
                                        Annulla
                                    </button>
                                </div>
                            ) : (
                                <div className="space-y-2">
                                    <p className="text-xs text-slate-600">Seleziona motivo:</p>
                                    <div className="space-y-1">
                                        {[
                                            'Il cliente non vuole procedere',
                                            'Rifiutata dall\'istituto creditizio',
                                            'Riabilitazione negativa',
                                        ].map((reason) => (
                                            <label
                                                key={reason}
                                                className={`flex items-center gap-2 px-2 py-1.5 rounded border cursor-pointer text-xs ${
                                                    selectedCancelReason === reason
                                                        ? 'border-red-400 bg-red-50 text-red-700'
                                                        : 'border-slate-200 hover:bg-slate-50'
                                                }`}
                                            >
                                                <input
                                                    type="radio"
                                                    name="cancelReason"
                                                    value={reason}
                                                    checked={selectedCancelReason === reason}
                                                    onChange={(e) => setSelectedCancelReason(e.target.value)}
                                                    className="w-3 h-3 text-red-500"
                                                />
                                                {reason}
                                            </label>
                                        ))}
                                    </div>
                                    <textarea
                                        value={cancelNotes}
                                        onChange={(e) => setCancelNotes(e.target.value)}
                                        placeholder="Note (opzionale)"
                                        className="w-full px-2 py-1.5 border border-slate-200 rounded text-xs resize-none"
                                        rows={1}
                                    />
                                    <div className="flex gap-2">
                                        <button
                                            onClick={() => setShowCancelForm(false)}
                                            disabled={cancelLoading}
                                            className="flex-1 px-2 py-1.5 text-xs border border-slate-300 text-slate-600 rounded hover:bg-slate-50"
                                        >
                                            Indietro
                                        </button>
                                        <button
                                            onClick={executeCancelProject}
                                            disabled={cancelLoading || !selectedCancelReason}
                                            className="flex-1 px-2 py-1.5 text-xs bg-red-500 text-white rounded hover:bg-red-600 disabled:opacity-50"
                                        >
                                            {cancelLoading ? '...' : 'Conferma'}
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Restore Button - Compact */}
                    {canPerformActions && (project.is_cancelled || project.status === 'completed') && (
                        <div className="p-3 border-t border-slate-200 bg-slate-50">
                            <button
                                onClick={handleRestoreProject}
                                className="w-full flex items-center justify-center gap-1.5 px-3 py-2 bg-green-500 text-white text-sm font-medium rounded-lg hover:bg-green-600 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="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                                </svg>
                                Ripristina
                            </button>
                        </div>
                    )}
                </div>
            </div>

            {/* Action Confirmation Modal */}
            {actionModal && (
                <ConfirmationModal
                    title={actionModal.title}
                    message={actionModal.message}
                    confirmText={actionModal.confirmText}
                    variant={actionModal.variant}
                    loading={actionModal.loading}
                    onConfirm={executeAction}
                    onCancel={() => setActionModal(null)}
                />
            )}

            {/* Confirmation Modal for Delete */}
            {confirmDelete && (
                <ConfirmationModal
                    title="Elimina Commento"
                    message="Sei sicuro di voler eliminare questo commento?"
                    confirmText="Elimina"
                    variant="danger"
                    onConfirm={executeDelete}
                    onCancel={() => setConfirmDelete(null)}
                />
            )}
        </div>
    );
}

// Comment display component for project comments
function ProjectCommentItem({ comment, currentUser, formatRelativeTime, onDelete }) {
    const canDelete = comment.created_by === currentUser?.id || currentUser?.role === 'admin';
    const avatarUrl = comment.created_by_avatar ? window.ApiUsers?.getAvatarUrl(comment.created_by_avatar) : null;

    return (
        <div id={`project-comment-${comment.id}`} className="p-3 hover:bg-slate-50 transition-all duration-300">
            <div className="flex items-start justify-between gap-2">
                <div className="flex items-center gap-2">
                    {avatarUrl ? (
                        <img
                            src={avatarUrl}
                            alt={comment.created_by_name}
                            className="w-8 h-8 rounded-full object-cover"
                        />
                    ) : (
                        <div className="w-8 h-8 bg-brand-100 rounded-full flex items-center justify-center text-brand-600 text-xs font-semibold">
                            {comment.created_by_name?.charAt(0).toUpperCase() || '?'}
                        </div>
                    )}
                    <div>
                        <span className="text-sm font-medium text-slate-800">
                            {comment.created_by_name || 'Utente'}
                        </span>
                        <span className="text-xs text-slate-400 ml-2">
                            {formatRelativeTime(comment.created_at)}
                        </span>
                    </div>
                </div>
                {canDelete && (
                    <button
                        onClick={() => onDelete(comment.id)}
                        className="text-slate-300 hover:text-red-500 transition-colors p-1"
                        title="Elimina commento"
                    >
                        <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>
            <p className="text-sm text-slate-600 mt-2 pl-10">
                <MentionText text={comment.content} />
            </p>
        </div>
    );
}

// ID Card Section Component - Always expanded panel for ID card upload and extraction
function IDCardSection({ projectId, project, onUpdate }) {
    const hasImages = project?.id_card_front_path || project?.id_card_back_path;

    return (
        <div className="pt-2 border-t border-slate-100 min-w-0 overflow-hidden">
            <div className="flex items-center justify-between mb-3">
                <span className="text-slate-500 text-[10px] uppercase tracking-wide flex items-center gap-1.5 min-w-0">
                    <span className="truncate">Documento d'Identita</span>
                    {hasImages && (
                        <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium bg-yellow-100 text-yellow-700 flex-shrink-0">
                            Caricato
                        </span>
                    )}
                </span>
            </div>

            <div className="space-y-3 min-w-0">
                {/* Image Uploader */}
                <IDCardUploader
                    projectId={projectId}
                    project={project}
                    onUpdate={onUpdate}
                />

                {/* Extracted Data Form - Always visible for manual input */}
                <div className="pt-3 border-t border-slate-200">
                    <ExtractedDataForm
                        projectId={projectId}
                        project={project}
                        onUpdate={onUpdate}
                    />
                </div>
            </div>
        </div>
    );
}

// Email Registration Section Component
function EmailSection({ project, onTrigger, onUpdate, onViewJob }) {
    const toast = useToast();
    const [email, setEmail] = React.useState(project?.email_address || '');
    const [password, setPassword] = React.useState(project?.email_password || '');
    const [saving, setSaving] = React.useState(false);
    const [editing, setEditing] = React.useState(false);
    const [linkedJob, setLinkedJob] = React.useState(null);
    const [loadingJob, setLoadingJob] = React.useState(false);
    const [showPassword, setShowPassword] = React.useState(false);

    // Check if personal data exists (required for automation)
    const hasPersonalData = project?.personal_data?.first_name &&
                            project?.personal_data?.last_name &&
                            project?.personal_data?.date_of_birth;

    // Check if email already exists (blocks automation)
    const hasEmail = !!project?.email_address;

    // Check if there's a pending/running job (job exists but no email yet)
    const hasPendingJob = project?.email_job_id && !hasEmail;

    // Update local state when project changes
    React.useEffect(() => {
        setEmail(project?.email_address || '');
        setPassword(project?.email_password || '');
    }, [project?.email_address, project?.email_password]);

    // Fetch linked job status when there's a pending job
    React.useEffect(() => {
        console.log('EmailSection effect:', {
            email_job_id: project?.email_job_id,
            email_address: project?.email_address,
            hasPendingJob,
            hasEmail
        });
        if (hasPendingJob && project?.email_job_id) {
            setLoadingJob(true);
            console.log('Fetching job status for:', project.email_job_id);
            fetch(`/queue/job/${project.email_job_id}`)
                .then(r => {
                    console.log('Job fetch response:', r.status, r.ok);
                    return r.ok ? r.json() : null;
                })
                .then(data => {
                    console.log('Job data received:', data);
                    if (data) setLinkedJob(data);
                })
                .catch(err => console.error('Job fetch error:', err))
                .finally(() => setLoadingJob(false));
        } else {
            setLinkedJob(null);
        }
    }, [project?.email_job_id, hasPendingJob]);

    // Clear job link when job fails (allow retry)
    const handleClearJobLink = async () => {
        setSaving(true);
        try {
            await ApiUtils.updateProject(project.id, { email_job_id: null });
            toast('Collegamento rimosso', 'success');
            setLinkedJob(null);
            onUpdate?.();
        } catch (err) {
            toast('Errore: ' + err.message, 'error');
        } finally {
            setSaving(false);
        }
    };

    const handleSaveCredentials = async () => {
        setSaving(true);
        try {
            await ApiUtils.updateProject(project.id, {
                email_address: email || null,
                email_password: password || null
            });
            toast('Credenziali salvate', 'success');
            setEditing(false);
            onUpdate?.();
        } catch (err) {
            toast('Errore: ' + err.message, 'error');
        } finally {
            setSaving(false);
        }
    };

    const handleClearCredentials = async () => {
        setSaving(true);
        try {
            await ApiUtils.updateProject(project.id, {
                email_address: null,
                email_password: null,
                email_job_id: null
            });
            toast('Credenziali rimosse', 'success');
            setEmail('');
            setPassword('');
            onUpdate?.();
        } catch (err) {
            toast('Errore: ' + err.message, 'error');
        } finally {
            setSaving(false);
        }
    };

    // Get job status display info
    const getJobStatusDisplay = () => {
        if (!linkedJob) return null;
        const status = linkedJob.status;
        if (status === 'queued') return { icon: '⏳', label: 'In coda', color: 'bg-yellow-50 text-yellow-700 border-yellow-200' };
        if (status === 'running') return { icon: '⚙️', label: 'In esecuzione', color: 'bg-blue-50 text-blue-700 border-blue-200' };
        if (status === 'error') return { icon: '❌', label: 'Errore', color: 'bg-red-50 text-red-700 border-red-200' };
        if (status === 'cancelled') return { icon: '⛔', label: 'Annullato', color: 'bg-slate-50 text-slate-700 border-slate-200' };
        return null;
    };

    const jobStatus = getJobStatusDisplay();

    return (
        <div className="pt-2 border-t border-slate-100">
            <span className="text-slate-500 text-[10px] uppercase tracking-wide flex items-center gap-1.5">
                <span>Registrazione Email</span>
                {hasEmail && (
                    <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-100 text-green-700">
                        Completata
                    </span>
                )}
                {hasPendingJob && linkedJob && (
                    <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium ${jobStatus?.color || 'bg-slate-100 text-slate-600'}`}>
                        {jobStatus?.icon} {jobStatus?.label || 'In corso'}
                    </span>
                )}
            </span>

            <div className="mt-2 space-y-2">
                {/* Show pending/running/failed job status */}
                {hasPendingJob && (
                    <div className={`rounded-lg p-3 space-y-2 border ${jobStatus?.color || 'bg-slate-50 border-slate-200'}`}>
                        {loadingJob ? (
                            <div className="flex items-center gap-2">
                                <Spinner size="sm" />
                                <span className="text-xs text-slate-600">Caricamento stato...</span>
                            </div>
                        ) : linkedJob ? (
                            <>
                                <div className="flex items-center gap-2">
                                    <span>{jobStatus?.icon}</span>
                                    <span className="text-sm font-medium">{jobStatus?.label}</span>
                                    {linkedJob.status === 'running' && <Spinner size="sm" />}
                                </div>
                                <p className="text-xs text-slate-600">
                                    {linkedJob.message || 'Automazione in corso...'}
                                </p>
                                <button
                                    onClick={() => onViewJob?.(linkedJob)}
                                    className="text-[10px] text-blue-600 hover:text-blue-800 underline"
                                >
                                    Vedi Job #{project.email_job_id?.slice(-8)} →
                                </button>
                                {/* Show retry option for failed jobs */}
                                {(linkedJob.status === 'error' || linkedJob.status === 'cancelled') && (
                                    <div className="flex gap-2 pt-1">
                                        <button
                                            onClick={async () => {
                                                // Clear the job link first, then trigger new automation
                                                await handleClearJobLink();
                                                // Small delay to let state update, then trigger
                                                setTimeout(() => onTrigger?.(project), 100);
                                            }}
                                            disabled={saving}
                                            className="text-xs text-blue-600 hover:text-blue-800 underline"
                                        >
                                            Riprova automazione
                                        </button>
                                        <button
                                            onClick={() => setEditing(true)}
                                            className="text-xs text-slate-600 hover:text-slate-800 underline"
                                        >
                                            Inserisci manualmente
                                        </button>
                                    </div>
                                )}
                            </>
                        ) : (
                            <p className="text-xs text-slate-500">Impossibile caricare lo stato del job</p>
                        )}
                    </div>
                )}

                {/* Show Email credentials if exists */}
                {hasEmail && !editing ? (
                    <div className="bg-green-50 rounded-lg p-3 space-y-2">
                        <div className="flex items-center gap-2">
                            <span className="text-green-500">✓</span>
                            <span className="text-sm font-medium text-slate-800">Credenziali Email</span>
                        </div>
                        <div className="text-xs space-y-1.5">
                            <div className="flex items-center gap-2">
                                <svg className="w-3.5 h-3.5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                </svg>
                                <span className="font-mono text-slate-700">{project.email_address}</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <svg className="w-3.5 h-3.5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                                </svg>
                                {project.email_password ? (
                                    <>
                                        <span className="font-mono text-slate-700">
                                            {showPassword ? project.email_password : '••••••••'}
                                        </span>
                                        <button
                                            onClick={() => setShowPassword(!showPassword)}
                                            className="text-slate-400 hover:text-slate-600"
                                            title={showPassword ? 'Nascondi' : 'Mostra'}
                                        >
                                            {showPassword ? (
                                                <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="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                                                </svg>
                                            ) : (
                                                <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="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                                </svg>
                                            )}
                                        </button>
                                    </>
                                ) : (
                                    <span className="text-slate-400 italic">Non impostata</span>
                                )}
                            </div>
                            {project.email_job_id && (
                                <p className="text-slate-500 mt-1 text-[10px]">
                                    Collegata a job #{project.email_job_id.slice(-8)}
                                </p>
                            )}
                        </div>
                        <div className="flex gap-2 pt-1">
                            <button
                                onClick={() => setEditing(true)}
                                className="text-xs text-blue-600 hover:text-blue-800 underline"
                            >
                                Modifica
                            </button>
                            <button
                                onClick={handleClearCredentials}
                                disabled={saving}
                                className="text-xs text-red-600 hover:text-red-800 underline"
                            >
                                Rimuovi
                            </button>
                        </div>
                    </div>
                ) : editing || (!hasEmail && !hasPersonalData) ? (
                    /* Manual Credentials Entry */
                    <div className="space-y-2">
                        <div className="space-y-1.5">
                            <input
                                type="email"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                placeholder="Email..."
                                className="w-full px-2 py-1.5 text-xs border border-slate-200 rounded focus:outline-none focus:ring-1 focus:ring-brand-500"
                            />
                            <input
                                type="text"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                placeholder="Password..."
                                className="w-full px-2 py-1.5 text-xs border border-slate-200 rounded focus:outline-none focus:ring-1 focus:ring-brand-500"
                            />
                        </div>
                        <div className="flex gap-2">
                            <button
                                onClick={handleSaveCredentials}
                                disabled={saving || !email}
                                className="flex-1 px-2 py-1.5 bg-brand-500 text-white text-xs rounded hover:bg-brand-600 disabled:opacity-50"
                            >
                                {saving ? '...' : 'Salva Credenziali'}
                            </button>
                            {editing && (
                                <button
                                    onClick={() => {
                                        setEditing(false);
                                        setEmail(project?.email_address || '');
                                        setPassword(project?.email_password || '');
                                    }}
                                    className="px-2 py-1.5 text-xs text-slate-600 hover:text-slate-800"
                                >
                                    Annulla
                                </button>
                            )}
                        </div>
                        {!hasPersonalData && !editing && (
                            <p className="text-[10px] text-slate-400 italic">
                                Compila i dati anagrafici per abilitare la registrazione automatica
                            </p>
                        )}
                    </div>
                ) : null}

                {/* Trigger Automation Button - only show when personal_data exists, no email, and no pending job */}
                {hasPersonalData && !hasEmail && !hasPendingJob && !editing && (
                    <div className="space-y-2">
                        <button
                            onClick={() => onTrigger?.(project)}
                            disabled={project.is_cancelled || project.status === 'completed'}
                            className="w-full flex items-center justify-center gap-1.5 px-3 py-2 bg-purple-500 text-white text-xs font-medium rounded-lg hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            <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="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                            </svg>
                            Automatizza Account Email
                        </button>
                        <p className="text-[10px] text-slate-400 text-center">
                            Oppure inserisci credenziali manualmente:
                        </p>
                        <div className="space-y-1.5">
                            <input
                                type="email"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                placeholder="Email..."
                                className="w-full px-2 py-1.5 text-xs border border-slate-200 rounded focus:outline-none focus:ring-1 focus:ring-brand-500"
                            />
                            <input
                                type="text"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                placeholder="Password..."
                                className="w-full px-2 py-1.5 text-xs border border-slate-200 rounded focus:outline-none focus:ring-1 focus:ring-brand-500"
                            />
                        </div>
                        <button
                            onClick={handleSaveCredentials}
                            disabled={saving || !email}
                            className="w-full px-2 py-1.5 bg-slate-100 text-slate-700 text-xs rounded hover:bg-slate-200 disabled:opacity-50"
                        >
                            {saving ? '...' : 'Salva Credenziali'}
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
}

window.ProjectDetailView = ProjectDetailView;
