import { Language, PitchMarket, PitchTeamMember, PitchMilestone, PitchFunding } from '@/lib/types'
import { Page, Callout, COLORS, StatLine } from './PrintLayout'
import { ComparisonBars, DonutChart } from './PrintCharts'
import {
  Briefcase, RefreshCw, Handshake, Scale, Lightbulb,
  Code, TrendingUp, CreditCard, ShieldCheck, Cpu,
} from 'lucide-react'

interface SlideBase { lang: Language; pageNum: number; totalPages: number; versionName: string }

function fmtEur(v: number, de: boolean) {
  if (v >= 1e9) return de ? `${(v / 1e9).toFixed(1).replace('.', ',')} Mrd. €` : `€${(v / 1e9).toFixed(1)}B`
  if (v >= 1e6) return de ? `${(v / 1e6).toFixed(0)} Mio. €` : `€${(v / 1e6).toFixed(0)}M`
  if (v >= 1e3) return de ? `${(v / 1e3).toFixed(0)}k €` : `€${(v / 1e3).toFixed(0)}k`
  return de ? `${v} €` : `€${v}`
}

/* ===== MARKET ===== */

export function PrintMarketPage({ market, lang, pageNum, totalPages, versionName }: SlideBase & { market: PitchMarket[] }) {
  const de = lang === 'de'
  const tam = market.find(m => m.market_segment === 'TAM')
  const sam = market.find(m => m.market_segment === 'SAM')
  const som = market.find(m => m.market_segment === 'SOM')

  // Fallbacks if data missing
  const tamValue = tam?.value_eur ?? 340_000_000_000
  const samValue = sam?.value_eur ?? 48_000_000_000
  const somValue = som?.value_eur ?? 2_100_000_000
  const cards = [
    { key: 'TAM', value: fmtEur(tamValue, de), growth: tam?.growth_rate_pct ?? 14, accent: 'violet' as const,
      desc: de ? 'Globaler Compliance- und GRC-Markt, alle Branchen, alle Größen.' : 'Global compliance and GRC market, all industries, all sizes.' },
    { key: 'SAM', value: fmtEur(samValue, de), growth: sam?.growth_rate_pct ?? 18, accent: 'violet-soft' as const,
      desc: de ? 'DACH + EU: regulierte Branchen, KMU und Enterprise.' : 'DACH + EU: regulated industries, SMB and enterprise.' },
    { key: 'SOM', value: fmtEur(somValue, de), growth: som?.growth_rate_pct ?? 25, accent: 'amber' as const, core: true,
      desc: de ? 'Anlagen- und Maschinenbau DACH, unser Kernsegment.' : 'Machine and plant manufacturing DACH, our core segment.' },
  ]

  // SVG nested-circles geometry — viewBox unitless, render up to ~130mm wide
  const CX = 65, CY = 65, R_TAM = 60, R_SAM = 36, R_SOM = 14

  return (
    <Page kicker="09" section={de ? 'MARKT' : 'MARKET'} title={de ? 'Compliance & Code-Security für produzierende Unternehmen.' : 'Compliance & code security for manufacturing companies.'} subtitle={de ? 'Validierter Markt: Top-10 Compliance-Anbieter erwirtschaften >$1,1 Mrd. ARR. Kein Anbieter bedient den Maschinenbau spezifisch.' : 'Validated market: top-10 compliance vendors generate >$1.1B ARR. No vendor specifically serves manufacturing.'} pageNum={pageNum} totalPages={totalPages} versionName={versionName} footnote="Sacra · Bitkom Cloud Monitor 2024 · DIHK 2024 · VDMA · Statista">

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.05fr', gap: '10mm', flex: 1, minHeight: 0 }}>
        {/* LEFT: nested-circles diagram */}
        <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '3mm' }}>{de ? 'Marktdimensionierung' : 'Market sizing'}</div>
          <div style={{ flex: 1, minHeight: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg viewBox="0 0 130 130" style={{ width: '100%', maxWidth: '130mm', height: 'auto', display: 'block' }} aria-hidden>
              <circle cx={CX} cy={CY} r={R_TAM} fill={COLORS.violet50} stroke={COLORS.violet400} strokeWidth="0.6" />
              <circle cx={CX} cy={CY} r={R_SAM} fill={COLORS.violet100} stroke={COLORS.violet500} strokeWidth="0.7" />
              <circle cx={CX} cy={CY} r={R_SOM} fill={COLORS.amber50} stroke={COLORS.amber600} strokeWidth="0.9" />
              <text x={CX} y={CY - R_TAM + 7} textAnchor="middle" fontSize="3.2" fontFamily="'JetBrains Mono', ui-monospace, monospace" fontWeight={700} letterSpacing="0.18em" fill={COLORS.violet700}>TAM</text>
              <text x={CX} y={CY - R_TAM + 11.5} textAnchor="middle" fontSize="3.6" fontWeight={700} fill={COLORS.slate700}>{fmtEur(tamValue, de)}</text>
              <text x={CX} y={CY - R_SAM + 6} textAnchor="middle" fontSize="3" fontFamily="'JetBrains Mono', ui-monospace, monospace" fontWeight={700} letterSpacing="0.18em" fill={COLORS.violet800}>SAM</text>
              <text x={CX} y={CY - R_SAM + 10} textAnchor="middle" fontSize="3.4" fontWeight={700} fill={COLORS.slate800}>{fmtEur(samValue, de)}</text>
              <text x={CX} y={CY - 1.2} textAnchor="middle" fontSize="2.8" fontFamily="'JetBrains Mono', ui-monospace, monospace" fontWeight={700} letterSpacing="0.18em" fill={COLORS.amber700}>SOM</text>
              <text x={CX} y={CY + 3} textAnchor="middle" fontSize="3.4" fontWeight={800} fill={COLORS.slate900}>{fmtEur(somValue, de)}</text>
            </svg>
          </div>
          <div style={{ marginTop: '3mm', fontSize: '7.5pt', color: COLORS.slate500, lineHeight: 1.4, textAlign: 'center' }}>
            {de ? 'Verschachtelte Marktanteile (TAM ⊃ SAM ⊃ SOM)' : 'Nested market shares (TAM ⊃ SAM ⊃ SOM)'}
          </div>
        </div>

        {/* RIGHT: stacked info cards + callout */}
        <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0, gap: '3.5mm' }}>
          {cards.map((c) => {
            const isAmber = c.accent === 'amber'
            const isSoft = c.accent === 'violet-soft'
            const stroke = isAmber ? COLORS.amber600 : isSoft ? COLORS.violet500 : COLORS.violet700
            const bg = isAmber ? COLORS.amber50 : isSoft ? COLORS.violet50 : 'transparent'
            const kickerColor = isAmber ? COLORS.amber700 : COLORS.violet700
            const valueColor = isAmber ? COLORS.amber700 : COLORS.slate900
            return (
              <div key={c.key} style={{ borderLeft: `3px solid ${stroke}`, background: bg, padding: '3mm 4mm', display: 'flex', flexDirection: 'column', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '3mm' }}>
                  <span style={{ fontFamily: "'JetBrains Mono', ui-monospace, monospace", fontSize: '7.5pt', fontWeight: 700, letterSpacing: '0.18em', color: kickerColor, textTransform: 'uppercase' }}>{c.key}</span>
                  {c.core && (<span style={{ fontSize: '7pt', fontWeight: 700, color: COLORS.amber700, background: '#fff', border: `1px solid ${COLORS.amber600}`, padding: '0.5mm 1.5mm', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{de ? '← unser Kernmarkt' : '← our core market'}</span>)}
                </div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: '3mm', marginTop: '1mm' }}>
                  <div style={{ fontSize: '22pt', fontWeight: 800, color: valueColor, lineHeight: 1, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>{c.value}</div>
                  <div style={{ fontSize: '7.5pt', color: COLORS.slate500, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>+{c.growth}% CAGR</div>
                </div>
                <div style={{ marginTop: '1.5mm', fontSize: '8pt', color: COLORS.slate700, lineHeight: 1.4 }}>{c.desc}</div>
              </div>
            )
          })}

          <div style={{ marginTop: 'auto' }}>
            <Callout tone="accent" label={de ? 'Warum Maschinenbau zuerst' : 'Why manufacturing first'}>
              {de
                ? 'Höchste Regulierungsdichte (DSGVO + AI Act + CRA + Maschinen-VO + ProdSG + LkSG) bei gleichzeitig kleinem Compliance-Team. Klare Schmerzpunkte. Bekannte Vertriebskanäle (VDMA, IHK, Messen).'
                : 'Highest regulation density (GDPR + AI Act + CRA + Machinery Reg. + ProdSG + LkSG) with simultaneously small compliance teams. Clear pain points. Known sales channels (VDMA, Chamber of Commerce, fairs).'}
            </Callout>
          </div>
        </div>
      </div>
    </Page>
  )
}

/* ===== MILESTONES / TRACTION ===== */

const MS_DE = [
  { d: 'Okt 2025', t: 'Gründerzuschuss & IHK Konstanz', s: 'done' },
  { d: '11 Nov 2025', t: 'DPMA-Markenanmeldung BreakPilot', s: 'done' },
  { d: '21 Nov 2025', t: 'Domain-Portfolio (.com, .de, .ai + Typo)', s: 'done' },
  { d: 'Jan 2026', t: 'Plattform-Entwicklung gestartet (500K+ LoC)', s: 'done' },
  { d: '27 Mär 2026', t: 'DPMA-Markeneintragung BreakPilot', s: 'done' },
  { d: 'Apr 2026', t: 'RAG mit 375+ Dokumenten · 25k+ Controls', s: 'done' },
  { d: '01 Mai 2026', t: 'EUIPO-Markenanmeldung (EU-weit)', s: 'next' },
  { d: 'Aug 2026', t: 'GmbH-Gründung Breakpilot COMPLAI', s: 'planned' },
  { d: 'Aug 2026', t: '2 zahlende Pilotkunden, erste Umsätze', s: 'planned' },
  { d: 'Q3 2026', t: 'Public Beta-Launch', s: 'planned' },
]
const MS_EN = [
  { d: 'Oct 2025', t: 'Founder grant & IHK Konstanz', s: 'done' },
  { d: '11 Nov 2025', t: 'DPMA trademark filing BreakPilot', s: 'done' },
  { d: '21 Nov 2025', t: 'Domain portfolio (.com, .de, .ai + typos)', s: 'done' },
  { d: 'Jan 2026', t: 'Platform development started (500K+ LoC)', s: 'done' },
  { d: '27 Mar 2026', t: 'DPMA trademark registration', s: 'done' },
  { d: 'Apr 2026', t: 'RAG with 375+ documents · 25k+ controls', s: 'done' },
  { d: '01 May 2026', t: 'EUIPO trademark filing (EU-wide)', s: 'next' },
  { d: 'Aug 2026', t: 'GmbH incorporation Breakpilot COMPLAI', s: 'planned' },
  { d: 'Aug 2026', t: '2 paying pilot customers, first revenue', s: 'planned' },
  { d: 'Q3 2026', t: 'Public beta launch', s: 'planned' },
]

export function PrintMilestonesPage({ milestones, lang, pageNum, totalPages, versionName }: SlideBase & { milestones: PitchMilestone[] }) {
  void milestones // we use the curated list above
  const de = lang === 'de'
  const items = de ? MS_DE : MS_EN
  const dotFor = (s: string) => s === 'done' ? COLORS.emerald600 : s === 'next' ? COLORS.amber600 : COLORS.slate400

  return (
    <Page kicker="11" section={de ? 'TRACTION & MEILENSTEINE' : 'TRACTION & MILESTONES'} title={de ? 'Was wir bereits erreicht haben, und was als Nächstes kommt.' : 'What we have achieved, and what comes next.'} subtitle={de ? 'Wir gehen mit Substanz: bereits gebaut, nicht nur geplant. 500.000+ Zeilen Code, 25.000+ Controls, Markenschutz gesichert.' : 'We arrive with substance: built, not just planned. 500,000+ lines of code, 25,000+ controls, trademark secured.'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>

      {/* Top KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '4mm', padding: '4mm 0', borderTop: `1px solid ${COLORS.slate200}`, borderBottom: `1px solid ${COLORS.slate200}` }}>
        {[
          { n: '500K+', l: de ? 'Lines of Code' : 'Lines of code' },
          { n: '25.000+', l: de ? 'Atomare Controls' : 'Atomic controls' },
          { n: '385', l: de ? 'Gesetze im RAG' : 'Laws in RAG' },
          { n: '12', l: de ? 'Compliance-Module' : 'Compliance modules' },
          { n: '2', l: de ? 'Pilotkunden (Aug 26)' : 'Pilot customers (Aug 26)' },
        ].map((k, i) => (
          <div key={i}>
            <div style={{ fontSize: '20pt', fontWeight: 800, color: COLORS.indigo600, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{k.n}</div>
            <div style={{ fontSize: '7pt', color: COLORS.slate500, marginTop: '1.5mm', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>{k.l}</div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: '5mm', flex: 1, minHeight: 0, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6mm' }}>
        <div>
          <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '2mm' }}>{de ? 'Erreicht (Okt 2025 – Apr 2026)' : 'Achieved (Oct 2025 – Apr 2026)'}</div>
          {items.filter(i => i.s === 'done').map((m, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: '4mm', padding: '2mm 0', borderBottom: `1px solid ${COLORS.slate100}` }}>
              <div style={{ flexShrink: 0, marginTop: '2pt', width: '6pt', height: '6pt', borderRadius: '50%', background: dotFor(m.s), WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: '7.5pt', color: COLORS.slate500, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{m.d}</div>
                <div style={{ fontSize: '9pt', color: COLORS.slate900, fontWeight: 600, lineHeight: 1.4, marginTop: '0.5mm' }}>{m.t}</div>
              </div>
            </div>
          ))}
        </div>

        <div>
          <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '2mm' }}>{de ? 'Nächste 4 Monate' : 'Next 4 months'}</div>
          {items.filter(i => i.s !== 'done').map((m, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: '4mm', padding: '2mm 0', borderBottom: `1px solid ${COLORS.slate100}` }}>
              <div style={{ flexShrink: 0, marginTop: '2pt', width: '6pt', height: '6pt', borderRadius: '50%', background: dotFor(m.s), border: m.s === 'next' ? 'none' : `1px solid ${COLORS.slate400}`, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: '7.5pt', color: COLORS.slate500, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{m.d} &middot; {m.s === 'next' ? (de ? 'Nächster Schritt' : 'Next step') : (de ? 'Geplant' : 'Planned')}</div>
                <div style={{ fontSize: '9pt', color: COLORS.slate900, fontWeight: 600, lineHeight: 1.4, marginTop: '0.5mm' }}>{m.t}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </Page>
  )
}

/* ===== TEAM ===== */

// Tuple shape: [LucideIcon, de_label, en_label]
type TeamBullet = [typeof Briefcase, string, string]

const TEAM_INFO: Array<{ tagline: [string, string]; bullets: TeamBullet[] }> = [
  {
    tagline: [
      'Diplom-Ökonom mit 20+ Jahren Industrie- und Digitalisierungs-Erfahrung.',
      'Business economist with 20+ years in industry and digital transformation.',
    ],
    bullets: [
      [Briefcase, '20+ Jahre Industrie, Strategie & Digitalisierung', '20+ yrs industry, strategy & digital transformation'],
      [RefreshCw, 'Aufbau IoT-, Blockchain- & KI-Plattformen', 'Built IoT, blockchain & AI platforms'],
      [Handshake, 'M&A: 4 Übernahmen & Beteiligungen geführt', 'M&A: led 4 acquisitions & investments'],
      [Scale, 'Regulatorik: DSGVO, MiCAR, CRA, Data Act', 'Regulatory: GDPR, MiCAR, CRA, Data Act'],
      [Lightbulb, '12 erteilte Patente (Erfinder/Miterfinder)', '12 granted patents (inventor / co-inventor)'],
    ],
  },
  {
    tagline: [
      'Engineering Leader mit 15+ Jahren in Fintech, Web3 und Enterprise-KI.',
      'Engineering leader with 15+ years across fintech, Web3 and enterprise AI.',
    ],
    bullets: [
      [Code, '15+ Jahre Engineering Leadership — Fintech, Web3, KI', '15+ yrs engineering leadership — fintech, Web3, AI'],
      [TrendingUp, 'Engineering-Org skaliert: 6 → 60 in 18 Monaten', 'Scaled engineering org: 6 → 60 in 18 months'],
      [CreditCard, 'ETOPay SaaS-Payment-Infrastruktur entwickelt', 'Built ETOPay SaaS payment infrastructure'],
      [ShieldCheck, 'MiCA-Compliance-Strategie ViviSwap', 'MiCA compliance strategy for ViviSwap'],
      [Cpu, 'Embedded Rust (Cortex-M) + Full-Stack TypeScript', 'Embedded Rust (Cortex-M) + full-stack TypeScript'],
    ],
  },
]

export function PrintTeamPage({ team, lang, pageNum, totalPages, versionName }: SlideBase & { team: PitchTeamMember[] }) {
  const de = lang === 'de'
  const members = team && team.length ? team : [
    { id: 1, name: 'Benjamin Bönisch', role_de: 'CEO & Co-Founder', role_en: 'CEO & Co-Founder', bio_de: '', bio_en: '', equity_pct: 37.3, expertise: ['B2B Sales', 'Go-to-Market', 'Manufacturing', 'Operations'], linkedin_url: '', photo_url: '' },
    { id: 2, name: 'Sharang Parnerkar', role_de: 'CTO & Co-Founder', role_en: 'CTO & Co-Founder', bio_de: '', bio_en: '', equity_pct: 37.3, expertise: ['AI Infrastructure', 'Distributed Systems', 'RAG', 'Go/Python/TypeScript'], linkedin_url: '', photo_url: '' },
  ]

  return (
    <Page kicker="13" section={de ? 'TEAM' : 'TEAM'} title={de ? 'Gründer mit Domain-Expertise.' : 'Founders with domain expertise.'} subtitle={de ? 'Komplementäres Gründerduo: Vertrieb + Engineering. Beide haben bereits skaliert. Beide kennen den Markt.' : 'Complementary founding duo: sales + engineering. Both have scaled. Both know the market.'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8mm', flex: 1, minHeight: 0 }}>
        {[0, 1].map(idx => {
          const m = members[idx]
          if (!m) return null
          const info = TEAM_INFO[idx]
          // Icon tile palette: violet for first founder, amber for second
          const tileBg = idx === 0 ? COLORS.violet50 : COLORS.amber50
          const tileColor = idx === 0 ? COLORS.violet700 : COLORS.amber700
          return (
            <div key={idx} style={{ border: `1px solid ${COLORS.slate200}`, borderTop: `3px solid ${COLORS.indigo600}`, padding: '5mm', display: 'flex', flexDirection: 'column', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
              <div style={{ display: 'flex', gap: '5mm', alignItems: 'flex-start', marginBottom: '4mm' }}>
                {/* Photo */}
                <div style={{ width: '32mm', height: '32mm', flexShrink: 0, border: `1px solid ${COLORS.slate200}`, background: COLORS.slate100, overflow: 'hidden', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
                  {m.photo_url ? (
                    /* eslint-disable-next-line @next/next/no-img-element */
                    <img src={m.photo_url} alt={m.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                  ) : (
                    <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '24pt', fontWeight: 800, color: COLORS.slate400, letterSpacing: '-0.02em' }}>
                      {m.name?.split(' ').map(s => s[0]).slice(0, 2).join('') || '?'}
                    </div>
                  )}
                </div>
                {/* Header text */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: '2mm' }}>
                    <span style={{ fontSize: '7pt', fontWeight: 700, color: COLORS.indigo600, textTransform: 'uppercase', letterSpacing: '0.14em' }}>CO-FOUNDER &middot; {String(idx + 1).padStart(2, '0')} / 02</span>
                    <span style={{ fontSize: '7pt', color: COLORS.slate500, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{(m.equity_pct ?? 37.3).toLocaleString('de-DE')}% Equity</span>
                  </div>
                  <div style={{ fontSize: '18pt', fontWeight: 800, color: COLORS.slate900, lineHeight: 1.05, marginBottom: '1mm', letterSpacing: '-0.015em' }}>{m.name}</div>
                  <div style={{ fontSize: '10pt', fontWeight: 600, color: COLORS.indigo600 }}>{de ? m.role_de : m.role_en}</div>
                </div>
              </div>
              {info && (
                <div style={{ fontSize: '8.5pt', color: COLORS.slate700, fontWeight: 600, lineHeight: 1.4, marginBottom: '3mm' }}>{info.tagline[de ? 0 : 1]}</div>
              )}
              {/* Bulleted skill list with icons */}
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '1.5mm' }}>
                {info?.bullets.map(([IconComp, deLabel, enLabel], bi) => (
                  <div key={bi} style={{ display: 'flex', alignItems: 'flex-start', gap: '3mm' }}>
                    <div style={{ width: '7mm', height: '7mm', flexShrink: 0, background: tileBg, color: tileColor, display: 'flex', alignItems: 'center', justifyContent: 'center', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
                      <IconComp size={13} strokeWidth={2} />
                    </div>
                    <div style={{ flex: 1, fontSize: '9pt', color: COLORS.slate700, lineHeight: 1.4, paddingTop: '1mm' }}>{de ? deLabel : enLabel}</div>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: '4mm', paddingTop: '3mm', borderTop: `1px solid ${COLORS.slate200}` }}>
                <div style={{ fontSize: '7.5pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '2mm' }}>{de ? 'Expertise' : 'Expertise'}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '1.5mm' }}>
                  {(m.expertise || []).map((e, i) => (
                    <span key={i} style={{ fontSize: '8pt', padding: '0.5mm 2mm', background: COLORS.indigo50, color: COLORS.indigo700, fontWeight: 600, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>{e}</span>
                  ))}
                </div>
              </div>
            </div>
          )
        })}
      </div>

      <div style={{ marginTop: '5mm', flexShrink: 0 }}>
        <Callout tone="accent" label={de ? 'Equity-Struktur' : 'Equity structure'}>
          {de
            ? 'Gründer 74,6% · Pre-Seed-Investor 20% · ESOP-Pool 5,4%. Beide Gründer mit Vesting (4 Jahre, 1 Jahr Cliff). Keine Side-Projekte, keine externen Verpflichtungen.'
            : 'Founders 74.6% · Pre-Seed Investor 20% · ESOP pool 5.4%. Both founders with vesting (4 years, 1 year cliff). No side projects, no external commitments.'}
        </Callout>
      </div>
    </Page>
  )
}

/* ===== THE ASK ===== */

function formatTargetDate(raw: string | undefined, de: boolean): string {
  if (!raw) return de ? 'Q3 2026' : 'Q3 2026'
  // Accept ISO timestamps, ISO dates, or already-formatted strings.
  const d = new Date(raw)
  if (isNaN(d.getTime())) return raw
  const months = de
    ? ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez']
    : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  return `${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`
}

function formatFunding(amount: number): string {
  if (amount >= 1_000_000) {
    const m = amount / 1_000_000
    return '€' + (m % 1 === 0 ? m.toFixed(0) : m.toFixed(1)) + 'M'
  }
  return '€' + Math.round(amount / 1_000) + 'k'
}

export function PrintTheAskPage({ funding, lang, pageNum, totalPages, versionName }: SlideBase & { funding: PitchFunding }) {
  const de = lang === 'de'
  const amount = funding?.amount_eur || 400_000
  const instrument = funding?.instrument || (de ? 'Wandeldarlehen' : 'Convertible Loan')
  const isConvertible = (instrument || '').toLowerCase().includes('wandeldarlehen') ||
                        (instrument || '').toLowerCase().includes('convertible') ||
                        (instrument || '').toLowerCase().includes('safe')
  // For equity rounds we display Pre/Post/Investor-Share computed from a 20%
  // assumed investor share. For convertibles those fields don't apply — show
  // typical convertible terms instead (Discount, Maturity, Interest).
  const equityShare = 0.20
  const postMoney = amount / equityShare
  const preMoney = postMoney - amount
  const fmtBig = (n: number) => n >= 1_000_000
    ? '€' + (n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1) + 'M'
    : '€' + Math.round(n / 1_000) + 'k'
  const termTiles: [string, string][] = isConvertible
    ? [
        [de ? 'Funding' : 'Funding', formatFunding(amount)],
        [de ? 'Discount' : 'Discount', '20%'],
        [de ? 'Laufzeit' : 'Maturity', de ? '24 Monate' : '24 months'],
        [de ? 'INVEST-Zuschuss' : 'INVEST grant', '20%'],
      ]
    : [
        [de ? 'Funding' : 'Funding', formatFunding(amount)],
        [de ? 'Pre-Money' : 'Pre-money', fmtBig(preMoney)],
        [de ? 'Post-Money' : 'Post-money', fmtBig(postMoney)],
        [de ? 'Investor-Anteil' : 'Investor share', Math.round(equityShare * 100) + '%'],
      ]
  const useOfFunds = funding?.use_of_funds || [
    { category: 'engineering', percentage: 45, label_de: 'Engineering & Produkt', label_en: 'Engineering & Product' },
    { category: 'sales', percentage: 30, label_de: 'Vertrieb & Marketing', label_en: 'Sales & Marketing' },
    { category: 'hardware', percentage: 10, label_de: 'Infrastruktur & Hardware', label_en: 'Infrastructure & Hardware' },
    { category: 'legal', percentage: 10, label_de: 'Legal & Compliance', label_en: 'Legal & Compliance' },
    { category: 'reserve', percentage: 5, label_de: 'Reserve', label_en: 'Reserve' },
  ]

  return (
    <Page kicker="14" section={de ? 'THE ASK' : 'THE ASK'} title={de ? `${funding?.round_name || 'Pre-Seed'}: ${formatFunding(amount)} via ${instrument}.` : `${funding?.round_name || 'Pre-Seed'}: ${formatFunding(amount)} via ${instrument.toLowerCase()}.`} subtitle={de ? '18 Monate Runway zur Profitabilität. Use of Funds in 5 Buckets. INVEST-Zuschuss 20% rückzahlbar.' : '18-month runway to profitability. Use of funds across 5 buckets. 20% INVEST grant eligible.'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '8mm', flex: 1, minHeight: 0 }}>
        {/* Hero amount */}
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <div style={{ borderLeft: `3px solid ${COLORS.indigo600}`, paddingLeft: '5mm', marginBottom: '6mm' }}>
            <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.indigo600, textTransform: 'uppercase', letterSpacing: '0.12em' }}>{de ? 'Funding' : 'Funding'}</div>
            <div style={{ fontSize: '54pt', fontWeight: 800, color: COLORS.slate900, lineHeight: 1, letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums', marginTop: '2mm' }}>
              {formatFunding(amount)}
            </div>
            <div style={{ fontSize: '10pt', color: COLORS.slate600, marginTop: '3mm' }}>{instrument} &middot; {funding?.round_name || 'Pre-Seed'} &middot; {de ? 'Zielabschluss' : 'Target close'}: {formatTargetDate(funding?.target_date, de)}</div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(' + termTiles.length + ', 1fr)', gap: '4mm' }}>
            {termTiles.map(([label, val], i) => (
              <div key={i} style={{ border: `1px solid ${COLORS.slate200}`, padding: '3mm' }}>
                <div style={{ fontSize: '7.5pt', color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>{label}</div>
                <div style={{ fontSize: '16pt', fontWeight: 800, color: COLORS.slate900, marginTop: '1mm', fontVariantNumeric: 'tabular-nums' }}>{val}</div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 'auto' }}>
            <Callout tone="accent" label={de ? 'Was wir damit erreichen' : 'What this gets us'}>
              {de
                ? '18 Monate Runway · GmbH-Gründung · Engineering-Team auf 5 erweitert · 50–100 Kunden onboarded · ARR €1,5–2,5M in 18 Monaten · Vorbereitung Series A.'
                : '18-month runway · GmbH incorporated · engineering team scaled to 5 · 50–100 customers onboarded · ARR €1.5–2.5M in 18 months · Series A readiness.'}
            </Callout>
          </div>
        </div>

        {/* Use of funds */}
        <div>
          <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '3mm' }}>{de ? 'Use of Funds' : 'Use of funds'}</div>
          {(() => {
            const palette = [COLORS.indigo600, COLORS.indigo500, COLORS.amber600, COLORS.slate600, COLORS.slate400]
            return (
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: '6mm' }}>
                <div style={{ flexShrink: 0 }}>
                  <DonutChart
                    size={48}
                    thickness={9}
                    segments={useOfFunds.map((u, i) => ({ label: de ? u.label_de : u.label_en, pct: u.percentage, color: palette[i % palette.length] }))}
                  />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  {useOfFunds.map((u, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '3mm', padding: '2mm 0', borderBottom: `1px solid ${COLORS.slate100}` }}>
                      <div style={{ width: '3mm', height: '3mm', background: palette[i % palette.length], flexShrink: 0, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
                      <div style={{ flex: 1, fontSize: '8.5pt', color: COLORS.slate800, fontWeight: 500 }}>{de ? u.label_de : u.label_en}</div>
                      <div style={{ fontSize: '11pt', fontWeight: 800, color: COLORS.slate900, fontVariantNumeric: 'tabular-nums', minWidth: '12mm', textAlign: 'right' }}>{u.percentage}%</div>
                      <div style={{ fontSize: '7.5pt', color: COLORS.slate500, fontVariantNumeric: 'tabular-nums', minWidth: '14mm', textAlign: 'right' }}>€{(amount * u.percentage / 100 / 1000).toFixed(0)}k</div>
                    </div>
                  ))}
                </div>
              </div>
            )
          })()}
        </div>
      </div>
    </Page>
  )
}

/* ===== CUSTOMER SAVINGS ===== */

export function PrintCustomerSavingsPage({ lang, pageNum, totalPages, versionName }: SlideBase) {
  const de = lang === 'de'
  const items = [
    { l: de ? 'Pentests' : 'Pentests', today: 15000, bp: 13000 },
    { l: de ? 'CE-SW-Risiko' : 'CE software risk', today: 12000, bp: 9000 },
    { l: de ? 'Compliance-Zeit' : 'Compliance time', today: 18000, bp: 15000 },
    { l: de ? 'Audit-Vorber.' : 'Audit prep', today: 9000, bp: 9000 },
    { l: de ? 'Legal (DSGVO/AI Act)' : 'Legal (GDPR/AI Act)', today: 8000, bp: 5000 },
    { l: de ? 'Auditmanager-Software' : 'Audit manager SW', today: 5000, bp: 0 },
    { l: de ? 'Schulungen extern' : 'External training', today: 4000, bp: 4000 },
  ]
  const totalToday = items.reduce((s, i) => s + i.today, 0)
  const totalSaved = items.reduce((s, i) => s + i.bp, 0)
  const totalBpCost = 25000

  return (
    <Page kicker="15" section={de ? 'KUNDENERSPARNIS' : 'CUSTOMER SAVINGS'} title={de ? 'Kunden sparen mehr als sie zahlen, vom ersten Tag an.' : 'Customers save more than they pay, from day one.'} subtitle={de ? 'Detaillierte Aufschlüsselung für ein typisches KMU (50 MA) im ersten Jahr. €25k Kosten, €55k Ersparnis.' : 'Detailed breakdown for a typical SME (50 emp.) in year one. €25k cost, €55k savings.'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>

      {/* Big stat header */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '4mm', padding: '4mm 0', borderTop: `1px solid ${COLORS.slate200}`, borderBottom: `1px solid ${COLORS.slate200}`, marginBottom: '5mm' }}>
        {[
          { l: de ? 'Heute (ohne BP)' : 'Today (without BP)', v: '€' + (totalToday / 1000).toFixed(0) + 'k', tone: COLORS.red700 },
          { l: de ? 'BreakPilot Pro / Jahr' : 'BreakPilot Pro / year', v: '€' + (totalBpCost / 1000).toFixed(0) + 'k', tone: COLORS.indigo600 },
          { l: de ? 'Ersparnis / KMU' : 'Savings / SME', v: '€' + (totalSaved / 1000).toFixed(0) + 'k', tone: COLORS.emerald700 },
          { l: de ? 'Netto-Effekt' : 'Net effect', v: '+€' + ((totalSaved - totalBpCost) / 1000).toFixed(0) + 'k', tone: COLORS.emerald700 },
        ].map((k, i) => (
          <div key={i}>
            <div style={{ fontSize: '26pt', fontWeight: 800, color: k.tone, lineHeight: 1, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>{k.v}</div>
            <div style={{ fontSize: '7.5pt', color: COLORS.slate500, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', marginTop: '1.5mm' }}>{k.l}</div>
          </div>
        ))}
      </div>

      {/* Bar comparison */}
      <div style={{ flex: 1, minHeight: 0, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8mm' }}>
        <div>
          <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '3mm' }}>{de ? 'Heute vs. mit BreakPilot (€/Jahr/KMU)' : 'Today vs. with BreakPilot (€/yr/SME)'}</div>
          <ComparisonBars
            rows={items.map(it => ({
              label: it.l,
              bars: [
                { tone: 'negative', value: it.today, cap: de ? 'Heute' : 'Today' },
                { tone: 'positive', value: it.bp, cap: de ? 'gespart mit BP' : 'saved with BP' },
              ],
            }))}
            formatValue={(n) => '€' + (n / 1000).toFixed(0) + 'k'}
          />
        </div>

        <div>
          <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '3mm' }}>{de ? 'Ersparnis-Aufschlüsselung' : 'Savings breakdown'}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '0' }}>
            <StatLine label={de ? 'Pentests (kontinuierlich, inklusive)' : 'Pentests (continuous, included)'} value="€13.000" tone="positive" />
            <StatLine label={de ? 'CE-Risiko (Code-basiert, inkl.)' : 'CE risk (code-based, incl.)'} value="€9.000" tone="positive" />
            <StatLine label={de ? 'Compliance-Zeit (−80%)' : 'Compliance time (−80%)'} value="€15.000" tone="positive" />
            <StatLine label={de ? 'Audit-Vorber. (auf Knopfdruck)' : 'Audit prep (one-click)'} value="€9.000" tone="positive" />
            <StatLine label={de ? 'Legal-Stunden (−60%)' : 'Legal hours (−60%)'} value="€5.000" tone="positive" />
            <StatLine label={de ? 'Schulungen (Academy inkl.)' : 'Training (Academy incl.)'} value="€4.000" tone="positive" />
          </div>

          <div style={{ marginTop: '5mm' }}>
            <Callout tone="negative" label={de ? 'Versteckte Kosten' : 'Hidden costs'}>
              {de
                ? 'Zeit der GF + Compliance-Beauftragten (~30 Tage/Jahr), DSGVO-Bußgelder (bis 4% Jahresumsatz), verlorene RFQs durch fehlende Compliance-Nachweise. Nicht in obigen Zahlen enthalten.'
                : 'Time of management + compliance officer (~30 days/year), GDPR fines (up to 4% annual revenue), lost RFQs from missing compliance evidence. Not included in numbers above.'}
            </Callout>
          </div>
        </div>
      </div>
    </Page>
  )
}
