'use client'

import { motion } from 'framer-motion'
import { FileText, Cpu, Shield, Search, ClipboardCheck, Download } from 'lucide-react'
import { useApp } from '@/lib/context'
import FadeInView from '@/components/ui/FadeInView'
import TechBadge from '@/components/ui/TechBadge'
import { ANIMATION } from '@/lib/constants'

const stepIcons = [FileText, Cpu, Shield, Search, ClipboardCheck, Download]

const flow = {
  de: {
    steps: [
      {
        num: '01',
        title: 'Grenzen & Verwendung',
        description: 'Der Nutzer füllt 14 Textfelder aus — Maschinenbeschreibung, bestimmungsgemäße Verwendung, Energiequellen, Betriebsarten, Personengruppen.',
        example: '"Kollaborativer 6-Achs-Roboter UR10e mit Kraft-/Momentsensorik, elektrischer Antrieb 48V DC, Ethernet/PROFINET..."',
        tags: [],
      },
      {
        num: '02',
        title: 'Automatische Analyse',
        description: '6 deterministische Schritte in Sekunden: Narrative Parser (200 Keywords) → Komponenten → Pattern Engine (1.058 Patterns) → Gefährdungen → Maßnahmen (225 Bibliothek) → Normen (751 A/B/C).',
        example: 'Pattern HP059 "Kollisionsgefahr Cobot": RequiredTags [cobot, rotating_joint] — PATTERN FEUERT ✓',
        tags: ['Deterministisch', 'Kein LLM', 'AND/NOT-Logik'],
      },
      {
        num: '03',
        title: 'Risikobewertung',
        description: 'Im Hazard Log erscheinen alle Gefährdungen mit Erstbewertung (S/E/P), RPZ-Berechnung und automatischer SIL/PL-Ableitung nach ISO-Risikograph.',
        example: 'Cobot-Ergebnis: 12 Gefährdungen, RPZ 4-48, SIL 0-2, PL a-d',
        tags: ['ISO 12100', 'SIL/PL', 'RPZ'],
      },
      {
        num: '04',
        title: 'Regulatorische Hinweise',
        description: 'On-Demand RAG-Suche in 36.708 Chunks: BAuA (TRBS/TRGS/ASR), OSHA Technical Manual, EU-Verordnungen. Keine ISO-Texte — nur gemeinfreie Quellen.',
        example: 'Gefährdung "Kollision" → TRBS 2111 Kap. 4.3, OSHA 1910.212(a)(1)',
        tags: ['RAG', 'BAuA', 'OSHA'],
      },
      {
        num: '05',
        title: 'Verifikation & Nachweise',
        description: '25 Evidenztypen werden automatisch vorgeschlagen. Der Nutzer erstellt Verifikationspläne und ordnet Prüfberichte zu.',
        example: 'E01 Hazard Analysis Report, E04 Electrical Safety Test, E14 Software Validation',
        tags: ['25 Evidenztypen', 'Traceability'],
      },
      {
        num: '06',
        title: 'CE-Akte generieren',
        description: 'Strukturiertes Dokument nach MVO 2023/1230 Anhang IV: Beschreibung, Risikobeurteilung, Normen, Maßnahmen, Nachweise, Konformitätserklärung. Export als PDF.',
        example: 'Vollständige Technische Dokumentation per Klick',
        tags: ['MVO 2023/1230', 'Anhang IV', 'PDF'],
      },
    ],
  },
  en: {
    steps: [
      {
        num: '01',
        title: 'Limits & Intended Use',
        description: 'The user fills in 14 text fields — machine description, intended use, energy sources, operating modes, user groups.',
        example: '"Collaborative 6-axis robot UR10e with force/torque sensing, electric drive 48V DC, Ethernet/PROFINET..."',
        tags: [],
      },
      {
        num: '02',
        title: 'Automatic Analysis',
        description: '6 deterministic steps in seconds: Narrative Parser (200 keywords) → Components → Pattern Engine (1,058 patterns) → Hazards → Mitigations (225 library) → Norms (751 A/B/C).',
        example: 'Pattern HP059 "Collision hazard cobot": RequiredTags [cobot, rotating_joint] — PATTERN FIRES ✓',
        tags: ['Deterministic', 'No LLM', 'AND/NOT logic'],
      },
      {
        num: '03',
        title: 'Risk Assessment',
        description: 'The Hazard Log shows all hazards with initial assessment (S/E/P), RPZ calculation and automatic SIL/PL derivation per ISO risk graph.',
        example: 'Cobot result: 12 hazards, RPZ 4-48, SIL 0-2, PL a-d',
        tags: ['ISO 12100', 'SIL/PL', 'RPZ'],
      },
      {
        num: '04',
        title: 'Regulatory Guidance',
        description: 'On-demand RAG search across 36,708 chunks: BAuA (TRBS/TRGS/ASR), OSHA Technical Manual, EU regulations. No ISO texts — only public domain sources.',
        example: 'Hazard "Collision" → TRBS 2111 Ch. 4.3, OSHA 1910.212(a)(1)',
        tags: ['RAG', 'BAuA', 'OSHA'],
      },
      {
        num: '05',
        title: 'Verification & Evidence',
        description: '25 evidence types are automatically suggested. Users create verification plans and assign test reports.',
        example: 'E01 Hazard Analysis Report, E04 Electrical Safety Test, E14 Software Validation',
        tags: ['25 evidence types', 'Traceability'],
      },
      {
        num: '06',
        title: 'Generate CE File',
        description: 'Structured document per MR 2023/1230 Annex IV: Description, risk assessment, norms, mitigations, evidence, declaration of conformity. Export as PDF.',
        example: 'Complete technical documentation with one click',
        tags: ['MR 2023/1230', 'Annex IV', 'PDF'],
      },
    ],
  },
}

function StepContent({ step, Icon }: { step: typeof flow.de.steps[0]; Icon: typeof FileText }) {
  return (
    <div className="relative pl-16">
      <div className="absolute left-0 w-12 h-12 rounded-xl bg-accent-electric/10 border border-accent-electric/20 flex items-center justify-center">
        <Icon className="w-5 h-5 text-accent-electric" />
      </div>
      <div className="rounded-2xl border border-white/[0.06] bg-white/[0.03] p-6">
        <div className="flex items-center gap-3 mb-3">
          <span className="font-mono text-xs text-accent-electric/60">{step.num}</span>
          <h3 className="text-lg font-bold">{step.title}</h3>
        </div>
        <p className="text-sm text-white/50 mb-3">{step.description}</p>
        <div className="rounded-lg bg-enterprise-darker border border-white/[0.04] px-4 py-3 mb-3">
          <p className="font-mono text-xs text-white/40">{step.example}</p>
        </div>
        {step.tags.length > 0 && (
          <div className="flex flex-wrap gap-1.5">
            {step.tags.map(tag => (
              <TechBadge key={tag}>{tag}</TechBadge>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default function CEFlowSection() {
  const { lang } = useApp()
  const { steps } = flow[lang]

  return (
    <section className="py-16 sm:py-24">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="relative">
          {/* Vertical line */}
          <div className="absolute left-6 top-0 bottom-0 w-px bg-white/[0.06]" />

          <div className="space-y-8">
            {steps.map((step, idx) => {
              const Icon = stepIcons[idx]
              if (idx < 2) {
                return (
                  <motion.div
                    key={idx}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: ANIMATION.duration, delay: 0.3 + idx * 0.15, ease: ANIMATION.ease }}
                  >
                    <StepContent step={step} Icon={Icon} />
                  </motion.div>
                )
              }
              return (
                <FadeInView key={idx} delay={0}>
                  <StepContent step={step} Icon={Icon} />
                </FadeInView>
              )
            })}
          </div>
        </div>
      </div>
    </section>
  )
}
