/* Interactive comparator, timeline, payment calculator, cost chart, feature table */

const { useEffect, useRef, useState, useMemo } = React;

// ============ COST CHART ============
function CostChart() {
  const [hover, setHover] = useState(null);
  const years = [0, 1, 2, 3, 4, 5];
  // Shopify Plus: ~£24k/yr licence + say £8k year-1 setup/maintenance
  const shopifyCum = years.map(y => y === 0 ? 8000 : 8000 + 24000 * y);
  // RVS Option A one-off £19,500 + hosting/support £400/mo standard = £4,800/yr
  const ownedCum = years.map(y => 19500 + 4800 * y);

  const W = 800, H = 340, P = { t: 30, r: 40, b: 40, l: 60 };
  const maxV = 150000;
  const x = (y) => P.l + (y / 5) * (W - P.l - P.r);
  const yScale = (v) => H - P.b - (v / maxV) * (H - P.t - P.b);

  const pathFrom = (arr) => arr.map((v, i) => `${i === 0 ? 'M' : 'L'}${x(i)},${yScale(v)}`).join(' ');
  const areaFrom = (arr) => `${pathFrom(arr)} L${x(5)},${H - P.b} L${x(0)},${H - P.b} Z`;

  return (
    <div className="chart-wrap">
      <div className="chart-legend">
        <span><span className="sw shopify"></span>Shopify Plus (cumulative)</span>
        <span><span className="sw owned"></span>Owned platform (cumulative)</span>
      </div>
      <div className="chart">
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet">
          {[0, 30000, 60000, 90000, 120000, 150000].map((v, i) => (
            <g key={i}>
              <line className="grid-line" x1={P.l} x2={W - P.r} y1={yScale(v)} y2={yScale(v)} />
              <text className="axis-label" x={P.l - 10} y={yScale(v) + 4} textAnchor="end">
                £{(v/1000).toFixed(0)}k
              </text>
            </g>
          ))}
          {years.map(y => (
            <text key={y} className="year-label" x={x(y)} y={H - P.b + 18} textAnchor="middle">
              {y === 0 ? 'Y0' : `Y${y}`}
            </text>
          ))}

          <path d={areaFrom(shopifyCum)} className="shopify-area" />
          <path d={areaFrom(ownedCum)} className="owned-area" />
          <path d={pathFrom(shopifyCum)} className="shopify-line" />
          <path d={pathFrom(ownedCum)} className="owned-line" />

          {years.map(y => (
            <g key={`s${y}`}>
              <circle cx={x(y)} cy={yScale(shopifyCum[y])} r="4" className="point" stroke="#7a1b1b" />
              <circle cx={x(y)} cy={yScale(ownedCum[y])} r="4" className="point" stroke="#c77b2c" />
            </g>
          ))}

          {/* crossover annotation */}
          <text className="value-label" x={x(5) - 8} y={yScale(shopifyCum[5]) - 10} textAnchor="end" fill="#7a1b1b">
            £{(shopifyCum[5]/1000).toFixed(0)}k
          </text>
          <text className="value-label" x={x(5) - 8} y={yScale(ownedCum[5]) + 20} textAnchor="end" fill="#c77b2c">
            £{(ownedCum[5]/1000).toFixed(0)}k
          </text>
        </svg>
      </div>
      <div style={{marginTop: 20, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1, background: 'color-mix(in oklab, var(--ink) 12%, transparent)'}}>
        {[
          {k: '5-year Shopify cost', v: '£128,000', sub: 'Approx — £2k/mo licence + setup'},
          {k: '5-year owned cost', v: '£43,500', sub: 'One-off + hosting + standard support'},
          {k: 'Five-year saving', v: '£84,500', sub: 'That’s a Discovery team for a year.'},
        ].map((c, i) => (
          <div key={i} style={{background: 'var(--paper)', padding: '22px 20px'}}>
            <div className="mono" style={{color: 'var(--ink-mute)'}}>{c.k}</div>
            <div style={{fontFamily: 'var(--serif)', fontSize: '2rem', lineHeight: 1, marginTop: 8, letterSpacing: '-0.02em'}}>{c.v}</div>
            <div style={{fontSize: '0.82rem', color: 'var(--ink-3)', marginTop: 8, fontStyle: 'italic', fontFamily: 'var(--serif)'}}>{c.sub}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============ COMPARATOR ============
function Comparator() {
  const [active, setActive] = useState(null);
  const data = {
    A: {
      label: 'Option A',
      name: 'Magento Open Source',
      tagline: 'Pragmatic. Proven. Shipped in 17 weeks.',
      invest: '£19,500',
      weeks: '17 wks',
      licence: '£0',
      plugins: 'Minimal',
      features: [
        'Native B2B suite — company accounts, quotes, quick order, requisition lists',
        'Magento 2 Certified agency — no learning-curve premium',
        'Battle-tested across thousands of B2B deployments',
        'Lightweight Tailwind Light theme — no legacy frontend bloat',
        'Lower Phase 1 investment; same feature set as Option B',
      ],
      verdict: 'Choose Magento if budget efficiency matters now and you want to go live faster, focused on operational excellence.',
      tag: 'Recommended for speed + value',
    },
    B: {
      label: 'Option B',
      name: 'Next.js Custom Development',
      tagline: 'Bespoke. Unlimited ceiling. Built for what’s next.',
      invest: '£25,589',
      weeks: '20 wks',
      licence: '£0',
      plugins: 'Zero',
      features: [
        'Headless architecture — Next.js 14 + React + TypeScript + Tailwind',
        'Every feature built to exact specification — no platform compromises',
        'Best foundation for Phase 2 AI (Media Selector, Formulation Assistant)',
        'Sub-second load times globally via edge caching + SSR',
        'API-first integrations — Sage, ERP, CRM, Punch-out remain clean',
      ],
      verdict: 'Choose Next.js if you’re thinking beyond a rebuild — a technology platform that becomes a competitive advantage.',
      tag: 'Recommended for AI-forward roadmap',
    },
  };

  const Card = ({ k }) => {
    const d = data[k];
    const isActive = active === k;
    return (
      <div className={`col ${isActive ? 'active' : ''}`} onMouseEnter={() => setActive(k)} onMouseLeave={() => setActive(null)}>
        <div className="label">{d.label}</div>
        <h3>{d.name}</h3>
        <div className="tagline">{d.tagline}</div>

        <div className="stat-row">
          <div className="stat"><div className="k">Phase 1</div><div className="v">{d.invest} <small>+ VAT</small></div></div>
          <div className="stat"><div className="k">Timeline</div><div className="v">{d.weeks}</div></div>
          <div className="stat"><div className="k">Licence</div><div className="v">{d.licence} <small>/ year</small></div></div>
          <div className="stat"><div className="k">Plugins</div><div className="v">{d.plugins}</div></div>
        </div>

        <ul className="feat-list">
          {d.features.map((f, i) => (
            <li key={i}><span className="mark">0{i+1}</span><span>{f}</span></li>
          ))}
        </ul>

        <div className="verdict">
          <span className="tag">{d.tag}</span>
          {d.verdict}
        </div>
      </div>
    );
  };

  return (
    <div className="comparator">
      <Card k="A" />
      <div className="vs">or</div>
      <Card k="B" />
    </div>
  );
}

// ============ FEATURE COMPARISON ============
function FeatureTable() {
  const groups = [
    { title: 'Ordering & Checkout', rows: [
      ['Quick Order / CSV Upload', 'Native B2B', 'Custom built'],
      ['PO Number at Checkout', 'Native payment', 'Custom built'],
      ['Quote Request System', 'Native negotiable quote', 'Custom built'],
      ['Repeat Orders / Templates', 'Requisition lists', 'Custom built'],
      ['VAT Exemption Certificate', 'Custom module', 'Custom built'],
      ['Scheduled / Forward Ordering', 'Extension', 'Custom built'],
      ['Split Shipment', 'Native shipping', 'Custom built'],
      ['MOQ Rules', 'Native product rules', 'Custom built'],
    ]},
    { title: 'B2B Account & University', rows: [
      ['Company Accounts', 'Native B2B', 'Custom built'],
      ['Multi-User Roles', 'Native B2B', 'Custom built'],
      ['Order Approval Workflows', 'Native B2B', 'Custom built'],
      ['Spending Limits per User', 'Native B2B', 'Custom built'],
      ['University Dashboard', 'Custom module', 'Custom built'],
      ['Credit Notes', 'Native', 'Custom built'],
      ['Consolidated Invoicing', 'Custom module', 'Custom built'],
    ]},
    { title: 'Pricing & Catalogue', rows: [
      ['Customer-Specific Pricing', 'Shared catalogues', 'Custom engine'],
      ['Volume Tiered Pricing', 'Native tier prices', 'Custom built'],
      ['Multi-Currency (GBP/EUR/USD)', 'Native', 'Custom built'],
      ['Price on Request', 'Native B2B', 'Custom built'],
    ]},
    { title: 'Integrations & Delivery', rows: [
      ['Sage Accounting Sync', 'Included', 'Included'],
      ['ERP / CRM / Punch-out / EDI', 'Scoped separately', 'Scoped separately'],
      ['Time to Market', '17 weeks', '20 weeks'],
      ['Design Flexibility', 'Good (Light theme)', 'Total freedom'],
      ['Phase 2 AI Foundation', 'Extensible', 'Best suited'],
    ]},
  ];
  const [open, setOpen] = useState([0]);
  const toggle = (i) => setOpen(o => o.includes(i) ? o.filter(x => x !== i) : [...o, i]);
  return (
    <div className="fcomp">
      <div className="fcomp-group-head" style={{borderBottom: '1px solid color-mix(in oklab, var(--ink) 18%, transparent)', background: 'var(--paper-2)'}}>
        <div className="title" style={{fontFamily: 'var(--mono)', fontSize: '0.72rem', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-mute)'}}>Feature</div>
        <div className="count" style={{fontFamily: 'var(--mono)', fontSize: '0.72rem', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-mute)'}}>Option A</div>
        <div className="count" style={{fontFamily: 'var(--mono)', fontSize: '0.72rem', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-mute)'}}>Option B</div>
      </div>
      {groups.map((g, gi) => (
        <div key={gi} className={`fcomp-group ${open.includes(gi) ? 'open' : ''}`}>
          <div className="fcomp-group-head" onClick={() => toggle(gi)}>
            <div className="title">{g.title}</div>
            <div className="count">{g.rows.length} items</div>
            <div className="tog">{open.includes(gi) ? '— Collapse' : '+ Expand'}</div>
          </div>
          <div className="fcomp-rows">
            {g.rows.map((r, ri) => (
              <div key={ri} className="fcomp-row">
                <div className="name">{r[0]}</div>
                <div className="cell"><span className="check">✓</span>{r[1]}</div>
                <div className="cell"><span className="check">✓</span>{r[2]}</div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

// ============ TIMELINE ============
function Timeline() {
  const [option, setOption] = useState('A');
  const magento = [
    { num: 'Phase 01', label: 'Discovery & scoping', start: 1, end: 3 },
    { num: 'Phase 02', label: 'Platform setup & B2B config', start: 3, end: 6 },
    { num: 'Phase 03', label: 'Ordering — VAT, PO, Quote, Quick Order', start: 6, end: 9 },
    { num: 'Phase 04', label: 'Account portal, pricing, Sage integration', start: 9, end: 13 },
    { num: 'Phase 05', label: 'Data migration & frontend QA', start: 13, end: 15 },
    { num: 'Phase 06', label: 'UAT, performance, go-live', start: 15, end: 18 },
  ];
  const nextjs = [
    { num: 'Phase 01', label: 'Discovery & architecture', start: 1, end: 4 },
    { num: 'Phase 02', label: 'Platform setup, data model, auth', start: 4, end: 8 },
    { num: 'Phase 03', label: 'Ordering — full custom build', start: 8, end: 12 },
    { num: 'Phase 04', label: 'Portal, pricing, Sage service', start: 12, end: 16 },
    { num: 'Phase 05', label: 'Migration, search, QA', start: 16, end: 18 },
    { num: 'Phase 06', label: 'UAT, performance, go-live', start: 18, end: 21 },
  ];
  const phases = option === 'A' ? magento : nextjs;
  const totalWks = option === 'A' ? 17 : 20;
  const launchPct = ((totalWks) / 20) * 100;

  return (
    <div className="tl">
      <div className="tl-toggle">
        <button className={option === 'A' ? 'on' : ''} onClick={() => setOption('A')}>Option A · Magento · 17 wks</button>
        <button className={option === 'B' ? 'on' : ''} onClick={() => setOption('B')}>Option B · Next.js · 20 wks</button>
      </div>
      <div className="tl-grid">
        <div className="tl-weeks">
          <span>Week</span>
          <div className="scale">
            {Array.from({length: 20}).map((_, i) => (
              <span key={i}>{(i + 1) % 2 === 0 || i === 0 || i === 19 ? i + 1 : ''}</span>
            ))}
          </div>
        </div>
        {phases.map((p, i) => (
          <div className="tl-phase" key={`${option}-${i}`} style={{animationDelay: `${i * 60}ms`}}>
            <div className="label">
              <span className="num">{p.num}</span>
              <span>{p.label}</span>
            </div>
            <div className="track">
              <div
                className="bar"
                style={{
                  '--start': p.start,
                  '--end': p.end,
                  animationDelay: `${i * 80}ms`,
                }}
                data-weeks={`wks ${p.start}–${p.end - 1}`}
              ></div>
            </div>
          </div>
        ))}
        <div className="tl-launch" style={{left: `calc(140px + 24px + ((100% - 140px - 24px) * ${launchPct / 100}))`}}></div>
      </div>
    </div>
  );
}

// ============ PAYMENT CALCULATOR ============
function PaymentCalc() {
  const [option, setOption] = useState('A');
  const [deposit, setDeposit] = useState(30);
  const [months, setMonths] = useState(10);

  const total = option === 'A' ? 19500 : 25589;
  const dep = Math.round(total * (deposit / 100));
  const mile = Math.round(total * (deposit / 100));
  const remaining = total - dep - mile;
  const monthly = Math.round(remaining / months);

  const gbp = (n) => '£' + n.toLocaleString('en-GB');

  return (
    <div className="calc">
      <div className="calc-controls">
        <div className="ctrl">
          <div className="head"><span className="k">Option</span></div>
          <div className="toggle-group">
            <button className={option === 'A' ? 'on' : ''} onClick={() => setOption('A')}>Magento</button>
            <button className={option === 'B' ? 'on' : ''} onClick={() => setOption('B')}>Next.js</button>
          </div>
        </div>
        <div className="ctrl">
          <div className="head">
            <span className="k">Deposit & milestone %</span>
            <span className="v">{deposit}%</span>
          </div>
          <input className="slider" type="range" min={15} max={50} step={5} value={deposit} onChange={(e) => setDeposit(+e.target.value)} />
          <div className="slider-scale"><span>15%</span><span>30% default</span><span>50%</span></div>
        </div>
        <div className="ctrl">
          <div className="head">
            <span className="k">Monthly instalments</span>
            <span className="v">× {months}</span>
          </div>
          <input className="slider" type="range" min={6} max={18} step={1} value={months} onChange={(e) => setMonths(+e.target.value)} />
          <div className="slider-scale"><span>6</span><span>10 default</span><span>18</span></div>
        </div>
      </div>
      <div className="calc-result">
        <div className="amount">
          <span className="per">Monthly instalment</span>
          <span className="big">{gbp(monthly)}</span>
          <span className="per" style={{marginTop: 0}}>interest-free for {months} months</span>
        </div>
        <div className="breakdown">
          <div className="row"><span className="k">Deposit on signing</span><span className="v">{gbp(dep)}</span></div>
          <div className="row"><span className="k">Milestone 2 (UAT sign-off)</span><span className="v">{gbp(mile)}</span></div>
          <div className="row"><span className="k">{months} × monthly</span><span className="v">{gbp(monthly * months)}</span></div>
          <div className="row total"><span className="k">Total (ex VAT)</span><span className="v">{gbp(total)}</span></div>
        </div>
      </div>
    </div>
  );
}

window.CostChart = CostChart;
window.Comparator = Comparator;
window.FeatureTable = FeatureTable;
window.Timeline = Timeline;
window.PaymentCalc = PaymentCalc;
