<script setup lang="ts">
import { Save, Settings2 } from '@lucide/vue'
import { computed } from 'vue'

import AdminPageHeader from '../../components/admin/AdminPageHeader.vue'
import AdminSettingsToggle from '../../components/admin/AdminSettingsToggle.vue'
import { useAdminTrackingRules } from '../../components/admin/useAdminTrackingRules'
import { watchAdminToast } from '../../composables/useAdminToast'
import Button from '../../components/ui/Button.vue'
import Card from '../../components/ui/Card.vue'
import NativeSelect from '../../components/ui/NativeSelect.vue'
import { useAuthStore } from '../../stores/auth'
import type { AdminTrackingMetricRule } from '../../types/awards'

const authStore = useAuthStore()
const canManageTrackingRules = computed(() => authStore.hasPermission('settings'))
const windowOptions = [
  { label: '7 Tage', value: '7d' },
  { label: '30 Tage', value: '30d' },
  { label: '3 Monate', value: '90d' },
  { label: 'All Time', value: 'all_time' },
]

const {
  trackingLoading,
  rulesSaving,
  sourceSaving,
  notesSaving,
  trackingError,
  trackingSuccess,
  trackingSource,
  importantMetrics,
  optionalMetrics,
  trackingFlags,
  manualReviewNotes,
  trackingSummary,
  hasUnsavedTrackingSourceChanges,
  hasUnsavedTrackingRuleChanges,
  hasUnsavedTrackingNotesChanges,
  updateImportantMetric,
  updateOptionalMetric,
  updateTrackingFlag,
  saveTrackingSource,
  saveTrackingNotes,
  saveTrackingRules,
} = useAdminTrackingRules()

watchAdminToast(trackingSuccess, trackingError)

const activeImportantMetrics = computed(() => importantMetrics.value.filter((rule) => rule.enabled))
const disabledImportantMetrics = computed(() => importantMetrics.value.filter((rule) => !rule.enabled))
const activeOptionalMetrics = computed(() => optionalMetrics.value.filter((rule) => rule.enabled))
const disabledOptionalMetrics = computed(() => optionalMetrics.value.filter((rule) => !rule.enabled))

function sourceSupportLabel(sourceSupport: string) {
  return sourceSupport === 'auto' ? 'Auto' : sourceSupport === 'manual' ? 'Manuell' : 'Kontext'
}

function sourceSupportClass(sourceSupport: string) {
  return sourceSupport === 'auto'
    ? 'bg-emerald-50 text-emerald-700 border-emerald-200'
    : sourceSupport === 'manual'
      ? 'bg-amber-50 text-amber-700 border-amber-200'
      : 'bg-slate-100 text-slate-700 border-slate-200'
}

function windowSupportText(rule: AdminTrackingMetricRule) {
  if (rule.sourceSupport !== 'auto') {
    return 'Diese Metrik ist nur Review-Kontext und wird nicht automatisch von TwitchTracker befuellt.'
  }

  if (rule.autoSupportedWindowKeys.includes(rule.windowKey)) {
    return 'Dieses Zeitfenster wird von der TwitchTracker API automatisch geliefert.'
  }

  const labels = rule.autoSupportedWindowKeys
    .map((value) => windowOptions.find((item) => item.value === value)?.label ?? value)
    .join(', ')

  return `Dieses Zeitfenster ist aktuell nicht automatisch verfügbar. Auto geht nur für: ${labels || 'keine Zeitfenster'}.`
}

function effectSummary(rule: AdminTrackingMetricRule, section: 'important' | 'optional') {
  const parts: string[] = []
  if (section === 'important' && rule.requiredForAutoClassification) {
    parts.push('Fehlt diese Metrik, kann die Nominierung automatisch geflaggt werden.')
  }

  if (rule.showInReview) {
    parts.push('Die Metrik wird im Nominierungsreview sichtbar.')
  } else {
    parts.push('Die Metrik wird im Nominierungsreview nicht angezeigt.')
  }

  if (rule.sourceSupport === 'auto') {
    parts.push('Werte kommen direkt aus TwitchTracker, sofern das Zeitfenster unterstützt wird.')
  } else if (rule.sourceSupport === 'manual') {
    parts.push('Diese Metrik ist für manuelle Pflege gedacht.')
  } else {
    parts.push('Diese Metrik dient nur als Review-Kontext.')
  }

  return parts
}

function isTopCategoriesRule(rule: AdminTrackingMetricRule) {
  return rule.key === 'top_categories_context'
}

function ignoredCategoriesValue(rule: AdminTrackingMetricRule) {
  return (rule.ignoredCategories ?? []).join(', ')
}

function updateIgnoredCategories(ruleKey: string, rawValue: string) {
  const ignoredCategories = rawValue
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean)

  updateOptionalMetric(ruleKey, { ignoredCategories })
}

function numericInputValue(event: Event) {
  const value = (event.target as HTMLInputElement | null)?.value?.trim() ?? ''
  if (!value) {
    return null
  }

  const parsed = Number(value)
  return Number.isFinite(parsed) ? parsed : null
}

function updateTopCount(ruleKey: string, event: Event) {
  updateOptionalMetric(ruleKey, { topCount: numericInputValue(event) })
}

function updateMinPrimaryCategorySharePercent(ruleKey: string, event: Event) {
  updateOptionalMetric(ruleKey, { minPrimaryCategorySharePercent: numericInputValue(event) })
}

function updateMinPrimaryCategoryHours(ruleKey: string, event: Event) {
  updateOptionalMetric(ruleKey, { minPrimaryCategoryHours: numericInputValue(event) })
}

function updateMaxDistinctCategoriesBeforeFlag(ruleKey: string, event: Event) {
  updateOptionalMetric(ruleKey, { maxDistinctCategoriesBeforeFlag: numericInputValue(event) })
}

function updateIgnoredCategoriesFromEvent(ruleKey: string, event: Event) {
  updateIgnoredCategories(ruleKey, (event.target as HTMLInputElement | null)?.value ?? '')
}

function activateImportantMetric(ruleKey: string) {
  updateImportantMetric(ruleKey, { enabled: true })
}

function activateOptionalMetric(ruleKey: string) {
  updateOptionalMetric(ruleKey, { enabled: true })
}
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Tracking Rules"
      description="Nur Regeln zeigen, die im Review oder in der Auto-Bewertung wirklich etwas bewirken. Deaktivierte Metriken bleiben aus dem Nominierungsreview komplett raus."
      :icon="Settings2"
    />

    <Card class="overflow-visible">
      <section class="border-b border-violet-100 p-5">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.22em] text-violet-500">Tracking Source</p>
            <h2 class="mt-1 text-xl font-bold text-slate-900">TwitchTracker API-Quelle</h2>
            <p class="mt-2 max-w-3xl text-sm leading-6 text-slate-500">
              Diese Base URL wird für automatische TwitchTracker-Lookups verwendet.
            </p>
          </div>
          <Button class="gap-2" :disabled="trackingLoading || sourceSaving || !hasUnsavedTrackingSourceChanges || !canManageTrackingRules" @click="saveTrackingSource">
            <Save class="h-4 w-4" />
            {{ sourceSaving ? 'Speichert ...' : 'Source speichern' }}
          </Button>
        </div>
      </section>

      <section class="grid gap-4 p-5 lg:grid-cols-[220px_minmax(0,1fr)]">
        <div class="rounded-2xl border border-violet-100 bg-violet-50/50 px-4 py-3">
          <p class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Provider</p>
          <strong class="mt-1 block text-lg text-violet-900">{{ trackingSource.providerLabel }}</strong>
          <p class="mt-1 text-sm text-slate-500">Key: {{ trackingSource.providerKey }}</p>
        </div>

        <label class="space-y-2">
          <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">API Base URL</span>
          <input
            v-model="trackingSource.baseUrl"
            type="url"
            :disabled="!canManageTrackingRules"
            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 disabled:cursor-not-allowed disabled:bg-slate-50"
            placeholder="https://twitchtracker.com/api"
          >
          <p class="text-sm text-amber-700">Erwartet wird die API-Basis, nicht die normale Website-Startseite.</p>
        </label>
      </section>
    </Card>

    <Card class="overflow-visible">
      <section class="border-b border-violet-100 p-5">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.22em] text-violet-500">Manual Review Notes</p>
            <h2 class="mt-1 text-xl font-bold text-slate-900">Admin-Notizen für Fallback-Quellen</h2>
            <p class="mt-2 max-w-3xl text-sm leading-6 text-slate-500">
              Diese Notizen erscheinen im Nominierungsreview als Hilfe für den manuellen Check.
            </p>
          </div>
          <Button class="gap-2" :disabled="trackingLoading || notesSaving || !hasUnsavedTrackingNotesChanges || !canManageTrackingRules" @click="saveTrackingNotes">
            <Save class="h-4 w-4" />
            {{ notesSaving ? 'Speichert ...' : 'Notizen speichern' }}
          </Button>
        </div>
      </section>

      <section class="space-y-4 p-5">
        <div class="rounded-2xl border border-violet-100 bg-violet-50/45 p-4">
          <div class="flex items-center justify-between gap-4">
            <div>
              <p class="text-sm font-semibold text-slate-900">Notizen im Nominierungsreview anzeigen</p>
              <p class="mt-1 text-sm text-slate-500">
                Wenn deaktiviert, bleiben die Admin-Notizen gespeichert, werden im Review aber komplett ausgeblendet.
              </p>
            </div>
            <AdminSettingsToggle
              :model-value="trackingSource.showManualReviewNotesInReview"
              label="Review-Notizen"
              :disabled="!canManageTrackingRules"
              active-label="Sichtbar"
              inactive-label="Versteckt"
              @update:model-value="trackingSource.showManualReviewNotesInReview = $event"
            />
          </div>
        </div>

        <textarea
          v-model="manualReviewNotes"
          rows="10"
          :disabled="!canManageTrackingRules"
          class="w-full rounded-2xl border border-violet-200 bg-white px-4 py-3 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:cursor-not-allowed disabled:bg-slate-50"
          placeholder="- SullyGnome Channel Summary&#10;- manueller Check für Category Fit&#10;- Sonderregeln für kleine Kanäle"
        />
      </section>
    </Card>

    <section class="grid gap-4 md:grid-cols-4">
      <Card class="p-5">
        <p class="text-xs font-semibold uppercase tracking-[0.2em] text-violet-500">Wichtige aktiv</p>
        <strong class="mt-3 block text-3xl text-violet-900">{{ trackingSummary.importantActive }}</strong>
      </Card>
      <Card class="p-5">
        <p class="text-xs font-semibold uppercase tracking-[0.2em] text-violet-500">Optionale aktiv</p>
        <strong class="mt-3 block text-3xl text-violet-900">{{ trackingSummary.optionalActive }}</strong>
      </Card>
      <Card class="p-5">
        <p class="text-xs font-semibold uppercase tracking-[0.2em] text-violet-500">Flags aktiv</p>
        <strong class="mt-3 block text-3xl text-violet-900">{{ trackingSummary.flagsActive }}</strong>
      </Card>
      <Card class="p-5">
        <p class="text-xs font-semibold uppercase tracking-[0.2em] text-violet-500">Manual Review</p>
        <strong class="mt-3 block text-3xl text-violet-900">{{ trackingSummary.manualReviewFlags }}</strong>
      </Card>
    </section>

    <Card class="overflow-visible">
      <section class="border-b border-violet-100 p-5">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <h2 class="text-xl font-bold text-slate-900">Wichtige Metriken</h2>
            <p class="mt-2 text-sm text-slate-500">Diese Regeln wirken direkt auf automatische Flags oder auf die Sichtbarkeit im Nominierungsreview.</p>
          </div>
          <Button class="gap-2" :disabled="trackingLoading || rulesSaving || !hasUnsavedTrackingRuleChanges || !canManageTrackingRules" @click="saveTrackingRules">
            <Save class="h-4 w-4" />
            {{ rulesSaving ? 'Speichert ...' : 'Regeln speichern' }}
          </Button>
        </div>
      </section>

      <section v-if="trackingLoading" class="p-5 text-sm text-slate-500">Tracking Rules werden geladen.</section>
      <section v-else class="space-y-4 p-5">
        <article v-for="rule in activeImportantMetrics" :key="rule.key" class="rounded-2xl border border-violet-100 bg-violet-50/35 p-4">
          <div class="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
            <div class="min-w-0">
              <div class="flex flex-wrap items-center gap-2">
                <h3 class="text-base font-semibold text-slate-900">{{ rule.label }}</h3>
                <span class="rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em]" :class="sourceSupportClass(rule.sourceSupport)">
                  {{ sourceSupportLabel(rule.sourceSupport) }}
                </span>
                <span v-if="rule.requiredForAutoClassification" class="rounded-full border border-rose-200 bg-rose-50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-rose-700">
                  Pflicht für Auto-Check
                </span>
                <span v-if="rule.showInReview" class="rounded-full border border-sky-200 bg-sky-50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-sky-700">
                  Im Review sichtbar
                </span>
              </div>
              <p class="mt-2 text-sm leading-6 text-slate-500">{{ rule.description }}</p>
              <p class="mt-2 text-xs text-amber-700">{{ windowSupportText(rule) }}</p>
            </div>

            <AdminSettingsToggle
              :model-value="rule.enabled"
              :label="`${rule.label} aktiv`"
              :disabled="!canManageTrackingRules"
              active-label="Aktiv"
              inactive-label="Inaktiv"
              @update:model-value="updateImportantMetric(rule.key, { enabled: $event })"
            />
          </div>

          <div class="mt-4 grid gap-3 md:grid-cols-3">
            <label class="space-y-2">
              <span class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Zeitraum</span>
              <NativeSelect
                :model-value="rule.windowKey"
                :disabled="!canManageTrackingRules"
                :options="windowOptions"
                @update:model-value="updateImportantMetric(rule.key, { windowKey: String($event) })"
              />
            </label>
            <AdminSettingsToggle
              :model-value="rule.requiredForAutoClassification"
              :label="`${rule.label} für Auto-Check erzwingen`"
              :disabled="!canManageTrackingRules"
              active-label="Pflicht"
              inactive-label="Nicht Pflicht"
              @update:model-value="updateImportantMetric(rule.key, { requiredForAutoClassification: $event })"
            />
            <AdminSettingsToggle
              :model-value="rule.showInReview"
              :label="`${rule.label} im Nominierungsreview anzeigen`"
              :disabled="!canManageTrackingRules"
              active-label="Sichtbar"
              inactive-label="Ausgeblendet"
              @update:model-value="updateImportantMetric(rule.key, { showInReview: $event })"
            />
          </div>

          <div class="mt-4 rounded-2xl border border-violet-100 bg-white px-4 py-3">
            <p class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Wirkung</p>
            <ul class="mt-2 space-y-1 text-sm text-slate-600">
              <li v-for="item in effectSummary(rule, 'important')" :key="item">{{ item }}</li>
            </ul>
          </div>
        </article>

        <div v-if="disabledImportantMetrics.length" class="rounded-2xl border border-dashed border-slate-200 bg-slate-50/70 p-4">
          <p class="text-sm font-semibold text-slate-700">Deaktivierte wichtige Metriken</p>
          <div class="mt-3 flex flex-wrap gap-2">
            <button
              v-for="rule in disabledImportantMetrics"
              :key="rule.key"
              type="button"
              class="rounded-full border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700 transition hover:border-violet-200 hover:text-violet-700"
              :disabled="!canManageTrackingRules"
              @click="activateImportantMetric(rule.key)"
            >
              {{ rule.label }} aktivieren
            </button>
          </div>
        </div>
      </section>
    </Card>

    <Card class="overflow-visible">
      <section class="border-b border-violet-100 p-5">
        <h2 class="text-xl font-bold text-slate-900">Optionale Metriken</h2>
        <p class="mt-2 text-sm text-slate-500">Nur aktive optionale Metriken können im Nominierungsreview erscheinen. Deaktivierte Metriken werden dort komplett ausgeblendet.</p>
      </section>

      <section class="space-y-4 p-5">
        <article v-for="rule in activeOptionalMetrics" :key="rule.key" class="rounded-2xl border border-violet-100 bg-violet-50/35 p-4">
          <div class="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
            <div class="min-w-0">
              <div class="flex flex-wrap items-center gap-2">
                <h3 class="text-base font-semibold text-slate-900">{{ rule.label }}</h3>
                <span class="rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em]" :class="sourceSupportClass(rule.sourceSupport)">
                  {{ sourceSupportLabel(rule.sourceSupport) }}
                </span>
                <span v-if="rule.showInReview" class="rounded-full border border-sky-200 bg-sky-50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-sky-700">
                  Im Review sichtbar
                </span>
              </div>
              <p class="mt-2 text-sm leading-6 text-slate-500">{{ rule.description }}</p>
              <p class="mt-2 text-xs text-amber-700">{{ windowSupportText(rule) }}</p>
            </div>

            <AdminSettingsToggle
              :model-value="rule.enabled"
              :label="`${rule.label} aktiv`"
              :disabled="!canManageTrackingRules"
              active-label="Aktiv"
              inactive-label="Inaktiv"
              @update:model-value="updateOptionalMetric(rule.key, { enabled: $event })"
            />
          </div>

          <div class="mt-4 grid gap-3 md:grid-cols-2">
            <label class="space-y-2">
              <span class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Zeitraum</span>
              <NativeSelect
                :model-value="rule.windowKey"
                :disabled="!canManageTrackingRules"
                :options="windowOptions"
                @update:model-value="updateOptionalMetric(rule.key, { windowKey: String($event) })"
              />
            </label>
            <AdminSettingsToggle
              :model-value="rule.showInReview"
              :label="`${rule.label} im Nominierungsreview anzeigen`"
              :disabled="!canManageTrackingRules"
              active-label="Sichtbar"
              inactive-label="Ausgeblendet"
              @update:model-value="updateOptionalMetric(rule.key, { showInReview: $event })"
            />
          </div>

          <div v-if="isTopCategoriesRule(rule)" class="mt-4 space-y-3 rounded-2xl border border-violet-100 bg-white p-4">
            <div>
              <p class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Review-Kontext für Top Categories</p>
              <p class="mt-1 text-sm text-slate-600">Diese Einstellungen erzeugen aktuell keinen automatischen TwitchTracker-Abgleich, steuern aber den manuellen Review-Rahmen für Admins.</p>
            </div>

            <div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
              <label class="space-y-2">
                <span class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Top X Kategorien</span>
                <input
                  :value="rule.topCount ?? ''"
                  type="number"
                  min="1"
                  max="20"
                  :disabled="!canManageTrackingRules"
                  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 disabled:cursor-not-allowed disabled:bg-slate-50"
                  @input="updateTopCount(rule.key, $event)"
                >
              </label>
              <label class="space-y-2">
                <span class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Min Anteil Hauptkategorie %</span>
                <input
                  :value="rule.minPrimaryCategorySharePercent ?? ''"
                  type="number"
                  min="0"
                  max="100"
                  :disabled="!canManageTrackingRules"
                  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 disabled:cursor-not-allowed disabled:bg-slate-50"
                  @input="updateMinPrimaryCategorySharePercent(rule.key, $event)"
                >
              </label>
              <label class="space-y-2">
                <span class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Min Stunden Hauptkategorie</span>
                <input
                  :value="rule.minPrimaryCategoryHours ?? ''"
                  type="number"
                  min="0"
                  :disabled="!canManageTrackingRules"
                  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 disabled:cursor-not-allowed disabled:bg-slate-50"
                  @input="updateMinPrimaryCategoryHours(rule.key, $event)"
                >
              </label>
              <label class="space-y-2">
                <span class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Max unterschiedliche Kategorien</span>
                <input
                  :value="rule.maxDistinctCategoriesBeforeFlag ?? ''"
                  type="number"
                  min="1"
                  :disabled="!canManageTrackingRules"
                  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 disabled:cursor-not-allowed disabled:bg-slate-50"
                  @input="updateMaxDistinctCategoriesBeforeFlag(rule.key, $event)"
                >
              </label>
            </div>

            <label class="space-y-2">
              <span class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Ignorierte Kategorien</span>
              <input
                :value="ignoredCategoriesValue(rule)"
                type="text"
                :disabled="!canManageTrackingRules"
                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 disabled:cursor-not-allowed disabled:bg-slate-50"
                placeholder="Just Chatting, Special Events"
                @input="updateIgnoredCategoriesFromEvent(rule.key, $event)"
              >
            </label>

            <div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
              <AdminSettingsToggle
                :model-value="rule.matchAwardCategoryAgainstTopCategories"
                :label="`${rule.label} mit Award-Kategorie abgleichen`"
                :disabled="!canManageTrackingRules"
                active-label="Abgleich aktiv"
                inactive-label="Nur Kontext"
                @update:model-value="updateOptionalMetric(rule.key, { matchAwardCategoryAgainstTopCategories: $event })"
              />
              <AdminSettingsToggle
                :model-value="rule.flagIfAwardCategoryNotInTopX"
                :label="`${rule.label} Flag bei fehlendem Match`"
                :disabled="!canManageTrackingRules"
                active-label="Flag aktiv"
                inactive-label="Kein Flag"
                @update:model-value="updateOptionalMetric(rule.key, { flagIfAwardCategoryNotInTopX: $event })"
              />
              <AdminSettingsToggle
                :model-value="rule.flagIfCategorySpreadTooWide"
                :label="`${rule.label} Flag bei zu breitem Mix`"
                :disabled="!canManageTrackingRules"
                active-label="Flag aktiv"
                inactive-label="Kein Flag"
                @update:model-value="updateOptionalMetric(rule.key, { flagIfCategorySpreadTooWide: $event })"
              />
              <AdminSettingsToggle
                :model-value="rule.flagIfNoCategoryContextAvailable"
                :label="`${rule.label} Flag wenn kein Kontext da ist`"
                :disabled="!canManageTrackingRules"
                active-label="Flag aktiv"
                inactive-label="Kein Flag"
                @update:model-value="updateOptionalMetric(rule.key, { flagIfNoCategoryContextAvailable: $event })"
              />
            </div>
          </div>

          <div v-else class="mt-4 rounded-2xl border border-violet-100 bg-white px-4 py-3">
            <p class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Wirkung</p>
            <ul class="mt-2 space-y-1 text-sm text-slate-600">
              <li v-for="item in effectSummary(rule, 'optional')" :key="item">{{ item }}</li>
            </ul>
          </div>
        </article>

        <div v-if="disabledOptionalMetrics.length" class="rounded-2xl border border-dashed border-slate-200 bg-slate-50/70 p-4">
          <p class="text-sm font-semibold text-slate-700">Deaktivierte optionale Metriken</p>
          <div class="mt-3 flex flex-wrap gap-2">
            <button
              v-for="rule in disabledOptionalMetrics"
              :key="rule.key"
              type="button"
              class="rounded-full border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700 transition hover:border-violet-200 hover:text-violet-700"
              :disabled="!canManageTrackingRules"
              @click="activateOptionalMetric(rule.key)"
            >
              {{ rule.label }} aktivieren
            </button>
          </div>
        </div>
      </section>
    </Card>

    <Card class="overflow-visible">
      <section class="border-b border-violet-100 p-5">
        <h2 class="text-xl font-bold text-slate-900">Flags</h2>
        <p class="mt-2 text-sm text-slate-500">Tracking-Flags markieren Review-Faelle und Hinweise, blockieren aber keine Annahme oder Verwerfung mehr.</p>
      </section>
      <section class="grid gap-3 p-5">
        <article v-for="rule in trackingFlags" :key="rule.key" class="rounded-2xl border border-violet-100 bg-violet-50/35 p-4">
          <div class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_180px_170px] xl:items-start">
            <div class="min-w-0">
              <h3 class="text-base font-semibold text-slate-900">{{ rule.label }}</h3>
              <p class="mt-2 text-sm leading-6 text-slate-500">{{ rule.description }}</p>
            </div>

            <label class="space-y-2">
              <span class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Severity</span>
              <NativeSelect
                :model-value="rule.severity"
                :disabled="!canManageTrackingRules"
                :options="[
                  { label: 'Hoch', value: 'high' },
                  { label: 'Mittel', value: 'medium' },
                  { label: 'Niedrig', value: 'low' },
                ]"
                @update:model-value="updateTrackingFlag(rule.key, { severity: String($event) })"
              />
            </label>

            <AdminSettingsToggle
              :model-value="rule.enabled"
              :label="`${rule.label} aktiv`"
              :disabled="!canManageTrackingRules"
              @update:model-value="updateTrackingFlag(rule.key, { enabled: $event })"
            />
          </div>

          <div class="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
            <AdminSettingsToggle
              :model-value="rule.autoTriggerEnabled"
              :label="`${rule.label} automatisch ausloesen`"
              :disabled="!canManageTrackingRules"
              active-label="Auto"
              inactive-label="Nur manuell"
              @update:model-value="updateTrackingFlag(rule.key, { autoTriggerEnabled: $event })"
            />
            <AdminSettingsToggle
              :model-value="rule.requiresManualReview"
              :label="`${rule.label} braucht Review`"
              :disabled="!canManageTrackingRules"
              active-label="Review nötig"
              inactive-label="Nur Hinweis"
              @update:model-value="updateTrackingFlag(rule.key, { requiresManualReview: $event })"
            />
            <div class="rounded-2xl border border-violet-100 bg-white px-4 py-3">
              <p class="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">Approve-Verhalten</p>
              <p class="mt-2 text-sm font-semibold text-slate-900">Warnt nur</p>
              <p class="mt-1 text-xs leading-5 text-slate-500">Tracking-Flags sind reine Zusatzinfos für den Review-Kontext und sperren die Entscheidung nicht.</p>
            </div>
            <AdminSettingsToggle
              :model-value="rule.adminNoteRequiredOnOverride"
              :label="`${rule.label} braucht Override-Notiz`"
              :disabled="!canManageTrackingRules"
              active-label="Notiz nötig"
              inactive-label="Optional"
              @update:model-value="updateTrackingFlag(rule.key, { adminNoteRequiredOnOverride: $event })"
            />
          </div>
        </article>
      </section>
    </Card>
  </div>
</template>
