'use client'

import { useEffect } from 'react'
import { Language, PitchData, FMResult, FMAssumption } from '@/lib/types'
import {
  PrintCoverPage, PrintExecSummaryPage1, PrintExecSummaryPage2,
  PrintProblemPage, PrintSolutionPage,
} from './PrintIntroSlides'
import {
  PrintUSPPage1, PrintUSPPage2, PrintRegulatoryLandscapePage,
  PrintProductPage, PrintHowItWorksPage, PrintBusinessModelPage,
} from './PrintProductSlides'
import {
  PrintMarketPage, PrintMilestonesPage, PrintTeamPage,
  PrintTheAskPage, PrintCustomerSavingsPage,
} from './PrintMarketSlides'
import {
  PrintCompetitionPage1, PrintCompetitionPage2,
} from './PrintCompetitionSlides'
import {
  PrintStrategyPage, PrintRegulatoryPage, PrintArchitecturePage,
  PrintEngineeringPage, PrintAIPipelinePage, PrintRisksPage, PrintGlossaryPage,
} from './PrintAnnexSlides'
import {
  PrintTLDRPage, PrintDifferentiatorsPage, PrintKPIHeroPage,
  PrintTechStackPage, PrintAnnexDividerPage,
} from './PrintNewSlides'
import {
  PrintFinanzplanPage1, PrintFinanzplanPage2, PrintAssumptionsPage,
  PrintFinancialsPage, PrintCapTablePage, PrintDisclaimerPage,
  aggregateAnnualRows,
} from './PrintFinancialSlides'

export { aggregateAnnualRows }

interface PrintDeckProps {
  pitchData: PitchData
  versionName: string
  fmResults: FMResult[]
  fmAssumptions: FMAssumption[]
  financial: boolean
  lang: Language
}

export default function PrintDeck({ pitchData, versionName, fmResults, fmAssumptions, financial, lang }: PrintDeckProps) {
  const isWandeldarlehen = (pitchData.funding?.instrument || '').toLowerCase().includes('wandeldarlehen') ||
                           (pitchData.funding?.instrument || '').toLowerCase().includes('convertible')
  const hasCapTable = financial && !isWandeldarlehen
  const annualRows = aggregateAnnualRows(fmResults)
  const hasFinancialData = annualRows.length > 0
  const de = lang === 'de'

  // Base standard PDF: 35 physical pages.
  // 2 (exec) + 1 (TL;DR) + 1 (cover) + 1 (problem) + 1 (solution) + 2 (usp) +
  // 1 (differentiators) + 1 (regL) + 1 (product) + 1 (how) + 1 (market) + 1 (bm) +
  // 1 (milestones) + 2 (competition) + 1 (team) + 1 (ask) + 1 (savings) +
  // 1 (anhang-divider) + 1 (strategy) + 1 (kpis) + 2 (finanzplan) + 1 (p&l detail) +
  // 1 (assumptions) + 1 (regulatory) + 1 (architecture) + 1 (engineering) +
  // 1 (tech-stack) + 1 (aipipeline) + 1 (risks) + 1 (glossary) + 1 (disclaimer) = 35
  // P&L detail is now in standard PDF (was financial-only); cap-table stays
  // financial-only (and is suppressed for Wandeldarlehen).
  const BASE_PAGES = 35
  const totalPages = BASE_PAGES + (hasCapTable ? 1 : 0)
  void hasFinancialData

  useEffect(() => {
    const t = setTimeout(() => window.print(), 900)
    return () => clearTimeout(t)
  }, [])

  let n = 0
  const p = () => ({ lang, pageNum: ++n, totalPages, versionName })

  return (
    <>
      {/* Toolbar, screen only */}
      <div className="no-print" style={{
        position: 'sticky', top: 0, zIndex: 100,
        background: '#0f172a', color: '#fff',
        padding: '10px 24px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontFamily: "'Plus Jakarta Sans', system-ui, sans-serif",
        fontSize: '13px', boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <span style={{ fontWeight: 800, letterSpacing: '-0.01em' }}>BreakPilot</span>
          <span style={{ opacity: 0.55, fontSize: '11px' }}>{versionName}</span>
          <span style={{ fontSize: '11px', padding: '2px 8px', borderRadius: '99px', background: financial ? '#4f46e533' : '#6366f133', color: financial ? '#a5b4fc' : '#a5b4fc', fontWeight: 600, letterSpacing: '0.02em' }}>
            {financial ? (de ? 'PDF + Finanzen' : 'PDF + Financial') : (de ? 'Standard PDF' : 'Standard PDF')}
          </span>
          <span style={{ fontSize: '11px', opacity: 0.5, fontVariantNumeric: 'tabular-nums' }}>{totalPages} {de ? 'Seiten' : 'pages'}</span>
        </div>
        <div style={{ display: 'flex', gap: '10px' }}>
          <button onClick={() => window.print()} style={{ padding: '6px 16px', background: '#4f46e5', color: '#fff', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' }}>
            {de ? 'Drucken / Als PDF speichern' : 'Print / Save as PDF'}
          </button>
          <button onClick={() => window.close()} style={{ padding: '6px 12px', background: 'rgba(255,255,255,0.1)', color: '#fff', border: '1px solid rgba(255,255,255,0.2)', borderRadius: '6px', cursor: 'pointer', fontSize: '13px' }}>
            {de ? 'Schließen' : 'Close'}
          </button>
        </div>
      </div>

      <div className="print-deck-wrapper" style={{ padding: '32px 0', fontFamily: "'Inter', system-ui, sans-serif" }}>
        {/* PITCH (slides 01–17) */}

        {/* 01–02 executive-summary (2 pages) */}
        <PrintExecSummaryPage1 market={pitchData.market || []} {...p()} />
        <PrintExecSummaryPage2 {...p()} />

        {/* 03 TL;DR — 30 Sekunden */}
        <PrintTLDRPage {...p()} />

        {/* 04 cover */}
        {(() => { n += 1; return <PrintCoverPage company={pitchData.company} funding={pitchData.funding} versionName={versionName} lang={lang} /> })()}

        {/* 05 problem */}
        <PrintProblemPage {...p()} />

        {/* 06 solution */}
        <PrintSolutionPage {...p()} />

        {/* 07–08 usp (2 pages) */}
        <PrintUSPPage1 {...p()} />
        <PrintUSPPage2 {...p()} />

        {/* 09 differentiators */}
        <PrintDifferentiatorsPage {...p()} />

        {/* 10 regulatory-landscape */}
        <PrintRegulatoryLandscapePage {...p()} />

        {/* 11 product / modular-toolkit */}
        <PrintProductPage products={pitchData.products || []} {...p()} />

        {/* 12 how-it-works */}
        <PrintHowItWorksPage {...p()} />

        {/* 13 market */}
        <PrintMarketPage market={pitchData.market || []} {...p()} />

        {/* 14 business-model / pricing */}
        <PrintBusinessModelPage {...p()} />

        {/* 15 traction (milestones) */}
        <PrintMilestonesPage milestones={pitchData.milestones || []} {...p()} />

        {/* 16–17 competition (2 pages) */}
        <PrintCompetitionPage1 {...p()} />
        <PrintCompetitionPage2 {...p()} />

        {/* 18 team */}
        <PrintTeamPage team={pitchData.team || []} {...p()} />

        {/* 19 the-ask */}
        <PrintTheAskPage funding={pitchData.funding} {...p()} />

        {/* 20 customer-savings */}
        <PrintCustomerSavingsPage {...p()} />

        {/* 21 ANHANG divider — chapter break before the appendix */}
        <PrintAnnexDividerPage {...p()} />

        {/* APPENDIX (slides 22–35) */}

        {/* 22 annex-strategy */}
        <PrintStrategyPage {...p()} />

        {/* 23 KPIs — 2026 → 2030 trajectory */}
        <PrintKPIHeroPage fmResults={fmResults} {...p()} />

        {/* 24–25 annex-finanzplan (2 pages) */}
        <PrintFinanzplanPage1 fmResults={fmResults} {...p()} />
        <PrintFinanzplanPage2 fmResults={fmResults} {...p()} />

        {/* 26 P&L detail (was financial-only; now standard) */}
        <PrintFinancialsPage annualRows={annualRows} {...p()} />

        {/* 27 annex-assumptions */}
        <PrintAssumptionsPage assumptions={fmAssumptions} {...p()} />

        {/* 28 annex-regulatory */}
        <PrintRegulatoryPage {...p()} />

        {/* 29 annex-architecture */}
        <PrintArchitecturePage {...p()} />

        {/* 30 annex-engineering */}
        <PrintEngineeringPage {...p()} />

        {/* 31 tech-stack */}
        <PrintTechStackPage {...p()} />

        {/* 32 annex-aipipeline */}
        <PrintAIPipelinePage {...p()} />

        {/* 33 risks */}
        <PrintRisksPage {...p()} />

        {/* 34 annex-glossary */}
        <PrintGlossaryPage {...p()} />

        {/* Financial-only: cap-table (suppressed for Wandeldarlehen) */}
        {hasCapTable && <PrintCapTablePage {...p()} />}

        {/* 35 legal-disclaimer */}
        <PrintDisclaimerPage {...p()} />
      </div>
    </>
  )
}
