'use client'

import { useState, useEffect, useCallback, useRef, useMemo } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Checkbox } from '@/components/ui/checkbox'
import { Skeleton } from '@/components/ui/skeleton'
import { Textarea } from '@/components/ui/textarea'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible'
import {
  Award,
  Play,
  Loader2,
  CheckCircle2,
  XCircle,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  ChevronDown,
  ChevronUp,
  Shield,
  Sparkles,
  Ban,
  Flag,
  RotateCcw,
  Search,
  ExternalLink,
  Plus,
  Pencil,
  Trash2,
  FileText,
  Brain,
  ListFilter,
  Settings2,
} from 'lucide-react'
import { motion, AnimatePresence } from 'motion/react'
import Link from 'next/link'
import type { Route } from 'next'
import { AwardShortlist } from './award-shortlist'
import { CountryDisplay } from '@/components/shared/country-display'

type FilteringDashboardProps = {
  competitionId: string
  roundId: string
}

type OutcomeFilter = 'ALL' | 'PASSED' | 'FILTERED_OUT' | 'FLAGGED'

type AIScreeningData = {
  meetsCriteria?: boolean
  confidence?: number
  reasoning?: string
  qualityScore?: number
  spamRisk?: boolean
}

export function FilteringDashboard({ competitionId, roundId }: FilteringDashboardProps) {
  const [outcomeFilter, setOutcomeFilter] = useState<OutcomeFilter>('ALL')
  const [page, setPage] = useState(1)
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [pollingJobId, setPollingJobId] = useState<string | null>(null)
  const [jobRunning, setJobRunning] = useState(false)
  const [overrideDialogOpen, setOverrideDialogOpen] = useState(false)
  const [overrideTarget, setOverrideTarget] = useState<{ id: string; name: string } | null>(null)
  const [overrideOutcome, setOverrideOutcome] = useState<'PASSED' | 'FILTERED_OUT' | 'FLAGGED'>('PASSED')
  const [overrideReason, setOverrideReason] = useState('')
  const [bulkOverrideDialogOpen, setBulkOverrideDialogOpen] = useState(false)
  const [bulkOutcome, setBulkOutcome] = useState<'PASSED' | 'FILTERED_OUT' | 'FLAGGED'>('PASSED')
  const [bulkReason, setBulkReason] = useState('')
  const [expandedId, setExpandedId] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState('')

  // AI criteria state
  const [criteriaText, setCriteriaText] = useState('')
  const [aiAction, setAiAction] = useState<'PASS' | 'REJECT' | 'FLAG' | 'AUTO_FILTER'>('FLAG')
  const [batchSize, setBatchSize] = useState(20)
  const [parallelBatches, setParallelBatches] = useState(3)
  const [autoFilterThreshold, setAutoFilterThreshold] = useState(4)
  const [advancedOpen, setAdvancedOpen] = useState(false)
  const [criteriaDirty, setCriteriaDirty] = useState(false)
  const criteriaLoaded = useRef(false)

  const utils = trpc.useUtils()

  // -- Queries --
  const { data: round } = trpc.round.getById.useQuery({ id: roundId })
  const roundConfig = (round?.configJson as Record<string, unknown>) ?? {}
  const aiParseFiles = !!roundConfig.aiParseFiles

  const updateRoundMutation = trpc.round.update.useMutation({
    onSuccess: () => utils.round.getById.invalidate({ id: roundId }),
    onError: (err) => toast.error(err.message),
  })

  // Dynamic refetch: all viewers get fast polling when a job is running (not just the one who started it)
  const { data: latestJob } = trpc.filtering.getLatestJob.useQuery(
    { roundId },
    { refetchInterval: jobRunning ? 3_000 : 15_000 },
  )

  const isRunning = !!pollingJobId || latestJob?.status === 'RUNNING'

  // Sync jobRunning so fast polling kicks in for ALL viewers, not just the job starter
  useEffect(() => {
    setJobRunning(isRunning)
  }, [isRunning])

  const { data: stats, isLoading: statsLoading } = trpc.filtering.getResultStats.useQuery(
    { roundId },
    { refetchInterval: isRunning ? 3_000 : 15_000 },
  )

  const { data: rules } = trpc.filtering.getRules.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  const { data: resultsPage, isLoading: resultsLoading } = trpc.filtering.getResults.useQuery(
    {
      roundId,
      outcome: outcomeFilter === 'ALL' ? undefined : outcomeFilter,
      page,
      perPage: 25,
    },
    { refetchInterval: isRunning ? 3_000 : 15_000 },
  )

  const { data: jobStatus } = trpc.filtering.getJobStatus.useQuery(
    { jobId: pollingJobId! },
    {
      enabled: !!pollingJobId,
      refetchInterval: 2000,
    },
  )

  // Load AI criteria from existing rule
  const aiRule = rules?.find((r: any) => r.ruleType === 'AI_SCREENING')
  useEffect(() => {
    if (aiRule && !criteriaLoaded.current) {
      const config = (aiRule.configJson || {}) as Record<string, unknown>
      setCriteriaText((config.criteriaText as string) || '')
      setAiAction((config.action as 'PASS' | 'REJECT' | 'FLAG' | 'AUTO_FILTER') || 'FLAG')
      setBatchSize((config.batchSize as number) || 20)
      setParallelBatches((config.parallelBatches as number) || 3)
      setAutoFilterThreshold((config.autoFilterThreshold as number) || 4)
      criteriaLoaded.current = true
    }
  }, [aiRule])

  // Stop polling when job completes
  useEffect(() => {
    if (jobStatus && (jobStatus.status === 'COMPLETED' || jobStatus.status === 'FAILED')) {
      setPollingJobId(null)
      utils.filtering.getLatestJob.invalidate({ roundId })
      utils.filtering.getResults.invalidate()
      utils.filtering.getResultStats.invalidate({ roundId })
      if (jobStatus.status === 'COMPLETED') {
        toast.success(`Filtering complete: ${jobStatus.passedCount} passed, ${jobStatus.filteredCount} filtered, ${jobStatus.flaggedCount} flagged`)
      } else {
        toast.error(`Filtering failed: ${jobStatus.errorMessage || 'Unknown error'}`)
      }
    }
  }, [jobStatus, roundId, utils])

  // Auto-detect running job on mount
  useEffect(() => {
    if (latestJob && latestJob.status === 'RUNNING') {
      setPollingJobId(latestJob.id)
    }
  }, [latestJob])

  // -- Mutations --
  const createRuleMutation = trpc.filtering.createRule.useMutation({
    onSuccess: () => utils.filtering.getRules.invalidate({ roundId }),
    onError: (err) => toast.error(err.message),
  })

  const updateRuleMutation = trpc.filtering.updateRule.useMutation({
    onSuccess: () => utils.filtering.getRules.invalidate({ roundId }),
    onError: (err) => toast.error(err.message),
  })

  const startJobMutation = trpc.filtering.startJob.useMutation({
    onSuccess: (data) => {
      setPollingJobId(data.jobId)
      toast.success('Filtering job started')
    },
    onError: (err) => toast.error(err.message),
  })

  const overrideMutation = trpc.filtering.overrideResult.useMutation({
    onSuccess: () => {
      utils.filtering.getResults.invalidate()
      utils.filtering.getResultStats.invalidate({ roundId })
      setOverrideDialogOpen(false)
      setOverrideTarget(null)
      setOverrideReason('')
      toast.success('Override applied')
    },
    onError: (err) => toast.error(err.message),
  })

  const bulkOverrideMutation = trpc.filtering.bulkOverride.useMutation({
    onSuccess: (data) => {
      utils.filtering.getResults.invalidate()
      utils.filtering.getResultStats.invalidate({ roundId })
      setBulkOverrideDialogOpen(false)
      setSelectedIds(new Set())
      setBulkReason('')
      toast.success(`${data.updated} results overridden`)
    },
    onError: (err) => toast.error(err.message),
  })

  const finalizeMutation = trpc.filtering.finalizeResults.useMutation({
    onSuccess: (data) => {
      utils.filtering.getResults.invalidate()
      utils.filtering.getResultStats.invalidate({ roundId })
      utils.roundEngine.getProjectStates.invalidate({ roundId })
      utils.project.list.invalidate()
      toast.success(
        `Finalized: ${data.passed} passed, ${data.filteredOut} filtered out` +
        (data.routedToAwards > 0 ? `, ${data.routedToAwards} routed to award tracks` : '') +
        (data.advancedToStageName ? `. Next round: ${data.advancedToStageName}` : '')
      )
      if (data.categoryWarnings.length > 0) {
        data.categoryWarnings.forEach((w) => toast.warning(w))
      }
    },
    onError: (err) => toast.error(err.message),
  })

  // -- Handlers --
  const handleSaveAndRun = async () => {
    if (!criteriaText.trim()) {
      toast.error('Please write screening criteria first')
      return
    }

    const configJson = {
      criteriaText,
      action: aiAction,
      batchSize,
      parallelBatches,
      ...(aiAction === 'AUTO_FILTER' && { autoFilterThreshold }),
    }

    try {
      if (aiRule) {
        await updateRuleMutation.mutateAsync({ id: (aiRule as any).id, configJson })
      } else {
        await createRuleMutation.mutateAsync({
          roundId,
          name: 'AI Screening',
          ruleType: 'AI_SCREENING',
          configJson,
          priority: 0,
        })
      }
      setCriteriaDirty(false)
      startJobMutation.mutate({ roundId })
    } catch {
      // Error handled by mutation onError
    }
  }

  const handleSaveCriteria = async () => {
    const configJson = {
      criteriaText,
      action: aiAction,
      batchSize,
      parallelBatches,
      ...(aiAction === 'AUTO_FILTER' && { autoFilterThreshold }),
    }

    if (aiRule) {
      await updateRuleMutation.mutateAsync({ id: (aiRule as any).id, configJson })
    } else {
      await createRuleMutation.mutateAsync({
        roundId,
        name: 'AI Screening',
        ruleType: 'AI_SCREENING',
        configJson,
        priority: 0,
      })
    }
    setCriteriaDirty(false)
    toast.success('Criteria saved')
  }

  const handleOverride = () => {
    if (!overrideTarget) return
    overrideMutation.mutate({
      id: overrideTarget.id,
      finalOutcome: overrideOutcome,
      reason: overrideReason,
    })
  }

  const handleBulkOverride = () => {
    bulkOverrideMutation.mutate({
      ids: Array.from(selectedIds),
      finalOutcome: bulkOutcome,
      reason: bulkReason,
    })
  }

  const handleFinalize = () => {
    finalizeMutation.mutate({ roundId })
  }

  const handleQuickOverride = (id: string, newOutcome: 'PASSED' | 'FILTERED_OUT' | 'FLAGGED') => {
    overrideMutation.mutate({
      id,
      finalOutcome: newOutcome,
      reason: 'Quick override by admin',
    })
  }

  const toggleSelect = (id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const toggleSelectAll = useCallback(() => {
    if (!resultsPage) return
    const allIds = resultsPage.results.map((r: any) => r.id)
    const allSelected = allIds.every((id: string) => selectedIds.has(id))
    if (allSelected) {
      setSelectedIds((prev) => {
        const next = new Set(prev)
        allIds.forEach((id: string) => next.delete(id))
        return next
      })
    } else {
      setSelectedIds((prev) => {
        const next = new Set(prev)
        allIds.forEach((id: string) => next.add(id))
        return next
      })
    }
  }, [resultsPage, selectedIds])

  const parseAIData = (json: unknown): AIScreeningData | null => {
    if (!json || typeof json !== 'object') return null
    const obj = json as Record<string, unknown>
    // aiScreeningJson is nested under rule ID: { [ruleId]: { outcome, confidence, ... } }
    // Unwrap first entry if top-level keys don't include expected AI fields
    if (!('outcome' in obj)) {
      const keys = Object.keys(obj)
      if (keys.length > 0) {
        const inner = obj[keys[0]]
        if (inner && typeof inner === 'object') return inner as AIScreeningData
      }
      return null
    }
    return obj as unknown as AIScreeningData
  }

  const activeJob = jobStatus || (latestJob?.status === 'RUNNING' ? latestJob : null)
  const hasResults = stats && stats.total > 0
  const nonAiRules = rules?.filter((r: any) => r.ruleType !== 'AI_SCREENING') ?? []
  const hasNonAiRules = nonAiRules.length > 0
  const isSaving = createRuleMutation.isPending || updateRuleMutation.isPending

  // Filter results by search query (client-side)
  const displayResults = resultsPage?.results.filter((r: any) => {
    if (!searchQuery.trim()) return true
    const q = searchQuery.toLowerCase()
    return (
      (r.project?.title || '').toLowerCase().includes(q) ||
      (r.project?.teamName || '').toLowerCase().includes(q)
    )
  }) ?? []

  // ── Staggered reveal: animate new results in one by one ─────────────
  const prevResultIdsRef = useRef<Set<string>>(new Set())
  const isFirstLoad = useRef(true)

  const resultStagger = useMemo(() => {
    const stagger: Record<string, number> = {}
    if (isFirstLoad.current && displayResults.length > 0) {
      isFirstLoad.current = false
      return stagger // No stagger on first load — show immediately
    }
    let newIdx = 0
    for (const r of displayResults) {
      if (!prevResultIdsRef.current.has((r as any).id)) {
        stagger[(r as any).id] = newIdx++
      }
    }
    return stagger
  }, [displayResults])

  // Update known IDs after render
  useEffect(() => {
    prevResultIdsRef.current = new Set(displayResults.map((r: any) => r.id))
  }, [displayResults])

  return (
    <div className="space-y-6">
      {/* Main Card: AI Screening Criteria + Controls */}
      <Card>
        <CardHeader>
          <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
            <div>
              <CardTitle className="text-base flex items-center gap-2">
                <Brain className="h-5 w-5 text-purple-600" />
                AI Screening
              </CardTitle>
              <CardDescription>
                Write all your screening criteria below — the AI evaluates each project against them
              </CardDescription>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              {criteriaDirty && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleSaveCriteria}
                  disabled={isSaving}
                >
                  {isSaving && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
                  Save
                </Button>
              )}
              <Button
                size="sm"
                onClick={handleSaveAndRun}
                disabled={isRunning || startJobMutation.isPending || !criteriaText.trim()}
              >
                {isRunning ? (
                  <><Loader2 className="h-4 w-4 mr-2 animate-spin" />Running...</>
                ) : (
                  <><Play className="h-4 w-4 mr-2" />Run Filtering</>
                )}
              </Button>
              {hasResults && !isRunning && (
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="outline" size="sm" disabled={finalizeMutation.isPending}>
                      <Shield className="h-4 w-4 mr-2" />
                      Finalize
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>Finalize Filtering Results?</AlertDialogTitle>
                      <AlertDialogDescription>
                        This will mark PASSED projects as eligible and FILTERED_OUT projects as rejected.
                        {stats && (
                          <span className="block mt-2 font-medium">
                            {stats.passed - (stats.routedToAwards || 0)} will pass to main pool, {stats.filteredOut} will be filtered out{stats.flagged > 0 ? `, ${stats.flagged} flagged for review` : ''}.
                            {(stats.routedToAwards || 0) > 0 && (
                              <span className="block text-amber-700">
                                {stats.routedToAwards} already routed to award tracks (excluded from main pool).
                              </span>
                            )}
                          </span>
                        )}
                        This action can be reversed but requires manual intervention.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>Cancel</AlertDialogCancel>
                      <AlertDialogAction onClick={handleFinalize}>
                        {finalizeMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                        Finalize
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <Textarea
            placeholder={`Write all your screening criteria here. The AI will evaluate each project against these requirements.\n\nExample:\n1. Project must have clear ocean conservation impact\n2. Documents should be in English or French\n3. For Business Concepts, academic rigor is acceptable\n4. For African projects, apply a lower quality threshold (score >= 5/10)\n5. Flag any submissions that appear to be AI-generated filler`}
            value={criteriaText}
            onChange={(e) => { setCriteriaText(e.target.value); setCriteriaDirty(true) }}
            rows={8}
            className="text-sm font-mono"
          />
          <p className="text-xs text-muted-foreground">
            Available data per project: category, country, region, founded year, ocean issue, tags,
            description, file details (type, pages, size, detected language), and team size.
          </p>

          {/* Advanced Settings */}
          <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
            <CollapsibleTrigger className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors">
              <Settings2 className="h-3.5 w-3.5" />
              Advanced Settings
              {advancedOpen ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
            </CollapsibleTrigger>
            <CollapsibleContent className="mt-3">
              <div className="space-y-3 rounded-lg border p-3 bg-muted/20">
                <div className="grid grid-cols-3 gap-3">
                  <div>
                    <Label className="text-xs text-muted-foreground mb-1 block">Default Action</Label>
                    <Select value={aiAction} onValueChange={(v) => { setAiAction(v as 'PASS' | 'REJECT' | 'FLAG' | 'AUTO_FILTER'); setCriteriaDirty(true) }}>
                      <SelectTrigger className="h-8 text-xs">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="AUTO_FILTER">Smart auto-filter</SelectItem>
                        <SelectItem value="FLAG">Flag for review</SelectItem>
                        <SelectItem value="REJECT">Auto-reject failures</SelectItem>
                        <SelectItem value="PASS">Auto-pass matches</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label className="text-xs text-muted-foreground mb-1 block">Batch Size</Label>
                    <Input
                      type="number"
                      min={1}
                      max={50}
                      className="h-8 text-xs"
                      value={batchSize}
                      onChange={(e) => { setBatchSize(parseInt(e.target.value) || 20); setCriteriaDirty(true) }}
                    />
                  </div>
                  <div>
                    <Label className="text-xs text-muted-foreground mb-1 block">Parallel Batches</Label>
                    <Input
                      type="number"
                      min={1}
                      max={10}
                      className="h-8 text-xs"
                      value={parallelBatches}
                      onChange={(e) => { setParallelBatches(parseInt(e.target.value) || 3); setCriteriaDirty(true) }}
                    />
                  </div>
                </div>

                {aiAction === 'AUTO_FILTER' && (
                  <div className="rounded-md border border-purple-200 bg-purple-50/50 p-3 space-y-2">
                    <div className="flex items-center justify-between">
                      <div>
                        <Label className="text-xs font-medium">Quality threshold</Label>
                        <p className="text-xs text-muted-foreground">
                          Projects scoring at or below this are auto-rejected as spam/junk
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        <Input
                          type="number"
                          min={1}
                          max={9}
                          className="h-8 w-16 text-xs text-center"
                          value={autoFilterThreshold}
                          onChange={(e) => {
                            const v = Math.min(9, Math.max(1, parseInt(e.target.value) || 4))
                            setAutoFilterThreshold(v)
                            setCriteriaDirty(true)
                          }}
                        />
                        <span className="text-xs text-muted-foreground">/10</span>
                      </div>
                    </div>
                    <div className="grid grid-cols-3 gap-1.5 text-xs">
                      <div className="rounded bg-red-100 border border-red-200 px-2 py-1.5 text-center">
                        <span className="font-medium text-red-800">Auto-reject</span>
                        <p className="text-red-600 mt-0.5">Score 1-{autoFilterThreshold} or spam</p>
                      </div>
                      <div className="rounded bg-amber-100 border border-amber-200 px-2 py-1.5 text-center">
                        <span className="font-medium text-amber-800">Flag for review</span>
                        <p className="text-amber-600 mt-0.5">Score {autoFilterThreshold + 1}+ but fails criteria</p>
                      </div>
                      <div className="rounded bg-green-100 border border-green-200 px-2 py-1.5 text-center">
                        <span className="font-medium text-green-800">Auto-pass</span>
                        <p className="text-green-600 mt-0.5">Meets criteria</p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </CollapsibleContent>
          </Collapsible>

          {/* AI Document Parsing — prominent toggle */}
          <div className="flex items-center justify-between rounded-lg border p-3">
            <div className="space-y-0.5">
              <Label htmlFor="ai-parse-files-filter" className="text-sm font-medium">
                AI document parsing
              </Label>
              <p className="text-xs text-muted-foreground">
                Allow AI to read uploaded file contents (PDF/text) for deeper analysis
              </p>
            </div>
            <Switch
              id="ai-parse-files-filter"
              checked={aiParseFiles}
              disabled={updateRoundMutation.isPending}
              onCheckedChange={(checked) => {
                updateRoundMutation.mutate({
                  id: roundId,
                  configJson: { ...roundConfig, aiParseFiles: checked },
                })
              }}
            />
          </div>

          {/* Job Progress */}
          {isRunning && activeJob && (
            <div className="space-y-2 pt-3 border-t">
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground flex items-center gap-2">
                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                  Processing batch {activeJob.currentBatch} of {activeJob.totalBatches || '?'}
                </span>
                <span className="font-mono text-sm">
                  {activeJob.processedCount}/{activeJob.totalProjects}
                </span>
              </div>
              <Progress
                value={activeJob.totalProjects > 0
                  ? (activeJob.processedCount / activeJob.totalProjects) * 100
                  : 0
                }
              />
              <p className="text-xs text-muted-foreground">
                Results appear in the table below as each batch completes
              </p>
            </div>
          )}

          {/* Last job summary */}
          {!isRunning && latestJob && latestJob.status === 'COMPLETED' && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground pt-3 border-t">
              <CheckCircle2 className="h-4 w-4 text-green-600" />
              Last run: {latestJob.passedCount} passed, {latestJob.filteredCount} filtered, {latestJob.flaggedCount} flagged
              <span className="text-xs">
                ({new Date(latestJob.completedAt!).toLocaleDateString()})
              </span>
            </div>
          )}

          {!isRunning && latestJob && latestJob.status === 'FAILED' && (
            <div className="flex items-center gap-2 text-sm text-red-600 pt-3 border-t">
              <XCircle className="h-4 w-4" />
              Last run failed: {latestJob.errorMessage || 'Unknown error'}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Additional Rules (Field-Based & Document Checks) */}
      <AdditionalRulesSection roundId={roundId} hasNonAiRules={hasNonAiRules} />

      {/* Stats Cards */}
      {statsLoading ? (
        <div className="grid gap-4 grid-cols-2 lg:grid-cols-5">
          {[1, 2, 3, 4, 5].map((i) => (
            <Skeleton key={i} className="h-24" />
          ))}
        </div>
      ) : stats && stats.total > 0 ? (
        <div className="grid gap-4 grid-cols-2 lg:grid-cols-6">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total</CardTitle>
              <Sparkles className="h-4 w-4 text-blue-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.total}</div>
              <p className="text-xs text-muted-foreground">Projects screened</p>
            </CardContent>
          </Card>
          <Card className="cursor-pointer hover:border-green-300 transition-colors" onClick={() => { setOutcomeFilter('PASSED'); setPage(1) }}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Passed</CardTitle>
              <CheckCircle2 className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-700">{stats.passed}</div>
              <p className="text-xs text-muted-foreground">
                {stats.total > 0 ? `${((stats.passed / stats.total) * 100).toFixed(0)}%` : '0%'}
                {stats.routedToAwards > 0 && (
                  <span className="block text-amber-600 mt-0.5">
                    {stats.passed - stats.routedToAwards} main + {stats.routedToAwards} award
                  </span>
                )}
              </p>
            </CardContent>
          </Card>
          <Card className="cursor-pointer hover:border-red-300 transition-colors" onClick={() => { setOutcomeFilter('FILTERED_OUT'); setPage(1) }}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Filtered Out</CardTitle>
              <Ban className="h-4 w-4 text-red-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-red-700">{stats.filteredOut}</div>
              <p className="text-xs text-muted-foreground">
                {stats.total > 0 ? `${((stats.filteredOut / stats.total) * 100).toFixed(0)}%` : '0%'}
              </p>
            </CardContent>
          </Card>
          <Card className="cursor-pointer hover:border-amber-300 transition-colors" onClick={() => { setOutcomeFilter('FLAGGED'); setPage(1) }}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Flagged</CardTitle>
              <Flag className="h-4 w-4 text-amber-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-amber-700">{stats.flagged}</div>
              <p className="text-xs text-muted-foreground">Need review</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Overridden</CardTitle>
              <RotateCcw className="h-4 w-4 text-purple-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-purple-700">{stats.overridden}</div>
              <p className="text-xs text-muted-foreground">Manual changes</p>
            </CardContent>
          </Card>
          {stats.routedToAwards > 0 && (
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Award Track</CardTitle>
                <Award className="h-4 w-4 text-amber-600" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-amber-700">{stats.routedToAwards}</div>
                <p className="text-xs text-muted-foreground">Routed to awards</p>
              </CardContent>
            </Card>
          )}
        </div>
      ) : null}

      {/* Results Table */}
      {(hasResults || resultsLoading || isRunning) && (
        <Card>
          <CardHeader>
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <div>
                <CardTitle className="text-base">Filtering Results</CardTitle>
                <CardDescription>
                  Review AI screening outcomes &mdash; click a row to see reasoning, use quick buttons to override
                  {isRunning && (
                    <span className="ml-2 text-purple-600 font-medium animate-pulse">
                      New results streaming in...
                    </span>
                  )}
                </CardDescription>
              </div>
              <div className="flex items-center gap-2">
                <div className="relative w-48">
                  <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
                  <Input
                    placeholder="Search..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-8 h-8 text-sm"
                  />
                </div>
                <Select
                  value={outcomeFilter}
                  onValueChange={(v) => {
                    setOutcomeFilter(v as OutcomeFilter)
                    setPage(1)
                    setSelectedIds(new Set())
                  }}
                >
                  <SelectTrigger className="w-[140px] h-8 text-sm">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ALL">All Outcomes</SelectItem>
                    <SelectItem value="PASSED">Passed</SelectItem>
                    <SelectItem value="FILTERED_OUT">Filtered Out</SelectItem>
                    <SelectItem value="FLAGGED">Flagged</SelectItem>
                  </SelectContent>
                </Select>
                {selectedIds.size > 0 && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setBulkOverrideDialogOpen(true)}
                  >
                    Override {selectedIds.size}
                  </Button>
                )}
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => {
                    utils.filtering.getResults.invalidate()
                    utils.filtering.getResultStats.invalidate({ roundId })
                  }}
                >
                  <RefreshCw className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            {resultsLoading ? (
              <div className="space-y-2">
                {[1, 2, 3, 4, 5].map((i) => (
                  <Skeleton key={i} className="h-14 w-full" />
                ))}
              </div>
            ) : displayResults.length > 0 ? (
              <div className="space-y-0">
                {/* Table Header */}
                <div className="grid grid-cols-[40px_1fr_120px_100px_70px_70px_120px] gap-2 px-3 py-2 text-xs font-medium text-muted-foreground border-b">
                  <div>
                    <Checkbox
                      checked={
                        displayResults.length > 0 &&
                        displayResults.every((r: any) => selectedIds.has(r.id))
                      }
                      onCheckedChange={toggleSelectAll}
                    />
                  </div>
                  <div>Project</div>
                  <div>Category</div>
                  <div>Outcome</div>
                  <div>Conf.</div>
                  <div>Quality</div>
                  <div>Quick Actions</div>
                </div>

                {/* Rows */}
                <AnimatePresence initial={false}>
                {displayResults.map((result: any) => {
                  const ai = parseAIData(result.aiScreeningJson)
                  const effectiveOutcome = result.finalOutcome || result.outcome
                  const isExpanded = expandedId === result.id
                  const staggerIdx = resultStagger[result.id]
                  const isNew = staggerIdx !== undefined

                  return (
                    <motion.div
                      key={result.id}
                      initial={isNew ? { opacity: 0, y: 16, scale: 0.98 } : false}
                      animate={{ opacity: 1, y: 0, scale: 1 }}
                      transition={{
                        duration: 0.35,
                        delay: isNew ? staggerIdx * 0.12 : 0,
                        ease: [0.25, 0.46, 0.45, 0.94],
                      }}
                      className="border-b last:border-b-0"
                    >
                      {/* Main Row */}
                      <div
                        className="grid grid-cols-[40px_1fr_120px_100px_70px_70px_120px] gap-2 px-3 py-2.5 items-center hover:bg-muted/50 text-sm cursor-pointer"
                        onClick={() => setExpandedId(isExpanded ? null : result.id)}
                      >
                        <div onClick={(e) => e.stopPropagation()}>
                          <Checkbox
                            checked={selectedIds.has(result.id)}
                            onCheckedChange={() => toggleSelect(result.id)}
                          />
                        </div>
                        <div className="min-w-0 flex items-center gap-2">
                          {isExpanded ? (
                            <ChevronUp className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
                          ) : (
                            <ChevronDown className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
                          )}
                          <div className="min-w-0">
                            <div className="flex items-center gap-1.5">
                              <Link
                                href={`/admin/projects/${result.projectId}` as Route}
                                className="font-medium truncate hover:underline text-foreground"
                                onClick={(e) => e.stopPropagation()}
                              >
                                {result.project?.title || 'Unknown'}
                              </Link>
                              {result.project?.awardEligibilities?.length > 0 && (
                                <Badge variant="outline" className="text-[10px] px-1.5 py-0 bg-amber-50 text-amber-700 border-amber-200 shrink-0">
                                  <Award className="h-2.5 w-2.5 mr-0.5" />
                                  {result.project.awardEligibilities[0].award.name}
                                </Badge>
                              )}
                            </div>
                            <p className="text-xs text-muted-foreground truncate">
                              {result.project?.teamName}
                              {result.project?.country && <> · <CountryDisplay country={result.project.country} /></>}
                            </p>
                          </div>
                        </div>
                        <div>
                          <Badge variant="outline" className="text-xs">
                            {formatCategory(result.project?.competitionCategory) || '\u2014'}
                          </Badge>
                        </div>
                        <div>
                          <OutcomeBadge outcome={effectiveOutcome} overridden={!!result.finalOutcome && result.finalOutcome !== result.outcome} />
                        </div>
                        <div>
                          {ai?.confidence != null ? (
                            <ConfidenceIndicator value={ai.confidence} />
                          ) : (
                            <span className="text-xs text-muted-foreground">&mdash;</span>
                          )}
                        </div>
                        <div>
                          {ai?.qualityScore != null ? (
                            <span className={`text-sm font-mono font-medium ${
                              ai.qualityScore >= 7 ? 'text-green-700' :
                              ai.qualityScore >= 4 ? 'text-amber-700' :
                              'text-red-700'
                            }`}>
                              {ai.qualityScore}/10
                            </span>
                          ) : (
                            <span className="text-xs text-muted-foreground">&mdash;</span>
                          )}
                        </div>
                        <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
                          {effectiveOutcome !== 'PASSED' && (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 px-2 text-green-700 hover:text-green-800 hover:bg-green-50"
                              disabled={overrideMutation.isPending}
                              onClick={() => handleQuickOverride(result.id, 'PASSED')}
                              title="Mark as Passed"
                            >
                              <CheckCircle2 className="h-3.5 w-3.5" />
                            </Button>
                          )}
                          {effectiveOutcome !== 'FLAGGED' && (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 px-2 text-amber-700 hover:text-amber-800 hover:bg-amber-50"
                              disabled={overrideMutation.isPending}
                              onClick={() => handleQuickOverride(result.id, 'FLAGGED')}
                              title="Mark as Flagged"
                            >
                              <Flag className="h-3.5 w-3.5" />
                            </Button>
                          )}
                          {effectiveOutcome !== 'FILTERED_OUT' && (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 px-2 text-red-700 hover:text-red-800 hover:bg-red-50"
                              disabled={overrideMutation.isPending}
                              onClick={() => handleQuickOverride(result.id, 'FILTERED_OUT')}
                              title="Mark as Filtered Out"
                            >
                              <Ban className="h-3.5 w-3.5" />
                            </Button>
                          )}
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-7 px-2"
                            onClick={() => {
                              setOverrideTarget({ id: result.id, name: result.project?.title || 'Unknown' })
                              setOverrideOutcome(effectiveOutcome === 'PASSED' ? 'FILTERED_OUT' : 'PASSED')
                              setOverrideDialogOpen(true)
                            }}
                            title="Override with reason"
                          >
                            <RotateCcw className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                      </div>

                      {/* Expanded Detail Row */}
                      {isExpanded && (
                        <div className="px-12 pb-4 bg-muted/20 border-t border-dashed">
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-3">
                            {/* Left: AI Reasoning */}
                            <div className="space-y-3">
                              {ai?.reasoning ? (
                                <div>
                                  <p className="text-xs font-medium text-muted-foreground mb-1.5">AI Reasoning</p>
                                  <div className="rounded-lg bg-background border p-3 text-sm whitespace-pre-wrap leading-relaxed">
                                    {ai.reasoning}
                                  </div>
                                </div>
                              ) : (
                                <p className="text-sm text-muted-foreground italic">No AI reasoning available</p>
                              )}

                              {result.overrideReason && (
                                <div>
                                  <p className="text-xs font-medium text-muted-foreground mb-1.5">Override Reason</p>
                                  <div className="rounded-lg bg-amber-50 border border-amber-200 p-3 text-sm">
                                    {result.overrideReason}
                                    {result.overriddenByUser && (
                                      <p className="text-xs text-muted-foreground mt-1">
                                        By {result.overriddenByUser.name || result.overriddenByUser.email}
                                        {result.overriddenAt && ` on ${new Date(result.overriddenAt).toLocaleDateString()}`}
                                      </p>
                                    )}
                                  </div>
                                </div>
                              )}
                            </div>

                            {/* Right: Metrics + Rule Results */}
                            <div className="space-y-3">
                              {ai && (
                                <div className="grid grid-cols-3 gap-2">
                                  <div className="rounded-lg border p-2.5 text-center">
                                    <p className="text-xs text-muted-foreground mb-0.5">Confidence</p>
                                    <p className="text-base font-bold">
                                      {ai.confidence != null ? `${(ai.confidence * 100).toFixed(0)}%` : '\u2014'}
                                    </p>
                                  </div>
                                  <div className="rounded-lg border p-2.5 text-center">
                                    <p className="text-xs text-muted-foreground mb-0.5">Quality</p>
                                    <p className="text-base font-bold">
                                      {ai.qualityScore != null ? `${ai.qualityScore}/10` : '\u2014'}
                                    </p>
                                  </div>
                                  <div className="rounded-lg border p-2.5 text-center">
                                    <p className="text-xs text-muted-foreground mb-0.5">Spam Risk</p>
                                    <p className={`text-base font-bold ${ai.spamRisk ? 'text-red-600' : 'text-green-600'}`}>
                                      {ai.spamRisk ? 'Yes' : 'No'}
                                    </p>
                                  </div>
                                </div>
                              )}

                              {result.finalOutcome && result.finalOutcome !== result.outcome && (
                                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                                  <span>Original AI decision:</span>
                                  <OutcomeBadge outcome={result.outcome} overridden={false} />
                                </div>
                              )}

                              {/* Rule-by-rule results */}
                              {result.ruleResultsJson && Array.isArray(result.ruleResultsJson) && result.ruleResultsJson.length > 0 && (
                                <div>
                                  <p className="text-xs font-medium text-muted-foreground mb-1.5">Rule Results</p>
                                  <div className="space-y-1">
                                    {(result.ruleResultsJson as any[]).map((rule: any, i: number) => (
                                      <div key={i} className="flex items-center justify-between text-sm px-2 py-1 rounded border bg-background">
                                        <span className="truncate">{rule.ruleName || `Rule ${i + 1}`}</span>
                                        <Badge variant={rule.passed ? 'default' : 'destructive'} className="text-xs shrink-0 ml-2">
                                          {rule.passed ? 'Pass' : 'Fail'}
                                        </Badge>
                                      </div>
                                    ))}
                                  </div>
                                </div>
                              )}

                              <div className="flex justify-end pt-1">
                                <Link
                                  href={`/admin/projects/${result.projectId}` as Route}
                                  className="text-xs text-muted-foreground hover:text-foreground inline-flex items-center gap-1"
                                >
                                  <ExternalLink className="h-3 w-3" />
                                  View Full Project
                                </Link>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                    </motion.div>
                  )
                })}
                </AnimatePresence>

                {/* Pagination */}
                {resultsPage && resultsPage.totalPages > 1 && (
                  <div className="flex items-center justify-between pt-4">
                    <p className="text-sm text-muted-foreground">
                      Page {resultsPage.page} of {resultsPage.totalPages} ({resultsPage.total} total)
                    </p>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={page <= 1}
                        onClick={() => setPage((p) => p - 1)}
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={page >= resultsPage.totalPages}
                        onClick={() => setPage((p) => p + 1)}
                      >
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center py-12 text-center">
                <Sparkles className="h-8 w-8 text-muted-foreground mb-3" />
                <p className="text-sm font-medium">
                  {searchQuery.trim() ? 'No results match your search' : isRunning ? 'Results will appear here as batches complete' : 'No results yet'}
                </p>
                <p className="text-xs text-muted-foreground mt-1">
                  {searchQuery.trim() ? 'Try a different search term' : isRunning ? 'The AI is processing projects...' : 'Run filtering to screen projects'}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Special Award Tracks */}
      {hasResults && <AwardTracksSection competitionId={competitionId} roundId={roundId} />}

      {/* Single Override Dialog (with reason) */}
      <Dialog open={overrideDialogOpen} onOpenChange={setOverrideDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Override Decision</DialogTitle>
            <DialogDescription>
              Change the outcome for: {overrideTarget?.name}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium mb-1.5 block">New Outcome</label>
              <Select value={overrideOutcome} onValueChange={(v) => setOverrideOutcome(v as any)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="PASSED">Passed</SelectItem>
                  <SelectItem value="FILTERED_OUT">Filtered Out</SelectItem>
                  <SelectItem value="FLAGGED">Flagged</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-sm font-medium mb-1.5 block">Reason</label>
              <Textarea
                placeholder="Explain why you're overriding this decision..."
                value={overrideReason}
                onChange={(e) => setOverrideReason(e.target.value)}
                rows={3}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOverrideDialogOpen(false)}>Cancel</Button>
            <Button
              onClick={handleOverride}
              disabled={!overrideReason.trim() || overrideMutation.isPending}
            >
              {overrideMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              Apply Override
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Bulk Override Dialog */}
      <Dialog open={bulkOverrideDialogOpen} onOpenChange={setBulkOverrideDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Bulk Override</DialogTitle>
            <DialogDescription>
              Override {selectedIds.size} selected results
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium mb-1.5 block">Set All To</label>
              <Select value={bulkOutcome} onValueChange={(v) => setBulkOutcome(v as any)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="PASSED">Passed</SelectItem>
                  <SelectItem value="FILTERED_OUT">Filtered Out</SelectItem>
                  <SelectItem value="FLAGGED">Flagged</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-sm font-medium mb-1.5 block">Reason</label>
              <Textarea
                placeholder="Explain why you're overriding these decisions..."
                value={bulkReason}
                onChange={(e) => setBulkReason(e.target.value)}
                rows={3}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setBulkOverrideDialogOpen(false)}>Cancel</Button>
            <Button
              onClick={handleBulkOverride}
              disabled={!bulkReason.trim() || bulkOverrideMutation.isPending}
            >
              {bulkOverrideMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              Override {selectedIds.size} Results
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

// -- Helpers --

const categoryLabels: Record<string, string> = {
  BUSINESS_CONCEPT: 'Concept',
  STARTUP: 'Startup',
}

function formatCategory(cat: string | null | undefined): string {
  if (!cat) return ''
  return categoryLabels[cat] ?? cat.charAt(0) + cat.slice(1).toLowerCase().replace(/_/g, ' ')
}

// -- Sub-components --

function OutcomeBadge({ outcome, overridden }: { outcome: string; overridden: boolean }) {
  const styles: Record<string, string> = {
    PASSED: 'bg-green-100 text-green-800 border-green-200',
    FILTERED_OUT: 'bg-red-100 text-red-800 border-red-200',
    FLAGGED: 'bg-amber-100 text-amber-800 border-amber-200',
  }
  return (
    <Badge variant="outline" className={`text-xs ${styles[outcome] || ''} ${overridden ? 'ring-1 ring-purple-400' : ''}`}>
      {outcome === 'FILTERED_OUT' ? 'Filtered' : outcome === 'PASSED' ? 'Passed' : 'Flagged'}
      {overridden && ' *'}
    </Badge>
  )
}

function ConfidenceIndicator({ value }: { value: number }) {
  const pct = Math.round(value * 100)
  const color = pct >= 80 ? 'text-green-700' : pct >= 50 ? 'text-amber-700' : 'text-red-700'
  return (
    <span className={`text-sm font-mono font-medium ${color}`}>
      {pct}%
    </span>
  )
}

// ─── Additional Rules Section (Field-Based & Document Checks only) ──────────

type RuleType = 'FIELD_BASED' | 'DOCUMENT_CHECK'

const RULE_TYPE_META: Record<RuleType, { label: string; icon: typeof ListFilter; color: string; description: string }> = {
  FIELD_BASED: { label: 'Field-Based', icon: ListFilter, color: 'bg-blue-100 text-blue-800 border-blue-200', description: 'Evaluate project fields (category, founding date, location, etc.)' },
  DOCUMENT_CHECK: { label: 'Document Check', icon: FileText, color: 'bg-teal-100 text-teal-800 border-teal-200', description: 'Validate file uploads (min count, formats, page limits)' },
}

const FIELD_OPTIONS = [
  { value: 'competitionCategory', label: 'Competition Category', operators: ['equals', 'not_equals'] },
  { value: 'foundedAt', label: 'Founded Date', operators: ['older_than_years', 'newer_than_years'] },
  { value: 'country', label: 'Country', operators: ['equals', 'not_equals', 'in', 'not_in'] },
  { value: 'geographicZone', label: 'Geographic Zone', operators: ['equals', 'not_equals', 'contains'] },
  { value: 'tags', label: 'Tags', operators: ['contains', 'in'] },
  { value: 'oceanIssue', label: 'Ocean Issue', operators: ['equals', 'not_equals', 'in'] },
]

const FILE_TYPES = [
  { value: 'EXEC_SUMMARY', label: 'Executive Summary' },
  { value: 'PRESENTATION', label: 'Presentation' },
  { value: 'BUSINESS_PLAN', label: 'Business Plan' },
  { value: 'VIDEO', label: 'Video' },
  { value: 'VIDEO_PITCH', label: 'Video Pitch' },
  { value: 'SUPPORTING_DOC', label: 'Supporting Doc' },
  { value: 'OTHER', label: 'Other' },
]

type FieldCondition = {
  field: string
  operator: string
  value: string | number | string[]
}

type RuleFormData = {
  name: string
  ruleType: RuleType
  priority: number
  // FIELD_BASED
  conditions: FieldCondition[]
  logic: 'AND' | 'OR'
  fieldAction: 'PASS' | 'REJECT' | 'FLAG'
  // DOCUMENT_CHECK
  requiredFileTypes: string[]
  minFileCount: number | ''
  maxPages: number | ''
  maxPagesByFileType: Record<string, number>
  docAction: 'PASS' | 'REJECT' | 'FLAG'
}

const DEFAULT_FORM: RuleFormData = {
  name: '',
  ruleType: 'FIELD_BASED',
  priority: 0,
  conditions: [{ field: 'competitionCategory', operator: 'equals', value: '' }],
  logic: 'AND',
  fieldAction: 'REJECT',
  requiredFileTypes: [],
  minFileCount: '',
  maxPages: '',
  maxPagesByFileType: {},
  docAction: 'REJECT',
}

function buildConfigJson(form: RuleFormData): Record<string, unknown> {
  switch (form.ruleType) {
    case 'FIELD_BASED':
      return {
        conditions: form.conditions.map((c) => ({
          field: c.field,
          operator: c.operator,
          value: c.value,
        })),
        logic: form.logic,
        action: form.fieldAction,
      }
    case 'DOCUMENT_CHECK': {
      const config: Record<string, unknown> = {
        action: form.docAction,
      }
      if (form.requiredFileTypes.length > 0) config.requiredFileTypes = form.requiredFileTypes
      if (form.minFileCount !== '' && form.minFileCount > 0) config.minFileCount = form.minFileCount
      if (form.maxPages !== '' && form.maxPages > 0) config.maxPages = form.maxPages
      if (Object.keys(form.maxPagesByFileType).length > 0) config.maxPagesByFileType = form.maxPagesByFileType
      return config
    }
  }
}

function parseConfigToForm(rule: { name: string; ruleType: string; configJson: unknown; priority: number }): RuleFormData {
  const config = (rule.configJson || {}) as Record<string, unknown>
  const base = { ...DEFAULT_FORM, name: rule.name, ruleType: rule.ruleType as RuleType, priority: rule.priority }

  switch (rule.ruleType) {
    case 'FIELD_BASED':
      return {
        ...base,
        conditions: (config.conditions as FieldCondition[]) || [{ field: 'competitionCategory', operator: 'equals', value: '' }],
        logic: (config.logic as 'AND' | 'OR') || 'AND',
        fieldAction: (config.action as 'PASS' | 'REJECT' | 'FLAG') || 'REJECT',
      }
    case 'DOCUMENT_CHECK':
      return {
        ...base,
        requiredFileTypes: (config.requiredFileTypes as string[]) || [],
        minFileCount: (config.minFileCount as number) || '',
        maxPages: (config.maxPages as number) || '',
        maxPagesByFileType: (config.maxPagesByFileType as Record<string, number>) || {},
        docAction: (config.action as 'PASS' | 'REJECT' | 'FLAG') || 'REJECT',
      }
    default:
      return base
  }
}

function AdditionalRulesSection({ roundId, hasNonAiRules }: { roundId: string; hasNonAiRules: boolean }) {
  const [isOpen, setIsOpen] = useState(false)
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingRule, setEditingRule] = useState<string | null>(null)
  const [form, setForm] = useState<RuleFormData>({ ...DEFAULT_FORM })
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null)

  const utils = trpc.useUtils()

  const { data: allRules, isLoading } = trpc.filtering.getRules.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  // Only show non-AI rules
  const rules = allRules?.filter((r: any) => r.ruleType !== 'AI_SCREENING') ?? []

  const createMutation = trpc.filtering.createRule.useMutation({
    onSuccess: () => {
      utils.filtering.getRules.invalidate({ roundId })
      setDialogOpen(false)
      setForm({ ...DEFAULT_FORM })
      toast.success('Rule created')
    },
    onError: (err) => toast.error(err.message),
  })

  const updateMutation = trpc.filtering.updateRule.useMutation({
    onSuccess: () => {
      utils.filtering.getRules.invalidate({ roundId })
      setDialogOpen(false)
      setEditingRule(null)
      setForm({ ...DEFAULT_FORM })
      toast.success('Rule updated')
    },
    onError: (err) => toast.error(err.message),
  })

  const deleteMutation = trpc.filtering.deleteRule.useMutation({
    onSuccess: () => {
      utils.filtering.getRules.invalidate({ roundId })
      setDeleteConfirmId(null)
      toast.success('Rule deleted')
    },
    onError: (err) => toast.error(err.message),
  })

  const toggleActiveMutation = trpc.filtering.updateRule.useMutation({
    onSuccess: () => {
      utils.filtering.getRules.invalidate({ roundId })
    },
    onError: (err) => toast.error(err.message),
  })

  const handleSave = () => {
    const configJson = buildConfigJson(form)
    if (editingRule) {
      updateMutation.mutate({ id: editingRule, name: form.name, ruleType: form.ruleType, configJson, priority: form.priority })
    } else {
      createMutation.mutate({ roundId, name: form.name, ruleType: form.ruleType, configJson, priority: form.priority })
    }
  }

  const openEdit = (rule: any) => {
    setEditingRule(rule.id)
    setForm(parseConfigToForm(rule))
    setDialogOpen(true)
  }

  const openCreate = () => {
    setEditingRule(null)
    setForm({ ...DEFAULT_FORM, priority: rules.length })
    setDialogOpen(true)
  }

  return (
    <>
      <Collapsible open={isOpen} onOpenChange={setIsOpen}>
        <Card>
          <CollapsibleTrigger asChild>
            <CardHeader className="cursor-pointer hover:bg-muted/30 transition-colors">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <ListFilter className="h-5 w-5 text-[#053d57]" />
                  <div>
                    <CardTitle className="text-base">Additional Rules</CardTitle>
                    <CardDescription>
                      {rules.length} field-based / document check rule{rules.length !== 1 ? 's' : ''} — applied alongside AI screening
                    </CardDescription>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={(e) => { e.stopPropagation(); openCreate() }}
                  >
                    <Plus className="h-3.5 w-3.5 mr-1" />
                    Add Rule
                  </Button>
                  {isOpen ? <ChevronUp className="h-4 w-4 text-muted-foreground" /> : <ChevronDown className="h-4 w-4 text-muted-foreground" />}
                </div>
              </div>
            </CardHeader>
          </CollapsibleTrigger>

          <CollapsibleContent>
            <CardContent className="pt-0">
              {isLoading ? (
                <div className="space-y-2">
                  {[1, 2, 3].map((i) => <Skeleton key={i} className="h-12 w-full" />)}
                </div>
              ) : rules.length > 0 ? (
                <div className="space-y-2">
                  {rules.map((rule: any, idx: number) => {
                    const typeMeta = RULE_TYPE_META[rule.ruleType as RuleType] || RULE_TYPE_META.FIELD_BASED
                    const Icon = typeMeta.icon
                    const config = (rule.configJson || {}) as Record<string, unknown>

                    return (
                      <div
                        key={rule.id}
                        className="flex items-center gap-3 rounded-lg border p-3 bg-background hover:bg-muted/30 transition-colors group"
                      >
                        <div className="flex items-center gap-1 text-muted-foreground">
                          <span className="text-xs font-mono w-5 text-center">{idx + 1}</span>
                        </div>

                        <Badge variant="outline" className={`text-xs shrink-0 ${typeMeta.color}`}>
                          <Icon className="h-3 w-3 mr-1" />
                          {typeMeta.label}
                        </Badge>

                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium truncate">{rule.name}</p>
                          <p className="text-xs text-muted-foreground truncate">
                            {rule.ruleType === 'FIELD_BASED' && (
                              <>
                                {((config.conditions as any[]) || []).length} condition{((config.conditions as any[]) || []).length !== 1 ? 's' : ''} ({config.logic as string || 'AND'}) &rarr; {config.action as string}
                              </>
                            )}
                            {rule.ruleType === 'DOCUMENT_CHECK' && (
                              <>
                                {config.minFileCount ? `Min ${config.minFileCount} files` : ''}
                                {config.requiredFileTypes ? ` \u00b7 Types: ${(config.requiredFileTypes as string[]).join(', ')}` : ''}
                                {config.maxPages ? ` \u00b7 Max ${config.maxPages} pages` : ''}
                                {' \u2192 '}{config.action as string}
                              </>
                            )}
                          </p>
                        </div>

                        <div className="flex items-center gap-2 shrink-0">
                          <Switch
                            checked={rule.isActive}
                            onCheckedChange={(checked) => {
                              toggleActiveMutation.mutate({ id: rule.id, isActive: checked })
                            }}
                          />
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8"
                            onClick={() => openEdit(rule)}
                          >
                            <Pencil className="h-3.5 w-3.5" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-red-600 hover:text-red-700 hover:bg-red-50"
                            onClick={() => setDeleteConfirmId(rule.id)}
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                      </div>
                    )
                  })}
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-6 text-center">
                  <ListFilter className="h-6 w-6 text-muted-foreground mb-2" />
                  <p className="text-sm text-muted-foreground">
                    No additional rules — AI screening criteria handle everything
                  </p>
                  <Button variant="outline" size="sm" className="mt-2" onClick={openCreate}>
                    <Plus className="h-3.5 w-3.5 mr-1" />
                    Add Rule
                  </Button>
                </div>
              )}
            </CardContent>
          </CollapsibleContent>
        </Card>
      </Collapsible>

      {/* Create/Edit Rule Dialog */}
      <Dialog open={dialogOpen} onOpenChange={(open) => {
        setDialogOpen(open)
        if (!open) { setEditingRule(null); setForm({ ...DEFAULT_FORM }) }
      }}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingRule ? 'Edit Rule' : 'Create Rule'}</DialogTitle>
            <DialogDescription>
              {editingRule ? 'Update this filtering rule' : 'Add a field-based or document check rule'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-5">
            {/* Rule Name + Priority */}
            <div className="grid grid-cols-[1fr_100px] gap-3">
              <div>
                <Label className="text-sm font-medium mb-1.5 block">Rule Name</Label>
                <Input
                  placeholder="e.g. Startup Age Check"
                  value={form.name}
                  onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                />
              </div>
              <div>
                <Label className="text-sm font-medium mb-1.5 block">Priority</Label>
                <Input
                  type="number"
                  min={0}
                  value={form.priority}
                  onChange={(e) => setForm((f) => ({ ...f, priority: parseInt(e.target.value) || 0 }))}
                />
              </div>
            </div>

            {/* Rule Type Selector (only Field-Based and Document Check) */}
            <div>
              <Label className="text-sm font-medium mb-2 block">Rule Type</Label>
              <div className="grid grid-cols-2 gap-2">
                {(Object.entries(RULE_TYPE_META) as [RuleType, typeof RULE_TYPE_META[RuleType]][]).map(([type, m]) => {
                  const Icon = m.icon
                  const selected = form.ruleType === type
                  return (
                    <button
                      key={type}
                      type="button"
                      className={`flex flex-col items-start gap-1.5 rounded-lg border p-3 text-left transition-all ${
                        selected ? 'border-[#053d57] bg-[#053d57]/5 ring-1 ring-[#053d57]/20' : 'hover:border-muted-foreground/30'
                      }`}
                      onClick={() => setForm((f) => ({ ...f, ruleType: type }))}
                    >
                      <div className="flex items-center gap-1.5">
                        <Icon className={`h-4 w-4 ${selected ? 'text-[#053d57]' : 'text-muted-foreground'}`} />
                        <span className={`text-sm font-medium ${selected ? 'text-[#053d57]' : ''}`}>{m.label}</span>
                      </div>
                      <p className="text-xs text-muted-foreground leading-snug">{m.description}</p>
                    </button>
                  )
                })}
              </div>
            </div>

            {/* Type-Specific Config */}
            {form.ruleType === 'FIELD_BASED' && (
              <div className="space-y-3 rounded-lg border p-4 bg-muted/20">
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-medium">Conditions</Label>
                  <Select value={form.logic} onValueChange={(v) => setForm((f) => ({ ...f, logic: v as 'AND' | 'OR' }))}>
                    <SelectTrigger className="w-20 h-7 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="AND">AND</SelectItem>
                      <SelectItem value="OR">OR</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {form.conditions.map((cond, i) => {
                  const fieldMeta = FIELD_OPTIONS.find((f) => f.value === cond.field)
                  return (
                    <div key={i} className="grid grid-cols-[1fr_1fr_1fr_36px] gap-2 items-end">
                      <div>
                        {i === 0 && <Label className="text-xs text-muted-foreground mb-1 block">Field</Label>}
                        <Select
                          value={cond.field}
                          onValueChange={(v) => {
                            const newConds = [...form.conditions]
                            const newFieldMeta = FIELD_OPTIONS.find((f) => f.value === v)
                            newConds[i] = { field: v, operator: newFieldMeta?.operators[0] || 'equals', value: '' }
                            setForm((f) => ({ ...f, conditions: newConds }))
                          }}
                        >
                          <SelectTrigger className="h-8 text-xs">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {FIELD_OPTIONS.map((fo) => (
                              <SelectItem key={fo.value} value={fo.value}>{fo.label}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        {i === 0 && <Label className="text-xs text-muted-foreground mb-1 block">Operator</Label>}
                        <Select
                          value={cond.operator}
                          onValueChange={(v) => {
                            const newConds = [...form.conditions]
                            newConds[i] = { ...newConds[i], operator: v }
                            setForm((f) => ({ ...f, conditions: newConds }))
                          }}
                        >
                          <SelectTrigger className="h-8 text-xs">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {(fieldMeta?.operators || ['equals']).map((op) => (
                              <SelectItem key={op} value={op}>{op.replace(/_/g, ' ')}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        {i === 0 && <Label className="text-xs text-muted-foreground mb-1 block">Value</Label>}
                        <Input
                          className="h-8 text-xs"
                          placeholder="Value..."
                          value={typeof cond.value === 'object' ? (cond.value as string[]).join(', ') : String(cond.value)}
                          onChange={(e) => {
                            const newConds = [...form.conditions]
                            const val = ['in', 'not_in'].includes(cond.operator)
                              ? e.target.value.split(',').map((s) => s.trim())
                              : ['older_than_years', 'newer_than_years'].includes(cond.operator)
                                ? parseInt(e.target.value) || 0
                                : e.target.value
                            newConds[i] = { ...newConds[i], value: val }
                            setForm((f) => ({ ...f, conditions: newConds }))
                          }}
                        />
                      </div>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 text-red-500"
                        disabled={form.conditions.length <= 1}
                        onClick={() => {
                          const newConds = form.conditions.filter((_, j) => j !== i)
                          setForm((f) => ({ ...f, conditions: newConds }))
                        }}
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  )
                })}

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setForm((f) => ({
                    ...f,
                    conditions: [...f.conditions, { field: 'competitionCategory', operator: 'equals', value: '' }],
                  }))}
                >
                  <Plus className="h-3 w-3 mr-1" />
                  Add Condition
                </Button>

                <div>
                  <Label className="text-xs text-muted-foreground mb-1 block">Action when conditions match</Label>
                  <Select value={form.fieldAction} onValueChange={(v) => setForm((f) => ({ ...f, fieldAction: v as any }))}>
                    <SelectTrigger className="w-40 h-8 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="PASS">Pass (keep project)</SelectItem>
                      <SelectItem value="REJECT">Reject (filter out)</SelectItem>
                      <SelectItem value="FLAG">Flag (manual review)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            )}

            {form.ruleType === 'DOCUMENT_CHECK' && (
              <div className="space-y-4 rounded-lg border p-4 bg-muted/20">
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <Label className="text-xs text-muted-foreground mb-1 block">Minimum File Count</Label>
                    <Input
                      type="number"
                      min={0}
                      className="h-8 text-xs"
                      placeholder="e.g. 3"
                      value={form.minFileCount}
                      onChange={(e) => setForm((f) => ({ ...f, minFileCount: e.target.value ? parseInt(e.target.value) : '' }))}
                    />
                  </div>
                  <div>
                    <Label className="text-xs text-muted-foreground mb-1 block">Max Pages (any file)</Label>
                    <Input
                      type="number"
                      min={0}
                      className="h-8 text-xs"
                      placeholder="e.g. 10"
                      value={form.maxPages}
                      onChange={(e) => setForm((f) => ({ ...f, maxPages: e.target.value ? parseInt(e.target.value) : '' }))}
                    />
                  </div>
                </div>

                <div>
                  <Label className="text-xs text-muted-foreground mb-1.5 block">Required File Formats</Label>
                  <div className="flex flex-wrap gap-2">
                    {['pdf', 'docx', 'pptx', 'mp4', 'xlsx'].map((ext) => (
                      <label key={ext} className="flex items-center gap-1.5 cursor-pointer">
                        <Checkbox
                          checked={form.requiredFileTypes.includes(ext)}
                          onCheckedChange={(checked) => {
                            setForm((f) => ({
                              ...f,
                              requiredFileTypes: checked
                                ? [...f.requiredFileTypes, ext]
                                : f.requiredFileTypes.filter((t) => t !== ext),
                            }))
                          }}
                        />
                        <span className="text-xs font-mono">.{ext}</span>
                      </label>
                    ))}
                  </div>
                </div>

                <div>
                  <Label className="text-xs text-muted-foreground mb-1.5 block">Max Pages by File Type</Label>
                  <div className="space-y-2">
                    {FILE_TYPES.map((ft) => {
                      const limit = form.maxPagesByFileType[ft.value]
                      const hasLimit = limit !== undefined
                      return (
                        <div key={ft.value} className="flex items-center gap-2">
                          <Checkbox
                            checked={hasLimit}
                            onCheckedChange={(checked) => {
                              setForm((f) => {
                                const next = { ...f.maxPagesByFileType }
                                if (checked) next[ft.value] = 10
                                else delete next[ft.value]
                                return { ...f, maxPagesByFileType: next }
                              })
                            }}
                          />
                          <span className="text-xs w-32">{ft.label}</span>
                          {hasLimit && (
                            <Input
                              type="number"
                              min={1}
                              className="h-7 text-xs w-20"
                              value={limit}
                              onChange={(e) => {
                                setForm((f) => ({
                                  ...f,
                                  maxPagesByFileType: { ...f.maxPagesByFileType, [ft.value]: parseInt(e.target.value) || 1 },
                                }))
                              }}
                            />
                          )}
                          {hasLimit && <span className="text-xs text-muted-foreground">pages max</span>}
                        </div>
                      )
                    })}
                  </div>
                </div>

                <div>
                  <Label className="text-xs text-muted-foreground mb-1 block">Action when check fails</Label>
                  <Select value={form.docAction} onValueChange={(v) => setForm((f) => ({ ...f, docAction: v as any }))}>
                    <SelectTrigger className="w-40 h-8 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="REJECT">Reject (filter out)</SelectItem>
                      <SelectItem value="FLAG">Flag (manual review)</SelectItem>
                      <SelectItem value="PASS">Pass (informational)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => { setDialogOpen(false); setEditingRule(null); setForm({ ...DEFAULT_FORM }) }}>
              Cancel
            </Button>
            <Button
              onClick={handleSave}
              disabled={!form.name.trim() || createMutation.isPending || updateMutation.isPending}
            >
              {(createMutation.isPending || updateMutation.isPending) && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              {editingRule ? 'Update Rule' : 'Create Rule'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation */}
      <AlertDialog open={!!deleteConfirmId} onOpenChange={(open) => { if (!open) setDeleteConfirmId(null) }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Filtering Rule?</AlertDialogTitle>
            <AlertDialogDescription>
              This will permanently remove this rule. Projects already filtered will not be affected.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              onClick={() => {
                if (deleteConfirmId) deleteMutation.mutate({ id: deleteConfirmId })
              }}
            >
              {deleteMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}

// ─── Award Tracks Section ───────────────────────────────────────────────────

function AwardTracksSection({ competitionId, roundId }: { competitionId: string; roundId: string }) {
  const { data: awards, isLoading } = trpc.specialAward.listForRound.useQuery(
    { roundId },
    { enabled: !!roundId }
  )

  if (isLoading) return null
  if (!awards || awards.length === 0) return null

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base flex items-center gap-2">
          <Award className="h-5 w-5 text-amber-600" />
          Special Award Tracks
        </CardTitle>
        <CardDescription>
          Award eligibility is evaluated automatically during AI filtering. Use Run Eligibility to re-evaluate.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-3">
        {awards.map((award) => (
          <AwardShortlist
            key={award.id}
            awardId={award.id}
            roundId={roundId}
            awardName={award.name}
            criteriaText={award.criteriaText}
            eligibilityMode={award.eligibilityMode}
            shortlistSize={award.shortlistSize}
            jobStatus={award.eligibilityJobStatus}
            jobTotal={award.eligibilityJobTotal}
            jobDone={award.eligibilityJobDone}
          />
        ))}
      </CardContent>
    </Card>
  )
}
