// 移动端登录页 - 支持验证码登录和密码登录
const { useState, useEffect, useRef } = React;

function AuthPage() {
  const [mode, setMode] = useState('codeLogin'); // 'login' | 'codeLogin'
  const [loading, setLoading] = useState(false);
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [smsCode, setSmsCode] = useState('');
  const [error, setError] = useState('');
  const [sendCooldown, setSendCooldown] = useState(0);
  const [sendingCode, setSendingCode] = useState(false);
  const timerRef = useRef(null);

  useEffect(() => {
    setPassword('');
    if (NK.Store.isLoggedIn()) {
      NK.Store.navigate('home');
    }
    return () => { if (timerRef.current) clearInterval(timerRef.current); };
  }, []);

  // Cooldown timer
  useEffect(() => {
    if (sendCooldown <= 0) {
      if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null; }
      return;
    }
    timerRef.current = setInterval(() => {
      setSendCooldown(function(c) { return c <= 1 ? 0 : c - 1; });
    }, 1000);
    return () => { if (timerRef.current) clearInterval(timerRef.current); };
  }, [sendCooldown > 0]);

  const handleSendCode = async () => {
    setError('');
    if (!phone) { setError('请输入手机号'); return; }
    if (!/^1[3-9]\d{9}$/.test(phone)) { setError('手机号格式不正确'); return; }
    if (sendCooldown > 0) return;

    setSendingCode(true);
    try {
      var res = await NK.Api.Sms.sendCode(phone, 'login');
      if (res.code === 0) {
        setSendCooldown(res.data.cooldownSeconds || 60);
        if (res.message) alert(res.message);
      } else {
        setError(res.message || '短信发送失败，请稍后重试');
      }
    } catch (err) {
      setError('网络错误');
    } finally {
      setSendingCode(false);
    }
  };

  const handleLogin = async (e) => {
    e.preventDefault();
    setError('');
    if (!phone) { setError('请输入手机号或用户号'); return; }
    if (!/^1[3-9]\d{9}$/.test(phone) && !/^\d{6,7}$/.test(phone)) { setError('手机号或用户号格式不正确'); return; }
    if (!password) { setError('请输入密码'); return; }
    if (password.length < 6) { setError('密码至少6位'); return; }

    setLoading(true);
    try {
      const res = await NK.Api.Auth.login({ identifier: phone, password: password });
      if (res.code === 0) {
        NK.Api.setToken(res.data.token);
        NK.Store.setAll({ user: res.data, page: 'home' });
      } else {
        setError(res.message || '登录失败');
      }
    } catch (err) {
      setError('网络错误');
    } finally {
      setLoading(false);
    }
  };

  const handleCodeLogin = async (e) => {
    e.preventDefault();
    setError('');
    if (!phone) { setError('请输入手机号'); return; }
    if (!/^1[3-9]\d{9}$/.test(phone)) { setError('手机号格式不正确'); return; }
    if (!smsCode || smsCode.length < 4) { setError('请输入验证码'); return; }

    setLoading(true);
    try {
      const res = await NK.Api.Auth.loginByCode({ phone, smsCode });
      if (res.code === 0) {
        NK.Api.setToken(res.data.token);
        NK.Store.setAll({ user: res.data, page: 'home' });
      } else {
        setError(res.message || '登录失败');
      }
    } catch (err) {
      setError('网络错误');
    } finally {
      setLoading(false);
    }
  };

  // Render SMS code row
  var renderSmsRow = function() {
    return React.createElement('div', {
      style: { display: 'flex', gap: 10, marginBottom: 14 }
    },
      React.createElement('input', {
        type: 'text', placeholder: '验证码', value: smsCode,
        onChange: function(e) { setSmsCode(e.target.value.replace(/\D/g, '')); },
        maxLength: 6,
        style: {
          flex: 1, height: 48, borderRadius: 24, border: '1px solid #e8e8e8',
          padding: '0 20px', fontSize: 16, outline: 'none'
        }
      }),
      React.createElement('button', {
        type: 'button',
        onClick: handleSendCode,
        disabled: sendCooldown > 0 || sendingCode,
        style: {
          width: 130, minWidth: 130, height: 48, borderRadius: 24, border: 'none',
          background: (sendCooldown > 0 || sendingCode) ? '#d9d9d9' : '#1677ff',
          color: '#fff', fontSize: 13, fontWeight: 500, cursor: (sendCooldown > 0 || sendingCode) ? 'not-allowed' : 'pointer',
          whiteSpace: 'nowrap'
        }
      }, sendingCode ? '发送中...' : (sendCooldown > 0 ? ('重新获取(' + sendCooldown + 's)') : '获取验证码'))
    );
  };

  return React.createElement('div', { className: 'auth-page' },
    // Logo
    React.createElement('div', { className: 'alogo' },
      React.createElement('div', { className: 'aicon' }, '\uD83C\uDFAE'),
      React.createElement('h2', null, '\u65B9\u5757\u53F7\u4ED3'),
      React.createElement('p', null, '\u6E38\u620F\u8D26\u53F7\u5B89\u5168\u4EA4\u6613')
    ),

    // Tab 切换
    React.createElement('div', {
      style: { display: 'flex', marginBottom: 24, borderRadius: 24, background: '#f0f0f0', padding: 3 }
    },
      React.createElement('div', {
        onClick: function() { setMode('codeLogin'); setError(''); setPassword(''); },
        style: {
          flex: 1, textAlign: 'center', padding: '10px 0', borderRadius: 21,
          fontSize: 14, fontWeight: 600, cursor: 'pointer',
          background: mode === 'codeLogin' ? '#fff' : 'transparent',
          color: mode === 'codeLogin' ? '#1677ff' : '#666',
          boxShadow: mode === 'codeLogin' ? '0 1px 4px rgba(0,0,0,.08)' : 'none',
          transition: 'all .2s'
        }
      }, '\u9A8C\u8BC1\u7801\u767B\u5F55'),
      React.createElement('div', {
        onClick: function() { setMode('login'); setError(''); setSmsCode(''); },
        style: {
          flex: 1, textAlign: 'center', padding: '10px 0', borderRadius: 21,
          fontSize: 14, fontWeight: 600, cursor: 'pointer',
          background: mode === 'login' ? '#fff' : 'transparent',
          color: mode === 'login' ? '#1677ff' : '#666',
          boxShadow: mode === 'login' ? '0 1px 4px rgba(0,0,0,.08)' : 'none',
          transition: 'all .2s'
        }
      }, '\u5BC6\u7801\u767B\u5F55'),

    ),

    // ---- Password Login Form ----
    mode === 'login' && React.createElement('form', { onSubmit: handleLogin },
      React.createElement('input', {
        type: 'text', placeholder: '\u624B\u673A\u53F7\u6216\u7528\u6237\u53F7', value: phone,
        onChange: function(e) { setPhone(e.target.value); }, maxLength: 11,
        style: { width: '100%', height: 48, borderRadius: 24, border: '1px solid #e8e8e8', padding: '0 20px', fontSize: 16, outline: 'none', marginBottom: 14 }
      }),
      React.createElement('input', {
        type: 'password', placeholder: '\u5BC6\u7801', value: password,
        onChange: function(e) { setPassword(e.target.value); },
        style: { width: '100%', height: 48, borderRadius: 24, border: '1px solid #e8e8e8', padding: '0 20px', fontSize: 16, outline: 'none', marginBottom: 14 }
      }),
      error && React.createElement('div', { style: { color: '#ff4d4f', fontSize: 13, marginBottom: 12, paddingLeft: 8 } }, error),
      React.createElement('button', {
        type: 'submit', disabled: loading,
        style: { width: '100%', height: 48, borderRadius: 24, border: 'none', background: loading ? '#91caff' : 'linear-gradient(135deg,#1677ff,#4096ff)', color: '#fff', fontSize: 17, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', marginTop: 8 }
      }, loading ? '\u5904\u7406\u4E2D...' : '\u767B\u5F55')
    ),

    // ---- Code Login Form ----
    mode === 'codeLogin' && React.createElement('form', { onSubmit: handleCodeLogin },
      React.createElement('input', {
        type: 'tel', placeholder: '\u8F93\u5165\u624B\u673A\u53F7\u6CE8\u518C\u6216\u767B\u5F55', value: phone,
        onChange: function(e) { setPhone(e.target.value); }, maxLength: 11,
        style: { width: '100%', height: 48, borderRadius: 24, border: '1px solid #e8e8e8', padding: '0 20px', fontSize: 16, outline: 'none', marginBottom: 14 }
      }),
      renderSmsRow(),
      error && React.createElement('div', { style: { color: '#ff4d4f', fontSize: 13, marginBottom: 12, paddingLeft: 8 } }, error),
      React.createElement('button', {
        type: 'submit', disabled: loading,
        style: { width: '100%', height: 48, borderRadius: 24, border: 'none', background: loading ? '#91caff' : 'linear-gradient(135deg,#1677ff,#4096ff)', color: '#fff', fontSize: 17, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', marginTop: 8 }
      }, loading ? '\u5904\u7406\u4E2D...' : '\u767B\u5F55')
    )
  );
}

window.NK = window.NK || {};
NK.AuthPage = AuthPage;
