'use client'

import { useState, useEffect } from 'react'
import { Language } from '@/lib/types'
import { t } from '@/lib/i18n'
import GradientText from '../ui/GradientText'
import FadeInView from '../ui/FadeInView'
import GlassCard from '../ui/GlassCard'
import {
  Brain,
  Search,
  Database,
  FileText,
  Bot,
  Zap,
  Layers,
  ArrowRight,
  Activity,
  Shield,
  Cpu,
  Eye,
  Gauge,
  Network,
  Sparkles,
  Scale,
  BookOpen,
  Gavel,
  Globe,
} from 'lucide-react'

interface AIPipelineSlideProps {
  lang: Language
}

type PipelineTab = 'rag' | 'agents' | 'quality'

type PipelineStat = { value: number; label_de: string; label_en: string }

export default function AIPipelineSlide({ lang }: AIPipelineSlideProps) {
  const i = t(lang)
  const de = lang === 'de'
  const [activeTab, setActiveTab] = useState<PipelineTab>('rag')
  const [stats, setStats] = useState<Record<string, PipelineStat>>({})

  useEffect(() => {
    fetch('/api/pipeline-stats', { cache: 'no-store' })
      .then(r => r.json())
      .then(setStats)
      .catch(() => {})
  }, [])

  const s = (key: string) => stats[key]?.value || 0
  const fmtK = (v: number) => v >= 1000 ? `${Math.round(v / 1000)}k+` : `${v}+`

  const heroStats = [
    { value: fmtK(s('legal_sources')), label: de ? 'Rechtsquellen' : 'Legal Sources', sub: de ? 'EU-Verordnungen · DACH-Gesetze · Frameworks' : 'EU regulations · DACH laws · Frameworks', color: 'text-indigo-400' },
    { value: fmtK(s('unique_controls')), label: de ? 'Unique Controls' : 'Unique Controls', sub: de ? 'Prüfbare Compliance-Anforderungen' : 'Auditable compliance requirements', color: 'text-purple-400' },
    { value: fmtK(s('extracted_obligations')), label: de ? 'Extrahierte Pflichten' : 'Extracted Obligations', sub: de ? 'Aus Gesetzestexten abgeleitet' : 'Derived from legal texts', color: 'text-emerald-400' },
    { value: String(s('pipeline_versions') || 6), label: de ? 'Pipeline-Versionen' : 'Pipeline Versions', sub: de ? 'Kontinuierliche Verbesserung' : 'Continuous improvement', color: 'text-amber-400' },
  ]

  const tabs: { id: PipelineTab; label: string; icon: typeof Brain }[] = [
    { id: 'rag', label: de ? 'RAG-Pipeline' : 'RAG Pipeline', icon: Search },
    { id: 'agents', label: de ? 'UCCA & Engines' : 'UCCA & Engines', icon: Bot },
    { id: 'quality', label: de ? 'QA & Infrastruktur' : 'QA & Infrastructure', icon: Gauge },
  ]

  // Source categories for investors
  const sourceCategories = [
    {
      icon: Globe,
      color: 'text-blue-400',
      bg: 'bg-blue-500/10 border-blue-500/20',
      title: de ? `EU-Verordnungen (~${s('eu_regulations') || 45})` : `EU Regulations (~${s('eu_regulations') || 45})`,
      why: de
        ? 'Bindende Vorgaben für alle EU-Unternehmen — Verstöße führen zu Bußgeldern bis 4% des Jahresumsatzes.'
        : 'Binding requirements for all EU companies — violations lead to fines up to 4% of annual revenue.',
      examples: 'DSGVO · AI Act · NIS2 · CRA · MiCA · DSA · Maschinenverordnung · Batterieverordnung',
    },
    {
      icon: Scale,
      color: 'text-purple-400',
      bg: 'bg-purple-500/10 border-purple-500/20',
      title: de ? `DACH-Gesetze (~${s('dach_laws') || 85})` : `DACH Laws (~${s('dach_laws') || 85})`,
      why: de
        ? 'Nationale Umsetzungen und eigenständige Gesetze — oft strenger als EU-Mindeststandards.'
        : 'National implementations and standalone laws — often stricter than EU minimum standards.',
      examples: 'BDSG · TKG · GwG · HGB · BGB · UrhG · GewO · KRITIS-DachG · AT ABGB · AT KSchG',
    },
    {
      icon: BookOpen,
      color: 'text-emerald-400',
      bg: 'bg-emerald-500/10 border-emerald-500/20',
      title: de ? 'Frameworks & Standards (~15)' : 'Frameworks & Standards (~15)',
      why: de
        ? 'Branchenstandards definieren den Stand der Technik — Aufsichtsbehoerden erwarten deren Einhaltung.'
        : 'Industry standards define state of the art — regulators expect compliance with them.',
      examples: 'NIST 800-53 · OWASP ASVS · OWASP SAMM · ENISA ICS · NIST Zero Trust · CISA Secure by Design',
    },
    {
      icon: Gavel,
      color: 'text-amber-400',
      bg: 'bg-amber-500/10 border-amber-500/20',
      title: de ? 'DSFA-Leitlinien & Urteile' : 'DPIA Guidelines & Rulings',
      why: de
        ? 'Urteile zeigen wie Gerichte Gesetze auslegen — entscheidend für präzise Compliance-Beratung statt generischer Antworten.'
        : 'Court rulings show how laws are interpreted — critical for precise compliance advice instead of generic answers.',
      examples: de
        ? '16 Bundesländer DSFA-Leitlinien · BAG-Urteile · Datenschutzkonferenz-Beschlüsse'
        : '16 federal state DPIA guidelines · Labor court rulings · Data protection conference decisions',
    },
  ]

  // RAG Pipeline steps
  const ragPipelineSteps = [
    {
      icon: FileText,
      color: 'text-blue-400',
      bg: 'bg-blue-500/10 border-blue-500/20',
      title: de ? '1. Dokument-Ingestion' : '1. Document Ingestion',
      items: de
        ? [`${s('legal_sources') || 380}+ Rechtsquellen aus EU, Deutschland und Österreich`, 'Strukturelles Chunking an Artikel- und Absatz-Grenzen', 'Automatische Lizenz-Klassifikation (frei / Zitat / geschützt)', 'Geschützte Quellen werden vollständig reformuliert']
        : [`${s('legal_sources') || 380}+ legal sources from EU, Germany and Austria`, 'Structural chunking at article and paragraph boundaries', 'Automatic license classification (free / citation / restricted)', 'Protected standards (ISO, BSI) are fully reformulated'],
    },
    {
      icon: Cpu,
      color: 'text-purple-400',
      bg: 'bg-purple-500/10 border-purple-500/20',
      title: de ? '2. Control-Extraktion' : '2. Control Extraction',
      items: de
        ? ['LLM extrahiert Pflichten und Anforderungen aus jedem Textabschnitt', `${s('pipeline_versions') || 6} Pipeline-Versionen mit kontinuierlicher Qualitätsverbesserung`, `Obligation Extraction: ${fmtK(s('extracted_obligations'))} einzelne Pflichten identifiziert`, 'Atomic Control Composition: Pflichten werden zu prüfbaren Controls']
        : ['LLM extracts obligations and requirements from each text section', `${s('pipeline_versions') || 6} pipeline versions with continuous quality improvement`, `Obligation extraction: ${fmtK(s('extracted_obligations'))} individual duties identified`, 'Atomic control composition: duties become auditable controls'],
    },
    {
      icon: Database,
      color: 'text-emerald-400',
      bg: 'bg-emerald-500/10 border-emerald-500/20',
      title: de ? '3. Deduplizierung & Speicherung' : '3. Deduplication & Storage',
      items: de
        ? [`${fmtK(s('generated_controls'))} generierte Controls → ${fmtK(s('unique_controls'))} nach Deduplizierung`, 'Embedding-basierte Ähnlichkeitserkennung (Cosine Similarity)', 'Cross-Regulation Harmonisierung: gleiche Pflicht aus verschiedenen Gesetzen wird zusammengeführt', `Aktuell: ${fmtK(s('unique_controls'))} atomare Master Controls`]
        : [`${fmtK(s('generated_controls'))} generated controls → ${fmtK(s('unique_controls'))} after deduplication`, 'Embedding-based similarity detection (cosine similarity)', 'Cross-regulation harmonization: same obligation from different laws is merged', `Current: ${fmtK(s('unique_controls'))} atomic master controls`],
    },
    {
      icon: Search,
      color: 'text-indigo-400',
      bg: 'bg-indigo-500/10 border-indigo-500/20',
      title: de ? '4. Hybrid Search & Beratung' : '4. Hybrid Search & Advisory',
      items: de
        ? ['Vektorsuche + Keyword-Suche über alle Rechtsquellen gleichzeitig', 'Cross-Encoder Re-Ranking für präzise Relevanz-Sortierung', 'Quellen-Attribution: Jede Antwort verweist auf Artikel und Absatz', 'Der Compliance-Agent antwortet mit Rechtsgrundlage — nicht mit Vermutungen']
        : ['Vector search + keyword search across all legal sources simultaneously', 'Cross-encoder re-ranking for precise relevance sorting', 'Source attribution: Every answer references article and paragraph', 'The compliance agent answers with legal basis — not guesswork'],
    },
  ]

  // Multi-Agent System content — UCCA + Policy Engine
  const agents = [
    { name: 'UCCA', soul: de ? 'Use-Case Compliance' : 'Use-Case Compliance', desc: de ? 'Policy Engine (45 Regeln) + Eskalation E0–E3' : 'Policy engine (45 rules) + escalation E0–E3', color: 'text-indigo-400' },
    { name: de ? 'Pflichten-Engine' : 'Obligations Engine', soul: `${fmtK(s('extracted_obligations'))} ${de ? 'Pflichten' : 'obligations'}`, desc: de ? 'Multi-Regulation: NIS2, DSGVO, AI Act, CRA, ...' : 'Multi-regulation: NIS2, GDPR, AI Act, CRA, ...', color: 'text-emerald-400' },
    { name: de ? 'Compliance-Berater' : 'Compliance Advisor', soul: de ? 'Legal RAG + LLM' : 'Legal RAG + LLM', desc: de ? 'Chatbot mit 75+ Rechtsquellen als Wissenbasis' : 'Chatbot with 75+ legal sources as knowledge base', color: 'text-purple-400' },
    { name: de ? 'Dokument-Generator' : 'Document Generator', soul: de ? '7+ Templates' : '7+ templates', desc: de ? 'AGB, DSE, AV-Vertrag, DSFA, FRIA, BV + weitere' : 'T&C, Privacy Policy, DPA, DPIA, FRIA, Works Agreement + more', color: 'text-amber-400' },
    { name: de ? 'DSFA-Agent' : 'DPIA Agent', soul: de ? 'Art. 35 DSGVO' : 'Art. 35 GDPR', desc: de ? 'Risikobewertung mit 16 Bundesländer-Leitlinien' : 'Risk assessment with 16 federal state guidelines', color: 'text-red-400' },
    { name: de ? 'Control-Pipeline' : 'Control Pipeline', soul: de ? '70.000+ Controls' : '70,000+ controls', desc: de ? 'Automatische Extraktion aus neuen Rechtsquellen' : 'Automatic extraction from new legal sources', color: 'text-blue-400' },
  ]

  const agentInfra = [
    { icon: Shield, label: de ? 'Policy Engine' : 'Policy Engine', desc: de ? 'Deterministisch · LLM ist NICHT Wahrheitsquelle' : 'Deterministic · LLM is NOT source of truth' },
    { icon: Brain, label: de ? 'LLM-Schicht' : 'LLM Layer', desc: de ? 'Claude + lokale Modelle · EU-only Hosting' : 'Claude + local models · EU-only hosting' },
    { icon: Network, label: 'LiteLLM Gateway', desc: de ? 'OpenAI-kompatibel · Multi-Provider Routing' : 'OpenAI-compatible · Multi-provider routing' },
    { icon: Activity, label: de ? 'Eskalation E0–E3' : 'Escalation E0–E3', desc: de ? 'Auto-Approve → Team-Lead → DSB → DSB+Legal' : 'Auto-approve → Team lead → DPO → DPO+Legal' },
  ]

  // Quality Assurance content
  const qaFeatures = [
    {
      icon: Shield,
      color: 'text-emerald-400',
      title: de ? 'Control Quality Pipeline' : 'Control Quality Pipeline',
      items: de
        ? ['97.000 Controls generiert, 70.000+ nach Deduplizierung', '6 Pipeline-Versionen mit steigender Extraktionsqualität', 'Automatische Lizenz-Prüfung: geschützte Quellen werden reformuliert', 'Jeder Control hat Quellen-Referenz auf Artikel und Absatz']
        : ['97,000 controls generated, 70,000+ after deduplication', '6 pipeline versions with increasing extraction quality', 'Automatic license check: protected standards are reformulated', 'Every control has source reference to article and paragraph'],
    },
    {
      icon: Eye,
      color: 'text-indigo-400',
      title: de ? 'Kontinuierliche Erweiterung' : 'Continuous Expansion',
      items: de
        ? ['Neue Gesetze werden automatisch ingestiert und verarbeitet', 'Pipeline erkennt Überschneidungen mit bestehenden Controls', 'Cross-Regulation Mapping: gleiche Pflicht aus DSGVO und BDSG wird verknuepft', 'Wachsender Wissensvorsprung gegenüber manueller Compliance-Beratung']
        : ['New laws are automatically ingested and processed', 'Pipeline detects overlaps with existing controls', 'Cross-regulation mapping: same obligation from GDPR and BDSG is linked', 'Growing knowledge advantage over manual compliance consulting'],
    },
    {
      icon: Sparkles,
      color: 'text-purple-400',
      title: de ? 'CI/CD & Testing' : 'CI/CD & Testing',
      items: de
        ? ['Gitea Actions: Lint → Tests → Validierung bei jedem Push', 'Go-Tests (AI SDK) + Python-Tests (Backend + Pipeline)', 'Orca Auto-Deploy mit Health-Check-Monitoring', 'arm64 → amd64 Cross-Build für Hetzner Production']
        : ['Gitea Actions: Lint → Tests → Validation on every push', 'Go tests (AI SDK) + Python tests (Backend + Pipeline)', 'Orca auto-deploy with health check monitoring', 'arm64 → amd64 cross-build for Hetzner production'],
    },
    {
      icon: Zap,
      color: 'text-amber-400',
      title: de ? 'Infrastruktur' : 'Infrastructure',
      items: de
        ? ['Qdrant Vektordatenbank für semantische Suche', 'BGE-M3 Multilingual Embedding (lokal gehostet)', 'MinIO Object Storage (S3-kompatibel, TLS-verschlüsselt)', '100% EU-Cloud · Keine US-Provider · BSI-konforme Hosting-Partner']
        : ['Qdrant vector database for semantic search', 'BGE-M3 multilingual embedding (locally hosted)', 'MinIO object storage (S3-compatible, TLS-encrypted)', '100% EU cloud · No US providers · BSI-compliant hosting partners'],
    },
  ]

  return (
    <div>
      <FadeInView className="text-center mb-5">
        <p className="text-xs font-mono text-indigo-400/60 uppercase tracking-widest mb-2">
          {de ? 'Anhang' : 'Appendix'}
        </p>
        <h2 className="text-4xl md:text-5xl font-bold mb-2">
          <GradientText>{i.annex.aipipeline.title}</GradientText>
        </h2>
        <p className="text-lg text-white/50 max-w-2xl mx-auto">{i.annex.aipipeline.subtitle}</p>
      </FadeInView>

      {/* Hero Stats */}
      <FadeInView delay={0.1}>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-2 mb-4">
          {heroStats.map((stat, idx) => (
            <div key={idx} className="border border-white/[0.08] rounded-xl p-2.5 bg-white/[0.03] text-center">
              <p className={`text-2xl font-black tracking-tight ${stat.color}`}>{stat.value}</p>
              <p className="text-[11px] font-semibold text-white/70">{stat.label}</p>
              <p className="text-[9px] text-white/30 mt-0.5 leading-tight">{stat.sub}</p>
            </div>
          ))}
        </div>
      </FadeInView>

      {/* Tab Navigation */}
      <FadeInView delay={0.15}>
        <div className="flex items-center justify-center gap-2 mb-4">
          {tabs.map((tab) => {
            const Icon = tab.icon
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm transition-all
                  ${activeTab === tab.id
                    ? 'bg-indigo-500/20 text-indigo-300 border border-indigo-500/30'
                    : 'bg-white/[0.04] text-white/40 border border-transparent hover:text-white/60 hover:bg-white/[0.06] animate-[pulse_3s_ease-in-out_infinite]'
                  }`}
              >
                <Icon className="w-4 h-4" />
                {tab.label}
              </button>
            )
          })}
        </div>
      </FadeInView>

      {/* Tab Content */}
      <FadeInView delay={0.2} key={activeTab}>
        {activeTab === 'rag' && (
          <div>
            {/* Source Categories — Why each matters */}
            <div className="grid md:grid-cols-2 gap-2 mb-4">
              {sourceCategories.map((cat, idx) => {
                const Icon = cat.icon
                return (
                  <div key={idx} className={`border rounded-xl p-2.5 ${cat.bg}`}>
                    <div className="flex items-center gap-2 mb-1.5">
                      <Icon className={`w-4 h-4 ${cat.color}`} />
                      <h3 className="text-xs font-bold text-white">{cat.title}</h3>
                    </div>
                    <p className="text-[10px] text-white/50 mb-1.5 leading-relaxed">{cat.why}</p>
                    <p className="text-[9px] text-white/25 font-mono leading-tight">{cat.examples}</p>
                  </div>
                )
              })}
            </div>

            {/* Pipeline Flow Visualization */}
            <div className="flex items-center justify-center gap-1 flex-wrap">
              {[
                { icon: FileText, label: de ? '75+ Quellen' : '75+ Sources' },
                { icon: Layers, label: de ? 'Chunking & Lizenz' : 'Chunking & License' },
                { icon: Cpu, label: de ? 'LLM-Extraktion' : 'LLM Extraction' },
                { icon: Database, label: de ? '70k+ Controls' : '70k+ Controls' },
                { icon: Search, label: de ? 'Hybrid Search' : 'Hybrid Search' },
                { icon: Brain, label: de ? 'Beratung' : 'Advisory' },
              ].map((step, idx, arr) => (
                <div key={idx} className="flex items-center gap-1">
                  <div className="flex items-center gap-1 px-2 py-1 rounded-lg bg-white/[0.05] border border-white/[0.08]">
                    <step.icon className="w-3 h-3 text-indigo-400" />
                    <span className="text-[10px] text-white/50">{step.label}</span>
                  </div>
                  {idx < arr.length - 1 && <ArrowRight className="w-3 h-3 text-white/20" />}
                </div>
              ))}
            </div>
          </div>
        )}

        {activeTab === 'agents' && (
          <div className="grid md:grid-cols-12 gap-4">
            {/* Agent List */}
            <div className="md:col-span-7">
              <GlassCard hover={false} className="p-4">
                <div className="flex items-center gap-2 mb-3">
                  <Bot className="w-4 h-4 text-white/40" />
                  <p className="text-xs font-semibold text-white/40 uppercase tracking-wider">
                    {de ? 'Compliance-Engines' : 'Compliance Engines'}
                  </p>
                </div>
                <div className="grid grid-cols-2 gap-2">
                  {agents.map((agent, idx) => (
                    <div key={idx} className="p-2 rounded-lg bg-white/[0.03] border border-white/5">
                      <div className="flex items-center gap-1.5 mb-1">
                        <div className={`w-1.5 h-1.5 rounded-full ${agent.color} bg-current`} />
                        <p className="text-xs font-bold text-white/80">{agent.name}</p>
                      </div>
                      <p className="text-[10px] text-white/40 leading-tight">{agent.desc}</p>
                      <p className="text-[9px] font-mono text-white/25 mt-1">{agent.soul}</p>
                    </div>
                  ))}
                </div>
              </GlassCard>
            </div>
            {/* Agent Infrastructure */}
            <div className="md:col-span-5">
              <GlassCard hover={false} className="p-4 h-full">
                <div className="flex items-center gap-2 mb-3">
                  <Network className="w-4 h-4 text-white/40" />
                  <p className="text-xs font-semibold text-white/40 uppercase tracking-wider">
                    {de ? 'Infrastruktur' : 'Infrastructure'}
                  </p>
                </div>
                <div className="space-y-2.5">
                  {agentInfra.map((inf, idx) => {
                    const Icon = inf.icon
                    return (
                      <div key={idx} className="flex items-start gap-2.5">
                        <div className="w-7 h-7 rounded-lg bg-purple-500/10 border border-purple-500/20 flex items-center justify-center shrink-0">
                          <Icon className="w-3.5 h-3.5 text-purple-400" />
                        </div>
                        <div>
                          <p className="text-xs font-semibold text-white/70">{inf.label}</p>
                          <p className="text-[10px] text-white/40">{inf.desc}</p>
                        </div>
                      </div>
                    )
                  })}
                </div>
                <div className="mt-3 pt-3 border-t border-white/5">
                  <p className="text-[10px] text-white/20">
                    {de
                      ? 'Wahrheit = Regeln + Evidenz · LLM = Übersetzer + Subsumtions-Helfer · 100% EU-Cloud'
                      : 'Truth = Rules + Evidence · LLM = Translator + Subsumption Helper · 100% EU Cloud'}
                  </p>
                </div>
              </GlassCard>
            </div>
          </div>
        )}

        {activeTab === 'quality' && (
          <div className="grid md:grid-cols-2 gap-3">
            {qaFeatures.map((feat, idx) => {
              const Icon = feat.icon
              return (
                <GlassCard key={idx} hover={false} className="p-3">
                  <div className="flex items-center gap-2 mb-2">
                    <Icon className={`w-4 h-4 ${feat.color}`} />
                    <h3 className="text-xs font-bold text-white">{feat.title}</h3>
                  </div>
                  <ul className="space-y-1">
                    {feat.items.map((item, iidx) => (
                      <li key={iidx} className="flex items-start gap-1.5 text-[11px] text-white/50">
                        <span className={`w-1 h-1 rounded-full mt-1.5 ${feat.color} bg-current shrink-0`} />
                        {item}
                      </li>
                    ))}
                  </ul>
                </GlassCard>
              )
            })}
          </div>
        )}
      </FadeInView>
    </div>
  )
}
