window.ContactCTA = function ContactCTA() {
  const isMobile = useIsMobile();
  const isTablet = useIsTablet();
  const [formState, setFormState] = React.useState({ name: '', email: '', company: '', size: '', message: '', website: '' });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);

  const validate = () => {
    const errs = {};
    if (!formState.name.trim()) errs.name = 'Required';
    if (!formState.email.trim()) errs.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formState.email.trim())) errs.email = 'Invalid email';
    if (!formState.company.trim()) errs.company = 'Required';
    if (!formState.message.trim()) errs.message = 'Tell us what you need';
    return errs;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitError(null);
    const errs = validate();
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;
    setSending(true);
    try {
      const res = await fetch('https://api.getstitchwork.com/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formState),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || data.error) throw new Error(data.error || `Request failed (HTTP ${res.status})`);
      setSubmitted(true);
    } catch (err) {
      setSubmitError((err && err.message) || 'Could not send. Try again, or email hello@getstitchwork.com directly.');
    } finally {
      setSending(false);
    }
  };

  const update = (key, val) => {
    setFormState(s => ({ ...s, [key]: val }));
    if (errors[key]) setErrors(e => { const n = { ...e }; delete n[key]; return n; });
  };

  const sectionPadding = isMobile ? '96px 24px' : isTablet ? '128px 32px' : '160px 48px';
  const h2Size = isMobile ? 40 : isTablet ? 56 : 80;

  return (
    <section id="contact" style={{ padding: sectionPadding, maxWidth: 1280, margin: '0 auto' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1fr 1.2fr',
        gap: isMobile ? 48 : 96,
        alignItems: 'start',
      }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 16 }}>Start here</div>
          <h2 style={{
            fontSize: h2Size, fontWeight: 800, lineHeight: 0.95,
            letterSpacing: '-0.035em', color: 'var(--text-primary)', margin: '0 0 24px',
          }}>
            Tell us where<br />
            the work hurts.
          </h2>
          <p style={{ fontSize: 17, lineHeight: 1.5, color: 'var(--text-secondary)', margin: 0, maxWidth: 380 }}>
            A 30-minute consultation. No deck. We'll ask questions, look at your stack, and tell you straight whether agents can help.
          </p>
        </div>
        <div>
          {submitted ? (
            <div style={{
              padding: 48,
              border: '1px solid var(--border)',
              textAlign: 'left',
            }}>
              <div className="mono" style={{ color: 'var(--accent)', marginBottom: 12, textTransform: 'uppercase' }}>
                Confirmed
              </div>
              <h3 style={{ fontSize: 32, fontWeight: 700, lineHeight: 1.05, letterSpacing: '-0.025em', margin: '0 0 12px' }}>
                We'll be in touch.
              </h3>
              <p style={{ fontSize: 16, color: 'var(--text-secondary)', margin: 0 }}>
                Typically within one business day.
              </p>
            </div>
          ) : (
            <form onSubmit={handleSubmit} style={{ display: 'grid', gap: 16, position: 'relative' }}>
              <V3Field label="Name" value={formState.name} error={errors.name} onChange={v => update('name', v)} />
              <V3Field type="email" label="Email" value={formState.email} error={errors.email} onChange={v => update('email', v)} placeholder="you@company.com" />
              <V3Field label="Company" value={formState.company} error={errors.company} onChange={v => update('company', v)} />
              <V3Field label="Team size (optional)" value={formState.size} onChange={v => update('size', v)} placeholder="e.g. 12 people" />
              <input
                type="text" name="website" tabIndex={-1} aria-hidden="true" autoComplete="off"
                value={formState.website} onChange={e => update('website', e.target.value)}
                style={{ position: 'absolute', left: '-10000px', top: 'auto', width: 1, height: 1, overflow: 'hidden' }}
              />
              <div>
                <label style={v3FieldLabel}>What's the hour you'd most like back?</label>
                <textarea
                  className={'input-v3' + (errors.message ? ' error' : '')}
                  rows={5}
                  value={formState.message}
                  onChange={e => update('message', e.target.value)}
                  placeholder="Walk us through it…"
                />
                {errors.message && <div style={v3ErrorStyle}>{errors.message}</div>}
              </div>
              <button type="submit" disabled={sending} className="btn-solid" style={{ marginTop: 8 }}>
                {sending ? 'Sending…' : 'Request a consultation'}
                {!sending && (
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                    <path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                )}
              </button>
              {submitError && (
                <div style={{ ...v3ErrorStyle, marginTop: 0, textAlign: 'center' }}>{submitError}</div>
              )}
            </form>
          )}
        </div>
      </div>
    </section>
  );
};

const v3FieldLabel = {
  display: 'block', marginBottom: 8,
  font: '500 12px Inter, sans-serif',
  letterSpacing: '0.06em', textTransform: 'uppercase',
  color: 'var(--text-secondary)',
};

const v3ErrorStyle = {
  marginTop: 6,
  font: '500 12px Inter, sans-serif',
  color: 'var(--accent)',
};

function V3Field({ label, value, error, onChange, placeholder, type = 'text' }) {
  return (
    <div>
      <label style={v3FieldLabel}>{label}</label>
      <input
        className={'input-v3' + (error ? ' error' : '')}
        type={type}
        value={value || ''}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
      />
      {error && <div style={v3ErrorStyle}>{error}</div>}
    </div>
  );
}
