<template>
  <Modal
    :open="open"
    size="xl"
    title="Unterkategorien konfigurieren"
    subtitle="Diese Viewer-Sektionen gelten für alle Hauptkategorien der ausgewählten Season."
    @close="$emit('close')"
  >
    <div class="grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(320px,0.72fr)]">
      <section class="space-y-4">
        <div class="flex items-center justify-between gap-3">
          <div>
            <p class="text-sm font-semibold text-slate-900">Globale Unterkategorien</p>
            <p class="text-sm text-slate-500">Die Hauptkategorien müssen sie nicht einzeln anlegen.</p>
          </div>
          <Button class="gap-2" @click="$emit('add-subcategory')">
            <PlusCircle class="h-4 w-4" />
            Unterkategorie
          </Button>
        </div>

        <div v-if="subcategories.length > 0" class="grid gap-3">
          <article
            v-for="(subcategory, index) in subcategories"
            :key="`${subcategory.slug}-${index}`"
            class="rounded-2xl border border-violet-100 bg-white px-4 py-4"
          >
            <div class="flex items-start justify-between gap-3">
              <div class="min-w-0">
                <div class="flex flex-wrap items-center gap-2">
                  <h3 class="text-base font-bold text-slate-900">{{ subcategory.name || 'Neue Unterkategorie' }}</h3>
                  <span class="rounded-full bg-violet-50 px-2.5 py-1 text-[11px] font-semibold text-violet-700">
                    {{ formatViewerRange(subcategory.viewerRangeMin, subcategory.viewerRangeMax) }}
                  </span>
                </div>
                <p class="mt-1 font-mono text-xs text-slate-400">/{{ subcategory.slug || 'slug-fehlt' }}</p>
              </div>

              <div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
                <span class="rounded-full bg-slate-100 px-2.5 py-1 text-[11px] font-semibold text-slate-600">
                  #{{ subcategory.sortOrder }}
                </span>
                <Button variant="ghost" size="sm" class="gap-2" @click="$emit('edit-subcategory', index)">
                  <Pencil class="h-4 w-4" />
                  Bearbeiten
                </Button>
                <Button variant="ghost" size="sm" class="gap-2 border-rose-200 bg-rose-50 text-rose-600 hover:bg-rose-100" @click="$emit('remove-subcategory', index)">
                  <Trash2 class="h-4 w-4" />
                  Entfernen
                </Button>
              </div>
            </div>
          </article>
        </div>

        <div v-else class="rounded-2xl border border-dashed border-violet-200 bg-violet-50/40 px-4 py-8 text-center text-sm text-slate-500">
          Noch keine Unterkategorien vorhanden.
        </div>
      </section>

      <aside class="rounded-2xl border border-violet-100 bg-violet-50/50 p-4">
        <div v-if="editorOpen" class="space-y-4">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.18em] text-violet-500">{{ editorTitle }}</p>
            <p class="mt-1 text-sm text-slate-500">Aenderungen werden erst mit der gesamten Unterkategorien-Konfiguration gespeichert.</p>
          </div>

          <label class="block space-y-2">
            <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Name</span>
            <input
              :value="form.name"
              type="text"
              class="h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100"
              placeholder="z. B. Rising Star"
              @input="form.name = ($event.target as HTMLInputElement).value"
            />
          </label>

          <label class="block space-y-2">
            <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Slug</span>
            <div class="flex gap-2">
              <input
                :value="form.slug"
                type="text"
                class="h-12 min-w-0 flex-1 rounded-2xl border border-violet-200 bg-white px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100"
                placeholder="rising-star"
                @input="form.slug = ($event.target as HTMLInputElement).value"
              />
              <Button variant="ghost" class="border border-violet-200 bg-white text-violet-700 hover:bg-violet-50" @click="$emit('fill-slug')">
                Auto
              </Button>
            </div>
          </label>

          <div class="grid gap-3 sm:grid-cols-2">
            <label class="space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Viewer von</span>
              <input
                :value="form.viewerRangeMin ?? ''"
                type="number"
                min="0"
                class="h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100"
                placeholder="0"
                @input="form.viewerRangeMin = toNullableNumber(($event.target as HTMLInputElement).value)"
              />
            </label>

            <label class="space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Viewer bis</span>
              <input
                :value="form.viewerRangeMax ?? ''"
                type="number"
                min="0"
                class="h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100"
                placeholder="offen"
                @input="form.viewerRangeMax = toNullableNumber(($event.target as HTMLInputElement).value)"
              />
            </label>
          </div>

          <label class="block space-y-2">
            <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Reihenfolge</span>
            <input
              :value="form.sortOrder"
              type="number"
              min="1"
              class="h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100"
              @input="form.sortOrder = Math.max(1, Number(($event.target as HTMLInputElement).value) || 1)"
            />
          </label>

          <div class="flex justify-end gap-2">
            <Button variant="ghost" @click="$emit('close-editor')">Abbrechen</Button>
            <Button :disabled="!canSaveSubcategory" @click="$emit('save-subcategory')">
              Unterkategorie uebernehmen
            </Button>
          </div>
        </div>

        <div v-else class="flex min-h-64 flex-col items-center justify-center rounded-2xl border border-dashed border-violet-200 bg-white/60 px-4 py-8 text-center">
          <Layers3 class="h-8 w-8 text-violet-300" />
          <p class="mt-3 font-semibold text-slate-700">Unterkategorie auswählen</p>
          <p class="mt-1 text-sm leading-6 text-slate-500">Bearbeite eine bestehende Sektion oder lege eine neue Viewer-Sektion an.</p>
        </div>
      </aside>
    </div>

    <template #footer>
      <Button variant="ghost" @click="$emit('close')">Abbrechen</Button>
      <Button :disabled="!canSave || saving" @click="$emit('save')">
        {{ saving ? 'Speichert ...' : 'Unterkategorien speichern' }}
      </Button>
    </template>
  </Modal>
</template>

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

import Button from '../ui/Button.vue'
import Modal from '../ui/Modal.vue'
import type { AdminSubcategoryDraft } from './useAdminCategoryManager'
import { formatViewerRange } from './useAdminCategoryManager'

defineProps<{
  open: boolean
  subcategories: AdminSubcategoryDraft[]
  canSave: boolean
  saving: boolean
  editorOpen: boolean
  editorTitle: string
  form: AdminSubcategoryDraft
  canSaveSubcategory: boolean
}>()

defineEmits<{
  close: []
  save: []
  'add-subcategory': []
  'edit-subcategory': [index: number]
  'remove-subcategory': [index: number]
  'close-editor': []
  'save-subcategory': []
  'fill-slug': []
}>()

function toNullableNumber(value: string) {
  const trimmed = value.trim()
  if (!trimmed) return null
  const number = Number(trimmed)
  return Number.isFinite(number) ? number : null
}
</script>
