跳到正文

闲话

spudcode脚本

Sutong123约 173 分钟
原文
文章信息与版本

文章信息

收录
2026年8月2日
更新
2026年8月2日
篇幅
约 173 分钟

版本

  1. v1当前
JavaScript
// ==UserScript==
// @name         SpudCode · 土豆主题 Codeforces
// @namespace    https://codeforces.com/
// @version      1.0.0
// @description  将 Codeforces 变成精致的 SpudCode:土豆宠物、虚构机房状态、请求土豆消耗、专注模式、样例复制、成就与主题美化。
// @author       小苏同学 & ChatGPT
// @match        *://codeforces.com/*
// @match        *://*.codeforces.com/*
// @icon         https://codeforces.org/s/0/favicon-96x96.png
// @run-at       document-start
// @grant        none
// ==/UserScript==

(() => {
    'use strict';

    /* ================================================================
     * SpudCode 1.0
     * - 单文件、无外部依赖、不开网络后门
     * - 所有“机房状态”和“土豆数量”均为娱乐模拟数据
     * - 不修改题面、代码、输入输出和用户提交内容
     * ================================================================ */

    const SCRIPT_ID = 'spudcode-v1';
    const STORAGE_KEY = `${SCRIPT_ID}:store`;
    const SESSION_STARTED_AT = performance.now();

    const DEFAULTS = Object.freeze({
        enabled: true,
        theme: 'auto',              // auto | light | dark
        petEnabled: true,
        requestMeter: true,
        statusCenter: true,
        tipsEnabled: true,
        achievements: true,
        verdictEffects: true,
        gentleAnimations: true,
        focusMode: false,
        petX: null,
        petY: null,
        petMood: 78,
        petEnergy: 82,
        petFood: 74,
        petLevel: 1,
        petExp: 0,
        reserve: 147,
        totalRequestsAllTime: 0,
        totalPotatoesAllTime: 0,
        unlocked: {},
        visits: 0,
        logoClicks: 0,
        crown: false
    });

    const session = {
        requestCount: 0,
        potatoesUsed: 0,
        lastRequestMs: 0,
        lastRequestPotatoes: 0,
        lastRequestLabel: '页面初始化',
        observedResources: new Set(),
        handledVerdicts: new WeakSet(),
        lastVerdictKey: '',
        panelOpen: false,
        settingsOpen: false,
        petMenuOpen: false,
        statusTimer: null,
        heartbeatTimer: null,
        saveTimer: null,
        brandMutationLock: false,
        lastTipAt: 0,
        logoBurstLock: false
    };

    const BRANDS = ['SpudCode', 'SpudOJ', 'CodePotato'];
    const BRAND_REPLACEMENTS = [
        { from: /Codeforces/gi, to: 'SpudCode' },
        { from: /CODEFORCES/g, to: 'SPUDCODE' }
    ];

    const STATUS_TEXTS = [
        ['马力前进', '正在推送测试点', '⚡'],
        ['搬运数据', '扛着输入文件往评测机跑', '📦'],
        ['认真评测', '逐行检查你的程序', '🔎'],
        ['尝试发芽', '等待灵感从头顶冒出来', '🌱'],
        ['补充淀粉', '正在食堂恢复体力', '🥣'],
        ['研究反例', '试图构造一个极端数据', '🧪'],
        ['原地狂奔', '催促超时程序快一点', '🏃'],
        ['晒太阳', '处理轻微发霉问题', '☀️'],
        ['轮班午睡', '保持机房长期稳定', '💤'],
        ['搬运答案', '将 verdict 送往浏览器', '✉️'],
        ['检查边界', '重点查看 0、1 与最大值', '📐'],
        ['滚动散热', '防止评测核心过热', '🌀']
    ];

    const LOG_MESSAGES = [
        '土豆 #{id} 成功搬运一个测试点。',
        '土豆 #{id} 对答案产生了一点怀疑。',
        '土豆 #{id} 开始检查数组边界。',
        '土豆 #{id} 被派去给评测机散热。',
        '土豆 #{id} 报告:传送带运转正常。',
        '土豆 #{id} 在输入数据里发现一颗小石子。',
        '土豆 #{id} 完成淀粉补给,重新上岗。',
        '土豆 #{id} 正在和超时程序赛跑。',
        '土豆 #{id} 把一份 verdict 装进了麻袋。',
        '土豆 #{id} 发芽 0.3 毫米,暂无大碍。'
    ];

    const PET_LINES = {
        idle: [
            '今天也要把边界条件看清楚。',
            '我只是土豆,但我不会把 long long 写成 int。',
            '评测机正在转,我也正在转。',
            '先造小样例,再怀疑评测机。',
            '不要盯排行榜,土豆还没写完。'
        ],
        pet: ['嗯……手感像刚出土。', '心情 +8,淀粉保持稳定。', '再摸一下也不是不行。'],
        feed: ['薯片喂土豆,属于同类循环利用。', '饱食度已恢复。', '咔嚓。这个逻辑有一点奇怪,但很好吃。'],
        work: ['安全帽戴好,开始搬测试点。', '收到。土豆进入高性能模式。', '正在替你盯着评测队列。'],
        sleep: ['我先睡一小会儿,TLE 了再叫我。', '进入低功耗淀粉模式。', '晚安,数组不要越界。'],
        ac: ['Accepted!这次不是土豆碰巧蒙对的。', '全体土豆批准通过。', 'AC 到手,可以短暂膨胀三秒。'],
        wa: ['先别重写,找一个最小反例。', 'WA 不等于思路全错,先查边界和笔误。', '土豆建议:把变量实际值推一遍。'],
        tle: ['跑快一点!我都开始滚了!', '复杂度似乎比土豆仓库还大。'],
        ce: ['编译器没看懂,土豆也没看懂。', '先看第一条编译错误,后面可能都是连锁反应。'],
        re: ['程序冒烟了。检查下标、除零和空容器。'],
        mle: ['内存被土豆麻袋压满了。']
    };

    let store = loadStore();
    store.visits += 1;
    store.reserve = clamp(Math.round(store.reserve || randomInt(136, 168)), 108, 189);
    scheduleSave();

    function loadStore() {
        try {
            const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
            return { ...DEFAULTS, ...parsed, unlocked: { ...DEFAULTS.unlocked, ...(parsed.unlocked || {}) } };
        } catch (_) {
            return { ...DEFAULTS };
        }
    }

    function saveStore() {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(store));
        } catch (_) {
            // 某些严格隐私模式下 localStorage 可能不可用;脚本仍可在当前页面运行。
        }
    }

    function scheduleSave() {
        clearTimeout(session.saveTimer);
        session.saveTimer = setTimeout(saveStore, 160);
    }

    function clamp(value, min, max) {
        return Math.min(max, Math.max(min, value));
    }

    function randomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function pick(array) {
        return array[Math.floor(Math.random() * array.length)];
    }

    function formatNumber(value, digits = 1) {
        return Number(value || 0).toFixed(digits).replace(/\.0$/, '');
    }

    function escapeHTML(value) {
        return String(value)
            .replace(/&/g, '&')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function nowTime() {
        return new Intl.DateTimeFormat('zh-CN', {
            hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
        }).format(new Date());
    }

    function isDarkPreferred() {
        return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    }

    function resolvedTheme() {
        return store.theme === 'auto' ? (isDarkPreferred() ? 'dark' : 'light') : store.theme;
    }

    function ready(callback) {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', callback, { once: true });
        } else {
            callback();
        }
    }

    /* --------------------------- 网络土豆计量 --------------------------- */

    function describeRequest(url) {
        try {
            const parsed = new URL(url, location.href);
            const path = parsed.pathname;
            if (/submit/i.test(path)) return '提交代码';
            if (/status|submissions/i.test(path)) return '读取评测状态';
            if (/standings/i.test(path)) return '搬运排行榜';
            if (/problem/i.test(path)) return '读取题面资源';
            if (/api/i.test(path)) return '调用接口';
            return '处理页面请求';
        } catch (_) {
            return '处理页面请求';
        }
    }

    function calculatePotatoes(elapsedMs, transferSize = 0, failed = false) {
        const timePart = Math.max(0.15, elapsedMs / 470);
        const sizePart = transferSize > 0 ? Math.min(3.6, transferSize / 420000) : 0;
        const jitter = 0.18 + Math.random() * 0.72;
        const failureTax = failed ? 1.35 : 0;
        return clamp(timePart + sizePart + jitter + failureTax, 0.2, 14.9);
    }

    function recordRequest({ elapsed = 0, size = 0, url = location.href, failed = false, source = 'network' } = {}) {
        if (!store.requestMeter) return;
        if (String(url).startsWith('data:') || String(url).startsWith('blob:')) return;

        const potatoes = calculatePotatoes(elapsed, size, failed);
        session.requestCount += 1;
        session.potatoesUsed += potatoes;
        session.lastRequestMs = elapsed;
        session.lastRequestPotatoes = potatoes;
        session.lastRequestLabel = failed ? '请求失败 · 土豆掉出传送带' : describeRequest(url);

        store.totalRequestsAllTime += 1;
        store.totalPotatoesAllTime += potatoes;
        scheduleSave();
        updateDock();

        if (failed) {
            showToast('传送带故障', `本次请求损耗 ${formatNumber(potatoes, 2)} 个土豆。`, 'warn');
        } else if (source !== 'resource' && elapsed > 1800) {
            petSay(`这个请求用了 ${Math.round(elapsed)}ms,土豆跑得有点累。`, 3200);
        }
    }

    function installNetworkHooks() {
        // fetch 监听
        if (typeof window.fetch === 'function' && !window.fetch.__spudWrapped) {
            const originalFetch = window.fetch;
            const wrappedFetch = async function (...args) {
                const started = performance.now();
                const url = args[0] && args[0].url ? args[0].url : args[0];
                try {
                    const response = await originalFetch.apply(this, args);
                    recordRequest({ elapsed: performance.now() - started, url, failed: !response.ok, source: 'fetch' });
                    return response;
                } catch (error) {
                    recordRequest({ elapsed: performance.now() - started, url, failed: true, source: 'fetch' });
                    throw error;
                }
            };
            wrappedFetch.__spudWrapped = true;
            wrappedFetch.__spudOriginal = originalFetch;
            window.fetch = wrappedFetch;
        }

        // XMLHttpRequest 监听
        if (window.XMLHttpRequest && !XMLHttpRequest.prototype.open.__spudWrapped) {
            const originalOpen = XMLHttpRequest.prototype.open;
            const originalSend = XMLHttpRequest.prototype.send;

            XMLHttpRequest.prototype.open = function (method, url, ...rest) {
                this.__spudUrl = url;
                return originalOpen.call(this, method, url, ...rest);
            };
            XMLHttpRequest.prototype.open.__spudWrapped = true;

            XMLHttpRequest.prototype.send = function (...args) {
                const started = performance.now();
                const finish = () => {
                    this.removeEventListener('loadend', finish);
                    recordRequest({
                        elapsed: performance.now() - started,
                        url: this.__spudUrl || location.href,
                        failed: this.status === 0 || this.status >= 400,
                        source: 'xhr'
                    });
                };
                this.addEventListener('loadend', finish);
                return originalSend.apply(this, args);
            };
        }

        // 初始页面资源兜底(CSS、脚本、图片等)
        try {
            const observer = new PerformanceObserver((list) => {
                for (const entry of list.getEntries()) {
                    const key = `${entry.name}|${Math.round(entry.startTime)}|${Math.round(entry.duration)}`;
                    if (session.observedResources.has(key)) continue;
                    session.observedResources.add(key);
                    if (!/^(script|css|img|link|other)$/.test(entry.initiatorType || 'other')) continue;
                    recordRequest({
                        elapsed: entry.duration || 0,
                        size: entry.transferSize || 0,
                        url: entry.name,
                        failed: false,
                        source: 'resource'
                    });
                }
            });
            observer.observe({ type: 'resource', buffered: true });
        } catch (_) {
            // 旧浏览器忽略。
        }
    }

    installNetworkHooks();

    /* --------------------------- CSS 与页面骨架 --------------------------- */

    const CSS = String.raw`
:root {
    --spud-bg: #f4efe6;
    --spud-bg-soft: #fbf8f1;
    --spud-card: rgba(255, 253, 247, .92);
    --spud-card-solid: #fffdf7;
    --spud-text: #33271f;
    --spud-muted: #75675d;
    --spud-line: rgba(107, 82, 60, .16);
    --spud-brown: #9b6335;
    --spud-brown-dark: #70411f;
    --spud-gold: #e5a93f;
    --spud-green: #5d8f57;
    --spud-green-soft: #e1efdd;
    --spud-red: #c85f55;
    --spud-orange: #dc8a38;
    --spud-purple: #8668a9;
    --spud-blue: #5b809d;
    --spud-shadow: 0 14px 40px rgba(73, 48, 28, .12);
    --spud-shadow-soft: 0 6px 20px rgba(73, 48, 28, .09);
    --spud-radius: 14px;
    --spud-font: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
    --spud-mono: "Cascadia Code", "SFMono-Regular", Consolas, "Liberation Mono", monospace;
}

html[data-spud-theme="dark"] {
    --spud-bg: #181411;
    --spud-bg-soft: #211b17;
    --spud-card: rgba(39, 31, 26, .94);
    --spud-card-solid: #271f1a;
    --spud-text: #f2e9dc;
    --spud-muted: #bcae9e;
    --spud-line: rgba(238, 213, 184, .13);
    --spud-brown: #d39a65;
    --spud-brown-dark: #f0b77d;
    --spud-gold: #edba58;
    --spud-green: #8fbd7c;
    --spud-green-soft: #2e422b;
    --spud-red: #e27a70;
    --spud-orange: #e9a15b;
    --spud-purple: #b49ad1;
    --spud-blue: #8dafc8;
    --spud-shadow: 0 18px 48px rgba(0, 0, 0, .34);
    --spud-shadow-soft: 0 8px 24px rgba(0, 0, 0, .24);
}

html.spudcode-active,
html.spudcode-active body {
    background: var(--spud-bg) !important;
    color: var(--spud-text) !important;
}

html.spudcode-active body {
    font-family: var(--spud-font) !important;
    transition: background-color .25s ease, color .25s ease;
}

html.spudcode-active body::before {
    content: "";
    position: fixed;
    inset: 0;
    pointer-events: none;
    z-index: -1;
    background:
        radial-gradient(circle at 10% 5%, rgba(229,169,63,.12), transparent 26rem),
        radial-gradient(circle at 90% 18%, rgba(93,143,87,.09), transparent 24rem),
        linear-gradient(180deg, rgba(255,255,255,.22), transparent 38rem);
}

html[data-spud-theme="dark"].spudcode-active body::before {
    background:
        radial-gradient(circle at 12% 8%, rgba(210,154,101,.10), transparent 25rem),
        radial-gradient(circle at 88% 14%, rgba(93,143,87,.08), transparent 22rem);
}

html.spudcode-active #body {
    background: transparent !important;
}

html.spudcode-active #pageContent,
html.spudcode-active .page-content {
    color: var(--spud-text) !important;
}

html.spudcode-active a {
    color: var(--spud-brown-dark);
    text-decoration-color: rgba(155,99,53,.35);
    text-underline-offset: 2px;
}

html.spudcode-active a:hover {
    color: var(--spud-green);
}

html.spudcode-active #header {
    border: 1px solid var(--spud-line) !important;
    border-radius: 0 0 18px 18px !important;
    background: var(--spud-card) !important;
    box-shadow: var(--spud-shadow-soft) !important;
    backdrop-filter: blur(14px);
    -webkit-backdrop-filter: blur(14px);
}

html.spudcode-active #header .second-level-menu {
    border-top-color: var(--spud-line) !important;
    background: transparent !important;
}

html.spudcode-active #header .second-level-menu-list li a,
html.spudcode-active #header .lang-chooser,
html.spudcode-active #header .lang-chooser a {
    color: var(--spud-muted) !important;
}

html.spudcode-active #header .second-level-menu-list li.current a,
html.spudcode-active #header .second-level-menu-list li a:hover {
    color: var(--spud-brown-dark) !important;
}

#spud-brand-logo {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    min-height: 44px;
    font: 800 24px/1 var(--spud-font);
    letter-spacing: -.8px;
    color: var(--spud-text);
    user-select: none;
}

#spud-brand-logo .spud-logo-mark {
    width: 34px;
    height: 29px;
    position: relative;
    display: inline-block;
    border-radius: 48% 52% 45% 55% / 56% 45% 55% 44%;
    background: linear-gradient(145deg, #d99a58, #aa6936);
    box-shadow: inset -5px -6px 0 rgba(99,51,20,.12), 0 4px 10px rgba(108,63,29,.18);
    transform: rotate(-5deg);
}

#spud-brand-logo .spud-logo-mark::before,
#spud-brand-logo .spud-logo-mark::after {
    content: "";
    position: absolute;
    width: 3px;
    height: 3px;
    border-radius: 50%;
    background: rgba(86,49,23,.55);
    box-shadow: 12px 6px 0 rgba(86,49,23,.42), 6px 16px 0 rgba(86,49,23,.35);
}

#spud-brand-logo .spud-logo-mark::before { left: 8px; top: 7px; }
#spud-brand-logo .spud-logo-mark::after { right: 8px; top: 11px; }

#spud-brand-logo .spud-logo-code { color: var(--spud-brown-dark); }
#spud-brand-logo .spud-logo-sub {
    display: block;
    margin-top: 3px;
    font-size: 9px;
    letter-spacing: 1.5px;
    color: var(--spud-muted);
    text-transform: uppercase;
}

html.spudcode-active .roundbox,
html.spudcode-active .datatable,
html.spudcode-active .topic,
html.spudcode-active .problemindexholder,
html.spudcode-active .sidebar-menu,
html.spudcode-active .roundbox.sidebox,
html.spudcode-active .userbox,
html.spudcode-active .comments,
html.spudcode-active .alert,
html.spudcode-active .notice {
    border-color: var(--spud-line) !important;
    border-radius: var(--spud-radius) !important;
    background: var(--spud-card) !important;
    box-shadow: var(--spud-shadow-soft) !important;
}

html.spudcode-active .datatable { overflow: hidden; }

html.spudcode-active .roundbox .caption,
html.spudcode-active .datatable .caption,
html.spudcode-active .roundbox .titled,
html.spudcode-active .caption.titled {
    background: linear-gradient(90deg, rgba(229,169,63,.15), rgba(93,143,87,.08)) !important;
    color: var(--spud-text) !important;
    border-color: var(--spud-line) !important;
}

html.spudcode-active table {
    color: var(--spud-text) !important;
}

html.spudcode-active .datatable table,
html.spudcode-active .problems,
html.spudcode-active .status-frame-datatable {
    border-collapse: separate !important;
    border-spacing: 0 !important;
}

html.spudcode-active .datatable td,
html.spudcode-active .datatable th,
html.spudcode-active .problems td,
html.spudcode-active .problems th,
html.spudcode-active .status-frame-datatable td,
html.spudcode-active .status-frame-datatable th {
    border-color: var(--spud-line) !important;
}

html.spudcode-active .datatable tr:hover td,
html.spudcode-active .problems tr:hover td,
html.spudcode-active .status-frame-datatable tr:hover td {
    background: rgba(229,169,63,.08) !important;
}

html.spudcode-active input,
html.spudcode-active select,
html.spudcode-active textarea,
html.spudcode-active button:not(.spud-btn):not(.spud-icon-btn):not(.spud-pet-action):not(.spud-switch):not(.spud-copy-btn) {
    border-color: var(--spud-line) !important;
    border-radius: 8px !important;
}

html.spudcode-active input,
html.spudcode-active select,
html.spudcode-active textarea {
    background: var(--spud-card-solid) !important;
    color: var(--spud-text) !important;
}

html.spudcode-active input[type="submit"],
html.spudcode-active button[type="submit"] {
    background: var(--spud-brown) !important;
    color: #fff !important;
    border-color: transparent !important;
    box-shadow: 0 4px 12px rgba(112,65,31,.18);
}

html.spudcode-active .problem-statement {
    color: var(--spud-text) !important;
    line-height: 1.72 !important;
}

html.spudcode-active .problem-statement .header {
    margin-bottom: 1.6em !important;
    padding: 24px 22px 20px !important;
    border: 1px solid var(--spud-line) !important;
    border-radius: var(--spud-radius) !important;
    background: linear-gradient(145deg, rgba(255,253,247,.88), rgba(229,169,63,.07)) !important;
    box-shadow: var(--spud-shadow-soft) !important;
}

html[data-spud-theme="dark"].spudcode-active .problem-statement .header {
    background: linear-gradient(145deg, rgba(39,31,26,.96), rgba(229,169,63,.07)) !important;
}

html.spudcode-active .problem-statement .title {
    color: var(--spud-text) !important;
    font-weight: 800 !important;
    letter-spacing: -.25px;
}

html.spudcode-active .problem-statement .time-limit,
html.spudcode-active .problem-statement .memory-limit,
html.spudcode-active .problem-statement .input-file,
html.spudcode-active .problem-statement .output-file {
    display: inline-flex !important;
    align-items: center;
    margin: 8px 4px 0 !important;
    padding: 5px 9px !important;
    border-radius: 999px;
    background: rgba(229,169,63,.12);
    color: var(--spud-muted) !important;
}

html.spudcode-active .problem-statement .section-title {
    margin-top: 1.55em !important;
    color: var(--spud-brown-dark) !important;
    font-weight: 800 !important;
}

html.spudcode-active .problem-statement pre,
html.spudcode-active pre {
    position: relative;
    border: 1px solid var(--spud-line) !important;
    border-radius: 11px !important;
    background: var(--spud-bg-soft) !important;
    color: var(--spud-text) !important;
    font-family: var(--spud-mono) !important;
    box-shadow: inset 0 1px 0 rgba(255,255,255,.35);
}

html.spudcode-active .sample-test .input,
html.spudcode-active .sample-test .output {
    position: relative;
    border-color: var(--spud-line) !important;
    border-radius: 12px !important;
    overflow: hidden;
    background: var(--spud-card-solid) !important;
}

.spud-sample-actions {
    position: absolute;
    top: 7px;
    right: 8px;
    display: flex;
    gap: 5px;
    z-index: 4;
}

.spud-copy-btn {
    border: 1px solid var(--spud-line);
    border-radius: 7px;
    padding: 4px 8px;
    background: var(--spud-card);
    color: var(--spud-muted);
    font: 600 11px/1.2 var(--spud-font);
    cursor: pointer;
    backdrop-filter: blur(8px);
}

.spud-copy-btn:hover {
    color: var(--spud-brown-dark);
    border-color: rgba(155,99,53,.32);
    transform: translateY(-1px);
}

.verdict-accepted,
.spud-verdict-ac { color: var(--spud-green) !important; font-weight: 800 !important; }
.verdict-rejected,
.spud-verdict-wa { color: var(--spud-red) !important; font-weight: 800 !important; }
.spud-verdict-tle { color: var(--spud-orange) !important; font-weight: 800 !important; }
.spud-verdict-ce { color: var(--spud-purple) !important; font-weight: 800 !important; }
.spud-verdict-run { color: var(--spud-gold) !important; font-weight: 800 !important; }

#spud-scroll-progress {
    position: fixed;
    top: 0;
    left: 0;
    width: 0;
    height: 3px;
    z-index: 2147483600;
    background: linear-gradient(90deg, var(--spud-gold), var(--spud-green));
    box-shadow: 0 1px 8px rgba(93,143,87,.35);
    transition: width .08s linear;
}

#spud-dock {
    position: fixed;
    left: 16px;
    bottom: 16px;
    z-index: 2147483000;
    display: flex;
    align-items: center;
    gap: 7px;
    max-width: calc(100vw - 120px);
    padding: 7px;
    border: 1px solid var(--spud-line);
    border-radius: 15px;
    background: var(--spud-card);
    box-shadow: var(--spud-shadow);
    backdrop-filter: blur(16px);
    -webkit-backdrop-filter: blur(16px);
    color: var(--spud-text);
    font-family: var(--spud-font);
    user-select: none;
}

.spud-dock-stat {
    display: flex;
    align-items: center;
    gap: 7px;
    min-width: 155px;
    padding: 3px 7px 3px 4px;
}

.spud-dock-potato {
    display: grid;
    place-items: center;
    width: 32px;
    height: 32px;
    border-radius: 10px;
    background: rgba(229,169,63,.15);
    font-size: 19px;
}

.spud-dock-main {
    display: block;
    color: var(--spud-text);
    font-size: 12px;
    font-weight: 800;
    white-space: nowrap;
}

.spud-dock-sub {
    display: block;
    margin-top: 2px;
    color: var(--spud-muted);
    font-size: 10px;
    white-space: nowrap;
}

.spud-icon-btn,
.spud-btn {
    appearance: none;
    border: 1px solid var(--spud-line);
    background: var(--spud-card-solid);
    color: var(--spud-text);
    font-family: var(--spud-font);
    cursor: pointer;
    transition: transform .15s ease, border-color .15s ease, background .15s ease;
}

.spud-icon-btn {
    display: grid;
    place-items: center;
    width: 34px;
    height: 34px;
    border-radius: 10px;
    font-size: 15px;
}

.spud-btn {
    border-radius: 10px;
    padding: 8px 12px;
    font-size: 12px;
    font-weight: 750;
}

.spud-btn.primary {
    background: var(--spud-brown);
    color: #fff;
    border-color: transparent;
}

.spud-icon-btn:hover,
.spud-btn:hover {
    transform: translateY(-1px);
    border-color: rgba(155,99,53,.34);
}

.spud-icon-btn.active {
    background: rgba(93,143,87,.14);
    color: var(--spud-green);
}

#spud-overlay {
    position: fixed;
    inset: 0;
    z-index: 2147483200;
    display: none;
    background: rgba(34,24,17,.28);
    backdrop-filter: blur(3px);
    -webkit-backdrop-filter: blur(3px);
}

#spud-overlay.visible { display: block; }

#spud-status-panel {
    position: fixed;
    top: 10px;
    right: 10px;
    bottom: 10px;
    z-index: 2147483300;
    width: min(410px, calc(100vw - 20px));
    border: 1px solid var(--spud-line);
    border-radius: 22px;
    background: var(--spud-card-solid);
    box-shadow: 0 24px 80px rgba(43,29,18,.28);
    color: var(--spud-text);
    font-family: var(--spud-font);
    overflow: hidden;
    transform: translateX(calc(100% + 30px));
    opacity: 0;
    transition: transform .28s cubic-bezier(.2,.8,.2,1), opacity .22s ease;
}

#spud-status-panel.visible {
    transform: translateX(0);
    opacity: 1;
}

.spud-panel-head {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 12px;
    padding: 19px 18px 14px;
    border-bottom: 1px solid var(--spud-line);
    background: linear-gradient(135deg, rgba(229,169,63,.14), rgba(93,143,87,.09));
}

.spud-panel-title {
    margin: 0;
    font-size: 18px;
    font-weight: 850;
    letter-spacing: -.25px;
}

.spud-panel-note {
    margin-top: 5px;
    color: var(--spud-muted);
    font-size: 11px;
    line-height: 1.45;
}

.spud-panel-body {
    height: calc(100% - 78px);
    overflow: auto;
    padding: 15px 16px 24px;
}

.spud-stat-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 9px;
}

.spud-stat-card {
    padding: 12px;
    border: 1px solid var(--spud-line);
    border-radius: 13px;
    background: var(--spud-bg-soft);
}

.spud-stat-label { color: var(--spud-muted); font-size: 10px; }
.spud-stat-value { margin-top: 4px; font-size: 22px; font-weight: 850; }
.spud-stat-unit { margin-left: 3px; color: var(--spud-muted); font-size: 10px; font-weight: 500; }

.spud-section-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 18px 1px 9px;
    font-size: 12px;
    font-weight: 850;
    color: var(--spud-text);
}

.spud-worker-list { display: grid; gap: 8px; }
.spud-worker {
    display: grid;
    grid-template-columns: 36px 1fr auto;
    gap: 10px;
    align-items: center;
    padding: 10px;
    border: 1px solid var(--spud-line);
    border-radius: 12px;
    background: var(--spud-card);
}

.spud-worker-icon {
    display: grid;
    place-items: center;
    width: 36px;
    height: 36px;
    border-radius: 11px;
    background: rgba(229,169,63,.13);
    font-size: 18px;
}

.spud-worker-name { font-size: 11px; font-weight: 800; }
.spud-worker-task { margin-top: 3px; color: var(--spud-muted); font-size: 10px; line-height: 1.35; }
.spud-worker-temp { color: var(--spud-muted); font-size: 10px; white-space: nowrap; }

.spud-log {
    max-height: 190px;
    overflow: auto;
    border: 1px solid var(--spud-line);
    border-radius: 12px;
    background: #1e1b18;
    color: #dacdbc;
    font: 10px/1.65 var(--spud-mono);
    padding: 9px 10px;
}

.spud-log-line .time { color: #8eaa7c; }
.spud-log-line + .spud-log-line { margin-top: 2px; }

#spud-settings {
    position: fixed;
    left: 50%;
    top: 50%;
    z-index: 2147483400;
    width: min(480px, calc(100vw - 28px));
    max-height: min(680px, calc(100vh - 28px));
    overflow: auto;
    border: 1px solid var(--spud-line);
    border-radius: 20px;
    background: var(--spud-card-solid);
    box-shadow: 0 24px 90px rgba(43,29,18,.34);
    color: var(--spud-text);
    font-family: var(--spud-font);
    transform: translate(-50%, -48%) scale(.97);
    opacity: 0;
    pointer-events: none;
    transition: opacity .18s ease, transform .2s ease;
}

#spud-settings.visible {
    opacity: 1;
    pointer-events: auto;
    transform: translate(-50%, -50%) scale(1);
}

.spud-settings-body { padding: 4px 18px 18px; }
.spud-setting-row {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 14px;
    align-items: center;
    padding: 12px 2px;
    border-bottom: 1px solid var(--spud-line);
}

.spud-setting-name { font-size: 12px; font-weight: 800; }
.spud-setting-desc { margin-top: 3px; color: var(--spud-muted); font-size: 10px; line-height: 1.45; }

.spud-switch {
    position: relative;
    width: 42px;
    height: 24px;
    border: 0;
    border-radius: 999px;
    background: rgba(117,103,93,.25);
    cursor: pointer;
    transition: background .18s ease;
}

.spud-switch::after {
    content: "";
    position: absolute;
    top: 3px;
    left: 3px;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background: #fff;
    box-shadow: 0 2px 6px rgba(0,0,0,.18);
    transition: transform .18s ease;
}

.spud-switch.on { background: var(--spud-green); }
.spud-switch.on::after { transform: translateX(18px); }

.spud-select {
    min-width: 112px;
    padding: 7px 9px;
    border: 1px solid var(--spud-line);
    border-radius: 9px;
    background: var(--spud-bg-soft);
    color: var(--spud-text);
    font: 600 11px var(--spud-font);
}

.spud-settings-actions {
    display: flex;
    justify-content: space-between;
    gap: 8px;
    padding-top: 15px;
}

#spud-pet-wrap {
    position: fixed;
    right: 23px;
    bottom: 18px;
    z-index: 2147483100;
    width: 82px;
    height: 102px;
    touch-action: none;
    user-select: none;
    cursor: grab;
    filter: drop-shadow(0 10px 12px rgba(73,48,28,.18));
}

#spud-pet-wrap.dragging { cursor: grabbing; }
#spud-pet-wrap.hidden { display: none !important; }

#spud-pet {
    position: absolute;
    left: 9px;
    bottom: 2px;
    width: 64px;
    height: 72px;
    border-radius: 47% 53% 43% 57% / 51% 45% 55% 49%;
    background:
        radial-gradient(circle at 27% 30%, rgba(255,255,255,.22) 0 3px, transparent 4px),
        radial-gradient(circle at 70% 65%, rgba(89,48,23,.20) 0 2px, transparent 3px),
        radial-gradient(circle at 25% 73%, rgba(89,48,23,.17) 0 2px, transparent 3px),
        linear-gradient(145deg, #e1a764 0%, #be783d 65%, #9d5d2f 100%);
    box-shadow: inset -8px -9px 0 rgba(91,47,20,.10), inset 6px 6px 0 rgba(255,234,196,.12);
    transform-origin: 50% 90%;
    animation: spud-breathe 3.2s ease-in-out infinite;
}

#spud-pet::before,
#spud-pet::after {
    content: "";
    position: absolute;
    bottom: -4px;
    width: 23px;
    height: 12px;
    border-radius: 55% 45% 55% 45%;
    background: #925027;
    z-index: -1;
}
#spud-pet::before { left: 3px; transform: rotate(-8deg); }
#spud-pet::after { right: 2px; transform: rotate(8deg); }

.spud-sprout {
    position: absolute;
    left: 31px;
    top: -21px;
    width: 4px;
    height: 27px;
    border-radius: 5px;
    background: #59824f;
    transform: rotate(-7deg);
    transform-origin: bottom;
    animation: spud-sprout-sway 3.8s ease-in-out infinite;
}

.spud-sprout::before,
.spud-sprout::after {
    content: "";
    position: absolute;
    width: 17px;
    height: 9px;
    border-radius: 90% 10% 90% 10%;
    background: #77a467;
}
.spud-sprout::before { top: 3px; left: -15px; transform: rotate(18deg); }
.spud-sprout::after { top: -1px; left: 3px; transform: scaleX(-1) rotate(13deg); }

.spud-eye {
    position: absolute;
    top: 27px;
    width: 7px;
    height: 9px;
    border-radius: 50%;
    background: #3d271c;
    animation: spud-blink 4.8s infinite;
}
.spud-eye.left { left: 17px; }
.spud-eye.right { right: 16px; }
.spud-eye::after {
    content: "";
    position: absolute;
    top: 1px;
    left: 1px;
    width: 2px;
    height: 2px;
    border-radius: 50%;
    background: rgba(255,255,255,.8);
}

.spud-mouth {
    position: absolute;
    left: 27px;
    top: 43px;
    width: 11px;
    height: 6px;
    border-bottom: 2px solid #603420;
    border-radius: 0 0 10px 10px;
}

.spud-cheek {
    position: absolute;
    top: 41px;
    width: 10px;
    height: 5px;
    border-radius: 50%;
    background: rgba(207,90,75,.22);
}
.spud-cheek.left { left: 9px; }
.spud-cheek.right { right: 8px; }

.spud-arm {
    position: absolute;
    top: 41px;
    width: 18px;
    height: 6px;
    border-radius: 999px;
    background: #a9602f;
    z-index: -1;
}
.spud-arm.left { left: -12px; transform: rotate(18deg); }
.spud-arm.right { right: -12px; transform: rotate(-18deg); }

.spud-crown {
    display: none;
    position: absolute;
    left: 18px;
    top: -27px;
    width: 31px;
    height: 20px;
    background: linear-gradient(#ffda69, #e4a82f);
    clip-path: polygon(0 100%, 0 30%, 25% 65%, 50% 0, 75% 65%, 100% 30%, 100% 100%);
    filter: drop-shadow(0 2px 2px rgba(90,53,15,.2));
    z-index: 5;
}
#spud-pet-wrap.has-crown .spud-crown { display: block; }

#spud-pet-wrap.night #spud-pet { filter: saturate(.88); }
#spud-pet-wrap.night .spud-mouth { width: 8px; height: 3px; left: 28px; }

#spud-pet-wrap.working #spud-pet { animation: spud-work .42s ease-in-out infinite alternate; }
#spud-pet-wrap.celebrate #spud-pet { animation: spud-celebrate .48s ease-in-out 6; }
#spud-pet-wrap.sad #spud-pet { animation: spud-sad .8s ease-in-out 2; }
#spud-pet-wrap.running #spud-pet { animation: spud-run .16s linear 15; }
#spud-pet-wrap.sleeping .spud-eye { height: 2px; top: 32px; animation: none; }
#spud-pet-wrap.sleeping .spud-mouth { border-bottom: 0; border-top: 2px solid #603420; }
#spud-pet-wrap.smoking::after {
    content: "💨";
    position: absolute;
    right: -5px;
    top: 10px;
    animation: spud-smoke 1s ease-out 3;
}

#spud-pet-bubble {
    position: absolute;
    right: 68px;
    bottom: 76px;
    width: max-content;
    max-width: min(250px, calc(100vw - 130px));
    padding: 9px 11px;
    border: 1px solid var(--spud-line);
    border-radius: 12px 12px 3px 12px;
    background: var(--spud-card-solid);
    box-shadow: var(--spud-shadow-soft);
    color: var(--spud-text);
    font: 600 11px/1.5 var(--spud-font);
    opacity: 0;
    transform: translateY(5px) scale(.98);
    pointer-events: none;
    transition: opacity .16s ease, transform .16s ease;
}

#spud-pet-bubble.visible {
    opacity: 1;
    transform: translateY(0) scale(1);
}

#spud-pet-menu {
    position: absolute;
    right: 66px;
    bottom: 5px;
    display: none;
    grid-template-columns: repeat(2, minmax(90px, 1fr));
    gap: 6px;
    width: 212px;
    padding: 8px;
    border: 1px solid var(--spud-line);
    border-radius: 13px;
    background: var(--spud-card-solid);
    box-shadow: var(--spud-shadow);
}
#spud-pet-menu.visible { display: grid; }

.spud-pet-action {
    border: 1px solid var(--spud-line);
    border-radius: 9px;
    padding: 7px 8px;
    background: var(--spud-bg-soft);
    color: var(--spud-text);
    font: 700 10px var(--spud-font);
    cursor: pointer;
    text-align: left;
}
.spud-pet-action:hover { border-color: rgba(155,99,53,.35); }

@media (min-width: 860px) {
    #spud-status-panel.visible ~ #spud-toast-stack { right: 438px; }
}

#spud-toast-stack {
    position: fixed;
    right: 18px;
    top: 18px;
    z-index: 2147483500;
    display: grid;
    gap: 8px;
    width: min(330px, calc(100vw - 36px));
    pointer-events: none;
}

.spud-toast {
    display: grid;
    grid-template-columns: 32px 1fr;
    gap: 9px;
    align-items: center;
    padding: 10px 12px;
    border: 1px solid var(--spud-line);
    border-radius: 13px;
    background: var(--spud-card-solid);
    box-shadow: var(--spud-shadow);
    color: var(--spud-text);
    font-family: var(--spud-font);
    opacity: 0;
    transform: translateY(-8px) scale(.98);
    animation: spud-toast-in .22s ease forwards;
}

.spud-toast-icon {
    display: grid;
    place-items: center;
    width: 32px;
    height: 32px;
    border-radius: 10px;
    background: rgba(229,169,63,.13);
    font-size: 17px;
}

.spud-toast-title { font-size: 11px; font-weight: 850; }
.spud-toast-text { margin-top: 2px; color: var(--spud-muted); font-size: 10px; line-height: 1.45; }
.spud-toast.warn .spud-toast-icon { background: rgba(200,95,85,.13); }
.spud-toast.success .spud-toast-icon { background: rgba(93,143,87,.14); }

#spud-confetti {
    position: fixed;
    inset: 0;
    z-index: 2147483050;
    overflow: hidden;
    pointer-events: none;
}

.spud-confetti-piece {
    position: absolute;
    top: -20px;
    font-size: 15px;
    animation: spud-confetti-fall var(--fall-time) cubic-bezier(.2,.7,.25,1) forwards;
}

.spud-focus-pill {
    position: fixed;
    top: 10px;
    left: 50%;
    z-index: 2147483001;
    transform: translateX(-50%);
    display: none;
    padding: 7px 11px;
    border: 1px solid var(--spud-line);
    border-radius: 999px;
    background: var(--spud-card);
    box-shadow: var(--spud-shadow-soft);
    color: var(--spud-muted);
    font: 700 10px var(--spud-font);
    cursor: pointer;
}

html.spud-focus #spud-focus-pill { display: block; }
html.spud-focus #header,
html.spud-focus #sidebar,
html.spud-focus .sidebar-menu,
html.spud-focus .sidebox,
html.spud-focus #footer,
html.spud-focus .footer,
html.spud-focus #spud-dock,
html.spud-focus #spud-pet-wrap {
    display: none !important;
}
html.spud-focus #pageContent,
html.spud-focus .problem-statement {
    width: min(920px, calc(100vw - 34px)) !important;
    max-width: 920px !important;
    margin-left: auto !important;
    margin-right: auto !important;
}

#spud-disabled-tab {
    position: fixed;
    left: 12px;
    bottom: 12px;
    z-index: 2147483000;
    display: none;
    border: 1px solid var(--spud-line);
    border-radius: 12px;
    padding: 9px 12px;
    background: #fffaf0;
    color: #70411f;
    box-shadow: 0 8px 24px rgba(73,48,28,.16);
    font: 750 12px var(--spud-font);
    cursor: pointer;
}

html:not(.spudcode-active) #spud-disabled-tab { display: block; }
html.spudcode-active #spud-disabled-tab { display: none; }

html.spud-reduced-motion #spud-pet,
html.spud-reduced-motion .spud-sprout,
html.spud-reduced-motion .spud-eye {
    animation: none !important;
}

html:not(.spudcode-active) #spud-dock,
html:not(.spudcode-active) #spud-pet-wrap,
html:not(.spudcode-active) #spud-scroll-progress {
    display: none !important;
}

@keyframes spud-breathe { 0%,100%{transform:translateY(0) rotate(-1deg)} 50%{transform:translateY(-2px) rotate(1deg)} }
@keyframes spud-blink { 0%,45%,49%,100%{transform:scaleY(1)} 47%{transform:scaleY(.08)} }
@keyframes spud-sprout-sway { 0%,100%{transform:rotate(-8deg)} 50%{transform:rotate(6deg)} }
@keyframes spud-work { from{transform:translateY(0) rotate(-3deg)} to{transform:translateY(-4px) rotate(4deg)} }
@keyframes spud-celebrate { 0%,100%{transform:translateY(0) rotate(0)} 50%{transform:translateY(-12px) rotate(8deg)} }
@keyframes spud-sad { 0%,100%{transform:translateY(0) rotate(0)} 50%{transform:translateY(3px) rotate(-4deg)} }
@keyframes spud-run { 0%{transform:translateX(-5px) rotate(-6deg)} 100%{transform:translateX(5px) rotate(6deg)} }
@keyframes spud-smoke { 0%{opacity:0;transform:translate(0,5px) scale(.5)} 40%{opacity:1} 100%{opacity:0;transform:translate(9px,-18px) scale(1.2)} }
@keyframes spud-toast-in { to{opacity:1;transform:translateY(0) scale(1)} }
@keyframes spud-toast-out { to{opacity:0;transform:translateY(-7px) scale(.98)} }
@keyframes spud-confetti-fall { to{transform:translate(var(--drift), 110vh) rotate(var(--spin));opacity:.1} }

@media (max-width: 760px) {
    #spud-dock { left: 9px; bottom: 9px; max-width: calc(100vw - 104px); }
    .spud-dock-stat { min-width: 0; }
    .spud-dock-stat .spud-dock-sub { display: none; }
    #spud-pet-wrap { right: 11px; bottom: 8px; transform: scale(.9); transform-origin: bottom right; }
    #spud-status-panel { top: 6px; right: 6px; bottom: 6px; width: calc(100vw - 12px); border-radius: 18px; }
    .spud-hide-mobile { display: none !important; }
    html.spudcode-active #header { border-radius: 0 0 12px 12px !important; }
    html.spudcode-active .problem-statement .header { padding: 18px 13px 15px !important; }
}

@media (prefers-reduced-motion: reduce) {
    #spud-pet, .spud-sprout, .spud-eye { animation-duration: .001ms !important; animation-iteration-count: 1 !important; }
    * { scroll-behavior: auto !important; }
}
`;

    function injectStyle() {
        if (document.getElementById('spudcode-style')) return;
        const style = document.createElement('style');
        style.id = 'spudcode-style';
        style.textContent = CSS;
        (document.head || document.documentElement).appendChild(style);
    }

    injectStyle();

    function createElement(tag, attrs = {}, html = '') {
        const element = document.createElement(tag);
        for (const [key, value] of Object.entries(attrs)) {
            if (key === 'class') element.className = value;
            else if (key === 'dataset') Object.assign(element.dataset, value);
            else if (key.startsWith('on') && typeof value === 'function') element.addEventListener(key.slice(2), value);
            else if (value !== null && value !== undefined) element.setAttribute(key, value);
        }
        if (html) element.innerHTML = html;
        return element;
    }

    function mountUI() {
        if (!document.body || document.getElementById('spud-dock')) return;

        const progress = createElement('div', { id: 'spud-scroll-progress' });
        const overlay = createElement('div', { id: 'spud-overlay' });
        const toastStack = createElement('div', { id: 'spud-toast-stack', 'aria-live': 'polite' });
        const confetti = createElement('div', { id: 'spud-confetti' });
        const focusPill = createElement('button', { id: 'spud-focus-pill', type: 'button' }, '退出专注模式 · Alt+P');
        const disabledTab = createElement('button', { id: 'spud-disabled-tab', type: 'button' }, '🥔 开启 SpudCode');

        const dock = createElement('div', { id: 'spud-dock' }, `
            <div class="spud-dock-stat" title="数据为娱乐模拟">
                <span class="spud-dock-potato">🥔</span>
                <span>
                    <strong class="spud-dock-main" id="spud-dock-main">土豆储备 ${store.reserve}</strong>
                    <small class="spud-dock-sub" id="spud-dock-sub">本页正在初始化</small>
                </span>
            </div>
            <button class="spud-icon-btn" id="spud-open-status" type="button" title="土豆机房(Alt+S)">📡</button>
            <button class="spud-icon-btn spud-hide-mobile" id="spud-focus-toggle" type="button" title="专注读题(Alt+P)">◎</button>
            <button class="spud-icon-btn" id="spud-theme-toggle" type="button" title="切换明暗主题">◐</button>
            <button class="spud-icon-btn" id="spud-open-settings" type="button" title="SpudCode 设置">⚙</button>
        `);

        const panel = createElement('aside', { id: 'spud-status-panel', 'aria-hidden': 'true' }, `
            <div class="spud-panel-head">
                <div>
                    <h2 class="spud-panel-title">🥔 土豆机房实时状态</h2>
                    <div class="spud-panel-note">娱乐模拟数据,不代表 Codeforces 的真实服务器状态。</div>
                </div>
                <button class="spud-icon-btn" id="spud-close-status" type="button" title="关闭">×</button>
            </div>
            <div class="spud-panel-body">
                <div class="spud-stat-grid" id="spud-stat-grid"></div>
                <div class="spud-section-title"><span>当前值班土豆</span><span id="spud-shift-label"></span></div>
                <div class="spud-worker-list" id="spud-worker-list"></div>
                <div class="spud-section-title"><span>传送带日志</span><button class="spud-btn" id="spud-refresh-workers" type="button">重新点名</button></div>
                <div class="spud-log" id="spud-log"></div>
            </div>
        `);

        const settings = createElement('section', { id: 'spud-settings', 'aria-hidden': 'true' }, `
            <div class="spud-panel-head">
                <div>
                    <h2 class="spud-panel-title">SpudCode 设置</h2>
                    <div class="spud-panel-note">所有设置仅保存在当前浏览器中。</div>
                </div>
                <button class="spud-icon-btn" id="spud-close-settings" type="button">×</button>
            </div>
            <div class="spud-settings-body">
                ${settingRow('enabled', '启用土豆主题', '关闭后刷新并恢复 Codeforces 原始样式,左下角仍可重新开启。')}
                <div class="spud-setting-row">
                    <div><div class="spud-setting-name">颜色主题</div><div class="spud-setting-desc">自动跟随系统,或固定使用浅色/深色。</div></div>
                    <select class="spud-select" id="spud-setting-theme">
                        <option value="auto">跟随系统</option>
                        <option value="light">浅色土豆</option>
                        <option value="dark">地下机房</option>
                    </select>
                </div>
                ${settingRow('petEnabled', '显示土豆宠物', '可拖动、互动,并对评测结果作出反应。')}
                ${settingRow('requestMeter', '请求土豆消耗', '根据真实加载耗时,生成虚构的土豆消耗量。')}
                ${settingRow('statusCenter', '土豆机房状态', '显示虚构的总量、工作状态和传送带日志。')}
                ${settingRow('verdictEffects', '评测结果动画', 'AC、WA、TLE 等结果出现时让宠物作出反应。')}
                ${settingRow('tipsEnabled', '土豆提示', '偶尔给出简短但不打扰的写题提示。')}
                ${settingRow('achievements', '本地成就', '记录访问、连续 WA、WA 后 AC 等轻量成就。')}
                ${settingRow('gentleAnimations', '轻柔动画', '关闭后减少宠物与面板的动态效果。')}
                <div class="spud-settings-actions">
                    <button class="spud-btn" id="spud-reset-data" type="button">清除记录</button>
                    <button class="spud-btn primary" id="spud-save-settings" type="button">保存并关闭</button>
                </div>
            </div>
        `);

        const petWrap = createElement('div', { id: 'spud-pet-wrap', title: '点击互动,拖动改变位置' }, `
            <div id="spud-pet-bubble"></div>
            <div id="spud-pet-menu">
                <button class="spud-pet-action" data-action="pet">🤚 摸摸土豆</button>
                <button class="spud-pet-action" data-action="feed">🍟 喂一块薯片</button>
                <button class="spud-pet-action" data-action="work">⛑ 让它工作</button>
                <button class="spud-pet-action" data-action="sleep">💤 让它睡觉</button>
                <button class="spud-pet-action" data-action="status">📋 查看状态</button>
                <button class="spud-pet-action" data-action="hide">🙈 暂时隐藏</button>
            </div>
            <div id="spud-pet">
                <span class="spud-crown"></span>
                <span class="spud-sprout"></span>
                <span class="spud-eye left"></span>
                <span class="spud-eye right"></span>
                <span class="spud-cheek left"></span>
                <span class="spud-cheek right"></span>
                <span class="spud-mouth"></span>
                <span class="spud-arm left"></span>
                <span class="spud-arm right"></span>
            </div>
        `);

        document.body.append(progress, dock, overlay, panel, settings, petWrap, toastStack, confetti, focusPill, disabledTab);
        bindUI();
        applyAllSettings();
        updateDock();
        updateStatusPanel(true);
        restorePetPosition();
        initPetDrag();
        initScrollProgress();
    }

    function settingRow(key, name, desc) {
        return `
            <div class="spud-setting-row">
                <div><div class="spud-setting-name">${name}</div><div class="spud-setting-desc">${desc}</div></div>
                <button class="spud-switch" id="spud-setting-${key}" data-setting="${key}" type="button" role="switch"></button>
            </div>`;
    }

    function bindUI() {
        document.getElementById('spud-open-status')?.addEventListener('click', openStatusPanel);
        document.getElementById('spud-close-status')?.addEventListener('click', closeStatusPanel);
        document.getElementById('spud-open-settings')?.addEventListener('click', openSettings);
        document.getElementById('spud-close-settings')?.addEventListener('click', closeSettings);
        document.getElementById('spud-save-settings')?.addEventListener('click', () => {
            const enabledChanged = applySettingsFromControls();
            closeSettings();
            showToast('设置已保存', enabledChanged ? '正在重新加载,以完整切换主题状态。' : '土豆机房已按照新配置重新排班。', 'success');
            if (enabledChanged) setTimeout(() => location.reload(), 260);
        });
        document.getElementById('spud-disabled-tab')?.addEventListener('click', () => {
            store.enabled = true;
            saveStore();
            location.reload();
        });
        document.getElementById('spud-theme-toggle')?.addEventListener('click', quickToggleTheme);
        document.getElementById('spud-focus-toggle')?.addEventListener('click', toggleFocusMode);
        document.getElementById('spud-focus-pill')?.addEventListener('click', toggleFocusMode);
        document.getElementById('spud-refresh-workers')?.addEventListener('click', () => updateStatusPanel(true));
        document.getElementById('spud-overlay')?.addEventListener('click', closeAllPanels);
        document.getElementById('spud-reset-data')?.addEventListener('click', resetLocalData);

        document.querySelectorAll('.spud-switch[data-setting]').forEach((button) => {
            button.addEventListener('click', () => {
                button.classList.toggle('on');
                button.setAttribute('aria-checked', String(button.classList.contains('on')));
            });
        });

        document.querySelectorAll('.spud-pet-action').forEach((button) => {
            button.addEventListener('click', (event) => {
                event.stopPropagation();
                handlePetAction(button.dataset.action);
            });
        });

        document.addEventListener('keydown', handleKeyboardShortcuts);
        document.addEventListener('click', (event) => {
            const petWrap = document.getElementById('spud-pet-wrap');
            if (session.petMenuOpen && petWrap && !petWrap.contains(event.target)) closePetMenu();
        });

        if (window.matchMedia) {
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener?.('change', () => {
                if (store.theme === 'auto') applyTheme();
            });
        }
    }

    function applyAllSettings() {
        document.documentElement.classList.toggle('spudcode-active', Boolean(store.enabled));
        document.documentElement.classList.toggle('spud-focus', Boolean(store.focusMode && store.enabled));
        applyTheme();

        const petWrap = document.getElementById('spud-pet-wrap');
        petWrap?.classList.toggle('hidden', !store.petEnabled || !store.enabled);
        petWrap?.classList.toggle('has-crown', Boolean(store.crown));
        petWrap?.classList.toggle('night', new Date().getHours() >= 22 || new Date().getHours() <= 5);

        document.documentElement.style.setProperty('--spud-motion-scale', store.gentleAnimations ? '1' : '0');
        if (!store.gentleAnimations) {
            document.documentElement.classList.add('spud-reduced-motion');
        } else {
            document.documentElement.classList.remove('spud-reduced-motion');
        }

        const statusButton = document.getElementById('spud-open-status');
        if (statusButton) statusButton.style.display = store.statusCenter ? '' : 'none';
        updateDock();
    }

    function applyTheme() {
        document.documentElement.dataset.spudTheme = resolvedTheme();
        updateThemeButton();
    }

    function updateThemeButton() {
        const button = document.getElementById('spud-theme-toggle');
        if (!button) return;
        const theme = resolvedTheme();
        button.textContent = theme === 'dark' ? '☀' : '☾';
        button.title = theme === 'dark' ? '切换到浅色土豆' : '切换到地下机房';
    }

    function quickToggleTheme() {
        store.theme = resolvedTheme() === 'dark' ? 'light' : 'dark';
        scheduleSave();
        applyTheme();
        showToast('主题已切换', store.theme === 'dark' ? '进入地下土豆机房。' : '回到阳光土豆农场。');
    }

    function populateSettings() {
        document.querySelectorAll('.spud-switch[data-setting]').forEach((button) => {
            const key = button.dataset.setting;
            button.classList.toggle('on', Boolean(store[key]));
            button.setAttribute('aria-checked', String(Boolean(store[key])));
        });
        const themeSelect = document.getElementById('spud-setting-theme');
        if (themeSelect) themeSelect.value = store.theme;
    }

    function applySettingsFromControls() {
        const previousEnabled = store.enabled;
        document.querySelectorAll('.spud-switch[data-setting]').forEach((button) => {
            store[button.dataset.setting] = button.classList.contains('on');
        });
        store.theme = document.getElementById('spud-setting-theme')?.value || 'auto';
        scheduleSave();
        applyAllSettings();
        return previousEnabled !== store.enabled;
    }

    function openStatusPanel() {
        if (!store.statusCenter) return;
        closeSettings();
        session.panelOpen = true;
        document.getElementById('spud-status-panel')?.classList.add('visible');
        document.getElementById('spud-status-panel')?.setAttribute('aria-hidden', 'false');
        document.getElementById('spud-overlay')?.classList.add('visible');
        updateStatusPanel(true);
    }

    function closeStatusPanel() {
        session.panelOpen = false;
        document.getElementById('spud-status-panel')?.classList.remove('visible');
        document.getElementById('spud-status-panel')?.setAttribute('aria-hidden', 'true');
        if (!session.settingsOpen) document.getElementById('spud-overlay')?.classList.remove('visible');
    }

    function openSettings() {
        closeStatusPanel();
        populateSettings();
        session.settingsOpen = true;
        document.getElementById('spud-settings')?.classList.add('visible');
        document.getElementById('spud-settings')?.setAttribute('aria-hidden', 'false');
        document.getElementById('spud-overlay')?.classList.add('visible');
    }

    function closeSettings() {
        session.settingsOpen = false;
        document.getElementById('spud-settings')?.classList.remove('visible');
        document.getElementById('spud-settings')?.setAttribute('aria-hidden', 'true');
        if (!session.panelOpen) document.getElementById('spud-overlay')?.classList.remove('visible');
    }

    function closeAllPanels() {
        closeStatusPanel();
        closeSettings();
        closePetMenu();
    }

    function resetLocalData() {
        const keepTheme = store.theme;
        const keepEnabled = store.enabled;
        store = { ...DEFAULTS, theme: keepTheme, enabled: keepEnabled, reserve: randomInt(136, 168) };
        session.requestCount = 0;
        session.potatoesUsed = 0;
        saveStore();
        populateSettings();
        applyAllSettings();
        restorePetPosition(true);
        updateStatusPanel(true);
        showToast('记录已清除', '土豆们集体失忆,但主题设置被保留。');
    }

    function toggleFocusMode() {
        store.focusMode = !store.focusMode;
        scheduleSave();
        document.documentElement.classList.toggle('spud-focus', store.focusMode && store.enabled);
        showToast(store.focusMode ? '专注模式已开启' : '专注模式已关闭', store.focusMode ? '只保留题目与必要内容。按 Alt+P 退出。' : '侧栏和土豆已恢复。');
    }

    function handleKeyboardShortcuts(event) {
        if (event.altKey && event.key.toLowerCase() === 'p') {
            event.preventDefault();
            toggleFocusMode();
        }
        if (event.altKey && event.key.toLowerCase() === 's') {
            event.preventDefault();
            session.panelOpen ? closeStatusPanel() : openStatusPanel();
        }
        if (event.key === 'Escape') closeAllPanels();

        handleKonami(event.key);
    }

    /* --------------------------- 状态中心 --------------------------- */

    function buildStatusSnapshot() {
        const total = store.reserve;
        const active = clamp(Math.round(total * (0.54 + Math.random() * 0.12)), 1, total);
        const sprouting = randomInt(7, 16);
        const moldy = randomInt(1, 4);
        const sleeping = clamp(total - active - sprouting - moldy, 0, total);
        const judging = clamp(Math.round(active * (0.28 + Math.random() * 0.13)), 2, active);
        const hauling = clamp(Math.round(active * (0.18 + Math.random() * 0.12)), 1, active);
        const running = clamp(active - judging - hauling, 0, active);
        return { total, active, sprouting, moldy, sleeping, judging, hauling, running };
    }

    function buildWorkers(count = 7) {
        const used = new Set();
        const workers = [];
        while (workers.length < count) {
            const id = randomInt(1, store.reserve);
            if (used.has(id)) continue;
            used.add(id);
            const [status, task, icon] = pick(STATUS_TEXTS);
            workers.push({
                id,
                status,
                task,
                icon,
                temp: randomInt(21, 31),
                mood: pick(['稳定', '自信', '认真', '略困', '非常兴奋', '想吃薯片'])
            });
        }
        return workers;
    }

    function updateStatusPanel(forceWorkers = false) {
        const grid = document.getElementById('spud-stat-grid');
        const workerList = document.getElementById('spud-worker-list');
        const log = document.getElementById('spud-log');
        if (!grid || !workerList || !log) return;

        const snapshot = buildStatusSnapshot();
        grid.innerHTML = [
            ['土豆总量', snapshot.total, '个'],
            ['当前活跃', snapshot.active, '个'],
            ['正在评测', snapshot.judging, '个'],
            ['搬运数据', snapshot.hauling, '个'],
            ['正在发芽', snapshot.sprouting, '个'],
            ['轻微发霉', snapshot.moldy, '个'],
            ['本页消耗', formatNumber(session.potatoesUsed, 2), '个'],
            ['请求次数', session.requestCount, '次']
        ].map(([label, value, unit]) => `
            <div class="spud-stat-card">
                <div class="spud-stat-label">${label}</div>
                <div class="spud-stat-value">${value}<span class="spud-stat-unit">${unit}</span></div>
            </div>`).join('');

        if (forceWorkers || !workerList.children.length) {
            workerList.innerHTML = buildWorkers().map((worker) => `
                <div class="spud-worker">
                    <div class="spud-worker-icon">${worker.icon}</div>
                    <div>
                        <div class="spud-worker-name">土豆 #${String(worker.id).padStart(3, '0')} · ${worker.status}</div>
                        <div class="spud-worker-task">${worker.task} · 心情:${worker.mood}</div>
                    </div>
                    <div class="spud-worker-temp">${worker.temp}℃</div>
                </div>`).join('');
        }

        const logLines = Array.from({ length: 9 }, () => {
            const id = String(randomInt(1, store.reserve)).padStart(3, '0');
            const text = pick(LOG_MESSAGES).replace('{id}', id);
            return `<div class="spud-log-line"><span class="time">${nowTime()}</span> ${escapeHTML(text)}</div>`;
        });
        if (session.lastRequestMs > 0) {
            logLines.unshift(`<div class="spud-log-line"><span class="time">${nowTime()}</span> 最近请求:${escapeHTML(session.lastRequestLabel)},耗时 ${Math.round(session.lastRequestMs)}ms,使用 ${formatNumber(session.lastRequestPotatoes, 2)} 个土豆。</div>`);
        }
        log.innerHTML = logLines.join('');
        document.getElementById('spud-shift-label').textContent = `第 ${Math.floor(Date.now() / 3600000) % 6 + 1} 班`;
    }

    function updateDock() {
        const main = document.getElementById('spud-dock-main');
        const sub = document.getElementById('spud-dock-sub');
        if (!main || !sub) return;
        main.textContent = `土豆储备 ${store.reserve} · 活跃 ${Math.max(1, Math.round(store.reserve * .62))}`;
        if (!store.requestMeter) {
            sub.textContent = '请求计量已关闭';
        } else if (session.requestCount === 0) {
            sub.textContent = '正在等待第一个请求';
        } else {
            sub.textContent = `最近 ${formatNumber(session.lastRequestPotatoes, 2)} 个 / ${Math.round(session.lastRequestMs)}ms · 本页 ${formatNumber(session.potatoesUsed, 2)} 个`;
        }
    }

    /* --------------------------- 品牌替换与页面增强 --------------------------- */

    const PROTECTED_SELECTOR = [
        '.problem-statement', 'pre', 'code', 'textarea', 'input', 'select', 'option',
        'script', 'style', 'noscript', '.ttypography', '.source', '.program-source',
        '.input', '.output', '.note', '.tutorial', '.spoiler-content', '[contenteditable="true"]',
        '#spud-status-panel', '#spud-settings', '#spud-dock', '#spud-pet-wrap', '#spud-toast-stack'
    ].join(',');

    function isProtectedNode(node) {
        const parent = node.nodeType === Node.TEXT_NODE ? node.parentElement : node;
        return !parent || Boolean(parent.closest(PROTECTED_SELECTOR));
    }

    function replaceBrandText(text, mode = 'body') {
        if (!text || !/Codeforces/i.test(text)) return text;
        if (mode === 'title') return text.replace(/Codeforces/gi, 'CodePotato');
        let output = text;
        for (const item of BRAND_REPLACEMENTS) output = output.replace(item.from, item.to);
        return output;
    }

    function replaceBranding(root = document.body) {
        if (!root || session.brandMutationLock) return;
        session.brandMutationLock = true;
        try {
            document.title = replaceBrandText(document.title, 'title');
            const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
                acceptNode(node) {
                    if (isProtectedNode(node)) return NodeFilter.FILTER_REJECT;
                    return /Codeforces/i.test(node.nodeValue || '') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
                }
            });
            const nodes = [];
            while (walker.nextNode()) nodes.push(walker.currentNode);
            for (const node of nodes) node.nodeValue = replaceBrandText(node.nodeValue);
        } finally {
            session.brandMutationLock = false;
        }
    }

    function installBrandLogo() {
        if (document.getElementById('spud-brand-logo')) return;
        const logoContainer = document.querySelector('#header .logo');
        if (!logoContainer) return;
        const anchor = logoContainer.querySelector('a') || logoContainer;
        logoContainer.querySelectorAll('img').forEach((img) => { img.style.display = 'none'; });
        const oldText = anchor.textContent;
        if (oldText && /Codeforces/i.test(oldText)) anchor.textContent = '';

        const logo = createElement('span', { id: 'spud-brand-logo' }, `
            <span class="spud-logo-mark"></span>
            <span><span class="spud-logo-code">SpudCode</span><small class="spud-logo-sub">Potato powered judge</small></span>
        `);
        anchor.appendChild(logo);

        let clickTimes = [];
        anchor.addEventListener('click', (event) => {
            // 只在点击土豆图标时计入彩蛋;点击文字仍正常返回首页。
            if (!event.target.closest('.spud-logo-mark')) return;
            event.preventDefault();
            const now = Date.now();
            clickTimes = clickTimes.filter((time) => now - time < 2200);
            clickTimes.push(now);
            if (clickTimes.length >= 5) {
                clickTimes = [];
                triggerPotatoStampede();
            } else {
                const mark = event.target.closest('.spud-logo-mark');
                mark?.animate?.([
                    { transform: 'rotate(-5deg) scale(1)' },
                    { transform: 'rotate(8deg) scale(1.12)' },
                    { transform: 'rotate(-5deg) scale(1)' }
                ], { duration: 260, easing: 'ease-out' });
            }
        });
    }

    function installFavicon() {
        if (document.querySelector('link[data-spud-favicon]')) return;
        const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="15" fill="#f6ead7"/><path d="M17 41C10 29 18 14 33 13c15-1 23 11 17 26-5 13-25 16-33 2Z" fill="#bd793f"/><circle cx="27" cy="30" r="2.4" fill="#493024"/><circle cx="40" cy="29" r="2.4" fill="#493024"/><path d="M28 38c4 3 8 3 12-1" fill="none" stroke="#493024" stroke-width="2.5" stroke-linecap="round"/><path d="M33 15c-1-8 4-10 7-11M36 12c5-5 10-3 12-1" fill="none" stroke="#5d8f57" stroke-width="3" stroke-linecap="round"/></svg>`;
        const link = createElement('link', { rel: 'icon', href: `data:image/svg+xml,${encodeURIComponent(svg)}`, 'data-spud-favicon': '1' });
        document.head.appendChild(link);
    }

    function enhanceSamples(root = document) {
        root.querySelectorAll('.sample-test .input, .sample-test .output').forEach((block) => {
            if (block.dataset.spudEnhanced) return;
            block.dataset.spudEnhanced = '1';
            const pre = block.querySelector('pre');
            if (!pre) return;
            const label = block.classList.contains('input') ? '输入' : '输出';
            const actions = createElement('div', { class: 'spud-sample-actions' });
            const button = createElement('button', { class: 'spud-copy-btn', type: 'button' }, `复制${label}`);
            button.addEventListener('click', async () => {
                const text = extractPreText(pre);
                const ok = await copyText(text);
                button.textContent = ok ? '已装进麻袋' : '复制失败';
                if (ok) {
                    petSay('土豆已经把样例装进麻袋。', 2200);
                    unlockAchievement('sample_bag', '样例装袋员', '第一次使用土豆复制样例。');
                }
                setTimeout(() => { button.textContent = `复制${label}`; }, 1700);
            });
            actions.appendChild(button);
            block.appendChild(actions);
        });

        const sampleTest = root.querySelector('.sample-test');
        if (sampleTest && !sampleTest.dataset.spudAllCopy) {
            sampleTest.dataset.spudAllCopy = '1';
            const sectionTitle = sampleTest.querySelector('.section-title');
            if (sectionTitle) {
                const allButton = createElement('button', { class: 'spud-copy-btn', type: 'button', style: 'margin-left:8px;vertical-align:middle;' }, '全部复制');
                allButton.addEventListener('click', async () => {
                    const chunks = [...sampleTest.querySelectorAll('.input, .output')].map((block, index) => {
                        const type = block.classList.contains('input') ? 'Input' : 'Output';
                        return `${type} ${Math.floor(index / 2) + 1}:\n${extractPreText(block.querySelector('pre'))}`;
                    });
                    const ok = await copyText(chunks.join('\n\n'));
                    showToast(ok ? '样例已全部复制' : '复制失败', ok ? '输入和输出已经整齐装袋。' : '浏览器拒绝了剪贴板请求。', ok ? 'success' : 'warn');
                });
                sectionTitle.appendChild(allButton);
            }
        }
    }

    function extractPreText(pre) {
        if (!pre) return '';
        const rendered = typeof pre.innerText === 'string' ? pre.innerText : pre.textContent;
        return String(rendered || '').replace(/\u00a0/g, ' ').replace(/\r\n/g, '\n').trim();
    }

    async function copyText(text) {
        try {
            await navigator.clipboard.writeText(text);
            return true;
        } catch (_) {
            try {
                const area = createElement('textarea');
                area.value = text;
                area.style.position = 'fixed';
                area.style.opacity = '0';
                document.body.appendChild(area);
                area.select();
                const ok = document.execCommand('copy');
                area.remove();
                return ok;
            } catch (_) {
                return false;
            }
        }
    }

    function classifyVerdict(text) {
        const t = String(text || '').trim().toLowerCase();
        if (!t) return null;
        if (t === 'accepted' || /\baccepted\b/.test(t)) return 'ac';
        if (/wrong answer|presentation error|failed/.test(t)) return 'wa';
        if (/time limit exceeded|idleness limit exceeded/.test(t)) return 'tle';
        if (/memory limit exceeded/.test(t)) return 'mle';
        if (/compilation error/.test(t)) return 'ce';
        if (/runtime error|security violated/.test(t)) return 're';
        if (/running|in queue|testing|judging/.test(t)) return 'run';
        return null;
    }

    function enhanceVerdicts(root = document) {
        const selector = '.verdict-accepted, .verdict-rejected, .status-small, [class*="verdict"], td';
        const candidates = [];
        if (root instanceof Element && root.matches(selector)) candidates.push(root);
        if (root.querySelectorAll) candidates.push(...root.querySelectorAll(selector));

        candidates.forEach((element) => {
            const type = classifyVerdict(element.textContent);
            if (!type) return;
            const previousType = element.dataset.spudVerdictType || '';
            if (previousType === type) return;
            ['ac', 'wa', 'tle', 'mle', 'ce', 're', 'run'].forEach((item) => element.classList.remove(`spud-verdict-${item}`));
            element.dataset.spudVerdictType = type;
            element.classList.add(`spud-verdict-${type}`);

            const row = element.closest('tr');
            if (type === 'run' && row) row.dataset.spudHadRunning = '1';
            const isFinal = ['ac', 'wa', 'tle', 'mle', 'ce', 're'].includes(type);
            const isSubmissionPage = /\/submission\/\d+/.test(location.pathname);
            const changedFromRunning = previousType === 'run' || row?.dataset.spudHadRunning === '1';
            const key = `${type}|${element.textContent.trim()}|${location.pathname}`;
            if (isFinal && (isSubmissionPage || changedFromRunning) && key !== session.lastVerdictKey) {
                session.lastVerdictKey = key;
                if (row) delete row.dataset.spudHadRunning;
                reactToVerdict(type);
            }
        });
    }

    function reactToVerdict(type) {
        if (!store.verdictEffects) return;
        const reactions = {
            ac: { cls: 'celebrate', line: pick(PET_LINES.ac), toast: ['Accepted', '全体土豆批准通过。'], confetti: true },
            wa: { cls: 'sad', line: pick(PET_LINES.wa), toast: ['Wrong Answer', '先找最小反例,再决定要不要重写。'] },
            tle: { cls: 'running', line: pick(PET_LINES.tle), toast: ['Time Limit Exceeded', '土豆已经开始原地狂奔。'] },
            mle: { cls: 'sad', line: pick(PET_LINES.mle), toast: ['Memory Limit Exceeded', '内存仓库被麻袋塞满了。'] },
            ce: { cls: 'smoking', line: pick(PET_LINES.ce), toast: ['Compilation Error', '先处理第一条编译错误。'] },
            re: { cls: 'smoking', line: pick(PET_LINES.re), toast: ['Runtime Error', '检查下标、除零和空容器。'] }
        };
        const info = reactions[type];
        if (!info) return;
        petAnimate(info.cls, 3000);
        petSay(info.line, 3900);
        showToast(info.toast[0], info.toast[1], type === 'ac' ? 'success' : 'warn');
        if (info.confetti) potatoConfetti();

        trackVerdictAchievement(type);
    }

    let verdictHistory = [];
    function trackVerdictAchievement(type) {
        verdictHistory.push({ type, at: Date.now() });
        verdictHistory = verdictHistory.filter((item) => Date.now() - item.at < 6 * 60 * 60 * 1000).slice(-8);
        if (!store.achievements) return;
        const lastThree = verdictHistory.slice(-3);
        if (lastThree.length === 3 && lastThree.every((item) => item.type === 'wa')) {
            unlockAchievement('triple_wa', '土豆抗压训练', '连续遇到 3 次 Wrong Answer。');
        }
        if (type === 'ac' && verdictHistory.slice(0, -1).some((item) => item.type === 'wa')) {
            unlockAchievement('wa_to_ac', '土豆翻身', '成功把 Wrong Answer 改成 Accepted。');
        }
    }

    function initMutationObserver() {
        const observer = new MutationObserver((mutations) => {
            if (session.brandMutationLock) return;
            for (const mutation of mutations) {
                const targetElement = mutation.target.nodeType === Node.ELEMENT_NODE
                    ? mutation.target
                    : mutation.target.parentElement;
                if (targetElement) {
                    replaceBranding(targetElement);
                    enhanceVerdicts(targetElement);
                }

                for (const node of mutation.addedNodes || []) {
                    if (node.nodeType !== Node.ELEMENT_NODE) continue;
                    replaceBranding(node);
                    enhanceSamples(node);
                    enhanceVerdicts(node);
                }
            }
            installBrandLogo();
        });
        observer.observe(document.body, { childList: true, characterData: true, subtree: true });
    }

    /* --------------------------- 宠物 --------------------------- */

    let bubbleTimer = null;

    function petSay(text, duration = 2800) {
        if (!store.petEnabled || !store.enabled) return;
        const bubble = document.getElementById('spud-pet-bubble');
        if (!bubble) return;
        bubble.textContent = text;
        bubble.classList.add('visible');
        clearTimeout(bubbleTimer);
        bubbleTimer = setTimeout(() => bubble.classList.remove('visible'), duration);
    }

    function petAnimate(className, duration = 1800) {
        const wrap = document.getElementById('spud-pet-wrap');
        if (!wrap) return;
        ['working', 'celebrate', 'sad', 'running', 'sleeping', 'smoking'].forEach((cls) => wrap.classList.remove(cls));
        wrap.classList.add(className);
        setTimeout(() => wrap.classList.remove(className), duration);
    }

    function openPetMenu() {
        const menu = document.getElementById('spud-pet-menu');
        if (!menu) return;
        session.petMenuOpen = true;
        menu.classList.add('visible');
    }

    function closePetMenu() {
        session.petMenuOpen = false;
        document.getElementById('spud-pet-menu')?.classList.remove('visible');
    }

    function handlePetAction(action) {
        closePetMenu();
        switch (action) {
            case 'pet':
                store.petMood = clamp(store.petMood + 8, 0, 100);
                store.petExp += 2;
                petAnimate('celebrate', 900);
                petSay(pick(PET_LINES.pet));
                break;
            case 'feed':
                store.petFood = clamp(store.petFood + 18, 0, 100);
                store.petMood = clamp(store.petMood + 4, 0, 100);
                store.petExp += 3;
                petSay(pick(PET_LINES.feed));
                break;
            case 'work':
                store.petEnergy = clamp(store.petEnergy - 9, 0, 100);
                store.petExp += 5;
                petAnimate('working', 2600);
                petSay(pick(PET_LINES.work));
                break;
            case 'sleep':
                store.petEnergy = clamp(store.petEnergy + 16, 0, 100);
                petAnimate('sleeping', 4200);
                petSay(pick(PET_LINES.sleep), 3400);
                break;
            case 'status':
                petSay(`心情 ${store.petMood} · 精力 ${store.petEnergy} · 饱食 ${store.petFood} · 等级 ${store.petLevel}`, 4300);
                break;
            case 'hide':
                store.petEnabled = false;
                document.getElementById('spud-pet-wrap')?.classList.add('hidden');
                showToast('宠物已隐藏', '在设置中可以重新叫回土豆。');
                break;
            default:
                return;
        }

        while (store.petExp >= store.petLevel * 20) {
            store.petExp -= store.petLevel * 20;
            store.petLevel += 1;
            unlockAchievement(`pet_level_${store.petLevel}`, `土豆升到 ${store.petLevel} 级`, '它看起来没有更聪明,但更有经验了。');
        }
        scheduleSave();
    }

    function initPetDrag() {
        const wrap = document.getElementById('spud-pet-wrap');
        if (!wrap || wrap.dataset.dragReady) return;
        wrap.dataset.dragReady = '1';

        let dragging = false;
        let moved = false;
        let startX = 0;
        let startY = 0;
        let startLeft = 0;
        let startTop = 0;

        wrap.addEventListener('pointerdown', (event) => {
            if (event.button !== 0 || event.target.closest('.spud-pet-action')) return;
            dragging = true;
            moved = false;
            startX = event.clientX;
            startY = event.clientY;
            const rect = wrap.getBoundingClientRect();
            startLeft = rect.left;
            startTop = rect.top;
            wrap.setPointerCapture(event.pointerId);
            wrap.classList.add('dragging');
        });

        wrap.addEventListener('pointermove', (event) => {
            if (!dragging) return;
            const dx = event.clientX - startX;
            const dy = event.clientY - startY;
            if (Math.abs(dx) + Math.abs(dy) > 5) moved = true;
            const left = clamp(startLeft + dx, 4, window.innerWidth - wrap.offsetWidth - 4);
            const top = clamp(startTop + dy, 4, window.innerHeight - wrap.offsetHeight - 4);
            wrap.style.left = `${left}px`;
            wrap.style.top = `${top}px`;
            wrap.style.right = 'auto';
            wrap.style.bottom = 'auto';
        });

        wrap.addEventListener('pointerup', (event) => {
            if (!dragging) return;
            dragging = false;
            wrap.classList.remove('dragging');
            try { wrap.releasePointerCapture(event.pointerId); } catch (_) {}
            if (moved) {
                const rect = wrap.getBoundingClientRect();
                store.petX = Math.round(rect.left);
                store.petY = Math.round(rect.top);
                scheduleSave();
            } else {
                session.petMenuOpen ? closePetMenu() : openPetMenu();
            }
        });

        wrap.addEventListener('dblclick', () => {
            store.petX = null;
            store.petY = null;
            scheduleSave();
            restorePetPosition(true);
            petSay('已滚回默认位置。');
        });

        window.addEventListener('resize', () => restorePetPosition(false));
    }

    function restorePetPosition(forceDefault = false) {
        const wrap = document.getElementById('spud-pet-wrap');
        if (!wrap) return;
        if (forceDefault || store.petX === null || store.petY === null) {
            wrap.style.left = '';
            wrap.style.top = '';
            wrap.style.right = '';
            wrap.style.bottom = '';
            return;
        }
        const left = clamp(store.petX, 4, Math.max(4, window.innerWidth - wrap.offsetWidth - 4));
        const top = clamp(store.petY, 4, Math.max(4, window.innerHeight - wrap.offsetHeight - 4));
        wrap.style.left = `${left}px`;
        wrap.style.top = `${top}px`;
        wrap.style.right = 'auto';
        wrap.style.bottom = 'auto';
    }

    function startPetHeartbeat() {
        clearInterval(session.heartbeatTimer);
        session.heartbeatTimer = setInterval(() => {
            if (!store.petEnabled || !store.enabled) return;
            store.petFood = clamp(store.petFood - .15, 0, 100);
            store.petEnergy = clamp(store.petEnergy - .08, 0, 100);
            scheduleSave();

            if (store.tipsEnabled && Date.now() - session.lastTipAt > 8 * 60 * 1000 && Math.random() < .16) {
                session.lastTipAt = Date.now();
                petSay(pageSpecificTip(), 4200);
            }
        }, 60000);
    }

    function pageSpecificTip() {
        const path = location.pathname;
        if (/submit/.test(path)) return '提交前扫一眼:数组范围、初始化、多测清空。';
        if (/status|submissions/.test(path)) return '先看 verdict,再看第几个测试点,不要立刻推翻整个思路。';
        if (/standings/.test(path)) return '排行榜不会帮你 AC,先把当前题做完。';
        if (/problem/.test(path)) return pick([
            '限制条件不是装饰,它通常在暗示复杂度。',
            '把样例推一遍,确认每个变量到底代表什么。',
            '先写清楚一轮循环做了什么,再动代码。'
        ]);
        return pick(PET_LINES.idle);
    }

    /* --------------------------- 成就、彩蛋、通知 --------------------------- */

    function showToast(title, text, type = '') {
        const stack = document.getElementById('spud-toast-stack');
        if (!stack) return;
        const icon = type === 'success' ? '🌱' : type === 'warn' ? '🥔' : '📌';
        const toast = createElement('div', { class: `spud-toast ${type}` }, `
            <div class="spud-toast-icon">${icon}</div>
            <div><div class="spud-toast-title">${escapeHTML(title)}</div><div class="spud-toast-text">${escapeHTML(text)}</div></div>
        `);
        stack.appendChild(toast);
        setTimeout(() => {
            toast.style.animation = 'spud-toast-out .2s ease forwards';
            setTimeout(() => toast.remove(), 220);
        }, 3800);
    }

    function unlockAchievement(id, title, desc) {
        if (!store.achievements || store.unlocked[id]) return;
        store.unlocked[id] = Date.now();
        scheduleSave();
        showToast(`成就解锁:${title}`, desc, 'success');
    }

    function checkVisitAchievements() {
        unlockAchievement('first_visit', '第一颗土豆', '第一次进入 SpudCode。');
        if (store.visits >= 5) unlockAchievement('five_visits', '熟练农场主', '累计访问 SpudCode 5 次。');
        const hour = new Date().getHours();
        if (hour >= 0 && hour <= 5) unlockAchievement('late_night', '深夜淀粉', '凌晨仍然在写题。');
    }

    function potatoConfetti(count = 34) {
        const layer = document.getElementById('spud-confetti');
        if (!layer || !store.gentleAnimations) return;
        const glyphs = ['🥔', '🌱', '✦', '·'];
        for (let i = 0; i < count; i++) {
            const piece = createElement('span', { class: 'spud-confetti-piece' }, pick(glyphs));
            piece.style.left = `${Math.random() * 100}vw`;
            piece.style.setProperty('--fall-time', `${2.4 + Math.random() * 2.2}s`);
            piece.style.setProperty('--drift', `${-90 + Math.random() * 180}px`);
            piece.style.setProperty('--spin', `${-360 + Math.random() * 720}deg`);
            piece.style.animationDelay = `${Math.random() * .55}s`;
            layer.appendChild(piece);
            setTimeout(() => piece.remove(), 5300);
        }
    }

    function triggerPotatoStampede() {
        if (session.logoBurstLock) return;
        session.logoBurstLock = true;
        showToast('土豆紧急出动', '你连续点击了 SpudCode 标志。', 'success');
        const layer = document.getElementById('spud-confetti');
        if (!layer) return;
        for (let i = 0; i < 18; i++) {
            const runner = createElement('span', {}, '🥔');
            Object.assign(runner.style, {
                position: 'fixed', left: '-40px', bottom: `${8 + Math.random() * 55}px`,
                zIndex: '2147483050', fontSize: `${18 + Math.random() * 18}px`,
                transition: `transform ${2.1 + Math.random() * 1.2}s linear`,
                transitionDelay: `${Math.random() * .8}s`, transform: 'translateX(0) rotate(0deg)'
            });
            layer.appendChild(runner);
            requestAnimationFrame(() => { runner.style.transform = `translateX(${window.innerWidth + 100}px) rotate(${720 + Math.random() * 900}deg)`; });
            setTimeout(() => runner.remove(), 4300);
        }
        setTimeout(() => { session.logoBurstLock = false; }, 4500);
    }

    const konami = ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight', 'b', 'a'];
    let konamiIndex = 0;
    function handleKonami(key) {
        const normalized = key.length === 1 ? key.toLowerCase() : key;
        if (normalized === konami[konamiIndex]) {
            konamiIndex += 1;
            if (konamiIndex === konami.length) {
                konamiIndex = 0;
                store.crown = true;
                scheduleSave();
                document.getElementById('spud-pet-wrap')?.classList.add('has-crown');
                potatoConfetti(52);
                petSay('黄金土豆王冠已装备。', 4300);
                unlockAchievement('golden_crown', '黄金土豆王', '成功输入隐藏指令。');
            }
        } else {
            konamiIndex = normalized === konami[0] ? 1 : 0;
        }
    }

    /* --------------------------- 滚动、初始化 --------------------------- */

    function initScrollProgress() {
        const bar = document.getElementById('spud-scroll-progress');
        if (!bar) return;
        let ticking = false;
        const update = () => {
            const max = document.documentElement.scrollHeight - window.innerHeight;
            const ratio = max > 0 ? clamp(window.scrollY / max, 0, 1) : 0;
            bar.style.width = `${ratio * 100}%`;
            ticking = false;
        };
        window.addEventListener('scroll', () => {
            if (!ticking) {
                ticking = true;
                requestAnimationFrame(update);
            }
        }, { passive: true });
        update();
    }

    function maybeShowWelcome() {
        if (store.visits === 1) {
            setTimeout(() => {
                showToast('SpudCode 已接管界面', `当前机房储备 ${store.reserve} 个土豆。所有状态均为娱乐模拟。`, 'success');
                petSay('你好,我是今天的值班土豆。点击我可以互动。', 5200);
            }, 900);
        } else if (store.tipsEnabled && Math.random() < .22) {
            setTimeout(() => petSay(pageSpecificTip(), 3600), 1400);
        }
    }

    function startStatusTicker() {
        clearInterval(session.statusTimer);
        session.statusTimer = setInterval(() => {
            if (session.panelOpen) updateStatusPanel(Math.random() < .35);
            updateDock();
        }, 5000);
    }

    function initialPagePass() {
        if (!store.enabled) return;
        installFavicon();
        installBrandLogo();
        replaceBranding(document.body);
        enhanceSamples(document);
        enhanceVerdicts(document);
        initMutationObserver();
        startStatusTicker();
        startPetHeartbeat();
        checkVisitAchievements();
        maybeShowWelcome();

        // 页面本身也算一次“开机任务”,这样首次打开立即有读数。
        setTimeout(() => {
            if (session.requestCount === 0) {
                recordRequest({ elapsed: performance.now() - SESSION_STARTED_AT, url: location.href, source: 'page' });
            }
        }, 850);
    }

    ready(() => {
        mountUI();
        initialPagePass();
    });
})();

原文