// Contact — big CTA + inquiry form with validation & submit state

window.AtContact = () => {
  const [form, setForm] = React.useState({ name: '', email: '', kind: 'Website', budget: '', msg: '' });
  const [touched, setTouched] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendError, setSendError] = React.useState('');

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Looks off';
    if (!form.msg.trim() || form.msg.length < 10) e.msg = 'A few more words, please';
    return e;
  };
  const errors = validate();
  const valid = Object.keys(errors).length === 0;

  const submit = async (e) => {
    e.preventDefault();
    setTouched({ name: true, email: true, msg: true });
    if (!valid) return;
    setSending(true);
    setSendError('');
    try {
      const res = await fetch('https://formsubmit.co/ajax/websites@guama.dev', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          kind: form.kind,
          budget: form.budget || '(not specified)',
          message: form.msg,
          _subject: `New inquiry from ${form.name} · ${form.kind}`,
          _template: 'table',
          _captcha: 'false',
        }),
      });
      const data = await res.json();
      if (data && (data.success === true || data.success === 'true')) {
        setSent(true);
      } else {
        setSendError('Something went wrong. Please email us directly.');
      }
    } catch (err) {
      setSendError('Network error. Please email us directly.');
    } finally {
      setSending(false);
    }
  };

  const setField = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const touch = (k) => setTouched((t) => ({ ...t, [k]: true }));

  const inputBase = {
    width: '100%',
    background: 'transparent',
    border: 'none',
    borderBottom: `1px solid ${TC.line}`,
    padding: '16px 4px 12px',
    fontFamily: 'inherit',
    fontSize: 17,
    color: TC.ink,
    outline: 'none',
    transition: 'border-color .2s',
  };
  const errStyle = (k) => (touched[k] && errors[k])
    ? { borderBottomColor: TC.terra }
    : {};
  const labelStyle = {
    fontFamily: TC.mono, fontSize: 10, color: TC.mute,
    letterSpacing: 2, textTransform: 'uppercase',
    display: 'flex', justifyContent: 'space-between',
  };

  return (
    <section id="contact" style={{
      background: TC.bone,
      padding: '140px 40px 120px',
      borderTop: `1px solid ${TC.line}`,
      position: 'relative',
    }}>
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'start' }}>
          {/* Left — headline + details */}
          <div>
            <Eyebrow>§ 05 — Let's talk</Eyebrow>
            <h2 style={{
              fontFamily: TC.serif, fontSize: 'clamp(56px, 7.2vw, 112px)',
              lineHeight: 0.94, letterSpacing: -2.6, fontWeight: 400,
              margin: '24px 0 32px', color: TC.ink,
            }}>
              Tell us<br />
              about your<br />
              <em style={{ color: TC.terraDeep }}>project.</em>
            </h2>
            <p style={{ fontSize: 18, lineHeight: 1.55, color: TC.inkSoft, maxWidth: 440, marginBottom: 48 }}>
              The form is fine — an email is better. Either way, we answer within a business day,
              usually with questions before we commit to anything.
            </p>

            <div style={{ display: 'grid', gap: 28 }}>
              {[
                ['Email', 'websites@guama.dev', 'mailto:websites@guama.dev'],
                ['Phone', '310 · 400 · 6052', 'tel:+13104006052'],
                ['Where', 'Los Angeles, CA', null],
                ['Hours', 'Mon – Fri · 9am – 6pm Pacific', null],
              ].map(([k, v, href]) => (
                <div key={k} style={{ display: 'grid', gridTemplateColumns: '80px 1fr', gap: 24, alignItems: 'baseline' }}>
                  <span style={{
                    fontFamily: TC.mono, fontSize: 10, color: TC.mute,
                    letterSpacing: 2, textTransform: 'uppercase',
                  }}>{k}</span>
                  {href ? (
                    <a href={href} style={{
                      fontFamily: TC.serif, fontSize: 26, letterSpacing: -0.5,
                      color: TC.ink, textDecoration: 'none', borderBottom: `1px solid ${TC.line}`,
                      paddingBottom: 2, transition: 'color .2s, border-color .2s',
                    }}
                      onMouseOver={(e) => { e.currentTarget.style.color = TC.terraDeep; e.currentTarget.style.borderColor = TC.terra; }}
                      onMouseOut={(e) => { e.currentTarget.style.color = TC.ink; e.currentTarget.style.borderColor = TC.line; }}
                    >{v}</a>
                  ) : (
                    <span style={{ fontFamily: TC.serif, fontSize: 26, letterSpacing: -0.5, color: TC.ink }}>{v}</span>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Right — form */}
          <div style={{
            background: TC.boneSoft,
            border: `1px solid ${TC.line}`,
            borderRadius: 8,
            padding: '44px 44px 40px',
            position: 'relative',
            overflow: 'hidden',
          }}>
            {sent ? (
              <div style={{
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center', textAlign: 'center',
                minHeight: 540, padding: 20,
              }}>
                <div style={{
                  width: 80, height: 80, borderRadius: 40,
                  background: TC.terraTint2, color: TC.terraDeep,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  marginBottom: 32,
                }}>
                  <svg width="36" height="36" viewBox="0 0 36 36" fill="none" stroke="currentColor" strokeWidth="1.6">
                    <path d="M8 18l6 6 14-14" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </div>
                <div style={{ fontFamily: TC.serif, fontSize: 40, letterSpacing: -1, color: TC.ink, marginBottom: 16 }}>
                  Thanks, <em style={{ color: TC.terraDeep }}>{form.name.split(' ')[0] || 'friend'}.</em>
                </div>
                <p style={{ fontSize: 16, lineHeight: 1.55, color: TC.inkSoft, maxWidth: 360, margin: '0 0 28px' }}>
                  We got it. Expect a reply from one of the three of us within a business day.
                </p>
                <button
                  onClick={() => { setSent(false); setSendError(''); setForm({ name: '', email: '', kind: 'Website', budget: '', msg: '' }); setTouched({}); }}
                  className="at-btn at-btn-ghost"
                  style={{ fontSize: 14 }}
                >
                  Send another
                </button>
              </div>
            ) : (
              <form onSubmit={submit}>
                <div style={{
                  fontFamily: TC.mono, fontSize: 10, color: TC.terra,
                  letterSpacing: 2, textTransform: 'uppercase', marginBottom: 28,
                  display: 'flex', alignItems: 'center', gap: 10,
                }}>
                  <span style={{ width: 6, height: 6, borderRadius: 3, background: TC.terra,
                    animation: 'atPulse 2s ease-in-out infinite' }} />
                  New inquiry
                </div>

                <div style={{ display: 'grid', gap: 28 }}>
                  <div>
                    <div style={labelStyle}>
                      <span>Your name</span>
                      {touched.name && errors.name && <span style={{ color: TC.terra }}>{errors.name}</span>}
                    </div>
                    <input
                      type="text" value={form.name}
                      onChange={(e) => setField('name', e.target.value)}
                      onBlur={() => touch('name')}
                      placeholder="Jane Doe"
                      style={{ ...inputBase, ...errStyle('name') }}
                    />
                  </div>

                  <div>
                    <div style={labelStyle}>
                      <span>Email</span>
                      {touched.email && errors.email && <span style={{ color: TC.terra }}>{errors.email}</span>}
                    </div>
                    <input
                      type="email" value={form.email}
                      onChange={(e) => setField('email', e.target.value)}
                      onBlur={() => touch('email')}
                      placeholder="jane@company.com"
                      style={{ ...inputBase, ...errStyle('email') }}
                    />
                  </div>

                  <div>
                    <div style={labelStyle}>
                      <span>Kind of project</span>
                    </div>
                    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 14 }}>
                      {['Website', 'Automation', 'AI systems', 'Mobile app', 'Cloud', 'Not sure yet'].map((k) => (
                        <button key={k} type="button" onClick={() => setField('kind', k)}
                          style={{
                            padding: '9px 14px', borderRadius: 999,
                            border: `1px solid ${form.kind === k ? TC.ink : TC.line}`,
                            background: form.kind === k ? TC.ink : 'transparent',
                            color: form.kind === k ? TC.bone : TC.inkSoft,
                            fontFamily: 'inherit', fontSize: 13,
                            cursor: 'pointer', transition: 'all .18s',
                          }}
                        >{k}</button>
                      ))}
                    </div>
                  </div>

                  <div>
                    <div style={labelStyle}>
                      <span>Budget</span>
                      <span style={{ color: TC.muteLight }}>optional</span>
                    </div>
                    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 14 }}>
                      {['< $5k', '$5–15k', '$15–50k', '$50k+'].map((b) => (
                        <button key={b} type="button" onClick={() => setField('budget', b)}
                          style={{
                            padding: '9px 14px', borderRadius: 999,
                            border: `1px solid ${form.budget === b ? TC.ink : TC.line}`,
                            background: form.budget === b ? TC.ink : 'transparent',
                            color: form.budget === b ? TC.bone : TC.inkSoft,
                            fontFamily: 'inherit', fontSize: 13,
                            cursor: 'pointer', transition: 'all .18s',
                          }}
                        >{b}</button>
                      ))}
                    </div>
                  </div>

                  <div>
                    <div style={labelStyle}>
                      <span>Tell us about it</span>
                      {touched.msg && errors.msg && <span style={{ color: TC.terra }}>{errors.msg}</span>}
                    </div>
                    <textarea
                      value={form.msg}
                      onChange={(e) => setField('msg', e.target.value)}
                      onBlur={() => touch('msg')}
                      placeholder="What's the problem? What does success look like?"
                      rows={4}
                      style={{ ...inputBase, ...errStyle('msg'), resize: 'vertical', minHeight: 100 }}
                    />
                  </div>

                  <button
                    type="submit"
                    className="at-btn at-btn-pri"
                    disabled={sending}
                    style={{
                      width: '100%', justifyContent: 'center',
                      padding: '18px 24px', fontSize: 15, marginTop: 12,
                      opacity: sending ? 0.7 : 1,
                      cursor: sending ? 'wait' : 'pointer',
                    }}
                  >
                    {sending ? 'Sending…' : 'Send inquiry'}
                    {!sending && (
                      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8">
                        <path d="M3 11L11 3M11 3H5M11 3V9" strokeLinecap="round" />
                      </svg>
                    )}
                  </button>

                  {sendError && (
                    <div style={{
                      fontFamily: TC.mono, fontSize: 11, color: TC.terra,
                      letterSpacing: 0.5, textAlign: 'center', marginTop: -4,
                    }}>
                      {sendError}
                    </div>
                  )}

                  <div style={{
                    fontFamily: TC.mono, fontSize: 10, color: TC.mute,
                    letterSpacing: 0.5, textAlign: 'center', marginTop: -8,
                  }}>
                    Or just email <a href="mailto:websites@guama.dev" style={{ color: TC.terraDeep, textDecoration: 'underline' }}>websites@guama.dev</a>
                  </div>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
};
