"use client";

import { useEffect, useState, Suspense, useCallback, useRef } from 'react';
import api from '../../lib/api';
import { Vulnerability, Asset, UserInfo, Group } from '../../types';
import { useSearchParams, useRouter } from 'next/navigation';
import { MagnifyingGlassIcon, FunnelIcon, XMarkIcon, BellSlashIcon, ClockIcon, UserGroupIcon, PencilSquareIcon, ShieldExclamationIcon, InformationCircleIcon, ChevronLeftIcon, ChevronRightIcon, NoSymbolIcon } from '@heroicons/react/24/outline';
import { UserCircleIcon } from '@heroicons/react/24/solid';
import SearchableSelect from '../../components/ui/SearchableSelect';

// Helper: Parse search text into individual terms, respecting quotes for multi-word terms
// Example: '!\"Mozilla Thunderbird\" kernel' -> ['!\"Mozilla Thunderbird\"', 'kernel']
function parseSearchTerms(searchText: string): string[] {
    const terms: string[] = [];
    const regex = /!?"[^"]+"|[^\s]+/g;
    let match;
    while ((match = regex.exec(searchText)) !== null) {
        terms.push(match[0]);
    }
    return terms;
}

// Helper: Get the clean term (without ! and quotes)
function getCleanTerm(term: string): { isNegated: boolean; cleanValue: string } {
    const isNegated = term.startsWith('!');
    let value = isNegated ? term.substring(1) : term;
    // Remove surrounding quotes if present
    if (value.startsWith('"') && value.endsWith('"')) {
        value = value.slice(1, -1);
    }
    return { isNegated, cleanValue: value };
}

// Helper: Quote a term if it contains spaces
function quoteIfNeeded(term: string): string {
    return term.includes(' ') ? `"${term}"` : term;
}

// Helper: Serialize terms back to search string
function serializeSearchTerms(terms: string[]): string {
    return terms.join(' ');
}


function VulnerabilitiesContent() {
    const [vulnerabilities, setVulnerabilities] = useState<Vulnerability[]>([]);
    const [assets, setAssets] = useState<Asset[]>([]);
    const [users, setUsers] = useState<UserInfo[]>([]);
    const [groups, setGroups] = useState<Group[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchText, setSearchText] = useState('');
    const [selectedSeverity, setSelectedSeverity] = useState('');
    const [selectedAssetId, setSelectedAssetId] = useState('');
    // Default to 'active' (open + pending_verification + patch_failed) so
    // SOC list isn't polluted with FP/accepted/deferred rows. Drop-down
    // exposes individual statuses + 'closed' group + 'all'.
    const [selectedStatus, setSelectedStatus] = useState('active');
    const [kevOnly, setKevOnly] = useState(false);
    const [euvdOnly, setEuvdOnly] = useState(false);
    const [sourceFilter, setSourceFilter] = useState<'all' | 'wazuh' | 'nessus' | 'manual'>('all');
    const [crossConfirmedOnly, setCrossConfirmedOnly] = useState(false);
    const [euCritical, setEuCritical] = useState(false);
    const [inBothCatalogs, setInBothCatalogs] = useState(false);
    const [epssMin, setEpssMin] = useState<string>('');
    const [isEnriching, setIsEnriching] = useState(false);
    const [isCorrectingScores, setIsCorrectingScores] = useState(false);
    // Async CVSS-correction job tracking
    type OverrideJob = {
        job_id: string;
        status: 'queued' | 'running' | 'completed' | 'failed';
        stage?: string;
        total?: number;
        done?: number;
        updated?: number;
        checked?: number;
        not_found?: number;
        error?: string | null;
    };
    const [overrideJob, setOverrideJob] = useState<OverrideJob | null>(null);
    const overridePollRef = useRef<NodeJS.Timeout | null>(null);

    // Sortierung (klickbare Header)
    const [sortBy, setSortBy] = useState<string>('priority');
    const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');

    // Horizontaler Tabellen-Scroll (Maus ohne H-Scroll-Rad)
    const tableScrollRef = useRef<HTMLDivElement>(null);
    const [scrollState, setScrollState] = useState<{ canLeft: boolean; canRight: boolean }>({ canLeft: false, canRight: false });

    const updateScrollState = useCallback(() => {
        const el = tableScrollRef.current;
        if (!el) return;
        const canLeft = el.scrollLeft > 5;
        const canRight = el.scrollLeft + el.clientWidth < el.scrollWidth - 5;
        setScrollState({ canLeft, canRight });
    }, []);

    const scrollTable = (direction: 'left' | 'right') => {
        const el = tableScrollRef.current;
        if (!el) return;
        const step = Math.max(el.clientWidth * 0.6, 300);
        el.scrollBy({ left: direction === 'left' ? -step : step, behavior: 'smooth' });
    };

    useEffect(() => {
        updateScrollState();
        const el = tableScrollRef.current;
        if (!el) return;
        el.addEventListener('scroll', updateScrollState, { passive: true });
        window.addEventListener('resize', updateScrollState);
        return () => {
            el.removeEventListener('scroll', updateScrollState);
            window.removeEventListener('resize', updateScrollState);
        };
    }, [updateScrollState, vulnerabilities]);

    // Stop polling the override-job status endpoint when the page unmounts
    // or the dev hot-reloads — otherwise the interval would leak across
    // route changes and keep hammering the backend.
    useEffect(() => {
        return () => {
            if (overridePollRef.current) {
                clearInterval(overridePollRef.current);
                overridePollRef.current = null;
            }
        };
    }, []);

    const handleSort = (column: string) => {
        if (sortBy === column) {
            // toggle order
            setSortOrder(prev => prev === 'desc' ? 'asc' : 'desc');
        } else {
            setSortBy(column);
            setSortOrder('desc');
        }
        setCurrentPage(1);
    };

    const SortArrow = ({ column }: { column: string }) => {
        if (sortBy !== column) {
            return <span className="text-gray-300 ml-1">↕</span>;
        }
        return <span className="text-vulncheck-blue ml-1">{sortOrder === 'desc' ? '↓' : '↑'}</span>;
    };

    // Help-Tooltip text per column
    const COLUMN_HELP: Record<string, string> = {
        cvss: 'CVSS (Common Vulnerability Scoring System) — technical severity score 0-10. CVSS 9-10 = Critical, 7-8.9 = High, 4-6.9 = Medium, 0.1-3.9 = Low. Source: NVD / Wazuh.',
        epss: 'EPSS (Exploit Prediction Scoring System) — probability (0-100%) that this CVE will be exploited within the next 30 days. Computed daily by FIRST.org via ML from honeypot data, PoC availability, and social-media mentions. Percentile (p-value): rank against all CVEs worldwide — p99 = top 1% most dangerous.',
        kev: 'CISA KEV (Known Exploited Vulnerabilities) — US cybersecurity agency catalog of CVEs proven to be exploited by attackers in real-world attacks. RANSOM badge = known use in ransomware campaigns (LockBit, BlackCat, etc.). KEV listing = patch immediately, regardless of CVSS score.',
        euvd: 'ENISA EUVD (European Union Vulnerability Database) — EU counterpart to CISA KEV. Maintains two lists: "Exploited" (~1600 CVEs actively exploited in the EU) and "Critical" (curated ENISA priorities). EU-CRIT badge = ENISA-flagged critical. Source: enisa.europa.eu.',
        cpr: 'CPR (Cybersecurity Priority Risk) — weighted blend of CVSS + EPSS percentiles (JacquesKruger algorithm): (CVSS×10 × 0.6) + (EPSS_Percentile × 0.4), capped at 100. Answers "how critical is the CVE objectively?". Critical 90-100, High 70-89, Medium 40-69, Low 0-39.',
        priority: 'Priority Score — operational 0-100 score: "what should we fix first in OUR environment?". Formula: (CVSS + Exploit-Signal[KEV/EUVD/EPSS/Wazuh]) × Asset-Criticality + Age + KEV-Bonus + EUVD-Bonus. Takes asset context (policies) into account — unlike CPR.',
        severity: 'Severity — classification based on CVSS score: Critical (≥9), High (≥7), Medium (≥4), Low (<4), None (0).',
    };

    const [openHelp, setOpenHelp] = useState<string | null>(null);

    // Close popover when clicking outside
    useEffect(() => {
        if (!openHelp) return;
        const handler = (e: MouseEvent) => {
            const target = e.target as HTMLElement;
            if (!target.closest('[data-help-popover]')) {
                setOpenHelp(null);
            }
        };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, [openHelp]);

    const HeaderHelp = ({ column }: { column: string }) => {
        const text = COLUMN_HELP[column];
        if (!text) return null;
        const isOpen = openHelp === column;
        return (
            <span className="relative ml-1 inline-flex" data-help-popover>
                <button
                    type="button"
                    onClick={(e) => {
                        e.stopPropagation();
                        setOpenHelp(isOpen ? null : column);
                    }}
                    className="text-gray-400 hover:text-vulncheck-blue cursor-pointer inline-flex"
                    title={text}
                    aria-label={`Help for ${column}`}
                >
                    <InformationCircleIcon className="h-3.5 w-3.5" />
                </button>
                {isOpen && (
                    <div
                        className="absolute left-1/2 top-full z-50 mt-2 w-96 -translate-x-1/2 rounded-md border border-gray-200 bg-white p-3 text-xs font-normal normal-case tracking-normal text-gray-700 shadow-lg"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="mb-1 flex items-center justify-between">
                            <strong className="text-vulncheck-blue uppercase text-[11px] tracking-wider">{column}</strong>
                            <button
                                onClick={(e) => { e.stopPropagation(); setOpenHelp(null); }}
                                className="text-gray-400 hover:text-gray-700"
                                aria-label="Close"
                            >
                                <XMarkIcon className="h-3.5 w-3.5" />
                            </button>
                        </div>
                        <p className="leading-relaxed">{text}</p>
                        {column === 'priority' && (
                            <div className="mt-3 pt-2 border-t border-gray-100">
                                <p className="text-[10px] uppercase tracking-wider text-gray-500 mb-1.5">Badge legend</p>
                                <ul className="space-y-1.5">
                                    <li className="flex items-start gap-2">
                                        <span className="inline-flex items-center rounded-sm bg-red-100 px-1.5 py-0.5 text-[10px] font-bold text-red-700 animate-pulse mt-0.5">EXPLOITABLE</span>
                                        <span className="text-[11px]">Wazuh/Nessus saw a public exploit (boolean flag).</span>
                                    </li>
                                    <li className="flex items-start gap-2">
                                        <span className="inline-flex items-center rounded-sm bg-orange-100 px-1.5 py-0.5 text-[10px] font-mono font-bold text-orange-700 mt-0.5">VPR 8.4</span>
                                        <span className="text-[11px]">Tenable Vulnerability Priority Rating (0-10) from Nessus.</span>
                                    </li>
                                    <li className="flex items-start gap-2">
                                        <span className="inline-flex items-center rounded-sm bg-yellow-100 px-1.5 py-0.5 text-[10px] font-bold text-yellow-700 mt-0.5">POC</span>
                                        <span className="text-[11px]">SSVC <em>Exploitation = poc</em>: public proof-of-concept exists.</span>
                                    </li>
                                    <li className="flex items-start gap-2">
                                        <span className="inline-flex items-center rounded-sm bg-orange-100 px-1.5 py-0.5 text-[10px] font-bold text-orange-700 mt-0.5">ACTIVE</span>
                                        <span className="text-[11px]">SSVC <em>Exploitation = active</em>: confirmed exploitation in the wild.</span>
                                    </li>
                                    <li className="flex items-start gap-2">
                                        <span className="inline-flex items-center rounded-sm bg-red-600 px-1.5 py-0.5 text-[10px] font-bold text-white mt-0.5">WIDESPREAD</span>
                                        <span className="text-[11px]">SSVC <em>Exploitation = widespread</em>: mass exploitation campaign.</span>
                                    </li>
                                    <li className="flex items-start gap-2">
                                        <span className="inline-flex items-center rounded-sm bg-red-100 px-1.5 py-0.5 text-[10px] font-bold text-red-700 mt-0.5">TI-TOTAL</span>
                                        <span className="text-[11px]">SSVC <em>Technical Impact = total</em>: attacker gains full control over the software.</span>
                                    </li>
                                    <li className="flex items-start gap-2">
                                        <span className="inline-flex items-center rounded-sm bg-amber-100 px-1.5 py-0.5 text-[10px] font-bold text-amber-700 mt-0.5">AUTO</span>
                                        <span className="text-[11px]">SSVC <em>Automatable = yes</em>: reliable mass exploitation is mechanically feasible.</span>
                                    </li>
                                    <li className="flex items-start gap-2">
                                        <span className="inline-flex items-center rounded-sm bg-emerald-100 px-1.5 py-0.5 text-[10px] font-bold text-emerald-700 mt-0.5">PATCH AVAILABLE</span>
                                        <span className="text-[11px]">fixed_version known — upgrade target visible on detail page.</span>
                                    </li>
                                </ul>
                                <p className="mt-2 text-[10px] text-gray-500">
                                    SSVC data from CISA Vulnrichment (set via <em>Correct CVSS</em> + nightly job).
                                    TI-TOTAL + AUTO + ACTIVE/WIDESPREAD = "patch right now".
                                </p>
                            </div>
                        )}
                    </div>
                )}
            </span>
        );
    };

    // Pagination
    const [currentPage, setCurrentPage] = useState(1);
    const [totalCount, setTotalCount] = useState(0);
    const pageSize = 100;

    // Status & Defer Modal State
    const [isStatusModalOpen, setIsStatusModalOpen] = useState(false);
    const [statusTarget, setStatusTarget] = useState<Vulnerability | null>(null);
    const [newStatus, setNewStatus] = useState<string>('');
    const [statusComment, setStatusComment] = useState('');
    const [deferDate, setDeferDate] = useState('');
    const [actionStatus, setActionStatus] = useState({ message: '', type: '' });
    const [currentUser, setCurrentUser] = useState<UserInfo | null>(null);

    // Multi-select State
    const [selectedIds, setSelectedIds] = useState<number[]>([]);
    const [bulkActionTarget, setBulkActionTarget] = useState<{ type: 'user' | 'group' | 'status', id?: number, value?: string } | null>(null);

    const router = useRouter();
    const searchParams = useSearchParams();

    // Initialize from URL params
    useEffect(() => {
        const assetId = searchParams.get('asset_id');
        const severity = searchParams.get('severity');
        const search = searchParams.get('cve_id') || searchParams.get('search') || '';
        if (assetId) setSelectedAssetId(assetId);
        if (severity) setSelectedSeverity(severity);
        if (search) setSearchText(search);
    }, [searchParams]);

    // Fetch Current User
    useEffect(() => {
        api.get('/auth/me')
            .then(res => setCurrentUser(res.data))
            .catch(err => console.error("Failed to fetch user info", err));
    }, []);

    const fetchData = useCallback(async () => {
        setLoading(true);
        try {
            const params: any = { limit: pageSize, offset: (currentPage - 1) * pageSize };
            if (selectedAssetId) params.asset_id = selectedAssetId;
            if (selectedSeverity) params.severity = selectedSeverity;
            if (searchText) params.search = searchText;
            // Always send the literal value (including 'all', 'active',
            // 'closed') — backend handles all three groups + enum literals.
            if (selectedStatus) params.status = selectedStatus;
            if (kevOnly) params.kev_only = true;
            if (euvdOnly) params.euvd_only = true;
            if (euCritical) params.eu_critical = true;
            if (inBothCatalogs) params.in_both_catalogs = true;
            if (sourceFilter !== 'all') params.source = sourceFilter;
            if (crossConfirmedOnly) params.cross_confirmed = true;
            if (epssMin) {
                // UI input is percentage (0-100), backend expects 0.0-1.0
                const v = parseFloat(epssMin);
                if (!isNaN(v) && v > 0) params.epss_min = v / 100;
            }
            params.sort_by = sortBy;
            params.sort_order = sortOrder;

            const [vulnRes, assetsRes, usersRes, groupsRes] = await Promise.all([
                api.get('/api/v1/vulnerabilities', { params }),
                api.get('/api/v1/assets'),
                api.get('/auth/users').catch(() => ({ data: [] })),
                api.get('/api/v1/groups'),
            ]);
            setVulnerabilities(vulnRes.data.items || vulnRes.data);
            setTotalCount(vulnRes.data.total || 0);
            setAssets(assetsRes.data);
            setUsers(usersRes.data);
            setGroups(groupsRes.data);
        } catch (error) {
            console.error("Failed to fetch data:", error);
        } finally {
            setLoading(false);
        }
    }, [selectedAssetId, selectedSeverity, searchText, selectedStatus, currentPage, kevOnly, euvdOnly, euCritical, inBothCatalogs, sourceFilter, crossConfirmedOnly, epssMin, sortBy, sortOrder]);

    const handleEnrichAll = async () => {
        if (isEnriching) return;
        if (!confirm('Start threat intel enrichment for all open vulnerabilities? (Fetches EPSS + CISA KEV + ENISA EUVD)')) return;
        setIsEnriching(true);
        try {
            const res = await api.post('/api/v1/vulnerabilities/enrich/bulk', { only_open: true });
            const s = res.data.stats || {};
            alert(`Enrichment done: ${s.epss_updated || 0} EPSS updates, ${s.kev_marked || 0} newly flagged as KEV, ${s.euvd_marked || 0} flagged as EUVD.`);
            fetchData();
        } catch (e: any) {
            alert(`Enrichment failed: ${e?.response?.data?.detail || e?.message || 'unknown'}`);
        } finally {
            setIsEnriching(false);
        }
    };

    const handleEnrichSingle = async (vulnId: number) => {
        try {
            await api.post(`/api/v1/vulnerabilities/${vulnId}/enrich`);
            fetchData();
        } catch (e: any) {
            alert(`Enrichment failed: ${e?.response?.data?.detail || e?.message || 'unknown'}`);
        }
    };

    const handleAssign = async (vulnId: number, value: string) => {
        try {
            const payload: any = {};
            if (value === "") {
                payload.user_id = null;
                payload.group_id = null;
            } else if (value.startsWith("group_")) {
                payload.group_id = parseInt(value.replace("group_", ""));
                payload.user_id = null; // Clear user if group assigned
            } else {
                payload.user_id = parseInt(value);
                payload.group_id = null; // Clear group if user assigned
            }

            await api.patch(`/api/v1/vulnerabilities/${vulnId}/assign`, payload);
            fetchData(); // Refresh to show update
        } catch (error) {
            console.error("Failed to assign user/group", error);
        }
    };

    const handleOpenStatusModal = (vuln: Vulnerability) => {
        setStatusTarget(vuln);
        setNewStatus(vuln.status);
        setStatusComment(vuln.defer_reason || '');

        // Default defer date: +7 days
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 7);
        setDeferDate(tomorrow.toISOString().split('T')[0]);

        setIsStatusModalOpen(true);
        setActionStatus({ message: '', type: '' });
    };

    const handleConfirmStatusChange = async () => {
        if (!statusTarget) return;
        try {
            const payload: any = { status: newStatus.toLowerCase() };

            // Always send the comment as `reason` (status-agnostic audit
            // trail field). For the deferred-status flow ALSO populate
            // `defer_reason` + `deferred_until` so the legacy columns on
            // the vulnerability row keep working.
            if (statusComment) {
                payload.reason = statusComment;
                if (newStatus === 'deferred') {
                    payload.defer_reason = statusComment;
                }
            }
            if (newStatus === 'deferred') {
                payload.deferred_until = new Date(deferDate).toISOString();
            }

            await api.patch(`/api/v1/vulnerabilities/${statusTarget.id}`, payload);
            setIsStatusModalOpen(false);
            fetchData();
        } catch (error: any) {
            setActionStatus({ message: error.response?.data?.detail || 'Failed to update vulnerability status', type: 'error' });
        }
    };

    const handleMarkFalsePositive = async (vuln: Vulnerability) => {
        const isFp = vuln.status === 'false_positive';
        if (isFp) {
            if (!confirm(`Revert ${vuln.cve_id} back to OPEN?`)) return;
            try {
                await api.patch(`/api/v1/vulnerabilities/${vuln.id}/unmark-false-positive`);
                fetchData();
            } catch (e: any) {
                alert(`Failed: ${e?.response?.data?.detail || 'unknown'}`);
            }
            return;
        }
        const reason = prompt(`Mark ${vuln.cve_id} as FALSE POSITIVE? Optional reason:`);
        if (reason === null) return; // cancelled
        try {
            await api.patch(`/api/v1/vulnerabilities/${vuln.id}/false-positive`, { reason });
            fetchData();
        } catch (e: any) {
            alert(`Failed: ${e?.response?.data?.detail || 'unknown'}`);
        }
    };

    const handleSuppressNotifications = async (vuln: Vulnerability) => {
        try {
            await api.patch(`/api/v1/vulnerabilities/${vuln.id}/suppress-notifications`);
            // Optimistic update
            setVulnerabilities(prev => prev.map(v =>
                v.id === vuln.id ? { ...v, notification_suppressed: !v.notification_suppressed } : v
            ));
        } catch (error) {
            console.error("Failed to toggle notifications", error);
        }
    };

    const [isBulkUpdating, setIsBulkUpdating] = useState(false);

    const handleBulkUpdate = async () => {
        if (selectedIds.length === 0 || !bulkActionTarget) {
            console.log('[BulkUpdate] Skipping: no selection or no target', { selectedIds, bulkActionTarget });
            return;
        }
        setIsBulkUpdating(true);
        try {
            const payload: any = {
                vulnerability_ids: selectedIds,
            };
            if (bulkActionTarget.type === 'user') payload.assigned_user_id = bulkActionTarget.id;
            if (bulkActionTarget.type === 'group') payload.assigned_group_id = bulkActionTarget.id;
            if (bulkActionTarget.type === 'status' && bulkActionTarget.value) payload.status = bulkActionTarget.value.toLowerCase();

            console.log('[BulkUpdate] Sending payload:', payload);
            await api.post('/api/v1/vulnerabilities/bulk-update', payload);
            setSelectedIds([]);
            setBulkActionTarget(null);
            fetchData();
        } catch (error: any) {
            console.error("Bulk update failed", error);
            if (error.response && error.response.status === 403) {
                setActionStatus({ message: "Permission denied: Read-only users cannot modify data.", type: 'error' });
                alert("Permission denied: You do not have permissions to perform this action.");
            } else {
                setActionStatus({ message: "Bulk update failed.", type: 'error' });
                alert(`Failed to update vulnerabilities: ${error.response?.data?.detail || "Unknown error"}`);
            }
        } finally {
            setIsBulkUpdating(false);
        }
    };

    const handleSelectAll = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.checked) {
            setSelectedIds(vulnerabilities.map(v => v.id));
        } else {
            setSelectedIds([]);
        }
    };

    const toggleSelect = (id: number) => {
        setSelectedIds(prev =>
            prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
        );
    };

    useEffect(() => {
        const timer = setTimeout(() => {
            fetchData();
        }, searchText ? 300 : 0); // debounce search
        return () => clearTimeout(timer);
    }, [fetchData, searchText]);

    const clearFilters = () => {
        setSearchText('');
        setSelectedSeverity('');
        setSelectedAssetId('');
        setKevOnly(false);
        setEuvdOnly(false);
        setEuCritical(false);
        setInBothCatalogs(false);
        setEpssMin('');
        setCurrentPage(1);
        router.push('/vulnerabilities');
    };

    const hasFilters = searchText || selectedSeverity || selectedAssetId || kevOnly || euvdOnly || euCritical || inBothCatalogs || epssMin;

    const severityCounts = vulnerabilities.reduce((acc, v) => {
        acc[v.severity] = (acc[v.severity] || 0) + 1;
        return acc;
    }, {} as Record<string, number>);

    return (
        <div className="w-full">
            {/* Floating progress card for the async CVSS-correction job.
                Stays visible until the user dismisses a completed/failed run. */}
            {overrideJob && (
                <div className="fixed bottom-4 right-4 z-50 w-96 rounded-lg border border-gray-200 bg-white shadow-xl">
                    <div className="border-b border-gray-100 px-4 py-3 flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <span className={`h-2.5 w-2.5 rounded-full ${
                                overrideJob.status === 'completed' ? 'bg-emerald-500' :
                                overrideJob.status === 'failed' ? 'bg-red-500' :
                                'bg-amber-500 animate-pulse'
                            }`} />
                            <h3 className="text-sm font-bold font-mono text-gray-900">
                                CVSS Correction
                            </h3>
                            <span className="text-[10px] uppercase tracking-wider font-mono text-gray-500">
                                {overrideJob.status}
                            </span>
                        </div>
                        {(overrideJob.status === 'completed' || overrideJob.status === 'failed') && (
                            <button
                                onClick={() => setOverrideJob(null)}
                                className="text-gray-400 hover:text-gray-600 text-lg leading-none"
                                aria-label="Dismiss"
                            >
                                ×
                            </button>
                        )}
                    </div>
                    <div className="px-4 py-3 space-y-2">
                        <p className="text-xs text-gray-600 font-mono break-words">
                            {overrideJob.stage || 'working...'}
                        </p>
                        {(overrideJob.total ?? 0) > 0 && (
                            <div className="space-y-1">
                                <div className="flex justify-between text-[10px] font-mono text-gray-500">
                                    <span>{overrideJob.done ?? 0} / {overrideJob.total ?? 0} CVEs</span>
                                    <span>
                                        {overrideJob.total ? Math.round(((overrideJob.done ?? 0) / overrideJob.total) * 100) : 0}%
                                    </span>
                                </div>
                                <div className="h-1.5 w-full overflow-hidden rounded-full bg-gray-100">
                                    <div
                                        className={`h-full rounded-full transition-all ${
                                            overrideJob.status === 'failed' ? 'bg-red-500' :
                                            overrideJob.status === 'completed' ? 'bg-emerald-500' :
                                            'bg-amber-500'
                                        }`}
                                        style={{
                                            width: overrideJob.total
                                                ? `${Math.min(((overrideJob.done ?? 0) / overrideJob.total) * 100, 100)}%`
                                                : '0%',
                                        }}
                                    />
                                </div>
                            </div>
                        )}
                        {overrideJob.status === 'completed' && (
                            <div className="grid grid-cols-3 gap-2 pt-2 border-t border-gray-100 text-center">
                                <div>
                                    <p className="text-base font-bold text-emerald-700 font-mono">{overrideJob.updated ?? 0}</p>
                                    <p className="text-[9px] uppercase text-gray-500 font-mono">Updated</p>
                                </div>
                                <div>
                                    <p className="text-base font-bold text-gray-700 font-mono">{overrideJob.checked ?? 0}</p>
                                    <p className="text-[9px] uppercase text-gray-500 font-mono">Checked</p>
                                </div>
                                <div>
                                    <p className="text-base font-bold text-amber-700 font-mono" title="CVEs not yet in CISA Vulnrichment feed">
                                        {overrideJob.not_found ?? 0}
                                    </p>
                                    <p className="text-[9px] uppercase text-gray-500 font-mono">Not in feed</p>
                                </div>
                            </div>
                        )}
                        {overrideJob.status === 'failed' && overrideJob.error && (
                            <p className="text-xs text-red-700 font-mono break-words pt-2 border-t border-red-100">
                                {overrideJob.error}
                            </p>
                        )}
                    </div>
                </div>
            )}

            {/* Sticky Header + Filter Bar (compact, stays at top while scrolling) */}
            <div className="sticky top-0 z-30 -mx-4 px-4 pt-2 pb-2 bg-[#F3F4F6]/95 backdrop-blur-sm sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8">
                <div className="mb-2 flex items-center justify-between">
                    <h2 className="text-xl font-bold text-gray-900 font-mono">
                        Vulnerabilities
                        <span className="ml-3 text-xs text-gray-500 font-normal">{totalCount} total · {vulnerabilities.length} shown</span>
                    </h2>
                </div>

                {/* Search & Filter Bar (compact) */}
                <div className="bg-white border border-gray-200 shadow-sm rounded-sm p-3">
                <div className="flex flex-wrap items-center gap-3">
                    {/* Search Input */}
                    <div className="relative flex-1 min-w-[250px]">
                        <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                        <input
                            type="text"
                            value={searchText}
                            onChange={(e) => setSearchText(e.target.value)}
                            placeholder="Search CVE, package, or title..."
                            className="w-full pl-9 pr-3 py-2 border border-gray-300 rounded-md text-sm font-mono focus:ring-vulncheck-blue focus:border-vulncheck-blue"
                        />
                    </div>

                    {/* Severity Filter */}
                    <div className="flex items-center gap-1">
                        <FunnelIcon className="h-4 w-4 text-gray-400" />
                        <select
                            value={selectedSeverity}
                            onChange={(e) => { setSelectedSeverity(e.target.value); setCurrentPage(1); }}
                            className="border border-gray-300 rounded-md text-sm font-mono py-2 px-3 focus:ring-vulncheck-blue focus:border-vulncheck-blue"
                        >
                            <option value="">All Severities</option>
                            <option value="critical">Critical</option>
                            <option value="high">High</option>
                            <option value="medium">Medium</option>
                            <option value="low">Low</option>
                        </select>
                    </div>

                    {/* Status Filter */}
                    <div className="flex items-center gap-1">
                        <FunnelIcon className="h-4 w-4 text-gray-400" />
                        <select
                            value={selectedStatus}
                            onChange={(e) => { setSelectedStatus(e.target.value); setCurrentPage(1); }}
                            className="border border-gray-300 rounded-md text-sm font-mono py-2 px-3 focus:ring-vulncheck-blue focus:border-vulncheck-blue"
                        >
                            <optgroup label="Groups">
                                <option value="active">Active (open + pending + patch failed)</option>
                                <option value="closed">Closed (patched / FP / accepted / deferred)</option>
                                <option value="all">All statuses</option>
                            </optgroup>
                            <optgroup label="Active states">
                                <option value="open">Open</option>
                                <option value="pending_verification">Pending Verification</option>
                                <option value="patch_failed">Patch Failed</option>
                            </optgroup>
                            <optgroup label="Closed states">
                                <option value="patched">Patched</option>
                                <option value="false_positive">False Positive</option>
                                <option value="accepted_risk">Accepted Risk</option>
                                <option value="deferred">Deferred</option>
                            </optgroup>
                        </select>
                    </div>

                    {/* Host Filter (Searchable) */}
                    <div className="w-[200px] z-20">
                        <SearchableSelect
                            options={[
                                { value: "", label: "All Hosts" },
                                ...assets.map(a => ({ value: String(a.id), label: a.hostname }))
                            ]}
                            value={selectedAssetId}
                            onChange={(val) => { setSelectedAssetId(String(val || "")); setCurrentPage(1); }}
                            placeholder="Select Host..."
                        />
                    </div>

                    {/* KEV Filter (CISA US) */}
                    <label className="inline-flex items-center gap-1 text-xs font-mono px-2 py-2 border border-gray-300 rounded-md cursor-pointer hover:bg-gray-50" title="Only CVEs in CISA Known Exploited Vulnerabilities catalog (US)">
                        <input
                            type="checkbox"
                            checked={kevOnly}
                            onChange={(e) => { setKevOnly(e.target.checked); setCurrentPage(1); }}
                            className="rounded border-gray-300 text-red-600 focus:ring-red-500"
                        />
                        <span className="text-red-700 font-bold">KEV</span>
                    </label>

                    {/* EUVD Filter (ENISA EU) */}
                    <label className="inline-flex items-center gap-1 text-xs font-mono px-2 py-2 border border-gray-300 rounded-md cursor-pointer hover:bg-gray-50" title="Only CVEs in ENISA EUVD (EU exploited vulnerabilities)">
                        <input
                            type="checkbox"
                            checked={euvdOnly}
                            onChange={(e) => { setEuvdOnly(e.target.checked); setCurrentPage(1); }}
                            className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <span className="text-blue-700 font-bold">EUVD</span>
                    </label>

                    {/* EU Critical */}
                    <label className="inline-flex items-center gap-1 text-xs font-mono px-2 py-2 border border-gray-300 rounded-md cursor-pointer hover:bg-gray-50" title="ENISA-flagged critical CVEs">
                        <input
                            type="checkbox"
                            checked={euCritical}
                            onChange={(e) => { setEuCritical(e.target.checked); setCurrentPage(1); }}
                            className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <span className="text-blue-700 font-bold">EU Critical</span>
                    </label>

                    {/* In Both Catalogs */}
                    <label className="inline-flex items-center gap-1 text-xs font-mono px-2 py-2 border border-gray-300 rounded-md cursor-pointer hover:bg-gray-50" title="CVEs confirmed by both CISA KEV and ENISA EUVD">
                        <input
                            type="checkbox"
                            checked={inBothCatalogs}
                            onChange={(e) => { setInBothCatalogs(e.target.checked); setCurrentPage(1); }}
                            className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
                        />
                        <span className="text-purple-700 font-bold">KEV + EUVD</span>
                    </label>

                    {/* Scanner source filter */}
                    <div className="flex items-center gap-1">
                        <label className="text-xs text-gray-500 font-mono">Source</label>
                        <select
                            value={sourceFilter}
                            onChange={(e) => { setSourceFilter(e.target.value as any); setCurrentPage(1); }}
                            className="border border-gray-300 rounded-md text-xs font-mono py-2 px-2 focus:ring-vulncheck-blue focus:border-vulncheck-blue"
                            title="Which scanner reported this CVE"
                        >
                            <option value="all">all scanners</option>
                            <option value="wazuh">Wazuh only</option>
                            <option value="nessus">Nessus only</option>
                            <option value="manual">manual</option>
                        </select>
                    </div>

                    {/* Cross-confirmed (both scanners) */}
                    <label className="inline-flex items-center gap-1 text-xs font-mono px-2 py-2 border border-gray-300 rounded-md cursor-pointer hover:bg-gray-50" title="CVEs reported by 2+ scanners (highest confidence)">
                        <input
                            type="checkbox"
                            checked={crossConfirmedOnly}
                            onChange={(e) => { setCrossConfirmedOnly(e.target.checked); setCurrentPage(1); }}
                            className="rounded border-gray-300 text-emerald-600 focus:ring-emerald-500"
                        />
                        <span className="text-emerald-700 font-bold">Cross-confirmed</span>
                    </label>

                    {/* EPSS Min Filter (Percent 0-100) */}
                    <div className="flex items-center gap-1">
                        <label className="text-xs text-gray-500 font-mono" title="Minimum EPSS probability in percent (0-100)">EPSS ≥</label>
                        <input
                            type="number"
                            min="0"
                            max="100"
                            step="5"
                            value={epssMin}
                            onChange={(e) => { setEpssMin(e.target.value); setCurrentPage(1); }}
                            placeholder="50"
                            className="w-20 border border-gray-300 rounded-md text-sm font-mono py-2 px-2 focus:ring-vulncheck-blue focus:border-vulncheck-blue"
                        />
                        <span className="text-xs text-gray-500 font-mono">%</span>
                    </div>

                    {/* Manual Bulk Enrich */}
                    <button
                        onClick={handleEnrichAll}
                        disabled={isEnriching || currentUser?.role === 'readonly'}
                        className="inline-flex items-center gap-1 text-xs font-mono px-3 py-2 border border-vulncheck-blue text-vulncheck-blue rounded-md hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed"
                        title="Run EPSS + CISA KEV enrichment for all open vulnerabilities"
                    >
                        {isEnriching ? 'Enriching…' : 'Refresh Threat Intel'}
                    </button>

                    {/* Clear Filters */}
                    {hasFilters && (
                        <button
                            onClick={clearFilters}
                            className="inline-flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700 font-mono px-2 py-2 border border-gray-300 rounded-md hover:bg-gray-50"
                        >
                            <XMarkIcon className="h-3.5 w-3.5" />
                            Clear
                        </button>
                    )}

                    {/* Correct CVSS Scores (CISA Vulnrichment) */}
                    {currentUser?.role !== 'readonly' && (
                        <button
                            onClick={async () => {
                                if (!confirm(
                                    'Run CVSS score correction from CISA Vulnrichment?\n\n' +
                                    'This downloads the full vulnrichment snapshot (~250 MB) ' +
                                    'and fixes placeholder 10.0 scores + severity mismatches. ' +
                                    'Runs in the background — you can keep using VulnCheck ' +
                                    'while it works. Progress shows below.'
                                )) return;
                                setIsCorrectingScores(true);
                                try {
                                    const res = await api.post('/api/v1/vulnerabilities/override/vulnrichment/start?dry_run=false');
                                    setOverrideJob({
                                        job_id: res.data.job_id,
                                        status: 'queued',
                                        stage: 'starting...',
                                    });
                                    // Poll every 2s; clear on terminal state
                                    if (overridePollRef.current) clearInterval(overridePollRef.current);
                                    overridePollRef.current = setInterval(async () => {
                                        try {
                                            const s = await api.get(
                                                `/api/v1/vulnerabilities/override/vulnrichment/status/${res.data.job_id}`
                                            );
                                            setOverrideJob(s.data);
                                            if (s.data.status === 'completed' || s.data.status === 'failed') {
                                                if (overridePollRef.current) {
                                                    clearInterval(overridePollRef.current);
                                                    overridePollRef.current = null;
                                                }
                                                setIsCorrectingScores(false);
                                                if (s.data.status === 'completed') fetchData();
                                            }
                                        } catch (pollErr) {
                                            // Transient poll error — keep trying.
                                        }
                                    }, 2000);
                                } catch (e: any) {
                                    alert(`Could not start correction job: ${e?.response?.data?.detail || e?.message || 'unknown'}`);
                                    setIsCorrectingScores(false);
                                }
                            }}
                            disabled={isCorrectingScores || isEnriching}
                            className="inline-flex items-center gap-1 text-xs font-mono px-3 py-2 border border-amber-500 text-amber-700 rounded-md hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"
                            title="Correct CVSS scores from CISA Vulnrichment (fixes placeholder values like 10.0). Runs in the background."
                        >
                            {isCorrectingScores ? (
                                <>
                                    <span className="animate-spin">⟳</span> Correcting...
                                </>
                            ) : (
                                <>
                                    <ShieldExclamationIcon className="h-4 w-4" />
                                    Correct CVSS
                                </>
                            )}
                        </button>
                    )}
                </div>

                {/* Active Search Tags */}
                {searchText && (() => {
                    const terms = parseSearchTerms(searchText);
                    return terms.length > 0 && (
                        <div className="mt-3 flex flex-wrap gap-2 animate-in fade-in slide-in-from-top-1 duration-200 border-t border-gray-100 pt-3">
                            {terms.map((term, index) => {
                                const { isNegated, cleanValue } = getCleanTerm(term);
                                return (
                                    <span
                                        key={index}
                                        className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-mono border shadow-sm transition-all
                                            ${isNegated
                                                ? 'bg-red-50 text-red-700 border-red-200'
                                                : 'bg-blue-50 text-blue-700 border-blue-200'}`}
                                    >
                                        <span className="font-bold opacity-70">{isNegated ? 'NOT' : 'HAS'}</span>
                                        {cleanValue}
                                        <button
                                            onClick={() => {
                                                const newTerms = terms.filter((_, i) => i !== index);
                                                setSearchText(serializeSearchTerms(newTerms));
                                            }}
                                            className={`ml-1 hover:bg-black/10 rounded-full p-0.5 transition-colors
                                                ${isNegated ? 'text-red-600' : 'text-blue-600'}`}
                                            title="Remove filter"
                                        >
                                            <XMarkIcon className="h-3 w-3" />
                                        </button>
                                    </span>
                                );
                            })}
                        </div>
                    );
                })()}
                </div>
            </div>

            {/* Results Table */}
            <div className="bg-white border border-gray-200 shadow-sm rounded-sm relative mt-3">
                {/* Horizontal Scroll Controls (for mice without H-scroll wheel) */}
                {(scrollState.canLeft || scrollState.canRight) && (
                    <div className="flex items-center justify-end gap-1 px-3 py-1.5 border-b border-gray-200 bg-gray-50/50">
                        <button
                            onClick={() => scrollTable('left')}
                            disabled={!scrollState.canLeft}
                            className="p-1 rounded border border-gray-300 bg-white hover:bg-vulncheck-blue hover:text-white hover:border-vulncheck-blue disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                            title="Scroll left"
                            aria-label="Scroll left"
                        >
                            <ChevronLeftIcon className="h-4 w-4" />
                        </button>
                        <button
                            onClick={() => scrollTable('right')}
                            disabled={!scrollState.canRight}
                            className="p-1 rounded border border-gray-300 bg-white hover:bg-vulncheck-blue hover:text-white hover:border-vulncheck-blue disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                            title="Scroll right"
                            aria-label="Scroll right"
                        >
                            <ChevronRightIcon className="h-4 w-4" />
                        </button>
                    </div>
                )}
                <div
                    ref={tableScrollRef}
                    className="overflow-x-auto scroll-visible-x"
                >
                    <table className="min-w-full divide-y divide-gray-200">
                        <thead className="bg-gray-50">
                            <tr>
                                <th className="px-4 py-3 text-left">
                                    <input
                                        type="checkbox"
                                        className="rounded border-gray-300 text-vulncheck-blue focus:ring-vulncheck-blue"
                                        checked={vulnerabilities.length > 0 && selectedIds.length === vulnerabilities.length}
                                        onChange={handleSelectAll}
                                        disabled={currentUser?.role === 'readonly'}
                                    />
                                </th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('cve_id')}
                                    className="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-tight font-mono cursor-pointer hover:bg-gray-100 select-none"
                                >
                                    CVE ID<SortArrow column="cve_id" />
                                </th>
                                <th scope="col" className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider">Host</th>
                                <th scope="col" className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider">Package</th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('severity')}
                                    className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                                >
                                    <span className="inline-flex items-center">Severity<HeaderHelp column="severity" /><SortArrow column="severity" /></span>
                                </th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('cvss')}
                                    className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                                >
                                    <span className="inline-flex items-center">CVSS<HeaderHelp column="cvss" /><SortArrow column="cvss" /></span>
                                </th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('epss')}
                                    className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                                >
                                    <span className="inline-flex items-center">EPSS<HeaderHelp column="epss" /><SortArrow column="epss" /></span>
                                </th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('kev')}
                                    className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                                >
                                    <span className="inline-flex items-center">KEV<HeaderHelp column="kev" /><SortArrow column="kev" /></span>
                                </th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('euvd')}
                                    className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                                >
                                    <span className="inline-flex items-center">EUVD<HeaderHelp column="euvd" /><SortArrow column="euvd" /></span>
                                </th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('cpr')}
                                    className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                                >
                                    <span className="inline-flex items-center">CPR<HeaderHelp column="cpr" /><SortArrow column="cpr" /></span>
                                </th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('priority')}
                                    className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                                >
                                    <span className="inline-flex items-center">Priority<HeaderHelp column="priority" /><SortArrow column="priority" /></span>
                                </th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('status')}
                                    className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                                >
                                    Status<SortArrow column="status" />
                                </th>
                                <th
                                    scope="col"
                                    onClick={() => handleSort('source')}
                                    className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                                    title="Which scanners detected this finding. Sorted by first-detected-by (wazuh / nessus / manual)."
                                >
                                    Source<SortArrow column="source" />
                                </th>
                                <th scope="col" className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider">Assigned To</th>
                                <th scope="col" className="sticky right-0 z-10 bg-gray-50 px-4 py-3 text-right text-xs font-mono font-medium text-gray-500 uppercase tracking-wider shadow-[-4px_0_8px_-2px_rgba(0,0,0,0.1)] border-l border-gray-200">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="bg-white divide-y divide-gray-200 font-mono text-sm">
                            {vulnerabilities.map((vuln) => (
                                <tr key={vuln.id} className={`group hover:bg-blue-50/30 transition-colors ${selectedIds.includes(vuln.id) ? 'bg-blue-50/50' : ''}`}>
                                    <td className="px-4 py-3">
                                        <input
                                            type="checkbox"
                                            className="rounded border-gray-200 text-vulncheck-blue focus:ring-vulncheck-blue"
                                            checked={selectedIds.includes(vuln.id)}
                                            onChange={() => toggleSelect(vuln.id)}
                                            disabled={currentUser?.role === 'readonly'}
                                        />
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        <a
                                            href={`/vulnerabilities/${vuln.id}`}
                                            className="font-bold text-vulncheck-blue hover:text-blue-800 hover:underline cursor-pointer"
                                        >
                                            {vuln.cve_id}
                                        </a>
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap text-gray-700">
                                        <a
                                            href={`/vulnerabilities?asset_id=${vuln.asset_id}`}
                                            className="hover:text-vulncheck-blue hover:underline"
                                            onClick={(e) => {
                                                e.preventDefault();
                                                setSelectedAssetId(String(vuln.asset_id));
                                            }}
                                        >
                                            {vuln.asset_hostname || `Asset #${vuln.asset_id}`}
                                        </a>
                                    </td>
                                    <td className="px-4 py-3 text-gray-500 max-w-[300px]">
                                        <div className="flex flex-wrap gap-1">
                                            {(vuln.package_name || '-').split(', ').map((pkgName, i) => {
                                                const pkg = pkgName.trim();
                                                const quotedPkg = quoteIfNeeded(pkg);
                                                const negQuotedPkg = `!${quotedPkg}`;

                                                // Parse terms properly
                                                const parsedTerms = parseSearchTerms(searchText);

                                                // Determine state: 0=none, 1=has, 2=not
                                                let state = 0; // none
                                                for (const term of parsedTerms) {
                                                    const { isNegated, cleanValue } = getCleanTerm(term);
                                                    if (cleanValue === pkg) {
                                                        state = isNegated ? 2 : 1;
                                                        break;
                                                    }
                                                }

                                                return (
                                                    <span
                                                        key={i}
                                                        className={`inline-block px-1.5 py-0.5 rounded text-[10px] cursor-pointer transition-colors border select-none
                                                            ${state === 1 ? 'bg-blue-100 text-blue-700 border-blue-200 font-bold' :
                                                                state === 2 ? 'bg-red-100 text-red-700 border-red-200 font-bold' :
                                                                    'bg-gray-50 text-gray-600 border-gray-100 hover:bg-gray-100 hover:border-gray-300'}`}
                                                        title={`Filter: ${pkg}`}
                                                        onClick={(e) => {
                                                            e.stopPropagation();

                                                            // Build new terms list
                                                            let newTerms = parsedTerms.filter(term => {
                                                                const { cleanValue } = getCleanTerm(term);
                                                                return cleanValue !== pkg;
                                                            });

                                                            if (state === 2) {
                                                                // Was excluded, now remove (do nothing more, already filtered)
                                                            } else {
                                                                // Not excluded, add exclusion
                                                                newTerms.push(negQuotedPkg);
                                                            }
                                                            setSearchText(serializeSearchTerms(newTerms));
                                                        }}
                                                    >
                                                        {state === 2 && '!'}
                                                        {pkg}
                                                    </span>
                                                );
                                            })}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        <span className={`inline-flex items-center rounded-md px-2 py-1 text-xs font-medium
                                            ${vuln.severity === 'critical' ? 'bg-red-100 text-red-700' :
                                                vuln.severity === 'high' ? 'bg-orange-100 text-orange-700' :
                                                    vuln.severity === 'medium' ? 'bg-blue-100 text-blue-700' : 'bg-green-100 text-green-700'}`}>
                                            {vuln.severity.toUpperCase()}
                                        </span>
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap font-bold">{vuln.cvss_score ?? '-'}</td>
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        {vuln.epss_score != null ? (
                                            <div className="flex flex-col items-start gap-0.5" title={`EPSS: ${(vuln.epss_score * 100).toFixed(2)}% | Percentile: ${((vuln.epss_percentile || 0) * 100).toFixed(1)}%`}>
                                                <span className={`font-mono font-bold ${vuln.epss_score >= 0.5 ? 'text-red-700' : vuln.epss_score >= 0.1 ? 'text-orange-600' : 'text-gray-700'}`}>
                                                    {(vuln.epss_score * 100).toFixed(1)}%
                                                </span>
                                                <span className="text-[9px] text-gray-400">p{((vuln.epss_percentile || 0) * 100).toFixed(0)}</span>
                                            </div>
                                        ) : (
                                            <span className="text-xs text-gray-300">—</span>
                                        )}
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        {vuln.kev_listed ? (
                                            <div className="flex flex-col items-start gap-0.5" title={`Listed in CISA Known Exploited Vulnerabilities catalog${vuln.kev_date_added ? ` (added ${new Date(vuln.kev_date_added).toLocaleDateString()})` : ''}`}>
                                                <span className="inline-flex items-center rounded-sm bg-red-100 px-1.5 py-0.5 text-[10px] font-bold text-red-700">
                                                    KEV
                                                </span>
                                                {vuln.kev_ransomware_use && (
                                                    <span className="inline-flex items-center rounded-sm bg-purple-100 px-1.5 py-0.5 text-[9px] font-bold text-purple-700" title="Known use in ransomware campaigns">
                                                        RANSOM
                                                    </span>
                                                )}
                                            </div>
                                        ) : (
                                            <span className="text-xs text-gray-300">—</span>
                                        )}
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        {vuln.euvd_listed ? (
                                            <div className="flex flex-col items-start gap-0.5" title={`Listed in ENISA EUVD${vuln.euvd_id ? ` (${vuln.euvd_id})` : ''}${vuln.euvd_date_added ? ` — added ${new Date(vuln.euvd_date_added).toLocaleDateString()}` : ''}`}>
                                                <span className="inline-flex items-center rounded-sm bg-blue-100 px-1.5 py-0.5 text-[10px] font-bold text-blue-700">
                                                    EUVD
                                                </span>
                                                {vuln.euvd_critical && (
                                                    <span className="inline-flex items-center rounded-sm bg-amber-100 px-1.5 py-0.5 text-[9px] font-bold text-amber-700" title="ENISA-flagged critical">
                                                        EU-CRIT
                                                    </span>
                                                )}
                                            </div>
                                        ) : (
                                            <span className="text-xs text-gray-300">—</span>
                                        )}
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        {vuln.cpr_score != null ? (
                                            <div className="flex items-center gap-1" title={`CPR = (CVSS×10 × 0.6) + (EPSS_Percentile × 0.4) — current value ${vuln.cpr_score.toFixed(2)} from CVSS ${(vuln.cvss_score ?? 0).toFixed(1)} + EPSS percentile ${((vuln.epss_percentile ?? 0) * 100).toFixed(1)}`}>
                                                <span className={`font-mono font-bold ${vuln.cpr_score >= 30 ? 'text-red-700' : vuln.cpr_score >= 10 ? 'text-orange-600' : 'text-gray-700'}`}>
                                                    {vuln.cpr_score.toFixed(1)}
                                                </span>
                                                <div className="w-12 h-1.5 bg-gray-100 rounded-full overflow-hidden">
                                                    <div
                                                        className={`h-full rounded-full ${vuln.cpr_score >= 30 ? 'bg-red-500' : vuln.cpr_score >= 10 ? 'bg-orange-500' : 'bg-green-500'}`}
                                                        style={{ width: `${Math.min(vuln.cpr_score, 100)}%` }}
                                                    />
                                                </div>
                                            </div>
                                        ) : (
                                            <span className="text-xs text-gray-300">—</span>
                                        )}
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        <div className="flex flex-col items-start gap-1">
                                            {(() => {
                                                const score = vuln.priority_score || 0;
                                                const bd = vuln.priority_breakdown;
                                                const tooltip = bd
                                                    ? `CVSS ${bd.cvss.toFixed(1)} + Exploit ${bd.exploit_bonus.toFixed(1)} (${bd.exploit_source}) × AssetFactor ${bd.asset_factor.toFixed(1)} + Age ${bd.age_bonus.toFixed(1)}${bd.kev_bonus ? ` + KEV ${bd.kev_bonus.toFixed(1)}` : ''}${bd.euvd_bonus ? ` + EUVD ${bd.euvd_bonus.toFixed(1)}` : ''} = ${bd.total.toFixed(1)}`
                                                    : `Priority: ${score.toFixed(1)}`;
                                                return (
                                                    <div className="flex items-center gap-1" title={tooltip}>
                                                        <span className="font-mono font-bold text-gray-900">{score.toFixed(0)}</span>
                                                        <div className="w-16 h-1.5 bg-gray-100 rounded-full overflow-hidden">
                                                            <div
                                                                className={`h-full rounded-full ${Math.round(score) >= 20 ? 'bg-red-500' : Math.round(score) >= 8 ? 'bg-orange-500' : 'bg-green-500'}`}
                                                                style={{ width: `${Math.min(score * 4, 100)}%` }}
                                                            />
                                                        </div>
                                                    </div>
                                                );
                                            })()}
                                            {vuln.exploit_available && (
                                                <span className="inline-flex items-center rounded-sm bg-red-100 px-1.5 py-0.5 text-[10px] font-bold text-red-700 animate-pulse">
                                                    EXPLOITABLE
                                                </span>
                                            )}
                                            {(() => {
                                                // Show PATCH AVAILABLE only when at least one package
                                                // has a real fix (fixed_version != installed_version).
                                                // has_fix_any handles the multi-package case + filters
                                                // out the Ghostscript inclusive-bound false-positive.
                                                if (vuln.status !== 'open') return null;
                                                const real = vuln.has_fix_any
                                                    ?? !!(vuln.fixed_version && vuln.fixed_version !== vuln.package_version);
                                                if (!real) return null;
                                                const fixCount = vuln.packages?.filter(p => p.has_fix).length || 0;
                                                const tt = fixCount > 1
                                                    ? `Patch available — ${fixCount} packages have a fix`
                                                    : `Patch available — upgrade to ${vuln.fixed_version || 'newer version'}`;
                                                return (
                                                    <span
                                                        className="inline-flex items-center rounded-sm bg-emerald-100 px-1.5 py-0.5 text-[10px] font-bold text-emerald-700"
                                                        title={tt}
                                                    >
                                                        PATCH AVAILABLE
                                                    </span>
                                                );
                                            })()}
                                            {vuln.nessus_vpr_score != null && (
                                                <span
                                                    className={`inline-flex items-center rounded-sm px-1.5 py-0.5 text-[10px] font-mono font-bold ${
                                                        vuln.nessus_vpr_score >= 9 ? 'bg-red-100 text-red-700' :
                                                        vuln.nessus_vpr_score >= 7 ? 'bg-orange-100 text-orange-700' :
                                                        vuln.nessus_vpr_score >= 4 ? 'bg-yellow-100 text-yellow-800' :
                                                        'bg-gray-100 text-gray-600'
                                                    }`}
                                                    title={`Tenable VPR Score: ${vuln.nessus_vpr_score.toFixed(1)} / 10`}
                                                >
                                                    VPR {vuln.nessus_vpr_score.toFixed(1)}
                                                </span>
                                            )}
                                            {vuln.exploitation_status && vuln.exploitation_status !== 'none' && (
                                                <span className={`inline-flex items-center rounded-sm px-1.5 py-0.5 text-[10px] font-bold uppercase ${
                                                    vuln.exploitation_status === 'widespread' ? 'bg-red-600 text-white' :
                                                    vuln.exploitation_status === 'active' ? 'bg-orange-100 text-orange-700' :
                                                    vuln.exploitation_status === 'poc' ? 'bg-yellow-100 text-yellow-700' :
                                                    'bg-gray-100 text-gray-500'
                                                }`} title={`SSVC Exploitation: ${vuln.exploitation_status}`}>
                                                    {vuln.exploitation_status.toUpperCase()}
                                                </span>
                                            )}
                                            {vuln.ssvc_technical_impact === 'total' && (
                                                <span className="inline-flex items-center rounded-sm bg-red-100 px-1.5 py-0.5 text-[10px] font-bold text-red-700 uppercase"
                                                      title="SSVC Technical Impact: total — attacker gains total control over the affected software">
                                                    TI-TOTAL
                                                </span>
                                            )}
                                            {vuln.ssvc_automatable === 'yes' && (
                                                <span className="inline-flex items-center rounded-sm bg-amber-100 px-1.5 py-0.5 text-[10px] font-bold text-amber-700 uppercase"
                                                      title="SSVC Automatable: yes — reliable mass exploitation is mechanically feasible">
                                                    AUTO
                                                </span>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        <button
                                            onClick={() => handleOpenStatusModal(vuln)}
                                            className={`inline-flex flex-col items-start px-2 py-1 rounded-md hover:bg-gray-100 transition-colors group w-full text-left`}
                                        >
                                            <span className={`inline-flex items-center rounded-md px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider
                                                ${vuln.status === 'open' ? 'bg-red-50 text-red-700 border border-red-100' :
                                                    vuln.status === 'patched' ? 'bg-green-50 text-green-700 border border-green-100' :
                                                        vuln.status === 'deferred' ? 'bg-purple-50 text-purple-700 border border-purple-100' :
                                                            'bg-gray-50 text-gray-600 border border-gray-100'}`}>
                                                {vuln.status.replace('_', ' ')}
                                            </span>
                                            {vuln.status === 'deferred' && vuln.deferred_until && (
                                                <div className="text-[10px] text-gray-500 mt-1 flex items-center gap-1 font-mono">
                                                    <ClockIcon className="h-3 w-3" />
                                                    {new Date(vuln.deferred_until).toLocaleDateString()}
                                                </div>
                                            )}
                                            {vuln.defer_reason && (
                                                <div className="text-[9px] text-gray-400 mt-0.5 italic truncate max-w-[120px]" title={vuln.defer_reason}>
                                                    "{vuln.defer_reason}"
                                                </div>
                                            )}
                                        </button>
                                    </td>
                                    {/* Source badges: which scanner(s) reported this CVE.
                                        For auto-patched rows, sources[] gets emptied by
                                        the scanner stale-pass; fall back to first_detected_by
                                        so the column does not go blank. */}
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        {(() => {
                                            const live = vuln.sources || [];
                                            const fallback = live.length === 0 && vuln.first_detected_by
                                                ? [vuln.first_detected_by]
                                                : [];
                                            const display = live.length > 0 ? live : fallback;
                                            return (
                                                <div className="flex flex-wrap items-center gap-1" title={`Detected by: ${live.join(', ') || 'no active scanner — history via ' + (vuln.first_detected_by || 'unknown')}`}>
                                                    {display.map(src => {
                                                        const cls = src === 'wazuh'
                                                            ? 'bg-green-100 text-green-700 border-green-200'
                                                            : src === 'nessus'
                                                                ? 'bg-purple-100 text-purple-700 border-purple-200'
                                                                : 'bg-gray-100 text-gray-600 border-gray-200';
                                                        // Italic + lower opacity when source is the fallback (no scanner sees it now)
                                                        const faded = live.length === 0 ? ' opacity-60 italic' : '';
                                                        return (
                                                            <span key={src} className={`inline-flex items-center rounded-sm border px-1.5 py-0.5 text-[10px] font-bold uppercase ${cls}${faded}`}>{src}</span>
                                                        );
                                                    })}
                                            {vuln.cross_confirmed && (
                                                <span className="inline-flex items-center rounded-sm border border-emerald-200 bg-emerald-100 px-1.5 py-0.5 text-[10px] font-bold uppercase text-emerald-700" title="Reported by multiple scanners — highest confidence">
                                                    ✓×2
                                                </span>
                                            )}
                                            {vuln.is_pseudo_cve && (
                                                <span className="inline-flex items-center rounded-sm border border-amber-200 bg-amber-50 px-1.5 py-0.5 text-[10px] font-bold uppercase text-amber-700" title="Non-CVE finding (EOL / Compliance / Cipher) imported as pseudo-CVE">
                                                    NON-CVE
                                                </span>
                                            )}
                                                </div>
                                            );
                                        })()}
                                    </td>
                                    <td className="px-4 py-3 whitespace-nowrap">
                                        <div className="flex items-center gap-2">
                                            {vuln.assigned_group_id ? (
                                                <UserGroupIcon className={`h-5 w-5 text-vulncheck-blue`} />
                                            ) : (
                                                <UserCircleIcon className={`h-5 w-5 ${vuln.assigned_user_id ? 'text-vulncheck-blue' : 'text-gray-300'}`} />
                                            )}
                                            <select
                                                value={vuln.assigned_group_id ? `group_${vuln.assigned_group_id}` : (vuln.assigned_user_id ? String(vuln.assigned_user_id) : "")}
                                                onChange={(e) => handleAssign(vuln.id, e.target.value)}
                                                className="block w-full rounded-md border-0 py-1.5 pl-2 pr-7 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-vulncheck-blue sm:text-xs sm:leading-6 bg-transparent"
                                                style={{ maxWidth: '120px' }}
                                            >
                                                <option value="">Unassigned</option>
                                                <optgroup label="Users">
                                                    {users.map(u => (
                                                        <option key={`u-${u.id}`} value={u.id}>{u.username}</option>
                                                    ))}
                                                </optgroup>
                                                <optgroup label="Groups">
                                                    {groups.map(g => (
                                                        <option key={`g-${g.id}`} value={`group_${g.id}`}>{g.name}</option>
                                                    ))}
                                                </optgroup>
                                            </select>
                                        </div>
                                    </td>
                                    <td
                                        className={`sticky right-0 z-10 px-4 py-3 whitespace-nowrap text-right shadow-[-4px_0_8px_-2px_rgba(0,0,0,0.1)] border-l border-gray-100 ${selectedIds.includes(vuln.id) ? 'bg-blue-50' : 'bg-white group-hover:bg-blue-50/30'}`}
                                    >
                                        <div className="flex justify-end gap-1">
                                            <button
                                                onClick={() => handleOpenStatusModal(vuln)}
                                                className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-vulncheck-blue"
                                                title="Change Status & Comment"
                                            >
                                                <PencilSquareIcon className="h-4 w-4" />
                                            </button>
                                            <button
                                                onClick={() => handleSuppressNotifications(vuln)}
                                                className={`p-1 hover:bg-gray-100 rounded ${vuln.notification_suppressed ? 'text-red-500' : 'text-gray-400 hover:text-red-500'}`}
                                                title={vuln.notification_suppressed ? 'Notifications Suppressed' : 'Suppress Notifications'}
                                            >
                                                <BellSlashIcon className="h-4 w-4" />
                                            </button>
                                            <button
                                                onClick={() => handleMarkFalsePositive(vuln)}
                                                className={`p-1 hover:bg-gray-100 rounded ${vuln.status === 'false_positive' ? 'text-amber-600' : 'text-gray-400 hover:text-amber-600'}`}
                                                title={vuln.status === 'false_positive' ? 'Marked as False Positive — click to revert' : 'Mark as False Positive'}
                                            >
                                                <NoSymbolIcon className="h-4 w-4" />
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                            {vulnerabilities.length === 0 && !loading && (
                                <tr><td colSpan={6} className="text-center py-8 text-gray-500">No vulnerabilities found.</td></tr>
                            )}
                        </tbody>
                    </table>
                </div>

                {/* Pagination */}
                {totalCount > pageSize && (
                    <div className="flex items-center justify-between px-4 py-3 bg-white border-t border-gray-200 rounded-b-lg">
                        <div className="text-sm text-gray-500 font-mono">
                            Showing {((currentPage - 1) * pageSize) + 1}–{Math.min(currentPage * pageSize, totalCount)} of {totalCount.toLocaleString()}
                        </div>
                        <div className="flex items-center gap-2">
                            <button
                                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                                disabled={currentPage === 1}
                                className="px-3 py-1.5 text-sm font-medium font-mono border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
                            >
                                Previous
                            </button>
                            {(() => {
                                const totalPages = Math.ceil(totalCount / pageSize);
                                const pages: (number | string)[] = [];
                                if (totalPages <= 7) {
                                    for (let i = 1; i <= totalPages; i++) pages.push(i);
                                } else {
                                    pages.push(1);
                                    if (currentPage > 3) pages.push('...');
                                    for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) pages.push(i);
                                    if (currentPage < totalPages - 2) pages.push('...');
                                    pages.push(totalPages);
                                }
                                return pages.map((page, idx) =>
                                    typeof page === 'string' ? (
                                        <span key={`ellipsis-${idx}`} className="px-2 text-gray-400">…</span>
                                    ) : (
                                        <button
                                            key={page}
                                            onClick={() => setCurrentPage(page)}
                                            className={`px-3 py-1.5 text-sm font-mono rounded-md ${
                                                currentPage === page
                                                    ? 'bg-vulncheck-blue text-white font-bold'
                                                    : 'border border-gray-300 hover:bg-gray-50'
                                            }`}
                                        >
                                            {page}
                                        </button>
                                    )
                                );
                            })()}
                            <button
                                onClick={() => setCurrentPage(p => Math.min(Math.ceil(totalCount / pageSize), p + 1))}
                                disabled={currentPage >= Math.ceil(totalCount / pageSize)}
                                className="px-3 py-1.5 text-sm font-medium font-mono border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
                            >
                                Next
                            </button>
                        </div>
                    </div>
                )}
            </div>


            {/* Status & Change Modal */}
            {isStatusModalOpen && statusTarget && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-500/75 backdrop-blur-sm">
                    <div className="bg-white rounded-lg shadow-xl max-w-lg w-full p-8 border border-gray-100 border-t-8 border-t-vulncheck-blue">
                        <h3 className="text-xl font-bold mb-2 font-mono flex items-center gap-2">
                            <ShieldExclamationIcon className="h-6 w-6 text-vulncheck-blue" />
                            Change Status
                        </h3>
                        <p className="text-gray-500 text-sm mb-6 font-mono">
                            Vulnerability: <span className="text-vulncheck-blue font-bold">{statusTarget.cve_id}</span>
                        </p>

                        <div className="space-y-6">
                            <div>
                                <label className="block text-xs font-mono font-bold text-gray-500 uppercase tracking-widest mb-2">New Status</label>
                                <select
                                    value={newStatus}
                                    onChange={(e) => setNewStatus(e.target.value)}
                                    className="w-full bg-gray-50 border border-gray-200 rounded-md py-2 px-3 focus:outline-none focus:ring-2 focus:ring-vulncheck-blue font-mono"
                                >
                                    <option value="open">OPEN</option>
                                    <option value="patched">PATCHED (Triggers Rescan)</option>
                                    <option value="deferred">DEFERRED</option>
                                    <option value="accepted_risk">ACCEPTED RISK</option>
                                    <option value="false_positive">FALSE POSITIVE</option>
                                </select>
                            </div>

                            {newStatus === 'deferred' && (
                                <div className="animate-in slide-in-from-top-2 duration-200">
                                    <label className="block text-xs font-mono font-bold text-gray-500 uppercase tracking-widest mb-2">Deferred Until</label>
                                    <input
                                        type="date"
                                        value={deferDate}
                                        onChange={(e) => setDeferDate(e.target.value)}
                                        className="w-full bg-gray-50 border border-gray-200 rounded-md py-2 px-3 focus:outline-none focus:ring-2 focus:ring-vulncheck-blue font-mono"
                                    />
                                </div>
                            )}

                            <div>
                                <label className="block text-xs font-mono font-bold text-gray-500 uppercase tracking-widest mb-2">Comment / Reason</label>
                                <textarea
                                    rows={4}
                                    value={statusComment}
                                    onChange={(e) => setStatusComment(e.target.value)}
                                    placeholder="Add a reason for this status change..."
                                    className="w-full bg-gray-50 border border-gray-200 rounded-md py-2 px-3 focus:outline-none focus:ring-2 focus:ring-vulncheck-blue font-mono text-sm"
                                />
                            </div>

                            {actionStatus.message && (
                                <div className={`p-4 rounded-md text-sm font-mono ${actionStatus.type === 'error' ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green-700'}`}>
                                    {actionStatus.message}
                                </div>
                            )}

                            <div className="flex h-12 gap-3 mt-8">
                                <button
                                    onClick={() => setIsStatusModalOpen(false)}
                                    className="flex-1 bg-gray-100 text-gray-600 font-bold font-mono rounded-md hover:bg-gray-200 transition-colors uppercase text-sm tracking-wider"
                                >
                                    Cancel
                                </button>
                                <button
                                    onClick={handleConfirmStatusChange}
                                    className="flex-1 bg-vulncheck-blue text-white font-bold font-mono rounded-md hover:bg-blue-600 shadow-md shadow-blue-500/20 transition-all uppercase text-sm tracking-wider"
                                >
                                    Update Status
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Bulk Actions Bar */}
            {selectedIds.length > 0 && (
                <div className="fixed bottom-8 left-1/2 -translate-x-1/2 z-40 animate-in fade-in slide-in-from-bottom-4 duration-300">
                    <div className="bg-white rounded-2xl shadow-2xl border border-blue-100 p-3 flex items-center gap-6 px-6">
                        <div className="flex items-center gap-3 pr-6 border-r border-gray-100">
                            <div className="bg-vulncheck-blue text-white w-8 h-8 rounded-full flex items-center justify-center font-bold font-mono text-sm leading-none shadow-lg shadow-blue-500/30">
                                {selectedIds.length}
                            </div>
                            <span className="text-gray-600 font-mono text-sm font-bold uppercase tracking-wider">Selected</span>
                        </div>

                        <div className="flex items-center gap-4">
                            <div className="flex items-center gap-2">
                                <UserCircleIcon className="h-5 w-5 text-gray-400" />
                                <select
                                    className="text-sm font-mono bg-gray-50 border-gray-100 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-vulncheck-blue outline-none border transition-all"
                                    onChange={(e) => setBulkActionTarget({ type: 'user', id: parseInt(e.target.value) })}
                                    value={bulkActionTarget?.type === 'user' ? bulkActionTarget.id : ""}
                                >
                                    <option value="" disabled>Assign User...</option>
                                    <option value="-1">Unassign</option>
                                    {users.map(u => (
                                        <option key={u.id} value={u.id}>{u.username}</option>
                                    ))}
                                </select>
                            </div>

                            <div className="flex items-center gap-2">
                                <UserGroupIcon className="h-5 w-5 text-gray-400" />
                                <select
                                    className="text-sm font-mono bg-gray-50 border-gray-100 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-vulncheck-blue outline-none border transition-all"
                                    onChange={(e) => setBulkActionTarget({ type: 'group', id: parseInt(e.target.value) })}
                                    value={bulkActionTarget?.type === 'group' ? bulkActionTarget.id : ""}
                                >
                                    <option value="" disabled>Assign Group...</option>
                                    <option value="-1">Unassign</option>
                                    {groups.map(g => (
                                        <option key={g.id} value={g.id}>{g.name}</option>
                                    ))}
                                </select>
                            </div>

                            <div className="flex items-center gap-2">
                                <ShieldExclamationIcon className="h-5 w-5 text-gray-400" />
                                <select
                                    className="text-sm font-mono bg-gray-50 border-gray-100 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-vulncheck-blue outline-none border transition-all"
                                    onChange={(e) => setBulkActionTarget({ type: 'status', value: e.target.value })}
                                    value={bulkActionTarget?.type === 'status' ? bulkActionTarget.value : ""}
                                >
                                    <option value="" disabled>Set Status...</option>
                                    <option value="open">Open</option>
                                    <option value="patched">Patched</option>
                                    <option value="deferred">Deferred</option>
                                    <option value="accepted_risk">Accepted Risk</option>
                                    <option value="false_positive">False Positive</option>
                                </select>
                            </div>

                            <button
                                onClick={handleBulkUpdate}
                                disabled={!bulkActionTarget || isBulkUpdating || currentUser?.role === 'readonly'}
                                title={currentUser?.role === 'readonly' ? "Read-Only User" : ""}
                                className={`px-4 py-1.5 rounded-lg font-mono text-sm font-bold uppercase tracking-wider transition-all
                                    ${bulkActionTarget && !isBulkUpdating && currentUser?.role !== 'readonly'
                                        ? 'bg-vulncheck-blue text-white shadow-lg shadow-blue-500/30 hover:bg-blue-600'
                                        : 'bg-gray-100 text-gray-400 cursor-not-allowed'}`}
                            >
                                {isBulkUpdating ? 'Applying...' : 'Apply'}
                            </button>

                            <button
                                onClick={() => {
                                    setSelectedIds([]);
                                    setBulkActionTarget(null);
                                }}
                                className="text-gray-400 hover:text-gray-600 p-2 hover:bg-gray-100 rounded-full transition-colors"
                                title="Clear Selection"
                            >
                                <XMarkIcon className="h-5 w-5" />
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

export default function VulnerabilitiesPage() {
    return (
        <Suspense fallback={<div className="p-8">Loading...</div>}>
            <VulnerabilitiesContent />
        </Suspense>
    );
}
