import React from 'react'

/* ===== DESIGN TOKENS ===== */

/**
 * Adapted from Claude Design tokens (light theme).
 * Primary accent = violet (#7c3aed). The names `indigo*` are kept as aliases
 * so existing slide files don't need to be touched — the *values* now resolve
 * to the violet palette. New code can use the explicit `violet*` names.
 */
export const COLORS = {
  // Body text — deep purple-tinted instead of pure slate
  slate900: '#1a0f34',
  slate800: '#2a1f4a',
  slate700: 'rgba(26,15,52,.88)',
  slate600: 'rgba(26,15,52,.72)',
  slate500: 'rgba(26,15,52,.60)',
  slate400: 'rgba(26,15,52,.46)',
  slate300: 'rgba(26,15,52,.28)',
  slate200: 'rgba(26,15,52,.14)',
  slate100: 'rgba(26,15,52,.06)',
  slate50: 'rgba(26,15,52,.03)',
  // Violet palette (new primary accent)
  violet900: '#3b0e7a',
  violet800: '#5b21b6',
  violet700: '#6d28d9',
  violet600: '#7c3aed',
  violet500: '#8b5cf6',
  violet400: '#a78bfa',
  violet300: '#c4b5fd',
  violet200: '#ddd6fe',
  violet100: '#ede9fe',
  violet50: '#f5f3ff',
  // Legacy `indigo*` aliases — kept so existing slide code compiles unchanged
  indigo700: '#6d28d9',
  indigo600: '#7c3aed',
  indigo500: '#8b5cf6',
  indigo50: '#f5f3ff',
  // Functional accents
  emerald700: '#047857',
  emerald600: '#059669',
  emerald50: '#ecfdf5',
  red700: '#b91c1c',
  red600: '#dc2626',
  red50: '#fef2f2',
  amber700: '#b45309',
  amber600: '#d97706',
  amber50: '#fffbeb',
  // Legacy aliases used by some callers
  dark: '#1a0f34',
  med: 'rgba(26,15,52,.88)',
  light: 'rgba(26,15,52,.60)',
  border: 'rgba(26,15,52,.14)',
  indigo: '#7c3aed',
  indigoLight: '#f5f3ff',
}

const FONT = "'Inter', 'Plus Jakarta Sans', system-ui, -apple-system, sans-serif"
const MONO_FONT = "'JetBrains Mono', ui-monospace, Menlo, Consolas, monospace"

/**
 * Brand wordmark: `Compl` rendered in the inherited text color, `AI` in violet.
 * No slashes, no separators — matches the BreakPilot/ComplAI brand guideline.
 * Use this anywhere the product name appears in body or display text.
 *
 * Use the optional `prefix` to prepend "BreakPilot " in the same style.
 */
export function ComplAI({ prefix = false }: { prefix?: boolean } = {}) {
  return (
    <>
      {prefix && <>BreakPilot </>}
      Compl<span style={{ color: COLORS.violet600 }}>AI</span>
    </>
  )
}

/* ===== PAGE WRAPPER ===== */

interface PageProps {
  kicker: string                 // "03"
  section: string                // "DAS PROBLEM"
  title: React.ReactNode         // string or JSX (e.g. <ComplAI prefix /> usage)
  subtitle?: React.ReactNode
  pageNum: number
  totalPages: number
  versionName: string
  children: React.ReactNode
  footnote?: React.ReactNode     // optional footnote line above footer
}

export function Page({ kicker, section, title, subtitle, pageNum, totalPages, versionName, children, footnote }: PageProps) {
  return (
    <div className="print-page-break">
      <div className="print-page print-page-bg" style={{
        width: '297mm',
        height: '210mm',
        color: COLORS.slate900,
        fontFamily: FONT,
        display: 'flex',
        flexDirection: 'column',
        boxSizing: 'border-box',
        padding: '11mm 14mm 8mm 14mm',
        // screen-only decoration
        margin: '0 auto 24px',
        boxShadow: '0 4px 24px rgba(59,26,122,0.10)',
        WebkitPrintColorAdjust: 'exact',
        printColorAdjust: 'exact',
      }}>
        {/* TITLE BLOCK — left-rule preserved */}
        <div style={{ display: 'flex', alignItems: 'stretch', gap: '7mm', marginBottom: '5mm', flexShrink: 0 }}>
          <div style={{ width: '3px', background: COLORS.violet600, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact', alignSelf: 'stretch', minHeight: '14mm' }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: '4mm', marginBottom: '2mm' }}>
              <span className="print-mono" style={{ fontFamily: MONO_FONT, fontSize: '7.5pt', fontWeight: 700, letterSpacing: '0.18em', color: COLORS.violet600, textTransform: 'uppercase' }}>
                {kicker} &middot; {section}
              </span>
              <span style={{ flex: 1, height: '1px', background: `linear-gradient(90deg, ${COLORS.violet400}, transparent 80%)`, alignSelf: 'center', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
              <span className="print-mono" style={{ fontFamily: MONO_FONT, fontSize: '7pt', color: COLORS.slate500, fontWeight: 500, letterSpacing: '0.06em' }}>BreakPilot &middot; ComplAI</span>
            </div>
            <h1 style={{ fontSize: '22pt', fontWeight: 800, color: COLORS.slate900, margin: 0, lineHeight: 1.1, letterSpacing: '-0.015em' }}>
              {title}
            </h1>
            {subtitle && (
              <p style={{ fontSize: '10pt', color: COLORS.slate600, margin: '2mm 0 0', fontWeight: 400, lineHeight: 1.45, maxWidth: '210mm' }}>
                {subtitle}
              </p>
            )}
            {/* Subtle violet accent gradient bar — echo of the Claude Design feel */}
            <div style={{ marginTop: '3mm', height: '2px', width: '100%', background: `linear-gradient(90deg, ${COLORS.violet700} 0%, ${COLORS.violet400} 50%, ${COLORS.violet700} 100%)`, opacity: 0.85, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
          </div>
        </div>

        {/* CONTENT */}
        <div style={{ flex: 1, minHeight: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          {children}
        </div>

        {/* FOOTNOTE (optional) */}
        {footnote && (
          <div style={{ flexShrink: 0, marginTop: '3mm', paddingTop: '2mm', borderTop: `1px solid ${COLORS.slate200}`, fontSize: '7pt', color: COLORS.slate500, lineHeight: 1.4 }}>
            {footnote}
          </div>
        )}

        {/* FOOTER — JetBrains Mono caps to match Claude Design */}
        <div className="print-mono" style={{ fontFamily: MONO_FONT, flexShrink: 0, marginTop: '3mm', paddingTop: '2mm', borderTop: `1px solid ${COLORS.slate200}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: '7pt', color: COLORS.slate500, letterSpacing: '0.16em', textTransform: 'uppercase', fontWeight: 700 }}>
          <span>BreakPilot &middot; ComplAI</span>
          <span style={{ color: COLORS.violet600 }}>{versionName}</span>
          <span style={{ fontVariantNumeric: 'tabular-nums' }}>{String(pageNum).padStart(2, '0')} / {String(totalPages).padStart(2, '0')}</span>
        </div>
      </div>
    </div>
  )
}

/* ===== KPI ROW ===== */

interface KpiItem { n: string; label: string; tone?: 'default' | 'positive' | 'negative' | 'accent' }

export function KpiRow({ items, align = 'left' }: { items: KpiItem[]; align?: 'left' | 'center' }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${items.length}, 1fr)`, gap: '4mm', borderTop: `1px solid ${COLORS.slate200}`, borderBottom: `1px solid ${COLORS.slate200}`, padding: '4mm 0', margin: '2mm 0' }}>
      {items.map((it, i) => {
        const color = it.tone === 'positive' ? COLORS.emerald700
          : it.tone === 'negative' ? COLORS.red700
          : it.tone === 'accent' ? COLORS.indigo600
          : COLORS.slate900
        return (
          <div key={i} style={{ textAlign: align }}>
            <div style={{ fontSize: '24pt', fontWeight: 800, color, lineHeight: 1, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>
              {it.n}
            </div>
            <div style={{ marginTop: '2mm', fontSize: '7.5pt', fontWeight: 600, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.08em', lineHeight: 1.3 }}>
              {it.label}
            </div>
          </div>
        )
      })}
    </div>
  )
}

/* ===== COLUMNS ===== */

export function TwoCol({ left, right, ratio = '1:1', gap = '8mm' }: { left: React.ReactNode; right: React.ReactNode; ratio?: '1:1' | '1:1.5' | '1.5:1' | '1:2' | '2:1'; gap?: string }) {
  const [l, r] = ratio.split(':').map(Number)
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `${l}fr ${r}fr`, gap, flex: 1, minHeight: 0 }}>
      <div style={{ minWidth: 0, display: 'flex', flexDirection: 'column' }}>{left}</div>
      <div style={{ minWidth: 0, display: 'flex', flexDirection: 'column' }}>{right}</div>
    </div>
  )
}

export function ThreeCol({ cols, gap = '6mm', equalHeight = true }: { cols: React.ReactNode[]; gap?: string; equalHeight?: boolean }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap, ...(equalHeight ? { flex: 1, minHeight: 0 } : {}) }}>
      {cols.map((c, i) => <div key={i} style={{ minWidth: 0, display: 'flex', flexDirection: 'column' }}>{c}</div>)}
    </div>
  )
}

export function FourCol({ cols, gap = '4mm' }: { cols: React.ReactNode[]; gap?: string }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap }}>
      {cols.map((c, i) => <div key={i} style={{ minWidth: 0 }}>{c}</div>)}
    </div>
  )
}

/* ===== PANEL (left-rule narrative card) ===== */

interface PanelProps {
  label?: string
  title?: string
  tone?: 'neutral' | 'positive' | 'negative' | 'caution' | 'accent'
  children: React.ReactNode
  dense?: boolean
}

export function Panel({ label, title, tone = 'neutral', children, dense }: PanelProps) {
  const color = tone === 'positive' ? COLORS.emerald700
    : tone === 'negative' ? COLORS.red700
    : tone === 'caution' ? COLORS.amber700
    : tone === 'accent' ? COLORS.indigo600
    : COLORS.slate600
  return (
    <div style={{ borderLeft: `2px solid ${color}`, paddingLeft: dense ? '4mm' : '5mm', paddingRight: '2mm', flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
      {label && (
        <div style={{ fontSize: '7.5pt', fontWeight: 700, color, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '2mm' }}>
          {label}
        </div>
      )}
      {title && (
        <div style={{ fontSize: '12pt', fontWeight: 700, color: COLORS.slate900, marginBottom: '3mm', lineHeight: 1.25, letterSpacing: '-0.005em' }}>
          {title}
        </div>
      )}
      <div style={{ flex: 1, minHeight: 0, fontSize: '9pt', color: COLORS.slate700, lineHeight: 1.55 }}>
        {children}
      </div>
    </div>
  )
}

/* ===== BULLETS ===== */

interface BulletsProps { items: (string | React.ReactNode)[]; dense?: boolean; tone?: 'neutral' | 'positive' | 'negative' | 'accent' }

export function Bullets({ items, dense, tone = 'neutral' }: BulletsProps) {
  const dotColor = tone === 'positive' ? COLORS.emerald600
    : tone === 'negative' ? COLORS.red600
    : tone === 'accent' ? COLORS.indigo600
    : COLORS.slate500
  /**
   * Em-dash marker uses display:flex to keep the rule vertically centered on
   * the first line of text — previously the `top: 4pt` absolute positioning
   * drifted relative to font size (looked off-center on the rendered PDF).
   * The marker now sits in a fixed-width column at the line height of the text.
   */
  const fontSize = dense ? '8.5pt' : '9pt'
  const lineH = 1.5
  return (
    <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
      {items.map((item, i) => (
        <li key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: '3mm', marginBottom: dense ? '1.5mm' : '2.5mm', fontSize, color: COLORS.slate700, lineHeight: lineH }}>
          {/* The dash sits on the first line: line-height pad above + 0.5pt rule */}
          <span style={{ flexShrink: 0, width: '3mm', display: 'inline-flex', alignItems: 'center', height: `${parseFloat(fontSize) * lineH}pt` }}>
            <span style={{ width: '100%', height: '0.5pt', background: dotColor, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
          </span>
          <span style={{ flex: 1, minWidth: 0 }}>{item}</span>
        </li>
      ))}
    </ul>
  )
}

/* ===== DATA TABLE ===== */

interface TableCol {
  header: string
  width?: string
  align?: 'left' | 'right' | 'center'
  numeric?: boolean
}

interface DataTableProps {
  cols: TableCol[]
  rows: (string | number | React.ReactNode)[][]
  dense?: boolean
  zebra?: boolean
  highlightFirstCol?: boolean
}

export function DataTable({ cols, rows, dense, zebra = true, highlightFirstCol }: DataTableProps) {
  const fontSize = dense ? '7.5pt' : '8.5pt'
  const padY = dense ? '1.5mm' : '2mm'
  return (
    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize, color: COLORS.slate800, fontVariantNumeric: 'tabular-nums' }}>
      <thead>
        <tr>
          {cols.map((c, i) => (
            <th key={i} style={{
              background: COLORS.indigo50,
              color: COLORS.indigo700,
              fontWeight: 700,
              textTransform: 'uppercase',
              letterSpacing: '0.08em',
              fontSize: dense ? '6.5pt' : '7pt',
              padding: `${padY} 2.5mm`,
              textAlign: c.align || (c.numeric ? 'right' : 'left'),
              width: c.width,
              borderBottom: `1px solid ${COLORS.slate200}`,
              WebkitPrintColorAdjust: 'exact',
              printColorAdjust: 'exact',
            }}>
              {c.header}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {rows.map((row, ri) => (
          <tr key={ri} style={{ background: zebra && ri % 2 === 1 ? COLORS.slate50 : 'transparent', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
            {row.map((cell, ci) => (
              <td key={ci} style={{
                padding: `${padY} 2.5mm`,
                textAlign: cols[ci]?.align || (cols[ci]?.numeric ? 'right' : 'left'),
                borderBottom: `1px solid ${COLORS.slate100}`,
                verticalAlign: 'top',
                lineHeight: 1.4,
                fontWeight: highlightFirstCol && ci === 0 ? 600 : 400,
                color: highlightFirstCol && ci === 0 ? COLORS.slate900 : COLORS.slate700,
                whiteSpace: cols[ci]?.numeric ? 'nowrap' : 'normal',
              }}>
                {cell}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  )
}

/* ===== FEATURE MATRIX (●/○/—) ===== */

export type Glyph = true | false | 'partial'

export function MatrixGlyph({ v, isUSP }: { v: Glyph; isUSP?: boolean }) {
  if (v === true) return <span style={{ color: isUSP ? COLORS.indigo600 : COLORS.slate800, fontWeight: 700 }}>&#9679;</span>
  if (v === 'partial') return <span style={{ color: COLORS.amber700 }}>&#9681;</span>
  return <span style={{ color: COLORS.slate300 }}>&mdash;</span>
}

/* ===== CALLOUT ===== */

interface CalloutProps {
  tone?: 'neutral' | 'positive' | 'negative' | 'caution' | 'accent'
  label?: string
  children: React.ReactNode
}

export function Callout({ tone = 'neutral', label, children }: CalloutProps) {
  const color = tone === 'positive' ? COLORS.emerald700
    : tone === 'negative' ? COLORS.red700
    : tone === 'caution' ? COLORS.amber700
    : tone === 'accent' ? COLORS.indigo600
    : COLORS.slate600
  const bg = tone === 'positive' ? COLORS.emerald50
    : tone === 'negative' ? COLORS.red50
    : tone === 'caution' ? COLORS.amber50
    : tone === 'accent' ? COLORS.indigo50
    : COLORS.slate50
  return (
    <div style={{ borderLeft: `3px solid ${color}`, background: bg, padding: '3mm 4mm', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
      {label && (
        <div style={{ fontSize: '7.5pt', fontWeight: 700, color, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '1.5mm' }}>{label}</div>
      )}
      <div style={{ fontSize: '9pt', color: COLORS.slate800, lineHeight: 1.5 }}>{children}</div>
    </div>
  )
}

/* ===== DIVIDER ===== */

export function Divider({ space = '4mm' }: { space?: string }) {
  return <div style={{ height: '1px', background: COLORS.slate200, margin: `${space} 0` }} />
}

/* ===== STAT INLINE (label: value) ===== */

export function StatLine({ label, value, tone = 'neutral' }: { label: string; value: string; tone?: 'neutral' | 'positive' | 'negative' | 'accent' }) {
  const color = tone === 'positive' ? COLORS.emerald700
    : tone === 'negative' ? COLORS.red700
    : tone === 'accent' ? COLORS.indigo600
    : COLORS.slate900
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '1.5mm 0', borderBottom: `1px solid ${COLORS.slate100}`, fontSize: '8.5pt' }}>
      <span style={{ color: COLORS.slate600 }}>{label}</span>
      <span style={{ fontWeight: 700, color, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
    </div>
  )
}

/* ===== LEGACY EXPORTS (preserved for any callers not yet migrated) ===== */

interface PrintPageProps {
  title: string
  pageNum: number
  totalPages: number
  versionName: string
  children: React.ReactNode
}

export function PrintPage({ title, pageNum, totalPages, versionName, children }: PrintPageProps) {
  // Legacy wrapper: maps to the new Page primitive without title/subtitle structure
  return (
    <Page
      kicker=""
      section={title.toUpperCase()}
      title={title}
      pageNum={pageNum}
      totalPages={totalPages}
      versionName={versionName}
    >
      {children}
    </Page>
  )
}

export function SectionTitle({ children, subtitle }: { children: React.ReactNode; subtitle?: string }) {
  return (
    <div style={{ marginBottom: '4mm' }}>
      <h2 style={{ fontSize: '14pt', fontWeight: 700, color: COLORS.slate900, margin: 0, lineHeight: 1.2 }}>{children}</h2>
      {subtitle && <p style={{ fontSize: '9pt', color: COLORS.slate600, marginTop: '1.5mm', marginBottom: 0 }}>{subtitle}</p>}
    </div>
  )
}

interface TableProps {
  headers: string[]
  rows: (string | React.ReactNode)[][]
  colWidths?: string[]
}

export function PrintTable({ headers, rows, colWidths }: TableProps) {
  const cols = headers.map((h, i) => ({ header: h, width: colWidths?.[i] }))
  return <DataTable cols={cols} rows={rows} />
}

export function Badge({ children, color = COLORS.indigo600 }: { children: React.ReactNode; color?: string }) {
  return (
    <span style={{ display: 'inline-block', padding: '0.5mm 2mm', borderRadius: '2pt', background: `${color}1f`, color, fontSize: '7.5pt', fontWeight: 600, letterSpacing: '0.02em', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
      {children}
    </span>
  )
}
