'use client'

import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Language, PitchMarket } from '@/lib/types'
import { t, formatEur } from '@/lib/i18n'
import { ExternalLink, X, TrendingUp, Shield } from 'lucide-react'
import GradientText from '../ui/GradientText'
import FadeInView from '../ui/FadeInView'
import AnimatedCounter from '../ui/AnimatedCounter'

interface MarketSlideProps {
  lang: Language
  market: PitchMarket[]
}

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

// Quellenangaben für die Marktzahlen
const marketSources: Record<string, MarketSourceInfo[]> = {
  TAM: [
    {
      name: 'Bottom-Up-Validierung: Echte Umsatzdaten der Top-10 Compliance-Anbieter',
      url: 'https://sacra.com/c/vanta/',
      date: '2025-2026',
      excerpt_de: 'Die Top-10 Compliance-Automation-Anbieter erzielen zusammen ~$1,13 Mrd. Umsatz (Vanta $220M, OneTrust $500M, Drata $100M, Usercentrics $117M, Securiti $76M, DataGuard €52M, Sprinto $38M, heyData €15M, Caralegal €5.8M, Proliance €3.9M). Mit 50+ weiteren Anbietern liegt der Gesamtmarkt bei ~$1,6-2 Mrd. — aktuell nur ~20% des adressierbaren Volumens (Gartner: 80% der Unternehmen managen Compliance noch manuell). Inkl. DevSecOps für Manufacturing (~$3,5 Mrd.) ergibt sich ein TAM von $8-12 Mrd.',
      excerpt_en: 'The top 10 compliance automation providers generate ~$1.13B combined revenue (Vanta $220M, OneTrust $500M, Drata $100M, Usercentrics $117M, Securiti $76M, DataGuard €52M, Sprinto $38M, heyData €15M, Caralegal €5.8M, Proliance €3.9M). With 50+ additional vendors, the total market is ~$1.6-2B — currently only ~20% of addressable volume (Gartner: 80% manage compliance manually). Incl. DevSecOps for manufacturing (~$3.5B), the TAM is $8-12B.',
    },
    {
      name: 'Grand View Research — GRC Market Report 2024',
      url: 'https://www.grandviewresearch.com/industry-analysis/governance-risk-management-compliance-market',
      date: '2024',
      excerpt_de: 'Der globale GRC-Software-Markt wurde 2023 auf 11,8 Mrd. USD bewertet, CAGR 13,8%. Die Compliance-Automation-Welle (Vanta, Drata) zeigt 30-45% Wachstum p.a. — deutlich über dem Branchendurchschnitt.',
      excerpt_en: 'The global GRC software market was valued at USD 11.8B in 2023, CAGR 13.8%. The compliance automation wave (Vanta, Drata) shows 30-45% p.a. growth — well above industry average.',
    },
  ],
  SAM: [
    {
      name: 'Bottom-Up: DACH Compliance-Anbieter + NIS2/CRA/AI-Act Expansion',
      url: 'https://www.vdma.org/statistics',
      date: '2025-2026',
      excerpt_de: 'DACH-Compliance-Umsaetze heute: DataGuard €52M + heyData €15M + Proliance €3.9M + Caralegal €5.8M + OneTrust DACH ~€30M + Secjur/andere ~€10M = ~€120M (nur DSGVO-Compliance). NIS2 erweitert die Regulierung auf 30.000+ Unternehmen (bisher 4.500). CRA und AI Act schaffen voellig neue Pflichten für Maschinenbauer. DACH-DevSecOps-Markt: +€300-400M. Gesamtes SAM für Compliance + Code-Security in DACH Manufacturing: €850M-1,2 Mrd.',
      excerpt_en: 'DACH compliance revenues today: DataGuard €52M + heyData €15M + Proliance €3.9M + Caralegal €5.8M + OneTrust DACH ~€30M + Secjur/others ~€10M = ~€120M (GDPR compliance only). NIS2 expands regulation to 30,000+ companies (from 4,500). CRA and AI Act create entirely new obligations for manufacturers. DACH DevSecOps market: +€300-400M. Total SAM for compliance + code security in DACH manufacturing: €850M-1.2B.',
    },
  ],
  SOM: [
    {
      name: 'VDMA Mitgliederstatistik + Wettbewerbs-Benchmarks',
      url: 'https://www.vdma.org/mitglieder',
      date: '2025-2026',
      excerpt_de: 'DACH-weit ca. 5.000 Maschinenbauer mit Eigenentwicklung (VDMA). Bei 10% Marktdurchdringung (~500 Unternehmen) und €14.400/Jahr ARPU (Blended Avg.) ergibt sich ein SOM von €7,2 Mio. Zum Vergleich: Proliance mit 65 Mitarbeitern erreicht €3,9M, heyData mit 58 MA bereits €15M. Mit KI-Automatisierung ist eine höhere Durchdringung bei niedrigerer Personalintensität möglich.',
      excerpt_en: 'Approx. 5,000 DACH machine manufacturers with in-house dev (VDMA). At 10% penetration (~500 companies) and €14,400/yr ARPU (blended avg.), SOM is €7.2M. For comparison: Proliance with 65 employees achieves €3.9M, heyData with 58 employees already €15M. AI automation enables higher penetration with lower headcount intensity.',
    },
  ],
}

// ─── Pentesting / AppSec Market Data ──────────────────────────────────────────

type MarketView = 'compliance' | 'pentesting'

interface PentestMarketEntry {
  segment: string
  label: { de: string; en: string }
  value_eur: number
  growth_rate_pct: number
  source: string
}

const PENTEST_MARKET: PentestMarketEntry[] = [
  { segment: 'TAM', label: { de: 'Total Addressable Market', en: 'Total Addressable Market' }, value_eur: 13_000_000_000, growth_rate_pct: 17, source: 'Gartner + MarketsAndMarkets 2025' },
  { segment: 'SAM', label: { de: 'Serviceable Addressable Market', en: 'Serviceable Addressable Market' }, value_eur: 1_600_000_000, growth_rate_pct: 22, source: 'DACH AST + Pentesting (Bottom-Up)' },
  { segment: 'SOM', label: { de: 'Serviceable Obtainable Market', en: 'Serviceable Obtainable Market' }, value_eur: 35_000_000, growth_rate_pct: 0, source: 'Year 5 Target (500 Kunden)' },
]

const pentestMarketSources: Record<string, MarketSourceInfo[]> = {
  TAM: [
    {
      name: 'MarketsAndMarkets — Application Security Testing Market 2025',
      url: 'https://www.marketsandmarkets.com/Market-Reports/application-security-testing-market-150735030.html',
      date: '2025',
      excerpt_de: 'Der globale AST-Markt (SAST, DAST, IAST, SCA) wird auf $8,5 Mrd. (2025) geschätzt und soll bis 2030 auf $19,5 Mrd. wachsen (CAGR 18,2%). Hinzu kommt der Pentesting-Markt ($2,7 Mrd.) und der Compliance-Convergence-Anteil ($1,8 Mrd.). Gesamt-TAM für integriertes AppSec + Compliance: ~$13 Mrd.',
      excerpt_en: 'The global AST market (SAST, DAST, IAST, SCA) is estimated at $8.5B (2025), projected to reach $19.5B by 2030 (CAGR 18.2%). Adding the pentesting market ($2.7B) and compliance convergence share ($1.8B), total TAM for integrated AppSec + compliance: ~$13B.',
    },
    {
      name: 'Gartner — Magic Quadrant for Application Security Testing 2024',
      url: 'https://www.gartner.com/reviews/market/application-security-testing',
      date: '2024',
      excerpt_de: 'Gartner bestätigt den Trend zur Konvergenz von AppSec und Compliance. Führende Anbieter (Snyk, Veracode, Checkmarx) erreichen zusammen >$850M Umsatz. Der Markt wächst mit 17-20% p.a., getrieben durch regulatorische Anforderungen (CRA, NIS2) und AI-getriebene Entwicklung.',
      excerpt_en: 'Gartner confirms the AppSec-compliance convergence trend. Leading vendors (Snyk, Veracode, Checkmarx) generate >$850M combined revenue. The market grows at 17-20% p.a., driven by regulatory requirements (CRA, NIS2) and AI-driven development.',
    },
  ],
  SAM: [
    {
      name: 'Bottom-Up: DACH AppSec + Manufacturing Pentesting',
      url: 'https://www.bitkom.org/Marktdaten/ITK-Konjunktur/IT-Markt-Deutschland',
      date: '2025-2026',
      excerpt_de: 'DACH IT-Security-Markt: €8,2 Mrd. (Bitkom 2025). AppSec-Anteil: ~15% = €1,2 Mrd. Davon Pentesting/DAST/SAST für produzierende Industrie: ~€400M. CRA-Pflicht für Maschinenbauer erzeugt neue Nachfrage: geschätzt +€200M bis 2028. SAM für integriertes AppSec + Compliance im DACH-Manufacturing: ~€1,6 Mrd.',
      excerpt_en: 'DACH IT security market: €8.2B (Bitkom 2025). AppSec share: ~15% = €1.2B. Pentesting/DAST/SAST for manufacturing: ~€400M. CRA obligation for manufacturers creates new demand: est. +€200M by 2028. SAM for integrated AppSec + compliance in DACH manufacturing: ~€1.6B.',
    },
  ],
  SOM: [
    {
      name: 'VDMA + Branchenbenchmarks — Pentesting SOM',
      url: 'https://www.vdma.org/statistics',
      date: '2025-2026',
      excerpt_de: 'Zielmarkt: 5.000 DACH-Maschinenbauer mit Eigenentwicklung. Bei 10% Durchdringung (500 Unternehmen) und €70K/Jahr Blended ARPU (Compliance €18K + AppSec €52K) ergibt sich ein SOM von €35 Mio. in Year 5. Zum Vergleich: Pentera erreicht mit 400 MA $100M ARR bei 900 Kunden. Intruder (100 MA) erreicht $10M bei 2.500 Kunden.',
      excerpt_en: 'Target market: 5,000 DACH manufacturers with in-house development. At 10% penetration (500 companies) and €70K/yr blended ARPU (compliance €18K + AppSec €52K), SOM is €35M in Year 5. For comparison: Pentera achieves $100M ARR with 400 employees and 900 customers. Intruder (100 employees) achieves $10M with 2,500 customers.',
    },
  ],
}

const sizes = [280, 200, 130]
const colors = ['border-indigo-500/30 bg-indigo-500/5', 'border-purple-500/30 bg-purple-500/5', 'border-blue-500/30 bg-blue-500/5']
const textColors = ['text-indigo-400', 'text-purple-400', 'text-blue-400']

function SourceModal({
  isOpen,
  onClose,
  segment,
  lang,
  sources: sourcesMap,
}: {
  isOpen: boolean
  onClose: () => void
  segment: string
  lang: Language
  sources?: Record<string, MarketSourceInfo[]>
}) {
  if (!isOpen) return null
  const sources = (sourcesMap || marketSources)[segment] || []

  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">{segment}</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 MarketSlide({ lang, market }: MarketSlideProps) {
  const i = t(lang)
  const labels = [i.market.tamLabel, i.market.samLabel, i.market.somLabel]
  const segments = [i.market.tam, i.market.sam, i.market.som]
  const segmentKeys = ['TAM', 'SAM', 'SOM']
  const [activeModal, setActiveModal] = useState<string | null>(null)
  const [marketView, setMarketView] = useState<MarketView>('compliance')

  const activeSources = marketView === 'compliance' ? marketSources : pentestMarketSources

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

      {/* Market View Toggle */}
      <FadeInView delay={0.1} className="flex justify-center gap-2 mb-8">
        <button
          onClick={() => setMarketView('compliance')}
          className={`px-4 py-1.5 rounded-full text-xs font-medium transition-all ${
            marketView === 'compliance'
              ? 'bg-indigo-500/20 text-indigo-300 border border-indigo-500/30'
              : 'bg-white/[0.04] text-white/40 border border-white/5 hover:bg-white/[0.08] animate-[pulse_3s_ease-in-out_infinite]'
          }`}
        >
          {lang === 'de' ? 'Compliance & Code-Security' : 'Compliance & Code Security'}
        </button>
        <button
          onClick={() => setMarketView('pentesting')}
          className={`px-4 py-1.5 rounded-full text-xs font-medium transition-all flex items-center gap-1.5 ${
            marketView === 'pentesting'
              ? 'bg-red-500/20 text-red-300 border border-red-500/30'
              : 'bg-white/[0.04] text-white/40 border border-white/5 hover:bg-white/[0.08] animate-[pulse_3s_ease-in-out_infinite]'
          }`}
        >
          <Shield className="w-3 h-3" />
          {lang === 'de' ? 'Pentesting & AppSec' : 'Pentesting & AppSec'}
        </button>
      </FadeInView>

      {/* Compliance Market */}
      {marketView === 'compliance' && (
        <div className="flex flex-col md:flex-row items-center justify-center gap-12">
          <div className="relative flex items-center justify-center" style={{ width: 300, height: 300 }}>
            {market.map((m, idx) => (
              <motion.div
                key={m.id}
                initial={{ scale: 0, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                transition={{ delay: 0.3 + idx * 0.2, type: 'spring', stiffness: 200 }}
                className={`absolute rounded-full border-2 ${colors[idx]} flex items-center justify-center`}
                style={{ width: sizes[idx], height: sizes[idx] }}
              >
                {idx === market.length - 1 && (
                  <div className="text-center">
                    <span className={`text-xs font-mono ${textColors[idx]}`}>{segments[idx]}</span>
                  </div>
                )}
              </motion.div>
            ))}
          </div>
          <div className="space-y-6">
            {market.map((m, idx) => {
              const segKey = segmentKeys[idx] || m.market_segment
              const sourceCount = marketSources[segKey]?.length || 0
              return (
                <motion.div
                  key={m.id}
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.5 + idx * 0.15 }}
                  className="group cursor-pointer"
                  onClick={() => setActiveModal(segKey)}
                >
                  <div className="flex items-center gap-4">
                    <div className={`w-3 h-3 rounded-full ${textColors[idx]} bg-current`} />
                    <div>
                      <div className="flex items-center gap-2">
                        <span className={`text-sm font-bold ${textColors[idx]}`}>{segments[idx]}</span>
                        <span className="text-xs text-white/30">{labels[idx]}</span>
                      </div>
                      <div className="text-2xl font-bold text-white">
                        {m.value_eur >= 1_000_000_000 ? (
                          <AnimatedCounter target={m.value_eur / 1_000_000_000} suffix={lang === 'de' ? ' Mrd. EUR' : 'B EUR'} decimals={1} duration={1500} />
                        ) : m.value_eur >= 1_000_000 ? (
                          <AnimatedCounter target={m.value_eur / 1_000_000} suffix={lang === 'de' ? ' Mio. EUR' : 'M EUR'} decimals={1} duration={1500} />
                        ) : (
                          <AnimatedCounter target={m.value_eur / 1_000} suffix={'k EUR'} decimals={0} duration={1500} />
                        )}
                      </div>
                      <div className="flex items-center gap-3 text-xs">
                        {m.growth_rate_pct > 0 && (
                          <span className="flex items-center gap-1 text-emerald-400">
                            <TrendingUp className="w-3 h-3" />
                            {m.growth_rate_pct}% p.a.
                          </span>
                        )}
                        <span className="text-white/40">{i.market.source}: {m.source}</span>
                      </div>
                      <p className="text-[10px] text-indigo-400/60 group-hover:text-indigo-400 transition-colors mt-0.5">
                        {sourceCount} {lang === 'de' ? (sourceCount === 1 ? 'Quelle' : 'Quellen') : (sourceCount === 1 ? 'source' : 'sources')}
                        {' · '}{lang === 'de' ? 'Klicken für Details' : 'Click for details'}
                      </p>
                    </div>
                  </div>
                </motion.div>
              )
            })}
          </div>
        </div>
      )}

      {/* Pentesting Market */}
      {marketView === 'pentesting' && (
        <div className="flex flex-col md:flex-row items-center justify-center gap-12">
          <div className="relative flex items-center justify-center" style={{ width: 300, height: 300 }}>
            {PENTEST_MARKET.map((pm, idx) => (
              <motion.div
                key={pm.segment}
                initial={{ scale: 0, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                transition={{ delay: 0.3 + idx * 0.2, type: 'spring', stiffness: 200 }}
                className={`absolute rounded-full border-2 ${
                  idx === 0 ? 'border-red-500/30 bg-red-500/5' :
                  idx === 1 ? 'border-orange-500/30 bg-orange-500/5' :
                  'border-yellow-500/30 bg-yellow-500/5'
                } flex items-center justify-center`}
                style={{ width: sizes[idx], height: sizes[idx] }}
              >
                {idx === PENTEST_MARKET.length - 1 && (
                  <div className="text-center">
                    <span className="text-xs font-mono text-yellow-400">{pm.segment}</span>
                  </div>
                )}
              </motion.div>
            ))}
          </div>
          <div className="space-y-6">
            {PENTEST_MARKET.map((pm, idx) => {
              const ptColors = ['text-red-400', 'text-orange-400', 'text-yellow-400']
              const sourceCount = pentestMarketSources[pm.segment]?.length || 0
              return (
                <motion.div
                  key={pm.segment}
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.5 + idx * 0.15 }}
                  className="group cursor-pointer"
                  onClick={() => setActiveModal(pm.segment)}
                >
                  <div className="flex items-center gap-4">
                    <div className={`w-3 h-3 rounded-full ${ptColors[idx]} bg-current`} />
                    <div>
                      <div className="flex items-center gap-2">
                        <span className={`text-sm font-bold ${ptColors[idx]}`}>{pm.segment}</span>
                        <span className="text-xs text-white/30">{pm.label[lang]}</span>
                      </div>
                      <div className="text-2xl font-bold text-white">
                        {pm.value_eur >= 1_000_000_000 ? (
                          <AnimatedCounter target={pm.value_eur / 1_000_000_000} suffix={lang === 'de' ? ' Mrd. EUR' : 'B EUR'} decimals={1} duration={1500} />
                        ) : pm.value_eur >= 1_000_000 ? (
                          <AnimatedCounter target={pm.value_eur / 1_000_000} suffix={lang === 'de' ? ' Mio. EUR' : 'M EUR'} decimals={1} duration={1500} />
                        ) : (
                          <AnimatedCounter target={pm.value_eur / 1_000} suffix={'k EUR'} decimals={0} duration={1500} />
                        )}
                      </div>
                      <div className="flex items-center gap-3 text-xs">
                        {pm.growth_rate_pct > 0 && (
                          <span className="flex items-center gap-1 text-emerald-400">
                            <TrendingUp className="w-3 h-3" />
                            {pm.growth_rate_pct}% p.a.
                          </span>
                        )}
                        <span className="text-white/40">{i.market.source}: {pm.source}</span>
                      </div>
                      <p className="text-[10px] text-red-400/60 group-hover:text-red-400 transition-colors mt-0.5">
                        {sourceCount} {lang === 'de' ? (sourceCount === 1 ? 'Quelle' : 'Quellen') : (sourceCount === 1 ? 'source' : 'sources')}
                        {' · '}{lang === 'de' ? 'Klicken für Details' : 'Click for details'}
                      </p>
                    </div>
                  </div>
                </motion.div>
              )
            })}
          </div>
        </div>
      )}

      {/* Source Modals — both compliance and pentesting */}
      {segmentKeys.map((seg) => (
        <SourceModal
          key={`c-${seg}`}
          isOpen={activeModal === seg}
          onClose={() => setActiveModal(null)}
          segment={seg}
          lang={lang}
          sources={activeSources}
        />
      ))}
    </div>
  )
}
