'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { useRouter } from 'next/navigation'
import { trpc } from '@/lib/trpc/client'
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 { Progress } from '@/components/ui/progress'
import { Separator } from '@/components/ui/separator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { FileViewer } from '@/components/shared/file-viewer'
import { ProjectLogoWithUrl } from '@/components/shared/project-logo-with-url'
import { UserAvatar } from '@/components/shared/user-avatar'
import { StatusBadge } from '@/components/shared/status-badge'
import { AnimatedCard } from '@/components/shared/animated-container'
import { CountryDisplay } from '@/components/shared/country-display'
import {
  AlertCircle,
  Users,
  FileText,
  Calendar,
  CheckCircle2,
  Circle,
  XCircle,
  BarChart3,
  ThumbsUp,
  ThumbsDown,
  MapPin,
  Waves,
  GraduationCap,
  Heart,
  Clock,
  MessageSquare,
  ArrowLeft,
} from 'lucide-react'
import { cn, formatDate, formatDateOnly } from '@/lib/utils'
import { ScoreExplainerDialog } from '@/components/shared/score-explainer-dialog'

export function ObserverProjectDetail({
  projectId,
  initialRoundId,
}: {
  projectId: string
  initialRoundId?: string
}) {
  const router = useRouter()
  const [activeRoundId, setActiveRoundId] = useState<string | undefined>(initialRoundId)

  // Resolve a default round when none is set: prefer the currently OPEN round
  // the project participates in, fall back to the most recently CLOSED one.
  const { data: roundCandidates } = trpc.analytics.getProjectRoundsForObserver.useQuery(
    { projectId },
  )
  useEffect(() => {
    if (activeRoundId || !roundCandidates) return
    const active = roundCandidates.find((r) => r.status === 'ROUND_ACTIVE')
    if (active) {
      setActiveRoundId(active.id)
      return
    }
    const closed = [...roundCandidates]
      .filter((r) => r.status === 'ROUND_CLOSED')
      .sort((a, b) => b.sortOrder - a.sortOrder)[0]
    if (closed) setActiveRoundId(closed.id)
  }, [roundCandidates, activeRoundId])

  const { data, isLoading } = trpc.analytics.getProjectDetail.useQuery(
    { id: projectId, roundId: activeRoundId },
    { refetchInterval: 30_000 },
  )
  const { data: flags } = trpc.settings.getFeatureFlags.useQuery()

  const roundId = activeRoundId ?? (data?.assignments?.[0]?.roundId as string | undefined)
  const { data: activeForm } = trpc.evaluation.getStageForm.useQuery(
    { roundId: roundId ?? '', category: data?.project?.competitionCategory },
    { enabled: !!roundId },
  )

  if (isLoading) {
    return <ProjectDetailSkeleton />
  }

  if (!data) {
    return (
      <div className="space-y-6">
        <nav className="flex items-center gap-1 text-sm text-muted-foreground">
          <Link href={'/observer' as Route} className="hover:text-foreground">
            Observer
          </Link>
          <span>/</span>
          <Link
            href={'/observer/projects' as Route}
            className="hover:text-foreground"
          >
            Projects
          </Link>
        </nav>
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <AlertCircle className="h-12 w-12 text-destructive/50" />
            <p className="mt-2 font-medium">Project Not Found</p>
            <Button className="mt-4" onClick={() => router.back()}>
              Back
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  const { project, assignments, stats, competitionRounds, projectRoundStates, filteringResult } =
    data

  const roundStateMap = new Map(
    (projectRoundStates ?? []).map((s) => [s.roundId, s]),
  )

  const criteriaMap = new Map<
    string,
    { label: string; type: string; trueLabel?: string; falseLabel?: string }
  >()
  if (activeForm?.criteriaJson) {
    for (const c of activeForm.criteriaJson as Array<{
      id: string
      label: string
      type?: string
      trueLabel?: string
      falseLabel?: string
    }>) {
      criteriaMap.set(c.id, {
        label: c.label,
        type: c.type || 'numeric',
        trueLabel: c.trueLabel,
        falseLabel: c.falseLabel,
      })
    }
  }

  // Compute per-criterion averages from all submitted evaluations
  const criterionTotals = new Map<string, { sum: number; count: number }>()
  for (const assignment of assignments) {
    const ev = assignment.evaluation
    if (ev?.status !== 'SUBMITTED') continue
    const scores = (ev.criterionScoresJson || {}) as Record<
      string,
      number | boolean | string
    >
    for (const [key, value] of Object.entries(scores)) {
      const meta = criteriaMap.get(key)
      const type =
        meta?.type ||
        (typeof value === 'boolean'
          ? 'boolean'
          : typeof value === 'string'
            ? 'text'
            : 'numeric')
      if (type !== 'numeric' && type !== 'section_header') continue
      if (type === 'section_header') continue
      if (typeof value !== 'number') continue
      const existing = criterionTotals.get(key) || { sum: 0, count: 0 }
      criterionTotals.set(key, {
        sum: existing.sum + value,
        count: existing.count + 1,
      })
    }
  }

  const criterionAverages = new Map<string, number>()
  for (const [key, { sum, count }] of criterionTotals.entries()) {
    if (count > 0) criterionAverages.set(key, sum / count)
  }

  return (
    <div className="space-y-6">
      {/* Back button */}
      <Button variant="ghost" size="sm" className="gap-1.5 -ml-2 text-muted-foreground" onClick={() => router.back()}>
        <ArrowLeft className="h-3.5 w-3.5" />
        Back
      </Button>

      {/* Project Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex items-start gap-4">
          <ProjectLogoWithUrl project={project} size="lg" fallback="initials" />
          <div className="min-w-0 space-y-1.5">
            <h1 className="text-2xl font-semibold tracking-tight">
              {project.title}
            </h1>
            {project.teamName && (
              <p className="text-muted-foreground">{project.teamName}</p>
            )}
            <div className="flex flex-wrap items-center gap-2">
              {(project.country || project.geographicZone) && (
                <Badge variant="outline" className="gap-1">
                  <MapPin className="h-3 w-3" />
                  {project.country ? <CountryDisplay country={project.country} /> : project.geographicZone}
                </Badge>
              )}
              {project.competitionCategory && (
                <Badge variant="outline" className="gap-1">
                  <GraduationCap className="h-3 w-3" />
                  {project.competitionCategory === 'STARTUP'
                    ? 'Start-up'
                    : 'Business Concept'}
                </Badge>
              )}
              {project.oceanIssue && (
                <Badge variant="outline" className="gap-1">
                  <Waves className="h-3 w-3" />
                  {project.oceanIssue.replace(/_/g, ' ')}
                </Badge>
              )}
              <StatusBadge status={project.status ?? 'SUBMITTED'} />
            </div>
          </div>
        </div>

        {/* Score card */}
        {stats && (
          <Card className="w-full shrink-0 sm:w-48">
            <CardContent className="pt-4">
              <div className="flex flex-col items-center text-center">
                <div className="rounded-lg bg-brand-teal/10 p-2">
                  <BarChart3 className="h-5 w-5 text-brand-teal" />
                </div>
                <p className="mt-2 text-4xl font-bold tabular-nums">
                  {stats.averageGlobalScore != null
                    ? stats.averageGlobalScore.toFixed(2)
                    : '-'}
                </p>
                <p className="text-xs text-muted-foreground">
                  {stats.minScore ?? '-'} – {stats.maxScore ?? '-'} range
                </p>
                <Separator className="my-2" />
                <p className="text-xs text-muted-foreground">
                  {stats.totalEvaluations} evaluation
                  {stats.totalEvaluations !== 1 ? 's' : ''}
                </p>
                {stats.yesPercentage != null && (
                  <p className="mt-0.5 text-xs font-medium text-emerald-600">
                    {stats.yesPercentage.toFixed(0)}% recommended
                  </p>
                )}
                {roundCandidates && roundCandidates.length > 1 && (
                  <div className="mt-3 w-full">
                    <select
                      className="w-full rounded border bg-background px-2 py-1 text-xs"
                      value={activeRoundId ?? ''}
                      onChange={(e) => setActiveRoundId(e.target.value)}
                    >
                      {roundCandidates.map((r) => (
                        <option key={r.id} value={r.id}>{r.name}</option>
                      ))}
                    </select>
                  </div>
                )}
                <div className="mt-2 w-full">
                  <ScoreExplainerDialog />
                </div>
              </div>
            </CardContent>
          </Card>
        )}
      </div>

      <Separator />

      {/* Tabs */}
      <Tabs defaultValue="overview">
        <TabsList>
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="evaluations">
            Evaluations
            {assignments.length > 0 && (
              <Badge variant="secondary" className="ml-1.5 h-4 px-1 text-xs">
                {assignments.length}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger value="files">Files</TabsTrigger>
          {flags?.observerShowTeamTab && project.teamMembers.length > 0 && (
            <TabsTrigger value="team">
              Team
              <Badge variant="secondary" className="ml-1.5 h-4 px-1 text-xs">
                {project.teamMembers.length}
              </Badge>
            </TabsTrigger>
          )}
        </TabsList>

        {/* ── Overview Tab ── */}
        <TabsContent value="overview" className="mt-6 space-y-6">
          {/* Criteria mini-cards */}
          {criterionAverages.size > 0 && (
            <AnimatedCard index={0}>
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2.5 text-lg">
                    <div className="rounded-lg bg-brand-teal/10 p-1.5">
                      <BarChart3 className="h-4 w-4 text-brand-teal" />
                    </div>
                    Criteria Averages
                  </CardTitle>
                  <CardDescription>
                    Averaged across all submitted evaluations
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
                    {Array.from(criterionAverages.entries()).map(
                      ([key, avg]) => {
                        const meta = criteriaMap.get(key)
                        const label = meta?.label || key
                        return (
                          <div
                            key={key}
                            className="rounded-lg border p-3 space-y-2"
                          >
                            <p className="text-xs font-medium text-muted-foreground line-clamp-2">
                              {label}
                            </p>
                            <p className="text-xl font-bold tabular-nums">
                              {avg.toFixed(1)}
                            </p>
                            <Progress
                              value={(avg / 10) * 100}
                              className="h-1.5"
                            />
                          </div>
                        )
                      },
                    )}
                  </div>
                </CardContent>
              </Card>
            </AnimatedCard>
          )}

          {/* AI Rejection Reason */}
          {project.status === 'REJECTED' && filteringResult?.aiScreeningJson && (() => {
            const screening = filteringResult.aiScreeningJson as Record<string, Record<string, unknown>>
            // Extract reasoning from the first rule's result
            const firstRule = Object.values(screening)[0]
            const reasoning = firstRule?.reasoning as string | undefined
            const confidence = firstRule?.confidence as number | undefined
            if (!reasoning) return null
            return (
              <AnimatedCard index={1}>
                <Card className="border-red-200 bg-red-50/50">
                  <CardHeader className="pb-2">
                    <CardTitle className="flex items-center gap-2.5 text-lg text-red-700">
                      <div className="rounded-lg bg-red-100 p-1.5">
                        <AlertCircle className="h-4 w-4 text-red-600" />
                      </div>
                      AI Screening — Rejected
                      {filteringResult.round && (
                        <span className="text-sm font-normal text-red-500 ml-auto">
                          at {filteringResult.round.name}
                        </span>
                      )}
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <p className="text-sm text-red-800 whitespace-pre-wrap">{reasoning}</p>
                    {confidence != null && (
                      <p className="mt-2 text-xs text-red-500">
                        AI Confidence: {Math.round(confidence * 100)}%
                      </p>
                    )}
                    {filteringResult.overrideReason && (
                      <div className="mt-3 border-t border-red-200 pt-3">
                        <p className="text-xs font-medium text-red-600">Override Reason</p>
                        <p className="text-sm text-red-800">{filteringResult.overrideReason}</p>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </AnimatedCard>
            )
          })()}

          {/* Project Info — matches admin layout */}
          <AnimatedCard index={2}>
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2.5 text-lg">
                  <div className="rounded-lg bg-emerald-500/10 p-1.5">
                    <FileText className="h-4 w-4 text-emerald-500" />
                  </div>
                  Project Information
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* Category & Ocean Issue badges */}
                <div className="flex flex-wrap gap-2">
                  {project.competitionCategory && (
                    <Badge variant="outline" className="gap-1">
                      <GraduationCap className="h-3 w-3" />
                      {project.competitionCategory === 'STARTUP' ? 'Start-up' : 'Business Concept'}
                    </Badge>
                  )}
                  {project.oceanIssue && (
                    <Badge variant="outline" className="gap-1">
                      <Waves className="h-3 w-3" />
                      {project.oceanIssue.replace(/_/g, ' ')}
                    </Badge>
                  )}
                  {project.wantsMentorship && (
                    <Badge variant="outline" className="gap-1 text-pink-600 border-pink-200 bg-pink-50">
                      <Heart className="h-3 w-3" />
                      Wants Mentorship
                    </Badge>
                  )}
                </div>

                {project.description && (
                  <div>
                    <p className="text-sm font-medium text-muted-foreground mb-1">Description</p>
                    <p className="text-sm whitespace-pre-wrap">{project.description}</p>
                  </div>
                )}

                {/* Location, Institution, Founded */}
                <div className="grid gap-4 sm:grid-cols-2">
                  {(project.country || project.geographicZone) && (
                    <div className="flex items-start gap-2">
                      <MapPin className="h-4 w-4 text-muted-foreground mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-muted-foreground">Location</p>
                        <p className="text-sm">{project.geographicZone}{project.geographicZone && project.country ? ', ' : ''}{project.country ? <CountryDisplay country={project.country} /> : null}</p>
                      </div>
                    </div>
                  )}
                  {project.institution && (
                    <div className="flex items-start gap-2">
                      <GraduationCap className="h-4 w-4 text-muted-foreground mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-muted-foreground">Institution</p>
                        <p className="text-sm">{project.institution}</p>
                      </div>
                    </div>
                  )}
                  {project.foundedAt && (
                    <div className="flex items-start gap-2">
                      <Calendar className="h-4 w-4 text-muted-foreground mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-muted-foreground">Founded</p>
                        <p className="text-sm">{formatDateOnly(project.foundedAt)}</p>
                      </div>
                    </div>
                  )}
                </div>

                {/* AI-Assigned Expertise Tags */}
                {project.projectTags && project.projectTags.length > 0 && (
                  <div>
                    <p className="text-sm font-medium text-muted-foreground mb-2">Expertise Tags</p>
                    <div className="flex flex-wrap gap-2">
                      {project.projectTags.map((pt) => (
                        <Badge
                          key={pt.tag.id}
                          variant="secondary"
                          className="flex items-center gap-1"
                          style={pt.tag.color ? { backgroundColor: `${pt.tag.color}20`, borderColor: pt.tag.color } : undefined}
                        >
                          {pt.tag.name}
                          {pt.confidence < 1 && (
                            <span className="text-xs opacity-60">
                              {Math.round(pt.confidence * 100)}%
                            </span>
                          )}
                        </Badge>
                      ))}
                    </div>
                  </div>
                )}

                {/* Simple Tags (legacy) */}
                {project.tags && project.tags.length > 0 && (
                  <div>
                    <p className="text-sm font-medium text-muted-foreground mb-2">Tags</p>
                    <div className="flex flex-wrap gap-2">
                      {project.tags.map((tag: string) => (
                        <Badge key={tag} variant="secondary">{tag}</Badge>
                      ))}
                    </div>
                  </div>
                )}

                {/* Internal Info */}
                {(project.internalComments || project.applicationStatus || project.referralSource) && (
                  <div className="border-t pt-4 mt-4">
                    <p className="text-sm font-medium text-muted-foreground mb-3">Internal Notes</p>
                    <div className="grid gap-3 sm:grid-cols-2">
                      {project.applicationStatus && (
                        <div>
                          <p className="text-xs text-muted-foreground">Application Status</p>
                          <p className="text-sm">{project.applicationStatus}</p>
                        </div>
                      )}
                      {project.referralSource && (
                        <div>
                          <p className="text-xs text-muted-foreground">Referral Source</p>
                          <p className="text-sm">{project.referralSource}</p>
                        </div>
                      )}
                    </div>
                    {project.internalComments && (
                      <div className="mt-3">
                        <p className="text-xs text-muted-foreground">Comments</p>
                        <p className="text-sm whitespace-pre-wrap">{project.internalComments}</p>
                      </div>
                    )}
                  </div>
                )}

                <div className="flex flex-wrap gap-6 text-sm pt-2">
                  <div>
                    <span className="text-muted-foreground">Created:</span>{' '}
                    {formatDateOnly(project.createdAt)}
                  </div>
                  <div>
                    <span className="text-muted-foreground">Updated:</span>{' '}
                    {formatDateOnly(project.updatedAt)}
                  </div>
                </div>
              </CardContent>
            </Card>
          </AnimatedCard>

          {/* Round History */}
          {competitionRounds.length > 0 && (() => {
            // Find the furthest round index where the project is active or beyond
            // Any round before this must have been passed
            let furthestActiveIdx = -1
            for (let i = competitionRounds.length - 1; i >= 0; i--) {
              const s = roundStateMap.get(competitionRounds[i].id)
              if (s && (s.state === 'IN_PROGRESS' || s.state === 'PASSED' || s.state === 'COMPLETED')) {
                furthestActiveIdx = i
                break
              }
            }

            // Find the rejection round — either explicit REJECTED state or inferred
            const isProjectRejected = project.status === 'REJECTED'
            const explicitRejectedRound = competitionRounds.find((r) => {
              const s = roundStateMap.get(r.id)
              return s?.state === 'REJECTED'
            })

            // If project is globally rejected but no round has explicit REJECTED state,
            // infer the rejection round as the furthest round the project reached
            let inferredRejectionRoundId: string | null = null
            if (isProjectRejected && !explicitRejectedRound) {
              for (let i = competitionRounds.length - 1; i >= 0; i--) {
                const s = roundStateMap.get(competitionRounds[i].id)
                if (s) {
                  if (s.state === 'PASSED' || s.state === 'COMPLETED') {
                    if (i + 1 < competitionRounds.length) {
                      inferredRejectionRoundId = competitionRounds[i + 1].id
                    }
                  } else {
                    inferredRejectionRoundId = competitionRounds[i].id
                  }
                  break
                }
              }
            }

            const rejectedRound = explicitRejectedRound
              ?? (inferredRejectionRoundId
                ? competitionRounds.find((r) => r.id === inferredRejectionRoundId)
                : null)

            const rejectedRoundIdx = rejectedRound
              ? competitionRounds.findIndex((r) => r.id === rejectedRound.id)
              : -1

            // Compute effective states for all rounds
            const effectiveStates = competitionRounds.map((round, idx) => {
              const rawState = roundStateMap.get(round.id)?.state
              const isRejectionRound = round.id === rejectedRound?.id
              const isNotReached = rejectedRoundIdx >= 0 && idx > rejectedRoundIdx

              if (isRejectionRound && !explicitRejectedRound) return 'REJECTED'
              if (isNotReached) return 'NOT_REACHED'
              // If this round is before the furthest active round and not already PASSED/COMPLETED,
              // the project must have passed it to reach the later round
              if (furthestActiveIdx > idx && (!rawState || rawState === 'PENDING')) return 'PASSED'
              return rawState
            })

            const passedCount = effectiveStates.filter(
              (s) => s === 'PASSED' || s === 'COMPLETED',
            ).length

            return (
              <AnimatedCard index={3}>
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2.5 text-lg">
                      <div className="rounded-lg bg-violet-500/10 p-1.5">
                        <Calendar className="h-4 w-4 text-violet-500" />
                      </div>
                      Round History
                    </CardTitle>
                    <CardDescription>
                      {rejectedRound
                        ? `Rejected at ${rejectedRound.name}`
                        : `Passed ${passedCount} of ${competitionRounds.length} rounds`}
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <ol className="relative">
                      {competitionRounds.map((round, idx) => {
                        const effectiveState = effectiveStates[idx]
                        const isLast = idx === competitionRounds.length - 1

                        const roundAssignments = assignments.filter(
                          (a) => a.roundId === round.id,
                        )

                        let icon: React.ReactNode
                        let statusLabel: string | null = null
                        let labelClass = 'text-muted-foreground'

                        if (effectiveState === 'PASSED' || effectiveState === 'COMPLETED') {
                          icon = <CheckCircle2 className="h-5 w-5 shrink-0 text-emerald-500" />
                          statusLabel = 'Passed'
                        } else if (effectiveState === 'REJECTED') {
                          icon = <XCircle className="h-5 w-5 shrink-0 text-red-500" />
                          statusLabel = 'Rejected at this round'
                          labelClass = 'text-red-600 font-medium'
                        } else if (effectiveState === 'IN_PROGRESS') {
                          icon = (
                            <span className="flex h-5 w-5 shrink-0 items-center justify-center">
                              <span className="relative flex h-3 w-3">
                                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-blue-400 opacity-75" />
                                <span className="relative inline-flex h-3 w-3 rounded-full bg-blue-500" />
                              </span>
                            </span>
                          )
                          statusLabel = 'Active'
                        } else if (effectiveState === 'NOT_REACHED') {
                          icon = <Circle className="h-5 w-5 shrink-0 text-muted-foreground/15" />
                          statusLabel = 'Not reached'
                          labelClass = 'text-muted-foreground/50 italic'
                        } else if (effectiveState === 'PENDING') {
                          icon = <Circle className="h-5 w-5 shrink-0 text-muted-foreground/40" />
                          statusLabel = 'Pending'
                        } else {
                          icon = <Circle className="h-5 w-5 shrink-0 text-muted-foreground/20" />
                        }

                        return (
                          <li key={round.id} className={cn(
                            'relative flex items-start gap-3 pb-6',
                            isLast && 'pb-0',
                            effectiveState === 'NOT_REACHED' && 'opacity-50',
                          )}>
                            {/* Connector line */}
                            {!isLast && (
                              <span
                                className="absolute left-[9px] top-6 h-[calc(100%-8px)] w-px bg-border"
                                aria-hidden="true"
                              />
                            )}
                            <span className="relative z-10 flex items-center justify-center">
                              {icon}
                            </span>
                            <div className="min-w-0 flex-1">
                              <p className={cn(
                                'text-sm font-medium',
                                effectiveState === 'NOT_REACHED' && 'text-muted-foreground',
                              )}>{round.name}</p>
                              {statusLabel && (
                                <p className={cn('text-xs', labelClass)}>
                                  {statusLabel}
                                </p>
                              )}
                              {roundAssignments.length > 0 && (
                                <p className="text-xs text-muted-foreground">
                                  {roundAssignments.filter((a) => a.evaluation?.status === 'SUBMITTED').length}/{roundAssignments.length} evaluations
                                </p>
                              )}
                            </div>
                            {effectiveState === 'IN_PROGRESS' && (
                              <Badge
                                variant="outline"
                                className="ml-auto shrink-0 border-blue-200 bg-blue-50 text-blue-600 text-xs"
                              >
                                Active
                              </Badge>
                            )}
                            {effectiveState === 'REJECTED' && (
                              <Badge
                                variant="destructive"
                                className="ml-auto shrink-0 text-xs"
                              >
                                Rejected
                              </Badge>
                            )}
                          </li>
                        )
                      })}
                    </ol>
                  </CardContent>
                </Card>
              </AnimatedCard>
            )
          })()}
        </TabsContent>

        {/* ── Evaluations Tab ── */}
        <TabsContent value="evaluations" className="mt-6 space-y-4">
          {assignments.length === 0 ? (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-12 text-center">
                <Users className="h-10 w-10 text-muted-foreground/40" />
                <p className="mt-2 text-sm text-muted-foreground">
                  {project.status === 'ASSIGNED'
                    ? 'Awaiting jury evaluation — assigned and pending review'
                    : 'No jury assignments yet'}
                </p>
              </CardContent>
            </Card>
          ) : (
            assignments.map((assignment) => {
              const ev = assignment.evaluation
              const isSubmitted = ev?.status === 'SUBMITTED'
              const criterionScores = (ev?.criterionScoresJson || {}) as Record<
                string,
                number | boolean | string
              >

              return (
                <AnimatedCard key={assignment.id} index={0}>
                  <Card>
                    <CardHeader className="pb-3">
                      <div className="flex items-center justify-between gap-3 flex-wrap">
                        <div className="flex items-center gap-3">
                          <UserAvatar
                            user={assignment.user}
                            avatarUrl={assignment.user.avatarUrl}
                            size="md"
                          />
                          <div>
                            <p className="text-sm font-semibold">
                              {assignment.user.name || 'Unnamed'}
                            </p>
                            <div className="flex items-center gap-2 mt-0.5">
                              <Badge
                                variant="outline"
                                className="text-xs whitespace-nowrap"
                              >
                                {assignment.round.name}
                              </Badge>
                              {isSubmitted && ev.submittedAt && (
                                <span className="text-xs text-muted-foreground">
                                  {formatDate(ev.submittedAt)}
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                        {isSubmitted && ev.globalScore != null && (
                          <div className="flex items-center gap-2">
                            <Badge className="bg-brand-teal text-white text-base px-3 py-1 font-bold">
                              {ev.globalScore}/10
                            </Badge>
                          </div>
                        )}
                      </div>
                    </CardHeader>

                    {isSubmitted && ev ? (
                      <CardContent className="space-y-4">
                        {/* Criterion scores */}
                        {Object.keys(criterionScores).length > 0 && (
                          <div className="space-y-2.5">
                            {Object.entries(criterionScores).map(
                              ([key, value]) => {
                                const meta = criteriaMap.get(key)
                                const label = meta?.label || key
                                const type =
                                  meta?.type ||
                                  (typeof value === 'boolean'
                                    ? 'boolean'
                                    : typeof value === 'string'
                                      ? 'text'
                                      : 'numeric')

                                if (type === 'section_header') return null

                                if (type === 'boolean' || type === 'advance') {
                                  return (
                                    <div
                                      key={key}
                                      className="flex items-center justify-between rounded-lg border p-2.5"
                                    >
                                      <span className="text-sm">{label}</span>
                                      {value === true ? (
                                        <Badge
                                          className="border-emerald-200 bg-emerald-100 text-emerald-700"
                                          variant="outline"
                                        >
                                          <ThumbsUp className="mr-1 h-3 w-3" />
                                          {meta?.trueLabel || 'Yes'}
                                        </Badge>
                                      ) : (
                                        <Badge
                                          className="border-red-200 bg-red-100 text-red-700"
                                          variant="outline"
                                        >
                                          <ThumbsDown className="mr-1 h-3 w-3" />
                                          {meta?.falseLabel || 'No'}
                                        </Badge>
                                      )}
                                    </div>
                                  )
                                }

                                if (type === 'text') {
                                  return (
                                    <div key={key} className="space-y-1">
                                      <p className="text-sm font-medium">
                                        {label}
                                      </p>
                                      <div className="whitespace-pre-wrap rounded-lg border bg-muted/50 p-2.5 text-sm text-muted-foreground">
                                        {typeof value === 'string'
                                          ? value
                                          : String(value)}
                                      </div>
                                    </div>
                                  )
                                }

                                // Numeric
                                return (
                                  <div
                                    key={key}
                                    className="flex items-center gap-3 rounded-lg border p-2.5"
                                  >
                                    <span className="flex-1 truncate text-sm">
                                      {label}
                                    </span>
                                    <div className="flex shrink-0 items-center gap-2">
                                      <Progress
                                        value={
                                          typeof value === 'number'
                                            ? (value / 10) * 100
                                            : 0
                                        }
                                        className="h-1.5 w-20"
                                      />
                                      <span className="w-8 text-right text-sm font-bold tabular-nums">
                                        {typeof value === 'number' ? value : '-'}
                                      </span>
                                    </div>
                                  </div>
                                )
                              },
                            )}
                          </div>
                        )}

                        {/* Feedback */}
                        {ev.feedbackText && (
                          <div>
                            <p className="mb-1.5 flex items-center gap-1.5 text-sm font-medium">
                              <MessageSquare className="h-4 w-4" />
                              Feedback
                            </p>
                            <div className="whitespace-pre-wrap rounded-lg border bg-muted/30 p-3 text-sm leading-relaxed text-muted-foreground">
                              {ev.feedbackText}
                            </div>
                          </div>
                        )}

                        {/* Binary decision */}
                        {ev.binaryDecision != null && (
                          <div className="flex items-center gap-2">
                            {ev.binaryDecision ? (
                              <div className="flex items-center gap-1.5 text-emerald-600 font-medium text-sm">
                                <ThumbsUp className="h-4 w-4" />
                                Recommended
                              </div>
                            ) : (
                              <div className="flex items-center gap-1.5 text-red-600 font-medium text-sm">
                                <ThumbsDown className="h-4 w-4" />
                                Not recommended
                              </div>
                            )}
                          </div>
                        )}
                      </CardContent>
                    ) : (
                      <CardContent>
                        <div className="flex items-center gap-2 text-sm text-muted-foreground">
                          <Clock className="h-4 w-4" />
                          Evaluation pending
                        </div>
                      </CardContent>
                    )}
                  </Card>
                </AnimatedCard>
              )
            })
          )}
        </TabsContent>

        {/* ── Team Tab ── */}
        {flags?.observerShowTeamTab && project.teamMembers.length > 0 && (
          <TabsContent value="team" className="mt-6">
            <AnimatedCard index={0}>
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2.5 text-lg">
                    <div className="rounded-lg bg-indigo-500/10 p-1.5">
                      <Users className="h-4 w-4 text-indigo-500" />
                    </div>
                    Team Members
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {project.teamMembers.map((member) => (
                      <div key={member.userId} className="flex items-center gap-3 rounded-lg border p-3">
                        <UserAvatar
                          user={member.user}
                          avatarUrl={(member.user as { avatarUrl?: string | null }).avatarUrl}
                          size="md"
                        />
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-semibold truncate">
                            {member.user.name || 'Unnamed'}
                          </p>
                          <p className="text-xs text-muted-foreground truncate">
                            {member.user.email}
                          </p>
                        </div>
                        <Badge variant="outline" className="shrink-0 text-xs">
                          {member.role === 'LEAD' ? 'Lead' : member.role === 'ADVISOR' ? 'Advisor' : 'Member'}
                        </Badge>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </AnimatedCard>
          </TabsContent>
        )}

        {/* ── Files Tab ── */}
        <TabsContent value="files" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2.5 text-lg">
                <div className="rounded-lg bg-rose-500/10 p-1.5">
                  <FileText className="h-4 w-4 text-rose-500" />
                </div>
                Project Files
              </CardTitle>
            </CardHeader>
            <CardContent>
              {project.files && project.files.length > 0 ? (() => {
                // Group files by round
                type FileItem = (typeof project.files)[number]
                const roundMap = new Map<string, { roundId: string | null; roundName: string; sortOrder: number; files: FileItem[] }>()
                // Build roundId→round lookup from competitionRounds
                const roundLookup = new Map(competitionRounds.map((r, idx) => [r.id, { name: r.name, sortOrder: idx }]))
                for (const f of project.files) {
                  const key = f.roundId ?? '__none__'
                  if (!roundMap.has(key)) {
                    const round = f.roundId ? roundLookup.get(f.roundId) : null
                    roundMap.set(key, {
                      roundId: f.roundId ?? null,
                      roundName: round?.name ?? 'Other Files',
                      sortOrder: round?.sortOrder ?? 999,
                      files: [],
                    })
                  }
                  roundMap.get(key)!.files.push(f)
                }
                const groups = Array.from(roundMap.values()).sort((a, b) => a.sortOrder - b.sortOrder)

                return (
                  <FileViewer
                    projectId={projectId}
                    groupedFiles={groups.map((g) => ({
                      roundId: g.roundId,
                      roundName: g.roundName,
                      sortOrder: g.sortOrder,
                      files: g.files.map((f) => ({
                        id: f.id,
                        fileName: f.fileName,
                        fileType: f.fileType as
                          | 'EXEC_SUMMARY'
                          | 'PRESENTATION'
                          | 'VIDEO'
                          | 'OTHER'
                          | 'BUSINESS_PLAN'
                          | 'VIDEO_PITCH'
                          | 'SUPPORTING_DOC',
                        mimeType: f.mimeType,
                        size: f.size,
                        bucket: f.bucket,
                        objectKey: f.objectKey,
                        pageCount: f.pageCount,
                        textPreview: f.textPreview,
                        detectedLang: f.detectedLang,
                        langConfidence: f.langConfidence,
                        analyzedAt: f.analyzedAt ? String(f.analyzedAt) : null,
                        requirementId: f.requirementId,
                        requirement: f.requirement
                          ? {
                              id: f.requirement.id,
                              name: f.requirement.name,
                              description: f.requirement.description,
                              isRequired: f.requirement.isRequired,
                            }
                          : null,
                      })),
                    }))}
                  />
                )
              })() : (
                <div className="flex flex-col items-center justify-center py-8 text-center">
                  <FileText className="h-12 w-12 text-muted-foreground/50" />
                  <p className="mt-2 text-sm text-muted-foreground">
                    No files uploaded yet
                  </p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}

function ProjectDetailSkeleton() {
  return (
    <div className="space-y-6">
      <div className="flex items-center gap-2">
        <Skeleton className="h-4 w-16" />
        <Skeleton className="h-4 w-2" />
        <Skeleton className="h-4 w-16" />
        <Skeleton className="h-4 w-2" />
        <Skeleton className="h-4 w-32" />
      </div>
      <div className="flex items-start justify-between gap-4">
        <div className="flex items-start gap-4">
          <Skeleton className="h-16 w-16 rounded-lg" />
          <div className="space-y-2">
            <Skeleton className="h-8 w-64" />
            <Skeleton className="h-4 w-40" />
            <div className="flex gap-2">
              <Skeleton className="h-5 w-20" />
              <Skeleton className="h-5 w-24" />
              <Skeleton className="h-5 w-16" />
            </div>
          </div>
        </div>
        <Skeleton className="h-32 w-48 rounded-lg" />
      </div>
      <Skeleton className="h-px w-full" />
      <div className="flex gap-2">
        <Skeleton className="h-9 w-24" />
        <Skeleton className="h-9 w-28" />
        <Skeleton className="h-9 w-16" />
      </div>
      <Card>
        <CardHeader>
          <Skeleton className="h-5 w-40" />
        </CardHeader>
        <CardContent>
          <Skeleton className="h-32 w-full" />
        </CardContent>
      </Card>
    </div>
  )
}
