// book-call-modal.jsx — Echo "Book a call" modal
// Editorial, brand-native. Triggered by any element with [data-open-book-call].
// Esc + click-outside to close. Submits to Formspree.

const { useState: useStateBC, useEffect: useEffectBC, useRef: useRefBC } = React;

const FORMSPREE_ENDPOINT = 'https://formspree.io/f/mbdbrpdd';

const PRIORITY_AREAS = [
  'Email triage',
  'Document intake',
  'AR & cash app',
  'Claims & disputes',
  'Scheduling & dispatch',
];

const TEAM_SIZES = ['1–10', '11–50', '51–200', '200+'];

function BookCallModal() {
  const [open, setOpen] = useStateBC(false);
  const [submitting, setSubmitting] = useStateBC(false);
  const [success, setSuccess] = useStateBC(false);
  const [error, setError] = useStateBC('');
  const [form, setForm] = useStateBC({
    name: '',
    email: '',
    company: '',
    role: '',
    teamSize: '',
    priorityAreas: [],
    notes: '',
  });
  const dialogRef = useRefBC(null);

  // Wire up triggers anywhere in the DOM that have [data-open-book-call].
  useEffectBC(() => {
    const handler = (e) => {
      const trigger = e.target.closest('[data-open-book-call]');
      if (trigger) {
        e.preventDefault();
        setOpen(true);
        setSuccess(false);
        setError('');
      }
    };
    document.addEventListener('click', handler);
    return () => document.removeEventListener('click', handler);
  }, []);

  // Esc key + lock body scroll when open.
  useEffectBC(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [open]);

  if (!open) return null;

  const setField = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const togglePriority = (area) => setForm(f => ({
    ...f,
    priorityAreas: f.priorityAreas.includes(area)
      ? f.priorityAreas.filter(a => a !== area)
      : [...f.priorityAreas, area],
  }));

  const valid = form.name.trim() && form.email.trim() && form.company.trim();

  const submit = async (e) => {
    e.preventDefault();
    if (!valid || submitting) return;
    setSubmitting(true);
    setError('');
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          ...form,
          priorityAreas: form.priorityAreas.join(', '),
          _subject: `New Echo book-a-call: ${form.company || form.name}`,
        }),
      });
      if (!res.ok) throw new Error('Submit failed');
      setSuccess(true);
    } catch (err) {
      setError('Couldn\'t send right now. Email jay@echoagents.io and we\'ll book directly.');
    } finally {
      setSubmitting(false);
    }
  };

  const onBackdropClick = (e) => {
    if (e.target === e.currentTarget) setOpen(false);
  };

  return (
    <div
      onClick={onBackdropClick}
      className="bc-backdrop"
      style={{
        position: 'fixed', inset: 0, zIndex: 9999,
        background: 'rgba(10, 22, 18, 0.62)',
        backdropFilter: 'blur(8px) saturate(140%)',
        WebkitBackdropFilter: 'blur(8px) saturate(140%)',
        display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
        padding: '64px 24px 24px',
        overflowY: 'auto',
        animation: 'bcFadeIn 0.28s cubic-bezier(0.16,1,0.3,1)',
      }}
    >
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby="bc-title"
        className="bc-dialog"
        style={{
          background: 'var(--bg)',
          width: '100%', maxWidth: 760,
          borderRadius: 18,
          border: '1px solid var(--hairline)',
          boxShadow: '0 40px 100px rgba(0,0,0,0.45), 0 4px 12px rgba(0,0,0,0.10)',
          overflow: 'hidden',
          animation: 'bcRise 0.36s cubic-bezier(0.16,1,0.3,1)',
          fontFamily: 'var(--ff-body)',
        }}
      >
        {success ? (
          <SuccessState onClose={() => setOpen(false)} name={form.name} />
        ) : (
          <>
            {/* Header */}
            <header style={{ padding: '32px 36px 28px', position: 'relative' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 24, marginBottom: 14 }}>
                <span style={{
                  fontFamily: 'var(--ff-mono)', fontSize: 10.5,
                  letterSpacing: '0.18em', textTransform: 'uppercase',
                  color: 'var(--muted)', fontWeight: 500,
                }}>Book a call</span>
                <button
                  type="button"
                  onClick={() => setOpen(false)}
                  aria-label="Close"
                  style={{
                    width: 32, height: 32,
                    background: 'var(--bg)',
                    border: '1px solid var(--hairline)',
                    borderRadius: 8,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    color: 'var(--ink-soft)', cursor: 'pointer',
                    transition: 'all 0.2s var(--ease-out)',
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--ink)'; e.currentTarget.style.color = 'var(--ink)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--hairline)'; e.currentTarget.style.color = 'var(--ink-soft)'; }}
                >
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
                </button>
              </div>
              <h2 id="bc-title" style={{
                fontFamily: 'var(--ff-display)',
                fontSize: 'clamp(26px, 3vw, 34px)',
                fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1.12,
                color: 'var(--ink)', marginBottom: 10,
              }}>
                See Echo on your workflows.
              </h2>
              <p style={{
                fontSize: 14, lineHeight: 1.55, color: 'var(--muted)',
                maxWidth: 540, margin: 0,
              }}>
                Tell us where your team is bleeding time. We'll show you exactly how Echo handles it.
              </p>
            </header>

            <div style={{ borderTop: '1px solid var(--hairline)' }} />

            {/* Form */}
            <form onSubmit={submit} style={{ padding: '28px 36px 8px' }}>
              <div className="bc-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 18 }}>
                <Field label="Name" required value={form.name} onChange={v => setField('name', v)} placeholder="Alex Rivera" />
                <Field label="Work email" required type="email" value={form.email} onChange={v => setField('email', v)} placeholder="alex@company.com" />
              </div>
              <div className="bc-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 22 }}>
                <Field label="Company" required value={form.company} onChange={v => setField('company', v)} placeholder="Summit Industrial" />
                <Field label="Role" value={form.role} onChange={v => setField('role', v)} placeholder="VP of Tech" />
              </div>

              {/* Team size */}
              <FieldLabel>Team size</FieldLabel>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 22 }}>
                {TEAM_SIZES.map(s => (
                  <Chip key={s} active={form.teamSize === s} onClick={() => setField('teamSize', form.teamSize === s ? '' : s)}>{s}</Chip>
                ))}
              </div>

              {/* Priority areas */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                <FieldLabel style={{ marginBottom: 0 }}>Priority areas</FieldLabel>
                <span style={{
                  fontFamily: 'var(--ff-mono)', fontSize: 9.5,
                  letterSpacing: '0.16em', textTransform: 'uppercase',
                  color: 'var(--muted)', fontWeight: 500,
                }}>Pick any</span>
              </div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 22 }}>
                {PRIORITY_AREAS.map(a => (
                  <Chip key={a} active={form.priorityAreas.includes(a)} onClick={() => togglePriority(a)}>{a}</Chip>
                ))}
              </div>

              {/* Notes */}
              <FieldLabel>What's on your plate?</FieldLabel>
              <textarea
                value={form.notes}
                onChange={e => setField('notes', e.target.value)}
                rows={3}
                placeholder="Current ERP, biggest manual lift, anything the team should know."
                style={{
                  width: '100%',
                  padding: '12px 14px',
                  background: 'var(--surface)',
                  border: '1px solid var(--hairline)',
                  borderRadius: 8,
                  fontFamily: 'var(--ff-body)',
                  fontSize: 14, lineHeight: 1.55, color: 'var(--ink)',
                  resize: 'vertical', outline: 'none',
                  transition: 'border-color 0.2s, background 0.2s',
                }}
                onFocus={(e) => { e.target.style.borderColor = 'var(--accent)'; e.target.style.background = 'var(--surface-raised)'; }}
                onBlur={(e) => { e.target.style.borderColor = 'var(--hairline)'; e.target.style.background = 'var(--surface)'; }}
              />

              {error && (
                <div style={{ marginTop: 14, fontSize: 13, color: '#B23A1F', fontFamily: 'var(--ff-mono)', letterSpacing: '0.02em' }}>
                  {error}
                </div>
              )}

              {/* Footer / submit */}
              <div style={{
                marginTop: 28,
                paddingTop: 22, paddingBottom: 18,
                borderTop: '1px solid var(--hairline)',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
              }}>
                <span style={{ fontSize: 12.5, color: 'var(--muted)' }}>
                  We reply within 24h. No spam, no sequences.
                </span>
                <button
                  type="submit"
                  disabled={!valid || submitting}
                  className="echo-cta echo-cta--nav"
                  style={{
                    opacity: (!valid || submitting) ? 0.55 : 1,
                    pointerEvents: (!valid || submitting) ? 'none' : 'auto',
                    fontSize: 12,
                  }}
                >
                  <span className="echo-cta__dot" />
                  <span className="echo-cta__label">{submitting ? 'Sending…' : 'Submit'}</span>
                  <span className="echo-cta__arrow">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
                  </span>
                </button>
              </div>
            </form>
          </>
        )}
      </div>

      <style>{`
        @keyframes bcFadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes bcRise   { from { opacity: 0; transform: translateY(20px) scale(0.985); } to { opacity: 1; transform: none; } }
        .bc-dialog input::placeholder,
        .bc-dialog textarea::placeholder { color: var(--muted-soft); }
        @media (max-width: 640px) {
          .bc-grid { grid-template-columns: 1fr !important; }
          .bc-dialog { border-radius: 14px !important; }
          .bc-backdrop { padding: 16px !important; }
        }
      `}</style>
    </div>
  );
}

function FieldLabel({ children, style }) {
  return (
    <label style={{
      display: 'block', marginBottom: 8,
      fontFamily: 'var(--ff-mono)', fontSize: 10.5,
      letterSpacing: '0.16em', textTransform: 'uppercase',
      color: 'var(--ink-soft)', fontWeight: 600,
      ...style,
    }}>
      {children}
    </label>
  );
}

function Field({ label, required, type = 'text', value, onChange, placeholder }) {
  return (
    <div>
      <FieldLabel>
        {label}{required && <span style={{ color: 'var(--accent)', marginLeft: 4 }}>*</span>}
      </FieldLabel>
      <input
        type={type}
        required={required}
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          width: '100%',
          padding: '11px 14px',
          background: 'var(--surface)',
          border: '1px solid var(--hairline)',
          borderRadius: 8,
          fontFamily: 'var(--ff-body)',
          fontSize: 14, color: 'var(--ink)',
          outline: 'none',
          transition: 'border-color 0.2s, background 0.2s',
        }}
        onFocus={(e) => { e.target.style.borderColor = 'var(--accent)'; e.target.style.background = 'var(--surface-raised)'; }}
        onBlur={(e) => { e.target.style.borderColor = 'var(--hairline)'; e.target.style.background = 'var(--surface)'; }}
      />
    </div>
  );
}

function Chip({ active, onClick, children }) {
  const [hover, setHover] = useStateBC(false);
  return (
    <button
      type="button"
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        padding: '8px 14px',
        background: active ? 'var(--accent)' : (hover ? 'var(--surface-raised)' : 'var(--surface)'),
        color: active ? '#fff' : 'var(--ink)',
        border: `1px solid ${active ? 'var(--accent)' : (hover ? 'var(--hairline-strong)' : 'var(--hairline)')}`,
        borderRadius: 8,
        fontFamily: 'var(--ff-body)',
        fontSize: 13, fontWeight: 500,
        cursor: 'pointer',
        transition: 'all 0.16s var(--ease-out)',
        boxShadow: active ? '0 4px 14px rgba(80, 89, 201, 0.28)' : 'none',
      }}
    >
      {children}
    </button>
  );
}

function SuccessState({ onClose, name }) {
  return (
    <div style={{ padding: '48px 36px 40px', textAlign: 'center' }}>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: 'rgba(80, 89, 201, 0.12)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 22,
      }}>
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="20 6 9 17 4 12"/>
        </svg>
      </div>
      <h2 style={{
        fontFamily: 'var(--ff-display)',
        fontSize: 28, fontWeight: 500, letterSpacing: '-0.015em',
        color: 'var(--ink)', marginBottom: 10,
      }}>
        Thanks{name ? `, ${name.split(' ')[0]}` : ''}.
      </h2>
      <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--muted)', maxWidth: 380, margin: '0 auto 28px' }}>
        We'll reply within 24 hours with a few times that work. Look out for an email from jay@echoagents.io.
      </p>
      <button
        type="button"
        onClick={onClose}
        style={{
          padding: '10px 20px',
          background: 'var(--bg)',
          border: '1px solid var(--hairline)',
          borderRadius: 8,
          fontFamily: 'var(--ff-mono)', fontSize: 11,
          letterSpacing: '0.12em', textTransform: 'uppercase',
          color: 'var(--ink)', fontWeight: 600, cursor: 'pointer',
          transition: 'all 0.2s',
        }}
        onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--ink)'; }}
        onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--hairline)'; }}
      >
        Close
      </button>
    </div>
  );
}

// Mount the modal once into the page. The trigger handler is delegated,
// so any element with [data-open-book-call] anywhere on the site opens it.
Object.assign(window, { BookCallModal });
