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

/* ====================================================================== */
/* DIAGRAMS                                                               */
/* ====================================================================== */

/** A single "node" in a flow / architecture diagram. */
export function FlowNode({
  title, subtitle, items, accent = COLORS.indigo600, icon, kicker, footer,
}: {
  title: string
  subtitle?: string
  items?: string[]
  accent?: string
  icon?: React.ReactNode
  kicker?: string
  footer?: string
}) {
  return (
    <div style={{
      border: `1px solid ${COLORS.slate200}`,
      borderTop: `3px solid ${accent}`,
      background: '#ffffff',
      padding: '3mm 4mm',
      display: 'flex',
      flexDirection: 'column',
      WebkitPrintColorAdjust: 'exact',
      printColorAdjust: 'exact',
    }}>
      {kicker && (
        <div style={{ fontSize: '6.5pt', fontWeight: 700, color: accent, textTransform: 'uppercase', letterSpacing: '0.14em', marginBottom: '1.5mm' }}>{kicker}</div>
      )}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: '3mm', marginBottom: '1mm' }}>
        {icon && <div style={{ flexShrink: 0, color: accent, marginTop: '0.5mm' }}>{icon}</div>}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: '11pt', fontWeight: 700, color: COLORS.slate900, lineHeight: 1.15 }}>{title}</div>
          {subtitle && <div style={{ fontSize: '8pt', color: accent, fontWeight: 600, marginTop: '0.5mm' }}>{subtitle}</div>}
        </div>
      </div>
      {items && items.length > 0 && (
        <div style={{ marginTop: '2mm', display: 'flex', flexDirection: 'column' }}>
          {items.map((it, i) => (
            <div key={i} style={{
              fontSize: '7.5pt',
              color: COLORS.slate700,
              padding: '1mm 0',
              borderTop: i > 0 ? `1px solid ${COLORS.slate100}` : 'none',
              lineHeight: 1.35,
            }}>{it}</div>
          ))}
        </div>
      )}
      {footer && (
        <div style={{ marginTop: '2mm', paddingTop: '1.5mm', borderTop: `1px solid ${COLORS.slate100}`, fontSize: '6.5pt', color: COLORS.slate500, fontFamily: 'monospace', lineHeight: 1.4 }}>{footer}</div>
      )}
    </div>
  )
}

/** Vertical down arrow (between rows of a flow diagram). */
export function VArrow({ color = COLORS.slate400, label }: { color?: string; label?: string }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '1.5mm 0' }}>
      <svg viewBox="0 0 24 32" style={{ width: '6mm', height: '6mm' }}>
        <line x1="12" y1="0" x2="12" y2="24" stroke={color} strokeWidth="1.5" />
        <polyline points="6,22 12,30 18,22" fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
      {label && <div style={{ fontSize: '6.5pt', color: COLORS.slate500, marginTop: '0.5mm', fontWeight: 600 }}>{label}</div>}
    </div>
  )
}

/** Horizontal right arrow (between steps of a horizontal flow). */
export function HArrow({ color = COLORS.slate400, label }: { color?: string; label?: string }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minWidth: '6mm', position: 'relative' }}>
      <svg viewBox="0 0 32 24" style={{ width: '8mm', height: '5mm' }}>
        <line x1="0" y1="12" x2="24" y2="12" stroke={color} strokeWidth="1.5" />
        <polyline points="20,6 30,12 20,18" fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
      {label && <div style={{ fontSize: '6.5pt', color: COLORS.slate500, marginTop: '0.5mm', fontWeight: 600, textAlign: 'center', whiteSpace: 'nowrap' }}>{label}</div>}
    </div>
  )
}

/** Horizontal step strip with built-in arrows between items. */
export function StepStrip({
  steps, accent = COLORS.indigo600,
}: {
  steps: { n: string; t: string; d: string }[]
  accent?: string
}) {
  return (
    <div style={{ display: 'flex', alignItems: 'stretch' }}>
      {steps.map((s, i) => (
        <React.Fragment key={i}>
          <div style={{ flex: 1, padding: '0 2mm', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: '3mm', marginBottom: '2mm' }}>
              <span style={{ fontSize: '24pt', fontWeight: 800, color: accent, lineHeight: 1, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>{s.n}</span>
              <div style={{ flex: 1, height: '1px', background: COLORS.slate200, alignSelf: 'center' }} />
            </div>
            <div style={{ fontSize: '12pt', fontWeight: 700, color: COLORS.slate900, lineHeight: 1.2, marginBottom: '2mm', letterSpacing: '-0.005em' }}>{s.t}</div>
            <div style={{ fontSize: '8.5pt', color: COLORS.slate700, lineHeight: 1.5, flex: 1 }}>{s.d}</div>
          </div>
          {i < steps.length - 1 && (
            <div style={{ width: '6mm', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg viewBox="0 0 24 24" style={{ width: '6mm', height: '6mm', color: COLORS.slate300 }}>
                <line x1="2" y1="12" x2="18" y2="12" stroke={COLORS.slate300} strokeWidth="1.5" />
                <polyline points="14,6 20,12 14,18" fill="none" stroke={COLORS.slate300} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
          )}
        </React.Fragment>
      ))}
    </div>
  )
}

/** 3-tier architecture diagram (product → proxy → inference) */
export function ArchitectureDiagram({
  product, proxy, inference, lang,
}: {
  product: { kicker: string; title: string; subtitle: string; tech: string; services: string[] }[]
  proxy: { title: string; subtitle: string; features: string[] }
  inference: { title: string; subtitle: string; tech: string; desc: string }[]
  lang: 'de' | 'en'
}) {
  const de = lang === 'de'
  const MONO = "'JetBrains Mono', ui-monospace, monospace"

  /** Layer pill: "01 · APPLICATION LAYER" + sub-label */
  const LayerChip = ({ n, label, sub, tint }: { n: string; label: string; sub: string; tint: string }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: '3mm', marginBottom: '2mm' }}>
      <span style={{ fontFamily: MONO, fontSize: '7pt', fontWeight: 700, color: tint, textTransform: 'uppercase', letterSpacing: '0.2em', background: '#ffffff', padding: '1mm 3mm', borderRadius: '99pt', border: `1px solid ${tint}66`, WebkitPrintColorAdjust: 'exact', printColorAdjust: 'exact' }}>{n} &middot; {label}</span>
      <span style={{ fontSize: '7.5pt', color: COLORS.slate600, fontStyle: 'italic' }}>{sub}</span>
    </div>
  )

  /**
   * ServiceNode — flat, no own border. Used INSIDE a tinted layer card so the
   * whole layer reads as one panel rather than nested boxes (which is what
   * was causing the architecture diagram to overflow).
   */
  const ServiceNode = ({ kicker, title, subtitle, items, footer, accent }: { kicker?: string; title: string; subtitle?: string; items: string[]; footer?: string; accent: string }) => (
    <div style={{ padding: '0 1mm', display: 'flex', flexDirection: 'column' }}>
      {kicker && <div style={{ fontFamily: MONO, fontSize: '6pt', fontWeight: 700, color: accent, textTransform: 'uppercase', letterSpacing: '0.16em', marginBottom: '0.5mm' }}>{kicker}</div>}
      <div style={{ fontSize: '10pt', fontWeight: 700, color: COLORS.slate900, lineHeight: 1.15 }}>{title}</div>
      {subtitle && <div style={{ fontSize: '7.5pt', color: accent, fontWeight: 600, marginTop: '0.5mm' }}>{subtitle}</div>}
      <div style={{ marginTop: '1.5mm' }}>
        {items.slice(0, 4).map((it, i) => (
          <div key={i} style={{ fontSize: '7pt', color: COLORS.slate700, lineHeight: 1.35, padding: '0.4mm 0', borderTop: i > 0 ? `1px solid ${COLORS.slate100}` : 'none' }}>&middot; {it}</div>
        ))}
      </div>
      {footer && <div style={{ marginTop: '1.5mm', paddingTop: '1mm', borderTop: `1px solid ${COLORS.slate200}`, fontFamily: MONO, fontSize: '6pt', color: COLORS.slate500, lineHeight: 1.4 }}>{footer}</div>}
    </div>
  )

  const productLayerBg = `linear-gradient(135deg, ${COLORS.violet50} 0%, #ffffff 60%, ${COLORS.violet50} 100%)`
  const proxyLayerBg = `linear-gradient(135deg, ${COLORS.amber50} 0%, #fffaf0 60%, ${COLORS.amber50} 100%)`

  /**
   * Faked-3D layer wrapper: shadow on the bottom edge (heavier than top), a 1px
   * top highlight, a 1px darker bottom seam, and a stagger indent on the right
   * to suggest the stack tilts slightly away from the viewer. This renders
   * crisply in Chromium's print-to-PDF, unlike `transform: rotateX(...)` which
   * has print-pipeline quirks.
   */
  const layerWrap = (indentRight: string, shadowTint: string, glowTop: string, seamBottom: string): React.CSSProperties => ({
    marginRight: indentRight,
    boxShadow: `inset 0 1px 0 ${glowTop}, inset 0 -1px 0 ${seamBottom}, 0 5mm 7mm -4mm ${shadowTint}`,
    WebkitPrintColorAdjust: 'exact',
    printColorAdjust: 'exact',
  })

  /** Connector that reads as "the upper plane resting on the next" — a soft chevron with a shadow. */
  const PlaneConnector = ({ color }: { color: string }) => (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '5mm', position: 'relative' }}>
      <svg viewBox="0 0 40 20" width="14mm" height="5mm" style={{ overflow: 'visible' }}>
        <polygon points="4,2 36,2 30,16 10,16" fill={color} opacity="0.18" />
        <polyline points="10,4 20,14 30,4" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    </div>
  )

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '1.5mm' }}>
      {/* APPLICATION (PRODUCT) LAYER — top plane, smallest indent footprint */}
      <div style={{
        background: productLayerBg,
        border: `1px solid ${COLORS.violet200}`,
        borderRadius: '4pt',
        padding: '3mm 4mm',
        ...layerWrap('0mm', 'rgba(59,26,122,0.20)', 'rgba(255,255,255,0.85)', COLORS.violet200),
      }}>
        <LayerChip n="01" label={de ? 'Application Layer' : 'Application Layer'} sub={de ? 'Kundenseitige Services' : 'User-facing services'} tint={COLORS.violet600} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '5mm' }}>
          {product.map((p, i) => (
            <ServiceNode key={i} kicker={p.kicker} title={p.title} subtitle={p.subtitle} items={p.services} accent={COLORS.violet600} footer={p.tech} />
          ))}
        </div>
      </div>

      <PlaneConnector color={COLORS.violet500} />

      {/* GATEWAY LAYER — middle plane, slight indent, slightly heavier shadow */}
      <div style={{
        background: proxyLayerBg,
        border: `1.5px solid ${COLORS.amber600}`,
        borderRadius: '4pt',
        padding: '3mm 4mm',
        ...layerWrap('2mm', 'rgba(180,83,9,0.22)', 'rgba(255,255,255,0.85)', '#e9b56a'),
      }}>
        <LayerChip n="02" label={de ? 'Gateway Layer' : 'Gateway Layer'} sub={de ? 'Routing & Guardrails' : 'Routing & guardrails'} tint={COLORS.amber700} />
        <div style={{ display: 'flex', alignItems: 'baseline', gap: '4mm', marginBottom: '2mm' }}>
          <span style={{ fontSize: '12pt', fontWeight: 800, color: COLORS.slate900, letterSpacing: '-0.005em' }}>{proxy.title}</span>
          <span style={{ fontFamily: MONO, fontSize: '7pt', color: COLORS.amber700, fontWeight: 600 }}>{proxy.subtitle}</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '3mm', fontSize: '7pt', color: COLORS.slate700 }}>
          {proxy.features.map((f, i) => (
            <div key={i} style={{ paddingLeft: '2mm', borderLeft: `1px solid ${COLORS.amber600}`, lineHeight: 1.3 }}>{f}</div>
          ))}
        </div>
      </div>

      <PlaneConnector color={COLORS.amber600} />

      {/* INFRASTRUCTURE (INFERENCE) LAYER — foundation, deepest indent + shadow */}
      <div style={{
        background: productLayerBg,
        border: `1px solid ${COLORS.violet300}`,
        borderRadius: '4pt',
        padding: '3.5mm 4mm',
        ...layerWrap('4mm', 'rgba(59,26,122,0.28)', 'rgba(255,255,255,0.85)', COLORS.violet300),
      }}>
        <LayerChip n="03" label={de ? 'Infrastructure Layer' : 'Infrastructure Layer'} sub={de ? 'Compute & Daten · lokal · air-gap-fähig' : 'Compute & data · local · air-gap capable'} tint={COLORS.violet600} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '5mm' }}>
          {inference.map((p, i) => (
            <ServiceNode key={i} title={p.title} subtitle={p.subtitle} items={[p.desc]} accent={COLORS.violet500} footer={p.tech} />
          ))}
        </div>
      </div>
    </div>
  )
}

/** Connected loop diagram for the USP "Compliance ↔ Code always in sync" closing card */
export function LoopDiagram({ lang }: { lang: 'de' | 'en' }) {
  const de = lang === 'de'
  return (
    <svg viewBox="0 0 320 80" style={{ width: '100%', height: '24mm', display: 'block' }}>
      <defs>
        <marker id="arrR" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse">
          <path d="M0,0 L10,5 L0,10 z" fill={COLORS.indigo600} />
        </marker>
      </defs>
      {/* Compliance box */}
      <rect x="6" y="20" width="80" height="40" rx="2" fill={COLORS.indigo50} stroke={COLORS.indigo600} strokeWidth="1" />
      <text x="46" y="38" fontSize="9" fontWeight="700" textAnchor="middle" fill={COLORS.indigo700}>Compliance</text>
      <text x="46" y="52" fontSize="7" textAnchor="middle" fill={COLORS.slate600}>{de ? 'Policies · Audits · VVT' : 'Policies · Audits · RoPA'}</text>

      {/* Code box */}
      <rect x="234" y="20" width="80" height="40" rx="2" fill={COLORS.indigo50} stroke={COLORS.indigo600} strokeWidth="1" />
      <text x="274" y="38" fontSize="9" fontWeight="700" textAnchor="middle" fill={COLORS.indigo700}>Code</text>
      <text x="274" y="52" fontSize="7" textAnchor="middle" fill={COLORS.slate600}>{de ? 'Repos · CI/CD · Findings' : 'Repos · CI/CD · Findings'}</text>

      {/* Top arrow: compliance → code */}
      <path d="M86,30 Q160,5 234,30" fill="none" stroke={COLORS.indigo600} strokeWidth="1.4" markerEnd="url(#arrR)" />
      <text x="160" y="12" fontSize="7" fontWeight="600" textAnchor="middle" fill={COLORS.indigo700}>{de ? 'Policies → Code (Real-time)' : 'Policies → Code (Real-time)'}</text>

      {/* Bottom arrow: code → compliance */}
      <path d="M234,50 Q160,75 86,50" fill="none" stroke={COLORS.indigo600} strokeWidth="1.4" markerEnd="url(#arrR)" />
      <text x="160" y="72" fontSize="7" fontWeight="600" textAnchor="middle" fill={COLORS.indigo700}>{de ? 'Code-Δ → Evidence (Auto)' : 'Code-Δ → Evidence (Auto)'}</text>
    </svg>
  )
}

/** 4-stage horizontal pipeline (e.g. RAG pipeline ingestion → ... → QA) */
export function PipelineFlow({
  stages, accent = COLORS.indigo600,
}: {
  stages: { n: string; t: string; d: string; kpi?: string }[]
  accent?: string
}) {
  return (
    <div style={{ display: 'flex', alignItems: 'stretch' }}>
      {stages.map((s, i) => (
        <React.Fragment key={i}>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
            <div style={{
              border: `1px solid ${COLORS.slate200}`,
              borderTop: `3px solid ${accent}`,
              padding: '3mm 4mm',
              display: 'flex',
              flexDirection: 'column',
              height: '100%',
              WebkitPrintColorAdjust: 'exact',
              printColorAdjust: 'exact',
            }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: '2mm' }}>
                <span style={{ fontSize: '18pt', fontWeight: 800, color: accent, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{s.n}</span>
                {s.kpi && <span style={{ fontSize: '7pt', color: COLORS.emerald700, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{s.kpi}</span>}
              </div>
              <div style={{ fontSize: '11pt', fontWeight: 700, color: COLORS.slate900, lineHeight: 1.2, marginBottom: '2mm' }}>{s.t}</div>
              <div style={{ fontSize: '8pt', color: COLORS.slate700, lineHeight: 1.5, flex: 1 }}>{s.d}</div>
            </div>
          </div>
          {i < stages.length - 1 && (
            <div style={{ width: '7mm', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg viewBox="0 0 24 24" style={{ width: '6mm', height: '6mm' }}>
                <line x1="2" y1="12" x2="18" y2="12" stroke={accent} strokeWidth="1.5" />
                <polyline points="14,6 20,12 14,18" fill="none" stroke={accent} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
          )}
        </React.Fragment>
      ))}
    </div>
  )
}
