const Contact = () => {
  const isMobile = useIsMobile();
  const [form, setForm] = useState({ name:'', email:'', company:'', budget:'', services: [], msg: '' });
  const [sent, setSent] = useState(false);
  const [errors, setErrors] = useState({});
  const ref = useReveal();

  const up = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleSvc = (s) => setForm(f => ({ ...f, services: f.services.includes(s) ? f.services.filter(x => x !== s) : [...f.services, s] }));

  const submit = async (e) => {
    e.preventDefault();
    const err = {};
    if (!form.name.trim()) err.name = 'required';
    if (!/^\S+@\S+\.\S+$/.test(form.email)) err.email = 'invalid';
    if (!form.msg.trim() || form.msg.length < 10) err.msg = 'Tell us a bit more';
    setErrors(err);
    if (Object.keys(err).length) return;

    let message = form.msg.trim();
    if (form.company) message += '\n\n— Company: ' + form.company;
    if (form.budget) message += '\n— Budget: ' + form.budget;
    if (form.services && form.services.length) message += '\n— Services: ' + form.services.join(', ');

    try {
      const res = await fetch('https://api.theprofitplatform.com.au/api/v2/contact/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name.trim(),
          email: form.email.trim(),
          message,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        setErrors({ submit: (data.details && data.details[0]) || data.error || 'Submission failed — try again?' });
        return;
      }
      setSent(true);
    } catch (e) {
      setErrors({ submit: 'Network error. Email us directly: hello@theprofitplatform.com.au' });
    }
  };

  return (
    <section id="contact" className="section" style={{ background: 'var(--section-alt)' }}>
      <div className="container">
        <div ref={ref} className="reveal split-even" style={{ alignItems:'flex-start' }}>
          {/* left — statement */}
          <div style={{ position: isMobile ? 'static' : 'sticky', top: 120 }}>
            <span className="eyebrow">Get in touch</span>
            <h2 className="h-xl" style={{ marginTop: 20 }}>
              Email us. We'll <span className="serif-i" style={{color:'var(--accent)'}}>write back</span> like a person.
            </h2>
            <p style={{ fontSize: 17, color:'var(--fg-2)', lineHeight: 1.55, marginTop: 20, maxWidth: 440 }}>
              No bots, no "a strategist will reach out". One of us two will read it and reply, usually same day, always within a working day.
            </p>
            <p style={{ fontSize: 14, color:'var(--fg-3)', lineHeight: 1.55, marginTop: 16, maxWidth: 440, fontStyle:'italic', fontFamily:'var(--serif)' }}>
              Happy to jump on a 20-minute call if it's easier. We don't do sales decks.
            </p>
            <div style={{ marginTop: 40, display:'flex', flexDirection:'column', gap: 0 }}>
              <a href="mailto:hello@theprofitplatform.com.au" style={{ display:'flex', alignItems:'center', gap: 14, padding: '16px 0', borderTop: '1px solid var(--line)' }}>
                <Icon name="mail" size={18}/>
                <div>
                  <div className="mono" style={{ fontSize: 10, color:'var(--fg-3)', letterSpacing:'.14em' }}>EMAIL</div>
                  <div style={{ fontSize: 14, marginTop: 2 }}>hello@theprofitplatform.com.au</div>
                </div>
              </a>
              <a href="tel:+61280000000" style={{ display:'flex', alignItems:'center', gap: 14, padding: '16px 0', borderTop: '1px solid var(--line)' }}>
                <Icon name="phone" size={18}/>
                <div>
                  <div className="mono" style={{ fontSize: 10, color:'var(--fg-3)', letterSpacing:'.14em' }}>PHONE · WEEKDAYS 9–5</div>
                  <div style={{ fontSize: 14, marginTop: 2 }}>0478 XXX XXX (Sam's mobile)</div>
                </div>
              </a>
              <div style={{ display:'flex', alignItems:'center', gap: 14, padding: '16px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
                <Icon name="globe" size={18}/>
                <div>
                  <div className="mono" style={{ fontSize: 10, color:'var(--fg-3)', letterSpacing:'.14em' }}>WHERE</div>
                  <div style={{ fontSize: 14, marginTop: 2 }}>Working from our place in Marrickville</div>
                </div>
              </div>
            </div>
          </div>

          {/* right — form */}
          <div className="glass" style={{ padding: 'clamp(22px, 4vw, 36px)' }}>
            {sent ? (
              <div style={{ padding: '40px 0', textAlign:'center' }}>
                <div style={{ width: 64, height: 64, borderRadius: '50%', background:'var(--accent)', display:'inline-flex', alignItems:'center', justifyContent:'center', color:'var(--bg)' }}>
                  <Icon name="check" size={28} stroke={2.5}/>
                </div>
                <h3 className="h-lg" style={{ marginTop: 24 }}>Got it, {form.name.split(' ')[0]}.</h3>
                <p style={{ color:'var(--fg-2)', marginTop: 10 }}>We'll reply to {form.email} — usually same day. If we don't, our inbox is a mess, please poke us.</p>
                <button onClick={() => { setSent(false); setForm({ name:'', email:'', company:'', budget:'', services:[], msg:'' }); }} className="btn btn-ghost" style={{ marginTop: 24 }}>Send another</button>
              </div>
            ) : (
              <form onSubmit={submit} style={{ display:'flex', flexDirection:'column', gap: 20 }}>
                <div className="grid-2" style={{ gap: 16 }}>
                  <Field label="Your name" err={errors.name}>
                    <input value={form.name} onChange={e => up('name', e.target.value)} placeholder="Jane Smith" style={inputSt}/>
                  </Field>
                  <Field label="Email" err={errors.email}>
                    <input value={form.email} onChange={e => up('email', e.target.value)} placeholder="jane@company.com" style={inputSt}/>
                  </Field>
                </div>
                <Field label="Company">
                  <input value={form.company} onChange={e => up('company', e.target.value)} placeholder="Acme Pty Ltd" style={inputSt}/>
                </Field>

                <Field label="What are you interested in? (pick any)">
                  <div style={{ display:'flex', flexWrap:'wrap', gap: 6 }}>
                    {['Website','SEO','Google Ads','Meta Ads','Social','IT','Software','Web App','Brand','Content','Not sure'].map(s => {
                      const on = form.services.includes(s);
                      return (
                        <button type="button" key={s} onClick={() => toggleSvc(s)}
                          style={{
                            padding: '8px 14px', borderRadius: 999, fontSize: 13,
                            background: on ? 'var(--accent)' : 'transparent',
                            color: on ? 'var(--bg)' : 'var(--fg-2)',
                            border: '1px solid ' + (on ? 'var(--accent)' : 'var(--line-2)'),
                            transition: 'all .2s'
                          }}>
                          {s}
                        </button>
                      );
                    })}
                  </div>
                </Field>

                <Field label="Roughly what's the budget?">
                  <div style={{ display:'flex', gap: 6, flexWrap:'wrap' }}>
                    {['Under $2k','$2k – $5k','$5k – $15k','$15k+','Honestly, no idea'].map(b => (
                      <button type="button" key={b} onClick={() => up('budget', b)}
                        style={{
                          padding: '8px 14px', borderRadius: 999, fontSize: 13,
                          background: form.budget === b ? 'var(--accent)' : 'transparent',
                          color: form.budget === b ? 'var(--bg)' : 'var(--fg-2)',
                          border: '1px solid ' + (form.budget === b ? 'var(--accent)' : 'var(--line-2)'),
                          transition: 'all .2s'
                        }}>
                        {b}
                      </button>
                    ))}
                  </div>
                </Field>

                <Field label="What's on your plate?" err={errors.msg}>
                  <textarea rows={4} value={form.msg} onChange={e => up('msg', e.target.value)} placeholder="We've got an old Squarespace site that's a pain to update and nobody finds us on Google..." style={{ ...inputSt, resize:'vertical', fontFamily:'inherit' }}/>
                </Field>

                <button type="submit" className="btn btn-accent" style={{ justifyContent:'center', width:'100%', padding: '16px 22px', fontSize: 14 }}>
                  Send <Icon name="arrow" size={14}/>
                </button>
                <div className="mono" style={{ fontSize: 10, color:'var(--fg-3)', textAlign:'center' }}>
                  We keep your details to ourselves. No newsletter.
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
};

const inputSt = {
  width:'100%', background:'var(--input-bg)',
  border:'1px solid var(--line-2)', borderRadius: 10,
  padding: '12px 14px', color:'var(--fg)', fontSize: 14, outline:'none',
  transition:'border-color .2s'
};

const Field = ({ label, err, children }) => (
  <label style={{ display:'flex', flexDirection:'column', gap: 8 }}>
    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
      <span className="mono" style={{ fontSize: 10, color:'var(--fg-3)', letterSpacing:'.14em', textTransform:'uppercase' }}>{label}</span>
      {err && <span className="mono" style={{ fontSize: 10, color:'var(--accent-3)' }}>⚠ {err}</span>}
    </div>
    {children}
  </label>
);

window.Contact = Contact;
