<template>
  <div>
    <div class="hidden grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)_130px_minmax(0,1.2fr)_110px_96px] gap-4 border-b border-violet-100 bg-violet-50/40 px-6 py-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-violet-500 xl:grid">
      <span>Kandidat</span>
      <span>Kategorie</span>
      <span>Annahme</span>
      <span>Clip-Compilation</span>
      <span>Plattform</span>
      <span class="text-right">Aktionen</span>
    </div>

    <div class="divide-y divide-violet-50">
      <div
        v-for="candidate in pagedCandidates"
        :key="candidate.id"
        class="grid grid-cols-1 gap-3 px-6 py-4 transition hover:bg-violet-50/40 xl:grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)_130px_minmax(0,1.2fr)_110px_96px] xl:items-center xl:gap-4"
      >
        <div class="flex min-w-0 items-center gap-3">
          <span class="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-[linear-gradient(135deg,#c4b5fd,#f5a9d6)] text-sm font-semibold text-white">
            {{ candidate.displayName.charAt(0) }}
          </span>
          <div class="min-w-0">
            <p class="truncate font-semibold text-slate-800">{{ candidate.displayName }}</p>
            <p class="truncate text-xs text-slate-500">{{ candidate.channelSlug }}</p>
            <p class="mt-1 text-xs text-slate-500">
              {{ avgViewerLabel(candidate.avgViewers) }}
              · {{ candidate.nominationTally.toLocaleString('de-DE') }} {{ candidate.nominationTally === 1 ? 'Nominierung' : 'Nominierungen' }}
              · {{ candidate.votes.toLocaleString('de-DE') }} {{ candidate.votes === 1 ? 'Vote' : 'Votes' }}
            </p>
            <p v-if="isDuplicate(candidate)" class="mt-1 text-xs font-semibold text-amber-700">
              Mögliches Duplikat in dieser Kategorie
            </p>
            <p
              v-for="notice in candidateWorkflowNotices[candidate.id] ?? []"
              :key="notice.message"
              class="mt-1 text-xs font-semibold"
              :class="notice.mode === 'block' ? 'text-rose-700' : 'text-amber-700'"
            >
              {{ notice.mode === 'block' ? 'Regel blockiert' : 'Regelhinweis' }}: {{ notice.message }}
            </p>
          </div>
        </div>
        <div class="min-w-0">
          <span class="inline-block max-w-full truncate rounded-full border border-violet-100 bg-violet-50/70 px-3 py-1 text-xs font-semibold text-violet-700">
            {{ categoryLabelMap[candidate.categoryId] || 'Ohne Kategorie' }}
          </span>
        </div>
        <div>
          <span class="inline-flex rounded-full border px-3 py-1 text-xs font-semibold" :class="acceptanceClass(candidate.acceptanceStatus)">
            {{ acceptanceLabel(candidate.acceptanceStatus) }}
          </span>
          <p v-if="candidate.acceptanceNote" class="mt-1 line-clamp-2 text-xs text-slate-500">{{ candidate.acceptanceNote }}</p>
        </div>
        <div class="min-w-0">
          <template v-if="candidate.clipCompilationUrl && candidate.clipEmbedStatus !== 'blocked'">
            <a
              :href="candidate.clipCompilationUrl"
              target="_blank"
              rel="noopener noreferrer"
              class="inline-flex max-w-full items-center gap-1 truncate text-sm font-semibold text-violet-700 hover:text-violet-900"
            >
              <ExternalLink class="h-3.5 w-3.5 shrink-0" />
              <span class="truncate">{{ candidate.clipCompilationTitle || 'Compilation öffnen' }}</span>
            </a>
            <p class="mt-1 text-xs text-slate-500">
              {{ candidate.clipCompilationPlatform || 'Plattform offen' }} · {{ embedLabel(candidate.clipEmbedStatus) }}
            </p>
          </template>
          <p v-else class="text-xs font-semibold text-amber-700">
            {{ candidate.clipEmbedStatus === 'blocked' ? 'Clip nicht nutzbar' : 'Clip fehlt' }}
          </p>
        </div>
        <div>
          <span class="rounded-full border border-amber-200 bg-amber-50 px-3 py-1 text-xs font-semibold text-amber-700">{{ candidate.platform }}</span>
        </div>
        <div class="flex gap-2 lg:justify-end">
          <button
            class="grid h-9 w-9 place-items-center rounded-full border border-violet-200 text-violet-600 transition hover:bg-violet-50"
            title="Bearbeiten"
            @click="$emit('edit', candidate)"
          >
            <Pencil class="h-4 w-4" />
          </button>
          <button
            class="grid h-9 w-9 place-items-center rounded-full border border-rose-200 text-rose-500 transition hover:bg-rose-50"
            title="Löschen"
            @click="$emit('delete', candidate)"
          >
            <Trash2 class="h-4 w-4" />
          </button>
        </div>
      </div>

      <div v-if="filteredCount === 0" class="px-6 py-12 text-center">
        <p class="text-sm text-slate-500">
          {{ totalCount === 0 ? 'Noch keine Kandidaten in diesem Jahr.' : 'Keine Treffer für den aktuellen Filter.' }}
        </p>
        <Button class="mt-4 gap-2" @click="$emit('open-create')"><UserPlus class="h-4 w-4" /> Ersten Kandidaten anlegen</Button>
      </div>
    </div>

    <PaginationFooter
      :page="page"
      :total-pages="totalPages"
      :range-start="rangeStart"
      :range-end="rangeEnd"
      :filtered-count="filteredCount"
      @update:page="$emit('update:page', $event)"
    />
  </div>
</template>

<script setup lang="ts">
import { ExternalLink, Pencil, Trash2, UserPlus } from '@lucide/vue'

import type { AdminCandidateItem } from '../../types/awards'
import Button from '../ui/Button.vue'
import PaginationFooter from '../ui/PaginationFooter.vue'

const props = defineProps<{
  pagedCandidates: AdminCandidateItem[]
  totalCount: number
  filteredCount: number
  page: number
  totalPages: number
  rangeStart: number
  rangeEnd: number
  categoryLabelMap: Record<number, string>
  duplicateCandidateKeys: Map<string, number>
  candidateWorkflowNotices: Record<number, Array<{ mode: 'warn' | 'block'; message: string }>>
  acceptanceStatusOptions: Array<{ label: string; value: string; description: string }>
}>()

defineEmits<{
  edit: [candidate: AdminCandidateItem]
  delete: [candidate: AdminCandidateItem]
  'update:page': [page: number]
  'open-create': []
}>()

function isDuplicate(candidate: AdminCandidateItem) {
  return (props.duplicateCandidateKeys.get(`${candidate.categoryId}:name:${candidate.displayName.trim().toLowerCase()}`) ?? 0) > 1
    || (props.duplicateCandidateKeys.get(`${candidate.categoryId}:slug:${candidate.channelSlug.trim().toLowerCase()}`) ?? 0) > 1
}

function acceptanceLabel(value: string) {
  return props.acceptanceStatusOptions.find((option) => option.value === value)?.label ?? 'Offen'
}

function acceptanceClass(value: string) {
  if (value === 'accepted') return 'border-emerald-200 bg-emerald-50 text-emerald-700'
  if (value === 'contacted') return 'border-sky-200 bg-sky-50 text-sky-700'
  if (value === 'declined') return 'border-rose-200 bg-rose-50 text-rose-700'
  return 'border-slate-200 bg-slate-50 text-slate-600'
}

function embedLabel(value: string) {
  if (value === 'embeddable') return 'Einbettbar'
  if (value === 'link_only') return 'Nur Link'
  if (value === 'blocked') return 'Nicht nutzbar'
  return 'Embed prüfen'
}

function avgViewerLabel(value: number | null) {
  return value != null
    ? `Ø ${value.toLocaleString('de-DE')} Viewer`
    : 'Tracker offen'
}
</script>
