/* Viamar PWA — AI scan, estimate, confirmation + flow controller */

// ── AI assessment step ─────────────────────────────────────
const SCAN_ITEMS = {
  box: [
    { t: 'Sofa — 3-seat', c: 98, v: '2.1 m³' },
    { t: 'Dining table + 4 chairs', c: 95, v: '1.8 m³' },
    { t: 'Wardrobe — large', c: 92, v: '1.5 m³' },
    { t: 'Queen mattress + frame', c: 96, v: '1.2 m³' },
    { t: 'Boxes — 14 medium', c: 89, v: '4.6 m³' },
  ],
  car: [
    { t: 'BMW M4 Competition · 2023', c: 99, v: '4.78 m' },
    { t: 'Exterior condition — clean', c: 97, v: '0 flags' },
    { t: 'Ground clearance — standard', c: 94, v: 'OK' },
  ],
  bike: [
    { t: 'Harley-Davidson Road Glide', c: 98, v: '2.4 m' },
    { t: 'Crate recommended', c: 91, v: 'enclosed' },
  ],
  ship: [
    { t: 'Boat on trailer — ~6.5 m', c: 93, v: '18 m³' },
    { t: 'RORO recommended', c: 90, v: 'wheeled' },
  ],
};

function AIScan({ cargo, onResult, result }) {
  const [phase, setPhase] = React.useState(result ? 'done' : 'idle');
  const [msg, setMsg] = React.useState('');
  const items = SCAN_ITEMS[cargo] || SCAN_ITEMS.box;

  const run = () => {
    setPhase('scanning');
    const steps = ['Detecting objects…', 'Estimating dimensions…', 'Calculating volume…', 'Matching shipping method…'];
    steps.forEach((m, i) => setTimeout(() => setMsg(m), i * 600));
    setTimeout(() => {
      setPhase('done');
      if (window.ViamarAnalytics) ViamarAnalytics.track('ai_scan_completed', { cargo_type: cargo, detected_items: items.length });
      onResult(true);
    }, 2500);
  };

  const totalVol = cargo === 'box' ? '11.2 m³' : cargo === 'ship' ? '18 m³' : cargo === 'car' ? '~12 m³' : '~3 m³';
  const fill = cargo === 'box' ? '≈ 4 pallets · 56% of a 20ft' : cargo === 'car' ? 'Fits shared 40ft (¼ space)' : cargo === 'bike' ? 'Crated · LCL or RORO' : 'RORO deck space';

  return (
    <div>
      {/* viewport */}
      <div style={{ position: 'relative', borderRadius: 18, overflow: 'hidden', marginBottom: 16 }}>
        <Placeholder label={phase === 'done' ? '' : 'CAMERA · POINT AT YOUR ITEMS'} h={200} r={18} dark>
          {/* corner brackets */}
          {['tl','tr','bl','br'].map(c => (
            <div key={c} style={{ position: 'absolute', width: 26, height: 26,
              borderTop: c[0]==='t'?'2.5px solid '+T.red:'none', borderBottom: c[0]==='b'?'2.5px solid '+T.red:'none',
              borderLeft: c[1]==='l'?'2.5px solid '+T.red:'none', borderRight: c[1]==='r'?'2.5px solid '+T.red:'none',
              top: c[0]==='t'?16:undefined, bottom: c[0]==='b'?16:undefined, left: c[1]==='l'?16:undefined, right: c[1]==='r'?16:undefined,
              borderRadius: 4 }} />
          ))}
          {phase === 'scanning' && <>
            <div className="scanline" style={{ position: 'absolute', left: 16, right: 16, height: 2, background: T.red, boxShadow: '0 0 12px 2px rgba(221,28,36,0.7)' }} />
            <div style={{ position: 'absolute', bottom: 14, left: 0, right: 0, textAlign: 'center', fontFamily: FM, fontSize: 11, color: '#fff', letterSpacing: 0.5 }}>{msg}</div>
          </>}
          {phase === 'done' && (
            <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, background: 'rgba(10,27,46,0.55)' }}>
              <div style={{ width: 52, height: 52, borderRadius: '50%', background: T.green, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={28} color="#fff" stroke={3} /></div>
              <span style={{ fontFamily: FM, fontSize: 11, color: '#fff', letterSpacing: 1, textTransform: 'uppercase' }}>{items.length} items detected</span>
            </div>
          )}
        </Placeholder>
      </div>

      {phase === 'idle' && (
        <div style={{ textAlign: 'center' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'rgba(221,28,36,0.08)', padding: '7px 13px', borderRadius: 999, marginBottom: 16 }}>
            <Icon name="spark" size={15} color={T.red} stroke={2} />
            <span style={{ fontFamily: FM, fontSize: 11, fontWeight: 700, color: T.red, letterSpacing: 0.5, textTransform: 'uppercase' }}>AI Volume Estimate</span>
          </div>
          <div style={{ fontFamily: FB, fontSize: 13.5, color: T.body, lineHeight: 1.5, marginBottom: 18, padding: '0 6px' }}>
            Snap a few photos of what you're shipping. Our AI identifies items and estimates volume in seconds — then our team verifies before your final price.
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <Btn full variant="primary" icon="camera" onClick={run}>Scan items</Btn>
            <Btn variant="ghost" icon="plus" onClick={run} style={{ flex: 1 }}>Upload</Btn>
          </div>
        </div>
      )}

      {phase === 'done' && (
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <Kicker color={T.navy3}>Detected items</Kicker>
            <span style={{ fontFamily: FM, fontSize: 10.5, color: T.green }}>● AI estimate · team-verified</span>
          </div>
          <div style={{ background: '#fff', borderRadius: 16, border: '1px solid ' + T.line2, overflow: 'hidden', marginBottom: 14 }}>
            {items.map((it, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '13px 15px', borderTop: i ? '1px solid ' + T.line2 : 'none' }}>
                <div style={{ width: 8, height: 8, borderRadius: '50%', background: T.green }} />
                <span style={{ flex: 1, fontFamily: FB, fontWeight: 600, fontSize: 14, color: T.ink }}>{it.t}</span>
                <span style={{ fontFamily: FM, fontSize: 11, color: T.muted }}>{it.v}</span>
                <span style={{ fontFamily: FM, fontSize: 10.5, color: T.green, background: 'rgba(46,139,111,0.1)', padding: '3px 7px', borderRadius: 7, minWidth: 38, textAlign: 'center' }}>{it.c}%</span>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <div style={{ flex: 1, background: T.navy, borderRadius: 14, padding: '13px 15px' }}>
              <div style={{ fontFamily: FM, fontSize: 9, letterSpacing: 1, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase' }}>Est. volume</div>
              <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 22, color: '#fff', fontStretch: '110%' }}>{totalVol}</div>
            </div>
            <div style={{ flex: 1.4, background: '#fff', borderRadius: 14, padding: '13px 15px', border: '1px solid ' + T.line2 }}>
              <div style={{ fontFamily: FM, fontSize: 9, letterSpacing: 1, color: T.faint, textTransform: 'uppercase' }}>Recommended</div>
              <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 13, color: T.ink, lineHeight: 1.3, marginTop: 3 }}>{fill}</div>
            </div>
          </div>
          <div onClick={run} style={{ textAlign: 'center', marginTop: 14, fontFamily: FM, fontSize: 11, color: T.red, letterSpacing: 0.5, textTransform: 'uppercase', cursor: 'pointer' }}>↺ Re-scan</div>
        </div>
      )}
    </div>
  );
}

// ── Estimate step ──────────────────────────────────────────
function methodsFor(cargo, service) {
  if (service === 'domestic') return [
    { id: 'shared', name: 'Shared container', sub: 'Per-pallet · best value', price: 580, days: '5–7 days' },
    { id: 'truck',  name: 'Dedicated truck',  sub: 'Door-to-door, fastest', price: 1240, days: '3–4 days' },
  ];
  if (cargo === 'car' || cargo === 'bike') return [
    { id: 'shared', name: 'Shared container', sub: 'Loaded in-house · best value', price: 1850, days: '14–18 days' },
    { id: 'fcl',    name: 'Full container (40ft)', sub: 'Exclusive, up to 4 cars', price: 4200, days: '14–18 days' },
    { id: 'roro',   name: 'RORO', sub: 'Roll-on / roll-off', price: 1400, days: '18–24 days' },
  ];
  return [
    { id: 'lcl',    name: 'LCL consolidated', sub: 'In-house groupage · best value', price: 1320, days: '15–19 days' },
    { id: 'fcl20',  name: 'Full 20ft container', sub: 'Exclusive use', price: 3100, days: '15–19 days' },
  ];
}

function StepEstimate({ cargo, service, dest, method, onMethod }) {
  const methods = methodsFor(cargo, service);
  const cur = methods.find(m => m.id === method) || methods[0];
  const breakdown = [
    ['Ocean / line freight', Math.round(cur.price * 0.62)],
    ['Door pickup & handling', Math.round(cur.price * 0.18)],
    ['Documentation & customs', Math.round(cur.price * 0.12)],
    ['Cargo insurance (est.)', Math.round(cur.price * 0.08)],
  ];
  return (
    <div>
      {/* price headline */}
      <div style={{ background: T.navy, borderRadius: 20, padding: 20, marginBottom: 16, position: 'relative', overflow: 'hidden' }}>
        <Kicker color={T.red} style={{ marginBottom: 6 }}>Estimated total</Kicker>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontFamily: FD, fontWeight: 900, fontSize: 38, color: '#fff', fontStretch: '120%', letterSpacing: '-0.01em' }}>${cur.price.toLocaleString()}</span>
          <span style={{ fontFamily: FM, fontSize: 12, color: 'rgba(255,255,255,0.5)', marginLeft: 2 }}>CAD</span>
        </div>
        <div style={{ fontFamily: FB, fontSize: 12.5, color: 'rgba(255,255,255,0.6)', marginTop: 4 }}>
          {dest ? `${'Toronto'} → ${dest.city} · ` : ''}<span style={{ color: '#fff', fontWeight: 600 }}>{cur.days}</span>
        </div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 14, background: 'rgba(255,255,255,0.08)', padding: '6px 11px', borderRadius: 999 }}>
          <Icon name="shield" size={14} color={T.gold} stroke={2} />
          <span style={{ fontFamily: FM, fontSize: 10, color: 'rgba(255,255,255,0.75)', letterSpacing: 0.3 }}>AI estimate · locked once team confirms</span>
        </div>
      </div>

      {/* method options */}
      <Kicker color={T.navy3} style={{ marginBottom: 10 }}>Shipping method</Kicker>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginBottom: 18 }}>
        {methods.map(m => {
          const sel = cur.id === m.id;
          return (
            <div key={m.id} onClick={() => onMethod(m.id)} style={{
              background: '#fff', borderRadius: 15, padding: '13px 15px', display: 'flex', alignItems: 'center', gap: 12,
              cursor: 'pointer', border: `2px solid ${sel ? T.red : T.line2}`,
            }}>
              <div style={{ width: 20, height: 20, borderRadius: '50%', border: `2px solid ${sel ? T.red : T.line}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {sel && <div style={{ width: 10, height: 10, borderRadius: '50%', background: T.red }} />}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14.5, color: T.ink }}>{m.name}</div>
                <div style={{ fontFamily: FB, fontSize: 11.5, color: T.muted }}>{m.sub}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 16, color: T.ink, fontStretch: '110%' }}>${m.price.toLocaleString()}</div>
                <div style={{ fontFamily: FM, fontSize: 9.5, color: T.muted }}>{m.days}</div>
              </div>
            </div>
          );
        })}
      </div>

      {/* breakdown */}
      <Kicker color={T.navy3} style={{ marginBottom: 10 }}>Price breakdown</Kicker>
      <div style={{ background: '#fff', borderRadius: 16, border: '1px solid ' + T.line2, overflow: 'hidden' }}>
        {breakdown.map(([l, v], i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 15px', borderTop: i ? '1px solid ' + T.line2 : 'none' }}>
            <span style={{ fontFamily: FB, fontSize: 13.5, color: T.body }}>{l}</span>
            <span style={{ fontFamily: FM, fontSize: 13, color: T.ink, fontWeight: 700 }}>${v.toLocaleString()}</span>
          </div>
        ))}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '13px 15px', background: T.paper, borderTop: '1px solid ' + T.line }}>
          <span style={{ fontFamily: FD, fontWeight: 800, fontSize: 14, color: T.ink, fontStretch: '110%' }}>Estimated total</span>
          <span style={{ fontFamily: FD, fontWeight: 800, fontSize: 17, color: T.red, fontStretch: '110%' }}>${cur.price.toLocaleString()}</span>
        </div>
      </div>
      <div style={{ fontFamily: FB, fontSize: 11.5, color: T.muted, lineHeight: 1.5, marginTop: 12, padding: '0 2px' }}>
        Includes 2 weeks free storage at our Courtice warehouse. Final price confirmed by your dedicated Viamar agent — usually within 1 business hour.
      </div>
    </div>
  );
}

// ── Customer contact step ──────────────────────────────────
function quoteContactValid(contact) {
  const name = (contact.name || '').trim();
  const email = (contact.email || '').trim();
  const phoneDigits = (contact.phone || '').replace(/\D/g, '');
  const emailOk = !email || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  return name.length > 1 && ((email && emailOk) || phoneDigits.length >= 7);
}

function ContactField({ label, value, onChange, placeholder, required }) {
  const filled = value && value.trim().length > 0;
  return (
    <div style={{ width: '100%' }}>
      <div style={{ fontFamily: FM, fontSize: 9.5, letterSpacing: 0.8, color: T.faint, textTransform: 'uppercase', marginBottom: 6 }}>
        {label}{required && <span style={{ color: T.red }}> *</span>}
      </div>
      <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder} style={{
        width: '100%', border: '1.5px solid ' + (required && !filled ? 'rgba(221,28,36,0.35)' : T.line),
        borderRadius: 12, padding: '13px 14px', fontFamily: FB, fontSize: 15, color: T.ink, background: '#fff', outline: 'none',
      }} />
    </div>
  );
}

function StepContact({ contact, setContact, dest }) {
  const set = (patch) => setContact(c => ({ ...c, ...patch }));
  const hasChannel = ((contact.email || '').trim().length > 0) || ((contact.phone || '').replace(/\D/g, '').length >= 7);
  return (
    <div>
      <div style={{ background: T.navy, borderRadius: 18, padding: 18, marginBottom: 18 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <div style={{ width: 42, height: 42, borderRadius: 13, background: T.red, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="user" size={21} color="#fff" stroke={2.2} />
          </div>
          <div>
            <Kicker color={T.red} style={{ marginBottom: 6 }}>Agent review</Kicker>
            <div style={{ fontFamily: FB, fontSize: 13.5, color: 'rgba(255,255,255,0.72)', lineHeight: 1.55 }}>
              A Viamar agent will confirm the price{dest ? ` to ${dest.city}` : ''}, check documents, and send next steps. Most quotes are confirmed within 1 business hour.
            </div>
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
        <ContactField label="Full name" value={contact.name} onChange={v => set({ name: v })} placeholder="Your full name" required />
        <ContactField label="Email" value={contact.email} onChange={v => set({ email: v })} placeholder="name@email.com" required={!hasChannel} />
        <ContactField label="Phone" value={contact.phone} onChange={v => set({ phone: v })} placeholder="+1 416 555 0100" required={!hasChannel} />
      </div>

      <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
        {[['clock', 'Fast callback', 'Usually within 1 business hour'], ['shield', 'Team verified', 'No price locks until Viamar reviews'], ['doc', 'Docs next', 'Only request what your shipment needs']].map(([ic, t, s], i) => (
          <div key={i} style={{ flex: 1, background: '#fff', border: '1px solid ' + T.line2, borderRadius: 13, padding: '12px 10px' }}>
            <Icon name={ic} size={17} color={i === 1 ? T.green : T.navy3} stroke={1.9} />
            <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 11.5, color: T.ink, marginTop: 7 }}>{t}</div>
            <div style={{ fontFamily: FB, fontSize: 10.5, color: T.muted, lineHeight: 1.35, marginTop: 2 }}>{s}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Confirmation screen ────────────────────────────────────
function QuoteConfirmed({ refId, dest, onTrack, onHome }) {
  return (
    <div style={{ height: '100%', background: T.navy, display: 'flex', flexDirection: 'column', paddingTop: 54 }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 28px', textAlign: 'center' }}>
        <div className="pop" style={{ width: 84, height: 84, borderRadius: '50%', background: 'rgba(46,139,111,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24 }}>
          <div style={{ width: 60, height: 60, borderRadius: '50%', background: T.green, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="check" size={34} color="#fff" stroke={3} />
          </div>
        </div>
        <Kicker color={T.red} style={{ marginBottom: 10 }}>Quote submitted</Kicker>
        <Display size={27} color="#fff" style={{ marginBottom: 14 }}>Your request is with<br/>our team.</Display>
        <div style={{ fontFamily: FB, fontSize: 14, color: 'rgba(255,255,255,0.65)', lineHeight: 1.55, marginBottom: 22 }}>
          A dedicated Viamar agent is reviewing your AI estimate{dest ? ` to ${dest.city}` : ''}. You'll get a confirmed, locked-in price — usually within <span style={{ color: '#fff', fontWeight: 700 }}>1 business hour</span>.
        </div>
        <div style={{ background: 'rgba(255,255,255,0.06)', borderRadius: 16, padding: '16px 22px', marginBottom: 30, width: '100%' }}>
          <div style={{ fontFamily: FM, fontSize: 9.5, letterSpacing: 1, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase' }}>Reference</div>
          <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 26, color: '#fff', fontStretch: '120%', letterSpacing: '0.02em' }}>{refId}</div>
        </div>
      </div>
      <div style={{ padding: '0 24px 40px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <Btn full variant="primary" icon="track" onClick={onTrack}>Track this request</Btn>
        <Btn full variant="ghost" onClick={onHome} style={{ color: '#fff', boxShadow: 'inset 0 0 0 1.5px rgba(255,255,255,0.2)' }}>Back to home</Btn>
      </div>
    </div>
  );
}

// ── Flow controller ────────────────────────────────────────
function QuoteFlow({ onClose, onSubmitted }) {
  const [step, setStep] = React.useState(0);
  const [cargo, setCargo] = React.useState(null);
  const [service, setService] = React.useState('intl');
  const [dest, setDest] = React.useState(null);
  const [scanned, setScanned] = React.useState(false);
  const [method, setMethod] = React.useState(null);
  const [contact, setContact] = React.useState({ name: '', email: '', phone: '' });
  const [quickConsent, setQuickConsent] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const ref = React.useMemo(() => 'VMR-' + (48000 + Math.floor(Math.random() * 900)), []);

  const back = () => {
    if (step === 0) {
      if (window.ViamarAnalytics) ViamarAnalytics.track('quote_abandoned', { quote_ref: ref, cargo_type: cargo, step: step + 1 });
      onClose();
    } else setStep(step - 1);
  };
  const next = () => setStep(step + 1);

  if (done) return <QuoteConfirmed refId={ref} dest={dest} onTrack={() => onSubmitted(ref, true)} onHome={() => onSubmitted(ref, false)} />;

  const titles = ['What are you shipping?', 'Where to?', 'Show us your shipment', 'Your estimate', 'Where should we send the quote?'];
  const kickers = ['Step 1 · Cargo', 'Step 2 · Route', 'Step 3 · AI assessment', 'Step 4 · Pricing', 'Step 5 · Contact'];

  let footer = null, body = null;
  if (step === 0) {
    body = <StepCargo value={cargo} onPick={c => { setCargo(c); }} />;
    footer = <Btn full variant="primary" icon="arrowR" disabled={!cargo} onClick={next}>Continue</Btn>;
  } else if (step === 1) {
    body = <StepRoute from="Toronto, ON (or door pickup)" dest={dest} onPickDest={setDest} service={service} onService={s => { setService(s); setDest(null); }} />;
    footer = <Btn full variant="primary" icon="arrowR" disabled={!dest} onClick={next}>Continue</Btn>;
  } else if (step === 2) {
    body = <AIScan cargo={cargo} result={scanned} onResult={() => setScanned(true)} />;
    footer = <Btn full variant="primary" icon="arrowR" disabled={!scanned} onClick={next}>See estimate</Btn>;
  } else if (step === 3) {
    body = <StepEstimate cargo={cargo} service={service} dest={dest} method={method} onMethod={setMethod} />;
    footer = <Btn full variant="primary" icon="arrowR" onClick={next}>Continue to contact</Btn>;
  } else {
    body = (
      <>
        <StepContact contact={contact} setContact={setContact} dest={dest} />
        <div onClick={() => setQuickConsent(v => !v)} style={{ marginTop: 14, display: 'flex', gap: 11, alignItems: 'flex-start', padding: '13px 14px', borderRadius: 14, background: quickConsent ? 'rgba(46,139,111,0.08)' : '#fff', border: '1px solid ' + (quickConsent ? 'rgba(46,139,111,0.22)' : T.line2), cursor: 'pointer' }}>
          <div style={{ width: 22, height: 22, borderRadius: 7, background: quickConsent ? T.green : T.paper, border: '1.5px solid ' + (quickConsent ? T.green : T.line2), display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            {quickConsent && <Icon name="check" size={13} color="#fff" stroke={3} />}
          </div>
          <div>
            <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 12.5, color: T.ink }}>I accept Viamar's standard trading terms</div>
            <div style={{ fontFamily: FM, fontSize: 10.8, color: T.muted, lineHeight: 1.45, marginTop: 3 }}>Viamar will review the route, documents, and final price before booking. Quoted rates exclude marine cargo insurance unless requested. <a href={window.VIAMAR_TERMS_URL || 'terms.html'} target="_blank" rel="noreferrer" onClick={e => e.stopPropagation()} style={{ color: T.red, fontWeight: 800 }}>Review terms</a> · <a href={window.VIAMAR_PRIVACY_URL || 'privacy.html'} target="_blank" rel="noreferrer" onClick={e => e.stopPropagation()} style={{ color: T.red, fontWeight: 800 }}>Data handling</a>.</div>
          </div>
        </div>
      </>
    );
    footer = <Btn full variant="primary" icon="checkC" onClick={() => {
      const priced = (methodsFor(cargo, service).find(m => m.id === method) || methodsFor(cargo, service)[0]);
      if (window.ViamarAPI) ViamarAPI.submitQuote({
        quote_ref: ref,
        customer: contact,
        cargo_type: cargo,
        service: service,
        origin: 'Toronto, ON',
        destination: dest,
        method: priced.id,
        estimate_price: priced.price,
        consent: {
          terms_accepted: true,
          payment_authorization_acknowledged: false,
          document_privacy_acknowledged: true,
          signature_name: contact.name,
          terms_version: 'viamar-standard-terms-2026-06-01',
          terms_label: 'Viamar standard trading terms, C.I.F.F.A. terms, no included marine cargo insurance',
          terms_url: window.VIAMAR_TERMS_URL || 'terms.html',
          accepted_at: new Date().toISOString(),
          source: 'quote-flow',
        },
        source: 'quote-flow',
      }).catch(function () {});
      if (window.ViamarAnalytics) ViamarAnalytics.track('quote_submitted', {
        quote_ref: ref,
        cargo_type: cargo,
        service: service,
        destination_port: dest && dest.port,
        destination_country: dest && dest.country,
        method: priced.id,
        amount: priced.price,
        has_email: !!contact.email,
        has_phone: !!contact.phone,
      });
      setDone(true);
    }} disabled={!quoteContactValid(contact) || !quickConsent}>Submit for review</Btn>;
  }

  return (
    <StepShell step={step} total={5} title={titles[step]} kicker={kickers[step]} onBack={back} footer={footer}>
      {body}
    </StepShell>
  );
}

Object.assign(window, { AIScan, StepEstimate, QuoteConfirmed, QuoteFlow });
