import { Language, FMResult, FMAssumption } from '@/lib/types'
import { Page, COLORS, Callout, DataTable } from './PrintLayout'
import { BarChart, LineChart, DonutChart } from './PrintCharts'
import { computeAnnualKPIs } from '@/lib/finanzplan/annual-kpis'

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

interface AnnualPLRow {
  year: number
  revenue_eur: number
  cogs_eur: number
  gross_profit_eur: number
  personnel_eur: number
  marketing_eur: number
  infra_eur: number
  ebitda_eur: number
  total_customers: number
  employees_count: number
}

export function aggregateAnnualRows(results: FMResult[]): AnnualPLRow[] {
  const byYear = new Map<number, FMResult[]>()
  for (const r of results) {
    if (!byYear.has(r.year)) byYear.set(r.year, [])
    byYear.get(r.year)!.push(r)
  }
  return Array.from(byYear.entries())
    .sort(([a], [b]) => a - b)
    .map(([year, rows]) => {
      const last = rows[rows.length - 1]
      const revenue = rows.reduce((s, r) => s + r.revenue_eur, 0)
      const cogs = rows.reduce((s, r) => s + r.cogs_eur, 0)
      const personnel = rows.reduce((s, r) => s + r.personnel_eur, 0)
      const marketing = rows.reduce((s, r) => s + r.marketing_eur, 0)
      const infra = rows.reduce((s, r) => s + r.infra_eur, 0)
      const gross = revenue - cogs
      const ebitda = gross - personnel - marketing - infra
      return {
        year, revenue_eur: revenue, cogs_eur: cogs, gross_profit_eur: gross,
        personnel_eur: personnel, marketing_eur: marketing, infra_eur: infra, ebitda_eur: ebitda,
        total_customers: last?.total_customers ?? 0, employees_count: last?.employees_count ?? 0,
      }
    })
}

function fmtEur(n: number, dense = false): string {
  const abs = Math.abs(n)
  const sign = n < 0 ? '−' : ''
  if (abs >= 1e6) return `${sign}${(abs / 1e6).toLocaleString('de-DE', { maximumFractionDigits: dense ? 1 : 2 })}M`
  if (abs >= 1e3) return `${sign}${(abs / 1e3).toLocaleString('de-DE', { maximumFractionDigits: 0 })}k`
  return `${sign}${abs.toLocaleString('de-DE', { maximumFractionDigits: 0 })}`
}

/* ===== FINANZPLAN, PAGE 1: P&L 2026-2030 ===== */

export function PrintFinanzplanPage1({ fmResults, lang, pageNum, totalPages, versionName }: SlideBase & { fmResults: FMResult[] }) {
  const de = lang === 'de'
  const rows = aggregateAnnualRows(fmResults)
  if (rows.length === 0) {
    return (
      <Page kicker="17" section={de ? 'ANHANG · FINANZPLAN · 1/2' : 'APPENDIX · FINANCIAL PLAN · 1/2'} title={de ? 'Finanzplan nicht verfügbar' : 'Financial plan unavailable'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>
        <p style={{ fontSize: '10pt', color: COLORS.slate600 }}>{de ? 'Keine Finanzdaten vorhanden. Bitte Base-Case-Szenario auswählen.' : 'No financial data available. Please select base-case scenario.'}</p>
      </Page>
    )
  }
  const years = rows.map(r => r.year)
  const dataRow = (label: string, values: number[], bold = false, sign: '+' | '-' | '' = '') => {
    const cells: (string | React.ReactNode)[] = [label]
    values.forEach(v => cells.push(<span style={{ fontWeight: bold ? 800 : 500, color: bold ? COLORS.slate900 : COLORS.slate700, fontVariantNumeric: 'tabular-nums' }}>{sign === '-' ? `(${fmtEur(v)})` : fmtEur(v)}</span>))
    return cells
  }
  const breakEvenYear = rows.find(r => r.ebitda_eur > 0)?.year

  return (
    <Page kicker="17" section={de ? 'ANHANG · FINANZPLAN · 1/2' : 'APPENDIX · FINANCIAL PLAN · 1/2'} title={de ? 'Gewinn- und Verlustrechnung 2026–2030.' : 'Profit & Loss Statement 2026–2030.'} subtitle={de ? 'Base-Case-Szenario · alle Werte in EUR · konsolidierte Jahreswerte · Break-Even erwartet ' + (breakEvenYear ?? 'Q3 2029') : 'Base-case scenario · all values in EUR · consolidated annual values · break-even expected ' + (breakEvenYear ?? 'Q3 2029')} pageNum={pageNum} totalPages={totalPages} versionName={versionName} footnote={de ? 'In Klammern () = Kosten · Base-Case · L-Bank Finanzplan-Mapping (SKR04-Klassen 4/5/6/7) · Stand: ' + versionName : 'Parentheses () = costs · Base case · L-Bank financial plan mapping (SKR04 classes 4/5/6/7) · As of: ' + versionName}>

      <DataTable
        cols={[
          { header: de ? 'Position' : 'Position', width: '24%' },
          ...years.map(y => ({ header: String(y), numeric: true, width: '13%' as string })),
          { header: 'CAGR', numeric: true, width: '11%' as string },
        ]}
        rows={[
          dataRow(de ? 'Umsatz (SaaS)' : 'Revenue (SaaS)', rows.map(r => r.revenue_eur), true, '+').concat([
            rows[0].revenue_eur > 0 ? `+${Math.round((Math.pow(rows[rows.length - 1].revenue_eur / Math.max(rows[0].revenue_eur, 1), 1 / (rows.length - 1)) - 1) * 100)}%` : '—',
          ]),
          dataRow(de ? 'Infrastruktur (Cloud/LLM)' : 'Infrastructure (Cloud/LLM)', rows.map(r => r.infra_eur), false, '-').concat(['']),
          dataRow(de ? 'Marketing & Vertrieb' : 'Marketing & Sales', rows.map(r => r.marketing_eur), false, '-').concat(['']),
          dataRow(de ? 'Personal (inkl. GF)' : 'Personnel (incl. C-suite)', rows.map(r => r.personnel_eur), false, '-').concat(['']),
          dataRow('COGS (5xxx)', rows.map(r => r.cogs_eur), false, '-').concat(['']),
          [<strong style={{ color: COLORS.slate900 }} key="ge">{de ? 'Gesamtaufwand' : 'Total OpEx'}</strong>,
            ...rows.map(r => <strong style={{ color: COLORS.slate900, fontVariantNumeric: 'tabular-nums' }}>({fmtEur(r.cogs_eur + r.personnel_eur + r.marketing_eur + r.infra_eur)})</strong>),
            '',
          ],
          [<strong style={{ color: COLORS.slate900 }} key="eb">EBITDA</strong>,
            ...rows.map(r => (
              <strong style={{ color: r.ebitda_eur >= 0 ? COLORS.emerald700 : COLORS.red700, fontVariantNumeric: 'tabular-nums', fontWeight: 800 }}>{fmtEur(r.ebitda_eur)}</strong>
            )),
            '',
          ],
          [de ? 'EBITDA-Marge' : 'EBITDA margin',
            ...rows.map(r => <span style={{ color: r.ebitda_eur >= 0 ? COLORS.emerald700 : COLORS.red700, fontVariantNumeric: 'tabular-nums' }}>{r.revenue_eur > 0 ? Math.round(r.ebitda_eur / r.revenue_eur * 100) + '%' : '—'}</span>),
            '',
          ],
          [<span style={{ fontWeight: 600 }} key="mh">───</span>, ...years.map(() => ''), ''],
          [de ? 'Kunden (Dez)' : 'Customers (Dec)', ...rows.map(r => r.total_customers.toLocaleString('de-DE')), ''],
          [de ? 'Mitarbeiter (Dez)' : 'Employees (Dec)', ...rows.map(r => r.employees_count.toLocaleString('de-DE')), ''],
          [de ? 'Umsatz / Mitarbeiter' : 'Revenue / employee',
            ...rows.map(r => r.employees_count > 0 ? fmtEur(Math.round(r.revenue_eur / r.employees_count)) : '—'),
            '',
          ],
        ]}
        highlightFirstCol
      />

      <div style={{ marginTop: '5mm', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '4mm', flexShrink: 0 }}>
        {[
          { l: de ? 'Umsatz 2030' : 'Revenue 2030', v: fmtEur(rows[rows.length - 1].revenue_eur, true), tone: COLORS.indigo600 },
          { l: 'EBITDA 2030', v: fmtEur(rows[rows.length - 1].ebitda_eur, true), tone: rows[rows.length - 1].ebitda_eur >= 0 ? COLORS.emerald700 : COLORS.red700 },
          { l: de ? 'Break-Even' : 'Break-even', v: String(breakEvenYear ?? 'Q3 2029'), tone: COLORS.emerald700 },
          { l: de ? 'Kunden 2030' : 'Customers 2030', v: rows[rows.length - 1].total_customers.toLocaleString('de-DE'), tone: COLORS.slate900 },
        ].map((k, i) => (
          <div key={i} style={{ border: `1px solid ${COLORS.slate200}`, padding: '3mm' }}>
            <div style={{ fontSize: '7pt', color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>{k.l}</div>
            <div style={{ fontSize: '18pt', fontWeight: 800, color: k.tone, lineHeight: 1, fontVariantNumeric: 'tabular-nums', marginTop: '1.5mm' }}>{k.v}</div>
          </div>
        ))}
      </div>
    </Page>
  )
}

/* ===== FINANZPLAN, PAGE 2: KPI dashboard + charts ===== */

export function PrintFinanzplanPage2({ fmResults, lang, pageNum, totalPages, versionName }: SlideBase & { fmResults: FMResult[] }) {
  const de = lang === 'de'
  const kpis = computeAnnualKPIs(fmResults)
  if (kpis.length === 0) {
    return <Page kicker="17" section={de ? 'ANHANG · FINANZPLAN · 2/2' : 'APPENDIX · FINANCIAL PLAN · 2/2'} title={de ? 'KPI-Dashboard nicht verfügbar' : 'KPI dashboard unavailable'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>
      <p style={{ fontSize: '10pt', color: COLORS.slate600 }}>{de ? 'Keine Finanzdaten vorhanden.' : 'No financial data available.'}</p>
    </Page>
  }

  const fmtM = (n: number) => '€' + (n / 1e6).toFixed(1) + 'M'
  const fmtK = (n: number) => '€' + (n / 1e3).toFixed(0) + 'k'
  const pickFmt = (max: number) => max >= 1e6 ? fmtM : fmtK

  return (
    <Page kicker="17" section={de ? 'ANHANG · FINANZPLAN · 2/2' : 'APPENDIX · FINANCIAL PLAN · 2/2'} title={de ? 'KPI-Dashboard und Wachstumskurve.' : 'KPI dashboard and growth trajectory.'} subtitle={de ? '19 KPIs pro Jahr aus den fp_*-Tabellen abgeleitet. Keine hardcodierten Werte. Base-Case-Szenario.' : '19 KPIs per year derived from fp_* tables. No hardcoded values. Base-case scenario.'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>

      {/* Compact KPI table */}
      <div style={{ marginBottom: '5mm' }}>
        <DataTable
          dense
          cols={[
            { header: de ? 'KPI' : 'KPI', width: '22%' },
            ...kpis.map(k => ({ header: String(k.year), numeric: true })),
          ]}
          rows={[
            ['ARR (Dez)', ...kpis.map(k => fmtEur(k.arr))],
            [de ? 'MRR · ARPU' : 'MRR · ARPU', ...kpis.map(k => fmtEur(k.mrr) + ' · ' + fmtEur(k.arpu))],
            [de ? 'Kunden · MA' : 'Customers · FTE', ...kpis.map(k => k.customers.toLocaleString('de-DE') + ' · ' + k.employees)],
            [de ? 'Umsatz / MA' : 'Revenue / FTE', ...kpis.map(k => fmtEur(k.revenuePerEmployee))],
            [de ? 'Bruttomarge' : 'Gross margin', ...kpis.map(k => k.grossMargin + '%')],
            [de ? 'EBIT · Marge' : 'EBIT · margin', ...kpis.map(k => <span key="e" style={{ color: k.ebit >= 0 ? COLORS.emerald700 : COLORS.red700, fontWeight: 700 }}>{fmtEur(k.ebit)} · {k.ebitMargin}%</span>)],
            [de ? 'Netto-Ergebnis' : 'Net income', ...kpis.map(k => <strong key="ni" style={{ color: k.netIncome >= 0 ? COLORS.emerald700 : COLORS.red700 }}>{fmtEur(k.netIncome)}</strong>)],
            [de ? 'Burn · Runway' : 'Burn · runway', ...kpis.map(k => fmtEur(k.burnRate) + ' · ' + (k.runway == null ? '∞' : String(k.runway) + 'm'))],
            [de ? 'Cash-Bestand' : 'Cash balance', ...kpis.map(k => fmtEur(k.cashBalance))],
          ]}
          highlightFirstCol
        />
      </div>

      {/* Charts grid 2x2 */}
      <div style={{ flex: 1, minHeight: 0, display: 'grid', gridTemplateColumns: '1fr 1fr', gridTemplateRows: '1fr 1fr', gap: '5mm 8mm' }}>
        <BarChart
          title={de ? 'Umsatz (€ Mio.)' : 'Revenue (€M)'}
          data={kpis.map(k => ({ label: String(k.year), value: k.totalRevenue, tone: 'default' }))}
          height={26}
          formatValue={pickFmt(Math.max(...kpis.map(k => k.totalRevenue)))}
        />
        <BarChart
          title={de ? 'EBIT (€)' : 'EBIT (€)'}
          data={kpis.map(k => ({ label: String(k.year), value: k.ebit, tone: k.ebit >= 0 ? 'positive' : 'negative' }))}
          height={26}
          formatValue={pickFmt(Math.max(...kpis.map(k => Math.abs(k.ebit))))}
        />
        <LineChart
          title={de ? 'Cash-Bestand (€)' : 'Cash balance (€)'}
          data={kpis.map(k => ({ label: String(k.year), value: Math.max(k.cashBalance, 0) }))}
          height={26}
          color={COLORS.indigo600}
          formatValue={pickFmt(Math.max(...kpis.map(k => k.cashBalance)))}
          fill
        />
        <BarChart
          title={de ? 'Mitarbeiter · FTE' : 'Employees · FTE'}
          data={kpis.map(k => ({ label: String(k.year), value: k.employees, tone: 'accent' }))}
          height={26}
          formatValue={(n) => String(Math.round(n))}
        />
      </div>
    </Page>
  )
}

/* ===== ASSUMPTIONS ===== */

export function PrintAssumptionsPage({ assumptions, lang, pageNum, totalPages, versionName }: SlideBase & { assumptions: FMAssumption[] }) {
  const de = lang === 'de'
  const scalars = assumptions
    .filter(a => a.value_type === 'scalar')
    .sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
  const byCategory = scalars.reduce<Record<string, FMAssumption[]>>((acc, a) => {
    const cat = a.category || 'General'
    if (!acc[cat]) acc[cat] = []
    acc[cat].push(a)
    return acc
  }, {})
  const categories = Object.entries(byCategory)

  const MONO = "'JetBrains Mono', ui-monospace, monospace"
  return (
    <Page kicker="18" section={de ? 'ANHANG · ANNAHMEN' : 'APPENDIX · ASSUMPTIONS'} title={de ? 'Treibervariablen des Finanzplans.' : 'Financial plan driver variables.'} subtitle={de ? 'Die Annahmen hinter dem Base-Case. Drei Szenarien (Best/Base/Worst) für Sensitivitätsanalyse verfügbar; Base-Case ist absichtlich konservativ angesetzt.' : 'The assumptions behind the base case. Three scenarios (best/base/worst) available for sensitivity analysis; base case is deliberately conservative.'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>

      {/* Visual category cards: each category as a violet-bordered panel with
          its assumptions laid out as a clean two-col list. */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gridAutoRows: 'min-content', gap: '5mm', flex: 1, minHeight: 0, alignContent: 'start' }}>
        {categories.slice(0, 6).map(([cat, items], i) => (
          <div key={cat} style={{ border: `1px solid ${COLORS.slate200}`, borderTop: `3px solid ${COLORS.violet600}`, background: '#ffffff', padding: '3.5mm 5mm', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: '2.5mm' }}>
              <span style={{ fontFamily: MONO, fontSize: '7.5pt', fontWeight: 700, color: COLORS.violet700, textTransform: 'uppercase', letterSpacing: '0.18em' }}>{cat}</span>
              <span style={{ fontFamily: MONO, fontSize: '6.5pt', color: COLORS.slate400, fontVariantNumeric: 'tabular-nums' }}>{String(i + 1).padStart(2, '0')} · {items.length} {de ? 'Variablen' : 'variables'}</span>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '8.5pt', fontVariantNumeric: 'tabular-nums' }}>
              <tbody>
                {items.map((a, j) => (
                  <tr key={a.key} style={{ borderTop: j > 0 ? `1px solid ${COLORS.slate100}` : 'none' }}>
                    <td style={{ padding: '1.5mm 0', color: COLORS.slate700, paddingRight: '4mm', lineHeight: 1.35 }}>{de ? a.label_de : a.label_en}</td>
                    <td style={{ padding: '1.5mm 0', textAlign: 'right', fontWeight: 700, color: COLORS.slate900, whiteSpace: 'nowrap' }}>
                      {typeof a.value === 'number' ? a.value.toLocaleString('de-DE') : String(a.value)}
                      {a.unit && <span style={{ fontFamily: MONO, color: COLORS.slate500, marginLeft: '1.5mm', fontWeight: 400, fontSize: '7pt' }}>{a.unit}</span>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ))}
      </div>

      <div style={{ marginTop: '5mm', flexShrink: 0 }}>
        <Callout tone="accent" label={de ? 'Sensitivität · Drei Szenarien' : 'Sensitivity · Three Scenarios'}>
          {de
            ? 'Best, Base und Worst Case variieren die kritischen Treiber (Wachstumsrate, Churn, ARPU, CAC). Sensitivitäts-Tornado verfügbar im Live-Modell. Der Base-Case ist absichtlich konservativ — Worst Case noch 8 Monate Runway, Best Case Break-Even 6 Monate früher.'
            : 'Best, base and worst case vary the critical drivers (growth rate, churn, ARPU, CAC). Sensitivity tornado available in the live model. The base case is deliberately conservative — worst case still gives 8 months runway, best case breaks even 6 months earlier.'}
        </Callout>
      </div>
    </Page>
  )
}

/* ===== P&L DETAIL — now in standard PDF ===== */

export function PrintFinancialsPage({ annualRows, lang, pageNum, totalPages, versionName }: SlideBase & { annualRows: AnnualPLRow[] }) {
  const de = lang === 'de'
  const breakEvenYear = annualRows.find(r => r.ebitda_eur > 0)?.year
  if (annualRows.length === 0) {
    return (
      <Page kicker="21" section={de ? 'ANHANG · P&L DETAIL' : 'APPENDIX · P&L DETAIL'} title={de ? 'P&L Detail nicht verfügbar' : 'P&L detail unavailable'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>
        <p style={{ fontSize: '10pt', color: COLORS.slate600 }}>{de ? 'Keine Finanzdaten vorhanden. Bitte Base-Case-Szenario auswählen.' : 'No financial data available. Please select base-case scenario.'}</p>
      </Page>
    )
  }
  return (
    <Page kicker="21" section={de ? 'ANHANG · P&L DETAIL' : 'APPENDIX · P&L DETAIL'} title={de ? 'Annualisierte Gewinn- und Verlust-Rechnung.' : 'Annualized profit & loss.'} subtitle={de ? 'Konsolidierte Jahreswerte 2026–2030 in EUR. Klammern () zeigen Aufwendungen. EBITDA in grün ab Break-Even.' : 'Consolidated annual values 2026–2030 in EUR. Parentheses () mark costs. EBITDA in green from break-even on.'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>

      <DataTable
        cols={[
          { header: de ? 'Jahr' : 'Year', width: '8%' },
          { header: de ? 'Umsatz' : 'Revenue', numeric: true, width: '13%' },
          { header: de ? 'Rohertrag' : 'Gross Profit', numeric: true, width: '13%' },
          { header: 'Personal', numeric: true, width: '12%' },
          { header: 'Marketing', numeric: true, width: '12%' },
          { header: 'Infra', numeric: true, width: '10%' },
          { header: 'EBITDA', numeric: true, width: '12%' },
          { header: de ? 'Kunden' : 'Customers', numeric: true, width: '10%' },
          { header: 'FTE', numeric: true, width: '10%' },
        ]}
        rows={annualRows.map(r => [
          <strong key="y">{r.year}</strong>,
          <span style={{ color: COLORS.slate900, fontWeight: 700 }} key="rev">{fmtEur(r.revenue_eur)}</span>,
          fmtEur(r.gross_profit_eur),
          `(${fmtEur(r.personnel_eur)})`,
          `(${fmtEur(r.marketing_eur)})`,
          `(${fmtEur(r.infra_eur)})`,
          <strong key="eb" style={{ color: r.ebitda_eur >= 0 ? COLORS.emerald700 : COLORS.red700 }}>{fmtEur(r.ebitda_eur)}</strong>,
          r.total_customers.toString(),
          r.employees_count.toString(),
        ])}
      />

      <div style={{ marginTop: '5mm', flexShrink: 0 }}>
        <Callout tone={breakEvenYear ? 'positive' : 'caution'} label={de ? 'Break-Even-Indikator' : 'Break-even indicator'}>
          {de
            ? `Erstes Jahr mit positivem EBITDA: ${breakEvenYear ?? 'außerhalb der Planungsperiode'}. In Klammern () = Kosten. Planzahlen, kein Versprechen.`
            : `First year with positive EBITDA: ${breakEvenYear ?? 'outside planning period'}. Parentheses () = costs. Projections, no guarantee.`}
        </Callout>
      </div>
    </Page>
  )
}

/* ===== CAP TABLE ===== */

const CAP_TABLE_DATA = [
  { name: 'Benjamin Bönisch (CEO)', pct: 37.3, color: '#4f46e5' },
  { name: 'Sharang Parnerkar (CTO)', pct: 37.3, color: '#6366f1' },
  { name: 'Pre-Seed Investor', pct: 20.0, color: '#d97706' },
  { name: 'ESOP Pool', pct: 5.4, color: '#94a3b8' },
]

export function PrintCapTablePage({ lang, pageNum, totalPages, versionName }: SlideBase) {
  const de = lang === 'de'
  return (
    <Page kicker="C" section={de ? 'CAP TABLE (FINANCIAL-ONLY)' : 'CAP TABLE (FINANCIAL ONLY)'} title={de ? '€4M Pre-Money · €1M Pre-Seed · Gründung Aug 2026.' : '€4M pre-money · €1M pre-seed · founding Aug 2026.'} subtitle={de ? 'Anteilsverteilung nach Pre-Seed-Closing. Beide Gründer mit 4-Jahres-Vesting + 1-Jahr-Cliff.' : 'Share distribution post pre-seed closing. Both founders on 4-year vesting + 1-year cliff.'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: '8mm', flex: 1, minHeight: 0 }}>
        <div>
          <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '3mm' }}>{de ? 'Anteilsverteilung Post Pre-Seed' : 'Share distribution post pre-seed'}</div>

          <div style={{ display: 'flex', alignItems: 'center', gap: '8mm', marginBottom: '5mm' }}>
            <DonutChart size={50} thickness={11} segments={CAP_TABLE_DATA.map(d => ({ label: d.name, pct: d.pct, color: d.color }))} />
            <div style={{ flex: 1 }}>
              {CAP_TABLE_DATA.map(d => (
                <div key={d.name} style={{ display: 'flex', alignItems: 'center', gap: '3mm', padding: '2mm 0', borderBottom: `1px solid ${COLORS.slate100}` }}>
                  <div style={{ width: '4mm', height: '4mm', background: d.color, flexShrink: 0, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
                  <span style={{ fontSize: '9.5pt', color: COLORS.slate800, flex: 1, fontWeight: 500 }}>{d.name}</span>
                  <span style={{ fontSize: '14pt', fontWeight: 800, color: COLORS.slate900, fontVariantNumeric: 'tabular-nums' }}>{d.pct}%</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div>
          <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '3mm' }}>{de ? 'Deal Terms' : 'Deal terms'}</div>
          <DataTable
            cols={[{ header: '', width: '50%' }, { header: '', numeric: true }]}
            rows={[
              [de ? 'Pre-Money' : 'Pre-money', '€4.000.000'],
              [de ? 'Investment' : 'Investment', '€1.000.000'],
              [de ? 'Post-Money' : 'Post-money', '€5.000.000'],
              [de ? 'Investor-Anteil' : 'Investor share', '20%'],
              ['ESOP Pool', '5,4%'],
              [de ? 'Vesting' : 'Vesting', de ? '4 J / 1 J Cliff' : '4 yr / 1 yr cliff'],
              ['INVEST-Zuschuss', '20% (BMWi)'],
              [de ? 'Liquidationspräf.' : 'Liquidation pref.', '1x non-part.'],
            ]}
            highlightFirstCol
          />
          <div style={{ marginTop: '4mm' }}>
            <Callout tone="accent" label={de ? 'INVEST-Zuschuss' : 'INVEST grant'}>
              {de
                ? 'BMWi-Förderung: 20% des Investments zurück an den Investor (bis €100k / Jahr). Effektive Kapitalkosten sinken entsprechend.'
                : 'BMWi grant: 20% of investment refunded to investor (up to €100k / year). Effective capital cost reduced accordingly.'}
            </Callout>
          </div>
        </div>
      </div>
    </Page>
  )
}

/* ===== DISCLAIMER ===== */

const DC_DE = {
  h1: 'Haftungsausschluss',
  p1: 'Dieses Dokument wird vorgelegt von Benjamin Bönisch, wohnhaft in Bodman, Deutschland, und Sharang Parnerkar, wohnhaft in Engen, Deutschland (nachfolgend „Gründer"). Die Gründer beabsichtigen die Gründung der BreakPilot GmbH im dritten Quartal 2026. Zum Zeitpunkt der Erstellung dieses Dokuments ist die Gesellschaft weder gegründet noch im Handelsregister eingetragen.',
  p2: 'Dieses Dokument stellt weder ein Angebot zum Verkauf noch eine Aufforderung zur Abgabe eines Angebots zum Erwerb von Wertpapieren dar. Es handelt sich nicht um einen Wertpapierprospekt im Sinne des VermAnlG oder der EU-Prospektverordnung.',
  p3: 'Dieses Dokument enthält zukunftsgerichtete Aussagen, die auf gegenwärtigen Erwartungen und Annahmen beruhen. Sämtliche Finanzangaben sind Planzahlen und stellen keine Garantie für künftige Ergebnisse dar.',
  p4: 'Eine Beteiligung an einem jungen Unternehmen ist mit erheblichen Risiken verbunden, einschließlich des Risikos eines Totalverlusts des eingesetzten Kapitals.',
  h2: 'Vertraulichkeit',
  p5: 'Dieses Dokument ist vertraulich und wurde ausschließlich für den namentlich eingeladenen Empfänger erstellt. Durch die Kenntnisnahme erklärt sich der Empfänger mit folgenden Bedingungen einverstanden:',
  pa: '(a) Geheimhaltung, Inhalt vertraulich behandeln und nicht an Dritte weitergeben.',
  pb: '(b) Zweckbindung, Ausschließlich zur Bewertung einer möglichen Beteiligung verwenden.',
  pc: '(c) Geltungsdauer, Diese Vertraulichkeitsverpflichtung gilt für drei (3) Jahre ab Übermittlung. Gerichtsstand ist Konstanz, Deutschland.',
  footer: 'Stand: April 2026 · Dieser Hinweis ersetzt keine Rechtsberatung.',
}
const DC_EN = {
  h1: 'Disclaimer',
  p1: 'This document is presented by Benjamin Bönisch, residing in Bodman, Germany, and Sharang Parnerkar, residing in Engen, Germany (hereinafter "Founders"). The Founders intend to establish BreakPilot GmbH in Q3 2026. At the time of this document, the company is neither founded nor registered.',
  p2: 'This document constitutes neither an offer to sell nor a solicitation of an offer to acquire securities. It is not a securities prospectus within the meaning of VermAnlG or the EU Prospectus Regulation.',
  p3: 'This document contains forward-looking statements based on current expectations. All financial figures are projections and do not constitute a guarantee of future results.',
  p4: 'An investment in a young company involves significant risks, including the risk of total loss of invested capital.',
  h2: 'Confidentiality',
  p5: 'This document is confidential and prepared exclusively for the personally invited recipient. By accessing, the recipient agrees to:',
  pa: '(a) Confidentiality, Treat contents confidentially and not disclose to third parties.',
  pb: '(b) Purpose limitation, Use only for evaluating a possible participation.',
  pc: '(c) Duration, This obligation applies for three (3) years from transmission. Place of jurisdiction is Konstanz, Germany.',
  footer: 'As of: April 2026 · This notice does not replace legal advice.',
}

export function PrintDisclaimerPage({ lang, pageNum, totalPages, versionName }: SlideBase) {
  const d = lang === 'de' ? DC_DE : DC_EN
  const sectionStyle: React.CSSProperties = { padding: '4mm 5mm', border: `1px solid ${COLORS.slate200}`, marginBottom: '3mm' }
  const pStyle: React.CSSProperties = { fontSize: '8.5pt', color: COLORS.slate700, lineHeight: 1.55, margin: '2mm 0 0' }
  const hStyle: React.CSSProperties = { fontSize: '9pt', fontWeight: 700, color: COLORS.indigo600, margin: 0, textTransform: 'uppercase', letterSpacing: '0.08em' }
  return (
    <Page kicker="25" section={lang === 'de' ? 'RECHTLICHER HINWEIS' : 'LEGAL NOTICE'} title={d.h1} subtitle={lang === 'de' ? 'Vertraulich · Nur für den eingeladenen Empfänger · Kein Wertpapierprospekt' : 'Confidential · For invited recipient only · Not a securities prospectus'} pageNum={pageNum} totalPages={totalPages} versionName={versionName}>
      <div style={sectionStyle}>
        <p style={hStyle}>{d.h1}</p>
        <p style={pStyle}>{d.p1}</p>
        <p style={pStyle}>{d.p2}</p>
        <p style={pStyle}>{d.p3}</p>
        <p style={pStyle}>{d.p4}</p>
      </div>
      <div style={sectionStyle}>
        <p style={hStyle}>{d.h2}</p>
        <p style={pStyle}>{d.p5}</p>
        <p style={pStyle}>{d.pa}</p>
        <p style={pStyle}>{d.pb}</p>
        <p style={pStyle}>{d.pc}</p>
      </div>
      <p style={{ fontSize: '8pt', color: COLORS.slate500, textAlign: 'center', marginTop: '4mm', fontStyle: 'italic' }}>{d.footer}</p>
    </Page>
  )
}
