'use client'

import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Language } from '@/lib/types'
import { t } from '@/lib/i18n'
import { AlertTriangle, Scale, Shield, ExternalLink, X } from 'lucide-react'
import GlassCard from '../ui/GlassCard'
import GradientText from '../ui/GradientText'
import FadeInView from '../ui/FadeInView'

interface ProblemSlideProps {
  lang: Language
}

interface SourceInfo {
  name: string
  url: string
  date: string
  excerpt_de: string
  excerpt_en: string
}

interface ProblemCardData {
  sources: SourceInfo[]
}

// Quellenangaben für jede Behauptung
const cardSources: ProblemCardData[] = [
  {
    // KI-Dilemma: Maschinenbauer wollen KI, aber nicht US-SaaS
    sources: [
      {
        name: 'Bitkom Cloud Monitor 2024 — Industrieunternehmen',
        url: 'https://www.bitkom.org/Themen/Datenschutz-Sicherheit/Cloud-Monitor',
        date: '2024',
        excerpt_de: 'Laut Bitkom Cloud Monitor lehnen 64% der deutschen Industrieunternehmen US-Cloud-Dienste für sensible Daten ab. Im Maschinenbau liegt die Ablehnung bei über 70%. Unternehmen wollen KI nutzen, aber nicht auf Kosten ihrer Datensouveraenitaet.',
        excerpt_en: 'According to Bitkom Cloud Monitor, 64% of German industrial companies reject US cloud services for sensitive data. In machine manufacturing, rejection exceeds 70%. Companies want AI but not at the cost of their data sovereignty.',
      },
      {
        name: 'DIHK Digitalisierungsumfrage 2024',
        url: 'https://www.dihk.de/de/themen-und-positionen/wirtschaft-digital/digitalisierung',
        date: '2024',
        excerpt_de: 'KMU wollen digitalisieren und KI einsetzen, trauen sich aber nicht: 83% sehen Datenschutzrisiken als Haupthindernis. Microsoft Copilot, ChatGPT und andere US-Tools werden im produzierenden Gewerbe kaum auf sensiblen Code angewendet.',
        excerpt_en: 'SMEs want to digitize and use AI but hesitate: 83% see data protection risks as the main barrier. Microsoft Copilot, ChatGPT and other US tools are rarely applied to sensitive code in manufacturing.',
      },
    ],
  },
  {
    // Patriots Act: Kein Schutz selbst auf EU-Servern
    sources: [
      {
        name: 'Schrems II — EuGH C-311/18',
        url: 'https://curia.europa.eu/juris/liste.jsf?num=C-311/18',
        date: '2020',
        excerpt_de: 'Der EuGH erklaerte das EU-US Privacy Shield für ungueltig. US-Unternehmen unterliegen dem CLOUD Act und dem FISA 702 — auch für Daten auf europaeischen Servern. Selbst EU-Rechenzentren von AWS, Google und Microsoft bieten keinen Schutz vor US-Zugriff.',
        excerpt_en: 'The CJEU invalidated the EU-US Privacy Shield. US companies are subject to the CLOUD Act and FISA 702 — even for data on European servers. Even EU data centers of AWS, Google and Microsoft offer no protection from US access.',
      },
    ],
  },
  {
    // Regulierungs-Tsunami: 5+ Gesetze, 50k+ Kosten
    sources: [
      {
        name: 'VDMA — Compliance-Kosten im Maschinenbau',
        url: 'https://www.vdma.org/',
        date: '2024',
        excerpt_de: 'Externe Pentests kosten 15.000-40.000 EUR pro Durchlauf, CE-Software-Risikobeurteilungen 10.000-25.000 EUR. Diese Prüfungen erfolgen einmal jaehrlich und decken nur eine Momentaufnahme ab. KMU mit 10-500 Mitarbeitern können sich weder Personal noch Budget für kontinuierliche Compliance leisten.',
        excerpt_en: 'External pentests cost EUR 15,000-40,000 per run, CE software risk assessments EUR 10,000-25,000. These audits occur annually, covering only a snapshot. SMEs with 10-500 employees can afford neither staff nor budget for continuous compliance.',
      },
      {
        name: 'Compliance-Markt: Top-10 Anbieter >$1,1 Mrd. Umsatz',
        url: 'https://sacra.com/c/vanta/',
        date: '2025',
        excerpt_de: 'Vanta ($220M ARR, $4,15 Mrd. Bewertung), Drata ($100M), OneTrust ($500M+), DataGuard (€52M). Der Markt ist validiert — aber keiner dieser Anbieter kombiniert Code-Security mit Compliance für den Maschinenbau.',
        excerpt_en: 'Vanta ($220M ARR, $4.15B valuation), Drata ($100M), OneTrust ($500M+), DataGuard (€52M). The market is validated — but none of these providers combine code security with compliance for manufacturing.',
      },
    ],
  },
]

const icons = [AlertTriangle, Scale, Shield]

function SourceModal({
  isOpen,
  onClose,
  cardIndex,
  lang,
  cardTitle,
}: {
  isOpen: boolean
  onClose: () => void
  cardIndex: number
  lang: Language
  cardTitle: string
}) {
  if (!isOpen) return null
  const sources = cardSources[cardIndex]?.sources || []

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          onClick={onClose}
        >
          <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
          <motion.div
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.9, opacity: 0 }}
            className="relative bg-slate-900/95 border border-white/10 rounded-2xl p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              onClick={onClose}
              className="absolute top-4 right-4 p-1 text-white/40 hover:text-white/80 transition-colors"
            >
              <X className="w-5 h-5" />
            </button>

            <h3 className="text-xl font-bold text-white mb-1">{cardTitle}</h3>
            <p className="text-sm text-white/40 mb-6">
              {lang === 'de' ? 'Quellenangaben' : 'Sources'}
            </p>

            <div className="space-y-4">
              {sources.map((src, idx) => (
                <div
                  key={idx}
                  className="bg-white/[0.05] border border-white/10 rounded-xl p-4"
                >
                  <div className="flex items-start justify-between gap-3 mb-2">
                    <div>
                      <p className="text-sm font-semibold text-white">{src.name}</p>
                      <p className="text-xs text-white/30">{src.date}</p>
                    </div>
                    <a
                      href={src.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex-shrink-0 p-1.5 text-indigo-400 hover:text-indigo-300 hover:bg-indigo-500/10 rounded-lg transition-colors"
                      title={lang === 'de' ? 'Quelle oeffnen' : 'Open source'}
                    >
                      <ExternalLink className="w-4 h-4" />
                    </a>
                  </div>
                  <p className="text-sm text-white/60 leading-relaxed">
                    {lang === 'de' ? src.excerpt_de : src.excerpt_en}
                  </p>
                </div>
              ))}
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}

export default function ProblemSlide({ lang }: ProblemSlideProps) {
  const i = t(lang)
  const [activeModal, setActiveModal] = useState<number | null>(null)

  return (
    <div>
      <FadeInView className="text-center mb-12">
        <h2 className="text-4xl md:text-5xl font-bold mb-3">
          <GradientText>{i.problem.title}</GradientText>
        </h2>
        <p className="text-lg text-white/50 max-w-2xl mx-auto">{i.problem.subtitle}</p>
      </FadeInView>

      <div className="grid md:grid-cols-3 gap-6 mb-12">
        {i.problem.cards.map((card, idx) => {
          const Icon = icons[idx]
          const sourceCount = cardSources[idx]?.sources.length || 0
          return (
            <GlassCard
              key={idx}
              delay={0.2 + idx * 0.15}
              className="text-center cursor-pointer group"
              onClick={() => setActiveModal(idx)}
            >
              <div className="w-12 h-12 mx-auto mb-4 rounded-xl bg-red-500/10 flex items-center justify-center">
                <Icon className="w-6 h-6 text-red-400" />
              </div>
              <h3 className="text-lg font-bold mb-2 text-white">{card.title}</h3>
              <p className="text-3xl font-bold text-red-400 mb-3">{card.stat}</p>
              <p className="text-sm text-white/50 leading-relaxed mb-3">{card.desc}</p>
              <p className="text-[10px] text-indigo-400/60 group-hover:text-indigo-400 transition-colors">
                {sourceCount} {lang === 'de' ? (sourceCount === 1 ? 'Quelle' : 'Quellen') : (sourceCount === 1 ? 'source' : 'sources')}
                {' · '}
                {lang === 'de' ? 'Klicken für Details' : 'Click for details'}
              </p>
            </GlassCard>
          )
        })}
      </div>

      <FadeInView delay={0.8} className="max-w-4xl mx-auto">
        <div className="bg-gradient-to-r from-amber-500/10 to-indigo-500/10 border border-amber-500/20 rounded-xl px-6 py-5">
          <div className="flex items-center gap-4">
            <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-amber-500 to-orange-600 flex items-center justify-center shrink-0 shadow-lg">
              <Shield className="w-8 h-8 text-white" />
            </div>
            <div>
              <h3 className="text-xl font-bold text-amber-300 mb-1">
                {lang === 'de' ? 'Die Konsequenz' : 'The Consequence'}
              </h3>
              <p className="text-sm text-white/50 leading-relaxed">
                {i.problem.quote}
              </p>
            </div>
          </div>
        </div>
      </FadeInView>

      {/* Source Modals */}
      {i.problem.cards.map((card, idx) => (
        <SourceModal
          key={idx}
          isOpen={activeModal === idx}
          onClose={() => setActiveModal(null)}
          cardIndex={idx}
          lang={lang}
          cardTitle={card.title}
        />
      ))}
    </div>
  )
}
