/* ContactModal — Rep by Rep marketing site.
   Opens when any element dispatches the 'rxr:open-contact' window event
   (the footer "Contact" link does this). Mirrors the Apply / Macro Guide
   modal pattern: scrim, slide-up panel, brand-styled fields, success state.

   SUBMISSION IS STUBBED. Wire to a real handler (Formspree / serverless /
   email service to info@repxrep.fit) at the Claude Code stage. Search
   "TODO: wire submit" below.

   Em dash rule respected. No exclamation marks. */

const ContactModal = () => {
  const [open, setOpen] = React.useState(false);
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [topic, setTopic] = React.useState('General');
  const [message, setMessage] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);

  // Open via global event so the footer (data-driven links) doesn't need
  // to prop-drill modal state.
  React.useEffect(() => {
    const handler = () => setOpen(true);
    window.addEventListener('rxr:open-contact', handler);
    return () => window.removeEventListener('rxr:open-contact', handler);
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  React.useEffect(() => {
    if (!open) {
      const t = setTimeout(() => {
        setName(''); setEmail(''); setTopic('General'); setMessage(''); setSubmitted(false);
      }, 300);
      return () => clearTimeout(t);
    }
  }, [open]);

  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const valid = name.trim() && emailValid && message.trim().length > 4;

  // Formspree endpoint — sign up at formspree.io, create a form for info@repxrep.fit,
  // then replace FORMSPREE_FORM_ID below with your 8-character form ID.
  const FORMSPREE_ID = 'xwvzgjvv';

  const submit = async (e) => {
    e.preventDefault();
    if (!valid) return;
    try {
      await fetch('https://formspree.io/f/' + FORMSPREE_ID, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({ name, email, topic, message }),
      });
    } catch (err) {
      console.error('Contact form submit error:', err);
    }
    setSubmitted(true);
  };

  if (!open) return null;

  const TOPICS = ['General', 'Coaching', 'Contest Prep', 'Press'];

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Contact Rep by Rep"
      onClick={e => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(17,20,24,0.85)',
        display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
        padding: '60px 24px', overflowY: 'auto',
        animation: 'rxrFadeIn 200ms cubic-bezier(.16,1,.3,1)',
      }}
    >
      <div style={{
        background: '#fff', borderRadius: 6, maxWidth: 560, width: '100%',
        position: 'relative', animation: 'rxrSlideUp 300ms cubic-bezier(.16,1,.3,1)',
      }}>
        <button
          onClick={() => setOpen(false)}
          aria-label="Close"
          style={{
            position: 'absolute', top: 18, right: 18, zIndex: 10,
            background: '#fff', border: 0, cursor: 'pointer',
            color: 'var(--fg-3)', padding: 8, borderRadius: 4, display: 'flex',
            boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'var(--rxr-haze)'; e.currentTarget.style.color = 'var(--fg)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = '#fff'; e.currentTarget.style.color = 'var(--fg-3)'; }}
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>

        {!submitted ? (
          <form onSubmit={submit}>
            <div style={{ padding: '40px 40px 24px', borderBottom: '1px solid var(--border)' }}>
              <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.32em', textTransform: 'uppercase', color: 'var(--accent)' }}>
                Contact
              </div>
              <h2 style={{
                fontFamily: 'var(--font-display)', fontSize: 38, lineHeight: 0.95,
                letterSpacing: '-0.005em', color: 'var(--fg)', textTransform: 'uppercase',
                margin: '14px 0 0',
              }}>
                Get in touch.
              </h2>
              <p style={{ fontSize: 14, color: 'var(--fg-2)', lineHeight: 1.55, margin: '12px 0 0', maxWidth: '46ch' }}>
                Questions before you apply, press, or anything else. Real reply from a real person, usually within a day. If you&apos;re ready to start, the apply button up top is the faster door.
              </p>
            </div>

            <div style={{ padding: '28px 40px 8px' }}>
              <div className="m-1" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <CField label="Name" value={name} onChange={setName} />
                <CField label="Email" type="email" value={email} onChange={setEmail} />
              </div>

              {/* Topic — segmented */}
              <div style={{ marginTop: 18 }}>
                <label style={cLabelStyle}>What&apos;s this about</label>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 8 }}>
                  {TOPICS.map(t => (
                    <button
                      type="button"
                      key={t}
                      onClick={() => setTopic(t)}
                      style={{
                        fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 600,
                        letterSpacing: '0.04em', padding: '9px 14px', borderRadius: 5,
                        cursor: 'pointer',
                        border: `1px solid ${topic === t ? 'var(--accent)' : 'var(--border-strong)'}`,
                        background: topic === t ? 'var(--accent-wash)' : '#fff',
                        color: topic === t ? 'var(--accent)' : 'var(--fg-2)',
                        transition: 'all 150ms cubic-bezier(.16,1,.3,1)',
                      }}
                    >{t}</button>
                  ))}
                </div>
              </div>

              {/* Message */}
              <div style={{ marginTop: 18 }}>
                <label style={cLabelStyle}>Message</label>
                <textarea
                  value={message}
                  onChange={e => setMessage(e.target.value)}
                  rows={4}
                  placeholder="A couple of sentences is plenty."
                  style={{
                    width: '100%', marginTop: 8, fontFamily: 'var(--font-body)', fontSize: 15,
                    padding: '12px 14px', borderRadius: 6, border: '1px solid var(--border-strong)',
                    background: '#fff', color: 'var(--fg)', resize: 'vertical', lineHeight: 1.55,
                    outline: 'none',
                  }}
                  onFocus={e => { e.target.style.borderColor = 'var(--accent)'; }}
                  onBlur={e => { e.target.style.borderColor = 'var(--border-strong)'; }}
                />
              </div>
            </div>

            <div style={{
              padding: '12px 40px 36px', display: 'flex', alignItems: 'center',
              justifyContent: 'space-between', gap: 16, flexWrap: 'wrap',
            }}>
              <div style={{ fontSize: 11, color: 'var(--fg-3)', letterSpacing: '0.04em', lineHeight: 1.5, maxWidth: '34ch' }}>
                Goes straight to info@repxrep.fit. We never share your address.
              </div>
              <button
                type="submit"
                disabled={!valid}
                className="btn btn-primary"
                style={{ padding: '14px 24px', opacity: valid ? 1 : 0.4, cursor: valid ? 'pointer' : 'not-allowed' }}
              >
                Send Message →
              </button>
            </div>
          </form>
        ) : (
          <div style={{ padding: 56, textAlign: 'center' }}>
            <div style={{
              width: 48, height: 48, borderRadius: 24, background: 'var(--rxr-volt)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', marginBottom: 20,
            }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="20 6 9 17 4 12"/>
              </svg>
            </div>
            <div style={{
              fontFamily: 'var(--font-display)', fontSize: 32, lineHeight: 1, letterSpacing: '-0.01em',
              color: 'var(--fg)', marginBottom: 12, textTransform: 'uppercase',
            }}>
              Message sent.
            </div>
            <div style={{ fontSize: 15, color: 'var(--fg-2)', lineHeight: 1.6, maxWidth: '40ch', margin: '0 auto' }}>
              Thanks, {name.trim().split(' ')[0]}. It landed in my inbox. You&apos;ll hear back at {email}, usually within a day.
            </div>
            <button onClick={() => setOpen(false)} className="btn btn-primary" style={{ marginTop: 26, padding: '12px 22px' }}>
              Done →
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

const cLabelStyle = {
  fontSize: 10, fontWeight: 600, textTransform: 'uppercase',
  letterSpacing: '0.18em', color: 'var(--fg-3)',
};

const CField = ({ label, type = 'text', value, onChange }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
    <label style={cLabelStyle}>{label}</label>
    <input
      type={type}
      value={value}
      onChange={e => onChange(e.target.value)}
      style={{
        fontFamily: 'var(--font-body)', fontSize: 15, padding: '11px 13px',
        borderRadius: 6, border: '1px solid var(--border-strong)', background: '#fff',
        color: 'var(--fg)', outline: 'none',
      }}
      onFocus={e => { e.target.style.borderColor = 'var(--accent)'; }}
      onBlur={e => { e.target.style.borderColor = 'var(--border-strong)'; }}
    />
  </div>
);

Object.assign(window, { ContactModal });
