/* BrandArchway — ROI Calculator
   Live tool: BrandArchway one-time investment vs ongoing agency retainer,
   plotted over time, with break-even and savings highlighted. */

const { useState: useStateRoi, useMemo: useMemoRoi } = React;
const { useEffect: useEffectRoi, useRef: useRefRoi } = React;

/* ── COUNT-UP HOOK ──
   Eases a displayed number toward its target whenever the target changes,
   so every slider move feels like the figure is "settling" into place. */
function useCountUp(target, { duration = 650 } = {}) {
  const [display, setDisplay] = useStateRoi(target);
  const fromRef = useRefRoi(target);
  const rafRef = useRefRoi(null);
  const startRef = useRefRoi(0);

  useEffectRoi(() => {
    const from = fromRef.current;
    const to = target;
    if (from === to) return;
    startRef.current = 0;
    const ease = p => 1 - Math.pow(1 - p, 3); // easeOutCubic
    const step = (ts) => {
      if (!startRef.current) startRef.current = ts;
      const p = Math.min(1, (ts - startRef.current) / duration);
      const v = from + (to - from) * ease(p);
      setDisplay(v);
      if (p < 1) {
        rafRef.current = requestAnimationFrame(step);
      } else {
        fromRef.current = to;
        setDisplay(to);
      }
    };
    rafRef.current = requestAnimationFrame(step);
    return () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); fromRef.current = to; };
  }, [target, duration]);

  return display;
}

/* Animated euro figure — counts up/down on change. */
function CountEur({ value, full = true, style }) {
  const v = useCountUp(value);
  const txt = full ? fmtEurFull(Math.round(v)) : fmtEur(Math.round(v));
  return <span style={style}>{txt}</span>;
}


/* ── ENGAGEMENT PLANS — labels translated, numbers fixed ── */
const PLANS = {
  full: {
    key: 'full',
    get label() { return T.roi.plans.full.label; },
    get sub() { return T.roi.plans.full.sub; },
    duration: 12,
    upfront: 12000,
    monthlyFee: 1500,
    monthlyStart: 4,
    monthlyEnd: 12,
    get total() { return this.upfront + this.monthlyFee * (this.monthlyEnd - this.monthlyStart + 1); },
  },
  two: {
    key: 'two',
    get label() { return T.roi.plans.two.label; },
    get sub() { return T.roi.plans.two.sub; },
    duration: 6,
    upfront: 12000,
    monthlyFee: 1500,
    monthlyStart: 4,
    monthlyEnd: 6,
    get total() { return this.upfront + this.monthlyFee * (this.monthlyEnd - this.monthlyStart + 1); },
  },
  single: {
    key: 'single',
    get label() { return T.roi.plans.single.label; },
    get sub() { return T.roi.plans.single.sub; },
    duration: 3,
    upfront: 9000,
    monthlyFee: 0,
    monthlyStart: 99,
    monthlyEnd: 99,
    get total() { return this.upfront; },
  },
};

/* ── MATH ── */
function archwayCum(t, plan) {
  if (t <= 0) return 0;
  let cum = plan.upfront; // paid at month 1
  if (plan.monthlyFee > 0 && t >= plan.monthlyStart) {
    const monthsPaid = Math.min(t, plan.monthlyEnd) - plan.monthlyStart + 1;
    cum += plan.monthlyFee * Math.max(0, monthsPaid);
  }
  return cum;
}
function agencyCum(t, monthly) {
  if (t <= 0) return 0;
  return monthly * t;
}
function niceCeil(v) {
  if (v <= 0) return 100000;
  const mag = Math.pow(10, Math.floor(Math.log10(v)));
  const norm = v / mag;
  const nice = norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 2.5 ? 2.5 : norm <= 5 ? 5 : 10;
  return nice * mag;
}
function fmtEur(v) {
  if (v >= 1_000_000) return `€${(v / 1_000_000).toFixed(2).replace(/\.?0+$/, '')}M`;
  if (v >= 10_000) return `€${Math.round(v / 1000)}k`;
  if (v >= 1000) return `€${(v / 1000).toFixed(1).replace(/\.0$/, '')}k`;
  return `€${Math.round(v).toLocaleString('en-US')}`;
}
function fmtEurFull(v) {
  return `€${Math.round(v).toLocaleString('en-US')}`;
}
function fmtMonthLabel(m) {
  if (m <= 0) return T.roi.todayLabel;
  if (m <= 12) return T.roi.monthN(m);
  const yrs = Math.floor(m / 12);
  const rem = m % 12;
  if (rem === 0) return T.roi.yearN(yrs);
  return T.roi.yearMonthN(yrs, rem);
}

/* ── SLIDER (custom track via linear-gradient) ── */
function RoiSlider({ value, min, max, step, onChange }) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <input
      type="range"
      min={min} max={max} step={step} value={value}
      onChange={e => onChange(Number(e.target.value))}
      className="roi-slider"
      style={{
        background: `linear-gradient(to right, ${C.primary} 0%, ${C.primary} ${pct}%, ${C.hairline} ${pct}%, ${C.hairline} 100%)`,
      }}
    />
  );
}

/* ── ENGAGEMENT TOGGLE ── */
function PlanToggle({ value, onChange }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
      gap: 8,
    }}>
      {Object.values(PLANS).map(p => {
        const active = value === p.key;
        return (
          <button
            key={p.key}
            onClick={() => onChange(p.key)}
            style={{
              background: active ? C.ink : C.card,
              color: active ? C.onDark : C.bodyStrong,
              border: `1px solid ${active ? C.ink : C.hairline}`,
              borderRadius: 10,
              padding: '14px 12px',
              cursor: 'pointer',
              textAlign: 'left',
              transition: 'background 0.15s, border-color 0.15s, color 0.15s',
              display: 'flex', flexDirection: 'column', gap: 4,
              fontFamily: 'Inter, sans-serif',
            }}
          >
            <span style={{ fontSize: 14, fontWeight: 700, lineHeight: 1.2 }}>{p.label}</span>
            <span style={{ fontSize: 11, opacity: 0.7, lineHeight: 1.35 }}>{fmtEur(p.total)} {T.roi.planTotalSuffix}</span>
          </button>
        );
      })}
    </div>
  );
}

/* ── CHART ── */
function RoiChart({ years, agencyMonthly, plan }) {
  const months = years * 12;
  const series = useMemoRoi(() => {
    const s = [];
    for (let t = 0; t <= months; t++) {
      s.push({ t, a: agencyCum(t, agencyMonthly), b: archwayCum(t, plan) });
    }
    return s;
  }, [months, agencyMonthly, plan]);

  // Break-even: first month where archway is BELOW agency cumulatively
  const breakIdx = series.findIndex((p, i) => i > 0 && p.b < p.a);

  const W = 1080, H = 380;
  const padL = 76, padR = 32, padT = 36, padB = 52;
  const innerW = W - padL - padR;
  const innerH = H - padT - padB;
  const lastAgency = series[months].a;
  const niceMax = niceCeil(Math.max(lastAgency, plan.total) * 1.05);
  const X = t => padL + (t / months) * innerW;
  const Y = v => padT + innerH - (v / niceMax) * innerH;

  const agencyPath = series.map((p, i) => `${i ? 'L' : 'M'} ${X(p.t).toFixed(2)} ${Y(p.a).toFixed(2)}`).join(' ');
  const archwayPath = series.map((p, i) => `${i ? 'L' : 'M'} ${X(p.t).toFixed(2)} ${Y(p.b).toFixed(2)}`).join(' ');

  let savingsArea = '';
  if (breakIdx > 0) {
    const seg = series.slice(breakIdx);
    const top = seg.map((p, i) => `${i ? 'L' : 'M'} ${X(p.t).toFixed(2)} ${Y(p.a).toFixed(2)}`).join(' ');
    const bot = [...seg].reverse().map(p => `L ${X(p.t).toFixed(2)} ${Y(p.b).toFixed(2)}`).join(' ');
    savingsArea = `${top} ${bot} Z`;
  }

  // X year ticks
  const xTicks = [];
  for (let y = 0; y <= years; y++) {
    xTicks.push({ t: y * 12, label: y === 0 ? T.roi.todayLabel : T.roi.yearN(y) });
  }
  // Y ticks (5 lines)
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(f => ({ v: niceMax * f }));

  const agencyEndY = Y(lastAgency);
  const archwayEndY = Y(series[months].b);

  return (
    <div style={{ background: C.card, borderRadius: 16, padding: '24px 28px 12px', border: `1px solid ${C.hairlineSoft}` }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: C.primary, letterSpacing: '1.2px', textTransform: 'uppercase', marginBottom: 4 }}>
            {T.roi.chartEyebrow}
          </div>
          <div style={{ fontSize: 16, fontWeight: 700, color: C.ink, letterSpacing: '-0.2px' }}>
            {T.roi.chartTitle}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: C.bodyStrong }}>
            <span style={{ width: 22, height: 3, background: C.ink, borderRadius: 2 }}></span>
            {T.roi.legendAgency}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: C.bodyStrong }}>
            <span style={{ width: 22, height: 3, background: C.primary, borderRadius: 2 }}></span>
            {T.roi.legendArchway}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: C.bodyStrong }}>
            <span style={{ width: 14, height: 10, background: 'rgba(46,196,113,0.24)', border: '1px solid rgba(46,196,113,0.5)', borderRadius: 2 }}></span>
            {T.roi.legendSavings}
          </div>
        </div>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
        {/* Y grid */}
        {yTicks.map(t => (
          <g key={t.v}>
            <line x1={padL} x2={padL + innerW} y1={Y(t.v)} y2={Y(t.v)} stroke={C.hairlineSoft} strokeWidth="1" />
            <text x={padL - 12} y={Y(t.v) + 4} textAnchor="end" fontSize="11" fill={C.muted} fontFamily="Inter">
              {fmtEur(t.v)}
            </text>
          </g>
        ))}
        {/* X labels */}
        {xTicks.map(t => (
          <g key={t.t}>
            <line x1={X(t.t)} x2={X(t.t)} y1={padT + innerH} y2={padT + innerH + 5} stroke={C.muted} strokeWidth="1" />
            <text x={X(t.t)} y={padT + innerH + 22} textAnchor="middle" fontSize="11" fill={C.muted} fontFamily="Inter">
              {t.label}
            </text>
          </g>
        ))}
        {/* Savings area */}
        {savingsArea && <path className="roi-savings-area" d={savingsArea} fill="rgba(46,196,113,0.20)" />}
        {/* Agency line */}
        <path className="roi-line roi-line-agency" d={agencyPath} pathLength="1" fill="none" stroke={C.ink} strokeWidth="2.5" strokeLinejoin="round" />
        {/* Archway line */}
        <path className="roi-line roi-line-archway" d={archwayPath} pathLength="1" fill="none" stroke={C.primary} strokeWidth="2.5" strokeLinejoin="round" />
        {/* Live endpoint pulse on the BrandArchway line */}
        <circle className="roi-pulse" cx={padL + innerW} cy={archwayEndY} r="5" fill={C.primary} />
        <circle cx={padL + innerW} cy={archwayEndY} r="4" fill={C.primary} stroke={C.card} strokeWidth="1.5" />
        {/* Break-even marker */}
        {breakIdx > 0 && (
          <g>
            <line x1={X(breakIdx)} x2={X(breakIdx)} y1={padT} y2={padT + innerH}
              stroke={C.muted} strokeWidth="1" strokeDasharray="4 4" opacity="0.5" />
            <circle cx={X(breakIdx)} cy={Y(series[breakIdx].a)} r="5" fill={C.primary} stroke={C.card} strokeWidth="2" />
            <g transform={`translate(${X(breakIdx) + 10}, ${padT + 4})`}>
              <rect x="0" y="0" width="160" height="34" rx="8" fill={C.ink} />
              <text x="14" y="14" fontSize="9.5" fill={C.primary} fontFamily="Inter" fontWeight="700" letterSpacing="0.6">
                {T.roi.chartBreakEvenLabel}
              </text>
              <text x="14" y="28" fontSize="12" fill={C.onDark} fontFamily="Inter" fontWeight="600">
                {T.roi.chartBreakEvenBy(fmtMonthLabel(breakIdx))}
              </text>
            </g>
          </g>
        )}
        {/* End labels — placed inside the chart at the right edge */}
        <g transform={`translate(${padL + innerW - 8}, ${agencyEndY - 12})`}>
          <text textAnchor="end" fontSize="12" fill={C.ink} fontFamily="Inter" fontWeight="700">
            {T.roi.chartAgencyEndLabel(fmtEurFull(lastAgency))}
          </text>
        </g>
        <g transform={`translate(${padL + innerW - 8}, ${archwayEndY + 22})`}>
          <text textAnchor="end" fontSize="12" fill={C.primary} fontFamily="Inter" fontWeight="700">
            {T.roi.chartArchwayEndLabel(fmtEurFull(series[months].b))}
          </text>
        </g>
      </svg>
    </div>
  );
}

/* ── HEADLINE STAT CARDS ── */
function StatBig({ label, value, sub, accent, hint }) {
  return (
    <div style={{
      background: C.card, borderRadius: 14, padding: '20px 22px',
      border: `1px solid ${C.hairlineSoft}`,
      display: 'flex', flexDirection: 'column', gap: 6,
    }}>
      <div style={{
        fontSize: 11, fontWeight: 700, color: C.muted,
        letterSpacing: '0.8px', textTransform: 'uppercase',
      }}>
        {label}
      </div>
      <div style={{
        fontSize: 28, fontWeight: 700, color: accent || C.ink, lineHeight: 1.1,
        letterSpacing: '-0.6px', fontVariantNumeric: 'tabular-nums',
      }}>
        {value}
      </div>
      {sub && <div style={{ fontSize: 13, color: C.bodyStrong, lineHeight: 1.45, fontWeight: 500 }}>{sub}</div>}
      {hint && <div style={{ fontSize: 12, color: C.muted, lineHeight: 1.45 }}>{hint}</div>}
    </div>
  );
}

/* ── CONTROL BLOCK ── */
function ControlBlock({ label, hint, value, children }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: C.bodyStrong, letterSpacing: '0.2px' }}>
          {label}
        </div>
        {value !== undefined && (
          <div style={{ fontSize: 18, fontWeight: 700, color: C.ink, letterSpacing: '-0.3px', fontVariantNumeric: 'tabular-nums' }}>
            {value}
          </div>
        )}
      </div>
      {children}
      {hint && <div style={{ fontSize: 12, color: C.muted, marginTop: 8, lineHeight: 1.45 }}>{hint}</div>}
    </div>
  );
}

/* ── ROOT: ROI CALCULATOR SECTION ── */
function useRoiState() {
  const [agencyMonthly, setAgencyMonthly] = useStateRoi(5000);
  const [years, setYears] = useStateRoi(5);
  const [planKey, setPlanKey] = useStateRoi('full');
  return {
    agencyMonthly, setAgencyMonthly,
    years, setYears,
    planKey, setPlanKey,
    plan: PLANS[planKey],
  };
}

function RoiCalculator({ state }) {
  const {
    agencyMonthly, setAgencyMonthly,
    years, setYears,
    planKey, setPlanKey,
    plan,
  } = state;

  const months = years * 12;
  const totalAgency = agencyCum(months, agencyMonthly);
  const totalArchway = archwayCum(months, plan);
  const savings = Math.max(0, totalAgency - totalArchway);

  // Break-even
  let breakEven = null;
  for (let t = 1; t <= months; t++) {
    if (agencyCum(t, agencyMonthly) > archwayCum(t, plan)) { breakEven = t; break; }
  }

  // After-handover yearly redirect
  const yearlyRedirect = agencyMonthly * 12;
  const postEngagementYears = Math.max(0, years - 1);
  const redirected = yearlyRedirect * postEngagementYears;

  // Reveal-on-scroll for the calculator card
  const cardRef = useRefRoi(null);
  useEffectRoi(() => {
    const el = cardRef.current;
    if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(en => { if (en.isIntersecting) { en.target.classList.add('in'); obs.unobserve(en.target); } });
    }, { threshold: 0.12 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  return (
    <section className="wave-bg" style={{ padding: '120px 0' }} data-screen-label="04 ROI">
      <WaveOverlay />
      <div style={sharedStyles.containerWide}>
        {/* Bridge from the timeline — provocations, not pitch */}
        <div style={{
          maxWidth: 820, marginBottom: 40,
          paddingBottom: 32, borderBottom: `1px solid ${C.hairline}`,
        }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            background: C.primary,
            color: C.onDark,
            borderRadius: 9999,
            padding: '10px 20px 10px 16px',
            marginBottom: 22,
            boxShadow: '0 6px 20px rgba(161,0,255,0.30)',
          }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%',
              background: C.onDark, flexShrink: 0, display: 'block',
              boxShadow: '0 0 0 0 rgba(255,255,255,0.7)',
              animation: 'roiBadgePulse 2.2s ease-out infinite',
            }}></span>
            <span style={{
              fontFamily: 'Inter, sans-serif', fontSize: 14, fontWeight: 700,
              letterSpacing: '0.4px',
            }}>
              {T.roi.badge}
            </span>
          </div>
          <p style={{
            fontFamily: 'Inter, sans-serif',
            fontSize: 'clamp(22px, 2.4vw, 28px)', fontWeight: 600,
            color: C.ink, lineHeight: 1.3, letterSpacing: '-0.4px',
            marginBottom: 20, textWrap: 'balance',
          }}>
            {T.roi.leadHook}
          </p>
          <p style={{ fontSize: 17, color: C.body, lineHeight: 1.65, marginBottom: 12 }}>
            {T.roi.leadP1}
          </p>
          <p style={{ fontSize: 17, color: C.body, lineHeight: 1.65 }}>
            {T.roi.leadP2}
          </p>
        </div>

        {/* The provocation question — small label + bold question */}
        <div style={{ maxWidth: 760, marginBottom: 36 }}>
          <SectionLabel text={T.roi.questionEyebrow} />
          <h2 style={{
            fontFamily: 'Inter, sans-serif', fontSize: 'clamp(36px, 4.6vw, 56px)', fontWeight: 700,
            lineHeight: 1.04, letterSpacing: '-1.3px', color: C.ink, marginBottom: 22, textWrap: 'balance',
          }}>
            {T.roi.questionTitleA}
            <em style={PAYOFF}>{T.roi.questionTitleB}</em>
          </h2>
          <p style={{ fontSize: 18, color: C.body, lineHeight: 1.65, maxWidth: 640, marginBottom: 18 }}>
            {T.roi.questionSub}
          </p>
          <p style={{
            fontSize: 16, color: C.bodyStrong, lineHeight: 1.6,
            fontStyle: 'italic', maxWidth: 640,
          }}>
            {T.roi.questionItalicLead}<strong style={{ color: C.ink, fontStyle: 'normal' }}>{T.roi.questionItalicQuote}</strong>{T.roi.questionItalicTail}
          </p>
        </div>

        {/* Three quick anchors of difference */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16,
          marginBottom: 48,
        }} className="roi-anchors">
          {T.roi.anchors.map(a => (
            <div key={a.k} style={{
              background: C.card, borderRadius: 14, padding: '20px 22px',
              border: `1px solid ${C.hairlineSoft}`,
              display: 'flex', flexDirection: 'column', gap: 6,
            }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: C.ink, letterSpacing: '-0.2px' }}>{a.k}</div>
              <div style={{ fontSize: 13, color: C.body, lineHeight: 1.55 }}>{a.v}</div>
            </div>
          ))}
        </div>

        {/* Calculator card */}
        <div ref={cardRef} className="roi-reveal" style={{
          background: C.surfaceSoft,
          borderRadius: 24,
          padding: 32,
          border: `1px solid ${C.hairline}`,
        }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '340px 1fr',
            gap: 32,
            alignItems: 'stretch',
          }} className="roi-grid">
            {/* LEFT: Controls */}
            <div style={{
              background: C.card, borderRadius: 16, padding: 28,
              display: 'flex', flexDirection: 'column', gap: 28,
              border: `1px solid ${C.hairlineSoft}`,
            }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, color: C.primary, letterSpacing: '1.2px', textTransform: 'uppercase', marginBottom: 4 }}>
                  {T.roi.inputsEyebrow}
                </div>
                <div style={{ fontSize: 18, fontWeight: 700, color: C.ink, letterSpacing: '-0.3px' }}>
                  {T.roi.inputsTitle}
                </div>
                <div style={{ fontSize: 13, color: C.body, lineHeight: 1.5, marginTop: 6 }}>
                  {T.roi.inputsSub}
                </div>
              </div>

              <ControlBlock
                label={T.roi.ctlRetainer}
                value={`€${agencyMonthly.toLocaleString('en-US')} / ${T.roi.perMonthAbbrev}`}
                hint={T.roi.ctlRetainerHint}
              >
                <RoiSlider value={agencyMonthly} min={1000} max={15000} step={250}
                  onChange={setAgencyMonthly} />
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11, color: C.muted, fontVariantNumeric: 'tabular-nums' }}>
                  <span>€1,000</span><span>€15,000</span>
                </div>
              </ControlBlock>

              <ControlBlock
                label={T.roi.ctlHorizon}
                value={`${years} ${years > 1 ? T.roi.yearPlural : T.roi.yearSingular}`}
                hint={T.roi.ctlHorizonHint}
              >
                <RoiSlider value={years} min={1} max={10} step={1}
                  onChange={setYears} />
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11, color: C.muted, fontVariantNumeric: 'tabular-nums' }}>
                  <span>1 {T.roi.yearSingular}</span><span>10 {T.roi.yearPlural}</span>
                </div>
              </ControlBlock>

              <ControlBlock
                label={T.roi.ctlEngagement}
                hint={T.roi.planHint(plan.sub, fmtEurFull(plan.total), plan.duration)}
              >
                <PlanToggle value={planKey} onChange={setPlanKey} />
              </ControlBlock>
            </div>

            {/* RIGHT: Results + chart */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {/* Side-by-side comparison */}
              <div style={{
                display: 'grid', gridTemplateColumns: '1fr 24px 1fr', gap: 0,
                background: C.card, borderRadius: 16, overflow: 'hidden',
                border: `1px solid ${C.hairlineSoft}`,
              }} className="roi-versus">
                {/* Agency column */}
                <div style={{ padding: '24px 24px 22px' }}>
                  <div style={{
                    fontSize: 11, fontWeight: 700, color: C.muted,
                    letterSpacing: '1px', textTransform: 'uppercase', marginBottom: 12,
                  }}>
                    {T.roi.agencyHeading(years)}
                  </div>
                  <div style={{
                    fontSize: 'clamp(32px, 4vw, 44px)', fontWeight: 700, color: C.ink,
                    lineHeight: 1, letterSpacing: '-1px', fontVariantNumeric: 'tabular-nums',
                  }}>
                    <CountEur value={totalAgency} />
                  </div>
                  <div style={{ fontSize: 13, color: C.body, lineHeight: 1.5, marginTop: 10 }}>
                    {T.roi.agencyExplain(agencyMonthly.toLocaleString('en-US'), years * 12)}
                  </div>
                </div>
                {/* Versus divider */}
                <div style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  background: C.surfaceSoft,
                  fontSize: 11, fontWeight: 700, color: C.muted, letterSpacing: '0.8px',
                }} className="roi-versus-vs">
                  {T.roi.versus}
                </div>
                {/* Archway column */}
                <div style={{ padding: '24px 24px 22px', background: 'rgba(161,0,255,0.05)' }}>
                  <div style={{
                    fontSize: 11, fontWeight: 700, color: C.primary,
                    letterSpacing: '1px', textTransform: 'uppercase', marginBottom: 12,
                  }}>
                    {T.roi.archwayHeading}
                  </div>
                  <div style={{
                    fontSize: 'clamp(32px, 4vw, 44px)', fontWeight: 700, color: C.ink,
                    lineHeight: 1, letterSpacing: '-1px', fontVariantNumeric: 'tabular-nums',
                  }}>
                    <CountEur value={totalArchway} />
                  </div>
                  <div style={{ fontSize: 13, color: C.body, lineHeight: 1.5, marginTop: 10 }}>
                    {T.roi.archwayExplain(plan.duration)}
                  </div>
                </div>
              </div>

              {/* Headline result — the single number */}
              <div style={{
                background: C.dark, borderRadius: 16, padding: '28px 32px',
                display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, alignItems: 'center',
              }} className="roi-headline">
                <div>
                  <div style={{ fontSize: 12, fontWeight: 700, color: C.primary, letterSpacing: '1.2px', textTransform: 'uppercase', marginBottom: 8 }}>
                    {T.roi.stayHeading(years)}
                  </div>
                  <div style={{
                    fontFamily: 'Inter, sans-serif', fontSize: 'clamp(48px, 6vw, 72px)', fontWeight: 700,
                    color: C.onDark, lineHeight: 1, letterSpacing: '-1.8px',
                    fontVariantNumeric: 'tabular-nums',
                  }}>
                    <CountEur value={savings} />
                  </div>
                  <div style={{ fontSize: 14, color: C.onDarkSoft, marginTop: 12, lineHeight: 1.55, maxWidth: 460 }}>
                    {T.roi.stayExplain(years * 12)}
                  </div>
                </div>
                <div style={{
                  background: C.darkElevated, borderRadius: 12, padding: '16px 18px',
                  borderLeft: `3px solid ${C.primary}`,
                  minWidth: 200,
                }} className="roi-breakeven">
                  <div style={{ fontSize: 11, fontWeight: 700, color: C.primary, letterSpacing: '1px', textTransform: 'uppercase', marginBottom: 6 }}>
                    {T.roi.breakEvenLabel}
                  </div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: C.onDark, lineHeight: 1.2, letterSpacing: '-0.4px' }}>
                    {breakEven ? fmtMonthLabel(breakEven) : T.roi.breakEvenNone}
                  </div>
                  <div style={{ fontSize: 12, color: C.onDarkSoft, marginTop: 6, lineHeight: 1.45 }}>
                    {breakEven ? T.roi.breakEvenSub : T.roi.breakEvenNoneSub}
                  </div>
                </div>
              </div>

              {/* Chart */}
              <RoiChart years={years} agencyMonthly={agencyMonthly} plan={plan} />

              {/* Secondary stats with plainer labels */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }} className="roi-stats">
                <StatBig
                  label={T.roi.stats.year1Label}
                  value={<CountEur value={archwayCum(12, plan)} />}
                  sub={T.roi.stats.year1Sub(fmtEurFull(agencyCum(12, agencyMonthly)))}
                  hint={T.roi.stats.year1Hint}
                />
                <StatBig
                  label={T.roi.stats.savedLabel}
                  value={<CountEur value={yearlyRedirect} />}
                  sub={T.roi.stats.savedSub}
                  hint={T.roi.stats.savedHint}
                  accent={C.primary}
                />
                <StatBig
                  label={T.roi.stats.keptLabel(years)}
                  value={<CountEur value={redirected} />}
                  sub={T.roi.stats.keptSub(postEngagementYears)}
                  hint={T.roi.stats.keptHint}
                />
              </div>

              {/* Reframe strip */}
              <div style={{
                background: C.card, borderRadius: 14, padding: '20px 24px',
                border: `1px solid ${C.hairlineSoft}`,
                display: 'flex', gap: 16, alignItems: 'flex-start',
              }}>
                <div style={{
                  width: 30, height: 30, borderRadius: '50%',
                  background: 'rgba(161,0,255,0.10)', color: C.primary,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0, fontFamily: 'Libre Baskerville, serif', fontStyle: 'italic',
                  fontSize: 18, lineHeight: 1,
                }}>
                  i
                </div>
                <div style={{ fontSize: 14, color: C.body, lineHeight: 1.6 }}>
                  <strong style={{ color: C.ink }}>{T.roi.howToReadLead}</strong>{T.roi.howToReadBody}
                  <em style={PAYOFF}>{T.roi.howToReadTail}</em>
                </div>
              </div>
            </div>
          </div>
        </div>

        <p style={{ fontSize: 12, color: C.muted, marginTop: 16, textAlign: 'center', letterSpacing: '0.1px' }}>
          {T.roi.pricingFootnote}
        </p>
      </div>
    </section>
  );
}

/* ── INVEST-BACK SECTION ──
   Reframes the savings as a recurring growth budget, with four concrete redirect paths.
   Reads from the same state as the calculator above. */
function InvestBack({ state }) {
  const { agencyMonthly, years } = state;

  // Live numbers
  const yearlyRedirect = agencyMonthly * 12;
  const monthly = agencyMonthly;
  const postYears = Math.max(0, years - 1);
  const totalRedirected = yearlyRedirect * postYears;

  // Per-card derived figures
  const adMonthly = Math.round(agencyMonthly * 0.85 / 50) * 50;            // 85% into media
  const hireAnnual = yearlyRedirect;                                       // 1 senior hire / yr
  const eventsPerYear = Math.max(1, Math.floor(yearlyRedirect / 15000));   // €15k per premium event
  const toolsAnnual = Math.round(yearlyRedirect * 0.3);                    // ~30% on tools/data
  const remainingForBets = yearlyRedirect - toolsAnnual;

  const cards = [
    {
      tag: 'Paid media',
      title: 'Pour it straight into ads.',
      figure: `${fmtEurFull(adMonthly)} / month`,
      sub: 'in LinkedIn and Google paid media — every month, no contract renewal needed.',
      body: 'The infrastructure is already live in your accounts. The retainer is gone. What used to disappear into agency margin now compounds in your pipeline.',
    },
    {
      tag: 'Senior hire',
      title: 'Hire the person who runs it.',
      figure: `${fmtEurFull(hireAnnual)} / year`,
      sub: 'covers a senior marketing manager who follows the playbooks you already own.',
      body: 'Same money, on your payroll. A teammate who shows up to standups instead of a contact you email when the dashboard breaks.',
    },
    {
      tag: 'Field & events',
      title: 'Show up where the deals close.',
      figure: `${eventsPerYear}× / year`,
      sub: 'premium trade-show stands, sponsorships, or executive dinners at €15,000 each.',
      body: 'Technical buyers still buy from people they shake hands with. Your former agency budget pays for the room, the booth, and the second flight.',
    },
    {
      tag: 'Stack & bets',
      title: 'Stack the table for your team.',
      figure: `${fmtEurFull(toolsAnnual)} + ${fmtEurFull(remainingForBets)}`,
      sub: 'on tools, intent data and a content stack — with the rest reserved for experimental bets.',
      body: 'Sales Navigator, intent platform, a real video setup — paid for, and still room left to run twelve €5k tests instead of asking permission for one.',
    },
  ];

  return (
    <section style={{ background: C.dark, padding: '120px 0' }} data-screen-label="05 InvestBack">
      <div style={sharedStyles.containerWide}>
        {/* Header */}
        <div style={{ maxWidth: 820, marginBottom: 48 }}>
          <SectionLabel text="Now, the upside" dark />
          <h2 style={{
            fontFamily: 'Inter, sans-serif', fontSize: 'clamp(36px, 5vw, 60px)', fontWeight: 700,
            lineHeight: 1.04, letterSpacing: '-1.4px', color: C.onDark, marginBottom: 22, textWrap: 'balance',
          }}>
            What if that money became your{' '}
            <em style={PAYOFF}>growth budget?</em>
          </h2>
          <p style={{ fontSize: 18, color: C.onDarkSoft, lineHeight: 1.65, maxWidth: 640 }}>
            After month 12, the engagement ends. The retainer you used to send out the door every month stays inside the company &mdash; and it does not stop. Here is what it could become.
          </p>
        </div>

        {/* "From → To" headline strip */}
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 80px 1fr', gap: 0,
          background: C.darkElevated, borderRadius: 20, overflow: 'hidden',
          marginBottom: 32, alignItems: 'stretch',
        }} className="redirect-strip">
          <div style={{ padding: '32px 36px' }}>
            <div style={{
              fontSize: 11, fontWeight: 700, color: C.onDarkMuted, letterSpacing: '1.4px',
              textTransform: 'uppercase', marginBottom: 12,
            }}>
              Today &middot; leaving the building
            </div>
            <div style={{
              fontSize: 'clamp(36px, 4.4vw, 52px)', fontWeight: 700,
              color: C.onDark, lineHeight: 1, letterSpacing: '-1.2px',
              fontVariantNumeric: 'tabular-nums',
              textDecoration: 'line-through', textDecorationColor: 'rgba(255,255,255,0.30)',
              textDecorationThickness: '3px',
            }}>
              {fmtEurFull(yearlyRedirect)}
            </div>
            <div style={{ fontSize: 14, color: C.onDarkMuted, marginTop: 10, lineHeight: 1.5 }}>
              Sent to an agency every year, indefinitely.
            </div>
          </div>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            borderLeft: `1px solid ${C.darkRule}`,
            borderRight: `1px solid ${C.darkRule}`,
          }} className="redirect-arrow">
            <svg width="40" height="20" viewBox="0 0 40 20" fill="none">
              <path d="M0 10 L35 10 M28 3 L35 10 L28 17" stroke={C.primary} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
          <div style={{ padding: '32px 36px', background: 'rgba(161,0,255,0.08)' }}>
            <div style={{
              fontSize: 11, fontWeight: 700, color: C.primary, letterSpacing: '1.4px',
              textTransform: 'uppercase', marginBottom: 12,
            }}>
              Tomorrow &middot; staying inside
            </div>
            <div style={{
              fontSize: 'clamp(36px, 4.4vw, 52px)', fontWeight: 700,
              color: C.onDark, lineHeight: 1, letterSpacing: '-1.2px',
              fontVariantNumeric: 'tabular-nums',
            }}>
              {fmtEurFull(yearlyRedirect)} <span style={{ fontSize: '0.55em', color: C.primary, fontWeight: 600 }}>/ year</span>
            </div>
            <div style={{ fontSize: 14, color: C.onDarkSoft, marginTop: 10, lineHeight: 1.5 }}>
              Your growth budget. {postYears > 0 ? `That is ${fmtEurFull(totalRedirected)} compounding inside your team over the next ${postYears} year${postYears > 1 ? 's' : ''}.` : 'Yours from the day we leave.'}
            </div>
          </div>
        </div>

        {/* Four redirect cards */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16,
        }} className="redirect-cards">
          {cards.map((c, i) => (
            <article key={c.title} style={{
              background: C.darkElevated, borderRadius: 16, padding: 28,
              border: `1px solid ${C.darkRule}`,
              display: 'flex', flexDirection: 'column', gap: 14,
              transition: 'transform 0.2s ease, border-color 0.2s ease',
            }}
              onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-3px)'; e.currentTarget.style.borderColor = 'rgba(161,0,255,0.5)'; }}
              onMouseLeave={e => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.borderColor = C.darkRule; }}
            >
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{
                  fontSize: 11, fontWeight: 700, color: C.primary, letterSpacing: '1.2px', textTransform: 'uppercase',
                }}>
                  {c.tag}
                </div>
                <div style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 12, fontWeight: 700,
                  color: C.onDarkMuted, letterSpacing: '0.5px',
                  fontVariantNumeric: 'tabular-nums',
                }}>
                  0{i + 1}
                </div>
              </div>
              <div style={{
                fontFamily: 'Inter, sans-serif', fontSize: 22, fontWeight: 700,
                color: C.onDark, lineHeight: 1.2, letterSpacing: '-0.4px',
              }}>
                {c.title}
              </div>
              <div style={{
                fontSize: 26, fontWeight: 700, color: C.primary, lineHeight: 1.1,
                letterSpacing: '-0.4px', fontVariantNumeric: 'tabular-nums',
                marginTop: 4,
              }}>
                {c.figure}
              </div>
              <div style={{ fontSize: 13, color: C.onDarkSoft, lineHeight: 1.55 }}>
                {c.sub}
              </div>
              <div style={{
                marginTop: 'auto', paddingTop: 14,
                borderTop: `1px solid ${C.darkRule}`,
                fontSize: 13, color: C.onDarkMuted, lineHeight: 1.55, fontStyle: 'italic',
              }}>
                {c.body}
              </div>
            </article>
          ))}
        </div>

        {/* Closing line */}
        <p style={{
          fontSize: 16, color: C.onDarkSoft, lineHeight: 1.65, marginTop: 36,
          textAlign: 'center', maxWidth: 720, marginLeft: 'auto', marginRight: 'auto',
        }}>
          Pick one. Pick all four. Pick something we have not listed.{' '}
          <span style={{ color: C.onDark, fontWeight: 600 }}>
            The point is that the money stops being someone else&rsquo;s revenue and starts being yours.
          </span>
        </p>
      </div>
    </section>
  );
}

Object.assign(window, { RoiCalculator, useRoiState, InvestBack });
