// Waitlist modal — validation, loading, success states.
const { useState: useStateW, useEffect: useEffectW, useRef: useRefW } = React;

function WaitlistModal({ open, onClose }) {
  const [step, setStep] = useStateW('form'); // form | loading | success
  const [form, setForm] = useStateW({ email: '', brand: '', gmv: '' });
  const [errors, setErrors] = useStateW({});
  const [shake, setShake] = useStateW(false);
  const firstRef = useRefW(null);

  useEffectW(() => {
    if (open) {
      setStep('form');
      setForm({ email: '', brand: '', gmv: '' });
      setErrors({});
      setTimeout(() => firstRef.current?.focus(), 300);
    }
  }, [open]);

  useEffectW(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  const validate = () => {
    const e = {};
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Enter a valid work email';
    if (form.brand.trim().length < 2) e.brand = 'Brand name required';
    if (!form.gmv) e.gmv = 'Select a range';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) {
      setShake(true);
      setTimeout(() => setShake(false), 500);
      return;
    }
    setStep('loading');
    setTimeout(() => setStep('success'), 1400);
  };

  if (!open) return null;

  return (
    <div
      role="dialog"
      aria-modal="true"
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(5, 5, 5, 0.78)',
        backdropFilter: 'blur(10px)',
        WebkitBackdropFilter: 'blur(10px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24,
        animation: 'fadeIn 300ms ease',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 520,
          background: 'var(--bg-2)',
          border: '1px solid var(--line-strong)',
          borderRadius: 2,
          overflow: 'hidden',
          animation: (shake ? 'shake' : 'slideUp') + ' 300ms ease',
          fontFamily: 'var(--font-display)',
        }}
      >
        {/* Header */}
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: '16px 24px',
          borderBottom: '1px solid var(--line)',
          fontFamily: 'var(--font-mono)',
          fontSize: 10,
          letterSpacing: '0.22em',
          textTransform: 'uppercase',
          color: 'var(--fg-dim)',
        }}>
          <span>ATTORA · OPERATOR APPLICATION</span>
          <button onClick={onClose} aria-label="Close" style={{
            background: 'transparent', border: 0, color: 'var(--fg-dim)',
            cursor: 'pointer', fontSize: 18, lineHeight: 1, padding: 0,
          }}>×</button>
        </div>

        {step === 'form' && (
          <form onSubmit={submit} style={{ padding: '32px 32px 28px' }}>
            <h3 style={{
              margin: 0, fontSize: 28, fontWeight: 500, letterSpacing: '-0.025em', lineHeight: 1.15,
              color: 'var(--fg)', textWrap: 'balance',
            }}>
              Apply to the beta.
            </h3>
            <p style={{
              margin: '10px 0 28px', fontSize: 14, lineHeight: 1.55, color: 'var(--fg-mute)',
              maxWidth: 400,
            }}>
              Tell us about your brand. A real human on our team will follow up within 48 hours.
            </p>

            <Field label="Work Email" error={errors.email}>
              <input
                ref={firstRef}
                type="email"
                value={form.email}
                onChange={(e) => setForm({ ...form, email: e.target.value })}
                placeholder="you@yourbrand.com"
                style={inputStyle}
              />
            </Field>

            <Field label="Brand" error={errors.brand}>
              <input
                type="text"
                value={form.brand}
                onChange={(e) => setForm({ ...form, brand: e.target.value })}
                placeholder="e.g. Huckberry"
                style={inputStyle}
              />
            </Field>

            <Field label="Annual GMV" error={errors.gmv}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
                {['<$1M', '$1–5M', '$5–20M', '$20M+'].map((r) => (
                  <button
                    key={r}
                    type="button"
                    onClick={() => setForm({ ...form, gmv: r })}
                    style={{
                      padding: '12px 8px',
                      background: form.gmv === r ? 'var(--accent)' : 'transparent',
                      color: form.gmv === r ? '#0A0A0A' : 'var(--fg-mute)',
                      border: '1px solid ' + (form.gmv === r ? 'var(--accent)' : 'var(--line-strong)'),
                      fontFamily: 'var(--font-mono)',
                      fontSize: 11,
                      letterSpacing: '0.08em',
                      cursor: 'pointer',
                      transition: 'all 160ms ease',
                      borderRadius: 2,
                    }}
                  >
                    {r}
                  </button>
                ))}
              </div>
            </Field>

            <button type="submit" className="btn-primary" style={{ marginTop: 20, width: '100%', justifyContent: 'center' }}>
              Submit Application
              <span className="arrow">→</span>
            </button>
            <p style={{ marginTop: 14, fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textAlign: 'center' }}>
              We read every application. No autoresponders.
            </p>
          </form>
        )}

        {step === 'loading' && (
          <div style={{ padding: '72px 32px', textAlign: 'center' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 12, color: 'var(--fg-dim)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase' }}>
              <span className="hb" style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} />
              Transmitting
            </div>
          </div>
        )}

        {step === 'success' && (
          <div style={{ padding: '56px 32px', textAlign: 'center' }}>
            <div style={{
              width: 56, height: 56, borderRadius: '50%',
              border: '1px solid var(--accent)',
              margin: '0 auto 24px',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--accent)', fontSize: 24,
            }}>✓</div>
            <h3 style={{ margin: 0, fontSize: 26, fontWeight: 500, letterSpacing: '-0.02em', color: 'var(--fg)' }}>
              Received.
            </h3>
            <p style={{ marginTop: 10, fontSize: 14, lineHeight: 1.55, color: 'var(--fg-mute)', maxWidth: 360, marginInline: 'auto' }}>
              We'll reach out within 48 hours from <span style={{ color: 'var(--accent)' }}>operators@attora.io</span>. In the meantime, watch your spam folder — our welcome doesn't always land clean.
            </p>
            <button onClick={onClose} className="btn-ghost" style={{ marginTop: 24 }}>
              Close
            </button>
          </div>
        )}
      </div>

      <style>{`
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes shake {
          0%, 100% { transform: translateX(0); }
          25% { transform: translateX(-6px); }
          75% { transform: translateX(6px); }
        }
      `}</style>
    </div>
  );
}

const inputStyle = {
  width: '100%',
  padding: '14px 16px',
  background: 'rgba(245, 243, 238, 0.02)',
  border: '1px solid var(--line-strong)',
  borderRadius: 2,
  color: 'var(--fg)',
  fontFamily: 'var(--font-display)',
  fontSize: 15,
  outline: 'none',
  transition: 'border-color 160ms ease, background 160ms ease',
};

function Field({ label, error, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        marginBottom: 8,
      }}>
        <label style={{
          fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em',
          textTransform: 'uppercase', color: 'var(--fg-dim)',
        }}>{label}</label>
        {error && (
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--accent)', letterSpacing: '0.08em' }}>
            ! {error}
          </span>
        )}
      </div>
      {children}
      <style>{`
        input:focus { border-color: var(--accent) !important; background: rgba(232, 168, 85, 0.04) !important; }
        input::placeholder { color: rgba(245, 243, 238, 0.25); }
      `}</style>
    </div>
  );
}

window.WaitlistModal = WaitlistModal;
