/* Contact — functional form. Submits to FormSubmit (delivers to info@qafactory.ai).
   FormSubmit needs a one-time activation: the first submission emails info@qafactory.ai
   a confirmation link; click it once and all later submissions arrive in the inbox. */
const CONTACT_ENDPOINT = 'https://formsubmit.co/ajax/info@qafactory.ai';

function Contact() {
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | error
  const [error, setError] = React.useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    const form = e.target;
    const fd = new FormData(form);

    // honeypot — bots fill this, humans don't
    if (fd.get('_honey')) return;

    const payload = Object.fromEntries(fd.entries());
    payload._subject = 'New qafactory.ai contact enquiry';
    payload._template = 'table';

    setStatus('sending');
    setError('');
    try {
      const res = await fetch(CONTACT_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(payload),
      });
      const json = await res.json().catch(() => ({}));
      if (res.ok && (json.success === 'true' || json.success === true)) {
        setStatus('sent');
        form.reset();
      } else {
        throw new Error(json.message || 'Submission failed. Please try again or email us directly.');
      }
    } catch (err) {
      setStatus('error');
      setError(err.message || 'Network error. Please try again, or email info@qafactory.ai.');
    }
  }

  return (
    <section id="contact" style={{ background: 'var(--bg-2)' }}>
      <div className="container">
        <div className="contact-grid" style={{ display: 'grid', gridTemplateColumns: '0.9fr 1.1fr', gap: 64, alignItems: 'start' }}>
          {/* Left — intro */}
          <div>
            <span className="eyebrow"><span className="dot" />09 — Contact</span>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(40px, 5vw, 64px)', lineHeight: 1.05, letterSpacing: '-0.025em', margin: '20px 0 16px' }}>
              Talk to a <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>QA lead.</em>
            </h2>
            <p style={{ color: 'var(--ink-3)', fontSize: 18, lineHeight: 1.5, maxWidth: 460, margin: '0 0 28px' }}>
              Tell us what you're shipping and where it hurts. A senior QA lead — not a sales bot — reads every message and replies within one business day.
            </p>
            <a href="mailto:info@qafactory.ai" className="mono" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--ink-2)', letterSpacing: '0.04em', borderBottom: '1px solid var(--accent-soft)', paddingBottom: 2 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', boxShadow: '0 0 8px var(--accent)' }} />
              info@qafactory.ai
            </a>
          </div>

          {/* Right — form card */}
          <div className="card" style={{ padding: 'clamp(20px, 3vw, 36px)' }}>
            {status === 'sent' ? (
              <div className="contact-success">
                <div style={{ width: 48, height: 48, borderRadius: '50%', background: 'var(--accent-tint)', border: '1px solid var(--accent-soft)', color: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, marginBottom: 18 }}>✓</div>
                <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 30, letterSpacing: '-0.02em', margin: '0 0 8px' }}>Message sent.</h3>
                <p style={{ color: 'var(--ink-3)', fontSize: 15, lineHeight: 1.55, margin: 0 }}>
                  Thanks — it's on its way to info@qafactory.ai. Your QA lead will reply within one business day.
                </p>
                <button type="button" className="btn btn-ghost" style={{ marginTop: 20 }} onClick={() => setStatus('idle')}>
                  Send another
                </button>
              </div>
            ) : (
              <form className="contact-form" onSubmit={handleSubmit} noValidate>
                <div className="contact-row">
                  <div className="contact-field">
                    <label className="contact-label" htmlFor="cf-name">Full name</label>
                    <input className="contact-input" id="cf-name" name="name" type="text" required placeholder="Jordan Kim" autoComplete="name" />
                  </div>
                  <div className="contact-field">
                    <label className="contact-label" htmlFor="cf-email">Work email</label>
                    <input className="contact-input" id="cf-email" name="email" type="email" required placeholder="you@company.com" autoComplete="email" />
                  </div>
                </div>
                <div className="contact-field">
                  <label className="contact-label" htmlFor="cf-company">Company <span style={{ textTransform: 'none', color: 'var(--ink-4)' }}>(optional)</span></label>
                  <input className="contact-input" id="cf-company" name="company" type="text" placeholder="Acme Inc." autoComplete="organization" />
                </div>
                <div className="contact-field">
                  <label className="contact-label" htmlFor="cf-message">How can we help?</label>
                  <textarea className="contact-input contact-textarea" id="cf-message" name="message" required placeholder="We ship every Friday and our checkout flow keeps regressing…" />
                </div>

                {/* anti-spam honeypot (hidden from humans) */}
                <input type="text" name="_honey" tabIndex="-1" autoComplete="off" style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }} aria-hidden="true" />

                {status === 'error' && (
                  <div style={{ fontSize: 13, color: 'var(--danger)', background: 'rgba(168,51,31,0.06)', border: '1px solid rgba(168,51,31,0.25)', borderRadius: 'var(--radius)', padding: '10px 12px' }}>
                    {error}
                  </div>
                )}

                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginTop: 4 }}>
                  <span className="contact-note">No spam. Your details go straight to a QA lead.</span>
                  <button type="submit" className="btn btn-primary" disabled={status === 'sending'} style={{ padding: '12px 22px', fontSize: 15, opacity: status === 'sending' ? 0.7 : 1 }}>
                    {status === 'sending' ? 'Sending…' : <>Send message <span className="arrow">→</span></>}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Contact });
