'use client'

/**
 * Architecture Overview — Interaktiver Service-Graph
 *
 * ReactFlow-Visualisierung der 13 Compliance-Services in 4 Schwimmbahnen:
 * Frontend, Backend APIs, Infrastructure, Data Sovereignty.
 * Analog zum SDK-Flow, aber fuer die Service-Topologie.
 */

import { useCallback, useState, useMemo, useEffect } from 'react'
import ReactFlow, {
  Node,
  Edge,
  Controls,
  Background,
  MiniMap,
  useNodesState,
  useEdgesState,
  BackgroundVariant,
  MarkerType,
  Panel,
} from 'reactflow'
import 'reactflow/dist/style.css'

import {
  ARCH_SERVICES,
  ARCH_EDGES,
  LAYERS,
  getAllDbTables,
  getAllRagCollections,
  type ArchService,
  type ServiceLayer,
} from './architecture-data'

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

type LayerFilter = 'alle' | ServiceLayer

// =============================================================================
// LAYOUT
// =============================================================================

const NODE_WIDTH = 180
const NODE_HEIGHT = 70
const NODE_X_SPACING = 220
const LANE_Y_START = 80
const LANE_LABEL_HEIGHT = 40

const LAYER_ORDER: ServiceLayer[] = ['frontend', 'backend', 'infrastructure', 'data-sovereignty']

function getServicePosition(service: ArchService): { x: number; y: number } {
  const layer = LAYERS[service.layer]
  const layerServices = ARCH_SERVICES.filter(s => s.layer === service.layer)
  const idx = layerServices.findIndex(s => s.id === service.id)

  return {
    x: 80 + idx * NODE_X_SPACING,
    y: LANE_Y_START + LANE_LABEL_HEIGHT + layer.y,
  }
}

// =============================================================================
// DETAIL PANEL
// =============================================================================

function DetailPanel({
  service,
  onClose,
}: {
  service: ArchService
  onClose: () => void
}) {
  const layer = LAYERS[service.layer]

  return (
    <div className="w-80 bg-white border-l border-slate-200 overflow-y-auto">
      <div className="sticky top-0 bg-white z-10 border-b border-slate-200">
        <div className="flex items-center justify-between p-4">
          <h3 className="font-bold text-slate-900">{service.name}</h3>
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-slate-600 text-lg leading-none"
          >
            x
          </button>
        </div>
        <div className="px-4 pb-3 flex items-center gap-2">
          <span
            className="px-2 py-0.5 rounded text-xs font-medium"
            style={{ background: layer.colorBg, color: layer.colorText }}
          >
            {layer.name}
          </span>
          <span className="text-xs text-slate-400">{service.tech}</span>
        </div>
      </div>

      <div className="p-4 space-y-4">
        {/* Beschreibung */}
        <p className="text-sm text-slate-700 leading-relaxed">{service.description}</p>

        {/* Tech + Port + Container */}
        <div className="bg-slate-50 rounded-lg p-3 space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-slate-500">Tech</span>
            <span className="font-medium text-slate-800">{service.tech}</span>
          </div>
          {service.port && (
            <div className="flex items-center justify-between text-sm">
              <span className="text-slate-500">Port</span>
              <code className="text-xs bg-slate-200 px-1.5 py-0.5 rounded">{service.port}</code>
            </div>
          )}
          {service.url && (
            <div className="flex items-center justify-between text-sm">
              <span className="text-slate-500">URL</span>
              <a
                href={service.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-xs text-blue-600 hover:underline truncate max-w-[180px]"
              >
                {service.url}
              </a>
            </div>
          )}
          <div className="flex items-center justify-between text-sm">
            <span className="text-slate-500">Container</span>
            <code className="text-xs bg-slate-200 px-1.5 py-0.5 rounded truncate max-w-[180px]">{service.container}</code>
          </div>
        </div>

        {/* DB Tables */}
        {service.dbTables.length > 0 && (
          <div>
            <h4 className="text-xs font-semibold text-slate-500 uppercase mb-1.5">
              DB-Tabellen ({service.dbTables.length})
            </h4>
            <div className="space-y-1">
              {service.dbTables.map(table => (
                <div
                  key={table}
                  className="text-sm bg-slate-100 rounded px-2 py-1"
                >
                  <code className="text-slate-700 text-xs">{table}</code>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* RAG Collections */}
        {service.ragCollections.length > 0 && (
          <div>
            <h4 className="text-xs font-semibold text-slate-500 uppercase mb-1.5">
              RAG-Collections ({service.ragCollections.length})
            </h4>
            <div className="space-y-1">
              {service.ragCollections.map(rag => (
                <div
                  key={rag}
                  className="text-sm bg-green-50 rounded px-2 py-1"
                >
                  <code className="text-green-700 text-xs">{rag}</code>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* API Endpoints */}
        {service.apiEndpoints.length > 0 && (
          <div>
            <h4 className="text-xs font-semibold text-slate-500 uppercase mb-1.5">
              API-Endpunkte ({service.apiEndpoints.length})
            </h4>
            <div className="space-y-1">
              {service.apiEndpoints.map(ep => (
                <div
                  key={ep}
                  className="text-sm bg-violet-50 rounded px-2 py-1"
                >
                  <code className="text-violet-700 text-xs">{ep}</code>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Dependencies */}
        {service.dependsOn.length > 0 && (
          <div>
            <h4 className="text-xs font-semibold text-slate-500 uppercase mb-1.5">
              Abhaengigkeiten
            </h4>
            <div className="space-y-1">
              {service.dependsOn.map(depId => {
                const dep = ARCH_SERVICES.find(s => s.id === depId)
                return (
                  <div
                    key={depId}
                    className="text-sm text-slate-600 bg-slate-50 rounded px-2 py-1"
                  >
                    {dep?.name || depId}
                  </div>
                )
              })}
            </div>
          </div>
        )}

        {/* Open URL */}
        {service.url && (
          <button
            onClick={() => window.open(service.url!, '_blank')}
            className="w-full mt-2 px-4 py-2 bg-purple-600 text-white rounded-lg text-sm font-medium hover:bg-purple-700 transition-colors"
          >
            Service oeffnen
          </button>
        )}
      </div>
    </div>
  )
}

// =============================================================================
// MAIN COMPONENT
// =============================================================================

export default function ArchitecturePage() {
  const [selectedService, setSelectedService] = useState<ArchService | null>(null)
  const [layerFilter, setLayerFilter] = useState<LayerFilter>('alle')
  const [showDb, setShowDb] = useState(false)
  const [showRag, setShowRag] = useState(false)
  const [showApis, setShowApis] = useState(false)
  const [expandedServices, setExpandedServices] = useState<Set<string>>(new Set())

  const toggleExpanded = useCallback((id: string) => {
    setExpandedServices(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }, [])

  const allDbTables = useMemo(() => getAllDbTables(), [])
  const allRagCollections = useMemo(() => getAllRagCollections(), [])

  // =========================================================================
  // Build Nodes + Edges
  // =========================================================================

  const { nodes: initialNodes, edges: initialEdges } = useMemo(() => {
    const nodes: Node[] = []
    const edges: Edge[] = []

    const visibleServices =
      layerFilter === 'alle'
        ? ARCH_SERVICES
        : ARCH_SERVICES.filter(s => s.layer === layerFilter)

    const visibleIds = new Set(visibleServices.map(s => s.id))

    // ── Service Nodes ──────────────────────────────────────────────────────
    visibleServices.forEach(service => {
      const layer = LAYERS[service.layer]
      const pos = getServicePosition(service)
      const isSelected = selectedService?.id === service.id

      nodes.push({
        id: service.id,
        type: 'default',
        position: pos,
        data: {
          label: (
            <div className="text-center px-1">
              <div className="font-medium text-xs leading-tight">
                {service.nameShort}
              </div>
              <div className="text-[10px] opacity-70 mt-0.5">
                {service.tech}
              </div>
              {service.port && (
                <div className="text-[9px] opacity-50 mt-0.5">
                  :{service.port}
                </div>
              )}
            </div>
          ),
        },
        style: {
          background: isSelected ? layer.colorBorder : layer.colorBg,
          color: isSelected ? 'white' : layer.colorText,
          border: `2px solid ${layer.colorBorder}`,
          borderRadius: '10px',
          padding: '8px 4px',
          minWidth: `${NODE_WIDTH}px`,
          maxWidth: `${NODE_WIDTH}px`,
          cursor: 'pointer',
          boxShadow: isSelected
            ? `0 0 16px ${layer.colorBorder}`
            : '0 1px 3px rgba(0,0,0,0.08)',
        },
      })
    })

    // ── Connection Edges ───────────────────────────────────────────────────
    ARCH_EDGES.forEach(archEdge => {
      if (visibleIds.has(archEdge.source) && visibleIds.has(archEdge.target)) {
        const isHighlighted =
          selectedService?.id === archEdge.source ||
          selectedService?.id === archEdge.target

        edges.push({
          id: `e-${archEdge.source}-${archEdge.target}`,
          source: archEdge.source,
          target: archEdge.target,
          type: 'smoothstep',
          animated: isHighlighted,
          label: archEdge.label,
          labelStyle: { fontSize: 9, fill: isHighlighted ? '#7c3aed' : '#94a3b8' },
          style: {
            stroke: isHighlighted ? '#7c3aed' : '#94a3b8',
            strokeWidth: isHighlighted ? 2.5 : 1.5,
          },
          markerEnd: {
            type: MarkerType.ArrowClosed,
            color: isHighlighted ? '#7c3aed' : '#94a3b8',
            width: 14,
            height: 14,
          },
        })
      }
    })

    // ── DB Table Nodes ─────────────────────────────────────────────────────
    if (showDb) {
      const dbTablesInUse = new Set<string>()
      visibleServices.forEach(s => s.dbTables.forEach(t => dbTablesInUse.add(t)))

      let dbIdx = 0
      dbTablesInUse.forEach(table => {
        const nodeId = `db-${table}`
        nodes.push({
          id: nodeId,
          type: 'default',
          position: { x: -250, y: LANE_Y_START + dbIdx * 60 },
          data: {
            label: (
              <div className="text-center">
                <div className="font-medium text-[10px] leading-tight">{table}</div>
              </div>
            ),
          },
          style: {
            background: '#f1f5f9',
            color: '#475569',
            border: '1px solid #94a3b8',
            borderRadius: '6px',
            padding: '4px 6px',
            fontSize: '10px',
            minWidth: '140px',
          },
        })

        visibleServices
          .filter(s => s.dbTables.includes(table))
          .forEach(svc => {
            edges.push({
              id: `e-db-${table}-${svc.id}`,
              source: nodeId,
              target: svc.id,
              type: 'straight',
              style: { stroke: '#94a3b8', strokeWidth: 1, strokeDasharray: '6 3' },
            })
          })

        dbIdx++
      })
    }

    // ── RAG Collection Nodes ───────────────────────────────────────────────
    if (showRag) {
      const ragInUse = new Set<string>()
      visibleServices.forEach(s => s.ragCollections.forEach(r => ragInUse.add(r)))

      let ragIdx = 0
      ragInUse.forEach(collection => {
        const nodeId = `rag-${collection}`
        const rightX = 1200

        nodes.push({
          id: nodeId,
          type: 'default',
          position: { x: rightX, y: LANE_Y_START + ragIdx * 60 },
          data: {
            label: (
              <div className="text-center">
                <div className="font-medium text-[10px] leading-tight">
                  {collection.replace('bp_', '')}
                </div>
              </div>
            ),
          },
          style: {
            background: '#dcfce7',
            color: '#166534',
            border: '1px solid #22c55e',
            borderRadius: '6px',
            padding: '4px 6px',
            fontSize: '10px',
            minWidth: '130px',
          },
        })

        visibleServices
          .filter(s => s.ragCollections.includes(collection))
          .forEach(svc => {
            edges.push({
              id: `e-rag-${collection}-${svc.id}`,
              source: nodeId,
              target: svc.id,
              type: 'straight',
              style: { stroke: '#22c55e', strokeWidth: 1, strokeDasharray: '6 3' },
            })
          })

        ragIdx++
      })
    }

    // ── API Endpoint Nodes ─────────────────────────────────────────────────
    if (showApis) {
      visibleServices.forEach(svc => {
        if (svc.apiEndpoints.length === 0) return
        const svcPos = getServicePosition(svc)

        svc.apiEndpoints.forEach((ep, idx) => {
          const nodeId = `api-${svc.id}-${idx}`
          nodes.push({
            id: nodeId,
            type: 'default',
            position: { x: svcPos.x + NODE_WIDTH + 30, y: svcPos.y + idx * 32 },
            data: {
              label: (
                <div className="text-[9px] font-mono leading-tight truncate">{ep}</div>
              ),
            },
            style: {
              background: '#faf5ff',
              color: '#7c3aed',
              border: '1px solid #c4b5fd',
              borderRadius: '4px',
              padding: '2px 6px',
              fontSize: '9px',
              minWidth: '160px',
            },
          })

          edges.push({
            id: `e-api-${svc.id}-${idx}`,
            source: svc.id,
            target: nodeId,
            type: 'straight',
            style: { stroke: '#c4b5fd', strokeWidth: 1 },
          })
        })
      })
    }

    return { nodes, edges }
  }, [layerFilter, showDb, showRag, showApis, selectedService])

  // =========================================================================
  // React Flow State
  // =========================================================================

  const [nodes, setNodes, onNodesChange] = useNodesState([])
  const [edges, setEdges, onEdgesChange] = useEdgesState([])

  useEffect(() => {
    setNodes(initialNodes)
    setEdges(initialEdges)
  }, [initialNodes, initialEdges, setNodes, setEdges])

  const onNodeClick = useCallback((_event: React.MouseEvent, node: Node) => {
    const service = ARCH_SERVICES.find(s => s.id === node.id)
    if (service) {
      setSelectedService(prev => (prev?.id === service.id ? null : service))
    }
  }, [])

  const onPaneClick = useCallback(() => {
    setSelectedService(null)
  }, [])

  // =========================================================================
  // Stats
  // =========================================================================

  const stats = useMemo(() => {
    return {
      services: ARCH_SERVICES.length,
      dbTables: allDbTables.length,
      ragCollections: allRagCollections.length,
      edges: ARCH_EDGES.length,
    }
  }, [allDbTables, allRagCollections])

  // =========================================================================
  // Render
  // =========================================================================

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="bg-white rounded-xl border border-slate-200 p-5 shadow-sm">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 rounded-xl bg-slate-700 flex items-center justify-center text-white">
            <svg className="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01" />
            </svg>
          </div>
          <div>
            <h2 className="text-xl font-bold text-slate-900">
              Architektur-Uebersicht
            </h2>
            <p className="text-sm text-slate-500">
              {stats.services} Services | {stats.dbTables} DB-Tabellen | {stats.ragCollections} RAG-Collections | {stats.edges} Verbindungen
            </p>
          </div>
        </div>
      </div>

      {/* Toolbar */}
      <div className="bg-white rounded-xl border border-slate-200 p-4 shadow-sm">
        <div className="flex flex-wrap items-center gap-2">
          {/* Layer Filter */}
          <button
            onClick={() => {
              setLayerFilter('alle')
              setSelectedService(null)
            }}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
              layerFilter === 'alle'
                ? 'bg-slate-800 text-white'
                : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
            }`}
          >
            Alle ({ARCH_SERVICES.length})
          </button>
          {LAYER_ORDER.map(layerId => {
            const layer = LAYERS[layerId]
            const count = ARCH_SERVICES.filter(s => s.layer === layerId).length
            return (
              <button
                key={layerId}
                onClick={() => {
                  setLayerFilter(layerFilter === layerId ? 'alle' : layerId)
                  setSelectedService(null)
                }}
                className="px-3 py-1.5 rounded-lg text-sm font-medium transition-all flex items-center gap-1.5"
                style={{
                  background: layerFilter === layerId ? layer.colorBorder : layer.colorBg,
                  color: layerFilter === layerId ? 'white' : layer.colorText,
                }}
              >
                <span
                  className="w-2.5 h-2.5 rounded-full"
                  style={{ background: layer.colorBorder }}
                />
                {layer.name} ({count})
              </button>
            )
          })}

          {/* Separator */}
          <div className="w-px h-6 bg-slate-200 mx-1" />

          {/* Toggles */}
          <button
            onClick={() => setShowDb(!showDb)}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
              showDb
                ? 'bg-slate-700 text-white'
                : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
            }`}
          >
            DB-Tabellen
          </button>
          <button
            onClick={() => setShowRag(!showRag)}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
              showRag
                ? 'bg-green-600 text-white'
                : 'bg-green-50 text-green-700 hover:bg-green-100'
            }`}
          >
            RAG-Collections
          </button>
          <button
            onClick={() => setShowApis(!showApis)}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
              showApis
                ? 'bg-violet-600 text-white'
                : 'bg-violet-50 text-violet-700 hover:bg-violet-100'
            }`}
          >
            API-Endpunkte
          </button>
        </div>
      </div>

      {/* Flow Canvas + Detail Panel */}
      <div className="flex bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden" style={{ height: '700px' }}>
        {/* Canvas */}
        <div className="flex-1 relative">
          <ReactFlow
            nodes={nodes}
            edges={edges}
            onNodesChange={onNodesChange}
            onEdgesChange={onEdgesChange}
            onNodeClick={onNodeClick}
            onPaneClick={onPaneClick}
            fitView
            fitViewOptions={{ padding: 0.15 }}
            attributionPosition="bottom-left"
          >
            <Controls />
            <MiniMap
              nodeColor={node => {
                if (node.id.startsWith('db-')) return '#94a3b8'
                if (node.id.startsWith('rag-')) return '#22c55e'
                if (node.id.startsWith('api-')) return '#c4b5fd'
                const svc = ARCH_SERVICES.find(s => s.id === node.id)
                return svc ? LAYERS[svc.layer].colorBorder : '#94a3b8'
              }}
              maskColor="rgba(0,0,0,0.08)"
            />
            <Background variant={BackgroundVariant.Dots} gap={16} size={1} />

            {/* Legende */}
            <Panel
              position="bottom-right"
              className="bg-white/95 p-3 rounded-lg shadow-lg text-xs"
            >
              <div className="font-medium text-slate-700 mb-2">Legende</div>
              <div className="space-y-1">
                {LAYER_ORDER.map(layerId => {
                  const layer = LAYERS[layerId]
                  return (
                    <div key={layerId} className="flex items-center gap-2">
                      <span
                        className="w-3 h-3 rounded"
                        style={{
                          background: layer.colorBg,
                          border: `1px solid ${layer.colorBorder}`,
                        }}
                      />
                      <span className="text-slate-600">{layer.name}</span>
                    </div>
                  )
                })}
                <div className="border-t border-slate-200 my-1.5 pt-1.5">
                  <div className="flex items-center gap-2">
                    <span className="w-3 h-3 rounded bg-slate-200 border border-slate-400" />
                    <span className="text-slate-500">DB-Tabelle</span>
                  </div>
                  <div className="flex items-center gap-2 mt-0.5">
                    <span className="w-3 h-3 rounded bg-green-100 border border-green-500" />
                    <span className="text-slate-500">RAG-Collection</span>
                  </div>
                  <div className="flex items-center gap-2 mt-0.5">
                    <span className="w-3 h-3 rounded bg-violet-100 border border-violet-400" />
                    <span className="text-slate-500">API-Endpunkt</span>
                  </div>
                </div>
              </div>
            </Panel>

            {/* Swim-Lane Labels */}
            {layerFilter === 'alle' && (
              <Panel position="top-left" className="pointer-events-none">
                <div className="space-y-1">
                  {LAYER_ORDER.map(layerId => {
                    const layer = LAYERS[layerId]
                    return (
                      <div
                        key={layerId}
                        className="px-3 py-1 rounded text-xs font-medium opacity-50"
                        style={{
                          background: layer.colorBg,
                          color: layer.colorText,
                          border: `1px solid ${layer.colorBorder}`,
                        }}
                      >
                        {layer.name}
                      </div>
                    )
                  })}
                </div>
              </Panel>
            )}
          </ReactFlow>
        </div>

        {/* Detail Panel */}
        {selectedService && (
          <DetailPanel
            service={selectedService}
            onClose={() => setSelectedService(null)}
          />
        )}
      </div>

      {/* Service Table (aufklappbar) */}
      <div className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
        <div className="px-4 py-3 bg-slate-50 border-b">
          <h3 className="font-medium text-slate-700">
            Alle Services ({
              layerFilter === 'alle'
                ? ARCH_SERVICES.length
                : `${ARCH_SERVICES.filter(s => s.layer === layerFilter).length} / ${ARCH_SERVICES.length}`
            })
          </h3>
        </div>
        <div className="divide-y max-h-[600px] overflow-y-auto">
          {ARCH_SERVICES.filter(
            s => layerFilter === 'alle' || s.layer === layerFilter
          ).map(service => {
            const layer = LAYERS[service.layer]
            const isExpanded = expandedServices.has(service.id)

            return (
              <div key={service.id}>
                {/* Row Header */}
                <button
                  onClick={() => toggleExpanded(service.id)}
                  className={`w-full flex items-center gap-3 p-3 text-left transition-colors ${
                    isExpanded
                      ? 'bg-purple-50'
                      : 'hover:bg-slate-50'
                  }`}
                >
                  {/* Chevron */}
                  <svg
                    className={`w-4 h-4 text-slate-400 shrink-0 transition-transform duration-200 ${
                      isExpanded ? 'rotate-90' : ''
                    }`}
                    fill="none" stroke="currentColor" viewBox="0 0 24 24"
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                  <span
                    className="w-8 h-8 rounded-lg flex items-center justify-center text-[10px] font-bold shrink-0"
                    style={{ background: layer.colorBg, color: layer.colorText }}
                  >
                    {service.port ? `:${service.port}` : '--'}
                  </span>
                  <div className="flex-1 min-w-0">
                    <div className="font-medium text-slate-800 text-sm">
                      {service.name}
                    </div>
                    <div className="text-xs text-slate-500 flex items-center gap-2 mt-0.5">
                      <span className="text-slate-400">{service.tech}</span>
                      {service.dbTables.length > 0 && (
                        <span className="text-slate-400">
                          DB: {service.dbTables.length}
                        </span>
                      )}
                      {service.ragCollections.length > 0 && (
                        <span className="text-green-600">
                          RAG: {service.ragCollections.length}
                        </span>
                      )}
                      {service.apiEndpoints.length > 0 && (
                        <span className="text-violet-600">
                          API: {service.apiEndpoints.length}
                        </span>
                      )}
                    </div>
                  </div>
                  <code className="text-[10px] text-slate-400 shrink-0 hidden sm:block">
                    {service.container}
                  </code>
                  <span
                    className="px-2 py-0.5 rounded text-[10px] font-medium shrink-0"
                    style={{ background: layer.colorBg, color: layer.colorText }}
                  >
                    {layer.name}
                  </span>
                </button>

                {/* Expanded Detail */}
                {isExpanded && (
                  <div className="px-4 pb-4 pt-1 bg-slate-50/50 border-t border-slate-100">
                    {/* Beschreibung */}
                    <p className="text-sm text-slate-700 leading-relaxed mb-3">
                      {service.description}
                    </p>

                    {/* Info Grid */}
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-3">
                      <div className="bg-white rounded-lg border border-slate-200 p-2.5">
                        <div className="text-[10px] font-semibold text-slate-400 uppercase">Tech</div>
                        <div className="text-sm font-medium text-slate-800 mt-0.5">{service.tech}</div>
                      </div>
                      <div className="bg-white rounded-lg border border-slate-200 p-2.5">
                        <div className="text-[10px] font-semibold text-slate-400 uppercase">Port</div>
                        <div className="text-sm font-medium text-slate-800 mt-0.5">
                          {service.port ? `:${service.port}` : 'Intern'}
                        </div>
                      </div>
                      <div className="bg-white rounded-lg border border-slate-200 p-2.5">
                        <div className="text-[10px] font-semibold text-slate-400 uppercase">Container</div>
                        <div className="text-xs font-mono text-slate-700 mt-0.5 truncate">{service.container}</div>
                      </div>
                      {service.url && (
                        <div className="bg-white rounded-lg border border-slate-200 p-2.5">
                          <div className="text-[10px] font-semibold text-slate-400 uppercase">URL</div>
                          <a
                            href={service.url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-xs text-blue-600 hover:underline mt-0.5 block truncate"
                          >
                            {service.url}
                          </a>
                        </div>
                      )}
                    </div>

                    {/* Sections */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                      {/* DB Tables */}
                      {service.dbTables.length > 0 && (
                        <div className="bg-white rounded-lg border border-slate-200 p-3">
                          <h4 className="text-[10px] font-semibold text-slate-500 uppercase mb-2">
                            DB-Tabellen ({service.dbTables.length})
                          </h4>
                          <div className="space-y-1 max-h-40 overflow-y-auto">
                            {service.dbTables.map(table => (
                              <div key={table} className="bg-slate-50 rounded px-2 py-1">
                                <code className="text-xs text-slate-700">{table}</code>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* RAG Collections */}
                      {service.ragCollections.length > 0 && (
                        <div className="bg-white rounded-lg border border-slate-200 p-3">
                          <h4 className="text-[10px] font-semibold text-slate-500 uppercase mb-2">
                            RAG-Collections ({service.ragCollections.length})
                          </h4>
                          <div className="space-y-1">
                            {service.ragCollections.map(rag => (
                              <div key={rag} className="bg-green-50 rounded px-2 py-1">
                                <code className="text-xs text-green-700">{rag}</code>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* API Endpoints */}
                      {service.apiEndpoints.length > 0 && (
                        <div className="bg-white rounded-lg border border-slate-200 p-3">
                          <h4 className="text-[10px] font-semibold text-slate-500 uppercase mb-2">
                            API-Endpunkte ({service.apiEndpoints.length})
                          </h4>
                          <div className="space-y-1 max-h-40 overflow-y-auto">
                            {service.apiEndpoints.map(ep => (
                              <div key={ep} className="bg-violet-50 rounded px-2 py-1">
                                <code className="text-xs text-violet-700">{ep}</code>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* Dependencies */}
                      {service.dependsOn.length > 0 && (
                        <div className="bg-white rounded-lg border border-slate-200 p-3">
                          <h4 className="text-[10px] font-semibold text-slate-500 uppercase mb-2">
                            Abhaengigkeiten ({service.dependsOn.length})
                          </h4>
                          <div className="space-y-1">
                            {service.dependsOn.map(depId => {
                              const dep = ARCH_SERVICES.find(s => s.id === depId)
                              const depLayer = dep ? LAYERS[dep.layer] : null
                              return (
                                <div key={depId} className="flex items-center gap-2 bg-slate-50 rounded px-2 py-1">
                                  {depLayer && (
                                    <span
                                      className="w-2 h-2 rounded-full shrink-0"
                                      style={{ background: depLayer.colorBorder }}
                                    />
                                  )}
                                  <span className="text-xs text-slate-700">{dep?.name || depId}</span>
                                </div>
                              )
                            })}
                          </div>
                        </div>
                      )}
                    </div>

                    {/* Open in Graph + URL */}
                    <div className="flex items-center gap-2 mt-3">
                      <button
                        onClick={() => {
                          setSelectedService(service)
                          window.scrollTo({ top: 0, behavior: 'smooth' })
                        }}
                        className="px-3 py-1.5 bg-slate-100 text-slate-700 rounded-lg text-xs font-medium hover:bg-slate-200 transition-colors"
                      >
                        Im Graph markieren
                      </button>
                      {service.url && (
                        <a
                          href={service.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="px-3 py-1.5 bg-purple-600 text-white rounded-lg text-xs font-medium hover:bg-purple-700 transition-colors"
                        >
                          Service oeffnen
                        </a>
                      )}
                    </div>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
}
