洛谷美化油猴插件

· · 闲话

隐藏题号 & 难度。

:::info[]

// ==UserScript==
// @name         Luogu 题号+难度 整合工具
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  题号切换+难度隐藏 整合版,主页面隐藏难度按钮,题库页不干扰
// @author       LTTXiaochuan
// @match        https://www.luogu.com.cn/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    // ====================== 工具函数:页面判断 ======================
    const path = location.pathname;
    const searchParams = new URLSearchParams(location.search);

    // 1. 仅匹配:/problem/Pxxxx 或 /contest/xxx/problem/xxx,排除 /problem/list 等题库页
    const isProblemDetailPage =
        (path.startsWith('/problem/') && !path.includes('/list')) ||
        (path.includes('/contest/') && path.includes('/problem/'));

    // 2. 判断是否为洛谷主页面(根路径 / 或 /?xxx)
    const isHomePage = path === '/' && searchParams.get('pid') === null;

    // ====================== 第一部分:题号切换功能(仅题目详情页执行) ======================
    if (isProblemDetailPage) {
        // 默认隐藏
        let mode = GM_getValue('pid_mode', 'hidden');

        // 核心样式
        const css1 = `
        #pidBtn {
            position: fixed;
            top: 12px;
            right: 12px;
            z-index: 999999;
            background: rgba(0,0,0,0.6);
            color: #fff !important;
            padding: 6px 8px;
            font-size: 12px;
            border-radius: 6px;
            cursor: move;
            user-select: none;
            box-shadow: 0 2px 6px rgba(0,0,0,.4);
            min-width: 120px;
            text-align: center;
            font-family: 'Segoe UI',微软雅黑,sans-serif;
        }
        #pidBtn small { opacity: .8; display:block; font-size:11px; margin-top:2px; color: #fff !important; }
        /* 隐藏题号 */
        body.hidePid .breadcrumb a[href*="P"] { display:none !important; }
        /* 打印只隐藏按钮,不破坏页面 */
        @media print { #pidBtn { display:none !important; } }
        `;
        const style1 = document.createElement('style');
        style1.textContent = css1;
        document.head.appendChild(style1);

        // 执行功能 + 侧栏暴力隐藏
        function run() {
            document.body.classList.toggle('hidePid', mode === 'hidden');

            if(mode === 'hidden'){
                const all = document.getElementsByTagName('*');
                for(let el of all){
                    if(el.textContent.trim() === '题目编号'){
                        const val = el.nextElementSibling || el.parentElement.lastElementChild;
                        if(val && val.textContent.startsWith('P')) val.style.display = 'none';
                    }
                }
            }else{
                const all = document.getElementsByTagName('*');
                for(let el of all){
                    if(el.textContent.trim() === '题目编号'){
                        const val = el.nextElementSibling || el.parentElement.lastElementChild;
                        if(val) val.style.display = '';
                    }
                }
            }

            // 主标题原版逻辑
            const h1 = document.querySelector('h1');
            if(h1){
                if(mode === 'hidden'){ h1._o = h1._o || h1.textContent; h1.textContent = 'LoveFurina'; }
                else { h1._o && (h1.textContent = h1._o); }
            }
            // 文字修改为:隐藏题号/显示题号 + (点击切换)
            const label = mode === 'hidden' ? '隐藏题号' : '显示题号';
            document.getElementById('pidBtn').innerHTML = `<strong>${label}</strong><small>(点击切换)</small>`;
        }

        // 创建按钮
        function btn() {
            const b = document.createElement('div');
            b.id = 'pidBtn';
            const x=GM_getValue('x'), y=GM_getValue('y');
            if(x!=null&&y!=null){
                b.style.left=x+'px';
                b.style.top=y+'px';
                b.style.right='auto';
            }else{
                b.style.bottom = "65px";
                b.style.right = "12px";
                b.style.top = "auto";
            }

            let ox,oy,d=false;
            let isDragged = false;

            b.onmousedown = (e)=>{
                d=true;
                isDragged = false;
                ox=e.clientX-b.offsetLeft;
                oy=e.clientY-b.offsetTop;
                b.style.opacity=0.6;
            };

            document.onmousemove = (e)=>{
                if(!d)return;
                isDragged = true;
                b.style.left=Math.max(0,Math.min(innerWidth-b.offsetWidth,e.clientX-ox))+'px';
                b.style.top=Math.max(0,Math.min(innerHeight-b.offsetHeight,e.clientY-oy))+'px';
            };

            document.onmouseup = ()=>{
                if(!d)return;
                d=false;
                b.style.opacity=1;
                GM_setValue('x',b.offsetLeft);
                GM_setValue('y',b.offsetTop);
            };

            b.onclick = ()=>{
                if(!isDragged){
                    mode=mode==='hidden'?'show':'hidden';
                    GM_setValue('pid_mode',mode);
                    run();
                }
            };

            document.body.appendChild(b);
            run();
        }

        // 标签页标题(仅题目页执行)
        const targetTitle = "芙芙超可爱~";
        function setFurinaTitle() {
            if (document.title !== targetTitle) {
                document.title = targetTitle;
            }
        }
        setInterval(setFurinaTitle, 300);

        // 极速响应:轮询间隔50ms(仅题目页执行)
        setInterval(() => {
            const h1 = document.querySelector('h1');
            if(h1){
                if(mode === 'hidden'){
                    h1._o = h1._o || h1.textContent;
                    h1.textContent = 'LoveFurina';
                } else {
                    h1._o && (h1.textContent = h1._o);
                }
            }
        }, 50);

        // 极速响应:题号隐藏(仅题目页执行)
        setInterval(() => {
            if(mode === 'hidden'){
                const all = document.getElementsByTagName('*');
                for(let el of all){
                    if(el.textContent.trim() === '题目编号'){
                        const val = el.nextElementSibling || el.parentElement.lastElementChild;
                        if(val && val.textContent.startsWith('P')) val.style.display = 'none';
                    }
                }
            }
        }, 50);

        // 启动题号功能(仅题目页执行)
        window.addEventListener('load', ()=>{ btn(); setTimeout(run,300); setTimeout(run,800); });
    }

    // ====================== 第二部分:难度隐藏功能(主页面除外,完全不变) ======================
    if (!isHomePage) { // 主页面不执行难度功能
        const DEFAULT_MODE = GM_getValue('lg_diff_mode', 'hover');
        const selectors = [
            '.l-flex-info-row a[href*="problem/list?difficulty"] span',
            '.difficulty span span',
            '.difficulty span.lfe-caption'
        ];

        const styleId = 'tm-luogu-diff-style';
        const css2 = `
        .tm-diff-hidden, .tm-diff-hover { transition: opacity .15s ease !important; }
        .tm-diff-hidden { opacity: 0 !important; }
        .tm-diff-hover { opacity: 0 !important; }
        .tm-diff-hover:hover { opacity: 1 !important; }
        #tm-luogu-diff-toggle {
            position: fixed;
            bottom: 12px;
            right: 12px;
            z-index: 999999;
            background: rgba(0,0,0,0.6);
            color: #fff !important;
            padding: 6px 8px;
            font-size: 12px;
            border-radius: 6px;
            cursor: move;
            user-select: none;
            box-shadow: 0 2px 6px rgba(0,0,0,.4);
        }
        #tm-luogu-diff-toggle small { opacity: .8; display:block; font-size:11px; margin-top:2px; color: #fff !important; }
        `;

        function injectStyle() {
            if (document.getElementById(styleId)) return;
            const s = document.createElement('style');
            s.id = styleId;
            s.textContent = css2;
            document.head.appendChild(s);
        }

        let currentMode = DEFAULT_MODE;
        function applyToElement(el, mode) {
            el.classList.remove('tm-diff-hidden', 'tm-diff-hover');
            if (mode === 'hidden') el.classList.add('tm-diff-hidden');
            else if (mode === 'hover') el.classList.add('tm-diff-hover');
        }

        function applyModeToAll(mode) {
            const combined = selectors.join(',');
            document.querySelectorAll(combined).forEach(el => applyToElement(el, mode));
        }

        let mo = null;
        function startObserver() {
            if (mo) return;
            mo = new MutationObserver(muts => {
                if (muts.some(m => m.addedNodes && m.addedNodes.length)) {
                    applyModeToAll(currentMode);
                }
            });
            mo.observe(document.body, { childList: true, subtree: true });
        }

        function saveMode(mode) {
            currentMode = mode;
            GM_setValue('lg_diff_mode', mode);
            updateToggleText();
            applyModeToAll(mode);
        }

        function nextMode(m) {
            if (m === 'show') return 'hover';
            if (m === 'hover') return 'hidden';
            return 'show';
        }

        function createToggle() {
            if (document.getElementById('tm-luogu-diff-toggle')) return;
            const btn = document.createElement('div');
            btn.id = 'tm-luogu-diff-toggle';
            btn.title = '点击切换难度显示模式';
            btn.style.minWidth = '120px';
            btn.style.textAlign = 'center';
            btn.style.fontFamily = 'Segoe UI,微软雅黑,sans-serif';

            const savedX = GM_getValue('lg_diff_x', null);
            const savedY = GM_getValue('lg_diff_y', null);
            if (savedX !== null && savedY !== null) {
                btn.style.left = savedX + 'px';
                btn.style.top = savedY + 'px';
                btn.style.right = 'auto';
            }

            btn.addEventListener('click', (e) => {
                if (btn._dragging) return;
                saveMode(nextMode(currentMode));
            });

            makeDraggable(btn);
            document.body.appendChild(btn);
            updateToggleText();
        }

        function updateToggleText() {
            const btn = document.getElementById('tm-luogu-diff-toggle');
            if (!btn) return;
            const label = (currentMode === 'show') ? '显示难度' : (currentMode === 'hover') ? '悬停显示难度' : '隐藏难度';
            btn.innerHTML = ` <strong> ${label} </strong> <small> (点击切换) </small> `;
        }

        // 拖动逻辑
        function makeDraggable(el) {
            let offsetX, offsetY, isDown = false;

            el.addEventListener('mousedown', (e) => {
                isDown = true;
                el._dragging = false;
                offsetX = e.clientX - el.offsetLeft;
                offsetY = e.clientY - el.offsetTop;
                el.style.opacity = "0.6";
                document.addEventListener('mousemove', move);
                document.addEventListener('mouseup', up);
            });

            function move(e) {
                if (!isDown) return;
                el._dragging = true;
                let newLeft = e.clientX - offsetX;
                let newTop = e.clientY - offsetY;

                const maxLeft = window.innerWidth - el.offsetWidth;
                const maxTop = window.innerHeight - el.offsetHeight;
                newLeft = Math.max(0, Math.min(maxLeft, newLeft));
                newTop = Math.max(0, Math.min(maxTop, newTop));

                el.style.left = newLeft + 'px';
                el.style.top = newTop + 'px';
                el.style.right = 'auto';
            }

            function up() {
                if (!isDown) return;
                isDown = false;
                el.style.opacity = "1";
                document.removeEventListener('mousemove', move);
                document.removeEventListener('mouseup', up);
                GM_setValue('lg_diff_x', el.offsetLeft);
                GM_setValue('lg_diff_y', el.offsetTop);
                setTimeout(() => { el._dragging = false; }, 50);
            }
        }

        function init() {
            injectStyle();
            createToggle();
            applyModeToAll(currentMode);
            startObserver();
            window.addEventListener('load', () => setTimeout(() => applyModeToAll(currentMode), 300));
        }

        // 启动难度功能
        init();
    }
})();

:::

预览题目显示难度 & 标签。

:::info[]

// ==UserScript==
// @name         洛谷题目难度着色+标签速览
// @namespace    https://www.luogu.com.cn/
// @version      2.2
// @description  自动着色洛谷题目编号,悬停显示标签,双击跳转题目;
// @author       Assistant
// @match        https://www.luogu.com.cn/*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_openInTab
// @connect      cdn.luogu.com.cn
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/pako.min.js
// ==/UserScript==

(function() {
    'use strict';

    // 难度颜色映射
    const DIFFICULTY_COLORS = {
        0: '#808080', // 灰色
        1: '#e74c3c', // 红色
        2: '#e67e22', // 橙色
        3: '#f1c40f', // 黄色
        4: '#2ecc71', // 绿色
        5: '#00bcd4', // 青色
        6: '#2196F3', // 蓝色
        7: '#9c3dcf', // 紫色
        8: '#000000'  // 黑色
    };

    const DATA_URL = 'https://cdn.luogu.com.cn/problemset-open/latest.ndjson.gz';
    const DB_NAME = 'LuoguProblemDB';
    const DB_VERSION = 1;
    const STORE_NAME = 'problems';
    const MIN_UPDATE_INTERVAL = 3 * 24 * 60 * 60 * 1000; // 3天(毫秒)

    // 题目编号正则,支持 P, B, CF, SP, AT, UVA 等
    const PID_PATTERN = /\b(?:P|B|CF|SP|AT(?:_[A-Za-z0-9]+)?|UVA)\d+[A-Za-z0-9]*\b/g;

    let problemDataMap = new Map();   // pid -> { difficulty, title, tags, type }
    let processedTextNodes = new WeakSet();
    let processedLinks = new WeakSet();
    let observer = null;
    let tooltip = null;

    // ---------- 提示框 ----------
    function createTooltip() {
        if (tooltip) return;
        tooltip = document.createElement('div');
        tooltip.id = 'luogu-problem-tooltip';
        tooltip.style.cssText = `
            position: fixed;
            z-index: 9999999;
            background: rgba(30, 30, 30, 0.95);
            color: #fff;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 12px;
            max-width: 300px;
            word-wrap: break-word;
            pointer-events: none;
            display: none;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
        `;
        document.body.appendChild(tooltip);
    }

    function showTooltip(x, y, content) {
        createTooltip();
        tooltip.innerHTML = content;
        tooltip.style.display = 'block';
        const rect = tooltip.getBoundingClientRect();
        let left = x + 10;
        let top = y + 10;
        if (left + rect.width > window.innerWidth - 5) left = x - rect.width - 10;
        if (top + rect.height > window.innerHeight - 5) top = y - rect.height - 10;
        tooltip.style.left = left + 'px';
        tooltip.style.top = top + 'px';
    }

    function hideTooltip() {
        if (tooltip) tooltip.style.display = 'none';
    }

    // ---------- 状态提示 ----------
    function showStatusMessage(text, isError = false) {
        const existing = document.getElementById('luogu-problem-status');
        if (existing) existing.remove();
        const div = document.createElement('div');
        div.id = 'luogu-problem-status';
        div.style.cssText = `
            position: fixed; top: 20px; right: 20px;
            background: ${isError ? '#f44336' : '#2196F3'};
            color: white; padding: 8px 16px;
            border-radius: 6px; z-index: 999999;
            font-size: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.2);
            max-width: 300px; word-wrap: break-word;
        `;
        div.textContent = text;
        document.body.appendChild(div);
        if (!isError) {
            setTimeout(() => { if (div.parentNode) div.remove(); }, 5000);
        }
    }

    // ---------- IndexedDB 操作 ----------
    function openDB() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(DB_NAME, DB_VERSION);
            request.onupgradeneeded = (e) => {
                const db = e.target.result;
                if (!db.objectStoreNames.contains(STORE_NAME)) {
                    db.createObjectStore(STORE_NAME, { keyPath: 'pid' });
                }
            };
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async function getProblemCount() {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(STORE_NAME, 'readonly');
            const store = tx.objectStore(STORE_NAME);
            const req = store.count();
            req.onsuccess = () => resolve(req.result);
            req.onerror = () => reject(req.error);
        });
    }

    async function clearProblems() {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(STORE_NAME, 'readwrite');
            const store = tx.objectStore(STORE_NAME);
            const req = store.clear();
            req.onsuccess = () => resolve();
            req.onerror = () => reject(req.error);
        });
    }

    async function bulkInsert(problems) {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(STORE_NAME, 'readwrite');
            const store = tx.objectStore(STORE_NAME);
            for (const p of problems) {
                store.put(p);
            }
            tx.oncomplete = () => resolve();
            tx.onerror = () => reject(tx.error);
        });
    }

    async function loadProblemDataMap() {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(STORE_NAME, 'readonly');
            const store = tx.objectStore(STORE_NAME);
            const req = store.getAll();
            req.onsuccess = () => {
                const map = new Map();
                req.result.forEach(item => {
                    map.set(item.pid, {
                        difficulty: item.difficulty,
                        title: item.title || '',
                        tags: item.tags || [],
                        type: item.type || ''
                    });
                });
                resolve(map);
            };
            req.onerror = () => reject(req.error);
        });
    }

    // ---------- 下载题库数据 ----------
    async function downloadAndStoreData(onProgress) {
        if (typeof pako === 'undefined') {
            throw new Error('pako 库未加载,请刷新页面重试。');
        }
        await clearProblems();
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: 'GET',
                url: DATA_URL,
                responseType: 'arraybuffer',
                onload: async (res) => {
                    try {
                        const compressed = new Uint8Array(res.response);
                        const decompressed = pako.ungzip(compressed, { to: 'string' });
                        const lines = decompressed.split('\n').filter(line => line.trim() !== '');
                        const total = lines.length;
                        const batchSize = 1000;
                        let imported = 0;

                        const importBatch = async (start) => {
                            const end = Math.min(start + batchSize, total);
                            const batch = [];
                            for (let i = start; i < end; i++) {
                                try {
                                    const obj = JSON.parse(lines[i]);
                                    batch.push({
                                        pid: obj.pid,
                                        title: obj.title,
                                        difficulty: obj.difficulty,
                                        type: obj.type,
                                        tags: obj.tags || []
                                    });
                                } catch (e) {}
                            }
                            if (batch.length > 0) {
                                await bulkInsert(batch);
                                imported += batch.length;
                                if (onProgress) onProgress(imported, total);
                            }
                            if (end < total) {
                                await importBatch(end);
                            } else {
                                resolve();
                            }
                        };

                        await importBatch(0);
                    } catch (e) {
                        reject(e);
                    }
                },
                onerror: (err) => reject(err)
            });
        });
    }

    // ---------- 工具函数:打开题目页面(新增) ----------
    function openProblemPage(pid) {
        const url = `https://www.luogu.com.cn/problem/${pid}`;
        if (typeof GM_openInTab === 'function') {
            GM_openInTab(url, { active: true, insert: true });
        } else {
            window.open(url, '_blank');
        }
    }

    // ---------- DOM 着色与事件绑定 ----------
    function colorizeNode(node) {
        if (!node) return;
        if (node.nodeType === Node.TEXT_NODE) {
            processTextNode(node);
        } else if (node.nodeType === Node.ELEMENT_NODE) {
            if (node.tagName === 'SCRIPT' || node.tagName === 'STYLE' || node.tagName === 'NOSCRIPT') return;
            if (node.classList && node.classList.contains('lg-diff-color')) return;

            // 处理指向题目的链接
            if (node.tagName === 'A' && node.getAttribute('href')?.includes('/problem/')) {
                processProblemLink(node);
                return;
            }

            const childNodes = node.childNodes;
            for (let i = 0; i < childNodes.length; i++) {
                colorizeNode(childNodes[i]);
            }
        }
    }

    function processTextNode(node) {
        if (processedTextNodes.has(node)) return;
        const text = node.textContent;
        if (!text) return;

        PID_PATTERN.lastIndex = 0;
        const replacements = [];
        let match;
        while ((match = PID_PATTERN.exec(text)) !== null) {
            const pid = match[0];
            const problemData = problemDataMap.get(pid);
            if (problemData) {
                replacements.push({
                    start: match.index,
                    end: PID_PATTERN.lastIndex,
                    pid: pid,
                    difficulty: problemData.difficulty,
                    tags: problemData.tags,
                    title: problemData.title
                });
            }
        }

        if (replacements.length === 0) {
            processedTextNodes.add(node);
            return;
        }

        const fragment = document.createDocumentFragment();
        let lastIndex = 0;
        for (const r of replacements) {
            if (r.start > lastIndex) {
                fragment.appendChild(document.createTextNode(text.substring(lastIndex, r.start)));
            }
            const span = document.createElement('span');
            span.className = 'lg-diff-color';
            span.style.color = DIFFICULTY_COLORS[r.difficulty] || '#808080';
            span.style.fontWeight = 'bold';
            span.textContent = r.pid;
            span.style.cursor = 'pointer';

            span.addEventListener('mouseenter', (e) => {
                const tags = r.tags && r.tags.length ? r.tags.join(', ') : '暂无标签';
                const title = r.title ? `<strong>${r.pid} ${r.title}</strong>` : `<strong>${r.pid}</strong>`;
                showTooltip(e.clientX, e.clientY, `${title}<br>标签:${tags}`);
            });
            span.addEventListener('mousemove', (e) => {
                if (tooltip && tooltip.style.display === 'block') {
                    showTooltip(e.clientX, e.clientY, tooltip.innerHTML);
                }
            });
            span.addEventListener('mouseleave', hideTooltip);

            // 双击打开题目页面(使用新函数)
            span.addEventListener('dblclick', (e) => {
                e.preventDefault();
                e.stopImmediatePropagation();
                openProblemPage(r.pid);
            });

            fragment.appendChild(span);
            lastIndex = r.end;
        }
        if (lastIndex < text.length) {
            fragment.appendChild(document.createTextNode(text.substring(lastIndex)));
        }

        node.parentNode.replaceChild(fragment, node);
        processedTextNodes.add(node);
    }

    function processProblemLink(a) {
        if (processedLinks.has(a)) return;
        const href = a.getAttribute('href');
        const match = href && href.match(/\/problem\/([^/?]+)/);
        if (!match) return;
        const pid = decodeURIComponent(match[1]);
        const data = problemDataMap.get(pid);

        processedLinks.add(a);

        if (data) {
            const color = DIFFICULTY_COLORS[data.difficulty] || '#808080';
            a.style.setProperty('color', color, 'important');
            a.style.fontWeight = 'bold';
        }
        a.style.cursor = 'pointer';

        // 阻止单击默认跳转,让双击事件能够生效
        a.addEventListener('click', (e) => {
            e.preventDefault();
        });

        a.addEventListener('mouseenter', (e) => {
            const tags = data && data.tags && data.tags.length ? data.tags.join(', ') : '暂无标签';
            const title = data && data.title ? `<strong>${pid} ${data.title}</strong>` : `<strong>${pid}</strong>`;
            showTooltip(e.clientX, e.clientY, `${title}<br>标签:${tags}`);
        });
        a.addEventListener('mousemove', (e) => {
            if (tooltip && tooltip.style.display === 'block') {
                showTooltip(e.clientX, e.clientY, tooltip.innerHTML);
            }
        });
        a.addEventListener('mouseleave', hideTooltip);

        // 双击打开新页面(使用新函数)
        a.addEventListener('dblclick', (e) => {
            e.preventDefault();
            e.stopImmediatePropagation();
            openProblemPage(pid);
        });
    }

    function colorizeExistingDOM() {
        colorizeNode(document.body);
    }

    function startObserver() {
        if (observer) observer.disconnect();
        observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    colorizeNode(node);
                });
            });
        });
        observer.observe(document.body, { childList: true, subtree: true });
    }

    // ---------- 初始化 ----------
    async function init() {
        try {
            const lastUpdate = GM_getValue('last_update_time', 0);
            const now = Date.now();

            let count = await getProblemCount();

            if (count === 0) {
                showStatusMessage('正在下载洛谷题库数据,首次使用可能需要几十秒...');
                console.log('[洛谷题目着色] 无本地题库,开始下载...');
                await downloadAndStoreData((current, total) => {
                    if (current % 5000 === 0 || current === total) {
                        showStatusMessage(`题库下载中: ${current}/${total}`);
                    }
                });
                GM_setValue('last_update_time', Date.now());
                showStatusMessage('题库下载完成,正在着色...');
                console.log('[洛谷题目着色] 下载完成');
            } else if (now - lastUpdate >= MIN_UPDATE_INTERVAL) {
                showStatusMessage('题库数据已超过3天未更新,正在更新...');
                console.log('[洛谷题目着色] 超过3天,开始更新题库...');
                await downloadAndStoreData((current, total) => {
                    if (current % 5000 === 0 || current === total) {
                        showStatusMessage(`题库更新中: ${current}/${total}`);
                    }
                });
                GM_setValue('last_update_time', Date.now());
                showStatusMessage('题库更新完成,正在着色...');
            } else {
                console.log('[洛谷题目着色] 题库数据在3天内已更新过,使用本地缓存');
            }

            problemDataMap = await loadProblemDataMap();
            console.log(`[洛谷题目着色] 已加载 ${problemDataMap.size} 条题目数据`);
            colorizeExistingDOM();
            startObserver();
            showStatusMessage('题目难度着色与标签速览已启用', false);
        } catch (err) {
            console.error('[洛谷题目着色] 初始化失败:', err);
            showStatusMessage('题库下载失败,请检查网络后刷新重试', true);
            startObserver();
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();

:::

预测等级分(貌似停工?) :::info[]

// ==UserScript==
// @name         洛谷等级分预测
// @namespace    https://www.luogu.com.cn/user/1523280
// @version      3.1
// @description  预测你的等级分曲线和比赛状况!
// @author       a_small_OIer & Sakument_tree
// @match        https://www.luogu.com.cn/contest/*
// @match        https://www.luogu.com.cn/user/*
// @grant        GM_xmlhttpRequest
// @connect      luogu.ac.cn
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js
// @run-at       document-end
// ==/UserScript==
(function (){
  'use strict';
  /**
   * 通用 GM_xmlhttpRequest Promise 封装
   * @param {string} url - 请求地址
   * @returns {Promise<object>} 解析后的 JSON 对象
   */
  function gmRequest(url) {
    return new Promise((resolve, reject) => {
      GM_xmlhttpRequest({
        method: 'GET',
        url: url,
        onload: function (resp) {
          try {
            resolve(JSON.parse(resp.responseText));
          } catch (e) {
            reject(e);
          }
        },
        onerror: reject
      });
    });
  }
  function isoToUnix(iso) {
    return new Date(iso).getTime() / 1000;
  }
  function formatTime(ts) {
    const d = new Date((ts + 8 * 3600) * 1000);
    const year = d.getUTCFullYear();
    const month = String(d.getUTCMonth() + 1).padStart(2, '0');
    const day = String(d.getUTCDate()).padStart(2, '0');
    const hours = String(d.getUTCHours()).padStart(2, '0');
    const minutes = String(d.getUTCMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  }
  const path = window.location.pathname;
  if (path.match(/^\/contest\/\d+/)) {
    (function () {
      const contestId = window.location.pathname.match(/\/contest\/(\d+)/)?.[1];
      if (!contestId) {
        console.warn('未找到比赛 ID');
        return;
      }
      // -------- 参数配置 --------
      const CACHE_KEY = 'luogu_contest_pred_cache';
      const PAGE_SIZE = 100;
      function getCacheTTL(mode) {
        return mode === 'official' ? 15 * 24 * 60 * 60 * 1000 : 2 * 60 * 60 * 1000;
      }
      let ratingMode = null;
      let dataMap = {};
      let isAllFetched = false;
      let isLoading = false;
      let initialized = false;
      let isUnrated = false;
      let initLock = false;
      let domCheckTimer = null;
      // -------- 缓存 --------
      function getCache() {
        try {
          const raw = localStorage.getItem(CACHE_KEY);
          return raw ? JSON.parse(raw) : {};
        } catch { return {}; }
      }
      function setCache(cache) {
        try {
          localStorage.setItem(CACHE_KEY, JSON.stringify(cache));
        } catch { }
      }
      function getRowBackgroundColor(row) {
        const userDiv = row.querySelector('.user');
        if (userDiv) {
          const bg = userDiv.style.backgroundColor;
          if (bg) return bg;
        }
        return null;
      }
      function fetchContestPredictions(page = 1) {
        const url = `https://luogu.ac.cn/api/v1/contest/${contestId}?page=${page}&page_size=${PAGE_SIZE}`;
        return gmRequest(url);
      }
      function removePredictionUI() {
        const headerRow = document.querySelector('.header-wrap .header');
        if(headerRow){
          const oldHeader = headerRow.querySelector('.header-container[data-prediction-header]');
          if(oldHeader)
            oldHeader.remove();
        }
        const rows = document.querySelectorAll('.row-wrap .row');
        rows.forEach(row => {
          const cell = row.querySelector('.problem[data-prediction-cell]');
          if (cell) cell.remove();
        });
      }
      function removeFooter() {
        const footer = document.querySelector('#prediction-footer');
        if (footer) footer.remove();
      }
      let height = -1;
      function setCellFullHeight(cell, row) {
        if(!cell || !row)
          return;
        if(height === -1){
          height = row.clientHeight;
        }
        if(height > 0){
          cell.style.height = height + 'px';
          cell.style.minHeight = height + 'px';
          cell.style.boxSizing = 'border-box';
        }else{
          cell.style.height = '100%';
          cell.style.minHeight = '100%';
          cell.style.alignSelf = 'stretch';
        }
      }
      function fillCurrentRows() {
        if (!window.location.hash.includes('scoreboard')) return;
        if (isUnrated) {
          removePredictionUI();
          removeFooter();
          return;
        }
        if (fail === 2) {
          removePredictionUI();
          updateFooter();
          return;
        }
        const rows = document.querySelectorAll('.row-wrap .row');
        if (rows.length === 0) return;
        ensureHeader();
        rows.forEach(row => {
          let cell = row.querySelector('.problem[data-prediction-cell]');
          if (!cell) {
            cell = document.createElement('div');
            cell.className = 'problem';
            cell.dataset.predictionCell = 'true';
            cell.style.cssText = 'flex: 0 0 80px; display: flex; flex-direction: column; justify-content: center; align-items: center;';
            row.appendChild(cell);
          }
          setCellFullHeight(cell, row);
          const bgColor = getRowBackgroundColor(row);
          if (bgColor) {
            cell.style.backgroundColor = bgColor;
          } else {
            cell.style.backgroundColor = '';
          }
          const uid = getUidFromRow(row);
          if (!uid) {
            cell.innerHTML = '';
            const scoreDiv = document.createElement('div');
            scoreDiv.className = 'td-score';
            scoreDiv.textContent = '-';
            cell.appendChild(scoreDiv);
            const runtimeDiv = document.createElement('div');
            runtimeDiv.className = 'td-runtime';
            runtimeDiv.textContent = '';
            cell.appendChild(runtimeDiv);
            return;
          }
          const info = dataMap[uid];
          if (!info) {
            cell.innerHTML = '';
            const scoreDiv = document.createElement('div');
            scoreDiv.className = 'td-score';
            const placeholder = document.createElement('span');
            placeholder.textContent = '获取中...';
            placeholder.style.color = 'rgba(0,0,0,0.55)';
            placeholder.style.fontSize = '13px';
            scoreDiv.appendChild(placeholder);
            cell.appendChild(scoreDiv);
            const runtimeDiv = document.createElement('div');
            runtimeDiv.className = 'td-runtime';
            runtimeDiv.textContent = '\u00A0';
            cell.appendChild(runtimeDiv);
            return;
          }
          const delta = info.delta;
          const newRating = info.newRating;
          const warnings = info.warnings || [];
          cell.innerHTML = '';
          const scoreDiv = document.createElement('div');
          scoreDiv.className = 'td-score';
          const deltaSpan = document.createElement('span');
          deltaSpan.style.fontWeight = 'bold';
          if (delta === null || delta === undefined) {
            deltaSpan.textContent = '-';
            deltaSpan.style.color = 'rgba(0,0,0,0.55)';
          } else if (delta > 0) {
            deltaSpan.style.color = 'rgb(82, 196, 26)';
            deltaSpan.textContent = `+${delta}`;
          } else if (delta < 0) {
            deltaSpan.style.color = 'rgb(231, 76, 60)';
            deltaSpan.textContent = `${delta}`;
          } else {
            deltaSpan.style.color = 'rgba(0,0,0,0.55)';
            deltaSpan.textContent = '±0';
          }
          scoreDiv.appendChild(deltaSpan);
          if (warnings.length > 0) {
            const warnIcon = document.createElement('span');
            warnIcon.textContent = ' ⓘ';
            warnIcon.style.cursor = 'help';
            warnIcon.style.fontSize = '14px';
            warnIcon.style.color = 'rgba(0,0,0,0.55)';
            warnIcon.title = warnings.join('\n');
            scoreDiv.appendChild(warnIcon);
          }
          cell.appendChild(scoreDiv);
          const runtimeDiv = document.createElement('div');
          runtimeDiv.className = 'td-runtime';
          if (newRating !== null && newRating !== undefined) {
            runtimeDiv.textContent = `新: ${newRating}`;
            runtimeDiv.style.color = 'rgba(0,0,0,0.55)';
            runtimeDiv.style.fontSize = '12px';
          } else {
            runtimeDiv.textContent = '\u00A0';
          }
          cell.appendChild(runtimeDiv);
        });
        updateFooter();
      }
      function getUidFromRow(row) {
        const link = row.querySelector('.user a[href^="/user/"]');
        if (link) {
          const match = link.href.match(/\/user\/(\d+)/);
          return match ? match[1] : null;
        }
        return null;
      }
      let fail = 0;
      async function loadData() {
        if (isLoading || isUnrated || fail === 2) return;
        if (isAllFetched) {
          fillCurrentRows();
          return;
        }
        isLoading = true;
        fail = 0;
        try{
          const firstPageData = await fetchContestPredictions(1);
          if (!firstPageData || !firstPageData.contest) {
            throw new Error('无法获取比赛信息');
          }
          const currentRatingMode = firstPageData.contest.rating_mode || null;
          console.log(`[等级分预测] 当前 rating_mode: ${currentRatingMode}`);
          if (currentRatingMode === 'unrated') {
            ratingMode = currentRatingMode;
            isUnrated = true;
            removePredictionUI();
            isLoading = false;
            return;
          }
          const cache = getCache();
          const now = Date.now();
          const cachedEntry = cache[contestId];
          if (cachedEntry) {
            const cachedMode = cachedEntry.ratingMode;
            const cachedTime = cachedEntry.timestamp;
            const ttl = getCacheTTL(cachedMode);
            if (cachedMode === currentRatingMode && (now - cachedTime < ttl)) {
              console.log('[等级分预测] 缓存有效,直接使用');
              ratingMode = cachedMode;
              isUnrated = (ratingMode === 'unrated');
              const cachedData = cachedEntry.data || [];
              cachedData.forEach(item => {
                dataMap[String(item.uid)] = {
                  delta: item.delta,
                  newRating: item.rating,
                  warnings: item.warnings || []
                };
              });
              isAllFetched = true;
              isLoading = false;
              fillCurrentRows();
              return;
            } else {
              console.log('[等级分预测] 缓存无效,重新获取');
            }
          }
          console.log('[等级分预测] 开始分页获取数据...');
          ratingMode = currentRatingMode;
          isUnrated = false;
          const firstItems = firstPageData.items || [];
          firstItems.forEach(item => {
            dataMap[String(item.uid)] = {
              delta: item.delta,
              newRating: item.rating,
              warnings: item.warnings || []
            };
          });
          ensureHeader();
          fillCurrentRows();
          let total = firstPageData.total || 0;
          let page = 2;
          while (true) {
            if (Object.keys(dataMap).length >= total) break;
            const data = await fetchContestPredictions(page);
            const items = data.items || [];
            if (items.length === 0) break;
            items.forEach(item => {
              dataMap[String(item.uid)] = {
                delta: item.delta,
                newRating: item.rating,
                warnings: item.warnings || []
              };
            });
            fillCurrentRows();
            total = data.total || total;
            page++;
          }
          const allData = Object.keys(dataMap).map(uid => ({
            uid: parseInt(uid),
            delta: dataMap[uid].delta,
            rating: dataMap[uid].newRating,
            warnings: dataMap[uid].warnings
          }));
          cache[contestId] = {
            data: allData,
            ratingMode: ratingMode,
            timestamp: Date.now()
          };
          setCache(cache);
          isAllFetched = true;
          console.log('[等级分预测] 全部数据获取完成,已缓存');
        } catch (e) {
          const cache = getCache();
          const cachedEntry = cache[contestId];
          if (cachedEntry && cachedEntry.data) {
            console.warn(`[等级分预测] 加载数据失败:${e}\n使用过期缓存作为降级`);
            fail = 1;
            const cachedData = cachedEntry.data || [];
            cachedData.forEach(item => {
              dataMap[String(item.uid)] = {
                delta: item.delta,
                newRating: item.rating,
                warnings: item.warnings || []
              };
            });
            isAllFetched = true;
            fillCurrentRows();
          } else {
            console.error(`[等级分预测] 加载数据失败:${e}\n无缓存可用`);
            fail = 2;
          }
        } finally {
          isLoading = false;
          fillCurrentRows();
        }
      }
      function ensureHeader() {
        if (isUnrated) {
          const headerRow = document.querySelector('.header-wrap .header');
          if (headerRow) {
            const oldHeader = headerRow.querySelector('.header-container[data-prediction-header]');
            if (oldHeader) oldHeader.remove();
          }
          return;
        }
        const headerRow = document.querySelector('.header-wrap .header');
        if (!headerRow) return;
        const oldHeader = headerRow.querySelector('.header-container[data-prediction-header]');
        if (oldHeader) oldHeader.remove();
        let headerHtml = '';
        let titleText = '';
        if (ratingMode === 'prediction') {
          headerHtml = '<span>Δ</span><span style="color:rgba(0,0,0,0.55);font-size:11px;display:block;">(预测)</span>';
          titleText = '等级分变动(预测结果,仅供参考)';
        } else if (ratingMode === 'official') {
          headerHtml = '<span>Δ</span>';
          titleText = '等级分变动(正式结果)';
        } else {
          headerHtml = '<span>Δ</span>';
          titleText = '等级分变动';
        }
        const newHeader = document.createElement('div');
        newHeader.className = 'header-container';
        newHeader.dataset.predictionHeader = 'true';
        newHeader.style.cssText = 'flex: 0 0 80px; text-align: center; display: flex; flex-direction: column; justify-content: center; cursor: help;';
        newHeader.title = titleText;
        newHeader.innerHTML = headerHtml;
        headerRow.appendChild(newHeader);
      }
      function updateFooter() {
        if (isUnrated) {
          const footer = document.querySelector('#prediction-footer');
          if (footer) footer.remove();
          return;
        }
        let footer = document.querySelector('#prediction-footer');
        if (!footer) {
          const container = document.querySelector('.l-card') || document.querySelector('main');
          if (!container) return;
          footer = document.createElement('div');
          footer.id = 'prediction-footer';
          footer.style.cssText = 'padding: 8px 16px; font-size: 12px; color: #999; text-align: right; border-top: 1px solid #eee; margin-top: 8px;';
          container.appendChild(footer);
        }
        if (fail === 2) {
          footer.textContent = '等级分预测:获取数据失败';
          return;
        }
        const cache = getCache();
        const entry = cache[contestId];
        if (entry) {
          const d = new Date(entry.timestamp);
          const timeStr = d.toLocaleString('zh-CN', { hour12: false });
          const modeStr = entry.ratingMode ? ` (${entry.ratingMode})` : '';
          const ttl = getCacheTTL(entry.ratingMode);
          const ttlHours = Math.round(ttl / (60 * 60 * 1000));
          const ttlDisplay = ttlHours >= 24 ? `${Math.round(ttlHours / 24)} 天` : `${ttlHours} 小时`;
          footer.textContent = `等级分预测:数据最后更新于 ${timeStr}${modeStr}`;
          if (fail === 1) {
            footer.textContent += '(缓存刷新失败)';
          } else {
            footer.textContent += `(缓存 ${ttlDisplay})`;
          }
          footer.textContent += '  数据来源:洛谷档案馆 luogu.ac.cn';
        } else {
          footer.textContent = '等级分预测:暂无缓存数据';
        }
      }
      async function init() {
        if (initialized) {
          if (isAllFetched) fillCurrentRows();
          else loadData();
          return;
        }
        initialized = true;
        if (!document.querySelector('.row-wrap .row')) {
          await new Promise(resolve => {
            const observer = new MutationObserver(() => {
              if (document.querySelector('.row-wrap .row')) {
                observer.disconnect();
                resolve();
              }
            });
            observer.observe(document.body, { childList: true, subtree: true });
            setTimeout(() => {
              observer.disconnect();
              resolve();
            }, 5000);
          });
        }
        setupObserver();
        await loadData();
      }
      function setupObserver() {
        const target = document.querySelector('.row-wrap') || document.querySelector('main');
        if (!target) return;
        let timer = null;
        const observer = new MutationObserver(() => {
          clearTimeout(timer);
          timer = setTimeout(() => {
            if (isUnrated) {
              removePredictionUI();
              return;
            }
            if (isAllFetched || isLoading) {
              fillCurrentRows();
            } else {
              loadData();
            }
          }, 500);
        });
        observer.observe(target, {
          childList: true,
          subtree: true,
          attributes: false,
          characterData: false
        });
      }
      function triggerInit() {
        if (!window.location.hash.includes('scoreboard')) return;
        if (initLock) return;
        initLock = true;
        clearTimeout(domCheckTimer);
        domCheckTimer = setTimeout(() => {
          if (document.querySelector('.row-wrap .row')) {
            if (!initialized) {
              init();
            } else {
              if (isAllFetched) fillCurrentRows();
              else loadData();
            }
          } else {
            const observer = new MutationObserver((mutations, obs) => {
              if (document.querySelector('.row-wrap .row')) {
                obs.disconnect();
                if (!initialized) {
                  init();
                } else {
                  if (isAllFetched) fillCurrentRows();
                  else loadData();
                }
              }
            });
            observer.observe(document.body, {
              childList: true,
              subtree: true
            });
            setTimeout(() => {
              observer.disconnect();
            }, 10000);
          }
          initLock = false;
        }, 300);
      }
      function startWatching() {
        window.addEventListener('hashchange', triggerInit);
        window.addEventListener('popstate', triggerInit);
        const targetNode = document.querySelector('#app') || document.querySelector('main') || document.body;
        const observer = new MutationObserver(() => {
          clearTimeout(window._domCheckTimer);
          window._domCheckTimer = setTimeout(() => {
            triggerInit();
          }, 200);
        });
        observer.observe(targetNode, {
          childList: true,
          subtree: true
        });
        setInterval(() => {
          if (window.location.hash.includes('scoreboard')) {
            triggerInit();
          }
        }, 2000);
      }
      startWatching();
      if (window.location.hash.includes('scoreboard')) {
        setTimeout(triggerInit, 500);
      }
    })();
  }
  else if (path.match(/^\/user\/\d+/)) {
    (function () {
      let lastUid = null;
      let lastPath = null;
      function waitForElement(selector, timeout = 5000) {
        return new Promise((resolve, reject) => {
          const start = Date.now();
          const check = () => {
            const el = document.querySelector(selector);
            if (el) resolve(el);
            else if (Date.now() - start > timeout) reject(new Error(`元素 ${selector} 加载超时`));
            else setTimeout(check, 200);
          };
          check();
        });
      }
      function getUid() {
        const match = window.location.pathname.match(/\/user\/(\d+)/);
        return match ? match[1] : null;
      }
      function parseHistoryData() {
        const contextEl = document.getElementById('lentille-context');
        if (!contextEl) throw new Error('未找到 #lentille-context');
        const raw = contextEl.textContent;
        const parsed = JSON.parse(raw);
        const elo = parsed?.data?.elo;
        return elo;
      }
      function fetchPredictions(uid) {
        const url = `https://luogu.ac.cn/api/v1/user/${uid}/rating-predictions`;
        return gmRequest(url);
      }
      function buildFullData(history, predictions) {
        const sortedHistory = history.slice().sort((a, b) => a.time - b.time).map(item => ({
          ...item,
          previousRating: item.rating - (item.prevDiff || 0)
        }));
        const rawItems = predictions?.items || [];
        const validItems = rawItems.filter(item => {
          const warnings = item.warnings || [];
          return !warnings.some(w => w.includes('赛前等级分不低于本场等级分阈值'));
        });
        const predData = validItems.map(item => ({
          isPredicted: true,
          rating: item.predicted_rating,
          time: isoToUnix(item.end_time),
          latest: false,
          contest: {
            id: item.contest_id,
            startTime: isoToUnix(item.start_time),
            endTime: isoToUnix(item.end_time),
            name: item.contest_name
          },
          userCount: 0,
          prevDiff: item.predicted_delta,
          previous: {
            rating: item.predicted_rating - item.predicted_delta,
            time: null,
            latest: false,
            contest: null,
            userCount: 0,
            prevDiff: null
          },
          previousRating: item.predicted_rating - item.predicted_delta,
          warnings: item.warnings || []
        }));
        const full = [...sortedHistory, ...predData];
        full.sort((a, b) => {
          if (a.time !== b.time) return a.time - b.time;
          return (a.previousRating || 0) - (b.previousRating || 0);
        });
        if (full.length > 0 && full[0].isPredicted) {
          full[0].isFirst = true;
        } else {
          let firstHistoricalFound = false;
          for (const item of full) {
            if (!item.isPredicted && !firstHistoricalFound) {
              item.isFirst = true;
              firstHistoricalFound = true;
              break;
            }
          }
        }
        const firstPredIdx = full.findIndex(d => d.isPredicted);
        if (firstPredIdx > 0) {
          const prevItem = full[firstPredIdx - 1];
          if (prevItem && !prevItem.isPredicted) {
            const placeholder = {
              ...prevItem,
              isPredicted: true,
              isPlaceholder: true,
            };
            full.splice(firstPredIdx, 0, placeholder);
          }
        }
        return full;
      }
      function gatPageType() {
        const path = window.location.pathname;
        const match = path.match(/^\/user\/(\d+)/);
        if (!match) return '';
        const rest = path.substring(match[0].length);
        if (rest === '' || rest === '/') return 'profile';
        if (/^\/user\/\d+\/practice/.test(window.location.pathname)) return 'practice';
        return '';
      }
      function prepareContainer(pagetype) {
        let existingCard = null;
        const cardById = document.querySelector('div.l-card:has(#rating-chart)');
        if (cardById) {
          existingCard = cardById;
        } else {
          const cards = document.querySelectorAll('div.l-card');
          for (const card of cards) {
            const header = card.querySelector('.header h3.lfe-h3');
            if (header && header.textContent.trim() === '比赛等级分趋势图') {
              existingCard = card;
              break;
            }
          }
        }
        if (existingCard) {
          const header = existingCard.querySelector('.header');
          while (existingCard.firstChild) {
            existingCard.removeChild(existingCard.firstChild);
          }
          if (header) existingCard.appendChild(header);
          const chartDiv = document.createElement('div');
          chartDiv.id = 'rating-chart';
          chartDiv.style.cssText = 'width: 100%; height: 320px;';
          existingCard.appendChild(chartDiv);
          return chartDiv;
        }
        const card = document.createElement('div');
        card.className = 'l-card';
        card.style.marginBottom = '20px';
        card.setAttribute('data-v-176b97b3', '');
        card.setAttribute('data-v-d3b68fa4', '');
        card.setAttribute('data-v-4ad5148e', '');
        card.setAttribute('data-v-754e1ea4-s', '');
        const header = document.createElement('div');
        header.className = 'header';
        header.setAttribute('data-v-03592857', '');
        const h3 = document.createElement('h3');
        h3.className = 'lfe-h3';
        h3.textContent = '比赛等级分趋势图';
        h3.setAttribute('data-v-03592857', '');
        header.appendChild(h3);
        card.appendChild(header);
        const span = document.createElement('span');
        span.className = 'lfe-caption';
        span.textContent = '选中记录后可打开比赛页面';
        span.setAttribute('data-v-03592857', '');
        header.appendChild(span);
        card.appendChild(header);
        const chartDiv = document.createElement('div');
        chartDiv.id = 'rating-chart';
        chartDiv.setAttribute('data-v-03592857', '');
        chartDiv.style.cssText = 'width: 100%; height: 320px;';
        card.appendChild(chartDiv);
        let inserted = false;
        if (pagetype === 'profile') {
          const allCards = document.querySelectorAll('.l-card');
          let refCard = null;
          for (const c of allCards) {
            const h = c.querySelector('.header h3');
            if (h && h.textContent.trim().includes('做题趋势热度图')) {
              refCard = c;
              break;
            }
          }
          if (refCard) {
            refCard.insertAdjacentElement('afterend', card);
            inserted = true;
          }
        } else if (pagetype === 'practice') {
          const container = document.querySelector('.user-main') || document.body;
          let targetCard = null;
          const allCards = container.querySelectorAll('.l-card');
          for (const c of allCards) {
            const emptyBlock = c.querySelector('.empty-block');
            if (emptyBlock) {
              const h3 = emptyBlock.querySelector('h3.title');
              if (h3 && h3.textContent.trim() === '该用户设置了完全隐私保护,无法查看练习记录') {
                targetCard = c;
                break;
              }
            }
            const directH3 = c.querySelector('h3.lfe-h3');
            if (directH3 && directH3.textContent.trim() === '尝试过的题目') {
              targetCard = c;
              break;
            }
          }
          if (targetCard) {
            targetCard.insertAdjacentElement('beforebegin', card);
          }
          inserted = true;
        }
        if (!inserted) return null;
        return chartDiv;
      }
      function renderChart(container, data) {
        if (!container) return;
        const myChart = echarts.init(container);
        const historicalData = data.filter(d => !d.isPredicted);
        const historicalMax = historicalData.length > 0 ? Math.max(...historicalData.map(d => d.rating)) : 0;
        const predictedData = data.filter(d => d.isPredicted && !d.isPlaceholder);
        const predictedMax = predictedData.length > 0 ? Math.max(...predictedData.map(d => d.rating)) : -Infinity;
        const showPredictedMax = predictedMax >= historicalMax;
        data.forEach(item => {
          if (!item.isPredicted) {
            item.isHistoricalMax = (item.rating === historicalMax);
          } else {
            item.isPredictedMax = (item.rating === predictedMax && showPredictedMax);
          }
        });
        const historical = data.filter(d => !d.isPredicted);
        const predictedFull = data.filter(d => d.isPredicted);
        const maxRating = Math.max(...data.map(d => d.rating));
        const yMax = Math.ceil(maxRating / 400) * 400 || 400;
        function buildSeriesItems(arr, isPredictedSeries = false) {
          return arr.map(item => {
            const base = {
              value: [item.time * 1000, item.rating],
              symbol: item.isPlaceholder ? 'none' : 'circle',
              symbolSize: 5,
              rawInfo: item
            };
            if (isPredictedSeries) {
              if (item.isPlaceholder) {
                base.itemStyle = { color: 'transparent', borderColor: 'transparent' };
              } else if (item.isPredictedMax) {
                base.itemStyle = {
                  color: 'rgba(255,255,255,0.4)',
                  borderColor: 'rgba(240,112,7,0.6)',
                  borderWidth: 2
                };
              } else {
                base.itemStyle = {
                  color: 'rgba(255,255,255,0.4)',
                  borderColor: 'rgba(93,173,226,0.6)',
                  borderWidth: 1.5
                };
              }
            } else {
              if (item.isHistoricalMax) {
                base.itemStyle = {
                  color: '#fff',
                  borderColor: '#e74c3c',
                  borderWidth: 2
                };
              } else {
                base.itemStyle = {
                  color: '#fff',
                  borderColor: '#5dade2',
                  borderWidth: 2
                };
              }
            }
            return base;
          });
        }
        const option = {
          grid: {
            left: 0,
            right: 15,
            top: 25,
            bottom: 20,
            containLabel: true
          },
          xAxis: {
            type: 'time',
            axisLine: { lineStyle: { color: '#ccc' } },
            axisLabel: {
              color: '#555',
              fontSize: 12,
              formatter: function (value) {
                const d = new Date(value);
                return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0');
              }
            },
            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', type: 'solid' } }
          },
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(42,42,42,0.95)',
            borderColor: 'transparent',
            borderRadius: 4,
            padding: [12, 16],
            textStyle: { color: '#fff' },
            formatter: function (params) {
              const item = params.data.rawInfo;
              if (!item || item.isPlaceholder) return '';
              const isPred = item.isPredicted || false;
              const Prefix = isPred ? '[预测] ' : '';
              const start = formatTime(item.contest.startTime);
              const end = formatTime(item.contest.endTime);
              let ratingDisplay = '';
              if (item.isFirst) {
                ratingDisplay = `等级分:<span style="color:#fff; font-weight:bold;">${item.rating}</span>`;
              } else {
                let prevRating = 0, diff = 0;
                if (item.previous && item.previous.rating !== undefined) {
                  prevRating = item.previous.rating;
                  diff = item.prevDiff || 0;
                } else {
                  prevRating = item.rating - (item.prevDiff || 0);
                  diff = item.prevDiff || 0;
                }
                let diffColor, diffDisplay;
                if (diff === 0) {
                  diffColor = '#888';
                  diffDisplay = '±0';
                } else if (diff > 0) {
                  diffColor = '#4caf50';
                  diffDisplay = '+' + diff;
                } else {
                  diffColor = '#e74c3c';
                  diffDisplay = diff;
                }
                ratingDisplay = `
                  等级分:<span style="color:#fff; font-weight:bold;">${prevRating}</span>
                  <span style="color:${diffColor}; font-weight:bold;"> ${diffDisplay}</span>
                  = <span style="color:#fff; font-weight:bold;">${item.rating}</span>
                `;
              }
              let extraText = '';
              if (item.isHistoricalMax) {
                extraText += '<div style="font-style:italic; color:#fff; margin-top:4px;">达成历史最高</div>';
              }
              if (item.isPredictedMax) {
                extraText += '<div style="font-style:italic; color:#fff; margin-top:4px;">预计达成历史最高</div>';
              }
              if (item.warnings && item.warnings.length > 0) {
                for (const warn of item.warnings) {
                  extraText += `<div style="color:rgb(170,170,170); margin-top:2px;">ⓘ ${warn}</div>`;
                }
              }
              return `
                <div style="font-size:14px; font-weight:bold; margin-bottom:4px;">${item.contest.name}</div>
                <div style="font-size:12px; color:#a0a0a0; margin-bottom:6px;">${start} ~ ${end}</div>
                <div style="font-size:14px;">${Prefix}${ratingDisplay}</div>
                ${extraText}
              `;
            }
          },
          series: [{
            name: '历史比赛',
            type: 'line',
            data: buildSeriesItems(historical, false),
            smooth: false,
            lineStyle: { type: 'solid', color: '#5dade2', width: 2.5 },
            animationDuration: 1500,
            animationEasing: 'cubicOut'
          }, {
            name: '预测比赛',
            type: 'line',
            data: buildSeriesItems(predictedFull, true),
            smooth: false,
            lineStyle: {
              type: 'dashed',
              color: '#5dade2',
              width: 2.5,
              dash: [8, 6],
              opacity: 0.6
            },
            animationDuration: 1500,
            animationEasing: 'cubicOut'
          }]
        };
        myChart.setOption(option);
        myChart.on('click', function (params) {
          const item = params.data?.rawInfo;
          if (!item || item.isPlaceholder) return;
          const contestId = item.contest?.id;
          if (contestId) {
            window.open(`https://www.luogu.com.cn/contest/${contestId}`, '_blank');
          }
        });
        const resizeHandler = () => myChart.resize();
        window.addEventListener('resize', resizeHandler);
        const observer = new ResizeObserver(resizeHandler);
        observer.observe(container);
      }
      async function main() {
        try {
          const pageType = gatPageType();
          if (pageType !== 'profile' && pageType !== 'practice') return;
          const uid = getUid();
          if (!uid) {
            console.warn('[等级分预测] 未找到用户 ID');
            return;
          }
          let history;
          try {
            history = parseHistoryData();
          } catch (e) {
            console.error('[等级分预测] 解析历史数据失败', e);
            return;
          }
          let predictions = null;
          let fetchError = false;
          try {
            predictions = await fetchPredictions(uid);
          } catch (e) {
            console.warn('[等级分预测] 获取预测数据失败,只显示历史比赛数据', e);
            fetchError = true;
            predictions = { items: [] };
          }
          const fullData = buildFullData(history, predictions);
          if (fullData.length === 0) {
            console.log('[等级分预测] 无数据可展示');
            return;
          }
          const chartDiv = prepareContainer(pageType);
          if (!chartDiv) {
            console.error('[等级分预测] 无法创建或找到卡片容器');
            return;
          }
          await new Promise(resolve => setTimeout(resolve, 100));
          renderChart(chartDiv, fullData);
          const card = chartDiv.parentNode;
          if (!card) return;
          const hasPrediction = fullData.some(d => d.isPredicted && !d.isPlaceholder);
          let showFooter = false;
          let footerText = '';
          if (fetchError) {
            showFooter = true;
            footerText = '获取预测数据失败,只显示历史比赛数据';
          } else if (hasPrediction) {
            showFooter = true;
            footerText = '虚线部分为预测,不代表最终等级分变动<br>数据来源:洛谷档案馆 luogu.ac.cn';
          }
          const oldFooter = card.querySelector('.rating-footer');
          if (oldFooter) oldFooter.remove();
          if (showFooter) {
            const footer = document.createElement('div');
            footer.className = 'rating-footer';
            footer.style.cssText = `
              margin-top: 8px;
              font-size: 12px;
              color: #999;
              text-align: right;
              border-top: 1px solid #f0f0f0;
              padding: 8px 20px 0 20px;
            `;
            footer.innerHTML = `
              <span style="display:inline-block; background:#eee; border-radius:50%; width:16px; height:16px; line-height:16px; text-align:center; color:#666; font-weight:bold; margin-right:4px;">!</span>
              ${footerText}
            `;
            card.appendChild(footer);
          }
        } catch (error) {
          console.error('[等级分预测] 脚本运行出错:', error);
        }
      }
      function checkAndRun() {
        const uid = getUid();
        const path = window.location.pathname;
        if (uid && (uid !== lastUid || path !== lastPath)) {
          lastUid = uid;
          lastPath = path;
          main();
        }
      }
      function init() {
        checkAndRun();
        window.addEventListener('popstate', checkAndRun);
        const originalPush = history.pushState;
        const originalReplace = history.replaceState;
        history.pushState = function () {
          originalPush.apply(this, arguments);
          checkAndRun();
        };
        history.replaceState = function () {
          originalReplace.apply(this, arguments);
          checkAndRun();
        };
      }
      if (document.readyState === 'complete') {
        init();
      } else {
        window.addEventListener('load', init);
      }
    })();
  }
})();

:::

随机跳题优化

:::info[]

/*
MIT License

Copyright (c) 2026 karsl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// ==UserScript==
// @name         洛谷随机跳题(离线)
// @namespace    http://tampermonkey.net/
// @version      2.8
// @description  筛选题库、难度、标签后随机跳题,使用离线题库
// @author       karsl
// @match        https://www.luogu.com.cn/
// @icon         https://www.luogu.com.cn/favicon.ico
// @grant        GM_xmlhttpRequest
// @grant        GM_info
// @connect      www.luogu.com.cn
// @connect      cdn.luogu.com.cn
// @connect      raw.githubusercontent.com
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/pako.min.js
// @downloadURL  https://raw.githubusercontent.com/karsl-program/LRJPP/main/main.user.js
// @updateURL    https://raw.githubusercontent.com/karsl-program/LRJPP/main/main.user.js
// ==/UserScript==

(function() {
    'use strict';

    const DB_NAME = 'LuoguOfflineDB';
    const DB_VERSION = 4;
    const STORE_NAME = 'problems';
    const METADATA_STORE = 'metadata';
    const USER_STATUS_STORE = 'user_status';
    const DATA_URL = 'https://cdn.luogu.com.cn/problemset-open/latest.ndjson.gz';
    const UPDATE_URL = 'https://raw.githubusercontent.com/karsl-program/LRJPP/main/main.user.js';
    const DOWNLOAD_URL = 'https://raw.githubusercontent.com/karsl-program/LRJPP/main/main.user.js';

    const DIFFICULTY_MAP = {
        0: '暂未评定',
        1: '入门',
        2: '普及-',
        3: '普及',
        4: '普及+/提高-',
        5: '提高',
        6: '提高+/省选-',
        7: '省选/NOI-',
        8: 'NOI/NOI+/CTS'
    };

    const TYPE_MAP = {
        '洛谷': 'luogu',
        '主题库': 'P',
        '入门与面试': 'B'
    };
    const TYPE_KEYS = Object.keys(TYPE_MAP);

    const dimensionMaps = {
        algorithm: [
            '语言入门',
            '字符串',
            '后缀自动机 SAM',
            '字典树 Trie',
            'AC 自动机',
            'KMP 算法',
            '后缀数组 SA',
            '后缀树',
            '有限状态自动机',
            '回文自动机 PAM',
            'Manacher 算法',
            '顺序结构',
            '分支结构',
            '循环结构',
            '数组',
            '字符串(入门)',
            '结构体',
            '函数与递归',
            'Lyndon 分解',
            'Z 函数',
            '动态规划 DP',
            '搜索',
            '广度优先搜索 BFS',
            '深度优先搜索 DFS',
            '剪枝',
            '记忆化搜索',
            '启发式搜索',
            '迭代加深搜索',
            '启发式迭代加深搜索 IDA*',
            'Dancing Links',
            '爬山算法 Local search',
            '模拟退火',
            '背包 DP',
            '数位 DP',
            '区间 DP',
            '树形 DP',
            '轮廓线 DP',
            '线性 DP',
            '状压 DP',
            '后缀平衡树',
            '数学',
            '图论',
            'Kruskal 重构树',
            '网络流',
            '信息论',
            '随机调整',
            '遗传算法',
            '图论建模',
            '图遍历',
            '拓扑排序',
            '最短路',
            '生成树',
            '平面图',
            '最小环',
            'A*  算法',
            '折半搜索 meet in the middle',
            '梯度下降法',
            '拉格朗日乘数法',
            '拉格朗日插值法',
            '单位根反演',
            '负权环',
            '连通块',
            '2-SAT',
            '平面图欧拉公式',
            '强连通分量',
            'Tarjan',
            '双连通分量',
            '欧拉回路',
            '差分约束',
            '仙人掌',
            '二分图',
            '一般图的最大匹配',
            '上下界网络流',
            '最小割',
            '费用流',
            '圆方树',
            '弦图',
            'Floyd 算法',
            '广义串并联图',
            'Hall 定理',
            '计算几何',
            '树形数据结构',
            '线段树',
            '并查集',
            '平衡树',
            '堆',
            '树状数组',
            'cdq 分治',
            '可并堆',
            '动态树 LCT',
            '三维计算几何',
            '向量',
            '凸包',
            '叉积',
            '线段相交',
            '半平面交',
            '旋转卡壳',
            '极角排序',
            '平面几何',
            '闵可夫斯基和 Minkowski sum',
            '博弈论',
            '线性数据结构',
            '单调队列',
            '颜色段均摊(珂朵莉树 ODT)',
            '树套树',
            '可持久化线段树',
            '可持久化',
            '前缀和',
            '栈',
            '队列',
            '博弈树',
            '整体二分',
            'K-D Tree',
            'Nim 积',
            '李超线段树',
            '吉司机线段树 segment tree beats',
            '线段树合并',
            'SG 函数',
            '二区间合并(猫树分治)',
            'KTT / Kinetic Tournament Tree',
            '原根',
            '多项式',
            '数论',
            '素数判断',
            '最大公约数 gcd',
            '扩展欧几里德算法',
            '不定方程',
            '进制',
            '分块',
            'ST 表',
            '快速傅里叶变换 FFT',
            '快速数论变换 NTT',
            '快速沃尔什变换 FWT',
            '快速莫比乌斯变换 FMT',
            '差分',
            '链表',
            '单调栈',
            'Berlekamp-Massey(BM) 算法',
            '集合幂级数,子集卷积',
            '哈希表',
            '模拟',
            '贪心',
            '基础算法',
            '中国剩余定理 CRT',
            '莫比乌斯反演',
            '逆元',
            'Lucas 定理',
            '类欧几里得算法',
            '调和级数',
            '欧拉降幂',
            'Stern-Brocot 树',
            '整除分块',
            'Dirichlet 卷积',
            '大步小步算法 BSGS',
            '二次剩余',
            'Bézout 定理',
            '杜教筛',
            '欧拉函数',
            '线性筛法',
            '亚线性快速求和算法',
            '递推',
            '倍增',
            '二分',
            '递归',
            '枚举',
            '分治',
            '排序',
            '动态规划优化',
            '优先队列',
            '矩阵加速',
            '斜率优化',
            '状态合并',
            '凸完全单调性(wqs 二分)',
            '四边形不等式',
            'DP 套 DP',
            '动态 DP',
            '决策单调性',
            'STL',
            '整体转移',
            '斜率维护技巧 slope trick',
            '点分治',
            '树上启发式合并',
            '树的遍历',
            '最近公共祖先 LCA',
            '树的直径',
            '树链剖分',
            '树论',
            '群论',
            '置换',
            'Pólya 定理',
            '虚树',
            '组合数学',
            '排列组合',
            '二项式定理',
            '康托展开',
            '基环树',
            '动态树分治',
            'Prüfer 序列',
            '全局平衡二叉树',
            '树的重心',
            'LGV 引理',
            '矩阵树定理',
            '矩阵运算',
            '鸽笼原理',
            '容斥原理',
            'Fibonacci 数列',
            'Catalan 数',
            'Stirling 数',
            '生成函数',
            '概率论',
            '期望',
            '线性代数',
            '矩阵乘法',
            '线性递推',
            '高斯消元',
            'Dilworth 定理',
            '拉格朗日反演',
            '杨表',
            '随机游走 Markov Chain',
            '鞅的停时定理',
            '暴力数据结构',
            '高精度',
            '莫队',
            '三分',
            '离散化',
            '霍夫曼树',
            '哈希 hashing',
            '线性基',
            '微积分',
            '导数',
            '积分',
            '定积分',
            '级数',
            '扫描线',
            '其它技巧',
            '随机化',
            '位运算',
            '构造',
            '行列式',
            '特征值',
            '分数规划',
            '线性规划',
            '双指针 two-pointer',
            'Ad-hoc',
            '笛卡尔树',
            '拟阵',
            '根号分治',
            '模拟费用流',
            '分散层叠',
            '均摊分析',
            '分类讨论',
            '近似算法',
            '线段树分治',
            '离线处理',
            'bitset',
            '组合优化',
            '整数规划',
            '原始对偶',
            '启发式合并',
            '反悔贪心',
            '最大流最小割定理',
            '保序回归'
        ],
        source: [
            '各省省选',
            '集训队互测',
            '福建省历届夏令营',
            'NOI',
            'NOIP 普及组',
            'NOIP 提高组',
            'APIO',
            'NOI 导刊',
            'CTT(清华集训/北大集训)',
            '网络流与线性规划 24 题',
            'CSP-S 提高级',
            'CSP-J 入门级',
            'NOI Online',
            'Ynoi',
            'NOI 系列赛事',
            '经典套题',
            '国际知名赛事',
            'WC',
            'CTSC/CTS',
            '模板题',
            'USACO',
            'POI(波兰)',
            'IOI',
            'CCO(加拿大)',
            'CCC(加拿大)',
            'CEOI(中欧)',
            'eJOI(欧洲)',
            'COCI(克罗地亚)',
            'BalticOI(波罗的海)',
            'JOI(日本)',
            'AGM',
            'PA(波兰)',
            'ROI(俄罗斯)',
            'EGOI(欧洲/女生)',
            'NOISG(新加坡)',
            'NordicOI(北欧)',
            'BalkanOI(巴尔干半岛)',
            'KOI(韩国)',
            'RMI(罗马尼亚)',
            'COI(克罗地亚)',
            '洛谷原创',
            'ICPC',
            '洛谷月赛',
            '语言月赛',
            '洛谷比赛',
            '大学竞赛',
            'ROIR(俄罗斯)',
            'INOI(伊朗)',
            'UOI(乌克兰)',
            'JOISC/JOIST(日本)',
            'COTS(克罗地亚)',
            'Google Code Jam',
            'Moscow Olympiad',
            'PO(瑞典)',
            'PAIO',
            'MCC/MCO(马来西亚)',
            'KTSC(韩国)',
            'IATI(保加利亚/东欧)',
            'Google Kick Start',
            '入门赛',
            '蓝桥杯国赛',
            '蓝桥杯省赛',
            '省赛/邀请赛',
            '传智杯',
            'THUPC',
            'GESP',
            '其他竞赛',
            'THUSC',
            '高校校赛',
            'THUWC',
            'CSP-X 小学组',
            'Code+',
            '梦熊比赛',
            '信息与未来',
            '科创活动',
            'BCSP-X',
            '小学活动',
            '初中活动',
            'CSPro',
            'CCPC',
            '科大国创杯',
            '蓝桥杯青少年组'
        ],
        time: [
            '1996',
            '1997',
            '1998',
            '1999',
            '2000',
            '2001',
            '2002',
            '2003',
            '2004',
            '2005',
            '2006',
            '2007',
            '2008',
            '2009',
            '2010',
            '2011',
            '2012',
            '2013',
            '2014',
            '2015',
            '2016',
            '2017',
            '2018',
            '2019',
            '2020',
            '2021',
            '2022',
            '2023',
            '2024',
            '2025',
            '2026',
            '2027',
            '2028',
            '2029',
            '2077',
            '2078',
            '2079'
        ],
        region: [
            '重庆',
            '四川',
            '河南',
            '浙江',
            '上海',
            '福建',
            '江苏',
            '安徽',
            '湖南',
            '北京',
            '河北',
            '广东',
            '山东',
            '吉林',
            '山西',
            '江西',
            '贵州',
            '广西',
            '陕西',
            '国内省市',
            '辽宁',
            '云南',
            '天津',
            '湖北',
            '黑龙江',
            '海南',
            '甘肃',
            '青海',
            '台湾',
            '内蒙古',
            '西藏',
            '宁夏',
            '新疆',
            '香港',
            '澳门',
            '济南',
            '南京',
            '青岛',
            '国内赛站',
            'EC Final',
            '国际赛区',
            'NERC/NEERC',
            'SEERC',
            'CERC',
            'NWRRC',
            'WF',
            'NAC',
            '杭州',
            '昆明',
            '西安',
            '哈尔滨',
            '首尔',
            '横浜',
            'SWERC',
            '成都',
            '雅加达'
        ],
        special: [
            '交互题',
            '提交答案',
            'Special Judge',
            'O2优化',
            '通信题'
        ]
    };

    const DIMENSION_NAMES = {
        algorithm: '算法',
        source: '来源',
        time: '时间',
        region: '区域',
        special: '特殊题目'
    };
    const DIMENSION_KEYS = ['algorithm', 'source', 'time', 'region', 'special'];

    const STORAGE_KEY = 'luogu_random_jump_settings';
    let selectedTypes = new Set();
    let selectedDifficulties = new Set();
    let selectedTags = {
        algorithm: new Set(),
        source: new Set(),
        time: new Set(),
        region: new Set(),
        special: new Set()
    };
    let filterAccepted = false;
    let filterSubmitted = false;

    let userUid = null;
    let acceptedSet = new Set();
    let submittedSet = new Set();
    let userStatusReady = false;

    function compareVersions(v1, v2) {
        const parts1 = v1.split('.').map(Number);
        const parts2 = v2.split('.').map(Number);
        const len = Math.max(parts1.length, parts2.length);
        for (let i = 0; i < len; i++) {
            const a = parts1[i] || 0;
            const b = parts2[i] || 0;
            if (a > b) return 1;
            if (a < b) return -1;
        }
        return 0;
    }

    function checkForUpdate() {
        return new Promise((resolve) => {
            console.log('[更新检查] 开始请求', UPDATE_URL);
            GM_xmlhttpRequest({
                method: 'GET',
                url: UPDATE_URL,
                onload: function(res) {
                    console.log('[更新检查] 响应状态:', res.status);
                    console.log('[更新检查] 响应长度:', res.responseText ? res.responseText.length : 0);
                    try {
                        const text = res.responseText;
                        const versionMatch = text.match(/@version\s+([\d.]+)/);
                        if (!versionMatch) {
                            console.warn('[更新检查] 未解析到版本号');
                            resolve(false);
                            return;
                        }
                        const remoteVersion = versionMatch[1];
                        const currentVersion = GM_info.script.version;
                        console.log('[更新检查] 当前版本:', currentVersion, '远程版本:', remoteVersion);
                        if (compareVersions(remoteVersion, currentVersion) > 0) {
                            console.log('[更新检查] 发现新版本,弹出对话框');
                            showUpdateDialog(currentVersion, remoteVersion);
                            resolve(true);
                        } else {
                            console.log('[更新检查] 已是最新版本');
                            resolve(false);
                        }
                    } catch (e) {
                        console.error('[更新检查] 解析出错', e);
                        resolve(false);
                    }
                },
                onerror: function(err) {
                    console.warn('[更新检查] 请求失败', err);
                    resolve(false);
                }
            });
        });
    }

    function showUpdateDialog(currentVersion, newVersion) {
        const existing = document.getElementById('luogu-update-dialog-overlay');
        if (existing) existing.remove();

        const overlay = document.createElement('div');
        overlay.id = 'luogu-update-dialog-overlay';
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(2px);
            z-index: 2147483647;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: fadeIn 0.2s ease;
        `;

        const dialog = document.createElement('div');
        dialog.style.cssText = `
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            padding: 24px 28px;
            width: 360px;
            max-width: 90vw;
            text-align: center;
            animation: slideUp 0.25s ease;
        `;

        const icon = document.createElement('div');
        icon.innerHTML = '🚀';
        icon.style.cssText = 'font-size: 42px; margin-bottom: 12px;';

        const title = document.createElement('h3');
        title.textContent = '发现新版本';
        title.style.cssText = 'margin: 0 0 12px; font-size: 20px; font-weight: 700; color: #1a1a1a;';

        const info = document.createElement('p');
        info.style.cssText = 'margin: 0 0 24px; font-size: 14px; color: #555; line-height: 1.5;';
        info.innerHTML = `当前版本 <b>v${currentVersion}</b><br>最新版本 <b style="color: #4f8ef7;">v${newVersion}</b>`;

        const btnContainer = document.createElement('div');
        btnContainer.style.cssText = 'display: flex; gap: 12px; justify-content: center;';

        const laterBtn = document.createElement('button');
        laterBtn.textContent = '稍后再说';
        laterBtn.style.cssText = `
            padding: 8px 20px;
            font-size: 14px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: #f5f5f5;
            cursor: pointer;
            transition: background 0.2s;
        `;
        laterBtn.onmouseenter = () => { laterBtn.style.background = '#e8e8e8'; };
        laterBtn.onmouseleave = () => { laterBtn.style.background = '#f5f5f5'; };
        laterBtn.onclick = () => overlay.remove();

        const updateBtn = document.createElement('button');
        updateBtn.textContent = '立即更新';
        updateBtn.style.cssText = `
            padding: 8px 20px;
            font-size: 14px;
            border: none;
            border-radius: 8px;
            background: #4f8ef7;
            color: white;
            cursor: pointer;
            transition: background 0.2s;
        `;
        updateBtn.onmouseenter = () => { updateBtn.style.background = '#3a7bd5'; };
        updateBtn.onmouseleave = () => { updateBtn.style.background = '#4f8ef7'; };
        updateBtn.onclick = () => {
            window.open(DOWNLOAD_URL, '_blank');
            overlay.remove();
        };

        btnContainer.appendChild(laterBtn);
        btnContainer.appendChild(updateBtn);

        dialog.appendChild(icon);
        dialog.appendChild(title);
        dialog.appendChild(info);
        dialog.appendChild(btnContainer);

        overlay.appendChild(dialog);
        document.body.appendChild(overlay);

        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
            @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        `;
        document.head.appendChild(style);
    }

    function loadSettings() {
        try {
            const raw = localStorage.getItem(STORAGE_KEY);
            if (!raw) return;
            const data = JSON.parse(raw);
            if (data.types) {
                const validTypes = Object.values(TYPE_MAP);
                selectedTypes = new Set(
                    Array.from(data.types).filter(v => validTypes.includes(v))
                );
            }
            if (data.difficulties) selectedDifficulties = new Set(data.difficulties);
            if (data.tags) {
                DIMENSION_KEYS.forEach(key => {
                    if (data.tags[key] && Array.isArray(data.tags[key])) {
                        selectedTags[key] = new Set(data.tags[key]);
                    }
                });
            }
            if (typeof data.filterAccepted === 'boolean') filterAccepted = data.filterAccepted;
            if (typeof data.filterSubmitted === 'boolean') filterSubmitted = data.filterSubmitted;
        } catch (e) {
            console.warn('读取存储失败', e);
        }
    }

    function saveSettings() {
        const data = {
            types: Array.from(selectedTypes),
            difficulties: Array.from(selectedDifficulties),
            tags: {},
            filterAccepted: filterAccepted,
            filterSubmitted: filterSubmitted
        };
        DIMENSION_KEYS.forEach(key => {
            data.tags[key] = Array.from(selectedTags[key]);
        });
        localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    }

    loadSettings();

    function openDB() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(DB_NAME, DB_VERSION);
            request.onupgradeneeded = function(e) {
                const db = e.target.result;
                if (!db.objectStoreNames.contains(STORE_NAME)) {
                    const store = db.createObjectStore(STORE_NAME, { keyPath: 'pid' });
                    store.createIndex('difficulty', 'difficulty', { unique: false });
                    store.createIndex('type', 'type', { unique: false });
                    store.createIndex('tags', 'tags', { multiEntry: true });
                }
                if (!db.objectStoreNames.contains(METADATA_STORE)) {
                    db.createObjectStore(METADATA_STORE, { keyPath: 'key' });
                }
                if (!db.objectStoreNames.contains(USER_STATUS_STORE)) {
                    db.createObjectStore(USER_STATUS_STORE, { keyPath: 'id' });
                    console.log('【洛谷随机跳题】数据库升级:创建做题记录存储');
                }
            };
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    function getProblemCount() {
        return openDB().then(db => {
            return new Promise((resolve, reject) => {
                const tx = db.transaction(STORE_NAME, 'readonly');
                const store = tx.objectStore(STORE_NAME);
                const countReq = store.count();
                countReq.onsuccess = () => resolve(countReq.result);
                countReq.onerror = () => reject(countReq.error);
            });
        });
    }

    function clearProblems() {
        return openDB().then(db => {
            return new Promise((resolve, reject) => {
                const tx = db.transaction(STORE_NAME, 'readwrite');
                const store = tx.objectStore(STORE_NAME);
                const req = store.clear();
                req.onsuccess = () => resolve();
                req.onerror = () => reject(req.error);
            });
        });
    }

    function bulkInsert(problems) {
        return openDB().then(db => {
            return new Promise((resolve, reject) => {
                const tx = db.transaction(STORE_NAME, 'readwrite');
                const store = tx.objectStore(STORE_NAME);
                for (const p of problems) {
                    store.put(p);
                }
                tx.oncomplete = () => resolve();
                tx.onerror = () => reject(tx.error);
            });
        });
    }

    function setMetadata(key, value) {
        return openDB().then(db => {
            return new Promise((resolve, reject) => {
                const tx = db.transaction(METADATA_STORE, 'readwrite');
                const store = tx.objectStore(METADATA_STORE);
                store.put({ key, value });
                tx.oncomplete = () => resolve();
                tx.onerror = () => reject(tx.error);
            });
        });
    }

    async function saveUserStatus(uid, acceptedPids, submittedPids) {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(USER_STATUS_STORE, 'readwrite');
            const store = tx.objectStore(USER_STATUS_STORE);
            store.put({
                id: 'user_status',
                uid,
                acceptedPids,
                submittedPids,
                timestamp: Date.now()
            });
            tx.oncomplete = () => {
                console.log('【洛谷随机跳题】做题记录已保存到 IndexedDB');
                resolve();
            };
            tx.onerror = (e) => {
                console.error('保存做题记录失败', e);
                reject(e);
            };
        });
    }

    async function loadUserStatus() {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(USER_STATUS_STORE, 'readonly');
            const store = tx.objectStore(USER_STATUS_STORE);
            const req = store.get('user_status');
            req.onsuccess = () => {
                console.log('【洛谷随机跳题】从 IndexedDB 读取做题记录:', req.result ? '成功' : '无数据');
                resolve(req.result || null);
            };
            req.onerror = (e) => {
                console.error('读取做题记录失败', e);
                reject(e);
            };
        });
    }

    function getUidFromDOM() {
        const avatarLinks = document.querySelectorAll('a[href*="/user/"]');
        for (const link of avatarLinks) {
            if (link.querySelector('img.avatar') || link.querySelector('img[alt]')) {
                const match = link.getAttribute('href').match(/\/user\/(\d+)/);
                if (match) return match[1];
            }
        }
        const avatarImg = document.querySelector('img.avatar, .user-nav img[alt]');
        if (avatarImg) {
            const parentLink = avatarImg.closest('a[href*="/user/"]');
            if (parentLink) {
                const match = parentLink.getAttribute('href').match(/\/user\/(\d+)/);
                if (match) return match[1];
            }
        }
        return null;
    }

    function waitForUid() {
        return new Promise((resolve) => {
            const uid = getUidFromDOM();
            if (uid) {
                resolve(uid);
                return;
            }
            let attempts = 0;
            const maxAttempts = 20;
            const interval = setInterval(() => {
                const uid = getUidFromDOM();
                if (uid) {
                    clearInterval(interval);
                    resolve(uid);
                } else {
                    attempts++;
                    if (attempts >= maxAttempts) {
                        clearInterval(interval);
                        resolve(null);
                    }
                }
            }, 500);
        });
    }

    function fetchPracticeData(uid) {
        return new Promise((resolve, reject) => {
            const url = `https://www.luogu.com.cn/user/${uid}/practice`;
            GM_xmlhttpRequest({
                method: 'GET',
                url: url,
                onload: function(res) {
                    try {
                        const html = res.responseText;
                        const match = html.match(/<script id="lentille-context"[^>]*>([\s\S]*?)<\/script>/);
                        if (!match) {
                            reject(new Error('无法解析个人练习页面'));
                            return;
                        }
                        const json = JSON.parse(match[1]);
                        const acceptedPids = [];
                        const submittedPids = [];
                        if (json.data && json.data.passed) {
                            json.data.passed.forEach(item => acceptedPids.push(item.pid));
                        }
                        if (json.data && json.data.submitted) {
                            json.data.submitted.forEach(item => submittedPids.push(item.pid));
                        }
                        resolve({ acceptedPids, submittedPids });
                    } catch (e) {
                        reject(e);
                    }
                },
                onerror: function(err) {
                    reject(err);
                }
            });
        });
    }

    function updateUserSets(uid, acceptedPids, submittedPids) {
        userUid = uid;
        acceptedSet = new Set(acceptedPids);
        submittedSet = new Set([...acceptedPids, ...submittedPids]);
        userStatusReady = true;
        console.log(`【洛谷随机跳题】状态已更新:AC ${acceptedSet.size} 题,尝试 ${submittedSet.size} 题`);
    }

    async function refreshUserStatus(showMsg = true) {
        const uid = getUidFromDOM();
        if (!uid) throw new Error('无法获取用户 UID');
        if (showMsg) showStatusMessage('正在刷新做题记录...');
        const { acceptedPids, submittedPids } = await fetchPracticeData(uid);
        updateUserSets(uid, acceptedPids, submittedPids);
        await saveUserStatus(uid, acceptedPids, submittedPids);
        if (showMsg) showStatusMessage('做题记录已刷新!');
        if (panelUpdateFilterUI) panelUpdateFilterUI();
    }

    async function initUserStatus(uid) {
        if (!uid) return false;

        const cached = await loadUserStatus();
        if (cached && cached.uid === uid) {
            updateUserSets(uid, cached.acceptedPids, cached.submittedPids);
            console.log('【洛谷随机跳题】已从缓存加载做题记录');
            return true;
        }

        console.log('【洛谷随机跳题】无有效缓存,尝试自动获取做题记录...');
        try {
            const { acceptedPids, submittedPids } = await fetchPracticeData(uid);
            updateUserSets(uid, acceptedPids, submittedPids);
            await saveUserStatus(uid, acceptedPids, submittedPids);
            return true;
        } catch (e) {
            console.warn('自动获取做题记录失败', e);
            acceptedSet = new Set();
            submittedSet = new Set();
            userStatusReady = false;
            return false;
        }
    }

    async function getRandomProblem(filters) {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(STORE_NAME, 'readonly');
            const store = tx.objectStore(STORE_NAME);
            const req = store.getAll();
            req.onsuccess = function() {
                let results = req.result;
                const totalBefore = results.length;

                if (filters.difficulties && filters.difficulties.size > 0) {
                    results = results.filter(p => filters.difficulties.has(p.difficulty));
                }
                if (filters.types && filters.types.size > 0) {
                    results = results.filter(p => filters.types.has(p.type));
                }
                if (filters.tags) {
                    const tagNames = [];
                    DIMENSION_KEYS.forEach(key => {
                        const tags = filters.tags[key] || new Set();
                        tags.forEach(tag => tagNames.push(tag));
                    });
                    if (tagNames.length > 0) {
                        results = results.filter(p => {
                            if (!p.tags || p.tags.length === 0) return false;
                            return tagNames.every(tag => p.tags.includes(tag));
                        });
                    }
                }

                if (filters.filterAccepted && userStatusReady) {
                    results = results.filter(p => !acceptedSet.has(p.pid));
                }
                if (filters.filterSubmitted && userStatusReady) {
                    results = results.filter(p => !submittedSet.has(p.pid));
                }

                console.log(`【洛谷随机跳题】筛选前 ${totalBefore} 题 → 筛选后 ${results.length} 题`,
                    filters.filterAccepted ? `(排除AC ${acceptedSet.size})` : '',
                    filters.filterSubmitted ? `(排除尝试 ${submittedSet.size})` : '');

                if (results.length === 0) {
                    resolve(null);
                } else {
                    const random = results[Math.floor(Math.random() * results.length)];
                    resolve(random);
                }
            };
            req.onerror = () => reject(req.error);
        });
    }

    let panelUpdateFilterUI = null;

    function createFloatingPanel(button) {
        const panel = document.createElement('div');
        panel.style.cssText = `
            position: fixed;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.08);
            padding: 16px 18px;
            width: 300px;
            max-height: 480px;
            overflow-y: auto;
            border: 1px solid #eee;
            z-index: 2147483647;
            display: none;
            font-size: 13px;
            line-height: 1.5;
            color: #333;
        `;

        const typeTitle = document.createElement('div');
        typeTitle.textContent = '题库';
        typeTitle.style.cssText = 'font-weight:600; font-size:14px; margin-bottom:8px; color:#111;';
        panel.appendChild(typeTitle);

        const typeContainer = document.createElement('div');
        typeContainer.style.cssText = 'display:grid; grid-template-columns:1fr 1fr; gap:4px 10px; margin-bottom:16px;';
        TYPE_KEYS.forEach(displayName => {
            const typeValue = TYPE_MAP[displayName];
            const labelEl = document.createElement('label');
            labelEl.style.cssText = 'display:flex; align-items:center; padding:3px 6px; cursor:pointer; border-radius:6px; transition:background 0.15s;';
            labelEl.onmouseenter = () => { labelEl.style.background = '#f5f7fa'; };
            labelEl.onmouseleave = () => { labelEl.style.background = 'transparent'; };

            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.value = typeValue;
            checkbox.style.cssText = 'margin-right:6px; width:15px; height:15px; accent-color:#4f8ef7; cursor:pointer;';
            checkbox.checked = selectedTypes.has(typeValue);
            checkbox.addEventListener('change', function() {
                const val = this.value;
                if (this.checked) selectedTypes.add(val);
                else selectedTypes.delete(val);
                saveSettings();
            });

            const span = document.createElement('span');
            span.textContent = displayName;
            span.style.fontSize = '12px';

            labelEl.appendChild(checkbox);
            labelEl.appendChild(span);
            typeContainer.appendChild(labelEl);
        });
        panel.appendChild(typeContainer);

        const diffTitle = document.createElement('div');
        diffTitle.textContent = '难度';
        diffTitle.style.cssText = 'font-weight:600; font-size:14px; margin-bottom:8px; color:#111;';
        panel.appendChild(diffTitle);

        const diffContainer = document.createElement('div');
        diffContainer.style.cssText = 'display:grid; grid-template-columns:1fr 1fr; gap:4px 10px; margin-bottom:16px;';
        Object.entries(DIFFICULTY_MAP).forEach(([value, label]) => {
            const labelEl = document.createElement('label');
            labelEl.style.cssText = 'display:flex; align-items:center; padding:3px 6px; cursor:pointer; border-radius:6px; transition:background 0.15s;';
            labelEl.onmouseenter = () => { labelEl.style.background = '#f5f7fa'; };
            labelEl.onmouseleave = () => { labelEl.style.background = 'transparent'; };

            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.value = value;
            checkbox.style.cssText = 'margin-right:6px; width:15px; height:15px; accent-color:#4f8ef7; cursor:pointer;';
            checkbox.checked = selectedDifficulties.has(parseInt(value));
            checkbox.addEventListener('change', function() {
                const val = parseInt(this.value);
                if (this.checked) selectedDifficulties.add(val);
                else selectedDifficulties.delete(val);
                saveSettings();
            });

            const span = document.createElement('span');
            span.textContent = label;
            span.style.fontSize = '12px';

            labelEl.appendChild(checkbox);
            labelEl.appendChild(span);
            diffContainer.appendChild(labelEl);
        });
        panel.appendChild(diffContainer);

        const filterTitle = document.createElement('div');
        filterTitle.textContent = '筛选';
        filterTitle.style.cssText = 'font-weight:600; font-size:14px; margin-bottom:8px; color:#111;';
        panel.appendChild(filterTitle);

        const filterContainer = document.createElement('div');
        filterContainer.style.cssText = 'display:flex; flex-direction:column; gap:6px; margin-bottom:16px;';

        const tip = document.createElement('div');
        tip.className = 'filter-status-tip';
        tip.style.cssText = 'font-size:11px; color:#999; margin-top:-4px; margin-bottom:4px;';
        filterContainer.appendChild(tip);

        const stats = document.createElement('div');
        stats.className = 'filter-stats';
        stats.style.cssText = 'font-size:11px; color:#666; margin-bottom:4px;';
        filterContainer.appendChild(stats);

        function createFilterCheckbox(text, getter, setter) {
            const label = document.createElement('label');
            label.className = 'filter-checkbox';
            label.style.cssText = 'display:flex; align-items:center; padding:3px 6px; cursor:pointer; border-radius:6px; transition:background 0.15s;';
            label.onmouseenter = () => { label.style.background = '#f5f7fa'; };
            label.onmouseleave = () => { label.style.background = 'transparent'; };

            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.style.cssText = 'margin-right:6px; width:15px; height:15px; accent-color:#4f8ef7; cursor:pointer;';
            checkbox.checked = getter();
            checkbox.addEventListener('change', function() {
                setter(this.checked);
                saveSettings();
            });

            const span = document.createElement('span');
            span.textContent = text;
            span.style.fontSize = '12px';

            label.appendChild(checkbox);
            label.appendChild(span);
            return { label, checkbox };
        }

        const cb1 = createFilterCheckbox('仅显示未 AC', () => filterAccepted, val => { filterAccepted = val; });
        const cb2 = createFilterCheckbox('仅显示未尝试', () => filterSubmitted, val => { filterSubmitted = val; });
        filterContainer.appendChild(cb1.label);
        filterContainer.appendChild(cb2.label);

        function updateFilterUI() {
            const enabled = userUid !== null && userStatusReady;
            tip.textContent = enabled ? '(已登录,筛选可用)' : '(请先点击下方“刷新做题记录”按钮登录/刷新)';
            stats.textContent = enabled
                ? `已缓存 AC ${acceptedSet.size} 题,尝试 ${submittedSet.size} 题`
                : '暂无做题记录';

            [cb1, cb2].forEach(cb => {
                cb.checkbox.disabled = !enabled;
                if (!enabled) {
                    cb.checkbox.checked = false;
                    if (cb === cb1) filterAccepted = false;
                    if (cb === cb2) filterSubmitted = false;
                }
                cb.label.style.opacity = enabled ? '1' : '0.5';
                cb.label.style.cursor = enabled ? 'pointer' : 'not-allowed';
            });
        }
        updateFilterUI();
        panelUpdateFilterUI = updateFilterUI;

        panel.appendChild(filterContainer);

        const actionContainer = document.createElement('div');
        actionContainer.style.cssText = 'display:flex; gap:8px; margin-bottom:16px; flex-wrap:wrap;';

        const refreshBtn = document.createElement('button');
        refreshBtn.textContent = '刷新做题记录';
        refreshBtn.style.cssText = `
            flex:1; padding:4px 8px; font-size:12px; border:1px solid #ccc; border-radius:4px;
            background:#f8f8f8; cursor:pointer; transition:background 0.15s;
        `;
        refreshBtn.onmouseenter = () => { refreshBtn.style.background = '#e8e8e8'; };
        refreshBtn.onmouseleave = () => { refreshBtn.style.background = '#f8f8f8'; };
        refreshBtn.onclick = async function(e) {
            e.stopPropagation();
            try {
                await refreshUserStatus(true);
            } catch (err) {
                console.error(err);
                showStatusMessage('刷新失败:' + err.message, true);
            }
        };
        actionContainer.appendChild(refreshBtn);

        const updateBtn = document.createElement('button');
        updateBtn.textContent = '更新题库';
        updateBtn.style.cssText = `
            flex:1; padding:4px 8px; font-size:12px; border:1px solid #ccc; border-radius:4px;
            background:#f8f8f8; cursor:pointer; transition:background 0.15s;
        `;
        updateBtn.onmouseenter = () => { updateBtn.style.background = '#e8e8e8'; };
        updateBtn.onmouseleave = () => { updateBtn.style.background = '#f8f8f8'; };
        updateBtn.onclick = function(e) {
            e.stopPropagation();
            if (confirm('确定要重新下载并更新题库吗?这将覆盖本地缓存。')) {
                showStatusMessage('正在更新题库...');
                downloadAndImportData((current, total) => {
                    showStatusMessage(`更新进度: ${current}/${total}`);
                }).then(() => {
                    showStatusMessage('题库更新完成!');
                }).catch(err => {
                    console.error(err);
                    showStatusMessage('更新失败,请检查网络。', true);
                });
            }
        };
        actionContainer.appendChild(updateBtn);

        panel.appendChild(actionContainer);

        DIMENSION_KEYS.forEach(dimKey => {
            const dimName = DIMENSION_NAMES[dimKey] || dimKey;
            const tagsList = dimensionMaps[dimKey] || [];
            const tagSet = selectedTags[dimKey];

            const section = document.createElement('div');
            section.style.cssText = 'margin-bottom:14px;';

            const header = document.createElement('div');
            header.textContent = dimName;
            header.style.cssText = 'font-weight:600; font-size:13px; color:#222; margin-bottom:4px;';
            section.appendChild(header);

            const selectedContainer = document.createElement('div');
            selectedContainer.style.cssText = 'display:flex; flex-wrap:wrap; gap:4px; margin-bottom:4px;';
            section.appendChild(selectedContainer);

            function updateSelectedDisplay() {
                selectedContainer.innerHTML = '';
                if (tagSet.size === 0) {
                    selectedContainer.style.display = 'none';
                    return;
                }
                selectedContainer.style.display = 'flex';
                tagSet.forEach(tagName => {
                    const tagEl = document.createElement('span');
                    tagEl.style.cssText = `
                        display:inline-flex; align-items:center;
                        background:#eef3ff; color:#2b5cd9;
                        padding:2px 10px; border-radius:14px;
                        font-size:11px; gap:4px;
                    `;
                    const nameSpan = document.createElement('span');
                    nameSpan.textContent = tagName;
                    const removeBtn = document.createElement('span');
                    removeBtn.textContent = '×';
                    removeBtn.style.cssText = 'cursor:pointer; font-weight:700; color:#7a8bb0; font-size:14px;';
                    removeBtn.onclick = (e) => {
                        e.stopPropagation();
                        tagSet.delete(tagName);
                        updateSelectedDisplay();
                        saveSettings();
                    };
                    tagEl.appendChild(nameSpan);
                    tagEl.appendChild(removeBtn);
                    selectedContainer.appendChild(tagEl);
                });
            }
            updateSelectedDisplay();

            const wrapper = document.createElement('div');
            wrapper.style.cssText = 'position:relative;';

            const input = document.createElement('input');
            input.type = 'text';
            input.placeholder = `搜索 ${dimName}`;
            input.style.cssText = `
                width:100%; padding:4px 10px;
                border:1px solid #ddd; border-radius:6px;
                font-size:12px; outline:none;
                transition:border 0.15s;
                box-sizing:border-box;
            `;
            input.onfocus = () => { input.style.borderColor = '#4f8ef7'; };
            input.onblur = () => { input.style.borderColor = '#ddd'; };
            wrapper.appendChild(input);

            const suggestionBox = document.createElement('div');
            suggestionBox.style.cssText = `
                position:absolute; top:100%; left:0; right:0;
                background:#fff; border:1px solid #ddd; border-top:none;
                border-radius:0 0 6px 6px;
                max-height:120px; overflow-y:auto;
                display:none; z-index:10001;
                box-shadow:0 4px 12px rgba(0,0,0,0.05);
            `;
            wrapper.appendChild(suggestionBox);

            input.addEventListener('input', function() {
                const query = this.value.trim().toLowerCase();
                if (!query) { suggestionBox.style.display = 'none'; return; }
                const matches = [];
                for (const tagName of tagsList) {
                    if (tagName.toLowerCase().includes(query)) {
                        if (!matches.includes(tagName)) {
                            matches.push(tagName);
                        }
                    }
                }
                if (matches.length === 0) { suggestionBox.style.display = 'none'; return; }
                suggestionBox.innerHTML = '';
                matches.slice(0, 10).forEach(tagName => {
                    const item = document.createElement('div');
                    item.style.cssText = `
                        padding:3px 10px; cursor:pointer; font-size:12px;
                        border-bottom:1px solid #f5f5f5;
                        transition:background 0.1s;
                    `;
                    item.onmouseenter = () => { item.style.background = '#f5f7fa'; };
                    item.onmouseleave = () => { item.style.background = 'transparent'; };
                    item.addEventListener('mousedown', function(e) { e.preventDefault(); });
                    item.onclick = () => {
                        if (!tagSet.has(tagName)) {
                            tagSet.add(tagName);
                            updateSelectedDisplay();
                            saveSettings();
                        }
                        input.value = '';
                        suggestionBox.style.display = 'none';
                    };
                    const nameSpan = document.createElement('span');
                    nameSpan.textContent = tagName;
                    item.appendChild(nameSpan);
                    suggestionBox.appendChild(item);
                });
                suggestionBox.style.display = 'block';
            });

            input.addEventListener('blur', function() {
                setTimeout(() => { suggestionBox.style.display = 'none'; }, 200);
            });

            section.appendChild(wrapper);

            const clearBtn = document.createElement('button');
            clearBtn.textContent = '清空';
            clearBtn.style.cssText = `
                font-size:11px; color:#e55c5c; background:none; border:none;
                cursor:pointer; padding:2px 6px; margin-top:4px;
                border-radius:4px; transition:background 0.15s;
            `;
            clearBtn.onmouseenter = () => { clearBtn.style.background = '#fef0f0'; };
            clearBtn.onmouseleave = () => { clearBtn.style.background = 'transparent'; };
            clearBtn.onclick = () => {
                tagSet.clear();
                updateSelectedDisplay();
                saveSettings();
            };
            section.appendChild(clearBtn);

            panel.appendChild(section);
        });

        let hoverTimeout = null;
        button.addEventListener('mouseenter', function() {
            clearTimeout(hoverTimeout);
            panel.style.display = 'block';
            const rect = button.getBoundingClientRect();
            const panelRect = panel.getBoundingClientRect();
            let left = rect.right - panelRect.width;
            if (left < 10) left = 10;
            const maxLeft = window.innerWidth - panelRect.width - 10;
            if (left > maxLeft) left = maxLeft;
            let top = rect.top - panelRect.height - 10;
            if (top < 10) {
                top = rect.bottom + 10;
            }
            panel.style.left = left + 'px';
            panel.style.top = top + 'px';
            panel.style.bottom = 'auto';
            panel.style.right = 'auto';
        });

        button.addEventListener('mouseleave', function(e) {
            hoverTimeout = setTimeout(() => {
                const related = e.relatedTarget;
                if (related && (panel.contains(related) || button.contains(related))) {
                    return;
                }
                panel.style.display = 'none';
            }, 200);
        });

        panel.addEventListener('mouseenter', function() {
            clearTimeout(hoverTimeout);
            panel.style.display = 'block';
        });

        panel.addEventListener('mouseleave', function(e) {
            const related = e.relatedTarget;
            if (related && (panel.contains(related) || button.contains(related))) {
                return;
            }
            panel.style.display = 'none';
        });

        const parent = button.parentNode;
        parent.style.position = 'relative';
        parent.appendChild(panel);

        return panel;
    }

    async function startRandomJump() {
        if ((filterAccepted || filterSubmitted) && !userStatusReady) {
            if (confirm('您启用了 AC/尝试筛选,但尚未刷新做题记录。是否立即刷新?')) {
                try {
                    await refreshUserStatus(true);
                } catch (err) {
                    console.error(err);
                    showStatusMessage('获取失败,请手动点击“刷新做题记录”按钮。', true);
                    return;
                }
            } else {
                const tempAccepted = filterAccepted;
                const tempSubmitted = filterSubmitted;
                filterAccepted = false;
                filterSubmitted = false;
                await doRandomJump();
                filterAccepted = tempAccepted;
                filterSubmitted = tempSubmitted;
                return;
            }
        }
        await doRandomJump();
    }

    async function doRandomJump() {
        let diffArray;
        if (selectedDifficulties.size === 0) {
            diffArray = Object.keys(DIFFICULTY_MAP).map(Number);
        } else {
            diffArray = Array.from(selectedDifficulties);
        }
        let typeArray;
        if (selectedTypes.size === 0) {
            typeArray = Object.values(TYPE_MAP);
        } else {
            typeArray = Array.from(selectedTypes);
        }

        const filters = {
            difficulties: new Set(diffArray),
            types: new Set(typeArray),
            tags: selectedTags,
            filterAccepted: filterAccepted && userStatusReady,
            filterSubmitted: filterSubmitted && userStatusReady
        };

        try {
            const problem = await getRandomProblem(filters);
            if (!problem) {
                alert('没有找到符合条件的题目,请调整筛选条件。');
                return;
            }
            window.open(`https://www.luogu.com.cn/problem/${problem.pid}`, '_blank');
        } catch (err) {
            console.error(err);
            alert('查询失败,请重试。');
        }
    }

    function showStatusMessage(text, isError = false) {
        const existing = document.getElementById('luogu-offline-status');
        if (existing) existing.remove();
        const div = document.createElement('div');
        div.id = 'luogu-offline-status';
        div.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${isError ? '#f44336' : '#2196F3'};
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            z-index: 99999;
            font-size: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
            max-width: 300px;
            word-wrap: break-word;
        `;
        div.textContent = text;
        document.body.appendChild(div);
        if (!isError) {
            setTimeout(() => { if (div.parentNode) div.remove(); }, 5000);
        }
    }

    function downloadAndImportData(progressCallback) {
        return new Promise((resolve, reject) => {
            if (typeof pako === 'undefined') {
                reject(new Error('pako 库未加载,请检查网络或刷新页面重试。'));
                return;
            }
            clearProblems().then(() => {
                GM_xmlhttpRequest({
                    method: 'GET',
                    url: DATA_URL,
                    responseType: 'arraybuffer',
                    onload: function(res) {
                        try {
                            const compressed = new Uint8Array(res.response);
                            const decompressed = pako.ungzip(compressed, { to: 'string' });
                            const lines = decompressed.split('\n').filter(line => line.trim() !== '');
                            const total = lines.length;
                            const batchSize = 1000;
                            let imported = 0;

                            function importBatch(start) {
                                const end = Math.min(start + batchSize, total);
                                const batch = [];
                                for (let i = start; i < end; i++) {
                                    try {
                                        const obj = JSON.parse(lines[i]);
                                        batch.push({
                                            pid: obj.pid,
                                            title: obj.title,
                                            difficulty: obj.difficulty,
                                            type: obj.type,
                                            tags: obj.tags || []
                                        });
                                    } catch (e) {}
                                }
                                if (batch.length === 0) {
                                    if (end < total) importBatch(end);
                                    else resolve();
                                    return;
                                }
                                bulkInsert(batch).then(() => {
                                    imported += batch.length;
                                    if (progressCallback) progressCallback(imported, total);
                                    if (end < total) {
                                        importBatch(end);
                                    } else {
                                        setMetadata('data_version', new Date().toISOString()).then(() => resolve());
                                    }
                                }).catch(err => reject(err));
                            }

                            importBatch(0);
                        } catch (e) {
                            reject(e);
                        }
                    },
                    onerror: function(err) {
                        reject(err);
                    }
                });
            }).catch(err => reject(err));
        });
    }

    async function init() {
        if (typeof pako === 'undefined') {
            console.warn('pako 库尚未加载,等待...');
            const checkPako = setInterval(() => {
                if (typeof pako !== 'undefined') {
                    clearInterval(checkPako);
                    initCore();
                }
            }, 500);
            return;
        }
        await initCore();
    }

    async function initCore() {
        setupUI();
        console.log('【洛谷随机跳题】UI 已创建,等待用户状态初始化...');

        checkForUpdate().catch(err => console.warn('检查更新失败', err));

        waitForUid().then(async (uid) => {
            if (uid) {
                const success = await initUserStatus(uid);
                if (success) {
                    console.log('【洛谷随机跳题】做题记录已就绪');
                    if (panelUpdateFilterUI) panelUpdateFilterUI();
                } else {
                    console.log('【洛谷随机跳题】做题记录未就绪,您可手动点击“刷新做题记录”');
                }
            } else {
                console.log('【洛谷随机跳题】未能获取用户 UID,筛选功能暂不可用');
            }
        });
    }

    function setupUI() {
        const btn = document.querySelector('[name="gotorandom"]');
        if (!btn) {
            console.warn('未找到随机跳题按钮');
            return;
        }

        const parent = btn.parentNode;
        const newBtn = document.createElement('button');
        newBtn.className = btn.className;
        newBtn.textContent = btn.textContent;
        newBtn.style.cssText = btn.style.cssText;
        for (const attr of btn.attributes) {
            if (attr.name !== 'name') {
                newBtn.setAttribute(attr.name, attr.value);
            }
        }
        newBtn.setAttribute('name', 'gotorandom-custom');
        parent.replaceChild(newBtn, btn);

        try {
            createFloatingPanel(newBtn);
        } catch (e) {
            console.error('创建面板失败:', e);
            showStatusMessage('UI 初始化失败,请刷新页面重试。', true);
            return;
        }

        newBtn.addEventListener('click', async function(e) {
            e.preventDefault();
            try {
                const count = await getProblemCount();
                if (count === 0) {
                    showStatusMessage('正在下载题库数据,请稍候...');
                    await downloadAndImportData((current, total) => {
                        showStatusMessage(`导入进度: ${current}/${total}`);
                    });
                    showStatusMessage('题库数据导入完成!');
                }
                await startRandomJump();
            } catch (err) {
                console.error(err);
                showStatusMessage('发生错误,请刷新重试。', true);
            }
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();

:::

将难度文字改为入门

:::info[]

// ==UserScript==
// @name         洛谷难度强制改入门(全页面通用版)
// @namespace    http://tampermonkey.net/
// @version      15.0
// @description  适配题目详情、列表、题单、用户练习情况页。清洗特殊符号,精准替换难度为“入门”,保留颜色
// @match        *://*.luogu.com.cn/*
// @match        *://*.luogu.com/*
// @run-at       document-end
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    console.log('【油猴脚本】v15.0 全页面通用版启动!');

    const difficultyTexts = [
        '入门', '普及-', '普及', '普及+/提高-', '普及/提高-',
        '提高', '提高+/省选-', '省选/NOI-', 'NOI/NOI+/CTS', 'NOI/NOI+/CTSC',
        '暂无评定'
    ];

    function cleanText(str) {
        return str.replace(/[\s\u00a0\u200b]+/g, '').replace(/[−—–]/g, '-');
    }

    const cleanDifficultyTexts = difficultyTexts.map(cleanText);

    function replaceDifficulty() {
        const walker = document.createTreeWalker(
            document.body,
            NodeFilter.SHOW_TEXT,
            null,
            false
        );

        let node;
        let changedCount = 0;

        while (node = walker.nextNode()) {
            const text = cleanText(node.nodeValue);

            if (cleanDifficultyTexts.includes(text) && text !== '入门') {
                node.nodeValue = '入门';
                changedCount++;
            }
        }

        if (changedCount > 0) {
            console.log(`【油猴脚本】成功将 ${changedCount} 处难度替换为“入门”!`);
        }
    }

    setInterval(replaceDifficulty, 100);

    const observer = new MutationObserver(() => {
        replaceDifficulty();
    });

    function init() {
        if (document.body) {
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
            replaceDifficulty();
        } else {
            setTimeout(init, 50);
        }
    }

    init();
})();

:::

虚假 RMJ

( https://www.luogu.com.cn/discuss/1399108 https://www.luogu.com.cn/discuss/1409952 ) :::info

// ==UserScript==
// @name         GenGen-RMJ
// @icon         https://cdn.luogu.com.cn/upload/image_hosting/yy27itbl.png
// @namespace    https://gengen.qzz.io/
// @version      5.3
// @description  GenGen RMJ
// @author       GenGen Dev
// @run-at       document-start
// @match        https://challenges.cloudflare.com/cdn-cgi/challenge-platform/*
// @match        https://www.luogu.com.cn/*
// @match        https://atcoder.jp/contests/*/submit?RMJ=1
// @match        https://atcoder.jp/contests/*/submissions/me
// @match        https://codeforces.com/*
// @connect      *
// @inject-into  page
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        unsafeWindow
// @license      MIT
// ==/UserScript==

// 重定向遮罩
(() => {
    const h = location.href;
    if (h.includes('challenges.cloudflare.com')) return;

    let flag = '';
    try { flag = GM_getValue('rmj-flag-action', ''); } catch { /* ignore */ }

    const ref = document.referrer || '';
    if (!(ref.includes('RMJ=1') || flag === 'submit')) return;

    const isStatus =
        h.includes('codeforces.com/problemset/status') ||
        (h.includes('atcoder.jp/contests/') && h.includes('/submissions/me'));
    if (!isStatus) return;

    const m = document.createElement('div');
    m.id = 'rmj-redirect-mask';
    m.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:#efefef;';

    const attach = () => {
        if (!document.getElementById('rmj-redirect-mask')) {
            (document.documentElement || document.body).appendChild(m);
        }
    };
    if (document.documentElement) attach();
    else new MutationObserver((_, o) => {
        if (document.documentElement) { o.disconnect(); attach(); }
    }).observe(document, { childList: true });
})();

(() => {
    'use strict';

    const TAG = '[RMJ]';
    const LOG = (...a) => console.log(TAG, ...a);
    const ERR = (...a) => console.error(TAG, ...a);

    const HOST = location.hostname;
    const isLuogu = () => HOST === 'www.luogu.com.cn';
    const isCF = () => HOST === 'codeforces.com';
    const isAT = () => HOST === 'atcoder.jp';
    const isCfChallenge = () => HOST === 'challenges.cloudflare.com';

    const docReady = (fn) =>
        document.readyState === 'loading'
            ? document.addEventListener('DOMContentLoaded', fn, { once: true })
            : fn();

    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

    const waitFor = (selector, cb, timeout = 12000) => {
        const t0 = Date.now();
        const timer = setInterval(() => {
            const el = document.querySelector(selector);
            if (el) {
                clearInterval(timer);
                cb(el);
            } else if (Date.now() - t0 > timeout) {
                clearInterval(timer);
            }
        }, 120);
        return timer;
    };

    const waitForEl = (selector, timeout = 10000) =>
        new Promise((resolve, reject) => {
            const hit = document.querySelector(selector);
            if (hit) return resolve(hit);
            const root = document.body || document.documentElement;
            const obs = new MutationObserver(() => {
                const el = document.querySelector(selector);
                if (el) {
                    obs.disconnect();
                    clearTimeout(timer);
                    resolve(el);
                }
            });
            obs.observe(root, { childList: true, subtree: true });
            const timer = setTimeout(() => {
                obs.disconnect();
                reject(new Error('超时: ' + selector));
            }, timeout);
        });

    const Timers = () => {
        const set = new Set();
        return {
            iv(fn, ms) { const id = setInterval(fn, ms); set.add(id); return id; },
            to(fn, ms) { const id = setTimeout(() => { set.delete(id); fn(); }, ms); set.add(id); return id; },
            clear(id) { set.delete(id); clearInterval(id); clearTimeout(id); },
            clearAll() { for (const id of set) { clearInterval(id); clearTimeout(id); } set.clear(); }
        };
    };

    // 主题存储
    const ThemeStore = (() => {
        const P = 'gen-at-';
        const get = (k) => GM_getValue(P + k, '');
        const set = (k, v) => GM_setValue(P + k, String(v));

        // 从洛谷 .theme-page 提取,找不到容器则不写入
        const extractFromLuogu = () => {
            const el =
                document.querySelector('.theme-page.theme-frosted') ||
                document.querySelector('.theme-page') ||
                document.querySelector('[class*="theme-page"]');
            if (!el) return false;

            const inlineStyle = (el.getAttribute('style') || '').replace(/&quot;/g, '"');
            let computed = null;
            try { computed = getComputedStyle(el); } catch { computed = null; }

            const readVar = (name) => {
                if (inlineStyle) {
                    const re = new RegExp(
                        name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*:\\s*([^;]+)'
                    );
                    const m = inlineStyle.match(re);
                    if (m && m[1].trim()) return m[1].trim();
                }
                if (computed) {
                    const v = computed.getPropertyValue(name);
                    if (v && v.trim()) return v.trim();
                }
                return '';
            };

            const vars = {
                body_back: '--theme-body-back',
                bg_image: '--theme-body-image',
                bg_color: '--theme-body-color',
                bg_repeat: '--theme-body-image-repeat',
                bg_size: '--theme-body-image-size',
                bg_pos: '--theme-body-image-position',
                mid_mask: '--theme-body-mid-mask',
                color_filter: '--theme-body-color-filter',
                card_bg: '--theme-card-background',
                card_blur: '--theme-card-backdrop-filter',
            };

            let found = false;
            for (const [key, cssVar] of Object.entries(vars)) {
                const v = readVar(cssVar);
                if (v) { set(key, v); found = true; }
            }

            try {
                const nu = document.querySelector('#app .user-nav .title span');
                if (nu && nu.textContent.trim()) set('luogu_user', nu.textContent.trim());
                const av = document.querySelector('#app .top-bar .avatar img');
                if (av && av.src) set('luogu_avatar', av.src);
            } catch { /* ignore */ }

            return found;
        };

        const extractWithRetry = (maxAttempts = 25, interval = 200) => {
            let n = 0;
            const tryIt = () => {
                if (extractFromLuogu()) return;
                if (++n < maxAttempts) setTimeout(tryIt, interval);
            };
            tryIt();
        };

        // 应用到任意遮罩容器
        const applyTo = (el) => {
            if (!el) return;

            const b64 = get('bg_b64');
            const raw = get('bg_image');

            let img = '';
            if (b64) {
                img = `url(${b64})`;
            } else if (raw) {
                const m = raw.match(/url\(\s*(['"]?)(.+?)\1\s*\)/i);
                let u = m ? m[2] : raw;
                if (u && !/^https?:\/\//i.test(u) && !/^data:/i.test(u)) {
                    try { u = new URL(u, 'https://www.luogu.com.cn/').href; } catch { /* keep */ }
                }
                if (u && u !== 'none') img = /^url\(/i.test(raw) ? `url(${u})` : `url(${u})`;
            }

            const M = {
                '--rmj-back': get('body_back') || '#f5f5f5',
                '--rmj-img': img,
                '--rmj-color': get('bg_color'),
                '--rmj-repeat': get('bg_repeat') || 'no-repeat',
                '--rmj-size': get('bg_size') || 'cover',
                '--rmj-pos': get('bg_pos') || 'center',
                '--rmj-mask': get('mid_mask') || 'none',
                '--rmj-filter': get('color_filter') || 'none',
                '--rmj-card': get('card_bg') || 'rgba(255,255,255,.78)',
                '--rmj-blur': get('card_blur') || 'blur(14px)',
            };
            for (const [k, v] of Object.entries(M)) {
                if (v) el.style.setProperty(k, v);
            }
        };

        return { get, set, applyTo, extractFromLuogu, extractWithRetry };
    })();

    // 共享遮罩样式
    GM_addStyle(`
        .rmj-ovl-base{
            position:fixed!important;inset:0!important;z-index:2147483647!important;
            display:flex!important;align-items:center!important;justify-content:center!important;
            overflow:hidden!important;pointer-events:all!important;cursor:default!important;
            background:var(--rmj-back,#f5f5f5)!important;
            color:#333!important;box-sizing:border-box!important;-webkit-font-smoothing:antialiased!important;
        }
        .rmj-ovl-base *{box-sizing:border-box!important;margin:0!important;padding:0!important;font-family:inherit!important;line-height:inherit!important}
        .rmj-ovl-base .rmj-ly{position:absolute!important;inset:0!important;pointer-events:none!important;
            -webkit-mask:var(--rmj-mask,none) no-repeat/100% 100%!important;mask:var(--rmj-mask,none) no-repeat/100% 100%!important}
        .rmj-ovl-base .rmj-ly-c{background:var(--rmj-color,transparent)!important;filter:var(--rmj-filter,none)!important}
        .rmj-ovl-base .rmj-ly-i{background:var(--rmj-img,none) var(--rmj-pos,center)/var(--rmj-size,cover) var(--rmj-repeat,no-repeat)!important}
        .rmj-ovl-card{
            position:relative!important;z-index:1!important;width:420px!important;max-width:90vw!important;
            padding:36px 32px 40px!important;border-radius:4px!important;border:none!important;
            background:var(--rmj-card,rgba(255,255,255,.78))!important;
            backdrop-filter:var(--rmj-blur,blur(14px))!important;-webkit-backdrop-filter:var(--rmj-blur,blur(14px))!important;
            box-shadow:0 8px 32px rgba(0,0,0,.18),0 1.5px 6px rgba(0,0,0,.08)!important;
            display:flex!important;flex-direction:column!important;align-items:center!important;gap:20px!important;
        }
        .rmj-ovl-card h2{font-size:20px!important;font-weight:600!important;color:#333!important;letter-spacing:.5px!important;user-select:none!important;text-align:center!important}
        .rmj-ovl-card p{font-size:13px!important;color:#888!important;text-align:center!important;user-select:none!important}
        .rmj-ovl-spin{width:26px;height:26px;border:3px solid rgba(0,0,0,.1);border-top-color:#005c97;border-radius:50%;animation:rmj-ovl-spin .7s linear infinite}
        @keyframes rmj-ovl-spin{to{transform:rotate(360deg)}}
    `);

    // 路由
    const Router = (() => {
        const handlers = new Set();
        let last = location.href;

        const notify = () => {
            const cur = location.href;
            if (cur === last) return;
            last = cur;
            for (const fn of handlers) {
                try { fn(cur); } catch (e) { ERR('路由回调异常', e); }
            }
        };

        const wrap = (name) => {
            const orig = history[name];
            if (!orig || orig.__rmjWrapped) return;
            const wrapped = function (...args) {
                const ret = orig.apply(this, args);
                setTimeout(notify, 0);
                return ret;
            };
            wrapped.__rmjWrapped = true;
            history[name] = wrapped;
        };

        wrap('pushState');
        wrap('replaceState');
        addEventListener('popstate', notify, true);
        addEventListener('hashchange', notify, true);

        return {
            on(fn) { handlers.add(fn); return () => handlers.delete(fn); },
            notify,
        };
    })();

    const CACHE_CF = 'cf-submissions-cache';
    const CACHE_AT = 'at-submissions-cache';
    const LAST_UPDATE_CF = 'cf-last-update';
    const LAST_UPDATE_AT = 'at-last-update';
    const SYNC_INTERVAL_MS = 24 * 60 * 60 * 1000;
    const FINAL_AT = new Set(['AC', 'WA', 'CE', 'RE', 'TLE', 'MLE', 'OLE', 'IE']);

    // CF 挑战页补丁
    const CfChallengePatch = {
        applied: false,
        apply() {
            if (this.applied || !isCfChallenge()) return;
            this.applied = true;
            const XHR = (unsafeWindow || window).XMLHttpRequest;
            if (!XHR) return;
            const origOpen = XHR.prototype.open;
            const origSend = XHR.prototype.send;
            XHR.prototype.open = function (method, url) {
                this._rmjUrl = url || '';
                return origOpen.apply(this, arguments);
            };
            XHR.prototype.send = function (body) {
                if (this._rmjUrl) this.timeout = undefined;
                return origSend.apply(this, arguments);
            };
        }
    };

    // 洛谷主界面
    const MainUI = (() => {
        const VERSION = '5.3';
        const POLL_MS = 1000;

        const SVG = {
            ok: `<svg class="svg-inline--fa fa-check lcolor--success" data-prefix="fas" data-icon="check" role="img" viewBox="0 0 448 512" aria-hidden="true"><path class="" fill="currentColor" d="M434.8 70.1c14.3 10.4 17.5 30.4 7.1 44.7l-256 352c-5.5 7.6-14 12.3-23.4 13.1s-18.5-2.7-25.1-9.3l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l101.5 101.5 234-321.7c10.4-14.3 30.4-17.5 44.7-7.1z"></path></svg>`,
            err: `<svg class="svg-inline--fa fa-xmark lcolor--error" data-prefix="fas" data-icon="xmark" role="img" viewBox="0 0 384 512" aria-hidden="true"><path class="" fill="currentColor" d="M55.1 73.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L147.2 256 9.9 393.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192.5 301.3 329.9 438.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.8 256 375.1 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192.5 210.7 55.1 73.4z"></path></svg>`,
            na: `<svg class="svg-inline--fa fa-minus lcolor--grey-4" data-prefix="fas" data-icon="minus" role="img" viewBox="0 0 448 512" aria-hidden="true"><path class="" fill="currentColor" d="M0 256c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 288c-17.7 0-32-14.3-32-32z"></path></svg>`
        };

        const C = {
            ac: '#52c41a', wa: '#e74c3c', na: '#404040',
            p: '#0ea5e9', bd: '#e2e8f0', t: '#1e293b',
            m: '#64748b', bg: '#fff', alt: '#f8fafc'
        };

        GM_addStyle(`
            .rmj-trigger{display:inline-flex;align-items:center;gap:8px;padding:8px 16px;background:#fff;color:${C.t};border:1px solid ${C.bd};border-radius:8px;font-weight:600;font-size:13px;cursor:pointer;transition:border-color .18s ease,color .18s ease,box-shadow .18s ease;box-shadow:0 1px 3px rgba(0,0,0,.04);user-select:none;margin-right:10px;height:36px}
            .rmj-trigger:hover{border-color:${C.p};color:${C.p};box-shadow:0 2px 10px rgba(14,165,233,.14)}
            .rmj-trigger:active{box-shadow:0 1px 3px rgba(14,165,233,.18) inset}
            .rmj-trigger img{width:20px;height:20px;border-radius:4px}
            .rmj-overlay{pointer-events:none;position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:2147483646;display:flex;align-items:center;justify-content:center;opacity:0;visibility:hidden;transition:opacity .22s ease,visibility .22s ease}
            .rmj-overlay.show{opacity:1;visibility:visible;pointer-events:auto}
            .rmj-modal{width:480px;max-height:85vh;background:rgba(255,255,255,0.82);backdrop-filter:blur(10px);border-radius:12px;box-shadow:0 25px 60px rgba(0,0,0,.14);display:flex;flex-direction:column;overflow:hidden;transform:scale(.97);transition:transform .25s cubic-bezier(.25,.8,.32,1),height .25s ease}
            .rmj-overlay.show .rmj-modal{transform:scale(1)}
            .rmj-overlay:not(.show) .rmj-modal *{pointer-events:none!important;cursor:default!important}
            .rmj-overlay:not(.show) .rmj-modal a{color:inherit!important;text-decoration:none!important}
            .rmj-pages{flex:1;overflow:hidden;position:relative;min-height:0;height:auto;transition:height .28s ease}
            .rmj-page:not(.active){visibility:hidden;pointer-events:none;position:absolute;top:0;left:50%;width:50%;height:100%}
            .rmj-page.active{visibility:visible;pointer-events:auto;opacity:1;z-index:1}
            .rmj-head{padding:20px 24px 16px;border-bottom:1px solid ${C.bd};display:flex;align-items:center;gap:12px}
            .rmj-head img{width:36px;height:36px;border-radius:8px}
            .rmj-title{flex:1;margin:0;font-weight:700;font-size:20px;background:linear-gradient(135deg,${C.p},#2563eb);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
            .rmj-close{width:32px;height:32px;border:0;background:0 0;color:${C.m};cursor:pointer;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:20px;transition:background .15s ease,color .15s ease}
            .rmj-close:hover{background:${C.alt};color:${C.t}}
            .rmj-pages{display:grid;width:100%;overflow:hidden;transition:height .28s ease}
            .rmj-pages-inner{display:contents}
            .rmj-page{grid-area:1/1/2/2;padding:24px;overflow-y:auto;box-sizing:border-box;visibility:hidden;pointer-events:none;opacity:0;transition:opacity .25s ease,visibility .25s}
            .rmj-welcome-title{font-size:18px;font-weight:700;color:${C.t};margin-bottom:12px}
            .rmj-update-badge{display:inline-block;padding:3px 10px;background:linear-gradient(135deg,${C.p},#2563eb);color:#fff;border-radius:20px;font-size:11px;font-weight:600;margin-left:8px}
            .rmj-feat{list-style:none;padding:0;margin:16px 0}
            .rmj-feat li{display:flex;align-items:flex-start;gap:10px;padding:8px 0;color:${C.m};font-size:14px;line-height:1.5}
            .rmj-feat li::before{content:'·';flex-shrink:0}
            .rmj-sec{font-size:11px;font-weight:700;color:${C.m};text-transform:uppercase;letter-spacing:1px;margin:0 0 12px}
            .rmj-sec:not(:first-child){margin-top:20px}
            .rmj-card{background:${C.alt};border:1px solid ${C.bd};border-radius:10px;padding:14px 16px;display:flex;align-items:center;justify-content:space-between;transition:border-color .18s ease,box-shadow .18s ease,background .18s ease}
            .rmj-card:hover{border-color:rgba(14,165,233,.35);box-shadow:0 2px 10px rgba(14,165,233,.08);background:#fff}
            .rmj-card+.rmj-card{margin-top:8px}
            .rmj-info{display:flex;align-items:center;gap:12px}
            .rmj-logo{width:32px;height:32px;border-radius:6px;object-fit:contain}
            .rmj-name{font-size:14px;font-weight:600;color:${C.t}}
            .rmj-badge{display:inline-flex;align-items:center;gap:4px;padding:4px 12px;border-radius:20px;font-size:12px;font-weight:600}
            .rmj-badge.on{background:rgba(82,196,26,.09);color:${C.ac}}
            .rmj-badge.off{background:rgba(231,76,60,.09);color:${C.wa};cursor:pointer;text-decoration:none;transition:background .15s ease,color .15s ease}
            .rmj-badge.off:hover{background:rgba(231,76,60,.16)}
            .rmj-badge.load{background:#f1f5f9;color:${C.m}}
            .rmj-spin{width:14px;height:14px;border:2px solid ${C.bd};border-top-color:${C.p};border-radius:50%;animation:spin .8s linear infinite}
            @keyframes spin{to{transform:rotate(360deg)}}
            .rmj-links{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:12px}
            .rmj-link{display:flex;align-items:center;gap:8px;padding:10px 12px;background:${C.alt};border:1px solid ${C.bd};border-radius:8px;color:${C.t};text-decoration:none;font-size:13px;font-weight:500;transition:border-color .18s ease,color .18s ease,box-shadow .18s ease,background .18s ease}
            .rmj-link:hover{border-color:${C.p};color:${C.p};background:#fff;box-shadow:0 2px 10px rgba(14,165,233,.10)}
            .rmj-link svg{width:16px;height:16px;flex-shrink:0}
            .rmj-foot{padding:16px 24px;border-top:1px solid ${C.bd};display:flex;align-items:center;justify-content:space-between;background:${C.alt}}
            .rmj-btn{padding:8px 16px;border:1px solid ${C.bd};background:#fff;color:${C.t};border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;transition:border-color .15s ease,color .15s ease,background .15s ease}
            .rmj-btn:hover:not(:disabled){border-color:${C.p};color:${C.p};background:#f8fafc}
            .rmj-btn:disabled{opacity:.4;cursor:not-allowed}
            .rmj-dots{display:flex;gap:6px}
            .rmj-dot{width:6px;height:6px;border-radius:50%;background:${C.bd};transition:background .2s ease,width .2s ease}
            .rmj-dot.active{background:${C.p};width:18px;border-radius:3px}
            .rmj-prob{display:inline-flex;align-items:center;transition:color .3s ease}
            .rmj-prob.ac{color:${C.ac};font-weight:bold}
            .rmj-prob.wa{color:${C.wa};font-weight:bold}
            .rmj-prob.na{color:#3498db}
            .rmj-ico{position:absolute;inset:0;background:0 0;display:flex;align-items:center;justify-content:center;z-index:10;border-radius:inherit;animation:fadeIn .3s}
            .rmj-ico svg{width:18px;height:18px;animation:popIn .3s cubic-bezier(.34,1.56,.64,1)}
            .rmj-hide>*:not(.rmj-ico){visibility:hidden!important}
            @keyframes fadeIn{from{opacity:0}to{opacity:1}}
            @keyframes popIn{from{transform:scale(.5);opacity:0}to{transform:scale(1);opacity:1}}
            @keyframes badgePop{0%{transform:scale(.8);opacity:0}60%{transform:scale(1.05)}100%{transform:scale(1);opacity:1}}
            .rmj-record-badge{animation:badgePop .4s ease-out}
            .rmj-sel{position:relative;display:inline-block;margin-left:8px}
            .rmj-sel-btn{position:relative;display:inline-flex;align-items:center;min-width:120px;padding:.3125em 1.5em .3125em 1em;border:1px solid #ccc;border-radius:3px;background:#fff;font-size:14px;line-height:1.4;cursor:pointer;text-align:left}
            .rmj-sel-btn::after{content:"";position:absolute;right:10px;top:50%;width:6px;height:6px;border-right:1.5px solid #555;border-bottom:1.5px solid #555;transform:translateY(-65%) rotate(45deg);transition:transform .2s}
            .rmj-sel.open .rmj-sel-btn::after{transform:translateY(-35%) rotate(-135deg)}
            .rmj-sel-menu{position:absolute;top:calc(100% + 4px);left:0;width:100%;margin:0;padding:4px 0;list-style:none;background:#fff;border:1px solid #ccc;border-radius:4px;box-shadow:0 4px 12px rgba(0,0,0,.1);opacity:0;transform:translateY(-8px);pointer-events:none;transition:opacity .2s ease,transform .2s ease;z-index:100}
            .rmj-sel-menu.open{opacity:1;transform:translateY(0);pointer-events:all}
            .rmj-sel-menu li{padding:3px 12px;cursor:pointer;font-size:14px}
            .rmj-sel-menu li:hover{background:#f0f9ff}
            .rmj-refresh-wrap{display:inline-flex;align-items:center;margin-left:8px;cursor:pointer;color:${C.m};transition:color .18s ease,transform .25s ease}
            .rmj-refresh-wrap:hover{color:${C.p};transform:rotate(90deg)}
            .rmj-refresh{width:14px;height:14px}
            .rmj-switch{position:relative;display:inline-block;width:40px;height:22px}
            .rmj-switch input{opacity:0;width:0;height:0}
            .rmj-slider{position:absolute;cursor:pointer;inset:0;background:#ccc;transition:background .2s ease;border-radius:22px}
            .rmj-slider:before{position:absolute;content:"";height:16px;width:16px;left:3px;bottom:3px;background:#fff;transition:transform .2s ease;border-radius:50%}
            .rmj-switch input:checked + .rmj-slider{background:${C.p}}
            .rmj-switch input:checked + .rmj-slider:before{transform:translateX(18px)}
            .rmj-switch input:disabled + .rmj-slider{opacity:.5;cursor:not-allowed}
        `);

        const cfMap = new Map();
        const atMap = new Map();
        let cfRawCache = '';
        let atRawCache = '';
        let atCapturing = false;
        let listTimer = null;
        let problemTimer = null;
        let problemObserver = null;
        let problemGen = 0;
        let currentProblemPath = '';
        let modalEl = null;
        let modalPage = 0;
        let cfPollTimer = null;
        let atLoginPollTimer = null;

        const SPECIAL_ACCOUNTS = ['General0000000826', 'General000000826'];

        const isSpecialAccount = () => {
            const cfH = GM_getValue('cf-handle', '');
            const atH = GM_getValue('at-handle', '');
            return SPECIAL_ACCOUNTS.includes(cfH) || SPECIAL_ACCOUNTS.includes(atH);
        };

        const isSyncDisabled = () => {
            if (isSpecialAccount()) return true;
            let fromParams = false;
            try {
                const params = new URLSearchParams(location.search);
                fromParams = params.get('rmj-disable-sync') === 'true';
            } catch (e) { /* ignore */ }
            if (fromParams) return true;
            if (GM_getValue('rmj-disable-sync', null) === null) {
                GM_setValue('rmj-disable-sync', false);
            }
            return GM_getValue('rmj-disable-sync', false) === true;
        };

        const captureCfHandle = () => {
            if (!isCF()) return;
            const attempt = () => {
                const el = document.querySelector('#header > div.lang-chooser > div:nth-child(2) > a:nth-child(1)');
                if (!el) return setTimeout(attempt, 1000);
                const text = el.textContent.trim();
                if (text && !['Enter', '登录'].includes(text)) {
                    const stored = GM_getValue('cf-handle', '');
                    if (stored !== text) GM_setValue('cf-handle', text);
                }
            };
            attempt();
        };

        // 拉取 AT 用户名;未登录返回 null
        const fetchAtHandle = () => new Promise((resolve) => {
            GM_xmlhttpRequest({
                method: 'GET',
                url: 'https://atcoder.jp/',
                timeout: 8000,
                onload: (r) => {
                    if (r.status !== 200) return resolve(null);
                    try {
                        const doc = new DOMParser().parseFromString(r.responseText, 'text/html');
                        const el = doc.querySelector('#navbar-collapse > ul.nav.navbar-nav.navbar-right > li:nth-child(2) > a');
                        if (!el) return resolve(null);
                        const t = el.textContent.trim();
                        if (!t || ['Sign Up', 'Login', '登录'].includes(t)) return resolve(null);
                        resolve(t);
                    } catch { resolve(null); }
                },
                onerror: () => resolve(null),
                ontimeout: () => resolve(null),
            });
        });

        const captureAtHandle = async () => {
            atCapturing = true;
            updateModal();

            const handle = await fetchAtHandle();
            if (handle) {
                const stored = GM_getValue('at-handle', '');
                if (stored !== handle) GM_setValue('at-handle', handle);
                atCapturing = false;
                return updateModal();
            }

            // 未登录:打开登录页并 5s 轮询
            try { window.open('https://atcoder.jp/login?lang=en', '_blank'); } catch { /* ignore */ }

            if (atLoginPollTimer) clearInterval(atLoginPollTimer);
            let polls = 0;
            atLoginPollTimer = setInterval(async () => {
                polls++;
                if (polls > 60) {
                    clearInterval(atLoginPollTimer);
                    atLoginPollTimer = null;
                    atCapturing = false;
                    updateModal();
                    return;
                }
                const h = await fetchAtHandle();
                if (h) {
                    clearInterval(atLoginPollTimer);
                    atLoginPollTimer = null;
                    const stored = GM_getValue('at-handle', '');
                    if (stored !== h) GM_setValue('at-handle', h);
                    atCapturing = false;
                    updateModal();
                }
            }, 5000);
        };

        const readCaches = () => {
            try {
                const cfData = GM_getValue(CACHE_CF, '[]');
                const atData = GM_getValue(CACHE_AT, '[]');

                if (cfData !== cfRawCache) {
                    cfRawCache = cfData;
                    cfMap.clear();
                    JSON.parse(cfData).forEach((s) => {
                        const m = s?.taskDisplay?.match(/CF[A-Z0-9]+/i);
                        if (!m) return;
                        const key = m[0].toUpperCase();
                        const status = s.status || null;
                        if (!cfMap.has(key) || (cfMap.get(key) !== 'OK' && status === 'OK')) {
                            cfMap.set(key, status);
                        }
                    });
                }

                if (atData !== atRawCache) {
                    atRawCache = atData;
                    atMap.clear();
                    JSON.parse(atData).forEach((s) => {
                        if (!s?.taskKey) return;
                        const key = s.taskKey.toLowerCase();
                        const status = s.status || null;
                        if (!atMap.has(key) || (atMap.get(key) !== 'AC' && status === 'AC')) {
                            atMap.set(key, status);
                        }
                    });
                }
            } catch (e) { ERR(e); }
        };

        const queryStatus = (pid) => {
            if (/^CF[A-Z0-9]+$/i.test(pid)) {
                const v = cfMap.get(pid.toUpperCase());
                return v === 'OK' ? 'AC' : v ? 'WA' : 'NONE';
            }
            if (/^AT_/i.test(pid)) {
                const k = pid.replace(/^AT_/i, '').toLowerCase();
                const v = atMap.get(k);
                return v === 'AC' ? 'AC' : v ? 'WA' : 'NONE';
            }
            return null;
        };

        const updateListIcons = () => {
            readCaches();
            document.querySelectorAll('.row').forEach((row) => {
                const [sc, pc] = row.children;
                if (!pc) return;
                const m = pc.textContent.trim().match(/^(\S+)/);
                if (!m) return;
                const st = queryStatus(m[1]);
                if (!st) {
                    const ov = sc.querySelector('.rmj-ico');
                    if (ov) { ov.remove(); sc.classList.remove('rmj-hide'); }
                    return;
                }
                let ov = sc.querySelector('.rmj-ico');
                if (!ov) {
                    ov = document.createElement('div');
                    ov.className = 'rmj-ico';
                    sc.style.position = 'relative';
                    sc.appendChild(ov);
                    sc.classList.add('rmj-hide');
                }
                const icon = st === 'AC' ? SVG.ok : st === 'WA' ? SVG.err : SVG.na;
                if (ov.dataset.s !== st) { ov.innerHTML = icon; ov.dataset.s = st; }
            });
        };

        const startListPoll = () => {
            if (listTimer) return;
            updateListIcons();
            listTimer = setInterval(updateListIcons, POLL_MS);
        };

        const stopListPoll = () => {
            if (!listTimer) return;
            clearInterval(listTimer);
            listTimer = null;
        };

        const updateProblemBadge = () => {
            readCaches();
            const pid = location.pathname.split('/problem/')[1];
            if (!pid) return;
            const st = queryStatus(pid);
            if (!st) return;
            const link = document.querySelectorAll('a[href*="/record/list?pid="]')[0];
            if (!link) return;

            let tag = link.querySelector('.rmj-prob');
            if (!tag) {
                const orig = link.querySelector('span');
                if (orig) orig.style.display = 'none';
                tag = document.createElement('span');
                tag.className = 'rmj-prob';
                link.appendChild(tag);
            }

            const way = document.querySelectorAll(
                'a[href*="https://help.luogu.com.cn/manual/luogu/problem/remote-judge"]'
            )[0];
            if (way && way.textContent !== 'GenGen RMJ') {
                way.textContent = 'GenGen RMJ';
                way.href = 'https://gengen.qzz.io/rmj/';
            }

            const cls = st === 'AC' ? 'ac' : st === 'WA' ? 'wa' : 'na';
            const txt = st === 'AC' ? 'Accepted' : st === 'WA' ? 'Unaccepted' : '暂无';
            if (tag.dataset.s !== st) {
                tag.className = 'rmj-prob ' + cls;
                tag.innerHTML = txt;
                tag.dataset.s = st;
            }
        };

        const startProblemPoll = () => {
            if (problemTimer) return;
            updateProblemBadge();
            problemTimer = setInterval(updateProblemBadge, POLL_MS);
        };

        const stopProblemPoll = () => {
            if (!problemTimer) return;
            clearInterval(problemTimer);
            problemTimer = null;
        };

        const teardownProblemObserver = () => {
            problemGen++;
            if (problemObserver) { problemObserver.disconnect(); problemObserver = null; }
            currentProblemPath = '';
        };

        const startCfPoll = () => {
            if (cfPollTimer) clearInterval(cfPollTimer);
            const initialHandle = GM_getValue('cf-handle', '');
            let checks = 0;
            cfPollTimer = setInterval(() => {
                checks++;
                const current = GM_getValue('cf-handle', '');
                if (current !== initialHandle || checks > 60) {
                    clearInterval(cfPollTimer);
                    cfPollTimer = null;
                    updateModal();
                }
            }, 1000);
            updateModal();
        };

        const buildModal = () => {
            if (modalEl) modalEl.remove();
            modalEl = document.createElement('div');
            modalEl.className = 'rmj-overlay';
            modalEl.innerHTML = `
                <div class="rmj-modal">
                    <div class="rmj-head">
                        <img src="https://cdn.luogu.com.cn/upload/image_hosting/yy27itbl.png">
                        <h2 class="rmj-title">GenGen RMJ</h2>
                        <button class="rmj-close">&times;</button>
                    </div>
                    <div class="rmj-pages">
                        <div class="rmj-pages-inner">
                            <div class="rmj-page">
                                <div class="rmj-welcome-title">👋 欢迎使用 GenGen RMJ 5 正式版 <span class="rmj-update-badge">v${VERSION}</span></div>
                                <p style="color:${C.m};font-size:14px;margin:0 0 8px">在洛谷上无缝刷 Codeforces 和 AtCoder 题目,同步提交记录。</p>
                                <ul class="rmj-feat">
                                    <strong><li>请点击下一页来绑定你的账户!</li></strong>
                                    <li>自动同步 CF/AT 账号提交记录</li>
                                    <li>题目列表和题单直观显示通过状态</li>
                                    <li>Cloudflare 验证加速绕过</li>
                                    <li>记录详细查看功能</li>
                                    <li>最新更新:完全适配新前端</li>
                                </ul>
                            </div>
                            <div class="rmj-page">
                                <div class="rmj-sec">账号绑定</div>
                                <div class="rmj-card"><div class="rmj-info"><img class="rmj-logo" src="https://codeforces.com/codeforces.org/s/33478/android-icon-192x192.png"><div class="rmj-name">Codeforces</div></div><div id="rmj-cf"></div></div>
                                <div class="rmj-card"><div class="rmj-info"><img class="rmj-logo" src="https://img.atcoder.jp/assets/atcoder.png"><div class="rmj-name">AtCoder</div></div><div id="rmj-at"></div></div>

                                <div class="rmj-sec">设置</div>
                                <div class="rmj-card">
                                    <div class="rmj-info">
                                        <div class="rmj-name">自动同步</div>
                                    </div>
                                    <label class="rmj-switch">
                                        <input type="checkbox" id="rmj-disable-sync">
                                        <span class="rmj-slider"></span>
                                    </label>
                                </div>

                                <div class="rmj-sec">快捷链接</div>
                                <div class="rmj-links">
                                    <a class="rmj-link" href="https://gengen.qzz.io" target="_blank"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>官网</a>
                                    <a class="rmj-link" href="https://gengen.qzz.io/ticket/" target="_blank"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>反馈</a>
                                    <a class="rmj-link" href="https://scriptcat.org/scripts/code/5099/GenGen-RMJ.user.js" target="_blank"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>源码</a>
                                    <a class="rmj-link" href="https://www.luogu.me/article/ttethqcb" target="_blank"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>文章</a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="rmj-foot">
                        <button class="rmj-btn rmj-prev" disabled>← 上一页</button>
                        <div class="rmj-dots"><div class="rmj-dot active"></div><div class="rmj-dot"></div></div>
                        <button class="rmj-btn rmj-next">下一页 →</button>
                    </div>
                </div>
            `;
            document.body.appendChild(modalEl);

            modalEl.querySelector('.rmj-close').onclick = () => {
                GM_setValue('rmj-version-shown', VERSION);
                hideModal();
                modalEl.addEventListener('click', (e) => {
                    if (!modalEl.classList.contains('show')) {
                        e.stopImmediatePropagation();
                        e.preventDefault();
                    }
                }, true);
            };
            modalEl.querySelector('.rmj-prev').onclick = () => switchModalPage(0);
            modalEl.querySelector('.rmj-next').onclick = () => switchModalPage(1);

            updateModal();
        };

        const updateModal = () => {
            if (!modalEl) return;
            const cfH = GM_getValue('cf-handle', '');
            const atH = GM_getValue('at-handle', '');
            const cfEl = modalEl.querySelector('#rmj-cf');
            const atEl = modalEl.querySelector('#rmj-at');

            const refreshIcon = `<span class="rmj-refresh-wrap"><svg class="rmj-refresh" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg></span>`;

            if (cfPollTimer) {
                cfEl.innerHTML = `<span class="rmj-badge load"><span class="rmj-spin"></span>同步中...</span>`;
            } else if (cfH) {
                cfEl.innerHTML = `<span class="rmj-badge on">${cfH}</span>${refreshIcon}`;
            } else {
                cfEl.innerHTML = `<a class="rmj-badge off" href="https://codeforces.com/enter" target="_blank" id="rmj-cf-bind">去绑定 →</a>`;
            }

            if (atCapturing) {
                atEl.innerHTML = `<span class="rmj-badge load"><span class="rmj-spin"></span>等待登录...</span>`;
            } else if (atH) {
                atEl.innerHTML = `<span class="rmj-badge on">${atH}</span>${refreshIcon}`;
            } else {
                atEl.innerHTML = `<a class="rmj-badge off" href="javascript:void(0)" id="rmj-at-bind">去绑定 →</a>`;
            }

            const cfBind = modalEl.querySelector('#rmj-cf-bind');
            if (cfBind) cfBind.onclick = () => { startCfPoll(); };

            const cfRefresh = modalEl.querySelector('#rmj-cf .rmj-refresh-wrap');
            if (cfRefresh) {
                cfRefresh.onclick = () => {
                    window.open('https://codeforces.com/enter', '_blank');
                    startCfPoll();
                };
            }

            const atBind = modalEl.querySelector('#rmj-at-bind');
            if (atBind) {
                atBind.onclick = (e) => { e.preventDefault(); captureAtHandle(); };
            }

            const atRefresh = modalEl.querySelector('#rmj-at .rmj-refresh-wrap');
            if (atRefresh) atRefresh.onclick = () => captureAtHandle();

            const syncToggle = modalEl.querySelector('#rmj-disable-sync');
            if (syncToggle) {
                const isDisabled = isSyncDisabled();
                syncToggle.checked = !isDisabled;

                if (isSpecialAccount()) {
                    syncToggle.checked = false;
                    syncToggle.disabled = true;
                    syncToggle.title = '特殊账号无法修改同步设置';
                }

                syncToggle.onchange = async () => {
                    if (isSpecialAccount()) {
                        syncToggle.checked = false;
                        return;
                    }
                    GM_setValue(CACHE_AT, '[]');
                    GM_setValue(CACHE_CF, '[]');
                    GM_setValue(LAST_UPDATE_AT, '0');
                    GM_setValue('cf-0last-update', '0');
                    updateListIcons();
                    updateProblemBadge();
                };
            }
        };

        const switchModalPage = (idx) => {
            if (!modalEl || idx === modalPage) return;
            const pagesContainer = modalEl.querySelector('.rmj-pages');
            const allPages = modalEl.querySelectorAll('.rmj-page');
            const targetPage = allPages[idx];
            const dots = modalEl.querySelectorAll('.rmj-dot');
            const prevBtn = modalEl.querySelector('.rmj-prev');
            const nextBtn = modalEl.querySelector('.rmj-next');

            allPages.forEach((p, i) => p.classList.toggle('active', i === idx));
            if (targetPage && pagesContainer) {
                pagesContainer.style.height = targetPage.scrollHeight + 'px';
            }
            dots.forEach((d, i) => d.classList.toggle('active', i === idx));
            prevBtn.disabled = idx === 0;
            nextBtn.disabled = idx === dots.length - 1;
            modalPage = idx;
            if (idx === 1 && !GM_getValue('at-handle', '') && !atCapturing) {
                fetchAtHandle().then((h) => {
                    if (h) {
                        const stored = GM_getValue('at-handle', '');
                        if (stored !== h) GM_setValue('at-handle', h);
                        updateModal();
                    }
                });
            }
        };

        const showModal = (page = 0) => {
            if (!modalEl) buildModal();
            modalPage = page;
            const pagesContainer = modalEl.querySelector('.rmj-pages');
            const allPages = modalEl.querySelectorAll('.rmj-page');
            const targetPage = allPages[page];
            const dots = modalEl.querySelectorAll('.rmj-dot');
            const prevBtn = modalEl.querySelector('.rmj-prev');
            const nextBtn = modalEl.querySelector('.rmj-next');

            allPages.forEach((p, i) => p.classList.toggle('active', i === page));
            requestAnimationFrame(() => {
                if (targetPage && pagesContainer) {
                    pagesContainer.style.height = targetPage.scrollHeight + 'px';
                }
            });
            dots.forEach((d, i) => d.classList.toggle('active', i === page));
            prevBtn.disabled = page === 0;
            nextBtn.disabled = page === dots.length - 1;
            modalEl.style.pointerEvents = '';
            modalEl.classList.add('show');
        };

        const hideModal = () => {
            if (!modalEl) return;
            modalEl.classList.remove('show');
            modalEl.style.pointerEvents = 'none';
        };

        const checkVersion = () => {
            if (GM_getValue('rmj-version-shown', '') !== VERSION) {
                setTimeout(() => showModal(0), 500);
            }
        };

        const injectHomeButton = () => {
            if (location.pathname !== '/' || document.querySelector('.rmj-trigger')) return;
            waitFor('.right', (nav) => {
                if (nav.dataset.rmj) return;
                nav.dataset.rmj = '1';
                const btn = document.createElement('button');
                btn.className = 'rmj-trigger';
                btn.innerHTML = `<img src="https://cdn.luogu.com.cn/upload/image_hosting/yy27itbl.png">GenGen RMJ`;
                btn.onclick = () => showModal(1);
                nav.parentElement.insertBefore(btn, nav);
            });
        };

        const initProblemPage = () => {
            const p = location.pathname;
            if (!p.startsWith('/problem/CF') && !p.startsWith('/problem/AT')) return;
            if (currentProblemPath === p && problemObserver) return;
            currentProblemPath = p;
            const myPath = p;
            const myGen = ++problemGen;

            const rmj = p.startsWith('/problem/CF') ? '1' : '2';
            const pid = p.split('/problem/')[1];
            if (!pid) return;

            if (problemObserver) { problemObserver.disconnect(); problemObserver = null; }

            waitFor('.side', (side) => {
                if (myGen !== problemGen || currentProblemPath !== myPath) return;
                problemObserver = new MutationObserver(() => {
                    side.querySelectorAll('a[href*="/record/list?pid="]').forEach((link) => {
                        if (link.dataset.rmjHook) return;
                        link.dataset.rmjHook = '1';
                        link.addEventListener('click', (e) => {
                            if (e.button !== 0) return;
                            e.preventDefault();
                            e.stopImmediatePropagation();
                            const u = new URL('/record/list', location.origin);
                            const sp = new URLSearchParams(location.search);
                            for (const [k, v] of sp) u.searchParams.set(k, v);
                            u.searchParams.set('pid', pid);
                            u.searchParams.set('rmj', rmj);
                            location.href = u.toString();
                        }, true);
                        link.addEventListener('mousedown', (e) => {
                            if (e.button !== 1) return;
                            const u = new URL('/record/list', location.origin);
                            const sp = new URLSearchParams(location.search);
                            for (const [k, v] of sp) u.searchParams.set(k, v);
                            u.searchParams.set('pid', pid);
                            u.searchParams.set('rmj', rmj);
                            link.href = u.toString();
                        }, true);
                    });
                    updateProblemBadge();
                });
                problemObserver.observe(side, { childList: true, subtree: true });
            });

            updateProblemBadge();
            startProblemPoll();
        };

        const injectRecordListSelector = () => {
            if (!location.pathname.startsWith('/record/list')) return;
            const myGen = problemGen;
            waitFor(
                '#app > div.main-container.lside-nav > div > main > div > div:nth-child(1) > section:nth-child(2) > div > div > div.text.lform-size-middle',
                (b) => {
                    if (myGen !== problemGen) return;
                    const cur = new URLSearchParams(location.search).get('rmj') || '';

                    let w = document.querySelector('.rmj-sel');
                    if (w) {
                        const btn = w.querySelector('.rmj-sel-btn');
                        const menu = w.querySelector('.rmj-sel-menu');
                        if (btn && menu) {
                            const act = menu.querySelector(`li[data-value="${cur}"]`);
                            if (act && btn.textContent !== act.textContent) {
                                btn.textContent = act.textContent;
                            }
                        }
                        return;
                    }

                    w = document.createElement('span');
                    w.className = 'rmj-sel';
                    w.innerHTML = `
                        <button class="rmj-sel-btn">洛谷</button>
                        <ul class="rmj-sel-menu">
                            <li data-value="">洛谷</li>
                            <li data-value="1">Codeforces</li>
                            <li data-value="2">AtCoder</li>
                        </ul>
                    `;
                    b.after(w);

                    const btn = w.querySelector('.rmj-sel-btn');
                    const menu = w.querySelector('.rmj-sel-menu');

                    btn.addEventListener('click', (e) => {
                        e.stopPropagation();
                        w.classList.toggle('open');
                        menu.classList.toggle('open');
                    });

                    menu.querySelectorAll('li').forEach((li) => {
                        li.addEventListener('click', (e) => {
                            e.stopPropagation();
                            const val = li.dataset.value;
                            btn.textContent = li.textContent;
                            w.classList.remove('open');
                            menu.classList.remove('open');
                            const p = new URLSearchParams(location.search);
                            if (val) p.set('rmj', val);
                            else p.delete('rmj');
                            location.search = p.toString();
                        });
                    });

                    document.addEventListener('click', () => {
                        w.classList.remove('open');
                        menu.classList.remove('open');
                    });

                    const act = menu.querySelector(`li[data-value="${cur}"]`);
                    if (act) btn.textContent = act.textContent;
                }
            );
        };

        const handleRoute = () => {
            if (!isLuogu()) return;
            const path = location.pathname;

            ThemeStore.extractWithRetry(15, 250);

            if (path === '/') injectHomeButton();

            if (path.startsWith('/problem/CF') || path.startsWith('/problem/AT')) {
                initProblemPage();
            } else {
                stopProblemPoll();
                teardownProblemObserver();
            }

            if (path.startsWith('/training') || path.startsWith('/problem/list')) {
                startListPoll();
            } else {
                stopListPoll();
            }

            if (path.startsWith('/record/list')) {
                injectRecordListSelector();
            }
        };

        const init = () => {
            if (!isLuogu()) return;
            checkVersion();
            handleRoute();
            addEventListener('beforeunload', () => { stopListPoll(); stopProblemPoll(); });
        };

        return { init, handleRoute, hideModal, captureCfHandle };
    })();

    // 洛谷记录详情页(DET)
    const RecordDetail = (() => {
        const _gmGet = GM_getValue;
        const _gmReq = GM_xmlhttpRequest;

        const VALID = [
            /^https:\/\/www\.luogu\.com\.cn\/record\/cf\/[^/]+\/[^/?#]+/,
            /^https:\/\/www\.luogu\.com\.cn\/record\/at\/[^/]+\/[^/?#]+/,
        ];

        const CF2LG = {
            OK: 12, WRONG_ANSWER: 6, TIME_LIMIT_EXCEEDED: 5, MEMORY_LIMIT_EXCEEDED: 4,
            OUTPUT_LIMIT_EXCEEDED: 3, RUNTIME_ERROR: 7, COMPILATION_ERROR: 2, TESTING: 1, WAITING: 0
        };
        const FINAL_CF = new Set(['OK', 'WRONG_ANSWER', 'COMPILATION_ERROR', 'RUNTIME_ERROR',
            'TIME_LIMIT_EXCEEDED', 'MEMORY_LIMIT_EXCEEDED', 'OUTPUT_LIMIT_EXCEEDED']);

        GM_addStyle(`
            #rmj-det-overlay.rmj-ovl-base{z-index:2147483647!important}
            #rmj-det-card{width:420px!important;max-width:90vw!important}
        `);

        const gmJson = (url) => new Promise((ok, no) => {
            _gmReq({
                method: 'GET', url, timeout: 15000, anonymous: true,
                onload: (r) => { try { ok(JSON.parse(r.responseText)); } catch (e) { no(e); } },
                onerror: () => no(new Error('网络错误')),
                ontimeout: () => no(new Error('请求超时'))
            });
        });

        const gmText = (url) => new Promise((ok, no) => {
            _gmReq({
                method: 'GET', url, timeout: 15000, anonymous: true,
                onload: (r) => r.status === 200 ? ok(r.responseText) : no(new Error('状态码 ' + r.status)),
                onerror: () => no(new Error('网络错误')),
                ontimeout: () => no(new Error('请求超时'))
            });
        });

        let lastKey = '';
        let generation = 0;
        const timers = Timers();

        const buildLoader = () => {
            const el = document.createElement('div');
            el.id = 'rmj-det-overlay';
            el.className = 'rmj-ovl-base';
            el.innerHTML = `
                <div class="rmj-ly rmj-ly-c"></div>
                <div class="rmj-ly rmj-ly-i"></div>
                <div id="rmj-det-card" class="rmj-ovl-card">
                    <h2>正在加载提交记录</h2>
                    <p>正在从 CF/AT 获取数据</p>
                    <div class="rmj-ovl-spin"></div>
                </div>
            `;
            ThemeStore.applyTo(el);
            return el;
        };

        // 未绑定提示
        const showBindError = (bindName) => {
            const el = document.createElement('div');
            el.id = 'rmj-det-overlay';
            el.className = 'rmj-ovl-base';
            el.innerHTML = `
                <div class="rmj-ly rmj-ly-c"></div>
                <div class="rmj-ly rmj-ly-i"></div>
                <div id="rmj-det-card" class="rmj-ovl-card">
                    <h2>账号未绑定</h2>
                    <p>请先在 GenGen RMJ 面板中绑定 ${bindName} 账号</p>
                    <a href="https://www.luogu.com.cn/" style="margin-top:8px!important;padding:8px 22px !important;background:#66ccff;color:#fff;text-decoration:none;border-radius:6px;font-size:14px;display:inline-block;">前往洛谷主页绑定</a>
                </div>
            `;
            ThemeStore.applyTo(el);
            (document.documentElement || document.body).appendChild(el);
        };

        const destroy = () => {
            generation++;
            timers.clearAll();
            const mask = document.getElementById('rmj-det-overlay');
            if (mask) mask.remove();
            lastKey = '';
        };

        const init = () => {
            if (!VALID.some((r) => r.test(location.href))) {
                if (lastKey) destroy();
                return;
            }

            const m = location.pathname.match(/\/record\/(cf|at)\/([^/]+)\/([^/?#]+)/);
            if (!m) return;
            const [, plat, cid, sid] = m;
            const key = `${plat}/${cid}/${sid}`;
            if (lastKey === key) return;

            destroy();
            lastKey = key;
            const myGen = generation;

            const isCFPage = plat === 'cf';
            const isATPage = plat === 'at';

            // 未绑定则拒绝查看
            const bindKey = isCFPage ? 'cf-handle' : 'at-handle';
            const bindName = isCFPage ? 'Codeforces' : 'AtCoder';
            if (!_gmGet(bindKey, '')) {
                showBindError(bindName);
                return;
            }

            const handle = _gmGet('cf-handle', '') || _gmGet('rmj-cf-handle', '') || '';
            const code = _gmGet(`{${cid},${sid}}`, '');

            const titleTimer = timers.iv(() => { document.title = 'GenGen RMJ 加载中'; }, 100);
            const mask = buildLoader();
            (document.documentElement || document.body || document).appendChild(mask);

            let cachedTpl = null;
            const fetchTemplate = async () => {
                if (cachedTpl) return cachedTpl;
                return new Promise((ok, no) => {
                    _gmReq({
                        method: 'GET', url: 'https://www.luogu.com.cn/record/290510067', timeout: 15000,
                        onload: (r) => {
                            if (r.status === 200) { cachedTpl = r.responseText; ok(cachedTpl); }
                            else no(new Error('模板获取失败'));
                        },
                        onerror: () => no(new Error('模板网络错误')),
                        ontimeout: () => no(new Error('模板请求超时'))
                    });
                });
            };

            async function findCF() {
                let url = `https://codeforces.com/api/contest.status?contestId=${encodeURIComponent(cid)}&from=1&count=100`;
                if (handle) url += `&handle=${encodeURIComponent(handle)}`;
                const d = await gmJson(url);
                if (d.status !== 'OK') throw new Error('CF ' + d.status);
                return (d.result || []).find((x) => String(x.id) === sid) || null;
            }

            function parseATStatus(text) {
                if (!text) return 'TESTING';
                text = text.trim();
                if (text === 'AC') return 'OK';
                if (text === 'WA') return 'WRONG_ANSWER';
                if (text === 'TLE' || text.includes('TLE')) return 'TIME_LIMIT_EXCEEDED';
                if (text === 'MLE') return 'MEMORY_LIMIT_EXCEEDED';
                if (text === 'OLE') return 'OUTPUT_LIMIT_EXCEEDED';
                if (text === 'RE') return 'RUNTIME_ERROR';
                if (text === 'CE') return 'COMPILATION_ERROR';
                if (text === 'WJ') return 'WAITING';
                if (text.includes('WA')) return 'WRONG_ANSWER';
                return 'TESTING';
            }

            async function findAT() {
                const url = `https://atcoder.jp/contests/${cid}/submissions/${sid}`;
                const html = await gmText(url);
                const doc = new DOMParser().parseFromString(html, 'text/html');

                const metaTable = doc.querySelector('table.table-bordered');
                const metaRows = metaTable ? metaTable.querySelectorAll('tr') : [];
                const meta = {};
                metaRows.forEach((row) => {
                    const th = row.querySelector('th');
                    const td = row.querySelector('td');
                    if (th && td) meta[th.textContent.trim()] = td.textContent.trim();
                });

                const codeEl = doc.querySelector('#submission-code');
                const sourceCode = codeEl ? codeEl.textContent : '';

                const tables = doc.querySelectorAll('table.table-bordered');
                const cases = [];
                let passedCount = 0;

                let caseTable = null;
                for (const t of tables) {
                    const header = t.querySelector('thead th, tr th');
                    if (header && (header.textContent.includes('Case Name') || header.textContent.includes('Status'))) {
                        caseTable = t;
                        break;
                    }
                }

                if (caseTable) {
                    caseTable.querySelectorAll('tbody tr').forEach((row, index) => {
                        const tds = row.querySelectorAll('td');
                        if (tds.length >= 4) {
                            const statusText = tds[1].textContent.trim();
                            const timeMatch = tds[2].textContent.trim().match(/(\d+)/);
                            const memMatch = tds[3].textContent.trim().match(/(\d+)/);
                            const verdict = parseATStatus(statusText);
                            if (verdict === 'OK') passedCount++;
                            cases.push({
                                id: `${index + 1}`,
                                status: verdict,
                                time: timeMatch ? parseInt(timeMatch[1]) : null,
                                memKB: memMatch ? parseInt(memMatch[1]) : null
                            });
                        }
                    });
                }

                let overallVerdict = parseATStatus(meta['Status'] || '');
                if (overallVerdict === 'OK' && passedCount < cases.length && cases.length > 0) {
                    overallVerdict = 'TESTING';
                }

                const timeMatch = (meta['Exec Time'] || '').match(/(\d+)/);
                const memMatch = (meta['Memory'] || '').match(/(\d+)/);

                const taskText = meta['Task'] || '';
                let taskIndex = 'a';
                const taskLink = metaTable ? metaTable.querySelector('a[href*="/tasks/"]') : null;
                if (taskLink) {
                    const linkMatch = (taskLink.getAttribute('href') || '').match(/\/tasks\/[^_]+_(.+)$/i);
                    if (linkMatch) taskIndex = linkMatch[1].toLowerCase();
                } else {
                    const textMatch = taskText.match(/^([A-Za-z0-9]+)/);
                    if (textMatch) taskIndex = textMatch[1].toLowerCase();
                }

                let submitTime = 0;
                const timeStr = meta['Submission Time'] || '';
                if (timeStr) {
                    const tm = timeStr.match(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})([+-]\d{2})(\d{2})$/);
                    submitTime = tm
                        ? Math.floor(new Date(`${tm[1]}T${tm[2]}${tm[3]}:${tm[4]}`).getTime() / 1000)
                        : (Math.floor(new Date(timeStr).getTime() / 1000) || 0);
                }

                return {
                    isAT: true, verdict: overallVerdict, passedTestCount: passedCount,
                    timeConsumedMillis: timeMatch ? parseInt(timeMatch[1]) : 0,
                    memoryConsumedBytes: memMatch ? parseInt(memMatch[1]) * 1024 : 0,
                    problem: { name: taskText, index: taskIndex }, sourceCode, cases,
                    creationTimeSeconds: submitTime
                };
            }

            function buildCases(sub, time, memKB) {
                if (sub.isAT) {
                    return sub.cases.map((c, index) => ({
                        id: index,
                        status: CF2LG[c.status] ?? 0,
                        time: c.time ?? 0,
                        memory: c.memKB ?? 0,
                        score: 1,
                        signal: 0,
                        exitCode: 0,
                        description: '',
                        subtaskID: 0
                    }));
                }
                const lgCode = CF2LG[sub.verdict] ?? 0;
                const isAC = sub.verdict === 'OK';
                const isCE = sub.verdict === 'COMPILATION_ERROR';
                const passed = sub.passedTestCount ?? 0;
                if (isCE) return [];

                const idNum = isAC ? (passed > 0 ? passed - 1 : 0) : passed;
                let status = isAC ? 12 : lgCode;
                if (sub.verdict === 'TESTING') status = 1;

                return [{
                    id: idNum, status,
                    time: time ?? 0, memory: memKB ?? 0,
                    score: 100, signal: 0, exitCode: 0,
                    description: '', subtaskID: 0
                }];
            }

            function buildHtml(tpl, sub) {
                const FE_RE = /<script\s+id="lentille-context"\s+type="application\/json">([\s\S]*?)<\/script>/i;
                const fm = tpl.match(FE_RE);
                if (!fm) return tpl;

                let data;
                try { data = JSON.parse(fm[1]); } catch (e) { return tpl; }

                const rec = data?.data?.record;
                if (!rec) return tpl;
                const cu = data?.data?.user || data?.user;

                if (rec.user && cu) {
                    Object.assign(rec.user, {
                        uid: cu.uid, name: cu.name, avatar: cu.avatar,
                        color: cu.color || '', slogan: cu.slogan || ''
                    });
                }

                if (isATPage && sub && sub.sourceCode) {
                    rec.sourceCode = sub.sourceCode;
                    rec.sourceCodeLength = sub.sourceCode.length;
                } else if (code) {
                    rec.sourceCode = code;
                    rec.sourceCodeLength = code.length;
                } else {
                    rec.sourceCode = '// 未找到该提交的源代码\n// 请前往原站查看';
                    rec.sourceCodeLength = 0;
                }

                if ((isCFPage || isATPage) && sub) {
                    const lgCode = CF2LG[sub.verdict] ?? 0;
                    const isFinal = FINAL_CF.has(sub.verdict);
                    const time = isFinal ? (sub.timeConsumedMillis ?? 0) : 0;
                    const memKB = isFinal ? Math.round((sub.memoryConsumedBytes ?? 0) / 1024) : 0;

                    if (rec.problem && sub.problem) {
                        if (isCFPage) {
                            rec.problem.pid = `CF${cid}${sub.problem.index}`;
                            rec.problem.type = 'CF';
                        } else if (isATPage) {
                            rec.problem.pid = `AT_${cid}_${sub.problem.index}`;
                            rec.problem.type = 'AT';
                        }
                        rec.problem.name = sub.problem.name;
                        delete rec.problem.title;
                    }

                    rec.status = lgCode;
                    rec.time = time;
                    rec.memory = memKB;
                    rec.id = Number(sid) || rec.id;
                    if (sub.creationTimeSeconds) rec.submitTime = sub.creationTimeSeconds;
                    if (rec.detail?.compileResult) {
                        rec.detail.compileResult.success = sub.verdict !== 'COMPILATION_ERROR';
                    }

                    const cases = buildCases(sub, time, memKB);

                    if (rec.detail?.judgeResult) {
                        rec.detail.judgeResult.subtasks = [{
                            id: 0, score: null, status: lgCode,
                            testCases: cases, judger: '',
                            time, memory: memKB
                        }];
                        rec.detail.judgeResult.finishedCaseCount = cases.length;
                        rec.detail.judgeResult.status = lgCode;
                        rec.detail.judgeResult.time = time;
                        rec.detail.judgeResult.memory = memKB;
                        rec.detail.judgeResult.score = null;
                    }
                }

                const newJsonStr = JSON.stringify(data).replace(/</g, '\\u003c').replace(/\//g, '\\/');
                return tpl.replace(FE_RE, `<script id="lentille-context" type="application/json">${newJsonStr}</script>`);
            }

            async function renderPage(sub) {
                if (myGen !== generation) return;
                const tpl = await fetchTemplate().catch(() => null);
                if (!tpl || myGen !== generation) return;

                const doc = new DOMParser().parseFromString(buildHtml(tpl, sub), 'text/html');
                document.replaceChild(doc.documentElement, document.documentElement);

                document.querySelectorAll('script').forEach((oldScript) => {
                    const newScript = document.createElement('script');
                    Array.from(oldScript.attributes).forEach((attr) => newScript.setAttribute(attr.name, attr.value));
                    newScript.textContent = oldScript.textContent;
                    oldScript.parentNode.replaceChild(newScript, oldScript);
                });
            }

            (async () => {
                const updateCache = (sub) => {
                    if (!sub || myGen !== generation) return;
                    if (isCFPage) {
                        let cache = [];
                        try { cache = JSON.parse(GM_getValue(CACHE_CF, '[]')); if (!Array.isArray(cache)) cache = []; }
                        catch { cache = []; }

                        const item = {
                            id: String(sid),
                            taskDisplay: `CF${cid}${sub.problem.index} - ${sub.problem.name}`,
                            status: sub.verdict || 'Waiting',
                            timestamp: (sub.creationTimeSeconds || 0) * 1000,
                            submitUrl: `https://www.luogu.com.cn/record/cf/${cid}/${sid}`,
                            luoguUrl: `https://www.luogu.com.cn/problem/CF${cid}${sub.problem.index}`,
                            passedTestCount: sub.passedTestCount
                        };

                        const idx = cache.findIndex((c) => c.id === String(sid));
                        if (idx !== -1) cache[idx] = { ...cache[idx], ...item };
                        else cache.unshift(item);
                        cache.sort((a, b) => Number(b.id) - Number(a.id));
                        GM_setValue(CACHE_CF, JSON.stringify(cache));
                        GM_setValue(LAST_UPDATE_CF, Date.now());
                    } else if (isATPage) {
                        let cache = [];
                        try { cache = JSON.parse(GM_getValue(CACHE_AT, '[]')); if (!Array.isArray(cache)) cache = []; }
                        catch { cache = []; }

                        const AT_VERDICT_MAP = {
                            OK: 'AC', WRONG_ANSWER: 'WA', TIME_LIMIT_EXCEEDED: 'TLE',
                            MEMORY_LIMIT_EXCEEDED: 'MLE', OUTPUT_LIMIT_EXCEEDED: 'OLE',
                            RUNTIME_ERROR: 'RE', COMPILATION_ERROR: 'CE', WAITING: 'WJ', TESTING: 'WJ'
                        };
                        const atStatus = AT_VERDICT_MAP[sub.verdict] || 'WJ';

                        const taskKey = `${cid}_${sub.problem.index}`;
                        const item = {
                            id: String(sid), taskKey,
                            taskDisplay: `${taskKey} - ${sub.problem.index.toUpperCase()} - ${sub.problem.name}`,
                            status: atStatus,
                            submitUrl: `https://atcoder.jp/contests/${cid}/submissions/${sid}`,
                            luoguUrl: `https://www.luogu.com.cn/problem/AT_${taskKey}`,
                            timestamp: (sub.creationTimeSeconds || 0) * 1000,
                            isFinal: FINAL_AT.has(atStatus)
                        };

                        const idx = cache.findIndex((c) => c.id === String(sid));
                        if (idx !== -1) cache[idx] = { ...cache[idx], ...item };
                        else cache.unshift(item);
                        cache.sort((a, b) => Number(b.id) - Number(a.id));
                        GM_setValue(CACHE_AT, JSON.stringify(cache));
                        GM_setValue(LAST_UPDATE_AT, Date.now());
                    }
                };

                const cfDomainPath = Number(cid) > 100000 ? 'gym' : 'contest';
                const origUrl = isCFPage
                    ? `https://codeforces.com/${cfDomainPath}/${cid}/submission/${sid}`
                    : `https://atcoder.jp/contests/${cid}/submissions/${sid}`;

                let sub = null;
                try {
                    sub = isCFPage ? await findCF() : (isATPage ? await findAT() : null);
                } catch (e) {
                    if (myGen !== generation) return;
                    if (isATPage) { timers.clear(titleTimer); location.replace(origUrl); return; }
                }

                if (myGen !== generation) return;
                if (isCFPage && sub === null) {
                    timers.clear(titleTimer);
                    location.replace(origUrl);
                    return;
                }

                if (sub) updateCache(sub);

                timers.clear(titleTimer);

                // 已拿到结果直接渲染一次
                await renderPage(sub);

                if (myGen !== generation) return;

                let currentSub = sub;
                let atWaitPollingId = null;

                timers.iv(() => {
                    if (myGen !== generation) return;
                    const m2 = document.getElementById('rmj-det-overlay');
                    if (m2 && (document.querySelector('#app') || document.querySelector('.lfe-body'))) m2.remove();

                    const hasCode = (isATPage && currentSub && currentSub.sourceCode) || code;
                    if (!hasCode) {
                        const vals = document.querySelectorAll('.value.lfe-caption');
                        if (vals.length >= 2 && vals[1].textContent !== '-') vals[1].textContent = '-';
                        const ce = document.querySelector('pre code');
                        if (ce) {
                            const pre = ce.closest('pre');
                            if (pre) pre.outerHTML = `<div class="card padding-default" style="text-align:center;color:#e74c3c;padding:40px;display:flex;flex-direction:column;align-items:center;justify-content:center;"><div>本代码非 GenGen RMJ 提交,无法查看</div><a href="${origUrl}" target="_blank" style="margin-top:8px;color:#3498db;text-decoration:none;">前往原站</a></div>`;
                        }
                    }

                    const card = document.querySelectorAll('.l-card')[1];
                    if (card && !card.querySelector('.rmj-orig-link')) {
                        const a = document.createElement('a');
                        a.href = origUrl;
                        a.target = '_blank';
                        a.className = 'rmj-orig-link';
                        a.textContent = '前往原站';
                        a.style.cssText = 'display:block;text-align:center;margin-top:16px;color:#3498db;text-decoration:none;';
                        card.appendChild(a);
                    }

                    if (currentSub && currentSub.verdict !== 'COMPILATION_ERROR') {
                        const tcs = document.querySelectorAll('.test-case');
                        if (currentSub.isAT) {
                            tcs.forEach((tc, idx) => {
                                const idEl = tc.querySelector('.id');
                                const target = `#${idx + 1}`;
                                if (idEl && idEl.textContent !== target) idEl.textContent = target;
                            });
                        } else {
                            const passed = currentSub.passedTestCount ?? 0;
                            const idNum = currentSub.verdict === 'OK' ? (passed > 0 ? passed : 1) : passed + 1;
                            const target = `#${idNum}`;
                            tcs.forEach((tc) => {
                                const idEl = tc.querySelector('.id');
                                if (idEl && idEl.textContent !== target) idEl.textContent = target;
                            });
                        }
                    }

                    // AT 未返回完整测试点时的等待提示
                    if (atWaitPollingId !== null) {
                        const h5 = document.querySelector(
                            '#app > div.main-container.lside-nav > div > main > div > div > div.main > div > section > div > h5'
                        );
                        if (h5 && h5.textContent !== '正在等待 AtCoder 评测完成') {
                            h5.textContent = '正在等待 AtCoder 评测完成';
                        }
                        const testWrap = document.querySelector('.test-case-wrap');
                        if (testWrap && !document.getElementById('rmj-at-wait-msg')) {
                            const waitMsg = document.createElement('div');
                            waitMsg.id = 'rmj-at-wait-msg';
                            waitMsg.textContent = '正在等待 AtCoder 完整评测完毕';
                            waitMsg.style.cssText = 'text-align:center;padding:12px;color:#666;font-size:14px;';
                            testWrap.appendChild(waitMsg);
                        }
                    }
                }, 500);

                if ((!isCFPage && !isATPage) || !sub) return;

                const startAtWaitPolling = () => {
                    if (atWaitPollingId !== null || !isATPage) return;
                    atWaitPollingId = timers.iv(async () => {
                        if (myGen !== generation) return;
                        try {
                            const s = await findAT();
                            if (myGen !== generation) return;
                            if (s && s.cases.length > 0) {
                                timers.clear(atWaitPollingId);
                                atWaitPollingId = null;
                                const msg = document.getElementById('rmj-at-wait-msg');
                                if (msg) msg.remove();
                                currentSub = s;
                                await renderPage(s);
                                updateCache(s);
                            }
                        } catch (e) { /* ignore */ }
                    }, 5000);
                };

                if (isATPage && sub.cases.length === 0 && sub.verdict !== 'COMPILATION_ERROR' && FINAL_CF.has(sub.verdict)) {
                    startAtWaitPolling();
                }

                if (!FINAL_CF.has(sub.verdict)) {
                    let polling = false;
                    const intervalId = timers.iv(async () => {
                        if (myGen !== generation) return;
                        if (polling) return;
                        polling = true;
                        try {
                            const s = isCFPage ? await findCF() : await findAT();
                            if (myGen !== generation) return;
                            if (s) {
                                currentSub = s;
                                updateCache(s);

                                if (FINAL_CF.has(s.verdict) && s.isAT && s.cases.length === 0 && s.verdict !== 'COMPILATION_ERROR') {
                                    startAtWaitPolling();
                                }

                                if (FINAL_CF.has(s.verdict)) {
                                    timers.clear(intervalId);
                                    await renderPage(s);
                                }
                            }
                        } catch (e) { /* ignore */ }
                        finally { polling = false; }
                    }, 3000);
                }
            })();
        };

        return { init, destroy };
    })();

    // 洛谷记录列表页
    const RecordList = (() => {
        let syncStarted = false;
        let pageKey = '';
        let pageGen = 0;
        const timers = Timers();

        const req = (url, opts = {}) => new Promise((res, rej) => {
            const t = setTimeout(() => rej(new Error('请求超时')), 8000);
            GM_xmlhttpRequest({
                method: 'GET', url, ...opts,
                onload: (r) => { clearTimeout(t); res(r); },
                onerror: (e) => { clearTimeout(t); rej(e); }
            });
        });

        const getCache = (key) => {
            try {
                const p = JSON.parse(GM_getValue(key, '[]'));
                if (!Array.isArray(p)) return [];
                return p.map((s) => {
                    if (s.submitUrl) {
                        let m = s.submitUrl.match(/atcoder\.jp\/contests\/([^/]+)\/submissions\/(\d+)/);
                        if (m) s.submitUrl = `https://www.luogu.com.cn/record/at/${m[1]}/${m[2]}`;
                        else {
                            m = s.submitUrl.match(/codeforces\.com\/(?:contest|gym)\/(\d+)\/submission\/(\d+)/);
                            if (m) s.submitUrl = `https://www.luogu.com.cn/record/cf/${m[1]}/${m[2]}`;
                        }
                    }
                    if (s.luoguUrl) {
                        let m = s.luoguUrl.match(/atcoder\.jp\/contests\/[^/]+\/tasks\/([^/\s?#]+)/);
                        if (m) s.luoguUrl = `https://www.luogu.com.cn/problem/AT_${m[1]}`;
                        else {
                            m = s.luoguUrl.match(/codeforces\.com\/(?:problemset\/problem|(?:contest|gym)\/\d+\/problem)\/(\d+)\/([A-Za-z]\d?)/);
                            if (m) s.luoguUrl = `https://www.luogu.com.cn/problem/CF${m[1]}${m[2]}`;
                        }
                    }
                    return s;
                });
            } catch { return []; }
        };
        const saveCache = (key, c) => GM_setValue(key, JSON.stringify(Array.isArray(c) ? c : []));
        const markUpdated = (key) => GM_setValue(key, Date.now());

        const crawlATContest = async (contestId, existingCache = []) => {
            if (!contestId) return existingCache;
            try {
                const r = await req(`https://atcoder.jp/contests/${contestId}/submissions/me`);
                if (r.status !== 200) return existingCache;

                const doc = new DOMParser().parseFromString(r.responseText, 'text/html');
                const rows = Array.from(doc.querySelectorAll('table.table tbody tr'));
                if (!rows.length) return existingCache;

                const cacheMap = new Map(existingCache.map((s) => [s.id, s]));
                let hasNew = false;

                for (const row of rows) {
                    const cells = Array.from(row.querySelectorAll('td'));
                    if (cells.length < 7) continue;

                    const tl = cells[1]?.querySelector('a');
                    const tHref = tl?.href || '';
                    const tName = tl?.innerText?.trim() || '';
                    const tKey = tHref.match(/\/tasks\/([^/\s]+)/)?.[1] || '';

                    let rs = 'Waiting';
                    for (const c of cells) {
                        const l = c.querySelector('.label');
                        if (l) { rs = l.innerText.trim(); break; }
                    }

                    const da = cells[cells.length - 1]?.querySelector('a.submission-details-link');
                    if (!da?.href) continue;

                    const sid = da.href.split('/').pop();
                    const isF = FINAL_AT.has(rs);
                    const prev = cacheMap.get(sid);

                    if (!prev || prev.status !== rs) {
                        cacheMap.set(sid, {
                            id: sid, taskKey: tKey,
                            taskDisplay: `${tKey} - ${tName}`,
                            status: rs,
                            submitUrl: `https://www.luogu.com.cn/record/at/${contestId}/${sid}`,
                            luoguUrl: `https://www.luogu.com.cn/problem/AT_${tKey}`,
                            timestamp: prev?.timestamp || Date.now(),
                            isFinal: isF
                        });
                        hasNew = true;
                    } else if (isF && !prev.isFinal) {
                        prev.isFinal = true;
                        prev.status = rs;
                        hasNew = true;
                    }
                }

                if (hasNew) {
                    return Array.from(cacheMap.values()).sort((a, b) => Number(b.id) - Number(a.id));
                }
                return existingCache;
            } catch (e) {
                LOG('AT 爬取失败', e.message || e);
                return existingCache;
            }
        };

        const fetchCFData = async (handle) => {
            const sr = await req(`https://codeforces.com/api/user.status?handle=${encodeURIComponent(handle)}&from=1`);
            if (sr.status !== 200) throw new Error('CF API 状态码非 200');
            const d = JSON.parse(sr.responseText);
            if (d.status !== 'OK') throw new Error('CF API 状态非 OK');
            const seen = new Set();
            return (d.result || []).filter((s) => {
                if (seen.has(s.id)) return false;
                seen.add(s.id);
                return true;
            }).map((s) => ({
                id: String(s.id),
                taskDisplay: `CF${s.contestId}${s.problem.index} - ${s.problem.name}`,
                status: s.verdict || 'Waiting',
                timestamp: s.creationTimeSeconds * 1000,
                submitUrl: `https://www.luogu.com.cn/record/cf/${s.contestId}/${s.id}`,
                luoguUrl: `https://www.luogu.com.cn/problem/CF${s.contestId}${s.problem.index}`,
                passedTestCount: s.passedTestCount
            }));
        };

        const fetchATProblems = async () => {
            try {
                const r = await req('https://kenkoooo.com/atcoder/resources/problems.json');
                if (r.status !== 200) return new Map();
                const m = new Map();
                for (const p of JSON.parse(r.responseText)) {
                    if (p.id) m.set(p.id, { index: p.problem_index || '', name: p.name || '' });
                }
                return m;
            } catch { return new Map(); }
        };

        const fmtATTask = (pid, pMap) => {
            const p = pMap.get(pid);
            if (p?.name && p.index) return `${pid} - ${p.index} - ${p.name}`;
            const parts = pid.split('_');
            const c = parts[0] || '';
            const i = parts[1] ? parts[1].toUpperCase() : '';
            return `${pid} - ${i ? `${c.toUpperCase()} ${i}` : pid}`;
        };

        const fetchATSubmissions = async (pMap, uid) => {
            try {
                if (!uid) return [];
                const sr = await req(`https://kenkoooo.com/atcoder/atcoder-api/v3/user/submissions?user=${encodeURIComponent(uid)}&from_second=0`);
                if (sr.status !== 200) return [];
                const subs = JSON.parse(sr.responseText);
                if (!Array.isArray(subs)) return [];
                return subs.map((s) => ({
                    id: String(s.id),
                    taskKey: s.problem_id,
                    taskDisplay: fmtATTask(s.problem_id, pMap),
                    status: s.result,
                    submitUrl: `https://www.luogu.com.cn/record/at/${s.contest_id}/${s.id}`,
                    luoguUrl: `https://www.luogu.com.cn/problem/AT_${s.problem_id}`,
                    timestamp: s.epoch_second * 1000,
                    isFinal: FINAL_AT.has(s.result)
                }));
            } catch (e) {
                LOG('Kenkoooo 拉取失败', e);
                return [];
            }
        };

        const fetchATData = async (uid) => {
            const pMap = await fetchATProblems();
            const subs = await fetchATSubmissions(pMap, uid);
            return subs.map((s) => ({ ...s, taskDisplay: fmtATTask(s.taskKey, pMap) }));
        };

        let isCFSyncing = false;
        let isATSyncing = false;

        const syncCF = async (options = {}) => {
            if (isCFSyncing) return;
            isCFSyncing = true;
            try {
                const { render = false, renderFn = null, mainDiv = null, force = false } = options;
                const cache = getCache(CACHE_CF);
                const lastUpdate = GM_getValue(LAST_UPDATE_CF, 0);
                const isStale = (Date.now() - lastUpdate) > SYNC_INTERVAL_MS;

                if (!force && cache.length > 0 && !isStale) {
                    if (render && renderFn && mainDiv) renderFn(cache, mainDiv);
                    return;
                }

                const handle = GM_getValue('cf-handle', '');
                if (!handle) {
                    LOG('未找到 CF 用户名');
                    return;
                }

                const subs = await fetchCFData(handle);
                saveCache(CACHE_CF, subs);
                markUpdated(LAST_UPDATE_CF);
                if (render && renderFn && mainDiv) renderFn(subs, mainDiv);
            } catch (e) {
                LOG('CF 同步失败', e.message || e);
            } finally {
                isCFSyncing = false;
            }
        };

        const syncAT = async (options = {}) => {
            if (isATSyncing) return;
            isATSyncing = true;
            try {
                const { render = false, renderFn = null, mainDiv = null, force = false } = options;
                const cache = getCache(CACHE_AT);
                const lastUpdate = GM_getValue(LAST_UPDATE_AT, 0);
                const isStale = (Date.now() - lastUpdate) > SYNC_INTERVAL_MS;

                if (!force && cache.length > 0 && !isStale) {
                    if (render && renderFn && mainDiv) renderFn(cache, mainDiv);
                    return;
                }

                const atHandle = GM_getValue('at-handle', '');
                if (!atHandle) {
                    LOG('未找到 AT 用户名');
                    return;
                }

                const subs = await fetchATData(atHandle);
                const mm = new Map();
                for (const s of [...subs, ...cache]) {
                    if (!mm.has(s.id)) mm.set(s.id, s);
                }
                const merged = Array.from(mm.values()).sort((a, b) => Number(b.id) - Number(a.id));

                saveCache(CACHE_AT, merged);
                markUpdated(LAST_UPDATE_AT);
                if (render && renderFn && mainDiv) renderFn(merged, mainDiv);
            } catch (e) {
                LOG('AT 同步失败', e.message || e);
            } finally {
                isATSyncing = false;
            }
        };

        const startBackgroundSync = () => {
            if (syncStarted) return;
            syncStarted = true;

            let disableSync = GM_getValue('rmj-disable-sync', false) === true;
            try {
                const params = new URLSearchParams(location.search);
                if (params.get('rmj-disable-sync') === 'true') disableSync = true;
            } catch { /* ignore */ }

            if (!disableSync) {
                syncCF({ render: false });
                syncAT({ render: false });
            } else {
                LOG('同步已禁用,仅显示模式');
            }
        };

        const destroy = () => {
            pageGen++;
            timers.clearAll();
            pageKey = '';
        };

        const init = async () => {
            if (!isLuogu()) return;

            startBackgroundSync();

            const URL_PATH = location.pathname;
            if (!/^\/record\/list/.test(URL_PATH)) {
                if (pageKey) destroy();
                return;
            }

            const params = new URLSearchParams(window.location.search);
            const rmj = params.get('rmj');
            if (!['1', '2'].includes(rmj)) {
                if (pageKey) destroy();
                return;
            }

            const key = `${URL_PATH}?rmj=${rmj}`;
            if (pageKey === key) return;

            destroy();
            pageKey = key;
            const myGen = pageGen;

            const pid = params.get('pid') || '';
            const contest = params.get('contest') || '';

            const isCFMode = rmj === '1';
            const isATMode = rmj === '2';

            const disableSync = GM_getValue('rmj-disable-sync', false) === true ||
                params.get('rmj-disable-sync') === 'true';

            const STATUS_MAP = isCFMode ? {
                OK: ['Accepted', 'cf-status-accepted'], WRONG_ANSWER: ['Wrong Answer', 'cf-status-wrong'],
                COMPILATION_ERROR: ['Compilation Error', 'cf-status-ce'], RUNTIME_ERROR: ['Runtime Error', 'cf-status-re'],
                TIME_LIMIT_EXCEEDED: ['Time Limit Exceeded', 'cf-status-limit'], MEMORY_LIMIT_EXCEEDED: ['Memory Limit Exceeded', 'cf-status-limit'],
                OUTPUT_LIMIT_EXCEEDED: ['Output Limit Exceeded', 'cf-status-limit'], TESTING: ['Running', 'cf-status-running']
            } : {
                AC: ['Accepted', 'cf-status-accepted'], WA: ['Wrong Answer', 'cf-status-wrong'],
                CE: ['Compilation Error', 'cf-status-ce'], RE: ['Runtime Error', 'cf-status-re'],
                TLE: ['Time Limit Exceeded', 'cf-status-limit'], MLE: ['Memory Limit Exceeded', 'cf-status-limit'],
                OLE: ['Output Limit Exceeded', 'cf-status-limit'], IE: ['Internal Error', 'cf-status-ce']
            };

            const style = document.createElement('style');
            style.textContent = `
                .cf-card{display:flex;align-items:center;font-size:16px;padding:10px 0;border-bottom:1px solid #eee}
                .cf-avatar img{width:35px;height:35px;border-radius:50%;margin-right:12px}
                .cf-nameblock{display:flex;flex-direction:column;width:180px;margin-right:12px}
                .cf-name{font-weight:bold;color:#333;font-size:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
                .cf-time{font-size:14px;color:#888;line-height:1.2;margin-top:2px;white-space:nowrap}
                .cf-status{flex:0 0 auto;margin-right:12px;text-align:left;width:200px}
                .cf-status span{border-radius:2px;padding:2px 3px;font-size:14px;font-weight:600;white-space:nowrap;display:inline-flex;align-items:center;position:relative;max-width:100%;overflow:hidden;text-overflow:ellipsis;box-sizing:border-box}
                .cf-status-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
                .cf-status-subtext{position:absolute;top:-2px;right:2px;font-size:10px!important;color:rgba(255,255,255,.8);font-weight:bold;line-height:1;pointer-events:none}
                .cf-status-accepted{background:rgb(82,196,26);color:#fff}
                .cf-status-wrong{background:rgb(231,76,60);color:#fff}
                .cf-status-re{background:rgb(157,61,207);color:#fff}
                .cf-status-ce{background:rgb(250,219,20);color:#fff}
                .cf-status-limit{background:rgb(5,34,66);color:#fff}
                .cf-status-running{background:#888;color:#fff}
                .cf-status-other{background:rgb(243,156,17);color:#fff}
                .cf-problem{flex:1;color:rgb(52,152,219);font-size:16px;text-align:left;min-width:100px;margin-left:60px}
                .cf-error{padding:10px;color:#e74c3c;font-weight:bold}
                .cf-loading{padding:10px;color:#708090;font-weight:bold}
            `;
            document.head.appendChild(style);

            const getUser = () => {
                const ne = document.querySelector("#app > div.user-nav.rside.hide.nav-scrollbar > div.title > div > span")
                    || document.querySelector("#app > div.user-nav.rside.show.nav-scrollbar > div.title > div > span");
                const ae = document.querySelector("#app > div.top-bar > div.right > div > span.avatar > a > img");
                return {
                    name: (ne?.textContent || 'User').trim(),
                    color: ne?.style?.color || '#333',
                    avatar: (ae?.src || 'https://cdn.luogu.com.cn/upload/usericon/default.png').trim()
                };
            };

            const fmtVerdict = (v) => STATUS_MAP[v] || [
                v.split('_').map((w) => w[0] + w.slice(1).toLowerCase()).join(' '),
                'cf-status-other'
            ];

            const createCard = (sub) => {
                const card = document.createElement('div');
                card.className = 'cf-card';
                if (sub.id) card.dataset.id = sub.id;
                const u = getUser();

                const av = document.createElement('div');
                av.className = 'cf-avatar';
                const img = document.createElement('img');
                img.src = u.avatar;
                img.onerror = () => img.src = 'https://cdn.luogu.com.cn/upload/usericon/1.png';
                av.appendChild(img);

                const nb = document.createElement('div');
                nb.className = 'cf-nameblock';
                const nd = document.createElement('div');
                nd.className = 'cf-name';
                nd.style.color = u.color;
                nd.textContent = u.name;
                const td = document.createElement('div');
                td.className = 'cf-time';
                td.textContent = sub.timeText;
                nb.append(nd, td);

                const sd = document.createElement('div');
                sd.className = 'cf-status';
                const sl = document.createElement('a');
                sl.href = sub.submitUrl;
                sl.target = '_blank';
                sl.rel = 'noopener noreferrer';
                const sp = document.createElement('span');
                const [full, cls] = (isCFMode || sub.isFinal) ? fmtVerdict(sub.status) : ['Running', 'cf-status-running'];
                sp.className = cls;
                const ts = document.createElement('span');
                ts.className = 'cf-status-text';
                ts.textContent = full;
                sp.appendChild(ts);
                if (isCFMode && sub.passedTestCount != null && !isNaN(sub.passedTestCount)) {
                    const st = document.createElement('span');
                    st.className = 'cf-status-subtext';
                    st.textContent = String((full === 'AC' || full === 'Accepted')
                        ? sub.passedTestCount
                        : sub.passedTestCount + 1);
                    sp.appendChild(st);
                }
                sl.appendChild(sp);
                sd.appendChild(sl);

                const pd = document.createElement('div');
                pd.className = 'cf-problem';
                const pl = document.createElement('a');
                pl.href = sub.luoguUrl;
                pl.textContent = sub.taskDisplay;
                pl.target = '_blank';
                pl.rel = 'noopener noreferrer';
                pd.appendChild(pl);

                card.append(av, nb, sd, pd);
                return card;
            };

            const CACHE_KEY = isCFMode ? CACHE_CF : CACHE_AT;
            const getLocalCache = () => getCache(CACHE_KEY);
            const saveLocalCache = (c) => saveCache(CACHE_KEY, c);

            const updCount = (n) => {
                const s = document.querySelector('.number');
                if (s) s.textContent = String(n || 0);
            };

            let searchFilter = pid;

            const render = (cache, mainDiv) => {
                if (myGen !== pageGen) return;
                let filtered = cache;
                if (searchFilter) {
                    const q = isCFMode
                        ? searchFilter.toLowerCase()
                        : searchFilter.replace(/^AT_/i, '').toLowerCase();
                    filtered = cache.filter((s) => s.taskDisplay?.toLowerCase().includes(q));
                }
                mainDiv.innerHTML = '';
                updCount(filtered.length);
                if (!filtered.length) {
                    const msg = document.createElement('div');
                    msg.className = 'cf-loading';
                    msg.textContent = '';
                    mainDiv.appendChild(msg);
                } else {
                    filtered.forEach((s) => {
                        mainDiv.appendChild(createCard({
                            ...s,
                            timeText: new Date(s.timestamp || 0).toLocaleString('zh-CN')
                        }));
                    });
                }
            };

            const bindSearch = async (mainDiv) => {
                try {
                    const input = await waitForEl(
                        '#app > div.main-container.lside-nav > div > main > div > div:nth-child(1) > section:nth-child(1) > div > input:nth-child(1)',
                        8000
                    );
                    if (myGen !== pageGen) return;
                    input.value = searchFilter;
                    const orig = input.oninput;
                    input.oninput = (e) => {
                        searchFilter = e.target.value.trim();
                        const url = new URL(window.location);
                        if (searchFilter) url.searchParams.set('pid', searchFilter);
                        else url.searchParams.delete('pid');
                        history.replaceState(null, '', url);
                        render(getLocalCache(), mainDiv);
                        orig?.call(input, e);
                    };
                } catch { LOG('未找到搜索框'); }
            };

            let mainDiv;
            try {
                mainDiv = await waitForEl(
                    '#app > div.main-container.lside-nav > div > main > div > div:nth-child(2)',
                    10000
                );
            } catch (e) {
                LOG('记录列表容器未找到', e);
                return;
            }
            if (myGen !== pageGen) return;

            render(getLocalCache(), mainDiv);
            await bindSearch(mainDiv);
            if (myGen !== pageGen) return;

            if (isCFMode) {
                if (!disableSync) {
                    let isFetching = false;
                    const updateNow = async () => {
                        if (myGen !== pageGen) return;
                        if (isFetching) return;
                        isFetching = true;
                        try {
                            const handle = GM_getValue('cf-handle', '');
                            if (!handle) return;
                            const sr = await req(`https://codeforces.com/api/user.status?handle=${encodeURIComponent(handle)}&from=1`);
                            if (myGen !== pageGen) return;
                            if (sr.status !== 200) return;
                            const d = JSON.parse(sr.responseText);
                            if (d.status !== 'OK') return;
                            const seen = new Set();
                            const subs = (d.result || []).filter((s) => {
                                if (seen.has(s.id)) return false;
                                seen.add(s.id);
                                return true;
                            }).map((s) => ({
                                id: String(s.id),
                                taskDisplay: `CF${s.contestId}${s.problem.index} - ${s.problem.name}`,
                                status: s.verdict || 'Waiting',
                                timestamp: s.creationTimeSeconds * 1000,
                                submitUrl: `https://www.luogu.com.cn/record/cf/${s.contestId}/${s.id}`,
                                luoguUrl: `https://www.luogu.com.cn/problem/CF${s.contestId}${s.problem.index}`,
                                passedTestCount: s.passedTestCount
                            }));
                            if (myGen !== pageGen) return;
                            saveLocalCache(subs);
                            markUpdated(LAST_UPDATE_CF);
                            render(subs, mainDiv);
                        } catch (e) {
                            LOG('CF 列表更新失败', e.message || e);
                        } finally {
                            isFetching = false;
                        }
                    };
                    updateNow();
                    timers.iv(updateNow, 6000);
                }
            } else {
                let cache = getLocalCache();

                if (!disableSync) {
                    (async () => {
                        try {
                            const atHandle = GM_getValue('at-handle', '');
                            if (!atHandle) return;
                            const pMap = await fetchATProblems();
                            const kSubs = await fetchATSubmissions(pMap, atHandle);
                            if (myGen !== pageGen) return;
                            const enhanced = kSubs.map((s) => ({ ...s, taskDisplay: fmtATTask(s.taskKey, pMap) }));
                            const mm = new Map();
                            for (const s of [...enhanced, ...cache]) {
                                if (!mm.has(s.id)) mm.set(s.id, s);
                            }
                            cache = Array.from(mm.values()).sort((a, b) => Number(b.id) - Number(a.id));
                            saveLocalCache(cache);
                            markUpdated(LAST_UPDATE_AT);
                            render(cache, mainDiv);
                        } catch (e) {
                            LOG('AT 后台加载失败', e);
                        }
                    })();

                    if (contest) {
                        timers.iv(async () => {
                            if (myGen !== pageGen) return;
                            const prev = getLocalCache();
                            const updated = await crawlATContest(contest, prev);
                            if (myGen !== pageGen) return;
                            if (updated !== prev) {
                                cache = updated;
                                saveLocalCache(cache);
                                markUpdated(LAST_UPDATE_AT);
                                render(cache, mainDiv);
                            }
                        }, 6000);
                    }
                }
            }
        };

        return { init, destroy };
    })();

    // CF/AT 盾提交
    const ShieldSubmit = (() => {
        const VALID = [
            /^https:\/\/www\.luogu\.com\.cn\/problem\/(AT|CF).+/,
            /^https:\/\/codeforces\.com\/problemset\/status\?my=on$/,
            /^https:\/\/atcoder\.jp\/contests\/[^/]+\/submit\?RMJ=1$/,
            /^https:\/\/atcoder\.jp\/contests\/[^/]+\/submissions\/me$/,
            /^https:\/\/codeforces\.com\/problemset\/submit\/.+/,
        ];

        const KEYS = ['code', 'contest', 'task', 'back', 'platform', 'pid', 'cf_contest', 'cf_index',
            'body_back', 'bg_image', 'bg_b64', 'bg_color', 'bg_repeat', 'bg_size', 'bg_pos',
            'mid_mask', 'color_filter', 'card_bg', 'card_blur'];
        const P = 'gen-at-';
        const set = (k, v) => GM_setValue(P + k, String(v));
        const get = (k) => GM_getValue(P + k, '');
        const clr = () => KEYS.forEach((k) => GM_setValue(P + k, ''));
        const LIMIT = 4e6;
        const LOGO = 'https://cdn.luogu.com.cn/upload/image_hosting/yy27itbl.png';

        const setFlag = (k, v) => GM_setValue('rmj-flag-' + k, String(v));
        const getFlag = (k, def) => GM_getValue('rmj-flag-' + k, def);
        const clearFlags = () => GM_setValue('rmj-flag-action', '');

        let submitting = false;
        let luoguSetupDone = false;
        let cfAtSetupDone = false;

        const stripUrl = (v) => {
            const m = (v || '').match(/url\(\s*(['"]?)(.+?)\1\s*\)/i);
            return m ? m[2] : v;
        };

        const showRedirectMask = () => {
            if (document.getElementById('rmj-redirect-mask')) return;
            const m = document.createElement('div');
            m.id = 'rmj-redirect-mask';
            m.style.cssText = 'position:fixed!important;inset:0!important;z-index:2147483647!important;background:rgb(239,239,239)!important;pointer-events:all!important;';
            const attach = () => (document.body || document.documentElement).appendChild(m);
            if (document.body) attach();
            else new MutationObserver((_, o) => { if (document.body) { o.disconnect(); attach(); } })
                .observe(document.documentElement, { childList: true });
        };

        GM_addStyle(`
            .swal2-loader{visibility:hidden}
            #rmj-overlay{
                position:fixed!important;inset:0!important;z-index:999998!important;
                display:flex!important;align-items:center!important;justify-content:center!important;
                overflow:hidden!important;pointer-events:all!important;cursor:default!important;
                background:var(--rmj-back,#f5f5f5)!important;
                color:#333!important;box-sizing:border-box!important;-webkit-font-smoothing:antialiased!important;
            }
            #rmj-overlay *{box-sizing:border-box!important;margin:0!important;padding:0!important;font-family:inherit!important;line-height:inherit!important}
            #rmj-overlay .ly{position:absolute!important;inset:0!important;pointer-events:none!important;
                -webkit-mask:var(--rmj-mask,none) no-repeat/100% 100%!important;mask:var(--rmj-mask,none) no-repeat/100% 100%!important}
            #rmj-overlay .ly-c{background:var(--rmj-color,transparent)!important;filter:var(--rmj-filter,none)!important}
            #rmj-overlay .ly-i{background:var(--rmj-img,none) var(--rmj-pos,center)/var(--rmj-size,cover) var(--rmj-repeat,no-repeat)!important}
            #rmj-card{
                position:relative!important;z-index:1!important;width:420px!important;max-width:90vw!important;
                padding:36px 32px 40px!important;border-radius:4px!important;border:none!important;
                background:var(--rmj-card,rgba(255,255,255,.78))!important;
                backdrop-filter:var(--rmj-blur,blur(14px))!important;-webkit-backdrop-filter:var(--rmj-blur,blur(14px))!important;
                box-shadow:0 8px 32px rgba(0,0,0,.18),0 1.5px 6px rgba(0,0,0,.08)!important;
                display:flex!important;flex-direction:column!important;align-items:center!important;gap:20px!important;
            }
            #rmj-overlay.anim #rmj-card{opacity:0!important;transform:translateY(8px)!important;transition:opacity .45s ease .15s,transform .45s ease .15s!important}
            #rmj-overlay.anim.open #rmj-card{opacity:1!important;transform:translateY(0)!important}
            #rmj-card h2{font-size:20px!important;font-weight:600!important;color:#333!important;letter-spacing:.5px!important;user-select:none!important}
            #rmj-card p{font-size:13px!important;color:#888!important;margin-top:-10px!important;text-align:center!important;user-select:none!important}
            #rmj-slot{width:100%!important;min-height:78px!important;display:flex!important;align-items:center!important;justify-content:center!important}
            #rmj-slot:empty::after{content:'等待验证组件加载…';font-size:13px;color:#aaa}
            #rmj-spin{width:26px;height:26px;border:3px solid rgba(0,0,0,.1);border-top-color:#005c97;border-radius:50%;animation:sp .7s linear infinite}
            #rmj-error{color:#d32f2f!important;font-size:13px!important;text-align:center!important;word-break:break-all!important;max-height:120px!important;overflow-y:auto!important;padding:8px 12px!important;background:rgba(211,47,47,.08)!important;border-radius:4px!important;width:100%!important;display:none!important}
            @keyframes sp{to{transform:rotate(360deg)}}
            body.rmj-lock{overflow:hidden!important;height:100vh!important}
        `);

        const toB64 = (raw) => new Promise((res, rej) => {
            const url = stripUrl(raw);
            if (!/^https?:\/\//i.test(url || '')) return res('');
            const img = new Image();
            img.crossOrigin = 'anonymous';
            img.onload = () => {
                try {
                    const cv = document.createElement('canvas');
                    const MAX = 1920;
                    let w = img.naturalWidth, h = img.naturalHeight;
                    if (Math.max(w, h) > MAX) {
                        const s = MAX / Math.max(w, h);
                        w = w * s | 0;
                        h = h * s | 0;
                    }
                    cv.width = w;
                    cv.height = h;
                    cv.getContext('2d').drawImage(img, 0, 0, w, h);
                    let q = 0.9, b = '';
                    while (q >= 0.1) {
                        b = cv.toDataURL('image/jpeg', q);
                        if (b.length <= LIMIT) break;
                        q = +(q - 0.1).toFixed(1);
                    }
                    if (b.length > LIMIT) {
                        const c2 = document.createElement('canvas');
                        c2.width = w >> 1;
                        c2.height = h >> 1;
                        c2.getContext('2d').drawImage(cv, 0, 0, c2.width, c2.height);
                        b = c2.toDataURL('image/jpeg', 0.5);
                    }
                    if (b.length > LIMIT) {
                        const c3 = document.createElement('canvas');
                        c3.width = w >> 2;
                        c3.height = h >> 2;
                        c3.getContext('2d').drawImage(cv, 0, 0, c3.width, c3.height);
                        b = c3.toDataURL('image/jpeg', 0.4);
                    }
                    res(b.length <= LIMIT ? b : '');
                } catch (e) { rej(e); }
            };
            img.onerror = () => rej(new Error('图片加载失败'));
            img.src = url;
        });

        const applyVars = (el) => ThemeStore.applyTo(el);

        const overlay = (anim, ox, oy) => {
            document.documentElement.style.overflow = 'hidden';
            let el = document.getElementById('rmj-overlay');
            if (el) return el;
            el = document.createElement('div');
            el.id = 'rmj-overlay';
            el.innerHTML = `<div class="ly ly-c"></div><div class="ly ly-i"></div>
                <div id="rmj-card"><h2>正在加载验证</h2><p>通过 Cloudflare 安全验证后将继续提交</p>
                <div id="rmj-error"></div>
                <div id="rmj-slot"><div id="rmj-spin"></div></div></div>`;
            applyVars(el);
            const mount = () => {
                document.body.appendChild(el);
                if (!anim) return;
                ox ??= innerWidth / 2;
                oy ??= innerHeight / 2;
                const R = Math.hypot(innerWidth, innerHeight) + 60;
                el.classList.add('anim');
                el.style.clipPath = `circle(0px at ${ox}px ${oy}px)`;
                requestAnimationFrame(() => requestAnimationFrame(() => {
                    el.style.transition = 'clip-path .6s cubic-bezier(.22,1,.36,1)';
                    el.style.clipPath = `circle(${R}px at ${ox}px ${oy}px)`;
                    el.classList.add('open');
                }));
            };
            document.body
                ? mount()
                : new MutationObserver((_, o) => { if (document.body) { o.disconnect(); mount(); } })
                    .observe(document.documentElement, { childList: true });
            return el;
        };

        const showError = (msg) => {
            const errEl = document.getElementById('rmj-error');
            const slot = document.getElementById('rmj-slot');
            const title = document.querySelector('#rmj-card h2');
            if (errEl) { errEl.textContent = msg; errEl.style.display = 'block'; }
            if (slot) slot.innerHTML = '';
            if (title) title.textContent = '操作失败,请检查你的远程 OJ 状态';
            ERR(msg);
        };

        const onBody = (cb) => document.body
            ? cb()
            : new MutationObserver((_, o) => { if (document.body) { o.disconnect(); cb(); } })
                .observe(document.documentElement, { childList: true });

        const setupMeta = (plat) => {
            document.title = plat === 'codeforces' ? 'GenGen RMJ on CF' : 'GenGen RMJ on AT';
            const fixIcon = () => {
                document.querySelectorAll('link[rel*="icon"]').forEach((l) => l.remove());
                const h = document.head;
                for (const s of ['16x16', '32x32', '48x48', '192x192']) {
                    const l = document.createElement('link');
                    l.rel = 'icon';
                    l.type = 'image/png';
                    l.href = LOGO;
                    l.sizes = s;
                    h.appendChild(l);
                }
                const a = document.createElement('link');
                a.rel = 'apple-touch-icon';
                a.href = LOGO;
                a.sizes = '180x180';
                h.appendChild(a);
            };
            const guard = () => new MutationObserver((muts) => {
                for (const m of muts) {
                    for (const n of m.addedNodes) {
                        if (n.nodeType === 1 && n.tagName === 'LINK' && /icon/i.test(n.rel) && n.href !== LOGO) {
                            n.remove();
                            fixIcon();
                            return;
                        }
                    }
                }
            }).observe(document.head, { childList: true, subtree: true });
            const noTrans = () => {
                const h = document.documentElement;
                h.classList.add('notranslate');
                h.setAttribute('translate', 'no');
                h.setAttribute('lang', 'zh-CN');
                const add = (a) => {
                    const m = document.createElement('meta');
                    Object.entries(a).forEach(([k, v]) => m.setAttribute(k, v));
                    document.head.appendChild(m);
                };
                add({ name: 'google', content: 'notranslate' });
                add({ 'http-equiv': 'Content-Language', content: 'zh-CN' });
                add({ name: 'msapplication-config', content: 'none' });
            };
            const run = () => { fixIcon(); guard(); noTrans(); };
            document.head
                ? run()
                : new MutationObserver((_, o) => { if (document.head) { o.disconnect(); run(); } })
                    .observe(document.documentElement, { childList: true, subtree: true });
        };

        const SUBMIT_RE = /\/fe\/api\/problem\/submit\/([^/?#]+)/;

        const setupLuogu = () => {
            if (luoguSetupDone) return;
            if (!location.href.includes('luogu.com.cn')) return;
            luoguSetupDone = true;

            let click = { x: innerWidth / 2, y: innerHeight / 2 };
            document.addEventListener('click', (e) => {
                click = { x: e.clientX, y: e.clientY };
            }, true);

            const pidTarget = (raw) => {
                const p = String(raw).trim();
                let m = p.match(/^CF(\d+)([A-Z]\d*)$/);
                if (m) return { plat: 'codeforces', contest: m[1], index: m[2] };
                m = p.match(/^AT_([a-z0-9]+)_(.+)$/i);
                if (m) return { plat: 'atcoder', contest: m[1], task: `${m[1]}_${m[2]}` };
                return null;
            };

            const atFromDOM = () => {
                for (const a of document.querySelectorAll('a[href*="atcoder.jp/contests/"]')) {
                    const m = a.href.match(/atcoder\.jp\/contests\/([^/]+)\/tasks\/([^/?#]+)/);
                    if (m) return { plat: 'atcoder', contest: m[1], task: m[2] };
                }
                return null;
            };

            const intercept = async (code, pid) => {
                pid = String(pid).trim();
                let t = pidTarget(pid);
                if (!t && /^AT/i.test(pid)) {
                    await new Promise((r) => document.body
                        ? r()
                        : new MutationObserver((_, o) => { if (document.body) { o.disconnect(); r(); } })
                            .observe(document.documentElement, { childList: true }));
                    for (let i = 0; i < 30 && !t; i++) {
                        t = atFromDOM();
                        if (!t) await sleep(200);
                    }
                }
                if (!t) return;

                // 未绑定:直接拒绝
                const bindKey = t.plat === 'codeforces' ? 'cf-handle' : 'at-handle';
                const bindName = t.plat === 'codeforces' ? 'Codeforces' : 'AtCoder';
                if (!GM_getValue(bindKey, '')) {
                    overlay(false);
                    showError(`请先在 GenGen RMJ 面板中绑定 ${bindName} 账号`);
                    return;
                }

                if (t.plat === 'codeforces' && (!/^\d+$/.test(t.contest) || !/^[A-Z]\d*$/.test(t.index))) {
                    ERR(`CF 目标非法: ${t.contest}/${t.index}`);
                    return;
                }

                ThemeStore.extractFromLuogu();

                set('code', code + `\n\n// 本代码使用 GenGen RMJ 于 ${Date()} 提交 | ${pid}`);
                set('back', location.href);
                set('platform', t.plat);
                set('pid', pid);
                if (t.plat === 'codeforces') {
                    set('cf_contest', t.contest);
                    set('cf_index', t.index);
                } else {
                    set('contest', t.contest);
                    set('task', t.task);
                }

                // 只在成功时覆盖 bg_b64,避免清空旧数据
                const bgRaw = get('bg_image');
                if (bgRaw) {
                    try {
                        const b64 = await toB64(bgRaw);
                        if (b64) set('bg_b64', b64);
                    } catch { /* 保留旧值 */ }
                }

                overlay(true, click.x, click.y);

                const url = t.plat === 'codeforces'
                    ? `https://codeforces.com/problemset/submit/${t.contest}/${t.index}?RMJ=1`
                    : `https://atcoder.jp/contests/${t.contest}/submit?RMJ=1`;
                setTimeout(() => { location.href = url; }, 700);
            };

            const XHR = unsafeWindow.XMLHttpRequest;
            const _open = XHR.prototype.open;
            const _send = XHR.prototype.send;

            XHR.prototype.open = function (m, u, ...r) {
                this._rmj = { m: m.toUpperCase(), u: String(u) };
                return _open.call(this, m, u, ...r);
            };
            XHR.prototype.send = function (body) {
                const m = this._rmj?.m === 'POST' && SUBMIT_RE.exec(this._rmj.u);
                if (m) {
                    let code = '';
                    try { code = JSON.parse(String(body ?? '')).code || ''; } catch { /* ignore */ }
                    if (code.trim()) intercept(code, m[1]);
                    this.abort();
                    return;
                }
                return _send.call(this, body);
            };
        };

        const setupCfAt = () => {
            if (cfAtSetupDone) return;
            cfAtSetupDone = true;

            const h = location.href;
            const isFromRMJ = document.referrer.includes('RMJ=1') || getFlag('action');

            if (h.includes('codeforces.com/problemset/status') && isFromRMJ) {
                showRedirectMask();
                handleStatusPage('codeforces');
                return;
            }
            if (h.includes('atcoder.jp/contests/') && h.includes('/submissions/me') && isFromRMJ) {
                showRedirectMask();
                handleStatusPage('atcoder');
                return;
            }

            onBody(async () => {
                if (h.includes('atcoder.jp') && h.includes('RMJ=1')) init('atcoder');
                else if (h.includes('codeforces.com') && new URL(h).searchParams.get('RMJ') === '1') init('codeforces');
            });
        };

        function init(plat) {
            setupMeta(plat);
            document.documentElement.classList.add('rmj-lock');
            overlay(false);
            const go = () => submit(plat);
            document.readyState === 'loading'
                ? document.addEventListener('DOMContentLoaded', go)
                : go();
        }

        async function handleStatusPage(plat) {
            let sid = null;
            for (let i = 0; i < 10; i++) {
                sid = await archiveCode(plat);
                if (sid) break;
                await sleep(1500);
            }
            clearFlags();

            let targetUrl;
            if (sid) {
                if (plat === 'codeforces') {
                    targetUrl = `https://www.luogu.com.cn/record/cf/${get('cf_contest')}/${sid}`;
                } else {
                    targetUrl = `https://www.luogu.com.cn/record/at/${get('contest')}/${sid}`;
                }
            } else {
                if (plat === 'codeforces') {
                    targetUrl = `https://codeforces.com/contest/${get('cf_contest')}/my`;
                } else {
                    targetUrl = `https://atcoder.jp/contests/${get('contest')}/submissions/me`;
                }
            }

            location.href = targetUrl;
        }

        async function archiveCode(plat) {
            try {
                const c = plat === 'codeforces' ? get('cf_contest') : get('contest');
                if (plat === 'codeforces') {
                    const code = get('code');
                    if (!code) return;
                    const my = `https://codeforces.com/contest/${c}/my`;
                    const doc = new DOMParser().parseFromString(
                        await (await fetch(my, { credentials: 'include' })).text(),
                        'text/html'
                    );
                    const sid = (doc.querySelector('a[href*="/submission"]')?.href || '')
                        .match(/submissions?\/(\d+)/)?.[1];
                    if (sid) GM_setValue(`{${c},${sid}}`, code);
                    return sid;
                } else {
                    const res = await fetch(
                        `https://atcoder.jp/contests/${c}/submissions/me/status/json`,
                        { credentials: 'include' }
                    );
                    if (!res.ok) return null;
                    const data = await res.json();
                    if (data && data.Result) {
                        const ids = Object.keys(data.Result);
                        if (ids.length > 0) {
                            ids.sort((a, b) => Number(b) - Number(a));
                            return ids[0];
                        }
                    }
                    return null;
                }
            } catch (e) {
                ERR(e);
            }
        }

        async function submit(plat) {
            if (submitting) return;
            submitting = true;
            try {
                const code = get('code');
                if (!code?.trim()) {
                    showError('代码为空,请返回重新操作');
                    clr();
                    return;
                }
                document.documentElement.classList.remove('rmj-lock');

                let form = null;
                for (let i = 0; i < 100; i++) {
                    form = plat === 'atcoder'
                        ? document.querySelector('form[action*="/submit"]')
                        : document.querySelector('form.submitFrameForm')
                            || document.querySelector('form.submit-form')
                            || document.querySelector('form[method="post"][action*="csrf_token"]');
                    if (form) break;
                    await sleep(100);
                }
                if (!form) {
                    const blocked = /403|just a moment|attention required/i.test(document.title)
                        || !!document.querySelector('#challenge-stage,#challenge-form,.cf-challenge,iframe[src*="challenges.cloudflare.com"]');
                    if (blocked) {
                        showError('页面被 Cloudflare 拦截,请手动完成验证后刷新');
                        return;
                    }
                    showError('未找到提交表单');
                    clr();
                    return;
                }

                if (plat === 'atcoder') {
                    const ta = document.getElementById('plain-textarea');
                    if (ta) { ta.value = code; ta.dispatchEvent(new Event('input', { bubbles: true })); }
                    const ace = document.getElementById('editor') || document.querySelector('.ace_editor');
                    if (ace && unsafeWindow.ace) {
                        try {
                            const e = unsafeWindow.ace.edit(ace);
                            e.setValue(code, 1);
                            e.clearSelection();
                        } catch { /* ignore */ }
                    }
                } else {
                    const ta = document.querySelector('#sourceCodeTextarea');
                    if (ta) { ta.value = code; ta.dispatchEvent(new Event('input', { bubbles: true })); }
                    const ace = document.getElementById('editor');
                    if (ace && unsafeWindow.ace) {
                        try {
                            const e = unsafeWindow.ace.edit(ace);
                            e.setValue(code, 1);
                            e.clearSelection();
                        } catch { /* ignore */ }
                    }
                }

                if (plat === 'atcoder') {
                    const task = get('task');
                    if (task) {
                        const s = document.querySelector('select[name="data.TaskScreenName"]');
                        if (s) { s.value = task; s.dispatchEvent(new Event('change', { bubbles: true })); }
                    }
                    const l = document.querySelector('select[name="data.LanguageId"]');
                    if (l) { l.value = '6017'; l.dispatchEvent(new Event('change', { bubbles: true })); }
                } else {
                    const l = document.querySelector('select[name="programTypeId"]');
                    if (l) { l.value = '91'; l.dispatchEvent(new Event('change', { bubbles: true })); }
                }

                const CF = '.cf-challenge,.cf-turnstile,iframe[src*="challenges.cloudflare.com"],[data-callback*="turnstile"]';
                let hasCF = false;
                for (let i = 0; i < 30; i++) {
                    if (document.querySelector(CF)) { hasCF = true; break; }
                    await sleep(100);
                }

                let cfToken = '';
                if (hasCF) {
                    const cfWidget = document.querySelector(CF);
                    const slot = document.getElementById('rmj-slot');
                    if (slot) {
                        const updatePosition = () => {
                            const rect = slot.getBoundingClientRect();
                            const w = 300, h = 65;
                            const top = rect.top + (rect.height - h) / 2;
                            const left = rect.left + (rect.width - w) / 2;
                            cfWidget.style.position = 'fixed';
                            cfWidget.style.top = `${top}px`;
                            cfWidget.style.left = `${left}px`;
                            cfWidget.style.width = `${w}px`;
                            cfWidget.style.height = `${h}px`;
                            cfWidget.style.zIndex = '9999999';
                            cfWidget.style.margin = '0';
                            cfWidget.style.padding = '0';
                        };
                        updatePosition();
                        window.addEventListener('resize', updatePosition);
                    }

                    let tokenFound = false;
                    for (let i = 0; ; i++) {
                        const t = document.querySelector('input[name="turnstileToken"],input[name^="cf-turnstile-response"]');
                        if (t?.value?.length > 10) {
                            cfToken = t.value;
                            tokenFound = true;
                            break;
                        }
                        await sleep(100);
                    }
                    if (!tokenFound) {
                        showError('验证超时,请手动点击提交');
                        return;
                    }
                }

                if (plat === 'codeforces' && hasCF) {
                    setFlag('action', 'submit');
                    let submitBtn = form.querySelector('input[type="submit"], button[type="submit"]');
                    if (!submitBtn) submitBtn = form.querySelector('.submit-form-submit, .submit, [name="action"][value="submitSolutionFormSubmitted"]');
                    if (submitBtn) {
                        submitBtn.click();
                    } else {
                        HTMLFormElement.prototype.submit.call(form);
                    }
                    return;
                }

                const contest = get('contest');
                const cfcon = get('cf_contest');
                let url;
                if (plat === 'codeforces') {
                    const csrf = form.querySelector('input[name="csrf_token"]')?.value
                        || document.querySelector('meta[name="csrf_token"]')?.content || '';
                    url = location.origin + location.pathname;
                    if (csrf) url += (url.includes('?') ? '&' : '?') + 'csrf_token=' + encodeURIComponent(csrf);
                } else {
                    url = form.action || location.href;
                }

                const fd = new FormData(form);
                if (plat === 'codeforces') {
                    fd.set('programTypeId', '91');
                    fd.set('source', code);
                } else if (plat === 'atcoder') {
                    fd.set('sourceCode', code);
                }

                if (cfToken) {
                    fd.set('cf-turnstile-response', cfToken);
                    fd.set('turnstileToken', cfToken);
                }

                try {
                    const r = await fetch(url, {
                        method: 'POST',
                        body: fd,
                        credentials: 'include',
                        redirect: 'manual',
                        headers: {
                            Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                            Referer: location.href
                        }
                    });

                    const isSuccess = r.type === 'opaqueredirect' || r.status === 302 || r.status === 303 || r.ok;
                    if (!isSuccess) throw new Error(`HTTP ${r.status}`);

                    let sid = null;
                    for (let i = 0; i < 8; i++) {
                        await sleep(1000);
                        sid = await archiveCode(plat);
                        if (sid) break;
                    }

                    clr();
                    if (plat === 'codeforces') {
                        location.href = `https://www.luogu.com.cn/record/cf/${cfcon}/${sid || ''}`;
                    } else if (plat === 'atcoder') {
                        location.href = `https://www.luogu.com.cn/record/at/${contest}/${sid || ''}`;
                    }
                } catch (e) {
                    showError(`提交失败:\n${e.message}`);
                    clr();
                }
            } finally {
                submitting = false;
            }
        }

        const run = () => {
            if (!VALID.some((r) => r.test(location.href))) return;
            setupLuogu();
            setupCfAt();
        };

        return { init: run, showRedirectMask };
    })();

    // 主调度
    const bootstrap = () => {
        CfChallengePatch.apply();

        if (isCF()) {
            MainUI.captureCfHandle();
            ShieldSubmit.init();
            return;
        }

        if (isLuogu()) {
            MainUI.init();
            RecordList.init();
            RecordDetail.init();
            ShieldSubmit.init();
            ThemeStore.extractWithRetry();

            Router.on(() => {
                MainUI.hideModal();
                MainUI.handleRoute();
                RecordList.init();
                RecordDetail.init();
                ShieldSubmit.init();
            });
            return;
        }

        if (isAT()) {
            ShieldSubmit.init();
            return;
        }

        if (isCfChallenge()) return;
    };

    docReady(bootstrap);
})();

:::

表情包收藏

:::info

// ==UserScript==
// @name         洛谷图片收藏
// @namespace    https://www.luogu.com.cn/
// @version      2.0.0
// @description  收藏图片网址,点击即可插入 Markdown,支持预览开关
// @author       xcb & ChatGPT
// @match        https://www.luogu.com.cn/*
// @match        https://*.luogu.com.cn/*
// @match        https://*.luogu.com/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(() => {
    'use strict';

    const STORAGE_KEY = 'lg_saved_images_v1';
    const PREVIEW_KEY = 'lg_image_preview_enabled';

    const PANEL_ID = 'lg-image-collection-root';

    // ==================== 数据管理 ====================

    function loadImages() {
        try {
            const data = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
            return Array.isArray(data) ? data : [];
        } catch {
            return [];
        }
    }

    function saveImages() {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(images));
    }

    let images = loadImages();

    // 默认关闭图片预览
    let previewEnabled = localStorage.getItem(PREVIEW_KEY) === 'true';

    // ==================== 编辑器光标记忆 ====================

    let lastEditor = null;
    let lastSelectionStart = 0;
    let lastSelectionEnd = 0;

    function isEditor(element) {
        if (!element || element.nodeType !== 1) return false;

        if (element.matches('textarea, input')) {
            return !element.disabled && !element.readOnly;
        }

        return element.isContentEditable;
    }

    function rememberCursor(element) {
        if (!isEditor(element)) return;

        lastEditor = element;

        if (
            element instanceof HTMLTextAreaElement ||
            element instanceof HTMLInputElement
        ) {
            lastSelectionStart = element.selectionStart ?? element.value.length;
            lastSelectionEnd = element.selectionEnd ?? element.value.length;
        }
    }

    document.addEventListener('focusin', event => {
        if (isEditor(event.target)) {
            rememberCursor(event.target);
        }
    }, true);

    document.addEventListener('keyup', event => {
        if (isEditor(event.target)) {
            rememberCursor(event.target);
        }
    }, true);

    document.addEventListener('click', event => {
        if (isEditor(event.target)) {
            rememberCursor(event.target);
        }
    }, true);

    document.addEventListener('input', event => {
        if (isEditor(event.target)) {
            rememberCursor(event.target);
        }
    }, true);

    // ==================== Markdown 插入 ====================

    function insertText(text) {
        let editor = lastEditor;

        // 如果当前焦点仍在编辑器中,优先使用当前编辑器
        if (isEditor(document.activeElement)) {
            editor = document.activeElement;
        }

        if (!editor || !editor.isConnected) {
            alert('没有找到编辑器,请先点击洛谷的编辑框。');
            return;
        }

        // textarea / input
        if (
            editor instanceof HTMLTextAreaElement ||
            editor instanceof HTMLInputElement
        ) {
            const start = Math.min(
                lastSelectionStart,
                editor.value.length
            );

            const end = Math.min(
                lastSelectionEnd,
                editor.value.length
            );

            editor.focus();

            editor.setRangeText(text, start, end, 'end');

            lastSelectionStart = editor.selectionStart;
            lastSelectionEnd = editor.selectionEnd;

            editor.dispatchEvent(new Event('input', {
                bubbles: true
            }));

            return;
        }

        // contenteditable
        if (editor.isContentEditable) {
            editor.focus();

            const selection = window.getSelection();

            if (selection && selection.rangeCount) {
                const range = selection.getRangeAt(0);

                if (editor.contains(range.commonAncestorContainer)) {
                    range.deleteContents();

                    const node = document.createTextNode(text);
                    range.insertNode(node);

                    range.setStartAfter(node);
                    range.collapse(true);

                    selection.removeAllRanges();
                    selection.addRange(range);

                    editor.dispatchEvent(new InputEvent('input', {
                        bubbles: true,
                        inputType: 'insertText',
                        data: text
                    }));

                    return;
                }
            }

            document.execCommand('insertText', false, text);
            return;
        }

        alert('暂不支持当前编辑器。');
    }

    // ==================== 创建 UI ====================

    if (document.getElementById(PANEL_ID)) return;

    const root = document.createElement('div');
    root.id = PANEL_ID;

    document.body.appendChild(root);

    const shadow = root.attachShadow({
        mode: 'open'
    });

    shadow.innerHTML = `
        <style>
            * {
                box-sizing: border-box;
            }

            :host {
                color-scheme: light dark;
                font-family:
                    -apple-system,
                    BlinkMacSystemFont,
                    "Segoe UI",
                    sans-serif;
            }

            .launcher {
                position: fixed;
                right: 22px;
                bottom: 24px;
                z-index: 999999;
                width: 48px;
                height: 48px;
                border: none;
                border-radius: 50%;
                background: #18a058;
                color: white;
                font-size: 22px;
                cursor: pointer;
                box-shadow: 0 3px 12px #0003;
                transition: transform .15s, background .15s;
            }

            .launcher:hover {
                background: #36ad6a;
                transform: scale(1.08);
            }

            .panel {
                position: fixed;
                right: 22px;
                bottom: 84px;
                z-index: 999999;
                width: 360px;
                max-width: calc(100vw - 32px);
                max-height: min(620px, calc(100vh - 120px));
                display: none;
                flex-direction: column;
                overflow: hidden;
                border: 1px solid var(--border);
                border-radius: 12px;
                background: var(--bg);
                color: var(--fg);
                box-shadow: 0 5px 24px #0003;
            }

            .panel.open {
                display: flex;
            }

            .header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 14px 16px;
                border-bottom: 1px solid var(--border);
                font-size: 16px;
                font-weight: 700;
            }

            .close {
                border: none;
                background: transparent;
                color: var(--muted);
                font-size: 22px;
                cursor: pointer;
            }

            .toolbar {
                padding: 12px;
                border-bottom: 1px solid var(--border);
            }

            input {
                width: 100%;
                min-width: 0;
                padding: 9px 10px;
                border: 1px solid var(--border);
                border-radius: 7px;
                outline: none;
                background: var(--input);
                color: var(--fg);
                font-size: 13px;
            }

            input:focus {
                border-color: #18a058;
            }

            button {
                font-family: inherit;
            }

            .add-row {
                display: flex;
                gap: 8px;
                margin-top: 8px;
            }

            .add-row input {
                flex: 1;
            }

            .btn {
                padding: 8px 12px;
                border: none;
                border-radius: 7px;
                background: #18a058;
                color: white;
                cursor: pointer;
                white-space: nowrap;
            }

            .btn:hover {
                background: #36ad6a;
            }

            .preview-row {
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 10px;
                margin-top: 10px;
                font-size: 13px;
            }

            .switch {
                display: flex;
                align-items: center;
                gap: 7px;
                cursor: pointer;
                user-select: none;
            }

            .switch input {
                width: 16px;
                height: 16px;
                accent-color: #18a058;
                cursor: pointer;
            }

            .hint {
                color: var(--muted);
                font-size: 11px;
            }

            .search {
                margin-top: 10px;
            }

            .list {
                flex: 1;
                min-height: 80px;
                overflow-y: auto;
                padding: 10px;
            }

            .item {
                display: flex;
                gap: 10px;
                align-items: center;
                padding: 9px;
                margin-bottom: 8px;
                border: 1px solid var(--border);
                border-radius: 8px;
                cursor: pointer;
                transition: background .15s;
            }

            .item:hover {
                background: var(--hover);
            }

            .preview {
                width: 64px;
                height: 64px;
                flex-shrink: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                overflow: hidden;
                border-radius: 6px;
                background: var(--hover);
                color: var(--muted);
                font-size: 11px;
                text-align: center;
            }

            .preview img {
                width: 100%;
                height: 100%;
                object-fit: contain;
            }

            .info {
                flex: 1;
                min-width: 0;
            }

            .url {
                overflow: hidden;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 3;
                word-break: break-all;
                font-size: 12px;
                line-height: 1.5;
            }

            .item-actions {
                display: flex;
                flex-direction: column;
                gap: 5px;
            }

            .delete {
                padding: 5px 8px;
                border: none;
                border-radius: 5px;
                background: #d03050;
                color: white;
                font-size: 11px;
                cursor: pointer;
            }

            .empty {
                padding: 35px 10px;
                color: var(--muted);
                text-align: center;
                font-size: 13px;
            }

            .footer {
                padding: 9px 12px;
                border-top: 1px solid var(--border);
                color: var(--muted);
                font-size: 11px;
                text-align: center;
            }

            @media (prefers-color-scheme: dark) {
                .panel {
                    --bg: #202127;
                    --fg: #e5e5e5;
                    --muted: #999;
                    --border: #41434b;
                    --input: #303139;
                    --hover: #303139;
                }
            }

            @media (prefers-color-scheme: light) {
                .panel {
                    --bg: #fff;
                    --fg: #222;
                    --muted: #888;
                    --border: #e5e5e5;
                    --input: #fafafa;
                    --hover: #f5f5f5;
                }
            }

            .panel.dark {
                --bg: #202127;
                --fg: #e5e5e5;
                --muted: #999;
                --border: #41434b;
                --input: #303139;
                --hover: #303139;
            }

            .panel.light {
                --bg: #fff;
                --fg: #222;
                --muted: #888;
                --border: #e5e5e5;
                --input: #fafafa;
                --hover: #f5f5f5;
            }
        </style>

        <button class="launcher" title="图片收藏">🧊</button>

        <div class="panel">
            <div class="header">
                <span>图片收藏</span>
                <button class="close" title="关闭">×</button>
            </div>

            <div class="toolbar">
                <div class="add-row">
                    <input
                        class="url-input"
                        type="text"
                        placeholder="输入图片网址..."
                    >
                    <button class="btn add-btn">添加</button>
                </div>

                <div class="preview-row">
                    <label class="switch">
                        <input class="preview-checkbox" type="checkbox">
                        <span>开启图片预览</span>
                    </label>
                    <span class="hint">默认关闭,不加载图片</span>
                </div>

                <input
                    class="search"
                    type="text"
                    placeholder="搜索图片网址..."
                >
            </div>

            <div class="list"></div>

            <div class="footer">
                点击条目插入 Markdown 图片语法
            </div>
        </div>
    `;

    const $ = selector => shadow.querySelector(selector);

    const launcher = $('.launcher');
    const panel = $('.panel');
    const closeButton = $('.close');
    const urlInput = $('.url-input');
    const addButton = $('.add-btn');
    const searchInput = $('.search');
    const list = $('.list');
    const previewCheckbox = $('.preview-checkbox');

    // ==================== 面板开关 ====================

    launcher.addEventListener('click', () => {
        panel.classList.toggle('open');
        if (panel.classList.contains('open')) {
            renderImages();
        }
    });

    closeButton.addEventListener('click', () => {
        panel.classList.remove('open');
    });

    // ==================== 图片预览开关 ====================

    function updatePreview() {
        previewCheckbox.checked = previewEnabled;

        localStorage.setItem(
            PREVIEW_KEY,
            String(previewEnabled)
        );

        renderImages();
    }

    previewCheckbox.checked = previewEnabled;

    previewCheckbox.addEventListener('change', () => {
        previewEnabled = previewCheckbox.checked;
        updatePreview();
    });

    // ==================== 添加图片 ====================

    function addImage() {
        const url = urlInput.value.trim();

        if (!url) {
            alert('请输入图片网址。');
            return;
        }

        let parsed;

        try {
            parsed = new URL(url);
        } catch {
            alert('图片网址格式不正确。');
            return;
        }

        if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
            alert('只支持 HTTP 和 HTTPS 图片网址。');
            return;
        }

        if (images.some(item => item.url === url)) {
            alert('这张图片已经收藏过了。');
            return;
        }

        images.unshift({
            id: Date.now() + Math.random().toString(16).slice(2),
            url
        });

        saveImages();

        urlInput.value = '';
        searchInput.value = '';

        renderImages();
    }

    addButton.addEventListener('click', addImage);

    urlInput.addEventListener('keydown', event => {
        if (event.key === 'Enter') {
            addImage();
        }
    });

    // ==================== 删除图片 ====================

    function deleteImage(id) {
        images = images.filter(item => item.id !== id);
        saveImages();
        renderImages();
    }

    // ==================== 渲染图片列表 ====================

    function renderImages() {
        list.replaceChildren();

        const keyword = searchInput.value.trim().toLowerCase();

        const filtered = images.filter(item =>
            item.url.toLowerCase().includes(keyword)
        );

        if (!filtered.length) {
            const empty = document.createElement('div');
            empty.className = 'empty';
            empty.textContent = images.length
                ? '没有找到匹配的图片。'
                : '还没有收藏图片,先添加一个吧。';

            list.appendChild(empty);
            return;
        }

        for (const item of filtered) {
            const row = document.createElement('div');
            row.className = 'item';

            const preview = document.createElement('div');
            preview.className = 'preview';

            if (previewEnabled) {
                const img = document.createElement('img');

                img.alt = '图片预览';
                img.loading = 'lazy';
                img.referrerPolicy = 'no-referrer';

                // 只有开启预览时才设置 src
                img.src = item.url;

                img.onerror = () => {
                    preview.textContent = '加载失败';
                };

                preview.appendChild(img);
            } else {
                preview.textContent = '预览关闭';
            }

            const info = document.createElement('div');
            info.className = 'info';

            const url = document.createElement('div');
            url.className = 'url';
            url.textContent = item.url;

            info.appendChild(url);

            const actions = document.createElement('div');
            actions.className = 'item-actions';

            const del = document.createElement('button');
            del.className = 'delete';
            del.textContent = '删除';

            del.addEventListener('click', event => {
                event.stopPropagation();

                if (confirm('确定删除这张图片吗?')) {
                    deleteImage(item.id);
                }
            });

            actions.appendChild(del);

            row.appendChild(preview);
            row.appendChild(info);
            row.appendChild(actions);

            // 点击条目插入 Markdown
            row.addEventListener('click', () => {
                insertText(`![](${item.url})`);
            });

            list.appendChild(row);
        }
    }

    searchInput.addEventListener('input', renderImages);

    // ==================== 暗色模式 ====================

    function updateTheme() {
        const dark = document.documentElement.classList.contains('dark')
            || document.body.classList.contains('dark')
            || document.documentElement.dataset.theme === 'dark';

        panel.classList.toggle('dark', dark);
        panel.classList.toggle('light', !dark);
    }

    updateTheme();

    const observer = new MutationObserver(updateTheme);

    observer.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ['class', 'data-theme']
    });

    observer.observe(document.body, {
        attributes: true,
        attributeFilter: ['class']
    });

    // ==================== 初始化 ====================

    renderImages();

})();

:::