跳到正文

科技·工程

网站字体更换器

woshiyhr约 229 分钟
原文

这是 2026年6月6日 存档的第 7 版,不是当前版本。查看当前版本

文章信息与版本

配置异常简单,下载油猴插件,谷歌浏览器开fq或者下载安装包
点击油猴—>添加新脚本->ctrl+a再ctrl+v然后ctrl+s就行了

JavaScript
// ==UserScript==
// @name         BZOJ 增强工具 + 网页字体更换器
// @namespace    https://bzoj.org/
// @version      1.6.0
// @description  整合 BZOJ 测试点大方块(自动轮询、完成通知、亮暗模式适配)与全站网页字体更换器,BZOJ 功能仅在 bzoj.org 下激活
// @author       bzoj-enhancer & FontSwitcher
// @match        *://*/*
// @grant        GM_notification
// @grant        GM_addStyle
// @grant        GM_getValue
// @grant        GM_setValue
// @run-at       document-idle
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    // ================================================================
    //  模块一:BZOJ 测试点大方块(仅 bzoj.org 站点下运行)
    // ================================================================

    const BZOJ_TestcaseModule = {
        LIGHT_STATUS_MAP: {
            'accepted':              { bg: '#f6ffed', text: 'AC',  display: 'Accepted',              color: '#389e0d', border: '#b7eb8f' },
            'wrong answer':          { bg: '#fff2f0', text: 'WA',  display: 'Wrong Answer',          color: '#cf1322', border: '#ffccc7' },
            'time limit exceeded':   { bg: '#e6f7ff', text: 'TLE', display: 'Time Limit Exceeded',   color: '#0958d9', border: '#91d5ff' },
            'memory limit exceeded': { bg: '#e6f7ff', text: 'MLE', display: 'Memory Limit Exceeded', color: '#0958d9', border: '#91d5ff' },
            'runtime error':         { bg: '#f9f0ff', text: 'RE',  display: 'Runtime Error',         color: '#722ed1', border: '#d3adf7' },
            'compile error':         { bg: '#fffbe6', text: 'CE',  display: 'Compile Error',         color: '#d48806', border: '#ffe58f' },
            'output limit exceeded': { bg: '#e6f7ff', text: 'OLE', display: 'Output Limit Exceeded', color: '#0958d9', border: '#91d5ff' },
            'system error':          { bg: '#f5f5f5', text: 'SE',  display: 'System Error',          color: '#434343', border: '#d9d9d9' },
            'judging':               { bg: '#e6f7ff', text: '⟳',   display: 'Judging',               color: '#0958d9', border: '#91d5ff', spin: true },
            'compiling':             { bg: '#e6f7ff', text: '⟳',   display: 'Compiling',             color: '#0958d9', border: '#91d5ff', spin: true },
            'waiting':               { bg: '#e6f7ff', text: '⟳',   display: 'Waiting',               color: '#0958d9', border: '#91d5ff', spin: true },
            'running':               { bg: '#e6f7ff', text: '⟳',   display: 'Running',               color: '#0958d9', border: '#91d5ff', spin: true },
            'fetched':               { bg: '#fff7e6', text: 'FET', display: 'Fetched',               color: '#d46b08', border: '#ffd591' },
        },
        DARK_STATUS_MAP: {
            'accepted':              { bg: '#1e3a1e', text: 'AC',  display: 'Accepted',              color: '#95de64', border: '#389e0d' },
            'wrong answer':          { bg: '#3d1f22', text: 'WA',  display: 'Wrong Answer',          color: '#ff9c9c', border: '#a8071a' },
            'time limit exceeded':   { bg: '#1a2d42', text: 'TLE', display: 'Time Limit Exceeded',   color: '#69c0ff', border: '#003a8c' },
            'memory limit exceeded': { bg: '#1a2d42', text: 'MLE', display: 'Memory Limit Exceeded', color: '#69c0ff', border: '#003a8c' },
            'runtime error':         { bg: '#2d1f3d', text: 'RE',  display: 'Runtime Error',         color: '#c9a0f5', border: '#531dab' },
            'compile error':         { bg: '#3d321e', text: 'CE',  display: 'Compile Error',         color: '#ffd666', border: '#ad6800' },
            'output limit exceeded': { bg: '#1a2d42', text: 'OLE', display: 'Output Limit Exceeded', color: '#69c0ff', border: '#003a8c' },
            'system error':          { bg: '#2e2e2e', text: 'SE',  display: 'System Error',          color: '#d9d9d9', border: '#434343' },
            'judging':               { bg: '#1a2d42', text: '⟳',   display: 'Judging',               color: '#69c0ff', border: '#003a8c', spin: true },
            'compiling':             { bg: '#1a2d42', text: '⟳',   display: 'Compiling',             color: '#69c0ff', border: '#003a8c', spin: true },
            'waiting':               { bg: '#1a2d42', text: '⟳',   display: 'Waiting',               color: '#69c0ff', border: '#003a8c', spin: true },
            'running':               { bg: '#1a2d42', text: '⟳',   display: 'Running',               color: '#69c0ff', border: '#003a8c', spin: true },
            'fetched':               { bg: '#3d321e', text: 'FET', display: 'Fetched',               color: '#ffc069', border: '#ad4e00' },
        },

        ALIAS_MAP: {
            'time exceeded': 'time limit exceeded', 'memory exceeded': 'memory limit exceeded',
            'ac': 'accepted', 'wa': 'wrong answer', 'tle': 'time limit exceeded',
            'mle': 'memory limit exceeded', 're': 'runtime error', 'ce': 'compile error',
            'ole': 'output limit exceeded', 'se': 'system error',
        },
        PENDING_STATES: new Set(['waiting', 'compiling', 'running', 'judging', 'pending', 'queueing', 'fetched']),
        POLL_INTERVAL: 1.5,
        lastBannerKey: '',
        pollTimer: null,
        lastOverallStatus: '',
        observer: null,
        _isDarkCache: false,
        _observerDebounce: null,
        _verifyTimer: null,
        _lastResult: null,

        isDarkMode: function () {
            const bgColor = getComputedStyle(document.body).backgroundColor;
            const match = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
            if (match) {
                const r = parseInt(match[1]);
                const g = parseInt(match[2]);
                const b = parseInt(match[3]);
                const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
                return luminance < 0.5;
            }
            return false;
        },

        normalizeStatus: function (raw) {
            if (!raw) return '';
            let text = raw.trim().toLowerCase();
            if (text.length > 40) {
                for (const kw of Object.keys(this.ALIAS_MAP).concat(Object.keys(this.LIGHT_STATUS_MAP))) {
                    if (text.includes(kw)) { text = kw; break; }
                }
            }
            if (this.ALIAS_MAP[text]) return this.ALIAS_MAP[text];
            if (this.LIGHT_STATUS_MAP[text]) return text;
            for (const key of Object.keys(this.LIGHT_STATUS_MAP)) {
                if (text.includes(key)) return key;
            }
            return text.substring(0, 30);
        },

        getStatusInfo: function (key) {
            const map = this._isDarkCache ? this.DARK_STATUS_MAP : this.LIGHT_STATUS_MAP;
            return map[key] || {
                bg: this._isDarkCache ? '#1f1f1f' : '#f5f5f5',
                text: key.substring(0, 3).toUpperCase(), display: key,
                color: this._isDarkCache ? '#bfbfbf' : '#434343',
                border: this._isDarkCache ? '#434343' : '#d9d9d9'
            };
        },

        isFinished: function (key) { return key && !this.PENDING_STATES.has(key); },

        getOverallStatusKey: function (doc = document) {
            const primary = doc.querySelector('.record-status--text');
            if (primary) { const raw = primary.textContent.trim(); if (raw) return this.normalizeStatus(raw); }
            const dataEl = doc.querySelector('[data-status]');
            if (dataEl) { const ds = dataEl.getAttribute('data-status'); if (ds) return this.normalizeStatus(ds); }
            const cells = doc.querySelectorAll('.detail-status, td[class*="status"]');
            for (const cell of cells) {
                const text = cell.textContent.trim();
                if (text.includes('#') && text.includes('ms')) continue;
                if (text.length < 40 && text.length > 0) return this.normalizeStatus(text);
            }
            const bodyText = doc.body.innerText.toLowerCase();
            for (const kw of ['accepted', 'wrong answer', 'time limit exceeded', 'memory limit exceeded', 'runtime error', 'compile error', 'output limit exceeded', 'system error', 'judging', 'compiling', 'waiting', 'running', 'fetched']) {
                if (bodyText.includes(kw)) return kw;
            }
            return '';
        },

        getWorstStatus: function (testcases) {
            const severity = { 'system error': 10, 'runtime error': 9, 'memory limit exceeded': 8, 'time limit exceeded': 7, 'output limit exceeded': 6, 'wrong answer': 5, 'compile error': 4, 'accepted': 3 };
            let worst = 'accepted', worstScore = 0;
            for (const tc of testcases) { const s = severity[tc.key] || 0; if (s > worstScore) { worstScore = s; worst = tc.key; } }
            return worst;
        },

        notifyAndBanner: function (statusKey) {
            // 仅记录状态,不弹出任何横幅
            if (statusKey === this.lastBannerKey) return;
            this.lastBannerKey = statusKey;
        },

        getColumnMap: function (table) {
            const ths = table.querySelectorAll('thead th, thead td');
            const map = { status: -1, score: -1, time: -1, memory: -1 };
            if (ths.length > 0) {
                for (let i = 0; i < ths.length; i++) {
                    const text = ths[i].textContent.trim().toLowerCase();
                    if (text.includes('状态') || text.includes('status')) map.status = i;
                    if (text.includes('分数') || text.includes('score') || text.includes('point')) map.score = i;
                    if (text.includes('耗时') || text.includes('时间') || text.includes('time')) map.time = i;
                    if (text.includes('内存') || text.includes('memory') || text.includes('空间')) map.memory = i;
                }
            }
            const rows = table.querySelectorAll('tbody tr');
            for (const row of rows) {
                const cells = row.cells;
                for (let i = 0; i < cells.length; i++) {
                    const t = cells[i].textContent.trim().toLowerCase();
                    if (map.time < 0 && /\d\s*(ms|sec|秒)/i.test(t) && !/(mib|kib|mb|kb)/i.test(t)) map.time = i;
                    if (map.memory < 0 && /\d\s*(mib|kib|mb|kb)/i.test(t)) map.memory = i;
                }
                if (map.time >= 0 && map.memory >= 0) break;
            }
            if (map.status < 0) map.status = 1; if (map.score < 0) map.score = 2;
            if (map.time < 0) map.time = 3; if (map.memory < 0) map.memory = 4;
            return map;
        },

        /** 将分组结果展平为一维测试点数组(用于 getWorstStatus 等旧接口) */
        flattenResult: function (result) {
            if (!result) return [];
            const all = [];
            for (const g of result.groups) {
                for (const tc of g.cases) all.push(tc);
            }
            return all;
        },

        /** 检查分组结果中是否所有测试点均已完成 */
        isAllFinished: function (result) {
            if (!result) return true;
            for (const g of result.groups) {
                for (const tc of g.cases) {
                    if (!this.isFinished(tc.key)) return false;
                }
            }
            return true;
        },

        /** 获取分组结果中第一个测试点的 key(用于 fetched 判断等) */
        firstCaseKey: function (result) {
            if (!result || !result.groups.length) return '';
            const g = result.groups[0];
            if (g.cases.length > 0) return g.cases[0].key;
            return g.key;
        },

        extractTestCases: function (doc) {
            const self = this;
            const isTimeLike = (val) => /\d\s*(ms|sec|秒)/i.test(val) && !/(mib|kib|mb|kb)/i.test(val);
            const isMemLike = (val) => /\d/.test(val) && /(mib|kib|mb|kb)/i.test(val);

            const rows = doc.querySelectorAll('table tbody tr');
            if (rows.length === 0) return null;

            // ========== 检测是否存在 subtask 分组 ==========
            // 方式1:通过 CSS class 检测(Hydro OJ 标准 HTML)
            let hasSubtaskClass = false;
            for (const row of rows) {
                if (row.classList && (row.classList.contains('subtask') || row.classList.contains('case') || row.classList.contains('subtask-case'))) {
                    hasSubtaskClass = true;
                    break;
                }
            }

            // 方式2:通过模式检测(#N 行无耗时内存 + #N-M 行有耗时内存 → 有分组)
            let hasSubtaskPattern = false;
            if (!hasSubtaskClass) {
                let subtaskHeaderCount = 0;
                let caseRowCount = 0;
                for (const row of rows) {
                    const first = row.cells[0]?.textContent.trim() || '';
                    if (/^#\d+$/.test(first)) {
                        // 检测该行是否缺少 time/memory(即它是 subtask 标题行而非独立测试点)
                        const timeCell = row.cells[3]?.textContent.trim() || '';
                        const memCell = row.cells[4]?.textContent.trim() || '';
                        const rowText = row.textContent;
                        if (!isTimeLike(timeCell) && !isMemLike(memCell) &&
                            !/\d\s*(ms|sec|秒)/i.test(rowText)) {
                            subtaskHeaderCount++;
                        }
                    }
                    if (/^#\d+-\d+$/.test(first)) caseRowCount++;
                }
                if (subtaskHeaderCount > 0 && caseRowCount > 0) hasSubtaskPattern = true;
            }

            const hasGroups = hasSubtaskClass || hasSubtaskPattern;

            // ========== 分组提取 ==========
            if (hasGroups) {
                return self.extractGroupedRows(rows, hasSubtaskClass, isTimeLike, isMemLike, doc);
            }

            // ========== 平铺提取(兼容无分组的页面) ==========
            let testRows = [];
            for (const row of rows) { const first = row.cells[0]?.textContent.trim(); if (/^#\d+-\d+$/.test(first)) testRows.push(row); }
            for (const row of rows) {
                const first = row.cells[0]?.textContent.trim();
                if (/^#\d+$/.test(first) && /\d\s*(ms|sec|秒|mib|kib|mb|kb)/i.test(row.textContent)) testRows.push(row);
            }
            if (testRows.length === 0) return null;
            const table = testRows[0].closest('table');
            const colMap = this.getColumnMap(table);
            const cases = [];
            for (const row of testRows) {
                const cells = row.cells;
                const id = cells[0]?.textContent.trim() || '?';
                const statusCell = cells[colMap.status];

                // 智能提取状态文本:优先从 .record-status--text span 获取(排除 .float-right 的分数)
                let rawStatus = '';
                const statusSpan = statusCell?.querySelector('.record-status--text:not(.float-right)');
                if (statusSpan) rawStatus = statusSpan.textContent.trim();
                else rawStatus = statusCell?.textContent.trim() || '';

                // 智能提取分数:优先从 .float-right span 获取
                let score = '0';
                const scoreSpan = statusCell?.querySelector('.float-right');
                if (scoreSpan) score = scoreSpan.textContent.trim();
                else {
                    const m = rawStatus.match(/(\d+)\s*$/);
                    if (m) { score = m[1]; rawStatus = rawStatus.replace(/\d+\s*$/, '').trim(); }
                }

                let time = cells[colMap.time]?.textContent.trim() || '';
                let memory = cells[colMap.memory]?.textContent.trim() || '';

                if (!isTimeLike(time)) {
                    for (let i = 1; i < cells.length; i++) {
                        if (i === colMap.status) continue;
                        const t = cells[i]?.textContent.trim() || '';
                        if (isTimeLike(t)) { time = t; break; }
                    }
                }
                if (!isMemLike(memory)) {
                    for (let i = 1; i < cells.length; i++) {
                        if (i === colMap.status) continue;
                        const t = cells[i]?.textContent.trim() || '';
                        if (isMemLike(t)) { memory = t; break; }
                    }
                }

                cases.push({ id, key: self.normalizeStatus(rawStatus), score, time, memory });
            }
            return { hasGroups: false, groups: [{ id: '', key: '', score: '', cases: cases }] };
        },

        /** 从含有 subtask 分组的表格行中提取分组数据 */
        extractGroupedRows: function (rows, useClassNames, isTimeLike, isMemLike, doc) {
            const self = this;
            const groups = [];
            let currentGroup = null;

            // 尝试获取 colMap:找到含有数据的 table
            let dataTable = null;
            for (const row of rows) {
                const t = row.closest('table');
                if (t) { dataTable = t; break; }
            }
            // 也尝试找含 thead 的 table(header table)
            const root = doc || document;
            const allTables = root.querySelectorAll('table');
            let headerTable = null;
            for (const t of allTables) {
                if (t.querySelector('thead') && t.querySelector('thead tr')) { headerTable = t; break; }
            }
            const colMap = headerTable ? self.getColumnMap(headerTable) : (dataTable ? self.getColumnMap(dataTable) : { status: 1, score: 2, time: 3, memory: 4 });

            for (const row of rows) {
                const cells = row.cells;
                const first = cells[0]?.textContent.trim() || '';

                const isSubtaskRow = useClassNames
                    ? (row.classList && row.classList.contains('subtask'))
                    : (/^#\d+$/.test(first) && !isTimeLike(cells[colMap.time]?.textContent.trim() || '') && !isMemLike(cells[colMap.memory]?.textContent.trim() || ''));

                const isCaseRow = useClassNames
                    ? (row.classList && (row.classList.contains('case') || row.classList.contains('subtask-case')))
                    : /^#\d+-\d+$/.test(first);

                if (isSubtaskRow) {
                    // 提取 subtask 状态和分数
                    const id = first || '?';
                    const statusCell = cells[colMap.status];
                    // 优先从 record-status--text span 获取状态(排除 float-right 的分数)
                    let rawStatus = '';
                    const statusSpan = statusCell?.querySelector('.record-status--text:not(.float-right)');
                    if (statusSpan) rawStatus = statusSpan.textContent.trim();
                    else rawStatus = statusCell?.textContent.trim() || '';
                    // 提取分数:从 float-right span 或 status 文本末尾数字
                    let score = '';
                    const scoreSpan = statusCell?.querySelector('.float-right');
                    if (scoreSpan) score = scoreSpan.textContent.trim();
                    else {
                        const m = rawStatus.match(/(\d+)\s*$/);
                        if (m) { score = m[1]; rawStatus = rawStatus.replace(/\d+\s*$/, '').trim(); }
                    }

                    currentGroup = { id, key: self.normalizeStatus(rawStatus), score, cases: [] };
                    groups.push(currentGroup);
                } else if (isCaseRow) {
                    const id = first || '?';
                    const statusCell = cells[colMap.status];
                    let rawStatus = '';
                    const statusSpan = statusCell?.querySelector('.record-status--text:not(.float-right)');
                    if (statusSpan) rawStatus = statusSpan.textContent.trim();
                    else rawStatus = statusCell?.textContent.trim() || '';

                    let score = '';
                    const scoreSpan = statusCell?.querySelector('.float-right');
                    if (scoreSpan) score = scoreSpan.textContent.trim();
                    else {
                        const m = rawStatus.match(/(\d+)\s*$/);
                        if (m) { score = m[1]; rawStatus = rawStatus.replace(/\d+\s*$/, '').trim(); }
                    }

                    let time = cells[colMap.time]?.textContent.trim() || '';
                    let memory = cells[colMap.memory]?.textContent.trim() || '';

                    // 校验 time/memory
                    if (!isTimeLike(time)) {
                        for (let i = 1; i < cells.length; i++) {
                            if (i === colMap.status) continue;
                            const t = cells[i]?.textContent.trim() || '';
                            if (isTimeLike(t)) { time = t; break; }
                        }
                    }
                    if (!isMemLike(memory)) {
                        for (let i = 1; i < cells.length; i++) {
                            if (i === colMap.status) continue;
                            const t = cells[i]?.textContent.trim() || '';
                            if (isMemLike(t)) { memory = t; break; }
                        }
                    }

                    const tc = { id, key: self.normalizeStatus(rawStatus), score, time, memory };
                    // 如果没有当前分组,创建一个默认分组
                    if (!currentGroup) {
                        currentGroup = { id: '', key: '', score: '', cases: [] };
                        groups.push(currentGroup);
                    }
                    currentGroup.cases.push(tc);
                }
            }

            if (groups.length === 0) return null;
            return { hasGroups: groups.length > 1 || (groups.length === 1 && groups[0].id !== ''), groups: groups };
        },

        updateBlocks: function (result) {
            const self = this;

            // ========== 隐藏原始表格 ==========
            self._hideTables();

            self._isDarkCache = self.isDarkMode();
            const isDark = self._isDarkCache;

            // ========== 创建/更新容器 ==========
            let container = document.getElementById('bzoj-testcase-blocks');
            if (!container) {
                container = document.createElement('div');
                container.id = 'bzoj-testcase-blocks';
                container.style.cssText = `margin: 16px 0; padding: 14px; border-radius: 12px; background: ${isDark ? '#323334' : '#ffffff'}; border: none;`;

                const statusEl = document.querySelector('.record-status--text') || document.querySelector('[data-status]');
                const statusSection = statusEl?.closest('.section');

                const testCaseTable = Array.from(document.querySelectorAll('table')).find(t => {
                    const rows = t.querySelectorAll('tbody tr');
                    for (const row of rows) {
                        const first = row.cells[0]?.textContent.trim();
                        if (first && /^#\d+(-\d+)?$/.test(first)) return true;
                    }
                    return false;
                });

                let inserted = false;

                // 策略1:插入到状态 section 之后
                if (statusSection && statusSection.parentElement) {
                    if (statusSection.nextElementSibling) {
                        statusSection.parentElement.insertBefore(container, statusSection.nextElementSibling);
                    } else {
                        statusSection.parentElement.appendChild(container);
                    }
                    inserted = true;
                }

                // 策略2:插入到测试点表格的 section 级祖先之前
                if (!inserted && testCaseTable) {
                    const sectionAncestor = testCaseTable.closest('.section') ||
                                            testCaseTable.closest('[class*="section"]') ||
                                            testCaseTable.closest('.section__table-container')?.parentElement;
                    if (sectionAncestor && sectionAncestor.parentElement) {
                        sectionAncestor.parentElement.insertBefore(container, sectionAncestor);
                        inserted = true;
                    }
                }

                if (!inserted) {
                    const recordContainer = document.querySelector('.record-container');
                    if (recordContainer && recordContainer.parentElement) {
                        recordContainer.parentElement.insertBefore(container, recordContainer);
                    } else {
                        (document.querySelector('.page-content') || document.querySelector('main') || document.body).prepend(container);
                    }
                }
            } else {
                container.style.background = isDark ? '#323334' : '#ffffff';
            }

            container.innerHTML = '';
            let allFinished = true;

            // ========== 渲染分组 ==========
            for (let gi = 0; gi < result.groups.length; gi++) {
                const group = result.groups[gi];

                // 分组区块
                const groupSection = document.createElement('div');
                groupSection.className = 'bzoj-group-section';
                groupSection.style.cssText = gi < result.groups.length - 1
                    ? 'margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid ' + (isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)') + ';'
                    : 'margin-bottom: 0;';

                // 分组标题(仅在有分组时显示)
                if (result.hasGroups && group.id) {
                    const groupInfo = self.getStatusInfo(group.key);
                    const header = document.createElement('div');
                    header.className = 'bzoj-group-header';
                    header.style.cssText = `display: flex; align-items: center; gap: 8px; padding: 6px 10px; margin-bottom: 10px; border-radius: 8px; font-size: 13px; font-weight: 600; font-family: system-ui, -apple-system, sans-serif; background: ${isDark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.025)'}; color: ${groupInfo.color}; border-left: 3px solid ${groupInfo.border};`;

                    const idSpan = document.createElement('span');
                    idSpan.textContent = group.id;
                    header.appendChild(idSpan);

                    if (group.score) {
                        const scoreSpan = document.createElement('span');
                        scoreSpan.style.cssText = `opacity: 0.65; font-weight: 500;`;
                        scoreSpan.textContent = '\u00B7 ' + group.score + ' \u5206';
                        header.appendChild(scoreSpan);
                    }

                    const statusSpan = document.createElement('span');
                    statusSpan.style.cssText = `font-weight: 500; opacity: 0.8; margin-left: auto;`;
                    statusSpan.textContent = groupInfo.display;
                    header.appendChild(statusSpan);

                    groupSection.appendChild(header);
                }

                // 测试点方块容器
                const casesRow = document.createElement('div');
                casesRow.style.cssText = 'display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-start;';

                for (const tc of group.cases) {
                    if (!self.isFinished(tc.key)) allFinished = false;
                    const info = self.getStatusInfo(tc.key);
                    const block = document.createElement('div');
                    block.className = 'bzoj-testcase-block';
                    block.style.cssText = `display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100px; height: 100px; font-weight: bold; background: ${info.bg}; color: ${info.color}; border: 1px solid ${info.border}; border-radius: 10px; cursor: default; font-family: system-ui, -apple-system, sans-serif; position: relative; overflow: hidden;`;

                    const num = document.createElement('span');
                    num.style.cssText = `position: absolute; top: 6px; left: 8px; font-size: 11px; font-weight: 500; color: ${isDark ? 'rgba(255,255,255,0.65)' : 'rgba(0,0,0,0.45)'}; line-height: 1; max-width: calc(100% - 12px); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;`;
                    num.textContent = tc.id;
                    block.appendChild(num);

                    // 得分标签(右上角,包括 0 分也显示)
                    if (tc.score !== undefined && tc.score !== null && tc.score !== '') {
                        const scoreTag = document.createElement('span');
                        scoreTag.style.cssText = `position: absolute; top: 5px; right: 7px; font-size: 11px; font-weight: 600; color: ${info.color}; opacity: 0.75; line-height: 1;`;
                        scoreTag.textContent = tc.score;
                        block.appendChild(scoreTag);
                    }

                    const statusSpan = document.createElement('span');
                    statusSpan.style.cssText = 'font-size:24px; font-weight:normal; margin-bottom:4px;';
                    if (info.spin) { statusSpan.textContent = info.text; statusSpan.style.animation = 'bzoj-spin 1.5s linear infinite'; }
                    else statusSpan.textContent = info.text;
                    block.appendChild(statusSpan);

                    // 详细信息行:耗时 / 内存,始终显示
                    const detail = document.createElement('span');
                    detail.style.cssText = `font-size:11px; font-weight:normal; text-align:center; white-space:normal; word-break:break-all; color: ${isDark ? 'rgba(255,255,255,0.55)' : 'rgba(0,0,0,0.45)'}; line-height: 1.3; max-width: 90px;`;
                    let dt = '';
                    if (tc.time && tc.memory) dt = `${tc.time} / ${tc.memory}`;
                    else if (tc.time) dt = tc.time;
                    else if (tc.memory) dt = tc.memory;
                    else if (info.spin) dt = 'waiting...';
                    detail.textContent = dt;
                    block.appendChild(detail);
                    casesRow.appendChild(block);
                }

                groupSection.appendChild(casesRow);
                container.appendChild(groupSection);
            }

            // 评测中提示
            if (!allFinished) {
                const hint = document.createElement('div');
                hint.textContent = '\u23F3 评测进行中...';
                hint.style.cssText = `margin-top: 10px; color:${isDark ? '#69b1ff' : '#0958d9'}; font-size:14px; font-family: system-ui, -apple-system, sans-serif;`;
                container.appendChild(hint);
            }

            return allFinished;
        },

        pollStatus: async function () {
            const self = this;
            try {
                const resp = await fetch(window.location.href, { credentials: 'same-origin' });
                const html = await resp.text();
                const doc = new DOMParser().parseFromString(html, 'text/html');
                const newResult = self.extractTestCases(doc);
                if (newResult) {
                    // 数据没变就不重建,避免鬼畜
                    const changed = !self._resultEquals(newResult, self._lastResult);
                    self._lastResult = newResult;
                    const allDone = changed ? self.updateBlocks(newResult) : self.isAllFinished(newResult);
                    const flatCases = self.flattenResult(newResult);
                    if (allDone && flatCases.length > 0) { clearInterval(self.pollTimer); self.pollTimer = null; self.notifyAndBanner(self.getOverallStatusKey(doc) || self.getWorstStatus(flatCases)); }
                    else { if (self.firstCaseKey(newResult) === 'fetched') self.notifyAndBanner('fetched'); }
                } else {
                    const overall = self.getOverallStatusKey(doc);
                    if (overall) {
                        if (self.isFinished(overall)) { clearInterval(self.pollTimer); self.pollTimer = null; self.notifyAndBanner(overall); }
                        else if (overall !== self.lastOverallStatus) { self.notifyAndBanner(overall); self.lastOverallStatus = overall; }
                    }
                }
            } catch (e) { console.error('[BZOJ轮询] 网络错误', e); }
        },

        startPolling: function () {
            if (this.pollTimer) return;
            this.pollTimer = setInterval(() => this.pollStatus(), this.POLL_INTERVAL * 1000);
        },

        /** 处理 MutationObserver 回调(防抖后调用) */
        _handleMutation: function () {
            const self = this;
            const container = document.getElementById('bzoj-testcase-blocks');

            if (!container) {
                // 容器被 Hydro 重建 DOM 时销毁了,需要重新提取并渲染
                const result = self.extractTestCases(document);
                if (result) {
                    self._lastResult = result;
                    self.updateBlocks(result);
                } else if (self._lastResult) {
                    setTimeout(() => {
                        const retry = self.extractTestCases(document);
                        if (retry) { self._lastResult = retry; self.updateBlocks(retry); }
                        else { self.updateBlocks(self._lastResult); }
                    }, 500);
                }
            } else {
                // 容器还在,只需确保表格隐藏
                self._hideTables();
                // 只有当数据真的变化了才重建方块,避免反复重建导致鬼畜
                const result = self.extractTestCases(document);
                if (result && !self._resultEquals(result, self._lastResult)) {
                    self._lastResult = result;
                    self.updateBlocks(result);
                }
            }
        },

        /** 比较两次提取结果是否相同,避免无意义的重建 */
        _resultEquals: function (a, b) {
            if (!a || !b) return false;
            if (a.hasGroups !== b.hasGroups) return false;
            if (a.groups.length !== b.groups.length) return false;
            for (let i = 0; i < a.groups.length; i++) {
                const ga = a.groups[i], gb = b.groups[i];
                if (ga.id !== gb.id || ga.key !== gb.key || ga.score !== gb.score) return false;
                if (ga.cases.length !== gb.cases.length) return false;
                for (let j = 0; j < ga.cases.length; j++) {
                    const ca = ga.cases[j], cb = gb.cases[j];
                    if (ca.id !== cb.id || ca.key !== cb.key || ca.score !== cb.score ||
                        ca.time !== cb.time || ca.memory !== cb.memory) return false;
                }
            }
            return true;
        },

        /** 隐藏原始测试点表格及相关容器(使用 CSS class,配合 !important 规则) */
        _hideTables: function () {
            const tables = document.querySelectorAll('table');
            for (const t of tables) {
                const rows = t.querySelectorAll('tbody tr');
                for (const row of rows) {
                    const first = row.cells[0]?.textContent.trim();
                    if (first && /^#\d+(-\d+)?$/.test(first)) {
                        t.classList.add('bzoj-hide-table');
                        break;
                    }
                }
            }
            // 隐藏粘性表头表格(Hydro OJ 会在数据表上方生成一个 position:sticky 的表头表)
            const headerTables = document.querySelectorAll('table.section__table-header');
            for (const t of headerTables) { t.classList.add('bzoj-hide-table'); }

            const tableContainers = document.querySelectorAll('.section__table-container');
            for (const tc of tableContainers) { tc.classList.add('bzoj-hide-container'); }

            // 隐藏包含测试点表格的 .section__body.no-padding(避免空表格留下空白)
            const noPaddingBodies = document.querySelectorAll('.section__body.no-padding');
            for (const body of noPaddingBodies) {
                if (body.querySelector('table') || body.querySelector('.section__table-container')) {
                    body.classList.add('bzoj-hide-section-body');
                }
            }
        },

        /** 周期性验证容器是否仍然存在(兜底机制) */
        _startVerifyTimer: function () {
            const self = this;
            if (self._verifyTimer) return;
            self._verifyTimer = setInterval(() => {
                const container = document.getElementById('bzoj-testcase-blocks');
                if (!container) {
                    // 容器被销毁了,尝试重建
                    const result = self.extractTestCases(document);
                    if (result) {
                        self._lastResult = result;
                        self.updateBlocks(result);
                    } else if (self._lastResult) {
                        self.updateBlocks(self._lastResult);
                    }
                } else {
                    // 容器还在,确保表格仍然隐藏
                    self._hideTables();
                }
            }, 2000);
        },

        installObserver: function () {
            const self = this;
            if (this.observer) return;

            this.observer = new MutationObserver(() => {
                // 立即隐藏表格(不防抖,避免闪烁)
                self._hideTables();

                // 重建方块需要防抖,等 DOM 稳定后再处理
                clearTimeout(self._observerDebounce);
                self._observerDebounce = setTimeout(() => {
                    self._handleMutation();
                }, 300);
            });

            this.observer.observe(document.body, { attributes: true, attributeFilter: ['style'] });
            this.observer.observe(document.head, { childList: true });
            this.observer.observe(document.body, { childList: true, subtree: true });

            // 启动周期性验证作为兜底
            self._startVerifyTimer();
        },

        init: function () {
            // 自动检测 Hydro OJ 记录详情页(兼容 bzoj.org / hydro.ac 及所有 Hydro 系 OJ)
            // 1. 路径匹配:/record/[id] 或 /d/[domain]/record/[id]
            if (!/\/record\/\w+/.test(window.location.pathname)) return;
            // 2. 结构检测:页面是否有 Hydro 特征元素
            const hasHydroElements = document.querySelector('.record-status--text') ||
                                      document.querySelector('[data-status]') ||
                                      document.querySelector('.record-container');
            if (!hasHydroElements) return;

            const self = this;
            GM_addStyle(`
                @keyframes bzoj-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
                .bzoj-testcase-block { transition: box-shadow 0.2s, background 0.3s, color 0.3s, border-color 0.3s; }
                .bzoj-testcase-block:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.18); }
                table thead { display: none !important; }
                /* 用 CSS !important 强制隐藏测试点表格及容器,即使 Hydro 重建 DOM 也立即生效,避免闪烁 */
                .bzoj-hide-table { display: none !important; }
                .bzoj-hide-container { display: none !important; }
                .bzoj-hide-section-body { display: none !important; }
            `);

            const initialResult = self.extractTestCases(document);
            if (initialResult) {
                self._lastResult = initialResult;
                const allDone = self.updateBlocks(initialResult);
                const flatCases = self.flattenResult(initialResult);
                if (!allDone) { self.startPolling(); if (self.firstCaseKey(initialResult) === 'fetched') self.notifyAndBanner('fetched'); }
                else self.notifyAndBanner(self.getOverallStatusKey() || self.getWorstStatus(flatCases));
            } else {
                const overall = self.getOverallStatusKey();
                if (overall) {
                    if (self.isFinished(overall)) self.notifyAndBanner(overall);
                    else { self.notifyAndBanner(overall); self.startPolling(); }
                } else {
                    setTimeout(() => {
                        const retry = self.getOverallStatusKey();
                        if (retry) { if (self.isFinished(retry)) self.notifyAndBanner(retry); else { self.notifyAndBanner(retry); self.startPolling(); } }
                    }, 1000);
                }
            }
            self.installObserver();
        }
    };

    // ================================================================
    //  模块二:网页字体更换器(所有站点运行)
    // ================================================================

    // ==================== 默认常量 ====================

    const FS_DEFAULT_BTN_SIZE = 42;
    const FS_COLLAPSED_VISIBLE = 6;
    const FS_HOVER_ZONE = 10;
    const FS_DEFAULT_IDLE_MS = 5000;
    const FS_DRAG_THRESHOLD = 4;
    const FS_PANEL_W = 360;
    const FS_PANEL_MAX_H = 560;
    const FS_MARGIN = 8;

    // ==================== 存储 ====================

    const FS_STORAGE_KEY_CUSTOM_FONTS = 'fontSwitcher_customFonts';
    const FS_STORAGE_KEY_GLOBAL_SETTINGS = 'fontSwitcher_globalSettings';
    const FS_CURRENT_HOST = location.hostname;

    function fsSiteKey(base) { return `${base}@${FS_CURRENT_HOST}`; }

    const FS_STORAGE_KEY_ACTIVE_FONT = fsSiteKey('fontSwitcher_activeFont');
    const FS_STORAGE_KEY_ENABLED = fsSiteKey('fontSwitcher_enabled');
    const FS_STORAGE_KEY_BTN_POS = fsSiteKey('fontSwitcher_btnPos');
    const FS_STORAGE_KEY_FONT_SETTINGS = fsSiteKey('fontSwitcher_fontSettings');

    function fsLoadFromStorage(key, fallback) {
        try {
            if (typeof GM_getValue === 'function') {
                const v = GM_getValue(key, null);
                if (v !== null && v !== undefined) return v;
            }
            const raw = localStorage.getItem(key);
            if (raw !== null) return JSON.parse(raw);
        } catch (e) { /* 忽略 */ }
        return fallback;
    }

    function fsSaveToStorage(key, value) {
        try {
            if (typeof GM_setValue === 'function') GM_setValue(key, value);
            localStorage.setItem(key, JSON.stringify(value));
        } catch (e) { /* 忽略 */ }
    }

    // ==================== 全局设置 ====================

    const FS_DEFAULT_GLOBAL_SETTINGS = {
        btnSize: 42,
        snapToEdge: true,
        autoCollapse: true,
        idleMs: 5000,
        excludeInputs: false,
        toastDuration: 2000,
    };

    let fsGlobalSettings = Object.assign({}, FS_DEFAULT_GLOBAL_SETTINGS, fsLoadFromStorage(FS_STORAGE_KEY_GLOBAL_SETTINGS, {}));

    function fsSaveGlobalSettings() {
        fsSaveToStorage(FS_STORAGE_KEY_GLOBAL_SETTINGS, fsGlobalSettings);
    }

    let FS_BTN_SIZE = fsGlobalSettings.btnSize || FS_DEFAULT_BTN_SIZE;
    let FS_IDLE_MS = fsGlobalSettings.autoCollapse ? (fsGlobalSettings.idleMs || FS_DEFAULT_IDLE_MS) : Infinity;
    let FS_COLLAPSED_SHIFT = FS_BTN_SIZE - FS_COLLAPSED_VISIBLE;

    function fsRefreshDerivedSettings() {
        FS_BTN_SIZE = fsGlobalSettings.btnSize || FS_DEFAULT_BTN_SIZE;
        FS_IDLE_MS = fsGlobalSettings.autoCollapse ? (fsGlobalSettings.idleMs || FS_DEFAULT_IDLE_MS) : Infinity;
        FS_COLLAPSED_SHIFT = FS_BTN_SIZE - FS_COLLAPSED_VISIBLE;
    }

    // ==================== 状态 ====================

    let fsCustomFonts = fsLoadFromStorage(FS_STORAGE_KEY_CUSTOM_FONTS, []);
    let fsActiveFontValue = fsLoadFromStorage(FS_STORAGE_KEY_ACTIVE_FONT, '');
    let fsIsEnabled = fsLoadFromStorage(FS_STORAGE_KEY_ENABLED, true);
    let fsFontSettings = fsLoadFromStorage(FS_STORAGE_KEY_FONT_SETTINGS, {});

    const fsSavedPos = fsLoadFromStorage(FS_STORAGE_KEY_BTN_POS, null);
    let fsBtnSide = (fsSavedPos && fsSavedPos.side) ? fsSavedPos.side : 'right';
    let fsBtnY = (fsSavedPos && typeof fsSavedPos.y === 'number') ? fsSavedPos.y : 60;
    let fsBtnX = (fsSavedPos && typeof fsSavedPos.x === 'number') ? fsSavedPos.x : -1;

    let fsPanelVisible = false;
    let fsBtnCollapsed = false;
    let fsIdleTimer = null;

    let fsIsDragging = false;
    let fsHasDragged = false;
    let fsDragStartX = 0, fsDragStartY = 0;
    let fsBtnStartLeft = 0, fsBtnStartTop = 0;

    let fsPreviewStyleEl = null;
    let fsExpandedSettingsSet = new Set();
    let fsSettingsViewActive = false;

    // ==================== 预置字体 ====================

    const FS_PRESET_FONTS = [
        { name: '默认(不替换)', value: '' },
        { name: '微软雅黑', value: '"Microsoft YaHei", "微软雅黑", sans-serif' },
        { name: '苹方', value: '"PingFang SC", "Helvetica Neue", sans-serif' },
        { name: '宋体', value: 'SimSun, "宋体", serif' },
        { name: '黑体', value: 'SimHei, "黑体", sans-serif' },
        { name: '楷体', value: 'KaiTi, "楷体", serif' },
        { name: '仿宋', value: 'FangSong, "仿宋", serif' },
        { name: '思源黑体', value: '"Source Han Sans SC", "Noto Sans SC", sans-serif' },
        { name: '思源宋体', value: '"Source Han Serif SC", "Noto Serif SC", serif' },
        { name: '文泉驿正黑', value: '"WenQuanYi Zen Hei", sans-serif' },
        { name: '霞鹜文楷', value: '"LXGW WenKai", sans-serif' },
        { name: '等线', value: 'DengXian, "等线", sans-serif' },
        { name: '华文黑体', value: '"STHeiti", sans-serif' },
        { name: '华文楷体', value: 'STKaiti, "华文楷体", serif' },
        { name: '华文宋体', value: 'STSong, "华文宋体", serif' },
        { name: '华文仿宋', value: 'STFangsong, "华文仿宋", serif' },
        { name: 'Arial', value: 'Arial, Helvetica, sans-serif' },
        { name: 'Times New Roman', value: '"Times New Roman", Times, serif' },
        { name: 'Georgia', value: 'Georgia, serif' },
        { name: 'Comic Sans MS', value: '"Comic Sans MS", cursive' },
        { name: 'Consolas', value: 'Consolas, "Courier New", monospace' },
        { name: 'Trebuchet MS', value: '"Trebuchet MS", Helvetica, sans-serif' },
        { name: 'Verdana', value: 'Verdana, Geneva, sans-serif' },
    ];

    // ==================== 字体可用性检测 ====================

    const fsFontAvailability = new Map();

    function fsDetectFontAvailability(fontValue) {
        if (!fontValue) return true;
        const primaryFont = fontValue.split(',')[0].trim().replace(/^"|"$/g, '');
        if (!primaryFont) return true;
        if (fsFontAvailability.has(primaryFont)) return fsFontAvailability.get(primaryFont);

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        if (!ctx) { fsFontAvailability.set(primaryFont, true); return true; }

        const testStr = 'mmmmmmmmmmlli1WqB@#&_%';
        const size = '72px';
        const fallbacks = ['sans-serif', 'serif', 'monospace'];
        const baseWidths = fallbacks.map(fb => {
            ctx.font = `${size} ${fb}`;
            return ctx.measureText(testStr).width;
        });

        ctx.font = `${size} "${primaryFont}", sans-serif`;
        const testWidth = ctx.measureText(testStr).width;
        const available = !baseWidths.every(bw => Math.abs(bw - testWidth) < 0.5);
        fsFontAvailability.set(primaryFont, available);
        return available;
    }

    function fsDetectAllFonts() {
        fsFontAvailability.clear();
        FS_PRESET_FONTS.forEach(font => {
            if (font.value) fsDetectFontAvailability(font.value);
        });
        fsCustomFonts.forEach(font => {
            if (font.value) {
                const primaryFont = font.value.split(',')[0].trim().replace(/^"|"$/g, '');
                if (primaryFont) fsFontAvailability.set(primaryFont, true);
            }
        });
    }

    // ==================== 字体设置工具 ====================

    function fsGetFontSettings(fontValue) {
        if (!fontValue) return null;
        return fsFontSettings[fontValue] || null;
    }

    function fsSetFontSettings(fontValue, settings) {
        if (!fontValue) return;
        fsFontSettings[fontValue] = settings;
        fsSaveToStorage(FS_STORAGE_KEY_FONT_SETTINGS, fsFontSettings);
    }

    function fsRemoveFontSettings(fontValue) {
        if (!fontValue) return;
        delete fsFontSettings[fontValue];
        fsSaveToStorage(FS_STORAGE_KEY_FONT_SETTINGS, fsFontSettings);
    }

    function fsHasNonDefaultSettings(fontValue) {
        if (!fontValue) return false;
        const s = fsFontSettings[fontValue];
        if (!s) return false;
        if (s.size) return true;
        if (s.weight && s.weight !== '' && s.weight !== 'normal') return true;
        return false;
    }

    // ==================== 样式注入 ====================

    function fsBuildStyles() {
        return `
        /* ========== 按钮 ========== */
        #fs-trigger-btn {
            position: fixed;
            z-index: 2147483647;
            width: ${FS_BTN_SIZE}px;
            height: ${FS_BTN_SIZE}px;
            border: none;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
            font-size: ${Math.round(FS_BTN_SIZE * 0.43)}px;
            font-weight: bold;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.45);
            display: flex;
            align-items: center;
            justify-content: center;
            user-select: none;
            -webkit-user-select: none;
            font-family: "Segoe UI", Arial, sans-serif !important;
            touch-action: none;
            opacity: 0.9;
            transition: transform 0.35s cubic-bezier(0.4, 0, 0.2, 1),
                        box-shadow 0.2s ease,
                        opacity 0.25s ease,
                        border-radius 0.3s ease,
                        width 0.25s ease,
                        height 0.25s ease;
        }
        #fs-trigger-btn:hover {
            box-shadow: 0 6px 24px rgba(102, 126, 234, 0.65);
            opacity: 1;
        }
        #fs-trigger-btn .fs-btn-icon {
            pointer-events: none;
            line-height: 1;
            font-size: ${Math.round(FS_BTN_SIZE * 0.48)}px;
            transition: opacity 0.2s;
        }

        #fs-trigger-btn.fs-free {
            left: auto;
            right: auto;
            border-radius: 50%;
        }
        #fs-trigger-btn.fs-free.fs-collapsed {
            opacity: 0.35;
            transform: scale(0.85);
            pointer-events: none;
        }
        #fs-trigger-btn.fs-free.fs-collapsed .fs-btn-icon { opacity: 0.6; }

        #fs-trigger-btn.fs-side-right {
            right: 0;
            left: auto;
            border-radius: ${FS_BTN_SIZE / 2}px 0 0 ${FS_BTN_SIZE / 2}px;
        }
        #fs-trigger-btn.fs-side-right.fs-collapsed {
            transform: translateX(${FS_COLLAPSED_SHIFT}px);
            border-radius: 8px 0 0 8px;
            pointer-events: none;
            opacity: 0.5;
        }
        #fs-trigger-btn.fs-side-right.fs-collapsed .fs-btn-icon { opacity: 0; }

        #fs-trigger-btn.fs-side-left {
            left: 0;
            right: auto;
            border-radius: 0 ${FS_BTN_SIZE / 2}px ${FS_BTN_SIZE / 2}px 0;
        }
        #fs-trigger-btn.fs-side-left.fs-collapsed {
            transform: translateX(-${FS_COLLAPSED_SHIFT}px);
            border-radius: 0 8px 8px 0;
            pointer-events: none;
            opacity: 0.5;
        }
        #fs-trigger-btn.fs-side-left.fs-collapsed .fs-btn-icon { opacity: 0; }

        #fs-trigger-btn.fs-dragging {
            cursor: grabbing !important;
            opacity: 1;
            box-shadow: 0 8px 30px rgba(118, 75, 162, 0.7);
            transform: scale(1.08) !important;
            border-radius: 50% !important;
            transition: box-shadow 0.15s, opacity 0.15s;
        }
        #fs-trigger-btn.fs-snapping {
            transition: left 0.35s cubic-bezier(0.25, 1, 0.5, 1),
                        top 0.25s ease,
                        border-radius 0.3s ease,
                        transform 0.3s ease !important;
            transform: scale(1) !important;
        }
        #fs-trigger-btn.fs-active {
            opacity: 1;
            box-shadow: 0 6px 24px rgba(118, 75, 162, 0.7);
        }
        @keyframes fs-btn-enter {
            from { opacity: 0; transform: scale(0.5); }
            to   { opacity: 0.9; transform: scale(1); }
        }
        #fs-trigger-btn.fs-entering {
            animation: fs-btn-enter 0.4s ease forwards;
        }

        /* ========== 遮罩 ========== */
        #fs-overlay {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            z-index: 2147483646;
            background: transparent;
            display: none;
        }
        #fs-overlay.fs-show { display: block; }

        /* ========== 面板 ========== */
        #fs-panel {
            position: fixed;
            z-index: 2147483647;
            width: ${FS_PANEL_W}px;
            max-height: ${FS_PANEL_MAX_H}px;
            background: #ffffff;
            border-radius: 16px;
            box-shadow: 0 12px 48px rgba(0,0,0,0.18), 0 2px 8px rgba(0,0,0,0.08);
            font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;
            font-size: 14px !important;
            color: #333 !important;
            overflow: hidden;
            display: none;
            flex-direction: column;
            animation: fs-slide-in 0.25s ease;
        }
        #fs-panel.fs-show { display: flex; }
        @keyframes fs-slide-in {
            from { opacity: 0; transform: translateY(-12px) scale(0.96); }
            to   { opacity: 1; transform: translateY(0) scale(1); }
        }

        #fs-panel .fs-header {
            padding: 16px 18px 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-shrink: 0;
        }
        #fs-panel .fs-header-left { display: flex; flex-direction: column; gap: 2px; }
        #fs-panel .fs-header-title { font-size: 15px; font-weight: 600; letter-spacing: 0.5px; }
        #fs-panel .fs-header-host { font-size: 10px; opacity: 0.7; font-weight: 400; }
        #fs-panel .fs-header-actions { display: flex; align-items: center; gap: 6px; }
        #fs-panel .fs-header-gear,
        #fs-panel .fs-header-close {
            width: 28px; height: 28px; border-radius: 50%; border: none;
            background: rgba(255,255,255,0.2); color: #fff; font-size: 16px;
            cursor: pointer; display: flex; align-items: center; justify-content: center;
            transition: background 0.15s; line-height: 1;
        }
        #fs-panel .fs-header-gear:hover,
        #fs-panel .fs-header-close:hover { background: rgba(255,255,255,0.35); }
        #fs-panel .fs-header-gear.fs-gear-active { background: rgba(255,255,255,0.45); }

        #fs-panel .fs-toggle-row {
            display: flex; align-items: center; justify-content: space-between;
            padding: 10px 18px; background: #f8f8ff; border-bottom: 1px solid #eee; flex-shrink: 0;
        }
        #fs-panel .fs-toggle-label { font-size: 13px; color: #666; }
        #fs-panel .fs-toggle-switch { position: relative; width: 44px; height: 24px; cursor: pointer; }
        #fs-panel .fs-toggle-switch input { opacity: 0; width: 0; height: 0; }
        #fs-panel .fs-toggle-slider {
            position: absolute; top: 0; left: 0; right: 0; bottom: 0;
            background: #ccc; border-radius: 24px; transition: background 0.25s;
        }
        #fs-panel .fs-toggle-slider::before {
            content: ''; position: absolute; width: 18px; height: 18px;
            left: 3px; bottom: 3px; background: #fff; border-radius: 50%; transition: transform 0.25s;
        }
        #fs-panel .fs-toggle-switch input:checked + .fs-toggle-slider { background: #667eea; }
        #fs-panel .fs-toggle-switch input:checked + .fs-toggle-slider::before { transform: translateX(20px); }

        #fs-panel .fs-list-container {
            flex: 1; overflow-y: auto; padding: 4px 0;
            scrollbar-width: thin; scrollbar-color: #d0d0d0 transparent;
        }
        #fs-panel .fs-list-container::-webkit-scrollbar { width: 5px; }
        #fs-panel .fs-list-container::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }

        #fs-panel .fs-group-title {
            padding: 8px 18px 4px; font-size: 11px; font-weight: 600;
            color: #999; text-transform: uppercase; letter-spacing: 1px; user-select: none;
        }

        #fs-panel .fs-font-item {
            display: flex; align-items: center; padding: 7px 12px 7px 18px;
            cursor: pointer; transition: background 0.12s; gap: 8px;
        }
        #fs-panel .fs-font-item:hover { background: #f0f0ff; }
        #fs-panel .fs-font-item.fs-active { background: #eef0ff; }
        #fs-panel .fs-font-item .fs-radio {
            width: 16px; height: 16px; border-radius: 50%; border: 2px solid #ccc;
            flex-shrink: 0; display: flex; align-items: center; justify-content: center;
            transition: border-color 0.15s;
        }
        #fs-panel .fs-font-item.fs-active .fs-radio { border-color: #667eea; }
        #fs-panel .fs-font-item.fs-active .fs-radio::after {
            content: ''; width: 8px; height: 8px; border-radius: 50%; background: #667eea;
        }
        #fs-panel .fs-font-item .fs-font-info { flex: 1; min-width: 0; }
        #fs-panel .fs-font-item .fs-font-name {
            font-size: 13px; color: #333; white-space: nowrap; overflow: hidden;
            text-overflow: ellipsis; display: flex; align-items: center; gap: 5px;
        }
        #fs-panel .fs-font-item .fs-font-unavail {
            font-size: 9px; color: #e57373; background: #fff5f5; border: 1px solid #ffcdd2;
            border-radius: 3px; padding: 0 4px; line-height: 16px; font-weight: 500;
            flex-shrink: 0; white-space: nowrap;
        }
        #fs-panel .fs-font-item.fs-unavail .fs-font-name { color: #bbb; }
        #fs-panel .fs-font-item.fs-unavail .fs-font-preview { color: #ccc; }
        #fs-panel .fs-font-item .fs-font-preview {
            font-size: 12px; color: #888; margin-top: 1px; white-space: nowrap;
            overflow: hidden; text-overflow: ellipsis;
        }
        #fs-panel .fs-font-item .fs-has-settings {
            font-size: 9px; color: #667eea; margin-left: 4px; font-weight: 600;
        }

        #fs-panel .fs-font-item .fs-settings-btn {
            width: 22px; height: 22px; border-radius: 4px; border: none;
            background: transparent; color: #bbb; font-size: 13px; cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            transition: all 0.15s; flex-shrink: 0; opacity: 0;
        }
        #fs-panel .fs-font-item:hover .fs-settings-btn { opacity: 1; }
        #fs-panel .fs-font-item .fs-settings-btn:hover { background: #e8e8ff; color: #667eea; }
        #fs-panel .fs-font-item .fs-settings-btn.fs-settings-active { opacity: 1; color: #667eea; }

        #fs-panel .fs-font-item .fs-delete-btn {
            width: 22px; height: 22px; border-radius: 4px; border: none;
            background: transparent; color: #bbb; font-size: 14px; cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            transition: all 0.15s; flex-shrink: 0; opacity: 0;
        }
        #fs-panel .fs-font-item:hover .fs-delete-btn { opacity: 1; }
        #fs-panel .fs-font-item .fs-delete-btn:hover { background: #ffe0e0; color: #e55; }

        #fs-panel .fs-font-settings {
            background: #f5f5ff; border-bottom: 1px solid #e0e0ee; padding: 10px 18px; display: none;
        }
        #fs-panel .fs-font-settings.fs-show { display: block; }
        #fs-panel .fs-font-settings .fs-settings-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
        #fs-panel .fs-font-settings .fs-settings-row:last-child { margin-bottom: 0; }
        #fs-panel .fs-font-settings .fs-settings-label { font-size: 11px; color: #777; width: 42px; flex-shrink: 0; }
        #fs-panel .fs-font-settings .fs-settings-input {
            flex: 1; height: 28px; border: 1px solid #d8d8e8; border-radius: 6px;
            padding: 0 8px; font-size: 12px; font-family: inherit; outline: none;
            background: #fff; color: #333; transition: border-color 0.15s;
        }
        #fs-panel .fs-font-settings .fs-settings-input:focus { border-color: #667eea; }
        #fs-panel .fs-font-settings .fs-settings-select {
            flex: 1; height: 28px; border: 1px solid #d8d8e8; border-radius: 6px;
            padding: 0 6px; font-size: 12px; font-family: inherit; outline: none;
            background: #fff; color: #333; cursor: pointer;
        }
        #fs-panel .fs-font-settings .fs-settings-hint { font-size: 10px; color: #aaa; margin-top: 4px; }

        /* ========== 设置视图 ========== */
        #fs-panel .fs-settings-view {
            flex: 1; overflow-y: auto; padding: 0;
            scrollbar-width: thin; scrollbar-color: #d0d0d0 transparent;
        }
        #fs-panel .fs-settings-view::-webkit-scrollbar { width: 5px; }
        #fs-panel .fs-settings-view::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }

        #fs-panel .fs-sv-section { padding: 12px 18px; border-bottom: 1px solid #f0f0f0; }
        #fs-panel .fs-sv-section:last-child { border-bottom: none; }
        #fs-panel .fs-sv-section-title {
            font-size: 12px; font-weight: 600; color: #888; margin-bottom: 10px;
            text-transform: uppercase; letter-spacing: 0.5px;
        }
        #fs-panel .fs-sv-row { display: flex; align-items: center; justify-content: space-between; padding: 6px 0; min-height: 32px; }
        #fs-panel .fs-sv-row-label { font-size: 13px; color: #444; flex-shrink: 0; }
        #fs-panel .fs-sv-row-label small { display: block; font-size: 10px; color: #aaa; font-weight: 400; margin-top: 1px; }
        #fs-panel .fs-sv-row-right { display: flex; align-items: center; gap: 6px; }

        #fs-panel .fs-sv-select {
            height: 30px; border: 1px solid #d8d8e8; border-radius: 6px;
            padding: 0 8px; font-size: 12px; font-family: inherit; outline: none;
            background: #fff; color: #333; cursor: pointer; min-width: 100px;
        }
        #fs-panel .fs-sv-select:focus { border-color: #667eea; }

        #fs-panel .fs-sv-range-wrapper { display: flex; align-items: center; gap: 10px; }
        #fs-panel .fs-sv-range {
            -webkit-appearance: none; appearance: none; width: 110px; height: 6px;
            border-radius: 3px;
            background: linear-gradient(to right, #667eea 0%, #667eea var(--range-pct, 50%), #ddd var(--range-pct, 50%), #ddd 100%);
            outline: none; cursor: pointer; transition: background 0.1s;
        }
        #fs-panel .fs-sv-range::-webkit-slider-thumb {
            -webkit-appearance: none; appearance: none; width: 18px; height: 18px;
            border-radius: 50%; background: #fff; border: 3px solid #667eea; cursor: pointer;
            box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);
            transition: transform 0.15s, box-shadow 0.15s;
        }
        #fs-panel .fs-sv-range::-webkit-slider-thumb:hover {
            transform: scale(1.15); box-shadow: 0 2px 8px rgba(102, 126, 234, 0.5);
        }
        #fs-panel .fs-sv-range::-moz-range-thumb {
            width: 18px; height: 18px; border-radius: 50%; background: #fff;
            border: 3px solid #667eea; cursor: pointer; box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);
        }
        #fs-panel .fs-sv-range::-moz-range-track { height: 6px; border-radius: 3px; background: #ddd; }
        #fs-panel .fs-sv-range::-moz-range-progress { height: 6px; border-radius: 3px; background: #667eea; }
        #fs-panel .fs-sv-range-value {
            font-size: 12px; color: #667eea; font-weight: 700; min-width: 38px;
            text-align: right; font-variant-numeric: tabular-nums;
        }
        #fs-panel .fs-sv-btn-preview {
            border-radius: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);
            transition: width 0.2s ease, height 0.2s ease; flex-shrink: 0;
        }

        #fs-panel .fs-sv-toggle { position: relative; width: 44px; height: 24px; cursor: pointer; }
        #fs-panel .fs-sv-toggle input { opacity: 0; width: 0; height: 0; }
        #fs-panel .fs-sv-toggle-slider {
            position: absolute; top: 0; left: 0; right: 0; bottom: 0;
            background: #ccc; border-radius: 24px; transition: background 0.25s;
        }
        #fs-panel .fs-sv-toggle-slider::before {
            content: ''; position: absolute; width: 18px; height: 18px;
            left: 3px; bottom: 3px; background: #fff; border-radius: 50%; transition: transform 0.25s;
        }
        #fs-panel .fs-sv-toggle input:checked + .fs-sv-toggle-slider { background: #667eea; }
        #fs-panel .fs-sv-toggle input:checked + .fs-sv-toggle-slider::before { transform: translateX(20px); }

        #fs-panel .fs-sv-btn {
            height: 32px; border: 1px solid #d8d8e8; border-radius: 8px;
            padding: 0 14px; font-size: 12px; font-family: inherit; cursor: pointer;
            background: #fff; color: #555; transition: all 0.15s;
        }
        #fs-panel .fs-sv-btn:hover { border-color: #667eea; color: #667eea; background: #f5f5ff; }
        #fs-panel .fs-sv-btn-danger { color: #e55; }
        #fs-panel .fs-sv-btn-danger:hover { border-color: #e55; color: #e55; background: #fff5f5; }

        #fs-panel .fs-sv-upload-btn {
            flex: 1; height: 36px; border: 1.5px dashed #bbb; border-radius: 8px;
            background: #fff; color: #667eea; font-size: 13px; font-weight: 500;
            cursor: pointer; transition: border-color 0.15s, background 0.15s;
            white-space: nowrap; display: flex; align-items: center; justify-content: center; gap: 6px;
        }
        #fs-panel .fs-sv-upload-btn:hover { border-color: #667eea; background: #f0f0ff; }
        #fs-panel .fs-sv-upload-hint { font-size: 10px; color: #aaa; margin-top: 6px; }

        #fs-toast {
            position: fixed; z-index: 2147483647; padding: 10px 24px; border-radius: 10px;
            font-size: 13px; font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;
            color: #fff; pointer-events: none; visibility: hidden; opacity: 0;
            left: 50%; transform: translateX(-50%) translateY(-12px); top: 24px;
            white-space: nowrap; transition: opacity 0.3s ease, transform 0.3s ease, visibility 0s 0.3s;
        }
        #fs-toast.fs-toast-show {
            visibility: visible; opacity: 1; transform: translateX(-50%) translateY(0);
            transition: opacity 0.25s ease, transform 0.25s cubic-bezier(0.4, 0, 0.2, 1), visibility 0s 0s;
        }
        #fs-toast.fs-toast-success { background: #4caf50; }
        #fs-toast.fs-toast-error   { background: #f44336; }
        #fs-toast.fs-toast-info    { background: #667eea; }
    `;
    }

    let fsMainStyleEl = null;

    function fsInjectStyles() {
        if (fsMainStyleEl) fsMainStyleEl.remove();
        fsMainStyleEl = document.createElement('style');
        fsMainStyleEl.id = 'fs-main-styles';
        fsMainStyleEl.textContent = fsBuildStyles();
        document.head.appendChild(fsMainStyleEl);
    }

    function fsUpdateStyles() {
        if (fsMainStyleEl) fsMainStyleEl.textContent = fsBuildStyles();
        fsTriggerBtn.style.width = FS_BTN_SIZE + 'px';
        fsTriggerBtn.style.height = FS_BTN_SIZE + 'px';
    }

    fsInjectStyles();

    fsPreviewStyleEl = document.createElement('style');
    fsPreviewStyleEl.id = 'fs-preview-styles';
    document.head.appendChild(fsPreviewStyleEl);

    const fsUiRecoveryStyleEl = document.createElement('style');
    fsUiRecoveryStyleEl.id = 'fs-ui-recovery';
    fsUiRecoveryStyleEl.textContent = `
        #fs-trigger-btn, #fs-trigger-btn *,
        #fs-overlay,
        #fs-panel, #fs-panel *,
        #fs-toast, #fs-toast * {
            font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;
        }
    `;
    document.head.appendChild(fsUiRecoveryStyleEl);

    // ==================== DOM 构建 ====================

    const fsTriggerBtn = document.createElement('button');
    fsTriggerBtn.id = 'fs-trigger-btn';
    fsTriggerBtn.title = '字体更换器(可拖拽移动)';
    fsTriggerBtn.innerHTML = '<span class="fs-btn-icon">Aa</span>';
    fsTriggerBtn.classList.add(fsGlobalSettings.snapToEdge !== false ? ('fs-side-' + fsBtnSide) : 'fs-free', 'fs-entering');
    document.body.appendChild(fsTriggerBtn);

    const fsOverlay = document.createElement('div');
    fsOverlay.id = 'fs-overlay';
    document.body.appendChild(fsOverlay);

    const fsPanel = document.createElement('div');
    fsPanel.id = 'fs-panel';
    fsPanel.innerHTML = `
        <div class="fs-header">
            <div class="fs-header-left">
                <span class="fs-header-title">字体更换器</span>
                <span class="fs-header-host">${FS_CURRENT_HOST}</span>
            </div>
            <div class="fs-header-actions">
                <button class="fs-header-gear" id="fs-header-gear-btn" title="设置">&#9881;</button>
                <button class="fs-header-close" title="关闭">&times;</button>
            </div>
        </div>
        <div class="fs-toggle-row">
            <span class="fs-toggle-label">启用字体替换(仅当前站点)</span>
            <label class="fs-toggle-switch">
                <input type="checkbox" id="fs-enabled-toggle">
                <span class="fs-toggle-slider"></span>
            </label>
        </div>
        <div class="fs-list-container" id="fs-font-list"></div>
        <div class="fs-settings-view" id="fs-settings-view" style="display:none;"></div>
    `;
    document.body.appendChild(fsPanel);

    const fsToast = document.createElement('div');
    fsToast.id = 'fs-toast';
    document.body.appendChild(fsToast);

    const fsFontFileInput = document.createElement('input');
    fsFontFileInput.type = 'file';
    fsFontFileInput.id = 'fs-font-file-input';
    fsFontFileInput.accept = '.woff2,.woff,.ttf,.otf,.eot';
    fsFontFileInput.multiple = true;
    fsFontFileInput.style.display = 'none';
    document.body.appendChild(fsFontFileInput);

    // ==================== 按钮位置管理 ====================

    function fsApplyBtnPosition() {
        fsTriggerBtn.classList.remove('fs-side-left', 'fs-side-right', 'fs-free');
        if (fsGlobalSettings.snapToEdge) {
            fsTriggerBtn.style.top = fsBtnY + 'px';
            fsTriggerBtn.style.left = '';
            fsTriggerBtn.style.right = '';
            fsTriggerBtn.classList.add('fs-side-' + fsBtnSide);
        } else {
            fsTriggerBtn.style.left = fsBtnX + 'px';
            fsTriggerBtn.style.right = 'auto';
            fsTriggerBtn.style.top = fsBtnY + 'px';
            fsTriggerBtn.classList.add('fs-free');
        }
        if (!fsBtnCollapsed) fsTriggerBtn.style.transform = '';
    }

    function fsClampBtnPos() {
        fsBtnY = Math.max(0, Math.min(fsBtnY, window.innerHeight - FS_BTN_SIZE));
        fsBtnX = Math.max(0, Math.min(fsBtnX, window.innerWidth - FS_BTN_SIZE));
    }

    function fsSaveBtnPosition() {
        fsSaveToStorage(FS_STORAGE_KEY_BTN_POS, { side: fsBtnSide, x: fsBtnX, y: fsBtnY });
    }

    // ==================== 收缩 / 展开 ====================

    function fsCollapseBtn() {
        if (fsBtnCollapsed || fsPanelVisible) return;
        if (!fsGlobalSettings.autoCollapse) return;
        fsBtnCollapsed = true;
        fsTriggerBtn.classList.add('fs-collapsed');
    }

    function fsIsSnapMode() {
        return fsGlobalSettings.snapToEdge !== false;
    }

    function fsExpandBtn() {
        if (!fsBtnCollapsed) return;
        fsBtnCollapsed = false;
        fsTriggerBtn.classList.remove('fs-collapsed');
        fsResetIdleTimer();
    }

    function fsResetIdleTimer() {
        if (fsIdleTimer) clearTimeout(fsIdleTimer);
        if (!fsPanelVisible && fsGlobalSettings.autoCollapse) {
            fsIdleTimer = setTimeout(fsCollapseBtn, FS_IDLE_MS);
        }
    }

    document.addEventListener('mousemove', (e) => {
        if (!fsBtnCollapsed) return;
        if (fsIsSnapMode()) {
            const vx = window.innerWidth;
            const nearEdge = (fsBtnSide === 'right' && e.clientX > vx - FS_HOVER_ZONE) ||
                             (fsBtnSide === 'left'  && e.clientX < FS_HOVER_ZONE);
            const nearBtnY = e.clientY >= fsBtnY - FS_HOVER_ZONE &&
                             e.clientY <= fsBtnY + FS_BTN_SIZE + FS_HOVER_ZONE;
            if (nearEdge && nearBtnY) fsExpandBtn();
        } else {
            const bx = fsBtnX >= 0 ? fsBtnX : (window.innerWidth - FS_BTN_SIZE - 10);
            const nearBtn = e.clientX >= bx - FS_HOVER_ZONE &&
                            e.clientX <= bx + FS_BTN_SIZE + FS_HOVER_ZONE &&
                            e.clientY >= fsBtnY - FS_HOVER_ZONE &&
                            e.clientY <= fsBtnY + FS_BTN_SIZE + FS_HOVER_ZONE;
            if (nearBtn) fsExpandBtn();
        }
    });

    fsTriggerBtn.addEventListener('mouseenter', () => {
        if (!fsBtnCollapsed) fsResetIdleTimer();
    });

    // ==================== 拖拽逻辑 ====================

    function fsOnPointerDown(e) {
        if (fsBtnCollapsed) return;
        if (e.button && e.button !== 0) return;
        const clientX = e.touches ? e.touches[0].clientX : e.clientX;
        const clientY = e.touches ? e.touches[0].clientY : e.clientY;
        fsIsDragging = true;
        fsHasDragged = false;
        fsDragStartX = clientX;
        fsDragStartY = clientY;
        const rect = fsTriggerBtn.getBoundingClientRect();
        fsBtnStartLeft = rect.left;
        fsBtnStartTop = rect.top;
        e.preventDefault();
    }

    function fsOnPointerMove(e) {
        if (!fsIsDragging) return;
        const clientX = e.touches ? e.touches[0].clientX : e.clientX;
        const clientY = e.touches ? e.touches[0].clientY : e.clientY;
        const dx = clientX - fsDragStartX;
        const dy = clientY - fsDragStartY;
        if (!fsHasDragged && Math.abs(dx) < FS_DRAG_THRESHOLD && Math.abs(dy) < FS_DRAG_THRESHOLD) return;
        if (!fsHasDragged) { fsHasDragged = true; fsClosePanel(); }
        fsTriggerBtn.style.right = 'auto';
        fsTriggerBtn.style.left = (fsBtnStartLeft + dx) + 'px';
        fsTriggerBtn.style.top = (fsBtnStartTop + dy) + 'px';
        fsTriggerBtn.classList.remove('fs-collapsed');
        fsTriggerBtn.classList.add('fs-dragging');
        fsBtnCollapsed = false;
        e.preventDefault();
    }

    function fsOnPointerUp(e) {
        if (!fsIsDragging) return;
        fsIsDragging = false;
        fsTriggerBtn.classList.remove('fs-dragging');
        if (fsHasDragged) {
            const rect = fsTriggerBtn.getBoundingClientRect();
            if (fsIsSnapMode()) {
                fsBtnSide = (rect.left + rect.width / 2) < window.innerWidth / 2 ? 'left' : 'right';
                fsBtnY = rect.top;
                fsClampBtnPos();
                fsSaveBtnPosition();

                fsTriggerBtn.style.right = 'auto';
                fsTriggerBtn.style.left = rect.left + 'px';
                fsTriggerBtn.style.top = fsBtnY + 'px';
                fsTriggerBtn.classList.add('fs-snapping');

                const targetLeft = fsBtnSide === 'left' ? 0 : window.innerWidth - FS_BTN_SIZE;
                const targetRadius = fsBtnSide === 'left'
                    ? `0 ${FS_BTN_SIZE / 2}px ${FS_BTN_SIZE / 2}px 0`
                    : `${FS_BTN_SIZE / 2}px 0 0 ${FS_BTN_SIZE / 2}px`;
                fsTriggerBtn.style.left = targetLeft + 'px';
                fsTriggerBtn.style.borderRadius = targetRadius;

                let snapFinished = false;
                const finishSnap = () => {
                    if (snapFinished) return;
                    snapFinished = true;
                    fsTriggerBtn.removeEventListener('transitionend', onSnapEnd);
                    fsTriggerBtn.classList.remove('fs-snapping');
                    fsTriggerBtn.style.borderRadius = '';
                    fsApplyBtnPosition();
                    fsResetIdleTimer();
                    setTimeout(() => { fsHasDragged = false; }, 50);
                };
                const onSnapEnd = (evt) => { if (evt.propertyName !== 'left') return; finishSnap(); };
                fsTriggerBtn.addEventListener('transitionend', onSnapEnd);
                setTimeout(finishSnap, 450);
            } else {
                fsBtnX = rect.left;
                fsBtnY = rect.top;
                fsClampBtnPos();
                fsSaveBtnPosition();
                fsApplyBtnPosition();
                fsResetIdleTimer();
                setTimeout(() => { fsHasDragged = false; }, 50);
            }
        }
    }

    fsTriggerBtn.addEventListener('mousedown', fsOnPointerDown);
    document.addEventListener('mousemove', fsOnPointerMove);
    document.addEventListener('mouseup', fsOnPointerUp);
    fsTriggerBtn.addEventListener('touchstart', fsOnPointerDown, { passive: false });
    document.addEventListener('touchmove', fsOnPointerMove, { passive: false });
    document.addEventListener('touchend', fsOnPointerUp);
    fsTriggerBtn.addEventListener('click', (e) => {
        if (fsHasDragged || fsBtnCollapsed) return;
        fsTogglePanel();
    });
    window.addEventListener('resize', () => {
        fsClampBtnPos();
        fsApplyBtnPosition();
        if (fsPanelVisible) fsPositionPanel();
    });

    // ==================== 面板定位 ====================

    function fsPositionPanel() {
        const btnRect = fsTriggerBtn.getBoundingClientRect();
        const vw = window.innerWidth;
        const vh = window.innerHeight;
        const gap = 10;
        const inwardOffset = FS_BTN_SIZE + 12;
        let left, top;

        if (fsIsSnapMode()) {
            if (fsBtnSide === 'right') {
                left = btnRect.left - FS_PANEL_W - gap;
                if (left < FS_MARGIN) left = btnRect.right - FS_PANEL_W + inwardOffset;
            } else {
                left = btnRect.right + gap;
                if (left + FS_PANEL_W > vw - FS_MARGIN) left = btnRect.left - inwardOffset;
            }
        } else {
            left = btnRect.left - FS_PANEL_W - gap;
            if (left < FS_MARGIN) left = btnRect.right + gap;
            if (left + FS_PANEL_W > vw - FS_MARGIN) left = btnRect.right - FS_PANEL_W + inwardOffset;
        }

        left = Math.max(FS_MARGIN, Math.min(left, vw - FS_PANEL_W - FS_MARGIN));
        top = btnRect.top;
        if (top + FS_PANEL_MAX_H > vh - FS_MARGIN) top = vh - FS_PANEL_MAX_H - FS_MARGIN;
        if (top < FS_MARGIN) top = FS_MARGIN;

        fsPanel.style.left = left + 'px';
        fsPanel.style.top = top + 'px';
    }

    // ==================== 字体应用(核心) ====================

    let fsInjectedStyleEl = null;

    function fsApplyFont(fontValue) {
        if (fsInjectedStyleEl) { fsInjectedStyleEl.remove(); fsInjectedStyleEl = null; }
        if (!fontValue || !fsIsEnabled) return;

        const settings = fsGetFontSettings(fontValue);
        const fontSize = (settings && settings.size) ? settings.size : '';
        const fontWeight = (settings && settings.weight) ? settings.weight : '';

        let extraProps = '';
        if (fontSize) extraProps += `font-size: ${fontSize} !important;\n`;
        if (fontWeight) extraProps += `font-weight: ${fontWeight} !important;\n`;

        const excludeInputs = fsGlobalSettings.excludeInputs;
        const inputSelector = excludeInputs ? '' : `, input, textarea, select, button`;

        fsInjectedStyleEl = document.createElement('style');
        fsInjectedStyleEl.id = 'fs-injected-font';
        fsInjectedStyleEl.textContent = `
            html, body, div, span, applet, object, iframe,
            h1, h2, h3, h4, h5, h6, p, blockquote, pre,
            a, abbr, acronym, address, big, cite, code,
            del, dfn, em, img, ins, kbd, q, s, samp,
            small, strike, strong, sub, sup, tt, var,
            b, u, i, center,
            dl, dt, dd, ol, ul, li,
            fieldset, form, label, legend,
            table, caption, tbody, tfoot, thead, tr, th, td,
            article, aside, canvas, details, embed,
            figure, figcaption, footer, header, hgroup,
            menu, nav, output, ruby, section, summary,
            time, mark, audio, video${inputSelector} {
                font-family: ${fontValue} !important;
                ${extraProps}
            }
        `;
        document.head.appendChild(fsInjectedStyleEl);
    }

    // Blob URL 缓存:fontName -> blobUrl,避免重复创建
    const fsBlobUrlCache = new Map();

    /**
     * 将 dataUrl 转换为 Blob URL(浏览器解析比 dataUrl 快得多)
     * Blob URL 在页面生命周期内有效,无需每次重新解码 base64
     */
    function fsDataUrlToBlobUrl(dataUrl) {
        if (fsBlobUrlCache.has(dataUrl)) return fsBlobUrlCache.get(dataUrl);
        try {
            const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);
            if (!match) return dataUrl; // 不是标准 dataUrl,原样返回
            const mimeType = match[1];
            const base64 = match[2];
            const binaryStr = atob(base64);
            const bytes = new Uint8Array(binaryStr.length);
            for (let i = 0; i < binaryStr.length; i++) bytes[i] = binaryStr.charCodeAt(i);
            const blob = new Blob([bytes], { type: mimeType });
            const blobUrl = URL.createObjectURL(blob);
            fsBlobUrlCache.set(dataUrl, blobUrl);
            return blobUrl;
        } catch (e) {
            return dataUrl; // 转换失败,回退到 dataUrl
        }
    }

    function fsLoadCustomFontFace(name, url, format) {
        const id = 'fs-fontface-' + CSS.escape(name.replace(/\s+/g, '-'));
        if (document.getElementById(id)) return;
        // 优先使用 Blob URL,提升浏览器解析速度
        const fontUrl = url.startsWith('data:') ? fsDataUrlToBlobUrl(url) : url;
        const styleEl = document.createElement('style');
        styleEl.id = id;
        const srcStr = format ? `url("${fontUrl}") format("${format}")` : `url("${fontUrl}")`;
        styleEl.textContent = `@font-face { font-family: "${name}"; src: ${srcStr}; }`;
        document.head.appendChild(styleEl);
    }

    // ==================== 预览样式更新 ====================

    function fsUpdatePreviewStyles() {
        const allFonts = [...FS_PRESET_FONTS, ...fsCustomFonts];
        let css = '';
        allFonts.forEach((font, i) => {
            if (font.value) css += `#fs-panel #fs-preview-${i} { font-family: ${font.value} !important; }\n`;
        });
        fsPreviewStyleEl.textContent = css;
    }

    // ==================== 渲染字体列表 ====================

    function fsRenderFontList() {
        const listContainer = document.getElementById('fs-font-list');
        listContainer.innerHTML = '';
        let idx = 0;

        const presetGroup = document.createElement('div');
        presetGroup.className = 'fs-group-title';
        presetGroup.textContent = '预置字体';
        listContainer.appendChild(presetGroup);
        FS_PRESET_FONTS.forEach(font => {
            presetGroup.appendChild(fsCreateFontItem(font, false, idx++));
        });

        if (fsCustomFonts.length > 0) {
            const customGroup = document.createElement('div');
            customGroup.className = 'fs-group-title';
            customGroup.textContent = '自定义字体(全局)';
            listContainer.appendChild(customGroup);
            fsCustomFonts.forEach(font => {
                customGroup.appendChild(fsCreateFontItem(font, true, idx++));
            });
        }

        fsUpdatePreviewStyles();
    }

    function fsCreateFontItem(font, isCustom, index) {
        const isActive = fsActiveFontValue === font.value;
        const wrapper = document.createElement('div');

        const item = document.createElement('div');
        item.className = 'fs-font-item' + (isActive ? ' fs-active' : '');

        const radio = document.createElement('div');
        radio.className = 'fs-radio';

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

        const nameEl = document.createElement('div');
        nameEl.className = 'fs-font-name';
        nameEl.textContent = font.name;

        if (font.value && !isCustom) {
            const primaryFont = font.value.split(',')[0].trim().replace(/^"|"$/g, '');
            if (primaryFont && fsFontAvailability.has(primaryFont) && !fsFontAvailability.get(primaryFont)) {
                item.classList.add('fs-unavail');
                const unavailTag = document.createElement('span');
                unavailTag.className = 'fs-font-unavail';
                unavailTag.textContent = '未安装';
                nameEl.appendChild(unavailTag);
            }
        }

        const settings = fsGetFontSettings(font.value);
        if (settings && (settings.size || settings.weight) && font.value) {
            const badge = document.createElement('span');
            badge.className = 'fs-has-settings';
            let label = '';
            if (settings.size) label += settings.size;
            if (settings.weight && settings.weight !== 'normal') label += (label ? ' ' : '') + 'B';
            badge.textContent = label ? `[${label}]` : '';
            nameEl.appendChild(badge);
        }

        const preview = document.createElement('div');
        preview.className = 'fs-font-preview';
        preview.id = 'fs-preview-' + index;
        preview.textContent = '你好世界 Hello World 0123';

        info.appendChild(nameEl);
        info.appendChild(preview);
        item.appendChild(radio);
        item.appendChild(info);

        if (font.value) {
            const settingsBtn = document.createElement('button');
            settingsBtn.className = 'fs-settings-btn' + (fsExpandedSettingsSet.has(font.value) ? ' fs-settings-active' : '');
            settingsBtn.innerHTML = '&#9881;';
            settingsBtn.title = '字号/加粗设置';
            settingsBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                fsToggleSettings(font.value, wrapper);
            });
            item.appendChild(settingsBtn);
        }

        if (isCustom) {
            const delBtn = document.createElement('button');
            delBtn.className = 'fs-delete-btn';
            delBtn.innerHTML = '&times;';
            delBtn.title = '删除此字体';
            delBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                fsDeleteCustomFont(font);
            });
            item.appendChild(delBtn);
        }

        item.addEventListener('click', () => fsSelectFont(font));
        wrapper.appendChild(item);

        if (font.value) {
            const settingsPanel = document.createElement('div');
            settingsPanel.className = 'fs-font-settings' + (fsExpandedSettingsSet.has(font.value) ? ' fs-show' : '');
            settingsPanel.id = 'fs-settings-' + index;

            const current = fsGetFontSettings(font.value) || {};

            settingsPanel.innerHTML = `
                <div class="fs-settings-row">
                    <span class="fs-settings-label">字号</span>
                    <input class="fs-settings-input" type="text"
                           data-font-value="${font.value.replace(/"/g, '&quot;')}"
                           data-field="size"
                           placeholder="如 16px, 1.2em, 120%"
                           value="${current.size || ''}" />
                </div>
                <div class="fs-settings-row">
                    <span class="fs-settings-label">加粗</span>
                    <select class="fs-settings-select"
                            data-font-value="${font.value.replace(/"/g, '&quot;')}"
                            data-field="weight">
                        <option value="">默认</option>
                        <option value="100">100 - 极细</option>
                        <option value="200">200 - 特细</option>
                        <option value="300">300 - 细体</option>
                        <option value="normal">400 - 常规</option>
                        <option value="500">500 - 中等</option>
                        <option value="600">600 - 半粗</option>
                        <option value="bold">700 - 粗体</option>
                        <option value="800">800 - 特粗</option>
                        <option value="900">900 - 极粗</option>
                    </select>
                </div>
                <div class="fs-settings-hint">设置仅对当前站点生效,留空则不覆盖</div>
            `;

            const selectEl = settingsPanel.querySelector('select');
            if (current.weight) selectEl.value = current.weight;

            settingsPanel.querySelectorAll('.fs-settings-input, .fs-settings-select').forEach(input => {
                const handler = () => {
                    const fv = input.dataset.fontValue;
                    const field = input.dataset.field;
                    const val = input.value.trim();
                    const s = fsGetFontSettings(fv) || {};
                    if (val) { s[field] = val; } else { delete s[field]; }
                    if (Object.keys(s).length === 0) { fsRemoveFontSettings(fv); } else { fsSetFontSettings(fv, s); }
                    if (fv === fsActiveFontValue) { fsApplyFont(fsActiveFontValue); }
                    const settingsPanelEl = input.closest('.fs-font-settings');
                    if (fsHasNonDefaultSettings(fv)) {
                        fsExpandedSettingsSet.add(fv);
                        if (settingsPanelEl) settingsPanelEl.classList.add('fs-show');
                    } else {
                        fsExpandedSettingsSet.delete(fv);
                        if (settingsPanelEl) settingsPanelEl.classList.remove('fs-show');
                    }
                    const wrapperEl = settingsPanelEl ? settingsPanelEl.previousElementSibling : null;
                    if (wrapperEl) {
                        const gearBtn = wrapperEl.querySelector('.fs-settings-btn');
                        if (gearBtn) {
                            if (fsExpandedSettingsSet.has(fv)) gearBtn.classList.add('fs-settings-active');
                            else gearBtn.classList.remove('fs-settings-active');
                        }
                    }
                };
                input.addEventListener('input', handler);
                input.addEventListener('change', handler);
            });

            wrapper.appendChild(settingsPanel);
        }

        return wrapper;
    }

    function fsToggleSettings(fontValue, wrapper) {
        if (fsExpandedSettingsSet.has(fontValue)) fsExpandedSettingsSet.delete(fontValue);
        else fsExpandedSettingsSet.add(fontValue);
        fsRenderFontList();
    }

    // ==================== 字体选择 ====================

    function fsSelectFont(font) {
        fsActiveFontValue = font.value;
        fsSaveToStorage(FS_STORAGE_KEY_ACTIVE_FONT, fsActiveFontValue);
        // 懒加载:选择自定义字体时才注入其 @font-face
        if (font.value && fsIsEnabled) {
            const customFont = fsCustomFonts.find(f => f.value === font.value);
            if (customFont) {
                const url = customFont.dataUrl || customFont.url;
                if (url) fsLoadCustomFontFace(customFont.name, url, customFont.format || null);
            }
            fsApplyFont(font.value);
        } else {
            fsApplyFont('');
        }
        fsRenderFontList();
        fsShowToast(`已切换为:${font.name}`, 'success');
    }

    function fsDeleteCustomFont(font) {
        fsCustomFonts = fsCustomFonts.filter(f => f.value !== font.value);
        fsSaveToStorage(FS_STORAGE_KEY_CUSTOM_FONTS, fsCustomFonts);
        fsRemoveFontSettings(font.value);
        if (fsActiveFontValue === font.value) {
            fsActiveFontValue = '';
            fsSaveToStorage(FS_STORAGE_KEY_ACTIVE_FONT, fsActiveFontValue);
            fsApplyFont('');
        }
        const faceId = 'fs-fontface-' + CSS.escape(font.name.replace(/\s+/g, '-'));
        const faceEl = document.getElementById(faceId);
        if (faceEl) faceEl.remove();
        fsRenderFontList();
        fsShowToast(`已删除:${font.name}`, 'info');
    }

    // ==================== 添加自定义字体 ====================

    function fsAddUploadedFont(name, dataUrl, format) {
        const value = `"${name}", sans-serif`;
        if (fsCustomFonts.some(f => f.name === name)) { fsShowToast('该字体名称已存在', 'error'); return; }
        fsLoadCustomFontFace(name, dataUrl, format);
        fsCustomFonts.push({ name, value, dataUrl, format });
        fsSaveToStorage(FS_STORAGE_KEY_CUSTOM_FONTS, fsCustomFonts);
        fsRenderFontList();
        fsShowToast(`已添加字体:${name}`, 'success');
    }

    function fsHandleFontFileUpload(files) {
        if (!files || files.length === 0) return;
        const validExts = ['.woff2', '.woff', '.ttf', '.otf', '.eot'];
        const formatMap = { 'woff2': 'woff2', 'woff': 'woff', 'ttf': 'truetype', 'otf': 'opentype', 'eot': 'embedded-opentype' };
        Array.from(files).forEach(file => {
            const ext = '.' + file.name.split('.').pop().toLowerCase();
            if (!validExts.includes(ext)) { fsShowToast(`不支持的格式:${file.name}`, 'error'); return; }
            const fontName = file.name.replace(/\.[^.]+$/, '');
            const format = formatMap[ext.replace('.', '')] || 'truetype';
            if (fsCustomFonts.some(f => f.name === fontName)) { fsShowToast(`字体已存在:${fontName}`, 'error'); return; }
            const reader = new FileReader();
            reader.onload = function(e) { fsAddUploadedFont(fontName, e.target.result, format); };
            reader.onerror = function() { fsShowToast(`读取失败:${file.name}`, 'error'); };
            reader.readAsDataURL(file);
        });
    }

    /**
     * 懒加载自定义字体:仅为当前激活的字体注入 @font-face
     * 非激活字体等到用户选择时再加载,大幅减少页面初始注入量
     */
    function fsReloadCustomFonts() {
        if (!fsActiveFontValue || !fsIsEnabled) return;
        // 找到当前激活的自定义字体
        const activeFont = fsCustomFonts.find(f => f.value === fsActiveFontValue);
        if (activeFont) {
            const url = activeFont.dataUrl || activeFont.url;
            if (url) fsLoadCustomFontFace(activeFont.name, url, activeFont.format || null);
        }
    }

    // ==================== 滑块进度更新工具 ====================

    function fsUpdateRangeProgress(rangeEl) {
        const min = parseFloat(rangeEl.min) || 0;
        const max = parseFloat(rangeEl.max) || 100;
        const val = parseFloat(rangeEl.value) || min;
        const pct = ((val - min) / (max - min)) * 100;
        rangeEl.style.setProperty('--range-pct', pct + '%');
    }

    // ==================== 设置视图渲染 ====================

    function fsRenderSettingsView() {
        const view = document.getElementById('fs-settings-view');
        view.innerHTML = '';

        // --- 外观 ---
        const secAppearance = document.createElement('div');
        secAppearance.className = 'fs-sv-section';
        secAppearance.innerHTML = `<div class="fs-sv-section-title">外观</div>`;

        const rowBtnSize = document.createElement('div');
        rowBtnSize.className = 'fs-sv-row';
        const btnPreviewSize = Math.max(12, Math.round(FS_BTN_SIZE * 0.42));
        rowBtnSize.innerHTML = `
            <span class="fs-sv-row-label">按钮大小<small>拖动滑块调整悬浮按钮尺寸</small></span>
            <div class="fs-sv-row-right">
                <div class="fs-sv-btn-preview" id="fs-sv-btnPreview" style="width:${btnPreviewSize}px;height:${btnPreviewSize}px;"></div>
                <div class="fs-sv-range-wrapper">
                    <input type="range" class="fs-sv-range" id="fs-sv-btnSize"
                           min="28" max="60" step="2" value="${FS_BTN_SIZE}">
                    <span class="fs-sv-range-value" id="fs-sv-btnSize-val">${FS_BTN_SIZE}px</span>
                </div>
            </div>
        `;
        secAppearance.appendChild(rowBtnSize);

        const rowExcludeInputs = document.createElement('div');
        rowExcludeInputs.className = 'fs-sv-row';
        rowExcludeInputs.innerHTML = `
            <span class="fs-sv-row-label">排除输入框<small>不对 input / textarea / select 应用字体</small></span>
            <div class="fs-sv-row-right">
                <label class="fs-sv-toggle">
                    <input type="checkbox" id="fs-sv-excludeInputs" ${fsGlobalSettings.excludeInputs ? 'checked' : ''}>
                    <span class="fs-sv-toggle-slider"></span>
                </label>
            </div>
        `;
        secAppearance.appendChild(rowExcludeInputs);
        view.appendChild(secAppearance);

        // --- 行为 ---
        const secBehavior = document.createElement('div');
        secBehavior.className = 'fs-sv-section';
        secBehavior.innerHTML = `<div class="fs-sv-section-title">行为</div>`;

        const rowSnapToEdge = document.createElement('div');
        rowSnapToEdge.className = 'fs-sv-row';
        rowSnapToEdge.innerHTML = `
            <span class="fs-sv-row-label">吸附到边缘<small>拖动后自动贴靠屏幕左/右边缘,关闭后可自由放置</small></span>
            <div class="fs-sv-row-right">
                <label class="fs-sv-toggle">
                    <input type="checkbox" id="fs-sv-snapToEdge" ${fsGlobalSettings.snapToEdge !== false ? 'checked' : ''}>
                    <span class="fs-sv-toggle-slider"></span>
                </label>
            </div>
        `;
        secBehavior.appendChild(rowSnapToEdge);

        const rowAutoCollapse = document.createElement('div');
        rowAutoCollapse.className = 'fs-sv-row';
        rowAutoCollapse.innerHTML = `
            <span class="fs-sv-row-label">自动吸附收起<small>闲置后按钮收缩至屏幕边缘</small></span>
            <div class="fs-sv-row-right">
                <label class="fs-sv-toggle">
                    <input type="checkbox" id="fs-sv-autoCollapse" ${fsGlobalSettings.autoCollapse ? 'checked' : ''}>
                    <span class="fs-sv-toggle-slider"></span>
                </label>
            </div>
        `;
        secBehavior.appendChild(rowAutoCollapse);

        const rowIdleMs = document.createElement('div');
        rowIdleMs.className = 'fs-sv-row';
        rowIdleMs.innerHTML = `
            <span class="fs-sv-row-label">收起延迟<small>闲置多久后自动收起</small></span>
            <div class="fs-sv-row-right">
                <select class="fs-sv-select" id="fs-sv-idleMs">
                    <option value="3000" ${fsGlobalSettings.idleMs === 3000 ? 'selected' : ''}>3 秒</option>
                    <option value="5000" ${fsGlobalSettings.idleMs === 5000 ? 'selected' : ''}>5 秒</option>
                    <option value="10000" ${fsGlobalSettings.idleMs === 10000 ? 'selected' : ''}>10 秒</option>
                    <option value="15000" ${fsGlobalSettings.idleMs === 15000 ? 'selected' : ''}>15 秒</option>
                    <option value="30000" ${fsGlobalSettings.idleMs === 30000 ? 'selected' : ''}>30 秒</option>
                </select>
            </div>
        `;
        secBehavior.appendChild(rowIdleMs);

        const rowToast = document.createElement('div');
        rowToast.className = 'fs-sv-row';
        rowToast.innerHTML = `
            <span class="fs-sv-row-label">提示显示时长<small>操作反馈提示的持续时间</small></span>
            <div class="fs-sv-row-right">
                <select class="fs-sv-select" id="fs-sv-toastDuration">
                    <option value="1000" ${fsGlobalSettings.toastDuration === 1000 ? 'selected' : ''}>1 秒</option>
                    <option value="2000" ${fsGlobalSettings.toastDuration === 2000 ? 'selected' : ''}>2 秒</option>
                    <option value="3000" ${fsGlobalSettings.toastDuration === 3000 ? 'selected' : ''}>3 秒</option>
                </select>
            </div>
        `;
        secBehavior.appendChild(rowToast);
        view.appendChild(secBehavior);

        // --- 字体管理 ---
        const secFonts = document.createElement('div');
        secFonts.className = 'fs-sv-section';
        secFonts.innerHTML = `<div class="fs-sv-section-title">字体管理</div>`;

        const rowUpload = document.createElement('div');
        rowUpload.style.cssText = 'padding: 4px 0;';
        rowUpload.innerHTML = `
            <button class="fs-sv-upload-btn" id="fs-sv-upload-btn">&#128194; 选择字体文件</button>
            <div class="fs-sv-upload-hint">支持 .woff2 / .woff / .ttf / .otf 格式,全局共享</div>
        `;
        secFonts.appendChild(rowUpload);

        if (fsCustomFonts.length > 0) {
            const rowFontCount = document.createElement('div');
            rowFontCount.className = 'fs-sv-row';
            rowFontCount.innerHTML = `
                <span class="fs-sv-row-label">已导入 ${fsCustomFonts.length} 个自定义字体</span>
                <div class="fs-sv-row-right">
                    <button class="fs-sv-btn fs-sv-btn-danger" id="fs-sv-clearFonts">全部清除</button>
                </div>
            `;
            secFonts.appendChild(rowFontCount);
        }
        view.appendChild(secFonts);

        // --- 数据 ---
        const secData = document.createElement('div');
        secData.className = 'fs-sv-section';
        secData.innerHTML = `<div class="fs-sv-section-title">数据</div>`;

        const rowResetPos = document.createElement('div');
        rowResetPos.className = 'fs-sv-row';
        rowResetPos.innerHTML = `
            <span class="fs-sv-row-label">重置按钮位置<small>将悬浮按钮恢复到默认位置</small></span>
            <div class="fs-sv-row-right">
                <button class="fs-sv-btn" id="fs-sv-resetPos">重置</button>
            </div>
        `;
        secData.appendChild(rowResetPos);

        const rowResetSite = document.createElement('div');
        rowResetSite.className = 'fs-sv-row';
        rowResetSite.innerHTML = `
            <span class="fs-sv-row-label">重置当前站点设置<small>清除本站的字体选择和字号等设置</small></span>
            <div class="fs-sv-row-right">
                <button class="fs-sv-btn fs-sv-btn-danger" id="fs-sv-resetSite">重置</button>
            </div>
        `;
        secData.appendChild(rowResetSite);
        view.appendChild(secData);

        // ========== 绑定设置事件 ==========

        const btnSizeRange = document.getElementById('fs-sv-btnSize');
        const btnSizeVal = document.getElementById('fs-sv-btnSize-val');
        const btnPreview = document.getElementById('fs-sv-btnPreview');
        fsUpdateRangeProgress(btnSizeRange);

        btnSizeRange.addEventListener('input', function() {
            const val = parseInt(this.value);
            btnSizeVal.textContent = val + 'px';
            fsUpdateRangeProgress(this);
            const previewPx = Math.max(12, Math.round(val * 0.42));
            btnPreview.style.width = previewPx + 'px';
            btnPreview.style.height = previewPx + 'px';
            fsGlobalSettings.btnSize = val;
            fsSaveGlobalSettings();
            fsRefreshDerivedSettings();
            fsUpdateStyles();
            fsClampBtnPos();
            fsApplyBtnPosition();
        });
        btnSizeRange.addEventListener('change', function() {
            fsShowToast(`按钮大小已更新为 ${this.value}px`, 'info');
        });

        document.getElementById('fs-sv-excludeInputs').addEventListener('change', function() {
            fsGlobalSettings.excludeInputs = this.checked;
            fsSaveGlobalSettings();
            if (fsActiveFontValue && fsIsEnabled) fsApplyFont(fsActiveFontValue);
            fsShowToast(this.checked ? '已排除输入框' : '输入框将应用字体', 'info');
        });

        document.getElementById('fs-sv-snapToEdge').addEventListener('change', function() {
            fsGlobalSettings.snapToEdge = this.checked;
            fsSaveGlobalSettings();
            fsClosePanel();

            if (this.checked) {
                const rect = fsTriggerBtn.getBoundingClientRect();
                fsBtnSide = (rect.left + rect.width / 2) < window.innerWidth / 2 ? 'left' : 'right';
                fsBtnY = rect.top;
                fsClampBtnPos();
                fsSaveBtnPosition();
                fsTriggerBtn.style.right = 'auto';
                fsTriggerBtn.style.left = rect.left + 'px';
                fsTriggerBtn.style.top = fsBtnY + 'px';
                fsTriggerBtn.classList.remove('fs-side-left', 'fs-side-right', 'fs-free');
                fsTriggerBtn.classList.add('fs-snapping');
                const targetLeft = fsBtnSide === 'left' ? 0 : window.innerWidth - FS_BTN_SIZE;
                const targetRadius = fsBtnSide === 'left'
                    ? `0 ${FS_BTN_SIZE / 2}px ${FS_BTN_SIZE / 2}px 0`
                    : `${FS_BTN_SIZE / 2}px 0 0 ${FS_BTN_SIZE / 2}px`;
                fsTriggerBtn.style.left = targetLeft + 'px';
                fsTriggerBtn.style.borderRadius = targetRadius;
                let snapFinished = false;
                const finishSnap = () => {
                    if (snapFinished) return;
                    snapFinished = true;
                    fsTriggerBtn.removeEventListener('transitionend', onSnapEnd);
                    fsTriggerBtn.classList.remove('fs-snapping');
                    fsTriggerBtn.style.borderRadius = '';
                    fsApplyBtnPosition();
                    fsResetIdleTimer();
                };
                const onSnapEnd = (evt) => { if (evt.propertyName !== 'left') return; finishSnap(); };
                fsTriggerBtn.addEventListener('transitionend', onSnapEnd);
                setTimeout(finishSnap, 450);
            } else {
                const rect = fsTriggerBtn.getBoundingClientRect();
                fsBtnX = rect.left;
                fsBtnY = rect.top;
                if (fsBtnCollapsed) fsExpandBtn();
                if (fsIdleTimer) clearTimeout(fsIdleTimer);
                fsClampBtnPos();
                fsSaveBtnPosition();
                fsApplyBtnPosition();
                fsResetIdleTimer();
            }
            fsShowToast(this.checked ? '已开启边缘吸附' : '已关闭边缘吸附,可自由拖动', 'info');
        });

        document.getElementById('fs-sv-autoCollapse').addEventListener('change', function() {
            fsGlobalSettings.autoCollapse = this.checked;
            fsSaveGlobalSettings();
            fsRefreshDerivedSettings();
            if (this.checked) fsResetIdleTimer();
            else { if (fsIdleTimer) clearTimeout(fsIdleTimer); if (fsBtnCollapsed) fsExpandBtn(); }
            fsShowToast(this.checked ? '已开启自动收起' : '已关闭自动收起', 'info');
        });

        document.getElementById('fs-sv-idleMs').addEventListener('change', function() {
            fsGlobalSettings.idleMs = parseInt(this.value);
            fsSaveGlobalSettings();
            fsRefreshDerivedSettings();
            fsResetIdleTimer();
            fsShowToast(`收起延迟已更新`, 'info');
        });

        document.getElementById('fs-sv-toastDuration').addEventListener('change', function() {
            fsGlobalSettings.toastDuration = parseInt(this.value);
            fsSaveGlobalSettings();
            fsShowToast(`提示时长已更新`, 'info');
        });

        document.getElementById('fs-sv-upload-btn').addEventListener('click', () => { fsFontFileInput.click(); });

        const clearBtn = document.getElementById('fs-sv-clearFonts');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                if (!confirm('确认清除所有自定义字体?此操作不可撤销。')) return;
                fsCustomFonts.forEach(font => {
                    const faceId = 'fs-fontface-' + CSS.escape(font.name.replace(/\s+/g, '-'));
                    const faceEl = document.getElementById(faceId);
                    if (faceEl) faceEl.remove();
                    fsRemoveFontSettings(font.value);
                });
                if (fsCustomFonts.some(f => f.value === fsActiveFontValue)) {
                    fsActiveFontValue = '';
                    fsSaveToStorage(FS_STORAGE_KEY_ACTIVE_FONT, fsActiveFontValue);
                    fsApplyFont('');
                }
                fsCustomFonts = [];
                fsSaveToStorage(FS_STORAGE_KEY_CUSTOM_FONTS, fsCustomFonts);
                fsRenderSettingsView();
                fsShowToast('已清除所有自定义字体', 'info');
            });
        }

        document.getElementById('fs-sv-resetPos').addEventListener('click', () => {
            fsBtnSide = 'right'; fsBtnY = 60; fsBtnX = -1;
            fsSaveBtnPosition(); fsApplyBtnPosition(); fsClosePanel();
            fsShowToast('按钮位置已重置', 'info');
        });

        document.getElementById('fs-sv-resetSite').addEventListener('click', () => {
            if (!confirm('确认重置当前站点的所有字体设置?')) return;
            fsActiveFontValue = ''; fsIsEnabled = true; fsFontSettings = {};
            fsSaveToStorage(FS_STORAGE_KEY_ACTIVE_FONT, '');
            fsSaveToStorage(FS_STORAGE_KEY_ENABLED, true);
            fsSaveToStorage(FS_STORAGE_KEY_FONT_SETTINGS, {});
            fsApplyFont('');
            document.getElementById('fs-enabled-toggle').checked = true;
            fsExpandedSettingsSet.clear();
            fsRenderFontList(); fsClosePanel();
            fsShowToast('当前站点设置已重置', 'info');
        });
    }

    // ==================== 设置视图切换 ====================

    function fsToggleSettingsView() {
        fsSettingsViewActive = !fsSettingsViewActive;
        const listContainer = document.getElementById('fs-font-list');
        const settingsView = document.getElementById('fs-settings-view');
        const gearBtn = document.getElementById('fs-header-gear-btn');
        const toggleRow = fsPanel.querySelector('.fs-toggle-row');

        if (fsSettingsViewActive) {
            listContainer.style.display = 'none';
            toggleRow.style.display = 'none';
            settingsView.style.display = 'block';
            gearBtn.classList.add('fs-gear-active');
            fsRenderSettingsView();
        } else {
            listContainer.style.display = '';
            toggleRow.style.display = '';
            settingsView.style.display = 'none';
            gearBtn.classList.remove('fs-gear-active');
        }
    }

    // ==================== 面板控制 ====================

    function fsTogglePanel() {
        fsPanelVisible = !fsPanelVisible;
        if (fsPanelVisible) {
            if (fsSettingsViewActive) fsToggleSettingsView();
            fsPositionPanel();
            fsPanel.classList.add('fs-show');
            fsOverlay.classList.add('fs-show');
            fsTriggerBtn.classList.add('fs-active');
            if (fsIdleTimer) clearTimeout(fsIdleTimer);
        } else {
            fsPanel.classList.remove('fs-show');
            fsOverlay.classList.remove('fs-show');
            fsTriggerBtn.classList.remove('fs-active');
            if (fsSettingsViewActive) {
                fsSettingsViewActive = false;
                document.getElementById('fs-font-list').style.display = '';
                fsPanel.querySelector('.fs-toggle-row').style.display = '';
                document.getElementById('fs-settings-view').style.display = 'none';
                document.getElementById('fs-header-gear-btn').classList.remove('fs-gear-active');
            }
            fsResetIdleTimer();
        }
    }

    function fsClosePanel() {
        if (!fsPanelVisible) return;
        fsPanelVisible = false;
        fsPanel.classList.remove('fs-show');
        fsOverlay.classList.remove('fs-show');
        fsTriggerBtn.classList.remove('fs-active');
        if (fsSettingsViewActive) {
            fsSettingsViewActive = false;
            document.getElementById('fs-font-list').style.display = '';
            fsPanel.querySelector('.fs-toggle-row').style.display = '';
            document.getElementById('fs-settings-view').style.display = 'none';
            document.getElementById('fs-header-gear-btn').classList.remove('fs-gear-active');
        }
        fsResetIdleTimer();
    }

    // ==================== Toast ====================

    let fsToastTimer = null;
    let fsToastHideTimer = null;
    function fsShowToast(msg, type = 'info') {
        if (fsToastTimer) clearTimeout(fsToastTimer);
        if (fsToastHideTimer) clearTimeout(fsToastHideTimer);
        fsToast.textContent = msg;
        fsToast.className = 'fs-toast-' + type + ' fs-toast-show';
        fsToastTimer = setTimeout(() => {
            fsToast.classList.remove('fs-toast-show');
            fsToastHideTimer = setTimeout(() => { fsToast.className = ''; fsToastHideTimer = null; }, 320);
            fsToastTimer = null;
        }, fsGlobalSettings.toastDuration || 2000);
    }

    // ==================== 事件绑定 ====================

    fsOverlay.addEventListener('click', fsClosePanel);
    fsPanel.querySelector('.fs-header-close').addEventListener('click', fsClosePanel);
    document.getElementById('fs-header-gear-btn').addEventListener('click', (e) => {
        e.stopPropagation();
        fsToggleSettingsView();
    });

    const fsEnabledToggle = document.getElementById('fs-enabled-toggle');
    fsEnabledToggle.checked = fsIsEnabled;
    fsEnabledToggle.addEventListener('change', () => {
        fsIsEnabled = fsEnabledToggle.checked;
        fsSaveToStorage(FS_STORAGE_KEY_ENABLED, fsIsEnabled);
        if (fsIsEnabled && fsActiveFontValue) fsApplyFont(fsActiveFontValue);
        else fsApplyFont('');
        fsShowToast(fsIsEnabled ? `字体替换已启用(${FS_CURRENT_HOST})` : `字体替换已关闭(${FS_CURRENT_HOST})`, 'info');
    });

    fsFontFileInput.addEventListener('change', (e) => {
        fsHandleFontFileUpload(e.target.files);
        e.target.value = '';
        if (fsSettingsViewActive) fsRenderSettingsView();
    });

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

    function fsInitExpandedSettings() {
        const allFonts = [...FS_PRESET_FONTS, ...fsCustomFonts];
        allFonts.forEach(font => {
            if (font.value && fsHasNonDefaultSettings(font.value)) fsExpandedSettingsSet.add(font.value);
        });
    }

    function fsInit() {
        fsDetectAllFonts();
        fsReloadCustomFonts();
        fsInitExpandedSettings();
        fsRenderFontList();
        fsClampBtnPos();
        fsApplyBtnPosition();
        if (fsIsEnabled && fsActiveFontValue) fsApplyFont(fsActiveFontValue);
        setTimeout(() => { fsTriggerBtn.classList.remove('fs-entering'); }, 500);
        fsResetIdleTimer();
    }

    // ================================================================
    //  主入口:初始化两个模块
    // ================================================================

    function main() {
        // 字体更换器:所有站点运行
        fsInit();

        // BZOJ 测试点模块:仅 bzoj.org 下运行(init 内部有双重判断)
        BZOJ_TestcaseModule.init();
    }

    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        main();
    } else {
        document.addEventListener('DOMContentLoaded', main);
    }

})();