/* Interactive pricing calculator
   - Monthly volume slider (£10K → £10M, log scale)
   - Customer profile picker → sets corridor mix
   - Live readouts: monthly cost, est. savings, effective FX margin
   - Animated breakdown bars per rail
*/
function PricingCalculator() {
  // log-scale slider — slider value 0–100 maps to £10K–£10M
  const [sliderPos, setSliderPos] = React.useState(48); // ~£500K
  const [profile, setProfile] = React.useState('fintech');

  // Profile presets — corridor mix as percentages
  const PROFILES = {
    marketplace: {
      label: 'Marketplace',
      sub: 'Stripe-style merchant payouts',
      mix: { sepa: 35, fps: 30, swift: 10, usdc: 25 },
    },
    fintech: {
      label: 'Fintech',
      sub: 'Neobank-to-bank settlement',
      mix: { sepa: 25, fps: 25, swift: 15, usdc: 35 },
    },
    crypto: {
      label: 'Crypto-native',
      sub: 'Heavy stablecoin flow',
      mix: { sepa: 10, fps: 10, swift: 5, usdc: 75 },
    },
    treasury: {
      label: 'Treasury',
      sub: 'Multi-entity corporate flow',
      mix: { sepa: 25, fps: 15, swift: 40, usdc: 20 },
    },
  };

  // Rail pricing — bps per transaction
  const RAIL_BPS = { sepa: 15, fps: 12, swift: 35, usdc: 8 };
  const RAIL_LABELS = {
    sepa: 'SEPA Instant',
    fps: 'Faster Payments',
    swift: 'SWIFT GPI',
    usdc: 'USDC on-chain',
  };

  // Compute volume from slider position (log scale)
  const min = 10000, max = 10000000;
  const volume = Math.round(Math.exp(Math.log(min) + (sliderPos / 100) * (Math.log(max) - Math.log(min))) / 1000) * 1000;

  // Tier-based FX margin
  const fxMargin = volume < 250000 ? 0.0030
                 : volume < 1000000 ? 0.0018
                 : volume < 5000000 ? 0.0012
                 : 0.0008;

  // Calculate cost by rail
  const mix = PROFILES[profile].mix;
  const byRail = Object.keys(mix).map((rail) => {
    const railVolume = volume * (mix[rail] / 100);
    const bpsCost = railVolume * (RAIL_BPS[rail] / 10000);
    return { rail, label: RAIL_LABELS[rail], pct: mix[rail], volume: railVolume, cost: bpsCost };
  });
  const railTotal = byRail.reduce((s, r) => s + r.cost, 0);

  // FX cost
  const fxCost = volume * fxMargin;

  // Platform fee — auto-selects tier
  const tier = volume < 25000 ? { name: 'Starter', fee: 0 }
             : volume < 250000 ? { name: 'Growth', fee: 99 }
             : volume < 1500000 ? { name: 'Business', fee: 499 }
             : { name: 'Enterprise', fee: 0 /* custom */ };

  const totalMonth = railTotal + fxCost + tier.fee;
  const effectiveBps = (totalMonth / volume) * 10000;

  // Bank comparison — assume 1.5% FX margin + £25 per international wire (estimate 1 wire / £50K)
  const bankFx = volume * 0.015;
  const bankWires = (volume / 50000) * 25;
  const bankTotal = bankFx + bankWires;
  const savings = Math.max(0, bankTotal - totalMonth);

  return (
    <section id="calculator" className="m-section" style={{ paddingTop: 56 }}>
      <div className="m-container">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 32, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <div className="m-eyebrow" style={{ marginBottom: 14 }}>Calculator</div>
            <h2 style={{
              font: '500 clamp(32px, 3.4vw, 44px)/1.1 var(--font-sans)',
              letterSpacing: '-0.025em', margin: 0,
            }}>
              See what you'd pay.
            </h2>
          </div>
        </div>

        <div style={{
          background: 'var(--m-fg)', color: 'var(--m-bg)',
          borderRadius: 28, padding: 40,
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48,
          position: 'relative', overflow: 'hidden',
        }}>
          {/* Subtle grid texture */}
          <div className="m-grid-bg" style={{ position: 'absolute', inset: 0, opacity: 0.04 }} />

          {/* LEFT — Inputs */}
          <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 36 }}>
            <div>
              <div style={{
                font: '500 11px/1 var(--font-sans)',
                letterSpacing: '0.12em', textTransform: 'uppercase',
                color: 'rgba(255,255,255,0.55)', marginBottom: 14,
              }}>Monthly volume</div>
              <div style={{
                font: '500 56px/1 var(--font-sans)',
                letterSpacing: '-0.03em',
                fontFamily: 'IBM Plex Mono, ui-monospace, monospace',
                fontVariantNumeric: 'tabular-nums',
                color: 'var(--m-bg)',
              }}>£{fmtK(volume)}</div>

              <input
                type="range" min="0" max="100" step="1"
                value={sliderPos}
                onChange={(e) => setSliderPos(+e.target.value)}
                style={{
                  width: '100%', marginTop: 20,
                  WebkitAppearance: 'none', appearance: 'none',
                  height: 4, borderRadius: 999,
                  background: `linear-gradient(to right, var(--m-bg) 0%, var(--m-bg) ${sliderPos}%, rgba(255,255,255,0.18) ${sliderPos}%, rgba(255,255,255,0.18) 100%)`,
                  outline: 'none',
                }}
                className="m-slider"
              />
              <style>{`
                .m-slider::-webkit-slider-thumb {
                  -webkit-appearance: none; appearance: none;
                  width: 18px; height: 18px; border-radius: 999px;
                  background: var(--m-bg);
                  border: 3px solid var(--m-fg);
                  box-shadow: 0 0 0 2px var(--m-bg);
                  cursor: pointer; transition: transform 120ms;
                }
                .m-slider::-webkit-slider-thumb:hover { transform: scale(1.15); }
                .m-slider::-moz-range-thumb {
                  width: 18px; height: 18px; border-radius: 999px;
                  background: var(--m-bg); border: 3px solid var(--m-fg);
                  cursor: pointer;
                }
              `}</style>
              <div style={{
                display: 'flex', justifyContent: 'space-between', marginTop: 8,
                font: '400 11.5px/1 var(--font-sans)',
                color: 'rgba(255,255,255,0.5)',
                fontFamily: 'IBM Plex Mono, ui-monospace, monospace',
              }}>
                <span>£10K</span><span>£100K</span><span>£1M</span><span>£10M</span>
              </div>
            </div>

            <div>
              <div style={{
                font: '500 11px/1 var(--font-sans)',
                letterSpacing: '0.12em', textTransform: 'uppercase',
                color: 'rgba(255,255,255,0.55)', marginBottom: 14,
              }}>Your profile</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {Object.entries(PROFILES).map(([k, p]) => (
                  <button key={k} onClick={() => setProfile(k)}
                    style={{
                      textAlign: 'left',
                      padding: '12px 14px',
                      borderRadius: 12,
                      background: profile === k ? 'var(--m-bg)' : 'rgba(255,255,255,0.06)',
                      color: profile === k ? 'var(--m-fg)' : 'var(--m-bg)',
                      border: '1px solid ' + (profile === k ? 'var(--m-bg)' : 'rgba(255,255,255,0.10)'),
                      cursor: 'pointer',
                      transition: 'background var(--dur-base) var(--ease-standard), color var(--dur-base) var(--ease-standard)',
                    }}>
                    <div style={{ font: '500 13.5px/1.2 var(--font-sans)' }}>{p.label}</div>
                    <div style={{
                      font: '400 11.5px/1.3 var(--font-sans)',
                      color: profile === k ? 'var(--m-fg-3)' : 'rgba(255,255,255,0.55)',
                      marginTop: 4,
                    }}>{p.sub}</div>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* RIGHT — Output */}
          <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 24 }}>
            <div style={{
              background: 'rgba(255,255,255,0.06)',
              borderRadius: 16, padding: 24,
              border: '1px solid rgba(255,255,255,0.10)',
            }}>
              <div style={{
                font: '500 11px/1 var(--font-sans)',
                letterSpacing: '0.12em', textTransform: 'uppercase',
                color: 'rgba(255,255,255,0.55)', marginBottom: 12,
              }}>Your monthly cost · {tier.name}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                <span style={{
                  font: '500 48px/1 var(--font-sans)',
                  letterSpacing: '-0.028em',
                  fontFamily: 'IBM Plex Mono, ui-monospace, monospace',
                  fontVariantNumeric: 'tabular-nums',
                  color: 'var(--m-bg)',
                }}>£{fmtMoney(totalMonth)}</span>
                <span style={{
                  font: '500 13px/1 var(--font-sans)',
                  color: 'rgba(255,255,255,0.55)',
                }}>{effectiveBps.toFixed(1)} bps effective</span>
              </div>

              {/* Breakdown */}
              <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <BreakdownRow label="Platform fee" value={tier.fee} color="rgba(255,255,255,0.6)" pct={(tier.fee / totalMonth) * 100} />
                <BreakdownRow label="FX margin · 0.18%" value={fxCost} color="rgba(255,255,255,0.8)" pct={(fxCost / totalMonth) * 100} />
                <BreakdownRow label="Rail fees · weighted" value={railTotal} color="var(--m-bg)" pct={(railTotal / totalMonth) * 100} />
              </div>
            </div>

            <div style={{
              background: 'rgba(116, 219, 168, 0.10)',
              borderRadius: 16, padding: 20,
              border: '1px solid rgba(116, 219, 168, 0.20)',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div>
                  <div style={{
                    font: '500 11px/1 var(--font-sans)',
                    letterSpacing: '0.12em', textTransform: 'uppercase',
                    color: '#9DE5C2', marginBottom: 10,
                  }}>You'd save vs. a typical bank</div>
                  <div style={{
                    font: '500 28px/1 var(--font-sans)',
                    letterSpacing: '-0.022em',
                    fontFamily: 'IBM Plex Mono, ui-monospace, monospace',
                    fontVariantNumeric: 'tabular-nums',
                    color: '#9DE5C2',
                  }}>£{fmtMoney(savings)}</div>
                </div>
                <div style={{
                  font: '400 12px/1.4 var(--font-sans)',
                  color: 'rgba(157, 229, 194, 0.7)',
                  textAlign: 'right', maxWidth: 180,
                }}>
                  vs. ~1.5% FX margin + £25 per int'l wire
                </div>
              </div>
            </div>

            <div style={{
              padding: '14px 16px',
              border: '1px dashed rgba(255,255,255,0.18)',
              borderRadius: 12,
              font: '400 12.5px/1.4 var(--font-sans)',
              color: 'rgba(255,255,255,0.5)',
            }}>
              Estimates only. Final pricing depends on counterparty mix, corridor cut-offs,
              and any custom terms negotiated with sales above £1M monthly volume.
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function BreakdownRow({ label, value, color, pct }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <span style={{
        font: '400 12.5px/1 var(--font-sans)',
        color: 'rgba(255,255,255,0.7)',
        width: 150, flexShrink: 0,
      }}>{label}</span>
      <div style={{
        flex: 1, height: 4, borderRadius: 999,
        background: 'rgba(255,255,255,0.08)', overflow: 'hidden',
      }}>
        <div style={{
          height: '100%',
          width: `${Math.min(100, pct)}%`,
          background: color,
          transition: 'width var(--dur-slow) var(--ease-standard)',
          borderRadius: 999,
        }} />
      </div>
      <span style={{
        font: '500 13px/1 var(--font-sans)',
        fontFamily: 'IBM Plex Mono, ui-monospace, monospace',
        fontVariantNumeric: 'tabular-nums',
        color: 'var(--m-bg)',
        width: 80, textAlign: 'right',
      }}>£{fmtMoney(value)}</span>
    </div>
  );
}

function fmtK(n) {
  if (n >= 1000000) return (n / 1000000).toFixed(n >= 10000000 ? 0 : 1) + 'M';
  if (n >= 1000) return (n / 1000).toFixed(0) + 'K';
  return n.toString();
}

function fmtMoney(n) {
  if (n === 0) return '0';
  if (n < 10) return n.toFixed(2);
  if (n < 1000) return n.toFixed(0);
  return Math.round(n).toLocaleString('en-GB');
}

window.PricingCalculator = PricingCalculator;
