import React from 'react'
import { COLORS } from './PrintLayout'

/* ====================================================================== */
/* CHARTS                                                                 */
/* ====================================================================== */

interface BarSeries {
  label: string
  value: number
  /** Optional secondary label rendered above the bar value (e.g. "Mio."). */
  unit?: string
  tone?: 'default' | 'positive' | 'negative' | 'accent'
}

export function BarChart({
  data, height = 36, maxOverride, formatValue, title, yAxisHint,
}: {
  data: BarSeries[]
  height?: number       // mm
  maxOverride?: number
  formatValue?: (n: number) => string
  title?: string
  yAxisHint?: string
}) {
  const max = maxOverride ?? Math.max(...data.map(d => d.value), 1)
  const fmt = formatValue ?? ((n: number) => n.toLocaleString('de-DE'))
  const ticks = [0, 0.25, 0.5, 0.75, 1].map(t => Math.round(max * t))

  return (
    <div>
      {(title || yAxisHint) && (
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: '2mm' }}>
          {title && <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate600, textTransform: 'uppercase', letterSpacing: '0.1em' }}>{title}</div>}
          {yAxisHint && <div style={{ fontSize: '7pt', color: COLORS.slate400 }}>{yAxisHint}</div>}
        </div>
      )}
      <div style={{ display: 'flex', alignItems: 'stretch', gap: '4mm', position: 'relative' }}>
        {/* Y-axis ticks */}
        <div style={{ width: '14mm', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', height: `${height}mm`, fontSize: '6.5pt', color: COLORS.slate400, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
          {ticks.slice().reverse().map((t, i) => (
            <div key={i}>{fmt(t)}</div>
          ))}
        </div>
        {/* Bars + grid */}
        <div style={{ flex: 1, position: 'relative', height: `${height}mm`, borderLeft: `1px solid ${COLORS.slate300}`, borderBottom: `1px solid ${COLORS.slate300}` }}>
          {/* Grid lines */}
          {ticks.slice(1).map((_, i) => (
            <div key={i} style={{ position: 'absolute', left: 0, right: 0, top: `${(1 - (i + 1) / 4) * 100}%`, height: '0.5pt', background: COLORS.slate100, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
          ))}
          {/* Bars */}
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'flex-end', gap: '3mm', padding: '0 2mm' }}>
            {data.map((d, i) => {
              const h = (d.value / max) * 100
              const color = d.tone === 'positive' ? COLORS.emerald600
                : d.tone === 'negative' ? COLORS.red600
                : d.tone === 'accent' ? COLORS.amber600
                : COLORS.indigo600
              return (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end', height: '100%', position: 'relative' }}>
                  <div style={{ fontSize: '7pt', fontWeight: 700, color: color, marginBottom: '0.8mm', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{fmt(d.value)}</div>
                  <div style={{ width: '100%', height: `${h}%`, minHeight: '1pt', background: color, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
                </div>
              )
            })}
          </div>
        </div>
      </div>
      {/* X-axis labels */}
      <div style={{ display: 'flex', gap: '3mm', paddingLeft: '18mm', paddingRight: '2mm', marginTop: '1mm' }}>
        {data.map((d, i) => (
          <div key={i} style={{ flex: 1, fontSize: '7pt', color: COLORS.slate500, textAlign: 'center', fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{d.label}</div>
        ))}
      </div>
    </div>
  )
}

interface LinePoint { label: string; value: number }

export function LineChart({
  data, height = 36, formatValue, color = COLORS.indigo600, title, fill = true,
}: {
  data: LinePoint[]
  height?: number
  formatValue?: (n: number) => string
  color?: string
  title?: string
  fill?: boolean
}) {
  if (data.length < 2) return null
  const max = Math.max(...data.map(d => d.value), 1)
  const fmt = formatValue ?? ((n: number) => n.toLocaleString('de-DE'))
  const w = 100
  const points = data.map((d, i) => ({
    x: (i / (data.length - 1)) * w,
    y: 100 - (d.value / max) * 100,
    v: d.value,
    label: d.label,
  }))
  const pathD = points.map((p, i) => (i === 0 ? `M${p.x},${p.y}` : `L${p.x},${p.y}`)).join(' ')
  const areaD = `${pathD} L100,100 L0,100 Z`

  return (
    <div>
      {title && <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate600, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '2mm' }}>{title}</div>}
      <div style={{ position: 'relative', height: `${height}mm`, borderLeft: `1px solid ${COLORS.slate300}`, borderBottom: `1px solid ${COLORS.slate300}` }}>
        <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
          {/* Grid */}
          {[0.25, 0.5, 0.75].map(t => (
            <line key={t} x1="0" x2="100" y1={t * 100} y2={t * 100} stroke={COLORS.slate100} strokeWidth="0.3" />
          ))}
          {fill && <path d={areaD} fill={color} fillOpacity="0.12" />}
          <path d={pathD} fill="none" stroke={color} strokeWidth="0.6" strokeLinejoin="round" strokeLinecap="round" />
          {points.map((p, i) => (
            <circle key={i} cx={p.x} cy={p.y} r="1.2" fill={color} />
          ))}
        </svg>
        {/* Value labels above each point */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
          {points.map((p, i) => (
            <div key={i} style={{ position: 'absolute', left: `${p.x}%`, top: `${p.y}%`, transform: 'translate(-50%, -120%)', fontSize: '6.5pt', fontWeight: 700, color, whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}>{fmt(p.v)}</div>
          ))}
        </div>
      </div>
      {/* X labels */}
      <div style={{ display: 'flex', marginTop: '1mm' }}>
        {points.map((p, i) => (
          <div key={i} style={{ flex: 1, fontSize: '7pt', color: COLORS.slate500, textAlign: 'center', fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{p.label}</div>
        ))}
      </div>
    </div>
  )
}

/** Horizontal stacked-bar comparison (e.g. "you pay" vs "you save") */
export function ComparisonBars({
  rows, formatValue,
}: {
  rows: { label: string; bars: { tone: 'positive' | 'negative' | 'accent' | 'default'; value: number; cap?: string }[] }[]
  formatValue?: (n: number) => string
}) {
  const max = Math.max(...rows.flatMap(r => r.bars.map(b => b.value)), 1)
  const fmt = formatValue ?? ((n: number) => n.toLocaleString('de-DE'))
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '3mm' }}>
      {rows.map((row, i) => (
        <div key={i}>
          <div style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate700, marginBottom: '1.5mm' }}>{row.label}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '1mm' }}>
            {row.bars.map((b, j) => {
              const w = (b.value / max) * 100
              const color = b.tone === 'positive' ? COLORS.emerald600
                : b.tone === 'negative' ? COLORS.red600
                : b.tone === 'accent' ? COLORS.amber600
                : COLORS.indigo600
              return (
                <div key={j} style={{ display: 'flex', alignItems: 'center', gap: '3mm' }}>
                  <div style={{ flex: 1, position: 'relative', height: '4mm', background: COLORS.slate50, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
                    <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${w}%`, background: color, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
                    {b.cap && <div style={{ position: 'absolute', left: '2mm', top: 0, bottom: 0, display: 'flex', alignItems: 'center', fontSize: '7pt', color: '#ffffff', fontWeight: 700, letterSpacing: '0.04em' }}>{b.cap}</div>}
                  </div>
                  <div style={{ width: '20mm', textAlign: 'right', fontSize: '9pt', fontWeight: 800, color, fontVariantNumeric: 'tabular-nums' }}>{fmt(b.value)}</div>
                </div>
              )
            })}
          </div>
        </div>
      ))}
    </div>
  )
}

/** Donut chart for percentages (use-of-funds, equity, etc.) */
export function DonutChart({
  segments, size = 32, thickness = 6,
}: {
  segments: { label: string; pct: number; color: string }[]
  size?: number       // mm
  thickness?: number  // mm
}) {
  const R = 50
  const r = R - (thickness / size) * 50
  let acc = 0
  const arcs = segments.map(s => {
    const start = acc / 100 * Math.PI * 2 - Math.PI / 2
    acc += s.pct
    const end = acc / 100 * Math.PI * 2 - Math.PI / 2
    const x1 = 50 + R * Math.cos(start), y1 = 50 + R * Math.sin(start)
    const x2 = 50 + R * Math.cos(end), y2 = 50 + R * Math.sin(end)
    const x3 = 50 + r * Math.cos(end), y3 = 50 + r * Math.sin(end)
    const x4 = 50 + r * Math.cos(start), y4 = 50 + r * Math.sin(start)
    const large = s.pct > 50 ? 1 : 0
    const d = `M${x1},${y1} A${R},${R} 0 ${large} 1 ${x2},${y2} L${x3},${y3} A${r},${r} 0 ${large} 0 ${x4},${y4} Z`
    return { d, color: s.color, pct: s.pct, label: s.label }
  })
  return (
    <svg viewBox="0 0 100 100" style={{ width: `${size}mm`, height: `${size}mm`, display: 'block' }}>
      {arcs.map((a, i) => (
        <path key={i} d={a.d} fill={a.color} />
      ))}
    </svg>
  )
}

/** Progress meter (0-100%) — horizontal */
export function ProgressBar({ pct, color = COLORS.indigo600, label, value }: { pct: number; color?: string; label?: string; value?: string }) {
  return (
    <div>
      {(label || value) && (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '1mm', fontSize: '8pt' }}>
          {label && <span style={{ color: COLORS.slate700, fontWeight: 500 }}>{label}</span>}
          {value && <span style={{ color: COLORS.slate900, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{value}</span>}
        </div>
      )}
      <div style={{ height: '3mm', background: COLORS.slate100, position: 'relative', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${Math.min(100, Math.max(0, pct))}%`, background: color, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }} />
      </div>
    </div>
  )
}

/** Nested market-size visual (TAM/SAM/SOM) */
export function MarketFunnel({
  tam, sam, som, fmt,
}: {
  tam: { value: number; label: string; growth?: number; note?: string }
  sam: { value: number; label: string; growth?: number; note?: string }
  som: { value: number; label: string; growth?: number; note?: string }
  fmt: (v: number) => string
}) {
  const samPct = sam.value / tam.value
  const somPct = som.value / tam.value
  return (
    <div>
      {/* TAM outer */}
      <div style={{ border: `1px solid ${COLORS.slate300}`, padding: '5mm', position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: '1.5mm' }}>
          <span style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.slate500, textTransform: 'uppercase', letterSpacing: '0.14em' }}>TAM &middot; {tam.label}</span>
          {tam.growth != null && <span style={{ fontSize: '7.5pt', color: COLORS.slate500, fontWeight: 600 }}>+{tam.growth}% p.a.</span>}
        </div>
        <div style={{ fontSize: '32pt', fontWeight: 800, color: COLORS.slate900, lineHeight: 1, letterSpacing: '-0.025em', fontVariantNumeric: 'tabular-nums' }}>{fmt(tam.value)}</div>
        {tam.note && <div style={{ fontSize: '8pt', color: COLORS.slate600, marginTop: '2mm', maxWidth: '120mm' }}>{tam.note}</div>}

        {/* SAM inner */}
        <div style={{ marginTop: '4mm', marginLeft: '10mm', border: `1px solid ${COLORS.indigo600}`, background: COLORS.indigo50, padding: '4mm', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: '1.5mm' }}>
            <span style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.indigo700, textTransform: 'uppercase', letterSpacing: '0.14em' }}>SAM &middot; {sam.label}</span>
            {sam.growth != null && <span style={{ fontSize: '7.5pt', color: COLORS.indigo700, fontWeight: 600 }}>+{sam.growth}% p.a. &middot; {Math.round(samPct * 100)}% TAM</span>}
          </div>
          <div style={{ fontSize: '26pt', fontWeight: 800, color: COLORS.indigo700, lineHeight: 1, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>{fmt(sam.value)}</div>
          {sam.note && <div style={{ fontSize: '8pt', color: COLORS.slate700, marginTop: '2mm' }}>{sam.note}</div>}

          {/* SOM inner-inner */}
          <div style={{ marginTop: '3mm', marginLeft: '8mm', border: `2px solid ${COLORS.emerald600}`, background: COLORS.emerald50, padding: '4mm', WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: '1.5mm' }}>
              <span style={{ fontSize: '8pt', fontWeight: 700, color: COLORS.emerald700, textTransform: 'uppercase', letterSpacing: '0.14em' }}>SOM &middot; {som.label}</span>
              {som.growth != null && <span style={{ fontSize: '7.5pt', color: COLORS.emerald700, fontWeight: 600 }}>+{som.growth}% p.a. &middot; {(somPct * 100).toFixed(1)}% TAM</span>}
            </div>
            <div style={{ fontSize: '24pt', fontWeight: 800, color: COLORS.emerald700, lineHeight: 1, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>{fmt(som.value)}</div>
            {som.note && <div style={{ fontSize: '8pt', color: COLORS.slate700, marginTop: '2mm' }}>{som.note}</div>}
          </div>
        </div>
      </div>
    </div>
  )
}
