// ContactPage.jsx — PROYECTO Contact

const ContactPage = () => {
  const cmsContent = (typeof useCMSContent === 'function') ? useCMSContent() : null;
  const contact = (cmsContent && cmsContent.contact) || {
    email: 'BOOKINGS@PROYECTO.LA',
    subtitle: 'PRIVATE FACILITY · BY APPOINTMENT ONLY'
  };
  const [name, setName]       = React.useState('');
  const [email, setEmail]     = React.useState('');
  const [message, setMessage] = React.useState('');
  const [honeypot, setHoneypot] = React.useState(''); // bots fill this; humans never see it
  const [focused, setFocused] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [sent, setSent]       = React.useState(false);
  const [error, setError]     = React.useState('');
  const [visible, setVisible] = React.useState(false);
  const [isMobile, setIsMobile] = React.useState(!!window.__IS_MOBILE);

  React.useEffect(() => {
    if (typeof window.__onMobileChange === 'function') {
      return window.__onMobileChange(setIsMobile);
    }
  }, []);

  React.useEffect(() => {
    const t = setTimeout(() => setVisible(true), 50);
    return () => clearTimeout(t);
  }, []);

  // Basic email shape check — same regex Chrome uses for type="email" inputs.
  // Stops typos like "alice@gmail" from getting submitted; doesn't replace
  // proper validation (Formspree validates server-side too).
  const isValidEmail = (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);

  const handleSend = async () => {
    if (sending || sent) return;
    if (!name.trim() || !email.trim() || !message.trim()) return;
    // Enforce length caps server-side-style — a determined attacker who edits
    // the DOM to remove maxLength can't bypass these. Bounds match the
    // maxLength attributes on the inputs below.
    if (name.length > 100 || email.length > 200 || message.length > 5000) {
      setError('Input too long. Trim and try again.');
      setTimeout(() => setError(''), 3000);
      return;
    }
    if (!isValidEmail(email.trim())) {
      setError('Enter a valid email address.');
      setTimeout(() => setError(''), 3000);
      return;
    }

    setError('');
    setSending(true);

    try {
      const res = await fetch('https://formspree.io/f/mpqkvoln', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: name.trim(),
          email: email.trim(),
          message: message.trim(),
          // Subject line for the inbox notification — overrides Formspree's default.
          _subject: 'PROYECTO — New inquiry from ' + name.trim(),
          // Honeypot: Formspree silently drops the submission if filled.
          // Hidden from humans via CSS; bots that auto-fill all fields trip it.
          _gotcha: honeypot,
        }),
      });

      if (res.ok) {
        setSending(false);
        setSent(true);
        setTimeout(() => {
          setName(''); setEmail(''); setMessage(''); setSent(false);
        }, 2600);
      } else {
        // Formspree returned a non-2xx — surface a useful fallback.
        setSending(false);
        setError('Transmission failed. Email INFO@PROYECTO.LA directly.');
        setTimeout(() => setError(''), 6000);
      }
    } catch (_) {
      // Network error / offline / blocked — same fallback.
      setSending(false);
      setError('Transmission failed. Email INFO@PROYECTO.LA directly.');
      setTimeout(() => setError(''), 6000);
    }
  };

  return (
    <div style={{ ...cs.page, opacity: visible ? 1 : 0 }}>

      {/* ── Title ── */}
      <div style={{
        ...cs.titleBlock,
        ...(isMobile ? { padding: '28px 20px 0' } : {}),
      }}>
        <div style={{
          ...cs.bgWord,
          ...(isMobile ? { fontSize: 64, top: 14, left: 16 } : {}),
        }}>CONTACT</div>
        <div style={{
          ...cs.titleRow,
          ...(isMobile ? { flexDirection: 'column', alignItems: 'flex-start', gap: 18, paddingBottom: 18 } : {}),
        }}>
          <div style={{
            ...cs.title,
            ...(isMobile ? { fontSize: 'clamp(28px, 9vw, 48px)', whiteSpace: 'nowrap' } : {}),
          }}>CONTACT</div>
          <div style={{
            ...cs.titleRight,
            ...(isMobile ? { textAlign: 'left', paddingBottom: 0 } : {}),
          }}>
            <div style={{...cs.email, color: contact.emailColor || 'var(--accent, #e6351e)',
              ...(isMobile ? { fontSize: 12, wordBreak: 'break-all' } : {})}}>{contact.email}</div>
            <div style={{...cs.subtitle,
              ...(isMobile ? { fontSize: 10 } : {})}}>{contact.subtitle}</div>
          </div>
        </div>
        <div style={cs.titleRule} />
      </div>

      {/* ── Form ── */}
      <div style={{
        ...cs.formWrap,
        ...(isMobile ? { padding: '28px 20px' } : {}),
      }}>

        <div style={{...cs.field, ...(isMobile ? { marginBottom: 28 } : {})}}>
          <label style={cs.label}>NAME <span style={cs.arrow}>&gt;</span></label>
          <div style={{ ...cs.inputWrap, borderBottomColor: focused === 'name' ? 'var(--accent, #e6351e)' : '#111' }}>
            <input
              type="text" value={name}
              onChange={(e) => setName(e.target.value)}
              onFocus={() => setFocused('name')} onBlur={() => setFocused('')}
              maxLength={100}
              style={{...cs.input, ...(isMobile ? { fontSize: 16 } : {})}} disabled={sending || sent}
            />
          </div>
        </div>

        <div style={{...cs.field, ...(isMobile ? { marginBottom: 28 } : {})}}>
          <label style={cs.label}>EMAIL <span style={cs.arrow}>&gt;</span></label>
          <div style={{ ...cs.inputWrap, borderBottomColor: focused === 'email' ? 'var(--accent, #e6351e)' : '#111' }}>
            <input
              type="email" value={email}
              onChange={(e) => setEmail(e.target.value)}
              onFocus={() => setFocused('email')} onBlur={() => setFocused('')}
              autoComplete="email"
              autoCapitalize="off" autoCorrect="off" spellCheck={false}
              maxLength={200}
              style={{...cs.input, ...(isMobile ? { fontSize: 16 } : {})}} disabled={sending || sent}
            />
          </div>
        </div>

        <div style={{...cs.field, ...(isMobile ? { marginBottom: 28 } : {})}}>
          <label style={cs.label}>MESSAGE <span style={cs.arrow}>&gt;</span></label>
          <div style={{ ...cs.textareaWrap, borderColor: focused === 'msg' ? 'var(--accent, #e6351e)' : '#111' }}>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              onFocus={() => setFocused('msg')} onBlur={() => setFocused('')}
              maxLength={5000}
              style={{...cs.textarea, ...(isMobile ? { fontSize: 16 } : {})}} rows={isMobile ? 5 : 6} disabled={sending || sent}
            />
          </div>
        </div>

        {/* Honeypot — hidden from real users, attractive to dumb spam bots.
            CSS hides it from sighted users; tabIndex/aria-hidden hide it from
            keyboard/AT users. If a submission has this field filled, Formspree
            silently drops it as spam. */}
        <div style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, overflow: 'hidden' }} aria-hidden="true">
          <label>
            Leave this field empty
            <input
              type="text" name="_gotcha" tabIndex={-1} autoComplete="off"
              value={honeypot}
              onChange={(e) => setHoneypot(e.target.value)}
            />
          </label>
        </div>

        <div style={{
          ...cs.sendRow,
          ...(isMobile ? { flexDirection: 'column', alignItems: 'flex-start', gap: 16 } : {}),
        }}>
          <button
            onClick={handleSend}
            onMouseEnter={(e) => { if (!isMobile && !sending && !sent) { e.currentTarget.style.background = 'var(--accent, #e6351e)'; e.currentTarget.style.color = '#000'; } }}
            onMouseLeave={(e) => { if (!isMobile && !sending && !sent) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--accent, #e6351e)'; } }}
            style={{
              ...cs.sendBtn,
              ...(isMobile ? { padding: '15px 36px', fontSize: 12, cursor: 'pointer', width: '100%' } : {}),
              ...((sending || sent) ? { opacity: 0.7 } : {}),
            }}
            disabled={sending || sent}
          >
            {sent ? 'SENT ▸' : sending ? 'SENDING ▸' : 'SEND ▸'}
          </button>
          {sent && (
            <div style={cs.sentMsg}>
              transmission received. response within 48h.<span style={cs.miniCursor} />
            </div>
          )}
          {error && !sent && (
            <div style={cs.sentMsg}>
              {error}<span style={cs.miniCursor} />
            </div>
          )}
        </div>
      </div>

      <div style={{
        ...cs.footerBar,
        ...(isMobile ? { padding: '20px 20px 32px', fontSize: 9 } : {}),
      }}>
        <span>PROYECTO</span>
        <span style={{ color: '#2a2a2a' }}>LOS ANGELES · {(cmsContent && cmsContent.global && cmsContent.global.footerYear) || '2025'}</span>
      </div>
    </div>
  );
};

const cs = {
  page: {
    minHeight: '100vh', background: '#050402',
    paddingTop: 48, fontFamily: "'Share Tech Mono', monospace",
    color: '#fff', transition: 'opacity 200ms linear',
  },
  titleBlock: {
    padding: '48px 48px 0',
    position: 'relative', overflow: 'hidden',
  },
  bgWord: {
    position: 'absolute', top: -10, left: 28,
    fontFamily: "'Cindie2', sans-serif",
    fontSize: 180, fontWeight: 700,
    color: 'rgba(255,255,255,0.02)',
    lineHeight: 1, letterSpacing: '-0.02em',
    pointerEvents: 'none', userSelect: 'none', zIndex: 0,
  },
  titleRow: {
    display: 'flex', alignItems: 'flex-end',
    justifyContent: 'space-between',
    position: 'relative', zIndex: 1,
    paddingBottom: 24,
  },
  title: {
    fontFamily: "'Cindie2', sans-serif",
    fontSize: 64, fontWeight: 600,
    letterSpacing: '0.02em', textTransform: 'uppercase',
    color: '#fff', lineHeight: 1,
  },
  titleRight: { textAlign: 'right', paddingBottom: 6 },
  email: {
    fontSize: 13, color: 'var(--accent, #e6351e)',
    letterSpacing: '0.18em', textTransform: 'uppercase',
    marginBottom: 6,
  },
  subtitle: {
    fontSize: 11, color: '#444',
    letterSpacing: '0.18em', textTransform: 'uppercase',
    fontFamily: "'Share Tech Mono', monospace",
  },
  titleRule: {
    height: 1,
    background: 'linear-gradient(90deg, var(--accent, #e6351e) 0%, #333 40%, transparent 100%)',
    position: 'relative', zIndex: 1,
  },
  formWrap: {
    padding: '48px 48px',
    maxWidth: 680,
  },
  field: { marginBottom: 40 },
  label: {
    display: 'block', fontSize: 11, color: '#555',
    letterSpacing: '0.24em', textTransform: 'uppercase', marginBottom: 12,
  },
  arrow: { color: 'var(--accent, #e6351e)', marginLeft: 4 },
  inputWrap: {
    display: 'flex', alignItems: 'center',
    borderBottom: '1px solid',
    padding: '8px 0',
    transition: 'border-color 120ms linear',
  },
  input: {
    flex: 1, background: 'transparent', border: 'none', outline: 'none',
    color: '#fff', fontFamily: "'Neogrotesk Pro', 'Helvetica Neue', sans-serif",
    fontSize: 15, letterSpacing: '0.04em', padding: 0,
    caretColor: 'var(--accent, #e6351e)',
  },
  textareaWrap: {
    border: '1px solid', padding: '12px 14px',
    transition: 'border-color 120ms linear',
  },
  textarea: {
    width: '100%', background: 'transparent', border: 'none', outline: 'none',
    color: '#fff', fontFamily: "'Neogrotesk Pro', 'Helvetica Neue', sans-serif",
    fontSize: 15, letterSpacing: '0.02em', lineHeight: 1.7,
    padding: 0, resize: 'vertical',
    caretColor: 'var(--accent, #e6351e)',
  },
  blockCursor: {
    display: 'inline-block', width: 8, height: 15,
    background: 'var(--accent, #e6351e)', animation: 'blink 1.1s step-end infinite', marginLeft: 2,
  },
  miniCursor: {
    display: 'inline-block', width: 7, height: 12,
    background: '#8A9099', animation: 'blink 1.1s step-end infinite',
    marginLeft: 6, verticalAlign: 'middle',
  },
  sendRow: { display: 'flex', alignItems: 'center', gap: 32, marginTop: 8 },
  sendBtn: {
    background: 'transparent', border: '1px solid var(--accent, #e6351e)',
    fontFamily: "'Share Tech Mono', monospace",
    fontSize: 13, letterSpacing: '0.20em', textTransform: 'uppercase',
    color: 'var(--accent, #e6351e)', padding: '13px 28px',
    transition: 'background 120ms linear, color 120ms linear',
    borderRadius: 0, cursor: 'none',
  },
  sentMsg: {
    fontSize: 13, color: 'var(--accent, #e6351e)',
    letterSpacing: '0.08em', animation: 'flicker 0.3s linear',
  },
  footerBar: {
    padding: '24px 48px 40px', marginTop: 'auto',
    display: 'flex', justifyContent: 'space-between',
    fontSize: 11, color: '#222', letterSpacing: '0.18em', textTransform: 'uppercase',
    borderTop: '1px solid #0a0a0a',
  },
};

Object.assign(window, { ContactPage });
