
function AuthModal({ show, mode = 'choice', onClose, onSuccess }) {
  const { showToast, api } = useApp();
  const [innerMode, setInnerMode] = React.useState(mode); // choice | login | register
  const [loading, setLoading] = React.useState(false);
  const [loginForm, setLoginForm] = React.useState({ account: '', password: '' });
  const [regForm, setRegForm] = React.useState({
    phone: '', password: '', nickname: '',
    gender: '', birthday: '',
    province: '', city: '',
    occupation: '', education: '',
  });
  // 注册滚动容器引用
  const sheetRef = React.useRef(null);

  React.useEffect(() => {
    if (show) {
      setInnerMode(mode);
      setLoginForm({ account: '', password: '' });
      setRegForm({
        phone: '', password: '', nickname: '',
        gender: '', birthday: '',
        province: '', city: '',
        occupation: '', education: '',
      });
    }
  }, [show, mode]);

  if (!show) return null;

  const handleLogin = async () => {
    if (!loginForm.account.trim()) { showToast('请输入手机号或账号'); return; }
    if (!loginForm.password) { showToast('请输入密码'); return; }
    setLoading(true);
    try {
      const res = await api.post('/user/login', {
        phone: loginForm.account,
        password: loginForm.password,
      });
      if (res.success) {
        showToast('登录成功');
        onSuccess && onSuccess(res.data);
      } else {
        showToast(res.message || '登录失败');
      }
    } catch (e) {
      showToast('登录失败');
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async () => {
    if (!regForm.phone.trim()) { showToast('请输入手机号'); return; }
    if (!regForm.nickname.trim()) { showToast('请输入昵称'); return; }
    if (!regForm.password) { showToast('请设置密码'); return; }
    if (regForm.password.length < 6) { showToast('密码至少6位'); return; }
    if (!regForm.gender) { showToast('请选择性别'); return; }
    setLoading(true);
    try {
      const res = await api.post('/user/register', regForm);
      if (res.success) {
        showToast('注册成功');
        onSuccess && onSuccess(res.data);
      } else {
        showToast(res.message || '注册失败');
      }
    } catch (e) {
      showToast('注册失败');
    } finally {
      setLoading(false);
    }
  };

  const PROVINCES = Object.keys(window.PROVINCE_CITY_MAP_UI || {});
  const CITIES = (regForm.province && (window.PROVINCE_CITY_MAP_UI || {})[regForm.province]) || [];
  const OCCUPATIONS = window.OCCUPATION_LIST_UI || [];
  const EDUCATIONS = window.EDUCATION_LIST_UI || [];

  const overlayStyle = {
    position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
    zIndex: 9999, display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
    padding: '20px 16px',
    overflowY: 'auto',
  };

  const sheetStyle = {
    width: '100%', maxWidth: 340,
    background: '#fff', borderRadius: 16,
    padding: '24px 20px 20px',
    position: 'relative',
    margin: 'auto 0',
  };

  const inputStyle = {
    width: '100%', height: 40,
    border: '1px solid #E5E7EB',
    borderRadius: 10,
    padding: '0 12px',
    fontSize: 13,
    boxSizing: 'border-box',
    marginBottom: 10,
    outline: 'none',
  };

  const labelStyle = {
    fontSize: 12,
    color: '#6B7280',
    marginBottom: 4,
    marginTop: 2,
  };

  const rowStyle = {
    display: 'flex',
    gap: 8,
    marginBottom: 10,
  };

  const selectStyle = {
    flex: 1,
    height: 40,
    border: '1px solid #E5E7EB',
    borderRadius: 10,
    padding: '0 10px',
    fontSize: 13,
    background: '#fff',
    color: '#374151',
    outline: 'none',
    boxSizing: 'border-box',
  };

  const btnPrimary = {
    width: '100%', height: 44,
    background: 'linear-gradient(135deg, #165DFF 0%, #4080FF 100%)',
    color: '#fff', border: 'none', borderRadius: 10,
    fontSize: 15, fontWeight: 500,
    cursor: 'pointer',
    marginTop: 6,
  };

  const btnOutline = {
    width: '100%', height: 44,
    background: '#fff', color: '#165DFF',
    border: '1px solid #165DFF',
    borderRadius: 10,
    fontSize: 15, fontWeight: 500,
    cursor: 'pointer',
    marginTop: 10,
  };

  // Choice mode
  if (innerMode === 'choice') {
    return (
      <div style={overlayStyle} onClick={onClose}>
        <div style={{ ...sheetStyle, margin: 'auto' }} onClick={e => e.stopPropagation()}>
          <div style={{ fontSize: 20, fontWeight: 600, textAlign: 'center', marginBottom: 6 }}>
            欢迎来到久存网
          </div>
          <div style={{ fontSize: 13, color: '#6B7280', textAlign: 'center', marginBottom: 24 }}>
            登录后解锁更多精彩内容
          </div>
          <button style={btnPrimary} onClick={() => setInnerMode('login')}>
            已有账号，去登录
          </button>
          <button style={btnOutline} onClick={() => setInnerMode('register')}>
            没有账号，去注册
          </button>
          <div
            onClick={onClose}
            style={{
              position: 'absolute', top: 12, right: 16,
              fontSize: 20, color: '#9CA3AF', cursor: 'pointer',
              width: 28, height: 28, display: 'flex',
              alignItems: 'center', justifyContent: 'center',
            }}
          >×</div>
        </div>
      </div>
    );
  }

  // Login mode
  if (innerMode === 'login') {
    return (
      <div style={overlayStyle} onClick={onClose}>
        <div style={{ ...sheetStyle, margin: 'auto' }} onClick={e => e.stopPropagation()}>
          <div style={{ fontSize: 20, fontWeight: 600, marginBottom: 4 }}>登录</div>
          <div style={{ fontSize: 12, color: '#9CA3AF', marginBottom: 20 }}>
            测试账号：admin / admin123
          </div>
          <input
            style={inputStyle}
            placeholder="手机号 / 账号"
            value={loginForm.account}
            onChange={e => setLoginForm({ ...loginForm, account: e.target.value })}
          />
          <input
            style={inputStyle}
            type="password"
            placeholder="密码"
            value={loginForm.password}
            onChange={e => setLoginForm({ ...loginForm, password: e.target.value })}
            onKeyDown={e => e.key === 'Enter' && handleLogin()}
          />
          <button
            style={{ ...btnPrimary, opacity: loading ? 0.6 : 1 }}
            onClick={handleLogin}
            disabled={loading}
          >
            {loading ? '登录中...' : '登录'}
          </button>
          <div style={{ textAlign: 'center', marginTop: 16, fontSize: 13, color: '#6B7280' }}>
            还没有账号？
            <span style={{ color: '#165DFF', cursor: 'pointer' }} onClick={() => setInnerMode('register')}>
              立即注册
            </span>
          </div>
          <div
            onClick={onClose}
            style={{
              position: 'absolute', top: 12, right: 16,
              fontSize: 20, color: '#9CA3AF', cursor: 'pointer',
              width: 28, height: 28, display: 'flex',
              alignItems: 'center', justifyContent: 'center',
            }}
          >×</div>
        </div>
      </div>
    );
  }

  // Register mode
  return (
    <div style={overlayStyle} onClick={onClose}>
      <div ref={sheetRef} style={sheetStyle} onClick={e => e.stopPropagation()}>
        <div style={{ fontSize: 20, fontWeight: 600, marginBottom: 4 }}>注册账号</div>
        <div style={{ fontSize: 11, color: '#9CA3AF', marginBottom: 14 }}>
          带 <span style={{ color: '#FF4757' }}>*</span> 为必填项
        </div>

        {/* 必填基本信息 */}
        <div style={labelStyle}>手机号 <span style={{ color: '#FF4757' }}>*</span></div>
        <input
          style={inputStyle}
          placeholder="请输入手机号"
          value={regForm.phone}
          onChange={e => setRegForm({ ...regForm, phone: e.target.value })}
        />
        <div style={labelStyle}>昵称 <span style={{ color: '#FF4757' }}>*</span></div>
        <input
          style={inputStyle}
          placeholder="请输入昵称"
          value={regForm.nickname}
          onChange={e => setRegForm({ ...regForm, nickname: e.target.value })}
        />
        <div style={labelStyle}>密码 <span style={{ color: '#FF4757' }}>*</span></div>
        <input
          style={inputStyle}
          type="password"
          placeholder="至少6位"
          value={regForm.password}
          onChange={e => setRegForm({ ...regForm, password: e.target.value })}
          onKeyDown={e => e.key === 'Enter' && handleRegister()}
        />

        {/* 性别 必选 */}
        <div style={labelStyle}>性别 <span style={{ color: '#FF4757' }}>*</span></div>
        <div style={{ display: 'flex', gap: 8, marginBottom: 10 }}>
          {['male', 'female'].map(g => (
            <div
              key={g}
              onClick={() => setRegForm({ ...regForm, gender: g })}
              style={{
                flex: 1, height: 38, borderRadius: 10,
                border: regForm.gender === g ? '1px solid #165DFF' : '1px solid #E5E7EB',
                background: regForm.gender === g ? 'rgba(22, 93, 255, 0.08)' : '#fff',
                color: regForm.gender === g ? '#165DFF' : '#6B7280',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 13, cursor: 'pointer', fontWeight: regForm.gender === g ? 600 : 400,
              }}
            >
              {g === 'male' ? '男' : '女'}
            </div>
          ))}
        </div>

        {/* 选填信息分隔 */}
        <div style={{
          fontSize: 11, color: '#9CA3AF',
          margin: '6px 0 10px',
          textAlign: 'center',
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <div style={{ flex: 1, height: 1, background: '#F3F4F6' }}></div>
          <span>以下选填，可后续在资料页完善</span>
          <div style={{ flex: 1, height: 1, background: '#F3F4F6' }}></div>
        </div>

        {/* 出生日期 */}
        <div style={labelStyle}>出生日期</div>
        <input
          type="date"
          style={inputStyle}
          value={regForm.birthday}
          onChange={e => setRegForm({ ...regForm, birthday: e.target.value })}
        />

        {/* 所在地区：省 + 市 */}
        <div style={labelStyle}>所在地区</div>
        <div style={rowStyle}>
          <select
            style={selectStyle}
            value={regForm.province}
            onChange={e => setRegForm({ ...regForm, province: e.target.value, city: '' })}
          >
            <option value="">请选择省份</option>
            {PROVINCES.map(p => (
              <option key={p} value={p}>{p}</option>
            ))}
          </select>
          <select
            style={selectStyle}
            value={regForm.city}
            onChange={e => setRegForm({ ...regForm, city: e.target.value })}
            disabled={!regForm.province}
          >
            <option value="">请选择城市</option>
            {CITIES.map(c => (
              <option key={c} value={c}>{c}</option>
            ))}
          </select>
        </div>

        {/* 职业 */}
        <div style={labelStyle}>职业</div>
        <select
          style={{ ...inputStyle, color: regForm.occupation ? '#374151' : '#9CA3AF' }}
          value={regForm.occupation}
          onChange={e => setRegForm({ ...regForm, occupation: e.target.value })}
        >
          <option value="">请选择职业</option>
          {OCCUPATIONS.map(o => (
            <option key={o} value={o}>{o}</option>
          ))}
        </select>

        {/* 学历 */}
        <div style={labelStyle}>学历</div>
        <select
          style={{ ...inputStyle, color: regForm.education ? '#374151' : '#9CA3AF', marginBottom: 16 }}
          value={regForm.education}
          onChange={e => setRegForm({ ...regForm, education: e.target.value })}
        >
          <option value="">请选择学历</option>
          {EDUCATIONS.map(o => (
            <option key={o} value={o}>{o}</option>
          ))}
        </select>

        <button
          style={{ ...btnPrimary, opacity: loading ? 0.6 : 1 }}
          onClick={handleRegister}
          disabled={loading}
        >
          {loading ? '注册中...' : '注册并登录'}
        </button>
        <div style={{ textAlign: 'center', marginTop: 14, fontSize: 13, color: '#6B7280' }}>
          已有账号？
          <span style={{ color: '#165DFF', cursor: 'pointer' }} onClick={() => setInnerMode('login')}>
            去登录
          </span>
        </div>
        <div
          onClick={onClose}
          style={{
            position: 'absolute', top: 12, right: 16,
            fontSize: 20, color: '#9CA3AF', cursor: 'pointer',
            width: 28, height: 28, display: 'flex',
            alignItems: 'center', justifyContent: 'center',
          }}
        >×</div>
      </div>
    </div>
  );
}

window.AuthModal = AuthModal;
