// MobileResetPassword.jsx — mobile password reset form
// SECURITY: same generic error messages. No enumeration.

const MobileResetPassword = ({ resetUrl, onLoggedIn, onSwitchToLogin }) => {
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [phase, setPhase] = React.useState('idle'); // idle | submitting | success | error
  const [err, setErr] = React.useState(null);
  const [turnstileToken, setTurnstileToken] = React.useState(null);
  const turnstileWidgetId = React.useRef(null);

  // Render Turnstile widget
  React.useEffect(() => {
    if (phase !== 'idle' || !window.turnstile) return;
    if (turnstileWidgetId.current != null) {
      try { window.turnstile.remove(turnstileWidgetId.current); } catch (e) { /* noop */ }
      turnstileWidgetId.current = null;
    }
    const el = document.getElementById('m-reset-turnstile');
    if (!el) return;
    turnstileWidgetId.current = window.turnstile.render('#m-reset-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();
    setErr(null);

    if (!resetUrl) { setErr('// invalid reset link. request a new one.'); setPhase('error'); return; }
    if (!password || !confirm) { setErr('// both fields required.'); return; }
    if (password.length < 8) { setErr('// password must be at least 8 characters.'); return; }
    if (password !== confirm) { setErr('// passwords do not match.'); return; }
    if (!turnstileToken && window.OBC_API.mode !== 'mock') { setErr('// complete captcha verification first.'); return; }

    setPhase('submitting');
    setErr('// resetting password...');

    try {
      const data = await window.OBC_API.resetPassword(resetUrl, password, turnstileToken);
      if (data.ok && data.customer) {
        setPhase('success');
        setErr(null);
        setTimeout(() => onLoggedIn(data.customer), 2000);
      } else if (data.ok) {
        setPhase('success');
        setErr(null);
      } else if (data.error === 'RESET_EXPIRED') {
        setPhase('error');
        setErr('// reset link has expired. request a new one.');
      } else if (data.error === 'PASSWORD_INVALID') {
        setPhase('idle');
        setErr('// ' + (data.detail || 'password does not meet requirements.'));
      } else {
        setPhase('error');
        setErr('// ' + (data.detail || 'reset failed. request a new link.'));
      }
    } catch (ex) {
      setPhase('error');
      setErr('// something went wrong. try requesting a new reset link.');
    }

    if (window.turnstile && turnstileWidgetId.current != null) {
      window.turnstile.reset(turnstileWidgetId.current);
    }
    setTurnstileToken(null);
  };

  const inputStyle = {
    width: '100%', background: '#0A0A0A', border: '1px solid rgba(255,255,255,0.28)',
    color: '#FFF', fontFamily: 'inherit', fontSize: 16, padding: '12px 14px', borderRadius: 2,
    boxSizing: 'border-box',
  };

  return (
    <section style={{ padding: '24px 16px 100px' }}>
      {/* terminal header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', background: '#0A0A0A', border: '1px solid rgba(255,255,255,0.22)' }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#FF3344' }}></span>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#FFD23F' }}></span>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#00FF41' }}></span>
        <span style={{ marginLeft: 8, fontSize: 13, color: '#BFBFBF', letterSpacing: '0.08em' }}>operator@brew-co</span>
      </div>

      <div style={{ border: '1px solid rgba(255,255,255,0.22)', borderTop: 'none', padding: '24px 16px', background: '#000' }}>
        {/* SUCCESS */}
        {phase === 'success' && (
          <div>
            <div style={{ fontSize: 14, color: '#00FF41', letterSpacing: '0.18em', marginBottom: 8 }}>$ ./auth --reset</div>
            <h2 style={{ fontSize: 24, fontWeight: 800, color: '#00FF41', letterSpacing: '0.04em', margin: '0 0 12px' }}>PASSWORD UPDATED</h2>
            <p style={{ fontSize: 15, color: '#BFBFBF', lineHeight: 1.5, letterSpacing: '0.04em', margin: '0 0 20px' }}>
              // credentials rotated. redirecting...
            </p>
            <a onClick={() => onSwitchToLogin()} style={{ fontSize: 14, color: '#00FF41', letterSpacing: '0.12em', cursor: 'pointer' }}>{'>'} ./login</a>
          </div>
        )}

        {/* ERROR */}
        {phase === 'error' && (
          <div>
            <div style={{ fontSize: 14, color: '#FF3344', letterSpacing: '0.18em', marginBottom: 8 }}>$ ./auth --reset</div>
            <h2 style={{ fontSize: 24, fontWeight: 800, color: '#FFF', letterSpacing: '0.04em', margin: '0 0 12px' }}>RESET FAILED</h2>
            {err && (
              <div role="alert" style={{ marginBottom: 16, padding: '8px 12px', border: '1px solid #FF3344', color: '#FF3344', fontSize: 14, letterSpacing: '0.06em' }}>
                {err}
              </div>
            )}
            <p style={{ fontSize: 15, color: '#BFBFBF', lineHeight: 1.5, letterSpacing: '0.04em', margin: '0 0 20px' }}>
              // use forgot password to request a new link.
            </p>
            <a onClick={() => onSwitchToLogin()} style={{ fontSize: 14, color: '#00FF41', letterSpacing: '0.12em', cursor: 'pointer' }}>{'>'} ./login</a>
          </div>
        )}

        {/* FORM */}
        {(phase === 'idle' || phase === 'submitting') && (
          <form onSubmit={submit}>
            <div style={{ fontSize: 14, color: '#00FF41', letterSpacing: '0.18em', marginBottom: 8 }}>$ ./auth --reset</div>
            <h2 style={{ fontSize: 24, fontWeight: 800, color: '#FFF', letterSpacing: '0.04em', margin: '0 0 6px' }}>SET NEW PASSWORD</h2>
            <p style={{ fontSize: 15, color: '#BFBFBF', lineHeight: 1.5, letterSpacing: '0.04em', margin: '0 0 20px' }}>
              // enter your new credentials.
            </p>

            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 14, letterSpacing: '0.18em', color: '#E0E0E0', fontWeight: 700, marginBottom: 4 }}>{'>'} NEW PASSWORD</div>
              <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="minimum 8 characters"
                autoComplete="new-password" maxLength={256} autoFocus style={inputStyle}
                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'; }}
              />
            </div>

            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 14, letterSpacing: '0.18em', color: '#E0E0E0', fontWeight: 700, marginBottom: 4 }}>{'>'} CONFIRM PASSWORD</div>
              <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder="re-enter new password"
                autoComplete="new-password" maxLength={256} style={inputStyle}
                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'; }}
              />
            </div>

            {/* Turnstile */}
            <div style={{ margin: '14px 0', padding: '10px', border: '1px dashed rgba(255,255,255,0.22)', background: '#0A0A0A' }}>
              <div style={{ fontSize: 13, letterSpacing: '0.08em', color: '#9A9A9A', marginBottom: 6 }}>// CAPTCHA — cf-turnstile</div>
              <div id="m-reset-turnstile"></div>
            </div>

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

            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 20 }}>
              <button type="submit" disabled={phase === 'submitting' || (!turnstileToken && window.OBC_API.mode !== 'mock')} style={{
                background: (phase === 'submitting' || (!turnstileToken && window.OBC_API.mode !== 'mock')) ? '#3A3A3A' : '#00FF41',
                color: '#000', border: 'none', padding: '12px 18px', fontFamily: 'inherit', fontWeight: 800, fontSize: 15,
                letterSpacing: '0.18em', cursor: (phase === 'submitting' || (!turnstileToken && window.OBC_API.mode !== 'mock')) ? 'not-allowed' : 'pointer', borderRadius: 2,
                opacity: (phase === 'submitting' || (!turnstileToken && window.OBC_API.mode !== 'mock')) ? 0.5 : 1,
              }}>{'>'} ./reset</button>

              <a style={{ marginLeft: 'auto', fontSize: 14, color: '#BFBFBF', letterSpacing: '0.12em', cursor: 'pointer' }} onClick={() => onSwitchToLogin()}>
                {'<'} login
              </a>
            </div>
          </form>
        )}
      </div>
    </section>
  );
};

window.MobileResetPassword = MobileResetPassword;
