// early-access-modal.jsx — Werkd isn't open for public sign-up yet. Every
// former "Start trial / Sign up" CTA now opens this instead: a simple email
// capture that POSTs to send-early-access.php (PHP mail(), works on
// Hostinger shared hosting with no extra setup — see that file's header).
// Open via window.dispatchEvent(new CustomEvent('werkd:open-early-access')).

function EarlyAccessModal() {
  const DA = window.DA;
  const [open, setOpen] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const [company, setCompany] = React.useState(''); // honeypot — left blank by humans
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const onOpen = () => { setOpen(true); setSent(false); setEmail(''); setError(''); setSubmitting(false); };
    window.addEventListener('werkd:open-early-access', onOpen);
    return () => window.removeEventListener('werkd:open-early-access', onOpen);
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 60);
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prevOverflow; clearTimeout(t); };
  }, [open]);

  if (!open) return null;

  const submit = async (e) => {
    e.preventDefault();
    if (!email.trim() || submitting) return;
    setSubmitting(true);
    setError('');
    try {
      const res = await fetch('send-early-access.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, company }),
      });
      const data = await res.json().catch(() => null);
      if (res.ok && data && data.ok) {
        setSent(true);
      } else {
        setError((data && data.error) || 'Something went wrong — please try again.');
      }
    } catch {
      setError('Could not reach the server — please try again, or email contact@werkd.pro directly.');
    } finally {
      setSubmitting(false);
    }
  };

  const modal = (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 9999,
        background: 'rgba(8,8,9,0.82)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
        fontFamily: DA ? DA.font : 'Inter, sans-serif',
      }}
    >
      <div style={{
        width: 'min(420px, 100%)', background: DA ? DA.ink : '#0a0a0b',
        border: '1px solid rgba(255,255,255,0.1)', borderRadius: 16,
        padding: '32px 28px', position: 'relative', color: '#fff',
        boxShadow: '0 32px 80px rgba(0,0,0,0.5)',
      }}>
        <button
          onClick={() => setOpen(false)} aria-label="Close"
          style={{
            position: 'absolute', top: 14, right: 14,
            width: 36, height: 36, borderRadius: '50%',
            background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.15)',
            color: '#fff', fontSize: 18, cursor: 'pointer', lineHeight: 1,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}
        >×</button>

        <h3 style={{ margin: '0 0 8px', fontSize: 24, fontWeight: 800, letterSpacing: '-0.02em' }}>
          Request early access
        </h3>

        {sent ? (
          <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.6, color: 'rgba(255,255,255,0.7)' }}>
            Thanks — we'll reach out as soon as werkd opens up.
          </p>
        ) : (
          <React.Fragment>
            <p style={{ margin: '0 0 18px', fontSize: 14.5, lineHeight: 1.6, color: 'rgba(255,255,255,0.6)' }}>
              Werkd isn't open for sign-ups yet. Leave your email and we'll let you know the moment it is.
            </p>
            <form onSubmit={submit} style={{ display: 'flex', gap: 8 }}>
              <input
                ref={inputRef}
                type="email" required placeholder="you@yourcompany.com" aria-label="Email address"
                value={email} onChange={(e) => setEmail(e.target.value)}
                style={{
                  flex: 1, minWidth: 0, height: 44, padding: '0 13px',
                  borderRadius: 6, border: '1px solid rgba(255,255,255,0.18)',
                  background: 'rgba(255,255,255,0.05)', color: '#fff', fontSize: 14,
                  fontFamily: 'inherit',
                }}
              />
              {/* Honeypot — hidden from sighted users and screen readers, off the
                  tab order. Bots that auto-fill every field trip it; humans never see it. */}
              <input
                type="text" tabIndex={-1} autoComplete="off" aria-hidden="true"
                value={company} onChange={(e) => setCompany(e.target.value)}
                style={{ position: 'absolute', width: 1, height: 1, opacity: 0, pointerEvents: 'none' }}
              />
              <button type="submit" disabled={submitting} style={{
                height: 44, padding: '0 18px', border: 'none', borderRadius: 6,
                background: (DA ? DA.brand : '#C4502A'), color: '#0a0a0b',
                fontSize: 14, fontWeight: 700, cursor: submitting ? 'default' : 'pointer', whiteSpace: 'nowrap',
                opacity: submitting ? 0.6 : 1,
              }}>{submitting ? 'Sending…' : 'Notify me'}</button>
            </form>
            {error && (
              <p style={{ margin: '10px 0 0', fontSize: 13, lineHeight: 1.5, color: '#ff9257' }}>{error}</p>
            )}
          </React.Fragment>
        )}
      </div>
    </div>
  );

  return ReactDOM.createPortal(modal, document.body);
}

window.EarlyAccessModal = EarlyAccessModal;
window.openEarlyAccess = () => window.dispatchEvent(new CustomEvent('werkd:open-early-access'));
