// ── Commission Wizard — 6-step bespoke flow ──────────────────────────

const SILHOUETTES = [
  { id: 'biker',     label: 'Biker',      sub: 'Moto · asymmetric zip' },
  { id: 'racer',     label: 'Café Racer', sub: 'Stand collar · clean front' },
  { id: 'bomber',    label: 'Bomber',     sub: 'Ribbed cuffs · welt pockets' },
  { id: 'aviator',   label: 'Aviator',    sub: 'B-3 silhouette · shearling collar' },
  { id: 'coat',      label: 'Long Coat',  sub: 'Knee or calf · notch lapel' },
  { id: 'blazer',    label: 'Blazer',     sub: 'Tailored · single-button' },
  { id: 'vest',      label: 'Vest',       sub: 'Five-snap front · twin pockets' },
  { id: 'custom',    label: 'Custom',     sub: 'Describe it · we draft from your reference' },
];

const HIDES = [
  { id: 'cowhide',   label: 'Full-grain cowhide',    sub: '1.2–1.8mm · structured, ages best' },
  { id: 'lamb',      label: 'Top-grain lambskin',    sub: '0.7–0.9mm · buttery, body-conscious' },
  { id: 'shearling', label: 'Real shearling',        sub: 'Toscana / merino · warmest, heaviest' },
  { id: 'nubuck',    label: 'Distressed nubuck',     sub: 'Velvety surface · patinas fastest' },
];

const FINISHES = [
  { id: 'onyx',      label: 'Onyx',          swatch: '#0c0a08' },
  { id: 'espresso',  label: 'Espresso',      swatch: '#2a1a10' },
  { id: 'tobacco',   label: 'Tobacco',       swatch: '#6f4a25' },
  { id: 'cognac',    label: 'Cognac',        swatch: '#8c5223' },
  { id: 'rust',      label: 'Rust Oxide',    swatch: '#7a3a1c' },
  { id: 'oxblood',   label: 'Oxblood',       swatch: '#4a1418' },
  { id: 'sand',      label: 'Sand Patina',   swatch: '#a48455' },
  { id: 'smoke',     label: 'Smoke',         swatch: '#4a4338' },
  { id: 'ink',       label: 'Ink',           swatch: '#0d1018' },
  { id: 'pewter',    label: 'Pewter',        swatch: '#5a5e63' },
];

const HARDWARE = [
  { id: 'gunmetal',  label: 'Brushed gunmetal', sub: 'Modern, low-shine' },
  { id: 'brass',     label: 'Antique brass',    sub: 'Warm, vintage' },
  { id: 'nickel',    label: 'Polished nickel',  sub: 'Bright, classical' },
  { id: 'black',     label: 'Matte black',      sub: 'Subtle, contemporary' },
];

const LININGS = [
  { id: 'satin',     label: 'Satin twill',  sub: 'Smooth, glides over a shirt' },
  { id: 'cotton',    label: 'Cotton sateen',sub: 'Breathes, less slip' },
  { id: 'silk',      label: 'Printed silk', sub: '+$80 · custom pattern' },
  { id: 'quilted',   label: 'Quilted satin',sub: '+$40 · warmer' },
];

const MEAS_METHODS = [
  { id: 'tape',      label: 'Tape measure',         sub: 'We send you a guide · you measure yourself' },
  { id: 'reference', label: 'Send a reference',     sub: 'Mail us a well-fitting jacket · we copy the fit' },
  { id: 'tailor',    label: 'Visit a local tailor', sub: 'We reimburse up to $40 for tailor measurements' },
];

const MEASUREMENTS = [
  ['chest',    'Chest',          'Around fullest part'],
  ['shoulder', 'Shoulder width', 'Seam to seam, across the back'],
  ['waist',    'Waist',          'Around natural waist'],
  ['hip',      'Hip',            'Around hip bone'],
  ['sleeve',   'Sleeve length',  'Shoulder seam to wrist bone'],
  ['back',     'Back length',    'Base of neck to desired hem'],
];

function CommissionWizard({ open, onClose }) {
  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState({
    silhouette: null,
    customNote: '',
    customLink: '',
    customPhoto: null,
    hide: null,
    finish: null,
    secondaryFinish: null,
    accentAreas: [],
    hardware: null,
    lining: null,
    monogram: '',
    patches: false,
    contrast: false,
    measMethod: null,
    measurements: {},
    notes: '',
    email: '',
    name: '',
  });
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitErr, setSubmitErr] = React.useState('');

  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const setMeas = (k, v) => setData((d) => ({ ...d, measurements: { ...d.measurements, [k]: v } }));

  React.useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = ''; };
    }
  }, [open]);

  // Step gating — disable Next when required fields missing
  const canAdvance = (() => {
    if (step === 1) return !!data.silhouette;
    if (step === 2) return !!data.hide && !!data.finish;
    if (step === 3) return !!data.hardware && !!data.lining;
    if (step === 4) return true; // optional
    if (step === 5) return !!data.measMethod;
    if (step === 6) return !!data.email && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email);
    return false;
  })();

  const submit = async () => {
    if (!canAdvance || submitting) return;
    setSubmitting(true);
    setSubmitErr('');
    try {
      const res = await fetch('/api/submit-commission', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type:            'wizard',
          silhouette:      data.silhouette,
          customNote:      data.customNote,
          customLink:      data.customLink,
          hide:            data.hide,
          finish:          data.finish,
          secondaryFinish: data.secondaryFinish,
          accentAreas:     data.accentAreas,
          hardware:        data.hardware,
          lining:          data.lining,
          monogram:        data.monogram,
          patches:         data.patches,
          contrast:        data.contrast,
          measMethod:      data.measMethod,
          measurements:    data.measurements,
          name:            data.name,
          email:           data.email,
          notes:           data.notes,
        }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(json.error || 'Submission failed. Please try again.');
      setSent(true);
      setTimeout(() => {
        onClose();
        setTimeout(() => { setSent(false); setStep(1); setSubmitting(false); }, 400);
      }, 3000);
    } catch (e) {
      setSubmitErr(e.message || 'Something went wrong. Please try again.');
      setSubmitting(false);
    }
  };

  if (!open) return null;

  return (
    <div className="commission-overlay" role="dialog" aria-modal="true">
      <header className="commission-head">
        <div className="commission-head-inner container">
          <button className="commission-back" onClick={() => step > 1 && !sent ? setStep(step - 1) : onClose()}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.3">
              <path d="M8.5 2 3 7l5.5 5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            {step > 1 && !sent ? 'Back' : 'Close'}
          </button>
          <div className="commission-progress" aria-label={`Step ${step} of 6`}>
            {[1,2,3,4,5,6].map((n) => (
              <span key={n}
                style={{
                  background: n <= step ? 'var(--fg)' : 'var(--line-2)',
                  width: n === step ? 32 : 18,
                }} />
            ))}
          </div>
          <button className="commission-close" onClick={onClose} aria-label="Close commission">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.3">
              <line x1="2" y1="2" x2="12" y2="12" />
              <line x1="12" y1="2" x2="2" y2="12" />
            </svg>
          </button>
        </div>
      </header>

      <div className="commission-body">
        {sent ? <Sent data={data} /> : (
          <>
            {step === 1 && <Step1 data={data} set={set} />}
            {step === 2 && <Step2 data={data} set={set} />}
            {step === 3 && <Step3 data={data} set={set} />}
            {step === 4 && <Step4 data={data} set={set} />}
            {step === 5 && <Step5 data={data} set={set} setMeas={setMeas} />}
            {step === 6 && <Step6 data={data} set={set} />}
          </>
        )}
      </div>

      {!sent && (
        <footer className="commission-foot">
          <div className="container commission-foot-inner">
            <div className="commission-summary">
              <span className="mono" style={{ color: 'var(--fg-3)' }}>Step {step} of 6</span>
              {data.silhouette && step >= 2 && (
                <span className="commission-chip">{SILHOUETTES.find(s => s.id === data.silhouette)?.label}</span>
              )}
              {data.finish && step >= 3 && (
                <span className="commission-chip">{FINISHES.find(s => s.id === data.finish)?.label}</span>
              )}
              {data.secondaryFinish && step >= 3 && (
                <span className="commission-chip" style={{ color: 'var(--fg-3)' }}>
                  + {FINISHES.find(s => s.id === data.secondaryFinish)?.label} accent
                </span>
              )}
              {data.hardware && step >= 4 && (
                <span className="commission-chip">{HARDWARE.find(s => s.id === data.hardware)?.label}</span>
              )}
            </div>
            {step < 6 ? (
              <button className="btn" disabled={!canAdvance}
                onClick={() => canAdvance && setStep(step + 1)}
                style={{ opacity: canAdvance ? 1 : .4, cursor: canAdvance ? 'pointer' : 'not-allowed' }}>
                Continue <span className="arrow">→</span>
              </button>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
                {submitErr && (
                  <span style={{ fontSize: 11, color: '#c0392b', fontFamily: 'var(--font-mono)' }}>{submitErr}</span>
                )}
                <button className="btn" disabled={!canAdvance || submitting}
                  onClick={submit}
                  style={{ opacity: (canAdvance && !submitting) ? 1 : .4, cursor: (canAdvance && !submitting) ? 'pointer' : 'not-allowed' }}>
                  {submitting ? 'Submitting…' : <><span>Submit commission</span> <span className="arrow">→</span></>}
                </button>
              </div>
            )}
          </div>
        </footer>
      )}
    </div>
  );
}

// ── Steps ────────────────────────────────────────────────────────────

function StepShell({ n, t, sub, children }) {
  return (
    <div className="commission-step container">
      <div className="mono" style={{ color: 'var(--fg-3)', marginBottom: 16 }}>
        Step {n} of 6
      </div>
      <h2 className="display" style={{ fontSize: 'clamp(40px, 6vw, 80px)', margin: 0, lineHeight: 1.02 }}>
        {t}
      </h2>
      {sub && (
        <p style={{
          fontSize: 14, lineHeight: 1.65, color: 'var(--fg-2)',
          maxWidth: 600, marginTop: 18, marginBottom: 40,
        }}>{sub}</p>
      )}
      <div style={{ marginTop: 32 }}>{children}</div>
    </div>
  );
}

function Step1({ data, set }) {
  return (
    <StepShell n={1} t={<><em>Pick</em> the silhouette.</>}
      sub="Choose a starting cut from our catalogue — or describe a custom shape and we'll draft a pattern from your reference.">
      <div className="commission-grid">
        {SILHOUETTES.map((s) => (
          <button key={s.id} onClick={() => set('silhouette', s.id)}
            className={`commission-card ${data.silhouette === s.id ? 'on' : ''}`}>
            <div className="commission-card-name display">{s.label}</div>
            <div className="commission-card-sub mono">{s.sub}</div>
          </button>
        ))}
      </div>
      {data.silhouette === 'custom' && (
        <div className="commission-custom">
          <div className="commission-custom-head mono">
            ◇ &nbsp; Tell us what you have in mind
          </div>
          <textarea
            className="commission-textarea"
            placeholder="Describe the cut, proportions, hardware, references — anything that paints the picture…"
            value={data.customNote} onChange={(e) => set('customNote', e.target.value)} />

          <div className="commission-custom-row">
            <div className="commission-custom-field">
              <label className="mono" style={{ color: 'var(--fg-2)', display: 'block', marginBottom: 6 }}>
                Reference link
              </label>
              <input type="url"
                className="commission-input"
                placeholder="https://… (Pinterest, lookbook, Instagram post)"
                value={data.customLink}
                onChange={(e) => set('customLink', e.target.value)} />
            </div>

            <div className="commission-custom-field">
              <label className="mono" style={{ color: 'var(--fg-2)', display: 'block', marginBottom: 6 }}>
                Upload a reference photo
              </label>
              <PhotoDrop
                value={data.customPhoto}
                onChange={(p) => set('customPhoto', p)} />
            </div>
          </div>
        </div>
      )}
    </StepShell>
  );
}

// Photo upload via drag-drop OR click-to-browse. Encodes to a thumbnail
// data URL purely in-memory — submission would post this off-page; for the
// prototype it just shows the file is captured.
function PhotoDrop({ value, onChange }) {
  const inputRef = React.useRef(null);
  const [dragOver, setDragOver] = React.useState(false);
  const [error, setError] = React.useState(null);

  const ingest = async (file) => {
    setError(null);
    if (!file) return;
    if (!/^image\//.test(file.type)) {
      setError('Please drop an image file.');
      return;
    }
    try {
      const url = await new Promise((res, rej) => {
        const r = new FileReader();
        r.onload = () => res(r.result);
        r.onerror = rej;
        r.readAsDataURL(file);
      });
      onChange({ name: file.name, size: file.size, url });
    } catch {
      setError('Could not read that file.');
    }
  };

  const onDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    const f = e.dataTransfer?.files?.[0];
    if (f) ingest(f);
  };

  if (value) {
    return (
      <div className="commission-photo-filled">
        <img src={value.url} alt={value.name} />
        <div className="commission-photo-meta">
          <div className="mono" style={{ color: 'var(--fg)' }}>{value.name}</div>
          <div className="mono" style={{ color: 'var(--fg-3)' }}>
            {(value.size / 1024).toFixed(0)} KB
          </div>
        </div>
        <button type="button" className="mono"
          onClick={() => onChange(null)}
          style={{ color: 'var(--fg-3)', alignSelf: 'flex-start' }}
          onMouseEnter={(e) => e.currentTarget.style.color = 'var(--fg)'}
          onMouseLeave={(e) => e.currentTarget.style.color = ''}>
          Remove ✕
        </button>
      </div>
    );
  }

  return (
    <>
      <button
        type="button"
        onClick={() => inputRef.current?.click()}
        onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={onDrop}
        className={`commission-photo-drop ${dragOver ? 'on' : ''}`}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="3" width="18" height="18" rx="2" />
          <circle cx="8.5" cy="8.5" r="1.5" />
          <path d="m21 15-5-5L5 21" />
        </svg>
        <div>
          <div style={{ color: 'var(--fg)', fontSize: 13 }}>Drop a photo here</div>
          <div className="mono" style={{ color: 'var(--fg-3)', marginTop: 4 }}>
            or click to browse · PNG / JPG / WebP
          </div>
        </div>
      </button>
      <input ref={inputRef} type="file" accept="image/*"
        style={{ display: 'none' }}
        onChange={(e) => ingest(e.target.files?.[0])} />
      {error && (
        <div className="mono" style={{ color: 'var(--fg)', marginTop: 8 }}>
          {error}
        </div>
      )}
    </>
  );
}

const ACCENT_AREAS = [
  { id: 'fur',     label: 'Fur / shearling collar' },
  { id: 'collar',  label: 'Collar trim' },
  { id: 'stitch',  label: 'Stitching' },
  { id: 'pocket',  label: 'Pocket trim' },
  { id: 'cuffs',   label: 'Cuff panels' },
];

function Step2({ data, set }) {
  const toggleArea = (id) => {
    const cur = data.accentAreas || [];
    set('accentAreas', cur.includes(id) ? cur.filter((a) => a !== id) : [...cur, id]);
  };

  return (
    <StepShell n={2} t={<><em>Choose</em> your leather.</>}
      sub="Hide first — then the finish. Every finish is hand-pulled in small batches and will continue developing once you start wearing it.">

      {/* ── Hide ── */}
      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.18em',
        textTransform: 'uppercase', color: 'var(--fg-2)', marginBottom: 14,
      }}>Hide</div>
      <div className="commission-grid">
        {HIDES.map((h) => (
          <button key={h.id} onClick={() => set('hide', h.id)}
            className={`commission-card ${data.hide === h.id ? 'on' : ''}`}>
            <div className="commission-card-name display">{h.label}</div>
            <div className="commission-card-sub mono">{h.sub}</div>
          </button>
        ))}
      </div>

      {/* ── Primary finish ── */}
      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.18em',
        textTransform: 'uppercase', color: 'var(--fg-2)',
        marginTop: 48, marginBottom: 14,
      }}>Primary finish</div>
      <div className="commission-finishes">
        {FINISHES.map((f) => (
          <button key={f.id} onClick={() => set('finish', f.id)}
            className={`commission-finish ${data.finish === f.id ? 'on' : ''}`}>
            <span className="commission-swatch" style={{ background: f.swatch }} />
            <span className="display">{f.label}</span>
          </button>
        ))}
      </div>

      {/* ── Secondary accent block ── */}
      <div style={{
        marginTop: 48,
        padding: '28px 28px 26px',
        border: '.5px solid var(--line-2)',
        background: 'color-mix(in srgb, var(--fg) 2%, transparent)',
      }}>
        {/* Header row */}
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10 }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.18em',
            textTransform: 'uppercase', color: 'var(--fg-2)',
          }}>Secondary accent</div>
          <span style={{
            fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '.12em',
            textTransform: 'uppercase', color: 'var(--fg-3)',
            border: '.5px solid var(--line-2)',
            padding: '2px 8px',
          }}>optional</span>
        </div>

        {/* Disclaimer */}
        <p style={{
          fontFamily: 'var(--font-mono)', fontSize: 10.5, lineHeight: 1.75,
          color: 'var(--fg-3)', maxWidth: 580, margin: '0 0 22px',
        }}>
          A second tone applied to accent surfaces — shearling or fur collars,
          contrast stitching, collar piping, or pocket trim. We send a digital
          proof before any cutting begins. If your silhouette doesn't include
          these surfaces, the selection is simply skipped.
        </p>

        {/* Secondary swatch grid */}
        <div className="commission-finishes">
          <button
            onClick={() => { set('secondaryFinish', null); set('accentAreas', []); }}
            className={`commission-finish ${!data.secondaryFinish ? 'on' : ''}`}>
            <span style={{
              width: 32, height: 32, flexShrink: 0,
              border: '.5px solid var(--line-2)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 15, color: 'var(--fg-3)',
            }}>—</span>
            <span className="display" style={{ fontSize: 16, color: 'var(--fg-3)' }}>None</span>
          </button>
          {FINISHES.map((f) => (
            <button key={f.id} onClick={() => set('secondaryFinish', f.id)}
              className={`commission-finish ${data.secondaryFinish === f.id ? 'on' : ''}`}>
              <span className="commission-swatch" style={{ background: f.swatch }} />
              <span className="display" style={{ fontSize: 16 }}>{f.label}</span>
            </button>
          ))}
        </div>

        {/* Accent surface checkboxes — only shown when a secondary finish is picked */}
        {data.secondaryFinish && (
          <div style={{ marginTop: 26 }}>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '.14em',
              textTransform: 'uppercase', color: 'var(--fg-2)', marginBottom: 12,
            }}>Apply accent to</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {ACCENT_AREAS.map((a) => {
                const checked = (data.accentAreas || []).includes(a.id);
                return (
                  <button key={a.id} onClick={() => toggleArea(a.id)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 9,
                      padding: '9px 16px',
                      border: `.5px solid ${checked ? 'var(--fg)' : 'var(--line-2)'}`,
                      background: checked
                        ? 'color-mix(in srgb, var(--fg) 6%, transparent)'
                        : 'transparent',
                      color: checked ? 'var(--fg)' : 'var(--fg-2)',
                      fontFamily: 'var(--font-mono)', fontSize: 10.5,
                      letterSpacing: '.08em',
                      cursor: 'pointer',
                      transition: 'border-color .18s, background .18s, color .18s',
                    }}>
                    {/* tiny checkbox square */}
                    <span style={{
                      width: 11, height: 11, flexShrink: 0,
                      border: `.5px solid ${checked ? 'var(--fg)' : 'var(--line-2)'}`,
                      background: checked ? 'var(--fg)' : 'transparent',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      transition: 'all .18s',
                    }}>
                      {checked && (
                        <svg width="7" height="5" viewBox="0 0 7 5" fill="none" stroke="var(--bg)" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round">
                          <path d="M1 2.5l1.8 1.8L6 1" />
                        </svg>
                      )}
                    </span>
                    {a.label}
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </div>

    </StepShell>
  );
}

function Step3({ data, set }) {
  return (
    <StepShell n={3} t={<><em>Hardware</em> & lining.</>}
      sub="Zips, snaps, buckles and the inside of your jacket — small choices that shift the whole feel.">
      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.18em',
        textTransform: 'uppercase', color: 'var(--fg-2)', marginBottom: 14,
      }}>Hardware</div>
      <div className="commission-grid">
        {HARDWARE.map((h) => (
          <button key={h.id} onClick={() => set('hardware', h.id)}
            className={`commission-card ${data.hardware === h.id ? 'on' : ''}`}>
            <div className="commission-card-name display">{h.label}</div>
            <div className="commission-card-sub mono">{h.sub}</div>
          </button>
        ))}
      </div>

      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.18em',
        textTransform: 'uppercase', color: 'var(--fg-2)',
        marginTop: 48, marginBottom: 14,
      }}>Lining</div>
      <div className="commission-grid">
        {LININGS.map((l) => (
          <button key={l.id} onClick={() => set('lining', l.id)}
            className={`commission-card ${data.lining === l.id ? 'on' : ''}`}>
            <div className="commission-card-name display">{l.label}</div>
            <div className="commission-card-sub mono">{l.sub}</div>
          </button>
        ))}
      </div>
    </StepShell>
  );
}

function Step4({ data, set }) {
  return (
    <StepShell n={4} t={<><em>Personal</em> details.</>}
      sub="Optional. Monogram is hand-stamped on the inner placket. We'll send back a digital proof for any of these before production.">
      <div className="commission-detail">
        <div>
          <div className="display" style={{ fontSize: 24, marginBottom: 6 }}>Monogram</div>
          <div className="mono" style={{ color: 'var(--fg-3)' }}>
            Up to 3 characters, hand-stamped inner placket
          </div>
        </div>
        <input
          type="text" maxLength={3}
          className="commission-input"
          placeholder="ABC"
          value={data.monogram}
          onChange={(e) => set('monogram', e.target.value.toUpperCase())}
          style={{ width: 120, textTransform: 'uppercase', letterSpacing: '.2em', textAlign: 'center' }} />
      </div>

      <div className="commission-detail">
        <div>
          <div className="display" style={{ fontSize: 24, marginBottom: 6 }}>Contrast stitching</div>
          <div className="mono" style={{ color: 'var(--fg-3)' }}>
            Yellow, white or red top-stitch across seams (+$45)
          </div>
        </div>
        <button onClick={() => set('contrast', !data.contrast)}
          className={`commission-toggle ${data.contrast ? 'on' : ''}`}
          aria-pressed={data.contrast}>
          <span />
        </button>
      </div>

      <div className="commission-detail">
        <div>
          <div className="display" style={{ fontSize: 24, marginBottom: 6 }}>Custom patches</div>
          <div className="mono" style={{ color: 'var(--fg-3)' }}>
            Send us up to 3 patches by mail (+$25 application)
          </div>
        </div>
        <button onClick={() => set('patches', !data.patches)}
          className={`commission-toggle ${data.patches ? 'on' : ''}`}
          aria-pressed={data.patches}>
          <span />
        </button>
      </div>
    </StepShell>
  );
}

function Step5({ data, set, setMeas }) {
  return (
    <StepShell n={5} t={<><em>Your</em> measurements.</>}
      sub="Tell us how you'd like to handle the fit. If you tape-measure, fill in what you can — we'll follow up if anything's missing.">
      <div className="commission-grid">
        {MEAS_METHODS.map((m) => (
          <button key={m.id} onClick={() => set('measMethod', m.id)}
            className={`commission-card ${data.measMethod === m.id ? 'on' : ''}`}>
            <div className="commission-card-name display">{m.label}</div>
            <div className="commission-card-sub mono">{m.sub}</div>
          </button>
        ))}
      </div>

      {data.measMethod === 'tape' && (
        <div style={{ marginTop: 40 }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.18em',
            textTransform: 'uppercase', color: 'var(--fg-2)', marginBottom: 14,
          }}>Measurements (inches)</div>
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16,
          }}>
            {MEASUREMENTS.map(([key, label, hint]) => (
              <div key={key}>
                <label style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                  fontFamily: 'var(--font-mono)', fontSize: 11,
                  letterSpacing: '.14em', textTransform: 'uppercase',
                  color: 'var(--fg-2)', marginBottom: 6,
                }}>
                  <span>{label}</span>
                  <span style={{ color: 'var(--fg-3)', textTransform: 'none', letterSpacing: 0 }}>{hint}</span>
                </label>
                <input type="number" min="0" step="0.25"
                  className="commission-input"
                  placeholder="in"
                  value={data.measurements[key] || ''}
                  onChange={(e) => setMeas(key, e.target.value)} />
              </div>
            ))}
          </div>
        </div>
      )}
    </StepShell>
  );
}

function Step6({ data, set }) {
  const sil = SILHOUETTES.find(s => s.id === data.silhouette);
  const hide = HIDES.find(h => h.id === data.hide);
  const fin = FINISHES.find(f => f.id === data.finish);
  const fin2 = FINISHES.find(f => f.id === data.secondaryFinish);
  const hw = HARDWARE.find(h => h.id === data.hardware);
  const ln = LININGS.find(l => l.id === data.lining);
  const meth = MEAS_METHODS.find(m => m.id === data.measMethod);
  const areaLabels = (data.accentAreas || [])
    .map((id) => ACCENT_AREAS.find((a) => a.id === id)?.label)
    .filter(Boolean).join(', ');

  return (
    <StepShell n={6} t={<><em>Review</em> & submit.</>}
      sub="Here's what we have. Submit and we'll be in touch within 24 hours with confirmation, a quote and digital proofs of any custom details.">
      <div className="commission-review">
        {[
          ['Silhouette', sil?.label, sil?.sub],
          ['Hide', hide?.label, hide?.sub],
          ['Primary finish', fin?.label, ''],
          ...(fin2 ? [['Secondary accent', fin2.label, areaLabels || 'Surfaces TBD']] : []),
          ['Hardware', hw?.label, hw?.sub],
          ['Lining', ln?.label, ln?.sub],
          ['Monogram', data.monogram || '—', ''],
          ['Contrast stitching', data.contrast ? 'Yes (+$45)' : '—', ''],
          ['Custom patches', data.patches ? 'Yes (+$25)' : '—', ''],
          ['Measurements', meth?.label, meth?.sub],
        ].map(([k, v, s]) => (
          <div key={k} className="commission-review-row">
            <div className="mono" style={{ color: 'var(--fg-3)' }}>{k}</div>
            <div>
              <div style={{ fontSize: 14 }}>{v}</div>
              {s && <div className="mono" style={{ color: 'var(--fg-3)', marginTop: 4 }}>{s}</div>}
            </div>
          </div>
        ))}
      </div>

      <div style={{
        marginTop: 40, padding: '24px 0', borderTop: '.5px solid var(--line)',
      }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16,
        }}>
          <div>
            <label className="mono" style={{ color: 'var(--fg-2)', display: 'block', marginBottom: 6 }}>
              Your name
            </label>
            <input type="text" className="commission-input"
              placeholder="Full name"
              value={data.name} onChange={(e) => set('name', e.target.value)} />
          </div>
          <div>
            <label className="mono" style={{ color: 'var(--fg-2)', display: 'block', marginBottom: 6 }}>
              Email *
            </label>
            <input type="email" className="commission-input"
              placeholder="your@email.com"
              value={data.email} onChange={(e) => set('email', e.target.value)} />
          </div>
        </div>
        <div style={{ marginTop: 16 }}>
          <label className="mono" style={{ color: 'var(--fg-2)', display: 'block', marginBottom: 6 }}>
            Notes for the team (optional)
          </label>
          <textarea className="commission-textarea"
            placeholder="Anything we should know — preferences, references, deadline…"
            value={data.notes} onChange={(e) => set('notes', e.target.value)} />
        </div>
      </div>

      <p className="mono" style={{ color: 'var(--fg-3)', marginTop: 24 }}>
        Submitting this isn't a commitment. We'll respond with a quote within 24 hours and
        you pay nothing until you approve the proofs.
      </p>
    </StepShell>
  );
}

function Sent({ data }) {
  return (
    <div className="container" style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      minHeight: '60vh', textAlign: 'center', padding: '60px 0',
    }}>
      <div className="mono" style={{ color: 'var(--fg-3)', marginBottom: 18 }}>
        ◇ &nbsp; Commission received
      </div>
      <h2 className="display" style={{ fontSize: 'clamp(48px, 7vw, 96px)', margin: 0, lineHeight: 1.02 }}>
        Thank you, <em className="gradient-text">{data.name ? data.name.split(' ')[0] : 'friend'}.</em>
      </h2>
      <p style={{
        fontSize: 15, lineHeight: 1.7, color: 'var(--fg-2)',
        maxWidth: 480, marginTop: 24,
      }}>
        We'll be in touch at <strong style={{ color: 'var(--fg)' }}>{data.email}</strong> within
        24 hours with confirmation, a quote and digital proofs of any custom details.
      </p>
      <div className="mono" style={{ color: 'var(--fg-3)', marginTop: 32 }}>
        Reference · LO-COM-{Date.now().toString(36).toUpperCase().slice(-6)}
      </div>
    </div>
  );
}

Object.assign(window, { CommissionWizard });
