// Improvements.jsx — opt-in UX enhancements, each toggled from the Tweaks panel.
const { useState: useImpState, useEffect: useImpEffect } = React;

/* ---------- 1a. Animated count-up stat ---------- */
function AnimatedStat({ value, label, run }) {
  // split "€500k+" -> prefix "€", number 500, suffix "k+"
  const m = String(value).match(/^([^\d]*)(\d+)(.*)$/);
  const prefix = m ? m[1] : '';
  const target = m ? parseInt(m[2], 10) : 0;
  const suffix = m ? m[3] : '';
  const [n, setN] = useImpState(target);
  useImpEffect(() => {
    if (!run) { setN(target); return; }
    const dur = 1100;
    const startedAt = Date.now();
    setN(0);
    const id = setInterval(() => {
      const p = Math.min(1, (Date.now() - startedAt) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(Math.round(eased * target));
      if (p >= 1) { setN(target); clearInterval(id); }
    }, 33);
    return () => clearInterval(id);
  }, [run, target]);
  return (
    <div className="stat-item">
      <span className="stat-num">{prefix}{n}{suffix}</span>
      <span className="stat-label">{label}</span>
    </div>
  );
}

/* ---------- 1b. Live "ops dashboard" KPI tile ---------- */
function HeroKpiTile() {
  const [bars, setBars] = useImpState([40, 55, 48, 62, 70, 66, 82]);
  const [otif, setOtif] = useImpState(91.4);
  useImpEffect(() => {
    const id = setInterval(() => {
      setBars((b) => [...b.slice(1), Math.max(30, Math.min(96, b[b.length - 1] + (Math.random() * 26 - 11)))]);
      setOtif((v) => Math.max(88, Math.min(99, +(v + (Math.random() * 1.2 - 0.5)).toFixed(1))));
    }, 1600);
    return () => clearInterval(id);
  }, []);
  return (
    <aside className="hero-kpi">
      <div className="hero-kpi-head">
        <span className="hero-kpi-title">Operations · this week</span>
        <span className="hero-kpi-live"><span className="hero-kpi-dot" />Live</span>
      </div>
      <div className="kpi-row"><span className="kpi-label">On-time fulfilment</span><span className="kpi-val">{otif}%<span className="kpi-trend">▲</span></span></div>
      <div className="kpi-row"><span className="kpi-label">Inventory accuracy</span><span className="kpi-val">98.2%<span className="kpi-trend">▲</span></span></div>
      <div className="kpi-row"><span className="kpi-label">Open escalations</span><span className="kpi-val">3<span className="kpi-trend" style={{ color: '#4ADE80' }}>▼</span></span></div>
      <div className="kpi-bars">
        {bars.map((h, i) => <div className="kpi-bar" key={i} style={{ height: h + '%' }} />)}
      </div>
    </aside>
  );
}

/* ---------- 2. Interactive SCALE stepper ---------- */
const STEPPER = [
  ['S', 'Stabilize', 'Create operational visibility. Map the current process, identify bottlenecks, clarify ownership, and stop recurring firefighting before it drains the team.'],
  ['C', 'Control', 'Install KPI dashboards, weekly reviews, fulfilment metrics, inventory controls, and supplier performance routines — so decisions are data-driven.'],
  ['A', 'Accountability', 'Define decision rights, meeting cadence, role clarity, escalation paths, and leadership routines that keep the team aligned and moving.'],
  ['L', 'Leverage', 'Standardize what works through SOPs, automation opportunities, supplier playbooks, and repeatable workflows that reduce founder dependence.'],
  ['E', 'Expand', 'Prepare for scalable growth through margin improvement, fulfilment reliability, team coaching, and 90-day execution roadmaps.'],
];

function ScaleStepper() {
  const [active, setActive] = useImpState(0);
  return (
    <section className="section">
      <SectionHeader id="scale-model" label="The Framework" title="The SCALE™ Model"
        sub="A practical operating system for e-commerce brands growing faster than their internal structure. Walk each stage →" />
      <div className="stepper-rail">
        {STEPPER.map(([letter, title], i) => (
          <React.Fragment key={letter}>
            <div className={'stepper-node' + (i === active ? ' active' : i < active ? ' done' : '')}
              onClick={() => setActive(i)} role="button" aria-label={title}>
              <div className="stepper-letter">{letter}</div>
              <div className="stepper-cap">{title}</div>
            </div>
            {i < STEPPER.length - 1 && <div className={'stepper-line' + (i < active ? ' filled' : '')} />}
          </React.Fragment>
        ))}
      </div>
      <div className="stepper-panel">
        <div className="num">Stage {active + 1} of 5 · {STEPPER[active][0]}</div>
        <h3>{STEPPER[active][1]}</h3>
        <p>{STEPPER[active][2]}</p>
      </div>
    </section>
  );
}

/* ---------- 3. Diagnostic micro-quiz ---------- */
const QUIZ = [
  { step: 'Question 1 of 3', q: "Where's your biggest operational leak right now?",
    opts: [
      { ic: '📦', label: 'Inventory & stockouts', key: 'inventory' },
      { ic: '🚚', label: 'Fulfilment & delivery', key: 'fulfilment' },
      { ic: '📊', label: 'Unclear KPIs & visibility', key: 'kpis' },
      { ic: '🧍', label: 'Founder is the bottleneck', key: 'founder' },
    ] },
  { step: 'Question 2 of 3', q: "What's your current annual revenue?",
    opts: [
      { ic: '🌱', label: '€500k – €1M', key: 'r1' },
      { ic: '📈', label: '€1M – €3M', key: 'r2' },
      { ic: '🚀', label: '€3M – €5M', key: 'r3' },
      { ic: '🏆', label: '€5M+', key: 'r4' },
    ] },
  { step: 'Question 3 of 3', q: 'How big is your team today?',
    opts: [
      { ic: '👤', label: 'Just me', key: 't1' },
      { ic: '👥', label: '2 – 5 people', key: 't2' },
      { ic: '👪', label: '6 – 15 people', key: 't3' },
      { ic: '🏢', label: '15+ people', key: 't4' },
    ] },
];

const LEAK_COPY = {
  inventory: ['Your margin is leaking through inventory.', 'Stockouts and overstock both quietly erode cash and trust. The first 90 days focus on inventory visibility, supplier rhythms, and a reorder system you can actually run.'],
  fulfilment: ['Fulfilment reliability is capping your growth.', 'Late and inconsistent delivery shows up in reviews and repeat rate. We install fulfilment metrics, a weekly ops cadence, and supplier accountability to stabilise it fast.'],
  kpis: ["You're flying without instruments.", 'No shared KPI rhythm means decisions run on gut feel. We stand up a dashboard and a weekly review so the whole team steers from the same numbers.'],
  founder: ["You've become the bottleneck.", 'When every decision routes through you, growth adds chaos, not momentum. We install decision rights, SOPs, and routines that hand the operation back to the team.'],
};

function DiagnosticQuiz({ onComplete }) {
  const [step, setStep] = useImpState(0);
  const [answers, setAnswers] = useImpState({});
  const choose = (key) => {
    const next = { ...answers, [step]: key };
    setAnswers(next);
    if (step < QUIZ.length - 1) setStep(step + 1);
    else setStep(QUIZ.length);
  };
  const restart = () => { setStep(0); setAnswers({}); };

  if (step >= QUIZ.length) {
    const leak = answers[0] || 'kpis';
    const rev = answers[1];
    const rec = rev === 'r1' ? 'Operational Diagnostic (€2,500)'
      : rev === 'r4' ? 'Scale Accelerator (€10k–€20k)'
        : 'Fractional COO (€3k–€5k/mo)';
    const [headline, body] = LEAK_COPY[leak];
    return (
      <section className="section">
        <SectionHeader label="60-Second Diagnostic" title="Your quick read"
          sub="A first look based on your answers — the full diagnostic goes far deeper." />
        <div className="quiz">
          <div className="quiz-inner quiz-result">
            <div className="rlabel">▸ Your likely priority</div>
            <h3>{headline}</h3>
            <p>{body}</p>
            <div className="quiz-rec">⚙️ Recommended start · {rec}</div>
            <div>
              <a href="#contact" className="hero-btn" style={{ marginRight: 0 }}
                onClick={() => onComplete && onComplete(rec)}>Get your full diagnostic →</a>
              <button type="button" className="quiz-restart" onClick={restart}>Start over</button>
            </div>
          </div>
        </div>
      </section>
    );
  }

  const cur = QUIZ[step];
  return (
    <section className="section">
      <SectionHeader label="60-Second Diagnostic" title="Find your biggest leak"
        sub="Three quick questions — get a tailored read before you book." />
      <div className="quiz">
        <div className="quiz-inner">
          <div className="quiz-step">{cur.step}</div>
          <div className="quiz-q">{cur.q}</div>
          <div className="quiz-opts">
            {cur.opts.map((o) => (
              <button className="quiz-opt" key={o.key} onClick={() => choose(o.key)}>
                <span className="opt-ic">{o.ic}</span>{o.label}
              </button>
            ))}
          </div>
          <div className="quiz-progress">
            {QUIZ.map((_, i) => <div key={i} className={'quiz-pdot' + (i <= step ? ' on' : '')} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- 4. Pricing comparison strip ---------- */
const COMPARE_ROWS = [
  ['Current-state process map', true, true, true],
  ['KPI dashboard', true, true, true],
  ['90-day roadmap', true, true, true],
  ['Weekly leadership cadence', false, true, true],
  ['SOPs & supplier routines', false, true, true],
  ['Team coaching & accountability', false, true, true],
  ['Full SCALE™ implementation', false, false, true],
];

function PricingCompare() {
  return (
    <div className="compare">
      <table>
        <thead>
          <tr>
            <th>What's included</th>
            <th>Diagnostic</th>
            <th className="feat">Fractional COO</th>
            <th>Accelerator</th>
          </tr>
        </thead>
        <tbody>
          {COMPARE_ROWS.map((r) => (
            <tr key={r[0]}>
              <td>{r[0]}</td>
              <td>{r[1] ? <span className="ck">✓</span> : <span className="no">—</span>}</td>
              <td className="feat-col">{r[2] ? <span className="ck">✓</span> : <span className="no">—</span>}</td>
              <td>{r[3] ? <span className="ck">✓</span> : <span className="no">—</span>}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ---------- 6. Trust / credentials layer (no personal name) ---------- */
const CREDENTIALS = [
  '25+ years operational leadership',
  'Profit Growth',
  'Global performance systems',
  'Cash Flow Management',
  'Operational Scaling',
  'KPI management',
  'Leadership coaching',
];

const TESTIMONIALS = [
  {
    quote: "Exceptional project delivery combined with genuine coaching capability. The organizational impact he creates doesn't just solve the immediate problem — it builds lasting operational capability across the team.",
    name: "Scott Phillips",
    role: "Senior Operations Leader",
  },
  {
    quote: "Full ownership, clear execution, real accountability. Exactly the operational leadership you want on a fast-moving program — the team always knew where they stood and what needed to happen next.",
    name: "Ronald van der Kraan",
    role: "Program & Engineering Leader",
  },
  {
    quote: "A strategic and operational partner at the executive level. He drove both growth and profitability simultaneously — disciplined execution without losing the strategic picture. Rare to find that combination.",
    name: "Robert Li",
    role: "EVP & General Manager",
  },
];

function TrustLayer() {
  return (
    <section className="section">
      <div className="trust">
        <div className="trust-id">
          <div className="trust-name">Your operating partner</div>
          <div className="trust-role">Fractional COO · Operational Excellence</div>
          <div className="trust-link">Senior operator · enterprise & ecom</div>
        </div>
        <div className="trust-creds">
          {CREDENTIALS.map((c) => (
            <span className="cred-chip" key={c}><span className="dot">▸</span>{c}</span>
          ))}
        </div>
      </div>
      <div className="quotes-grid">
        {TESTIMONIALS.map((t) => (
          <div className="quote" key={t.name}>
            <p><span className="mark">"</span>{t.quote}</p>
            <div className="quote-by">
              <span className="quote-name">{t.name}</span>
              <span className="quote-role">{t.role}</span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { AnimatedStat, HeroKpiTile, ScaleStepper, DiagnosticQuiz, PricingCompare, TrustLayer });
