'use client'

import { useState } from 'react'
import Link from 'next/link'
import { ArrowLeft, Cpu, Brain, MessageSquare, Database, Activity, Shield, ChevronDown, ChevronRight, GitBranch, Layers, Server, FileText, AlertTriangle, CheckCircle, Zap, RefreshCw } from 'lucide-react'

interface Section {
  id: string
  title: string
  icon: React.ReactNode
  content: React.ReactNode
}

export default function ArchitecturePage() {
  const [expandedSections, setExpandedSections] = useState<string[]>(['overview', 'agents', 'soul-files'])

  const toggleSection = (id: string) => {
    setExpandedSections(prev =>
      prev.includes(id)
        ? prev.filter(s => s !== id)
        : [...prev, id]
    )
  }

  const sections: Section[] = [
    {
      id: 'overview',
      title: 'System-Uebersicht',
      icon: <Layers className="w-5 h-5" />,
      content: (
        <div className="space-y-6">
          <p className="text-gray-600">
            Das Breakpilot Multi-Agent-System basiert auf dem Mission Control Konzept. Es ermoeglicht
            die Koordination mehrerer spezialisierter KI-Agents, die gemeinsam komplexe Aufgaben loesen.
          </p>

          {/* Architecture Diagram */}
          <div className="bg-gray-50 rounded-xl p-6 font-mono text-sm overflow-x-auto">
            <pre className="text-gray-700">{`
┌─────────────────────────────────────────────────────────────────┐
│                     Breakpilot Services                          │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────────┐  │
│  │Voice Service│  │Klausur Svc  │  │  Admin-v2 / AlertAgent  │  │
│  └──────┬──────┘  └──────┬──────┘  └───────────┬─────────────┘  │
│         │                │                      │                │
│         └────────────────┼──────────────────────┘                │
│                          │                                       │
│  ┌───────────────────────▼───────────────────────────────────┐  │
│  │                    Agent Core                              │  │
│  │  ┌─────────────┐  ┌─────────────┐  ┌───────────────────┐  │  │
│  │  │   Sessions  │  │Shared Brain │  │   Orchestrator    │  │  │
│  │  │ - Manager   │  │ - Memory    │  │ - Message Bus     │  │  │
│  │  │ - Heartbeat │  │ - Context   │  │ - Supervisor      │  │  │
│  │  │ - Checkpoint│  │ - Knowledge │  │ - Task Router     │  │  │
│  │  └─────────────┘  └─────────────┘  └───────────────────┘  │  │
│  └───────────────────────────────────────────────────────────┘  │
│                          │                                       │
│  ┌───────────────────────▼───────────────────────────────────┐  │
│  │                   Infrastructure                           │  │
│  │     Valkey (Redis)          PostgreSQL          Qdrant     │  │
│  └───────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
            `}</pre>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <Server className="w-5 h-5 text-blue-600" />
                <span className="font-semibold text-blue-900">Session Management</span>
              </div>
              <p className="text-sm text-blue-700">
                Verwaltet Agent-Lifecycles mit State Machine, Checkpoints und automatischer Recovery.
              </p>
            </div>
            <div className="bg-purple-50 border border-purple-200 rounded-xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <Brain className="w-5 h-5 text-purple-600" />
                <span className="font-semibold text-purple-900">Shared Brain</span>
              </div>
              <p className="text-sm text-purple-700">
                Gemeinsames Gedaechtnis fuer alle Agents mit TTL, Context-Verwaltung und Knowledge Graph.
              </p>
            </div>
            <div className="bg-green-50 border border-green-200 rounded-xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <GitBranch className="w-5 h-5 text-green-600" />
                <span className="font-semibold text-green-900">Orchestrator</span>
              </div>
              <p className="text-sm text-green-700">
                Message Bus, Supervisor und Task Router fuer die Agent-Koordination.
              </p>
            </div>
          </div>
        </div>
      )
    },
    {
      id: 'agents',
      title: 'Agent-Typen',
      icon: <Cpu className="w-5 h-5" />,
      content: (
        <div className="space-y-4">
          <p className="text-gray-600 mb-4">
            Jeder Agent hat eine spezialisierte Rolle im System. Die Agents kommunizieren ueber den Message Bus
            und nutzen das Shared Brain fuer konsistente Entscheidungen.
          </p>

          <div className="grid gap-4">
            {/* TutorAgent */}
            <div className="border border-gray-200 rounded-xl p-4 hover:border-blue-300 transition-colors">
              <div className="flex items-start gap-4">
                <div className="p-3 bg-blue-100 rounded-lg">
                  <Brain className="w-6 h-6 text-blue-600" />
                </div>
                <div className="flex-1">
                  <h4 className="font-semibold text-gray-900">TutorAgent</h4>
                  <p className="text-sm text-gray-600 mb-2">Lernbegleitung und Fragen beantworten</p>
                  <div className="flex flex-wrap gap-2">
                    <span className="px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded-full">Geduldig</span>
                    <span className="px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded-full">Ermutigend</span>
                    <span className="px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded-full">Sokratisch</span>
                  </div>
                  <div className="mt-2 text-xs text-gray-500">
                    SOUL: tutor-agent.soul.md | Routing: learning_*, help_*, question_*
                  </div>
                </div>
              </div>
            </div>

            {/* GraderAgent */}
            <div className="border border-gray-200 rounded-xl p-4 hover:border-green-300 transition-colors">
              <div className="flex items-start gap-4">
                <div className="p-3 bg-green-100 rounded-lg">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
                <div className="flex-1">
                  <h4 className="font-semibold text-gray-900">GraderAgent</h4>
                  <p className="text-sm text-gray-600 mb-2">Klausur-Korrektur und Bewertung</p>
                  <div className="flex flex-wrap gap-2">
                    <span className="px-2 py-1 bg-green-50 text-green-700 text-xs rounded-full">Objektiv</span>
                    <span className="px-2 py-1 bg-green-50 text-green-700 text-xs rounded-full">Fair</span>
                    <span className="px-2 py-1 bg-green-50 text-green-700 text-xs rounded-full">Konstruktiv</span>
                  </div>
                  <div className="mt-2 text-xs text-gray-500">
                    SOUL: grader-agent.soul.md | Routing: grade_*, evaluate_*, correct_*
                  </div>
                </div>
              </div>
            </div>

            {/* QualityJudge */}
            <div className="border border-gray-200 rounded-xl p-4 hover:border-amber-300 transition-colors">
              <div className="flex items-start gap-4">
                <div className="p-3 bg-amber-100 rounded-lg">
                  <Shield className="w-6 h-6 text-amber-600" />
                </div>
                <div className="flex-1">
                  <h4 className="font-semibold text-gray-900">QualityJudge</h4>
                  <p className="text-sm text-gray-600 mb-2">BQAS Qualitaetspruefung</p>
                  <div className="flex flex-wrap gap-2">
                    <span className="px-2 py-1 bg-amber-50 text-amber-700 text-xs rounded-full">Kritisch</span>
                    <span className="px-2 py-1 bg-amber-50 text-amber-700 text-xs rounded-full">Praezise</span>
                    <span className="px-2 py-1 bg-amber-50 text-amber-700 text-xs rounded-full">Schnell</span>
                  </div>
                  <div className="mt-2 text-xs text-gray-500">
                    SOUL: quality-judge.soul.md | Routing: quality_*, review_*, validate_*
                  </div>
                </div>
              </div>
            </div>

            {/* AlertAgent */}
            <div className="border border-gray-200 rounded-xl p-4 hover:border-red-300 transition-colors">
              <div className="flex items-start gap-4">
                <div className="p-3 bg-red-100 rounded-lg">
                  <AlertTriangle className="w-6 h-6 text-red-600" />
                </div>
                <div className="flex-1">
                  <h4 className="font-semibold text-gray-900">AlertAgent</h4>
                  <p className="text-sm text-gray-600 mb-2">Monitoring und Benachrichtigungen</p>
                  <div className="flex flex-wrap gap-2">
                    <span className="px-2 py-1 bg-red-50 text-red-700 text-xs rounded-full">Wachsam</span>
                    <span className="px-2 py-1 bg-red-50 text-red-700 text-xs rounded-full">Proaktiv</span>
                    <span className="px-2 py-1 bg-red-50 text-red-700 text-xs rounded-full">Priorisierend</span>
                  </div>
                  <div className="mt-2 text-xs text-gray-500">
                    SOUL: alert-agent.soul.md | Routing: alert_*, monitor_*, notify_*
                  </div>
                </div>
              </div>
            </div>

            {/* Orchestrator */}
            <div className="border border-gray-200 rounded-xl p-4 hover:border-purple-300 transition-colors">
              <div className="flex items-start gap-4">
                <div className="p-3 bg-purple-100 rounded-lg">
                  <MessageSquare className="w-6 h-6 text-purple-600" />
                </div>
                <div className="flex-1">
                  <h4 className="font-semibold text-gray-900">Orchestrator</h4>
                  <p className="text-sm text-gray-600 mb-2">Task-Koordination und Routing</p>
                  <div className="flex flex-wrap gap-2">
                    <span className="px-2 py-1 bg-purple-50 text-purple-700 text-xs rounded-full">Koordinierend</span>
                    <span className="px-2 py-1 bg-purple-50 text-purple-700 text-xs rounded-full">Effizient</span>
                    <span className="px-2 py-1 bg-purple-50 text-purple-700 text-xs rounded-full">Zuverlaessig</span>
                  </div>
                  <div className="mt-2 text-xs text-gray-500">
                    SOUL: orchestrator.soul.md | Routing: Fallback fuer alle unbekannten Intents
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )
    },
    {
      id: 'soul-files',
      title: 'SOUL-Files (Persoenlichkeiten)',
      icon: <FileText className="w-5 h-5" />,
      content: (
        <div className="space-y-4">
          <p className="text-gray-600 mb-4">
            SOUL-Dateien (Semantic Outline for Unified Learning) definieren die Persoenlichkeit und
            Verhaltensregeln jedes Agents. Sie bestimmen, wie ein Agent kommuniziert, entscheidet und eskaliert.
          </p>

          <div className="bg-gray-900 rounded-xl p-6 text-gray-100 font-mono text-sm overflow-x-auto">
            <div className="text-gray-400 mb-4"># Beispiel: tutor-agent.soul.md</div>
            <pre className="text-green-400">{`
# TutorAgent SOUL

## Identitaet
Du bist ein geduldiger, ermutigender Lernbegleiter fuer Schueler.
Dein Ziel ist es, Verstaendnis zu foerdern, nicht Antworten vorzugeben.

## Kommunikationsstil
- Verwende einfache, klare Sprache
- Stelle Rueckfragen, um Verstaendnis zu pruefen
- Gib Hinweise statt direkter Loesungen
- Feiere kleine Erfolge

## Fachgebiete
- Mathematik (Grundschule bis Abitur)
- Naturwissenschaften (Physik, Chemie, Biologie)
- Sprachen (Deutsch, Englisch)

## Einschraenkungen
- Gib NIEMALS vollstaendige Loesungen fuer Hausaufgaben
- Verweise bei komplexen Themen auf Lehrkraefte
- Erkenne Frustration und biete Pausen an

## Eskalation
- Bei wiederholtem Unverstaendnis: Schlage alternatives Erklaerformat vor
- Bei emotionaler Belastung: Empfehle Gespraech mit Vertrauensperson
- Bei technischen Problemen: Eskaliere an Support
            `}</pre>
          </div>

          <div className="mt-6">
            <h4 className="font-semibold text-gray-900 mb-3">SOUL-Struktur</h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="bg-white border border-gray-200 rounded-lg p-4">
                <h5 className="font-medium text-gray-900 mb-2">Identitaet</h5>
                <p className="text-sm text-gray-600">Wer ist der Agent? Welche Rolle nimmt er ein?</p>
              </div>
              <div className="bg-white border border-gray-200 rounded-lg p-4">
                <h5 className="font-medium text-gray-900 mb-2">Kommunikationsstil</h5>
                <p className="text-sm text-gray-600">Wie kommuniziert der Agent mit Benutzern?</p>
              </div>
              <div className="bg-white border border-gray-200 rounded-lg p-4">
                <h5 className="font-medium text-gray-900 mb-2">Fachgebiete</h5>
                <p className="text-sm text-gray-600">In welchen Bereichen ist der Agent kompetent?</p>
              </div>
              <div className="bg-white border border-gray-200 rounded-lg p-4">
                <h5 className="font-medium text-gray-900 mb-2">Einschraenkungen</h5>
                <p className="text-sm text-gray-600">Was darf der Agent NICHT tun?</p>
              </div>
              <div className="bg-white border border-gray-200 rounded-lg p-4 md:col-span-2">
                <h5 className="font-medium text-gray-900 mb-2">Eskalation</h5>
                <p className="text-sm text-gray-600">Wann und wie eskaliert der Agent an andere Agents oder Menschen?</p>
              </div>
            </div>
          </div>
        </div>
      )
    },
    {
      id: 'message-bus',
      title: 'Message Bus & Kommunikation',
      icon: <MessageSquare className="w-5 h-5" />,
      content: (
        <div className="space-y-4">
          <p className="text-gray-600 mb-4">
            Der Message Bus ermoeglicht die asynchrone Kommunikation zwischen Agents via Redis Pub/Sub.
            Er unterstuetzt Prioritaeten, Request-Response-Pattern und Broadcast-Nachrichten.
          </p>

          <div className="bg-gray-50 rounded-xl p-6 font-mono text-sm">
            <div className="text-gray-500 mb-2"># Nachrichtenfluss</div>
            <pre className="text-gray-700">{`
┌──────────────┐                    ┌──────────────┐
│   Sender     │                    │   Receiver   │
│   (Agent)    │                    │   (Agent)    │
└──────┬───────┘                    └──────▲───────┘
       │                                   │
       │ publish(AgentMessage)             │ handle(message)
       │                                   │
       ▼                                   │
┌────────────────────────────────────────────────────────┐
│                     Message Bus                         │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐    │
│  │ Priority Q  │  │   Routing   │  │   Logging   │    │
│  │ HIGH/NORMAL │  │   Rules     │  │   Audit     │    │
│  └─────────────┘  └─────────────┘  └─────────────┘    │
│                                                         │
│                 Redis Pub/Sub                          │
└────────────────────────────────────────────────────────┘
            `}</pre>
          </div>

          <div className="mt-6">
            <h4 className="font-semibold text-gray-900 mb-3">Nachrichtentypen</h4>
            <div className="overflow-x-auto">
              <table className="min-w-full border border-gray-200 rounded-lg">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-2 text-left text-sm font-medium text-gray-900">Typ</th>
                    <th className="px-4 py-2 text-left text-sm font-medium text-gray-900">Prioritaet</th>
                    <th className="px-4 py-2 text-left text-sm font-medium text-gray-900">Beschreibung</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  <tr>
                    <td className="px-4 py-2 text-sm font-mono text-gray-700">task_request</td>
                    <td className="px-4 py-2"><span className="px-2 py-1 bg-yellow-100 text-yellow-700 text-xs rounded">NORMAL</span></td>
                    <td className="px-4 py-2 text-sm text-gray-600">Neue Aufgabe an Agent senden</td>
                  </tr>
                  <tr>
                    <td className="px-4 py-2 text-sm font-mono text-gray-700">task_response</td>
                    <td className="px-4 py-2"><span className="px-2 py-1 bg-yellow-100 text-yellow-700 text-xs rounded">NORMAL</span></td>
                    <td className="px-4 py-2 text-sm text-gray-600">Antwort auf task_request</td>
                  </tr>
                  <tr>
                    <td className="px-4 py-2 text-sm font-mono text-gray-700">escalation</td>
                    <td className="px-4 py-2"><span className="px-2 py-1 bg-orange-100 text-orange-700 text-xs rounded">HIGH</span></td>
                    <td className="px-4 py-2 text-sm text-gray-600">Eskalation an anderen Agent</td>
                  </tr>
                  <tr>
                    <td className="px-4 py-2 text-sm font-mono text-gray-700">alert</td>
                    <td className="px-4 py-2"><span className="px-2 py-1 bg-red-100 text-red-700 text-xs rounded">CRITICAL</span></td>
                    <td className="px-4 py-2 text-sm text-gray-600">Kritische Benachrichtigung</td>
                  </tr>
                  <tr>
                    <td className="px-4 py-2 text-sm font-mono text-gray-700">heartbeat</td>
                    <td className="px-4 py-2"><span className="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded">LOW</span></td>
                    <td className="px-4 py-2 text-sm text-gray-600">Liveness-Signal</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )
    },
    {
      id: 'shared-brain',
      title: 'Shared Brain (Gedaechtnis)',
      icon: <Brain className="w-5 h-5" />,
      content: (
        <div className="space-y-4">
          <p className="text-gray-600 mb-4">
            Das Shared Brain speichert Wissen und Kontext, auf den alle Agents zugreifen koennen.
            Es besteht aus drei Komponenten: Memory Store, Context Manager und Knowledge Graph.
          </p>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-white border border-gray-200 rounded-xl p-5">
              <div className="flex items-center gap-2 mb-3">
                <Database className="w-5 h-5 text-blue-600" />
                <h4 className="font-semibold text-gray-900">Memory Store</h4>
              </div>
              <p className="text-sm text-gray-600 mb-3">
                Langzeit-Gedaechtnis fuer Fakten, Entscheidungen und Lernfortschritte.
              </p>
              <ul className="text-xs text-gray-500 space-y-1">
                <li>- TTL-basierte Expiration (30 Tage default)</li>
                <li>- Access-Tracking (Haeufigkeit)</li>
                <li>- Pattern-basierte Suche</li>
                <li>- Hybrid: Redis + PostgreSQL</li>
              </ul>
            </div>

            <div className="bg-white border border-gray-200 rounded-xl p-5">
              <div className="flex items-center gap-2 mb-3">
                <Activity className="w-5 h-5 text-purple-600" />
                <h4 className="font-semibold text-gray-900">Context Manager</h4>
              </div>
              <p className="text-sm text-gray-600 mb-3">
                Verwaltet Konversationskontext mit automatischer Komprimierung.
              </p>
              <ul className="text-xs text-gray-500 space-y-1">
                <li>- Max 50 Messages pro Context</li>
                <li>- Automatische Zusammenfassung</li>
                <li>- System-Messages bleiben erhalten</li>
                <li>- Entity-Extraktion</li>
              </ul>
            </div>

            <div className="bg-white border border-gray-200 rounded-xl p-5">
              <div className="flex items-center gap-2 mb-3">
                <GitBranch className="w-5 h-5 text-green-600" />
                <h4 className="font-semibold text-gray-900">Knowledge Graph</h4>
              </div>
              <p className="text-sm text-gray-600 mb-3">
                Graph-basierte Darstellung von Entitaeten und ihren Beziehungen.
              </p>
              <ul className="text-xs text-gray-500 space-y-1">
                <li>- Entitaeten: Student, Lehrer, Fach</li>
                <li>- Beziehungen: lernt, unterrichtet</li>
                <li>- BFS-basierte Pfadsuche</li>
                <li>- Verwandte Entitaeten finden</li>
              </ul>
            </div>
          </div>

          <div className="bg-gray-50 rounded-xl p-6 font-mono text-sm mt-6">
            <div className="text-gray-500 mb-2"># Memory Store Beispiel</div>
            <pre className="text-gray-700">{`
# Speichern
await store.remember(
    key="student:123:progress",
    value={"level": 5, "score": 85, "topic": "algebra"},
    agent_id="tutor-agent",
    ttl_days=30
)

# Abrufen
progress = await store.recall("student:123:progress")
# → {"level": 5, "score": 85, "topic": "algebra"}

# Suchen
all_progress = await store.search("student:123:*")
# → [Memory(...), Memory(...), ...]
            `}</pre>
          </div>
        </div>
      )
    },
    {
      id: 'task-routing',
      title: 'Task Routing',
      icon: <Zap className="w-5 h-5" />,
      content: (
        <div className="space-y-4">
          <p className="text-gray-600 mb-4">
            Der Task Router entscheidet, welcher Agent eine Anfrage bearbeitet. Er verwendet
            Intent-basierte Regeln mit Prioritaeten und Fallback-Ketten.
          </p>

          <div className="overflow-x-auto">
            <table className="min-w-full border border-gray-200 rounded-lg">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-2 text-left text-sm font-medium text-gray-900">Intent-Pattern</th>
                  <th className="px-4 py-2 text-left text-sm font-medium text-gray-900">Ziel-Agent</th>
                  <th className="px-4 py-2 text-left text-sm font-medium text-gray-900">Prioritaet</th>
                  <th className="px-4 py-2 text-left text-sm font-medium text-gray-900">Fallback</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                <tr>
                  <td className="px-4 py-2 text-sm font-mono text-blue-700">learning_*</td>
                  <td className="px-4 py-2 text-sm text-gray-700">TutorAgent</td>
                  <td className="px-4 py-2 text-sm text-gray-700">10</td>
                  <td className="px-4 py-2 text-sm text-gray-500">Orchestrator</td>
                </tr>
                <tr>
                  <td className="px-4 py-2 text-sm font-mono text-blue-700">help_*, question_*</td>
                  <td className="px-4 py-2 text-sm text-gray-700">TutorAgent</td>
                  <td className="px-4 py-2 text-sm text-gray-700">8</td>
                  <td className="px-4 py-2 text-sm text-gray-500">Orchestrator</td>
                </tr>
                <tr>
                  <td className="px-4 py-2 text-sm font-mono text-green-700">grade_*, evaluate_*</td>
                  <td className="px-4 py-2 text-sm text-gray-700">GraderAgent</td>
                  <td className="px-4 py-2 text-sm text-gray-700">10</td>
                  <td className="px-4 py-2 text-sm text-gray-500">Orchestrator</td>
                </tr>
                <tr>
                  <td className="px-4 py-2 text-sm font-mono text-amber-700">quality_*, review_*</td>
                  <td className="px-4 py-2 text-sm text-gray-700">QualityJudge</td>
                  <td className="px-4 py-2 text-sm text-gray-700">10</td>
                  <td className="px-4 py-2 text-sm text-gray-500">GraderAgent</td>
                </tr>
                <tr>
                  <td className="px-4 py-2 text-sm font-mono text-red-700">alert_*, monitor_*</td>
                  <td className="px-4 py-2 text-sm text-gray-700">AlertAgent</td>
                  <td className="px-4 py-2 text-sm text-gray-700">10</td>
                  <td className="px-4 py-2 text-sm text-gray-500">Orchestrator</td>
                </tr>
                <tr className="bg-gray-50">
                  <td className="px-4 py-2 text-sm font-mono text-gray-500">* (alle anderen)</td>
                  <td className="px-4 py-2 text-sm text-gray-700">Orchestrator</td>
                  <td className="px-4 py-2 text-sm text-gray-700">0</td>
                  <td className="px-4 py-2 text-sm text-gray-500">-</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-white border border-gray-200 rounded-xl p-4">
              <h4 className="font-semibold text-gray-900 mb-2">Routing-Strategien</h4>
              <ul className="text-sm text-gray-600 space-y-2">
                <li><span className="font-mono text-blue-600">ROUND_ROBIN</span> - Gleichmaessige Verteilung</li>
                <li><span className="font-mono text-blue-600">LEAST_LOADED</span> - Agent mit wenigsten Tasks</li>
                <li><span className="font-mono text-blue-600">PRIORITY</span> - Hoechste Prioritaet zuerst</li>
                <li><span className="font-mono text-blue-600">RANDOM</span> - Zufaellige Auswahl</li>
              </ul>
            </div>
            <div className="bg-white border border-gray-200 rounded-xl p-4">
              <h4 className="font-semibold text-gray-900 mb-2">Fallback-Verhalten</h4>
              <ul className="text-sm text-gray-600 space-y-2">
                <li>1. Versuche Ziel-Agent zu erreichen</li>
                <li>2. Bei Timeout: Fallback-Agent nutzen</li>
                <li>3. Bei Fehler: Orchestrator uebernimmt</li>
                <li>4. Bei kritischen Fehlern: Alert an Admin</li>
              </ul>
            </div>
          </div>
        </div>
      )
    },
    {
      id: 'session-lifecycle',
      title: 'Session Lifecycle',
      icon: <RefreshCw className="w-5 h-5" />,
      content: (
        <div className="space-y-4">
          <p className="text-gray-600 mb-4">
            Sessions verwalten den Zustand von Agent-Interaktionen. Jede Session hat einen definierten
            Lebenszyklus mit Checkpoints fuer Recovery.
          </p>

          <div className="bg-gray-50 rounded-xl p-6 font-mono text-sm">
            <div className="text-gray-500 mb-2"># Session State Machine</div>
            <pre className="text-gray-700">{`
                    ┌─────────────────────────────────────┐
                    │                                     │
                    ▼                                     │
┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐
│  ACTIVE  │───▶│  PAUSED  │───▶│ COMPLETED│    │  FAILED  │
└──────────┘    └──────────┘    └──────────┘    └──────────┘
     │               │                               ▲
     │               │                               │
     └───────────────┴───────────────────────────────┘
                          (bei Fehler)

States:
- ACTIVE: Session laeuft, Agent verarbeitet Tasks
- PAUSED: Session pausiert, wartet auf Eingabe
- COMPLETED: Session erfolgreich beendet
- FAILED: Session mit Fehler beendet
            `}</pre>
          </div>

          <div className="mt-6">
            <h4 className="font-semibold text-gray-900 mb-3">Heartbeat Monitoring</h4>
            <div className="bg-white border border-gray-200 rounded-xl p-5">
              <div className="grid grid-cols-3 gap-4 text-center">
                <div>
                  <div className="text-2xl font-bold text-gray-900">30s</div>
                  <div className="text-sm text-gray-500">Timeout</div>
                </div>
                <div>
                  <div className="text-2xl font-bold text-gray-900">5s</div>
                  <div className="text-sm text-gray-500">Check Interval</div>
                </div>
                <div>
                  <div className="text-2xl font-bold text-gray-900">3</div>
                  <div className="text-sm text-gray-500">Max Missed Beats</div>
                </div>
              </div>
              <p className="text-sm text-gray-600 mt-4 text-center">
                Nach 3 verpassten Heartbeats wird der Agent als ausgefallen markiert und die
                Restart-Policy greift (max. 3 Versuche).
              </p>
            </div>
          </div>
        </div>
      )
    },
    {
      id: 'database',
      title: 'Datenbank-Schema',
      icon: <Database className="w-5 h-5" />,
      content: (
        <div className="space-y-4">
          <p className="text-gray-600 mb-4">
            Das Agent-System nutzt PostgreSQL fuer persistente Daten und Valkey (Redis) fuer Caching und Pub/Sub.
          </p>

          <div className="space-y-4">
            {/* agent_sessions */}
            <div className="bg-white border border-gray-200 rounded-xl p-4">
              <h4 className="font-semibold text-gray-900 mb-2 font-mono">agent_sessions</h4>
              <p className="text-sm text-gray-600 mb-3">Speichert Session-Daten mit Checkpoints</p>
              <div className="bg-gray-50 rounded-lg p-3 font-mono text-xs overflow-x-auto">
                <pre>{`
CREATE TABLE agent_sessions (
    id UUID PRIMARY KEY,
    agent_type VARCHAR(50) NOT NULL,
    user_id UUID REFERENCES users(id),
    state VARCHAR(20) NOT NULL DEFAULT 'active',
    context JSONB DEFAULT '{}',
    checkpoints JSONB DEFAULT '[]',
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    last_heartbeat TIMESTAMPTZ DEFAULT NOW()
);
                `}</pre>
              </div>
            </div>

            {/* agent_memory */}
            <div className="bg-white border border-gray-200 rounded-xl p-4">
              <h4 className="font-semibold text-gray-900 mb-2 font-mono">agent_memory</h4>
              <p className="text-sm text-gray-600 mb-3">Langzeit-Gedaechtnis mit TTL</p>
              <div className="bg-gray-50 rounded-lg p-3 font-mono text-xs overflow-x-auto">
                <pre>{`
CREATE TABLE agent_memory (
    id UUID PRIMARY KEY,
    namespace VARCHAR(100) NOT NULL,
    key VARCHAR(500) NOT NULL,
    value JSONB NOT NULL,
    agent_id VARCHAR(50) NOT NULL,
    access_count INTEGER DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    expires_at TIMESTAMPTZ,
    UNIQUE(namespace, key)
);
                `}</pre>
              </div>
            </div>

            {/* agent_messages */}
            <div className="bg-white border border-gray-200 rounded-xl p-4">
              <h4 className="font-semibold text-gray-900 mb-2 font-mono">agent_messages</h4>
              <p className="text-sm text-gray-600 mb-3">Audit-Trail fuer Inter-Agent Kommunikation</p>
              <div className="bg-gray-50 rounded-lg p-3 font-mono text-xs overflow-x-auto">
                <pre>{`
CREATE TABLE agent_messages (
    id UUID PRIMARY KEY,
    sender VARCHAR(50) NOT NULL,
    receiver VARCHAR(50) NOT NULL,
    message_type VARCHAR(50) NOT NULL,
    payload JSONB NOT NULL,
    priority INTEGER DEFAULT 1,
    correlation_id UUID,
    created_at TIMESTAMPTZ DEFAULT NOW()
);
                `}</pre>
              </div>
            </div>
          </div>
        </div>
      )
    }
  ]

  return (
    <div className="p-6 max-w-5xl mx-auto">
      {/* Header */}
      <div className="mb-8">
        <Link
          href="/ai/agents"
          className="flex items-center gap-2 text-gray-500 hover:text-gray-700 mb-4"
        >
          <ArrowLeft className="w-4 h-4" />
          Zurueck zur Agent-Verwaltung
        </Link>
        <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-3">
          <div className="p-2 bg-purple-100 rounded-lg">
            <FileText className="w-6 h-6 text-purple-600" />
          </div>
          Multi-Agent Architektur
        </h1>
        <p className="text-gray-500 mt-1">
          Technische Dokumentation des Breakpilot Multi-Agent-Systems
        </p>
      </div>

      {/* Table of Contents */}
      <div className="bg-gray-50 rounded-xl p-5 mb-8">
        <h2 className="font-semibold text-gray-900 mb-3">Inhaltsverzeichnis</h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
          {sections.map(section => (
            <button
              key={section.id}
              onClick={() => {
                if (!expandedSections.includes(section.id)) {
                  setExpandedSections(prev => [...prev, section.id])
                }
                document.getElementById(section.id)?.scrollIntoView({ behavior: 'smooth' })
              }}
              className="flex items-center gap-2 text-sm text-gray-600 hover:text-teal-600 text-left p-2 rounded-lg hover:bg-gray-100 transition-colors"
            >
              {section.icon}
              <span className="truncate">{section.title}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Sections */}
      <div className="space-y-4">
        {sections.map(section => (
          <div
            key={section.id}
            id={section.id}
            className="bg-white border border-gray-200 rounded-xl overflow-hidden"
          >
            <button
              onClick={() => toggleSection(section.id)}
              className="w-full flex items-center justify-between p-5 hover:bg-gray-50 transition-colors"
            >
              <div className="flex items-center gap-3">
                <div className="p-2 bg-gray-100 rounded-lg">
                  {section.icon}
                </div>
                <span className="font-semibold text-gray-900">{section.title}</span>
              </div>
              {expandedSections.includes(section.id) ? (
                <ChevronDown className="w-5 h-5 text-gray-400" />
              ) : (
                <ChevronRight className="w-5 h-5 text-gray-400" />
              )}
            </button>
            {expandedSections.includes(section.id) && (
              <div className="px-5 pb-5 border-t border-gray-100 pt-4">
                {section.content}
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Footer Links */}
      <div className="mt-8 bg-teal-50 border border-teal-200 rounded-xl p-5">
        <h3 className="font-semibold text-teal-900 mb-3">Weiterführende Ressourcen</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <Link
            href="/ai/agents"
            className="flex items-center gap-2 text-sm text-teal-700 hover:text-teal-900"
          >
            <Cpu className="w-4 h-4" />
            Agent-Uebersicht
          </Link>
          <Link
            href="/ai/agents/sessions"
            className="flex items-center gap-2 text-sm text-teal-700 hover:text-teal-900"
          >
            <Activity className="w-4 h-4" />
            Aktive Sessions
          </Link>
          <Link
            href="/ai/agents/statistics"
            className="flex items-center gap-2 text-sm text-teal-700 hover:text-teal-900"
          >
            <Database className="w-4 h-4" />
            Statistiken
          </Link>
        </div>
      </div>
    </div>
  )
}
