import type { Metadata } from 'next'
import { Suspense } from 'react'
import Link from 'next/link'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { AutoRefresh } from '@/components/shared/auto-refresh'

export const metadata: Metadata = { title: 'Jury Dashboard' }
export const dynamic = 'force-dynamic'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import {
  ClipboardList,
  CheckCircle2,
  Clock,
  ArrowRight,
  GitCompare,
  Zap,
  BarChart3,
  Waves,
  Send,
  Trophy,
  FileText,
} from 'lucide-react'
import { userCanReviewFinals, getOpenFinaleRound } from '@/server/services/final-documents'
import { formatDateOnly } from '@/lib/utils'
import { CountdownTimer } from '@/components/shared/countdown-timer'
import { AnimatedCard } from '@/components/shared/animated-container'
import { JuryPreferencesBanner } from '@/components/jury/preferences-banner'
import { cn } from '@/lib/utils'

function getGreeting(): string {
  const hour = new Date().getHours()
  if (hour < 12) return 'Good morning'
  if (hour < 18) return 'Good afternoon'
  return 'Good evening'
}

/**
 * Prominent entry point to the finalist documents review, shown only to
 * Grand-Final jury members (and admins). Rendered at the top of the dashboard
 * regardless of whether the juror has individual assignments, so finals jurors
 * can always find the teams' files in one obvious place.
 */
async function FinalsJuryBanner() {
  const session = await auth()
  const userId = session?.user?.id
  if (!userId) return null

  const program = await prisma.program.findFirst({
    where: { status: 'ACTIVE' },
    orderBy: { year: 'desc' },
    select: { id: true },
  })
  if (!program) return null

  const canReview = await userCanReviewFinals(prisma, userId, session.user.role, program.id)
  if (!canReview) return null

  const round = await getOpenFinaleRound(prisma, program.id)
  const teamCount = round
    ? await prisma.projectRoundState.count({ where: { roundId: round.id } })
    : 0

  return (
    <AnimatedCard index={0}>
      <Card className="overflow-hidden border-0 shadow-lg">
        <div className="rounded-lg bg-gradient-to-r from-brand-blue to-brand-teal p-[1px]">
          <CardContent className="flex flex-col gap-4 rounded-[7px] bg-background p-5 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex items-start gap-4">
              <div className="shrink-0 rounded-xl bg-gradient-to-br from-brand-blue to-brand-teal p-3 shadow-sm">
                <Trophy className="h-6 w-6 text-white" />
              </div>
              <div>
                <p className="text-[11px] font-semibold uppercase tracking-wider text-brand-teal">
                  Grand Final
                </p>
                <h2 className="text-lg font-bold text-brand-blue">Finalist Documents</h2>
                <p className="mt-0.5 max-w-md text-sm text-muted-foreground">
                  {teamCount > 0 ? `All ${teamCount} finalist teams’ ` : 'Every finalist team’s '}
                  pitch decks, business plans, executive summaries and videos — in one place.
                </p>
              </div>
            </div>
            <Button
              asChild
              size="lg"
              className="w-full shrink-0 bg-brand-blue shadow-md hover:bg-brand-blue-light sm:w-auto"
            >
              <Link href="/jury/finals-documents">
                <FileText className="mr-2 h-4 w-4" />
                Review Finalist Documents
                <ArrowRight className="ml-2 h-4 w-4" />
              </Link>
            </Button>
          </CardContent>
        </div>
      </Card>
    </AnimatedCard>
  )
}

async function JuryDashboardContent() {
  const session = await auth()
  const userId = session?.user?.id

  if (!userId) {
    return null
  }

  // Get assignments, grace periods, feature flags, and award juror records in parallel
  const [assignments, gracePeriods, compareFlag, myAwardJurorRecords] = await Promise.all([
    prisma.assignment.findMany({
      where: { userId },
      include: {
        project: {
          select: {
            id: true,
            title: true,
            teamName: true,
            country: true,
          },
        },
        round: {
          select: {
            id: true,
            name: true,
            status: true,
            windowOpenAt: true,
            windowCloseAt: true,
            competition: {
              select: {
                program: {
                  select: {
                    name: true,
                    year: true,
                  },
                },
              },
            },
          },
        },
        evaluation: {
          select: {
            id: true,
            status: true,
            submittedAt: true,
            criterionScoresJson: true,
            form: {
              select: { criteriaJson: true },
            },
          },
        },
      },
      orderBy: [
        { round: { windowCloseAt: 'asc' } },
        { createdAt: 'asc' },
      ],
    }),
    prisma.gracePeriod.findMany({
      where: {
        userId,
        extendedUntil: { gte: new Date() },
      },
      select: {
        roundId: true,
        extendedUntil: true,
      },
    }),
    prisma.systemSettings.findUnique({ where: { key: 'jury_compare_enabled' } }),
    prisma.awardJuror.findMany({
      where: { userId },
      include: {
        award: {
          select: {
            id: true,
            name: true,
            description: true,
            status: true,
            votingStartAt: true,
            votingEndAt: true,
            scoringMode: true,
            maxRankedPicks: true,
            _count: { select: { eligibilities: { where: { eligible: true } } } },
          },
        },
      },
    }),
  ])

  const juryCompareEnabled = compareFlag?.value === 'true'

  // Check which awards the user has already voted on
  const awardIds = myAwardJurorRecords.map((r) => r.award.id)
  const myAwardVotes = awardIds.length > 0
    ? await prisma.awardVote.groupBy({
        by: ['awardId'],
        where: { userId, awardId: { in: awardIds } },
        _count: { id: true },
      })
    : []
  const votedAwardIds = new Set(myAwardVotes.filter((v) => v._count.id > 0).map((v) => v.awardId))

  // Awards where voting is open
  const activeAwards = myAwardJurorRecords.filter(
    (r) => r.award.status === 'VOTING_OPEN'
  )
  const upcomingAwards = myAwardJurorRecords.filter(
    (r) => r.award.status === 'NOMINATIONS_OPEN'
  )

  // Calculate stats
  const totalAssignments = assignments.length
  const completedAssignments = assignments.filter(
    (a) => a.evaluation?.status === 'SUBMITTED'
  ).length
  const inProgressAssignments = assignments.filter(
    (a) => a.evaluation?.status === 'DRAFT'
  ).length
  const pendingAssignments =
    totalAssignments - completedAssignments - inProgressAssignments

  const completionRate =
    totalAssignments > 0 ? (completedAssignments / totalAssignments) * 100 : 0

  // Group assignments by round
  const assignmentsByRound = assignments.reduce(
    (acc, assignment) => {
      const roundId = assignment.round.id
      if (!acc[roundId]) {
        acc[roundId] = {
          round: assignment.round,
          assignments: [],
        }
      }
      acc[roundId].assignments.push(assignment)
      return acc
    },
    {} as Record<string, { round: (typeof assignments)[0]['round']; assignments: typeof assignments }>
  )

  const graceByRound = new Map<string, Date>()
  for (const gp of gracePeriods) {
    const existing = graceByRound.get(gp.roundId)
    if (!existing || gp.extendedUntil > existing) {
      graceByRound.set(gp.roundId, gp.extendedUntil)
    }
  }

  // Active rounds (voting window open)
  const now = new Date()
  const activeRounds = Object.values(assignmentsByRound).filter(
    ({ round }) =>
      round.status === 'ROUND_ACTIVE' &&
      round.windowOpenAt &&
      round.windowCloseAt &&
      new Date(round.windowOpenAt) <= now &&
      new Date(round.windowCloseAt) >= now
  )

  // Find next unevaluated assignment in an active round
  const nextUnevaluated = assignments.find((a) => {
    const isActive =
      a.round.status === 'ROUND_ACTIVE' &&
      a.round.windowOpenAt &&
      a.round.windowCloseAt &&
      new Date(a.round.windowOpenAt) <= now &&
      new Date(a.round.windowCloseAt) >= now
    const isIncomplete = !a.evaluation || a.evaluation.status === 'NOT_STARTED' || a.evaluation.status === 'DRAFT'
    return isActive && isIncomplete
  })

  // Recent assignments for the quick list (latest 5)
  const recentAssignments = assignments.slice(0, 6)

  // Get active round remaining count
  const activeRemaining = assignments.filter((a) => {
    const isActive =
      a.round.status === 'ROUND_ACTIVE' &&
      a.round.windowOpenAt &&
      a.round.windowCloseAt &&
      new Date(a.round.windowOpenAt) <= now &&
      new Date(a.round.windowCloseAt) >= now
    const isIncomplete = !a.evaluation || a.evaluation.status !== 'SUBMITTED'
    return isActive && isIncomplete
  }).length

  const stats = [
    {
      value: totalAssignments,
      label: 'Assigned',
      detail: 'Total projects',
      accent: 'text-brand-blue',
    },
    {
      value: completedAssignments,
      label: 'Completed',
      detail: `${completionRate.toFixed(0)}% done`,
      accent: 'text-emerald-600',
    },
    {
      value: inProgressAssignments,
      label: 'In draft',
      detail: inProgressAssignments > 0 ? 'Work in progress' : 'None started',
      accent: inProgressAssignments > 0 ? 'text-amber-600' : 'text-emerald-600',
    },
    {
      value: pendingAssignments,
      label: 'Pending',
      detail: pendingAssignments > 0 ? 'Not yet started' : 'All started',
      accent: pendingAssignments > 0 ? 'text-amber-600' : 'text-emerald-600',
    },
  ]

  // Zero-assignment state: compact welcome card (but still show awards if any)
  if (totalAssignments === 0 && activeAwards.length === 0 && upcomingAwards.length === 0) {
    return (
      <AnimatedCard index={0}>
        <Card className="overflow-hidden">
          <div className="h-1 w-full bg-gradient-to-r from-brand-teal/40 via-brand-blue/40 to-brand-teal/40" />
          <CardContent className="py-8 px-6">
            <div className="flex flex-col items-center text-center mb-6">
              <div className="rounded-2xl bg-gradient-to-br from-brand-teal/10 to-brand-blue/10 p-4 mb-3">
                <ClipboardList className="h-8 w-8 text-brand-teal/60" />
              </div>
              <p className="text-lg font-semibold">No assignments yet</p>
              <p className="text-sm text-muted-foreground mt-1 max-w-sm">
                Your project assignments will appear here once an administrator assigns them to you.
              </p>
            </div>
            <div className={`grid gap-3 max-w-md mx-auto ${juryCompareEnabled ? 'sm:grid-cols-2' : ''}`}>
              <Link
                href="/jury/competitions"
                className="group flex items-center gap-3 rounded-xl border border-border/60 p-3 transition-all duration-200 hover:border-brand-blue/30 hover:bg-brand-blue/5 hover:-translate-y-0.5 hover:shadow-md"
              >
                <div className="rounded-lg bg-blue-50 p-2 transition-colors group-hover:bg-blue-100">
                  <ClipboardList className="h-4 w-4 text-blue-600" />
                </div>
                <div className="text-left">
                  <p className="font-semibold text-sm group-hover:text-brand-blue transition-colors">All Assignments</p>
                  <p className="text-xs text-muted-foreground">View evaluations</p>
                </div>
              </Link>
              {juryCompareEnabled && (
                <Link
                  href="/jury/competitions"
                  className="group flex items-center gap-3 rounded-xl border border-border/60 p-3 transition-all duration-200 hover:border-brand-teal/30 hover:bg-brand-teal/5 hover:-translate-y-0.5 hover:shadow-md"
                >
                  <div className="rounded-lg bg-teal-50 p-2 transition-colors group-hover:bg-teal-100">
                    <GitCompare className="h-4 w-4 text-brand-teal" />
                  </div>
                  <div className="text-left">
                    <p className="font-semibold text-sm group-hover:text-brand-teal transition-colors">Compare Projects</p>
                    <p className="text-xs text-muted-foreground">Side-by-side view</p>
                  </div>
                </Link>
              )}
            </div>
          </CardContent>
        </Card>
      </AnimatedCard>
    )
  }

  return (
    <>
      {/* Active Awards Banner */}
      {activeAwards.length > 0 && (
        <AnimatedCard index={0}>
          <Card className="overflow-hidden border-0 shadow-lg">
            <div className="bg-gradient-to-r from-amber-400 to-amber-500 p-[1px] rounded-lg">
              <div className="rounded-[7px] bg-background">
                <CardHeader className="pb-2 pt-4 px-5">
                  <div className="flex items-center gap-2.5">
                    <div className="rounded-lg bg-amber-100 p-1.5">
                      <Trophy className="h-4 w-4 text-amber-600" />
                    </div>
                    <CardTitle className="text-lg">Special Awards — Voting Open</CardTitle>
                  </div>
                </CardHeader>
                <CardContent className="px-5 pb-4 space-y-3">
                  {activeAwards.map((record) => {
                    const award = record.award
                    const deadline = award.votingEndAt ? new Date(award.votingEndAt) : null
                    const isUrgent = deadline && (deadline.getTime() - now.getTime()) < 24 * 60 * 60 * 1000
                    const hasVoted = votedAwardIds.has(award.id)

                    return (
                      <div
                        key={award.id}
                        className={cn(
                          'rounded-xl border p-4 space-y-3 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md',
                          hasVoted
                            ? 'border-green-200/60 bg-green-50/30'
                            : isUrgent
                              ? 'border-red-200 bg-red-50/50'
                              : 'border-amber-200/60 bg-amber-50/30'
                        )}
                      >
                        <div className="flex items-start justify-between">
                          <div>
                            <h3 className={cn('font-semibold', hasVoted ? 'text-green-700' : 'text-amber-700')}>{award.name}</h3>
                            <p className="text-xs text-muted-foreground mt-0.5">
                              {award._count.eligibilities} project{award._count.eligibilities !== 1 ? 's' : ''} to review
                              {record.isChair && ' · You are the Chair'}
                            </p>
                          </div>
                          {hasVoted ? (
                            <Badge className="bg-green-100 text-green-800 border-green-300">
                              <CheckCircle2 className="mr-1 h-3 w-3" />
                              Submitted
                            </Badge>
                          ) : (
                            <Badge className="bg-amber-100 text-amber-800 border-amber-300">
                              Vote Now
                            </Badge>
                          )}
                        </div>
                        {deadline && (
                          <CountdownTimer deadline={deadline} label="Voting closes:" />
                        )}
                        <Button asChild size="sm" className={cn(
                          'w-full shadow-sm',
                          hasVoted
                            ? 'bg-green-600 hover:bg-green-700 text-white'
                            : 'bg-amber-600 hover:bg-amber-700 text-white'
                        )}>
                          <Link href={`/jury/awards/${award.id}`}>
                            {hasVoted ? 'Edit Rankings' : 'Review & Vote'}
                            <ArrowRight className="ml-2 h-4 w-4" />
                          </Link>
                        </Button>
                      </div>
                    )
                  })}
                </CardContent>
              </div>
            </div>
          </Card>
        </AnimatedCard>
      )}

      {/* Hero CTA - Jump to next evaluation */}
      {nextUnevaluated && activeRemaining > 0 && (
        <AnimatedCard index={0}>
          <Card className="overflow-hidden border-0 shadow-lg">
            <div className="bg-gradient-to-r from-brand-blue to-brand-teal p-[1px] rounded-lg">
              <CardContent className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 py-5 px-6 rounded-[7px] bg-background">
                <div className="flex items-center gap-4">
                  <div className="rounded-xl bg-gradient-to-br from-brand-blue to-brand-teal p-3 shadow-sm">
                    <Zap className="h-5 w-5 text-white" />
                  </div>
                  <div>
                    <p className="font-semibold text-base">
                      {activeRemaining} evaluation{activeRemaining > 1 ? 's' : ''} remaining
                    </p>
                    <p className="text-sm text-muted-foreground">
                      Continue with &quot;{nextUnevaluated.project.title}&quot;
                    </p>
                  </div>
                </div>
                <Button asChild size="lg" className="bg-brand-blue hover:bg-brand-blue-light shadow-md">
                  <Link href={`/jury/competitions/${nextUnevaluated.round.id}/projects/${nextUnevaluated.project.id}/evaluate`}>
                    {nextUnevaluated.evaluation?.status === 'DRAFT' ? 'Continue Evaluation' : 'Start Evaluation'}
                    <ArrowRight className="ml-2 h-4 w-4" />
                  </Link>
                </Button>
              </CardContent>
            </div>
          </Card>
        </AnimatedCard>
      )}

      {/* Stats — editorial strip */}
      <AnimatedCard index={1}>
        {/* Mobile: compact horizontal data strip */}
        <div className="flex items-baseline justify-between border-b border-t py-3 md:hidden">
          {stats.map((s, i) => (
            <div key={i} className={`flex-1 text-center ${i > 0 ? 'border-l border-border/50' : ''}`}>
              <span className="text-xl font-bold tabular-nums tracking-tight">{s.value}</span>
              <p className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground mt-0.5">{s.label}</p>
            </div>
          ))}
        </div>

        {/* Desktop: editorial stat row */}
        <div className="hidden md:block">
          <div className="grid grid-cols-4 gap-px rounded-lg bg-border/40 overflow-hidden">
            {stats.map((s, i) => (
              <div
                key={i}
                className="bg-background px-5 py-4 group hover:bg-muted/30 transition-colors"
              >
                <span className="text-3xl font-bold tabular-nums tracking-tight">{s.value}</span>
                <p className="text-xs font-medium text-muted-foreground mt-1">{s.label}</p>
                <p className={`text-xs mt-0.5 ${s.accent}`}>{s.detail}</p>
              </div>
            ))}
          </div>
        </div>
      </AnimatedCard>

      {/* Main content -- two column layout */}
      <div className="grid gap-4 lg:grid-cols-12">
        {/* Left column */}
        <div className="lg:col-span-7 space-y-4">
          {/* Recent Assignments */}
          <AnimatedCard index={6}>
            <Card>
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2.5">
                    <div className="rounded-lg bg-brand-blue/10 p-1.5">
                      <ClipboardList className="h-4 w-4 text-brand-blue" />
                    </div>
                    <CardTitle className="text-lg">My Assignments</CardTitle>
                  </div>
                  <Button variant="ghost" size="sm" asChild className="text-brand-teal hover:text-brand-blue">
                    <Link href="/jury/competitions">
                      View all
                      <ArrowRight className="ml-1 h-3 w-3" />
                    </Link>
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                {recentAssignments.length > 0 ? (
                  <div className="space-y-1">
                    {recentAssignments.map((assignment, idx) => {
                      const evaluation = assignment.evaluation
                      const isCompleted = evaluation?.status === 'SUBMITTED'
                      const isDraft = evaluation?.status === 'DRAFT'
                      const isVotingOpen = assignment.round.status === 'ROUND_ACTIVE'

                      return (
                        <div
                          key={assignment.id}
                          className={cn(
                            'flex items-center justify-between gap-3 py-3 px-3 -mx-3 rounded-lg transition-colors duration-150',
                            'hover:bg-muted/50',
                            idx !== recentAssignments.length - 1 && 'border-b border-border/50',
                          )}
                        >
                          <Link
                            href={`/jury/competitions/${assignment.round.id}/projects/${assignment.project.id}`}
                            className="flex-1 min-w-0 group"
                          >
                            <p className="text-sm font-medium truncate group-hover:text-brand-blue transition-colors">
                              {assignment.project.title}
                            </p>
                            <div className="flex items-center gap-2 mt-1">
                              <span className="text-xs text-muted-foreground truncate">
                                {assignment.project.teamName}
                              </span>
                              <Badge variant="secondary" className="text-[10px] px-1.5 py-0 bg-brand-blue/5 text-brand-blue/80 border-0">
                                {assignment.round.name}
                              </Badge>
                            </div>
                          </Link>
                          <div className="flex items-center gap-2 shrink-0">
                            {isCompleted ? (
                              <Badge variant="success" className="text-xs">
                                <CheckCircle2 className="mr-1 h-3 w-3" />
                                Done
                              </Badge>
                            ) : isDraft && isVotingOpen ? (
                              <Badge className="text-xs bg-amber-100 text-amber-800 border-amber-300 animate-pulse">
                                <Send className="mr-1 h-3 w-3" />
                                Ready to submit
                              </Badge>
                            ) : isDraft ? (
                              <Badge variant="warning" className="text-xs">
                                <Clock className="mr-1 h-3 w-3" />
                                Draft
                              </Badge>
                            ) : (
                              <Badge variant="secondary" className="text-xs">Pending</Badge>
                            )}
                            {isCompleted ? (
                              <Button variant="ghost" size="sm" asChild className="h-7 px-2">
                                <Link href={`/jury/competitions/${assignment.round.id}/projects/${assignment.project.id}/evaluate`}>
                                  View
                                </Link>
                              </Button>
                            ) : isVotingOpen && isDraft ? (
                              <Button size="sm" asChild className="h-7 px-3 bg-amber-600 hover:bg-amber-700 text-white shadow-sm">
                                <Link href={`/jury/competitions/${assignment.round.id}/projects/${assignment.project.id}/evaluate`}>
                                  <Send className="mr-1 h-3 w-3" />
                                  Review & Submit
                                </Link>
                              </Button>
                            ) : isVotingOpen ? (
                              <Button size="sm" asChild className="h-7 px-3 bg-brand-blue hover:bg-brand-blue-light shadow-sm">
                                <Link href={`/jury/competitions/${assignment.round.id}/projects/${assignment.project.id}/evaluate`}>
                                  Evaluate
                                </Link>
                              </Button>
                            ) : (
                              <Button variant="ghost" size="sm" asChild className="h-7 px-2">
                                <Link href={`/jury/competitions/${assignment.round.id}/projects/${assignment.project.id}`}>
                                  View
                                </Link>
                              </Button>
                            )}
                          </div>
                        </div>
                      )
                    })}
                  </div>
                ) : (
                  <div className="flex flex-col items-center justify-center py-6 text-center">
                    <div className="rounded-2xl bg-brand-teal/10 p-3 mb-2">
                      <ClipboardList className="h-6 w-6 text-brand-teal/60" />
                    </div>
                    <p className="font-medium text-sm text-muted-foreground">
                      No assignments yet
                    </p>
                    <p className="text-xs text-muted-foreground/70 mt-1 max-w-[240px]">
                      Assignments will appear here once an administrator assigns projects to you.
                    </p>
                  </div>
                )}
              </CardContent>
            </Card>
          </AnimatedCard>

          {/* Quick Actions */}
          <AnimatedCard index={7}>
            <Card>
              <CardHeader className="pb-3">
                <div className="flex items-center gap-2.5">
                  <div className="rounded-lg bg-brand-teal/10 p-1.5">
                    <Zap className="h-4 w-4 text-brand-teal" />
                  </div>
                  <CardTitle className="text-lg">Quick Actions</CardTitle>
                </div>
              </CardHeader>
              <CardContent>
                <div className={`grid gap-3 ${juryCompareEnabled ? 'sm:grid-cols-2' : ''}`}>
                  <Link
                    href="/jury/competitions"
                    className="group flex items-center gap-4 rounded-xl border border-border/60 p-4 transition-all duration-200 hover:border-brand-blue/30 hover:bg-brand-blue/5 hover:-translate-y-0.5 hover:shadow-md"
                  >
                    <div className="rounded-xl bg-blue-50 p-3 transition-colors group-hover:bg-blue-100">
                      <ClipboardList className="h-5 w-5 text-blue-600" />
                    </div>
                    <div className="text-left">
                      <p className="font-semibold text-sm group-hover:text-brand-blue transition-colors">All Assignments</p>
                      <p className="text-xs text-muted-foreground mt-0.5">View and manage evaluations</p>
                    </div>
                  </Link>
                  {juryCompareEnabled && (
                    <Link
                      href="/jury/competitions"
                      className="group flex items-center gap-4 rounded-xl border border-border/60 p-4 transition-all duration-200 hover:border-brand-teal/30 hover:bg-brand-teal/5 hover:-translate-y-0.5 hover:shadow-md"
                    >
                      <div className="rounded-xl bg-teal-50 p-3 transition-colors group-hover:bg-teal-100">
                        <GitCompare className="h-5 w-5 text-brand-teal" />
                      </div>
                      <div className="text-left">
                        <p className="font-semibold text-sm group-hover:text-brand-teal transition-colors">Compare Projects</p>
                        <p className="text-xs text-muted-foreground mt-0.5">Side-by-side comparison</p>
                      </div>
                    </Link>
                  )}
                </div>
              </CardContent>
            </Card>
          </AnimatedCard>
        </div>

        {/* Right column */}
        <div className="lg:col-span-5 space-y-4">
          {/* Active Rounds */}
          {activeRounds.length > 0 && (
            <AnimatedCard index={8}>
              <Card className="overflow-hidden">
                <div className="h-1 w-full bg-gradient-to-r from-brand-blue via-brand-teal to-brand-blue" />
                <CardHeader className="pb-3">
                  <div className="flex items-center gap-2.5">
                    <div className="rounded-lg bg-brand-blue/10 p-1.5">
                      <Waves className="h-4 w-4 text-brand-blue" />
                    </div>
                    <div>
                      <CardTitle className="text-lg">Active Voting Stages</CardTitle>
                      <CardDescription className="mt-0.5">
                        Stages currently open for evaluation
                      </CardDescription>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  {activeRounds.map(({ round, assignments: roundAssignments }: { round: (typeof assignments)[0]['round']; assignments: typeof assignments }) => {
                    const roundCompleted = roundAssignments.filter(
                      (a: typeof assignments[0]) => a.evaluation?.status === 'SUBMITTED'
                    ).length
                    const roundTotal = roundAssignments.length
                    const roundProgress =
                      roundTotal > 0 ? (roundCompleted / roundTotal) * 100 : 0
                    const isAlmostDone = roundProgress >= 80
                    const deadline = graceByRound.get(round.id) ?? (round.windowCloseAt ? new Date(round.windowCloseAt) : null)
                    const isUrgent = deadline && (deadline.getTime() - now.getTime()) < 24 * 60 * 60 * 1000
                    const program = round.competition.program

                    return (
                      <div
                        key={round.id}
                        className={cn(
                          'rounded-xl border p-4 space-y-3 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md',
                          isUrgent
                            ? 'border-red-200 bg-red-50/50'
                            : 'border-border/60 bg-muted/20'
                        )}
                      >
                        <div className="flex items-start justify-between">
                          <div>
                            <h3 className="font-semibold text-brand-blue">{round.name}</h3>
                            <p className="text-xs text-muted-foreground mt-0.5">
                              {program.name} &middot; {program.year}
                            </p>
                          </div>
                          {isAlmostDone ? (
                            <Badge variant="success">Almost done</Badge>
                          ) : (
                            <Badge variant="info">Active</Badge>
                          )}
                        </div>

                        <div className="space-y-1.5">
                          <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Progress</span>
                            <span className="font-semibold tabular-nums">
                              {roundCompleted}/{roundTotal}
                            </span>
                          </div>
                          <div className="relative h-2.5 w-full overflow-hidden rounded-full bg-muted/60">
                            <div
                              className="h-full rounded-full bg-gradient-to-r from-brand-teal to-brand-blue transition-all duration-500 ease-out"
                              style={{ width: `${roundProgress}%` }}
                            />
                          </div>
                        </div>

                        {deadline && (
                          <div className="flex items-center gap-2 flex-wrap">
                            <CountdownTimer
                              deadline={deadline}
                              label="Deadline:"
                            />
                            {round.windowCloseAt && (
                              <span className="text-xs text-muted-foreground">
                                ({formatDateOnly(round.windowCloseAt)})
                              </span>
                            )}
                          </div>
                        )}

                        <Button asChild size="sm" className="w-full bg-brand-blue hover:bg-brand-blue-light shadow-sm">
                          <Link href={`/jury/competitions/${round.id}`}>
                            View Assignments
                            <ArrowRight className="ml-2 h-4 w-4" />
                          </Link>
                        </Button>
                      </div>
                    )
                  })}
                </CardContent>
              </Card>
            </AnimatedCard>
          )}

          {/* No active stages */}
          {activeRounds.length === 0 && (
            <AnimatedCard index={8}>
              <Card>
                <CardContent className="flex flex-col items-center justify-center py-6 text-center">
                  <div className="rounded-2xl bg-brand-teal/10 p-3 mb-2">
                    <Clock className="h-6 w-6 text-brand-teal/70" />
                  </div>
                  <p className="font-semibold text-sm">No active voting stages</p>
                  <p className="text-xs text-muted-foreground mt-1 max-w-[220px]">
                    Check back later when a voting window opens
                  </p>
                </CardContent>
              </Card>
            </AnimatedCard>
          )}

          {/* Completion Summary by Round */}
          {Object.keys(assignmentsByRound).length > 0 && (
            <AnimatedCard index={9}>
              <Card>
                <CardHeader className="pb-3">
                  <div className="flex items-center gap-2.5">
                    <div className="rounded-lg bg-brand-teal/10 p-1.5">
                      <BarChart3 className="h-4 w-4 text-brand-teal" />
                    </div>
                    <CardTitle className="text-lg">Round Summary</CardTitle>
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  {Object.values(assignmentsByRound).map(({ round, assignments: roundAssignments }: { round: (typeof assignments)[0]['round']; assignments: typeof assignments }) => {
                    const done = roundAssignments.filter((a: typeof assignments[0]) => a.evaluation?.status === 'SUBMITTED').length
                    const total = roundAssignments.length
                    const pct = total > 0 ? Math.round((done / total) * 100) : 0
                    return (
                      <div key={round.id} className="space-y-2">
                        <div className="flex items-center justify-between text-sm">
                          <span className="font-medium truncate">{round.name}</span>
                          <div className="flex items-baseline gap-1 shrink-0 ml-2">
                            <span className="font-bold tabular-nums text-brand-blue">{pct}%</span>
                            <span className="text-xs text-muted-foreground">({done}/{total})</span>
                          </div>
                        </div>
                        <div className="relative h-2 w-full overflow-hidden rounded-full bg-muted/60">
                          <div
                            className="h-full rounded-full bg-gradient-to-r from-brand-teal to-brand-blue transition-all duration-500 ease-out"
                            style={{ width: `${pct}%` }}
                          />
                        </div>
                      </div>
                    )
                  })}
                </CardContent>
              </Card>
            </AnimatedCard>
          )}
        </div>
      </div>
    </>
  )
}

function DashboardSkeleton() {
  return (
    <>
      {/* Stats skeleton */}
      <div className="flex items-baseline justify-between border-b border-t py-3 md:hidden">
        {[...Array(4)].map((_, i) => (
          <div key={i} className={`flex-1 text-center ${i > 0 ? 'border-l border-border/50' : ''}`}>
            <Skeleton className="h-6 w-8 mx-auto" />
            <Skeleton className="h-3 w-14 mx-auto mt-1" />
          </div>
        ))}
      </div>
      <div className="hidden md:block">
        <div className="grid grid-cols-4 gap-px rounded-lg bg-border/40 overflow-hidden">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="bg-background px-5 py-4">
              <Skeleton className="h-9 w-12" />
              <Skeleton className="h-4 w-20 mt-1" />
              <Skeleton className="h-3 w-16 mt-1" />
            </div>
          ))}
        </div>
      </div>
      {/* Two-column skeleton */}
      <div className="grid gap-6 lg:grid-cols-12">
        <div className="lg:col-span-7">
          <Card>
            <CardHeader className="pb-3">
              <Skeleton className="h-5 w-40" />
            </CardHeader>
            <CardContent className="space-y-4">
              {[...Array(4)].map((_, i) => (
                <div key={i} className="flex items-center justify-between py-2">
                  <div className="space-y-2">
                    <Skeleton className="h-4 w-48" />
                    <Skeleton className="h-3 w-32" />
                  </div>
                  <Skeleton className="h-7 w-20" />
                </div>
              ))}
            </CardContent>
          </Card>
        </div>
        <div className="lg:col-span-5 space-y-6">
          <Card className="overflow-hidden">
            <div className="h-1 w-full bg-muted" />
            <CardHeader className="pb-3">
              <Skeleton className="h-5 w-44" />
            </CardHeader>
            <CardContent className="space-y-4">
              <Skeleton className="h-28 w-full rounded-xl" />
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <Skeleton className="h-5 w-36" />
            </CardHeader>
            <CardContent className="space-y-4">
              {[...Array(2)].map((_, i) => (
                <div key={i} className="space-y-2">
                  <Skeleton className="h-4 w-full" />
                  <Skeleton className="h-2 w-full rounded-full" />
                </div>
              ))}
            </CardContent>
          </Card>
        </div>
      </div>
    </>
  )
}

export default async function JuryDashboardPage() {
  const session = await auth()

  return (
    <div className="space-y-4">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold tracking-tight text-brand-blue">
          {getGreeting()}, {session?.user?.name || 'Juror'}
        </h1>
        <p className="text-muted-foreground mt-0.5">
          Here&apos;s an overview of your evaluation progress
        </p>
      </div>

      {/* Preferences banner (shown when juror has unconfirmed preferences) */}
      <JuryPreferencesBanner />

      {/* Grand-Final finalist documents — prominent entry for finals jurors */}
      <Suspense fallback={null}>
        <FinalsJuryBanner />
      </Suspense>

      {/* Content */}
      <Suspense fallback={<DashboardSkeleton />}>
        <JuryDashboardContent />
      </Suspense>

      {/* Auto-refresh every 30s so voting round changes appear promptly */}
      <AutoRefresh intervalMs={30_000} />
    </div>
  )
}
