/* global React, SectionLabel */
const { useState: useStateContact, useEffect: useEffectContact, useRef: useRefContact } = React;

const TURNSTILE_SITEKEY = '0x4AAAAAACivvVC8vxuvDuRO';

function Contact() {
  const [name, setName] = useStateContact('');
  const [email, setEmail] = useStateContact('');
  const [msg, setMsg] = useStateContact('');
  const [submitting, setSubmitting] = useStateContact(false);
  const [status, setStatus] = useStateContact({ kind: 'idle', text: '' });
  const [videoFailed, setVideoFailed] = useStateContact(false);
  const widgetContainerRef = useRefContact(null);
  const widgetIdRef = useRefContact(null);
  const tokenRef = useRefContact('');

  useEffectContact(() => {
    const render = () => {
      if (!window.turnstile || !widgetContainerRef.current) return;
      if (widgetIdRef.current !== null) return;
      widgetIdRef.current = window.turnstile.render(widgetContainerRef.current, {
        sitekey: TURNSTILE_SITEKEY,
        theme: 'dark',
        callback: (token) => { tokenRef.current = token; },
        'expired-callback': () => { tokenRef.current = ''; },
        'error-callback': () => { tokenRef.current = ''; },
      });
    };
    if (window.turnstile) {
      render();
    } else {
      const prev = window.onloadTurnstileCallback;
      window.onloadTurnstileCallback = () => {
        if (typeof prev === 'function') prev();
        render();
      };
    }
    return () => {
      if (window.turnstile && widgetIdRef.current !== null) {
        try { window.turnstile.remove(widgetIdRef.current); } catch (_) { /* noop */ }
        widgetIdRef.current = null;
      }
    };
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const token = tokenRef.current;
    if (!token) {
      setStatus({ kind: 'error', text: 'Please wait for the CAPTCHA to load and complete it before submitting.' });
      return;
    }
    setSubmitting(true);
    setStatus({ kind: 'idle', text: '' });
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, email, message: msg, captchaToken: token }),
      });
      if (res.ok || res.status === 204) {
        setStatus({ kind: 'success', text: 'Thank you! We will be in touch shortly.' });
        setName('');
        setEmail('');
        setMsg('');
        tokenRef.current = '';
        if (window.turnstile && widgetIdRef.current !== null) {
          window.turnstile.reset(widgetIdRef.current);
        }
      } else {
        setStatus({ kind: 'error', text: 'Submission failed. Please try again or email us directly.' });
      }
    } catch (_) {
      setStatus({ kind: 'error', text: 'Network error. Please try again or email us directly.' });
    } finally {
      setSubmitting(false);
    }
  };
  const fieldStyle = {
    width: '100%',
    background: 'rgba(255, 255, 255, 0.12)',
    backdropFilter: 'blur(12px)',
    WebkitBackdropFilter: 'blur(12px)',
    border: 'none',
    borderRadius: 10,
    padding: '18px 10px 20px 15px',
    font: '400 16px/22px var(--font-body)',
    color: 'rgba(255,255,255,0.95)',
    outline: 'none',
  };

  return (
    <section id="contact" data-screen-label="Contact" style={{
      position: 'relative', background: '#0a0b0a',
      minHeight: '100svh',
      padding: 'clamp(48px, 8vh, 96px) clamp(20px, 4vw, 40px)',
      textAlign: 'center', overflow: 'hidden',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      boxSizing: 'border-box',
    }}>
      {!videoFailed && (
        <video autoPlay muted loop playsInline
               onError={() => setVideoFailed(true)}
               src="assets/background-image2.mp4"
               style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.85, zIndex: 0 }} />
      )}
      {videoFailed && (
        <img src="assets/static-image.jpg" alt=""
             style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.85, zIndex: 0 }} />
      )}
      <div style={{
        position: 'absolute', inset: 0, zIndex: 0, pointerEvents: 'none',
        background: 'linear-gradient(150deg, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.2) 60%)',
      }} />
      <div style={{ position: 'relative', zIndex: 1, maxWidth: 1120, width: '100%', margin: '0 auto' }}>
        <SectionLabel variant="dark" style={{ marginLeft: 'auto', marginRight: 'auto', marginBottom: 28, display: 'flex' }}>Contact</SectionLabel>
        <h2 style={{ font: '400 clamp(24px, 3.6vw, 36px)/1.15 var(--font-display)', color: '#FFF', margin: '0 0 8px 0' }}>
          Creating bespoke together.
        </h2>
        <p style={{ font: '400 clamp(24px, 3.6vw, 36px)/1.15 var(--font-display)', color: 'rgba(255, 255, 255, 0.50)', margin: '0 0 32px 0' }}>
          Let's discuss how LexPars can create a bespoke data platform for your Single Family Office
        </p>
        <p style={{ color: 'rgba(255,255,255,0.5)', fontSize: 18, margin: '0 0 8px 0' }}>—</p>
        <p style={{
          font: '400 clamp(15px, 1.6vw, 18px)/1.4 var(--font-body)', color: '#FFF',
          margin: '0 auto 32px', maxWidth: 580,
        }}>
          For general enquiries and demo requests, email <a href="mailto:operations@lexpars.com" style={{ color: '#FFF', textDecoration: 'underline' }}>operations@lexpars.com</a>.
        </p>

        <form onSubmit={handleSubmit}
              style={{ textAlign: 'left', maxWidth: 668, width: '100%', margin: '0 auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 10, marginBottom: 10 }}>
            <div style={{ position: 'relative' }}>
              <input name="Name" value={name} onChange={(e) => setName(e.target.value)}
                     placeholder="Name" style={{ ...fieldStyle, paddingRight: 40 }} />
              {name.trim().length > 2 && (
                <img src="assets/icon-check.svg" alt=""
                     style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', width: 22, height: 22, pointerEvents: 'none' }} />
              )}
            </div>
            <input type="email" name="Email" value={email} onChange={(e) => setEmail(e.target.value)}
                   placeholder="Email Address" style={fieldStyle} />
          </div>
          <textarea name="Message" value={msg} onChange={(e) => setMsg(e.target.value)}
                    placeholder="Message"
                    style={{ ...fieldStyle, minHeight: 140, resize: 'vertical', marginBottom: 20, display: 'block' }} />
          <div ref={widgetContainerRef} style={{ marginBottom: 16 }} />
          <button type="submit"
            disabled={submitting}
            onMouseEnter={(e) => { if (!submitting) { e.currentTarget.style.background = '#fff'; e.currentTarget.style.color = '#283836'; } }}
            onMouseLeave={(e) => { if (!submitting) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = '#FFF'; } }}
            style={{
              width: '100%', height: 50, padding: '0 15px',
              background: 'transparent',
              border: '1px solid #FFF', borderRadius: 10,
              backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
              font: '400 16px/22px var(--font-body)',
              color: '#FFF', cursor: submitting ? 'default' : 'pointer',
              opacity: submitting ? 0.7 : 1,
              transition: 'background 0.15s ease, color 0.15s ease',
            }}>
            {submitting ? 'Submitting…' : 'Submit Form'}
          </button>
          {status.kind !== 'idle' && (
            <p style={{
              marginTop: 12,
              font: '400 14px/1.4 var(--font-body)',
              color: status.kind === 'error' ? '#ff9b9b' : 'rgba(255,255,255,0.85)',
            }}>{status.text}</p>
          )}
        </form>
      </div>
    </section>
  );
}

window.Contact = Contact;
