'use client'

import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Language } from '@/lib/types'
import { t } from '@/lib/i18n'
import GradientText from '../ui/GradientText'
import FadeInView from '../ui/FadeInView'
import {
  Brain, Shield, ScanLine, Zap, Cpu,
  Layers, Wrench, X, Users, Lock,
  Server, Network, ChevronRight, BadgeCheck,
} from 'lucide-react'

interface ArchitectureSlideProps {
  lang: Language
}

type NodeId = 'certifai' | 'complai' | 'scanner' | 'litellm' | 'llm' | 'embeddings' | 'tools'
type ConnType = 'api' | 'mcp' | 'embed' | 'tool'

interface NodeDef {
  id: NodeId
  icon: React.ElementType
  title: string
  subtitle: string
  color: string
  twColor: string
  twBorder: string
  twBg: string
  twDot: string
  cx: number
  cy: number
  tier: 'product' | 'proxy' | 'inference'
  tech: string[]
  services: { name: string; desc: string }[]
  badge?: string
}

interface ConnDef {
  from: NodeId
  to: NodeId
  type: ConnType
  d: string
  revD?: string  // reverse path for bidirectional MCP
}

const CONNS: ConnDef[] = [
  { from: 'certifai', to: 'litellm', type: 'api',   d: 'M 18 22 Q 28 43 50 52' },
  { from: 'complai',  to: 'litellm', type: 'api',   d: 'M 50 22 L 50 52' },
  { from: 'scanner',  to: 'litellm', type: 'api',   d: 'M 82 22 Q 72 43 50 52' },
  { from: 'complai',  to: 'scanner', type: 'mcp',   d: 'M 50 22 Q 66 9 82 22', revD: 'M 82 22 Q 66 9 50 22' },
  { from: 'litellm',  to: 'llm',        type: 'api',   d: 'M 50 52 Q 37 67 18 82' },
  { from: 'litellm',  to: 'embeddings', type: 'embed', d: 'M 50 52 L 50 82' },
  { from: 'litellm',  to: 'tools',      type: 'tool',  d: 'M 50 52 Q 63 67 82 82' },
]

function getNodes(de: boolean): NodeDef[] {
  return [
    {
      id: 'certifai',
      icon: Brain,
      title: 'CERTifAI',
      subtitle: de ? 'GenAI Mandantenportal' : 'GenAI Tenant Portal',
      color: '#c084fc', twColor: 'text-purple-400',
      twBorder: 'border-purple-500/50', twBg: 'bg-purple-500/10', twDot: 'bg-purple-400',
      cx: 18, cy: 22, tier: 'product',
      badge: 'Rust · Dioxus',
      tech: ['Rust', 'Dioxus', 'MongoDB', 'Keycloak', 'SearXNG', 'LangGraph'],
      services: [
        { name: 'LiteLLM Dashboard', desc: de ? 'Modellverwaltung & Kostentracking' : 'Model mgmt & cost tracking' },
        { name: 'LibreChat + SSO', desc: de ? 'Mandanten-Chat mit Keycloak' : 'Tenant chat with Keycloak' },
        { name: 'LangGraph Agents', desc: de ? 'Agent-Orchestrierung' : 'Agent orchestration' },
        { name: 'MCP Hub', desc: de ? 'Tool-Integration für KI-Clients' : 'Tool integration for AI clients' },
      ],
    },
    {
      id: 'complai',
      icon: Shield,
      title: 'COMPLAI',
      subtitle: de ? 'Compliance & Audit' : 'Compliance & Audit',
      color: '#818cf8', twColor: 'text-indigo-400',
      twBorder: 'border-indigo-500/50', twBg: 'bg-indigo-500/10', twDot: 'bg-indigo-400',
      cx: 50, cy: 22, tier: 'product',
      badge: 'Next.js · FastAPI',
      tech: ['Next.js 15', 'FastAPI', 'Go/Gin', 'PostgreSQL', 'Qdrant', 'Valkey'],
      services: [
        { name: de ? 'DSGVO / AI Act / NIS2' : 'GDPR / AI Act / NIS2', desc: de ? '70k+ auditierbare Controls' : '70k+ auditable controls' },
        { name: 'RAG Pipeline', desc: de ? '75+ Rechtsquellen, semantische Suche' : '75+ legal sources, semantic search' },
        { name: 'Control Pipeline', desc: de ? 'Gesetzestextanalyse via LLM' : 'Legal text analysis via LLM' },
        { name: 'MCP Client', desc: de ? 'Echtzeit-Findings vom Scanner' : 'Real-time findings from Scanner' },
      ],
    },
    {
      id: 'scanner',
      icon: ScanLine,
      title: 'Compliance Scanner',
      subtitle: de ? 'Code-Sicherheit' : 'Code Security',
      color: '#34d399', twColor: 'text-emerald-400',
      twBorder: 'border-emerald-500/50', twBg: 'bg-emerald-500/10', twDot: 'bg-emerald-400',
      cx: 82, cy: 22, tier: 'product',
      badge: 'Rust · Axum',
      tech: ['Rust', 'Axum', 'MongoDB', 'Semgrep', 'Gitleaks', 'Syft'],
      services: [
        { name: 'SAST / SBOM / CVE', desc: de ? 'Vollautomatische Pipeline' : 'Fully automated pipeline' },
        { name: de ? 'KI-Triage' : 'AI Triage', desc: de ? 'LLM filtert False Positives' : 'LLM filters false positives' },
        { name: de ? 'KI-Pentest' : 'AI Pentest', desc: de ? 'Autonome Angriffsketten' : 'Autonomous attack chains' },
        { name: 'MCP Server', desc: de ? 'Live-Findings für COMPLAI' : 'Live findings for COMPLAI' },
      ],
    },
    {
      id: 'litellm',
      icon: Zap,
      title: 'LiteLLM Proxy',
      subtitle: de ? 'KI-Gateway & Guardrails' : 'AI Gateway & Guardrails',
      color: '#fbbf24', twColor: 'text-amber-400',
      twBorder: 'border-amber-500/60', twBg: 'bg-amber-500/10', twDot: 'bg-amber-400',
      cx: 50, cy: 52, tier: 'proxy',
      badge: 'Hub',
      tech: ['OpenAI-kompatible API', 'Bearer Auth', 'Rate Limiting', 'PII-Filter', 'Spend Tracking'],
      services: [
        { name: de ? 'Token-Budget' : 'Token Budget', desc: de ? 'Pro-Mandant Kontingente & Abrechnung' : 'Per-tenant quotas & billing' },
        { name: 'PII Guardrails', desc: de ? 'Datenschutz-Filter für alle Anfragen' : 'Privacy filter on all requests' },
        { name: de ? 'Web-Suche (anonym)' : 'Web Search (anon)', desc: de ? 'SearXNG-Proxy, kein US-Anbieter' : 'SearXNG proxy, no US providers' },
        { name: de ? 'Namespace-Isolierung' : 'Namespace Isolation', desc: de ? 'Mandantentrennung per API-Key' : 'Tenant isolation per API key' },
        { name: de ? 'Failover-Routing' : 'Failover Routing', desc: de ? 'Automatisches Fallback' : 'Automatic fallback between models' },
      ],
    },
    {
      id: 'llm',
      icon: Cpu,
      title: de ? 'LLM Inferenz' : 'LLM Inference',
      subtitle: de ? 'Lokale Sprachmodelle' : 'Local Language Models',
      color: '#60a5fa', twColor: 'text-blue-400',
      twBorder: 'border-blue-500/50', twBg: 'bg-blue-500/10', twDot: 'bg-blue-400',
      cx: 18, cy: 82, tier: 'inference',
      badge: de ? 'On-Premise · BSI' : 'On-Premise · BSI',
      tech: ['Qwen3-32B', 'Qwen3-Coder-30B', 'DeepSeek-R1-8B', 'Ollama'],
      services: [
        { name: de ? 'Vollständig lokal' : 'Fully local', desc: de ? 'Daten verlassen nie den Server' : 'Data never leaves the server' },
        { name: de ? 'Air-Gap fähig' : 'Air-Gap Capable', desc: de ? 'Kein Internet erforderlich' : 'No internet required' },
        { name: de ? 'GPU-optimiert' : 'GPU-optimized', desc: de ? 'Dedizierte Inferenz-Hardware' : 'Dedicated inference hardware' },
      ],
    },
    {
      id: 'embeddings',
      icon: Layers,
      title: 'Embeddings',
      subtitle: de ? 'Semantische Suche' : 'Semantic Search',
      color: '#a78bfa', twColor: 'text-violet-400',
      twBorder: 'border-violet-500/50', twBg: 'bg-violet-500/10', twDot: 'bg-violet-400',
      cx: 50, cy: 82, tier: 'inference',
      badge: de ? 'EU-Souverän' : 'EU Sovereign',
      tech: ['bge-m3', 'Qdrant Vector DB', 'Sentence-Transformers'],
      services: [
        { name: 'RAG Pipeline', desc: de ? '75+ Rechtsquellen indexiert' : '75+ legal sources indexed' },
        { name: de ? 'Semantische Suche' : 'Semantic Search', desc: de ? 'Multi-linguale Einbettungen' : 'Multi-lingual embeddings' },
        { name: de ? 'Lokal' : 'Fully local', desc: de ? 'Keine externen APIs' : 'No external APIs' },
      ],
    },
    {
      id: 'tools',
      icon: Wrench,
      title: de ? 'KI-Tools' : 'AI Tools',
      subtitle: de ? 'Web-Suche & MCP' : 'Web Search & MCP',
      color: '#2dd4bf', twColor: 'text-teal-400',
      twBorder: 'border-teal-500/50', twBg: 'bg-teal-500/10', twDot: 'bg-teal-400',
      cx: 82, cy: 82, tier: 'inference',
      badge: de ? 'EU-Souverän' : 'EU Sovereign',
      tech: ['SearXNG', 'MCP Protocol', 'Semgrep API', 'Gitleaks API'],
      services: [
        { name: 'SearXNG', desc: de ? 'Anonymisierte EU-Websuche' : 'Anonymized EU web search' },
        { name: 'MCP Tools', desc: de ? 'Auditdokumente & Code-Findings' : 'Audit docs & code findings' },
        { name: de ? 'Kein US-Anbieter' : 'No US providers', desc: de ? '100% DSGVO-konform' : '100% GDPR-compliant' },
      ],
    },
  ]
}

// ── Token counter (inference tier ambient animation) ─────────────────────────
function TokenTicker({ color }: { color: string }) {
  const [n, setN] = useState(() => 12480 + Math.floor(Math.random() * 8000))
  useEffect(() => {
    const id = setInterval(() => setN(v => v + Math.floor(Math.random() * 180 + 40)), 220)
    return () => clearInterval(id)
  }, [])
  return (
    <div className="flex items-center gap-1">
      <motion.div
        className="w-1 h-1 rounded-full"
        style={{ background: color }}
        animate={{ opacity: [1, 0.3, 1] }}
        transition={{ duration: 0.6, repeat: Infinity }}
      />
      <span className="text-[7px] font-mono tabular-nums" style={{ color, opacity: 0.65 }}>
        {n.toLocaleString('de-DE')} tok/s
      </span>
    </div>
  )
}

// ── Data-flow path (always-on packets, fast when active) ─────────────────────
function DataFlow({
  d, revD, color, active, type,
}: {
  d: string; revD?: string; color: string; active: boolean; type: ConnType
}) {
  const isMcp = type === 'mcp'
  const speed  = active ? 1.2 : 5
  const op     = active ? 0.85 : 0.2
  const w      = active ? 2.5 : 1.2
  const dash   = active ? 3   : 2

  return (
    <g>
      {/* Base line */}
      <path
        d={d} fill="none"
        stroke={color}
        strokeWidth={active ? 1 : 0.5}
        strokeOpacity={active ? 0.4 : 0.07}
        strokeDasharray={isMcp ? '3 6' : undefined}
        vectorEffect="non-scaling-stroke"
      />

      {/* Forward packets */}
      {[0, -28, -56].map((off, i) => (
        <motion.path key={`f${i}`}
          d={d} fill="none"
          stroke={color} strokeWidth={w} strokeLinecap="round"
          strokeDasharray={`${dash} 80`}
          strokeOpacity={op - i * 0.07}
          vectorEffect="non-scaling-stroke"
          initial={{ strokeDashoffset: off }}
          animate={{ strokeDashoffset: off - 83 }}
          transition={{ duration: speed, repeat: Infinity, ease: 'linear' }}
        />
      ))}

      {/* Reverse packets for MCP (bidirectional) */}
      {isMcp && revD && [0, -42].map((off, i) => (
        <motion.path key={`r${i}`}
          d={revD} fill="none"
          stroke={color} strokeWidth={w * 0.75} strokeLinecap="round"
          strokeDasharray={`${dash} 80`}
          strokeOpacity={(op - i * 0.1) * 0.75}
          vectorEffect="non-scaling-stroke"
          initial={{ strokeDashoffset: off }}
          animate={{ strokeDashoffset: off - 83 }}
          transition={{ duration: speed * 1.4, repeat: Infinity, ease: 'linear' }}
        />
      ))}
    </g>
  )
}

// ── Node card ──────────────────────────────────────────────────────────────────
// Position wrapper (div) is never scaled — only the inner motion.button scales.
// This prevents the "snap" that happened when translate(-50%,-50%) and scale
// were on the same element.
function NodeCard({
  node, active, onClick, de,
}: {
  node: NodeDef; active: boolean; onClick: () => void; de: boolean
}) {
  const Icon = node.icon
  const isHub = node.id === 'litellm'

  return (
    <div
      className="absolute"
      style={{ left: `${node.cx}%`, top: `${node.cy}%`, transform: 'translate(-50%, -50%)' }}
    >
      <motion.button
        onClick={onClick}
        whileHover={{ scale: 1.06 }}
        whileTap={{ scale: 0.95 }}
        transition={{ type: 'spring', stiffness: 400, damping: 25 }}
        className="focus:outline-none block"
      >
        <div
          className={`relative rounded-xl border text-left transition-colors duration-200 overflow-hidden ${
            isHub ? 'w-[148px] px-3 py-3' : 'w-[128px] px-2.5 py-2.5'
          } ${
            active
              ? `${node.twBorder} ${node.twBg}`
              : 'border-white/[0.09] bg-white/[0.04] hover:border-white/20'
          }`}
          style={{ boxShadow: active ? `0 0 22px -6px ${node.color}55` : 'none' }}
        >
          {/* Left accent bar */}
          <div
            className="absolute left-0 top-0 bottom-0 w-[2px] rounded-l-xl transition-all duration-300"
            style={{ background: active ? node.color : `${node.color}28` }}
          />

          {/* Icon + title */}
          <div className="flex items-center gap-2 pl-1 mb-1">
            <div
              className={`w-[22px] h-[22px] rounded-md flex items-center justify-center flex-shrink-0 border transition-colors duration-200 ${
                active ? `${node.twBorder} ${node.twBg}` : 'border-white/10 bg-white/[0.05]'
              }`}
            >
              <Icon className={`w-3 h-3 ${active ? node.twColor : 'text-white/35'}`} />
            </div>
            <span className={`text-[10px] font-semibold leading-tight truncate ${active ? 'text-white' : 'text-white/55'}`}>
              {node.title}
            </span>
            {active && (
              <div className={`w-1.5 h-1.5 rounded-full flex-shrink-0 animate-pulse ${node.twDot}`} />
            )}
          </div>

          {/* Subtitle */}
          <p className={`text-[8px] leading-snug pl-1 mb-1 ${active ? node.twColor : 'text-white/28'}`}
             style={{ opacity: active ? 0.8 : 1 }}>
            {node.subtitle}
          </p>

          {/* Badge */}
          {node.badge && (
            <div className="pl-1">
              <span className={`text-[7px] px-1.5 py-[1px] rounded border transition-colors duration-200 ${
                active ? `${node.twBorder} ${node.twColor}` : 'border-white/[0.08] text-white/22'
              }`}>
                {node.badge}
              </span>
            </div>
          )}

          {/* Token ticker on inference nodes */}
          {active && node.tier === 'inference' && (
            <div className="pl-1 mt-1.5">
              <TokenTicker color={node.color} />
            </div>
          )}

          {/* Hub: spinning indicator ring */}
          {isHub && active && (
            <motion.div
              className="absolute rounded-full pointer-events-none"
              style={{ inset: -5, border: `1px dashed ${node.color}45`, borderRadius: '12px' }}
              animate={{ rotate: 360 }}
              transition={{ duration: 12, repeat: Infinity, ease: 'linear' }}
            />
          )}
        </div>
      </motion.button>
    </div>
  )
}

// ── Main slide ─────────────────────────────────────────────────────────────────
export default function ArchitectureSlide({ lang }: ArchitectureSlideProps) {
  const i      = t(lang)
  const de     = lang === 'de'
  const nodes  = getNodes(de)

  const [activeId, setActiveId] = useState<NodeId | null>(null)
  const active = nodes.find(n => n.id === activeId) ?? null

  function toggle(id: NodeId) {
    setActiveId(prev => (prev === id ? null : id))
  }

  const tenants = de
    ? ['Mandant A', 'Mandant B', 'Mandant C', 'Mandant N…']
    : ['Namespace A', 'Namespace B', 'Namespace C', 'Namespace N…']

  const tiers = [
    { y: '22%', label: de ? 'Anwendungsschicht' : 'Application Layer',  clr: '#818cf8', badge: null },
    { y: '52%', label: de ? 'GenAI-Infrastruktur' : 'GenAI Infrastructure', clr: '#fbbf24', badge: de ? 'BSI-Rechenzentrum' : 'BSI Data Center' },
    { y: '82%', label: de ? 'Inferenzschicht' : 'Inference Layer', clr: '#60a5fa', badge: de ? 'BSI · EU-Souverän' : 'BSI · EU Sovereign' },
  ]

  return (
    <div className="space-y-3">
      {/* Header */}
      <FadeInView className="text-center mb-3">
        <p className="text-[10px] font-mono text-indigo-400/50 uppercase tracking-widest mb-1.5">
          {de ? 'Anhang' : 'Appendix'}
        </p>
        <h2 className="text-3xl md:text-4xl font-bold mb-1.5">
          <GradientText>{i.annex.architecture.title}</GradientText>
        </h2>
        <p className="text-xs text-white/35">
          {de ? 'Klicke auf eine Komponente für Details' : 'Click any component to explore'}
        </p>
      </FadeInView>

      <FadeInView delay={0.15} className="space-y-3">
        {/* Customer namespace strip */}
        <div className="flex items-center gap-2 flex-wrap px-[4%]">
          <Users className="w-3 h-3 text-white/25 flex-shrink-0" />
          <span className="text-[9px] font-mono text-white/25 uppercase tracking-widest mr-1">
            {de ? 'Kundenmandanten' : 'Customer Namespaces'}
          </span>
          {tenants.map(tn => (
            <span key={tn}
              className="text-[9px] px-2 py-0.5 rounded-full border border-white/[0.08] bg-white/[0.03] text-white/35 font-mono">
              {tn}
            </span>
          ))}
          <div className="flex-1 h-px bg-gradient-to-r from-white/10 to-transparent ml-1" />
        </div>

        {/* ── MAP ──────────────────────────────────────────────────────────── */}
        <div className="relative w-full" style={{ height: '410px' }}>

          {/* Background */}
          <div className="absolute inset-0 rounded-xl overflow-hidden"
            style={{
              background: `
                radial-gradient(ellipse 50% 30% at 50% 52%, rgba(251,191,36,0.06) 0%, transparent 65%),
                radial-gradient(ellipse 60% 22% at 50% 22%, rgba(129,140,248,0.07) 0%, transparent 55%),
                radial-gradient(ellipse 60% 20% at 50% 82%, rgba(96,165,250,0.045) 0%, transparent 55%),
                linear-gradient(170deg, #030d1e 0%, #040f21 50%, #030c1b 100%)
              `,
            }}
          >
            <div className="absolute inset-0 opacity-[0.04]"
              style={{
                backgroundImage: 'radial-gradient(circle, #6b7280 1px, transparent 1px)',
                backgroundSize: '22px 22px',
              }}
            />
          </div>

          {/* Tier separator lines */}
          {['37%', '66%'].map(y => (
            <div key={y} className="absolute left-0 right-0 h-px pointer-events-none"
              style={{ top: y, background: 'linear-gradient(to right, transparent 0%, rgba(255,255,255,0.055) 15%, rgba(255,255,255,0.055) 85%, transparent 100%)' }}
            />
          ))}

          {/* Tier labels (left) + BSI badges (right) */}
          {tiers.map(({ y, label, clr, badge }) => (
            <div key={label} className="absolute inset-x-0 flex items-center justify-between px-3 pointer-events-none select-none"
              style={{ top: y, transform: 'translateY(-50%)' }}>
              <div className="flex items-center gap-1.5">
                <div className="w-2.5 h-px" style={{ background: clr, opacity: 0.3 }} />
                <span className="text-[7.5px] font-mono tracking-[0.14em] uppercase" style={{ color: clr, opacity: 0.42 }}>
                  {label}
                </span>
              </div>
              {badge && (
                <div className="flex items-center gap-1" style={{ opacity: 0.45 }}>
                  <BadgeCheck className="w-2.5 h-2.5" style={{ color: clr }} />
                  <span className="text-[7px] font-mono tracking-wider" style={{ color: clr }}>
                    {badge}
                  </span>
                </div>
              )}
            </div>
          ))}

          {/* MCP badge between COMPLAI and Scanner */}
          <div
            className="absolute text-[7px] px-2 py-[2px] rounded-full border border-emerald-500/35 text-emerald-400/65 font-mono tracking-wider select-none pointer-events-none"
            style={{ left: '66%', top: '9%', transform: 'translate(-50%, -50%)' }}
          >
            MCP ↔
          </div>

          {/* Infra tech chips (secondary, very subtle, in the infra tier band) */}
          <div className="absolute left-[5%] right-[5%] flex flex-wrap gap-1.5 pointer-events-none select-none"
            style={{ top: '51.5%', transform: 'translateY(-50%)', paddingRight: '160px' }}>
            {['PostgreSQL', 'MongoDB', 'Qdrant', 'Valkey', 'Nginx', 'Vault', 'Gitea', 'Orca', 'Woodpecker'].map(chip => (
              <span key={chip}
                className="text-[6.5px] px-1.5 py-[1px] rounded border border-white/[0.055] text-white/14 font-mono">
                {chip}
              </span>
            ))}
          </div>

          {/* SVG: island territories + data-flow paths */}
          <svg className="absolute inset-0 w-full h-full pointer-events-none"
            viewBox="0 0 100 100"
            preserveAspectRatio="none">

            {/* Tier zone fills */}
            <rect x="0" y="0"  width="100" height="37"  fill="#818cf8" fillOpacity="0.018" />
            <rect x="0" y="37" width="100" height="29"  fill="#fbbf24" fillOpacity="0.022" />
            <rect x="0" y="66" width="100" height="34"  fill="#60a5fa"  fillOpacity="0.015" />

            {/* Island blobs per node */}
            {nodes.map(n => {
              const isHub = n.id === 'litellm'
              const isActive = activeId === n.id
              return (
                <g key={`blob-${n.id}`}>
                  <ellipse cx={n.cx} cy={n.cy}
                    rx={isHub ? 14 : 8} ry={isHub ? 8.5 : 5}
                    fill={n.color} fillOpacity={isActive ? 0.13 : 0.038}
                    stroke={n.color} strokeWidth={0.5}
                    strokeOpacity={isActive ? 0.35 : 0.09}
                    strokeDasharray={isHub ? undefined : '1.5 3.5'}
                    vectorEffect="non-scaling-stroke"
                  />
                </g>
              )
            })}

            {/* Connection flows */}
            {CONNS.map(c => {
              const fromNode  = nodes.find(n => n.id === c.from)!
              const toNode    = nodes.find(n => n.id === c.to)!
              const isActive  = activeId === c.from || activeId === c.to
              const color     = isActive
                ? (activeId === c.from ? fromNode.color : toNode.color)
                : '#ffffff'
              return (
                <DataFlow
                  key={`${c.from}-${c.to}`}
                  d={c.d} revD={c.revD}
                  color={color} active={isActive} type={c.type}
                />
              )
            })}
          </svg>

          {/* Node cards */}
          {nodes.map(node => (
            <NodeCard
              key={node.id}
              node={node}
              active={activeId === node.id}
              onClick={() => toggle(node.id)}
              de={de}
            />
          ))}

          {!activeId && (
            <div className="absolute bottom-3 right-3 flex items-center gap-1 text-[8px] text-white/18 pointer-events-none">
              <ChevronRight className="w-3 h-3" />
              {de ? 'Komponente anklicken' : 'Click any node'}
            </div>
          )}
        </div>

        {/* ── DETAIL PANEL ──────────────────────────────────────────────────── */}
        <AnimatePresence>
          {active && (
            <motion.div
              initial={{ opacity: 0, y: 12 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: 8 }}
              transition={{ duration: 0.22, ease: [0.22, 1, 0.36, 1] }}
              className={`relative rounded-2xl border ${active.twBorder} ${active.twBg} p-4`}
              style={{ boxShadow: `0 0 32px -10px ${active.color}45` }}
            >
              <button
                onClick={() => setActiveId(null)}
                className="absolute top-3 right-3 w-6 h-6 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors"
              >
                <X className="w-3 h-3 text-white/50" />
              </button>

              {/* Header */}
              <div className="flex items-start gap-3 mb-4">
                <div className={`w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 border ${active.twBorder} ${active.twBg}`}>
                  <active.icon className={`w-5 h-5 ${active.twColor}`} />
                </div>
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2 flex-wrap">
                    <h3 className="text-sm font-bold text-white">{active.title}</h3>
                    {active.badge && (
                      <span className={`text-[9px] px-1.5 py-0.5 rounded uppercase font-semibold tracking-wider border ${active.twBorder} ${active.twColor}`}>
                        {active.badge}
                      </span>
                    )}
                    <span className={`text-[8px] px-1.5 py-0.5 rounded border border-white/10 text-white/35`}>
                      {active.tier === 'product' ? (de ? 'Anwendungsschicht' : 'Application Layer') :
                       active.tier === 'proxy'   ? (de ? 'GenAI-Infrastruktur' : 'GenAI Infra') :
                       (de ? 'Inferenzschicht' : 'Inference Layer')}
                    </span>
                  </div>
                  <p className="text-xs text-white/45 mt-0.5">{active.subtitle}</p>
                </div>
              </div>

              {/* Body */}
              <div className="grid grid-cols-2 gap-5">
                <div>
                  <p className="text-[9px] uppercase tracking-widest text-white/30 mb-2 font-semibold">
                    {de ? 'Stack' : 'Tech Stack'}
                  </p>
                  <div className="flex flex-wrap gap-1.5">
                    {active.tech.map(tk => (
                      <span key={tk} className="text-[10px] px-2 py-0.5 rounded bg-white/[0.05] border border-white/[0.08] text-white/55 font-mono">
                        {tk}
                      </span>
                    ))}
                  </div>
                </div>
                <div>
                  <p className="text-[9px] uppercase tracking-widest text-white/30 mb-2 font-semibold">
                    {de ? 'Funktionen' : 'Capabilities'}
                  </p>
                  <div className="space-y-1.5">
                    {active.services.map(s => (
                      <div key={s.name} className="flex items-start gap-2">
                        <div className={`w-1 h-1 rounded-full mt-1.5 flex-shrink-0 ${active.twDot} opacity-70`} />
                        <div className="min-w-0">
                          <span className="text-xs font-semibold text-white/80">{s.name}</span>
                          <span className="text-[10px] text-white/40 ml-1.5">{s.desc}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              {/* Connects-to */}
              <div className="mt-3 pt-3 border-t border-white/[0.06] flex items-center gap-2 flex-wrap">
                <Network className="w-3 h-3 text-white/20 flex-shrink-0" />
                <span className="text-[9px] text-white/30">
                  {de ? 'Verbunden mit:' : 'Connects to:'}
                </span>
                {CONNS
                  .filter(c => c.from === active.id || c.to === active.id)
                  .map(c => {
                    const peerId = c.from === active.id ? c.to : c.from
                    const peer   = nodes.find(n => n.id === peerId)!
                    const label  = c.type === 'mcp' ? 'MCP' : c.type === 'embed' ? 'Embed' : c.type === 'tool' ? 'Tool' : 'API'
                    return (
                      <button
                        key={peerId}
                        onClick={() => setActiveId(peerId)}
                        className={`text-[9px] px-2 py-0.5 rounded-full border ${peer.twBorder} ${peer.twColor} transition-opacity hover:opacity-80 flex items-center gap-1`}
                      >
                        {peer.title}
                        <span className="opacity-50 text-[7px]">{label}</span>
                      </button>
                    )
                  })}
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Bottom legend */}
        {!active && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
            className="flex items-center justify-center gap-6 flex-wrap">
            {[
              { icon: Lock,   text: de ? 'Kein US-Anbieter · 100% DSGVO' : 'No US providers · 100% GDPR' },
              { icon: Server, text: de ? 'BSI-zertifiziertes Rechenzentrum' : 'BSI-certified data center' },
              { icon: BadgeCheck, text: de ? 'EU-souveräne Inferenz' : 'EU-sovereign inference' },
            ].map(({ icon: Icon, text }) => (
              <span key={text} className="flex items-center gap-1.5 text-[10px] text-white/22">
                <Icon className="w-3 h-3" />
                {text}
              </span>
            ))}
          </motion.div>
        )}
      </FadeInView>
    </div>
  )
}
