'use client'

import React, { useState, useEffect, useCallback } from 'react'
import Link from 'next/link'
import { useParams, useRouter } from 'next/navigation'
import {
  DSFA,
  DSFARisk,
  DSFAMitigation,
  DSFA_SECTIONS,
  DSFA_STATUS_LABELS,
  DSFA_RISK_LEVEL_LABELS,
  DSFA_LEGAL_BASES,
  DSFA_AFFECTED_RIGHTS,
  calculateRiskLevel,
  SDM_GOALS,
} from '@/lib/sdk/dsfa/types'
import type { SDMGoal, DSFARiskCategory } from '@/lib/sdk/dsfa/types'
import {
  RISK_CATALOG,
  RISK_CATEGORY_LABELS,
  COMPONENT_FAMILY_LABELS,
  getRisksByCategory,
  getRisksBySDMGoal,
} from '@/lib/sdk/dsfa/risk-catalog'
import type { CatalogRisk } from '@/lib/sdk/dsfa/risk-catalog'
import {
  MITIGATION_LIBRARY,
  MITIGATION_TYPE_LABELS,
  SDM_GOAL_LABELS,
  EFFECTIVENESS_LABELS,
  getMitigationsBySDMGoal,
  getMitigationsByType,
  getMitigationsForRisk,
} from '@/lib/sdk/dsfa/mitigation-library'
import type { CatalogMitigation } from '@/lib/sdk/dsfa/mitigation-library'
import {
  getDSFA,
  updateDSFASection,
  addDSFARisk,
  removeDSFARisk,
  addDSFAMitigation,
  updateDSFAMitigationStatus,
  updateDSFA,
} from '@/lib/sdk/dsfa/api'
import {
  RiskMatrix,
  ApprovalPanel,
  DSFASidebar,
  ThresholdAnalysisSection,
  StakeholderConsultationSection,
  Art36Warning,
  ReviewScheduleSection,
} from '@/components/sdk/dsfa'
import { SourceAttribution } from '@/components/sdk/dsfa/SourceAttribution'
import type { DSFALicenseCode, SourceAttributionProps } from '@/lib/sdk/types'

// =============================================================================
// SECTION EDITORS
// =============================================================================

interface SectionProps {
  dsfa: DSFA
  onUpdate: (data: Record<string, unknown>) => Promise<void>
  isSubmitting: boolean
}

// Section 1: Systematische Beschreibung (Art. 35 Abs. 7 lit. a)
function Section1Editor({ dsfa, onUpdate, isSubmitting }: SectionProps) {
  const [formData, setFormData] = useState({
    processing_description: dsfa.processing_description || '',
    processing_purpose: dsfa.processing_purpose || '',
    data_categories: dsfa.data_categories || [],
    data_subjects: dsfa.data_subjects || [],
    recipients: dsfa.recipients || [],
    legal_basis: dsfa.legal_basis || '',
    legal_basis_details: dsfa.legal_basis_details || '',
  })
  const [newCategory, setNewCategory] = useState('')
  const [newSubject, setNewSubject] = useState('')
  const [newRecipient, setNewRecipient] = useState('')

  const handleSave = () => {
    onUpdate(formData)
  }

  const addItem = (field: 'data_categories' | 'data_subjects' | 'recipients', value: string, setter: (v: string) => void) => {
    if (value.trim()) {
      setFormData(prev => ({
        ...prev,
        [field]: [...prev[field], value.trim()]
      }))
      setter('')
    }
  }

  const removeItem = (field: 'data_categories' | 'data_subjects' | 'recipients', index: number) => {
    setFormData(prev => ({
      ...prev,
      [field]: prev[field].filter((_, i) => i !== index)
    }))
  }

  return (
    <div className="space-y-6">
      {/* Processing Purpose */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Verarbeitungszweck *
        </label>
        <textarea
          value={formData.processing_purpose}
          onChange={(e) => setFormData(prev => ({ ...prev, processing_purpose: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={3}
          placeholder="Beschreiben Sie den Zweck der Datenverarbeitung..."
        />
      </div>

      {/* Processing Description */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Beschreibung der Verarbeitung *
        </label>
        <textarea
          value={formData.processing_description}
          onChange={(e) => setFormData(prev => ({ ...prev, processing_description: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={4}
          placeholder="Detaillierte Beschreibung der Verarbeitungsvorgaenge..."
        />
      </div>

      {/* Data Categories */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Datenkategorien *
        </label>
        <div className="flex flex-wrap gap-2 mb-2">
          {formData.data_categories.map((cat, idx) => (
            <span key={idx} className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm flex items-center gap-2">
              {cat}
              <button onClick={() => removeItem('data_categories', idx)} className="hover:text-blue-900">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </span>
          ))}
        </div>
        <div className="flex gap-2">
          <input
            type="text"
            value={newCategory}
            onChange={(e) => setNewCategory(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && addItem('data_categories', newCategory, setNewCategory)}
            className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
            placeholder="Kategorie hinzufuegen..."
          />
          <button
            onClick={() => addItem('data_categories', newCategory, setNewCategory)}
            className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
          >
            +
          </button>
        </div>
      </div>

      {/* Data Subjects */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Betroffene Personen *
        </label>
        <div className="flex flex-wrap gap-2 mb-2">
          {formData.data_subjects.map((subj, idx) => (
            <span key={idx} className="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm flex items-center gap-2">
              {subj}
              <button onClick={() => removeItem('data_subjects', idx)} className="hover:text-green-900">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </span>
          ))}
        </div>
        <div className="flex gap-2">
          <input
            type="text"
            value={newSubject}
            onChange={(e) => setNewSubject(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && addItem('data_subjects', newSubject, setNewSubject)}
            className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
            placeholder="z.B. Kunden, Mitarbeiter..."
          />
          <button
            onClick={() => addItem('data_subjects', newSubject, setNewSubject)}
            className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
          >
            +
          </button>
        </div>
      </div>

      {/* Recipients */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Empfaenger
        </label>
        <div className="flex flex-wrap gap-2 mb-2">
          {formData.recipients.map((rec, idx) => (
            <span key={idx} className="px-3 py-1 bg-orange-100 text-orange-700 rounded-full text-sm flex items-center gap-2">
              {rec}
              <button onClick={() => removeItem('recipients', idx)} className="hover:text-orange-900">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </span>
          ))}
        </div>
        <div className="flex gap-2">
          <input
            type="text"
            value={newRecipient}
            onChange={(e) => setNewRecipient(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && addItem('recipients', newRecipient, setNewRecipient)}
            className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
            placeholder="Empfaenger hinzufuegen..."
          />
          <button
            onClick={() => addItem('recipients', newRecipient, setNewRecipient)}
            className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
          >
            +
          </button>
        </div>
      </div>

      {/* Legal Basis */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Rechtsgrundlage *
        </label>
        <select
          value={formData.legal_basis}
          onChange={(e) => setFormData(prev => ({ ...prev, legal_basis: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
        >
          <option value="">Bitte waehlen...</option>
          {Object.entries(DSFA_LEGAL_BASES).map(([key, label]) => (
            <option key={key} value={key}>{label}</option>
          ))}
        </select>
      </div>

      {/* Legal Basis Details */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Begruendung der Rechtsgrundlage
        </label>
        <textarea
          value={formData.legal_basis_details}
          onChange={(e) => setFormData(prev => ({ ...prev, legal_basis_details: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={3}
          placeholder="Erlaeutern Sie, warum diese Rechtsgrundlage anwendbar ist..."
        />
      </div>

      {/* Save Button */}
      <div className="flex justify-end pt-4 border-t border-gray-200">
        <button
          onClick={handleSave}
          disabled={isSubmitting}
          className="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
        >
          {isSubmitting ? 'Speichern...' : 'Abschnitt speichern'}
        </button>
      </div>
    </div>
  )
}

// Section 2: Notwendigkeit & Verhaeltnismaessigkeit (Art. 35 Abs. 7 lit. b)
function Section2Editor({ dsfa, onUpdate, isSubmitting }: SectionProps) {
  const [formData, setFormData] = useState({
    necessity_assessment: dsfa.necessity_assessment || '',
    proportionality_assessment: dsfa.proportionality_assessment || '',
    data_minimization: dsfa.data_minimization || '',
    alternatives_considered: dsfa.alternatives_considered || '',
    retention_justification: dsfa.retention_justification || '',
  })

  const handleSave = () => {
    onUpdate(formData)
  }

  return (
    <div className="space-y-6">
      {/* Necessity */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Notwendigkeit der Verarbeitung *
        </label>
        <p className="text-xs text-gray-500 mb-2">
          Erklaeren Sie, warum die Verarbeitung fuer den angegebenen Zweck notwendig ist.
        </p>
        <textarea
          value={formData.necessity_assessment}
          onChange={(e) => setFormData(prev => ({ ...prev, necessity_assessment: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={4}
          placeholder="Beschreiben Sie die Notwendigkeit..."
        />
      </div>

      {/* Proportionality */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Verhaeltnismaessigkeit *
        </label>
        <p className="text-xs text-gray-500 mb-2">
          Begruenden Sie, warum der Eingriff in die Rechte der Betroffenen verhaeltnismaessig ist.
        </p>
        <textarea
          value={formData.proportionality_assessment}
          onChange={(e) => setFormData(prev => ({ ...prev, proportionality_assessment: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={4}
          placeholder="Beschreiben Sie die Verhaeltnismaessigkeit..."
        />
      </div>

      {/* Data Minimization */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Datenminimierung
        </label>
        <p className="text-xs text-gray-500 mb-2">
          Welche Massnahmen wurden ergriffen, um nur die notwendigen Daten zu erheben?
        </p>
        <textarea
          value={formData.data_minimization}
          onChange={(e) => setFormData(prev => ({ ...prev, data_minimization: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={3}
          placeholder="Beschreiben Sie die Datenminimierungsmassnahmen..."
        />
      </div>

      {/* Alternatives */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Gepruefe Alternativen
        </label>
        <p className="text-xs text-gray-500 mb-2">
          Welche weniger eingriffsintensiven Alternativen wurden geprueft?
        </p>
        <textarea
          value={formData.alternatives_considered}
          onChange={(e) => setFormData(prev => ({ ...prev, alternatives_considered: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={3}
          placeholder="Beschreiben Sie gepruefe Alternativen..."
        />
      </div>

      {/* Retention */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Speicherdauer / Loeschfristen
        </label>
        <textarea
          value={formData.retention_justification}
          onChange={(e) => setFormData(prev => ({ ...prev, retention_justification: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={3}
          placeholder="Begruenden Sie die geplante Speicherdauer..."
        />
      </div>

      {/* Save Button */}
      <div className="flex justify-end pt-4 border-t border-gray-200">
        <button
          onClick={handleSave}
          disabled={isSubmitting}
          className="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
        >
          {isSubmitting ? 'Speichern...' : 'Abschnitt speichern'}
        </button>
      </div>
    </div>
  )
}

// Section 3: Risikobewertung (Art. 35 Abs. 7 lit. c)
function Section3Editor({ dsfa, onUpdate, isSubmitting }: SectionProps) {
  const [selectedRisk, setSelectedRisk] = useState<DSFARisk | null>(null)
  const [showAddRiskModal, setShowAddRiskModal] = useState(false)
  const [newRiskLikelihood, setNewRiskLikelihood] = useState<'low' | 'medium' | 'high'>('medium')
  const [newRiskImpact, setNewRiskImpact] = useState<'low' | 'medium' | 'high'>('medium')
  const [affectedRights, setAffectedRights] = useState<string[]>(dsfa.affected_rights || [])

  const handleAddRisk = (likelihood: 'low' | 'medium' | 'high', impact: 'low' | 'medium' | 'high') => {
    setNewRiskLikelihood(likelihood)
    setNewRiskImpact(impact)
    setShowAddRiskModal(true)
  }

  const toggleAffectedRight = (rightId: string) => {
    setAffectedRights(prev =>
      prev.includes(rightId)
        ? prev.filter(r => r !== rightId)
        : [...prev, rightId]
    )
  }

  const handleSaveSection = () => {
    onUpdate({
      affected_rights: affectedRights,
      overall_risk_level: dsfa.overall_risk_level,
    })
  }

  return (
    <div className="space-y-6">
      {/* Risk Matrix */}
      <div className="bg-gray-50 rounded-xl p-6">
        <RiskMatrix
          risks={dsfa.risks || []}
          onRiskSelect={(risk) => setSelectedRisk(risk)}
          onAddRisk={handleAddRisk}
          selectedRiskId={selectedRisk?.id}
          readOnly={dsfa.status !== 'draft' && dsfa.status !== 'needs_update'}
        />
      </div>

      {/* Triggered Rules from UCCA */}
      {dsfa.triggered_rule_codes && dsfa.triggered_rule_codes.length > 0 && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4">
          <h4 className="text-sm font-medium text-red-800 mb-2">
            DSFA-ausloesende Regeln (aus UCCA)
          </h4>
          <div className="flex flex-wrap gap-2">
            {dsfa.triggered_rule_codes.map(code => (
              <span key={code} className="px-2 py-1 bg-red-100 text-red-700 rounded text-xs">
                {code}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Risk List */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">Identifizierte Risiken ({(dsfa.risks || []).length})</h4>
        {(dsfa.risks || []).length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            <svg className="w-12 h-12 mx-auto text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <p>Noch keine Risiken erfasst</p>
            <p className="text-sm mt-1">Klicken Sie in der Matrix auf eine Zelle, um ein Risiko hinzuzufuegen.</p>
          </div>
        ) : (
          <div className="space-y-3">
            {(dsfa.risks || []).map(risk => {
              const { level } = calculateRiskLevel(risk.likelihood, risk.impact)
              const levelColors = {
                low: 'bg-green-100 text-green-700 border-green-200',
                medium: 'bg-yellow-100 text-yellow-700 border-yellow-200',
                high: 'bg-orange-100 text-orange-700 border-orange-200',
                very_high: 'bg-red-100 text-red-700 border-red-200',
              }
              return (
                <div
                  key={risk.id}
                  className={`p-4 rounded-xl border cursor-pointer transition-all ${
                    selectedRisk?.id === risk.id ? 'ring-2 ring-purple-500' : ''
                  } ${levelColors[level]}`}
                  onClick={() => setSelectedRisk(risk)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="font-medium">{risk.description}</div>
                      <div className="text-sm mt-1 opacity-75">
                        Kategorie: {risk.category === 'confidentiality' ? 'Vertraulichkeit' :
                                    risk.category === 'integrity' ? 'Integritaet' :
                                    risk.category === 'availability' ? 'Verfuegbarkeit' :
                                    'Rechte & Freiheiten'}
                      </div>
                      <div className="text-sm opacity-75">
                        Eintrittswahrscheinlichkeit: {risk.likelihood === 'low' ? 'Niedrig' : risk.likelihood === 'medium' ? 'Mittel' : 'Hoch'} |
                        Auswirkung: {risk.impact === 'low' ? 'Niedrig' : risk.impact === 'medium' ? 'Mittel' : 'Hoch'}
                      </div>
                    </div>
                    <span className={`px-2 py-1 rounded text-xs font-medium ${levelColors[level]}`}>
                      {DSFA_RISK_LEVEL_LABELS[level]}
                    </span>
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>

      {/* RAG Search for Risks */}
      <RAGSearchPanel
        context={`Risiken Datenschutz-Folgenabschaetzung ${dsfa.processing_description || ''} ${dsfa.processing_purpose || ''}`}
        categories={['risk_assessment', 'threshold_analysis']}
      />

      {/* Affected Rights */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">Betroffene Rechte & Freiheiten</h4>
        <div className="grid grid-cols-2 gap-2">
          {DSFA_AFFECTED_RIGHTS.map(right => (
            <label
              key={right.id}
              className={`flex items-center gap-2 p-3 rounded-lg border cursor-pointer transition-colors ${
                affectedRights.includes(right.id)
                  ? 'bg-purple-50 border-purple-300'
                  : 'bg-white border-gray-200 hover:bg-gray-50'
              }`}
            >
              <input
                type="checkbox"
                checked={affectedRights.includes(right.id)}
                onChange={() => toggleAffectedRight(right.id)}
                className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
              />
              <span className="text-sm">{right.label}</span>
            </label>
          ))}
        </div>
      </div>

      {/* Save Button */}
      <div className="flex justify-end pt-4 border-t border-gray-200">
        <button
          onClick={handleSaveSection}
          disabled={isSubmitting}
          className="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
        >
          {isSubmitting ? 'Speichern...' : 'Abschnitt speichern'}
        </button>
      </div>

      {/* Add Risk Modal */}
      {showAddRiskModal && (
        <AddRiskModal
          likelihood={newRiskLikelihood}
          impact={newRiskImpact}
          onClose={() => setShowAddRiskModal(false)}
          onAdd={async (riskData) => {
            // This would call the API
            setShowAddRiskModal(false)
          }}
        />
      )}
    </div>
  )
}

// Section 4: Abhilfemassnahmen (Art. 35 Abs. 7 lit. d)
function Section4Editor({ dsfa, onUpdate, isSubmitting }: SectionProps) {
  const [showAddMitigation, setShowAddMitigation] = useState(false)

  const mitigationsByType = {
    technical: (dsfa.mitigations || []).filter(m => m.type === 'technical'),
    organizational: (dsfa.mitigations || []).filter(m => m.type === 'organizational'),
    legal: (dsfa.mitigations || []).filter(m => m.type === 'legal'),
  }

  const getStatusBadge = (status: string) => {
    const styles = {
      planned: 'bg-gray-100 text-gray-600',
      in_progress: 'bg-yellow-100 text-yellow-700',
      implemented: 'bg-blue-100 text-blue-700',
      verified: 'bg-green-100 text-green-700',
    }
    const labels = {
      planned: 'Geplant',
      in_progress: 'In Umsetzung',
      implemented: 'Umgesetzt',
      verified: 'Verifiziert',
    }
    return (
      <span className={`px-2 py-1 rounded text-xs font-medium ${styles[status as keyof typeof styles] || styles.planned}`}>
        {labels[status as keyof typeof labels] || status}
      </span>
    )
  }

  const renderMitigationSection = (
    title: string,
    icon: React.ReactNode,
    mitigations: DSFAMitigation[],
    bgColor: string
  ) => (
    <div>
      <div className="flex items-center gap-2 mb-3">
        {icon}
        <h4 className="text-sm font-medium text-gray-700">{title} ({mitigations.length})</h4>
      </div>
      {mitigations.length === 0 ? (
        <div className={`p-4 rounded-lg ${bgColor} text-center text-sm text-gray-500`}>
          Keine Massnahmen definiert
        </div>
      ) : (
        <div className="space-y-2">
          {mitigations.map(m => (
            <div key={m.id} className={`p-4 rounded-lg ${bgColor} border border-gray-200`}>
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="font-medium text-gray-900">{m.description}</div>
                  <div className="text-sm text-gray-500 mt-1">
                    Verantwortlich: {m.responsible_party || '-'}
                    {m.tom_reference && ` | TOM: ${m.tom_reference}`}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  {getStatusBadge(m.status)}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )

  return (
    <div className="space-y-6">
      {/* Add Mitigation Button */}
      <div className="flex justify-end">
        <button
          onClick={() => setShowAddMitigation(true)}
          className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
          Massnahme hinzufuegen
        </button>
      </div>

      {/* Technical Measures */}
      {renderMitigationSection(
        'Technische Massnahmen',
        <svg className="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
        </svg>,
        mitigationsByType.technical,
        'bg-blue-50'
      )}

      {/* Organizational Measures */}
      {renderMitigationSection(
        'Organisatorische Massnahmen',
        <svg className="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
        </svg>,
        mitigationsByType.organizational,
        'bg-green-50'
      )}

      {/* Legal Measures */}
      {renderMitigationSection(
        'Rechtliche Massnahmen',
        <svg className="w-5 h-5 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3" />
        </svg>,
        mitigationsByType.legal,
        'bg-purple-50'
      )}

      {/* RAG Search for Mitigations */}
      <RAGSearchPanel
        context={`Massnahmen Datenschutz-Folgenabschaetzung ${dsfa.processing_description || ''} ${dsfa.processing_purpose || ''}`}
        categories={['mitigation', 'risk_assessment']}
      />

      {/* TOM References */}
      {dsfa.tom_references && dsfa.tom_references.length > 0 && (
        <div className="bg-gray-50 rounded-xl p-4">
          <h4 className="text-sm font-medium text-gray-700 mb-2">Verknuepfte TOM-Eintraege</h4>
          <div className="flex flex-wrap gap-2">
            {dsfa.tom_references.map((ref, idx) => (
              <span key={idx} className="px-3 py-1 bg-white border border-gray-200 rounded-full text-sm text-gray-600">
                {ref}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Add Mitigation Modal */}
      {showAddMitigation && (
        <AddMitigationModal
          risks={dsfa.risks || []}
          onClose={() => setShowAddMitigation(false)}
          onAdd={async (mitigationData) => {
            // This would call the API
            setShowAddMitigation(false)
          }}
        />
      )}
    </div>
  )
}

// Section 5: Stellungnahme DSB (Art. 35 Abs. 2 + Art. 36)
function Section5Editor({ dsfa, onUpdate, isSubmitting }: SectionProps) {
  const [formData, setFormData] = useState({
    dpo_consulted: dsfa.dpo_consulted || false,
    dpo_name: dsfa.dpo_name || '',
    dpo_opinion: dsfa.dpo_opinion || '',
    authority_consulted: dsfa.authority_consulted || false,
    authority_reference: dsfa.authority_reference || '',
    authority_decision: dsfa.authority_decision || '',
  })

  const handleSave = () => {
    onUpdate(formData)
  }

  return (
    <div className="space-y-6">
      {/* DPO Consultation */}
      <div className="bg-blue-50 border border-blue-200 rounded-xl p-6">
        <div className="flex items-start gap-4">
          <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
            <svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
          </div>
          <div className="flex-1">
            <label className="flex items-center gap-3">
              <input
                type="checkbox"
                checked={formData.dpo_consulted}
                onChange={(e) => setFormData(prev => ({ ...prev, dpo_consulted: e.target.checked }))}
                className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span className="font-medium text-blue-800">
                Datenschutzbeauftragter wurde konsultiert
              </span>
            </label>
            <p className="text-sm text-blue-600 mt-2">
              Gemaess Art. 35 Abs. 2 DSGVO muss bei einer DSFA der Rat des DSB eingeholt werden.
            </p>
          </div>
        </div>

        {formData.dpo_consulted && (
          <div className="mt-4 space-y-4 pt-4 border-t border-blue-200">
            <div>
              <label className="block text-sm font-medium text-blue-800 mb-2">
                Name des DSB
              </label>
              <input
                type="text"
                value={formData.dpo_name}
                onChange={(e) => setFormData(prev => ({ ...prev, dpo_name: e.target.value }))}
                className="w-full px-4 py-2 border border-blue-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white"
                placeholder="Name des Datenschutzbeauftragten"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-blue-800 mb-2">
                Stellungnahme des DSB
              </label>
              <textarea
                value={formData.dpo_opinion}
                onChange={(e) => setFormData(prev => ({ ...prev, dpo_opinion: e.target.value }))}
                className="w-full px-4 py-3 border border-blue-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white"
                rows={4}
                placeholder="Stellungnahme und Empfehlungen des DSB..."
              />
            </div>
          </div>
        )}
      </div>

      {/* Authority Consultation */}
      <div className="bg-orange-50 border border-orange-200 rounded-xl p-6">
        <div className="flex items-start gap-4">
          <div className="w-12 h-12 bg-orange-100 rounded-full flex items-center justify-center flex-shrink-0">
            <svg className="w-6 h-6 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
            </svg>
          </div>
          <div className="flex-1">
            <label className="flex items-center gap-3">
              <input
                type="checkbox"
                checked={formData.authority_consulted}
                onChange={(e) => setFormData(prev => ({ ...prev, authority_consulted: e.target.checked }))}
                className="w-5 h-5 rounded border-gray-300 text-orange-600 focus:ring-orange-500"
              />
              <span className="font-medium text-orange-800">
                Aufsichtsbehoerde wurde konsultiert (Art. 36)
              </span>
            </label>
            <p className="text-sm text-orange-600 mt-2">
              Falls nach Durchfuehrung der Massnahmen weiterhin ein hohes Risiko besteht, ist die Aufsichtsbehoerde zu konsultieren.
            </p>
          </div>
        </div>

        {formData.authority_consulted && (
          <div className="mt-4 space-y-4 pt-4 border-t border-orange-200">
            <div>
              <label className="block text-sm font-medium text-orange-800 mb-2">
                Aktenzeichen / Referenz
              </label>
              <input
                type="text"
                value={formData.authority_reference}
                onChange={(e) => setFormData(prev => ({ ...prev, authority_reference: e.target.value }))}
                className="w-full px-4 py-2 border border-orange-300 rounded-lg focus:ring-2 focus:ring-orange-500 bg-white"
                placeholder="Aktenzeichen der Behoerde"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-orange-800 mb-2">
                Entscheidung der Behoerde
              </label>
              <textarea
                value={formData.authority_decision}
                onChange={(e) => setFormData(prev => ({ ...prev, authority_decision: e.target.value }))}
                className="w-full px-4 py-3 border border-orange-300 rounded-lg focus:ring-2 focus:ring-orange-500 bg-white"
                rows={4}
                placeholder="Entscheidung und Auflagen der Aufsichtsbehoerde..."
              />
            </div>
          </div>
        )}
      </div>

      {/* Info Box */}
      <div className="bg-gray-50 border border-gray-200 rounded-xl p-4">
        <div className="flex items-start gap-3">
          <svg className="w-5 h-5 text-gray-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <div className="text-sm text-gray-600">
            <p className="font-medium text-gray-700 mb-1">Hinweis zur Konsultation</p>
            <p>
              Die Konsultation der Aufsichtsbehoerde ist nur erforderlich, wenn nach Umsetzung der
              geplanten Massnahmen weiterhin ein hohes Risiko fuer die Rechte und Freiheiten der
              betroffenen Personen besteht.
            </p>
          </div>
        </div>
      </div>

      {/* Save Button */}
      <div className="flex justify-end pt-4 border-t border-gray-200">
        <button
          onClick={handleSave}
          disabled={isSubmitting}
          className="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
        >
          {isSubmitting ? 'Speichern...' : 'Abschnitt speichern'}
        </button>
      </div>
    </div>
  )
}

// =============================================================================
// SDM COVERAGE OVERVIEW
// =============================================================================

function SDMCoverageOverview({ dsfa }: { dsfa: DSFA }) {
  const goals = Object.keys(SDM_GOALS) as SDMGoal[]
  const riskCount = dsfa.risks?.length || 0
  const mitigationCount = dsfa.mitigations?.length || 0

  // Count catalog risks and mitigations per SDM goal by matching descriptions
  const goalCoverage = goals.map(goal => {
    const catalogRisks = RISK_CATALOG.filter(r => r.sdmGoal === goal)
    const catalogMitigations = MITIGATION_LIBRARY.filter(m => m.sdmGoals.includes(goal))

    // Check if any DSFA risk descriptions contain catalog risk titles for this goal
    const matchedRisks = catalogRisks.filter(cr =>
      dsfa.risks?.some(r => r.description?.includes(cr.title))
    ).length

    // Check if any DSFA mitigation descriptions contain catalog mitigation titles for this goal
    const matchedMitigations = catalogMitigations.filter(cm =>
      dsfa.mitigations?.some(m => m.description?.includes(cm.title))
    ).length

    const totalCatalogRisks = catalogRisks.length
    const totalCatalogMitigations = catalogMitigations.length

    // Coverage: simple heuristic based on whether there are mitigations for risks in this area
    const hasRisks = matchedRisks > 0 || dsfa.risks?.some(r => {
      const cat = r.category
      if (goal === 'vertraulichkeit' && cat === 'confidentiality') return true
      if (goal === 'integritaet' && cat === 'integrity') return true
      if (goal === 'verfuegbarkeit' && cat === 'availability') return true
      if (goal === 'nichtverkettung' && cat === 'rights_freedoms') return true
      return false
    })

    const coverage = matchedMitigations > 0 ? 'covered' :
                     hasRisks ? 'gaps' : 'no_data'

    return {
      goal,
      info: SDM_GOALS[goal],
      matchedRisks,
      matchedMitigations,
      totalCatalogRisks,
      totalCatalogMitigations,
      coverage,
    }
  })

  return (
    <div className="mt-6 bg-white rounded-xl border p-6">
      <h3 className="text-md font-semibold text-gray-900 mb-1">SDM-Abdeckung (Gewaehrleistungsziele)</h3>
      <p className="text-xs text-gray-500 mb-4">Uebersicht ueber die Abdeckung der 7 Gewaehrleistungsziele des Standard-Datenschutzmodells.</p>

      <div className="grid grid-cols-7 gap-2">
        {goalCoverage.map(({ goal, info, matchedRisks, matchedMitigations, coverage }) => (
          <div
            key={goal}
            className={`p-3 rounded-lg text-center border ${
              coverage === 'covered' ? 'bg-green-50 border-green-200' :
              coverage === 'gaps' ? 'bg-yellow-50 border-yellow-200' :
              'bg-gray-50 border-gray-200'
            }`}
          >
            <div className={`text-lg mb-1 ${
              coverage === 'covered' ? 'text-green-600' :
              coverage === 'gaps' ? 'text-yellow-600' :
              'text-gray-400'
            }`}>
              {coverage === 'covered' ? '\u2713' : coverage === 'gaps' ? '!' : '\u2013'}
            </div>
            <div className="text-xs font-medium text-gray-900 leading-tight">{info.name}</div>
            <div className="text-[10px] text-gray-500 mt-1">
              {matchedRisks}R / {matchedMitigations}M
            </div>
          </div>
        ))}
      </div>

      <div className="flex items-center gap-4 mt-3 text-xs text-gray-500">
        <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-green-500"></span> Abgedeckt</span>
        <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-yellow-500"></span> Luecken</span>
        <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-gray-300"></span> Keine Daten</span>
        <span className="ml-auto">R = Risiken, M = Massnahmen</span>
      </div>
    </div>
  )
}

// =============================================================================
// RAG SEARCH PANEL
// =============================================================================

const RAG_API_BASE = process.env.NEXT_PUBLIC_KLAUSUR_SERVICE_URL || 'http://localhost:8086'

interface RAGSearchResult {
  chunk_id: string
  content: string
  score: number
  source_code: string
  source_name: string
  attribution_text: string
  license_code: string
  license_name: string
  license_url?: string
  source_url?: string
  document_type?: string
  category?: string
  section_title?: string
}

interface RAGSearchResponse {
  query: string
  results: RAGSearchResult[]
  total_results: number
  licenses_used: string[]
  attribution_notice: string
}

function RAGSearchPanel({
  context,
  categories,
  onInsertText,
}: {
  context: string
  categories?: string[]
  onInsertText?: (text: string) => void
}) {
  const [isOpen, setIsOpen] = useState(false)
  const [query, setQuery] = useState('')
  const [isSearching, setIsSearching] = useState(false)
  const [results, setResults] = useState<RAGSearchResponse | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [copiedId, setCopiedId] = useState<string | null>(null)

  const buildQuery = () => {
    if (query.trim()) return query.trim()
    // Auto-generate query from context
    return context.substring(0, 200)
  }

  const handleSearch = async () => {
    const searchQuery = buildQuery()
    if (!searchQuery || searchQuery.length < 3) return

    setIsSearching(true)
    setError(null)

    try {
      const params = new URLSearchParams({ query: searchQuery, limit: '5' })
      if (categories?.length) {
        categories.forEach(c => params.append('categories', c))
      }

      const response = await fetch(`${RAG_API_BASE}/api/v1/dsfa-rag/search?${params}`)
      if (!response.ok) throw new Error(`Suche fehlgeschlagen (${response.status})`)
      const data: RAGSearchResponse = await response.json()
      setResults(data)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Suche fehlgeschlagen')
      setResults(null)
    } finally {
      setIsSearching(false)
    }
  }

  const handleInsert = (text: string, chunkId: string) => {
    if (onInsertText) {
      onInsertText(text)
    } else {
      navigator.clipboard.writeText(text)
    }
    setCopiedId(chunkId)
    setTimeout(() => setCopiedId(null), 2000)
  }

  const sourcesForAttribution: SourceAttributionProps['sources'] = (results?.results || []).map(r => ({
    sourceCode: r.source_code,
    sourceName: r.source_name,
    attributionText: r.attribution_text,
    licenseCode: r.license_code as DSFALicenseCode,
    sourceUrl: r.source_url,
    score: r.score,
  }))

  if (!isOpen) {
    return (
      <button
        onClick={() => setIsOpen(true)}
        className="flex items-center gap-2 px-4 py-2 text-sm bg-indigo-50 text-indigo-700 rounded-lg border border-indigo-200 hover:bg-indigo-100 transition-colors"
      >
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
        Empfehlung suchen (RAG)
      </button>
    )
  }

  return (
    <div className="bg-indigo-50 border border-indigo-200 rounded-xl p-4 space-y-4">
      <div className="flex items-center justify-between">
        <h4 className="text-sm font-medium text-indigo-800 flex items-center gap-2">
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          DSFA-Wissenssuche (RAG)
        </h4>
        <button
          onClick={() => { setIsOpen(false); setResults(null); setError(null) }}
          className="text-indigo-400 hover:text-indigo-600"
        >
          <svg className="w-4 h-4" 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>

      {/* Search Input */}
      <div className="flex gap-2">
        <input
          type="text"
          value={query}
          onChange={e => setQuery(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && handleSearch()}
          placeholder={`Suchbegriff (oder leer fuer automatische Kontextsuche)...`}
          className="flex-1 px-3 py-2 text-sm border border-indigo-300 rounded-lg bg-white focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
        />
        <button
          onClick={handleSearch}
          disabled={isSearching}
          className="px-4 py-2 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 transition-colors"
        >
          {isSearching ? 'Suche...' : 'Suchen'}
        </button>
      </div>

      {/* Error */}
      {error && (
        <div className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg p-3">
          {error}
        </div>
      )}

      {/* Results */}
      {results && results.results.length > 0 && (
        <div className="space-y-3">
          <p className="text-xs text-indigo-600">{results.total_results} Ergebnis(se) gefunden</p>

          {results.results.map(r => (
            <div key={r.chunk_id} className="bg-white rounded-lg border border-indigo-100 p-3">
              <div className="flex items-start justify-between gap-2">
                <div className="flex-1 min-w-0">
                  {r.section_title && (
                    <div className="text-xs font-medium text-indigo-600 mb-1">{r.section_title}</div>
                  )}
                  <p className="text-sm text-gray-700 leading-relaxed whitespace-pre-line">
                    {r.content.length > 400 ? r.content.substring(0, 400) + '...' : r.content}
                  </p>
                  <div className="flex items-center gap-2 mt-2">
                    <span className="text-xs text-gray-400 font-mono">
                      {r.source_code} ({(r.score * 100).toFixed(0)}%)
                    </span>
                    {r.category && (
                      <span className="text-xs px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">{r.category}</span>
                    )}
                  </div>
                </div>
                <button
                  onClick={() => handleInsert(r.content, r.chunk_id)}
                  className={`flex-shrink-0 px-3 py-1.5 text-xs rounded-lg transition-colors ${
                    copiedId === r.chunk_id
                      ? 'bg-green-100 text-green-700'
                      : 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200'
                  }`}
                  title="In Beschreibung uebernehmen"
                >
                  {copiedId === r.chunk_id ? 'Kopiert!' : 'Uebernehmen'}
                </button>
              </div>
            </div>
          ))}

          {/* Source Attribution */}
          <SourceAttribution sources={sourcesForAttribution} compact showScores />
        </div>
      )}

      {results && results.results.length === 0 && (
        <div className="text-sm text-indigo-600 text-center py-4">
          Keine Ergebnisse gefunden. Versuchen Sie einen anderen Suchbegriff.
        </div>
      )}
    </div>
  )
}

// =============================================================================
// MODALS
// =============================================================================

function AddRiskModal({
  likelihood,
  impact,
  onClose,
  onAdd,
}: {
  likelihood: 'low' | 'medium' | 'high'
  impact: 'low' | 'medium' | 'high'
  onClose: () => void
  onAdd: (data: { category: string; description: string }) => void
}) {
  const [mode, setMode] = useState<'catalog' | 'manual'>('catalog')
  const [category, setCategory] = useState('confidentiality')
  const [description, setDescription] = useState('')
  const [catalogFilter, setCatalogFilter] = useState<DSFARiskCategory | 'all'>('all')
  const [sdmFilter, setSdmFilter] = useState<SDMGoal | 'all'>('all')

  const { level } = calculateRiskLevel(likelihood, impact)

  const filteredCatalog = RISK_CATALOG.filter(r => {
    if (catalogFilter !== 'all' && r.category !== catalogFilter) return false
    if (sdmFilter !== 'all' && r.sdmGoal !== sdmFilter) return false
    return true
  })

  function selectCatalogRisk(risk: CatalogRisk) {
    setCategory(risk.category)
    setDescription(`${risk.title}\n\n${risk.description}`)
    setMode('manual')
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl p-6 max-w-2xl w-full mx-4 max-h-[85vh] overflow-y-auto">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Risiko hinzufuegen</h3>

        <div className="mb-4 p-3 rounded-lg bg-gray-50">
          <div className="text-sm text-gray-500">
            Eintrittswahrscheinlichkeit: <span className="font-medium text-gray-700">{likelihood === 'low' ? 'Niedrig' : likelihood === 'medium' ? 'Mittel' : 'Hoch'}</span>
            {' | '}
            Auswirkung: <span className="font-medium text-gray-700">{impact === 'low' ? 'Niedrig' : impact === 'medium' ? 'Mittel' : 'Hoch'}</span>
            {' | '}
            Risikostufe: <span className="font-medium">{DSFA_RISK_LEVEL_LABELS[level]}</span>
          </div>
        </div>

        {/* Tab Toggle */}
        <div className="flex border-b mb-4">
          <button
            onClick={() => setMode('catalog')}
            className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px ${
              mode === 'catalog' ? 'border-purple-500 text-purple-600' : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            Aus Katalog waehlen ({RISK_CATALOG.length})
          </button>
          <button
            onClick={() => setMode('manual')}
            className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px ${
              mode === 'manual' ? 'border-purple-500 text-purple-600' : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            Manuell eingeben
          </button>
        </div>

        {mode === 'catalog' ? (
          <div className="space-y-3">
            {/* Filters */}
            <div className="flex gap-2">
              <select
                value={catalogFilter}
                onChange={e => setCatalogFilter(e.target.value as DSFARiskCategory | 'all')}
                className="text-sm border rounded px-2 py-1"
              >
                <option value="all">Alle Kategorien</option>
                {Object.entries(RISK_CATEGORY_LABELS).map(([key, label]) => (
                  <option key={key} value={key}>{label}</option>
                ))}
              </select>
              <select
                value={sdmFilter}
                onChange={e => setSdmFilter(e.target.value as SDMGoal | 'all')}
                className="text-sm border rounded px-2 py-1"
              >
                <option value="all">Alle SDM-Ziele</option>
                {Object.entries(SDM_GOAL_LABELS).map(([key, label]) => (
                  <option key={key} value={key}>{label}</option>
                ))}
              </select>
            </div>

            {/* Catalog List */}
            <div className="max-h-[40vh] overflow-y-auto space-y-2">
              {filteredCatalog.map(risk => (
                <button
                  key={risk.id}
                  onClick={() => selectCatalogRisk(risk)}
                  className="w-full text-left p-3 rounded-lg border hover:border-purple-300 hover:bg-purple-50 transition-colors"
                >
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs font-mono text-gray-400">{risk.id}</span>
                    <span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600">
                      {RISK_CATEGORY_LABELS[risk.category]}
                    </span>
                    <span className="text-xs px-2 py-0.5 rounded-full bg-blue-50 text-blue-600">
                      {SDM_GOAL_LABELS[risk.sdmGoal]}
                    </span>
                  </div>
                  <div className="text-sm font-medium text-gray-900">{risk.title}</div>
                  <div className="text-xs text-gray-500 mt-1 line-clamp-2">{risk.description}</div>
                </button>
              ))}
            </div>
            {filteredCatalog.length === 0 && (
              <p className="text-sm text-gray-500 text-center py-4">Keine Risiken fuer die gewaehlten Filter.</p>
            )}
          </div>
        ) : (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Kategorie</label>
              <select
                value={category}
                onChange={(e) => setCategory(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              >
                <option value="confidentiality">Vertraulichkeit</option>
                <option value="integrity">Integritaet</option>
                <option value="availability">Verfuegbarkeit</option>
                <option value="rights_freedoms">Rechte & Freiheiten</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Beschreibung</label>
              <textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                rows={4}
                placeholder="Beschreiben Sie das Risiko..."
              />
            </div>
          </div>
        )}

        <div className="flex gap-3 mt-6">
          <button
            onClick={onClose}
            className="flex-1 py-2 px-4 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
          >
            Abbrechen
          </button>
          <button
            onClick={() => onAdd({ category, description })}
            disabled={!description.trim() || mode === 'catalog'}
            className="flex-1 py-2 px-4 bg-purple-600 text-white rounded-lg font-medium hover:bg-purple-700 disabled:opacity-50"
          >
            Hinzufuegen
          </button>
        </div>
      </div>
    </div>
  )
}

function AddMitigationModal({
  risks,
  onClose,
  onAdd,
}: {
  risks: DSFARisk[]
  onClose: () => void
  onAdd: (data: { risk_id: string; description: string; type: string; responsible_party: string }) => void
}) {
  const [mode, setMode] = useState<'library' | 'manual'>('library')
  const [riskId, setRiskId] = useState(risks[0]?.id || '')
  const [type, setType] = useState('technical')
  const [description, setDescription] = useState('')
  const [responsibleParty, setResponsibleParty] = useState('')
  const [typeFilter, setTypeFilter] = useState<'all' | 'technical' | 'organizational' | 'legal'>('all')
  const [sdmFilter, setSdmFilter] = useState<SDMGoal | 'all'>('all')

  const filteredLibrary = MITIGATION_LIBRARY.filter(m => {
    if (typeFilter !== 'all' && m.type !== typeFilter) return false
    if (sdmFilter !== 'all' && !m.sdmGoals.includes(sdmFilter)) return false
    return true
  })

  function selectCatalogMitigation(m: CatalogMitigation) {
    setType(m.type)
    setDescription(`${m.title}\n\n${m.description}\n\nRechtsgrundlage: ${m.legalBasis}`)
    setMode('manual')
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl p-6 max-w-2xl w-full mx-4 max-h-[85vh] overflow-y-auto">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Massnahme hinzufuegen</h3>

        {/* Tab Toggle */}
        <div className="flex border-b mb-4">
          <button
            onClick={() => setMode('library')}
            className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px ${
              mode === 'library' ? 'border-purple-500 text-purple-600' : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            Aus Bibliothek waehlen ({MITIGATION_LIBRARY.length})
          </button>
          <button
            onClick={() => setMode('manual')}
            className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px ${
              mode === 'manual' ? 'border-purple-500 text-purple-600' : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            Manuell eingeben
          </button>
        </div>

        {mode === 'library' ? (
          <div className="space-y-3">
            {/* Filters */}
            <div className="flex gap-2">
              <select
                value={typeFilter}
                onChange={e => setTypeFilter(e.target.value as typeof typeFilter)}
                className="text-sm border rounded px-2 py-1"
              >
                <option value="all">Alle Typen</option>
                {Object.entries(MITIGATION_TYPE_LABELS).map(([key, label]) => (
                  <option key={key} value={key}>{label}</option>
                ))}
              </select>
              <select
                value={sdmFilter}
                onChange={e => setSdmFilter(e.target.value as SDMGoal | 'all')}
                className="text-sm border rounded px-2 py-1"
              >
                <option value="all">Alle SDM-Ziele</option>
                {Object.entries(SDM_GOAL_LABELS).map(([key, label]) => (
                  <option key={key} value={key}>{label}</option>
                ))}
              </select>
            </div>

            {/* Library List */}
            <div className="max-h-[40vh] overflow-y-auto space-y-2">
              {filteredLibrary.map(m => (
                <button
                  key={m.id}
                  onClick={() => selectCatalogMitigation(m)}
                  className="w-full text-left p-3 rounded-lg border hover:border-purple-300 hover:bg-purple-50 transition-colors"
                >
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs font-mono text-gray-400">{m.id}</span>
                    <span className={`text-xs px-2 py-0.5 rounded-full ${
                      m.type === 'technical' ? 'bg-blue-50 text-blue-600' :
                      m.type === 'organizational' ? 'bg-green-50 text-green-600' :
                      'bg-purple-50 text-purple-600'
                    }`}>
                      {MITIGATION_TYPE_LABELS[m.type]}
                    </span>
                    {m.sdmGoals.map(g => (
                      <span key={g} className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600">
                        {SDM_GOAL_LABELS[g]}
                      </span>
                    ))}
                    <span className={`text-xs px-2 py-0.5 rounded-full ${
                      m.effectiveness === 'high' ? 'bg-green-50 text-green-700' :
                      m.effectiveness === 'medium' ? 'bg-yellow-50 text-yellow-700' :
                      'bg-gray-50 text-gray-500'
                    }`}>
                      {EFFECTIVENESS_LABELS[m.effectiveness]}
                    </span>
                  </div>
                  <div className="text-sm font-medium text-gray-900">{m.title}</div>
                  <div className="text-xs text-gray-500 mt-1 line-clamp-2">{m.description}</div>
                </button>
              ))}
            </div>
            {filteredLibrary.length === 0 && (
              <p className="text-sm text-gray-500 text-center py-4">Keine Massnahmen fuer die gewaehlten Filter.</p>
            )}
          </div>
        ) : (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Zugehoeriges Risiko</label>
              <select
                value={riskId}
                onChange={(e) => setRiskId(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              >
                {risks.map(risk => (
                  <option key={risk.id} value={risk.id}>
                    {risk.description.substring(0, 50)}...
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Typ</label>
              <select
                value={type}
                onChange={(e) => setType(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              >
                <option value="technical">Technisch</option>
                <option value="organizational">Organisatorisch</option>
                <option value="legal">Rechtlich</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Beschreibung</label>
              <textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                rows={3}
                placeholder="Beschreiben Sie die Massnahme..."
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Verantwortlich</label>
              <input
                type="text"
                value={responsibleParty}
                onChange={(e) => setResponsibleParty(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                placeholder="Name oder Rolle..."
              />
            </div>
          </div>
        )}

        <div className="flex gap-3 mt-6">
          <button
            onClick={onClose}
            className="flex-1 py-2 px-4 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
          >
            Abbrechen
          </button>
          <button
            onClick={() => onAdd({ risk_id: riskId, description, type, responsible_party: responsibleParty })}
            disabled={!description.trim() || mode === 'library'}
            className="flex-1 py-2 px-4 bg-purple-600 text-white rounded-lg font-medium hover:bg-purple-700 disabled:opacity-50"
          >
            Hinzufuegen
          </button>
        </div>
      </div>
    </div>
  )
}

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

export default function DSFAEditorPage() {
  const params = useParams()
  const router = useRouter()
  const dsfaId = params.id as string

  const [dsfa, setDSFA] = useState<DSFA | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  const [activeSection, setActiveSection] = useState(0) // Start at Section 0: Threshold Analysis
  const [saveMessage, setSaveMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)

  // Load DSFA data
  useEffect(() => {
    const loadDSFA = async () => {
      setIsLoading(true)
      try {
        const data = await getDSFA(dsfaId)
        setDSFA(data)
      } catch (error) {
        console.error('Failed to load DSFA:', error)
      } finally {
        setIsLoading(false)
      }
    }
    loadDSFA()
  }, [dsfaId])

  const handleSectionUpdate = useCallback(async (sectionNumber: number, data: Record<string, unknown>) => {
    if (!dsfa) return

    setIsSaving(true)
    setSaveMessage(null)

    try {
      const updated = await updateDSFASection(dsfaId, sectionNumber, data)
      setDSFA(updated)
      setSaveMessage({ type: 'success', text: 'Abschnitt gespeichert' })
      setTimeout(() => setSaveMessage(null), 3000)
    } catch (error) {
      console.error('Failed to update section:', error)
      setSaveMessage({ type: 'error', text: 'Fehler beim Speichern' })
    } finally {
      setIsSaving(false)
    }
  }, [dsfa, dsfaId])

  const handleSubmitForReview = async () => {
    // Implementation would call submitDSFAForReview
    alert('Zur Pruefung einreichen - Coming soon')
  }

  const handleApprove = async (opinion: string) => {
    // Implementation would call approveDSFA
    alert('Genehmigen - Coming soon')
  }

  const handleReject = async (reason: string) => {
    // Implementation would call approveDSFA with approved: false
    alert('Ablehnen - Coming soon')
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <svg className="animate-spin w-8 h-8 text-purple-600" fill="none" viewBox="0 0 24 24">
          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
        </svg>
      </div>
    )
  }

  if (!dsfa) {
    return (
      <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
        <div className="w-16 h-16 mx-auto bg-red-100 rounded-full flex items-center justify-center mb-4">
          <svg className="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </div>
        <h3 className="text-lg font-semibold text-gray-900">DSFA nicht gefunden</h3>
        <p className="mt-2 text-gray-500">
          Die angeforderte DSFA existiert nicht oder wurde geloescht.
        </p>
        <Link
          href="/sdk/dsfa"
          className="mt-4 inline-flex items-center gap-2 px-4 py-2 text-purple-600 hover:bg-purple-50 rounded-lg transition-colors"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          Zurueck zur Uebersicht
        </Link>
      </div>
    )
  }

  const sectionConfig = DSFA_SECTIONS.find(s => s.number === activeSection)
  const statusColors: Record<string, string> = {
    draft: 'bg-gray-100 text-gray-600',
    in_review: 'bg-yellow-100 text-yellow-700',
    approved: 'bg-green-100 text-green-700',
    rejected: 'bg-red-100 text-red-700',
    needs_update: 'bg-orange-100 text-orange-700',
  }

  // Handler for generic DSFA updates (used by new section components)
  const handleGenericUpdate = useCallback(async (data: Record<string, unknown>) => {
    if (!dsfa) return

    setIsSaving(true)
    setSaveMessage(null)

    try {
      const updated = await updateDSFA(dsfaId, data as Partial<DSFA>)
      setDSFA(updated)
      setSaveMessage({ type: 'success', text: 'Abschnitt gespeichert' })
      setTimeout(() => setSaveMessage(null), 3000)
    } catch (error) {
      console.error('Failed to update DSFA:', error)
      setSaveMessage({ type: 'error', text: 'Fehler beim Speichern' })
    } finally {
      setIsSaving(false)
    }
  }, [dsfa, dsfaId])

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            href="/sdk/dsfa"
            className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
            </svg>
          </Link>
          <div>
            <div className="flex items-center gap-2">
              <span className={`px-2 py-1 text-xs rounded-full ${statusColors[dsfa.status]}`}>
                {DSFA_STATUS_LABELS[dsfa.status]}
              </span>
              <span className={`px-2 py-1 text-xs rounded-full ${
                dsfa.overall_risk_level === 'low' ? 'bg-green-100 text-green-700' :
                dsfa.overall_risk_level === 'medium' ? 'bg-yellow-100 text-yellow-700' :
                dsfa.overall_risk_level === 'high' ? 'bg-orange-100 text-orange-700' :
                'bg-red-100 text-red-700'
              }`}>
                Risiko: {DSFA_RISK_LEVEL_LABELS[dsfa.overall_risk_level]}
              </span>
              {dsfa.assessment_id && (
                <span className="px-2 py-1 text-xs rounded-full bg-purple-100 text-purple-700">
                  UCCA-verknuepft
                </span>
              )}
            </div>
            <h1 className="text-2xl font-bold text-gray-900 mt-1">{dsfa.name}</h1>
            {dsfa.description && (
              <p className="text-sm text-gray-500 mt-1">{dsfa.description}</p>
            )}
          </div>
        </div>

        {/* Save Message */}
        {saveMessage && (
          <div className={`px-4 py-2 rounded-lg text-sm ${
            saveMessage.type === 'success'
              ? 'bg-green-100 text-green-700'
              : 'bg-red-100 text-red-700'
          }`}>
            {saveMessage.text}
          </div>
        )}
      </div>

      {/* Main Content: Sidebar + Content Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* Left Column - Sidebar (1/4) */}
        <div className="lg:col-span-1">
          <DSFASidebar
            dsfa={dsfa}
            activeSection={activeSection}
            onSectionChange={setActiveSection}
          />
        </div>

        {/* Right Column - Content (3/4) */}
        <div className="lg:col-span-3 space-y-6">
          {/* Section Content Card */}
          <div className="bg-white rounded-xl border border-gray-200">
            {/* Section Header */}
            {sectionConfig && (
              <div className="p-4 bg-gray-50 border-b border-gray-200 rounded-t-xl">
                <div className="flex items-start justify-between">
                  <div>
                    <h2 className="text-lg font-semibold text-gray-900">
                      {sectionConfig.number}. {sectionConfig.titleDE}
                    </h2>
                    <p className="text-sm text-gray-500 mt-1">{sectionConfig.description}</p>
                  </div>
                  <span className="px-2 py-1 bg-blue-50 text-blue-600 rounded text-xs">
                    {sectionConfig.gdprRef}
                  </span>
                </div>
              </div>
            )}

            {/* Section Content */}
            <div className="p-6">
              {/* Section 0: Threshold Analysis (NEW) */}
              {activeSection === 0 && (
                <ThresholdAnalysisSection
                  dsfa={dsfa}
                  onUpdate={handleGenericUpdate}
                  isSubmitting={isSaving}
                />
              )}

              {/* Sections 1-4: Existing */}
              {activeSection === 1 && (
                <Section1Editor
                  dsfa={dsfa}
                  onUpdate={(data) => handleSectionUpdate(1, data)}
                  isSubmitting={isSaving}
                />
              )}
              {activeSection === 2 && (
                <Section2Editor
                  dsfa={dsfa}
                  onUpdate={(data) => handleSectionUpdate(2, data)}
                  isSubmitting={isSaving}
                />
              )}
              {activeSection === 3 && (
                <Section3Editor
                  dsfa={dsfa}
                  onUpdate={(data) => handleSectionUpdate(3, data)}
                  isSubmitting={isSaving}
                />
              )}
              {activeSection === 4 && (
                <Section4Editor
                  dsfa={dsfa}
                  onUpdate={(data) => handleSectionUpdate(4, data)}
                  isSubmitting={isSaving}
                />
              )}

              {/* SDM Coverage Overview (shown in Section 3 and 4) */}
              {(activeSection === 3 || activeSection === 4) && (dsfa.risks?.length > 0 || dsfa.mitigations?.length > 0) && (
                <SDMCoverageOverview dsfa={dsfa} />
              )}

              {/* Section 5: Stakeholder Consultation (NEW) */}
              {activeSection === 5 && (
                <StakeholderConsultationSection
                  dsfa={dsfa}
                  onUpdate={handleGenericUpdate}
                  isSubmitting={isSaving}
                />
              )}

              {/* Section 6: DPO & Authority Consultation */}
              {activeSection === 6 && (
                <div className="space-y-6">
                  {/* Original Section 5 Editor (DPO Opinion) */}
                  <Section5Editor
                    dsfa={dsfa}
                    onUpdate={(data) => handleSectionUpdate(5, data)}
                    isSubmitting={isSaving}
                  />

                  {/* Art. 36 Warning (NEW) */}
                  <div className="border-t border-gray-200 pt-6">
                    <h3 className="text-lg font-semibold text-gray-900 mb-4">
                      Art. 36 Behoerdenkonsultation
                    </h3>
                    <Art36Warning
                      dsfa={dsfa}
                      onUpdate={handleGenericUpdate}
                      isSubmitting={isSaving}
                    />
                  </div>
                </div>
              )}

              {/* Section 7: Review & Maintenance (NEW) */}
              {activeSection === 7 && (
                <ReviewScheduleSection
                  dsfa={dsfa}
                  onUpdate={handleGenericUpdate}
                  isSubmitting={isSaving}
                />
              )}
            </div>
          </div>

          {/* Bottom Actions Row */}
          <div className="flex items-center justify-between bg-white rounded-xl border border-gray-200 p-4">
            {/* Navigation */}
            <div className="flex items-center gap-2">
              {activeSection > 0 && (
                <button
                  onClick={() => setActiveSection(activeSection - 1)}
                  className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                  </svg>
                  Zurueck
                </button>
              )}
              {activeSection < 7 && (
                <button
                  onClick={() => setActiveSection(activeSection + 1)}
                  className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
                >
                  Weiter
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              )}
            </div>

            {/* Quick Info */}
            <div className="flex items-center gap-4 text-sm text-gray-500">
              <span>Risiken: {(dsfa.risks || []).length}</span>
              <span>Massnahmen: {(dsfa.mitigations || []).length}</span>
              <span>Version: {dsfa.version || 1}</span>
            </div>

            {/* Export */}
            <div className="flex items-center gap-2">
              <button className="flex items-center gap-2 px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">
                <svg className="w-5 h-5 text-red-500" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6z"/>
                  <path d="M14 2v6h6M16 13H8M16 17H8M10 9H8"/>
                </svg>
                PDF
              </button>
              <button className="flex items-center gap-2 px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">
                <svg className="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                JSON
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
