// Current logged-in user — sourced from 知乎 OAuth → localStorage.
//
// 流程: oauth.jsx 在登录成功后 saveUser(...) 写 localStorage. 这里在脚本加载时
// 同步读出来, 拼成 CURRENT_USER. 其他组件 (feed / profile / question) 拿同一份
// shape 用, 跟以前的 hardcoded 一致, 不需要改下游.
//
// 没登录时 (getStoredUser() === null) 走 GUEST_PLACEHOLDER, 但 main.jsx 会拦在
// LoginGate, 实际不会渲染到下游, 这里只是兜底.

const GUEST_PLACEHOLDER = {
  name: '游客',
  initials: '游',
  bio: '',
  avatarUrl: null,
  avatarGradient: ['#9CA3AF', '#4B5563'],
  badge: null,
  badgeText: '',
  stats: { following: 0, followers: 0, collections: 0, recentViews: 0, answers: 0, likes: 0 },
};

// 把 OAuth /user 返回的 raw shape 转成我们 demo 用的 CURRENT_USER shape
function _zhihuUserToCurrent(z) {
  const fullname = z.fullname || '知乎用户';
  // 中文取前 2 个字符, 英文取前 2 个字母 — 用做头像 fallback
  const initials = fullname.slice(0, 2);
  // _stats 是 dev mock 给的随机数据. 真 OAuth /user 不返回 stats — TODO 改成调
  // /openapi/user/following + followers 等接口. 暂时给一份合理的默认值, 不要 0,
  // 这样"评审官"账号看起来像个真实活跃用户.
  const stats = z._stats || {
    following: 247, followers: 1832, collections: 86,
    recentViews: 213, answers: 92, likes: 5421,
  };
  return {
    name: fullname,
    initials,
    bio: z.headline || z.description || '',
    avatarUrl: z.avatar_path || null,
    avatarGradient: ['#E69A6B', '#B8623E'],   // fallback 渐变
    badge: 'verified',
    badgeText: z.headline || '',
    stats,
    // 原始字段保留 (uid 用做后续 API 调用; access_token 用做圈子/搜索 API)
    _uid: z.uid,
    _accessToken: z.access_token,
    _devBypass: z._devBypass === true,
  };
}

const _storedZhihu = (typeof getStoredUser === 'function') ? getStoredUser() : null;
const CURRENT_USER = _storedZhihu ? _zhihuUserToCurrent(_storedZhihu) : GUEST_PLACEHOLDER;

// 头像组件 — 有真实 URL 用 <img>, 失败/没有则走"渐变 + 首字"兜底.
// onError 兜底很关键: 知乎 /user 接口返回的 avatar_path 可能是知乎 CDN, 在某些
// 网络环境下不可达 (CORS / hot-link 屏蔽), 这时如果不兜底就会显示破图问号.
function UserAvatar({ size = 28, fontScale = 0.32, style = {} }) {
  const u = CURRENT_USER;
  const [imgFailed, setImgFailed] = React.useState(false);
  if (u.avatarUrl && !imgFailed) {
    return (
      <img src={u.avatarUrl} alt=""
        onError={() => setImgFailed(true)}
        style={{
          width: size, height: size, borderRadius: '50%',
          objectFit: 'cover', flexShrink: 0,
          ...style,
        }}/>
    );
  }
  const [a, b] = u.avatarGradient;
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: `linear-gradient(135deg, ${a}, ${b})`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: '#fff', fontWeight: 700, letterSpacing: -1, flexShrink: 0,
      fontSize: Math.round(size * fontScale),
      fontFamily: '"PingFang SC", "Noto Sans SC", system-ui',
      ...style,
    }}>{u.initials}</div>
  );
}

Object.assign(window, { CURRENT_USER, UserAvatar });
