// ContactModal.jsx — clean editorial contact form, responsive
function ChContactModal({ open, onClose }) {
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [form, setForm] = React.useState({ name: '', email: '', questions: '' });
  const isMobile = window.useIsMobile();

  React.useEffect(() => {
    if (!open) {
      setSubmitted(false);
      setSending(false);
      setError(null);
      setForm({ name: '', email: '', questions: '' });
    }
  }, [open]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    if (open) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const fieldLabel = {
    fontFamily: 'Montserrat, sans-serif', fontWeight: 700, fontSize: 12,
    letterSpacing: '1.5px', textTransform: 'uppercase',
    color: '#1B544F', marginBottom: 8, display: 'block',
  };
  const inputStyle = {
    width: '100%', padding: '14px 16px', fontFamily: 'Montserrat, sans-serif',
    fontSize: 15, color: '#1A1A1A', background: '#FDFBF6',
    border: '1.5px solid #DCD8CF', borderRadius: 8, outline: 'none',
    transition: 'border-color 180ms ease, box-shadow 180ms ease',
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError(null);
    try {
      const res = await fetch('https://formspree.io/f/xqenopbj', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          message: form.questions,
          _replyto: form.email,
          _subject: `New message from ${form.name} via Clinically Happy`,
        }),
      });
      if (res.ok) {
        setSubmitted(true);
      } else {
        setError('Something went wrong. Please email us directly at hello@clinicallyhappy.com');
      }
    } catch {
      setError('Could not send your message. Please try again or email hello@clinicallyhappy.com');
    } finally {
      setSending(false);
    }
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(20,19,15,0.60)',
        backdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: isMobile ? 16 : 24,
        animation: 'chFadeIn 220ms ease',
      }}
    >
      <style>{`
        @keyframes chFadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes chSlideUp { from { transform: translateY(20px); opacity: 0 } to { transform: translateY(0); opacity: 1 } }
        .ch-input:focus { border-color: #1B544F !important; box-shadow: 0 0 0 3px rgba(27,84,79,0.12) !important; }
      `}</style>

      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: '#fff', borderRadius: isMobile ? 12 : 16, width: '100%', maxWidth: 600,
          maxHeight: '94vh', overflow: 'auto',
          boxShadow: '0 32px 90px rgba(0,0,0,0.28)',
          animation: 'chSlideUp 320ms cubic-bezier(0.22, 0.61, 0.36, 1)',
          fontFamily: 'Montserrat, sans-serif',
          position: 'relative',
        }}
      >
        {/* Close button */}
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: 16, right: 16,
            width: 52, height: 52,
            borderRadius: '50%', border: 'none',
            background: '#F0EEE6',
            cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 24, color: '#1B544F', lineHeight: 1,
            fontWeight: 700,
            transition: 'background 200ms ease, transform 200ms ease',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = '#7FD6CF'; e.currentTarget.style.color = '#fff'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = '#F0EEE6'; e.currentTarget.style.color = '#1B544F'; }}
        >×</button>

        <div style={{ padding: isMobile ? '44px 24px 36px' : '56px 52px 52px' }}>
          {/* Header */}
          <div style={{ textAlign: 'center', marginBottom: 32 }}>
            <div style={{
              fontWeight: 700, fontSize: 11, letterSpacing: '3.5px', textTransform: 'uppercase',
              color: '#7FD6CF', marginBottom: 14,
            }}>Get in touch</div>
            <h2 style={{
              margin: 0, color: '#1B544F',
              fontWeight: 800, fontSize: isMobile ? 34 : 42, letterSpacing: '-0.5px', lineHeight: 1.05,
            }}>Contact Us</h2>
          </div>

          {submitted ? (
            <div style={{ textAlign: 'center', padding: '24px 0 12px' }}>
              <img src="/assets/smile-mark-forest.png" alt=""
                   style={{ width: 72, marginBottom: 20, opacity: 0.9 }} />
              <p style={{ fontSize: 18, color: '#1A1A1A', margin: 0, fontWeight: 700, lineHeight: 1.4 }}>
                Thank you for reaching out!
              </p>
              <p style={{ fontSize: 14, color: '#888', marginTop: 10, lineHeight: 1.6 }}>
                We've received your message and will get back to you as soon as possible.
                <br />The DrF's read every note.
              </p>
            </div>
          ) : (
            <>
              <p style={{
                textAlign: 'center', fontSize: 14, lineHeight: 1.75, color: '#666',
                margin: '0 auto 36px', maxWidth: 460,
              }}>
                For media inquiries and speaking engagements only. We will not respond to clinical matters
                via email. For general questions, visit our{' '}
                <a href="#qa" style={{ color: '#1B544F', fontWeight: 700, textDecoration: 'underline', textUnderlineOffset: 3 }}>
                  Q + A Sessions
                </a>{' '}page.
              </p>

              <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                <div>
                  <label style={fieldLabel}>Name <span style={{ color: '#C0392B' }}>*</span></label>
                  <input
                    className="ch-input" required
                    style={inputStyle}
                    placeholder="Your full name"
                    value={form.name}
                    onChange={(e) => setForm({ ...form, name: e.target.value })}
                  />
                </div>
                <div>
                  <label style={fieldLabel}>Email <span style={{ color: '#C0392B' }}>*</span></label>
                  <input
                    className="ch-input" type="email" required
                    style={inputStyle}
                    placeholder="your@email.com"
                    value={form.email}
                    onChange={(e) => setForm({ ...form, email: e.target.value })}
                  />
                </div>
                <div>
                  <label style={fieldLabel}>Message <span style={{ color: '#C0392B' }}>*</span></label>
                  <textarea
                    className="ch-input" required rows={5}
                    style={{ ...inputStyle, resize: 'vertical', minHeight: 130 }}
                    placeholder="Tell us what's on your mind..."
                    value={form.questions}
                    onChange={(e) => setForm({ ...form, questions: e.target.value })}
                  />
                </div>

                {error && (
                  <p style={{ color: '#C0392B', fontSize: 13, textAlign: 'center', margin: '-4px 0 0' }}>
                    {error}
                  </p>
                )}

                <SubmitButton sending={sending} />
              </form>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function SubmitButton({ sending }) {
  const [hover, setHover] = React.useState(false);
  const [press, setPress] = React.useState(false);
  return (
    <button
      type="submit"
      disabled={sending}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)}
      onMouseUp={() => setPress(false)}
      style={{
        width: '100%',
        padding: '20px 32px',
        background: sending ? '#7FD6CF' : press ? '#0E2D2A' : hover ? '#143D39' : '#1B544F',
        color: '#fff',
        border: 'none', borderRadius: 10,
        fontFamily: 'Montserrat, sans-serif',
        fontWeight: 700, fontSize: 14, letterSpacing: '2px', textTransform: 'uppercase',
        cursor: sending ? 'not-allowed' : 'pointer',
        opacity: sending ? 0.8 : 1,
        transform: press && !sending ? 'scale(0.98)' : 'scale(1)',
        transition: 'all 220ms cubic-bezier(0.22, 0.61, 0.36, 1)',
        marginTop: 8,
      }}
    >
      {sending ? 'Sending…' : 'Send Message'}
    </button>
  );
}

window.ChContactModal = ChContactModal;
