// IntakeWizard — guided Q&A flow that replaces the long-scroll new-
// order form. Each top-level step is a focused screen; cabinets are
// added in a tight inner loop with three actions (Back / Add another
// / Done adding). Uses the same data shape as the legacy form so
// save-draft / submit / insurance PDF all keep working unchanged.
//
// Steps:
//   1. Vendor contact            (phone required)
//   2. Service type              Yes/No/Potential — gates step 3
//   3. Customer                  (Yes branch only; name + address required)
//   4. Property type
//   5. Timing + RUSH (auto-prompts when within rushThresholdDays)
//   6. Cabinets loop             (per-cabinet sub-wizard a→h)
//   7. Toe kick
//   8. Scribe
//   9. Special instructions
//  10. Review + Submit / Save Draft / Insurance Estimate
//
// Key fixes from the first iteration:
//   - First cabinet is created in a useEffect, NEVER during render
//     (the previous setData-during-render caused 2-4 ghost cabinets).
//   - Cabinet flow ends with three buttons instead of window.confirm.
//   - Rush upcharge reads from pricing.rush_upcharge_flat (the source
//     of truth for prices) so wizard and submitted-order agree.
//   - Running total displayed in the footer on every step.
//   - Review screen has Edit buttons per section + per-cabinet edit
//     and remove, plus the "estimate" disclaimer.
//   - Date picker enforces today+3 minimum; 3-10 days is the rush
//     window.

const { useState: uS, useEffect: uE, useMemo: uM, useRef: uR } = React;

const MS_PER_DAY = 24 * 60 * 60 * 1000;
const todayPlus = (n) => {
  const d = new Date(Date.now() + n * MS_PER_DAY);
  return d.toISOString().slice(0, 10);
};
const daysBetween = (iso) => {
  if (!iso) return null;
  const target = new Date(iso).getTime();
  return Math.round((target - Date.now()) / MS_PER_DAY);
};

// ---------- shared layout ----------

function StepShell({ step, total, title, subtitle, onBack, onNext, nextLabel, nextDisabled, runningTotal, children, extraActions }) {
  return (
    <div className="wiz-shell">
      <div className="wiz-progress">
        <div className="wiz-progress-bar" style={{ width: `${(step / total) * 100}%` }} />
      </div>
      <div className="wiz-body">
        <div className="wiz-stepnum">Step {step} of {total}</div>
        <h1 className="wiz-title">{title}</h1>
        {subtitle && <p className="wiz-sub">{subtitle}</p>}
        <div className="wiz-content">{children}</div>
      </div>
      <div className="wiz-footer">
        <button className="btn ghost" onClick={onBack} disabled={!onBack}>← Back</button>
        {runningTotal != null && (
          <div className="wiz-runningtotal">
            <span className="wiz-runningtotal-l">Running total</span>
            <span className="wiz-runningtotal-v mono">{fmtMoney(runningTotal)}</span>
          </div>
        )}
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {extraActions}
          {onNext && (
            <button className="btn primary lg" onClick={onNext} disabled={nextDisabled}>
              {nextLabel || 'Next →'}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function Field({ label, required, children, hint }) {
  return (
    <div className="wiz-field">
      <label className="wiz-label">{label}{required && <span className="req"> *</span>}</label>
      {children}
      {hint && <div className="hint" style={{ fontSize: 11, marginTop: 4 }}>{hint}</div>}
    </div>
  );
}

function Segmented({ value, options, onChange }) {
  return (
    <div className="segmented">
      {options.map(o => {
        const v = typeof o === 'string' ? o : o.v;
        const l = typeof o === 'string' ? o : o.l;
        return (
          <button key={v} className={value === v ? 'on' : ''} onClick={() => onChange(v)}>{l}</button>
        );
      })}
    </div>
  );
}

// Lightweight cabinet visual — front view, scaled to fit a fixed box.
function CabinetPreview({ cab }) {
  const wIn = parseFloat(cab.w) || 0;
  const hIn = parseFloat(cab.h) || 0;
  const dIn = parseFloat(cab.d) || 0;
  if (!wIn || !hIn) return null;
  const maxBox = 220;
  const ratio = wIn / hIn;
  const boxW = ratio >= 1 ? maxBox : Math.round(maxBox * ratio);
  const boxH = ratio >= 1 ? Math.round(maxBox / ratio) : maxBox;

  const doors = parseInt(cab.doors) || 0;
  const drawers = parseInt(cab.drawers) || 0;
  // Layout: drawer bank fills top portion when drawers present.
  const drawerBankPct = drawers > 0 && doors > 0 ? 0.4 : (drawers > 0 ? 1.0 : 0);
  const drawerBankH = boxH * drawerBankPct;
  const doorAreaH = boxH - drawerBankH - (drawers > 0 && doors > 0 ? 4 : 0);
  const stileW = 6;

  return (
    <div className="wiz-cabpreview">
      <svg width={boxW} height={boxH} style={{ display: 'block' }}>
        {/* outer box */}
        <rect x="0" y="0" width={boxW} height={boxH} fill="#fdf8e9" stroke="#0a2240" strokeWidth="2" />
        {/* face frame stiles */}
        <rect x="0" y="0" width={stileW} height={boxH} fill="#0a2240" opacity="0.15" />
        <rect x={boxW - stileW} y="0" width={stileW} height={boxH} fill="#0a2240" opacity="0.15" />

        {/* drawer bank */}
        {drawers > 0 && Array.from({ length: drawers }).map((_, i) => {
          const dh = drawerBankH / drawers;
          return (
            <g key={'dr' + i}>
              <rect x={stileW + 2} y={i * dh + 2} width={boxW - 2 * (stileW + 2)} height={dh - 4}
                    fill="#fff" stroke="#0a2240" strokeWidth="1" rx="2" />
            </g>
          );
        })}

        {/* doors */}
        {doors > 0 && (
          <g>
            {Array.from({ length: doors }).map((_, i) => {
              const dw = (boxW - 2 * stileW - (doors - 1) * 4) / doors;
              const dx = stileW + i * (dw + 4);
              const dy = drawerBankH + (drawers > 0 ? 4 : 0);
              const hingeOnLeft = (() => {
                if (cab.hingeConfig === 'left') return true;
                if (cab.hingeConfig === 'right') return false;
                if (cab.hingeConfig === 'meeting') return i < doors / 2 ? true : false;
                if (cab.hingeConfig === 'custom' && cab.hinges?.[i]) return cab.hinges[i] === 'L';
                return i < doors / 2;
              })();
              return (
                <g key={'dr' + i}>
                  <rect x={dx} y={dy} width={dw} height={doorAreaH}
                        fill="#fff" stroke="#0a2240" strokeWidth="1" rx="2" />
                  <circle cx={hingeOnLeft ? dx + 5 : dx + dw - 5} cy={dy + doorAreaH / 2} r="2" fill="#b08720" />
                </g>
              );
            })}
          </g>
        )}

        {/* labels */}
        <text x={boxW / 2} y={boxH + 14} textAnchor="middle" fontSize="11" fill="#555" fontFamily="JetBrains Mono, monospace">
          {wIn}" × {hIn}" × {dIn}"
        </text>
      </svg>
    </div>
  );
}

// ---------- Step 1 — Vendor contact ----------

function VendorContactStep({ data, setData, vendor, ...nav }) {
  return (
    <StepShell {...nav} title="Your contact info" subtitle="So we can reach you about this order.">
      <Field label="Vendor name" required>
        <input className="input" value={data.vendorName || vendor.name || ''}
               onChange={e => setData({ ...data, vendorName: e.target.value })} />
      </Field>
      <Field label="Contact person">
        <input className="input" value={data.vendorContact || ''}
               placeholder="Point of contact"
               onChange={e => setData({ ...data, vendorContact: e.target.value })} />
      </Field>
      <Field label="Phone" required>
        <input className="input mono" value={data.vendorPhone || ''}
               placeholder="(480) 555-0100"
               onChange={e => setData({ ...data, vendorPhone: e.target.value })} />
      </Field>
      <Field label="Email">
        <input className="input" value={data.vendorEmail || ''}
               placeholder="pm@company.com"
               onChange={e => setData({ ...data, vendorEmail: e.target.value })} />
      </Field>
      <Field label="PO / job ref">
        <input className="input mono" value={data.vendorPO || ''}
               placeholder="Your PO or job number"
               onChange={e => setData({ ...data, vendorPO: e.target.value })} />
      </Field>
      <div className="hint" style={{ fontSize: 12, marginTop: 8 }}>
        Phone is required so we can text or call about the order. Email and PO are optional.
      </div>
    </StepShell>
  );
}

// ---------- Step 2 — Service type ----------

function ServiceTypeStep({ data, setData, ...nav }) {
  const choose = (v) => setData({ ...data, installNeeded: v });
  return (
    <StepShell {...nav} title="Will this order require pickup, drop-off, or install?"
      subtitle="Pick one. We'll only ask for the customer's address if it does.">
      <div className="wiz-bigchips">
        {[
          { v: 'Yes',       l: 'Yes',       d: 'Pickup, drop-off, or install at the customer\'s location.' },
          { v: 'No',        l: 'No',        d: 'Vendor handles the cabinets — no Precision visit needed.' },
          { v: 'Potential', l: 'Potential', d: 'Maybe later — we can fill in customer details when known.' },
        ].map(o => (
          <button key={o.v}
                  className={'wiz-bigchip' + (data.installNeeded === o.v ? ' on' : '')}
                  onClick={() => choose(o.v)}>
            <div className="wiz-bigchip-l">{o.l}</div>
            <div className="wiz-bigchip-d">{o.d}</div>
          </button>
        ))}
      </div>
    </StepShell>
  );
}

// ---------- Step 3 — Customer ----------

function CustomerStep({ data, setData, ...nav }) {
  return (
    <StepShell {...nav} title="Customer info" subtitle="Required: name and address. Contact info optional.">
      <Field label="Customer name" required>
        <input className="input" value={data.clientName || ''}
               onChange={e => setData({ ...data, clientName: e.target.value })} />
      </Field>
      <Field label="Address" required>
        <input className="input" value={data.address || ''}
               placeholder="Street, city, state, ZIP"
               onChange={e => setData({ ...data, address: e.target.value })} />
      </Field>
      <Field label="Phone">
        <input className="input mono" value={data.clientPhone || ''}
               onChange={e => setData({ ...data, clientPhone: e.target.value })} />
      </Field>
      <Field label="Email">
        <input className="input" value={data.clientEmail || ''}
               onChange={e => setData({ ...data, clientEmail: e.target.value })} />
      </Field>
      <Field label="Preferred contact">
        <Segmented value={data.preferredContact || 'Phone'}
                   options={['Phone', 'Text', 'Email']}
                   onChange={v => setData({ ...data, preferredContact: v })} />
      </Field>
      <Field label="Access notes">
        <textarea className="textarea" value={data.accessNotes || ''}
                  placeholder="Gate code, pets, parking…"
                  onChange={e => setData({ ...data, accessNotes: e.target.value })} />
      </Field>
    </StepShell>
  );
}

// ---------- Step 4 — Property ----------

function PropertyStep({ data, setData, ...nav }) {
  return (
    <StepShell {...nav} title="What type of property?" subtitle="Helps us size the trip and prep the right materials.">
      <Segmented value={data.homeType || 'Single fam.'}
                 options={['Single fam.', 'Condo', 'Rental', 'Commercial']}
                 onChange={v => setData({ ...data, homeType: v })} />
    </StepShell>
  );
}

// ---------- Step 5 — Timing + RUSH ----------

function TimingStep({ data, setData, pricing, sc, onConfirmRush, ...nav }) {
  const dateChosen = data.completionRequested || '';
  const minDate = todayPlus(3);
  const threshold = (sc && sc.rushThresholdDays) || 10;       // default 10
  const upcharge = (pricing && pricing.rush_upcharge_flat?.price) || 0;
  const days = daysBetween(dateChosen);
  const tooSoon = days != null && days < 3;
  const insideRush = days != null && days >= 3 && days <= threshold;

  const onNext = () => {
    if (!dateChosen) return;
    if (tooSoon) {
      alert('Earliest completion date is 3 days from today. Please pick a later date.');
      return;
    }
    if (insideRush && data.rush !== true) {
      onConfirmRush({ days, threshold, upcharge });
    } else {
      nav.onNext();
    }
  };

  return (
    <StepShell {...nav} onNext={onNext} title="When does the customer need this?" subtitle={`Earliest is 3 days out. Anything ${threshold} days or sooner triggers RUSH.`}>
      <Field label="Completion requested" required>
        <input className="input mono" type="date" value={dateChosen}
               min={minDate}
               onChange={e => setData({ ...data, completionRequested: e.target.value })} />
        {days != null && (
          <div className="hint" style={{ fontSize: 11, marginTop: 4, color: tooSoon ? '#b91c1c' : (insideRush ? '#b08720' : 'var(--ink-faint)') }}>
            {tooSoon ? `Too soon — earliest is 3 days out.`
              : `${days} day${days === 1 ? '' : 's'} from today.`
            }
            {insideRush && ` Inside our ${threshold}-day rush window.`}
          </div>
        )}
      </Field>
      <Field label="RUSH order?" hint={`Adds $${upcharge} to the order. We'll auto-prompt if your date is within ${threshold} days.`}>
        <Segmented value={data.rush ? 'Yes' : 'No'}
                   options={['No', 'Yes']}
                   onChange={v => setData({ ...data, rush: v === 'Yes' })} />
      </Field>
    </StepShell>
  );
}

// ---------- Step 6 — Cabinets loop ----------

// Vanity presets — 21" is the typical depth, 24" available for the
// larger units. Each preset bakes in width × height × depth + the
// door/drawer config that goes with the layout. Picking any of these
// auto-sets cabType='Vanity' so the cabinet-type step is skipped.
const VANITY_PRESETS = [
  { code: 'V18',       w: '18', h: '32', d: '21', doors: 1, drawers: 0, drawerLayout: '', desc: '18×32×21 — single door' },
  { code: 'V24',       w: '24', h: '32', d: '21', doors: 1, drawers: 0, drawerLayout: '', desc: '24×32×21 — single door' },
  { code: 'V30',       w: '30', h: '32', d: '21', doors: 2, drawers: 0, drawerLayout: '', desc: '30×32×21 — 2 doors' },
  { code: 'V36',       w: '36', h: '32', d: '21', doors: 2, drawers: 0, drawerLayout: '', desc: '36×32×21 — 2 doors' },
  { code: 'V36-24D',   w: '36', h: '32', d: '24', doors: 2, drawers: 0, drawerLayout: '', desc: '36×32×24 — 2 doors (deep)' },
  { code: 'V36-3D',    w: '36', h: '32', d: '21', doors: 2, drawers: 3, drawerLayout: '3-equal', desc: '36×32×21 — 3 drw ctr, 2 outer doors' },
  { code: 'V36-3DL',   w: '36', h: '32', d: '21', doors: 1, drawers: 3, drawerLayout: '3-equal', desc: '36×32×21 — 3 drw L, 1 door R' },
  { code: 'V36-3DR',   w: '36', h: '32', d: '21', doors: 1, drawers: 3, drawerLayout: '3-equal', desc: '36×32×21 — 3 drw R, 1 door L' },
  { code: 'V42',       w: '42', h: '32', d: '21', doors: 2, drawers: 0, drawerLayout: '', desc: '42×32×21 — 2 doors' },
  { code: 'V48',       w: '48', h: '32', d: '21', doors: 2, drawers: 0, drawerLayout: '', desc: '48×32×21 — 2 doors' },
  { code: 'V48-3D',    w: '48', h: '32', d: '21', doors: 2, drawers: 3, drawerLayout: '3-equal', desc: '48×32×21 — 3 drw ctr, 2 outer doors' },
  { code: 'V48-24D',   w: '48', h: '32', d: '24', doors: 2, drawers: 3, drawerLayout: '3-equal', desc: '48×32×24 — 3 drw ctr, 2 doors (deep)' },
  { code: 'V60',       w: '60', h: '32', d: '21', doors: 2, drawers: 0, drawerLayout: '', desc: '60×32×21 — 2 doors' },
  { code: 'V60-3D',    w: '60', h: '32', d: '21', doors: 2, drawers: 3, drawerLayout: '3-equal', desc: '60×32×21 — 3 drw ctr, 2 outer doors' },
  { code: 'V60-24D',   w: '60', h: '32', d: '24', doors: 2, drawers: 3, drawerLayout: '3-equal', desc: '60×32×24 — 3 drw ctr, 2 doors (deep)' },
  { code: 'V72-3D',    w: '72', h: '32', d: '21', doors: 2, drawers: 3, drawerLayout: '3-equal', desc: '72×32×21 — 3 drw ctr, 2 outer doors' },
  { code: 'V72-24D',   w: '72', h: '32', d: '24', doors: 2, drawers: 3, drawerLayout: '3-equal', desc: '72×32×24 — 3 drw ctr, 2 doors (deep)' },
];

function PhotosBlock({ cab, onChange }) {
  if (!cab.photo) {
    return (
      <div style={{ display: 'flex', gap: 8 }}>
        <PhotoCaptureButton kind="camera" onSet={(src) => onChange({ photo: src })} />
        <PhotoCaptureButton kind="upload" onSet={(src) => onChange({ photo: src })} />
      </div>
    );
  }
  return (
    <div>
      <MarkupCanvas photo={cab.photo} annotations={cab.annotations || []} setAnnotations={(ann) => onChange({ annotations: ann })} />
      <button className="btn ghost" style={{ marginTop: 6 }}
        onClick={() => onChange({ photo: null, annotations: [] })}><Icon.X/> Replace photo</button>
    </div>
  );
}

function DoorsBlock({ cab, onChange }) {
  const doors = parseInt(cab.doors) || 0;
  return (
    <div className="wiz-block">
      <div className="wiz-block-head">
        <div>
          <div className="wiz-block-title">Doors</div>
          <div className="wiz-block-sub">How many, and is Precision repairing them?</div>
        </div>
        <NumberStepper value={cab.doors || 0} onChange={(v) => onChange({ doors: v })} />
      </div>
      <label className="wiz-checkbox">
        <input type="checkbox" checked={cab.doorsRepair === true}
               onChange={e => onChange({ doorsRepair: e.target.checked })} />
        <span>Doors need repair (charged)</span>
      </label>
      {doors > 0 && (
        <div style={{ marginTop: 8 }}>
          <div className="wiz-block-sub" style={{ marginBottom: 4 }}>Hinge configuration</div>
          {doors === 1 ? (
            <Segmented value={cab.hingeConfig || 'left'}
                       options={[{ v: 'left', l: 'Hinged Left' }, { v: 'right', l: 'Hinged Right' }]}
                       onChange={v => onChange({ hingeConfig: v })} />
          ) : (
            <>
              <Segmented value={cab.hingeConfig || 'meeting'}
                         options={[
                           { v: 'meeting', l: 'Double / outer hinges' },
                           { v: 'custom',  l: 'Custom per door' },
                         ]}
                         onChange={v => onChange({
                           hingeConfig: v,
                           hinges: v === 'custom' ? Array.from({ length: doors }, (_, i) => (cab.hinges?.[i] || 'L')) : [],
                         })} />
              {cab.hingeConfig === 'custom' && (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
                  {Array.from({ length: doors }).map((_, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 12 }}>
                      <span>Door {i + 1}</span>
                      <Segmented value={cab.hinges?.[i] || 'L'}
                                 options={[{ v: 'L', l: 'L' }, { v: 'R', l: 'R' }]}
                                 onChange={v => {
                                   const next = [...(cab.hinges || [])];
                                   next[i] = v;
                                   onChange({ hinges: next });
                                 }} />
                    </div>
                  ))}
                </div>
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
}

function DrawersBlock({ cab, onChange }) {
  const drawers = parseInt(cab.drawers) || 0;
  return (
    <div className="wiz-block">
      <div className="wiz-block-head">
        <div>
          <div className="wiz-block-title">Drawers</div>
          <div className="wiz-block-sub">How many, and is Precision repairing them?</div>
        </div>
        <NumberStepper value={cab.drawers || 0} onChange={(v) => onChange({ drawers: v })} />
      </div>
      <label className="wiz-checkbox">
        <input type="checkbox" checked={cab.drawersRepair === true}
               onChange={e => onChange({ drawersRepair: e.target.checked })} />
        <span>Drawers need repair (charged)</span>
      </label>
      {drawers >= 2 && (
        <div style={{ marginTop: 8 }}>
          <div className="wiz-block-sub" style={{ marginBottom: 4 }}>Drawer layout</div>
          <div className="chips">
            {[
              { v: '',          l: 'Equal' },
              { v: 'deep-bottom', l: 'Deep bottom' },
              ...(drawers === 4 ? [{ v: '2up-2down', l: '2 up + 2 down' }] : []),
              { v: 'custom',    l: 'Custom…' },
            ].map(o => (
              <button key={o.v}
                      className={'chip' + ((cab.drawerLayout || '') === o.v ? ' on' : '')}
                      onClick={() => onChange({ drawerLayout: o.v })}>
                <span className="dot"></span>{o.l}
              </button>
            ))}
          </div>
          {cab.drawerLayout === 'custom' && (
            <input className="input mono" style={{ marginTop: 6 }}
                   placeholder="Heights inches, comma-separated (e.g. 6, 6, 8, 14)"
                   value={cab.drawerHeights || ''}
                   onChange={e => onChange({ drawerHeights: e.target.value })} />
          )}
        </div>
      )}
    </div>
  );
}

function ShelvesBlock({ cab, onChange }) {
  return (
    <div className="wiz-block">
      <div className="wiz-block-head">
        <div>
          <div className="wiz-block-title">Shelves</div>
          <div className="wiz-block-sub">How many, and is Precision repairing them?</div>
        </div>
        <NumberStepper value={cab.shelves || 0} onChange={(v) => onChange({ shelves: v })} />
      </div>
      <label className="wiz-checkbox">
        <input type="checkbox" checked={cab.shelvesRepair === true}
               onChange={e => onChange({ shelvesRepair: e.target.checked })} />
        <span>Shelves need repair (charged)</span>
      </label>
    </div>
  );
}

// Build the combined preset list once (legacy CABINET_PRESETS from
// app.jsx + Vanity presets defined here). Each row carries its type
// tab so the size step can show the relevant subset based on the
// active tab.
const PRESET_ALL = (() => {
  const base = (window.CABINET_PRESETS || []).map(p => ({ ...p }));
  const vanityRows = VANITY_PRESETS.map(p => ({
    code: p.code, type: 'Vanity', w: p.w, h: p.h, d: p.d, desc: p.desc,
    doors: p.doors, drawers: p.drawers, drawerLayout: p.drawerLayout,
  }));
  return [...base, ...vanityRows];
})();
const PRESET_TABS = ['Base', 'Wall', 'Drawer Base', 'Sink Base', 'Tall', 'Lazy Susan', 'Vanity'];

function SubSize({ cab, onChange }) {
  const [mode, setMode] = uS(cab.presetCode ? 'preset' : (cab.w ? 'custom' : 'preset'));
  // Default the type tab from the cabinet's type/preset, falling
  // back to Base on first entry.
  const defaultTab = (() => {
    if (cab.cabType === 'Vanity' || cab.typeCode === 'V' || cab.presetCode?.startsWith('V')) return 'Vanity';
    if (cab.presetCode?.startsWith('W')) return 'Wall';
    if (cab.presetCode?.startsWith('DB')) return 'Drawer Base';
    if (cab.presetCode?.startsWith('SB')) return 'Sink Base';
    if (cab.presetCode?.startsWith('T')) return 'Tall';
    if (cab.presetCode?.startsWith('LS')) return 'Lazy Susan';
    return 'Base';
  })();
  const [tab, setTab] = uS(defaultTab);
  const filtered = PRESET_ALL.filter(p => p.type === tab);

  const pickPreset = (p) => {
    const isVanity = p.type === 'Vanity';
    onChange({
      presetCode: p.code, w: p.w, h: p.h, d: p.d,
      wu: 'in', hu: 'in', du: 'in',
      ...(p.doors != null ? { doors: p.doors } : {}),
      ...(p.drawers != null ? { drawers: p.drawers } : {}),
      ...(p.drawerLayout != null ? { drawerLayout: p.drawerLayout } : {}),
      ...(isVanity ? { cabType: 'Vanity', typeCode: 'V' } : {}),
    });
  };

  return (
    <>
      <Field label="Size">
        <Segmented value={mode}
                   options={[{ v: 'preset', l: 'Quick pick' }, { v: 'custom', l: 'Custom size' }]}
                   onChange={(v) => setMode(v)} />
      </Field>
      {mode === 'preset' ? (
        <Field label="Quick picks">
          {/* Type tabs — horizontal scroll on small screens */}
          <div className="wiz-typetabs">
            {PRESET_TABS.map(t => (
              <button key={t}
                      className={'wiz-typetab' + (tab === t ? ' on' : '')}
                      onClick={() => setTab(t)}>{t}</button>
            ))}
          </div>
          <div className="wiz-presetgrid">
            {filtered.map(p => (
              <button key={p.code}
                      className={'size-preset-item' + (cab.presetCode === p.code ? ' on' : '')}
                      onClick={() => pickPreset(p)}>
                <span className="size-preset-item-code">{p.code}</span>
                <span className="size-preset-item-dims">{p.desc}</span>
              </button>
            ))}
            {filtered.length === 0 && (
              <div style={{ gridColumn: '1 / -1', textAlign: 'center', color: 'var(--ink-faint)', fontSize: 13, padding: '12px' }}>
                No quick picks for this type.
              </div>
            )}
          </div>
        </Field>
      ) : (
        <div className="v-fields">
          <DimField label="Width" value={cab.w} unit={cab.wu} onValue={v => onChange({ w: v })} onUnit={u => onChange({ wu: u })} />
          <DimField label="Height" value={cab.h} unit={cab.hu} onValue={v => onChange({ h: v })} onUnit={u => onChange({ hu: u })} />
          <DimField label="Depth" value={cab.d} unit={cab.du} onValue={v => onChange({ d: v })} onUnit={u => onChange({ du: u })} />
        </div>
      )}
      {/* Visual preview once dimensions are chosen */}
      {(cab.w && cab.h) && (
        <div className="wiz-cabpreview-wrap">
          <CabinetPreview cab={cab} />
        </div>
      )}
    </>
  );
}

const SUB_TITLES = [
  'Pick a size',
  'Photos',
  'Doors / Drawers / Shelves',
  'Finished sides',
  'Box material + thickness',
  'Cabinet type',
  'Under-counter install?',
  'Anything to note?',
];

function CabinetSubWizard({ cab, idx, total, onChange, onBackToPrev, onAddAnother, onDoneAdding }) {
  const [sub, setSub] = uS(0);
  const isLast = sub === SUB_TITLES.length - 1;

  // Per-sub-step validation. Each sub-step that needs required fields
  // returns false when those aren't satisfied so Next stays disabled.
  const subValid = (() => {
    if (sub === 0) return !!(cab.w && cab.h && cab.d);
    if (sub === 4) return !!cab.boxMaterial;             // material required
    return true;
  })();

  const next = () => {
    if (!subValid) return;
    setSub(s => Math.min(SUB_TITLES.length - 1, s + 1));
  };
  const back = () => sub === 0 ? onBackToPrev() : setSub(s => Math.max(0, s - 1));
  const update = (patch) => onChange({ ...cab, ...patch });

  return (
    <div className="wiz-subshell">
      <div className="wiz-subhead">
        <strong>Cabinet {idx + 1}{total > 1 ? ' of ' + total : ''}</strong>
        <span className="wiz-substep">{SUB_TITLES[sub]}</span>
      </div>
      <div className="wiz-subbody">
        {sub === 0 && <SubSize cab={cab} onChange={update} />}
        {sub === 1 && (
          <Field label="Photos" hint="Optional but encouraged. Use Pin to call out specific issues, Draw to circle areas.">
            <PhotosBlock cab={cab} onChange={update} />
          </Field>
        )}
        {sub === 2 && (
          <>
            <DoorsBlock cab={cab} onChange={update} />
            <DrawersBlock cab={cab} onChange={update} />
            <ShelvesBlock cab={cab} onChange={update} />
          </>
        )}
        {sub === 3 && (
          <>
            <Field label="Finished sides?">
              <Segmented value={cab.finishedSide || 'No'}
                         options={['No', 'Yes']}
                         onChange={v => update({ finishedSide: v })} />
            </Field>
            {cab.finishedSide === 'Yes' && (
              <Field label="Which side?">
                <Segmented value={cab.finishedWhich || ''}
                           options={['Left', 'Right', 'Both']}
                           onChange={v => update({ finishedWhich: v })} />
              </Field>
            )}
          </>
        )}
        {sub === 4 && (
          <>
            <Field label="Box material">
              <select className="select" value={cab.boxMaterial || ''}
                      onChange={e => update({ boxMaterial: e.target.value })}>
                <option value="">Select…</option>
                {BOX_MATERIALS.map(m => <option key={m}>{m}</option>)}
              </select>
            </Field>
            <Field label="Thickness" hint="Default 1/2&quot;.">
              <Segmented value={cab.boxThickness || '1/2"'}
                         options={['1/2"', '5/8"', '3/4"']}
                         onChange={v => update({ boxThickness: v })} />
            </Field>
          </>
        )}
        {sub === 5 && (
          <Field
            label="Cabinet placement"
            hint={cab.cabType === 'Vanity'
              ? 'Vanity selected from the quick-pick — placement step skipped.'
              : 'How is this cabinet installed? Affects the island/peninsula surcharge.'}
          >
            {cab.cabType === 'Vanity' ? (
              <div style={{ padding: '12px 14px', background: '#fdf8e9', borderRadius: 8, fontSize: 13 }}>
                Vanity (auto-selected from quick-pick).
              </div>
            ) : (
              <Segmented value={cab.cabType || 'Standard wall'}
                         options={['Standard wall', 'Island', 'Peninsula']}
                         onChange={v => update({ cabType: v, typeCode: cab.typeCode || 'B' })} />
            )}
          </Field>
        )}
        {sub === 6 && (
          <Field label="Installs under existing countertop?"
                 hint="Yes shortens the box and adds adjustable feet so it slides under an existing counter.">
            <Segmented value={cab.installUnderExisting || 'No'}
                       options={['No', 'Yes']}
                       onChange={v => update({ installUnderExisting: v })} />
          </Field>
        )}
        {sub === 7 && (
          <Field label="Notes (optional)">
            <textarea className="textarea" value={cab.notes || ''}
                      placeholder="Damage, hardware preferences, finish details…"
                      onChange={e => update({ notes: e.target.value })} />
          </Field>
        )}
      </div>
      <div className="wiz-subfooter">
        <button className="btn ghost" onClick={back}>← Back</button>
        {isLast ? (
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn"
                    style={{ background: '#fff', color: '#0a2240', border: '2px solid #0a2240', fontWeight: 600 }}
                    onClick={onAddAnother}>+ Add Cabinet</button>
            <button className="btn primary lg" onClick={onDoneAdding}>✓ Done Adding</button>
          </div>
        ) : (
          <button className="btn primary lg" onClick={next} disabled={!subValid}>
            {subValid ? 'Next →' : (sub === 0 ? 'Pick a size first' : 'Pick box material')}
          </button>
        )}
      </div>
    </div>
  );
}

// ---------- Step 7 — Toe kick ----------

const TOEKICK_LF_QUICKPICKS = [2, 3, 4, 6, 8, 10, 12, 14, 16, 20];

function FractionStepper({ value, onChange, step = 0.25, min = 0, max = 12, suffix = '"' }) {
  const v = parseFloat(value) || 0;
  const set = (next) => {
    const clamped = Math.max(min, Math.min(max, next));
    onChange(String(Math.round(clamped * 100) / 100));
  };
  return (
    <div className="wiz-fracstep">
      <button type="button" className="wiz-fracstep-btn" onClick={() => set(v - step)}>−</button>
      <input
        type="number"
        className="input mono"
        value={value || ''}
        step={step}
        min={min}
        max={max}
        onChange={(e) => onChange(e.target.value)}
        style={{ width: 80, textAlign: 'center' }}
      />
      <button type="button" className="wiz-fracstep-btn" onClick={() => set(v + step)}>+</button>
      <span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{suffix}</span>
    </div>
  );
}

function ToeKickStep({ data, setData, ...nav }) {
  const tk = data.toeKick || {};
  const update = (patch) => setData({ ...data, toeKick: { ...tk, ...patch } });
  return (
    <StepShell {...nav} title="Toe kick" subtitle="The recessed strip under the base cabinets. Defaults to 4&quot; tall × 3&quot; setback.">
      <Field label="Toe Kick Height" hint="¼&quot; increments. Default 4&quot;.">
        <FractionStepper value={tk.height || ''} onChange={v => update({ height: v })} />
      </Field>
      <Field label="Setback" hint="¼&quot; increments. Default 3&quot;.">
        <FractionStepper value={tk.setback || ''} onChange={v => update({ setback: v })} />
      </Field>
      <Field label="Thickness" hint="Default 1/4&quot;.">
        <Segmented value={tk.thickness || '1/4"'}
                   options={['1/4"', '1/2"', '5/8"', '3/4"']}
                   onChange={v => update({ thickness: v })} />
      </Field>
      <Field label="Total length (linear ft)">
        <div className="chips" style={{ marginBottom: 8 }}>
          {TOEKICK_LF_QUICKPICKS.map(n => (
            <button key={n}
                    className={'chip' + ((parseFloat(tk.linearFt) || 0) === n ? ' on' : '')}
                    onClick={() => update({ linearFt: String(n) })}>
              <span className="dot"></span>{n} ft
            </button>
          ))}
        </div>
        <DimField label="Custom length" value={tk.linearFt} onValue={v => update({ linearFt: v })} />
      </Field>
    </StepShell>
  );
}

// ---------- Step 8 — Scribe ----------

function ScribeStep({ data, setData, ...nav }) {
  const sc = data.scribe || {};
  const update = (patch) => setData({ ...data, scribe: { ...sc, ...patch } });
  return (
    <StepShell {...nav} title="Scribe" subtitle="Trim that hides gaps where cabinets meet walls or appliances.">
      <Field label="Need scribe?">
        <Segmented value={sc.needed || 'No'} options={['No', 'Yes']} onChange={v => update({ needed: v })} />
      </Field>
      {sc.needed === 'Yes' && (
        <>
          <DimField label="Total scribe (linear ft)" value={sc.linearFeet} onValue={v => update({ linearFeet: v })} />
          <Field label="Match cabinet material?" hint="Yes uses the order's primary material. No uses our cheapest stock — cheaper but doesn't match exactly.">
            <Segmented value={sc.matchMaterial || 'Yes'} options={['Yes', 'No']} onChange={v => update({ matchMaterial: v })} />
          </Field>
        </>
      )}
    </StepShell>
  );
}

// ---------- Step 9 — Special instructions ----------

function SpecialStep({ data, setData, ...nav }) {
  return (
    <StepShell {...nav} title="Anything else?" subtitle="Color match notes, hardware preferences, special handling.">
      <textarea className="textarea" value={data.specialInstructions || ''}
                placeholder="Special instructions…"
                style={{ minHeight: 120 }}
                onChange={e => setData({ ...data, specialInstructions: e.target.value })} />
    </StepShell>
  );
}

// ---------- Step 10 — Review ----------

function ReviewStep({ data, estimate, runningTotal, ...actions }) {
  const cabs = data.cabinets || [];
  return (
    <div className="wiz-shell">
      <div className="wiz-progress"><div className="wiz-progress-bar" style={{ width: '100%' }} /></div>
      <div className="wiz-body">
        <div className="wiz-stepnum">Review</div>
        <h1 className="wiz-title">Looks good?</h1>
        <p className="wiz-sub">Tap Edit on any section to adjust. Estimate updates live.</p>

        <ReviewSection title="Customer" onEdit={() => actions.onJump(data.installNeeded === 'Yes' ? 3 : 2)}>
          <div>{data.clientName || <em style={{ color: 'var(--ink-faint)' }}>(none)</em>}</div>
          <div style={{ fontSize: 12, color: 'var(--ink-soft)' }}>{data.address || ''}</div>
        </ReviewSection>

        <ReviewSection title="Timing" onEdit={() => actions.onJump(5)}>
          <div>{data.completionRequested || 'no date'}</div>
          {data.rush && <span className="status-badge" style={{ '--badge-color': '#b91c1c', fontSize: 10 }}>RUSH</span>}
        </ReviewSection>

        <ReviewSection title={`Cabinets (${cabs.length})`} onEdit={() => actions.onJump(6)}>
          {cabs.length === 0 ? (
            <div style={{ color: 'var(--ink-faint)', fontSize: 13 }}>No cabinets added.</div>
          ) : (
            cabs.map((c, i) => (
              <div key={c.id || i} className="wiz-review-cabrow">
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600 }}>
                    Cab {String(i + 1).padStart(2, '0')} · {c.presetCode || `${c.w || '?'}×${c.h || '?'}×${c.d || '?'}`}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--ink-faint)' }}>
                    {c.cabType || 'Standard wall'}{c.boxMaterial ? ' · ' + c.boxMaterial : ''}
                    {c.doors > 0 ? ` · ${c.doors} door${c.doors === 1 ? '' : 's'}${c.doorsRepair ? ' (repair)' : ''}` : ''}
                    {c.drawers > 0 ? ` · ${c.drawers} drawer${c.drawers === 1 ? '' : 's'}${c.drawersRepair ? ' (repair)' : ''}` : ''}
                  </div>
                </div>
                <button className="btn ghost" style={{ padding: 4 }} onClick={() => actions.onEditCab(i)} title="Edit">
                  <Icon.Pencil/>
                </button>
                <button className="btn ghost danger-hover" style={{ padding: 4 }} onClick={() => actions.onRemoveCab(i)} title="Remove">
                  <Icon.Trash/>
                </button>
              </div>
            ))
          )}
        </ReviewSection>

        <ReviewSection title="Toe kick" onEdit={() => actions.onJump(7)}>
          <div style={{ fontSize: 13 }}>
            {data.toeKick?.height ? `${data.toeKick.height}" tall` : '4" tall'}
            {data.toeKick?.setback ? ` · ${data.toeKick.setback}" setback` : ' · 3" setback'}
            {data.toeKick?.linearFt ? ` · ${data.toeKick.linearFt} lf` : ''}
          </div>
        </ReviewSection>

        <ReviewSection title="Scribe" onEdit={() => actions.onJump(8)}>
          <div style={{ fontSize: 13 }}>
            {data.scribe?.needed === 'Yes'
              ? `${data.scribe.linearFeet || 0} lf · ${data.scribe.matchMaterial === 'No' ? 'cheapest material' : 'matched'}`
              : 'Not needed'}
          </div>
        </ReviewSection>

        <ReviewSection title="Special instructions" onEdit={() => actions.onJump(9)}>
          <div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{data.specialInstructions || <em>(none)</em>}</div>
        </ReviewSection>

        <div className="wiz-review-block" style={{ background: '#fdf8e9', borderColor: '#0a2240' }}>
          <div className="wiz-review-h">Estimate</div>
          <div className="mono" style={{ fontSize: 28, fontWeight: 700, color: '#0a2240' }}>{fmtMoney(estimate.total)}</div>
          {estimate.rushApplied && <div className="hint" style={{ fontSize: 11, color: '#b91c1c' }}>RUSH upcharge applied.</div>}
          <div className="hint" style={{ fontSize: 11, marginTop: 8, fontStyle: 'italic' }}>
            This is an <strong>estimate</strong>. Actual cost will be calculated after items are built and verified against the order.
          </div>
        </div>
      </div>
      <div className="wiz-footer wiz-footer-multi">
        <button className="btn ghost" onClick={actions.onBack}>← Back</button>
        <div className="wiz-runningtotal">
          <span className="wiz-runningtotal-l">Total</span>
          <span className="wiz-runningtotal-v mono">{fmtMoney(runningTotal)}</span>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button className="btn"
                  style={{ background: '#fff', color: '#0a2240', border: '2px solid #0a2240', fontWeight: 600 }}
                  onClick={actions.onSaveDraft} disabled={actions.savingDraft}>
            {actions.savingDraft ? 'Saving…' : '💾 Save Draft'}
          </button>
          <button className="btn"
                  style={{ background: '#b08720', color: '#fff', border: 0, fontWeight: 600 }}
                  onClick={actions.onInsurance} disabled={!cabs.length}>
            📄 Insurance Estimate
          </button>
          <button className="btn primary lg" onClick={actions.onSubmit} disabled={actions.submitting || !cabs.length}>
            {actions.submitting ? 'Submitting…' : 'Submit Order →'}
          </button>
        </div>
      </div>
    </div>
  );
}

function ReviewSection({ title, onEdit, children }) {
  return (
    <div className="wiz-review-block">
      <div className="wiz-review-row">
        <div className="wiz-review-h">{title}</div>
        <button className="btn ghost" style={{ padding: '2px 8px', fontSize: 11 }} onClick={onEdit}>
          <Icon.Pencil/> Edit
        </button>
      </div>
      <div>{children}</div>
    </div>
  );
}

// ---------- Confirm modal ----------

function RushConfirmModal({ days, threshold, upcharge, onAccept, onDecline }) {
  return (
    <div className="modal-backdrop" onClick={onDecline}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 420 }}>
        <h3 style={{ margin: '0 0 4px' }}>That's a rush date</h3>
        <p>The completion date you picked is <strong>{days} day{days === 1 ? '' : 's'}</strong> from today, inside our <strong>{threshold}-day</strong> rush window.</p>
        <p>Add the <strong>${upcharge} rush upcharge</strong> to this order?</p>
        <div style={{ display: 'flex', gap: 8, marginTop: 16, justifyContent: 'flex-end' }}>
          <button className="btn ghost" onClick={onDecline}>No, keep without rush</button>
          <button className="btn primary" onClick={onAccept}>Yes, add ${upcharge}</button>
        </div>
      </div>
    </div>
  );
}

// ---------- Wizard root ----------

function IntakeWizard({ vendor, data, setData, pricing, onSubmit, onSaveDraft, onInsurancePreview, submitting, savingDraft, sc }) {
  const [step, setStep] = uS(1);
  const [rushPrompt, setRushPrompt] = uS(null);
  const [editingCabIdx, setEditingCabIdx] = uS(0);
  const cabs = data.cabinets || [];

  const TOTAL_STEPS = 10;
  const skipsCustomer = data.installNeeded !== 'Yes';

  // Live estimate for the running total + review screen.
  const estimate = uM(() => {
    try { return computeEstimate(data, pricing || {}); } catch { return { total: 0, lineItems: [] }; }
  }, [data, pricing]);

  // Create the first cabinet ONCE when entering step 6. Doing this in
  // a useEffect (not during render) prevents the previous bug where
  // multiple ghost cabinets were added.
  uE(() => {
    if (step === 6 && cabs.length === 0) {
      const next = makeCabinet(1);
      setData({ ...data, cabinets: [next] });
      setEditingCabIdx(0);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [step]);

  const canAdvance = () => {
    if (step === 1) return !!(data.vendorPhone && data.vendorPhone.trim());
    if (step === 2) return !!data.installNeeded;
    if (step === 3) return !!(data.clientName && data.address);
    if (step === 5) return !!data.completionRequested;
    return true;
  };

  const goNext = () => {
    if (step === 1 && !canAdvance()) return;
    if (step === 2) {
      setStep(skipsCustomer ? 4 : 3);
      return;
    }
    if (step === 3 && !canAdvance()) return;
    setStep(s => Math.min(TOTAL_STEPS, s + 1));
  };
  const goBack = () => {
    if (step === 4 && skipsCustomer) { setStep(2); return; }
    setStep(s => Math.max(1, s - 1));
  };

  const updateCab = (idx, next) => {
    const list = [...cabs];
    list[idx] = next;
    setData({ ...data, cabinets: list });
  };
  const addCab = () => {
    const newCab = makeCabinet(cabs.length + 1);
    const next = [...cabs, newCab];
    setData({ ...data, cabinets: next });
    setEditingCabIdx(next.length - 1);
  };
  const removeCab = (idx) => {
    const next = cabs.filter((_, i) => i !== idx);
    setData({ ...data, cabinets: next });
    if (editingCabIdx >= next.length) setEditingCabIdx(Math.max(0, next.length - 1));
  };
  const goEditCab = (i) => {
    setEditingCabIdx(i);
    setStep(6);
  };

  const stepProps = {
    step, total: TOTAL_STEPS,
    runningTotal: estimate.total,
  };

  // ---- Render the right step ----
  if (step === 1) return (
    <VendorContactStep data={data} setData={setData} vendor={vendor}
      {...stepProps} onBack={null} onNext={goNext} nextDisabled={!canAdvance()} />
  );
  if (step === 2) return (
    <ServiceTypeStep data={data} setData={setData}
      {...stepProps} onBack={goBack} onNext={goNext} nextDisabled={!canAdvance()} />
  );
  if (step === 3) return (
    <CustomerStep data={data} setData={setData}
      {...stepProps} onBack={goBack} onNext={goNext} nextDisabled={!canAdvance()} />
  );
  if (step === 4) return (
    <PropertyStep data={data} setData={setData}
      {...stepProps} onBack={goBack} onNext={goNext} />
  );
  if (step === 5) return (
    <>
      <TimingStep data={data} setData={setData} pricing={pricing} sc={sc}
        {...stepProps} onBack={goBack} onNext={goNext}
        onConfirmRush={(info) => setRushPrompt(info)} />
      {rushPrompt && (
        <RushConfirmModal {...rushPrompt}
          onAccept={() => {
            // Apply rush and stay on step 5 so the user can see the
            // running total update before clicking Next themselves.
            setData({ ...data, rush: true });
            setRushPrompt(null);
          }}
          onDecline={() => {
            // Decline → keep going. Don't apply rush.
            setRushPrompt(null);
            setStep(6);
          }} />
      )}
    </>
  );
  if (step === 6) {
    if (cabs.length === 0) {
      // useEffect will create the first cabinet on the next tick.
      return <div className="wiz-shell"><div className="wiz-body"><p>Loading…</p></div></div>;
    }
    const cab = cabs[editingCabIdx] || cabs[0];
    return (
      <div className="wiz-shell">
        <div className="wiz-progress"><div className="wiz-progress-bar" style={{ width: `${(6 / TOTAL_STEPS) * 100}%` }} /></div>
        <div className="wiz-body">
          <div className="wiz-stepnum">Step 6 of {TOTAL_STEPS}</div>
          <h1 className="wiz-title">Cabinets</h1>
          <p className="wiz-sub">Walk through each cabinet. When you're done with one, "+ Add Cabinet" or "Done Adding".</p>
          {cabs.length > 1 && (
            <div className="wiz-cabnav">
              {cabs.map((_, i) => (
                <button key={i}
                        className={'wiz-cabnav-chip' + (i === editingCabIdx ? ' on' : '')}
                        onClick={() => setEditingCabIdx(i)}>
                  Cab {String(i + 1).padStart(2, '0')}
                </button>
              ))}
            </div>
          )}
          <CabinetSubWizard
            key={cab.id}
            cab={cab}
            idx={editingCabIdx}
            total={cabs.length}
            onChange={(next) => updateCab(editingCabIdx, next)}
            onBackToPrev={() => {
              if (editingCabIdx === 0) goBack();
              else setEditingCabIdx(i => Math.max(0, i - 1));
            }}
            onAddAnother={addCab}
            onDoneAdding={() => setStep(7)}
          />
        </div>
        <div className="wiz-footer">
          <button className="btn ghost" onClick={goBack}>← Back to timing</button>
          <div className="wiz-runningtotal">
            <span className="wiz-runningtotal-l">Running total</span>
            <span className="wiz-runningtotal-v mono">{fmtMoney(estimate.total)}</span>
          </div>
          <button className="btn ghost" onClick={() => setStep(7)}>Skip to toe kick →</button>
        </div>
      </div>
    );
  }
  if (step === 7) return (
    <ToeKickStep data={data} setData={setData}
      {...stepProps} onBack={() => setStep(6)} onNext={goNext} />
  );
  if (step === 8) return (
    <ScribeStep data={data} setData={setData}
      {...stepProps} onBack={goBack} onNext={goNext} />
  );
  if (step === 9) return (
    <SpecialStep data={data} setData={setData}
      {...stepProps} onBack={goBack} onNext={goNext} />
  );
  // Step 10
  return (
    <ReviewStep data={data} estimate={estimate} runningTotal={estimate.total}
      onBack={() => setStep(9)}
      onJump={(s) => setStep(s)}
      onEditCab={goEditCab}
      onRemoveCab={removeCab}
      onSubmit={onSubmit} onSaveDraft={onSaveDraft} onInsurance={onInsurancePreview}
      submitting={submitting} savingDraft={savingDraft} />
  );
}

Object.assign(window, { IntakeWizard });
