"use client";

import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import Link from "next/link";
import {
    GripVertical, Loader2, LayoutList, SlidersHorizontal,
    CheckSquare, X, ArrowRight, Settings, Undo2, Trash2
} from "lucide-react";
import { getOrCreatePipeline, moveApplicationStage } from "@/app/actions/pipelineActions";
import { validateStageTransition, bulkMoveApplications } from "@/app/actions/stageConfigActions";
import { evaluateTransition } from "@/app/actions/transitionRuleActions";
import {
    DndContext, DragOverlay, closestCorners, KeyboardSensor,
    PointerSensor, useSensor, useSensors, DragStartEvent,
    DragOverEvent, DragEndEvent, defaultDropAnimationSideEffects,
} from '@dnd-kit/core';
import {
    SortableContext, arrayMove, sortableKeyboardCoordinates,
    verticalListSortingStrategy, useSortable
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { ConfirmMoveModal } from "@/components/ats/ConfirmMoveModal";
import { TransitionBlockedModal } from "@/components/ats/TransitionBlockedModal";
import { StageActionBar } from "@/components/ats/StageActionBar";
import { StageConfigPanel } from "@/components/ats/StageConfigPanel";
import { PipelineFilterPanel, type PipelineFilters, DEFAULT_FILTERS } from "@/components/ats/PipelineFilterPanel";
import { BulkActionBar } from "@/components/ats/BulkActionBar";
import { getStageConfig, type StageConfig } from "@/app/actions/stageConfigActions";

interface KanbanBoardProps {
    applications: any[];
    selectedJobId?: string | null;
}

type PendingMove = {
    applicationId: string;
    fromStageId: string;
    toStageId: string;
    toStageName: string;
    toStageType: string;
    candidateName: string;
    blockers: string[];
    isBackward: boolean;
};

const NEEDS_CONFIRM_TYPES = new Set(["rejected", "offer", "hired"]);

export function KanbanBoard({ applications: initialApplications, selectedJobId }: KanbanBoardProps) {
    const [pipeline, setPipeline] = useState<any>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [items, setItems] = useState<Record<string, any[]>>({});
    const [activeId, setActiveId] = useState<string | null>(null);

    // Task 3 — Confirm move
    const [pendingMove, setPendingMove] = useState<PendingMove | null>(null);

    // Task 4 — Bulk selection
    const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

    // Task 5 — Filters
    const [showFilters, setShowFilters] = useState(false);
    const [filters, setFilters] = useState<PipelineFilters>(DEFAULT_FILTERS);

    // Task 2 — Stage config
    const [configuringStage, setConfiguringStage] = useState<{ id: string; name: string; config: StageConfig } | null>(null);

    // Undo toast
    const [undoToast, setUndoToast] = useState<{ message: string; show: boolean } | null>(null);
    const undoTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

    // Previous items for undo
    const prevItemsRef = useRef<Record<string, any[]>>({});

    // Rule violations modal
    const [ruleViolations, setRuleViolations] = useState<{
        applicationId: string;
        candidateName: string;
        fromStageName: string;
        toStageName: string;
        fromStageId: string;
        toStageId: string;
        violations: any[];
        warnings: string[];
    } | null>(null);

    useEffect(() => {
        if (!selectedJobId) { setPipeline(null); setItems({}); return; }
        let isMounted = true;
        async function fetchPipeline() {
            setIsLoading(true);
            try {
                const res = await getOrCreatePipeline(selectedJobId!);
                if (res.success && res.pipeline && isMounted) {
                    setPipeline(res.pipeline);
                    const newItems: Record<string, any[]> = {};
                    res.pipeline.stages.forEach((stage: any) => { newItems[stage.id] = stage.applications || []; });
                    setItems(newItems);
                }
            } catch (err) { console.error("Failed to load pipeline", err); }
            finally { if (isMounted) setIsLoading(false); }
        }
        fetchPipeline();
        return () => { isMounted = false; };
    }, [selectedJobId]);

    const sensors = useSensors(
        useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
        useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
    );

    // --- Utility ---
    const findContainer = useCallback((id: string) => {
        if (id in items) return id;
        return Object.keys(items).find(key => items[key].some(item => item.id === id));
    }, [items]);

    const getStageOrder = useCallback((stageId: string) => {
        if (!pipeline) return -1;
        return pipeline.stages.findIndex((s: any) => s.id === stageId);
    }, [pipeline]);

    // --- DnD Handlers ---
    const handleDragStart = (event: DragStartEvent) => setActiveId(event.active.id as string);

    const handleDragOver = (event: DragOverEvent) => {
        const { active, over } = event;
        const overId = over?.id;
        if (!overId || active.id === overId) return;
        const activeContainer = findContainer(active.id as string);
        const overContainer = findContainer(overId as string);
        if (!activeContainer || !overContainer || activeContainer === overContainer) return;

        setItems(prev => {
            const activeItems = prev[activeContainer];
            const overItems = prev[overContainer];
            const activeIndex = activeItems.findIndex(i => i.id === active.id);
            const overIndex = overId in prev ? overItems.length + 1 : overItems.findIndex(i => i.id === overId);
            return {
                ...prev,
                [activeContainer]: prev[activeContainer].filter(item => item.id !== active.id),
                [overContainer]: [...prev[overContainer].slice(0, overIndex), activeItems[activeIndex], ...prev[overContainer].slice(overIndex)]
            };
        });
    };

    const handleDragEnd = async (event: DragEndEvent) => {
        const { active, over } = event;
        setActiveId(null);
        if (!over) return;

        const activeContainer = findContainer(active.id as string);
        const overContainer = findContainer(over.id as string);
        if (!activeContainer || !overContainer) return;

        if (activeContainer === overContainer) {
            const activeIndex = items[activeContainer].findIndex(i => i.id === active.id);
            const overIndex = items[activeContainer].findIndex(i => i.id === over.id);
            if (activeIndex !== overIndex) {
                setItems(prev => ({ ...prev, [activeContainer]: arrayMove(prev[activeContainer], activeIndex, overIndex) }));
            }
            return;
        }

        // Cross-stage move
        const toStage = pipeline?.stages.find((s: any) => s.id === overContainer);
        const fromStage = pipeline?.stages.find((s: any) => s.id === activeContainer);
        const application = Object.values(items).flat().find(a => a.id === active.id);
        if (!toStage || !application) return;

        const isBackward = getStageOrder(overContainer) < getStageOrder(activeContainer);

        // Validate blockers from exit config
        const { valid, blockers } = await validateStageTransition(active.id as string, overContainer);

        // Evaluate transition rules
        const ruleResult = await evaluateTransition(active.id as string, activeContainer, overContainer);
        const hasRuleViolations = ruleResult.success && ruleResult.result && !ruleResult.result.allowed;

        if (hasRuleViolations && ruleResult.result) {
            // Show rule violations modal
            setRuleViolations({
                applicationId: active.id as string,
                candidateName: application.candidate?.name || "Candidate",
                fromStageName: fromStage?.name || "Unknown",
                toStageName: toStage.name,
                fromStageId: activeContainer,
                toStageId: overContainer,
                violations: ruleResult.result.violations,
                warnings: ruleResult.result.warnings,
            });
            return;
        }

        const needsConfirm = NEEDS_CONFIRM_TYPES.has(toStage.stage_type) || isBackward || !valid;

        if (needsConfirm) {
            setPendingMove({
                applicationId: active.id as string,
                fromStageId: activeContainer,
                toStageId: overContainer,
                toStageName: toStage.name,
                toStageType: toStage.stage_type || "interview",
                candidateName: application.candidate?.name || "Candidate",
                blockers,
                isBackward,
            });
            // Revert optimistic move while modal is open
            setItems(prev => {
                const currentItem = prev[overContainer]?.find(i => i.id === active.id);
                if (!currentItem) return prev;
                return {
                    ...prev,
                    [activeContainer]: [...(prev[activeContainer] || []), currentItem],
                    [overContainer]: prev[overContainer].filter(i => i.id !== active.id),
                };
            });
            return;
        }

        // Direct move — show undo
        prevItemsRef.current = items;
        await persistMove(active.id as string, overContainer);
        showUndo(`Moved ${application.candidate?.name || "Candidate"} to ${toStage.name}`);
    };

    const persistMove = async (applicationId: string, toStageId: string) => {
        try {
            await moveApplicationStage(applicationId, toStageId);
        } catch (err) {
            console.error("Move failed:", err);
        }
    };

    const showUndo = (message: string) => {
        if (undoTimer.current) clearTimeout(undoTimer.current);
        setUndoToast({ message, show: true });
        undoTimer.current = setTimeout(() => setUndoToast(null), 8000);
    };

    const handleUndo = () => {
        if (prevItemsRef.current && Object.keys(prevItemsRef.current).length > 0) {
            setItems(prevItemsRef.current);
        }
        setUndoToast(null);
    };

    const handleConfirmMove = async (data: any) => {
        if (!pendingMove) return;
        prevItemsRef.current = items;
        // Optimistically update
        setItems(prev => {
            const currentItem = Object.values(prev).flat().find(i => i.id === pendingMove.applicationId);
            if (!currentItem) return prev;
            return {
                ...prev,
                [pendingMove.fromStageId]: prev[pendingMove.fromStageId].filter(i => i.id !== pendingMove.applicationId),
                [pendingMove.toStageId]: [...(prev[pendingMove.toStageId] || []), currentItem],
            };
        });
        setPendingMove(null);
        await persistMove(pendingMove.applicationId, pendingMove.toStageId);
        showUndo(`Moved candidate to ${pendingMove.toStageName}`);
    };

    // --- Bulk Actions ---
    const toggleSelect = useCallback((id: string) => {
        setSelectedIds(prev => {
            const next = new Set(prev);
            next.has(id) ? next.delete(id) : next.add(id);
            return next;
        });
    }, []);

    const clearSelection = () => setSelectedIds(new Set());

    const selectAllInStage = useCallback((stageId: string) => {
        const stageApps = items[stageId] || [];
        setSelectedIds(prev => {
            const next = new Set(prev);
            const allSelected = stageApps.every((a: any) => next.has(a.id));
            if (allSelected) {
                stageApps.forEach((a: any) => next.delete(a.id));
            } else {
                stageApps.forEach((a: any) => next.add(a.id));
            }
            return next;
        });
    }, [items]);

    const handleBulkActionComplete = useCallback(async () => {
        if (!selectedJobId) return;
        try {
            const res = await getOrCreatePipeline(selectedJobId);
            if (res.success && res.pipeline) {
                setPipeline(res.pipeline);
                const newItems: Record<string, any[]> = {};
                res.pipeline.stages.forEach((stage: any) => { newItems[stage.id] = stage.applications || []; });
                setItems(newItems);
            }
        } catch (err) { console.error("Failed to refresh pipeline", err); }
    }, [selectedJobId]);

    // --- Filtering ---
    const filteredItems = useMemo(() => {
        if (!pipeline) return items;
        const result: Record<string, any[]> = {};
        pipeline.stages.forEach((stage: any) => {
            let apps = items[stage.id] || [];
            if (filters.stages.length > 0 && !filters.stages.includes(stage.id)) {
                result[stage.id] = [];
                return;
            }
            if (filters.scoreMin !== null) apps = apps.filter(a => (a.score?.overall_score || a.match_score || 0) >= filters.scoreMin!);
            if (filters.scoreMax !== null) apps = apps.filter(a => (a.score?.overall_score || a.match_score || 100) <= filters.scoreMax!);
            if (filters.tags.length > 0) {
                apps = apps.filter(a => {
                    const tagNames = (a.application_tags || []).map((t: any) => t.tag?.name);
                    return filters.tags.some(ft => tagNames.includes(ft));
                });
            }
            if (filters.applicationDateRange !== "all") {
                const daysMap: Record<string, number> = { today: 1, week: 7, month: 30, quarter: 90 };
                const days = daysMap[filters.applicationDateRange];
                const cutoff = new Date(Date.now() - days * 86400000);
                apps = apps.filter(a => new Date(a.applied_at) >= cutoff);
            }
            if (filters.source) apps = apps.filter(a => a.source === filters.source);
            result[stage.id] = apps;
        });
        return result;
    }, [items, filters, pipeline]);

    const totalCount = Object.values(items).flat().length;
    const filteredCount = Object.values(filteredItems).flat().length;

    const allTags = useMemo(() => {
        const tagMap = new Map<string, any>();
        Object.values(items).flat().forEach(app => {
            (app.application_tags || []).forEach((rel: any) => {
                if (rel.tag) tagMap.set(rel.tag.id, rel.tag);
            });
        });
        return Array.from(tagMap.values());
    }, [items]);

    const handleOpenStageConfig = async (stage: any) => {
        const res = await getStageConfig(stage.id);
        if (res.success) {
            setConfiguringStage({ id: stage.id, name: stage.name, config: res.config! });
        }
    };

    if (!selectedJobId) {
        return (
            <div className="flex flex-col items-center justify-center py-20 rounded-2xl border-2 border-dashed border-slate-200 bg-slate-50/50">
                <LayoutList className="w-12 h-12 text-slate-300 mb-4" />
                <h3 className="text-lg font-bold text-slate-700">Select a job to view pipeline</h3>
                <p className="text-sm text-slate-500 mt-2">The Kanban board reflects the custom hiring stages for a specific job.</p>
            </div>
        );
    }
    if (isLoading) {
        return (
            <div className="flex flex-col items-center justify-center py-32">
                <Loader2 className="w-8 h-8 text-primary animate-spin mb-4" />
                <p className="text-slate-500 font-medium">Loading applicant pipeline...</p>
            </div>
        );
    }
    if (!pipeline) return null;

    const activeItem = activeId ? Object.values(items).flat().find(i => i.id === activeId) : null;

    return (
        <div className="flex gap-4 h-[calc(100vh-250px)] min-h-[500px] relative">
            {/* Confirm Move Modal */}
            {pendingMove && (
                <ConfirmMoveModal
                    candidateName={pendingMove.candidateName}
                    fromStage={pipeline.stages.find((s: any) => s.id === pendingMove.fromStageId)?.name || ""}
                    toStage={pendingMove.toStageName}
                    toStageType={pendingMove.toStageType}
                    isBackwardMove={pendingMove.isBackward}
                    blockers={pendingMove.blockers}
                    onConfirm={handleConfirmMove}
                    onCancel={() => setPendingMove(null)}
                />
            )}

            {/* Stage Config Panel */}
            {configuringStage && (
                <StageConfigPanel
                    stageId={configuringStage.id}
                    stageName={configuringStage.name}
                    initialConfig={configuringStage.config}
                    onClose={() => setConfiguringStage(null)}
                />
            )}

            {/* Undo Toast */}
            {undoToast?.show && (
                <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 px-4 py-3 bg-slate-900 text-white text-sm font-semibold rounded-2xl shadow-2xl animate-fade-in">
                    <span>{undoToast.message}</span>
                    <button onClick={handleUndo} className="flex items-center gap-1.5 px-2.5 py-1 bg-white/10 hover:bg-white/20 rounded-lg transition-colors text-xs">
                        <Undo2 className="w-3 h-3" /> Undo
                    </button>
                    <button onClick={() => setUndoToast(null)} className="text-white/60 hover:text-white"><X className="w-4 h-4" /></button>
                </div>
            )}

            {/* Filter Panel */}
            {showFilters && (
                <PipelineFilterPanel
                    stages={pipeline.stages}
                    availableTags={allTags}
                    filters={filters}
                    totalCount={totalCount}
                    filteredCount={filteredCount}
                    onChange={setFilters}
                    onClear={() => setFilters(DEFAULT_FILTERS)}
                />
            )}

            {/* Board Area */}
            <div className="flex-1 flex flex-col min-w-0">
                {/* Toolbar */}
                <div className="flex items-center gap-3 mb-4">
                    <button
                        onClick={() => setShowFilters(!showFilters)}
                        className={`flex items-center gap-2 px-3 py-2 text-sm font-bold rounded-xl transition-colors ${showFilters ? "bg-primary text-white" : "bg-white border border-slate-200 text-slate-600 hover:bg-slate-50"}`}
                    >
                        <SlidersHorizontal className="w-4 h-4" />
                        Filters
                        {Object.values(filters).some(v => v !== null && v !== "all" && (Array.isArray(v) ? v.length > 0 : !!v)) && (
                            <span className="w-5 h-5 bg-white text-primary text-xs rounded-full flex items-center justify-center font-bold">!</span>
                        )}
                    </button>
                    <span className="text-sm text-slate-500">
                        {filteredCount !== totalCount ? `${filteredCount} / ${totalCount} candidates` : `${totalCount} candidates`}
                    </span>

                    {selectedIds.size > 0 && (
                        <span className="ml-auto text-xs font-semibold text-primary bg-primary/10 px-2.5 py-1 rounded-lg">
                            {selectedIds.size} selected
                        </span>
                    )}
                </div>

                {/* Kanban Columns */}
                <div className="flex gap-5 overflow-x-auto pb-4 items-start flex-1">
                    <DndContext
                        sensors={sensors}
                        collisionDetection={closestCorners}
                        onDragStart={handleDragStart}
                        onDragOver={handleDragOver}
                        onDragEnd={handleDragEnd}
                    >
                        {pipeline.stages.map((stage: any) => (
                            <StageColumn
                                key={stage.id}
                                stage={stage}
                                items={filteredItems[stage.id] || []}
                                selectedIds={selectedIds}
                                onToggleSelect={toggleSelect}
                                onSelectAll={selectAllInStage}
                                onConfigureStage={() => handleOpenStageConfig(stage)}
                            />
                        ))}
                        <DragOverlay dropAnimation={{ sideEffects: defaultDropAnimationSideEffects({ styles: { active: { opacity: '0.4' } } }) }}>
                            {activeItem ? <CandidateCard application={activeItem} isDragging stage={null} onToggleSelect={() => { }} isSelected={false} /> : null}
                        </DragOverlay>
                    </DndContext>
                </div>
            </div>

            {/* Bulk Action Bar */}
            <BulkActionBar
                selectedIds={Array.from(selectedIds)}
                onClearSelection={clearSelection}
                onActionComplete={handleBulkActionComplete}
            />

            {/* Rule Violations Modal */}
            {ruleViolations && (
                <TransitionBlockedModal
                    isOpen={true}
                    onClose={() => setRuleViolations(null)}
                    onOverrideSuccess={async () => {
                        // After override, proceed with the move
                        prevItemsRef.current = items;
                        setItems(prev => {
                            const currentItem = Object.values(prev).flat().find(i => i.id === ruleViolations.applicationId);
                            if (!currentItem) return prev;
                            return {
                                ...prev,
                                [ruleViolations.fromStageId]: prev[ruleViolations.fromStageId]?.filter(i => i.id !== ruleViolations.applicationId) || [],
                                [ruleViolations.toStageId]: [...(prev[ruleViolations.toStageId] || []), currentItem],
                            };
                        });
                        await persistMove(ruleViolations.applicationId, ruleViolations.toStageId);
                        showUndo(`Moved ${ruleViolations.candidateName} to ${ruleViolations.toStageName} (override)`);
                        setRuleViolations(null);
                    }}
                    applicationId={ruleViolations.applicationId}
                    candidateName={ruleViolations.candidateName}
                    fromStageName={ruleViolations.fromStageName}
                    toStageName={ruleViolations.toStageName}
                    violations={ruleViolations.violations}
                    warnings={ruleViolations.warnings}
                />
            )}
        </div>
    );
}

// --- Stage Column ---
function StageColumn({ stage, items, selectedIds, onToggleSelect, onSelectAll, onConfigureStage }: {
    stage: any; items: any[]; selectedIds: Set<string>;
    onToggleSelect: (id: string) => void; onSelectAll: (stageId: string) => void; onConfigureStage: () => void;
}) {
    const allSelected = items.length > 0 && items.every(a => selectedIds.has(a.id));
    const { setNodeRef } = useSortable({ id: stage.id, data: { type: 'Container', stage } });
    const avgMatch = items.length > 0
        ? Math.round(items.reduce((sum, a) => sum + (a.score?.overall_score || a.match_score || 0), 0) / items.length)
        : 0;

    return (
        <div className="flex-shrink-0 w-80 bg-slate-50 rounded-2xl flex flex-col max-h-full border border-slate-200">
            <div className="flex items-center gap-2 p-3.5 border-b border-slate-200 bg-white/50 rounded-t-2xl">
                <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: stage.color }} />
                <h3 className="font-bold text-slate-900 text-sm flex-1 truncate">{stage.name}</h3>
                {avgMatch > 0 && <span className="text-[10px] font-semibold text-slate-400">~{avgMatch}%</span>}
                <span className="text-xs font-semibold text-slate-500 bg-white shadow-sm px-2 py-0.5 rounded-full">{items.length}</span>
                {items.length > 0 && (
                    <button
                        onClick={() => onSelectAll(stage.id)}
                        title={allSelected ? "Deselect all" : "Select all"}
                        className={`p-1 rounded-lg transition-colors ${allSelected ? 'bg-primary/10 text-primary' : 'text-slate-400 hover:text-primary hover:bg-primary/5'}`}
                    >
                        <CheckSquare className="w-3.5 h-3.5" />
                    </button>
                )}
                <button onClick={onConfigureStage} title="Configure stage" className="p-1 hover:bg-slate-100 rounded-lg text-slate-400 hover:text-slate-600 transition-colors">
                    <Settings className="w-3.5 h-3.5" />
                </button>
            </div>
            <div ref={setNodeRef} className="flex-1 overflow-y-auto p-3 space-y-3 min-h-[150px]">
                <SortableContext id={stage.id} items={items.map(i => i.id)} strategy={verticalListSortingStrategy}>
                    {items.map(app => (
                        <SortableCandidateCard
                            key={app.id}
                            application={app}
                            stage={stage}
                            isSelected={selectedIds.has(app.id)}
                            onToggleSelect={onToggleSelect}
                        />
                    ))}
                    {items.length === 0 && (
                        <div className="flex items-center justify-center h-24 border-2 border-dashed border-slate-200 rounded-xl text-slate-400 text-xs font-medium">
                            Drop here
                        </div>
                    )}
                </SortableContext>
            </div>
        </div>
    );
}

// --- Sortable Wrapper ---
function SortableCandidateCard({ application, stage, isSelected, onToggleSelect }: { application: any; stage: any; isSelected: boolean; onToggleSelect: (id: string) => void }) {
    const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
        id: application.id, data: { type: 'Application', application }
    });
    const style = { transform: CSS.Transform.toString(transform), transition };
    return (
        <div ref={setNodeRef} style={style} className={`touch-none ${isDragging ? 'opacity-40' : ''}`} {...attributes} {...listeners}>
            <CandidateCard application={application} stage={stage} isDragging={false} isSelected={isSelected} onToggleSelect={onToggleSelect} />
        </div>
    );
}

// --- Candidate Card ---
function CandidateCard({ application, stage, isDragging, isSelected, onToggleSelect }: {
    application: any; stage: any | null; isDragging?: boolean; isSelected: boolean; onToggleSelect: (id: string) => void;
}) {
    const candidate = application.candidate;
    if (!candidate) return null;
    const rawTags = application.application_tags || [];
    const matchScore = application.score?.overall_score || application.match_score || null;
    const stageType = stage?.stage_type || "interview";

    const handleQuickAction = (action: string) => {
        // Quick actions from stage action bar that need local handling
        console.log("Quick action:", action, "for application:", application.id);
    };

    return (
        <div
            className={`bg-white rounded-xl border p-3.5 transition-all shadow-sm ${isDragging ? 'shadow-xl border-primary/50 rotate-1' :
                isSelected ? 'border-primary bg-primary/5 shadow-md' :
                    'border-slate-200 hover:shadow-md hover:border-slate-300'
                }`}
            onPointerDown={e => e.stopPropagation()}
        >
            <div className="flex items-start gap-2.5">
                {/* Selection checkbox */}
                <button
                    onClick={() => onToggleSelect(application.id)}
                    className={`mt-1 flex-shrink-0 w-4 h-4 rounded border-2 flex items-center justify-center transition-all ${isSelected ? 'bg-primary border-primary' : 'border-slate-300 hover:border-primary'
                        }`}
                >
                    {isSelected && <div className="w-2 h-2 bg-white rounded-sm" />}
                </button>

                <div className="flex-1 min-w-0">
                    <Link href={`/dashboard/applications/${application.id}`} onPointerDown={e => e.stopPropagation()} className="block group">
                        <div className="flex items-start justify-between mb-2">
                            <div className="flex items-center gap-2.5">
                                <div className="flex-shrink-0 w-8 h-8 rounded-full bg-gradient-to-br from-primary/80 to-accent flex items-center justify-center text-white text-xs font-bold shadow-sm">
                                    {(candidate.name || 'U').charAt(0).toUpperCase()}
                                </div>
                                <div>
                                    <h4 className="font-bold text-slate-900 text-sm truncate group-hover:text-primary transition-colors">{candidate.name}</h4>
                                    <p className="text-[11px] text-slate-400">
                                        {new Date(application.applied_at || Date.now()).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                                    </p>
                                </div>
                            </div>
                            {matchScore !== null && (
                                <div className={`ml-1 flex-shrink-0 flex items-center justify-center w-8 h-8 rounded-full border-2 text-[10px] font-bold ${Number(matchScore) >= 80 ? 'text-emerald-600 border-emerald-100 bg-emerald-50' :
                                    Number(matchScore) >= 60 ? 'text-amber-600 border-amber-100 bg-amber-50' :
                                        'text-slate-500 border-slate-100 bg-slate-50'
                                    }`}>
                                    {Math.round(Number(matchScore))}
                                </div>
                            )}
                        </div>

                        {candidate.profile?.headline && (
                            <p className="text-xs text-slate-500 line-clamp-1">{candidate.profile.headline}</p>
                        )}
                    </Link>

                    {rawTags.length > 0 && (
                        <div className="flex flex-wrap gap-1 mt-2">
                            {rawTags.slice(0, 3).map((tagRel: any) => (
                                <span key={tagRel.tag?.id} className="px-2 py-0.5 text-[10px] font-bold rounded" style={{ backgroundColor: `${tagRel.tag?.color}20`, color: tagRel.tag?.color }}>
                                    {tagRel.tag?.name}
                                </span>
                            ))}
                            {rawTags.length > 3 && <span className="px-2 py-0.5 text-[10px] rounded bg-slate-100 text-slate-500 font-bold">+{rawTags.length - 3}</span>}
                        </div>
                    )}

                    {/* Stage Action Bar */}
                    {!isDragging && (
                        <StageActionBar
                            applicationId={application.id}
                            candidateId={candidate.id}
                            stageType={stageType}
                            onAction={handleQuickAction as any}
                        />
                    )}
                </div>
            </div>
        </div>
    );
}
