'use client'

/**
 * Voice Service Admin Page
 *
 * Displays:
 * - Voice-First Architecture Overview
 * - Developer Guide Content
 * - Live Voice Demo (embedded from studio-v2)
 * - Task State Machine Documentation
 * - DSGVO Compliance Information
 */

import { useState } from 'react'
import AdminLayout from '@/components/admin/AdminLayout'
import Link from 'next/link'

type TabType = 'overview' | 'demo' | 'tasks' | 'intents' | 'dsgvo' | 'api'

// Task State Machine data
const TASK_STATES = [
  { state: 'DRAFT', description: 'Task erstellt, noch nicht verarbeitet', color: 'bg-gray-100 text-gray-800', next: ['QUEUED', 'PAUSED'] },
  { state: 'QUEUED', description: 'In Warteschlange fuer Verarbeitung', color: 'bg-blue-100 text-blue-800', next: ['RUNNING', 'PAUSED'] },
  { state: 'RUNNING', description: 'Wird aktuell verarbeitet', color: 'bg-yellow-100 text-yellow-800', next: ['READY', 'PAUSED'] },
  { state: 'READY', description: 'Fertig, wartet auf User-Bestaetigung', color: 'bg-green-100 text-green-800', next: ['APPROVED', 'REJECTED', 'PAUSED'] },
  { state: 'APPROVED', description: 'Vom User bestaetigt', color: 'bg-emerald-100 text-emerald-800', next: ['COMPLETED'] },
  { state: 'REJECTED', description: 'Vom User abgelehnt', color: 'bg-red-100 text-red-800', next: ['DRAFT'] },
  { state: 'COMPLETED', description: 'Erfolgreich abgeschlossen', color: 'bg-teal-100 text-teal-800', next: [] },
  { state: 'EXPIRED', description: 'TTL ueberschritten', color: 'bg-orange-100 text-orange-800', next: [] },
  { state: 'PAUSED', description: 'Vom User pausiert', color: 'bg-purple-100 text-purple-800', next: ['DRAFT', 'QUEUED', 'RUNNING', 'READY'] },
]

// Intent Types (22 types organized by group)
const INTENT_GROUPS = [
  {
    group: 'Notizen',
    color: 'bg-blue-50 border-blue-200',
    intents: [
      { type: 'student_observation', example: 'Notiz zu Max: heute wiederholt gestoert', description: 'Schuelerbeobachtungen' },
      { type: 'reminder', example: 'Erinner mich morgen an Konferenz', description: 'Erinnerungen setzen' },
      { type: 'homework_check', example: '7b Mathe Hausaufgabe kontrollieren', description: 'Hausaufgaben pruefen' },
      { type: 'conference_topic', example: 'Thema Lehrerkonferenz: iPad-Regeln', description: 'Konferenzthemen' },
      { type: 'correction_thought', example: 'Aufgabe 3: haeufiger Fehler erklaeren', description: 'Korrekturgedanken' },
    ]
  },
  {
    group: 'Content-Generierung',
    color: 'bg-green-50 border-green-200',
    intents: [
      { type: 'worksheet_generate', example: 'Erstelle 3 Lueckentexte zu Vokabeln', description: 'Arbeitsblaetter erstellen' },
      { type: 'quiz_generate', example: '10-Minuten Vokabeltest mit Loesungen', description: 'Quiz/Tests erstellen' },
      { type: 'quick_activity', example: '10 Minuten Einstieg, 5 Aufgaben', description: 'Schnelle Aktivitaeten' },
      { type: 'differentiation', example: 'Zwei Schwierigkeitsstufen: Basis und Plus', description: 'Differenzierung' },
    ]
  },
  {
    group: 'Kommunikation',
    color: 'bg-yellow-50 border-yellow-200',
    intents: [
      { type: 'parent_letter', example: 'Neutraler Elternbrief wegen Stoerungen', description: 'Elternbriefe erstellen' },
      { type: 'class_message', example: 'Nachricht an 8a: Hausaufgaben bis Mittwoch', description: 'Klassennachrichten' },
    ]
  },
  {
    group: 'Canvas-Editor',
    color: 'bg-purple-50 border-purple-200',
    intents: [
      { type: 'canvas_edit', example: 'Ueberschriften groesser, Zeilenabstand kleiner', description: 'Formatierung aendern' },
      { type: 'canvas_layout', example: 'Alles auf eine Seite, Drucklayout A4', description: 'Layout anpassen' },
      { type: 'canvas_element', example: 'Kasten fuer Merke hinzufuegen', description: 'Elemente hinzufuegen' },
      { type: 'canvas_image', example: 'Bild 2 nach links, Pfeil auf Aufgabe 3', description: 'Bilder positionieren' },
    ]
  },
  {
    group: 'RAG & Korrektur',
    color: 'bg-pink-50 border-pink-200',
    intents: [
      { type: 'operator_checklist', example: 'Operatoren-Checkliste fuer diese Aufgabe', description: 'Operatoren abrufen' },
      { type: 'eh_passage', example: 'Erwartungshorizont-Passage zu diesem Thema', description: 'EH-Passagen suchen' },
      { type: 'feedback_suggestion', example: 'Kurze Feedbackformulierung vorschlagen', description: 'Feedback vorschlagen' },
    ]
  },
  {
    group: 'Follow-up (TaskOrchestrator)',
    color: 'bg-teal-50 border-teal-200',
    intents: [
      { type: 'task_summary', example: 'Fasse alle offenen Tasks zusammen', description: 'Task-Uebersicht' },
      { type: 'convert_note', example: 'Mach aus der Notiz von gestern einen Elternbrief', description: 'Notizen konvertieren' },
      { type: 'schedule_reminder', example: 'Erinner mich morgen an das Gespraech mit Max', description: 'Erinnerungen planen' },
    ]
  },
]

// DSGVO Data Categories
const DSGVO_CATEGORIES = [
  { category: 'Audio', processing: 'NUR transient im RAM, NIEMALS persistiert', storage: 'Keine', ttl: '-', icon: '🎤', risk: 'low' },
  { category: 'PII (Schuelernamen)', processing: 'NUR auf Lehrergeraet', storage: 'Client-side', ttl: '-', icon: '👤', risk: 'high' },
  { category: 'Pseudonyme', processing: 'Server erlaubt (student_ref, class_ref)', storage: 'Valkey Cache', ttl: '24h', icon: '🔢', risk: 'low' },
  { category: 'Transkripte', processing: 'NUR verschluesselt (AES-256-GCM)', storage: 'PostgreSQL', ttl: '7 Tage', icon: '📝', risk: 'medium' },
  { category: 'Task States', processing: 'TaskOrchestrator', storage: 'Valkey', ttl: '30 Tage', icon: '📋', risk: 'low' },
  { category: 'Audit Logs', processing: 'Nur truncated IDs, keine PII', storage: 'PostgreSQL', ttl: '90 Tage', icon: '📊', risk: 'low' },
]

// API Endpoints
const API_ENDPOINTS = [
  { method: 'POST', path: '/api/v1/sessions', description: 'Voice Session erstellen' },
  { method: 'GET', path: '/api/v1/sessions/{id}', description: 'Session Status abrufen' },
  { method: 'DELETE', path: '/api/v1/sessions/{id}', description: 'Session beenden' },
  { method: 'GET', path: '/api/v1/sessions/{id}/tasks', description: 'Pending Tasks abrufen' },
  { method: 'POST', path: '/api/v1/tasks', description: 'Task erstellen' },
  { method: 'GET', path: '/api/v1/tasks/{id}', description: 'Task Status abrufen' },
  { method: 'PUT', path: '/api/v1/tasks/{id}/transition', description: 'Task State aendern' },
  { method: 'DELETE', path: '/api/v1/tasks/{id}', description: 'Task loeschen' },
  { method: 'WS', path: '/ws/voice', description: 'Voice Streaming (WebSocket)' },
  { method: 'GET', path: '/health', description: 'Health Check' },
]

export default function VoicePage() {
  const [activeTab, setActiveTab] = useState<TabType>('overview')
  const [demoLoaded, setDemoLoaded] = useState(false)

  const tabs = [
    { id: 'overview', name: 'Architektur', icon: '🏗️' },
    { id: 'demo', name: 'Live Demo', icon: '🎤' },
    { id: 'tasks', name: 'Task States', icon: '📋' },
    { id: 'intents', name: 'Intents (22)', icon: '🎯' },
    { id: 'dsgvo', name: 'DSGVO', icon: '🔒' },
    { id: 'api', name: 'API', icon: '🔌' },
  ]

  return (
    <AdminLayout title="Voice Service" description="Voice-First Interface mit PersonaPlex-7B & TaskOrchestrator">
      {/* Quick Links */}
      <div className="mb-6 flex flex-wrap gap-3">
        <Link
          href="/voice-test"
          target="_blank"
          className="flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 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="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
          </svg>
          Voice Test (Studio)
        </Link>
        <a
          href="http://localhost:8091/health"
          target="_blank"
          rel="noopener noreferrer"
          className="flex items-center gap-2 px-4 py-2 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          Health Check
        </a>
        <Link
          href="/admin/docs"
          className="flex items-center gap-2 px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 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="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          Developer Docs
        </Link>
      </div>

      {/* Stats Overview */}
      <div className="grid grid-cols-2 md:grid-cols-6 gap-4 mb-6">
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-3xl font-bold text-teal-600">8091</div>
          <div className="text-sm text-slate-500">Port</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-3xl font-bold text-blue-600">22</div>
          <div className="text-sm text-slate-500">Task Types</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-3xl font-bold text-purple-600">9</div>
          <div className="text-sm text-slate-500">Task States</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-3xl font-bold text-green-600">24kHz</div>
          <div className="text-sm text-slate-500">Audio Rate</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-3xl font-bold text-orange-600">80ms</div>
          <div className="text-sm text-slate-500">Frame Size</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-3xl font-bold text-red-600">0</div>
          <div className="text-sm text-slate-500">Audio Persist</div>
        </div>
      </div>

      {/* Tabs */}
      <div className="bg-white rounded-lg shadow mb-6">
        <div className="border-b border-slate-200 px-4">
          <div className="flex gap-1 overflow-x-auto">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as TabType)}
                className={`px-4 py-3 text-sm font-medium whitespace-nowrap transition-colors border-b-2 ${
                  activeTab === tab.id
                    ? 'border-teal-600 text-teal-600'
                    : 'border-transparent text-slate-500 hover:text-slate-700'
                }`}
              >
                <span className="mr-2">{tab.icon}</span>
                {tab.name}
              </button>
            ))}
          </div>
        </div>

        <div className="p-6">
          {/* Overview Tab */}
          {activeTab === 'overview' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-slate-900">Voice-First Architektur</h3>

              {/* Architecture Diagram */}
              <div className="bg-slate-50 rounded-lg p-6 font-mono text-sm overflow-x-auto">
                <pre className="text-slate-700">{`
┌──────────────────────────────────────────────────────────────────┐
│                    LEHRERGERAET (PWA / App)                       │
│  ┌────────────────────────────────────────────────────────────┐  │
│  │ VoiceCapture.tsx │ voice-encryption.ts │ voice-api.ts      │  │
│  │ Mikrofon         │ AES-256-GCM         │ WebSocket Client  │  │
│  └────────────────────────────────────────────────────────────┘  │
└───────────────────────────┬──────────────────────────────────────┘
                            │ WebSocket (wss://)
                            ▼
┌──────────────────────────────────────────────────────────────────┐
│                    VOICE SERVICE (Port 8091)                      │
│  ┌────────────────────────────────────────────────────────────┐  │
│  │ main.py │ streaming.py │ sessions.py │ tasks.py            │  │
│  └────────────────────────────────────────────────────────────┘  │
│  ┌────────────────────────────────────────────────────────────┐  │
│  │ task_orchestrator.py │ intent_router.py │ encryption        │  │
│  └────────────────────────────────────────────────────────────┘  │
└───────────────────────────┬──────────────────────────────────────┘
                            │
         ┌──────────────────┼──────────────────┐
         ▼                  ▼                  ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ PersonaPlex-7B  │ │ Ollama Fallback │ │ Valkey Cache    │
│ (A100 GPU)      │ │ (Mac Mini)      │ │ (Sessions)      │
└─────────────────┘ └─────────────────┘ └─────────────────┘
`}</pre>
              </div>

              {/* Technology Stack */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h4 className="font-semibold text-blue-800 mb-2">Voice Model (Produktion)</h4>
                  <p className="text-sm text-blue-700">PersonaPlex-7B (NVIDIA)</p>
                  <p className="text-xs text-blue-600 mt-1">Full-Duplex Speech-to-Speech</p>
                  <p className="text-xs text-blue-500">Lizenz: MIT + NVIDIA Open Model</p>
                </div>
                <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                  <h4 className="font-semibold text-green-800 mb-2">Agent Orchestration</h4>
                  <p className="text-sm text-green-700">TaskOrchestrator</p>
                  <p className="text-xs text-green-600 mt-1">Task State Machine</p>
                  <p className="text-xs text-green-500">Lizenz: Proprietary</p>
                </div>
                <div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
                  <h4 className="font-semibold text-purple-800 mb-2">Audio Codec</h4>
                  <p className="text-sm text-purple-700">Mimi (24kHz, 80ms)</p>
                  <p className="text-xs text-purple-600 mt-1">Low-Latency Streaming</p>
                  <p className="text-xs text-purple-500">Lizenz: MIT</p>
                </div>
              </div>

              {/* Key Files */}
              <div>
                <h4 className="font-semibold text-slate-800 mb-3">Wichtige Dateien</h4>
                <div className="bg-white border border-slate-200 rounded-lg overflow-hidden">
                  <table className="min-w-full divide-y divide-slate-200">
                    <thead className="bg-slate-50">
                      <tr>
                        <th className="px-4 py-2 text-left text-xs font-medium text-slate-500 uppercase">Datei</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-slate-500 uppercase">Beschreibung</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-200">
                      <tr><td className="px-4 py-2 font-mono text-sm">voice-service/main.py</td><td className="px-4 py-2 text-sm text-slate-600">FastAPI Entry, WebSocket Handler</td></tr>
                      <tr><td className="px-4 py-2 font-mono text-sm">voice-service/services/task_orchestrator.py</td><td className="px-4 py-2 text-sm text-slate-600">Task State Machine</td></tr>
                      <tr><td className="px-4 py-2 font-mono text-sm">voice-service/services/intent_router.py</td><td className="px-4 py-2 text-sm text-slate-600">Intent Detection (22 Types)</td></tr>
                      <tr><td className="px-4 py-2 font-mono text-sm">voice-service/services/encryption_service.py</td><td className="px-4 py-2 text-sm text-slate-600">Namespace Key Management</td></tr>
                      <tr><td className="px-4 py-2 font-mono text-sm">studio-v2/components/voice/VoiceCapture.tsx</td><td className="px-4 py-2 text-sm text-slate-600">Frontend Mikrofon + Crypto</td></tr>
                      <tr><td className="px-4 py-2 font-mono text-sm">studio-v2/lib/voice/voice-encryption.ts</td><td className="px-4 py-2 text-sm text-slate-600">AES-256-GCM Client-side</td></tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* Demo Tab */}
          {activeTab === 'demo' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-semibold text-slate-900">Live Voice Demo</h3>
                <a
                  href="http://localhost:3001/voice-test"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-sm text-teal-600 hover:text-teal-700 flex items-center gap-1"
                >
                  In neuem Tab oeffnen
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                </a>
              </div>

              <div className="bg-slate-100 rounded-lg p-4 text-sm text-slate-600 mb-4">
                <p><strong>Hinweis:</strong> Die Demo erfordert, dass der Voice Service (Port 8091) und das Studio-v2 Frontend (Port 3001) laufen.</p>
                <code className="block mt-2 bg-slate-200 p-2 rounded">docker compose up -d voice-service && cd studio-v2 && npm run dev</code>
              </div>

              {/* Embedded Demo */}
              <div className="relative bg-slate-900 rounded-lg overflow-hidden" style={{ height: '600px' }}>
                {!demoLoaded && (
                  <div className="absolute inset-0 flex items-center justify-center">
                    <button
                      onClick={() => setDemoLoaded(true)}
                      className="px-6 py-3 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors flex items-center gap-2"
                    >
                      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      Voice Demo laden
                    </button>
                  </div>
                )}
                {demoLoaded && (
                  <iframe
                    src="http://localhost:3001/voice-test?embed=true"
                    className="w-full h-full border-0"
                    title="Voice Demo"
                    allow="microphone"
                  />
                )}
              </div>
            </div>
          )}

          {/* Task States Tab */}
          {activeTab === 'tasks' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-slate-900">Task State Machine (TaskOrchestrator)</h3>

              {/* State Diagram */}
              <div className="bg-slate-50 rounded-lg p-6 font-mono text-sm overflow-x-auto">
                <pre className="text-slate-700">{`
DRAFT → QUEUED → RUNNING → READY
                              │
                  ┌───────────┴───────────┐
                  │                       │
              APPROVED                REJECTED
                  │                       │
              COMPLETED               DRAFT (revision)

Any State → EXPIRED (TTL)
Any State → PAUSED (User Interrupt)
`}</pre>
              </div>

              {/* States Table */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {TASK_STATES.map((state) => (
                  <div key={state.state} className={`${state.color} rounded-lg p-4`}>
                    <div className="font-semibold text-lg">{state.state}</div>
                    <p className="text-sm mt-1">{state.description}</p>
                    {state.next.length > 0 && (
                      <div className="mt-2 text-xs">
                        <span className="opacity-75">Naechste:</span>{' '}
                        {state.next.join(', ')}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Intents Tab */}
          {activeTab === 'intents' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-slate-900">Intent Types (22 unterstuetzte Typen)</h3>

              {INTENT_GROUPS.map((group) => (
                <div key={group.group} className={`${group.color} border rounded-lg p-4`}>
                  <h4 className="font-semibold text-slate-800 mb-3">{group.group}</h4>
                  <div className="space-y-2">
                    {group.intents.map((intent) => (
                      <div key={intent.type} className="bg-white rounded-lg p-3 shadow-sm">
                        <div className="flex items-start justify-between">
                          <div>
                            <code className="text-sm font-mono text-teal-700 bg-teal-50 px-2 py-0.5 rounded">
                              {intent.type}
                            </code>
                            <p className="text-sm text-slate-600 mt-1">{intent.description}</p>
                          </div>
                        </div>
                        <div className="mt-2 text-xs text-slate-500 italic">
                          Beispiel: &quot;{intent.example}&quot;
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* DSGVO Tab */}
          {activeTab === 'dsgvo' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-slate-900">DSGVO-Compliance</h3>

              {/* Key Principles */}
              <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                <h4 className="font-semibold text-green-800 mb-2">Kernprinzipien</h4>
                <ul className="list-disc list-inside text-sm text-green-700 space-y-1">
                  <li><strong>Audio NIEMALS persistiert</strong> - Nur transient im RAM</li>
                  <li><strong>Namespace-Verschluesselung</strong> - Key nur auf Lehrergeraet</li>
                  <li><strong>Keine Klartext-PII serverseitig</strong> - Nur verschluesselt oder pseudonymisiert</li>
                  <li><strong>TTL-basierte Auto-Loeschung</strong> - 7/30/90 Tage je nach Kategorie</li>
                </ul>
              </div>

              {/* Data Categories Table */}
              <div className="bg-white border border-slate-200 rounded-lg overflow-hidden">
                <table className="min-w-full divide-y divide-slate-200">
                  <thead className="bg-slate-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Kategorie</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Verarbeitung</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Speicherort</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">TTL</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Risiko</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-200">
                    {DSGVO_CATEGORIES.map((cat) => (
                      <tr key={cat.category}>
                        <td className="px-4 py-3">
                          <span className="mr-2">{cat.icon}</span>
                          <span className="font-medium">{cat.category}</span>
                        </td>
                        <td className="px-4 py-3 text-sm text-slate-600">{cat.processing}</td>
                        <td className="px-4 py-3 text-sm text-slate-600">{cat.storage}</td>
                        <td className="px-4 py-3 text-sm text-slate-600">{cat.ttl}</td>
                        <td className="px-4 py-3">
                          <span className={`px-2 py-1 rounded text-xs font-medium ${
                            cat.risk === 'low' ? 'bg-green-100 text-green-700' :
                            cat.risk === 'medium' ? 'bg-yellow-100 text-yellow-700' :
                            'bg-red-100 text-red-700'
                          }`}>
                            {cat.risk.toUpperCase()}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Audit Log Info */}
              <div className="bg-slate-50 border border-slate-200 rounded-lg p-4">
                <h4 className="font-semibold text-slate-800 mb-2">Audit Logs (ohne PII)</h4>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-green-600 font-medium">Erlaubt:</span>
                    <ul className="list-disc list-inside text-slate-600 mt-1">
                      <li>ref_id (truncated)</li>
                      <li>content_type</li>
                      <li>size_bytes</li>
                      <li>ttl_hours</li>
                    </ul>
                  </div>
                  <div>
                    <span className="text-red-600 font-medium">Verboten:</span>
                    <ul className="list-disc list-inside text-slate-600 mt-1">
                      <li>user_name</li>
                      <li>content / transcript</li>
                      <li>email</li>
                      <li>student_name</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* API Tab */}
          {activeTab === 'api' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-slate-900">Voice Service API (Port 8091)</h3>

              {/* REST Endpoints */}
              <div className="bg-white border border-slate-200 rounded-lg overflow-hidden">
                <table className="min-w-full divide-y divide-slate-200">
                  <thead className="bg-slate-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Methode</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Endpoint</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Beschreibung</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-200">
                    {API_ENDPOINTS.map((ep, idx) => (
                      <tr key={idx}>
                        <td className="px-4 py-3">
                          <span className={`px-2 py-1 rounded text-xs font-medium ${
                            ep.method === 'GET' ? 'bg-green-100 text-green-700' :
                            ep.method === 'POST' ? 'bg-blue-100 text-blue-700' :
                            ep.method === 'PUT' ? 'bg-yellow-100 text-yellow-700' :
                            ep.method === 'DELETE' ? 'bg-red-100 text-red-700' :
                            'bg-purple-100 text-purple-700'
                          }`}>
                            {ep.method}
                          </span>
                        </td>
                        <td className="px-4 py-3 font-mono text-sm">{ep.path}</td>
                        <td className="px-4 py-3 text-sm text-slate-600">{ep.description}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* WebSocket Protocol */}
              <div className="bg-slate-50 rounded-lg p-4">
                <h4 className="font-semibold text-slate-800 mb-3">WebSocket Protocol</h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                  <div className="bg-white rounded-lg p-3 border border-slate-200">
                    <div className="font-medium text-slate-700 mb-2">Client → Server</div>
                    <ul className="list-disc list-inside text-slate-600 space-y-1">
                      <li><code className="bg-slate-100 px-1 rounded">Binary</code>: Int16 PCM Audio (24kHz, 80ms)</li>
                      <li><code className="bg-slate-100 px-1 rounded">JSON</code>: {`{type: "config|end_turn|interrupt"}`}</li>
                    </ul>
                  </div>
                  <div className="bg-white rounded-lg p-3 border border-slate-200">
                    <div className="font-medium text-slate-700 mb-2">Server → Client</div>
                    <ul className="list-disc list-inside text-slate-600 space-y-1">
                      <li><code className="bg-slate-100 px-1 rounded">Binary</code>: Audio Response (base64)</li>
                      <li><code className="bg-slate-100 px-1 rounded">JSON</code>: {`{type: "transcript|intent|status|error"}`}</li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* Example curl commands */}
              <div className="bg-slate-900 rounded-lg p-4 text-sm">
                <h4 className="font-semibold text-slate-300 mb-3">Beispiel: Session erstellen</h4>
                <pre className="text-green-400 overflow-x-auto">{`curl -X POST http://localhost:8091/api/v1/sessions \\
  -H "Content-Type: application/json" \\
  -d '{
    "namespace_id": "ns-12345678abcdef12345678abcdef12",
    "key_hash": "sha256:dGVzdGtleWhhc2h0ZXN0a2V5aGFzaHRlc3Q=",
    "device_type": "pwa"
  }'`}</pre>
              </div>
            </div>
          )}
        </div>
      </div>
    </AdminLayout>
  )
}
