/* =====================================================
   ETL Contact Wizard — integrated version
   Ported to ETL design tokens (--accent-amber, --font-mono,
   --bg-card, --radius-sm/md/lg, --space-*). No standalone
   chrome. Posts to formsubmit.co/ajax/sales@embeddedc.co.uk
   with Cloudflare Turnstile, matching the existing site.
   ===================================================== */

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

const FORM_ENDPOINT = 'https://formsubmit.co/ajax/sales@embeddedc.co.uk';
const TURNSTILE_SITEKEY = '0x4AAAAAACvzVSnkhV7BMa72';

const ENQUIRY_PATHS = [
  {
    id: 'project',
    glyph: '</>',
    title: 'New project / firmware build',
    sub: 'Board bring-up, BLE, IoT, embedded Linux, mobile pairing.',
    steps: ['path', 'scope', 'platform', 'timeline', 'budget', 'contact'],
  },
  {
    id: 'retainer',
    glyph: '∿',
    title: 'Flexible workforce retainer',
    sub: 'Full team on tap — firmware, BLE, Linux, mobile. 30-day notice.',
    steps: ['path', 'retainer', 'coverage', 'timeline', 'contact'],
  },
  {
    id: 'partnership',
    glyph: '◇',
    title: 'Recruitment / partnership',
    sub: 'Sub-contracting, specialist referrals, joint bids.',
    steps: ['path', 'partnership', 'contact'],
  },
];

const STEP_LABELS = {
  path: 'Select path',
  scope: 'Project scope',
  platform: 'Stack',
  timeline: 'Timeline',
  budget: 'Budget',
  retainer: 'Retainer size',
  coverage: 'Coverage gap',
  partnership: 'Partnership',
  contact: 'Your details',
};

const PLATFORMS = [
  'ARM Cortex M4/M7', 'Nordic nRF5340', 'ESP32', 'Raspberry Pi',
  'Atmel', 'PIC', 'Ambiq', 'Custom / TBD', "Don't know"
];
const PROTOCOLS = ['BLE', 'WiFi', 'MQTT', 'LoRa', 'CAN', 'SPI / I2C', 'Cellular', 'USB'];
const STAGES = [
  { id: 'concept', t: 'Concept', s: 'Spec and architecture only' },
  { id: 'proto', t: 'Prototype', s: 'Breadboard / dev-kit stage' },
  { id: 'pilot', t: 'Pilot', s: 'Small-batch hardware, early firmware' },
  { id: 'production', t: 'Production', s: 'Certifying or live' },
];
const TEAM_SIZES = [
  { id: 'one', t: '1 engineer', hrs: '40 hrs/mo' },
  { id: 'two', t: '2 engineers', hrs: '80 hrs/mo' },
  { id: 'team', t: 'Full team', hrs: 'Flex capacity' },
  { id: 'scoping', t: 'Scoping call first', hrs: '' },
];
const TIMELINE_OPTS = [
  { id: 'urgent', t: 'Urgent — within 2 weeks', s: 'We hold a small urgent slice; let us know why it burns.', g: '!' },
  { id: 'q1',     t: 'Within the next quarter', s: 'The sweet spot. We can start in 1–2 weeks.', g: 'Q1' },
  { id: 'q2',     t: '3–6 months out',          s: 'Scoping now gives the best architecture time.', g: 'Q2' },
  { id: 'flex',   t: 'Exploratory / flexible',  s: 'Happy to shape the plan with you before committing dates.', g: '∞' },
];

function budgetLabel(v) {
  if (v < 20) return 'Under £10k';
  if (v < 40) return '£10k – £50k';
  if (v < 60) return '£50k – £100k';
  if (v < 80) return '£100k – £250k';
  return '£250k+';
}
function budgetValueForForm(v) {
  if (v < 20) return 'under-10k';
  if (v < 40) return '10k-50k';
  if (v < 60) return '50k-100k';
  if (v < 80) return '100k-250k';
  return '250k-plus';
}

/* -----------------------------------------------------
   Cloudflare Turnstile (rendered once, reused across path changes)
   ----------------------------------------------------- */
function TurnstileBox({ onToken }) {
  const ref = useRef(null);
  const rendered = useRef(false);

  useEffect(() => {
    if (rendered.current) return;
    const tryRender = () => {
      if (window.turnstile && ref.current) {
        window.turnstile.render(ref.current, {
          sitekey: TURNSTILE_SITEKEY,
          theme: 'dark',
          callback: (token) => onToken(token),
        });
        rendered.current = true;
      } else {
        setTimeout(tryRender, 200);
      }
    };
    tryRender();
  }, [onToken]);

  return <div ref={ref} className="cf-turnstile" />;
}

/* -----------------------------------------------------
   Wizard
   ----------------------------------------------------- */
function Wizard({ onComplete }) {
  const [pathId, setPathId] = useState(null);
  const path = useMemo(() => ENQUIRY_PATHS.find(p => p.id === pathId), [pathId]);
  const steps = path ? path.steps : ['path'];
  const [stepIdx, setStepIdx] = useState(0);
  const currentStep = steps[stepIdx];

  const [data, setData] = useState({
    scope: '', platforms: [], protocols: [], stage: null,
    timeline: 'q1', budget: 50,
    teamSize: null, disciplines: [], coverage: '',
    orgType: '', brief: '',
    name: '', email: '', company: '', phone: '', channel: 'email', nda: false,
    source: '',
  });
  const [errors, setErrors] = useState({});
  const [sending, setSending] = useState(false);
  const [submitError, setSubmitError] = useState('');
  const [turnstileToken, setTurnstileToken] = useState('');

  useEffect(() => { setStepIdx(0); setErrors({}); }, [pathId]);

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));
  const toggleArr = (k, v) => setData(d => ({
    ...d,
    [k]: d[k].includes(v) ? d[k].filter(x => x !== v) : [...d[k], v],
  }));

  function hasLink(s) {
    return /\b(?:https?:\/\/|www\.|ftp:\/\/)\S+/i.test(s)
      || /\b[a-z0-9-]+\.(?:com|net|org|io|co|uk|ru|cn|info|biz|xyz|top|online|site|live|shop|club|me|tv|app|dev|ly|gg|tk|ml|ga|cf)\b/i.test(s)
      || /<a\s|href\s*=/i.test(s)
      || /\[url[=\]]/i.test(s);
  }

  function validateStep() {
    const e = {};
    if (currentStep === 'scope') {
      const v = data.scope.trim();
      if (v.length < 12) e.scope = 'A couple of sentences, please.';
      else if (hasLink(v)) e.scope = 'Links are not permitted in the project brief.';
    }
    if (currentStep === 'platform' && data.platforms.length === 0) {
      e.platforms = 'Pick at least one, or "Custom / TBD".';
    }
    if (currentStep === 'retainer' && !data.teamSize) e.teamSize = 'Pick a rough size.';
    if (currentStep === 'coverage') {
      const v = data.coverage.trim();
      if (v.length < 10) e.coverage = 'A line on the gap, please.';
      else if (hasLink(v)) e.coverage = 'Links are not permitted.';
    }
    if (currentStep === 'partnership') {
      const v = data.brief.trim();
      if (v.length < 12) e.brief = 'A little more to go on.';
      else if (hasLink(v)) e.brief = 'Links are not permitted.';
    }
    if (currentStep === 'contact') {
      if (!data.name.trim()) e.name = 'Required.';
      if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email)) e.email = 'A working email, please.';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function next() {
    if (!validateStep()) return;
    if (stepIdx + 1 < steps.length) {
      setStepIdx(stepIdx + 1);
    } else {
      submit();
    }
  }
  function back() {
    setSubmitError('');
    if (stepIdx === 0) { setPathId(null); return; }
    setStepIdx(stepIdx - 1);
  }

  function buildBriefText() {
    const lines = [];
    lines.push(`Enquiry type: ${path?.title || 'unspecified'}`);
    if (data.scope) lines.push(`\nProject brief:\n${data.scope}`);
    if (data.stage) lines.push(`Stage: ${STAGES.find(s => s.id === data.stage)?.t}`);
    if (data.platforms.length) lines.push(`Platforms: ${data.platforms.join(', ')}`);
    if (data.protocols.length) lines.push(`Protocols: ${data.protocols.join(', ')}`);
    if (path?.id === 'project') {
      lines.push(`Timeline: ${TIMELINE_OPTS.find(t => t.id === data.timeline)?.t}`);
      lines.push(`Budget: ${budgetLabel(data.budget)}`);
      if (data.nda) lines.push('NDA: requested before first call.');
    }
    if (path?.id === 'retainer') {
      const sz = TEAM_SIZES.find(t => t.id === data.teamSize);
      lines.push(`Retainer size: ${sz?.t}`);
      if (data.disciplines.length) lines.push(`Disciplines: ${data.disciplines.join(', ')}`);
      if (data.coverage) lines.push(`\nCoverage gap:\n${data.coverage}`);
      lines.push(`Timeline: ${TIMELINE_OPTS.find(t => t.id === data.timeline)?.t}`);
    }
    if (path?.id === 'partnership') {
      if (data.orgType) lines.push(`Org type: ${data.orgType}`);
      if (data.brief) lines.push(`\nBrief:\n${data.brief}`);
    }
    lines.push(`\nPreferred first contact: ${data.channel}`);
    return lines.join('\n');
  }

  async function submit() {
    setSubmitError('');
    if (!turnstileToken) {
      setSubmitError('Please complete the security check below.');
      return;
    }
    setSending(true);

    const payload = {
      _subject: 'New enquiry from ETL website',
      _template: 'table',
      _captcha: 'false',
      name: data.name,
      email: data.email,
      company: data.company,
      phone: data.phone,
      enquiry_type: path?.id || '',
      budget: path?.id === 'project' ? budgetValueForForm(data.budget) : '',
      timeline: (path?.id === 'project' || path?.id === 'retainer') ? data.timeline : '',
      preferred_contact: data.channel,
      brief: buildBriefText(),
      'cf-turnstile-response': turnstileToken,
    };

    try {
      const res = await fetch(FORM_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error('bad status');
      setSending(false);
      onComplete({ ...data, path: pathId });
    } catch (err) {
      setSending(false);
      setSubmitError('Something went wrong. Please email us directly at sales@embeddedc.co.uk');
      // Reset Turnstile so the user can retry
      if (window.turnstile) window.turnstile.reset();
      setTurnstileToken('');
    }
  }

  const totalSteps = steps.length;
  const pktCount = Math.max(1, totalSteps - 1);
  const pktIdx = Math.max(0, stepIdx - 1);

  return (
    <div className="etl-wizard">
      {/* Left rail: stepper + trust */}
      <aside className="etl-rail">
        <div className="etl-stepper">
          {steps.map((s, i) => {
            const active = i === stepIdx;
            const complete = i < stepIdx;
            return (
              <div key={s} className={`etl-step-row ${active ? 'active' : ''} ${complete ? 'complete' : ''}`}>
                <div className="node">{complete ? '✓' : String(i + 1).padStart(2, '0')}</div>
                <div className="lbl">{STEP_LABELS[s]}</div>
                <div className="node-line" />
              </div>
            );
          })}
        </div>

        <div className="etl-rail-trust">
          <div className="t-row"><span>Response SLA</span><span>1 business day</span></div>
          <div className="t-row"><span>First call</span><span>20 min</span></div>
          <div className="t-row"><span>NDA on request</span><span>Same-day</span></div>
          <div className="t-row"><span>Location</span><span>Bacup, Lancs</span></div>
        </div>
      </aside>

      {/* Panel */}
      <section className="etl-panel" style={{ position: 'relative' }}>
        <div className="etl-panel-head">
          <span className="session">session /contact/{pathId || 'triage'}</span>
          <div className="etl-pkt-row">
            {Array.from({ length: pktCount }).map((_, i) => (
              <div key={i} className={`etl-pkt ${i < pktIdx ? 'done' : ''} ${i === pktIdx && pathId ? 'active' : ''}`} />
            ))}
          </div>
        </div>

        <div className="etl-panel-body">

          {/* STEP: path */}
          <div className={`etl-step ${currentStep === 'path' ? 'active' : ''}`}>
            <div className="etl-step-kicker">Step 01 / 0{pktCount + 1} · Triage</div>
            <h3 className="etl-step-h">What brings you to us?</h3>
            <p className="etl-step-sub">Pick the closest match — we'll branch from here. Not a perfect fit? Select the nearest and we'll route you correctly after the first call.</p>

            <div style={{ display: 'grid', gap: 10 }}>
              {ENQUIRY_PATHS.map(p => (
                <div key={p.id}
                     className={`etl-card-choice ${pathId === p.id ? 'active' : ''}`}
                     onClick={() => setPathId(p.id)}>
                  <div className="glyph" style={{ fontSize: 15 }}>{p.glyph}</div>
                  <div>
                    <div className="c-title">{p.title}</div>
                    <div className="c-sub">{p.sub}</div>
                  </div>
                  <div className="radio" />
                </div>
              ))}
            </div>
          </div>

          {/* STEP: scope */}
          <div className={`etl-step ${currentStep === 'scope' ? 'active' : ''}`}>
            <div className="etl-step-kicker">Step 02 · Scope</div>
            <h3 className="etl-step-h">Describe what you're building.</h3>
            <p className="etl-step-sub">A few sentences is plenty. What is it, what's the hardest part, and where are you stuck? Please do not include links or URLs.</p>

            <div>
              <div className="etl-field-label">
                Project brief <span className="req">*</span>
                <span className="hint">{data.scope.length} / 600</span>
              </div>
              <textarea
                className={`etl-textarea ${errors.scope ? 'error' : ''}`}
                maxLength={600}
                value={data.scope}
                onChange={e => update('scope', e.target.value)}
                placeholder="e.g. Wearable BLE device streaming from an nRF5340 to a companion app. Need help with BLE service design and a production-ready firmware architecture."
              />
              {errors.scope && <div className="etl-err">{errors.scope}</div>}
            </div>

            <div>
              <div className="etl-field-label">Current stage <span className="hint">optional</span></div>
              <div className="etl-chips">
                {STAGES.map(s => (
                  <div key={s.id} className={`etl-chip ${data.stage === s.id ? 'active' : ''}`}
                       onClick={() => update('stage', data.stage === s.id ? null : s.id)}>
                    <span>{s.t}</span>
                    <span style={{ color: 'var(--text-muted)', fontSize: 11 }}>· {s.s}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* STEP: platform */}
          <div className={`etl-step ${currentStep === 'platform' ? 'active' : ''}`}>
            <div className="etl-step-kicker">Step 03 · Stack</div>
            <h3 className="etl-step-h">Which silicon are we on?</h3>
            <p className="etl-step-sub">Even a best-guess helps us assign the right engineer from day one. Pick as many as apply.</p>

            <div>
              <div className="etl-field-label">Hardware platforms <span className="req">*</span></div>
              <div className="etl-chips">
                {PLATFORMS.map(p => (
                  <div key={p} className={`etl-chip ${data.platforms.includes(p) ? 'active' : ''}`}
                       onClick={() => toggleArr('platforms', p)}>
                    {p}<span className="x">×</span>
                  </div>
                ))}
              </div>
              {errors.platforms && <div className="etl-err">{errors.platforms}</div>}
            </div>

            <div>
              <div className="etl-field-label">Wireless / protocols <span className="hint">optional</span></div>
              <div className="etl-chips">
                {PROTOCOLS.map(p => (
                  <div key={p} className={`etl-chip ${data.protocols.includes(p) ? 'active' : ''}`}
                       onClick={() => toggleArr('protocols', p)}>
                    {p}<span className="x">×</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* STEP: timeline */}
          <div className={`etl-step ${currentStep === 'timeline' ? 'active' : ''}`}>
            <div className="etl-step-kicker">Step 04 · Timeline</div>
            <h3 className="etl-step-h">When do you need to ship?</h3>
            <p className="etl-step-sub">Our calendar is currently booking next-quarter — but we hold a slice of capacity for urgent briefs.</p>

            <div style={{ display: 'grid', gap: 10 }}>
              {TIMELINE_OPTS.map(t => (
                <div key={t.id} className={`etl-card-choice ${data.timeline === t.id ? 'active' : ''}`}
                     onClick={() => update('timeline', t.id)}>
                  <div className="glyph" style={{ fontSize: 13 }}>{t.g}</div>
                  <div>
                    <div className="c-title">{t.t}</div>
                    <div className="c-sub">{t.s}</div>
                  </div>
                  <div className="radio" />
                </div>
              ))}
            </div>
          </div>

          {/* STEP: budget */}
          <div className={`etl-step ${currentStep === 'budget' ? 'active' : ''}`}>
            <div className="etl-step-kicker">Step 05 · Budget</div>
            <h3 className="etl-step-h">Rough budget envelope?</h3>
            <p className="etl-step-sub">This doesn't lock anything in — we use it to size the first conversation. Ballpark is fine.</p>

            <div className="etl-slider-wrap">
              <div className="etl-slider-value">{budgetLabel(data.budget)}</div>
              <div className="etl-slider-hint">Indicative only. We'll firm up scope on the first call.</div>
              <input type="range" min="0" max="100" value={data.budget}
                     onChange={e => update('budget', +e.target.value)}
                     className="etl-slider" />
              <div className="etl-slider-meta">
                <span>&lt; £10k</span><span>£10–50k</span><span>£50–100k</span><span>£100–250k</span><span>£250k+</span>
              </div>
            </div>

            <label className="etl-checkrow">
              <input type="checkbox" checked={data.nda} onChange={e => update('nda', e.target.checked)} />
              <span>Send me a mutual NDA before the first call.</span>
            </label>
          </div>

          {/* STEP: retainer */}
          <div className={`etl-step ${currentStep === 'retainer' ? 'active' : ''}`}>
            <div className="etl-step-kicker">Step 02 · Sizing</div>
            <h3 className="etl-step-h">How much capacity do you need?</h3>
            <p className="etl-step-sub">Retainers scale monthly. Pick the closest size — the exact mix gets shaped on the first call.</p>

            <div style={{ display: 'grid', gap: 10 }}>
              {TEAM_SIZES.map(t => (
                <div key={t.id} className={`etl-card-choice ${data.teamSize === t.id ? 'active' : ''}`}
                     onClick={() => update('teamSize', t.id)}>
                  <div className="glyph" style={{ fontSize: 13 }}>{t.id === 'one' ? '1' : t.id === 'two' ? '2' : t.id === 'team' ? 'T' : '?'}</div>
                  <div>
                    <div className="c-title">{t.t}</div>
                    <div className="c-sub">{t.hrs}</div>
                  </div>
                  <div className="radio" />
                </div>
              ))}
            </div>
            {errors.teamSize && <div className="etl-err">{errors.teamSize}</div>}

            <div>
              <div className="etl-field-label">Disciplines needed <span className="hint">optional</span></div>
              <div className="etl-chips">
                {['Firmware', 'BLE', 'Embedded Linux', 'Android', 'Mobile Development', 'Hardware', 'PCB / KiCad', 'IoT', 'Payments'].map(p => (
                  <div key={p} className={`etl-chip ${data.disciplines.includes(p) ? 'active' : ''}`}
                       onClick={() => toggleArr('disciplines', p)}>
                    {p}<span className="x">×</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* STEP: coverage */}
          <div className={`etl-step ${currentStep === 'coverage' ? 'active' : ''}`}>
            <div className="etl-step-kicker">Step 03 · Coverage</div>
            <h3 className="etl-step-h">What's the gap we're filling?</h3>
            <p className="etl-step-sub">Absence cover, surge capacity, a skill you can't hire for? Tell us what's broken and we'll match the right people.</p>
            <div>
              <div className="etl-field-label">Where's the pressure? <span className="req">*</span></div>
              <textarea
                className={`etl-textarea ${errors.coverage ? 'error' : ''}`}
                value={data.coverage}
                onChange={e => update('coverage', e.target.value)}
                placeholder="e.g. Lead firmware engineer on parental leave, BLE bring-up deadline in 6 weeks, no Nordic experience in-house."
              />
              {errors.coverage && <div className="etl-err">{errors.coverage}</div>}
            </div>
          </div>

          {/* STEP: partnership */}
          <div className={`etl-step ${currentStep === 'partnership' ? 'active' : ''}`}>
            <div className="etl-step-kicker">Step 02 · Partnership</div>
            <h3 className="etl-step-h">Tell us about the partnership.</h3>
            <p className="etl-step-sub">Sub-contracts, joint bids, specialist referrals — say what you're after and who you're representing.</p>

            <div className="etl-two-col">
              <div>
                <div className="etl-field-label">Organisation type</div>
                <select className="etl-select" value={data.orgType} onChange={e => update('orgType', e.target.value)}>
                  <option value="">Select a type</option>
                  <option>Agency / consultancy</option>
                  <option>Product company</option>
                  <option>Individual contractor</option>
                  <option>Recruiter</option>
                  <option>Other</option>
                </select>
              </div>
              <div>
                <div className="etl-field-label">Company</div>
                <input className="etl-input" value={data.company} onChange={e => update('company', e.target.value)} placeholder="Company name" />
              </div>
            </div>

            <div>
              <div className="etl-field-label">Brief <span className="req">*</span></div>
              <textarea
                className={`etl-textarea ${errors.brief ? 'error' : ''}`}
                value={data.brief}
                onChange={e => update('brief', e.target.value)}
                placeholder="What's the opportunity, what's the skill mix, and what's the timeline?"
              />
              {errors.brief && <div className="etl-err">{errors.brief}</div>}
            </div>
          </div>

          {/* STEP: contact */}
          <div className={`etl-step ${currentStep === 'contact' ? 'active' : ''}`}>
            <div className="etl-step-kicker">Final · Contact</div>
            <h3 className="etl-step-h">Where should we reach you?</h3>
            <p className="etl-step-sub">We reply from a real engineer, not an auto-responder. Typical response within one business day.</p>

            <div className="etl-two-col">
              <div>
                <div className="etl-field-label">Name <span className="req">*</span></div>
                <input className={`etl-input ${errors.name ? 'error' : ''}`} value={data.name}
                       onChange={e => update('name', e.target.value)} placeholder="Your name" autoComplete="name" />
                {errors.name && <div className="etl-err">{errors.name}</div>}
              </div>
              <div>
                <div className="etl-field-label">Email <span className="req">*</span></div>
                <input className={`etl-input ${errors.email ? 'error' : ''}`} type="email" value={data.email}
                       onChange={e => update('email', e.target.value)} placeholder="name@company.com" autoComplete="email" />
                {errors.email && <div className="etl-err">{errors.email}</div>}
              </div>
            </div>

            <div className="etl-two-col">
              <div>
                <div className="etl-field-label">Company <span className="hint">optional</span></div>
                <input className="etl-input" value={data.company} onChange={e => update('company', e.target.value)} placeholder="Company name" autoComplete="organization" />
              </div>
              <div>
                <div className="etl-field-label">Phone <span className="hint">optional</span></div>
                <input className="etl-input" value={data.phone} onChange={e => update('phone', e.target.value)} placeholder="+44 ..." autoComplete="tel" />
              </div>
            </div>

            <div>
              <div className="etl-field-label">Preferred first contact</div>
              <div className="etl-chips">
                {[
                  { id: 'email', t: 'Email' },
                  { id: 'call',  t: '20-min call' },
                  { id: 'video', t: 'Video' },
                ].map(c => (
                  <div key={c.id} className={`etl-chip ${data.channel === c.id ? 'active' : ''}`}
                       onClick={() => update('channel', c.id)}>
                    {c.t}
                  </div>
                ))}
              </div>
            </div>

            <div>
              <div className="etl-field-label">Security check</div>
              <TurnstileBox onToken={setTurnstileToken} />
            </div>

            {submitError && <div className="etl-err" style={{ fontSize: '0.8rem', marginTop: 4 }}>{submitError}</div>}
          </div>

          {/* Live scope readout */}
          {pathId && currentStep !== 'path' && (
            <div className="etl-scope">
              <div className="sl"><span>// enquiry</span><span className="v">{path.title}</span></div>
              {data.stage && <div className="sl"><span>// stage</span><span className="v">{STAGES.find(s => s.id === data.stage)?.t}</span></div>}
              {data.platforms.length > 0 && <div className="sl"><span>// platforms</span><span className="v">{data.platforms.slice(0, 3).join(' · ')}{data.platforms.length > 3 ? ` +${data.platforms.length - 3}` : ''}</span></div>}
              {data.protocols.length > 0 && <div className="sl"><span>// protocols</span><span className="v">{data.protocols.join(' · ')}</span></div>}
              {(currentStep === 'budget' || steps.indexOf('budget') < stepIdx) && path.id === 'project' && <div className="sl"><span>// budget</span><span className="v">{budgetLabel(data.budget)}</span></div>}
              {data.teamSize && <div className="sl"><span>// team</span><span className="v">{TEAM_SIZES.find(t => t.id === data.teamSize)?.t}</span></div>}
            </div>
          )}
        </div>

        <div className="etl-foot">
          <button className="etl-btn ghost" onClick={back} type="button">
            <span>←</span> {stepIdx === 0 ? 'Change path' : 'Back'}
          </button>
          <span className="sp" />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.7rem', color: 'var(--text-muted)' }}>
            <span className="etl-kbd">Enter</span> to continue
          </span>
          <button className="etl-btn primary" onClick={next} type="button"
                  disabled={(!pathId && currentStep === 'path') || sending}>
            {stepIdx === steps.length - 1 ? 'Send enquiry' : 'Continue'} <span>→</span>
          </button>
        </div>

        <div className={`etl-sending ${sending ? 'on' : ''}`}>
          <div className="dots">Transmitting</div>
        </div>
      </section>
    </div>
  );
}

/* -----------------------------------------------------
   Confirmation receipt
   ----------------------------------------------------- */
function Confirmation({ payload }) {
  const ticketId = useMemo(() => {
    const r = Math.random().toString(36).slice(2, 6).toUpperCase();
    return `ETL-${new Date().getFullYear().toString().slice(-2)}${String(new Date().getMonth()+1).padStart(2,'0')}-${r}`;
  }, []);

  const path = ENQUIRY_PATHS_W_FALLBACK(payload.path);

  return (
    <div className="etl-receipt show">
      <div className="etl-receipt-hdr">
        <div className="stamp">RECEIVED</div>
        <div className="ticket-id">TICKET · {ticketId}</div>
        <h3>Thanks, {payload.name.split(' ')[0] || 'we got it'} — your brief is in.</h3>
        <p>We've logged your enquiry and a senior engineer will read it within one business day. Expect a reply from a real inbox — not an auto-responder.</p>
      </div>

      <div className="etl-receipt-grid">
        {/* Summary */}
        <div className="etl-rcard">
          <h4>Brief summary</h4>
          <div className="etl-summary-row"><div className="k">Enquiry</div><div className="v">{path}</div></div>
          <div className="etl-summary-row"><div className="k">Name</div><div className="v">{payload.name}</div></div>
          <div className="etl-summary-row"><div className="k">Email</div><div className="v">{payload.email}</div></div>
          {payload.company && <div className="etl-summary-row"><div className="k">Company</div><div className="v">{payload.company}</div></div>}
          {payload.platforms?.length > 0 && <div className="etl-summary-row"><div className="k">Platforms</div><div className="v">{payload.platforms.join(' · ')}</div></div>}
          {payload.protocols?.length > 0 && <div className="etl-summary-row"><div className="k">Protocols</div><div className="v">{payload.protocols.join(' · ')}</div></div>}
          {payload.path === 'project' && <div className="etl-summary-row"><div className="k">Budget</div><div className="v">{budgetLabel(payload.budget)}</div></div>}
          {payload.teamSize && <div className="etl-summary-row"><div className="k">Retainer</div><div className="v">{TEAM_SIZES.find(t=>t.id===payload.teamSize)?.t}</div></div>}
          <div className="etl-summary-row"><div className="k">First contact</div><div className="v">{payload.channel}</div></div>
          {payload.nda && <div className="etl-summary-row"><div className="k">NDA</div><div className="v">Requested</div></div>}
        </div>

        {/* What happens next */}
        <div className="etl-rcard">
          <h4>What happens next</h4>
          <div className="etl-tl">
            <div className="etl-tl-item">
              <div className="etl-tl-dot" />
              <div>
                <div className="tl-h">Brief received</div>
                <div className="tl-s">Logged at {new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })}. Confirmation sent to {payload.email}.</div>
                <span className="tl-t">now</span>
              </div>
            </div>
            <div className="etl-tl-item">
              <div className="etl-tl-dot pending" />
              <div>
                <div className="tl-h">Engineer review</div>
                <div className="tl-s">A senior engineer reads your brief and replies from a real inbox.</div>
                <span className="tl-t">within 1 business day</span>
              </div>
            </div>
            {payload.nda && (
              <div className="etl-tl-item">
                <div className="etl-tl-dot pending" />
                <div>
                  <div className="tl-h">Mutual NDA</div>
                  <div className="tl-s">Sent same day; signed before any technical specifics are shared.</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

    </div>
  );
}

// small safe map for labelling enquiry type on confirmation
function ENQUIRY_PATHS_W_FALLBACK(id) {
  const p = ENQUIRY_PATHS.find(x => x.id === id);
  return p ? p.title : 'Enquiry';
}

/* -----------------------------------------------------
   Root
   ----------------------------------------------------- */
function App() {
  const [done, setDone] = useState(null);
  if (done) return <Confirmation payload={done} />;
  return <Wizard onComplete={setDone} />;
}

const mount = document.getElementById('etlContact');
if (mount) {
  ReactDOM.createRoot(mount).render(<App />);
}
