/* Viamar — shared lead-first capture for desktop, mobile and /new-quote. */

function LeadFirstField({ label, type = 'text', value, onChange, placeholder, autoComplete }) {
  const id = 'lead-' + label.toLowerCase().replace(/[^a-z0-9]+/g, '-');
  return (
    <label htmlFor={id} style={{ display: 'flex', flexDirection: 'column', gap: 6, flex: 1, minWidth: 0 }}>
      <span style={{ fontFamily: FM, fontSize: 9.5, letterSpacing: 0.8, textTransform: 'uppercase', color: T.faint }}>{label}</span>
      <input
        id={id}
        type={type}
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        autoComplete={autoComplete}
        style={{ width: '100%', border: '1.5px solid ' + T.line, borderRadius: 12, padding: '12px 13px', background: '#fff', color: T.ink, fontFamily: FB, fontSize: 14, outline: 'none' }}
      />
    </label>
  );
}

function CapturedWelcome({ result, compact }) {
  const next = result && result.next_action;
  const ref = result && result.case && result.case.id;
  const recovery = result && result.recovery;
  const recoverySent = !!(recovery && recovery.delivery === 'webhook_sent');
  return (
    <div role="status" style={{ background: '#fff', border: '1px solid rgba(46,139,111,0.28)', borderRadius: 18, padding: compact ? 18 : 24, boxShadow: '0 8px 24px rgba(10,27,46,0.07)' }}>
      <div style={{ display: 'flex', gap: 13, alignItems: 'flex-start' }}>
        <div style={{ width: 42, height: 42, borderRadius: 13, background: T.green, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="check" size={22} color="#fff" stroke={3} />
        </div>
        <div style={{ flex: 1 }}>
          <Kicker color={T.green} style={{ marginBottom: 5 }}>Request saved</Kicker>
          <Display size={compact ? 20 : 25} color={T.ink}>We saved your request.</Display>
          <div style={{ fontFamily: FB, fontSize: 13, color: T.body, lineHeight: 1.5, marginTop: 7 }}>
            {recoverySent
              ? 'Viamar is reviewing it now. We sent a secure link so you can return on another device.'
              : 'Viamar is reviewing it now. Use your reference and contact details to return or speak with our team.'}
          </div>
        </div>
      </div>
      {next && (
        <div style={{ marginTop: 16, background: T.paper, borderRadius: 14, padding: '13px 14px', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 36, height: 36, borderRadius: 11, background: 'rgba(221,28,36,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="arrowR" size={18} color={T.red} stroke={2.3} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: FM, fontSize: 9, color: T.red, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase' }}>Your next step</div>
            <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 13.5, color: T.ink, marginTop: 2 }}>{next.title}</div>
            <div style={{ fontFamily: FB, fontSize: 11.5, color: T.muted, marginTop: 2 }}>{next.detail}</div>
          </div>
        </div>
      )}
      {ref && <div style={{ fontFamily: FM, fontSize: 10, color: T.faint, marginTop: 12 }}>REFERENCE · {ref}</div>}
    </div>
  );
}

function LeadCapture({ compact = false, onCaptured, source = 'viamar-app' }) {
  const model = window.ViamarLeadFirstModel;
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', category: '', origin: '', destination: '', consent: false });
  const [error, setError] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [result, setResult] = React.useState(null);

  React.useEffect(() => {
    if (window.ViamarAnalytics) ViamarAnalytics.track('lead_capture_viewed', { source });
  }, [source]);

  const set = patch => {
    setForm(current => ({ ...current, ...patch }));
    setError('');
  };
  const validation = model ? model.validate(form) : { valid: false, error: 'Lead capture is loading.' };
  const categories = [
    ['vehicle', 'car', 'Vehicle', 'Car, SUV, motorcycle or classic'],
    ['household', 'box', 'Household belongings', 'Boxes, furniture or a full move'],
    ['equipment', 'package', 'Commercial cargo or equipment', 'Machinery, pallets or oversized cargo'],
    ['unsure', 'help', "I'm not sure", 'Viamar will help choose the service'],
  ];

  const submit = async e => {
    e.preventDefault();
    const checked = model.validate(form);
    if (!checked.valid) { setError(checked.error); return; }
    if (!window.ViamarAPI || !ViamarAPI.captureLead) { setError('The request service is unavailable. Please call 1-800-277-7570.'); return; }
    setSubmitting(true);
    if (window.ViamarAnalytics) ViamarAnalytics.track('lead_capture_submitted', { source, category: form.category });
    try {
      const params = new URLSearchParams(window.location.search || '');
      const captured = await ViamarAPI.captureLead({
        customer: { name: form.name, email: form.email, phone: form.phone },
        category: form.category,
        origin: form.origin,
        destination: form.destination,
        source,
        attribution: {
          utm_source: params.get('utm_source'),
          utm_medium: params.get('utm_medium'),
          utm_campaign: params.get('utm_campaign'),
          utm_keyword: params.get('utm_term'),
          landing_page: window.location.href,
        },
        consent: { contact_accepted: true, accepted_at: new Date().toISOString() },
      });
      setResult(captured);
      if (onCaptured) onCaptured(captured);
      try {
        window.dispatchEvent(new CustomEvent('viamar:case-captured', { detail: captured }));
      } catch (eventError) {}
    } catch (err) {
      const message = (err && err.message) || 'We could not save your request.';
      setError(message + ' Please call 1-800-277-7570.');
      if (window.ViamarAnalytics) ViamarAnalytics.track('lead_capture_failed', { source, category: form.category });
    } finally {
      setSubmitting(false);
    }
  };

  if (result) return <CapturedWelcome result={result} compact={compact} />;

  return (
    <form onSubmit={submit} style={{ background: '#fff', border: '1px solid ' + T.line2, borderRadius: 20, padding: compact ? 18 : 26, boxShadow: '0 10px 30px rgba(10,27,46,0.08)' }}>
      <Kicker color={T.red} style={{ marginBottom: 7 }}>Start here</Kicker>
      <Display size={compact ? 21 : 27} color={T.ink}>What can we help you ship?</Display>
      <div style={{ fontFamily: FB, fontSize: 13, lineHeight: 1.5, color: T.body, marginTop: 7 }}>
        Save your request first. Then we'll guide you one simple step at a time.
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: compact ? '1fr' : '1fr 1fr', gap: 9, marginTop: 18 }}>
        {categories.map(([id, icon, title, sub]) => {
          const selected = form.category === id;
          return (
            <button key={id} type="button" aria-pressed={selected} onClick={() => set({ category: id })} style={{ display: 'flex', alignItems: 'center', gap: 11, textAlign: 'left', border: '1.5px solid ' + (selected ? T.red : T.line2), background: selected ? 'rgba(221,28,36,0.06)' : '#fff', borderRadius: 13, padding: '11px 12px', cursor: 'pointer' }}>
              <Icon name={icon} size={20} color={selected ? T.red : T.navy} stroke={2} />
              <span>
                <span style={{ display: 'block', fontFamily: FB, fontWeight: 700, fontSize: 13, color: T.ink }}>{title}</span>
                <span style={{ display: 'block', fontFamily: FB, fontSize: 10.5, color: T.muted, marginTop: 2 }}>{sub}</span>
              </span>
            </button>
          );
        })}
      </div>

      <div style={{ display: 'flex', flexDirection: compact ? 'column' : 'row', gap: 10, marginTop: 16 }}>
        <LeadFirstField label="First name" value={form.name} onChange={name => set({ name })} placeholder="Your first name" autoComplete="given-name" />
        <LeadFirstField label="Email" type="email" value={form.email} onChange={email => set({ email })} placeholder="you@example.com" autoComplete="email" />
        <LeadFirstField label="Mobile number" type="tel" value={form.phone} onChange={phone => set({ phone })} placeholder="416 555 0100" autoComplete="tel" />
      </div>

      <div style={{ display: 'flex', flexDirection: compact ? 'column' : 'row', gap: 10, marginTop: 10 }}>
        <LeadFirstField label="From (optional)" value={form.origin} onChange={origin => set({ origin })} placeholder="City or country" autoComplete="address-level2" />
        <LeadFirstField label="To (optional)" value={form.destination} onChange={destination => set({ destination })} placeholder="City or country" />
      </div>

      <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginTop: 14, cursor: 'pointer' }}>
        <input type="checkbox" checked={form.consent} onChange={e => set({ consent: e.target.checked })} style={{ width: 18, height: 18, marginTop: 1, accentColor: T.red }} />
        <span style={{ fontFamily: FB, fontSize: 11.5, lineHeight: 1.45, color: T.body }}>
          Viamar may contact me about this request by email or mobile. <a href={window.VIAMAR_PRIVACY_URL || '/privacy/'} target="_blank" rel="noreferrer" style={{ color: T.red, fontWeight: 700 }}>Privacy</a>
        </span>
      </label>

      {error && <div role="alert" style={{ marginTop: 12, borderRadius: 11, padding: '10px 12px', background: 'rgba(221,28,36,0.08)', color: T.red, fontFamily: FB, fontSize: 12 }}>{error}</div>}

      <button type="submit" disabled={!validation.valid || submitting} style={{ width: '100%', marginTop: 15, border: 0, borderRadius: 12, padding: '13px 16px', background: validation.valid && !submitting ? T.red : T.line, color: '#fff', fontFamily: FB, fontWeight: 800, fontSize: 14, cursor: validation.valid && !submitting ? 'pointer' : 'not-allowed' }}>
        {submitting ? 'Saving…' : 'Save my request'}
      </button>
      <div style={{ fontFamily: FM, fontSize: 9.5, color: T.faint, textAlign: 'center', marginTop: 9 }}>No password · no shipping expertise needed</div>
    </form>
  );
}

window.ViamarLeadFirst = { LeadCapture, CapturedWelcome };
