// MobileRegister.jsx — mobile-optimized terminal registration with Turnstile captcha
// SECURITY: same validation + generic errors as desktop. No user enumeration.

const MobileRegister = ({ onRegistered, onSwitchToLogin }) => {
  const [form, setForm] = React.useState({ email: '', name: '', handle: '', password: '', confirm: '' });
  const [agree, setAgree] = React.useState(false);
  const [marketing, setMarketing] = React.useState(true);
  const [phase, setPhase] = React.useState('idle'); // idle | submitting | success
  const [err, setErr] = React.useState(null);
  const [logLines, setLogLines] = React.useState([]);
  const [newUser, setNewUser] = React.useState(null);
  const [turnstileToken, setTurnstileToken] = React.useState(null);
  const turnstileWidgetId = React.useRef(null);

  const set = (k, v) => { setForm((f) => ({ ...f, [k]: v })); setErr(null); };

  const passwordStrength = (pw) => {
    if (!pw) return 0;
    let s = 0;
    if (pw.length >= 8) s++;
    if (pw.length >= 12) s++;
    if (pw.length >= 16) s++;
    if (/[A-Z]/.test(pw) && /[a-z]/.test(pw)) s++;
    if (/[0-9]/.test(pw)) s++;
    if (/[^A-Za-z0-9]/.test(pw)) s++;
    return Math.min(s, 5);
  };
  const strength = passwordStrength(form.password);
  const strengthLabels = ['BRITTLE', 'WEAK', 'OKAY', 'STRONG', 'HARDENED', 'FORTRESS'];
  const strengthColors = ['#FF3344', '#FF3344', '#FF8C42', '#FFD23F', '#00FF41', '#00FF41'];

  // Turnstile widget lifecycle
  React.useEffect(() => {
    if (phase === 'idle' && window.turnstile) {
      if (turnstileWidgetId.current != null) {
        try { window.turnstile.remove(turnstileWidgetId.current); } catch (e) { /* noop */ }
        turnstileWidgetId.current = null;
      }
      const el = document.getElementById('m-register-turnstile');
      if (!el) return;
      turnstileWidgetId.current = window.turnstile.render('#m-register-turnstile', {
        sitekey: '0x4AAAAAADT5ebjsA6gd7yaa',
        theme: 'dark',
        callback: (token) => setTurnstileToken(token),
        'expired-callback': () => setTurnstileToken(null),
        'error-callback': () => setTurnstileToken(null),
      });
    }
    return () => {
      if (turnstileWidgetId.current != null) {
        try { window.turnstile.remove(turnstileWidgetId.current); } catch (e) { /* noop */ }
        turnstileWidgetId.current = null;
      }
    };
  }, [phase]);

  const submit = async (e) => {
    e.preventDefault();
    if (phase !== 'idle') return;

    if (!form.email.includes('@') || form.email.length < 5) return setErr('// invalid email format.');
    if (!form.name.trim() || form.name.trim().length < 2) return setErr('// name is required (first and last).');
    if (!form.handle.match(/^[a-zA-Z0-9_]{3,32}$/)) return setErr('// handle must be 3-32 alphanumeric chars or underscore.');
    if (form.password.length < 12) return setErr('// password must be at least 12 characters.');
    if (form.password !== form.confirm) return setErr('// passwords do not match.');
    if (strength < 3) return setErr('// password too weak. add length, mix cases + symbols.');
    if (!agree) return setErr('// must accept terms to continue.');
    if (form.email.length > 320 || form.handle.length > 32 || form.name.length > 128) return setErr('// payload too large.');
    if (!turnstileToken && window.OBC_API.mode !== 'mock') return setErr('// captcha verification required.');

    setErr(null);
    setPhase('submitting');

    const lines = [
      { t: 100,  text: 'validating email ............. [ OK ]' },
      { t: 400,  text: 'checking handle .............. [ OK ]' },
      { t: 800,  text: 'hashing password (argon2id) .. [ OK ]' },
      { t: 1300, text: 'provisioning record .......... [ OK ]' },
      { t: 1700, text: 'generating recovery codes .... [ OK ]' },
      { t: 2100, text: 'syncing to shopify ........... [ OK ]' },
      { t: 2400, text: 'issuing session token ........ [ OK ]' },
    ];

    const ANIM_DURATION = 2800;
    setLogLines([]);
    lines.forEach((l) => { setTimeout(() => setLogLines((prev) => [...prev, l]), l.t); });

    const apiPromise = window.OBC_API.register(
      { email: form.email, name: form.name.trim(), handle: form.handle, password: form.password, marketing },
      turnstileToken,
    );
    const animPromise = new Promise((resolve) => setTimeout(resolve, ANIM_DURATION));

    try {
      const [provisioned] = await Promise.all([apiPromise, animPromise]);
      setNewUser(provisioned);
      setPhase('success');
      if (!provisioned._needs_activation) {
        setTimeout(() => onRegistered(provisioned), 2200);
      }
    } catch (error) {
      setPhase('idle');
      setTurnstileToken(null);
      const code = error.code || error.message || '';
      if (code === 'EMAIL_TAKEN') { setErr('// email already registered. try logging in instead.'); }
      else if (code === 'PASSWORD_INVALID') { setErr('// password rejected by server' + (error.detail ? ': ' + error.detail : '.')); }
      else if (code === 'CAPTCHA_FAILED') { setErr('// captcha verification failed. reload and try again.'); }
      else { setErr('// registration failed.' + (error.detail ? ' ' + error.detail : ' try again.')); }
    }
  };

  const isMock = window.OBC_API.mode === 'mock';
  const canSubmit = turnstileToken || isMock;

  return (
    <section style={{ padding: '24px 16px 60px', maxWidth: 480, margin: '0 auto' }}>
      {phase === 'idle' && (
        <form onSubmit={submit}>
          <div style={{ fontSize: 11, color: '#00FF41', letterSpacing: '0.22em', marginBottom: 8 }}>$ ./register --new-operator</div>
          <h2 style={{ fontSize: 26, fontWeight: 800, color: '#FFF', letterSpacing: '0.04em', margin: '0 0 6px' }}>ENLIST</h2>
          <p style={{ fontSize: 12, color: '#BFBFBF', lineHeight: 1.6, letterSpacing: '0.04em', margin: '0 0 24px' }}>
            // create an account. unlock order history, subscriptions, and early drops.
          </p>

          <MRegField label="EMAIL" value={form.email} onChange={(v) => set('email', v)} type="email" placeholder="operator@target.coffee" autoFocus autoComplete="email" />
          <MRegField label="NAME" value={form.name} onChange={(v) => set('name', v)} placeholder="first last" hint="// real name — for shipping and receipts." autoComplete="name" />
          <MRegField label="HANDLE" value={form.handle} onChange={(v) => set('handle', v)} placeholder="op1337" hint="// display name. 3-32 chars." autoComplete="username" />
          <MRegField label="PASSWORD" value={form.password} onChange={(v) => set('password', v)} type="password" placeholder="min 12 chars" autoComplete="new-password" />

          {/* strength meter */}
          {form.password && (
            <div style={{ marginTop: -6, marginBottom: 12 }}>
              <div style={{ display: 'flex', gap: 3 }}>
                {[1, 2, 3, 4, 5].map((i) => (
                  <div key={i} style={{
                    flex: 1, height: 4,
                    background: i <= strength ? strengthColors[strength] : 'rgba(255,255,255,0.14)',
                    transition: 'background 120ms',
                  }}></div>
                ))}
              </div>
              <div style={{ marginTop: 4, fontSize: 10, letterSpacing: '0.2em', color: strengthColors[strength], fontWeight: 700 }}>
                [{strengthLabels[strength]}]
              </div>
            </div>
          )}

          <MRegField label="CONFIRM PASSWORD" value={form.confirm} onChange={(v) => set('confirm', v)} type="password" placeholder="re-enter to confirm" autoComplete="new-password" />

          <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginTop: 14, cursor: 'pointer' }}>
            <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} style={{ marginTop: 3, accentColor: '#00FF41', minWidth: 18, minHeight: 18 }} />
            <span style={{ fontSize: 12, color: '#E0E0E0', lineHeight: 1.6, letterSpacing: '0.03em' }}>
              i agree to the <span style={{ color: '#00FF41' }}>terms</span> and <span style={{ color: '#00FF41' }}>privacy policy</span>.
            </span>
          </label>
          <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginTop: 10, cursor: 'pointer' }}>
            <input type="checkbox" checked={marketing} onChange={(e) => setMarketing(e.target.checked)} style={{ marginTop: 3, accentColor: '#00FF41', minWidth: 18, minHeight: 18 }} />
            <span style={{ fontSize: 12, color: '#BFBFBF', lineHeight: 1.6, letterSpacing: '0.03em' }}>
              send me new drop alerts. (~1/month.)
            </span>
          </label>

          {/* Turnstile */}
          <div style={{ margin: '16px 0', padding: '12px', border: '1px dashed rgba(255,255,255,0.22)', background: '#0A0A0A' }}>
            <div style={{ fontSize: 10, letterSpacing: '0.2em', color: '#9A9A9A', marginBottom: 8 }}>// CAPTCHA VERIFICATION</div>
            <div id="m-register-turnstile"></div>
          </div>

          {err && (
            <div role="alert" style={{ marginTop: 14, padding: '10px 14px', border: '1px solid #FF3344', color: '#FF3344', fontSize: 12, letterSpacing: '0.06em' }}>
              {err}
            </div>
          )}

          <button type="submit" disabled={!canSubmit} style={{
            width: '100%', marginTop: 20, background: canSubmit ? '#00FF41' : '#3A3A3A',
            color: '#000', border: '1px solid ' + (canSubmit ? '#00FF41' : '#3A3A3A'),
            padding: '16px', fontFamily: 'inherit', fontWeight: 800, fontSize: 14,
            letterSpacing: '0.22em', cursor: canSubmit ? 'pointer' : 'not-allowed',
            borderRadius: 2, opacity: canSubmit ? 1 : 0.5, minHeight: 52,
          }}>{'>'} ./create-account</button>

          <div style={{ marginTop: 16, textAlign: 'center' }}>
            <span onClick={onSwitchToLogin} style={{ fontSize: 12, color: '#00FF41', cursor: 'pointer', letterSpacing: '0.1em' }}>
              $ ./login
            </span>
          </div>
        </form>
      )}

      {phase === 'submitting' && (
        <div style={{ color: '#00FF41', fontSize: 13, lineHeight: 1.9, letterSpacing: '0.04em', padding: '40px 0' }}>
          <div>$ ./register --provision</div>
          {logLines.map((l, i) => (
            <div key={i}>&nbsp;&nbsp;{l.text}</div>
          ))}
          {logLines.length < 7 && (
            <div style={{ marginTop: 8, color: '#BFBFBF' }}>// provisioning<span className="m-provision-cursor"></span></div>
          )}
        </div>
      )}

      {phase === 'success' && newUser && (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <div style={{ fontSize: 11, color: '#00FF41', letterSpacing: '0.22em', marginBottom: 14 }}>$ whoami</div>
          <div style={{ fontSize: 14, color: '#BFBFBF', letterSpacing: '0.04em', lineHeight: 1.8 }}>
            <div>NAME: <span style={{ color: '#FFF', fontWeight: 700 }}>{newUser.name}</span></div>
            <div>HANDLE: <span style={{ color: '#00FF41', fontWeight: 700 }}>{newUser.handle}</span></div>
            <div>EMAIL: <span style={{ color: '#00E5FF', fontWeight: 700 }}>{newUser.email}</span></div>
            <div>TIER: <span style={{ color: '#FFD23F', fontWeight: 700 }}>{newUser.tier}</span></div>
          </div>
          <div style={{ marginTop: 24 }}>
            <span className="m-reg-granted">[ ACCOUNT PROVISIONED ]</span>
          </div>
          {newUser._needs_activation ? (
            <div style={{ marginTop: 18 }}>
              <div style={{ fontSize: 13, color: '#FFD23F', letterSpacing: '0.08em', lineHeight: 1.7 }}>
                // check your email to activate.
              </div>
              <span onClick={onSwitchToLogin} style={{ display: 'inline-block', marginTop: 14, fontSize: 12, color: '#00FF41', letterSpacing: '0.15em', cursor: 'pointer', textDecoration: 'underline' }}>
                ./login
              </span>
            </div>
          ) : (
            <div style={{ marginTop: 18, fontSize: 12, color: '#BFBFBF', letterSpacing: '0.15em' }}>
              routing to /account<span className="m-provision-cursor"></span>
            </div>
          )}
        </div>
      )}

      <style>{`
        .m-reg-granted {
          display: inline-block;
          background: #00FF41; color: #000;
          padding: 10px 20px;
          font-size: 16px; font-weight: 800; letter-spacing: 0.22em;
          box-shadow: 0 0 24px rgba(0,255,65,0.6);
          animation: mRegFlash 160ms steps(2) 5;
        }
        @keyframes mRegFlash {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.2; }
        }
        .m-provision-cursor::after {
          content: '█';
          animation: mProvBlink 1s steps(2) infinite;
          margin-left: 4px;
          color: #00FF41;
        }
        @keyframes mProvBlink { to { opacity: 0; } }
      `}</style>
    </section>
  );
};

const MRegField = ({ label, value, onChange, type = 'text', placeholder, autoFocus, hint, autoComplete }) => (
  <div style={{ marginBottom: 14 }}>
    <div style={{ fontSize: 11, letterSpacing: '0.22em', color: '#E0E0E0', fontWeight: 700, marginBottom: 6 }}>{'>'} {label}</div>
    <input
      type={type}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      autoFocus={autoFocus}
      autoComplete={autoComplete}
      maxLength={type === 'password' ? 256 : 320}
      style={{
        width: '100%', background: '#0A0A0A', border: '1px solid rgba(255,255,255,0.28)',
        color: '#FFF', fontFamily: 'inherit', fontSize: 16, padding: '14px', borderRadius: 2,
        minHeight: 48,
      }}
      onFocus={(e) => { e.target.style.borderColor = '#00FF41'; e.target.style.boxShadow = '0 0 0 1px #00FF41'; }}
      onBlur={(e) => { e.target.style.borderColor = 'rgba(255,255,255,0.28)'; e.target.style.boxShadow = 'none'; }}
    />
    {hint && <div style={{ marginTop: 4, fontSize: 10, color: '#9A9A9A', letterSpacing: '0.05em' }}>{hint}</div>}
  </div>
);

window.MobileRegister = MobileRegister;
