// 登录页 - 全栈版本：支持登录/注册切换 + 图形验证码
function LoginPage({ onLoginSuccess, showToast }) {
  const [mode, setMode] = React.useState('login'); // login | register
  const [phone, setPhone] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [confirmPassword, setConfirmPassword] = React.useState('');
  const [captchaInput, setCaptchaInput] = React.useState('');
  const [captchaText, setCaptchaText] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  // 刷新验证码（纯前端 Canvas 生成）
  const refreshCaptcha = React.useCallback(() => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let text = '';
    for (let i = 0; i < 4; i++) {
      text += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setCaptchaText(text);
  }, []);

  React.useEffect(() => {
    if (mode === 'register') {
      refreshCaptcha();
    }
  }, [mode, refreshCaptcha]);

  const handleSubmit = async () => {
    if (loading) return;

    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(phone)) {
      showToast('请输入正确的手机号');
      return;
    }
    if (!password) {
      showToast('请输入密码');
      return;
    }

    setLoading(true);
    try {
      if (mode === 'login') {
        const res = await api.login({ phone, password });
        showToast('登录成功');
        setTimeout(() => onLoginSuccess(res.user), 500);
      } else {
        // 注册
        if (password.length < 6) {
          showToast('密码长度至少6位');
          setLoading(false);
          return;
        }
        if (!/[a-zA-Z]/.test(password) || !/\d/.test(password)) {
          showToast('密码需包含字母和数字');
          setLoading(false);
          return;
        }
        if (password !== confirmPassword) {
          showToast('两次输入的密码不一致');
          setLoading(false);
          return;
        }
        if (!captchaInput.trim()) {
          showToast('请输入验证码');
          setLoading(false);
          return;
        }

        // 前端验证码校验
        if (captchaInput.trim().toUpperCase() !== captchaText.toUpperCase()) {
          showToast('验证码错误');
          setCaptchaInput('');
          refreshCaptcha();
          setLoading(false);
          return;
        }
        const res = await api.register({
          phone, password, confirmPassword,
        });
        showToast('注册成功');
        setTimeout(() => onLoginSuccess(res.user), 500);
      }
    } catch (err) {
      showToast(err.message);
      // 注册失败刷新验证码
      if (mode === 'register') {
        setCaptchaInput('');
        refreshCaptcha();
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="page" style={{ paddingBottom: 0, background: '#faf8f3' }}>
      {/* 顶部装饰 */}
      <div style={{
        height: 220,
        background: 'linear-gradient(135deg, #3a8f7a 0%, #5aab94 50%, #7bc4ae 100%)',
        borderRadius: '0 0 40px 40px',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        paddingTop: 30,
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute',
          width: 200, height: 200,
          borderRadius: '50%',
          background: 'rgba(255,255,255,0.1)',
          top: -60, right: -40,
        }} />
        <div style={{
          position: 'absolute',
          width: 120, height: 120,
          borderRadius: '50%',
          background: 'rgba(255,255,255,0.08)',
          bottom: -30, left: -20,
        }} />
        <div style={{
          width: 60, height: 60,
          borderRadius: 18,
          background: 'rgba(255,255,255,0.25)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 14,
        }}>
          <Icon.Heart color="#fff" size={30} />
        </div>
        <h1 style={{ color: '#fff', fontSize: 22, fontWeight: 700, marginBottom: 4 }}>
          慢病共病管理
        </h1>
        <p style={{ color: 'rgba(255,255,255,0.85)', fontSize: 13 }}>
          一站式个人慢病档案管理助手
        </p>
      </div>

      <div style={{ padding: '28px 24px' }}>
        {/* Tab 切换 */}
        <div style={{
          display: 'flex',
          background: '#f0ebe0',
          borderRadius: 12,
          padding: 4,
          marginBottom: 24,
        }}>
          <button
            style={{
              flex: 1,
              padding: '10px 0',
              borderRadius: 9,
              fontSize: 15,
              fontWeight: mode === 'login' ? 600 : 400,
              color: mode === 'login' ? '#2c3e3a' : '#8a9390',
              background: mode === 'login' ? '#fff' : 'transparent',
              transition: 'all 0.2s',
            }}
            onClick={() => { setMode('login'); setCaptchaInput(''); }}
          >
            登录
          </button>
          <button
            style={{
              flex: 1,
              padding: '10px 0',
              borderRadius: 9,
              fontSize: 15,
              fontWeight: mode === 'register' ? 600 : 400,
              color: mode === 'register' ? '#2c3e3a' : '#8a9390',
              background: mode === 'register' ? '#fff' : 'transparent',
              transition: 'all 0.2s',
            }}
            onClick={() => { setMode('register'); setCaptchaInput(''); }}
          >
            注册
          </button>
        </div>

        {/* 手机号 */}
        <div className="form-group">
          <label className="form-label">手机号</label>
          <input
            className="form-input"
            type="tel"
            placeholder="请输入手机号"
            maxLength={11}
            value={phone}
            onChange={e => setPhone(e.target.value.replace(/\D/g, ''))}
          />
        </div>

        {/* 密码 */}
        <div className="form-group">
          <label className="form-label">密码</label>
          <input
            className="form-input"
            type="password"
            placeholder={mode === 'register' ? '6-20位，包含字母和数字' : '请输入密码'}
            value={password}
            onChange={e => setPassword(e.target.value)}
          />
        </div>

        {/* 注册确认密码 */}
        {mode === 'register' && (
          <div className="form-group">
            <label className="form-label">确认密码</label>
            <input
              className="form-input"
              type="password"
              placeholder="请再次输入密码"
              value={confirmPassword}
              onChange={e => setConfirmPassword(e.target.value)}
            />
          </div>
        )}

        {/* 图形验证码（注册时显示） */}
        {mode === 'register' && (
          <div className="form-group">
            <label className="form-label">图形验证码</label>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <input
                className="form-input"
                style={{ flex: 1 }}
                type="text"
                placeholder="请输入验证码"
                maxLength={4}
                value={captchaInput}
                onChange={e => setCaptchaInput(e.target.value.toUpperCase())}
              />
              <CaptchaCanvas captchaText={captchaText} onClick={refreshCaptcha} />
            </div>
            <div className="form-hint">点击图片可刷新验证码（不区分大小写）</div>
          </div>
        )}

        <button
          className="btn btn-primary"
          style={{ marginTop: 8, height: 48, fontSize: 16 }}
          onClick={handleSubmit}
          disabled={loading}
        >
          {loading ? '处理中...' : (mode === 'login' ? '登 录' : '注 册')}
        </button>

        {/* 隐私协议 */}
        <div style={{
          marginTop: 18,
          display: 'flex',
          alignItems: 'flex-start',
          gap: 8,
          fontSize: 12,
          color: '#8a9390',
          lineHeight: 1.6,
        }}>
          <div
            style={{
              width: 16, height: 16,
              borderRadius: 4,
              border: '1.5px solid #3a8f7a',
              background: '#3a8f7a',
              flexShrink: 0,
              marginTop: 1,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}
          >
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="20 6 9 17 4 12"/>
            </svg>
          </div>
          <span>
            我已阅读并同意
            <a style={{ color: '#3a8f7a' }}>《用户服务协议》</a>
            和
            <a style={{ color: '#3a8f7a' }}>《隐私政策》</a>
            。本工具仅用于个人慢病档案管理，不提供诊断与处方服务。
          </span>
        </div>

        <div style={{
          marginTop: 30,
          textAlign: 'center',
          fontSize: 11,
          color: '#b5b9b2',
        }}>
          <p>本工具不替代医生诊断 · 具体诊疗请遵医嘱</p>
        </div>
      </div>
    </div>
  );
}
