// JoinCustomer — customer sign-up section.
// Two modes, controlled by SHOW_PAY_FLOW below:
//   true  → original "Sign up in 10 seconds" flow (QR on desktop, Apple Pay /
//           Google Pay on mobile). Use once the venue network is live.
//   false → "Coming soon" waitlist: collects email + postcode (+ optional
//           comments) and POSTs to /api/join-customer. The original flow
//           code stays in this file so we can flip the flag and revert.
window.JoinCustomer = function JoinCustomer() {
  // Flip to `true` to restore the QR / Apple Pay sign-up flow.
  const SHOW_PAY_FLOW = false;

  // Detect "is this a touch / phone-sized device". Uses matchMedia so the
  // component re-renders if the user resizes between desktop and mobile.
  const [isMobile, setIsMobile] = React.useState(() => {
    if (typeof window === 'undefined' || !window.matchMedia) return false;
    return window.matchMedia('(max-width: 720px)').matches;
  });

  React.useEffect(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia('(max-width: 720px)');
    const handler = (e) => setIsMobile(e.matches);
    if (mq.addEventListener) mq.addEventListener('change', handler);
    else mq.addListener(handler);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', handler);
      else mq.removeListener(handler);
    };
  }, []);

  // Placeholder QR — pure CSS / SVG so we don't ship an external image.
  // Replace with a real QR (e.g. linking to the signup URL) before launch.
  const qrPlaceholder = React.createElement('div', {
    style: {
      width: 220, height: 220,
      background: 'var(--ivory)',
      border: '1.5px dashed rgba(58,53,48,0.3)',
      borderRadius: 18,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexDirection: 'column', gap: 10,
      padding: 18, textAlign: 'center',
      flexShrink: 0,
    }
  },
    React.createElement('div', {
      style: {
        width: 140, height: 140,
        background: 'repeating-conic-gradient(var(--charcoal) 0deg 90deg, transparent 0deg 180deg) 0 0 / 18px 18px',
        borderRadius: 6,
        opacity: 0.85,
      }
    }),
    React.createElement('div', {
      style: { fontSize: 11, fontWeight: 500, color: 'var(--silver)', letterSpacing: '0.4px', textTransform: 'uppercase' }
    }, 'QR code placeholder'),
  );

  // Mobile Apple/Google Pay buttons — placeholders for now.
  const payButton = (provider) => React.createElement('button', {
    key: provider,
    onClick: () => alert(`${provider} sign-up flow is a placeholder — wire to real handler before launch.`),
    style: {
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      width: '100%',
      padding: '16px 22px',
      fontSize: 16, fontWeight: 600,
      fontFamily: 'inherit',
      color: 'var(--ivory)',
      background: 'var(--charcoal)',
      border: 'none',
      borderRadius: 14,
      cursor: 'pointer',
      transition: 'transform 0.15s, background 0.15s',
    }
  },
    // Lightweight inline mark for the provider — not a real brand mark, just a hint.
    React.createElement('span', {
      style: {
        fontFamily: 'var(--font-serif)', fontSize: 18, fontWeight: 500,
        opacity: 0.95, lineHeight: 1,
      }
    }, provider === 'Apple Pay' ? '' : 'G'),
    `Sign up with ${provider}`,
  );

  // ─────────────────────────────────────────────────────────────────────────
  // WAITLIST MODE (SHOW_PAY_FLOW = false)
  // POSTs to /api/join-customer, which forwards to a separate Airtable webhook.
  // ─────────────────────────────────────────────────────────────────────────
  const [waitForm, setWaitForm] = React.useState({ email: '', postcode: '', comments: '' });
  const [waitSubmitted, setWaitSubmitted] = React.useState(false);
  const [waitSubmitting, setWaitSubmitting] = React.useState(false);
  const [waitSubmitError, setWaitSubmitError] = React.useState(null);
  const [waitErrors, setWaitErrors] = React.useState({});

  const updateWait = (k) => (e) => {
    setWaitForm({ ...waitForm, [k]: e.target.value });
    if (waitErrors[k]) setWaitErrors({ ...waitErrors, [k]: null });
  };

  const submitWait = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!waitForm.email.trim()) errs.email = 'Email is required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(waitForm.email)) errs.email = 'Enter a valid email';
    if (!waitForm.postcode.trim()) errs.postcode = 'Postcode is required';
    if (Object.keys(errs).length) { setWaitErrors(errs); return; }

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

  // Shared input/label styles (mirror the venue Join form for visual continuity).
  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,
  };

  if (!SHOW_PAY_FLOW) {
    return React.createElement('section', { id: 'join-customer', 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.1fr', gap: 56, alignItems: 'start' }
        },
          // LEFT — coming-soon 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 }
            },
              'Coming soon to a venue ',
              React.createElement('span', { className: 'serif-accent' }, 'near you.'),
            ),
            React.createElement('p', { style: { fontSize: 17, color: 'var(--stone)', lineHeight: 1.65, marginBottom: 28, maxWidth: 460 } },
              'Want to stay in the LÜP? Enter your email address and we\'ll let you know when we are in your area!'
            ),
            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' } }, 'Got questions?'),
                React.createElement('a', { href: 'mailto:contact@lupit.com.au', style: { fontSize: 15, color: 'var(--charcoal)', textDecoration: 'none', fontWeight: 500 } }, 'contact@lupit.com.au'),
              ),
            ),
          ),

          // RIGHT — waitlist form (or success state)
          React.createElement(Reveal, { as: 'div', delay: 1,
            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',
            }
          },
            waitSubmitted
              ? 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 }
                  }, 'You\'re on the list!'),
                  React.createElement('p', { style: { fontSize: 16, color: 'var(--stone)', lineHeight: 1.6, maxWidth: 380, margin: '0 auto' } },
                    'We\'ll email ', React.createElement('em', { className: 'hi' }, waitForm.email),
                    ' as soon as a LÜP venue lands near ', React.createElement('em', { className: 'hi' }, waitForm.postcode), '.'
                  ),
                )
              : React.createElement('form', { onSubmit: submitWait, 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 }
                    }, 'Stay in the LÜP'),
                    React.createElement('h3', {
                      style: { fontFamily: 'var(--font-serif)', fontSize: 26, fontWeight: 500, color: 'var(--charcoal)', lineHeight: 1.2 }
                    }, 'Get notified when we launch near you'),
                  ),
                  React.createElement('div', {},
                    React.createElement('label', { htmlFor: 'wl-email', style: labelStyle }, 'Email *'),
                    React.createElement('input', {
                      id: 'wl-email', type: 'email', value: waitForm.email, onChange: updateWait('email'),
                      placeholder: 'youremail@domain.com.au', style: inputStyle(waitErrors.email),
                      onFocus: e => e.target.style.borderColor = 'var(--terracotta)',
                      onBlur: e => e.target.style.borderColor = waitErrors.email ? '#b53333' : 'var(--border-warm)',
                    }),
                    waitErrors.email && React.createElement('div', { style: { fontSize: 12, color: '#b53333', marginTop: 6 } }, waitErrors.email),
                  ),
                  React.createElement('div', {},
                    React.createElement('label', { htmlFor: 'wl-postcode', style: labelStyle }, 'Postcode *'),
                    React.createElement('input', {
                      id: 'wl-postcode', type: 'text', inputMode: 'numeric', value: waitForm.postcode, onChange: updateWait('postcode'),
                      placeholder: '2010', style: inputStyle(waitErrors.postcode),
                      onFocus: e => e.target.style.borderColor = 'var(--terracotta)',
                      onBlur: e => e.target.style.borderColor = waitErrors.postcode ? '#b53333' : 'var(--border-warm)',
                    }),
                    waitErrors.postcode && React.createElement('div', { style: { fontSize: 12, color: '#b53333', marginTop: 6 } }, waitErrors.postcode),
                  ),
                  React.createElement('div', {},
                    React.createElement('label', { htmlFor: 'wl-comments', style: labelStyle }, 'Comments (optional)'),
                    React.createElement('textarea', {
                      id: 'wl-comments', rows: 4, value: waitForm.comments, onChange: updateWait('comments'),
                      placeholder: 'Anything you\'d like us to know? Favourite local cafés, etc.',
                      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: waitSubmitting,
                    className: 'btn btn-terracotta',
                    style: {
                      padding: '16px 28px', fontSize: 16, fontWeight: 500,
                      borderRadius: 14, marginTop: 8, justifyContent: 'center',
                      opacity: waitSubmitting ? 0.7 : 1,
                      cursor: waitSubmitting ? 'wait' : 'pointer',
                    }
                  },
                    waitSubmitting ? 'Sending…' : 'Notify me',
                    !waitSubmitting && React.createElement(IconArrowRight, { size: 16 }),
                  ),
                  waitSubmitError && React.createElement('div', {
                    style: { fontSize: 13, color: '#b53333', textAlign: 'center', lineHeight: 1.5, marginTop: -4 }
                  }, waitSubmitError),
                  React.createElement('div', { style: { fontSize: 12, color: 'var(--silver)', textAlign: 'center', lineHeight: 1.5 } },
                    'We\'ll only email you about LÜP launches. No spam, unsubscribe anytime.'
                  ),
                ),
          ),
        ),
      ),
    );
  }

  return React.createElement('section', { id: 'join-customer', 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.1fr', gap: 56, alignItems: 'center' }
      },
        // 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 }
          },
            'Sign up in ', React.createElement('span', { className: 'serif-accent' }, '10 seconds.'),
          ),
          React.createElement('p', { style: { fontSize: 17, color: 'var(--stone)', lineHeight: 1.65, marginBottom: 28, maxWidth: 460 } },
            isMobile
              ? 'One tap with Apple Pay or Google Pay. No app to install, no account to remember — your phone is your LÜP card.'
              : 'Scan this QR with your phone\'s camera to start. Sign-up takes 10 seconds with Apple Pay or Google Pay — no app, no account hassle.'
          ),
          React.createElement('hr', { className: 'dashed-divider', style: { margin: '24px 0' } }),
          React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 14 } },
            [
              { hl: 'Free to use.', rest: ' Borrow and return at zero cost.' },
              { hl: 'Return anywhere.', rest: ' Any LÜP venue, not just where you got the bowl.' },
              { hl: 'Skip the bin.', rest: ' Each bowl replaces 500+ disposables.' },
            ].map(item => React.createElement('div', {
              key: item.hl,
              style: { display: 'flex', gap: 12, alignItems: 'flex-start', fontSize: 15, color: 'var(--charcoal)' }
            },
              React.createElement(IconCheck, { size: 18, color: 'var(--sage-dark)' }),
              React.createElement('span', {},
                React.createElement('em', { className: 'hi' }, item.hl),
                item.rest,
              ),
            )),
          ),
        ),

        // RIGHT — QR (desktop) or Apple/Google Pay buttons (mobile)
        React.createElement(Reveal, { as: 'div', delay: 1,
          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)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 22,
            position: 'relative',
          }
        },
          isMobile
            ? React.createElement(React.Fragment, null,
                React.createElement('div', {
                  style: { fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 500, color: 'var(--charcoal)', textAlign: 'center', lineHeight: 1.3 }
                }, 'Sign up with one tap'),
                React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 12, width: '100%' } },
                  payButton('Apple Pay'),
                  payButton('Google Pay'),
                ),
                React.createElement('div', {
                  style: { fontSize: 12, color: 'var(--silver)', textAlign: 'center', lineHeight: 1.5, marginTop: 4 }
                }, 'No card charged at sign-up. Cards on file with Stripe; only billed if a bowl isn\'t returned within 14 days.'),
              )
            : React.createElement(React.Fragment, null,
                React.createElement('div', {
                  style: { fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 500, color: 'var(--charcoal)', textAlign: 'center', lineHeight: 1.3 }
                }, 'Scan to sign up'),
                qrPlaceholder,
                React.createElement('div', {
                  style: { fontSize: 13, color: 'var(--stone)', textAlign: 'center', lineHeight: 1.55, maxWidth: 280 }
                },
                  'Open your phone camera and scan. Sign-up takes ',
                  React.createElement('em', { className: 'hi' }, '10 seconds'),
                  ' with Apple Pay or Google Pay.',
                ),
              ),
        ),
      ),
    ),
  );
};
