XLG-等级分 V0.1.0

· · 个人记录

一个本地计算洛谷 Rating 变动的小工具。参考公开公式实现,不依赖第三方服务,所有计算在你浏览器里完成。

前言

本插件基于 px_poxiao 公布的等级分预测公式开发。该公式是对洛谷已公开结算数据的拟合结果,不是官方公式,预测值仅供参考,不代表真实等级分变动。

感谢 px_poxiao 开源并授权使用。

用途

在洛谷原生「比赛等级分趋势图」基础上,增加两个功能:

  1. 主页趋势图:把原来的原生图表替换成我们自己的版本,展示你全部历史比赛 Rating 曲线。
  2. 未结算比赛预测:对于你已经参加、但洛谷还没结算 Rating 的比赛,在主页显示预估的变动值。

不修改洛谷任何数据,只读取页面公开信息。

计算原理

详细公式可以去看 px_poxiao 的专栏。

简单说,洛谷的 Rating 计算由这几部分组成:

最后合成展示 Rating。这套逻辑在插件里完全本地实现。

需要说明的是,洛谷没有公开 RATEDBOUND 和 Center 的精确值,插件用比赛名称推测(Div.2 → 2000,Div.3 → 1600,Div.4 → 1200),可能与真实值有偏差。

功能

主页趋势图

替换掉原生的「比赛等级分趋势图」,展示你自己的实现:

未结算比赛预测

打开一场已结束的比赛页面(详情页或排行榜页均可),插件会在后台查询排行榜,找到你的排名,然后:

下次打开自己主页,会在图表下方显示:

⏳ 有 1 场已参加、未结算的比赛
「FAOI」Round 13  排名 #5/17  [精确]  +85 → 1566

等这场比赛正式结算后,插件会自动从待处理列表里移除它。

项 说明
邻近选手精确查询 开启后会查询你排名附近选手的真实 Rating,精度更高但请求更多
调试日志 在控制台输出详细日志,排查问题用
邻近范围 ±5 / ±8 / ±10 / ±15,控制查询范围
最大排行榜页数 最多翻几页找你的排名
请求间隔 3.5 / 5 / 8 秒,越长越安全
数据管理 清空未结算记录 / 已结算列表 / Rating 缓存

请求策略

考虑到洛谷对爬虫的态度,插件在请求方面做了限制:

单个请求失败不会重试,只记录状态等下一次触发。

安装

  1. 浏览器装 Tampermonkey 或 脚本猫
  2. 新建脚本,把代码粘贴进去
  3. 保存

打开任意洛谷页面,右上角头像左边应该出现一个齿轮图标,表示插件已工作。

数据说明

所有数据存在浏览器 localStorage 里,不会上传。清除浏览器数据会丢失,需要重新触发查询。

已知限制

  1. 预测不是官方结果。洛谷未公开公式参数,插件用的是拟合值和经验值。
  2. 排行榜很靠后时查不到。如果默认 5 页内找不到你的排名,会跳过,下次再试。
  3. 别人主页不受影响。插件只在本人主页工作,别人主页的原生图表完全保持原样。
  4. 不保证长期可用。洛谷前端改版可能让插件失效,需要跟着更新。

作者说明

写这个插件主要是为了满足自己的好奇:参加完比赛、还没结算的这段时间里,大概能涨多少分。

公式部分完全参考 px_poxiao 的公开工作,没有原创贡献。插件代码借助 AI 完成了大部分实现,我做了需求设计、测试和调试。不敢说有多精妙,能用就行。

如果发现 bug 或者有改进建议,欢迎反馈。

免责声明:本插件为非官方工具,预测结果仅供参考。使用本插件产生的一切后果由用户自行承担。 ::::info[代码] :::info[V0.1.0]

// ==UserScript==
// @name         XLG-等级分 V0.1.0 Trie2025
// @namespace    https://www.luogu.com.cn/user/1271480
// @version      0.1.0
// @description  洛谷原生等级分图增强 + 未结算比赛预测(最小请求、串行限速、遇限流立即停止)
// @author       Trie2025
// @match        https://www.luogu.com.cn/*
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js
// @run-at       document-end
// @grant        GM_xmlhttpRequest
// @connect      www.luogu.com.cn
// ==/UserScript==

(function () {
  'use strict';

  // ================= 常量 =================
  const CHART_ID = 'xlg-rating-chart';
  const NATIVE_CARD_TITLE = '比赛等级分趋势图';
  const PENDING_KEY = 'xlg-pending-contests-v4';
  const SETTLED_KEY = 'xlg-settled-contest-ids-v4';
  const RATING_CACHE_KEY = 'xlg-user-rating-cache-v1';
  const SETTINGS_KEY = 'xlg-settings-v1';
  const PENDING_TTL = 30 * 24 * 3600;
  const RATING_CACHE_TTL = 7 * 24 * 3600;

  // ================= 默认配置 =================
  const DEFAULT_SETTINGS = {
    fetchMode: 'nearby',
    nearbyRange: 8,
    requestDelay: 5000,
    maxPages: 5,
    maxOthers: 20,
    debug: false
  };

  // 修复 1:缓存配置,避免频繁读 localStorage
  let _cfgCache = null;
  function getConfig() {
    if (_cfgCache) return _cfgCache;
    try {
      const raw = localStorage.getItem(SETTINGS_KEY);
      _cfgCache = raw ? { ...DEFAULT_SETTINGS, ...JSON.parse(raw) } : { ...DEFAULT_SETTINGS };
    } catch { _cfgCache = { ...DEFAULT_SETTINGS }; }
    return _cfgCache;
  }
  function saveConfig(cfg) {
    _cfgCache = cfg;
    try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(cfg)); } catch {}
  }

  // ================= 状态 =================
  let chart = null;
  let chartContainer = null;
  let resizeHandler = null;
  let resizeObserver = null;
  let lastSig = null;
  let myUid = null;
  let runTimer = null;
  let querying = false;
  let settingsPanelEl = null;
  let lastRoutePath = '';

  // 全局串行限速
  let requestChain = Promise.resolve();
  let lastApiRequestAt = 0;
  const API_COOLDOWN_KEY = 'xlg-api-cooldown-v1';
  const MIN_API_INTERVAL = 3500;
  const RATE_LIMIT_COOLDOWN = 30 * 60 * 1000;
  const ERROR_COOLDOWN = 10 * 60 * 1000;

  // ================= 日志 =================
  const log  = (...a) => { if (getConfig().debug) console.log('[XLG-等级分]', ...a); };
  const warn = (...a) => console.warn('[XLG-等级分]', ...a);

  // ================= HTML 转义(修复 2:防 XSS)=================
  function escapeHtml(s) {
    if (s == null) return '';
    return String(s)
      .replace(/&/g, '&')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  // ================= 限速与冷却 =================
  function getApiCooldownUntil() {
    try { return Number(localStorage.getItem(API_COOLDOWN_KEY) || 0); }
    catch { return 0; }
  }
  function setApiCooldown(ms) {
    const until = Date.now() + ms;
    try { localStorage.setItem(API_COOLDOWN_KEY, String(until)); } catch {}
    return until;
  }
  function getApiCooldownRemaining() {
    return Math.max(0, getApiCooldownUntil() - Date.now());
  }
  function createApiError(message, extra = {}) {
    const error = new Error(message);
    Object.assign(error, extra);
    return error;
  }
  function isRateLimitedStatus(status) {
    return status === 429 || status === 403 || status === 503;
  }

  // ================= GM 请求 =================
  function gmRequest(url) {
    const task = requestChain
      .catch(() => {})
      .then(async () => {
        const cooldown = getApiCooldownRemaining();
        if (cooldown > 0) {
          throw createApiError(
            `API 冷却中,还需等待 ${Math.ceil(cooldown / 1000)} 秒`,
            { cooldown: true, rateLimited: true }
          );
        }

        const cfg = getConfig();
        const configuredDelay = Number(cfg.requestDelay) || 5000;
        const interval = Math.max(MIN_API_INTERVAL, Math.min(configuredDelay, 30000));
        const waitTime = Math.max(0, interval - (Date.now() - lastApiRequestAt));
        if (waitTime > 0) await sleep(waitTime);

        const cooldownAgain = getApiCooldownRemaining();
        if (cooldownAgain > 0) {
          throw createApiError(
            `API 冷却中,还需等待 ${Math.ceil(cooldownAgain / 1000)} 秒`,
            { cooldown: true, rateLimited: true }
          );
        }

        lastApiRequestAt = Date.now();

        return new Promise((resolve, reject) => {
          GM_xmlhttpRequest({
            method: 'GET',
            url,
            timeout: 15000,
            onload: resp => {
              if (resp.status >= 200 && resp.status < 300) {
                try { resolve(JSON.parse(resp.responseText)); }
                catch { reject(createApiError('JSON 解析失败')); }
                return;
              }
              if (isRateLimitedStatus(resp.status)) {
                setApiCooldown(resp.status === 429 ? RATE_LIMIT_COOLDOWN : ERROR_COOLDOWN);
                reject(createApiError(
                  `HTTP ${resp.status},已进入冷却期`,
                  { status: resp.status, rateLimited: true }
                ));
                return;
              }
              reject(createApiError(`HTTP ${resp.status}`, { status: resp.status }));
            },
            onerror: () => reject(createApiError('网络错误')),
            ontimeout: () => reject(createApiError('请求超时'))
          });
        });
      });

    requestChain = task.catch(() => {});
    return task;
  }

  function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }

  // ==================================================================
  //  原生 canvas 的隐藏/恢复(inline style,不用 CSS 类)
  // ==================================================================
  function hideNativeRatingCanvas() {
    document.querySelectorAll('canvas#rating-chart').forEach(c => {
      if (c.style.display !== 'none') {
        if (c.dataset.xlgPrevDisplay === undefined) {
          c.dataset.xlgPrevDisplay = c.style.display || '';
        }
        c.style.display = 'none';
      }
    });
    document.querySelectorAll('.tooltip[data-v-120dc024]').forEach(t => {
      if (t.style.display !== 'none') {
        if (t.dataset.xlgPrevDisplay === undefined) {
          t.dataset.xlgPrevDisplay = t.style.display || '';
        }
        t.style.display = 'none';
      }
    });
  }

  function restoreNativeRatingCanvas() {
    document.querySelectorAll('canvas#rating-chart').forEach(c => {
      if (c.dataset.xlgPrevDisplay !== undefined) {
        c.style.display = c.dataset.xlgPrevDisplay;
        delete c.dataset.xlgPrevDisplay;
      } else if (c.style.display === 'none') {
        c.style.display = '';
      }
    });
    document.querySelectorAll('.tooltip[data-v-120dc024]').forEach(t => {
      if (t.dataset.xlgPrevDisplay !== undefined) {
        t.style.display = t.dataset.xlgPrevDisplay;
        delete t.dataset.xlgPrevDisplay;
      } else if (t.style.display === 'none') {
        t.style.display = '';
      }
    });
  }

  // ================= 样式 =================
  function injectBaseStyles() {
    // 清理旧版残留
    ['xlg-hide-native-style'].forEach(id => {
      const old = document.getElementById(id);
      if (old) old.remove();
    });
    const oldBase = document.getElementById('xlg-base-style');
    if (oldBase) oldBase.remove();

    const style = document.createElement('style');
    style.id = 'xlg-base-style';
    style.textContent = `
      #xlg-toast-container {
        position: fixed; right: 20px; bottom: 20px;
        display: flex; flex-direction: column; gap: 10px;
        z-index: 999999; pointer-events: none;
      }
      .xlg-toast {
        min-width: 220px; max-width: 340px;
        padding: 12px 16px; border-radius: 6px;
        color: #fff; font-size: 13px; line-height: 1.5;
        box-shadow: 0 4px 14px rgba(0,0,0,0.18);
        transform: translateX(120%); opacity: 0;
        transition: transform 0.35s cubic-bezier(0.22,1,0.36,1),
                    opacity 0.35s ease;
        pointer-events: auto; word-break: break-word;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
      }
      .xlg-toast.show { transform: translateX(0); opacity: 1; }
      .xlg-toast.hide { transform: translateX(120%); opacity: 0; }
      .xlg-toast.success { background: linear-gradient(135deg,#52c41a,#389e0d); }
      .xlg-toast.error   { background: linear-gradient(135deg,#ff4d4f,#cf1322); }
      .xlg-toast.warn    { background: linear-gradient(135deg,#faad14,#d48806); }
      .xlg-toast.info    { background: linear-gradient(135deg,#595959,#2b2b2b); }
      .xlg-toast.loading { background: linear-gradient(135deg,#595959,#2b2b2b); }

      #xlg-topbar-btn {
        position: relative;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        color: inherit;
      }
      #xlg-topbar-btn svg.xlg-gear-icon {
        height: 1em; width: 1em;
        vertical-align: -0.125em;
        fill: none;
        stroke: currentColor;
        stroke-width: 1.8;
        stroke-linecap: round;
        stroke-linejoin: round;
        transition: transform 0.35s cubic-bezier(0.22,1,0.36,1);
      }
      #xlg-topbar-btn:hover svg.xlg-gear-icon { transform: rotate(60deg); }
      #xlg-topbar-btn .xlg-badge {
        position: absolute; top: -4px; right: -7px;
        min-width: 14px; height: 14px; padding: 0 4px;
        background: rgb(231,76,60); color: #fff;
        font-size: 10px; line-height: 14px; text-align: center;
        border-radius: 7px; font-weight: 600; box-sizing: border-box;
      }

      #xlg-settings-overlay {
        position: fixed; inset: 0;
        background: transparent;
        z-index: 999998; display: block;
      }
      #xlg-settings-panel {
        position: fixed;
        width: 320px;
        max-width: calc(100vw - 16px);
        max-height: calc(100vh - 80px);
        background: #fff;
        border: 1px solid rgba(0,0,0,0.08);
        border-radius: 4px;
        box-shadow: 0 3px 12px rgba(0,0,0,0.16), 0 1px 4px rgba(0,0,0,0.08);
        overflow: hidden; display: flex; flex-direction: column;
        animation: xlgDropdownIn 0.14s ease-out;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI",
          "PingFang SC", "Microsoft YaHei", sans-serif;
        color: #333;
      }
      @keyframes xlgDropdownIn {
        from { opacity: 0; transform: translateY(-4px); }
        to   { opacity: 1; transform: translateY(0); }
      }
      .xlg-sp-header {
        min-height: 38px; padding: 9px 13px;
        border-bottom: 1px solid #f0f0f0;
        display: flex; justify-content: space-between; align-items: center;
        background: #fff;
      }
      .xlg-sp-header h3 {
        margin: 0; font-size: 13px; font-weight: 500; color: #333;
        display: flex; align-items: center; gap: 7px;
      }
      .xlg-sp-header h3 svg {
        width: 14px; height: 14px; color: #666;
        fill: none; stroke: currentColor; stroke-width: 1.8;
        stroke-linecap: round; stroke-linejoin: round;
      }
      .xlg-sp-header .xlg-sp-close {
        background: none; border: none; cursor: pointer;
        font-size: 18px; color: #aaa; padding: 0 2px; line-height: 1;
      }
      .xlg-sp-header .xlg-sp-close:hover { color: #333; }
      .xlg-sp-body { padding: 0; overflow-y: auto; flex: 1; }
      .xlg-sp-section { padding: 6px 0; border-bottom: 1px solid #f0f0f0; }
      .xlg-sp-section:last-child { border-bottom: none; }
      .xlg-sp-section-title {
        padding: 4px 13px 6px; margin: 0;
        font-size: 11px; font-weight: 500; color: #999;
      }
      .xlg-sp-toggle { display: block; padding: 0; }
      .xlg-sp-toggle input[type=checkbox] {
        position: absolute; opacity: 0; pointer-events: none;
      }
      .xlg-sp-toggle label {
        display: flex; align-items: center; gap: 8px;
        min-height: 32px; padding: 0 13px;
        cursor: pointer; font-size: 13px; color: #444;
        user-select: none;
        transition: background-color 0.12s ease, color 0.12s ease;
      }
      .xlg-sp-toggle label:hover { background: #f5f5f5; color: #222; }
      .xlg-sp-toggle svg {
        width: 16px; height: 16px; flex: 0 0 16px;
        color: #777; fill: currentColor;
      }
      .xlg-sp-toggle input:checked + label { color: #333; }
      .xlg-sp-toggle input:checked + label svg { color: #777; }
      .xlg-sp-toggle .xlg-sp-toggle-icon-on { display: none; }
      .xlg-sp-toggle input:checked + label .xlg-sp-toggle-icon-off { display: none; }
      .xlg-sp-toggle input:checked + label .xlg-sp-toggle-icon-on { display: inline-block; }
      .xlg-sp-toggle .xlg-sp-toggle-hint {
        margin-left: auto; font-size: 11px; color: #aaa;
      }
      .xlg-sp-row {
        margin: 0; padding: 7px 13px;
        border-top: 1px solid #f5f5f5;
      }
      .xlg-sp-section .xlg-sp-row:first-of-type { border-top: none; }
      .xlg-sp-label {
        display: flex; align-items: center; justify-content: space-between;
        font-size: 12px; color: #666; margin-bottom: 6px;
      }
      .xlg-sp-label .xlg-sp-hint { font-size: 11px; color: #aaa; }
      .xlg-sp-options { display: flex; gap: 4px; flex-wrap: wrap; }
      .xlg-sp-option {
        flex: 1; min-width: 0; padding: 5px 7px;
        border: 1px solid #ddd; border-radius: 3px;
        background: #fff; cursor: pointer;
        font-size: 12px; color: #666; text-align: center;
        transition: background-color 0.12s ease, border-color 0.12s ease, color 0.12s ease;
      }
      .xlg-sp-option:hover {
        border-color: #aaa; color: #333; background: #fafafa;
      }
      .xlg-sp-option.active {
        background: #f2f2f2; border-color: #999; color: #333; font-weight: 500;
      }
      .xlg-sp-actions { display: flex; gap: 6px; flex-wrap: wrap; }
      .xlg-sp-btn {
        padding: 5px 11px; border-radius: 3px;
        border: 1px solid #d8d8d8; background: #fff;
        color: #555; font-size: 12px; cursor: pointer;
        transition: all 0.12s ease;
      }
      .xlg-sp-btn:hover { border-color: #999; color: #222; background: #f7f7f7; }
      .xlg-sp-btn.danger { color: #a33; border-color: #e2caca; }
      .xlg-sp-btn.danger:hover { border-color: #b66; background: #fff8f8; }
      .xlg-sp-btn.primary { background: #444; border-color: #444; color: #fff; }
      .xlg-sp-btn.primary:hover { background: #222; border-color: #222; }
      .xlg-sp-footer {
        padding: 9px 13px; border-top: 1px solid #eee;
        display: flex; justify-content: space-between; gap: 6px;
        background: #fafafa;
      }
      .xlg-sp-info {
        padding: 8px 13px; font-size: 11px; color: #999;
        line-height: 1.55; background: #fafafa;
        border-top: 1px solid #f0f0f0;
      }

      .xlg-pending-wrap {
        margin-top: 12px; padding: 12px 14px;
        border-radius: 8px;
        background: linear-gradient(135deg, #fff8e6, #fffbf0);
        border: 1px solid #fadb14;
        font-size: 13px; color: #595959;
      }
      .xlg-pending-title {
        font-weight: 600; color: #ad8b00; margin-bottom: 8px;
        display: flex; align-items: center; gap: 6px;
      }
      .xlg-pending-row {
        display: flex; justify-content: space-between; align-items: center;
        gap: 10px; padding: 6px 0;
        border-top: 1px dashed #fadb14;
        font-variant-numeric: tabular-nums;
      }
      .xlg-pending-row:first-of-type { border-top: none; }
      .xlg-pending-name {
        flex: 1; overflow: hidden; text-overflow: ellipsis;
        white-space: nowrap; color: #262626;
      }
      .xlg-pending-name a { color: #262626; text-decoration: none; }
      .xlg-pending-name a:hover { text-decoration: underline; }
      .xlg-pending-meta { font-size: 12px; color: #8c8c8c; margin-left: 8px; }
      .xlg-pending-delta { font-weight: 600; min-width: 60px; text-align: right; }
      .xlg-pending-delta.pos { color: #389e0d; }
      .xlg-pending-delta.neg { color: #cf1322; }
      .xlg-pending-delta.zero { color: #8c8c8c; }
      .xlg-pending-est { font-size: 11px; color: #bfbfbf; margin-left: 4px; }
      .xlg-pending-hint { margin-top: 8px; font-size: 11px; color: #bfbfbf; }
      .xlg-pending-badge {
        display: inline-block; background: #52c41a; color: #fff;
        font-size: 10px; padding: 1px 5px; border-radius: 3px;
        margin-left: 4px; vertical-align: 1px;
      }
      .xlg-pending-badge.wait { background: #bfbfbf; }
      .xlg-pending-badge.fail { background: #faad14; }
      .xlg-pending-badge.acc  { background: #722ed1; }
    `;
    document.head.appendChild(style);
  }

  // ================= 图标 =================
  const ICON_GEAR = `
    <svg class="svg-inline--fa xlg-gear-icon"
      role="img" viewBox="0 0 24 24" aria-hidden="true"
      fill="none" stroke="currentColor" stroke-width="1.8"
      stroke-linecap="round" stroke-linejoin="round">
      <circle cx="12" cy="12" r="3"></circle>
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
    </svg>
  `;

  const TOGGLE_OFF = `<svg class="svg-inline--fa fa-toggle-off xlg-sp-toggle-icon-off" data-prefix="far" data-icon="toggle-off" role="img" viewBox="0 0 576 512" aria-hidden="true"><path fill="currentColor" d="M384 112c79.5 0 144 64.5 144 144S463.5 400 384 400l-192 0c-79.5 0-144-64.5-144-144s64.5-144 144-144l192 0zM576 256c0-106-86-192-192-192L192 64C86 64 0 150 0 256S86 448 192 448l192 0c106 0 192-86 192-192zm-336 0a48 48 0 1 1 -96 0 48 48 0 1 1 96 0zM96 256a96 96 0 1 0 192 0 96 96 0 1 0 -192 0z"></path></svg>`;
  const TOGGLE_ON  = `<svg class="svg-inline--fa fa-toggle-on xlg-sp-toggle-icon-on" data-prefix="far" data-icon="toggle-on" role="img" viewBox="0 0 576 512" aria-hidden="true"><path fill="currentColor" d="M192 112c-79.5 0-144 64.5-144 144s64.5 144 144 144l192 0c79.5 0 144-64.5 144-144S463.5 112 384 112l-192 0zM0 256C0 150 86 64 192 64l192 0c106 0 192 86 192 192S490 448 384 448l-192 0C86 448 0 362 0 256zm384-96a96 96 0 1 1 0 192 96 96 0 1 1 0-192z"></path></svg>`;

  // ================= Toast =================
  const toast = (() => {
    let lastMsg = '';
    let lastTime = 0;
    const DEDUP = 3000;
    const MAX = 3;
    const ICONS = { success: '✓', error: '✕', warn: '⚠', info: 'ℹ', loading: '⟳' };

    function getContainer() {
      let c = document.getElementById('xlg-toast-container');
      if (!c) {
        c = document.createElement('div');
        c.id = 'xlg-toast-container';
        document.body.appendChild(c);
      }
      return c;
    }

    return function toast(msg, type = 'info', duration = 3500) {
      const now = Date.now();
      if (msg === lastMsg && now - lastTime < DEDUP) return;
      lastMsg = msg;
      lastTime = now;

      const container = getContainer();
      while (container.children.length >= MAX) {
        container.removeChild(container.firstChild);
      }

      const el = document.createElement('div');
      el.className = 'xlg-toast ' + type;
      const icon = document.createElement('span');
      icon.textContent = ICONS[type] || '';
      icon.style.cssText = 'margin-right:6px;font-weight:bold;';
      el.appendChild(icon);
      el.appendChild(document.createTextNode(msg));
      container.appendChild(el);

      void el.offsetWidth;
      el.classList.add('show');

      setTimeout(() => {
        el.classList.remove('show');
        el.classList.add('hide');
        setTimeout(() => el.remove(), 400);
      }, duration);
    };
  })();

  // ================= 工具 =================
  function formatTime(ts) {
    const d = new Date((ts + 8 * 3600) * 1000);
    const Y = d.getUTCFullYear();
    const M = String(d.getUTCMonth() + 1).padStart(2, '0');
    const D = String(d.getUTCDate()).padStart(2, '0');
    const h = String(d.getUTCHours()).padStart(2, '0');
    const m = String(d.getUTCMinutes()).padStart(2, '0');
    return `${Y}-${M}-${D} ${h}:${m}`;
  }

  function parseContext() {
    const scripts = document.querySelectorAll('script#lentille-context');
    if (!scripts.length) return null;
    try {
      const parsed = JSON.parse(scripts[scripts.length - 1].textContent);
      return (parsed && parsed.data) ? parsed : null;
    } catch { return null; }
  }

  function detectMyUid() {
    if (myUid) return myUid;
    const ctx = parseContext();
    const u = ctx?.data?.user;
    if (u && u.uid && ('unreadMessageCount' in u || 'unreadNoticeCount' in u || 'learnMode' in u)) {
      myUid = String(u.uid); return myUid;
    }
    for (const sel of ['.user-nav .avatar a[href^="/user/"]', '.user-nav a[href^="/user/"]']) {
      for (const a of document.querySelectorAll(sel)) {
        const m = (a.getAttribute('href') || '').match(/^\/user\/(\d+)/);
        if (m) { myUid = m[1]; return myUid; }
      }
    }
    return null;
  }

  // ================= 存储 =================
  function loadPending() {
    try {
      const arr = JSON.parse(localStorage.getItem(PENDING_KEY) || '[]');
      if (!Array.isArray(arr)) return [];
      const now = Math.floor(Date.now() / 1000);
      return arr.filter(c => c.endTime && now - c.endTime < PENDING_TTL);
    } catch { return []; }
  }
  function savePending(arr) {
    try { localStorage.setItem(PENDING_KEY, JSON.stringify(arr)); } catch {}
  }
  function loadSettled() {
    try {
      const arr = JSON.parse(localStorage.getItem(SETTLED_KEY) || '[]');
      return Array.isArray(arr) ? arr.map(String) : [];
    } catch { return []; }
  }
  function saveSettled(arr) {
    try { localStorage.setItem(SETTLED_KEY, JSON.stringify([...new Set(arr.map(String))])); } catch {}
  }
  function upsertPending(record) {
    const arr = loadPending();
    const idx = arr.findIndex(c => String(c.id) === String(record.id));
    if (idx >= 0) arr[idx] = { ...arr[idx], ...record };
    else arr.push(record);
    savePending(arr);
  }
  function getPending(contestId) {
    return loadPending().find(c => String(c.id) === String(contestId)) || null;
  }
  function loadRatingCache() {
    try {
      const obj = JSON.parse(localStorage.getItem(RATING_CACHE_KEY) || '{}');
      return (obj && typeof obj === 'object') ? obj : {};
    } catch { return {}; }
  }
  function saveRatingCache(cache) {
    try { localStorage.setItem(RATING_CACHE_KEY, JSON.stringify(cache)); } catch {}
  }
  function getCachedRating(uid) {
    const cache = loadRatingCache();
    const entry = cache[String(uid)];
    if (!entry) return null;
    if (Math.floor(Date.now() / 1000) - entry.t > RATING_CACHE_TTL) return null;
    return entry.r;
  }
  function setCachedRating(uid, rating) {
    const cache = loadRatingCache();
    cache[String(uid)] = { r: rating, t: Math.floor(Date.now() / 1000) };
    saveRatingCache(cache);
  }

  // ==================================================================
  //  Rating 预测引擎
  // ==================================================================
  function lowPerfPenalty(n) {
    if (n <= 0) return 1200;
    let s09 = 0, s081 = 0;
    for (let i = 1; i <= n; i++) {
      s09 += Math.pow(0.9, i);
      s081 += Math.pow(0.81, i);
    }
    const Fn = Math.sqrt(s081) / s09;
    const F_inf = (1 - 0.9) / Math.sqrt(1 - 0.81);
    return 1200 * (Fn - F_inf) / (1 - F_inf);
  }
  function ratingFromRPerfHistory(rperfHistory) {
    const n = rperfHistory.length;
    if (n === 0) return 0;
    let num = 0, den = 0;
    for (let i = 0; i < n; i++) {
      const w = Math.pow(0.9, i + 1);
      num += Math.pow(2, rperfHistory[i] / 800) * w;
      den += w;
    }
    const raw = 800 * Math.log2(num / den) - lowPerfPenalty(n);
    return Math.round(Math.max(0, raw));
  }
  function incrementalRating(oldRating, n, rperfNew) {
    const S_n = (0.9 * (1 - Math.pow(0.9, n))) / (1 - 0.9);
    const M_old = Math.pow(2, (oldRating + lowPerfPenalty(n)) / 800);
    const M_new = (Math.pow(2, rperfNew / 800) + M_old * S_n) / (1 + S_n);
    const raw = 800 * Math.log2(M_new) - lowPerfPenalty(n + 1);
    return Math.round(Math.max(0, raw));
  }
  function calcAPerf(perfHistory) {
    if (!perfHistory.length) return null;
    let num = 0, den = 0;
    for (let i = 0; i < perfHistory.length; i++) {
      const w = Math.pow(0.9, i + 1);
      num += perfHistory[i] * w;
      den += w;
    }
    return num / den;
  }
  function sigmoidStable(x, ap) {
    const exp = (x - ap) / 400;
    if (exp > 80) return 0;
    if (exp < -80) return 1;
    return 1 / (1 + Math.pow(6, exp));
  }
  function solvePerfStable(apList, rank) {
    // 修复 3:空 apList 保护
    if (!apList || apList.length === 0) return 1200;
    const target = rank - 0.5;
    let lo = -2000, hi = 5000;
    for (let iter = 0; iter < 80; iter++) {
      const mid = (lo + hi) / 2;
      let sum = 0;
      for (const ap of apList) sum += sigmoidStable(mid, ap);
      if (sum > target) hi = mid; else lo = mid;
    }
    return (lo + hi) / 2;
  }
  function backOutRPerf(oldRating, n, newRating) {
    let lo = -2000, hi = 5000;
    for (let iter = 0; iter < 60; iter++) {
      const mid = (lo + hi) / 2;
      const computed = incrementalRating(oldRating, n, mid);
      if (computed < newRating) lo = mid; else hi = mid;
    }
    return (lo + hi) / 2;
  }
  function rebuildRPerfHistory(elo) {
    if (!Array.isArray(elo) || !elo.length) return [];
    const sorted = elo.slice().sort((a, b) => a.time - b.time);
    const rperfHistory = [];
    for (let i = 0; i < sorted.length; i++) {
      const item = sorted[i];
      const n = i;
      const oldRating = item.rating - (item.prevDiff || 0);
      const newRating = item.rating;
      if (item.prevDiff == null) {
        rperfHistory.push(newRating + lowPerfPenalty(n + 1));
      } else {
        rperfHistory.push(backOutRPerf(oldRating, n, newRating));
      }
    }
    return rperfHistory;
  }
  function rperfToPerf(rperfHistory) {
    return rperfHistory.map(r => Math.min(r, 2400));
  }
  function inferRatedBound(contest) {
    const name = (contest.name || '').toLowerCase();
    if (name.includes('div.1') || name.includes('div1')) return Infinity;
    if (name.includes('div.2') || name.includes('div2')) return 2000;
    if (name.includes('div.3') || name.includes('div3')) return 1600;
    if (name.includes('div.4') || name.includes('div4')) return 1200;
    if (name.includes('普及')) return 1600;
    if (name.includes('提高')) return 2000;
    return 1600;
  }
  function inferCenter(ratedBound) {
    return isFinite(ratedBound) ? ratedBound * 0.4 : 1200;
  }
  function approxAPerf(rank, totalN) {
    const p = (rank - 0.5) / totalN;
    const A = 1800, B = 3.5, C = 200;
    return A * Math.exp(-B * p) + C;
  }
  function buildAPerfPool(allEntries, nearbyAPerfs, myRank, myAPerf, myUid) {
    const pool = [];
    const n = allEntries.length;
    if (n === 0) return pool;
    for (const e of allEntries) {
      const uid = String(e.uid);
      if (uid === String(myUid)) { pool.push(myAPerf); continue; }
      if (nearbyAPerfs.has(uid)) { pool.push(nearbyAPerfs.get(uid)); continue; }
      pool.push(approxAPerf(e.rank || (pool.length + 1), n));
    }
    return pool;
  }

  // ==================================================================
  //  排行榜查询
  // ==================================================================
  async function fetchScoreboardPage(contestId, page) {
    const url = `https://www.luogu.com.cn/contest/${contestId}/scoreboard?page=${page}&_contentOnly=1`;
    const data = await gmRequest(url);
    // 修复 4:扩展字段匹配
    const sb = data?.currentData?.scoreboard
            || data?.currentData?.result
            || data?.scoreboard
            || data?.currentData
            || null;
    if (!sb) throw new Error('排行榜数据结构未知');
    const list = sb.result || sb.list || sb.entries || sb.rankList || sb.users || [];
    const count = sb.count || sb.total || sb.totalCount || 0;
    const perPage = sb.perPage || sb.per_page || sb.pageSize || 50;
    return { list, count, perPage };
  }

  async function findMyRankInScoreboard(contestId, uid) {
    const cfg = getConfig();
    let totalCount = 0;
    let perPage = 50;
    const allEntries = [];

    for (let page = 1; page <= cfg.maxPages; page++) {
      const { list, count, perPage: pp } = await fetchScoreboardPage(contestId, page);
      if (!list.length) break;
      totalCount = count || totalCount;
      perPage = pp || perPage;

      for (let i = 0; i < list.length; i++) {
        const entry = list[i];
        const entryUid = entry?.user?.uid ?? entry?.uid;
        const globalRank = (page - 1) * perPage + i + 1;
        allEntries.push({
          uid: String(entryUid),
          rank: entry.rank ?? entry.ranking ?? globalRank,
          entry
        });
        if (String(entryUid) === String(uid)) {
          return { myRank: entry.rank ?? globalRank, totalCount, allEntries };
        }
      }
      if (list.length < perPage) break;
    }
    return { myRank: null, totalCount, allEntries };
  }

  async function fetchUserAPerf(uid) {
    const cached = getCachedRating(uid);
    if (cached != null) return cached;

    try {
      const url = `https://www.luogu.com.cn/user/${uid}?_contentOnly=1`;
      const data = await gmRequest(url);
      const user = data?.currentData?.user || data?.user;
      const elo = user?.elo || data?.currentData?.elo || [];

      let aperf = null;
      if (Array.isArray(elo) && elo.length > 0) {
        const rperfHist = rebuildRPerfHistory(elo);
        const perfHist = rperfToPerf(rperfHist);
        aperf = calcAPerf(perfHist);
      } else if (user?.rating != null) {
        aperf = user.rating;
      }

      if (aperf != null) {
        setCachedRating(uid, aperf);
        return aperf;
      }
    } catch (e) {
      if (e.rateLimited || e.cooldown) throw e;
      warn(`查询 UID ${uid} 失败:`, e.message);
    }
    return null;
  }

  async function fetchNearbyAPerfs(entries, myRank, myUid) {
    const cfg = getConfig();
    const result = new Map();
    if (entries.length === 0 || myRank == null) return result;

    const lower = Math.max(1, myRank - cfg.nearbyRange);
    const upper = myRank + cfg.nearbyRange;

    const targets = entries.filter(e => {
      const r = e.rank;
      if (r < lower || r > upper) return false;
      if (String(e.uid) === String(myUid)) return false;
      return true;
    });

    const limited = targets.slice(0, cfg.maxOthers);

    if (limited.length > 0) {
      toast(`查询 ${limited.length} 位邻近选手...`, 'loading', 120000);
    }

    let done = 0;
    for (const t of limited) {
      const cached = getCachedRating(t.uid);
      if (cached != null) {
        result.set(t.uid, cached);
        done++;
        continue;
      }
      const aperf = await fetchUserAPerf(t.uid);
      if (aperf != null) result.set(t.uid, aperf);
      done++;
      if (done % 3 === 0) {
        toast(`查询邻近选手 ${done}/${limited.length}...`, 'loading', 8000);
      }
    }
    return result;
  }

  // ==================================================================
  //  比赛页面处理
  // ==================================================================
  async function handleContestPage() {
    const m = location.pathname.match(/\/contest\/(\d+)/);
    if (!m) return;
    const contestId = m[1];

    if (querying) return;

    const ctx = parseContext();
    const contest = ctx?.data?.contest;
    if (!contest) return;
    if (contest.rated !== 1) return;

    const now = Math.floor(Date.now() / 1000);
    if (!contest.endTime || contest.endTime > now) return;
    if (loadSettled().includes(contestId)) return;

    const existing = getPending(contestId);
    if (existing?.retryAt && Number(existing.retryAt) > now) return;
    if (existing?.queried && !existing?.failed) return;

    const uid = detectMyUid();
    if (!uid) return;

    querying = true;
    log(`开始查询比赛 #${contestId}`);

    try {
      const cfg = getConfig();
      const attempts = (existing?.attempts || 0) + 1;

      const ratedBound = inferRatedBound(contest);
      const center = inferCenter(ratedBound);

      toast(`查询「${contest.name}」排行榜...`, 'loading', 120000);
      const sb = await findMyRankInScoreboard(contestId, uid);

      if (sb.myRank == null) {
        upsertPending({
          id: contestId, name: contest.name,
          startTime: contest.startTime, endTime: contest.endTime,
          queried: false, failed: true, attempts,
          retryAt: now + 6 * 3600,
          recordedAt: now
        });
        toast(`「${contest.name}」未找到你的排名,6 小时后再试`, 'warn', 4000);
        return;
      }

      const myRank = sb.myRank;
      const allEntries = sb.allEntries;
      const totalCount = sb.totalCount || allEntries.length;

      let nearbyAPerfs = new Map();
      if (cfg.fetchMode === 'nearby') {
        nearbyAPerfs = await fetchNearbyAPerfs(allEntries, myRank, uid);
      }

      let myAPerf = center;
      const myElo = ctx?.data?.elo;
      if (Array.isArray(myElo) && myElo.length > 0) {
        const myRperf = rebuildRPerfHistory(myElo);
        const myPerf = rperfToPerf(myRperf);
        const computed = calcAPerf(myPerf);
        if (computed != null) myAPerf = computed;
      }

      const apList = buildAPerfPool(allEntries, nearbyAPerfs, myRank, myAPerf, uid);
      const perf = solvePerfStable(apList, myRank);
      const rperf = isFinite(ratedBound) ? Math.min(perf, ratedBound + 400) : perf;

      const lastKnown = findLastKnownRating();
      const currentRating = lastKnown.rating;
      const ratedCount = lastKnown.count;

      const newRating = currentRating > 0
        ? incrementalRating(currentRating, ratedCount, rperf)
        : ratingFromRPerfHistory([rperf]);

      const prediction = {
        delta: newRating - currentRating,
        newRating,
        perf: Math.round(perf),
        rperf: Math.round(rperf)
      };

      const accuracy = nearbyAPerfs.size >= cfg.nearbyRange ? 'high'
                     : nearbyAPerfs.size > 0 ? 'mid' : 'low';

      upsertPending({
        id: contestId, name: contest.name,
        startTime: contest.startTime, endTime: contest.endTime,
        queried: true, failed: false, attempts,
        myRank, totalRated: totalCount,
        currentRating, ratedBound, prediction,
        accuracy, nearbyCount: nearbyAPerfs.size,
        recordedAt: now
      });

      const accLabel = accuracy === 'high' ? '精确'
                     : accuracy === 'mid' ? '较精确' : '粗略';
      toast(
        `「${contest.name}」排名 #${myRank},预测 ${prediction.delta >= 0 ? '+' : ''}${prediction.delta}(${accLabel})`,
        'success', 4500
      );

      updateTopbarBadge();

    } catch (e) {
      const attempts = (existing?.attempts || 0) + 1;
      const cooldownSeconds = Math.ceil(getApiCooldownRemaining() / 1000);
      warn('查询失败:', e);

      upsertPending({
        id: contestId, name: contest.name,
        startTime: contest.startTime, endTime: contest.endTime,
        queried: false, failed: true, attempts,
        retryAt: now + (e.rateLimited
          ? Math.max(cooldownSeconds, 1800)
          : 3600),
        lastError: e.message,
        recordedAt: now
      });

      if (e.rateLimited) {
        const mins = Math.ceil(getApiCooldownRemaining() / 60000);
        toast(`洛谷接口暂时不可用,已停止请求,${mins} 分钟后再试`, 'warn', 6000);
      } else {
        toast(`「${contest.name}」查询失败,稍后再试`, 'error', 3500);
      }
    } finally {
      querying = false;
    }
  }

  function findLastKnownRating() {
    const pending = loadPending();
    for (const p of pending) {
      if (p.currentRating != null) {
        return { rating: p.currentRating, count: p.ratedCount || 0 };
      }
    }
    return { rating: 0, count: 0 };
  }

  // ==================================================================
  //  用户主页处理
  // ==================================================================
  function buildHistory(history) {
    if (!history.length) return [];
    const valid = history.filter(item =>
      typeof item.time === 'number' && typeof item.rating === 'number'
    );
    const sorted = valid.slice().sort((a, b) => a.time - b.time).map(item => {
      const prevDiff = (item.prevDiff === null || item.prevDiff === undefined) ? null : item.prevDiff;
      const rating = item.rating;
      return { ...item, rating, prevDiff,
        previousRating: prevDiff === null ? null : rating - prevDiff };
    });
    if (sorted.length > 0) sorted[0].isFirst = true;
    let maxRating = -Infinity;
    for (const d of sorted) if (d.rating > maxRating) maxRating = d.rating;
    for (const d of sorted) d.isHistoricalMax = d.rating === maxRating;
    return sorted;
  }

  function cleanupSettled(historyData) {
    const settledIds = new Set(
      historyData
        .map(h => h.contest?.id)
        .filter(id => id !== null && id !== undefined)
        .map(String)
    );
    const settledList = loadSettled();
    for (const id of settledIds) {
      if (!settledList.includes(id)) settledList.push(id);
    }
    saveSettled(settledList);

    const pending = loadPending();
    const remaining = pending.filter(p => !settledIds.has(String(p.id)));
    if (remaining.length !== pending.length) savePending(remaining);
    return remaining;
  }

  function getSignature(uid, history) {
    if (!history.length) return `${uid}:empty`;
    let sum = 0;
    for (const h of history) sum += (h.rating || 0) * 131 + (h.time || 0);
    return `${uid}:${history.length}:${sum}`;
  }

  function findCardByTitle(title) {
    for (const c of document.querySelectorAll('.l-card, [class*="l-card"]')) {
      const h = c.querySelector('.header h3, h3.lfe-h3');
      if (h && h.textContent && h.textContent.trim() === title) return c;
    }
    return null;
  }

  function fuseIntoNativeCard() {
    const nativeCard = findCardByTitle(NATIVE_CARD_TITLE);
    if (!nativeCard) return null;
    const nativeCanvas = nativeCard.querySelector('canvas#rating-chart');
    let ourDiv = nativeCard.querySelector('#' + CHART_ID);
    if (!ourDiv || !document.body.contains(ourDiv)) {
      ourDiv = document.createElement('div');
      ourDiv.id = CHART_ID;
      ourDiv.style.cssText = 'width:100%;height:320px;';
      if (nativeCanvas && nativeCanvas.parentNode === nativeCard) {
        nativeCanvas.insertAdjacentElement('afterend', ourDiv);
      } else nativeCard.appendChild(ourDiv);
    }
    return ourDiv;
  }

  // 修复 5:tooltip 内容全部转义
  function buildTooltipHtml(item) {
    if (!item) return '';
    const start = item.contest?.startTime ? formatTime(item.contest.startTime) : '未知';
    const end   = item.contest?.endTime   ? formatTime(item.contest.endTime)   : '未知';
    const title = escapeHtml(item.contest?.name || '未知比赛');

    let ratingLine;
    if (item.previousRating == null) {
      ratingLine = `等级分:<b style="color:#fff;">${item.rating}</b>`;
    } else {
      const prevRating = Math.round(item.previousRating);
      const diff = item.prevDiff || 0;
      let dHtml;
      if (diff > 0) dHtml = `<b style="color:#94d66d;">+${diff}</b>`;
      else if (diff < 0) dHtml = `<b style="color:#ff9ea3;">${diff}</b>`;
      else dHtml = `<b style="color:#bfbfbf;">±0</b>`;
      ratingLine = `等级分: ${prevRating} ${dHtml} = <b style="color:#fff;">${item.rating}</b>`;
    }

    const maxLine = item.isHistoricalMax
      ? `<i style="display:block;color:#ffc116;font-size:12px;margin-top:4px;font-style:italic;">达成历史最高</i>`
      : '';

    return `
      <div style="max-width:300px;
        font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif;
        line-height:1.5;text-align:left;">
        <div style="font-size:14px;font-weight:600;color:#fff;margin-bottom:4px;
          white-space:normal;word-break:break-word;">${title}</div>
        <div style="font-size:12px;color:#a0a0a0;margin-bottom:8px;
          font-variant-numeric:tabular-nums;">${start} ~ ${end}</div>
        <div style="font-size:13px;color:#d0d0d0;
          font-variant-numeric:tabular-nums;">${ratingLine}</div>
        ${maxLine}
      </div>
    `;
  }

  function buildOption(data) {
    let maxRating = 0;
    for (const d of data) if (d.rating > maxRating) maxRating = d.rating;
    const yMax = Math.ceil(maxRating / 400) * 400 || 400;

    const seriesData = data.map(item => {
      const base = {
        value: [item.time * 1000, item.rating],
        symbol: 'circle', symbolSize: 8, rawInfo: item
      };
      if (item.isHistoricalMax) {
        base.itemStyle = {
          color: '#fff', borderColor: '#e74c3c', borderWidth: 2,
          shadowBlur: 6, shadowColor: 'rgba(231,76,60,0.5)'
        };
      } else {
        base.itemStyle = { color: '#fff', borderColor: '#5dade2', borderWidth: 2 };
      }
      return base;
    });

    return {
      grid: { left: 0, right: 15, top: 25, bottom: 20, containLabel: true },
      xAxis: {
        type: 'time',
        axisLine: { lineStyle: { color: '#ccc' } },
        axisLabel: { color: '#555', fontSize: 12, hideOverlap: true, formatter: '{yyyy}-{MM}' },
        splitLine: { show: false }
      },
      yAxis: {
        type: 'value', min: 0, max: yMax, interval: 400,
        axisLine: { show: false },
        axisLabel: { color: '#555', fontSize: 12 },
        splitLine: { show: true, lineStyle: { color: '#e0e0e0' } }
      },
      tooltip: {
        trigger: 'item', appendToBody: true,
        showDelay: 0, hideDelay: 80,
        backgroundColor: 'rgba(34,34,34,0.94)',
        borderColor: 'rgba(255,255,255,0.08)', borderWidth: 1,
        borderRadius: 8, padding: [10, 14],
        textStyle: { color: '#fff', fontSize: 13 },
        extraCssText: 'box-shadow: 0 6px 24px rgba(0,0,0,0.28), 0 2px 6px rgba(0,0,0,0.18);',
        formatter: params => buildTooltipHtml(params.data?.rawInfo)
      },
      series: [{
        name: '等级分', type: 'line', data: seriesData, smooth: false,
        lineStyle: { type: 'solid', color: '#5dade2', width: 2.5 },
        animationDuration: 600,
        emphasis: {
          scale: 1.5,
          itemStyle: { borderWidth: 3, shadowBlur: 10, shadowColor: 'rgba(93,173,226,0.85)' }
        }
      }]
    };
  }

  function attachResize(container) {
    if (!resizeHandler) {
      resizeHandler = () => {
        if (chart && chartContainer && document.body.contains(chartContainer)) chart.resize();
      };
      window.addEventListener('resize', resizeHandler, { passive: true });
    }
    if (resizeObserver) resizeObserver.disconnect();
    resizeObserver = new ResizeObserver(() => { if (chart) chart.resize(); });
    resizeObserver.observe(container);
  }

  function bindChartClick() {
    if (!chart) return;
    chart.off('click');
    chart.on('click', params => {
      const item = params.data?.rawInfo;
      if (!item) return;
      const cid = item.contest?.id;
      if (cid) window.open(`https://www.luogu.com.cn/contest/${cid}`, '_blank');
    });
  }

  function renderPendingList(card, pending, currentRating) {
    const old = card.querySelector('.xlg-pending-wrap');
    if (old) old.remove();
    if (!pending.length) return;

    const wrap = document.createElement('div');
    wrap.className = 'xlg-pending-wrap';

    const title = document.createElement('div');
    title.className = 'xlg-pending-title';
    title.textContent = `⏳ 有 ${pending.length} 场已参加、未结算的比赛`;
    wrap.appendChild(title);

    for (const c of pending) {
      const pred = c.prediction || {};
      const delta = pred.delta != null ? pred.delta : 0;
      const newRating = pred.newRating != null ? pred.newRating : currentRating;

      const row = document.createElement('div');
      row.className = 'xlg-pending-row';

      const nameWrap = document.createElement('div');
      nameWrap.className = 'xlg-pending-name';
      const a = document.createElement('a');
      a.href = `https://www.luogu.com.cn/contest/${c.id}/scoreboard`;
      a.target = '_blank';
      a.textContent = c.name;
      nameWrap.appendChild(a);

      const meta = document.createElement('span');
      meta.className = 'xlg-pending-meta';
      if (c.myRank != null) meta.textContent = `排名 #${c.myRank}/${c.totalRated}`;
      else if (c.failed) meta.textContent = `查询失败 ×${c.attempts || 0}`;
      else meta.textContent = '待查询';
      nameWrap.appendChild(meta);

      const badge = document.createElement('span');
      if (c.queried && c.myRank != null && !c.failed) {
        if (c.accuracy === 'high') { badge.className = 'xlg-pending-badge'; badge.textContent = '精确'; }
        else if (c.accuracy === 'mid') { badge.className = 'xlg-pending-badge acc'; badge.textContent = '较精确'; }
        else { badge.className = 'xlg-pending-badge fail'; badge.textContent = '粗略'; }
      } else if (c.failed) {
        badge.className = 'xlg-pending-badge fail'; badge.textContent = '待重试';
      } else {
        badge.className = 'xlg-pending-badge wait'; badge.textContent = '待查询';
      }
      nameWrap.appendChild(badge);

      const deltaWrap = document.createElement('div');
      deltaWrap.className = 'xlg-pending-delta';
      if (c.myRank != null && c.prediction) {
        if (delta > 0) { deltaWrap.classList.add('pos'); deltaWrap.textContent = `+${delta}`; }
        else if (delta < 0) { deltaWrap.classList.add('neg'); deltaWrap.textContent = `${delta}`; }
        else { deltaWrap.classList.add('zero'); deltaWrap.textContent = '±0'; }
        const estTag = document.createElement('span');
        estTag.className = 'xlg-pending-est';
        estTag.textContent = `→ ${newRating}`;
        deltaWrap.appendChild(estTag);
      } else {
        deltaWrap.classList.add('zero');
        deltaWrap.textContent = '—';
      }

      row.appendChild(nameWrap);
      row.appendChild(deltaWrap);
      wrap.appendChild(row);
    }

    const hint = document.createElement('div');
    hint.className = 'xlg-pending-hint';
    hint.textContent = '⚠ 预测基于公开公式与经验参数,实际以洛谷官方结算为准。';
    wrap.appendChild(hint);

    card.appendChild(wrap);
  }

  function handleUserPage() {
    const uidMatch = location.pathname.match(/\/user\/(\d+)/);
    if (!uidMatch) {
      restoreNativeRatingCanvas();
      return;
    }
    const pageUid = uidMatch[1];

    const me = detectMyUid();
    if (!me) {
      restoreNativeRatingCanvas();
      return;
    }

    if (pageUid !== me) {
      restoreNativeRatingCanvas();
      log(`非本人主页 (${pageUid} ≠ ${me}),恢复原生 canvas`);
      return;
    }

    const ctx = parseContext();
    const elo = ctx?.data?.elo;
    if (!Array.isArray(elo) || !elo.length) return;

    const historyData = buildHistory(elo);
    const currentRating = historyData[historyData.length - 1]?.rating || 0;
    const pending = cleanupSettled(historyData);

    if (pending.length > 0) {
      const arr = loadPending();
      for (const c of arr) {
        if (c.currentRating == null) {
          c.currentRating = currentRating;
          c.ratedCount = historyData.length;
        }
      }
      savePending(arr);
    }

    const chartDiv = fuseIntoNativeCard();
    if (!chartDiv) return;

    hideNativeRatingCanvas();

    const sig = getSignature(me, historyData);
    const needRender = sig !== lastSig ||
      !chart || !chartContainer || !document.body.contains(chartContainer);

    if (needRender) {
      if (chart && (chartContainer !== chartDiv || !document.body.contains(chartContainer))) {
        chart.dispose(); chart = null; chartContainer = null;
      }
      if (!chart) {
        try {
          // 修复 6:容器宽高为 0 时延迟初始化
          if (chartDiv.clientWidth === 0 || chartDiv.clientHeight === 0) {
            setTimeout(() => { lastSig = null; handleUserPage(); }, 200);
            return;
          }
          chart = echarts.init(chartDiv, null, { renderer: 'canvas' });
          chartContainer = chartDiv;
          attachResize(chartDiv);
          bindChartClick();
        } catch (e) {
          toast('ECharts 初始化失败:' + e.message, 'error'); return;
        }
      }
      chart.setOption(buildOption(historyData), true);
      lastSig = sig;
    }

    const parentCard = chartDiv.closest('.l-card, [class*="l-card"]') || chartDiv.parentElement;
    if (parentCard) renderPendingList(parentCard, pending, currentRating);
  }

  // ==================================================================
  //  顶栏图标 + 设置面板
  // ==================================================================
  function injectTopbarIcon() {
    if (document.getElementById('xlg-topbar-btn')) return;

    const userNav = document.querySelector('.user-nav');
    if (!userNav) return;
    const avatar = userNav.querySelector('.avatar');
    if (!avatar) return;

    const btn = document.createElement('a');
    btn.id = 'xlg-topbar-btn';
    btn.href = 'javascript:void 0';
    btn.className = 'link';
    btn.title = 'XLG-等级分设置';
    btn.innerHTML = ICON_GEAR;

    btn.addEventListener('click', e => {
      e.preventDefault();
      e.stopPropagation();
      toggleSettingsPanel();
    });

    avatar.insertAdjacentElement('beforebegin', btn);
    updateTopbarBadge();
  }

  function updateTopbarBadge() {
    const btn = document.getElementById('xlg-topbar-btn');
    if (!btn) return;
    const old = btn.querySelector('.xlg-badge');
    if (old) old.remove();
    const pending = loadPending();
    if (pending.length > 0) {
      const badge = document.createElement('span');
      badge.className = 'xlg-badge';
      badge.textContent = pending.length;
      btn.appendChild(badge);
    }
  }

  function renderToggle(id, label, checked, hint) {
    return `
      <div class="xlg-sp-toggle">
        <input type="checkbox" id="${id}" ${checked ? 'checked' : ''}>
        <label for="${id}">
          ${TOGGLE_OFF}
          ${TOGGLE_ON}
          <span>${label}</span>
          ${hint ? `<span class="xlg-sp-toggle-hint">${hint}</span>` : ''}
        </label>
      </div>
    `;
  }

  function toggleSettingsPanel() {
    if (settingsPanelEl) closeSettingsPanel();
    else openSettingsPanel();
  }

  function openSettingsPanel() {
    if (settingsPanelEl) return;

    const cfg = getConfig();
    const pendingCount = loadPending().length;

    const overlay = document.createElement('div');
    overlay.id = 'xlg-settings-overlay';

    const panel = document.createElement('div');
    panel.id = 'xlg-settings-panel';

    panel.innerHTML = `
      <div class="xlg-sp-header">
        <h3>${ICON_GEAR}<span>XLG-等级分设置</span></h3>
        <button class="xlg-sp-close" title="关闭">×</button>
      </div>
      <div class="xlg-sp-body">
        <div class="xlg-sp-section">
          <div class="xlg-sp-section-title">预测</div>
          ${renderToggle('xlg-cb-nearby', '邻近选手精确查询', cfg.fetchMode === 'nearby', '关闭后仅分布近似')}
          ${renderToggle('xlg-cb-debug', '调试日志', cfg.debug, '控制台输出')}
        </div>
        <div class="xlg-sp-section">
          <div class="xlg-sp-section-title">查询范围</div>
          <div class="xlg-sp-row">
            <div class="xlg-sp-label"><span>邻近范围</span><span class="xlg-sp-hint">前后各 N 名</span></div>
            <div class="xlg-sp-options" data-key="nearbyRange">
              <div class="xlg-sp-option" data-value="5">±5</div>
              <div class="xlg-sp-option" data-value="8">±8</div>
              <div class="xlg-sp-option" data-value="10">±10</div>
              <div class="xlg-sp-option" data-value="15">±15</div>
            </div>
          </div>
          <div class="xlg-sp-row">
            <div class="xlg-sp-label"><span>最大排行榜页数</span><span class="xlg-sp-hint">每页约 50 人</span></div>
            <div class="xlg-sp-options" data-key="maxPages">
              <div class="xlg-sp-option" data-value="3">3 页</div>
              <div class="xlg-sp-option" data-value="5">5 页</div>
              <div class="xlg-sp-option" data-value="8">8 页</div>
            </div>
          </div>
        </div>
        <div class="xlg-sp-section">
          <div class="xlg-sp-section-title">速率控制</div>
          <div class="xlg-sp-row">
            <div class="xlg-sp-label"><span>请求间隔</span><span class="xlg-sp-hint">最小 3.5 秒</span></div>
            <div class="xlg-sp-options" data-key="requestDelay">
              <div class="xlg-sp-option" data-value="3500">3.5 秒</div>
              <div class="xlg-sp-option" data-value="5000">5 秒</div>
              <div class="xlg-sp-option" data-value="8000">8 秒</div>
            </div>
          </div>
        </div>
        <div class="xlg-sp-section">
          <div class="xlg-sp-section-title">数据管理</div>
          <div class="xlg-sp-row">
            <div class="xlg-sp-label"><span>未结算比赛</span><span class="xlg-sp-hint">当前 ${pendingCount} 场</span></div>
            <div class="xlg-sp-actions">
              <button class="xlg-sp-btn danger" data-action="clear-pending">清空未结算</button>
              <button class="xlg-sp-btn danger" data-action="clear-settled">清空已结算</button>
              <button class="xlg-sp-btn danger" data-action="clear-cache">清空缓存</button>
            </div>
          </div>
        </div>
      </div>
      <div class="xlg-sp-info">
        预测基于公开公式与经验参数,实际结果以洛谷官方结算为准。所有请求严格串行,最小间隔 3.5 秒,遇限流自动冷却。
      </div>
      <div class="xlg-sp-footer">
        <button class="xlg-sp-btn" data-action="reset">重置默认</button>
        <button class="xlg-sp-btn primary" data-action="save">保存并关闭</button>
      </div>
    `;

    overlay.appendChild(panel);
    document.body.appendChild(overlay);
    settingsPanelEl = overlay;

    positionSettingsPanel();

    function refreshOptions() {
      const c = getConfig();
      for (const group of panel.querySelectorAll('.xlg-sp-options')) {
        const key = group.dataset.key;
        const val = String(c[key]);
        for (const opt of group.querySelectorAll('.xlg-sp-option')) {
          opt.classList.toggle('active', opt.dataset.value === val);
        }
      }
      const cbNearby = panel.querySelector('#xlg-cb-nearby');
      const cbDebug = panel.querySelector('#xlg-cb-debug');
      if (cbNearby) cbNearby.checked = c.fetchMode === 'nearby';
      if (cbDebug) cbDebug.checked = c.debug;
    }
    refreshOptions();

    panel.querySelector('.xlg-sp-close').addEventListener('click', closeSettingsPanel);

    panel.addEventListener('click', e => {
      const opt = e.target.closest('.xlg-sp-option');
      if (!opt) return;
      const group = opt.closest('.xlg-sp-options');
      if (!group) return;
      const key = group.dataset.key;
      let value = opt.dataset.value;
      if (['nearbyRange', 'requestDelay', 'maxPages'].includes(key)) {
        value = parseInt(value);
      }
      const c = getConfig();
      c[key] = value;
      saveConfig(c);
      refreshOptions();
    });

    panel.addEventListener('change', e => {
      const id = e.target.id;
      if (!id) return;
      const c = getConfig();
      if (id === 'xlg-cb-nearby') c.fetchMode = e.target.checked ? 'nearby' : 'none';
      else if (id === 'xlg-cb-debug') c.debug = e.target.checked;
      saveConfig(c);
    });

    panel.addEventListener('click', e => {
      const btn = e.target.closest('button[data-action]');
      if (!btn) return;
      const action = btn.dataset.action;

      if (action === 'save') {
        toast('设置已保存', 'success', 1800);
        closeSettingsPanel();
      } else if (action === 'reset') {
        if (!confirm('确定重置为默认设置?')) return;
        saveConfig({ ...DEFAULT_SETTINGS });
        refreshOptions();
        toast('已重置默认设置', 'info', 1800);
      } else if (action === 'clear-pending') {
        if (!confirm('确定清空所有未结算比赛记录?')) return;
        localStorage.removeItem(PENDING_KEY);
        updateTopbarBadge();
        toast('已清空未结算记录', 'success', 1800);
        closeSettingsPanel();
      } else if (action === 'clear-settled') {
        if (!confirm('确定清空已结算比赛 ID 列表?')) return;
        localStorage.removeItem(SETTLED_KEY);
        toast('已清空已结算列表', 'success', 1800);
      } else if (action === 'clear-cache') {
        if (!confirm('确定清空用户 Rating 缓存?')) return;
        localStorage.removeItem(RATING_CACHE_KEY);
        toast('已清空 Rating 缓存', 'success', 1800);
      }
    });

    overlay.addEventListener('click', e => {
      if (e.target === overlay) closeSettingsPanel();
    });

    window.addEventListener('resize', positionSettingsPanel, { passive: true });
    window.addEventListener('scroll', positionSettingsPanel, { passive: true, capture: true });
  }

  function positionSettingsPanel() {
    if (!settingsPanelEl) return;
    const panel = settingsPanelEl.querySelector('#xlg-settings-panel');
    const btn = document.getElementById('xlg-topbar-btn');
    if (!panel || !btn) return;

    const rect = btn.getBoundingClientRect();
    const top = Math.round(rect.bottom + 6);
    const right = Math.max(8, Math.round(window.innerWidth - rect.right));

    panel.style.top = `${top}px`;
    panel.style.right = `${right}px`;
    panel.style.left = 'auto';
  }

  function closeSettingsPanel() {
    if (!settingsPanelEl) return;
    window.removeEventListener('resize', positionSettingsPanel, { passive: true });
    window.removeEventListener('scroll', positionSettingsPanel, { capture: true });
    settingsPanelEl.remove();
    settingsPanelEl = null;
  }

  // ==================================================================
  //  路由 + 初始化
  // ==================================================================
  function route() {
    clearTimeout(runTimer);
    runTimer = setTimeout(() => {
      injectTopbarIcon();

      const path = location.pathname;

      // 修复 7:只在路径变化时才处理,避免无意义的重复
      if (path === lastRoutePath) return;
      lastRoutePath = path;

      restoreNativeRatingCanvas();

      if (path.match(/^\/user\/\d+/)) {
        handleUserPage();
      } else if (path.match(/^\/contest\/\d+/)) {
        handleContestPage();
      }
    }, 500);
  }

  function init() {
    injectBaseStyles();

    const push = history.pushState;
    const replace = history.replaceState;
    history.pushState = function () { push.apply(this, arguments); route(); };
    history.replaceState = function () { replace.apply(this, arguments); route(); };
    window.addEventListener('popstate', route, { passive: true });
    window.addEventListener('hashchange', route, { passive: true });

    // 修复 8:节流顶栏图标检查
    let topbarCheckTimer = null;
    const observer = new MutationObserver(() => {
      if (topbarCheckTimer) return;
      topbarCheckTimer = setTimeout(() => {
        topbarCheckTimer = null;
        if (!document.getElementById('xlg-topbar-btn')) {
          injectTopbarIcon();
        }
      }, 300);
    });
    observer.observe(document.body, { childList: true, subtree: true });

    route();
  }

  if (document.readyState === 'complete') init();
  else window.addEventListener('load', init, { once: true });
})();
:::