/* global React */
const DS_SUPPORT = window.SubEarthDesignSystem_9ae0a6;

function Support() {
  const { Eyebrow, Input, Button } = window.SubEarthDesignSystem_9ae0a6;
  const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [status, setStatus] = React.useState(null); // null | 'sending' | 'ok' | 'err'
  const [error, setError] = React.useState('');
  const hpRef = React.useRef(null); // honeypot — bots fill it; humans never see it

  async function send() {
    const n = name.trim();
    const e = email.trim();
    const m = message.trim();
    if (n.length < 1)      { setStatus('err'); setError('Add your name.'); return; }
    if (!EMAIL_RE.test(e)) { setStatus('err'); setError('Enter a valid email so we can reply.'); return; }
    if (m.length < 4)      { setStatus('err'); setError('Add a short message.'); return; }
    setStatus('sending'); setError('');
    try {
      const r = await fetch('/api/support', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: n, email: e, message: m, website: hpRef.current ? hpRef.current.value : '' }),
      });
      if (r.ok) { setStatus('ok'); setName(''); setEmail(''); setMessage(''); }
      else { setStatus('err'); setError('Could not send right now — try again, or email support@sub.earth directly.'); }
    } catch {
      setStatus('err'); setError('Could not send right now — try again, or email support@sub.earth directly.');
    }
  }

  const clearErr = () => { if (status === 'err') { setStatus(null); setError(''); } };

  return (
    <section id="support" style={{ padding: 'var(--section-y) var(--gutter)' }}>
      <div style={{ maxWidth: '820px', margin: '0 auto' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)', marginBottom: 'var(--space-12)' }}>
          <Eyebrow index="05">Support</Eyebrow>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 'var(--tr-tight)', lineHeight: 1.0, margin: 0, fontSize: 'var(--fs-d2)' }}>Get in touch</h2>
          <p style={{ margin: 0, maxWidth: '52ch', color: 'var(--text-tertiary)', fontSize: 'var(--fs-md)', lineHeight: 1.6 }}>
            Questions, bugs, or license help — send a message and it goes straight to us.
          </p>
        </div>

        {status === 'ok' ? (
          <div style={{ padding: 'var(--space-8)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--ring-strong)', textAlign: 'center', maxWidth: '560px' }}>
            <p style={{ margin: 0, fontFamily: 'var(--font-sans)', fontWeight: 500, fontSize: 'var(--fs-lg)', color: 'var(--text-primary)' }}>Thanks — we got your message.</p>
            <p style={{ margin: '8px 0 0', color: 'var(--text-tertiary)', fontSize: 'var(--fs-sm)' }}>We'll reply to your email shortly.</p>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)', maxWidth: '560px' }}>
            {/* honeypot: hidden from humans; bots fill it and get silently dropped */}
            <input ref={hpRef} type="text" name="website" tabIndex={-1} autoComplete="off" aria-hidden="true"
              style={{ position: 'absolute', left: '-9999px', width: '1px', height: '1px', opacity: 0 }} />
            <Input
              type="text"
              placeholder="your name"
              value={name}
              onChange={(e) => { setName(e.target.value); clearErr(); }}
            />
            <Input
              type="email"
              placeholder="your@email.com"
              value={email}
              onChange={(e) => { setEmail(e.target.value); clearErr(); }}
            />
            <textarea
              placeholder="How can we help?"
              value={message}
              onChange={(e) => { setMessage(e.target.value); clearErr(); }}
              rows={6}
              style={{
                width: '100%', resize: 'vertical', minHeight: '140px',
                padding: '14px 18px', border: 'none', outline: 'none',
                background: 'var(--fill-faint)', borderRadius: 'var(--radius-lg)',
                boxShadow: 'var(--ring-strong)',
                color: 'var(--text-primary)', fontFamily: 'var(--font-mono)',
                fontSize: 'var(--fs-sm)', letterSpacing: '0.04em', lineHeight: 1.6,
                boxSizing: 'border-box',
              }}
            />
            <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-5)', flexWrap: 'wrap' }}>
              <Button variant="primary" onClick={send} disabled={status === 'sending'}>
                {status === 'sending' ? 'Sending…' : 'Send message'}
              </Button>
              {status === 'err' && (
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--fs-2xs)', color: 'var(--text-tertiary)' }}>{error}</span>
              )}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

window.Support = Support;
window.__appReady.Support = true;
