// ContactModal — site-wide "Talk to ___" lead-capture modal.
//
// Rendered once via <ContactModalRoot/> inside SiteNav (and ServiceNav for
// /services/* pages). Exposes a global controller so any CTA can trigger it:
//
//   window.__abgsContact.open({ source, topic, intent, prefill })
//
// On submit, saves to the same Firestore `leads` collection with
// source='talk-to-expert' so admin/leads.jsx sees one inbox.
const { useState: useStateCM, useEffect: useEffectCM, useRef: useRefCM } = React;

// Title / subtitle / submit copy keyed by intent. Defaults handle 'specialist'.
const CM_INTENT_COPY = {
  sales: {
    title: 'Talk to sales',
    subtitle: 'A solutions consultant will reach out within one business day.',
    submit: 'Request a call',
    msgLabel: 'What are you looking to ship or scale?',
  },
  logistics: {
    title: 'Talk to logistics',
    subtitle: 'Get connected to a dispatcher — never a call queue.',
    submit: 'Talk to logistics',
    msgLabel: 'Tell us about your lanes, volume, or freight type',
  },
  compliance: {
    title: 'Talk to compliance',
    subtitle: 'Licensed brokers and compliance specialists, 1-business-day response.',
    submit: 'Request compliance review',
    msgLabel: 'Tell us about your customs, classification, or filing needs',
  },
  integrations: {
    title: 'Talk to a solutions engineer',
    subtitle: 'API, ERP, EDI — we’ll scope your integration on the call.',
    submit: 'Book the call',
    msgLabel: 'Stack, ERP, carriers, current pain points',
  },
  specialist: {
    title: 'Talk to a specialist',
    subtitle: 'A real human will reach out within one business day.',
    submit: 'Send message',
    msgLabel: 'How can we help?',
  },
  support: {
    title: 'Talk to support',
    subtitle: 'We respond within one business day.',
    submit: 'Send message',
    msgLabel: 'How can we help?',
  },
};

function ContactModalRoot() {
  const [open, setOpen] = useStateCM(false);
  const [meta, setMeta] = useStateCM({ source: 'unknown', topic: null, intent: 'specialist' });
  const [form, setForm] = useStateCM({ name: '', email: '', company: '', phone: '', message: '' });
  const [submitting, setSubmitting] = useStateCM(false);
  const [error, setError] = useStateCM(null);
  const [sent, setSent] = useStateCM(false);
  const closeTimer = useRefCM(null);

  // Register the global controller once on mount.
  useEffectCM(() => {
    const ctl = {
      open: (opts) => {
        opts = opts || {};
        setMeta({
          source: opts.source || 'unknown',
          topic: opts.topic || null,
          intent: opts.intent || 'specialist',
        });
        setForm(f => ({
          name: (opts.prefill && opts.prefill.name) || f.name || '',
          email: (opts.prefill && opts.prefill.email) || f.email || '',
          company: (opts.prefill && opts.prefill.company) || f.company || '',
          phone: f.phone || '',
          message: '',
        }));
        setError(null);
        setSent(false);
        setSubmitting(false);
        setOpen(true);
      },
      close: () => setOpen(false),
    };
    window.__abgsContact = ctl;
    window.dispatchEvent(new Event('abgs:contact-ready'));
    return () => {
      if (window.__abgsContact === ctl) delete window.__abgsContact;
    };
  }, []);

  // Lock body scroll while open.
  useEffectCM(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  // Esc to close.
  useEffectCM(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  // Auto-close after success.
  useEffectCM(() => {
    if (!sent) return;
    closeTimer.current = setTimeout(() => setOpen(false), 4000);
    return () => clearTimeout(closeTimer.current);
  }, [sent]);

  if (!open) return null;

  const copy = CM_INTENT_COPY[meta.intent] || CM_INTENT_COPY.specialist;

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(form.email.trim());

  async function onSubmit(e) {
    e.preventDefault();
    if (submitting) return;
    setError(null);

    if (!form.name.trim()) { setError('Please enter your name.'); return; }
    if (!validEmail)       { setError('Please enter a valid email address.'); return; }
    if (!form.company.trim()) { setError('Please enter your company.'); return; }

    setSubmitting(true);

    const leadDoc = {
      name: form.name.trim(),
      email: form.email.trim(),
      company: form.company.trim(),
      phone: form.phone.trim() || '',
      source: 'talk-to-expert',
      attribution: meta.source || 'unknown',
      topic: meta.topic || null,
      intent: meta.intent || 'specialist',
      message: form.message.trim() || null,
      pageUrl: typeof location !== 'undefined' ? location.href : null,
      pageTitle: typeof document !== 'undefined' ? document.title : null,
      referrer: (typeof document !== 'undefined' && document.referrer) || null,
      userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : null,
    };

    try {
      if (window.__abgsLeads && window.__abgsLeads.saveLead) {
        await window.__abgsLeads.saveLead(leadDoc);
      } else {
        throw new Error('Contact service unavailable. Please refresh and try again.');
      }
    } catch (err) {
      setSubmitting(false);
      setError(err && err.message ? err.message : 'Could not send your message. Please try again.');
      return;
    }

    setSubmitting(false);
    setSent(true);
  }

  return (
    <div role="dialog" aria-modal="true" aria-label={copy.title}
      style={{ position: 'fixed', inset: 0, zIndex: 9999,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16,
        fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }}>
      {/* Backdrop */}
      <div onClick={() => setOpen(false)} aria-hidden
        style={{ position: 'absolute', inset: 0, background: 'rgba(11,18,32,0.55)',
          backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
          animation: 'cm-fade-in 180ms ease' }}/>

      {/* Card */}
      <div style={{ position: 'relative', width: '100%', maxWidth: 480,
        background: '#fff', borderRadius: 18,
        boxShadow: '0 24px 64px -12px rgba(11,18,32,0.35), 0 0 0 1px rgba(16,24,40,0.04)',
        animation: 'cm-pop-in 220ms cubic-bezier(0.34,1.56,0.64,1)',
        overflow: 'hidden' }}>

        {/* Close */}
        <button onClick={() => setOpen(false)} aria-label="Close"
          style={{ position: 'absolute', top: 14, right: 14, width: 32, height: 32,
            borderRadius: 9999, background: 'transparent', border: 'none',
            color: '#667085', cursor: 'pointer', display: 'inline-flex',
            alignItems: 'center', justifyContent: 'center', zIndex: 2 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M18 6L6 18M6 6l12 12"/>
          </svg>
        </button>

        {sent ? (
          <div style={{ padding: '40px 32px 36px', textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: 9999,
              background: '#ECFDF3', color: '#027A48', margin: '0 auto',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 6L9 17l-5-5"/>
              </svg>
            </div>
            <h3 style={{ margin: '20px 0 0', fontSize: 22, fontWeight: 700,
              letterSpacing: '-0.02em', color: '#0B1220' }}>
              Thanks — we’ll be in touch.
            </h3>
            <p style={{ margin: '8px auto 0', fontSize: 14, color: '#475467',
              maxWidth: 320, lineHeight: 1.55 }}>
              A specialist will reach out to <strong>{form.email}</strong> within
              one business day.
            </p>
          </div>
        ) : (
          <form onSubmit={onSubmit} style={{ padding: '28px 28px 24px' }}>
            <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '0.08em',
              textTransform: 'uppercase', color: '#1846B0', marginBottom: 6 }}>
              {meta.topic || 'Get in touch'}
            </div>
            <h3 style={{ margin: 0, fontSize: 22, fontWeight: 700,
              letterSpacing: '-0.02em', color: '#0B1220' }}>
              {copy.title}
            </h3>
            <p style={{ margin: '6px 0 18px', fontSize: 13.5, color: '#475467',
              lineHeight: 1.5 }}>
              {copy.subtitle}
            </p>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <CMField label="Full name" required>
                <input value={form.name} onChange={e => set('name', e.target.value)}
                  placeholder="Your name" required style={cmInput}/>
              </CMField>
              <CMField label="Company" required>
                <input value={form.company} onChange={e => set('company', e.target.value)}
                  placeholder="Company" required style={cmInput}/>
              </CMField>
              <CMField label="Work email" required>
                <input type="email" value={form.email} onChange={e => set('email', e.target.value)}
                  placeholder="you@company.com" required style={cmInput}/>
              </CMField>
              <CMField label="Phone">
                <input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)}
                  placeholder="Optional" style={cmInput}/>
              </CMField>
            </div>

            <CMField label={copy.msgLabel} style={{ marginTop: 10 }}>
              <textarea value={form.message} onChange={e => set('message', e.target.value)}
                placeholder="A few details so we can route you to the right person."
                rows={3} maxLength={2000}
                style={{ ...cmInput, resize: 'vertical', minHeight: 78, fontFamily: 'inherit' }}/>
            </CMField>

            {error && (
              <div role="alert" style={{ marginTop: 12, padding: '10px 12px', borderRadius: 8,
                background: '#FEF3F2', border: '1px solid #FECDCA',
                color: '#B42318', fontSize: 13, lineHeight: 1.45 }}>
                {error}
              </div>
            )}

            <button type="submit" disabled={submitting} style={{
              marginTop: 16, width: '100%', padding: '13px 20px', borderRadius: 10,
              background: submitting ? '#94aef0' : '#1E57D6', color: '#fff', border: 0,
              fontFamily: 'inherit', fontSize: 14.5, fontWeight: 700,
              cursor: submitting ? 'wait' : 'pointer', display: 'inline-flex',
              alignItems: 'center', justifyContent: 'center', gap: 8,
              boxShadow: '0 8px 16px -8px rgba(30,87,214,0.5)' }}>
              {submitting ? 'Sending…' : copy.submit}
            </button>

            <div style={{ marginTop: 10, fontSize: 11.5, color: '#98a2b3',
              textAlign: 'center', lineHeight: 1.4 }}>
              We only use your info to route this conversation — no marketing spam.
            </div>
          </form>
        )}
      </div>

      <style>{`
        @keyframes cm-fade-in { from { opacity: 0 } to { opacity: 1 } }
        @keyframes cm-pop-in {
          from { opacity: 0; transform: scale(0.96) translateY(6px) }
          to   { opacity: 1; transform: scale(1) translateY(0) }
        }
      `}</style>
    </div>
  );
}

function CMField({ label, required, children, style }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 5, ...style }}>
      <span style={{ fontSize: 11.5, fontWeight: 600, color: '#344054',
        letterSpacing: '-0.005em' }}>
        {label}{required && <span style={{ color: '#dc2626' }}> *</span>}
      </span>
      {children}
    </label>
  );
}

const cmInput = {
  padding: '11px 12px', borderRadius: 9, border: '1px solid #d0d5dd',
  fontFamily: 'inherit', fontSize: 14, color: '#101828',
  background: '#fff', outline: 'none', width: '100%', boxSizing: 'border-box',
};

window.ContactModalRoot = ContactModalRoot;
