// Join the network — form
// POSTs to our own server's /api/join, which forwards to the Airtable webhook
// (see server.js). Same-origin so no CORS issues.
window.JoinNetwork = function JoinNetwork() {
  const [form, setForm] = React.useState({ name: '', email: '', mobile: '', venue: '', comments: '' });
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [errors, setErrors] = React.useState({});

  // After a successful submit, scroll the form card (now showing the success
  // state) into view. Without this, mobile users stay at the bottom of the
  // long form and the new short success card sits above the next section,
  // leaving them visually parked in the FAQ.
  React.useEffect(() => {
    if (!submitted) return;
    const el = document.getElementById('join-form-card');
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }, [submitted]);

  const update = (k) => (e) => {
    setForm({ ...form, [k]: e.target.value });
    if (errors[k]) setErrors({ ...errors, [k]: null });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = 'Name is required';
    if (!form.email.trim()) errs.email = 'Email is required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errs.email = 'Enter a valid email';
    if (!form.mobile.trim()) errs.mobile = 'Mobile is required';
    if (Object.keys(errs).length) { setErrors(errs); return; }

    setSubmitError(null);
    setSubmitting(true);
    try {
      const res = await fetch('/api/join', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name.trim(),
          email: form.email.trim(),
          mobile: form.mobile.trim(),
          venue: form.venue.trim(),
          comments: form.comments.trim(),
          source: 'Website /join',
        }),
      });
      if (!res.ok) throw new Error(`Server returned ${res.status}`);
      setSubmitted(true);
    } catch (err) {
      console.error('Join form submission failed:', err);
      setSubmitError('Sorry — something went wrong sending your application. Please try again, or email contact@lupit.com.au.');
      setSubmitting(false);
    }
  };

  const inputStyle = (hasErr) => ({
    width: '100%',
    padding: '14px 16px',
    fontFamily: 'var(--font-sans)',
    fontSize: 15,
    color: 'var(--charcoal)',
    background: 'var(--ivory)',
    border: `1px solid ${hasErr ? '#b53333' : 'var(--border-warm)'}`,
    borderRadius: 12,
    outline: 'none',
    transition: 'border-color 0.15s, box-shadow 0.15s',
  });

  const labelStyle = {
    display: 'block', fontSize: 12, fontWeight: 500,
    letterSpacing: '0.4px', textTransform: 'uppercase',
    color: 'var(--stone)', marginBottom: 8,
  };

  return React.createElement('section', { id: 'join', style: { background: 'var(--ivory)', borderTop: '1px solid var(--border-cream)' } },
    React.createElement('div', { className: 'container' },
      React.createElement('div', {
        className: 'stack-md',
        style: { display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 56, alignItems: 'start' }
      },
        // LEFT — pitch
        React.createElement(Reveal, { as: 'div' },
          React.createElement('div', { className: 'eyebrow', style: { marginBottom: 22 } },
            React.createElement('span', { className: 'dot' }), 'Join the LÜP'
          ),
          React.createElement('h2', {
            style: { fontSize: 'clamp(36px, 4vw, 56px)', lineHeight: 1.05, letterSpacing: '-0.02em', marginBottom: 20 }
          },
            'From single-use to ', React.createElement('span', { className: 'serif-accent' }, 'reuse,'), React.createElement('br'), 'effortlessly.'
          ),
          React.createElement('p', { style: { fontSize: 17, color: 'var(--stone)', lineHeight: 1.65, marginBottom: 28, maxWidth: 420 } },
            'Give us your details and we\'ll be in touch within ', React.createElement('em', { className: 'hi' }, '24-hours'), ' to design a plan tailored to your needs.'
          ),
          React.createElement('hr', { className: 'dashed-divider', style: { margin: '24px 0' } }),
          React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 28 } },
            [
              'Free delivery on starter kit: bowls, lids, in-store signage and marketing materials',
              'In-person onboarding session with regular check-ins and support',
              'Daily tracking of savings & sustainability impact',
              'Cancel anytime for a full refund'
            ].map(t => React.createElement('div', { key: t, style: { display: 'flex', gap: 12, alignItems: 'flex-start', fontSize: 15, color: 'var(--charcoal)' } },
              React.createElement(IconCheck, { size: 18, color: 'var(--sage-dark)' }), t
            )),
          ),
          // Contact card
          React.createElement('div', {
            style: {
              background: 'var(--parchment)', borderRadius: 16, padding: '20px 22px',
              display: 'flex', alignItems: 'center', gap: 14,
              border: '1px solid var(--border-cream)',
            }
          },
            React.createElement(IconMail, { size: 22, color: 'var(--terracotta)' }),
            React.createElement('div', {},
              React.createElement('div', { style: { fontSize: 12, color: 'var(--silver)', letterSpacing: '0.3px' } }, 'Prefer email?'),
              React.createElement('a', { href: 'mailto:contact@lupit.com.au', style: { fontSize: 15, color: 'var(--charcoal)', textDecoration: 'none', fontWeight: 500 } }, 'contact@lupit.com.au'),
            ),
          ),
        ),

        // RIGHT — form
        React.createElement(Reveal, { as: 'div', delay: 1,
          id: 'join-form-card',
          style: {
            background: 'var(--parchment)',
            borderRadius: 28,
            padding: '40px 40px',
            border: '1px solid var(--border-cream)',
            boxShadow: '0 4px 40px rgba(0,0,0,0.04)',
            position: 'relative',
            scrollMarginTop: 120,
          }
        },
          submitted
            ? React.createElement('div', { style: { padding: '40px 10px', textAlign: 'center' } },
                React.createElement('div', {
                  style: {
                    width: 72, height: 72, borderRadius: '50%',
                    background: 'rgba(122,140,110,0.2)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    marginBottom: 22,
                  }
                },
                  React.createElement(IconCheck, { size: 36, color: 'var(--sage-dark)' }),
                ),
                React.createElement('h3', {
                  style: { fontFamily: 'var(--font-serif)', fontSize: 26, fontWeight: 500, color: 'var(--charcoal)', marginBottom: 10, lineHeight: 1.25 }
                }, 'Thanks, ', form.name.split(' ')[0] || 'friend', '!'),
                React.createElement('p', { style: { fontSize: 16, color: 'var(--stone)', lineHeight: 1.6, maxWidth: 380, margin: '0 auto' } },
                  'We\'ve received your details and will be in touch within 24-hours. We look forward to having you in the LÜP Reuse Network.'
                ),
                React.createElement('button', {
                  onClick: () => {
                    setSubmitted(false);
                    setSubmitting(false);
                    setSubmitError(null);
                    setForm({ name: '', email: '', mobile: '', venue: '', comments: '' });
                  },
                  className: 'btn btn-secondary',
                  style: { marginTop: 30, borderRadius: 100 }
                }, 'Submit another'),
              )
            : React.createElement('form', { onSubmit: handleSubmit, style: { display: 'flex', flexDirection: 'column', gap: 20 } },
                React.createElement('div', { style: { marginBottom: 4 } },
                  React.createElement('div', {
                    style: { fontSize: 11, fontWeight: 500, letterSpacing: '0.8px', textTransform: 'uppercase', color: 'var(--sage-dark)', marginBottom: 8 }
                  }, 'Tell us about your venue'),
                  React.createElement('h3', {
                    style: { fontFamily: 'var(--font-serif)', fontSize: 26, fontWeight: 500, color: 'var(--charcoal)', lineHeight: 1.2 }
                  }, 'Join the LÜP Reuse Network'),
                ),
                React.createElement('div', {},
                  React.createElement('label', { htmlFor: 'name', style: labelStyle }, 'Full name *'),
                  React.createElement('input', {
                    id: 'name', type: 'text', value: form.name, onChange: update('name'),
                    placeholder: 'Enter your full name', style: inputStyle(errors.name),
                    onFocus: e => e.target.style.borderColor = 'var(--terracotta)',
                    onBlur: e => e.target.style.borderColor = errors.name ? '#b53333' : 'var(--border-warm)',
                  }),
                  errors.name && React.createElement('div', { style: { fontSize: 12, color: '#b53333', marginTop: 6 } }, errors.name),
                ),
                React.createElement('div', { className: 'stack-md', style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 } },
                  React.createElement('div', {},
                    React.createElement('label', { htmlFor: 'email', style: labelStyle }, 'Email *'),
                    React.createElement('input', {
                      id: 'email', type: 'email', value: form.email, onChange: update('email'),
                      placeholder: 'youremail@domain.com.au', style: inputStyle(errors.email),
                      onFocus: e => e.target.style.borderColor = 'var(--terracotta)',
                      onBlur: e => e.target.style.borderColor = errors.email ? '#b53333' : 'var(--border-warm)',
                    }),
                    errors.email && React.createElement('div', { style: { fontSize: 12, color: '#b53333', marginTop: 6 } }, errors.email),
                  ),
                  React.createElement('div', {},
                    React.createElement('label', { htmlFor: 'mobile', style: labelStyle }, 'Mobile *'),
                    React.createElement('input', {
                      id: 'mobile', type: 'tel', value: form.mobile, onChange: update('mobile'),
                      placeholder: '0400 000 000', style: inputStyle(errors.mobile),
                      onFocus: e => e.target.style.borderColor = 'var(--terracotta)',
                      onBlur: e => e.target.style.borderColor = errors.mobile ? '#b53333' : 'var(--border-warm)',
                    }),
                    errors.mobile && React.createElement('div', { style: { fontSize: 12, color: '#b53333', marginTop: 6 } }, errors.mobile),
                  ),
                ),
                React.createElement('div', {},
                  React.createElement('label', { htmlFor: 'venue', style: labelStyle }, 'Venue name (optional)'),
                  React.createElement('input', {
                    id: 'venue', type: 'text', value: form.venue, onChange: update('venue'),
                    placeholder: 'Restaurant or Café Name', style: inputStyle(false),
                    onFocus: e => e.target.style.borderColor = 'var(--terracotta)',
                    onBlur: e => e.target.style.borderColor = 'var(--border-warm)',
                  }),
                ),
                React.createElement('div', {},
                  React.createElement('label', { htmlFor: 'comments', style: labelStyle }, 'Comments'),
                  React.createElement('textarea', {
                    id: 'comments', rows: 4, value: form.comments, onChange: update('comments'),
                    placeholder: 'How many meals a day? Any existing packaging you use today?',
                    style: { ...inputStyle(false), resize: 'vertical', fontFamily: 'var(--font-sans)' },
                    onFocus: e => e.target.style.borderColor = 'var(--terracotta)',
                    onBlur: e => e.target.style.borderColor = 'var(--border-warm)',
                  }),
                ),
                React.createElement('button', {
                  type: 'submit',
                  disabled: submitting,
                  className: 'btn btn-terracotta',
                  style: {
                    padding: '16px 28px', fontSize: 16, fontWeight: 500,
                    borderRadius: 14, marginTop: 8, justifyContent: 'center',
                    opacity: submitting ? 0.7 : 1,
                    cursor: submitting ? 'wait' : 'pointer',
                  }
                },
                  submitting ? 'Sending…' : 'Submit form',
                  !submitting && React.createElement(IconArrowRight, { size: 16 }),
                ),
                submitError && React.createElement('div', {
                  style: { fontSize: 13, color: '#b53333', textAlign: 'center', lineHeight: 1.5, marginTop: -4 }
                }, submitError),
                React.createElement('div', { style: { fontSize: 12, color: 'var(--silver)', textAlign: 'center', lineHeight: 1.5 } },
                  'By submitting, you agree to our privacy policy. We\'ll never share your details.'
                ),
              ),
        ),
      ),
    ),
  );
};
