/* Viamar Desktop — Quote wizard (modal overlay) */

function StepRail({ step, cargo, dest, method, comp, assessMode }) {
  const cargoLabel = (CARGO_TYPES.find(c => c.id === cargo) || {}).label;
  const isVehicle = cargo === 'car' || cargo === 'bike';
  const compSub = isVehicle ? 'Vehicle ownership' : (dest && dest.region === 'Europe') ? 'ICS2 consignee' : 'Shipment details';
  const steps = [
    { t: 'Cargo type', sub: cargoLabel },
    { t: 'Route', sub: dest ? `Toronto → ${dest.city}` : null },
    { t: 'Assessment', sub: assessMode === 'human' ? 'Human · team' : (step > 2 ? 'AI · scanned' : 'AI estimate') },
    { t: 'Documents', sub: step > 3 ? 'Submitted' : compSub },
    { t: 'Estimate', sub: null },
    { t: 'Review & pay', sub: step > 5 ? 'Signed' : null },
  ];
  return (
    <div style={{ width: 268, flexShrink: 0, background: T.navy, padding: '30px 26px', display: 'flex', flexDirection: 'column' }}>
      <div style={{ fontFamily: FD, fontWeight: 900, fontSize: 22, color: '#fff', fontStretch: '125%', letterSpacing: '0.02em', lineHeight: 1 }}>
        VIA<span style={{ color: T.red }}>MAR</span>
      </div>
      <Kicker color={T.red} style={{ marginTop: 6, marginBottom: 30 }}>Instant quote</Kicker>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, flex: 1 }}>
        {steps.map((st, i) => {
          const done = i < step, current = i === step;
          return (
            <div key={i} style={{ display: 'flex', gap: 13, alignItems: 'flex-start' }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <div style={{ width: 26, height: 26, borderRadius: '50%', flexShrink: 0,
                  background: done ? T.green : current ? T.red : 'rgba(255,255,255,0.08)',
                  border: current ? 'none' : done ? 'none' : '1.5px solid rgba(255,255,255,0.18)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  boxShadow: current ? '0 0 0 4px rgba(221,28,36,0.2)' : 'none' }}>
                  {done ? <Icon name="check" size={14} color="#fff" stroke={3} />
                    : <span style={{ fontFamily: FM, fontSize: 11, fontWeight: 700, color: current ? '#fff' : 'rgba(255,255,255,0.5)' }}>{i + 1}</span>}
                </div>
                {i < steps.length - 1 && <div style={{ width: 2, height: 30, background: done ? T.green : 'rgba(255,255,255,0.12)' }} />}
              </div>
              <div style={{ paddingTop: 3 }}>
                <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14, color: current || done ? '#fff' : 'rgba(255,255,255,0.5)' }}>{st.t}</div>
                {st.sub && <div style={{ fontFamily: FM, fontSize: 10.5, color: 'rgba(255,255,255,0.5)', marginTop: 2 }}>{st.sub}</div>}
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 14, padding: '14px 16px', display: 'flex', gap: 11, alignItems: 'flex-start' }}>
        <Icon name="shield" size={18} color={T.gold} stroke={2} />
        <div style={{ fontFamily: FB, fontSize: 11.5, color: 'rgba(255,255,255,0.7)', lineHeight: 1.45 }}>Final price confirmed by your agent — usually within 1 business hour.</div>
      </div>
    </div>
  );
}

function QuoteConfirmedDesktop({ refId, dest, onTrack, onHome }) {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 64px', textAlign: 'center' }}>
      <div className="pop" style={{ width: 88, height: 88, borderRadius: '50%', background: 'rgba(46,139,111,0.14)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 26 }}>
        <div style={{ width: 62, height: 62, borderRadius: '50%', background: T.green, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="check" size={36} color="#fff" stroke={3} />
        </div>
      </div>
      <Kicker color={T.red} style={{ marginBottom: 10 }}>Booking signed</Kicker>
      <Display size={30} color={T.ink} style={{ marginBottom: 14 }}>Your booking is with our team.</Display>
      <div style={{ fontFamily: FB, fontSize: 15, color: T.body, lineHeight: 1.55, marginBottom: 26, maxWidth: 470 }}>
        A dedicated Viamar agent is confirming your price{dest ? ` to ${dest.city}` : ''} — usually within <span style={{ color: T.ink, fontWeight: 700 }}>1 business hour</span>. Your prepayment is authorised and charged only once the final price is locked.
      </div>
      <div style={{ background: T.paper, borderRadius: 16, padding: '16px 30px', marginBottom: 30, border: '1px solid ' + T.line2 }}>
        <div style={{ fontFamily: FM, fontSize: 9.5, letterSpacing: 1, color: T.faint, textTransform: 'uppercase' }}>Reference</div>
        <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 28, color: T.ink, fontStretch: '120%', letterSpacing: '0.02em' }}>{refId}</div>
      </div>
      <div style={{ display: 'flex', gap: 12 }}>
        <Btn variant="primary" icon="track" onClick={onTrack}>Track this request</Btn>
        <Btn variant="ghost" onClick={onHome}>Back to dashboard</Btn>
      </div>
    </div>
  );
}

function QuoteWizardDesktop({ 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 [comp, setComp] = React.useState({ paidInFull: false, docs: {}, prohibitedAck: false, declared: '',
    consignee: { name: 'Klajdi Hoxha', addr: 'Via Roma 14, 16121 Genoa', phone: '+39 010 555 0102', email: 'klajdi.h@email.com' } });
  const [pay, setPay] = React.useState({ terms: false, sign: '', email: '', phone: '', method: 'card' });
  const [assessMode, setAssessMode] = React.useState('ai');
  const [notes, setNotes] = React.useState('');
  const [done, setDone] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [paymentState, setPaymentState] = React.useState({ status: 'idle' });
  const refId = React.useMemo(() => 'VMR-' + (48000 + Math.floor(Math.random() * 900)), []);

  const titles = ['What are you shipping?', 'Where to?', 'How should we assess it?', 'Documents & compliance', 'Your estimate', 'Review, sign & pay'];
  const canNext = [!!cargo, !!dest, assessMode === 'human' ? true : scanned, complianceValid(cargo, service, dest, comp), true, reviewValid(pay)][step];
  const paymentBlocking = step === 5 && pay.method === 'card' && paymentState && paymentState.status === 'loading';
  const next = () => setStep(s => s + 1);
  const abandon = () => {
    if (window.ViamarAnalytics) ViamarAnalytics.track('quote_abandoned', {
      quote_ref: refId,
      cargo_type: cargo,
      service: service,
      destination_port: dest && dest.port,
      step: step + 1,
      source: 'desktop',
    });
    onClose();
  };
  const back = () => { if (step === 0) abandon(); else setStep(s => s - 1); };

  let body;
  if (step === 0) body = <StepCargo value={cargo} onPick={setCargo} />;
  else if (step === 1) body = <StepRoute from="Toronto, ON (or door pickup)" dest={dest} onPickDest={setDest} service={service} onService={s => { setService(s); setDest(null); }} />;
  else if (step === 2) body = <AssessmentStep cargo={cargo} mode={assessMode} setMode={setAssessMode} scanned={scanned} onResult={() => setScanned(true)} notes={notes} setNotes={setNotes} />;
  else if (step === 3) body = <ComplianceStep cargo={cargo} service={service} dest={dest} comp={comp} setComp={setComp} quoteRef={refId} />;
  else if (step === 4) body = <>{assessMode === 'human' && <HumanEstimateBanner />}<StepEstimate cargo={cargo} service={service} dest={dest} method={method} onMethod={setMethod} /><EstimateExtras cargo={cargo} service={service} /></>;
  else body = <ReviewSignPay cargo={cargo} service={service} dest={dest} method={method} pay={pay} setPay={setPay} quoteRef={refId} paymentState={paymentState} setPaymentState={setPaymentState} />;

  return (
    <div className="fadein" style={{ position: 'absolute', inset: 0, zIndex: 90, background: 'rgba(6,16,28,0.55)', backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40 }}>
      <div className="overlay" style={{ width: 940, height: 640, background: T.paper, borderRadius: 24, overflow: 'hidden', display: 'flex', boxShadow: '0 30px 90px rgba(0,0,0,0.45)' }}>
        {done ? (
          <QuoteConfirmedDesktop refId={refId} dest={dest} onTrack={() => onSubmitted(refId, true)} onHome={() => onSubmitted(refId, false)} />
        ) : (
          <>
            <StepRail step={step} cargo={cargo} dest={dest} method={method} comp={comp} assessMode={assessMode} />
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
              {/* header */}
              <div style={{ padding: '26px 34px 18px', borderBottom: '1px solid ' + T.line, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                  <div style={{ fontFamily: FM, fontSize: 11, color: T.muted, letterSpacing: 0.5, marginBottom: 4 }}>Step {step + 1} of 6</div>
                  <Display size={24} color={T.ink}>{titles[step]}</Display>
                </div>
                <div onClick={abandon} style={{ width: 38, height: 38, borderRadius: 11, background: '#fff', border: '1px solid ' + T.line2, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                  <span style={{ display: 'flex', transform: 'rotate(45deg)' }}><Icon name="plus" size={20} color={T.muted} stroke={2.2} /></span>
                </div>
              </div>
              {/* body */}
              <div key={step} className="vscroll fadein" style={{ flex: 1, overflowY: 'auto', padding: '24px 34px' }}>{body}</div>
              {/* footer */}
              <div style={{ padding: '16px 34px', borderTop: '1px solid ' + T.line, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Btn variant="ghost" icon="chevL" onClick={back}>{step === 0 ? 'Cancel' : 'Back'}</Btn>
                {step < 5
                  ? <Btn variant="primary" icon="arrowR" disabled={!canNext} onClick={next}>{step === 2 ? 'Add documents' : step === 3 ? (assessMode === 'human' ? 'See indicative price' : 'See estimate') : step === 4 ? 'Review & pay' : 'Continue'}</Btn>
                  : <Btn variant="primary" icon="checkC" disabled={!canNext || submitting || paymentBlocking} onClick={async () => {
                    setSubmitting(true);
                    const priced = quotePrice(cargo, service, method);
                    const consent = {
                      terms_accepted: !!pay.terms,
                      payment_authorization_acknowledged: true,
                      document_privacy_acknowledged: true,
                      signature_name: pay.sign,
                      contact_email: pay.email,
                      contact_phone: pay.phone,
                      payment_method: pay.method,
                      ci_ffa_terms_acknowledged: true,
                      marine_insurance_excluded_acknowledged: true,
                      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: 'desktop-booking',
                    };
                    let payment = paymentState && paymentState.payment ? paymentState.payment : null;
                    let paymentResult = null;
                    if (pay.method === 'card' && paymentState && paymentState.status === 'ready' && paymentState.stripe && paymentState.elements) {
                      paymentResult = await paymentState.stripe.confirmPayment({
                        elements: paymentState.elements,
                        redirect: 'if_required',
                        confirmParams: {
                          return_url: window.location.href,
                          receipt_email: pay.email || undefined,
                        },
                      });
                      if (paymentResult && paymentResult.error) {
                        setPaymentState({ ...paymentState, status: 'error', message: paymentResult.error.message || 'Card authorization failed.' });
                        setSubmitting(false);
                        return;
                      }
                      payment = Object.assign({}, payment || {}, {
                        confirmation_status: paymentResult && paymentResult.paymentIntent && paymentResult.paymentIntent.status,
                        provider: 'stripe',
                      });
                    } else if (window.ViamarAPI && (!payment || pay.method !== 'card')) {
                      try {
                        payment = await ViamarAPI.createPaymentIntent({
                          quote_ref: refId,
                          amount: priced.price,
                          currency: 'cad',
                          method: pay.method,
                          customer: { name: pay.sign, email: pay.email, phone: pay.phone },
                          consent: consent,
                          source: 'desktop-booking',
                        });
                      } catch (err) {
                        payment = { success: false, error: (err && err.message) || 'payment setup failed' };
                      }
                    }
                    if (window.ViamarAPI) {
                      ViamarAPI.submitQuote({
                        quote_ref: refId,
                        cargo_type: cargo,
                        service: service,
                        origin: 'Toronto, ON',
                        destination: dest,
                        method: priced.id,
                        estimate_price: priced.price,
                        customer: {
                          name: pay.sign,
                          email: pay.email,
                          phone: pay.phone,
                        },
                        payment: payment,
                        consent: consent,
                        source: 'desktop-booking',
                      }).catch(function () {});
                    }
                    if (window.ViamarAnalytics) {
                      ViamarAnalytics.track('quote_submitted', {
                        quote_ref: refId,
                        cargo_type: cargo,
                        service: service,
                        destination_port: dest && dest.port,
                        destination_country: dest && dest.country,
                        method: priced.id,
                        amount: priced.price,
                        has_email: !!pay.email,
                        has_phone: !!pay.phone,
                        payment_provider: payment && payment.provider,
                        payment_status: payment && payment.status,
                        source: 'desktop',
                      });
                      ViamarAnalytics.track((payment && (payment.confirmation_status === 'requires_capture' || payment.status === 'requires_capture')) ? 'payment_authorized' : 'payment_request_created', {
                        quote_ref: refId,
                        amount: priced.price,
                        currency: 'CAD',
                        method: pay.method,
                        provider: payment && payment.provider,
                        status: (payment && (payment.confirmation_status || payment.status)) || null,
                        source: 'desktop',
                      });
                    }
                    setDone(true);
                    setSubmitting(false);
                  }}>{submitting ? 'Submitting...' : 'Sign & submit booking'}</Btn>}
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function HumanAssessment({ cargo, notes, setNotes }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'flex', gap: 13, background: 'rgba(27,58,87,0.06)', border: '1px solid rgba(27,58,87,0.18)', borderRadius: 14, padding: '16px 18px' }}>
        <div style={{ width: 42, height: 42, borderRadius: 12, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, boxShadow: '0 1px 3px rgba(10,27,46,0.08)' }}><Icon name="user" size={22} color={T.navy} stroke={2} /></div>
        <div>
          <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14.5, color: T.ink }}>A Viamar specialist will assess your shipment</div>
          <div style={{ fontFamily: FB, fontSize: 12.5, color: T.body, lineHeight: 1.5, marginTop: 3 }}>No scan needed. We measure your items at door pickup or our Courtice warehouse, confirm the exact volume, and lock your price — ideal for oversized, fragile or mixed loads.</div>
        </div>
      </div>
      <div>
        <div style={{ fontFamily: FM, fontSize: 9.5, letterSpacing: 0.8, color: T.faint, textTransform: 'uppercase', marginBottom: 8 }}>What we'll need from you (optional now)</div>
        <textarea value={notes} onChange={e => setNotes(e.target.value)} rows={4}
          placeholder={cargo === 'car' || cargo === 'bike' ? 'Year, make, model, condition, any modifications…' : 'Rough item list or dimensions, anything fragile or oversized…'}
          style={{ width: '100%', border: '1.5px solid ' + T.line, borderRadius: 12, padding: '12px 14px', fontFamily: FB, fontSize: 14, color: T.ink, outline: 'none', resize: 'none', background: '#fff' }} />
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        {[['camera', 'We measure', 'At pickup or warehouse'], ['scan', 'We confirm volume', 'Exact m³, no estimate'], ['shield', 'Price locked', 'Within 1 business hour']].map(([ic, t, s], i) => (
          <div key={i} style={{ flex: 1, background: '#fff', border: '1px solid ' + T.line2, borderRadius: 13, padding: '13px 14px' }}>
            <Icon name={ic} size={18} color={T.navy3} stroke={1.9} />
            <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 12.5, color: T.ink, marginTop: 8 }}>{t}</div>
            <div style={{ fontFamily: FB, fontSize: 11, color: T.muted, marginTop: 2, lineHeight: 1.35 }}>{s}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AssessmentStep({ cargo, mode, setMode, scanned, onResult, notes, setNotes }) {
  return (
    <div>
      <div style={{ display: 'flex', gap: 6, background: '#fff', border: '1px solid ' + T.line2, borderRadius: 13, padding: 5, marginBottom: 18 }}>
        {[['ai', 'spark', 'AI estimate', 'Scan in seconds'], ['human', 'user', 'Human assessment', 'Our team measures']].map(([id, ic, lbl, sub]) => {
          const on = mode === id;
          return (
            <div key={id} onClick={() => setMode(id)} style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px', borderRadius: 10, cursor: 'pointer', background: on ? T.navy : 'transparent', transition: 'background .2s' }}>
              <Icon name={ic} size={19} color={on ? '#fff' : T.muted} stroke={2} />
              <div>
                <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 13.5, color: on ? '#fff' : T.ink }}>{lbl}</div>
                <div style={{ fontFamily: FM, fontSize: 9.5, color: on ? 'rgba(255,255,255,0.6)' : T.faint }}>{sub}</div>
              </div>
            </div>
          );
        })}
      </div>
      {mode === 'ai'
        ? <AIScan cargo={cargo} result={scanned} onResult={onResult} />
        : <HumanAssessment cargo={cargo} notes={notes} setNotes={setNotes} />}
    </div>
  );
}

function HumanEstimateBanner() {
  return (
    <div style={{ display: 'flex', gap: 11, background: 'rgba(27,58,87,0.06)', border: '1px solid rgba(27,58,87,0.18)', borderRadius: 14, padding: '13px 16px', marginBottom: 16 }}>
      <Icon name="user" size={18} color={T.navy3} stroke={2} />
      <div style={{ fontFamily: FB, fontSize: 12.5, color: T.body, lineHeight: 1.5 }}>
        <span style={{ color: T.ink, fontWeight: 700 }}>Indicative pricing.</span> You chose a human assessment — the figures below are a guide. Your dedicated agent confirms the exact price after measuring, usually within 1 business hour.
      </div>
    </div>
  );
}

Object.assign(window, { QuoteWizardDesktop });
