'use client'

/**
 * Notfallplan & Breach Response (Art. 33/34 DSGVO)
 *
 * 4 Tabs:
 * 1. Notfallplan-Konfiguration (Meldewege, Zustaendigkeiten, Eskalation)
 * 2. Incident-Register (Art. 33 Abs. 5)
 * 3. Melde-Templates (Art. 33 + Art. 34)
 * 4. Uebungen & Tests
 */

import { useState, useEffect, useCallback } from 'react'
import { useSDK } from '@/lib/sdk'
import StepHeader from '@/components/sdk/StepHeader/StepHeader'

// =============================================================================
// TYPES
// =============================================================================

type Tab = 'config' | 'incidents' | 'templates' | 'exercises'

type IncidentStatus = 'detected' | 'classified' | 'assessed' | 'reported' | 'not_reportable' | 'closed'
type IncidentSeverity = 'low' | 'medium' | 'high' | 'critical'

interface NotfallplanConfig {
  meldewege: MeldeStep[]
  zustaendigkeiten: Zustaendigkeit[]
  aufsichtsbehoerde: {
    name: string
    state: string
    email: string
    phone: string
    url: string
  }
  eskalationsstufen: Eskalationsstufe[]
  sofortmassnahmen: string[]
}

interface MeldeStep {
  id: string
  order: number
  role: string
  name: string
  action: string
  maxHours: number
}

interface Zustaendigkeit {
  id: string
  role: string
  name: string
  email: string
  phone: string
}

interface Eskalationsstufe {
  id: string
  level: number
  label: string
  triggerCondition: string
  actions: string[]
}

interface Incident {
  id: string
  title: string
  description: string
  detectedAt: string
  detectedBy: string
  status: IncidentStatus
  severity: IncidentSeverity
  affectedDataCategories: string[]
  estimatedAffectedPersons: number
  measures: string[]
  art34Required: boolean
  art34Justification: string
  reportedToAuthorityAt?: string
  notifiedAffectedAt?: string
  closedAt?: string
  closedBy?: string
  lessonsLearned?: string
}

interface MeldeTemplate {
  id: string
  type: 'art33' | 'art34'
  title: string
  content: string
}

interface Exercise {
  id: string
  title: string
  type: 'tabletop' | 'simulation' | 'full_drill'
  scenario: string
  scheduledDate: string
  completedDate?: string
  participants: string[]
  lessonsLearned: string
  nextExerciseDate?: string
}

// =============================================================================
// INITIAL DATA
// =============================================================================

const DEFAULT_CONFIG: NotfallplanConfig = {
  meldewege: [
    { id: '1', order: 1, role: 'Entdecker', name: '', action: 'Incident melden an IT-Sicherheit', maxHours: 0 },
    { id: '2', order: 2, role: 'IT-Sicherheit', name: '', action: 'Erstbewertung und Klassifizierung', maxHours: 4 },
    { id: '3', order: 3, role: 'Datenschutzbeauftragter', name: '', action: 'Meldepflicht pruefen (Art. 33)', maxHours: 12 },
    { id: '4', order: 4, role: 'Geschaeftsfuehrung', name: '', action: 'Freigabe der Meldung', maxHours: 24 },
    { id: '5', order: 5, role: 'DSB', name: '', action: 'Meldung an Aufsichtsbehoerde', maxHours: 72 },
  ],
  zustaendigkeiten: [
    { id: '1', role: 'Incident Owner', name: '', email: '', phone: '' },
    { id: '2', role: 'Datenschutzbeauftragter', name: '', email: '', phone: '' },
    { id: '3', role: 'IT-Sicherheit', name: '', email: '', phone: '' },
    { id: '4', role: 'Recht / Legal', name: '', email: '', phone: '' },
    { id: '5', role: 'Kommunikation / PR', name: '', email: '', phone: '' },
  ],
  aufsichtsbehoerde: {
    name: '',
    state: '',
    email: '',
    phone: '',
    url: '',
  },
  eskalationsstufen: [
    { id: '1', level: 1, label: 'Standard', triggerCondition: 'Einzelfall, keine sensiblen Daten', actions: ['IT-Sicherheit informieren', 'DSB benachrichtigen'] },
    { id: '2', level: 2, label: 'Erhoehte Prioritaet', triggerCondition: 'Sensible Daten oder > 100 Betroffene', actions: ['Geschaeftsfuehrung informieren', 'Notfallteam einberufen'] },
    { id: '3', level: 3, label: 'Kritisch', triggerCondition: 'Besondere Kategorien Art. 9 oder > 1000 Betroffene', actions: ['Sofortige Krisensitzung', 'Art. 34 Benachrichtigung vorbereiten', 'PR/Kommunikation einbinden'] },
  ],
  sofortmassnahmen: [
    'Betroffene Systeme isolieren / vom Netz nehmen',
    'Zugriffsrechte pruefen und ggf. sperren',
    'Beweise sichern (Logs, Screenshots)',
    'Zeitleiste der Ereignisse dokumentieren',
    'Erstbewertung: Art der Daten, Anzahl Betroffene, Schaden',
    'DSB unverzueglich informieren',
  ],
}

const DEFAULT_TEMPLATES: MeldeTemplate[] = [
  {
    id: 'tpl-art33',
    type: 'art33',
    title: 'Meldung an Aufsichtsbehoerde (Art. 33 DSGVO)',
    content: `Meldung einer Verletzung des Schutzes personenbezogener Daten
gemaess Art. 33 DSGVO

1. Beschreibung der Verletzung:
[Art der Verletzung, betroffene Kategorien personenbezogener Daten]

2. Kategorien und ungefaehre Zahl der betroffenen Personen:
[Anzahl und Kategorien der Betroffenen]

3. Kategorien und ungefaehre Zahl der betroffenen Datensaetze:
[Datensatz-Kategorien und Anzahl]

4. Name und Kontaktdaten des Datenschutzbeauftragten:
[Name, E-Mail, Telefon]

5. Beschreibung der wahrscheinlichen Folgen:
[Moegliche Auswirkungen auf die Betroffenen]

6. Beschreibung der ergriffenen/vorgeschlagenen Massnahmen:
[Sofortmassnahmen und geplante Abhilfemassnahmen]

7. Zeitpunkt der Feststellung:
[Datum, Uhrzeit]

8. Begruendung bei verspaeteter Meldung (falls > 72h):
[Begruendung]`,
  },
  {
    id: 'tpl-art34',
    type: 'art34',
    title: 'Benachrichtigung Betroffene (Art. 34 DSGVO)',
    content: `Benachrichtigung ueber eine Verletzung des Schutzes
Ihrer personenbezogenen Daten

Sehr geehrte/r [Name/Betroffene],

wir informieren Sie gemaess Art. 34 DSGVO ueber eine Verletzung
des Schutzes personenbezogener Daten, die Ihre Daten betrifft.

Was ist passiert?
[Beschreibung in klarer, einfacher Sprache]

Welche Daten sind betroffen?
[Betroffene Datenkategorien]

Welche Folgen sind moeglich?
[Moegliche Auswirkungen]

Was haben wir unternommen?
[Ergriffene Massnahmen]

Was koennen Sie tun?
[Empfehlungen fuer Betroffene, z.B. Passwort aendern]

Kontakt:
Unser Datenschutzbeauftragter steht Ihnen fuer Rueckfragen
zur Verfuegung:
[Name, E-Mail, Telefon]

Mit freundlichen Gruessen
[Verantwortlicher]`,
  },
]

const INCIDENT_STATUS_LABELS: Record<IncidentStatus, string> = {
  detected: 'Erkannt',
  classified: 'Klassifiziert',
  assessed: 'Bewertet',
  reported: 'Gemeldet',
  not_reportable: 'Nicht meldepflichtig',
  closed: 'Abgeschlossen',
}

const INCIDENT_STATUS_COLORS: Record<IncidentStatus, string> = {
  detected: 'bg-red-100 text-red-800',
  classified: 'bg-yellow-100 text-yellow-800',
  assessed: 'bg-blue-100 text-blue-800',
  reported: 'bg-green-100 text-green-800',
  not_reportable: 'bg-gray-100 text-gray-800',
  closed: 'bg-gray-100 text-gray-600',
}

const SEVERITY_LABELS: Record<IncidentSeverity, string> = {
  low: 'Niedrig',
  medium: 'Mittel',
  high: 'Hoch',
  critical: 'Kritisch',
}

const SEVERITY_COLORS: Record<IncidentSeverity, string> = {
  low: 'bg-green-100 text-green-800',
  medium: 'bg-yellow-100 text-yellow-800',
  high: 'bg-orange-100 text-orange-800',
  critical: 'bg-red-100 text-red-800',
}

// =============================================================================
// LOCAL STORAGE HELPERS
// =============================================================================

const STORAGE_KEY = 'bp_notfallplan'

function loadFromStorage(): {
  config: NotfallplanConfig
  incidents: Incident[]
  templates: MeldeTemplate[]
  exercises: Exercise[]
} {
  if (typeof window === 'undefined') {
    return { config: DEFAULT_CONFIG, incidents: [], templates: DEFAULT_TEMPLATES, exercises: [] }
  }
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      return JSON.parse(stored)
    }
  } catch {
    // ignore
  }
  return { config: DEFAULT_CONFIG, incidents: [], templates: DEFAULT_TEMPLATES, exercises: [] }
}

function saveToStorage(data: {
  config: NotfallplanConfig
  incidents: Incident[]
  templates: MeldeTemplate[]
  exercises: Exercise[]
}) {
  if (typeof window === 'undefined') return
  localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
}

// =============================================================================
// COMPONENT: 72h Countdown
// =============================================================================

function CountdownTimer({ detectedAt }: { detectedAt: string }) {
  const [remaining, setRemaining] = useState('')
  const [overdue, setOverdue] = useState(false)

  useEffect(() => {
    function update() {
      const detected = new Date(detectedAt).getTime()
      const deadline = detected + 72 * 60 * 60 * 1000
      const now = Date.now()
      const diff = deadline - now

      if (diff <= 0) {
        const overdueMs = Math.abs(diff)
        const hours = Math.floor(overdueMs / (1000 * 60 * 60))
        const mins = Math.floor((overdueMs % (1000 * 60 * 60)) / (1000 * 60))
        setRemaining(`${hours}h ${mins}min ueberfaellig`)
        setOverdue(true)
      } else {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        const mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
        setRemaining(`${hours}h ${mins}min verbleibend`)
        setOverdue(false)
      }
    }
    update()
    const interval = setInterval(update, 60000)
    return () => clearInterval(interval)
  }, [detectedAt])

  return (
    <span className={`text-sm font-medium ${overdue ? 'text-red-600' : 'text-orange-600'}`}>
      72h-Frist: {remaining}
    </span>
  )
}

// =============================================================================
// MAIN PAGE
// =============================================================================

// =============================================================================
// API TYPES (for DB-backed Notfallplan data)
// =============================================================================

interface ApiContact {
  id: string
  name: string
  role: string | null
  email: string | null
  phone: string | null
  is_primary: boolean
  available_24h: boolean
  created_at: string | null
}

interface ApiScenario {
  id: string
  title: string
  category: string | null
  severity: string
  description: string | null
  is_active: boolean
  created_at: string | null
}

interface ApiExercise {
  id: string
  title: string
  exercise_type: string
  exercise_date: string | null
  outcome: string | null
  notes: string | null
  created_at: string | null
}

const NOTFALLPLAN_API = '/api/sdk/v1/notfallplan'

export default function NotfallplanPage() {
  const { state } = useSDK()
  const [activeTab, setActiveTab] = useState<Tab>('config')
  const [config, setConfig] = useState<NotfallplanConfig>(DEFAULT_CONFIG)
  const [incidents, setIncidents] = useState<Incident[]>([])
  const [templates, setTemplates] = useState<MeldeTemplate[]>(DEFAULT_TEMPLATES)
  const [exercises, setExercises] = useState<Exercise[]>([])
  const [showAddIncident, setShowAddIncident] = useState(false)
  const [showAddExercise, setShowAddExercise] = useState(false)
  const [showExerciseModal, setShowExerciseModal] = useState(false)
  const [saved, setSaved] = useState(false)

  // API-backed state
  const [apiContacts, setApiContacts] = useState<ApiContact[]>([])
  const [apiScenarios, setApiScenarios] = useState<ApiScenario[]>([])
  const [apiExercises, setApiExercises] = useState<ApiExercise[]>([])
  const [apiLoading, setApiLoading] = useState(false)
  const [showContactModal, setShowContactModal] = useState(false)
  const [showScenarioModal, setShowScenarioModal] = useState(false)
  const [newContact, setNewContact] = useState({ name: '', role: '', email: '', phone: '', is_primary: false, available_24h: false })
  const [newScenario, setNewScenario] = useState({ title: '', category: 'data_breach', severity: 'medium', description: '' })
  const [newExercise, setNewExercise] = useState({ title: '', exercise_type: 'tabletop', exercise_date: '', notes: '' })
  const [savingContact, setSavingContact] = useState(false)
  const [savingScenario, setSavingScenario] = useState(false)
  const [savingExercise, setSavingExercise] = useState(false)

  useEffect(() => {
    // Only load config and exercises from localStorage (incidents/templates use API)
    const data = loadFromStorage()
    setConfig(data.config)
    setExercises(data.exercises)
  }, [])

  useEffect(() => {
    loadApiData()
  }, [])

  async function loadApiData() {
    setApiLoading(true)
    try {
      const [contactsRes, scenariosRes, exercisesRes, incidentsRes, templatesRes] = await Promise.all([
        fetch(`${NOTFALLPLAN_API}/contacts`),
        fetch(`${NOTFALLPLAN_API}/scenarios`),
        fetch(`${NOTFALLPLAN_API}/exercises`),
        fetch(`${NOTFALLPLAN_API}/incidents`),
        fetch(`${NOTFALLPLAN_API}/templates`),
      ])
      if (contactsRes.ok) {
        const data = await contactsRes.json()
        setApiContacts(Array.isArray(data) ? data : [])
      }
      if (scenariosRes.ok) {
        const data = await scenariosRes.json()
        setApiScenarios(Array.isArray(data) ? data : [])
      }
      if (exercisesRes.ok) {
        const data = await exercisesRes.json()
        setApiExercises(Array.isArray(data) ? data : [])
      }
      if (incidentsRes.ok) {
        const data = await incidentsRes.json()
        setIncidents(Array.isArray(data) ? data.map(apiToIncident) : [])
      }
      if (templatesRes.ok) {
        const data = await templatesRes.json()
        setTemplates(Array.isArray(data) && data.length > 0 ? data : DEFAULT_TEMPLATES)
      }
    } catch (err) {
      console.error('Failed to load Notfallplan API data:', err)
    } finally {
      setApiLoading(false)
    }
  }

  function apiToIncident(raw: any): Incident {
    return {
      id: raw.id,
      title: raw.title,
      description: raw.description || '',
      detectedAt: raw.detected_at,
      detectedBy: raw.detected_by || 'Admin',
      status: raw.status,
      severity: raw.severity,
      affectedDataCategories: raw.affected_data_categories || [],
      estimatedAffectedPersons: raw.estimated_affected_persons || 0,
      measures: raw.measures || [],
      art34Required: raw.art34_required || false,
      art34Justification: raw.art34_justification || '',
      reportedToAuthorityAt: raw.reported_to_authority_at,
      notifiedAffectedAt: raw.notified_affected_at,
      closedAt: raw.closed_at,
      closedBy: raw.closed_by,
      lessonsLearned: raw.lessons_learned,
    }
  }

  async function apiAddIncident(newIncident: Partial<Incident>) {
    try {
      const res = await fetch(`${NOTFALLPLAN_API}/incidents`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: newIncident.title,
          description: newIncident.description,
          severity: newIncident.severity || 'medium',
          estimated_affected_persons: newIncident.estimatedAffectedPersons || 0,
          art34_required: newIncident.art34Required || false,
          art34_justification: newIncident.art34Justification || '',
        }),
      })
      if (res.ok) {
        const created = await res.json()
        setIncidents(prev => [apiToIncident(created), ...prev])
      }
    } catch (err) {
      console.error('Failed to create incident:', err)
    }
  }

  async function apiUpdateIncidentStatus(id: string, status: IncidentStatus) {
    try {
      const body: any = { status }
      if (status === 'reported') body.reported_to_authority_at = new Date().toISOString()
      if (status === 'closed') { body.closed_at = new Date().toISOString(); body.closed_by = 'Admin' }
      const res = await fetch(`${NOTFALLPLAN_API}/incidents/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      if (res.ok) {
        const updated = await res.json()
        setIncidents(prev => prev.map(inc => inc.id === id ? apiToIncident(updated) : inc))
      }
    } catch (err) {
      console.error('Failed to update incident status:', err)
    }
  }

  async function apiDeleteIncident(id: string) {
    try {
      const res = await fetch(`${NOTFALLPLAN_API}/incidents/${id}`, { method: 'DELETE' })
      if (res.ok || res.status === 204) {
        setIncidents(prev => prev.filter(inc => inc.id !== id))
      }
    } catch (err) {
      console.error('Failed to delete incident:', err)
    }
  }

  async function apiSaveTemplate(template: MeldeTemplate) {
    try {
      const isNew = !template.id.startsWith('tpl-')
      const method = isNew || template.id.length < 10 ? 'POST' : 'PUT'
      const url = method === 'POST'
        ? `${NOTFALLPLAN_API}/templates`
        : `${NOTFALLPLAN_API}/templates/${template.id}`
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: template.type, title: template.title, content: template.content }),
      })
      if (res.ok) {
        const saved = await res.json()
        setTemplates(prev => {
          const existing = prev.find(t => t.id === template.id)
          if (existing) return prev.map(t => t.id === template.id ? { ...t, ...saved } : t)
          return [...prev, saved]
        })
      }
    } catch (err) {
      console.error('Failed to save template:', err)
    }
  }

  async function handleCreateContact() {
    if (!newContact.name) return
    setSavingContact(true)
    try {
      const res = await fetch(`${NOTFALLPLAN_API}/contacts`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newContact),
      })
      if (res.ok) {
        const created = await res.json()
        setApiContacts(prev => [created, ...prev])
        setShowContactModal(false)
        setNewContact({ name: '', role: '', email: '', phone: '', is_primary: false, available_24h: false })
      }
    } catch (err) {
      console.error('Failed to create contact:', err)
    } finally {
      setSavingContact(false)
    }
  }

  async function handleDeleteContact(id: string) {
    try {
      const res = await fetch(`${NOTFALLPLAN_API}/contacts/${id}`, { method: 'DELETE' })
      if (res.ok) {
        setApiContacts(prev => prev.filter(c => c.id !== id))
      }
    } catch (err) {
      console.error('Failed to delete contact:', err)
    }
  }

  async function handleCreateScenario() {
    if (!newScenario.title) return
    setSavingScenario(true)
    try {
      const res = await fetch(`${NOTFALLPLAN_API}/scenarios`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newScenario),
      })
      if (res.ok) {
        const created = await res.json()
        setApiScenarios(prev => [created, ...prev])
        setShowScenarioModal(false)
        setNewScenario({ title: '', category: 'data_breach', severity: 'medium', description: '' })
      }
    } catch (err) {
      console.error('Failed to create scenario:', err)
    } finally {
      setSavingScenario(false)
    }
  }

  async function handleCreateExercise() {
    if (!newExercise.title.trim()) return
    setSavingExercise(true)
    try {
      const res = await fetch(`${NOTFALLPLAN_API}/exercises`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: newExercise.title.trim(),
          exercise_type: newExercise.exercise_type,
          exercise_date: newExercise.exercise_date || null,
          notes: newExercise.notes.trim() || null,
        }),
      })
      if (res.ok) {
        setShowExerciseModal(false)
        setNewExercise({ title: '', exercise_type: 'tabletop', exercise_date: '', notes: '' })
        loadApiData()
      }
    } catch (e) {
      console.error('Uebung erstellen fehlgeschlagen:', e)
    } finally {
      setSavingExercise(false)
    }
  }

  async function handleDeleteExercise(id: string) {
    try {
      const res = await fetch(`${NOTFALLPLAN_API}/exercises/${id}`, { method: 'DELETE' })
      if (res.ok) {
        setApiExercises(prev => prev.filter(e => e.id !== id))
      }
    } catch (e) {
      console.error('Löschen fehlgeschlagen:', e)
    }
  }

  async function handleDeleteScenario(id: string) {
    try {
      const res = await fetch(`${NOTFALLPLAN_API}/scenarios/${id}`, { method: 'DELETE' })
      if (res.ok) {
        setApiScenarios(prev => prev.filter(s => s.id !== id))
      }
    } catch (err) {
      console.error('Failed to delete scenario:', err)
    }
  }

  const handleSave = useCallback(() => {
    // Only config and exercises are persisted to localStorage; incidents/templates use API
    saveToStorage({ config, incidents: [], templates: DEFAULT_TEMPLATES, exercises })
    setSaved(true)
    setTimeout(() => setSaved(false), 2000)
  }, [config, exercises])

  const tabs: { id: Tab; label: string; count?: number }[] = [
    { id: 'config', label: 'Notfallplan' },
    { id: 'incidents', label: 'Incident-Register', count: incidents.filter(i => i.status !== 'closed').length || undefined },
    { id: 'templates', label: 'Melde-Templates' },
    { id: 'exercises', label: 'Uebungen & Tests', count: exercises.filter(e => !e.completedDate).length || undefined },
  ]

  return (
    <div className="space-y-6">
      <StepHeader stepId="notfallplan" />

      {/* API Stats Banner */}
      {!apiLoading && (apiContacts.length > 0 || apiScenarios.length > 0) && (
        <div className="bg-blue-50 border border-blue-200 rounded-lg px-4 py-3 flex items-center gap-6 text-sm">
          <span className="font-medium text-blue-900">Notfallplan-Datenbank:</span>
          <span className="text-blue-700">{apiContacts.length} Kontakte</span>
          <span className="text-blue-700">{apiScenarios.length} Szenarien</span>
          <span className="text-blue-700">{apiExercises.length} Uebungen</span>
        </div>
      )}

      {/* Tab Navigation */}
      <div className="border-b border-gray-200">
        <nav className="-mb-px flex space-x-8">
          {tabs.map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm ${
                activeTab === tab.id
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              {tab.label}
              {tab.count && (
                <span className="ml-2 bg-red-100 text-red-800 text-xs font-medium px-2 py-0.5 rounded-full">
                  {tab.count}
                </span>
              )}
            </button>
          ))}
        </nav>
      </div>

      {/* Save Button */}
      <div className="flex justify-end">
        <button
          onClick={handleSave}
          className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
            saved
              ? 'bg-green-600 text-white'
              : 'bg-blue-600 text-white hover:bg-blue-700'
          }`}
        >
          {saved ? 'Gespeichert!' : 'Speichern'}
        </button>
      </div>

      {/* Tab Content */}
      {activeTab === 'config' && (
        <>
          {/* API Contacts & Scenarios section */}
          <div className="space-y-4">
            {/* Contacts */}
            <div className="bg-white rounded-lg border p-5">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="text-base font-semibold">Notfallkontakte (Datenbank)</h3>
                  <p className="text-sm text-gray-500">Zentral gespeicherte Kontakte fuer den Notfall</p>
                </div>
                <button
                  onClick={() => setShowContactModal(true)}
                  className="px-3 py-1.5 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700"
                >
                  + Kontakt hinzufuegen
                </button>
              </div>
              {apiLoading ? (
                <div className="text-sm text-gray-500 py-4 text-center">Lade Kontakte...</div>
              ) : apiContacts.length === 0 ? (
                <div className="text-sm text-gray-400 py-4 text-center">Noch keine Kontakte hinterlegt</div>
              ) : (
                <div className="space-y-2">
                  {apiContacts.map(contact => (
                    <div key={contact.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <div className="flex items-center gap-3">
                        {contact.is_primary && <span className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full font-medium">Primaer</span>}
                        {contact.available_24h && <span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full font-medium">24/7</span>}
                        <div>
                          <span className="font-medium text-sm">{contact.name}</span>
                          {contact.role && <span className="text-gray-500 text-sm ml-2">({contact.role})</span>}
                          <div className="text-xs text-gray-400">{contact.email} {contact.phone && `| ${contact.phone}`}</div>
                        </div>
                      </div>
                      <button
                        onClick={() => handleDeleteContact(contact.id)}
                        className="text-xs text-red-500 hover:text-red-700 px-2 py-1 rounded hover:bg-red-50"
                      >
                        Loeschen
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Scenarios */}
            <div className="bg-white rounded-lg border p-5">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="text-base font-semibold">Notfallszenarien (Datenbank)</h3>
                  <p className="text-sm text-gray-500">Definierte Szenarien und Reaktionsplaene</p>
                </div>
                <button
                  onClick={() => setShowScenarioModal(true)}
                  className="px-3 py-1.5 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700"
                >
                  + Szenario hinzufuegen
                </button>
              </div>
              {apiLoading ? (
                <div className="text-sm text-gray-500 py-4 text-center">Lade Szenarien...</div>
              ) : apiScenarios.length === 0 ? (
                <div className="text-sm text-gray-400 py-4 text-center">Noch keine Szenarien definiert</div>
              ) : (
                <div className="space-y-2">
                  {apiScenarios.map(scenario => (
                    <div key={scenario.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <div>
                        <span className="font-medium text-sm">{scenario.title}</span>
                        <div className="flex items-center gap-2 mt-1">
                          {scenario.category && <span className="text-xs bg-slate-100 text-slate-600 px-2 py-0.5 rounded">{scenario.category}</span>}
                          <span className={`text-xs px-2 py-0.5 rounded ${
                            scenario.severity === 'critical' ? 'bg-red-100 text-red-700' :
                            scenario.severity === 'high' ? 'bg-orange-100 text-orange-700' :
                            scenario.severity === 'medium' ? 'bg-yellow-100 text-yellow-700' :
                            'bg-green-100 text-green-700'
                          }`}>{scenario.severity}</span>
                        </div>
                        {scenario.description && <p className="text-xs text-gray-500 mt-1 truncate max-w-lg">{scenario.description}</p>}
                      </div>
                      <button
                        onClick={() => handleDeleteScenario(scenario.id)}
                        className="text-xs text-red-500 hover:text-red-700 px-2 py-1 rounded hover:bg-red-50"
                      >
                        Loeschen
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
          <ConfigTab config={config} setConfig={setConfig} />
        </>
      )}
      {activeTab === 'incidents' && (
        <IncidentsTab
          incidents={incidents}
          setIncidents={setIncidents}
          showAdd={showAddIncident}
          setShowAdd={setShowAddIncident}
          onAdd={apiAddIncident}
          onStatusChange={apiUpdateIncidentStatus}
          onDelete={apiDeleteIncident}
        />
      )}
      {activeTab === 'templates' && (
        <TemplatesTab templates={templates} setTemplates={setTemplates} onSave={apiSaveTemplate} />
      )}
      {activeTab === 'exercises' && (
        <>
          {/* API Exercises */}
          {(apiExercises.length > 0 || !apiLoading) && (
            <div className="bg-white rounded-lg border p-5">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-base font-semibold">Uebungen (Datenbank)</h3>
                <div className="flex items-center gap-3">
                  <span className="text-sm text-gray-500">{apiExercises.length} Eintraege</span>
                  <button
                    onClick={() => setShowExerciseModal(true)}
                    className="px-3 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    + Neue Uebung
                  </button>
                </div>
              </div>
              {apiExercises.length === 0 ? (
                <div className="text-sm text-gray-400 py-2 text-center">Noch keine Uebungen in der Datenbank</div>
              ) : (
                <div className="space-y-2">
                  {apiExercises.map(ex => (
                    <div key={ex.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <div>
                        <span className="font-medium text-sm">{ex.title}</span>
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-xs bg-slate-100 text-slate-600 px-2 py-0.5 rounded">{ex.exercise_type}</span>
                          {ex.exercise_date && <span className="text-xs text-gray-400">{new Date(ex.exercise_date).toLocaleDateString('de-DE')}</span>}
                          {ex.outcome && <span className={`text-xs px-2 py-0.5 rounded ${ex.outcome === 'passed' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>{ex.outcome}</span>}
                        </div>
                      </div>
                      <button
                        onClick={() => {
                          if (window.confirm(`Uebung "${ex.title}" loeschen?`)) {
                            handleDeleteExercise(ex.id)
                          }
                        }}
                        className="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                        title="Loeschen"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
          <ExercisesTab
            exercises={exercises}
            setExercises={setExercises}
            showAdd={showAddExercise}
            setShowAdd={setShowAddExercise}
          />
        </>
      )}

      {/* Contact Create Modal */}
      {showContactModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full mx-4">
            <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
              <h3 className="font-semibold text-gray-900">Notfallkontakt hinzufuegen</h3>
              <button onClick={() => setShowContactModal(false)} className="text-gray-400 hover:text-gray-600">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Name *</label>
                <input
                  type="text"
                  value={newContact.name}
                  onChange={e => setNewContact(p => ({ ...p, name: e.target.value }))}
                  placeholder="Vollstaendiger Name"
                  className="w-full border rounded px-3 py-2 text-sm"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Rolle</label>
                <input
                  type="text"
                  value={newContact.role}
                  onChange={e => setNewContact(p => ({ ...p, role: e.target.value }))}
                  placeholder="z.B. Datenschutzbeauftragter"
                  className="w-full border rounded px-3 py-2 text-sm"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">E-Mail</label>
                  <input
                    type="email"
                    value={newContact.email}
                    onChange={e => setNewContact(p => ({ ...p, email: e.target.value }))}
                    placeholder="email@example.com"
                    className="w-full border rounded px-3 py-2 text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Telefon</label>
                  <input
                    type="tel"
                    value={newContact.phone}
                    onChange={e => setNewContact(p => ({ ...p, phone: e.target.value }))}
                    placeholder="+49..."
                    className="w-full border rounded px-3 py-2 text-sm"
                  />
                </div>
              </div>
              <div className="flex items-center gap-6">
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <input
                    type="checkbox"
                    checked={newContact.is_primary}
                    onChange={e => setNewContact(p => ({ ...p, is_primary: e.target.checked }))}
                    className="rounded"
                  />
                  Primaerkontakt
                </label>
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <input
                    type="checkbox"
                    checked={newContact.available_24h}
                    onChange={e => setNewContact(p => ({ ...p, available_24h: e.target.checked }))}
                    className="rounded"
                  />
                  24/7 erreichbar
                </label>
              </div>
            </div>
            <div className="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
              <button onClick={() => setShowContactModal(false)} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">
                Abbrechen
              </button>
              <button
                onClick={handleCreateContact}
                disabled={!newContact.name || savingContact}
                className="px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 rounded-lg font-medium disabled:opacity-50"
              >
                {savingContact ? 'Speichern...' : 'Hinzufuegen'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Exercise Create Modal */}
      {showExerciseModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full mx-4">
            <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
              <h3 className="font-semibold text-gray-900">Neue Uebung planen</h3>
              <button onClick={() => setShowExerciseModal(false)} className="text-gray-400 hover:text-gray-600">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Titel *</label>
                <input
                  type="text"
                  value={newExercise.title}
                  onChange={e => setNewExercise(p => ({ ...p, title: e.target.value }))}
                  placeholder="z.B. Tabletop-Uebung Ransomware"
                  className="w-full border rounded px-3 py-2 text-sm"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Uebungstyp</label>
                  <select
                    value={newExercise.exercise_type}
                    onChange={e => setNewExercise(p => ({ ...p, exercise_type: e.target.value }))}
                    className="w-full border rounded px-3 py-2 text-sm"
                  >
                    <option value="tabletop">Tabletop</option>
                    <option value="simulation">Simulation</option>
                    <option value="walkthrough">Walkthrough</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Datum</label>
                  <input
                    type="date"
                    value={newExercise.exercise_date}
                    onChange={e => setNewExercise(p => ({ ...p, exercise_date: e.target.value }))}
                    className="w-full border rounded px-3 py-2 text-sm"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Notizen</label>
                <textarea
                  value={newExercise.notes}
                  onChange={e => setNewExercise(p => ({ ...p, notes: e.target.value }))}
                  placeholder="Ziele, Teilnehmer, Ablauf..."
                  rows={3}
                  className="w-full border rounded px-3 py-2 text-sm"
                />
              </div>
            </div>
            <div className="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
              <button onClick={() => setShowExerciseModal(false)} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">
                Abbrechen
              </button>
              <button
                onClick={handleCreateExercise}
                disabled={!newExercise.title || savingExercise}
                className="px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 rounded-lg font-medium disabled:opacity-50"
              >
                {savingExercise ? 'Speichern...' : 'Uebung erstellen'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Scenario Create Modal */}
      {showScenarioModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full mx-4">
            <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
              <h3 className="font-semibold text-gray-900">Notfallszenario hinzufuegen</h3>
              <button onClick={() => setShowScenarioModal(false)} className="text-gray-400 hover:text-gray-600">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Titel *</label>
                <input
                  type="text"
                  value={newScenario.title}
                  onChange={e => setNewScenario(p => ({ ...p, title: e.target.value }))}
                  placeholder="z.B. Ransomware-Angriff auf Produktivsysteme"
                  className="w-full border rounded px-3 py-2 text-sm"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Kategorie</label>
                  <select
                    value={newScenario.category}
                    onChange={e => setNewScenario(p => ({ ...p, category: e.target.value }))}
                    className="w-full border rounded px-3 py-2 text-sm"
                  >
                    <option value="data_breach">Datenpanne</option>
                    <option value="system_failure">Systemausfall</option>
                    <option value="physical">Physischer Vorfall</option>
                    <option value="other">Sonstiges</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Schweregrad</label>
                  <select
                    value={newScenario.severity}
                    onChange={e => setNewScenario(p => ({ ...p, severity: e.target.value }))}
                    className="w-full border rounded px-3 py-2 text-sm"
                  >
                    <option value="low">Niedrig</option>
                    <option value="medium">Mittel</option>
                    <option value="high">Hoch</option>
                    <option value="critical">Kritisch</option>
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
                <textarea
                  value={newScenario.description}
                  onChange={e => setNewScenario(p => ({ ...p, description: e.target.value }))}
                  placeholder="Kurzbeschreibung des Szenarios und moeglicher Auswirkungen..."
                  rows={3}
                  className="w-full border rounded px-3 py-2 text-sm"
                />
              </div>
            </div>
            <div className="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
              <button onClick={() => setShowScenarioModal(false)} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">
                Abbrechen
              </button>
              <button
                onClick={handleCreateScenario}
                disabled={!newScenario.title || savingScenario}
                className="px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 rounded-lg font-medium disabled:opacity-50"
              >
                {savingScenario ? 'Speichern...' : 'Hinzufuegen'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

// =============================================================================
// TAB 1: Notfallplan-Konfiguration
// =============================================================================

function ConfigTab({
  config,
  setConfig,
}: {
  config: NotfallplanConfig
  setConfig: React.Dispatch<React.SetStateAction<NotfallplanConfig>>
}) {
  return (
    <div className="space-y-8">
      {/* Meldewege */}
      <section className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">Meldewege (intern → Aufsichtsbehoerde)</h3>
        <p className="text-sm text-gray-500 mb-4">
          Definieren Sie die interne Eskalationskette bei einer Datenpanne.
        </p>
        <div className="space-y-3">
          {config.meldewege.map((step, idx) => (
            <div key={step.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
              <span className="flex-shrink-0 w-8 h-8 rounded-full bg-blue-100 text-blue-800 flex items-center justify-center text-sm font-bold">
                {step.order}
              </span>
              <div className="flex-1 grid grid-cols-3 gap-2">
                <input
                  type="text"
                  value={step.role}
                  onChange={e => {
                    const updated = [...config.meldewege]
                    updated[idx] = { ...updated[idx], role: e.target.value }
                    setConfig(prev => ({ ...prev, meldewege: updated }))
                  }}
                  placeholder="Rolle"
                  className="text-sm border rounded px-2 py-1"
                />
                <input
                  type="text"
                  value={step.name}
                  onChange={e => {
                    const updated = [...config.meldewege]
                    updated[idx] = { ...updated[idx], name: e.target.value }
                    setConfig(prev => ({ ...prev, meldewege: updated }))
                  }}
                  placeholder="Name"
                  className="text-sm border rounded px-2 py-1"
                />
                <input
                  type="text"
                  value={step.action}
                  onChange={e => {
                    const updated = [...config.meldewege]
                    updated[idx] = { ...updated[idx], action: e.target.value }
                    setConfig(prev => ({ ...prev, meldewege: updated }))
                  }}
                  placeholder="Aktion"
                  className="text-sm border rounded px-2 py-1"
                />
              </div>
              <div className="flex-shrink-0 text-xs text-gray-500">
                max. {step.maxHours}h
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Zustaendigkeiten */}
      <section className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">Zustaendigkeiten</h3>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b">
                <th className="text-left py-2 pr-4">Rolle</th>
                <th className="text-left py-2 pr-4">Name</th>
                <th className="text-left py-2 pr-4">E-Mail</th>
                <th className="text-left py-2">Telefon</th>
              </tr>
            </thead>
            <tbody>
              {config.zustaendigkeiten.map((z, idx) => (
                <tr key={z.id} className="border-b last:border-0">
                  <td className="py-2 pr-4 font-medium">{z.role}</td>
                  <td className="py-2 pr-4">
                    <input
                      type="text"
                      value={z.name}
                      onChange={e => {
                        const updated = [...config.zustaendigkeiten]
                        updated[idx] = { ...updated[idx], name: e.target.value }
                        setConfig(prev => ({ ...prev, zustaendigkeiten: updated }))
                      }}
                      placeholder="Name eingeben"
                      className="w-full text-sm border rounded px-2 py-1"
                    />
                  </td>
                  <td className="py-2 pr-4">
                    <input
                      type="email"
                      value={z.email}
                      onChange={e => {
                        const updated = [...config.zustaendigkeiten]
                        updated[idx] = { ...updated[idx], email: e.target.value }
                        setConfig(prev => ({ ...prev, zustaendigkeiten: updated }))
                      }}
                      placeholder="email@example.com"
                      className="w-full text-sm border rounded px-2 py-1"
                    />
                  </td>
                  <td className="py-2">
                    <input
                      type="tel"
                      value={z.phone}
                      onChange={e => {
                        const updated = [...config.zustaendigkeiten]
                        updated[idx] = { ...updated[idx], phone: e.target.value }
                        setConfig(prev => ({ ...prev, zustaendigkeiten: updated }))
                      }}
                      placeholder="+49..."
                      className="w-full text-sm border rounded px-2 py-1"
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      {/* Aufsichtsbehoerde */}
      <section className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">Zustaendige Aufsichtsbehoerde</h3>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
            <input
              type="text"
              value={config.aufsichtsbehoerde.name}
              onChange={e => setConfig(prev => ({
                ...prev,
                aufsichtsbehoerde: { ...prev.aufsichtsbehoerde, name: e.target.value },
              }))}
              placeholder="z.B. LfD Niedersachsen"
              className="w-full text-sm border rounded px-3 py-2"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Bundesland</label>
            <input
              type="text"
              value={config.aufsichtsbehoerde.state}
              onChange={e => setConfig(prev => ({
                ...prev,
                aufsichtsbehoerde: { ...prev.aufsichtsbehoerde, state: e.target.value },
              }))}
              placeholder="z.B. Niedersachsen"
              className="w-full text-sm border rounded px-3 py-2"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">E-Mail</label>
            <input
              type="email"
              value={config.aufsichtsbehoerde.email}
              onChange={e => setConfig(prev => ({
                ...prev,
                aufsichtsbehoerde: { ...prev.aufsichtsbehoerde, email: e.target.value },
              }))}
              placeholder="poststelle@lfd.niedersachsen.de"
              className="w-full text-sm border rounded px-3 py-2"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Telefon</label>
            <input
              type="tel"
              value={config.aufsichtsbehoerde.phone}
              onChange={e => setConfig(prev => ({
                ...prev,
                aufsichtsbehoerde: { ...prev.aufsichtsbehoerde, phone: e.target.value },
              }))}
              placeholder="+49..."
              className="w-full text-sm border rounded px-3 py-2"
            />
          </div>
        </div>
      </section>

      {/* Eskalationsstufen */}
      <section className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">Eskalationsstufen</h3>
        <div className="space-y-4">
          {config.eskalationsstufen.map((stufe) => (
            <div key={stufe.id} className="p-4 bg-gray-50 rounded-lg">
              <div className="flex items-center gap-3 mb-2">
                <span className={`px-2 py-1 rounded text-xs font-bold ${
                  stufe.level === 1 ? 'bg-yellow-100 text-yellow-800' :
                  stufe.level === 2 ? 'bg-orange-100 text-orange-800' :
                  'bg-red-100 text-red-800'
                }`}>
                  Stufe {stufe.level}
                </span>
                <span className="font-medium">{stufe.label}</span>
              </div>
              <p className="text-sm text-gray-600 mb-2">Ausloeser: {stufe.triggerCondition}</p>
              <ul className="list-disc list-inside text-sm text-gray-700">
                {stufe.actions.map((action, i) => (
                  <li key={i}>{action}</li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </section>

      {/* Sofortmassnahmen-Checkliste */}
      <section className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">Sofortmassnahmen-Checkliste</h3>
        <p className="text-sm text-gray-500 mb-4">
          Diese Massnahmen sind sofort bei Entdeckung einer Datenpanne durchzufuehren.
        </p>
        <ul className="space-y-2">
          {config.sofortmassnahmen.map((m, idx) => (
            <li key={idx} className="flex items-start gap-3 p-2">
              <span className="flex-shrink-0 w-6 h-6 rounded border-2 border-gray-300 mt-0.5" />
              <span className="text-sm">{m}</span>
            </li>
          ))}
        </ul>
      </section>
    </div>
  )
}

// =============================================================================
// TAB 2: Incident-Register
// =============================================================================

function IncidentsTab({
  incidents,
  setIncidents,
  showAdd,
  setShowAdd,
  onAdd,
  onStatusChange,
  onDelete,
}: {
  incidents: Incident[]
  setIncidents: React.Dispatch<React.SetStateAction<Incident[]>>
  showAdd: boolean
  setShowAdd: (v: boolean) => void
  onAdd?: (incident: Partial<Incident>) => Promise<void>
  onStatusChange?: (id: string, status: IncidentStatus) => Promise<void>
  onDelete?: (id: string) => Promise<void>
}) {
  const [newIncident, setNewIncident] = useState<Partial<Incident>>({
    title: '',
    description: '',
    severity: 'medium',
    affectedDataCategories: [],
    estimatedAffectedPersons: 0,
    measures: [],
    art34Required: false,
    art34Justification: '',
  })

  async function addIncident() {
    if (!newIncident.title) return
    if (onAdd) {
      await onAdd(newIncident)
    } else {
      const incident: Incident = {
        id: `INC-${Date.now()}`,
        title: newIncident.title || '',
        description: newIncident.description || '',
        detectedAt: new Date().toISOString(),
        detectedBy: 'Admin',
        status: 'detected',
        severity: newIncident.severity as IncidentSeverity || 'medium',
        affectedDataCategories: newIncident.affectedDataCategories || [],
        estimatedAffectedPersons: newIncident.estimatedAffectedPersons || 0,
        measures: newIncident.measures || [],
        art34Required: newIncident.art34Required || false,
        art34Justification: newIncident.art34Justification || '',
      }
      setIncidents(prev => [incident, ...prev])
    }
    setShowAdd(false)
    setNewIncident({
      title: '', description: '', severity: 'medium',
      affectedDataCategories: [], estimatedAffectedPersons: 0,
      measures: [], art34Required: false, art34Justification: '',
    })
  }

  async function updateStatus(id: string, status: IncidentStatus) {
    if (onStatusChange) {
      await onStatusChange(id, status)
    } else {
      setIncidents(prev => prev.map(inc =>
        inc.id === id
          ? {
              ...inc,
              status,
              ...(status === 'reported' ? { reportedToAuthorityAt: new Date().toISOString() } : {}),
              ...(status === 'closed' ? { closedAt: new Date().toISOString(), closedBy: 'Admin' } : {}),
            }
          : inc
      ))
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">Incident-Register (Art. 33 Abs. 5)</h3>
          <p className="text-sm text-gray-500">Alle Datenpannen dokumentieren — auch nicht-meldepflichtige.</p>
        </div>
        <button
          onClick={() => setShowAdd(true)}
          className="px-4 py-2 bg-red-600 text-white rounded-lg text-sm font-medium hover:bg-red-700"
        >
          + Datenpanne melden
        </button>
      </div>

      {/* Add Incident Form */}
      {showAdd && (
        <div className="bg-white rounded-lg border p-6 space-y-4">
          <h4 className="font-medium">Neue Datenpanne erfassen</h4>
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">Titel</label>
              <input
                type="text"
                value={newIncident.title}
                onChange={e => setNewIncident(prev => ({ ...prev, title: e.target.value }))}
                placeholder="Kurzbeschreibung der Datenpanne"
                className="w-full border rounded px-3 py-2 text-sm"
              />
            </div>
            <div className="col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
              <textarea
                value={newIncident.description}
                onChange={e => setNewIncident(prev => ({ ...prev, description: e.target.value }))}
                placeholder="Detaillierte Beschreibung: Was ist passiert, wie wurde es entdeckt?"
                rows={3}
                className="w-full border rounded px-3 py-2 text-sm"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Schweregrad</label>
              <select
                value={newIncident.severity}
                onChange={e => setNewIncident(prev => ({ ...prev, severity: e.target.value as IncidentSeverity }))}
                className="w-full border rounded px-3 py-2 text-sm"
              >
                <option value="low">Niedrig</option>
                <option value="medium">Mittel</option>
                <option value="high">Hoch</option>
                <option value="critical">Kritisch</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Geschaetzte Betroffene</label>
              <input
                type="number"
                value={newIncident.estimatedAffectedPersons}
                onChange={e => setNewIncident(prev => ({ ...prev, estimatedAffectedPersons: parseInt(e.target.value) || 0 }))}
                className="w-full border rounded px-3 py-2 text-sm"
              />
            </div>
            <div className="col-span-2 flex items-center gap-2">
              <input
                type="checkbox"
                checked={newIncident.art34Required}
                onChange={e => setNewIncident(prev => ({ ...prev, art34Required: e.target.checked }))}
                className="rounded"
              />
              <label className="text-sm">Hohes Risiko fuer Betroffene (Art. 34 Benachrichtigungspflicht)</label>
            </div>
          </div>
          <div className="flex gap-2 justify-end">
            <button
              onClick={() => setShowAdd(false)}
              className="px-4 py-2 border rounded-lg text-sm"
            >
              Abbrechen
            </button>
            <button
              onClick={addIncident}
              disabled={!newIncident.title}
              className="px-4 py-2 bg-red-600 text-white rounded-lg text-sm font-medium hover:bg-red-700 disabled:opacity-50"
            >
              Datenpanne erfassen
            </button>
          </div>
        </div>
      )}

      {/* Incidents List */}
      {incidents.length === 0 ? (
        <div className="bg-white rounded-lg border p-12 text-center text-gray-500">
          <p className="text-lg mb-2">Keine Datenpannen erfasst</p>
          <p className="text-sm">Dokumentieren Sie hier alle Datenpannen — auch solche, die nicht meldepflichtig sind (Art. 33 Abs. 5).</p>
        </div>
      ) : (
        <div className="space-y-4">
          {incidents.map(incident => (
            <div key={incident.id} className="bg-white rounded-lg border p-6">
              <div className="flex items-start justify-between mb-3">
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs text-gray-500 font-mono">{incident.id}</span>
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${INCIDENT_STATUS_COLORS[incident.status]}`}>
                      {INCIDENT_STATUS_LABELS[incident.status]}
                    </span>
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${SEVERITY_COLORS[incident.severity]}`}>
                      {SEVERITY_LABELS[incident.severity]}
                    </span>
                    {incident.art34Required && (
                      <span className="px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                        Art. 34
                      </span>
                    )}
                  </div>
                  <h4 className="font-medium">{incident.title}</h4>
                </div>
                {incident.status !== 'closed' && incident.status !== 'reported' && incident.status !== 'not_reportable' && (
                  <CountdownTimer detectedAt={incident.detectedAt} />
                )}
              </div>
              <p className="text-sm text-gray-600 mb-3">{incident.description}</p>
              <div className="flex items-center gap-4 text-xs text-gray-500 mb-3">
                <span>Entdeckt: {new Date(incident.detectedAt).toLocaleString('de-DE')}</span>
                <span>Betroffene: ~{incident.estimatedAffectedPersons}</span>
                {incident.reportedToAuthorityAt && (
                  <span>Gemeldet: {new Date(incident.reportedToAuthorityAt).toLocaleString('de-DE')}</span>
                )}
              </div>
              {incident.status !== 'closed' && (
                <div className="flex gap-2">
                  {incident.status === 'detected' && (
                    <button onClick={() => updateStatus(incident.id, 'classified')} className="text-xs px-3 py-1 bg-yellow-100 text-yellow-800 rounded hover:bg-yellow-200">
                      Klassifizieren
                    </button>
                  )}
                  {incident.status === 'classified' && (
                    <button onClick={() => updateStatus(incident.id, 'assessed')} className="text-xs px-3 py-1 bg-blue-100 text-blue-800 rounded hover:bg-blue-200">
                      Bewerten
                    </button>
                  )}
                  {incident.status === 'assessed' && (
                    <>
                      <button onClick={() => updateStatus(incident.id, 'reported')} className="text-xs px-3 py-1 bg-green-100 text-green-800 rounded hover:bg-green-200">
                        Als gemeldet markieren
                      </button>
                      <button onClick={() => updateStatus(incident.id, 'not_reportable')} className="text-xs px-3 py-1 bg-gray-100 text-gray-800 rounded hover:bg-gray-200">
                        Nicht meldepflichtig
                      </button>
                    </>
                  )}
                  {(incident.status === 'reported' || incident.status === 'not_reportable') && (
                    <button onClick={() => updateStatus(incident.id, 'closed')} className="text-xs px-3 py-1 bg-gray-100 text-gray-600 rounded hover:bg-gray-200">
                      Abschliessen
                    </button>
                  )}
                  {onDelete && (
                    <button
                      onClick={() => { if (window.confirm('Incident loeschen?')) onDelete(incident.id) }}
                      className="text-xs px-2 py-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded ml-auto"
                    >
                      Loeschen
                    </button>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

// =============================================================================
// TAB 3: Melde-Templates
// =============================================================================

function TemplatesTab({
  templates,
  setTemplates,
  onSave,
}: {
  templates: MeldeTemplate[]
  setTemplates: React.Dispatch<React.SetStateAction<MeldeTemplate[]>>
  onSave?: (template: MeldeTemplate) => Promise<void>
}) {
  const [saving, setSaving] = useState<string | null>(null)

  async function handleSave(template: MeldeTemplate) {
    if (!onSave) return
    setSaving(template.id)
    try {
      await onSave(template)
    } finally {
      setSaving(null)
    }
  }

  return (
    <div className="space-y-6">
      <div>
        <h3 className="text-lg font-semibold">Melde-Templates</h3>
        <p className="text-sm text-gray-500">
          Vorlagen fuer Meldungen an die Aufsichtsbehoerde (Art. 33) und Benachrichtigung Betroffener (Art. 34).
        </p>
      </div>

      {templates.map(template => (
        <div key={template.id} className="bg-white rounded-lg border p-6">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <span className={`px-2 py-1 rounded text-xs font-bold ${
                template.type === 'art33'
                  ? 'bg-blue-100 text-blue-800'
                  : 'bg-purple-100 text-purple-800'
              }`}>
                {template.type === 'art33' ? 'Art. 33' : 'Art. 34'}
              </span>
              <h4 className="font-medium">{template.title}</h4>
            </div>
            {onSave && (
              <button
                onClick={() => handleSave(template)}
                disabled={saving === template.id}
                className="px-3 py-1 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
              >
                {saving === template.id ? 'Gespeichert...' : 'Speichern'}
              </button>
            )}
          </div>
          <textarea
            value={template.content}
            onChange={e => {
              setTemplates(prev => prev.map(t =>
                t.id === template.id ? { ...t, content: e.target.value } : t
              ))
            }}
            rows={12}
            className="w-full border rounded px-3 py-2 text-sm font-mono"
          />
        </div>
      ))}
    </div>
  )
}

// =============================================================================
// TAB 4: Uebungen & Tests
// =============================================================================

function ExercisesTab({
  exercises,
  setExercises,
  showAdd,
  setShowAdd,
}: {
  exercises: Exercise[]
  setExercises: React.Dispatch<React.SetStateAction<Exercise[]>>
  showAdd: boolean
  setShowAdd: (v: boolean) => void
}) {
  const [newExercise, setNewExercise] = useState<Partial<Exercise>>({
    title: '',
    type: 'tabletop',
    scenario: '',
    scheduledDate: '',
    participants: [],
    lessonsLearned: '',
  })

  const SCENARIO_PRESETS = [
    { label: 'Ransomware-Angriff', scenario: 'Ein Ransomware-Angriff verschluesselt saemtliche Produktivdaten. Backups sind vorhanden, aber der letzte Restore-Test liegt 6 Monate zurueck.' },
    { label: 'Datenabfluss durch Mitarbeiter', scenario: 'Ein ausscheidender Mitarbeiter hat vor seinem letzten Arbeitstag umfangreiche Kundendaten auf einen privaten USB-Stick kopiert.' },
    { label: 'Cloud-Provider-Ausfall', scenario: 'Ihr primaerer Cloud-Provider meldet einen groesseren Ausfall. Die Wiederherstellungszeit ist unbekannt. Betroffene koennen keine DSGVO-Rechte ausueben.' },
    { label: 'Phishing-Angriff', scenario: 'Mehrere Mitarbeiter haben auf einen Phishing-Link geklickt. Es besteht Verdacht, dass Anmeldedaten kompromittiert wurden und auf Personaldaten zugegriffen wurde.' },
  ]

  function addExercise() {
    if (!newExercise.title || !newExercise.scheduledDate) return
    const exercise: Exercise = {
      id: `EX-${Date.now()}`,
      title: newExercise.title || '',
      type: (newExercise.type as Exercise['type']) || 'tabletop',
      scenario: newExercise.scenario || '',
      scheduledDate: newExercise.scheduledDate || '',
      participants: newExercise.participants || [],
      lessonsLearned: '',
    }
    setExercises(prev => [...prev, exercise])
    setShowAdd(false)
    setNewExercise({ title: '', type: 'tabletop', scenario: '', scheduledDate: '', participants: [], lessonsLearned: '' })
  }

  function completeExercise(id: string, lessonsLearned: string) {
    setExercises(prev => prev.map(ex =>
      ex.id === id
        ? { ...ex, completedDate: new Date().toISOString(), lessonsLearned }
        : ex
    ))
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">Notfalluebungen & Tests</h3>
          <p className="text-sm text-gray-500">Planen und dokumentieren Sie regelmaessige Notfalluebungen.</p>
        </div>
        <button
          onClick={() => setShowAdd(true)}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700"
        >
          + Uebung planen
        </button>
      </div>

      {/* Add Exercise Form */}
      {showAdd && (
        <div className="bg-white rounded-lg border p-6 space-y-4">
          <h4 className="font-medium">Neue Uebung planen</h4>
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">Titel</label>
              <input
                type="text"
                value={newExercise.title}
                onChange={e => setNewExercise(prev => ({ ...prev, title: e.target.value }))}
                placeholder="z.B. Tabletop: Ransomware-Angriff"
                className="w-full border rounded px-3 py-2 text-sm"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Typ</label>
              <select
                value={newExercise.type}
                onChange={e => setNewExercise(prev => ({ ...prev, type: e.target.value as Exercise['type'] }))}
                className="w-full border rounded px-3 py-2 text-sm"
              >
                <option value="tabletop">Tabletop-Uebung</option>
                <option value="simulation">Simulation</option>
                <option value="full_drill">Vollstaendige Uebung</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Geplantes Datum</label>
              <input
                type="date"
                value={newExercise.scheduledDate}
                onChange={e => setNewExercise(prev => ({ ...prev, scheduledDate: e.target.value }))}
                className="w-full border rounded px-3 py-2 text-sm"
              />
            </div>
            <div className="col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Szenario
                <span className="text-gray-400 font-normal ml-2">oder Vorlage waehlen:</span>
              </label>
              <div className="flex flex-wrap gap-2 mb-2">
                {SCENARIO_PRESETS.map(preset => (
                  <button
                    key={preset.label}
                    onClick={() => setNewExercise(prev => ({
                      ...prev,
                      scenario: preset.scenario,
                      title: prev.title || `Tabletop: ${preset.label}`,
                    }))}
                    className="text-xs px-3 py-1 bg-gray-100 rounded-full hover:bg-gray-200"
                  >
                    {preset.label}
                  </button>
                ))}
              </div>
              <textarea
                value={newExercise.scenario}
                onChange={e => setNewExercise(prev => ({ ...prev, scenario: e.target.value }))}
                placeholder="Beschreiben Sie das Uebungsszenario..."
                rows={3}
                className="w-full border rounded px-3 py-2 text-sm"
              />
            </div>
          </div>
          <div className="flex gap-2 justify-end">
            <button onClick={() => setShowAdd(false)} className="px-4 py-2 border rounded-lg text-sm">
              Abbrechen
            </button>
            <button
              onClick={addExercise}
              disabled={!newExercise.title || !newExercise.scheduledDate}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
            >
              Uebung planen
            </button>
          </div>
        </div>
      )}

      {/* Exercises List */}
      {exercises.length === 0 ? (
        <div className="bg-white rounded-lg border p-12 text-center text-gray-500">
          <p className="text-lg mb-2">Keine Uebungen geplant</p>
          <p className="text-sm">Regelmaessige Notfalluebungen sind essentiell fuer ein funktionierendes Datenpannen-Management.</p>
        </div>
      ) : (
        <div className="space-y-4">
          {exercises.map(exercise => (
            <div key={exercise.id} className="bg-white rounded-lg border p-6">
              <div className="flex items-center gap-2 mb-2">
                <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                  exercise.completedDate ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'
                }`}>
                  {exercise.completedDate ? 'Abgeschlossen' : 'Geplant'}
                </span>
                <span className="text-xs text-gray-500 capitalize">
                  {exercise.type === 'tabletop' ? 'Tabletop' : exercise.type === 'simulation' ? 'Simulation' : 'Vollstaendige Uebung'}
                </span>
              </div>
              <h4 className="font-medium mb-1">{exercise.title}</h4>
              <p className="text-sm text-gray-600 mb-2">{exercise.scenario}</p>
              <div className="flex items-center gap-4 text-xs text-gray-500">
                <span>Geplant: {new Date(exercise.scheduledDate).toLocaleDateString('de-DE')}</span>
                {exercise.completedDate && (
                  <span>Durchgefuehrt: {new Date(exercise.completedDate).toLocaleDateString('de-DE')}</span>
                )}
              </div>
              {exercise.lessonsLearned && (
                <div className="mt-3 p-3 bg-blue-50 rounded text-sm">
                  <span className="font-medium text-blue-800">Lessons Learned:</span>
                  <p className="text-blue-700 mt-1">{exercise.lessonsLearned}</p>
                </div>
              )}
              {!exercise.completedDate && (
                <div className="mt-3">
                  <button
                    onClick={() => {
                      const lessons = prompt('Lessons Learned aus der Uebung:')
                      if (lessons !== null) {
                        completeExercise(exercise.id, lessons)
                      }
                    }}
                    className="text-xs px-3 py-1 bg-green-100 text-green-800 rounded hover:bg-green-200"
                  >
                    Als durchgefuehrt markieren
                  </button>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
