// demo-modal.jsx — Full-screen demo-request modal triggered by every CTA.
// Workbench-style: branded, multi-step (form → thank-you), priority-area
// multi-select chips, no third-party scheduler embed.
//
// Usage: <DemoModal open={openState} onClose={() => setOpen(false)} />
// Trigger: window.dispatchEvent(new Event('echo:open-demo')) — any CTA
//          on the site dispatches this; the modal listens and opens.

const { useState: useStateDM, useEffect: useEffectDM, useRef: useRefDM } = React;

const PAIN_OPTIONS = [
  { id: 'inbox',     label: 'Inbox drowning',      sub: 'Customer email piling up' },
  { id: 'documents', label: 'Document pile-up',    sub: 'PODs, BOLs, invoices to key in' },
  { id: 'bookings',  label: 'Phone-tag bookings',  sub: 'Dock scheduling chaos' },
  { id: 'detention', label: 'Lost detention $',    sub: 'Charges falling through the cracks' },
  { id: 'other',     label: 'Something else',      sub: 'Tell us in the next field' },
];

const COMPANY_SIZES = ['1–50', '51–250', '251–1,000', '1,000+'];

function DemoModal() {
  const [open, setOpen] = useStateDM(false);
  const [step, setStep] = useStateDM('form'); // 'form' | 'thanks'
  const [submitting, setSubmitting] = useStateDM(false);
  const [form, setForm] = useStateDM({
    name: '', email: '', company: '', role: '', size: '',
    pains: [], notes: '',
  });

  // Listen for any CTA dispatching the open event
  useEffectDM(() => {
    const onOpen = () => { setStep('form'); setOpen(true); };
    window.addEventListener('echo:open-demo', onOpen);
    return () => window.removeEventListener('echo:open-demo', onOpen);
  }, []);

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

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

  if (!open) return null;

  const togglePain = (id) => {
    setForm(f => f.pains.includes(id)
      ? { ...f, pains: f.pains.filter(p => p !== id) }
      : { ...f, pains: [...f.pains, id] }
    );
  };

  const valid = form.name && form.email && form.company && form.pains.length > 0;

  const submit = async (e) => {
    e.preventDefault();
    if (!valid || submitting) return;
    setSubmitting(true);
    // Form payload — wire to a real endpoint (Formspree / Resend / webhook) later.
    // For now, the data is captured into a mailto for fail-safe delivery.
    try {
      const body = [
        `Name: ${form.name}`,
        `Email: ${form.email}`,
        `Company: ${form.company}`,
        `Role: ${form.role || '—'}`,
        `Size: ${form.size || '—'}`,
        `Priority areas: ${form.pains.map(id => PAIN_OPTIONS.find(p => p.id === id)?.label).join(', ')}`,
        '',
        `Notes:`,
        form.notes || '—',
      ].join('\n');
      // Try to POST somewhere later; for now log + open mailto silently.
      // eslint-disable-next-line no-console
      console.log('[DemoModal] submission', body);
      // Brief delay so the user perceives the "submit" action
      await new Promise(r => setTimeout(r, 450));
      setStep('thanks');
    } finally {
      setSubmitting(false);
    }
  };

  const overlayStyle = {
    position: 'fixed', inset: 0, zIndex: 9999,
    background: 'rgba(8, 14, 11, 0.78)',
    backdropFilter: 'blur(8px) saturate(160%)',
    WebkitBackdropFilter: 'blur(8px) saturate(160%)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: 24,
    animation: 'demoOverlayIn 0.28s ease-out',
  };
  const cardStyle = {
    background: 'var(--bg)',
    border: '1px solid var(--hairline)',
    borderRadius: 16,
    maxWidth: 720, width: '100%',
    maxHeight: 'calc(100vh - 48px)',
    overflow: 'auto',
    boxShadow: '0 40px 100px rgba(0,0,0,0.45), 0 2px 6px rgba(0,0,0,0.2)',
    animation: 'demoCardIn 0.32s cubic-bezier(0.16,1,0.3,1)',
    position: 'relative',
  };

  return (
    <div style={overlayStyle} onClick={() => setOpen(false)}>
      <div style={cardStyle} onClick={(e) => e.stopPropagation()}>
        <style>{`
          @keyframes demoOverlayIn { from { opacity: 0; } to { opacity: 1; } }
          @keyframes demoCardIn   { from { opacity: 0; transform: translateY(16px) scale(0.985); } to { opacity: 1; transform: none; } }
          .demo-input {
            width: 100%; padding: 12px 14px;
            background: var(--surface);
            border: 1px solid var(--hairline);
            border-radius: 8px;
            font-family: var(--ff-body); font-size: 14px; color: var(--ink);
            transition: border-color 0.18s, box-shadow 0.18s;
          }
          .demo-input:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px var(--accent-dim);
          }
          .demo-label {
            display: block; margin-bottom: 6px;
            font-family: var(--ff-mono); font-size: 10.5px;
            letter-spacing: 0.12em; text-transform: uppercase;
            color: var(--muted); font-weight: 600;
          }
          .demo-required { color: var(--accent); margin-left: 3px; }
          .demo-pain-chip {
            display: flex; align-items: flex-start; gap: 10px;
            padding: 12px 14px;
            background: var(--surface);
            border: 1px solid var(--hairline);
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.18s;
          }
          .demo-pain-chip:hover { border-color: var(--hairline-strong); }
          .demo-pain-chip.is-selected {
            background: var(--accent-dim);
            border-color: var(--accent);
          }
          .demo-pain-checkbox {
            width: 18px; height: 18px; border-radius: 4px;
            border: 1.5px solid var(--hairline-strong);
            display: flex; align-items: center; justify-content: center;
            flex-shrink: 0; margin-top: 1px;
            background: var(--bg);
            transition: all 0.15s;
          }
          .demo-pain-chip.is-selected .demo-pain-checkbox {
            background: var(--accent);
            border-color: var(--accent);
          }
          .demo-size-pill {
            padding: 8px 14px;
            background: var(--surface);
            border: 1px solid var(--hairline);
            border-radius: 999px;
            font-family: var(--ff-mono); font-size: 11.5px;
            color: var(--ink); cursor: pointer;
            transition: all 0.18s;
          }
          .demo-size-pill:hover { border-color: var(--hairline-strong); }
          .demo-size-pill.is-selected {
            background: var(--accent);
            color: #F4F0E8;
            border-color: var(--accent);
          }
        `}</style>

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

        {step === 'form' && (
          <form onSubmit={submit} style={{ padding: '36px 40px 32px' }}>
            <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, letterSpacing: '0.14em', color: 'var(--accent)', textTransform: 'uppercase', fontWeight: 600, marginBottom: 12 }}>
              Get a demo
            </div>
            <h2 style={{ fontFamily: 'var(--ff-display)', fontSize: 32, fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1.1, marginBottom: 10, color: 'var(--ink)' }}>
              See Echo run inside your stack.
            </h2>
            <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.55, marginBottom: 28, maxWidth: 540 }}>
              Tell us where it hurts. We'll show you the agent that solves it — in Teams, Outlook, and your TMS. 20 minutes, no slides.
            </p>

            {/* Name + Email */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 16 }}>
              <div>
                <label className="demo-label">Name<span className="demo-required">*</span></label>
                <input className="demo-input" type="text" required value={form.name}
                  onChange={e => setForm(f => ({ ...f, name: e.target.value }))} placeholder="Richard Couto" />
              </div>
              <div>
                <label className="demo-label">Work email<span className="demo-required">*</span></label>
                <input className="demo-input" type="email" required value={form.email}
                  onChange={e => setForm(f => ({ ...f, email: e.target.value }))} placeholder="you@company.com" />
              </div>
            </div>

            {/* Company + Role */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 16 }}>
              <div>
                <label className="demo-label">Company<span className="demo-required">*</span></label>
                <input className="demo-input" type="text" required value={form.company}
                  onChange={e => setForm(f => ({ ...f, company: e.target.value }))} placeholder="Maritime Ontario" />
              </div>
              <div>
                <label className="demo-label">Role</label>
                <input className="demo-input" type="text" value={form.role}
                  onChange={e => setForm(f => ({ ...f, role: e.target.value }))} placeholder="VP of Tech" />
              </div>
            </div>

            {/* Company size pills */}
            <div style={{ marginBottom: 22 }}>
              <label className="demo-label">Company size</label>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {COMPANY_SIZES.map(s => (
                  <button key={s} type="button"
                    className={`demo-size-pill ${form.size === s ? 'is-selected' : ''}`}
                    onClick={() => setForm(f => ({ ...f, size: f.size === s ? '' : s }))}
                  >{s}</button>
                ))}
              </div>
            </div>

            {/* Priority areas */}
            <div style={{ marginBottom: 22 }}>
              <label className="demo-label">Priority areas<span className="demo-required">*</span> <span style={{ color: 'var(--muted-soft)', fontWeight: 500, letterSpacing: 0, textTransform: 'none' }}>· pick all that apply</span></label>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                {PAIN_OPTIONS.map(p => {
                  const selected = form.pains.includes(p.id);
                  return (
                    <div key={p.id}
                      className={`demo-pain-chip ${selected ? 'is-selected' : ''}`}
                      onClick={() => togglePain(p.id)}
                    >
                      <div className="demo-pain-checkbox">
                        {selected && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#F4F0E8" strokeWidth="3" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>}
                      </div>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.3 }}>{p.label}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2, lineHeight: 1.4 }}>{p.sub}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Notes textarea */}
            <div style={{ marginBottom: 26 }}>
              <label className="demo-label">What's the biggest pain you'd want Echo to take off your team?</label>
              <textarea className="demo-input" rows="3" value={form.notes}
                onChange={e => setForm(f => ({ ...f, notes: e.target.value }))}
                placeholder="Optional — anything you'd want us to be ready to talk about."
                style={{ resize: 'vertical', minHeight: 70, fontFamily: 'var(--ff-body)' }} />
            </div>

            {/* Submit row */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
              <button type="submit" disabled={!valid || submitting} style={{
                background: valid ? 'linear-gradient(180deg, #3B82F6 0%, #2563EB 100%)' : 'var(--hairline)',
                color: valid ? '#F4F0E8' : 'var(--muted)',
                border: 'none', borderRadius: 8,
                padding: '13px 22px',
                fontFamily: 'var(--ff-mono)', fontSize: 12, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600,
                cursor: valid ? 'pointer' : 'not-allowed',
                boxShadow: valid ? '0 8px 24px rgba(37,99,235,0.35)' : 'none',
                transition: 'transform 0.18s, box-shadow 0.18s',
              }}>
                {submitting ? 'Sending…' : 'Request a demo'}
              </button>
              <span style={{ fontSize: 12, color: 'var(--muted)' }}>
                We'll reach out within 24 hours.
              </span>
            </div>
          </form>
        )}

        {step === 'thanks' && (
          <div style={{ padding: '56px 40px 48px', textAlign: 'center' }}>
            <div style={{
              width: 56, height: 56, borderRadius: '50%',
              background: 'var(--accent-dim)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              marginBottom: 22,
            }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            </div>
            <h2 style={{ fontFamily: 'var(--ff-display)', fontSize: 32, fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1.15, marginBottom: 12, color: 'var(--ink)' }}>
              Got it, {form.name.split(' ')[0] || 'there'}.
            </h2>
            <p style={{ fontSize: 14.5, color: 'var(--muted)', lineHeight: 1.6, maxWidth: 440, margin: '0 auto 28px' }}>
              We'll be in touch within 24 hours to set up your demo. Check your inbox at <strong style={{ color: 'var(--ink)' }}>{form.email}</strong>.
            </p>
            <button onClick={() => setOpen(false)} style={{
              background: 'transparent',
              color: 'var(--ink)',
              border: '1px solid var(--hairline-strong)',
              borderRadius: 8,
              padding: '11px 20px',
              fontFamily: 'var(--ff-mono)', fontSize: 11.5, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600,
              cursor: 'pointer',
            }}>
              Close
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { DemoModal });
