☰

Brilliant Chess

Brilliant Chess is the most advanced Chess.com & Lichess assistant. Powered by Stockfish 19 and Maia-3 — real-time best moves, eval bar, humanized play, auto-move, puzzle solver. Get your free key on Discord (discord.gg/9eSM5dhdnv), enter it once, menu opens forever. By Bayarsaikhan Enhtulga.

Voor het installeren van scripts heb je een extensie nodig, zoals Tampermonkey, Greasemonkey of Violentmonkey.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

Voor het installeren van scripts heb je een extensie nodig, zoals Tampermonkey of Violentmonkey.

Voor het installeren van scripts heb je een extensie nodig, zoals Tampermonkey of Userscripts.

Voor het installeren van scripts heb je een extensie nodig, zoals {tampermonkey_link:Tampermonkey}.

Voor het installeren van scripts heb je een gebruikersscriptbeheerder nodig.

(Ik heb al een user script manager, laat me het downloaden!)

Voor het installeren van gebruikersstijlen heb je een extensie nodig, zoals {stylus_link:Stylus}.

Voor het installeren van gebruikersstijlen heb je een extensie nodig, zoals {stylus_link:Stylus}.

Voor het installeren van gebruikersstijlen heb je een extensie nodig, zoals {stylus_link:Stylus}.

Voor het installeren van gebruikersstijlen heb je een gebruikersstijlbeheerder nodig.

Voor het installeren van gebruikersstijlen heb je een gebruikersstijlbeheerder nodig.

Voor het installeren van gebruikersstijlen heb je een gebruikersstijlbeheerder nodig.

(Ik heb al een beheerder - laat me doorgaan met de installatie!)

// ==UserScript==
// @name          Brilliant Chess
// @namespace     http://tampermonkey.net/
// @version       14.1.0
// @description   Brilliant Chess is the most advanced Chess.com & Lichess assistant. Powered by Stockfish 19 and Maia-3 — real-time best moves, eval bar, humanized play, auto-move, puzzle solver. Get your free key on Discord (discord.gg/9eSM5dhdnv), enter it once, menu opens forever. By Bayarsaikhan Enhtulga.
// @author        Bayarsaikhan Enhtulga
// @copyright     2026, Bayarsaikhan Enhtulga
// @license       MIT
// @match         https://www.chess.com/play
// @match         https://www.chess.com/play/*
// @match         https://www.chess.com/game/*
// @match         https://www.chess.com/analysis
// @match         https://www.chess.com/analysis/*
// @match         https://www.chess.com/puzzles/*
// @match         https://www.chess.com/daily
// @match         https://www.chess.com/daily/*
// @match         https://lichess.org/*
// @connect       chess-api.com
// @connect       stockfish.online
// @connect       unpkg.com
// @connect       cdnjs.cloudflare.com
// @connect       cdn.jsdelivr.net
// @connect       huggingface.co
// @connect       *
// @grant         GM_getResourceText
// @grant         GM_getValue
// @grant         GM_setValue
// @grant         GM_xmlhttpRequest
// @grant         unsafeWindow
// @resource      stockfish.js https://unpkg.com/[email protected]/bin/stockfish-19-lite-single.js
// @run-at        document-start
// ==/UserScript==
(function () {
    "use strict";

    // =========================================================
    //  KEY SYSTEM — Brilliant Chess
    //  DISCORD: https://discord.gg/9eSM5dhdnv  (free keys here)
    //  1-day key  : BC20261130-xxxxxxxxxxxxxxxx  (valid today only)
    //  Lifetime   : BCL-N-xxxxxxxxxxxxxxxx  (N = any number, unlimited)
    //  Generate in browser console:
    //    await generateKey("20261130")   → 1-day key for that date
    //    await generateKey(5)            → lifetime key #5
    //    await generateKey(99)           → lifetime key #99  (unlimited)
    //  One key per user. Once unlocked → menu opens directly forever.
    // =========================================================
    const KEY_SECRET  = "brilliant-chess-enhtulgaa-2026"; // keep private
    const DISCORD_URL = "https://discord.gg/9eSM5dhdnv";

    async function _hmacSHA256(secret, message) {
        const enc = new TextEncoder();
        const keyMat = await crypto.subtle.importKey(
            "raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]
        );
        const sig = await crypto.subtle.sign("HMAC", keyMat, enc.encode(message));
        return btoa(String.fromCharCode(...new Uint8Array(sig)));
    }

    // input = "20261130"  → 1-day key
    // input = 1,2,3,...   → lifetime key #N (unlimited, one per user)
    async function generateKey(input) {
        const isLifetime = typeof input === "number" || /^\d+$/.test(String(input)) && !String(input).includes("-");
        if (isLifetime) {
            const n = parseInt(input, 10);
            const mac   = await _hmacSHA256(KEY_SECRET, `LIFETIME${n}`);
            const short = mac.replace(/[^a-zA-Z0-9]/g, "").slice(0, 16).toLowerCase();
            return `BCL-${n}-${short}`;
        }
        // 1-day key
        const mac   = await _hmacSHA256(KEY_SECRET, String(input));
        const short = mac.replace(/[^a-zA-Z0-9]/g, "").slice(0, 16).toLowerCase();
        return `BC${input}-${short}`;
    }
    try { unsafeWindow.generateKey = generateKey; } catch(_) { try { window.generateKey = generateKey; } catch(__) {} }

    async function _validateKey(key) {
        if (!key || typeof key !== "string") return false;

        // Lifetime key: BCL-N-hash (N = any positive integer)
        const ltMatch = key.match(/^BCL-(\d+)-([a-z0-9]{16})$/);
        if (ltMatch) {
            const n = parseInt(ltMatch[1], 10);
            const supplied = ltMatch[2];
            const mac   = await _hmacSHA256(KEY_SECRET, `LIFETIME${n}`);
            const short = mac.replace(/[^a-zA-Z0-9]/g, "").slice(0, 16).toLowerCase();
            return supplied === short;
        }

        // 1-day key: BCYYYYMMDD-hash
        const match = key.match(/^BC(\d{8})-([a-z0-9]{16})$/);
        if (!match) return false;
        const dateStr = match[1], supplied = match[2];
        const y  = parseInt(dateStr.slice(0,4),10);
        const mo = parseInt(dateStr.slice(4,6),10) - 1;
        const d  = parseInt(dateStr.slice(6,8),10);
        const keyDate  = new Date(Date.UTC(y, mo, d));
        const now      = new Date();
        const todayUTC = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
        if (keyDate.getTime() !== todayUTC.getTime()) return false;
        const expected = await generateKey(dateStr);
        return supplied === expected.split("-")[1];
    }

    function _getKey()   { try { const v = GM_getValue("bc_key",null); return v; } catch(_) { try { const v = localStorage.getItem("bc_key"); return v ? JSON.parse(v) : null; } catch(__) { return null; } } }
    function _setKey(v)  { try { GM_setValue("bc_key", v); } catch(_) {} try { localStorage.setItem("bc_key", JSON.stringify(v)); } catch(__) {} }
    function _clearKey() { try { GM_setValue("bc_key", null); } catch(_) {} try { localStorage.removeItem("bc_key"); } catch(__) {} }

    function _showKeyScreen(onUnlock) {
        const waitForBody = (cb) => {
            if (document.body) { cb(); return; }
            const obs = new MutationObserver(() => { if (document.body) { obs.disconnect(); cb(); } });
            obs.observe(document.documentElement, { childList: true });
        };
        waitForBody(() => {
            const mount = document.createElement("div");
            mount.id = "bcKeyMount";
            mount.style.cssText = "position:fixed;top:0;left:0;width:0;height:0;z-index:2147483647;";
            const shadow = mount.attachShadow({ mode: "closed" });
            document.body.appendChild(mount);

            shadow.innerHTML = `
            <style>
                :host { all: initial; }
                * { box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
                .ov {
                    position: fixed; inset: 0;
                    background: rgba(0,0,0,0.90);
                    display: flex; align-items: center; justify-content: center;
                    z-index: 2147483647;
                    backdrop-filter: blur(12px);
                    pointer-events: all;
                }
                .card {
                    background: rgba(10,14,20,0.98);
                    border: 1px solid rgba(255,255,255,0.10);
                    border-radius: 20px;
                    padding: 38px 32px;
                    width: min(380px, 92vw);
                    display: flex; flex-direction: column; gap: 16px;
                    box-shadow:
                        0 32px 80px rgba(0,0,0,0.95),
                        0 0 0 1px rgba(46,160,67,0.12) inset,
                        0 1px 0 rgba(255,255,255,0.08) inset;
                    color: #f0f6fc;
                    backdrop-filter: blur(32px) saturate(180%);
                    position: relative;
                    overflow: hidden;
                }
                .card::before {
                    content: '';
                    position: absolute;
                    top: 0; left: 0; right: 0;
                    height: 2px;
                    background: linear-gradient(90deg,
                        transparent 0%,
                        rgba(46,160,67,0.7) 30%,
                        rgba(63,185,80,0.9) 50%,
                        rgba(46,160,67,0.7) 70%,
                        transparent 100%);
                    pointer-events: none;
                }
                .logo {
                    text-align:center; font-size:28px; font-weight:900; letter-spacing:-0.8px;
                    text-shadow: 0 2px 12px rgba(0,0,0,0.5);
                }
                .logo span {
                    color:#3fb950;
                    text-shadow: 0 0 20px rgba(63,185,80,0.4);
                }
                .sub  { text-align:center; font-size:12px; color:#8b949e; line-height:1.7; margin-top:-4px; }
                .sub a { color:#7289da; text-decoration:none; }
                .sub a:hover { text-decoration:underline; }
                input {
                    width:100%; height:44px; padding:0 14px;
                    background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.14);
                    border-radius:9px; color:#f0f6fc; font-size:13px; font-family:monospace;
                    outline:none; transition:border-color 0.2s;
                }
                input:focus { border-color:rgba(46,160,67,0.6); }
                input.err   { border-color:rgba(248,81,73,0.7); }
                .btn {
                    width:100%; height:44px; border-radius:9px; font-size:13.5px; font-weight:700;
                    cursor:pointer; border:none; transition:opacity 0.15s, transform 0.1s;
                }
                .btn:active { transform:scale(0.98); }
                .btn-primary {
                    background: linear-gradient(135deg, #1a7f37, #2ea043, #3fb950);
                    color:#fff;
                    box-shadow: 0 4px 16px rgba(46,160,67,0.35), inset 0 1px 0 rgba(255,255,255,0.15);
                    transition: all 0.2s ease;
                    letter-spacing: 0.03em;
                }
                .btn-primary:hover {
                    transform: translateY(-1px);
                    box-shadow: 0 6px 20px rgba(46,160,67,0.45), inset 0 1px 0 rgba(255,255,255,0.15);
                }
                .btn-primary:active { transform: translateY(0); }
                .btn-discord {
                    background: rgba(88,101,242,0.15); color:#7289da;
                    border:1px solid rgba(114,137,218,0.35);
                    font-size:12.5px; height:40px;
                }
                .btn-discord:hover { background:rgba(88,101,242,0.28); }
                .err-msg { font-size:11.5px; color:#f85149; text-align:center; min-height:16px; }
                .divider { border:none; border-top:1px solid rgba(255,255,255,0.08); margin:0; }
                .note { font-size:11px; color:#484f58; text-align:center; line-height:1.5; }
            </style>
            <div class="ov">
              <div class="card">
                <div class="logo">Brilliant <span>Chess</span></div>
                <div class="sub">
                  Enter your key to unlock the full menu.<br>
                  Get a <strong style="color:#f0f6fc">free key</strong> by joining our Discord:<br>
                  <a href="https://discord.gg/9eSM5dhdnv" target="_blank">discord.gg/9eSM5dhdnv</a><br>
                  <span style="color:#484f58; font-size:10px;">by Bayarsaikhan Enhtulga</span>
                </div>
                <input type="text" id="keyInp" placeholder="BCL-1-xxxxxxxxxxxxxxxx" autocomplete="off" spellcheck="false">
                <div class="err-msg" id="errMsg"></div>
                <button class="btn btn-primary" id="unlockBtn">Unlock</button>
                <hr class="divider">
                <button class="btn btn-discord" id="discordBtn">🔗 Join Discord to get a free key</button>
                <div class="note">Once unlocked, the menu opens automatically on future visits.</div>
              </div>
            </div>`;

            const inp       = shadow.getElementById("keyInp");
            const errMsg    = shadow.getElementById("errMsg");
            const unlockBtn = shadow.getElementById("unlockBtn");

            shadow.getElementById("discordBtn").onclick = () => window.open(DISCORD_URL, "_blank");

            const tryUnlock = async () => {
                const val = inp.value.trim();
                if (!val) { errMsg.textContent = "Please enter a key."; inp.classList.add("err"); return; }
                unlockBtn.textContent = "Verifying...";
                unlockBtn.disabled = true;
                const ok = await _validateKey(val);
                if (ok) {
                    _setKey(val);
                    mount.remove();
                    onUnlock();
                } else {
                    errMsg.textContent = "Invalid or expired key.";
                    inp.classList.add("err");
                    unlockBtn.textContent = "Unlock";
                    unlockBtn.disabled = false;
                }
            };

            unlockBtn.onclick = tryUnlock;
            inp.addEventListener("keydown", e => { if (e.key === "Enter") tryUnlock(); });
            inp.oninput = () => { inp.classList.remove("err"); errMsg.textContent = ""; };
        });
    }

    // Per-user bypass: stored valid key → straight to menu, no screen shown
    async function _runKeyGate(onUnlock) {
        const stored = _getKey();
        if (stored) {
            const valid = await _validateKey(stored);
            if (valid) { onUnlock(); return; }
            _clearKey();
        }
        _showKeyScreen(onUnlock);
    }

    // --- CONFIGURATION ---
    const CONFIG = {
        BOARD_SEL: ".round__app__board cg-container, .round__app__board cg-board, chess-board, wc-chess-board, #board, .board",
        LOOP_MS: 15,
        API: { MAX_DEPTH: 18, MAX_TIME: 2000 }
    };

    const _pageWin = (typeof unsafeWindow !== "undefined") ? unsafeWindow : window;

    function isCgSite() {
        return Boolean(document.querySelector(".round__app__board cg-board, main.round"));
    }

    function getActiveGame() {
        if (isCgSite()) return getCgGameProxy();
        const cb = document.querySelector("chess-board, wc-chess-board");
        return state.board?.game || cb?.game || null;
    }

    function isBoardFlipped(boardEl) {
        const b = boardEl || state.board;
        if (!b) return false;
        if (b.classList?.contains("flipped")) return true;
        const cgWrap = b.closest?.(".cg-wrap");
        if (cgWrap?.classList?.contains("orientation-black")) return true;
        if (cgWrap?.classList?.contains("orientation-white")) return false;
        const g = getActiveGame();
        if (g?.getPlayingAs) {
            const pa = g.getPlayingAs();
            if (pa === "b" || pa === 2 || pa === "black") return true;
        }
        return false;
    }

    function positionSquareEl(el, alg, boardEl) {
        if (!isCgSite() || !el || !alg || alg.length < 2) return;
        const flipped = isBoardFlipped(boardEl);
        const file = alg.charCodeAt(0) - 97;
        const rank = parseInt(alg[1], 10) - 1;
        el.style.left = ((flipped ? (7 - file) : file) * 12.5) + "%";
        el.style.top = ((flipped ? rank : (7 - rank)) * 12.5) + "%";
    }

    // --- WEBSOCKET CAPTURE FOR LIVE CHESSGROUND GAMES ---
    const _wsState = {
        liveWs: null,
        ack: 0,
        lastMovesByPly: {},
        liveClock: null,
        ended: false
    };

    function hookWsInstance(ws) {
        if (!ws || ws._sfBotHooked) return;
        ws._sfBotHooked = true;
        ws.addEventListener("message", (ev) => {
            if (typeof ev.data !== "string" || !ev.data.startsWith("{")) return;
            let msg;
            try { msg = JSON.parse(ev.data); } catch (_) { return; }
            if (msg.t === "move" && msg.d) {
                if (typeof msg.d.ply === "number" && msg.d.uci) {
                    _wsState.lastMovesByPly[msg.d.ply] = msg.d.uci;
                }
                if (msg.d.clock && typeof msg.d.clock.white === "number" && typeof msg.d.clock.black === "number") {
                    _wsState.liveClock = {
                        wMs: Math.max(100, Math.round(msg.d.clock.white * 1000)),
                        bMs: Math.max(100, Math.round(msg.d.clock.black * 1000))
                    };
                }
                if (msg.d.status && msg.d.status.id && msg.d.status.id >= 30) {
                    _wsState.ended = true;
                }
            } else if (msg.t === "endData") {
                _wsState.ended = true;
            }
        });
    }

    (function installWsHooks() {
        try {
            const OrigWS = _pageWin.WebSocket;
            if (OrigWS && !OrigWS._sfWrapped) {
                const WrappedWS = function (url, protocols) {
                    const ws = protocols !== undefined ? new OrigWS(url, protocols) : new OrigWS(url);
                    const uStr = String(url || "");
                    if (!uStr.includes("chess-api.com") && !uStr.includes("stockfish.online")) {
                        _wsState.liveWs = ws;
                        _wsState.ack = 0;
                        _wsState.lastMovesByPly = {};
                        _wsState.liveClock = null;
                        _wsState.ended = false;
                        hookWsInstance(ws);
                    }
                    return ws;
                };
                WrappedWS.prototype = OrigWS.prototype;
                Object.setPrototypeOf(WrappedWS, OrigWS);
                WrappedWS._sfWrapped = true;
                _pageWin.WebSocket = WrappedWS;
            }
            const proto = _pageWin.WebSocket?.prototype || WebSocket.prototype;
            if (proto && !proto._sfSendHooked) {
                proto._sfSendHooked = true;
                const origSend = proto.send;
                proto.send = function (data) {
                    const url = String(this.url || "");
                    if (!url.includes("chess-api.com") && !url.includes("stockfish.online")) {
                        if (_wsState.liveWs !== this && this.readyState === 1) {
                            _wsState.liveWs = this;
                            _wsState.ack = 0;
                        }
                        hookWsInstance(this);
                        if (typeof data === "string" && data.startsWith("{")) {
                            try {
                                const j = JSON.parse(data);
                                if (j.t === "move" && j.d && typeof j.d.a === "number") {
                                    _wsState.ack = Math.max(_wsState.ack, j.d.a);
                                }
                            } catch (_) {}
                        }
                    }
                    return origSend.apply(this, arguments);
                };
            }
        } catch (_) {}
    })();

    // --- ZERO-DEPENDENCY CHESS STATE TRACKER (FULL FEN / LEGAL MOVES / SAN) ---
    class ChessMini {
        constructor(fen) {
            this.load(fen || "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
        }
        load(fen) {
            const parts = String(fen).trim().split(/\s+/);
            const rows = (parts[0] || "8/8/8/8/8/8/8/8").split("/");
            this.b = new Array(64).fill(".");
            for (let r = 0; r < 8 && r < rows.length; r++) {
                let c = 0;
                for (const ch of rows[r]) {
                    if (ch >= "1" && ch <= "8") c += parseInt(ch, 10);
                    else if (c < 8) this.b[r * 8 + c++] = ch;
                }
            }
            this.turn = parts[1] === "b" ? "b" : "w";
            this.castling = parts[2] || "-";
            if (parts[3] && /^[a-h][1-8]$/i.test(parts[3])) {
                const ep = parts[3].toLowerCase();
                this.ep = (8 - parseInt(ep[1], 10)) * 8 + (ep.charCodeAt(0) - 97);
            } else {
                this.ep = -1;
            }
            this.half = parseInt(parts[4], 10) || 0;
            this.full = parseInt(parts[5], 10) || 1;
        }
        sqName(idx) {
            return String.fromCharCode(97 + (idx % 8)) + (8 - Math.floor(idx / 8));
        }
        fen() {
            const rows = [];
            for (let r = 0; r < 8; r++) {
                let s = "", empty = 0;
                for (let f = 0; f < 8; f++) {
                    const ch = this.b[r * 8 + f];
                    if (ch === ".") empty++;
                    else { if (empty) { s += empty; empty = 0; } s += ch; }
                }
                if (empty) s += empty;
                rows.push(s);
            }
            const epStr = this.ep >= 0 ? this.sqName(this.ep) : "-";
            return `${rows.join("/")} ${this.turn} ${this.castling || "-"} ${epStr} ${this.half} ${this.full}`;
        }
        isFriendly(ch, side = this.turn) {
            return ch !== "." && (side === "w" ? ch === ch.toUpperCase() : ch === ch.toLowerCase());
        }
        isEnemy(ch, side = this.turn) {
            return ch !== "." && !this.isFriendly(ch, side);
        }
        genLegalMoves() {
            const side = this.turn;
            const isW = side === "w";
            const moves = [];
            const push = (fromIdx, toIdx, promo = "") => {
                moves.push({
                    fromIdx, toIdx,
                    from: this.sqName(fromIdx),
                    to: this.sqName(toIdx),
                    fromF: fromIdx % 8,
                    fromR: Math.floor(fromIdx / 8),
                    piece: this.b[fromIdx].toLowerCase(),
                    promotion: promo
                });
            };
            for (let idx = 0; idx < 64; idx++) {
                const raw = this.b[idx];
                if (!this.isFriendly(raw, side)) continue;
                const p = raw.toLowerCase();
                const r = Math.floor(idx / 8), f = idx % 8;
                if (p === "p") {
                    const dir = isW ? -1 : 1;
                    const startR = isW ? 6 : 1;
                    const promoR = isW ? 0 : 7;
                    const r1 = r + dir;
                    if (r1 >= 0 && r1 < 8) {
                        const t1 = r1 * 8 + f;
                        if (this.b[t1] === ".") {
                            if (r1 === promoR) { for (const pr of ["q","r","b","n"]) push(idx, t1, pr); }
                            else {
                                push(idx, t1);
                                if (r === startR) {
                                    const t2 = (r + dir * 2) * 8 + f;
                                    if (this.b[t2] === ".") push(idx, t2);
                                }
                            }
                        }
                        for (const df of [-1, 1]) {
                            const cf = f + df;
                            if (cf < 0 || cf > 7) continue;
                            const tc = r1 * 8 + cf;
                            if (this.isEnemy(this.b[tc], side) || tc === this.ep) {
                                if (r1 === promoR) { for (const pr of ["q","r","b","n"]) push(idx, tc, pr); }
                                else push(idx, tc);
                            }
                        }
                    }
                } else if (p === "n") {
                    for (const [dr, df] of [[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]]) {
                        const rr = r + dr, ff = f + df;
                        if (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                            const tc = rr * 8 + ff;
                            if (!this.isFriendly(this.b[tc], side)) push(idx, tc);
                        }
                    }
                } else if (p === "k") {
                    for (let dr = -1; dr <= 1; dr++) for (let df = -1; df <= 1; df++) {
                        if (!dr && !df) continue;
                        const rr = r + dr, ff = f + df;
                        if (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                            const tc = rr * 8 + ff;
                            if (!this.isFriendly(this.b[tc], side)) push(idx, tc);
                        }
                    }
                    if (isW && idx === 60) {
                        if (this.castling.includes("K") && this.b[61] === "." && this.b[62] === "." && this.b[63] === "R" &&
                            !isAttackedBy(this.b, 60, false) && !isAttackedBy(this.b, 61, false) && !isAttackedBy(this.b, 62, false)) {
                            push(60, 62);
                        }
                        if (this.castling.includes("Q") && this.b[59] === "." && this.b[58] === "." && this.b[57] === "." && this.b[56] === "R" &&
                            !isAttackedBy(this.b, 60, false) && !isAttackedBy(this.b, 59, false) && !isAttackedBy(this.b, 58, false)) {
                            push(60, 58);
                        }
                    } else if (!isW && idx === 4) {
                        if (this.castling.includes("k") && this.b[5] === "." && this.b[6] === "." && this.b[7] === "r" &&
                            !isAttackedBy(this.b, 4, true) && !isAttackedBy(this.b, 5, true) && !isAttackedBy(this.b, 6, true)) {
                            push(4, 6);
                        }
                        if (this.castling.includes("q") && this.b[3] === "." && this.b[2] === "." && this.b[1] === "." && this.b[0] === "r" &&
                            !isAttackedBy(this.b, 4, true) && !isAttackedBy(this.b, 3, true) && !isAttackedBy(this.b, 2, true)) {
                            push(4, 2);
                        }
                    }
                } else {
                    const dirs = [];
                    if (p === "b" || p === "q") dirs.push([-1,-1],[-1,1],[1,-1],[1,1]);
                    if (p === "r" || p === "q") dirs.push([-1,0],[1,0],[0,-1],[0,1]);
                    for (const [dr, df] of dirs) {
                        let rr = r + dr, ff = f + df;
                        while (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                            const tc = rr * 8 + ff;
                            if (this.b[tc] === ".") push(idx, tc);
                            else {
                                if (this.isEnemy(this.b[tc], side)) push(idx, tc);
                                break;
                            }
                            rr += dr; ff += df;
                        }
                    }
                }
            }
            const kChar = isW ? "K" : "k";
            return moves.filter(mv => {
                const sim = this.applySim(mv);
                const kIdx = sim.indexOf(kChar);
                return kIdx >= 0 && !isAttackedBy(sim, kIdx, !isW);
            });
        }
        applySim(mv) {
            const sim = this.b.slice();
            const isW = this.turn === "w";
            const raw = sim[mv.fromIdx];
            if (mv.piece === "p" && mv.toIdx === this.ep && sim[mv.toIdx] === ".") {
                sim[mv.fromR * 8 + (mv.toIdx % 8)] = ".";
            }
            sim[mv.toIdx] = mv.promotion ? (isW ? mv.promotion.toUpperCase() : mv.promotion.toLowerCase()) : raw;
            sim[mv.fromIdx] = ".";
            if (mv.piece === "k" && Math.abs((mv.toIdx % 8) - mv.fromF) === 2) {
                if (mv.toIdx === 62) { sim[61] = sim[63]; sim[63] = "."; }
                else if (mv.toIdx === 58) { sim[59] = sim[56]; sim[56] = "."; }
                else if (mv.toIdx === 6) { sim[5] = sim[7]; sim[7] = "."; }
                else if (mv.toIdx === 2) { sim[3] = sim[0]; sim[0] = "."; }
            }
            return sim;
        }
        commitMove(mv) {
            const isW = this.turn === "w";
            const cap = this.b[mv.toIdx];
            this.b = this.applySim(mv);
            if (mv.piece === "p" || cap !== ".") this.half = 0;
            else this.half++;
            if (mv.piece === "p" && Math.abs(Math.floor(mv.toIdx / 8) - mv.fromR) === 2) {
                this.ep = ((mv.fromR + Math.floor(mv.toIdx / 8)) / 2) * 8 + mv.fromF;
            } else {
                this.ep = -1;
            }
            let c = this.castling === "-" ? "" : this.castling;
            if (mv.fromIdx === 60) c = c.replace(/[KQ]/g, "");
            if (mv.fromIdx === 4)  c = c.replace(/[kq]/g, "");
            if (mv.fromIdx === 63 || mv.toIdx === 63) c = c.replace("K", "");
            if (mv.fromIdx === 56 || mv.toIdx === 56) c = c.replace("Q", "");
            if (mv.fromIdx === 7  || mv.toIdx === 7)  c = c.replace("k", "");
            if (mv.fromIdx === 0  || mv.toIdx === 0)  c = c.replace("q", "");
            this.castling = c || "-";
            if (!isW) this.full++;
            this.turn = isW ? "b" : "w";
        }
        moveUCI(uci) {
            if (!uci || uci.length < 4) return false;
            const from = uci.slice(0, 2), to = uci.slice(2, 4), promo = uci[4] ? uci[4].toLowerCase() : "";
            const mv = this.genLegalMoves().find(m => m.from === from && m.to === to && (!promo || m.promotion === promo));
            if (!mv) return false;
            this.commitMove(mv);
            return true;
        }
        moveSAN(san) {
            if (!san) return false;
            const clean = String(san).trim().replace(/[+#!?]+$/g, "");
            if (!clean) return false;
            const legals = this.genLegalMoves();
            if (clean === "O-O" || clean === "0-0") {
                const mv = legals.find(m => m.piece === "k" && (m.toIdx % 8) - m.fromF === 2);
                if (mv) { this.commitMove(mv); return true; }
                return false;
            }
            if (clean === "O-O-O" || clean === "0-0-0") {
                const mv = legals.find(m => m.piece === "k" && (m.toIdx % 8) - m.fromF === -2);
                if (mv) { this.commitMove(mv); return true; }
                return false;
            }
            const m = clean.match(/^([KQRBN])?([a-h])?([1-8])?x?([a-h][1-8])(?:=([QRBN]))?$/);
            if (!m) return false;
            const piece = (m[1] || "P").toLowerCase();
            const fromF = m[2] ? (m[2].charCodeAt(0) - 97) : -1;
            const fromR = m[3] ? (8 - parseInt(m[3], 10)) : -1;
            const toSq = m[4];
            const promo = m[5] ? m[5].toLowerCase() : "";
            const mv = legals.find(x =>
                x.piece === piece && x.to === toSq &&
                (!promo || x.promotion === promo) &&
                (fromF < 0 || x.fromF === fromF) &&
                (fromR < 0 || x.fromR === fromR)
            );
            if (!mv) return false;
            this.commitMove(mv);
            return true;
        }
    }

    // --- CHESSGROUND / LIVE GAME ADAPTER ---
    const _cgCache = {
        initData: undefined,
        pathAtLoad: location.pathname,
        lastSig: "",
        startFen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        turn: "w",
        legalMoves: [],
        gameOver: false,
        viewedPly: 0,
        latestPly: 0,
        timeline: [{ fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", prevFen: null, mvInfo: null }]
    };

    function getCgInitData() {
        if (_cgCache.initData !== undefined) return _cgCache.initData;
        try {
            const el = document.getElementById("page-init-data");
            _cgCache.initData = (el && el.textContent) ? JSON.parse(el.textContent) : null;
        } catch (_) {
            _cgCache.initData = null;
        }
        return _cgCache.initData;
    }

    function getCgDomMoves() {
        const roundApp = document.querySelector(".round__app");
        if (!roundApp) return { sans: [], hasResult: false, activeIdx: -1, atStart: false };
        const navBtn = roundApp.querySelector("button.repeatable[data-ply]");
        const moveWidget = navBtn?.parentElement?.parentElement;
        const moveListEl = moveWidget?.children?.[1];
        if (!moveListEl) return { sans: [], hasResult: false, activeIdx: -1, atStart: false };
        const sans = [];
        let hasResult = false;
        let activeIdx = -1;
        for (const child of moveListEl.children) {
            if (child.tagName === "DIV" || child.classList.contains("result-wrap")) {
                if (child.classList.contains("result-wrap")) hasResult = true;
                continue;
            }
            const txt = child.textContent.trim();
            if (!txt || /^\d+$/.test(txt)) continue;
            if (/^(1-0|0-1|1\/2-1\/2|\*)$/.test(txt)) { hasResult = true; continue; }
            sans.push(txt);
            if (child.classList.contains("a1t") || child.classList.contains("active") || child.querySelector?.(".a1t, .active")) {
                activeIdx = sans.length;
            }
        }
        let atStart = false;
        if (activeIdx === -1 && sans.length > 0) {
            const repBtns = navBtn?.parentElement ? Array.from(navBtn.parentElement.querySelectorAll("button.repeatable")) : [];
            const prevBtn = repBtns.length >= 4 ? repBtns[1] : (repBtns[0] || null);
            const nextBtn = repBtns.length >= 4 ? repBtns[2] : (repBtns[1] || null);
            if (prevBtn && nextBtn && prevBtn.disabled && !nextBtn.disabled) {
                atStart = true;
            }
        }
        return { sans, hasResult, activeIdx, atStart };
    }

    function getCgPlayingColor() {
        if (!document.body.classList.contains("playing")) return null;
        const myUser = (document.body.dataset.username || "").trim().toLowerCase();
        if (myUser) {
            const wName = document.querySelector(".game__meta__players .player.white .user-link")?.childNodes?.[0]?.textContent?.trim()?.toLowerCase();
            const bName = document.querySelector(".game__meta__players .player.black .user-link")?.childNodes?.[0]?.textContent?.trim()?.toLowerCase();
            if (wName && wName === myUser) return 1;
            if (bName && bName === myUser) return 2;
        }
        const init = getCgInitData();
        if (location.pathname === _cgCache.pathAtLoad && init?.data?.player?.color) {
            return init.data.player.color === "black" ? 2 : 1;
        }
        if (document.querySelector(".rcontrols .rematch.white")) return 1;
        if (document.querySelector(".rcontrols .rematch.black")) return 2;
        const botClock = document.querySelector(".rclock-bottom");
        if (botClock?.classList.contains("rclock-black")) return 2;
        if (botClock?.classList.contains("rclock-white")) return 1;
        const cgWrap = document.querySelector(".round__app__board .cg-wrap");
        if (cgWrap?.classList.contains("orientation-black")) return 2;
        return 1;
    }

    function isCgGameOver(domHasResult) {
        if (_wsState.ended || domHasResult) return true;
        if (document.querySelector(".result-wrap, .rcontrols .follow-up .new-opponent")) return true;
        const stEl = document.querySelector(".game__meta .status, section.status");
        if (stEl) {
            const st = stEl.textContent.toLowerCase();
            if (/checkmate|resign|time out|stalemate|draw|aborted|victorious|mate|cheat/.test(st)) return true;
        }
        return false;
    }

    function syncCgState() {
        const init = getCgInitData();
        const sameInitialPage = (location.pathname === _cgCache.pathAtLoad);
        const startFen = (sameInitialPage && init?.data?.steps?.[0]?.fen)
            ? init.data.steps[0].fen
            : "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
        const { sans, hasResult, activeIdx, atStart } = getCgDomMoves();
        const wsCount = Object.keys(_wsState.lastMovesByPly).length;
        const initSteps = (sameInitialPage && Array.isArray(init?.data?.steps)) ? init.data.steps : [];
        const maxInitPly = Math.max(0, initSteps.length - 1);
        const maxWsPly = Object.keys(_wsState.lastMovesByPly).reduce((mx, k) => Math.max(mx, parseInt(k, 10) || 0), 0);
        const totalTarget = Math.max(sans.length, maxInitPly, maxWsPly);
        const viewedPly = totalTarget === 0 ? 0 : (atStart ? 0 : (activeIdx >= 1 ? Math.min(activeIdx, totalTarget) : totalTarget));
        const sig = `${location.pathname}|${startFen}|${sans.length}|${sans[sans.length - 1] || ""}|${wsCount}|${viewedPly}`;
        if (sig !== _cgCache.lastSig) {
            _cgCache.lastSig = sig;
            _cgCache.startFen = startFen;
            const cm = new ChessMini(startFen);
            const timeline = [{ fen: cm.fen(), prevFen: null, mvInfo: null }];
            let ply = 0;
            for (let i = 1; i < initSteps.length; i++) {
                const uci = initSteps[i]?.uci;
                if (uci) {
                    const prevFen = cm.fen();
                    if (cm.moveUCI(uci)) {
                        const currFen = cm.fen();
                        const mvInfo = detectMoveBetweenFens(prevFen, currFen);
                        timeline.push({ fen: currFen, prevFen, mvInfo: mvInfo.uci ? mvInfo : { from: uci.slice(0, 2), to: uci.slice(2, 4), uci, singleHalfMove: true } });
                        ply++;
                    }
                }
            }
            for (let p = ply + 1; p <= totalTarget; p++) {
                const prevFen = cm.fen();
                const wsUci = _wsState.lastMovesByPly[p];
                let moved = false;
                if (wsUci && cm.moveUCI(wsUci)) moved = true;
                else {
                    const san = sans[p - 1];
                    if (san && cm.moveSAN(san)) moved = true;
                }
                if (!moved) continue;
                const currFen = cm.fen();
                const mvInfo = detectMoveBetweenFens(prevFen, currFen);
                timeline.push({ fen: currFen, prevFen, mvInfo });
            }
            const safeViewed = Math.min(viewedPly, timeline.length - 1);
            const viewedEntry = timeline[safeViewed] || timeline[timeline.length - 1];
            const cmView = new ChessMini(viewedEntry.fen);
            _cgCache.timeline = timeline;
            _cgCache.latestPly = timeline.length - 1;
            _cgCache.viewedPly = safeViewed;
            _cgCache.fen = cmView.fen();
            _cgCache.turn = cmView.turn;
            _cgCache.legalMoves = cmView.genLegalMoves().map(m => ({ from: m.from, to: m.to, promotion: m.promotion }));
        }
        _cgCache.gameOver = isCgGameOver(hasResult) || (_cgCache.viewedPly >= _cgCache.latestPly && _cgCache.legalMoves.length === 0);
    }

    function getCgGameProxy() {
        syncCgState();
        return {
            _isCgProxy: true,
            getFEN: () => _cgCache.fen,
            getTurn: () => _cgCache.turn,
            getPlayingAs: () => getCgPlayingColor(),
            isPlaying: () => document.body.classList.contains("playing") && _cgCache.viewedPly >= _cgCache.latestPly,
            isViewingLive: () => _cgCache.viewedPly >= _cgCache.latestPly,
            isGameOver: () => _cgCache.gameOver,
            getLegalMoves: () => _cgCache.legalMoves
        };
    }

    function drawCgNativeArrow(move, id) {
        const svg = document.querySelector(".round__app__board svg.cg-shapes");
        if (!svg || !move || move.length < 4) return;
        const g = svg.querySelector("g") || svg;
        g.querySelectorAll(`.cg-bot-native.${id}`).forEach(el => el.remove());
        const flipped = isBoardFlipped();
        const sqToCg = (sq) => {
            const f = sq.charCodeAt(0) - 97, r = parseInt(sq[1], 10) - 1;
            return { x: flipped ? (3.5 - f) : (f - 3.5), y: flipped ? (r - 3.5) : (3.5 - r) };
        };
        const a = sqToCg(move.slice(0, 2)), b = sqToCg(move.slice(2, 4));
        const dx = b.x - a.x, dy = b.y - a.y;
        const len = Math.hypot(dx, dy);
        if (!len) return;
        const ux = dx / len, uy = dy / len, px = -uy, py = ux;
        const headLen = 0.42, headW = 0.36;
        const ex = b.x - ux * headLen, ey = b.y - uy * headLen;
        const ns = "http://www.w3.org/2000/svg";
        const grp = document.createElementNS(ns, "g");
        grp.setAttribute("class", `cg-bot-native ${id}`);
        grp.setAttribute("opacity", "0.45");
        const line = document.createElementNS(ns, "line");
        line.setAttribute("x1", a.x); line.setAttribute("y1", a.y);
        line.setAttribute("x2", ex); line.setAttribute("y2", ey);
        line.setAttribute("stroke", "#15781B");
        line.setAttribute("stroke-width", "0.15625");
        line.setAttribute("stroke-linecap", "round");
        const poly = document.createElementNS(ns, "polygon");
        poly.setAttribute("points", `${b.x},${b.y} ${ex + px * (headW / 2)},${ey + py * (headW / 2)} ${ex - px * (headW / 2)},${ey - py * (headW / 2)}`);
        poly.setAttribute("fill", "#15781B");
        grp.appendChild(line);
        grp.appendChild(poly);
        g.appendChild(grp);
    }

    const STOCKFISH_ICON = `<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M5 20h14v2H5v-2zm1-1c0-5.5 1.8-11.5 5.2-15.8L12.8 5l1.8-2 .7 2.5L19 8.5c.5.5.2 2.3-1 2.7l-2.8.4c-1.2.2-2-.6-2.4-1.4.4 2.8 3.4 5 4.8 8.8H6z"/></svg>`;

    // --- LOCAL ENGINE REGISTRY ---
    const LOCAL_ENGINES = [
        {
            id:              "sf19_lite",
            label:           "Stockfish 19 Lite (Latest NNUE · 1.8 MB)",
            cdn:             "unpkg",
            format:          "wasm",
            cacheKey:        "sf19_lite",
            jsUrl:           "https://unpkg.com/[email protected]/bin/stockfish-19-lite-single.js",
            wasmUrl:         "https://unpkg.com/[email protected]/bin/stockfish-19-lite-single.wasm",
            maxDepth:        25,
            hasHash:         true,
            hasMoveOverhead: true,
            hasSlowMover:    false,
            hasSkillLevel:   true,
            hasNNUE:         true,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     true,
            defaults: { hashMB: 64, moveOverhead: 100, skillLevel: 20,
                        limitStrength: false, elo: 3190, showWDL: false, minThinkTime: 20 },
        },
        {
            id:              "sf19_full",
            label:           "Stockfish 19 Full (Full NNUE · 94.6 MB)",
            cdn:             "unpkg",
            format:          "wasm",
            cacheKey:        "sf19_full",
            jsUrl:           "https://unpkg.com/[email protected]/bin/stockfish-19-single.js",
            wasmUrl:         "https://unpkg.com/[email protected]/bin/stockfish-19-single.wasm",
            maxDepth:        25,
            hasHash:         true,
            hasMoveOverhead: true,
            hasSlowMover:    false,
            hasSkillLevel:   true,
            hasNNUE:         true,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     true,
            defaults: { hashMB: 128, moveOverhead: 100, skillLevel: 20,
                        limitStrength: false, elo: 3190, showWDL: false, minThinkTime: 0 },
        },
        {
            id:              "sf19_asm",
            label:           "Stockfish 19 asm.js (Zero WASM · Pure JS)",
            cdn:             "unpkg",
            format:          "asmjs",
            cacheKey:        "sf19_asm",
            jsUrl:           "https://unpkg.com/[email protected]/bin/stockfish-19-asm.js",
            wasmUrl:         null,
            maxDepth:        22,
            hasHash:         true,
            hasMoveOverhead: true,
            hasSlowMover:    false,
            hasSkillLevel:   true,
            hasNNUE:         false,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     true,
            defaults: { hashMB: 32, moveOverhead: 100, skillLevel: 20, minThinkTime: 20 },
        },
        {
            id:              "sf18_lite",
            label:           "Stockfish 18.0.8 Lite (NNUE · 6.9 MB)",
            cdn:             "unpkg",
            format:          "wasm",
            cacheKey:        "sf18_lite",
            jsUrl:           "https://unpkg.com/[email protected]/bin/stockfish-18-lite-single.js",
            wasmUrl:         "https://unpkg.com/[email protected]/bin/stockfish-18-lite-single.wasm",
            maxDepth:        25,
            hasHash:         true,
            hasMoveOverhead: true,
            hasSlowMover:    false,
            hasSkillLevel:   true,
            hasNNUE:         true,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     true,
            defaults: { hashMB: 64, moveOverhead: 100, skillLevel: 20,
                        limitStrength: false, elo: 3190, showWDL: false, minThinkTime: 0 },
        },
        {
            id:              "sf18_05",
            label:           "Stockfish 18.0.5 Full (Full NNUE · 108 MB)",
            cdn:             "unpkg",
            format:          "wasm",
            cacheKey:        "sf18_05",
            jsUrl:           "https://unpkg.com/[email protected]/bin/stockfish-18-single.js",
            wasmUrl:         "https://unpkg.com/[email protected]/bin/stockfish-18-single.wasm",
            maxDepth:        25,
            hasHash:         true,
            hasMoveOverhead: true,
            hasSlowMover:    false,
            hasSkillLevel:   true,
            hasNNUE:         true,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     true,
            defaults: { hashMB: 128, moveOverhead: 100, skillLevel: 20,
                        limitStrength: false, elo: 3190, showWDL: false, minThinkTime: 0 },
        },
        {
            id:              "sf17_1_lite",
            label:           "Stockfish 17.1 Lite (NNUE · 7.0 MB)",
            cdn:             "unpkg",
            format:          "wasm",
            cacheKey:        "sf17_1_lite",
            jsUrl:           "https://unpkg.com/[email protected]/src/stockfish-17.1-lite-single-03e3232.js",
            wasmUrl:         "https://unpkg.com/[email protected]/src/stockfish-17.1-lite-single-03e3232.wasm",
            maxDepth:        25,
            hasHash:         true,
            hasMoveOverhead: true,
            hasSlowMover:    false,
            hasSkillLevel:   true,
            hasNNUE:         true,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     true,
            defaults: { hashMB: 64, moveOverhead: 100, skillLevel: 20,
                        limitStrength: false, elo: 3190, showWDL: false, minThinkTime: 0 },
        },
        {
            id:              "sf16_00",
            label:           "Stockfish 16.0 (NNUE · Ultra Light 0.5 MB)",
            cdn:             "unpkg",
            format:          "wasm",
            cacheKey:        "sf16_00",
            jsUrl:           "https://unpkg.com/[email protected]/src/stockfish-nnue-16-single.js",
            wasmUrl:         "https://unpkg.com/[email protected]/src/stockfish-nnue-16-single.wasm",
            maxDepth:        25,
            hasHash:         true,
            hasMoveOverhead: true,
            hasSlowMover:    false,
            hasSkillLevel:   true,
            hasNNUE:         true,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     true,
            defaults: { hashMB: 64, moveOverhead: 100, skillLevel: 20,
                        limitStrength: false, elo: 3190, showWDL: false, minThinkTime: 20 },
        },
        {
            id:              "sf11_00",
            label:           "Stockfish 11.0 (Classical HCE · 1.3 MB)",
            cdn:             "unpkg",
            format:          "wasm",
            cacheKey:        "sf11_00",
            jsUrl:           "https://unpkg.com/[email protected]/src/stockfish.js",
            wasmUrl:         "https://unpkg.com/[email protected]/src/stockfish.wasm",
            maxDepth:        20,
            hasHash:         true,
            hasMoveOverhead: false,
            hasSlowMover:    true,
            hasSkillLevel:   true,
            hasNNUE:         false,
            hasWDL:          false,
            hasContempt:     true,
            hasMinThink:     true,
            defaults: { hashMB: 32, slowMover: 100, skillLevel: 20,
                        contempt: 24, minThinkTime: 20 },
        },
        {
            id:              "sf10_02",
            label:           "Stockfish 10.0.2 (asm.js · 1.5 MB)",
            cdn:             "cdnjs",
            format:          "asmjs",
            cacheKey:        "sf10_02",
            jsUrl:           "https://cdnjs.cloudflare.com/ajax/libs/stockfish.js/10.0.2/stockfish.js",
            wasmUrl:         null,
            maxDepth:        20,
            hasHash:         true,
            hasMoveOverhead: false,
            hasSlowMover:    true,
            hasSkillLevel:   true,
            hasNNUE:         false,
            hasWDL:          false,
            hasContempt:     true,
            hasMinThink:     true,
            defaults: { hashMB: 32, slowMover: 100, skillLevel: 20,
                        contempt: 24, minThinkTime: 20 },
        },
        {
            id:              "sf9_00",
            label:           "Stockfish 9.0.0 (asm.js · 1.2 MB)",
            cdn:             "cdnjs",
            format:          "asmjs",
            cacheKey:        "sf9_00",
            jsUrl:           "https://cdnjs.cloudflare.com/ajax/libs/stockfish.js/9.0.0/stockfish.js",
            wasmUrl:         null,
            maxDepth:        18,
            hasHash:         true,
            hasMoveOverhead: false,
            hasSlowMover:    true,
            hasSkillLevel:   true,
            hasNNUE:         false,
            hasWDL:          false,
            hasContempt:     true,
            hasMinThink:     true,
            defaults: { hashMB: 16, slowMover: 100, skillLevel: 20,
                        contempt: 24, minThinkTime: 20 },
        },
        {
            id:              "maia3_5m",
            label:           "Maia-3 5M (Human-Like NN · ~21 MB)",
            cdn:             "jsdelivr",
            format:          "onnx",
            maiaVariant:     "5m",
            cacheKey:        "maia3_5m",
            maxDepth:        1,
            hasHash:         false,
            hasMoveOverhead: false,
            hasSlowMover:    false,
            hasSkillLevel:   false,
            hasNNUE:         false,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     false,
            hasMaiaElo:      true,
            defaults: { maiaElo: 1500, maiaTemp: 0.0, maiaTopP: 0.95 },
        },
        {
            id:              "maia3_23m",
            label:           "Maia-3 23M (Human-Like NN · ~91 MB)",
            cdn:             "huggingface",
            format:          "onnx",
            maiaVariant:     "23m",
            cacheKey:        "maia3_23m",
            maxDepth:        1,
            hasHash:         false,
            hasMoveOverhead: false,
            hasSlowMover:    false,
            hasSkillLevel:   false,
            hasNNUE:         false,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     false,
            hasMaiaElo:      true,
            defaults: { maiaElo: 1500, maiaTemp: 0.0, maiaTopP: 0.95 },
        },
        {
            id:              "maia3_79m",
            label:           "Maia-3 79M (Full Human NN · ~312 MB)",
            cdn:             "huggingface",
            format:          "onnx",
            maiaVariant:     "79m",
            cacheKey:        "maia3_79m",
            maxDepth:        1,
            hasHash:         false,
            hasMoveOverhead: false,
            hasSlowMover:    false,
            hasSkillLevel:   false,
            hasNNUE:         false,
            hasWDL:          true,
            hasContempt:     false,
            hasMinThink:     false,
            hasMaiaElo:      true,
            defaults: { maiaElo: 1500, maiaTemp: 0.0, maiaTopP: 0.95 },
        },
    ];

    const getEngineById = (id) => LOCAL_ENGINES.find(e => e.id === id) || LOCAL_ENGINES[0];

    // --- STATE MANAGEMENT ---
    const state = {
        board: null,
        isThinking: false,
        ui: {},
        lastSentFEN: "",
        lastSanitizedBoardFEN: "",
        lastMoveResult: "Awaiting next move...",
        lastLiveResult: "Start a match to see live engine recommendations.",
        moveTargetTime: 0,
        calculatedDelay: 0,
        localEngine: null,
        engineLoadingInProgress: false,
        engineStatus: "not_installed",
        currentCloudRequest: null,
        currentBestMove: null,
        currentPV: [],
        analysisStartTime: 0,
        h: 180, s: 100, l: 50,
        newGameObserver: null,
        queueTimeout: null,
        localEval: null,
        localMate: null,
        localPV: null,
        localDepth: null,
        lastSeenFEN: "",
        playingAs: null,
        pendingManualMove: false,
        lastGrade: null,
        lastUserGrade: null,
        lastOppGrade: null,
        _chosenDelayMs: 0,
        gradeSnapshots: {},
        gradesByMoveKey: {},
        ccTimeline: [],
        ccActiveIdx: 0,
        isBrowsingHistory: false,
        lastPagePath: location.pathname,
        pendingGrades: [],
        graderEngine: null,
        graderReady: false,
        graderLoading: false,
        graderSearching: false,
        graderQueue: [],
        graderActiveFen: null,
        graderMultiPV: {},
        graderLiveDepth: 0,
        graderStopSent: false,
        graderAborted: false,
        graderMode: "grade",
        pendingCandEval: null,
        graderBlobUrls: [],
        uiVisible: true,
        hudEvalTxt: "0.0",
        hudStatus: { text: "Ready", color: "#8b949e" },
        hudMove: "--",
        gradeTally: null,
        gradeBreakdownOpen: false,
        activeMainTab: "engine",
        lastCandidates: [],
        visuals: [],
        shadow: null
    };

    const HUMAN_PRESETS = {
        beginner:     { targetTop1: 0.14, temp: 52, critMissRate: 0.78, maxCritLoss: 550, baseBudget: 240, minEvenFloor: -450, tankScale: 0.35, minDepthAdj: -6 },
        novice:       { targetTop1: 0.19, temp: 38, critMissRate: 0.68, maxCritLoss: 420, baseBudget: 165, minEvenFloor: -340, tankScale: 0.45, minDepthAdj: -5 },
        casual:       { targetTop1: 0.24, temp: 29, critMissRate: 0.58, maxCritLoss: 310, baseBudget: 115, minEvenFloor: -250, tankScale: 0.55, minDepthAdj: -4 },
        intermediate: { targetTop1: 0.29, temp: 23, critMissRate: 0.51, maxCritLoss: 250, baseBudget: 85,  minEvenFloor: -190, tankScale: 0.62, minDepthAdj: -3 },
        club:         { targetTop1: 0.34, temp: 18, critMissRate: 0.45, maxCritLoss: 200, baseBudget: 55,  minEvenFloor: -140, tankScale: 0.70, minDepthAdj: -2 },
        expert:       { targetTop1: 0.40, temp: 14, critMissRate: 0.32, maxCritLoss: 145, baseBudget: 40,  minEvenFloor: -100, tankScale: 0.85, minDepthAdj: -1 },
        master:       { targetTop1: 0.44, temp: 12, critMissRate: 0.22, maxCritLoss: 95,  baseBudget: 32,  minEvenFloor: -70,  tankScale: 1.00, minDepthAdj:  0 },
        hikaru:       { targetTop1: 0.50, temp: 10, critMissRate: 0.14, maxCritLoss: 65,  baseBudget: 24,  minEvenFloor: -45,  tankScale: 1.15, minDepthAdj:  1 },
        gm:           { targetTop1: 0.65, temp: 6,  critMissRate: 0.03, maxCritLoss: 40,  baseBudget: 12,  minEvenFloor: -25,  tankScale: 1.20, minDepthAdj:  3 },
        stealth:      { targetTop1: 0.78, temp: 4,  critMissRate: 0.00, maxCritLoss: 0,   baseBudget: 6,   minEvenFloor: -10,  tankScale: 1.10, minDepthAdj:  4 }
    };

    const DEFAULT_SETTINGS = {
        engineMode: "cloud",
        depth: 18,
        autoTimeMgmt: true,
        autoFallback: true,
        humanMode: false,
        humanPreset: "master",
        moveKeybind: "None",
        uiKeybind: "None",
        panelLayout: "double",
        language: "en",
        autoQueueDelay: 2,
        uiPreset: "basic",
        advAccentColor: "#58a6ff",
        advCardStyle: "glass",
        advGradientBg: true,
        advRadius: 14,
        advBlur: 22,
        advGlow: 55,
        advDensity: "normal",
        advFontScale: 100,
        advHeaderStyle: "gradient",
        advAnimations: true,
        advScorePillStyle: "tinted",
        maxThinkingTime: 0,
        searchMoves: "",
        autoRun: true,
        silentMode: false,
        moveGrading: false,
        gradeDepth: 15,
        autoMove: true,
        autoQueue: false,
        showEvalBar: true,
        showPVArrows: false,
        showMultiBest: false,
        engineFocus: "balanced",
        focusAttack: 50,
        focusSafety: 50,
        focusSimplify: 50,
        focusTolerance: 35,
        pvDepth: 5,
        pvShowNumbers: false,
        pvCustomGradient: false,
        pvStartColor: "#FFFF00",
        pvEndColor: "#FF0000",
        minDelay: 0,
        maxDelay: 0,
        highlightColor: "#00eeff",
        visualType: "outline",
        innerOpacity: 0.6,
        outerOpacity: 0.2,
        gradientBias: 0,
        arrowOpacity: 0.85,
        arrowWidth: 15,
        visualOutlineWidth: 4,
        visualOutlineOpacity: 0.8,
        visualOutlineGlow: true,
        visualOutlineGlowRadius: 24,
        visualDuration: 0.6,
        visualFadeOut: true,
        highlightPersist: true,
        themeBg: "rgba(15, 19, 24, 0.94)",
        themeText: "#f0f6fc",
        themeBorder: "rgba(255,255,255,0.12)",
        themePrimary: "#2ea043",
        menuOpacity: 0.96,
        menuPosition: "top-right",
        localModelId: "sf19_lite",
        localHashMB: 64,
        localMoveOverhead: 100,
        localSkillLevel: 20,
        localLimitStrength: false,
        localElo: 3190,
        localShowWDL: false,
        localMinThinkTime: 20,
        localSlowMover: 100,
        localContempt: 24,
        localMaiaElo: 1500,
        localMaiaTemp: 0.0,
        localMaiaTopP: 0.95,
    };
    const settings = { ...DEFAULT_SETTINGS };

    // --- COLOR HELPERS ---
    const hexToRgb = (hex) => {
        const r = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return r ? { r: parseInt(r[1], 16), g: parseInt(r[2], 16), b: parseInt(r[3], 16) } : { r: 0, g: 0, b: 0 };
    };
    const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    const rgbToHsl = (r, g, b) => {
        r /= 255; g /= 255; b /= 255;
        const max = Math.max(r, g, b), min = Math.min(r, g, b);
        let h, s, l = (max + min) / 2;
        if (max === min) h = s = 0;
        else {
            const d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            h /= 6;
        }
        return { h: h * 360, s: s * 100, l: l * 100 };
    };
    const hslToRgb = (h, s, l) => {
        let r, g, b;
        h /= 360; s /= 100; l /= 100;
        if (s === 0) r = g = b = l;
        else {
            const hue2rgb = (p, q, t) => {
                if (t < 0) t += 1;
                if (t > 1) t -= 1;
                if (t < 1 / 6) return p + (q - p) * 6 * t;
                if (t < 1 / 2) return q;
                if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
                return p;
            };
            const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            const p = 2 * l - q;
            r = hue2rgb(p, q, h + 1 / 3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1 / 3);
        }
        return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
    };

    // --- SAVE/LOAD HELPERS ---
    // --- LOCAL STORAGE HELPERS ---
    function lsGet(key, def) {
        try { const r = localStorage.getItem(key); if (r !== null) return JSON.parse(r); } catch(_) {}
        return def;
    }
    function lsSet(key, val) {
        try { localStorage.setItem(key, JSON.stringify(val)); } catch(_) {}
    }

    function getSiteKey() {
        const h = (location.hostname || "").toLowerCase();
        if (h.includes("lichess") || h.includes("lichess.org")) return "cg";
        if (h.includes("chess.com") || h.includes("chess.com")) return "cc";
        return isCgSite() ? "cg" : "cc";
    }

    const SITE_UI_DEFAULTS = {
        cc: {
            menuPosition: "top-right",
            panel: {
                single: { w: "310px", h: "auto", minW: 296 },
                double: { w: "560px", h: "auto", minW: 480 },
                tabs:   { w: "320px", h: "auto", minW: 296 }
            },
            tally: { w: "276px", h: "auto", minW: 240, minH: 180, x: "auto", y: 64, right: 340 }
        },
        cg: {
            menuPosition: "top-right",
            panel: {
                single: { w: "310px", h: "auto", minW: 296 },
                double: { w: "560px", h: "auto", minW: 480 },
                tabs:   { w: "320px", h: "auto", minW: 296 }
            },
            tally: { w: "276px", h: "auto", minW: 240, minH: 180, x: "auto", y: 64, right: 340 }
        }
    };

    const SITE_ONLY_KEYS = new Set(["menuPosition"]);

    function saveSetting(key, val) {
        settings[key] = val;
        // Model-specific settings are saved exclusively via saveModelSetting
        if (MODEL_ONLY_KEYS.has(key)) return;
        const storageKey = SITE_ONLY_KEYS.has(key) ? `bot_${getSiteKey()}_${key}` : `bot_${key}`;
        try { GM_setValue(storageKey, val); } catch(_) {}
        lsSet(storageKey, val);
    }

    function saveModelSetting(key, val, modelId) {
        const mid = modelId || settings.localModelId || "sf19_lite";
        settings[key] = val;
        try { GM_setValue(`m_${mid}_${key}`, val); } catch(_) {}
        lsSet(`m_${mid}_${key}`, val);
    }

    function loadModelSettings(modelId) {
        const m = getEngineById(modelId);
        const d = m.defaults;
        const g = (k, def) => {
            let v;
            try { v = GM_getValue(`m_${modelId}_${k}`); } catch(_) {}
            if (v !== undefined && v !== null) return v;
            const lsVal = lsGet(`m_${modelId}_${k}`, def);
            return (lsVal !== undefined && lsVal !== null) ? lsVal : def;
        };
        settings.localHashMB = Number(g("localHashMB", d.hashMB ?? 64)) || 64;
        settings.localMoveOverhead = Number(g("localMoveOverhead", d.moveOverhead ?? 100));
        if (Number.isNaN(settings.localMoveOverhead)) settings.localMoveOverhead = 100;
        settings.localSkillLevel = Number(g("localSkillLevel", d.skillLevel ?? 20));
        if (Number.isNaN(settings.localSkillLevel)) settings.localSkillLevel = 20;
        settings.localLimitStrength = Boolean(g("localLimitStrength", d.limitStrength ?? false));
        settings.localElo = Number(g("localElo", d.elo ?? 3190)) || 3190;
        settings.localShowWDL = Boolean(g("localShowWDL", d.showWDL ?? false));
        settings.localMinThinkTime = Number(g("localMinThinkTime", d.minThinkTime ?? 20));
        if (Number.isNaN(settings.localMinThinkTime)) settings.localMinThinkTime = 20;
        settings.localSlowMover = Number(g("localSlowMover", d.slowMover ?? 100)) || 100;
        settings.localContempt = Number(g("localContempt", d.contempt ?? 24));
        if (Number.isNaN(settings.localContempt)) settings.localContempt = 24;
        settings.localMaiaElo = Math.min(2600, Math.max(600, Number(g("localMaiaElo", d.maiaElo ?? 1500)) || 1500));
        const rawTemp = Number(g("localMaiaTemp", d.maiaTemp ?? 0.0));
        settings.localMaiaTemp = Number.isNaN(rawTemp) ? 0.0 : Math.min(1.5, Math.max(0.0, rawTemp));
        const rawTopP = Number(g("localMaiaTopP", d.maiaTopP ?? 0.95));
        settings.localMaiaTopP = Number.isNaN(rawTopP) ? 0.95 : Math.min(1.0, Math.max(0.1, rawTopP));
    }

    // Keys managed exclusively by loadModelSettings — do not load via bot_ prefix
    const MODEL_ONLY_KEYS = new Set([
        "localHashMB","localMoveOverhead","localSkillLevel","localLimitStrength",
        "localElo","localShowWDL","localMinThinkTime","localSlowMover","localContempt",
        "localMaiaElo","localMaiaTemp","localMaiaTopP"
    ]);

    function loadSettings() {
        const site = getSiteKey();
        Object.keys(DEFAULT_SETTINGS).forEach((k) => {
            // Skip model-specific keys — loadModelSettings() handles them
            if (MODEL_ONLY_KEYS.has(k)) return;
            const storageKey = SITE_ONLY_KEYS.has(k) ? `bot_${site}_${k}` : `bot_${k}`;
            let saved;
            // Try GM storage first
            try { saved = GM_getValue(storageKey); } catch(_) {}
            // null is treated as missing (some GM implementations return null)
            if (saved === undefined || saved === null) {
                saved = undefined;
                // Fall back to localStorage
                try { const raw = localStorage.getItem(storageKey); if (raw !== null) saved = JSON.parse(raw); } catch(_) {}
            }
            if (saved !== undefined && saved !== null) {
                settings[k] = saved;
                // Mirror to localStorage so both stores stay in sync
                lsSet(storageKey, saved);
            } else if (SITE_ONLY_KEYS.has(k) && SITE_UI_DEFAULTS[site]?.[k] !== undefined) {
                settings[k] = SITE_UI_DEFAULTS[site][k];
            }
        });
        loadModelSettings(settings.localModelId || "sf19_lite");
        // Init HSL from loaded highlightColor so color picker is correct on first load
        try {
            const _hsl = rgbToHsl(...Object.values(hexToRgb(settings.highlightColor || "#00eeff")));
            state.h = _hsl.h; state.s = _hsl.s; state.l = _hsl.l;
        } catch(_) { state.h = 185; state.s = 100; state.l = 50; }
    }

    // --- BOARD FEN LOGIC ---
    function getRawBoardFEN() {
        const game = getActiveGame();
        if (!game) return null;
        try {
            if (typeof game.getFEN === "function") return game.getFEN();
            if (typeof game.fen === "string") return game.fen;
            if (game.getPosition) return game.getPosition();
        } catch (e) {}
        return null;
    }

    function sanitizeFEN(rawFEN) {
        if (!rawFEN || typeof rawFEN !== "string") return "";
        let parts = rawFEN.trim().split(/\s+/);
        if (parts.length < 4) {
            let activeColor = "w";
            if (state.board?.game) {
                if (typeof state.board.game.getTurn === "function") activeColor = state.board.game.getTurn();
                else if (typeof state.board.game.getPlayingAs === "function") activeColor = state.board.game.getPlayingAs();
            }
            if (parts.length === 1) parts = [parts[0], activeColor, "KQkq", "-", "0", "1"];
            else if (parts.length === 2) parts = [parts[0], parts[1], "KQkq", "-", "0", "1"];
            else if (parts.length === 3) parts = [parts[0], parts[1], parts[2], "-", "0", "1"];
        }
        if (parts[3] && parts[3] !== "-") parts[3] = parts[3].toLowerCase();
        return parts.join(" ");
    }

    // --- VISUAL MANAGER ---
    const Visuals = {
        add: (move, type) => {
            if (!move) return;
            if (settings.silentMode) {
                Visuals.removeByType('bestmove');
                Visuals.removeByType('analysis');
                return;
            }
            if (type === 'bestmove') {
                Visuals.removeByType('bestmove');
                Visuals.removeByType('analysis');
            } else if (type === 'analysis') {
                Visuals.removeByType('analysis');
            }
            const id = `vis-${type}-${move}`;
            const existingIdx = state.visuals.findIndex(v => v.id === id);
            if (existingIdx !== -1) Visuals.remove(id);

            if (!settings.highlightPersist && settings.visualDuration <= 0) return;

            if (settings.visualType === "nativeArrow") {
                if (isCgSite()) {
                    state.board = document.querySelector(CONFIG.BOARD_SEL);
                    drawCgNativeArrow(move, id);
                    const interval = setInterval(() => {
                        const vis = state.visuals.find(v => v.id === id);
                        if (!vis || vis.isFading) { clearInterval(interval); return; }
                        if (!document.querySelector(`.cg-bot-native.${id}`)) drawCgNativeArrow(move, id);
                    }, 120);
                    const vis = { id, move, type, interval, timeoutId: null, isFading: false, timerStarted: false, isNative: true };
                    state.visuals.push(vis);
                    if (type === 'bestmove' && !settings.highlightPersist) Visuals.startTimer(id);
                    return;
                }
                const cb = document.querySelector("chess-board, wc-chess-board");
                state.board = (cb && cb.game) ? cb : (document.querySelector(CONFIG.BOARD_SEL) || cb);
                if (state.board?.game?.markings) {
                    state.board.game.markings.addOne({
                        type: "arrow",
                        tags: ["Arrows", id],
                        data: {
                            from: move.substring(0, 2),
                            to: move.substring(2, 4)
                        }
                    });
                }
                const vis = { id, move, type, interval: null, timeoutId: null, isFading: false, timerStarted: false, isNative: true };
                state.visuals.push(vis);
                if (type === 'bestmove' && !settings.highlightPersist) Visuals.startTimer(id);
                return;
            }

            Visuals.draw(id, move);
            const interval = setInterval(() => {
                const vis = state.visuals.find(v => v.id === id);
                if (!vis || vis.isFading) { clearInterval(interval); return; }
                Visuals.draw(id, move);
            }, 50);
            const vis = { id, move, type, interval, timeoutId: null, isFading: false, timerStarted: false, isNative: false };
            state.visuals.push(vis);
            if (type === 'bestmove' && !settings.highlightPersist) Visuals.startTimer(id);
        },
        draw: (id, move) => {
            state.board = document.querySelector(CONFIG.BOARD_SEL);
            if (!state.board) return;
            const curFlip = String(isBoardFlipped(state.board));
            const existingAll = document.querySelectorAll(`.${id}`);
            if (existingAll.length) {
                const allGood = Array.from(existingAll).every(el => state.board.contains(el) && el.dataset.flip === curFlip);
                if (allGood) return;
                existingAll.forEach(el => el.remove());
            }
            const { r, g, b } = hexToRgb(settings.highlightColor);
            const col = (a) => `rgba(${r}, ${g}, ${b}, ${a})`;
            const from = move.substring(0, 2);
            const to = move.substring(2, 4);

            const drawBox = () => {
                [from, to].forEach((alg) => {
                    const sqId = `${alg.charCodeAt(0) - 96}${alg.charAt(1)}`;
                    const div = document.createElement("div");
                    div.className = `square-${sqId} board-highlight ${id}`;
                    div.dataset.flip = curFlip;
                    let baseStyle = "position: absolute; pointer-events: none !important; z-index: 150 !important; width: 12.5%; height: 12.5%; box-sizing: border-box; opacity: 1; transition: none !important; border-radius: 6px; ";
                    if (settings.visualType === "outline") {
                        let glow = settings.visualOutlineGlow ? `box-shadow: 0 0 ${settings.visualOutlineGlowRadius}px ${col(0.85)}, inset 0 0 ${settings.visualOutlineGlowRadius/2}px ${col(0.35)} !important;` : "";
                        div.style.cssText = baseStyle + `border: ${settings.visualOutlineWidth}px solid ${col(settings.visualOutlineOpacity)} !important; ${glow}`;
                    } else {
                        const bias = settings.gradientBias + "%";
                        div.style.cssText = baseStyle + `background: radial-gradient(closest-side, ${col(settings.innerOpacity)} ${bias}, ${col(settings.outerOpacity)} 100%) !important;`;
                    }
                    positionSquareEl(div, alg, state.board);
                    state.board.appendChild(div);
                });
            };
            if (settings.visualType === "arrow") drawArrow(move, id);
            else drawBox();
        },
        startTimer: (id) => {
            const vis = state.visuals.find(v => v.id === id);
            if (!vis || vis.timerStarted) return;
            vis.timerStarted = true;
            if (settings.visualDuration <= 0) {
                Visuals.remove(id);
                return;
            }
            if (settings.visualFadeOut) Visuals.fadeOut(id);
            else vis.timeoutId = setTimeout(() => Visuals.remove(id), settings.visualDuration * 1000);
        },
        onMovePlayed: () => {
            Visuals.removeByType('analysis');
            state.visuals.filter(v => v.type === 'bestmove').forEach(v => Visuals.startTimer(v.id));
        },
        fadeOut: (id) => {
            const vis = state.visuals.find(v => v.id === id);
            if (!vis) return;
            vis.isFading = true;
            if (vis.interval) clearInterval(vis.interval);
            const secs = settings.visualDuration;
            const els = Array.from(document.querySelectorAll(`.${id}`));
            if (vis.isNative && els.length === 0) {
                const cb = document.querySelector("chess-board, wc-chess-board");
                const board = (state.board?.isConnected && state.board?.game) ? state.board : ((cb && cb.game) ? cb : document.querySelector(CONFIG.BOARD_SEL));
                const sq = vis.move ? vis.move.substring(0, 4) : "";
                if (board && sq) {
                    const roots = [board, board.shadowRoot].filter(Boolean);
                    for (const root of roots) {
                        root.querySelectorAll(`[data-arrow="${sq}"], [id="arrow-${sq}"], .arrow-${sq}`).forEach(el => els.push(el));
                    }
                }
            }
            if (els.length > 0) {
                els.forEach(el => {
                    el.style.setProperty("opacity", "1", "important");
                    el.style.setProperty("transition", `opacity ${secs}s cubic-bezier(0.4, 0, 0.2, 1)`, "important");
                });
                requestAnimationFrame(() => {
                    requestAnimationFrame(() => {
                        if (!state.visuals.some(v => v.id === id)) return;
                        els.forEach(el => el.style.setProperty("opacity", "0", "important"));
                    });
                });
            }
            vis.timeoutId = setTimeout(() => Visuals.remove(id), secs * 1000);
        },
        remove: (id) => {
            const idx = state.visuals.findIndex(v => v.id === id);
            const vis = idx !== -1 ? state.visuals[idx] : null;
            if (vis) {
                if (vis.interval) clearInterval(vis.interval);
                if (vis.timeoutId) clearTimeout(vis.timeoutId);
                state.visuals.splice(idx, 1);
            }
            document.querySelectorAll(`.${id}, .cg-bot-native.${id}`).forEach(el => el.remove());

            if ((vis?.isNative || settings.visualType === "nativeArrow") && !isCgSite()) {
                const cb = document.querySelector("chess-board, wc-chess-board");
                const board = (state.board?.isConnected && state.board?.game) ? state.board : ((cb && cb.game) ? cb : document.querySelector(CONFIG.BOARD_SEL));
                const mk = board?.game?.markings;
                if (mk) {
                    const from = vis?.move?.substring(0, 2);
                    const to = vis?.move?.substring(2, 4);
                    let cleared = false;
                    if (typeof mk.getAll === "function" && typeof mk.removeOne === "function") {
                        const mine = (mk.getAll() || []).filter(m =>
                            m?.tags?.includes?.(id) ||
                            (from && to && m?.type === "arrow" && m?.data?.from === from && m?.data?.to === to)
                        );
                        for (const m of mine) mk.removeOne(m.key ?? m);
                        const stillThere = (mk.getAll() || []).some(m =>
                            m?.tags?.includes?.(id) ||
                            (from && to && m?.type === "arrow" && m?.data?.from === from && m?.data?.to === to)
                        );
                        cleared = !stillThere;
                    }
                    if (!cleared && typeof mk.removeAll === "function") {
                        mk.removeAll();
                    }
                }
            }
        },
        removeByType: (type) => {
            const toRemove = state.visuals.filter(v => v.type === type);
            toRemove.forEach(v => Visuals.remove(v.id));
        }
    };

    // --- 3RD-PARTY STOCKFISH 19 LITE MOVE GRADING ENGINE & BADGE ---
    const getTargetGradeDepth = () => Math.min(20, Math.max(10, parseInt(settings.gradeDepth, 10) || 15));
    const GRADE_META = {
        brilliant:  { code: "brilliant",  label: "Brilliant",  symbol: "!!", color: "#26c2a3" },
        great:      { code: "great",      label: "Great",      symbol: "!",  color: "#749bbf" },
        best:       { code: "best",       label: "Best",       symbol: "★",  color: "#81b64c" },
        excellent:  { code: "excellent",  label: "Excellent",  symbol: "👍", color: "#96bc4b" },
        good:       { code: "good",       label: "Good",       symbol: "✓",  color: "#95b776" },
        inaccuracy: { code: "inaccuracy", label: "Inaccuracy", symbol: "?!", color: "#f7c631" },
        miss:       { code: "miss",       label: "Miss",       symbol: "✕",  color: "#ff7769" },
        mistake:    { code: "mistake",    label: "Mistake",    symbol: "?",  color: "#e6912c" },
        blunder:    { code: "blunder",    label: "Blunder",    symbol: "??", color: "#ca3431" }
    };

    function gradeIconSvg(code, px = 14) {
        const s = `width:${px}px;height:${px}px;display:block;flex-shrink:0;`;
        switch (code) {
            case "best":
                return `<svg viewBox="0 0 24 24" style="${s}" fill="#fff"><path d="M12 2.4l2.9 5.88 6.49.94-4.7 4.58 1.11 6.46L12 17.21l-5.8 3.05 1.11-6.46-4.7-4.58 6.49-.94z"/></svg>`;
            case "excellent":
                return `<svg viewBox="0 0 24 24" style="${s}" fill="#fff"><path d="M2 21h4V9H2v12zm20-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2z"/></svg>`;
            case "good":
                return `<svg viewBox="0 0 24 24" style="${s}" fill="none" stroke="#fff" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`;
            case "miss":
                return `<svg viewBox="0 0 24 24" style="${s}" fill="none" stroke="#fff" stroke-width="3.4" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`;
            default:
                return null;
        }
    }

    function gradeBadgeInnerHtml(meta, iconPx) {
        const svg = gradeIconSvg(meta.code, iconPx);
        return svg || meta.symbol;
    }

    function isMaiaLocalActive() {
        return settings.engineMode === "local" && getEngineById(settings.localModelId || "sf19_lite").format === "onnx";
    }

    const GradeVisual = {
        sq: null,
        meta: null,
        interval: null,
        show: (sq, meta) => {
            if (!sq || !meta || !settings.moveGrading) { GradeVisual.clear(); return; }
            GradeVisual.sq = sq;
            GradeVisual.meta = meta;
            GradeVisual.draw();
            if (!GradeVisual.interval) GradeVisual.interval = setInterval(GradeVisual.draw, 120);
        },
        draw: () => {
            if (!GradeVisual.sq || !GradeVisual.meta || !settings.moveGrading) { GradeVisual.clear(); return; }
            state.board = document.querySelector(CONFIG.BOARD_SEL);
            if (!state.board) return;
            const sq = GradeVisual.sq;
            const meta = GradeVisual.meta;
            const curFlip = String(isBoardFlipped(state.board));
            const existing = document.querySelector(".board-grade-badge");
            if (existing && state.board.contains(existing) && existing.dataset.sq === sq && existing.dataset.code === meta.code && existing.dataset.flip === curFlip) return;
            document.querySelectorAll(".board-grade-badge, .board-grade-tint").forEach(el => el.remove());

            const sqId = `${sq.charCodeAt(0) - 96}${sq.charAt(1)}`;
            const sqPx = Math.max(36, (state.board.clientWidth || 560) / 8);
            const fontPx = Math.max(12, Math.round(sqPx * (meta.symbol.length > 1 ? 0.19 : 0.22)));

            const tint = document.createElement("div");
            tint.className = `square-${sqId} board-grade-tint`;
            tint.style.cssText = `position:absolute; pointer-events:none !important; z-index:140 !important; width:12.5%; height:12.5%; background:${meta.color}; opacity:0.22; box-sizing:border-box;`;
            positionSquareEl(tint, sq, state.board);
            state.board.appendChild(tint);

            const wrap = document.createElement("div");
            wrap.className = `square-${sqId} board-grade-badge`;
            wrap.dataset.sq = sq;
            wrap.dataset.code = meta.code;
            wrap.dataset.flip = curFlip;
            wrap.style.cssText = "position:absolute; pointer-events:none !important; z-index:260 !important; width:12.5%; height:12.5%; display:flex; justify-content:flex-end; align-items:flex-start; box-sizing:border-box;";
            positionSquareEl(wrap, sq, state.board);
            const pill = document.createElement("div");
            pill.innerHTML = gradeBadgeInnerHtml(meta, Math.max(12, Math.round(sqPx * 0.23)));
            pill.style.cssText = `width:40%; height:40%; border-radius:50%; background:${meta.color}; color:#ffffff; font-weight:900; font-size:${fontPx}px; letter-spacing:-0.04em; line-height:1; display:flex; align-items:center; justify-content:center; box-shadow:0 3px 10px rgba(0,0,0,0.6), inset 0 1px 2px rgba(255,255,255,0.35); border:2px solid #ffffff; transform:translate(22%, -22%); font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;`;
            wrap.appendChild(pill);
            state.board.appendChild(wrap);
        },
        clear: () => {
            if (GradeVisual.interval) { clearInterval(GradeVisual.interval); GradeVisual.interval = null; }
            GradeVisual.sq = null;
            GradeVisual.meta = null;
            document.querySelectorAll(".board-grade-badge, .board-grade-tint").forEach(el => el.remove());
        }
    };

    function evalToWinPct(evalWhite, mate, side) {
        let wWin = 50;
        if (mate !== null && mate !== undefined && mate !== 0) {
            wWin = parseInt(mate, 10) > 0 ? 99.9 : 0.1;
        } else if (evalWhite !== null && evalWhite !== undefined && !Number.isNaN(parseFloat(evalWhite))) {
            const cpW = parseFloat(evalWhite) * 100;
            wWin = 50 + 50 * (2 / (1 + Math.exp(-0.00368208 * cpW)) - 1);
        }
        return side === "b" ? (100 - wWin) : wWin;
    }

    function computeGap12WinPct(mpv, side) {
        const p1 = mpv?.[1], p2 = mpv?.[2];
        if (!p1 || !p2) return 0;
        const w1 = evalToWinPct(p1.type === "mate" ? null : p1.whiteVal / 100, p1.type === "mate" ? p1.whiteVal : null, side);
        const w2 = evalToWinPct(p2.type === "mate" ? null : p2.whiteVal / 100, p2.type === "mate" ? p2.whiteVal : null, side);
        return Math.max(0, w1 - w2);
    }

    function revokeGraderBlobUrls() {
        if (Array.isArray(state.graderBlobUrls)) {
            state.graderBlobUrls.forEach(u => { try { URL.revokeObjectURL(u); } catch (_) {} });
        }
        state.graderBlobUrls = [];
    }

    function destroyGraderEngine() {
        if (state.graderEngine) {
            try { state.graderEngine.terminate(); } catch (_) {}
            state.graderEngine = null;
        }
        revokeGraderBlobUrls();
        state.graderReady = false;
        state.graderLoading = false;
        state.graderSearching = false;
        state.graderStopSent = false;
        state.graderAborted = false;
        state.graderActiveFen = null;
        state.graderQueue = [];
        state.graderMultiPV = {};
        state.graderMode = "grade";
        state.pendingCandEval = null;
        GradeVisual.clear();
        state.lastGrade = null;
        state.pendingGrades = [];
    }

    function initGraderEngine() {
        const needed = settings.moveGrading || (settings.showMultiBest && isMaiaLocalActive());
        if (!needed || state.graderEngine || state.graderLoading) return;
        state.graderLoading = true;
        state.graderReady = false;
        const sfLite = getEngineById("sf19_lite");

        const launch = (jsCode, wasmBytes) => {
            try {
                revokeGraderBlobUrls();
                const wasmBlobUrl = URL.createObjectURL(new Blob([wasmBytes], { type: "application/wasm" }));
                const patchCode = `
var _wasmBlobUrl = "${wasmBlobUrl}";
var _origFetch = typeof self.fetch === "function" ? self.fetch : null;
self.fetch = function(url, opts) {
    if (_origFetch) {
        if (typeof url === "string" && url.indexOf("blob:") === 0) return _origFetch.apply(self, arguments);
        return _origFetch(_wasmBlobUrl, opts);
    }
    return Promise.reject(new Error("fetch unavailable"));
};`;
                const workerBlobUrl = URL.createObjectURL(new Blob([patchCode + "\n" + jsCode], { type: "application/javascript" }));
                state.graderBlobUrls = [wasmBlobUrl, workerBlobUrl];
                const w = new Worker(workerBlobUrl + "#" + encodeURIComponent(wasmBlobUrl));
                w.onmessage = handleGraderMessage;
                w.onerror = () => {
                    state.graderLoading = false;
                    state.graderReady = false;
                    state.graderSearching = false;
                    state.graderEngine = null;
                };
                state.graderEngine = w;
                w.postMessage("uci");
            } catch (_) {
                state.graderLoading = false;
                state.graderReady = false;
            }
        };

        openCache((_, db) => {
            const getJs = (cb) => {
                let bundled = null;
                try { if (typeof GM_getResourceText === "function") bundled = GM_getResourceText("stockfish.js"); } catch (_) {}
                if (bundled) { cb(bundled); return; }
                if (db) {
                    readCache(db, sfLite.cacheKey + "_js", (__, cachedJs) => {
                        if (cachedJs) { cb(cachedJs); return; }
                        xhrText(sfLite.jsUrl, (js) => { writeCache(db, sfLite.cacheKey + "_js", js); cb(js); }, () => { state.graderLoading = false; });
                    });
                } else {
                    xhrText(sfLite.jsUrl, cb, () => { state.graderLoading = false; });
                }
            };
            const getWasm = (jsCode) => {
                if (db) {
                    readCache(db, sfLite.cacheKey + "_wasm", (__, cachedWasm) => {
                        if (cachedWasm) { launch(jsCode, cachedWasm); return; }
                        xhrBinary(sfLite.wasmUrl, (bytes) => { writeCache(db, sfLite.cacheKey + "_wasm", bytes); launch(jsCode, bytes); }, () => { state.graderLoading = false; });
                    });
                } else {
                    xhrBinary(sfLite.wasmUrl, (bytes) => launch(jsCode, bytes), () => { state.graderLoading = false; });
                }
            };
            getJs((js) => { if (js) getWasm(js); });
        });
    }

    function handleGraderMessage(e) {
        const msg = typeof e.data === "string" ? e.data : null;
        if (!msg || !state.graderEngine) return;

        if (msg === "uciok") {
            [
                "setoption name Hash value 64",
                "setoption name Move Overhead value 10",
                "setoption name Skill Level value 20",
                "setoption name UCI_LimitStrength value false",
                "setoption name UCI_ShowWDL value false",
                "setoption name MultiPV value 1",
                "isready"
            ].forEach(c => state.graderEngine.postMessage(c));
            return;
        }
        if (msg === "readyok") {
            state.graderLoading = false;
            state.graderReady = true;
            revokeGraderBlobUrls();
            if (state.lastSeenFEN && !state.gradeSnapshots[state.lastSeenFEN] && !state.graderQueue.includes(state.lastSeenFEN)) {
                state.graderQueue.push(state.lastSeenFEN);
            }
            pumpGraderQueue();
            return;
        }
        if (msg.startsWith("info") && msg.includes("depth") && msg.includes("score") && state.graderSearching && state.graderActiveFen) {
            const depthMatch = msg.match(/depth (\d+)/);
            const scoreMatch = msg.match(/score (cp|mate) (-?\d+)/);
            const pvMatch = msg.match(/ pv (.*)/);
            const mpvMatch = msg.match(/ multipv (\d+)/);
            if (!depthMatch || !scoreMatch) return;
            const dNum = parseInt(depthMatch[1], 10);
            const type = scoreMatch[1];
            const rawVal = parseInt(scoreMatch[2], 10);
            const pvIdx = mpvMatch ? parseInt(mpvMatch[1], 10) : 1;
            const pv = pvMatch ? pvMatch[1].trim() : "";
            const isBound = msg.includes("upperbound") || msg.includes("lowerbound");
            const side = (state.graderActiveFen.split(" ")[1] || "w");
            const whiteVal = (side === "b") ? -rawVal : rawVal;

            if (!isBound) {
                state.graderMultiPV[pvIdx] = {
                    depth: dNum,
                    type,
                    rawVal,
                    whiteVal,
                    pv,
                    move: pv ? pv.split(" ")[0] : null
                };
                state.graderLiveDepth = Math.max(state.graderLiveDepth || 0, dNum);
            }

            if (!state.graderStopSent && state.graderMode === "grade" && settings.engineMode === "local" && (state.isThinking || state.isLocalSearching)) {
                state.graderAborted = true;
                state.graderStopSent = true;
                state.graderEngine.postMessage("stop");
            }
            return;
        }
        if (msg.startsWith("bestmove")) {
            const fen = state.graderActiveFen;
            const mpv = state.graderMultiPV || {};
            const p1 = mpv[1];
            const bm = msg.split(" ")[1];
            const wasAborted = state.graderAborted;
            const mode = state.graderMode || "grade";
            const targetD = getTargetGradeDepth();
            state.graderSearching = false;
            state.graderStopSent = false;
            state.graderAborted = false;
            state.graderMode = "grade";
            state.graderActiveFen = null;
            state.graderMultiPV = {};
            if (mode === "cand") {
                try { state.graderEngine.postMessage("setoption name MultiPV value 1"); } catch (_) {}
                if (!wasAborted && fen && fen === state.lastSeenFEN && settings.showMultiBest && mpv[1]?.move) {
                    const cands = buildCandidatesFromMultiPV(mpv, fen);
                    state.lastCandidates = cands;
                    MultiBest.update(cands, fen);
                }
                pumpGraderQueue();
                return;
            }
            if (fen) {
                if (wasAborted) {
                    pumpGraderQueue();
                    return;
                }
                const side = (fen.split(" ")[1] || "w");
                if (bm === "(none)") {
                    const b64 = fenToBoard64(fen);
                    const kIdx = b64 ? b64.indexOf(side === "w" ? "K" : "k") : -1;
                    const inCheck = kIdx >= 0 && isAttackedBy(b64, kIdx, side !== "w");
                    const winM = inCheck ? 0.0 : 50.0;
                    const evW = inCheck ? (side === "w" ? "-999.00" : "999.00") : "0.00";
                    recordGradeSnapshot(fen, {
                        bestMove: null,
                        winMover: winM,
                        evalWhite: evW,
                        mate: inCheck ? 0 : null,
                        isCheckmate: inCheck,
                        depth: targetD
                    });
                    if (settings.moveGrading && fen === state.lastSeenFEN) {
                        const mDir = inCheck ? (side === "w" ? -1 : 1) : null;
                        EvalBar.update(inCheck ? null : 0, mDir);
                        state.hudEvalTxt = inCheck ? (mDir < 0 ? "-M0" : "M0") : "0.0";
                        state.hudStatus = getEvalStatusData(mDir !== null ? mDir : 0, inCheck);
                    }
                } else if (p1 && (p1.type === "mate" || p1.depth >= targetD)) {
                    recordGradeSnapshot(fen, {
                        bestMove: (p1.move || bm || null),
                        evalWhite: p1.type === "mate" ? null : (p1.whiteVal / 100).toFixed(2),
                        mate: p1.type === "mate" ? p1.whiteVal : null,
                        pv: p1.pv ? p1.pv.split(" ") : (bm ? [bm] : []),
                        gap12Win: computeGap12WinPct(mpv, side),
                        hasAltMove: mpv[2] ? Boolean(mpv[2].move) : true,
                        depth: p1.depth
                    });
                    if (settings.moveGrading && fen === state.lastSeenFEN) {
                        const gEv = p1.type === "mate" ? null : (p1.whiteVal / 100);
                        const gM = p1.type === "mate" ? p1.whiteVal : null;
                        EvalBar.update(gEv, gM);
                        state.hudEvalTxt = gM !== null ? `${gM < 0 ? "-" : ""}M${Math.abs(gM)}` : `${p1.whiteVal > 0 ? "+" : ""}${(p1.whiteVal / 100).toFixed(2)}`;
                        state.hudStatus = getEvalStatusData(gM !== null ? gM : (p1.whiteVal / 100), gM !== null);
                    }
                }
            }
            pumpGraderQueue();
        }
    }

    function requestMaiaCandEval(fen, moves) {
        if (!settings.showMultiBest || !fen || !Array.isArray(moves) || !moves.length) return;
        state.pendingCandEval = { fen, moves: moves.slice(0, 3) };
        if (!state.graderEngine && !state.graderLoading) initGraderEngine();
        pumpGraderQueue();
    }

    function pumpGraderQueue() {
        const needCand = Boolean(state.pendingCandEval && settings.showMultiBest && !settings.silentMode && state.pendingCandEval.fen === state.lastSeenFEN);
        if (!settings.moveGrading && !needCand) return;
        if (!state.graderEngine && !state.graderLoading) { initGraderEngine(); return; }
        if (!state.graderReady || state.graderSearching) return;
        if (settings.engineMode === "local" && (state.isThinking || state.isLocalSearching)) return;

        if (settings.moveGrading) {
            while (state.graderQueue.length > 0) {
                const nextFen = state.graderQueue.shift();
                if (!nextFen || state.gradeSnapshots[nextFen]) continue;
                state.graderSearching = true;
                state.graderMode = "grade";
                state.graderStopSent = false;
                state.graderAborted = false;
                state.graderActiveFen = nextFen;
                state.graderMultiPV = {};
                state.graderLiveDepth = 0;
                state.graderEngine.postMessage(`position fen ${nextFen}`);
                state.graderEngine.postMessage(`go depth ${getTargetGradeDepth()}`);
                return;
            }
        }

        if (needCand) {
            const ce = state.pendingCandEval;
            state.pendingCandEval = null;
            state.graderSearching = true;
            state.graderMode = "cand";
            state.graderStopSent = false;
            state.graderAborted = false;
            state.graderActiveFen = ce.fen;
            state.graderMultiPV = {};
            state.graderLiveDepth = 0;
            state.graderEngine.postMessage("setoption name MultiPV value 3");
            state.graderEngine.postMessage(`position fen ${ce.fen}`);
            state.graderEngine.postMessage(`go depth 12 searchmoves ${ce.moves.join(" ")}`);
        }
    }

    function enqueueGraderFen(fen, toFront = false) {
        if (!settings.moveGrading || !fen || state.gradeSnapshots[fen]) return;
        if (state.graderActiveFen === fen) return;
        const idx = state.graderQueue.indexOf(fen);
        if (idx !== -1) {
            if (!toFront) return;
            state.graderQueue.splice(idx, 1);
        }
        if (toFront) state.graderQueue.unshift(fen);
        else state.graderQueue.push(fen);
        while (state.graderQueue.length > 20) state.graderQueue.pop();
        pumpGraderQueue();
    }

    function findLeastValuableAttacker(b64, sqIdx, isWhite) {
        if (!b64 || sqIdx < 0 || sqIdx > 63) return null;
        const r = Math.floor(sqIdx / 8), f = sqIdx % 8;
        const kChar = isWhite ? "K" : "k";
        const kIdx = b64.indexOf(kChar);
        const wouldExposeKing = (fromIdx) => {
            if (kIdx < 0 || fromIdx === kIdx) return false;
            const sim = b64.slice();
            sim[sqIdx] = sim[fromIdx];
            sim[fromIdx] = ".";
            return isAttackedBy(sim, kIdx, !isWhite);
        };
        const at = (rr, ff) => (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) ? b64[rr * 8 + ff] : ".";

        const pr = isWhite ? r + 1 : r - 1;
        const pCh = isWhite ? "P" : "p";
        for (const df of [-1, 1]) {
            const ff = f + df;
            if (pr >= 0 && pr < 8 && ff >= 0 && ff < 8 && b64[pr * 8 + ff] === pCh) {
                const idx = pr * 8 + ff;
                if (!wouldExposeKing(idx)) return { idx, piece: "p" };
            }
        }
        const nCh = isWhite ? "N" : "n";
        for (const [dr, df] of [[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]]) {
            const rr = r + dr, ff = f + df;
            if (rr >= 0 && rr < 8 && ff >= 0 && ff < 8 && b64[rr * 8 + ff] === nCh) {
                const idx = rr * 8 + ff;
                if (!wouldExposeKing(idx)) return { idx, piece: "n" };
            }
        }
        const bCh = isWhite ? "B" : "b";
        for (const [dr, df] of [[-1,-1],[-1,1],[1,-1],[1,1]]) {
            let rr = r + dr, ff = f + df;
            while (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                const c = at(rr, ff);
                if (c !== ".") {
                    if (c === bCh && !wouldExposeKing(rr * 8 + ff)) return { idx: rr * 8 + ff, piece: "b" };
                    break;
                }
                rr += dr; ff += df;
            }
        }
        const rCh = isWhite ? "R" : "r";
        for (const [dr, df] of [[-1,0],[1,0],[0,-1],[0,1]]) {
            let rr = r + dr, ff = f + df;
            while (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                const c = at(rr, ff);
                if (c !== ".") {
                    if (c === rCh && !wouldExposeKing(rr * 8 + ff)) return { idx: rr * 8 + ff, piece: "r" };
                    break;
                }
                rr += dr; ff += df;
            }
        }
        const qCh = isWhite ? "Q" : "q";
        for (const [dr, df] of [[-1,-1],[-1,1],[1,-1],[1,1],[-1,0],[1,0],[0,-1],[0,1]]) {
            let rr = r + dr, ff = f + df;
            while (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                const c = at(rr, ff);
                if (c !== ".") {
                    if (c === qCh && !wouldExposeKing(rr * 8 + ff)) return { idx: rr * 8 + ff, piece: "q" };
                    break;
                }
                rr += dr; ff += df;
            }
        }
        for (let dr = -1; dr <= 1; dr++) for (let df = -1; df <= 1; df++) {
            const rr = r + dr, ff = f + df;
            if ((dr || df) && rr >= 0 && rr < 8 && ff >= 0 && ff < 8 && b64[rr * 8 + ff] === kChar) {
                return { idx: rr * 8 + ff, piece: "k" };
            }
        }
        return null;
    }

    function seeCapture(b64, sqIdx, attackerIsWhite) {
        if (!b64 || sqIdx < 0 || sqIdx > 63 || b64[sqIdx] === ".") return 0;
        const pVal = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 100 };
        const sim = b64.slice();
        const gains = [];
        let sideW = attackerIsWhite;
        let targetVal = pVal[sim[sqIdx].toLowerCase()] || 0;

        for (let ply = 0; ply < 16; ply++) {
            const atk = findLeastValuableAttacker(sim, sqIdx, sideW);
            if (!atk) break;
            gains.push(targetVal);
            if (atk.piece === "k") {
                sim[sqIdx] = sideW ? "K" : "k";
                sim[atk.idx] = ".";
                if (isAttackedBy(sim, sqIdx, !sideW)) {
                    gains.pop();
                    break;
                }
                targetVal = 100;
                sideW = !sideW;
                continue;
            }
            targetVal = pVal[atk.piece] || 0;
            sim[sqIdx] = sim[atk.idx];
            sim[atk.idx] = ".";
            sideW = !sideW;
        }
        if (!gains.length) return 0;
        for (let i = gains.length - 2; i >= 0; i--) {
            gains[i] = Math.max(0, gains[i] - gains[i + 1]);
        }
        return gains[0];
    }

    function recordGradeSnapshot(fen, info) {
        if (!fen || !info) return;
        const side = (fen.split(" ")[1] || "w");
        const winMover = (typeof info.winMover === "number")
            ? info.winMover
            : evalToWinPct(info.evalWhite, info.mate, side);
        const prevSnap = state.gradeSnapshots[fen];
        state.gradeSnapshots[fen] = {
            fen,
            side,
            bestMove: info.bestMove || prevSnap?.bestMove || null,
            winMover,
            evalWhite: info.evalWhite ?? null,
            mate: info.mate ?? null,
            gap12Win: (typeof info.gap12Win === "number" && info.gap12Win > 0) ? info.gap12Win : (prevSnap?.gap12Win || 0),
            isCheckmate: Boolean(info.isCheckmate || prevSnap?.isCheckmate),
            hasAltMove: (info.hasAltMove !== undefined) ? Boolean(info.hasAltMove) : (prevSnap?.hasAltMove ?? true),
            depth: info.depth || prevSnap?.depth || getTargetGradeDepth(),
            wasOppBlunder: prevSnap?.wasOppBlunder || false
        };
        const keys = Object.keys(state.gradeSnapshots);
        if (keys.length > 48) delete state.gradeSnapshots[keys[0]];

        if (Array.isArray(state.pendingGrades) && state.pendingGrades.length) {
            const remaining = [];
            for (const pg of state.pendingGrades) {
                if (state.gradeSnapshots[pg.prevFen] && state.gradeSnapshots[pg.currFen]) {
                    computeAndShowGrade(pg.prevFen, pg.currFen, pg.mvInfo);
                } else {
                    remaining.push(pg);
                }
            }
            state.pendingGrades = remaining;
        }
    }

    function computeAndShowGrade(prevFen, currFen, mvInfo) {
        if (!settings.moveGrading) return;
        const before = state.gradeSnapshots[prevFen];
        const after = state.gradeSnapshots[currFen];
        if (!before || !after || !mvInfo?.uci) return;

        const moverSide = before.side;
        const playedUci = mvInfo.uci;
        const winBefore = before.winMover;
        const winAfter = 100 - after.winMover;
        const winLoss = Math.max(0, winBefore - winAfter);
        const isBestMove = Boolean(
            before.bestMove &&
            playedUci.slice(0, 4) === before.bestMove.slice(0, 4) &&
            (playedUci.length <= 4 || before.bestMove.length <= 4 || playedUci[4] === before.bestMove[4])
        );

        const b64Prev = fenToBoard64(prevFen);
        const b64Curr = fenToBoard64(currFen);
        const feat = analyzeMoveFeatures(playedUci, b64Prev, moverSide, null);
        const pValMap = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
        const fromIdx = (8 - parseInt(playedUci[1], 10)) * 8 + (playedUci.charCodeAt(0) - 97);
        const toIdx = (8 - parseInt(playedUci[3], 10)) * 8 + (playedUci.charCodeAt(2) - 97);
        const oppIsWhite = (moverSide !== "w");

        const capVal = feat.capVal || 0;
        const fromSeeBefore = (b64Prev && feat.piece !== "p" && feat.piece !== "k") ? seeCapture(b64Prev, fromIdx, oppIsWhite) : 0;
        const destSeeLoss = (feat.piece !== "p" && feat.piece !== "k" && !feat.isQueenTrade)
            ? Math.max(0, seeCapture(b64Curr, toIdx, oppIsWhite) - capVal)
            : 0;
        const isDesperado = (destSeeLoss > 0 && fromSeeBefore >= 2 && destSeeLoss <= fromSeeBefore && winAfter < 55 && !isBestMove);

        let leftPieceSeeLoss = 0;
        if (b64Prev && b64Curr) {
            for (let idx = 0; idx < 64; idx++) {
                if (idx === toIdx) continue;
                const ch = b64Curr[idx];
                if (ch === ".") continue;
                const isMine = (moverSide === "w") ? (ch === ch.toUpperCase()) : (ch === ch.toLowerCase());
                if (!isMine) continue;
                const pLow = ch.toLowerCase();
                if ((pValMap[pLow] || 0) < 3) continue;
                const seeAfter = seeCapture(b64Curr, idx, oppIsWhite);
                if (seeAfter >= 2) {
                    const prevCh = b64Prev[idx];
                    const seeBefore = (prevCh === ch) ? seeCapture(b64Prev, idx, oppIsWhite) : 0;
                    if (seeAfter - seeBefore >= 2 || (seeBefore >= 2 && (isBestMove || (before.gap12Win || 0) >= 6) && seeAfter - capVal >= 2)) {
                        leftPieceSeeLoss = Math.max(leftPieceSeeLoss, seeAfter - capVal);
                    }
                }
            }
        }

        const directSacOk = (destSeeLoss >= 1 && !isDesperado);
        const indirectSacOk = (leftPieceSeeLoss >= 2);
        const pv2Win = Math.max(0, winBefore - (before.gap12Win || 0));
        const notAlreadyCrushing = (before.gap12Win > 0) ? (pv2Win < 92) : (winBefore < 94);
        const isTrueBrilliant = Boolean(
            !after.isCheckmate &&
            before.hasAltMove &&
            !feat.isRecapture &&
            (directSacOk || indirectSacOk) &&
            (isBestMove || winLoss <= 2.0) &&
            notAlreadyCrushing &&
            winAfter >= 45
        );

        const isGreat = Boolean(
            before.hasAltMove &&
            (isBestMove || winLoss <= 0.8) && !after.isCheckmate && (
                (before.gap12Win >= 12 && winBefore < 88 && winAfter >= 42) ||
                (winBefore <= 60 && winAfter >= 72 && before.gap12Win >= 8) ||
                (winBefore <= 36 && winAfter >= 46 && before.gap12Win >= 8)
            )
        );

        let meta;
        if (isTrueBrilliant) {
            meta = GRADE_META.brilliant;
        } else if (isGreat) {
            meta = GRADE_META.great;
        } else if (isBestMove || winLoss <= 0.6) {
            meta = GRADE_META.best;
        } else if (winLoss <= 2.4) {
            meta = GRADE_META.excellent;
        } else if (winLoss <= 5.5 || winAfter >= 92) {
            meta = GRADE_META.good;
        } else if (before.wasOppBlunder && winLoss >= 8.0 && winAfter < 78) {
            meta = GRADE_META.miss;
        } else if (winLoss <= 10.0 || winAfter >= 84) {
            meta = GRADE_META.inaccuracy;
        } else if (winLoss <= 20.0) {
            meta = GRADE_META.mistake;
        } else {
            meta = GRADE_META.blunder;
        }

        if (winLoss >= 14.0) after.wasOppBlunder = true;

        const myChar = (state.playingAs === 2) ? "b" : "w";
        const isUserMove = (moverSide === myChar);
        const gradeObj = {
            who: isUserMove ? "You" : "Opp",
            moverSide,
            rawWinLoss: winLoss,
            uci: playedUci,
            sq: mvInfo.to,
            meta,
            winLoss: winLoss.toFixed(1),
            depth: Math.min(before.depth || getTargetGradeDepth(), after.depth || getTargetGradeDepth())
        };
        if (!state.gradesByMoveKey) state.gradesByMoveKey = {};
        const moveKey = `${prevFen}|${currFen}|${playedUci}`;
        const isNewGrade = !state.gradesByMoveKey[moveKey];
        state.gradesByMoveKey[moveKey] = gradeObj;

        const { timeline, idx } = getActiveTimelineAndIdx();
        if (timeline && timeline.length > 1) {
            refreshGradesForTimeline(timeline, idx);
        } else if (isNewGrade) {
            recordGradeInTally(moverSide, meta, winLoss);
            if (currFen === state.lastSeenFEN) {
                state.lastGrade = gradeObj;
                if (isUserMove) state.lastUserGrade = gradeObj;
                else state.lastOppGrade = gradeObj;
            }
        }
        if (currFen === state.lastSeenFEN) {
            GradeVisual.show(mvInfo.to, meta);
        }
        updateUI();
    }

    function getActiveTimelineAndIdx() {
        if (isCgSite()) return { timeline: _cgCache.timeline || [], idx: _cgCache.viewedPly || 0 };
        return { timeline: state.ccTimeline || [], idx: state.ccActiveIdx || 0 };
    }

    function refreshGradesForTimeline(timeline, idx) {
        const tally = resetGradeTally();
        let lastAny = null, lastUser = null, lastOpp = null;
        const myChar = (state.playingAs === 2) ? "b" : "w";
        for (let i = 1; i < timeline.length; i++) {
            const e = timeline[i];
            if (!e?.prevFen || !e?.mvInfo?.uci) continue;
            const k = `${e.prevFen}|${e.fen}|${e.mvInfo.uci}`;
            const g = state.gradesByMoveKey?.[k];
            if (!g) continue;
            const bucket = tally[g.moverSide === "b" ? "b" : "w"];
            if (bucket && g.meta?.code && bucket[g.meta.code] !== undefined) {
                bucket[g.meta.code]++;
                const acc = Math.max(0, Math.min(100, 103.1668 * Math.exp(-0.04354 * Math.max(0, g.rawWinLoss || 0)) - 3.1669));
                bucket.accSum += acc;
                bucket.moves++;
            }
            if (i <= idx) {
                const isU = (g.moverSide === myChar);
                const cloned = { ...g, who: isU ? "You" : "Opp" };
                if (i === idx) lastAny = cloned;
                if (isU) lastUser = cloned;
                else lastOpp = cloned;
            }
        }
        state.gradeTally = tally;
        state.lastGrade = (idx >= 1) ? lastAny : null;
        state.lastUserGrade = (idx >= 1) ? lastUser : null;
        state.lastOppGrade = (idx >= 1) ? lastOpp : null;
    }

    function syncGradingToViewedState(currFen, moveEntry) {
        if (!settings.moveGrading) {
            GradeVisual.clear();
            return;
        }

        const snap = currFen ? state.gradeSnapshots?.[currFen] : null;
        if (snap) {
            const gEv = snap.mate !== null ? null : (snap.evalWhite !== null ? parseFloat(snap.evalWhite) : 0);
            EvalBar.update(gEv, snap.mate);
            state.hudEvalTxt = snap.mate !== null ? `${snap.mate < 0 ? "-" : ""}M${Math.abs(snap.mate)}` : `${gEv > 0 ? "+" : ""}${gEv.toFixed(2)}`;
            state.hudStatus = getEvalStatusData(snap.mate !== null ? snap.mate : gEv, snap.mate !== null);
        } else if (!moveEntry) {
            EvalBar.reset();
            state.hudEvalTxt = "0.0";
            state.hudStatus = { text: "Ready", color: "#8b949e" };
        } else if (currFen) {
            enqueueGraderFen(currFen, true);
        }

        const { timeline, idx } = getActiveTimelineAndIdx();
        if (timeline && timeline.length) refreshGradesForTimeline(timeline, idx);

        if (!moveEntry || !moveEntry.prevFen || !moveEntry.mvInfo?.uci) {
            GradeVisual.clear();
            state.lastGrade = null;
            return;
        }
        const k = `${moveEntry.prevFen}|${currFen}|${moveEntry.mvInfo.uci}`;
        const cached = state.gradesByMoveKey?.[k];
        if (cached) {
            state.lastGrade = { ...cached, who: (cached.moverSide === ((state.playingAs === 2) ? "b" : "w")) ? "You" : "Opp" };
            GradeVisual.show(moveEntry.mvInfo.to, cached.meta);
        } else {
            onMoveDetectedForGrading(moveEntry.prevFen, currFen, moveEntry.mvInfo);
        }
    }

    function onMoveDetectedForGrading(prevFen, currFen, mvInfo) {
        if (!settings.moveGrading || !mvInfo?.uci) return;
        GradeVisual.clear();
        const k = `${prevFen}|${currFen}|${mvInfo.uci}`;
        if (state.gradesByMoveKey?.[k]) {
            if (currFen === state.lastSeenFEN) GradeVisual.show(mvInfo.to, state.gradesByMoveKey[k].meta);
            return;
        }
        if (state.graderSearching && state.graderActiveFen && !state.graderAborted) {
            const activeFen = state.graderActiveFen;
            // Only abort if searching an older stale position; keep going if it's already working on prevFen or currFen
            if (activeFen !== prevFen && activeFen !== currFen) {
                state.graderAborted = true;
                state.graderStopSent = true;
                try { state.graderEngine.postMessage("stop"); } catch (_) {}
                if (!state.gradeSnapshots[activeFen] && !state.graderQueue.includes(activeFen)) {
                    state.graderQueue.push(activeFen);
                }
            }
        }
        const alreadyPending = state.pendingGrades.some(pg => pg.prevFen === prevFen && pg.currFen === currFen && pg.mvInfo?.uci === mvInfo.uci);
        if (!alreadyPending) {
            state.pendingGrades.push({ prevFen, currFen, mvInfo });
            if (state.pendingGrades.length > 30) state.pendingGrades.shift();
        }
        // LIFO priority: newest position pair always goes to the front of the queue
        enqueueGraderFen(currFen, true);
        if (!state.gradeSnapshots[prevFen]) enqueueGraderFen(prevFen, true);
    }

    // --- PV MANAGER ---
    const PV = {
        interval: null,
        lastMoves: [],
        update: (pvMoves) => {
            PV.lastMoves = pvMoves || [];
            if (!settings.showPVArrows || settings.silentMode) { PV.clear(); return; }
            PV.draw();
            if (!PV.interval) PV.interval = setInterval(PV.draw, 100);
        },
        clear: () => {
            if (PV.interval) { clearInterval(PV.interval); PV.interval = null; }
            document.querySelectorAll('.board-pv-arrow').forEach(el => el.remove());
        },
        draw: () => {
            state.board = document.querySelector(CONFIG.BOARD_SEL);
            if (!state.board) return;
            if (!settings.showPVArrows || !PV.lastMoves.length) { PV.clear(); return; }
            const existing = document.querySelector('.board-pv-arrow');
            if (existing && !state.board.contains(existing)) PV.clear();
            const limit = Math.min(PV.lastMoves.length, settings.pvDepth);
            for (let i = 0; i < limit; i++) {
                const move = PV.lastMoves[i];
                const id = `board-pv-arrow-${i}`;
                const el = document.querySelector(`.${id}`);
                if (el && state.board.contains(el)) {
                    if (el.dataset.move === move) continue;
                    el.remove();
                } else if (el) el.remove();
                let color = settings.highlightColor;
                if (settings.pvCustomGradient) {
                    const start = hexToRgb(settings.pvStartColor);
                    const end = hexToRgb(settings.pvEndColor);
                    const factor = limit === 1 ? 0 : i / (limit - 1);
                    const r = Math.round(start.r + factor * (end.r - start.r));
                    const g = Math.round(start.g + factor * (end.g - start.g));
                    const b = Math.round(start.b + factor * (end.b - start.b));
                    color = `rgb(${r},${g},${b})`;
                }
                drawPVArrow(move, id, color, i + 1);
            }
            let i = limit;
            while (document.querySelector(`.board-pv-arrow-${i}`)) {
                document.querySelectorAll(`.board-pv-arrow-${i}`).forEach(e => e.remove());
                i++;
            }
        }
    };

    function drawPVArrow(move, id, color, index) {
        state.board = document.querySelector(CONFIG.BOARD_SEL);
        if (!state.board) return;
        const isFlipped = isBoardFlipped(state.board);
        const from = move.substring(0, 2), to = move.substring(2, 4);
        const getCoords = (sq) => {
            const file = sq.charCodeAt(0) - 97, rank = parseInt(sq[1]) - 1;
            return isFlipped ? { x: (7 - file) * 12.5 + 6.25, y: rank * 12.5 + 6.25 } : { x: file * 12.5 + 6.25, y: (7 - rank) * 12.5 + 6.25 };
        };
        const start = getCoords(from), end = getCoords(to);
        const dx = end.x - start.x, dy = end.y - start.y;
        const len = Math.sqrt(dx * dx + dy * dy);
        if (len === 0) return;
        const scale = (settings.arrowWidth || 15) / 15;
        const headLen = 3.6 + 1.5 * (scale - 1), headWidth = 3.0 + 1.8 * (scale - 1), lineWidth = 1.35 * Math.pow(scale, 0.95);
        const ux = dx / len, uy = dy / len;
        const endLineX = end.x - ux * headLen, endLineY = end.y - uy * headLen;
        const px = -uy, py = ux;
        const ns = "http://www.w3.org/2000/svg";
        const svg = document.createElementNS(ns, "svg");
        svg.setAttribute("class", `board-pv-arrow pv-arrow ${id}`);
        svg.dataset.move = move;
        svg.style.cssText = "position:absolute; top:0; left:0; width:100%; height:100%; pointer-events:none; z-index:900;";
        svg.setAttribute("viewBox", "0 0 100 100");
        const line = document.createElementNS(ns, "line");
        line.setAttribute("x1", start.x); line.setAttribute("y1", start.y);
        line.setAttribute("x2", endLineX); line.setAttribute("y2", endLineY);
        line.setAttribute("stroke", color); line.setAttribute("stroke-width", lineWidth);
        line.setAttribute("stroke-opacity", settings.arrowOpacity || 0.85);
        line.setAttribute("stroke-linecap", "round");
        const poly = document.createElementNS(ns, "polygon");
        poly.setAttribute("points", `${end.x},${end.y} ${endLineX + px * (headWidth / 2)},${endLineY + py * (headWidth / 2)} ${endLineX - px * (headWidth / 2)},${endLineY - py * (headWidth / 2)}`);
        poly.setAttribute("fill", color); poly.setAttribute("fill-opacity", settings.arrowOpacity || 0.85);
        svg.appendChild(line); svg.appendChild(poly);
        if (settings.pvShowNumbers) {
            const text = document.createElementNS(ns, "text");
            text.setAttribute("x", (start.x + end.x) / 2); text.setAttribute("y", (start.y + end.y) / 2);
            text.setAttribute("dy", "0.3em"); text.setAttribute("text-anchor", "middle");
            text.setAttribute("fill", "#fff"); text.setAttribute("font-size", "2.5");
            text.setAttribute("font-weight", "bold"); text.setAttribute("stroke", "#000");
            text.setAttribute("stroke-width", "0.1"); text.textContent = index;
            svg.appendChild(text);
        }
        state.board.appendChild(svg);
    }

    function drawArrow(move, id) {
        state.board = document.querySelector(CONFIG.BOARD_SEL);
        if (!state.board) return;
        const color = settings.highlightColor, opacity = settings.arrowOpacity || 0.85, width = settings.arrowWidth || 15;
        const isFlipped = isBoardFlipped(state.board);
        const from = move.substring(0, 2), to = move.substring(2, 4);
        const getCoords = (sq) => {
            const file = sq.charCodeAt(0) - 97, rank = parseInt(sq[1]) - 1;
            return isFlipped ? { x: (7 - file) * 12.5 + 6.25, y: rank * 12.5 + 6.25 } : { x: file * 12.5 + 6.25, y: (7 - rank) * 12.5 + 6.25 };
        };
        const start = getCoords(from), end = getCoords(to);
        const dx = end.x - start.x, dy = end.y - start.y;
        const len = Math.sqrt(dx * dx + dy * dy);
        if (len === 0) return;
        const scale = width / 15, headLen = 3.8 + 1.7 * (scale - 1), headWidth = 3.2 + 2.0 * (scale - 1), lineWidth = 1.65 * Math.pow(scale, 0.95);
        const df = Math.abs(to.charCodeAt(0) - from.charCodeAt(0));
        const dr = Math.abs(parseInt(to[1], 10) - parseInt(from[1], 10));
        const isKnight = (df === 1 && dr === 2) || (df === 2 && dr === 1);
        let elbow = start;
        if (isKnight) {
            elbow = (Math.abs(dx) > Math.abs(dy)) ? { x: end.x, y: start.y } : { x: start.x, y: end.y };
        }
        const segDx = end.x - elbow.x, segDy = end.y - elbow.y;
        const segLen = Math.hypot(segDx, segDy) || 1;
        const ux = segDx / segLen, uy = segDy / segLen;
        const endLineX = end.x - ux * headLen, endLineY = end.y - uy * headLen;
        const px = -uy, py = ux;
        const ns = "http://www.w3.org/2000/svg";
        const svg = document.createElementNS(ns, "svg");
        svg.setAttribute("class", `board-highlight ${id}`);
        svg.style.cssText = "position:absolute; top:0; left:0; width:100%; height:100%; pointer-events:none; z-index:200; opacity:1;";
        svg.setAttribute("viewBox", "0 0 100 100");
        const line = document.createElementNS(ns, "path");
        line.setAttribute("d", isKnight ? `M ${start.x} ${start.y} L ${elbow.x} ${elbow.y} L ${endLineX} ${endLineY}` : `M ${start.x} ${start.y} L ${endLineX} ${endLineY}`);
        line.setAttribute("fill", "none");
        line.setAttribute("stroke", color); line.setAttribute("stroke-width", lineWidth);
        line.setAttribute("stroke-opacity", opacity);
        line.setAttribute("stroke-linecap", "round");
        line.setAttribute("stroke-linejoin", "round");
        const polygon = document.createElementNS(ns, "polygon");
        polygon.setAttribute("points", `${end.x},${end.y} ${endLineX + px * (headWidth / 2)},${endLineY + py * (headWidth / 2)} ${endLineX - px * (headWidth / 2)},${endLineY - py * (headWidth / 2)}`);
        polygon.setAttribute("fill", color); polygon.setAttribute("fill-opacity", opacity);
        svg.appendChild(line); svg.appendChild(polygon);
        state.board.appendChild(svg);
    }

    // --- MULTI-BEST CANDIDATE ARROWS, TALLY & ENGINE FOCUS ---
    function resetGradeTally() {
        const blank = () => ({ brilliant: 0, great: 0, best: 0, excellent: 0, good: 0, inaccuracy: 0, miss: 0, mistake: 0, blunder: 0, accSum: 0, moves: 0 });
        return { w: blank(), b: blank() };
    }

    function recordGradeInTally(side, meta, winLoss) {
        if (!state.gradeTally) state.gradeTally = resetGradeTally();
        const bucket = state.gradeTally[side === "b" ? "b" : "w"];
        if (bucket && meta?.code && bucket[meta.code] !== undefined) {
            bucket[meta.code]++;
            const acc = Math.max(0, Math.min(100, 103.1668 * Math.exp(-0.04354 * Math.max(0, winLoss)) - 3.1669));
            bucket.accSum += acc;
            bucket.moves++;
        }
    }

    function getTallyAccText(side) {
        const b = state.gradeTally?.[side];
        if (!b || !b.moves) return "--";
        return (b.accSum / b.moves).toFixed(1) + "%";
    }

    function gradeForCandidate(cand, bestCand, side, rankIdx, fen, secondCand = null) {
        const gSnap = fen ? state.gradeSnapshots?.[fen] : null;
        const bestWin = evalToWinPct(bestCand.evalWhite, bestCand.mate, side);
        const refWin = (gSnap && typeof gSnap.winMover === "number") ? Math.max(bestWin, gSnap.winMover) : bestWin;
        const cWin = evalToWinPct(cand.evalWhite, cand.mate, side);
        const loss = Math.max(0, refWin - cWin);
        const refBest = gSnap?.bestMove || bestCand.move;
        const isBest = Boolean(refBest && cand.move && cand.move.slice(0, 4) === refBest.slice(0, 4));
        const pv2Win = secondCand
            ? evalToWinPct(secondCand.evalWhite, secondCand.mate, side)
            : (gSnap?.gap12Win ? Math.max(0, refWin - gSnap.gap12Win) : null);
        const notAlreadyCrushing = (pv2Win !== null) ? (pv2Win < 92) : (refWin < 94);

        const b64 = fenToBoard64(fen);
        if (b64 && cand.move && cand.move.length >= 4 && (isBest || loss <= 2.0)) {
            const feat = analyzeMoveFeatures(cand.move, b64, side, state.oppLastTo);
            const oppIsWhite = (side !== "w");
            const toIdx = (8 - parseInt(cand.move[3], 10)) * 8 + (cand.move.charCodeAt(2) - 97);
            const fromIdx = (8 - parseInt(cand.move[1], 10)) * 8 + (cand.move.charCodeAt(0) - 97);
            const fromSeeBefore = (feat.piece !== "p" && feat.piece !== "k") ? seeCapture(b64, fromIdx, oppIsWhite) : 0;
            const nextB = b64.slice();
            nextB[toIdx] = cand.move.length > 4 ? (side === "w" ? cand.move[4].toUpperCase() : cand.move[4].toLowerCase()) : b64[fromIdx];
            nextB[fromIdx] = ".";
            const destSac = (feat.piece !== "p" && feat.piece !== "k" && !feat.isQueenTrade)
                ? Math.max(0, seeCapture(nextB, toIdx, oppIsWhite) - (feat.capVal || 0))
                : 0;
            const isDesperado = (destSac > 0 && fromSeeBefore >= 2 && destSac <= fromSeeBefore && cWin < 55 && !isBest);
            if (destSac >= 1 && !isDesperado && !feat.isRecapture && notAlreadyCrushing && cWin >= 45) return GRADE_META.brilliant;
        }
        const gap12 = pv2Win !== null ? Math.max(0, refWin - pv2Win) : (gSnap?.gap12Win || 0);
        if (isBest && gap12 >= 12 && refWin < 88 && cWin >= 42) return GRADE_META.great;
        if (isBest || (rankIdx === 0 && !gSnap) || loss <= 0.6) return GRADE_META.best;
        if (loss <= 2.4) return GRADE_META.excellent;
        if (loss <= 5.5 || cWin >= 92) return GRADE_META.good;
        if (loss <= 10.5 || cWin >= 84) return GRADE_META.inaccuracy;
        if (loss <= 20.5) return GRADE_META.mistake;
        return GRADE_META.blunder;
    }

    function buildCandidatesFromMultiPV(mpv, fen) {
        const side = (fen?.split(" ")[1] || "w");
        const arr = [1, 2, 3].map(i => mpv?.[i]).filter(p => p && p.move);
        return arr.map((p, idx) => ({
            move: p.move,
            evalWhite: p.type === "mate" ? null : (p.whiteVal / 100),
            mate: p.type === "mate" ? p.whiteVal : null,
            cpMover: p.cpMover,
            rank: idx,
            side
        }));
    }

    function pickFocusMove(bestMove, mpv, fen) {
        const focus = settings.engineFocus || "balanced";
        if (settings.humanMode || focus === "balanced") return mpv?.[1] || { move: bestMove };
        const pv1 = mpv?.[1];
        if (!pv1 || !pv1.move) return { move: bestMove };
        if (pv1.type === "mate" && pv1.rawVal > 0 && pv1.rawVal <= 3) return pv1;

        const side = (fen?.split(" ")[1] || "w");
        const b64 = fenToBoard64(fen);
        if (!b64) return pv1;

        const maxDrop = focus === "custom"
            ? Math.min(80, Math.max(10, Number(settings.focusTolerance) || 35))
            : (focus === "gambit" ? 50 : (focus === "aggressive" || focus === "initiative" ? 38 : 30));
        const cands = [1, 2, 3, 4].map(i => mpv?.[i]).filter(p => p && p.move && (pv1.cpMover - p.cpMover) <= maxDrop && !(p.type === "mate" && p.rawVal < 0));
        if (cands.length <= 1) return pv1;

        const geom = analyzeBoardGeometry(b64, side);
        let atkW = 0, safW = 0, simW = 0;
        if (focus === "aggressive") { atkW = 1.0; simW = -0.5; }
        else if (focus === "gambit") { atkW = 1.3; safW = -0.3; simW = -0.8; }
        else if (focus === "initiative") { atkW = 0.8; simW = -0.4; }
        else if (focus === "safety") { safW = 1.2; atkW = -0.3; simW = 0.4; }
        else if (focus === "conversion") { simW = 1.2; safW = 0.5; atkW = -0.3; }
        else if (focus === "custom") {
            atkW = ((Number(settings.focusAttack) ?? 50) - 50) / 35;
            safW = ((Number(settings.focusSafety) ?? 50) - 50) / 35;
            simW = ((Number(settings.focusSimplify) ?? 50) - 50) / 35;
        }

        let bestCand = pv1, bestScore = -1e9;
        for (const p of cands) {
            const feat = analyzeMoveFeatures(p.move, b64, side, state.oppLastTo);
            const cpLoss = Math.max(0, pv1.cpMover - p.cpMover);
            let fScore = 0;

            let atkPart = 0;
            if (feat.givesCheck) atkPart += 22;
            if (feat.isSacrifice && feat.piece !== "p") atkPart += (focus === "gambit" ? 32 : 20);
            if (feat.nearEnemyKing) atkPart += 18;
            if (feat.isCapture && !feat.isQueenTrade) atkPart += 12;
            if (feat.isEndgamePawnPush || feat.score >= 16) atkPart += 8;

            let safPart = 0;
            if (feat.piece === "k" && !feat.isQuietKing) safPart += 26;
            if (feat.isRetreat) safPart += 14;
            if (feat.isQueenTrade && geom.myKingExposed >= 2) safPart += 16;
            if (feat.isSacrifice) safPart -= 22;
            if (feat.isWeirdRookLift) safPart -= 16;
            if (feat.piece === "p" && feat.score < 0) safPart -= 18;

            let simPart = 0;
            if (feat.isQueenTrade) simPart += 28;
            if (feat.isCapture) simPart += 18;
            if (feat.isEndgamePawnPush || feat.isKingActiveEnd) simPart += 14;
            if (feat.isSacrifice) simPart -= 16;

            fScore = atkW * atkPart + safW * safPart + simW * simPart;
            const util = fScore - cpLoss * 0.72;
            if (util > bestScore) { bestScore = util; bestCand = p; }
        }
        return bestCand;
    }

    const MultiBest = {
        cands: [],
        fen: "",
        interval: null,
        update: (cands, fen) => {
            MultiBest.cands = Array.isArray(cands) ? cands.slice(0, 3) : [];
            MultiBest.fen = fen || "";
            if (!settings.showMultiBest || settings.silentMode || !MultiBest.cands.length) {
                MultiBest.clear();
                return;
            }
            MultiBest.draw();
            if (!MultiBest.interval) MultiBest.interval = setInterval(MultiBest.draw, 120);
        },
        clear: () => {
            if (MultiBest.interval) { clearInterval(MultiBest.interval); MultiBest.interval = null; }
            MultiBest.cands = [];
            document.querySelectorAll(".board-multibest-el").forEach(el => el.remove());
        },
        draw: () => {
            if (!settings.showMultiBest || settings.silentMode || !MultiBest.cands.length) { MultiBest.clear(); return; }
            state.board = document.querySelector(CONFIG.BOARD_SEL);
            if (!state.board) return;
            const curFlip = String(isBoardFlipped(state.board));
            const sig = MultiBest.cands.map(c => c.move).join(",") + "|" + curFlip;
            const existing = document.querySelector(".board-multibest-el");
            if (existing && state.board.contains(existing) && existing.dataset.sig === sig) return;
            document.querySelectorAll(".board-multibest-el").forEach(el => el.remove());

            const isFlipped = isBoardFlipped(state.board);
            const getCoords = (sq) => {
                const file = sq.charCodeAt(0) - 97, rank = parseInt(sq[1], 10) - 1;
                return isFlipped ? { x: (7 - file) * 12.5 + 6.25, y: rank * 12.5 + 6.25 } : { x: file * 12.5 + 6.25, y: (7 - rank) * 12.5 + 6.25 };
            };

            const side = (MultiBest.fen.split(" ")[1] || "w");
            const bestCand = MultiBest.cands[0];
            const sqCounts = {};
            const sqPx = Math.max(36, (state.board.clientWidth || 560) / 8);
            const ns = "http://www.w3.org/2000/svg";

            for (let i = MultiBest.cands.length - 1; i >= 0; i--) {
                const c = MultiBest.cands[i];
                if (!c?.move || c.move.length < 4) continue;
                const from = c.move.slice(0, 2), to = c.move.slice(2, 4);
                const meta = gradeForCandidate(c, bestCand, side, i, MultiBest.fen, MultiBest.cands[1] || null);
                const arrowColor = meta.color || (i === 0 ? "#81b64c" : "#58a6ff");
                const opacity = Math.min(1, Math.max(0.25, (settings.arrowOpacity || 0.85) * (i === 0 ? 1 : (i === 1 ? 0.88 : 0.78))));
                const scale = ((settings.arrowWidth || 15) / 15) * (i === 0 ? 1 : 0.84);

                const start = getCoords(from), end = getCoords(to);
                const df = Math.abs(to.charCodeAt(0) - from.charCodeAt(0));
                const dr = Math.abs(parseInt(to[1], 10) - parseInt(from[1], 10));
                const isKnight = (df === 1 && dr === 2) || (df === 2 && dr === 1);

                const headLen = 3.6 + 1.6 * (scale - 1), headWidth = 3.1 + 1.9 * (scale - 1), lineWidth = 1.65 * Math.pow(scale, 0.95);
                let elbow = start;
                if (isKnight) {
                    elbow = (Math.abs(end.x - start.x) > Math.abs(end.y - start.y))
                        ? { x: end.x, y: start.y }
                        : { x: start.x, y: end.y };
                }
                const segDx = end.x - elbow.x, segDy = end.y - elbow.y;
                const segLen = Math.hypot(segDx, segDy) || 1;
                const ux = segDx / segLen, uy = segDy / segLen;
                const endLineX = end.x - ux * headLen, endLineY = end.y - uy * headLen;
                const px = -uy, py = ux;

                const svg = document.createElementNS(ns, "svg");
                svg.setAttribute("class", "board-multibest-el");
                svg.dataset.sig = sig;
                svg.style.cssText = `position:absolute; top:0; left:0; width:100%; height:100%; pointer-events:none; z-index:${180 + (3 - i)};`;
                svg.setAttribute("viewBox", "0 0 100 100");

                const path = document.createElementNS(ns, "path");
                const dStr = isKnight
                    ? `M ${start.x} ${start.y} L ${elbow.x} ${elbow.y} L ${endLineX} ${endLineY}`
                    : `M ${start.x} ${start.y} L ${endLineX} ${endLineY}`;
                path.setAttribute("d", dStr);
                path.setAttribute("fill", "none");
                path.setAttribute("stroke", arrowColor);
                path.setAttribute("stroke-width", lineWidth);
                path.setAttribute("stroke-opacity", opacity);
                path.setAttribute("stroke-linecap", "round");
                path.setAttribute("stroke-linejoin", "round");

                const poly = document.createElementNS(ns, "polygon");
                poly.setAttribute("points", `${end.x},${end.y} ${endLineX + px * (headWidth / 2)},${endLineY + py * (headWidth / 2)} ${endLineX - px * (headWidth / 2)},${endLineY - py * (headWidth / 2)}`);
                poly.setAttribute("fill", arrowColor);
                poly.setAttribute("fill-opacity", opacity);

                svg.appendChild(path);
                svg.appendChild(poly);
                state.board.appendChild(svg);

                const offsetIdx = sqCounts[to] || 0;
                sqCounts[to] = offsetIdx + 1;
                const sqId = `${to.charCodeAt(0) - 96}${to.charAt(1)}`;
                const badgeWrap = document.createElement("div");
                badgeWrap.className = `square-${sqId} board-multibest-el`;
                badgeWrap.dataset.sig = sig;
                badgeWrap.style.cssText = `position:absolute; pointer-events:none !important; z-index:${240 + (3 - i)} !important; width:12.5%; height:12.5%; display:flex; justify-content:flex-end; align-items:flex-start; box-sizing:border-box;`;
                positionSquareEl(badgeWrap, to, state.board);
                const pill = document.createElement("div");
                const fontPx = Math.max(10, Math.round(sqPx * 0.17));
                pill.innerHTML = gradeBadgeInnerHtml(meta, Math.max(10, Math.round(sqPx * 0.19)));
                const shiftX = 16 - offsetIdx * 28;
                pill.style.cssText = `width:34%; height:34%; border-radius:50%; background:${meta.color}; color:#fff; font-weight:900; font-size:${fontPx}px; letter-spacing:-0.04em; line-height:1; display:flex; align-items:center; justify-content:center; box-shadow:0 2px 6px rgba(0,0,0,0.55); border:1.5px solid #fff; transform:translate(${shiftX}%, -14%); font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;`;
                badgeWrap.appendChild(pill);
                state.board.appendChild(badgeWrap);
            }
        }
    };

    // --- TOGGLEABLE EVALUATION BAR ---
    const injectEvalStyles = () => {
        if (document.getElementById('real-eval-styles')) return;
        const style = document.createElement('style');
        style.id = 'real-eval-styles';
        style.innerHTML = `
            /* Open grid column for the eval bar */
            .board-layout-chessboard {
                grid-template-columns: [evaluation] 2.2rem [pieces] 0 [board] 1fr [board-controls] var(--boardControlsWidth, 0) !important;
                column-gap: 0.75rem;
            }
            main.round.with-cg-eval {
                column-gap: 46px !important;
            }
            /* Wrapper */
            #custom-eval-wrapper {
                display: flex !important;
                align-items: stretch;
                height: 100%;
                z-index: 10;
                position: relative;
            }
            /* Bar */
            #custom-eval-wrapper .evaluation-bar-bar {
                position: relative;
                width: 100%;
                height: 100%;
                border-radius: 4px;
                overflow: hidden;
                background: #262421;
                box-shadow: 0 2px 10px rgba(0,0,0,0.35);
                user-select: none;
            }
            /* Score label */
            #custom-eval-wrapper .evaluation-bar-scoreAbbreviated {
                position: absolute;
                left: 0; right: 0;
                text-align: center;
                font-weight: 800;
                font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
                font-size: 10px;
                letter-spacing: -0.04em;
                padding: 0 1px;
                z-index: 3;
                pointer-events: none;
                transition: top 0.35s ease, bottom 0.35s ease, color 0.2s ease;
                text-rendering: geometricPrecision;
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
                transform: translateZ(0);
            }
            #custom-eval-wrapper .evaluation-bar-dark  { color: #262421; }
            #custom-eval-wrapper .evaluation-bar-light { color: #ffffff; }
            /* Fill layers */
            #custom-eval-wrapper .evaluation-bar-fill {
                position: relative;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
            #custom-eval-wrapper .evaluation-bar-color {
                position: absolute;
                top: 0; left: 0;
                width: 100%;
                height: 100%;
                transition: transform 0.35s cubic-bezier(0.16, 1, 0.3, 1);
                will-change: transform;
            }
            #custom-eval-wrapper .evaluation-bar-black { background: #262421; }
            #custom-eval-wrapper .evaluation-bar-draw  { background: #9e9e9e; transform: translate3d(0px, 100%, 0px); }
            #custom-eval-wrapper .evaluation-bar-white { background: #ffffff; }
            /* Flip the bar when playing as black */
            #custom-eval-wrapper .evaluation-bar-bar.evaluation-bar-flipped {
                transform: scaleY(-1);
            }
            /* Counter-rotate the label so text stays upright and readable */
            #custom-eval-wrapper .evaluation-bar-bar.evaluation-bar-flipped .evaluation-bar-scoreAbbreviated {
                transform: scaleY(-1);
            }
        `;
        document.head.appendChild(style);
    };

    const EvalBar = {
        el: null, whiteFill: null, scoreAbbr: null, barInner: null,

        create: () => {
            if (!settings.showEvalBar) { EvalBar.destroy(); return; }
            if (EvalBar.el && EvalBar.el.isConnected && EvalBar.whiteFill) return;
            injectEvalStyles();

            // Hide the native Chess.com eval bar to avoid grid slot conflict
            const nativeBar = document.getElementById('board-layout-evaluation');
            if (nativeBar) nativeBar.style.display = 'none';

            if (!document.body.classList.contains('with-evaluation'))
                document.body.classList.add('with-evaluation', 'with-visible-evaluation');

            const cgBoardWrap = isCgSite() ? document.querySelector('.round__app__board') : null;
            const boardLayout = cgBoardWrap || document.querySelector('.board-layout-chessboard');
            if (!boardLayout) return;
            if (cgBoardWrap && getComputedStyle(cgBoardWrap).position === 'static') {
                cgBoardWrap.style.position = 'relative';
            }
            if (cgBoardWrap) {
                const mainRound = document.querySelector('main.round');
                if (mainRound) mainRound.classList.add('with-cg-eval');
            }

            // If already built, just re-bind refs and ensure visible
            const existing = document.getElementById('custom-eval-wrapper');
            if (existing) {
                existing.style.display = 'flex';
                EvalBar.el = existing;
                EvalBar.barInner = existing.querySelector('.evaluation-bar-bar');
                EvalBar.whiteFill = existing.querySelector('.evaluation-bar-white');
                EvalBar.scoreAbbr = existing.querySelector('.evaluation-bar-scoreAbbreviated');
                return;
            }

            const wrapper = document.createElement('div');
            wrapper.id = 'custom-eval-wrapper';
            wrapper.className = 'board-layout-evaluation';
            wrapper.style.cssText = cgBoardWrap
                ? 'display:flex; align-items:stretch; position:absolute; left:-38px; top:0; bottom:0; width:30px; min-width:30px; height:100%; z-index:50;'
                : 'display:flex; align-items:stretch; height:100%; z-index:10;';
            wrapper.innerHTML = `
                <div class="evaluation-bar-bar">
                    <span class="evaluation-bar-scoreAbbreviated evaluation-bar-dark" style="bottom:8px;">0.0</span>
                    <div class="evaluation-bar-fill">
                        <div class="evaluation-bar-color evaluation-bar-black"></div>
                        <div class="evaluation-bar-color evaluation-bar-draw"></div>
                        <div class="evaluation-bar-color evaluation-bar-white" style="transform:translate3d(0px,50%,0px);"></div>
                    </div>
                </div>
            `;
            boardLayout.prepend(wrapper);
            EvalBar.el = wrapper;
            EvalBar.barInner = wrapper.querySelector('.evaluation-bar-bar');
            EvalBar.whiteFill = wrapper.querySelector('.evaluation-bar-white');
            EvalBar.scoreAbbr = wrapper.querySelector('.evaluation-bar-scoreAbbreviated');
        },

        destroy: () => {
            const mainRound = document.querySelector('main.round');
            if (mainRound) mainRound.classList.remove('with-cg-eval');
            // Restore native eval bar if it was hidden
            const nativeBar = document.getElementById('board-layout-evaluation');
            if (nativeBar) nativeBar.style.display = '';
            const existing = document.getElementById('custom-eval-wrapper');
            if (existing) existing.style.display = 'none';
            EvalBar.el = null; EvalBar.barInner = null;
            EvalBar.whiteFill = null; EvalBar.scoreAbbr = null;
            document.body.classList.remove('with-evaluation', 'with-visible-evaluation');
            const styleEl = document.getElementById('real-eval-styles');
            if (styleEl) styleEl.remove();
        },

        update: (evalScore, mate) => {
            if (!settings.showEvalBar) { EvalBar.destroy(); return; }
            if (!EvalBar.el || !EvalBar.whiteFill) EvalBar.create();
            if (!EvalBar.whiteFill || !EvalBar.scoreAbbr) return;

            const playingAsBlack = (state.playingAs === 2) || isBoardFlipped(state.board);
            if (EvalBar.barInner) {
                if (playingAsBlack) EvalBar.barInner.classList.add('evaluation-bar-flipped');
                else EvalBar.barInner.classList.remove('evaluation-bar-flipped');
            }

            let percentage = 50, displayScore = '0.0';
            if (mate !== null && mate !== undefined && mate !== 0) {
                const m = parseInt(mate);
                displayScore = 'M' + Math.abs(m);
                percentage = m > 0 ? 0 : 100;
            } else if (evalScore !== null && evalScore !== undefined) {
                const ev = parseFloat(evalScore);
                displayScore = Math.abs(ev) >= 10 ? Math.round(ev).toString() : ev.toFixed(1);
                if (ev > 0 && displayScore !== '0.0') displayScore = '+' + displayScore;
                percentage = 50 - (Math.atan(ev / 2.5) / (Math.PI / 2) * 50);
                percentage = Math.max(5, Math.min(95, percentage));
            }

            EvalBar.whiteFill.style.transform = `translate3d(0px,${percentage.toFixed(2)}%,0px)`;
            EvalBar.scoreAbbr.innerText = displayScore;

            // Label always on the bigger fill (winning side).
            // White fill grows from bottom; black fill from top.
            // percentage < 50 → white region bigger → label at bottom (dark text on white).
            // percentage > 50 → black region bigger → label at top (light text on black).
            // Flip is handled by CSS class evaluation-bar-flipped (rotates the bar visually),
            // but the DOM order is fixed, so label logic is the same regardless of side.
            const whiteIsBigger = percentage <= 50;
            if (whiteIsBigger) {
                EvalBar.scoreAbbr.className = 'evaluation-bar-scoreAbbreviated evaluation-bar-dark';
                EvalBar.scoreAbbr.style.bottom = '8px';
                EvalBar.scoreAbbr.style.top = '';
            } else {
                EvalBar.scoreAbbr.className = 'evaluation-bar-scoreAbbreviated evaluation-bar-light';
                EvalBar.scoreAbbr.style.top = '8px';
                EvalBar.scoreAbbr.style.bottom = '';
            }
        },

        reset: () => {
            if (!EvalBar.whiteFill) return;
            EvalBar.whiteFill.style.transform = 'translate3d(0px,50%,0px)';
            if (EvalBar.scoreAbbr) {
                EvalBar.scoreAbbr.innerText = '0.0';
                EvalBar.scoreAbbr.className = 'evaluation-bar-scoreAbbreviated evaluation-bar-dark';
                EvalBar.scoreAbbr.style.bottom = '8px';
                EvalBar.scoreAbbr.style.top = '';
            }
        }
    };
    // --- EVAL STATUS LOGIC ---
    function getEvalStatusData(val, isMate) {
        const pa = state.playingAs || 1;
        let relativeScore = (pa === 2) ? -val : val;
        if (isMate) {
            if (relativeScore > 0) return { text: "Winning (Mate)", color: "#2ea043" };
            return { text: "Losing (Mate)", color: "#f85149" };
        }
        if (relativeScore > 2.5) return { text: "Decisive Win", color: "#2ea043" };
        if (relativeScore > 1.2) return { text: "Clear Advantage", color: "#3fb950" };
        if (relativeScore > 0.3) return { text: "Slight Advantage", color: "#7ee787" };
        if (relativeScore >= -0.3) return { text: "Equal", color: "#8b949e" };
        if (relativeScore >= -1.2) return { text: "Slight Disadvantage", color: "#ffa657" };
        if (relativeScore >= -2.5) return { text: "Clear Disadvantage", color: "#ff7b72" };
        return { text: "Decisive Disadvantage", color: "#f85149" };
    }

    // --- ENGINE CORE ---
    function setEngineStatus(status, detail = "") {
        state.engineStatus = status;
        state.engineErrorDetail = (status === "error") ? (detail || "Engine error") : "";
        if (status === "error") {
            console.error("[Engine Status Error]", state.engineErrorDetail);
            state.isThinking = false;
            state.isLocalSearching = false;
            state.ignoreLocalBestMoves = 0;
            if (state._searchCapTimer) { clearTimeout(state._searchCapTimer); state._searchCapTimer = null; }
        }
        updateLocalSettingsUI();
    }

    function sendEngineInitCommands(eng) {
        const m = getEngineById(eng || settings.localModelId);
        const cmds = ["ucinewgame"];
        if (m.hasHash)         cmds.push(`setoption name Hash value ${settings.localHashMB}`);
        if (m.hasMoveOverhead) cmds.push(`setoption name Move Overhead value ${settings.localMoveOverhead}`);
        if (m.hasSlowMover)    cmds.push(`setoption name Slow Mover value ${settings.localSlowMover}`);
        if (m.hasMinThink)     cmds.push(`setoption name Minimum Thinking Time value ${settings.localMinThinkTime}`);
        const wantWDL = Boolean(m.hasWDL && (settings.humanMode || settings.localShowWDL));
        if (m.hasWDL) {
            cmds.push(`setoption name UCI_ShowWDL value ${wantWDL}`);
            state._lastShowWDL = wantWDL;
        }
        if (m.hasSkillLevel)   cmds.push(`setoption name Skill Level value ${settings.localSkillLevel}`);
        if (m.hasNNUE) {
            cmds.push(`setoption name UCI_LimitStrength value ${settings.localLimitStrength}`);
            cmds.push(`setoption name UCI_Elo value ${settings.localElo}`);
        }
        if (m.hasContempt) cmds.push(`setoption name Contempt value ${settings.localContempt}`);
        state._lastMultiPV = 1;
        cmds.push("setoption name MultiPV value 1");
        cmds.forEach(c => state.localEngine.postMessage(c));
    }

    function revokeEngineBlobUrls() {
        if (Array.isArray(state._engineBlobUrls)) {
            state._engineBlobUrls.forEach(u => { try { URL.revokeObjectURL(u); } catch (_) {} });
        }
        state._engineBlobUrls = [];
    }

    function buildWasmPatchedEngine(jsCode, wasmBytes) {
        revokeEngineBlobUrls();
        const wasmBlob = new Blob([wasmBytes], { type: "application/wasm" });
        const wasmBlobUrl = URL.createObjectURL(wasmBlob);

        const patchCode = `
var _wasmBlobUrl = "${wasmBlobUrl}";
var _origFetch = typeof self.fetch === "function" ? self.fetch : null;
self.fetch = function(url, opts) {
    if (_origFetch) {
        if (typeof url === "string" && url.indexOf("blob:") === 0) {
            return _origFetch.apply(self, arguments);
        }
        return _origFetch(_wasmBlobUrl, opts);
    }
    return Promise.reject(new Error("fetch unavailable in worker"));
};
function _fmtWorkerErr(e) {
    if (!e) return "Unknown worker error";
    var inner = e.error || e.reason || null;
    if (inner) {
        if (typeof inner === "string") return inner;
        if (inner.stack) return inner.stack;
        if (inner.message) return (inner.name ? inner.name + ": " : "") + inner.message;
        try { return JSON.stringify(inner); } catch(_) { return String(inner); }
    }
    if (e.message && e.message !== "Uncaught [object Object]") return e.message;
    try { return JSON.stringify(e); } catch(_) { return String(e); }
}
self.addEventListener("error", function(err) {
    var loc = (err && err.filename) ? (" (" + err.filename + ":" + err.lineno + ":" + (err.colno||0) + ")") : "";
    self.postMessage("worker_err:" + _fmtWorkerErr(err) + loc);
});
self.addEventListener("unhandledrejection", function(ev) {
    self.postMessage("worker_err:Unhandled Rejection: " + _fmtWorkerErr(ev));
});
`;
        const workerBlob = new Blob([patchCode + "\n" + jsCode], { type: "application/javascript" });
        const workerBlobUrl = URL.createObjectURL(workerBlob);
        state._engineBlobUrls = [wasmBlobUrl, workerBlobUrl];
        return new Worker(workerBlobUrl + "#" + encodeURIComponent(wasmBlobUrl));
    }

    function buildAsmJsEngine(jsCode) {
        revokeEngineBlobUrls();
        const blob = new Blob([jsCode], { type: "application/javascript" });
        const blobUrl = URL.createObjectURL(blob);
        state._engineBlobUrls = [blobUrl];
        return new Worker(blobUrl);
    }

    function finalizeEngine(modelId) {
        if (_engineInitTimer) { clearTimeout(_engineInitTimer); _engineInitTimer = null; }
        state.engineLoadingInProgress = false;
        setEngineStatus("loading", "Initializing engine...");
        _engineInitTimer = setTimeout(() => {
            if (state.engineStatus === "loading") {
                setEngineStatus("error", "Engine initialization timed out (30s). Please click Re-download.");
                updateUI();
                updateLocalSettingsUI();
            }
        }, 30000);
        const m = getEngineById(modelId);
        state.localEngine.postMessage("uci");
        sendEngineInitCommands(modelId);
        state.localEngine.postMessage("isready");
        updateUI();
        updateLocalSettingsUI();
    }

    function onEngineWorkerError(e) {
        const detail = (e && e.message) ? `${e.message} (${e.filename||"worker"}:${e.lineno||0}:${e.colno||0})` : (e ? String(e) : "Worker script error");
        console.error("[Engine Worker Error]", detail, e);
        if (state._searchCapTimer) { clearTimeout(state._searchCapTimer); state._searchCapTimer = null; }
        state.searchTrace = null;
        state.isLocalSearching = false;
        handleError("Engine Worker Error", detail);
        setEngineStatus("error", detail);
        state.localEngine = null;
        state.engineLoadingInProgress = false;
        updateUI();
        updateLocalSettingsUI();
    }

    // --- CACHE HELPERS ---
    function openCache(cb) {
        const dbReq = indexedDB.open("sfEngineCache", 4);
        dbReq.onupgradeneeded = (e) => {
            const db = e.target.result;
            if (!db.objectStoreNames.contains("engines")) db.createObjectStore("engines");
        };
        dbReq.onsuccess = (e) => cb(null, e.target.result);
        dbReq.onerror = () => cb(new Error("IndexedDB open failed"), null);
    }



    function readCache(db, key, cb) {
        try {
            const req = db.transaction("engines", "readonly").objectStore("engines").get(key);
            req.onsuccess = (e) => cb(null, e.target.result || null);
            req.onerror = () => cb(null, null);
        } catch (e) { cb(null, null); }
    }

    function writeCache(db, key, data) {
        try {
            const tx = db.transaction("engines", "readwrite");
            tx.objectStore("engines").put(data, key);
        } catch (e) {}
    }

    function deleteCache(db, key, cb) {
        try {
            const tx = db.transaction("engines", "readwrite");
            const req = tx.objectStore("engines").delete(key);
            tx.oncomplete = () => cb && cb();
            req.onerror = () => cb && cb();
        } catch (e) { cb && cb(); }
    }

    // --- DOWNLOAD HELPERS ---
    function xhrText(url, cb, errCb, progCb) {
        GM_xmlhttpRequest({
            method: "GET", url, timeout: 35000,
            onprogress: (p) => {
                if (p.lengthComputable && progCb) {
                    const pct = Math.min(100, Math.max(0, Math.round((p.loaded / p.total) * 100)));
                    const loadedKB = (p.loaded / 1024).toFixed(1);
                    const totalKB = (p.total / 1024).toFixed(1);
                    progCb(pct, `${loadedKB}/${totalKB} KB (${pct}%)`, p.loaded, p.total);
                } else if (progCb && p.loaded) {
                    const loadedKB = (p.loaded / 1024).toFixed(1);
                    progCb(50, `${loadedKB} KB downloaded...`, p.loaded, 0);
                }
            },
            onload: (r) => {
                if (r.status >= 400) { errCb(new Error(`HTTP ${r.status} (${url.split("/").slice(-2).join("/")})`)); return; }
                cb(r.responseText);
            },
            onerror: (e) => errCb(new Error("Network error: " + url)),
            ontimeout: () => errCb(new Error("Timeout: " + url)),
        });
    }

    function xhrBinary(url, cb, errCb, progCb) {
        GM_xmlhttpRequest({
            method: "GET", url, responseType: "arraybuffer", timeout: 240000,
            onprogress: (p) => {
                if (p.lengthComputable && progCb) {
                    const pct = Math.min(100, Math.max(0, Math.round((p.loaded / p.total) * 100)));
                    const loadedMB = (p.loaded / 1048576).toFixed(2);
                    const totalMB = (p.total / 1048576).toFixed(2);
                    progCb(pct, `${loadedMB}/${totalMB} MB (${pct}%)`, p.loaded, p.total);
                } else if (progCb && p.loaded) {
                    const loadedMB = (p.loaded / 1048576).toFixed(2);
                    progCb(50, `${loadedMB} MB downloaded...`, p.loaded, 0);
                }
            },
            onload: (r) => {
                if (r.status >= 400) { errCb(new Error(`HTTP ${r.status}`)); return; }
                cb(new Uint8Array(r.response));
            },
            onerror: (e) => errCb(new Error("Download failed: " + url)),
            ontimeout: () => errCb(new Error("Download timed out: " + url)),
        });
    }

    function updateProgressUI(pct, phaseText, detailText) {
        if (state.shadow) {
            const fill = state.shadow.getElementById("localProgressFill");
            if (fill) fill.style.width = Math.min(100, Math.max(0, pct)) + "%";
            const phaseEl = state.shadow.getElementById("progressPhaseLabel");
            if (phaseEl) phaseEl.textContent = phaseText;
            const detailEl = state.shadow.getElementById("progressDetailLabel");
            if (detailEl) detailEl.textContent = detailText || (pct + "%");
            const badge = state.shadow.getElementById("activeModelBadge");
            if (badge) {
                badge.className = "status-badge downloading";
                badge.textContent = `⚡ DOWNLOADING ${pct}%`;
            }
        }
        state.lastMoveResult = formatMoveResult(getActiveModelTitle(), `${pct}%`, phaseText);
        state.lastLiveResult = formatLiveResult("...", { text: detailText || "Downloading...", color: "#d29922" }, "", "Preparing local engine...");
        updateUI();
    }

    function inspectModelStorage(model, cb) {
        openCache((err, db) => {
            if (!db) { cb({ isCached: false, jsStatus: "DB unavailable", wasmStatus: "DB unavailable", totalMB: 0 }); return; }
            if (model.format === "onnx") {
                const rtKey = "maia3_js_bundle_v020_ort1220_r4";
                const onnxKey = model.cacheKey + "_onnx";
                readCache(db, rtKey, (_, rtData) => {
                    readCache(db, onnxKey, (_, onnxData) => {
                        const hasRt = !!rtData;
                        const hasOnnx = !!onnxData;
                        const onnxBytes = (onnxData && onnxData.byteLength) ? onnxData.byteLength : (onnxData && onnxData.length ? onnxData.length : 0);
                        const onnxMB = onnxBytes > 0 ? (onnxBytes / 1048576).toFixed(2) : 0;
                        cb({
                            isCached: hasRt && hasOnnx,
                            jsStatus: hasRt ? "💾 Saved ONNX + Maia-3 Runtime" : "○ Not Downloaded",
                            wasmStatus: hasOnnx ? `💾 Saved in IndexedDB (${onnxMB} MB)` : "○ Not Downloaded",
                            totalMB: onnxMB
                        });
                    });
                });
            } else if (model.format === "asmjs") {
                readCache(db, model.cacheKey, (_, jsData) => {
                    const isCached = !!jsData;
                    const sizeMB = jsData ? (jsData.length / 1048576).toFixed(2) : 0;
                    cb({
                        isCached,
                        jsStatus: isCached ? `💾 Saved in IndexedDB (${sizeMB} MB)` : "○ Not Downloaded",
                        wasmStatus: "— (Pure JS / No WASM)",
                        totalMB: sizeMB
                    });
                });
            } else {
                const jsKey = model.cacheKey + "_js";
                const wasmKey = model.cacheKey + "_wasm";
                const isBundled = (model.id === "sf19_lite" && typeof GM_getResourceText === "function" && !!GM_getResourceText("stockfish.js"));
                readCache(db, jsKey, (_, jsData) => {
                    readCache(db, wasmKey, (_, wasmData) => {
                        const hasJs = isBundled || !!jsData;
                        const hasWasm = !!wasmData;
                        const jsText = isBundled ? "📦 Bundled (@resource)" : (jsData ? `💾 Saved in IndexedDB (${(jsData.length/1024).toFixed(1)} KB)` : "○ Not Downloaded");
                        const wasmBytes = (wasmData && wasmData.byteLength) ? wasmData.byteLength : (wasmData && wasmData.length ? wasmData.length : 0);
                        const wasmMB = wasmBytes > 0 ? (wasmBytes / 1048576).toFixed(2) : 0;
                        const wasmText = wasmData ? `💾 Saved in IndexedDB (${wasmMB} MB)` : "○ Not Downloaded";
                        cb({
                            isCached: hasJs && hasWasm,
                            jsStatus: jsText,
                            wasmStatus: wasmText,
                            totalMB: wasmMB
                        });
                    });
                });
            }
        });
    }

    function gmFetchTextPromise(url) {
        return new Promise((resolve, reject) => {
            xhrText(url, resolve, reject, null);
        });
    }

    async function buildMaia3RuntimeBundle(db) {
        const cacheKey = "maia3_js_bundle_v020_ort1220_r4";
        if (db) {
            const cached = await new Promise(res => readCache(db, cacheKey, (_, v) => res(v)));
            if (cached && cached.modules && cached.entryUrl && cached.ortEntryUrl && cached.ortMjs && cached.ortWasm) {
                return cached;
            }
        }
        const PKG_ROOT = "https://cdn.jsdelivr.net/npm/[email protected]/";
        let entrySubpath = "./dist/web/index.web.js";
        try {
            updateProgressUI(6, "Reading Maia-3 Manifest", "package.json");
            const pkg = JSON.parse(await gmFetchTextPromise(PKG_ROOT + "package.json"));
            const webExp = pkg?.exports?.["./web"];
            if (typeof webExp === "string") entrySubpath = webExp;
            else if (webExp && typeof webExp === "object") entrySubpath = webExp.import || webExp.default || entrySubpath;
        } catch (_) {}
        const ENTRY_URL = new URL(entrySubpath, PKG_ROOT).href;
        const CHESS_ESM_URL = "https://cdn.jsdelivr.net/npm/chess.js/+esm";
        const ORT_VER = "1.22.0";
        const ORT_ESM_URL = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ORT_VER}/dist/ort.wasm.min.mjs`;
        const ORT_MJS_URL = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ORT_VER}/dist/ort-wasm-simd-threaded.mjs`;
        const ORT_WASM_URL = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ORT_VER}/dist/ort-wasm-simd-threaded.wasm`;

        const modules = {};
        const visiting = new Set();
        const importRe = /(?:(?:^|[\s;{}(),])(?:import|export)\b(?:[\s*{][^"';]*?\bfrom)?\s*|\bimport\s*\(\s*)["']([^"']+)["']/gm;
        const isResolvableSpec = (spec) => Boolean(
            spec && (
                spec === "chess.js" || spec.startsWith("chess.js/") ||
                spec === "onnxruntime-web" || spec.startsWith("onnxruntime-web/") ||
                spec.startsWith(".") || spec.startsWith("/") ||
                spec.startsWith("http://") || spec.startsWith("https://")
            )
        );
        const normalizeUrl = (spec, base) => {
            if (spec === "onnxruntime-web" || spec.startsWith("onnxruntime-web/")) return ORT_ESM_URL;
            if (spec === "chess.js" || spec.startsWith("chess.js/")) return CHESS_ESM_URL;
            const abs = new URL(spec, base).href;
            if (abs.includes("/onnxruntime-web")) return ORT_ESM_URL;
            return abs;
        };

        const fetchModule = async (url) => {
            if (modules[url] || visiting.has(url)) return;
            visiting.add(url);
            const shortName = url.split("/").filter(Boolean).slice(-2).join("/");
            updateProgressUI(Math.min(45, 8 + Object.keys(modules).length * 4), "Downloading Maia-3 Runtime", shortName);
            const code = await gmFetchTextPromise(url);
            const deps = [];
            importRe.lastIndex = 0;
            let match;
            while ((match = importRe.exec(code)) !== null) {
                const spec = match[1];
                if (isResolvableSpec(spec)) deps.push(normalizeUrl(spec, url));
            }
            modules[url] = code;
            for (const dep of deps) await fetchModule(dep);
        };

        await fetchModule(ENTRY_URL);
        await fetchModule(ORT_ESM_URL);

        updateProgressUI(52, "Downloading ONNX Glue", "ort-wasm-simd-threaded.mjs");
        const ortMjs = await gmFetchTextPromise(ORT_MJS_URL);

        updateProgressUI(60, "Downloading ONNX Runtime WASM", "Connecting...");
        const ortWasm = await new Promise((resolve, reject) => {
            xhrBinary(ORT_WASM_URL, resolve, reject, (pct, txt) => updateProgressUI(60 + Math.round(pct * 0.25), "Downloading ONNX Runtime WASM", txt));
        });

        const bundle = { entryUrl: ENTRY_URL, ortEntryUrl: ORT_ESM_URL, chessEsmUrl: CHESS_ESM_URL, ortMjsUrl: ORT_MJS_URL, modules, ortMjs, ortWasm };
        if (db) writeCache(db, cacheKey, bundle);
        return bundle;
    }

    function spawnMaia3Worker(bundle, model, db) {
        revokeEngineBlobUrls();
        const blobUrls = [];
        const blobMap = {};
        const importRe = /(?:(?:^|[\s;{}(),])(?:import|export)\b(?:[\s*{][^"';]*?\bfrom)?\s*|\bimport\s*\(\s*)["']([^"']+)["']/gm;
        const isResolvableSpec = (spec) => Boolean(
            spec && (
                spec === "chess.js" || spec.startsWith("chess.js/") ||
                spec === "onnxruntime-web" || spec.startsWith("onnxruntime-web/") ||
                spec.startsWith(".") || spec.startsWith("/") ||
                spec.startsWith("http://") || spec.startsWith("https://")
            )
        );
        const normalizeUrl = (spec, base) => {
            if (spec === "onnxruntime-web" || spec.startsWith("onnxruntime-web/")) return bundle.ortEntryUrl;
            if (spec === "chess.js" || spec.startsWith("chess.js/")) return bundle.chessEsmUrl;
            const abs = new URL(spec, base).href;
            if (abs.includes("/onnxruntime-web")) return bundle.ortEntryUrl;
            return abs;
        };

        const ortMjsFixed = bundle.ortMjs.replace(/\bimport\.meta\.url\b/g, JSON.stringify(bundle.ortMjsUrl || ""));
        const ortMjsBlob = URL.createObjectURL(new Blob([ortMjsFixed], { type: "application/javascript" }));
        const ortWasmBlob = URL.createObjectURL(new Blob([bundle.ortWasm], { type: "application/wasm" }));
        const ortMjsHolderBlob = URL.createObjectURL(new Blob([
            `import _ortWasmFactory from "${ortMjsBlob}";\n` +
            `const __ortWasmMod = { default: _ortWasmFactory };\n` +
            `export const __ortDynImport = async (u) => {\n` +
            `    const s = String(u || "");\n` +
            `    if (!s || s === "${ortMjsBlob}" || s.includes("ort-wasm")) return __ortWasmMod;\n` +
            `    throw new Error("Unexpected dynamic import in ORT worker: " + s);\n` +
            `};\n`
        ], { type: "application/javascript" }));
        blobUrls.push(ortMjsBlob, ortWasmBlob, ortMjsHolderBlob);

        const replaceDynamicImports = (code, fnName) => {
            let out = "", i = 0, n = code.length;
            let lastSigChar = "", lastWord = "";
            const regexPrevWords = new Set(["return", "throw", "case", "in", "of", "typeof", "void", "delete", "else", "do", "await", "yield"]);
            while (i < n) {
                const ch = code[i];
                if (ch === "'" || ch === '"' || ch === "`") {
                    const q = ch;
                    let j = i + 1;
                    while (j < n) {
                        if (code[j] === "\\") { j += 2; continue; }
                        if (code[j] === q) { j++; break; }
                        j++;
                    }
                    out += code.slice(i, j);
                    lastSigChar = q; lastWord = ""; i = j;
                    continue;
                }
                if (ch === "/" && code[i + 1] === "/") {
                    let j = code.indexOf("\n", i + 2);
                    if (j === -1) j = n;
                    out += code.slice(i, j);
                    i = j;
                    continue;
                }
                if (ch === "/" && code[i + 1] === "*") {
                    let j = code.indexOf("*/", i + 2);
                    j = (j === -1) ? n : (j + 2);
                    out += code.slice(i, j);
                    i = j;
                    continue;
                }
                if (ch === "/" && (!lastSigChar || "(=,:![!&|?;{}~+-*%<>^".includes(lastSigChar) || regexPrevWords.has(lastWord))) {
                    let j = i + 1, inClass = false;
                    while (j < n) {
                        if (code[j] === "\\") { j += 2; continue; }
                        if (code[j] === "[") inClass = true;
                        else if (code[j] === "]") inClass = false;
                        else if (code[j] === "/" && !inClass) { j++; break; }
                        j++;
                    }
                    while (j < n && /[a-z]/i.test(code[j])) j++;
                    out += code.slice(i, j);
                    lastSigChar = "/"; lastWord = ""; i = j;
                    continue;
                }
                if (/[A-Za-z_$]/.test(ch)) {
                    let j = i + 1;
                    while (j < n && /[A-Za-z0-9_$]/.test(code[j])) j++;
                    const word = code.slice(i, j);
                    if (word === "import" && lastSigChar !== ".") {
                        let k = j;
                        while (k < n) {
                            if (/\s/.test(code[k])) { k++; continue; }
                            if (code[k] === "/" && code[k + 1] === "*") {
                                const ce = code.indexOf("*/", k + 2);
                                k = (ce === -1) ? n : (ce + 2);
                                continue;
                            }
                            break;
                        }
                        if (code[k] === "(") {
                            out += fnName + "(";
                            lastSigChar = "("; lastWord = ""; i = k + 1;
                            continue;
                        }
                    }
                    out += word;
                    lastSigChar = word[word.length - 1]; lastWord = word; i = j;
                    continue;
                }
                if (!/\s/.test(ch)) { lastSigChar = ch; lastWord = ""; }
                out += ch;
                i++;
            }
            return out;
        };

        const urls = Object.keys(bundle.modules);
        const built = new Set();
        const buildMod = (modUrl) => {
            if (built.has(modUrl)) return;
            built.add(modUrl);
            const rawCode = bundle.modules[modUrl];
            if (!rawCode) return;
            importRe.lastIndex = 0;
            let m;
            const deps = [];
            while ((m = importRe.exec(rawCode)) !== null) {
                const spec = m[1];
                if (isResolvableSpec(spec)) deps.push(normalizeUrl(spec, modUrl));
            }
            deps.forEach(buildMod);

            let rewritten = rawCode.replace(importRe, (full, spec) => {
                if (!isResolvableSpec(spec)) return full;
                const target = normalizeUrl(spec, modUrl);
                const bUrl = blobMap[target];
                if (!bUrl) return full;
                const qIdx = full.lastIndexOf(spec);
                return full.slice(0, qIdx) + bUrl + full.slice(qIdx + spec.length);
            });
            rewritten = rewritten.replace(/\bimport\.meta\.url\b/g, JSON.stringify(modUrl));

            if (modUrl === bundle.ortEntryUrl) {
                rewritten = `import { __ortDynImport } from "${ortMjsHolderBlob}";\n` + replaceDynamicImports(rewritten, "__ortDynImport");
                const rawOrtBlob = URL.createObjectURL(new Blob([rewritten], { type: "application/javascript" }));
                blobUrls.push(rawOrtBlob);
                const shimCode = `import * as _ort from "${rawOrtBlob}"; export * from "${rawOrtBlob}"; export default (_ort.default || _ort);`;
                const shimUrl = URL.createObjectURL(new Blob([shimCode], { type: "application/javascript" }));
                blobUrls.push(shimUrl);
                blobMap[modUrl] = shimUrl;
            } else {
                const u = URL.createObjectURL(new Blob([rewritten], { type: "application/javascript" }));
                blobUrls.push(u);
                blobMap[modUrl] = u;
            }
        };
        urls.forEach(buildMod);

        const workerScript = `
const _origFetch = self.fetch.bind(self);
const _gmPending = new Map();
let _gmSeq = 0;

self.fetch = function(input, init) {
    const url = (typeof input === "string") ? input : (input && input.url ? input.url : String(input));
    if (url.startsWith("blob:") || url.startsWith("data:")) {
        return _origFetch(input, init);
    }
    return new Promise((resolve, reject) => {
        const id = ++_gmSeq;
        _gmPending.set(id, { resolve, reject, url });
        self.postMessage({ type: "gm_fetch", id, url });
    });
};

import * as ort from "${blobMap[bundle.ortEntryUrl]}";
import { Maia3 } from "${blobMap[bundle.entryUrl]}";

const _lockedWasmPaths = { mjs: "${ortMjsBlob}", wasm: "${ortWasmBlob}" };
try {
    ort.env.wasm.numThreads = 1;
    ort.env.wasm.proxy = false;
    ort.env.wasm.wasmPaths = _lockedWasmPaths;
    Object.defineProperty(ort.env.wasm, "wasmPaths", { get: () => _lockedWasmPaths, set: () => {}, configurable: true });
    Object.defineProperty(ort.env.wasm, "numThreads", { get: () => 1, set: () => {}, configurable: true });
} catch (_) {}

let _maia = null;

self.onmessage = async (ev) => {
    const d = ev.data;
    if (!d || typeof d !== "object") return;
    if (d.type === "gm_fetch_res") {
        const p = _gmPending.get(d.id);
        if (!p) return;
        _gmPending.delete(d.id);
        if (!d.ok) {
            if (d.status && d.status >= 400) {
                p.resolve(new Response(null, { status: d.status, statusText: d.statusText || "Error" }));
            } else {
                p.reject(new Error(d.error || "Fetch failed"));
            }
            return;
        }
        p.resolve(new Response(d.buffer, {
            status: d.status || 200,
            headers: {
                "Content-Type": d.contentType || (p.url.endsWith(".wasm") ? "application/wasm" : "application/octet-stream"),
                "Content-Length": String(d.buffer.byteLength)
            }
        }));
        return;
    }
    if (d.type === "init") {
        try {
            _maia = new Maia3({
                variant: d.variant || "5m",
                intraOpNumThreads: 1,
                graphOptimizationLevel: "all",
                onProgress: (loaded, total) => {
                    self.postMessage({ type: "progress", loaded, total });
                }
            });
            await _maia.load();
            self.postMessage({ type: "ready" });
        } catch (err) {
            self.postMessage({ type: "error", message: err?.message || String(err) });
        }
        return;
    }
    if (d.type === "predict") {
        try {
            if (!_maia) throw new Error("Maia-3 not initialized");
            const opts = {
                fen: d.fen,
                selfElo: d.selfElo || 1500,
                oppoElo: d.oppoElo || 1500,
                topK: 0
            };
            if (Array.isArray(d.priorFens) && d.priorFens.length > 0) {
                opts.priorFens = d.priorFens;
            }
            const res = await _maia.predict(opts);
            let cands = Array.isArray(res?.candidates) ? res.candidates : [];
            if (!cands.length && res?.moves && typeof res.moves.entries === "function") {
                cands = Array.from(res.moves.entries())
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 8)
                    .map(([uci, probability]) => ({ uci, probability }));
            }
            self.postMessage({
                type: "result",
                reqId: d.reqId,
                isGrade: !!d.isGrade,
                result: {
                    bestMove: res?.bestMove,
                    winProbability: res?.winProbability,
                    wdl: res?.wdl,
                    candidates: cands
                }
            });
        } catch (err) {
            self.postMessage({ type: "error", reqId: d.reqId, isGrade: !!d.isGrade, message: err?.message || String(err) });
        }
    }
};
`;
        const workerBlobUrl = URL.createObjectURL(new Blob([workerScript], { type: "application/javascript" }));
        blobUrls.push(workerBlobUrl);
        state._engineBlobUrls = blobUrls;
        const w = new Worker(workerBlobUrl, { type: "module" });
        w._maiaModel = model;
        w._maiaDb = db;
        return w;
    }

    // --- LOCAL ENGINE LOADER ---
    let _engineInitTimer = null;
    function loadLocalEngine() {
        if (state.localEngine) {
            try { state.localEngine.terminate(); } catch (_) {}
            state.localEngine = null;
        }
        if (state.engineLoadingInProgress) return;
        state.engineLoadingInProgress = true;
        state.isThinking = false;
        if (_engineInitTimer) { clearTimeout(_engineInitTimer); _engineInitTimer = null; }
        const modelId = settings.localModelId || "sf19_lite";
        const m = getEngineById(modelId);
        setEngineStatus("loading", "Inspecting local storage...");
        updateProgressUI(5, "Checking Local Cache", "IndexedDB...");

        openCache((dbErr, db) => {
            if (m.format === "onnx") {
                buildMaia3RuntimeBundle(db).then((bundle) => {
                    if (settings.localModelId !== modelId) return;
                    updateProgressUI(88, "Loading Maia-3 Model", "Spawning ONNX Worker...");
                    state.engineLoadingInProgress = false;
                    state.localEngine = spawnMaia3Worker(bundle, m, db);
                    state.localEngine.onerror = onEngineWorkerError;
                    state.localEngine.onmessage = handleLocalMessage;
                    setEngineStatus("loading", "Loading ONNX model weights...");
                    _engineInitTimer = setTimeout(() => {
                        if (state.engineStatus === "loading") {
                            setEngineStatus("error", "Maia-3 initialization timed out. Click Re-download.");
                            updateUI();
                            updateLocalSettingsUI();
                        }
                    }, 180000);
                    state.localEngine.postMessage({ type: "init", variant: m.maiaVariant || "5m" });
                    updateUI();
                    updateLocalSettingsUI();
                }).catch((e) => {
                    state.engineLoadingInProgress = false;
                    setEngineStatus("error", "Maia-3 load failed: " + (e?.message || e));
                    updateUI();
                    updateLocalSettingsUI();
                });
                return;
            }
            if (m.format === "asmjs") {
                const launch = (jsCode) => {
                    try {
                        updateProgressUI(95, "Initializing Worker", "Spawning thread...");
                        state.localEngine = buildAsmJsEngine(jsCode);
                        state.localEngine.onerror = onEngineWorkerError;
                        state.localEngine.onmessage = handleLocalMessage;
                        finalizeEngine(modelId);
                    } catch (e) {
                        state.engineLoadingInProgress = false;
                        setEngineStatus("error", e.message || "Build failed");
                    }
                };
                if (db) {
                    readCache(db, m.cacheKey, (_, cached) => {
                        if (cached) {
                            updateProgressUI(80, "Found in Local Storage", "Loading cached JS...");
                            launch(cached);
                        } else {
                            updateProgressUI(10, "Connecting to CDN", m.jsUrl);
                            xhrText(m.jsUrl,
                                (js) => {
                                    if (db) writeCache(db, m.cacheKey, js);
                                    updateProgressUI(85, "Saved to Local Cache", "Launching engine...");
                                    launch(js);
                                },
                                (e) => { state.engineLoadingInProgress = false; setEngineStatus("error", "Download failed: " + e.message); },
                                (pct, text) => updateProgressUI(pct, "Downloading Engine JavaScript", text)
                            );
                        }
                    });
                } else {
                    xhrText(m.jsUrl, launch,
                        (e) => { state.engineLoadingInProgress = false; setEngineStatus("error", e.message); },
                        (pct, text) => updateProgressUI(pct, "Downloading Engine JavaScript", text)
                    );
                }
            } else {
                const jsKey   = m.cacheKey + "_js";
                const wasmKey = m.cacheKey + "_wasm";

                const launch = (jsCode, wasmBytes) => {
                    try {
                        updateProgressUI(95, "Compiling WebAssembly", "Instantiating Worker...");
                        state.localEngine = buildWasmPatchedEngine(jsCode, wasmBytes);
                        state.localEngine.onerror = onEngineWorkerError;
                        state.localEngine.onmessage = handleLocalMessage;
                        finalizeEngine(modelId);
                    } catch (e) {
                        state.engineLoadingInProgress = false;
                        setEngineStatus("error", e.message || "Build failed");
                    }
                };

                const getJs = (cb) => {
                    if (m.id === "sf19_lite") {
                        let bundled = null;
                        try { if (typeof GM_getResourceText === "function") bundled = GM_getResourceText("stockfish.js"); } catch (_) {}
                        if (bundled) { cb(bundled); return; }
                    }
                    if (db) {
                        readCache(db, jsKey, (_, cachedJs) => {
                            if (cachedJs) {
                                cb(cachedJs);
                            } else {
                                updateProgressUI(10, "Downloading JS Runner", "Starting transfer...");
                                xhrText(m.jsUrl,
                                    (js) => { writeCache(db, jsKey, js); cb(js); },
                                    (e)  => { state.engineLoadingInProgress = false; setEngineStatus("error", "JS download failed: " + e.message); },
                                    (pct, text) => updateProgressUI(Math.round(pct * 0.15), "Downloading JS Runner", text)
                                );
                            }
                        });
                    } else {
                        xhrText(m.jsUrl, cb,
                            (e) => { state.engineLoadingInProgress = false; setEngineStatus("error", "JS download failed: " + e.message); },
                            (pct, text) => updateProgressUI(Math.round(pct * 0.15), "Downloading JS Runner", text)
                        );
                    }
                };

                const getWasm = (jsCode, cb) => {
                    if (db) {
                        readCache(db, wasmKey, (_, cachedWasm) => {
                            if (cachedWasm) {
                                updateProgressUI(85, "Found in Local Storage", "Loading cached WASM...");
                                cb(jsCode, cachedWasm);
                            } else {
                                updateProgressUI(15, "Downloading WASM Neural Weights", "Connecting...");
                                xhrBinary(m.wasmUrl,
                                    (bytes) => {
                                        writeCache(db, wasmKey, bytes);
                                        updateProgressUI(90, "Saved WASM to IndexedDB", "Done");
                                        cb(jsCode, bytes);
                                    },
                                    (e) => { state.engineLoadingInProgress = false; setEngineStatus("error", "WASM failed: " + e.message); },
                                    (pct, text) => {
                                        const overallPct = 15 + Math.round(pct * 0.75);
                                        updateProgressUI(overallPct, "Downloading WASM Neural Weights", text);
                                    }
                                );
                            }
                        });
                    } else {
                        xhrBinary(m.wasmUrl,
                            (bytes) => cb(jsCode, bytes),
                            (e)     => { state.engineLoadingInProgress = false; setEngineStatus("error", e.message); },
                            (pct, text) => updateProgressUI(pct, "Downloading WASM Neural Weights", text)
                        );
                    }
                };

                getJs((jsCode) => {
                    if (!jsCode) return;
                    getWasm(jsCode, launch);
                });
            }
        });
    }

    function reinstallEngine() {
        if (state.localEngine) {
            try { state.localEngine.terminate(); } catch (e) {}
            state.localEngine = null;
        }
        state.engineLoadingInProgress = false;
        const m = getEngineById(settings.localModelId);
        setEngineStatus("loading", "Clearing cache...");
        openCache((dbErr, db) => {
            if (!db) { loadLocalEngine(); return; }
            deleteCache(db, m.cacheKey + "_js", () =>
                deleteCache(db, m.cacheKey + "_wasm", () =>
                    deleteCache(db, m.cacheKey + "_onnx", () =>
                        deleteCache(db, "maia3_js_bundle_v020_ort1220_r4", () =>
                            deleteCache(db, m.cacheKey, () => loadLocalEngine())
                        )
                    )
                )
            );
        });
    }

    function uninstallEngine() {
        if (state.localEngine) {
            try { state.localEngine.terminate(); } catch (e) {}
            state.localEngine = null;
        }
        state.engineLoadingInProgress = false;
        const m = getEngineById(settings.localModelId);
        openCache((dbErr, db) => {
            if (!db) { setEngineStatus("not_installed", ""); return; }
            deleteCache(db, m.cacheKey + "_js", () =>
                deleteCache(db, m.cacheKey + "_wasm", () =>
                    deleteCache(db, m.cacheKey + "_onnx", () =>
                        deleteCache(db, "maia3_js_bundle_v020_ort1220_r4", () =>
                            deleteCache(db, m.cacheKey, () =>
                                deleteCache(db, "sf18_05_wasm", () =>
                                    deleteCache(db, "sf18_05_js", () =>
                                        deleteCache(db, "sf18_05", () => {
                                            setEngineStatus("not_installed", "");
                                            updateLocalSettingsUI();
                                        })
                                    )
                                )
                            )
                        )
                    )
                )
            );
        });
        state.lastMoveResult = "Local engine uninstalled and storage cleared.";
        updateUI();
    }

    function triggerFallback() {
        if (settings.engineMode === 'local') return;
        state.isThinking = false;
        if (state.currentCloudRequest) {
            try { state.currentCloudRequest.abort(); } catch (_) {}
            state.currentCloudRequest = null;
        }
        const allowSwitch = Boolean(settings.autoFallback) &&
            settings.autoFallback !== "false" &&
            (!state.ui?.chkAutoFallback || state.ui.chkAutoFallback.checked);
        if (!allowSwitch) {
            state.pendingManualMove = false;
            state.lastMoveResult = formatMoveResult(getActiveModelTitle(), "API Error", "--");
            state.lastLiveResult = formatLiveResult("!", { text: "Cloud API Failed (Auto-Switch Off)", color: "#f85149" }, "", "Click Analyze Position to retry");
            updateUI();
            return;
        }
        settings.engineMode = 'local';
        saveSetting('engineMode', 'local');
        if (state.ui.segLocal) state.ui.segLocal.click();
        state.lastMoveResult = "⚠️ API fallback: switched to Local engine.";
        loadLocalEngine();
        if (state.lastSanitizedBoardFEN) analyzeLocal(state.lastSanitizedBoardFEN, settings.depth);
        updateUI();
    }

    // --- ANALYSIS ENGINE DISPATCH ---
    function analyze(depth = settings.depth, fenOverride = null, isRetry = false) {
        if (state.isThinking && !fenOverride && !isRetry) return;
        if (state.currentCloudRequest) {
            try { state.currentCloudRequest.abort(); } catch (_) {}
            state.currentCloudRequest = null;
        }
        let finalFEN = fenOverride || sanitizeFEN(getRawBoardFEN());
        if (!finalFEN) return;
        const isNewPos = finalFEN !== state.lastSentFEN;
        state.lastSentFEN = finalFEN;
        if (!fenOverride) state.lastSanitizedBoardFEN = finalFEN;
        if (isNewPos && !isRetry) {
            state.currentBestMove = null;
            state.pendingManualMove = false;
        }
        state.isThinking = true;
        state.analysisStartTime = performance.now();
        const minSec = Math.min(180, Math.max(0, parseFloat(settings.minDelay) || 0));
        const maxSec = Math.min(180, Math.max(minSec, parseFloat(settings.maxDelay) || 0));
        const minMs = minSec * 1000;
        const maxMs = maxSec * 1000;
        const delay = Math.random() * (maxMs - minMs) + minMs;
        state._chosenDelayMs = delay;
        state.moveTargetTime = performance.now() + delay;
        state.calculatedDelay = (delay / 1000).toFixed(2);
        updateUI();

        if (settings.engineMode === "cloud") analyzeCloud(finalFEN, depth, isRetry);
        else if (settings.engineMode === "sfonline") analyzeSFOnline(finalFEN, depth);
        else analyzeLocal(finalFEN, depth);
    }

    function prepareCloudHumanContext(fen, requestedDepth, maxApiDepth) {
        const game = getActiveGame();
        const clocks = (settings.autoTimeMgmt || settings.humanMode) ? getClockTimesMs(game, fen) : null;
        state.localStartClocks = clocks;
        state.localEval = null; state.localMate = null; state.localPV = null; state.localDepth = null;
        state.localMultiPV = {};

        const fParts = fen.split(" ");
        const fBoard = fParts[0] || "";
        const sideToMove = fParts[1] || "w";
        const fMoveNum = parseInt(fParts[5], 10) || 1;
        const fPly = (fMoveNum - 1) * 2 + (sideToMove === "b" ? 1 : 0);

        const myMs = clocks ? (sideToMove === "w" ? clocks.wMs : clocks.bMs) : 60000;
        const oppMs = clocks ? (sideToMove === "w" ? clocks.bMs : clocks.wMs) : 60000;
        const incMs = clocks ? clocks.incMs : 0;
        const effectiveMs = myMs + incMs * 16;

        const b64Now = fenToBoard64(fen);
        const oppRecapturedUs = !!(state.lastOurTo && state.oppLastTo && state.lastOurTo === state.oppLastTo);
        const ourKingIdx = b64Now ? b64Now.indexOf(sideToMove === "w" ? "K" : "k") : -1;
        const oppGaveCheck = ourKingIdx >= 0 && isAttackedBy(b64Now, ourKingIdx, sideToMove !== "w");

        let onPlannedLine = false;
        let plannedReply = null;
        let oppDeviated = false;
        let surpriseBase = 0;

        if (settings.humanMode && Array.isArray(state.plannedPV) && state.plannedPV.length >= 2 && state.oppLastUCI) {
            if (state.plannedPV[0].slice(0, 4) === state.oppLastUCI.slice(0, 4)) {
                onPlannedLine = true;
                plannedReply = state.plannedPV[1];
                state.plannedPV = state.plannedPV.slice(2);
            } else {
                oppDeviated = true;
                state.plannedPV = [];
                if (!oppRecapturedUs) {
                    surpriseBase += 0.45;
                    if (oppGaveCheck) surpriseBase += 0.30;
                }
            }
        } else if (settings.humanMode && fPly >= 8 && !oppRecapturedUs && oppGaveCheck) {
            surpriseBase += 0.35;
        }

        const wMap = { q: 4, r: 2, b: 1, n: 1 };
        let mSum = 0;
        for (const ch of fBoard) { const w = wMap[ch.toLowerCase()]; if (w) mSum += w; }
        const matPhase = 1 - Math.min(24, mSum) / 24;
        const openingFactor = Math.exp(-Math.pow(fPly / 8, 2));

        if (!state.attentionMap || state.attentionMap.length !== 64) state.attentionMap = new Array(64).fill(0);
        for (let i = 0; i < 64; i++) state.attentionMap[i] *= 0.62;
        const spikeHeat = (sq, amt) => {
            if (!sq || sq.length < 2) return;
            const sf = sq.charCodeAt(0) - 97, sr = 8 - parseInt(sq[1], 10);
            for (let dr = -2; dr <= 2; dr++) for (let df = -2; df <= 2; df++) {
                const rr = sr + dr, ff = sf + df;
                if (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                    const dist = Math.abs(dr) + Math.abs(df);
                    state.attentionMap[rr * 8 + ff] = Math.min(2.5, state.attentionMap[rr * 8 + ff] + amt / (1 + dist));
                }
            }
        };
        spikeHeat(state.oppLastTo, 1.2);
        spikeHeat(state.lastOurTo, 0.7);
        state.plannedStreak = onPlannedLine ? (state.plannedStreak || 0) + 1 : 0;

        const paceMs = Math.min(1050, Math.max(180, Math.pow(Math.max(1000, effectiveMs) / 1000, 0.60) * 38));
        const scrambleDrop = effectiveMs < 15000 ? Math.round((15000 - effectiveMs) / 3800) : 0;
        const legalLen = typeof game?.getLegalMoves === "function" ? game.getLegalMoves().length : 20;
        const preset = HUMAN_PRESETS[settings.humanPreset] || HUMAN_PRESETS.master;
        const depthAdj = settings.humanMode ? preset.minDepthAdj : 0;

        let actualDepth = Math.min(requestedDepth, maxApiDepth);
        if (settings.autoTimeMgmt && clocks) {
            if (settings.humanMode) {
                const rawCloudD = onPlannedLine
                    ? Math.round(10 + 2 * matPhase + Math.max(0, depthAdj - 1) - scrambleDrop)
                    : Math.round(13 - 2 * openingFactor + 3 * Math.pow(matPhase, 1.2) - scrambleDrop + depthAdj);
                actualDepth = Math.max(Math.min(7, maxApiDepth), Math.min(maxApiDepth, rawCloudD));
            } else {
                const rawMaxD = Math.round(16 - 2 * scrambleDrop + 2 * matPhase);
                actualDepth = Math.max(Math.min(8, maxApiDepth), Math.min(maxApiDepth, rawMaxD));
            }
        }

        const maxPVForPreset = (settings.humanPreset === "hikaru" || settings.humanPreset === "gm" || settings.humanPreset === "stealth") ? 3 : 5;
        const isFastBookOrForced = (fPly <= 2) || legalLen <= 2;
        const needFocusMulti = !settings.humanMode && (settings.showMultiBest || (settings.engineFocus && settings.engineFocus !== "balanced"));
        const wantMultiPV = (!settings.humanMode && !needFocusMulti) || isFastBookOrForced
            ? 1
            : (!settings.humanMode ? 3 : (!settings.autoTimeMgmt ? Math.min(3, maxPVForPreset) : (myMs > 14000 ? maxPVForPreset : (myMs > 9000 ? Math.min(3, maxPVForPreset) : 1))));
        const finalMultiPV = Math.min(wantMultiPV, Math.max(1, legalLen));
        const boardGeom = analyzeBoardGeometry(b64Now, sideToMove);

        state.searchTrace = {
            phase: "deep",
            fen,
            expectedMultiPV: finalMultiPV,
            paceMs,
            openingFactor,
            matPhase,
            ply: fPly,
            legalCount: legalLen,
            b64: b64Now,
            side: sideToMove,
            myMs,
            oppMs,
            incMs,
            oppThinkMs: state.oppLastThinkMs ?? null,
            boardGeom,
            onPlannedLine,
            plannedReply,
            oppDeviated,
            oppRecapturedUs,
            oppGaveCheck,
            surpriseBase,
            isTank: false,
            movesByDepth: {},
            evalByDepth: {},
            seldepthByDepth: {},
            nodesByDepth: {},
            wdlByDepth: {},
            snapshotsByDepth: {},
            volatilityIntegral: 0,
            flipCount: 0,
            lastFlipDepth: 0,
            maxEvalSwing: 0,
            lastCompletedDepth: 0,
            tier: null
        };

        return { actualDepth, wantMultiPV: finalMultiPV, clocks, game };
    }

    function parseCloudResultToPVEntry(item, sideToMove) {
        if (!item) return null;
        const mv = item.move || item.bestmove || item.lan;
        if (!mv) return null;
        const dNum = parseInt(item.depth, 10) || 12;
        const dbg = typeof item.debug === "string" ? item.debug : "";
        const selM = dbg.match(/\bseldepth (\d+)/);
        const nodesM = dbg.match(/\bnodes (\d+)/);
        const mpvM = dbg.match(/\bmultipv (\d+)/);
        const pvM = dbg.match(/\bpv (.*)/);

        const selD = selM ? parseInt(selM[1], 10) : dNum;
        const nodesVal = nodesM ? parseInt(nodesM[1], 10) : null;
        const mpvIdx = mpvM ? parseInt(mpvM[1], 10) : null;

        let pvStr = pvM ? pvM[1].trim() : "";
        const contArr = Array.isArray(item.continuationArr) ? item.continuationArr : [];
        if (!pvStr) {
            const fullArr = (contArr[0] === mv) ? contArr : [mv, ...contArr];
            pvStr = fullArr.join(" ");
        }

        const mateRaw = (item.mate !== null && item.mate !== undefined && item.mate !== "" && parseInt(item.mate, 10) !== 0)
            ? parseInt(item.mate, 10) : null;
        let type = "cp", whiteVal = 0, rawVal = 0, cpMover = 0;
        if (mateRaw !== null && !Number.isNaN(mateRaw)) {
            type = "mate";
            whiteVal = mateRaw;
            rawVal = (sideToMove === "b") ? -mateRaw : mateRaw;
            cpMover = rawVal > 0 ? (30000 - rawVal * 100) : (-30000 - rawVal * 100);
        } else {
            const cpWhite = (item.centipawns !== undefined && item.centipawns !== null && !Number.isNaN(parseInt(item.centipawns, 10)))
                ? parseInt(item.centipawns, 10)
                : Math.round((parseFloat(item.eval) || 0) * 100);
            whiteVal = cpWhite;
            rawVal = (sideToMove === "b") ? -cpWhite : cpWhite;
            cpMover = rawVal;
        }

        return {
            mpvIdx,
            entry: {
                depth: dNum,
                seldepth: selD,
                type,
                rawVal,
                whiteVal,
                cpMover,
                wdl: null,
                nodes: nodesVal,
                pv: pvStr,
                move: mv,
                evalPawns: item.eval,
                mate: mateRaw,
                continuationArr: contArr,
                winChance: item.winChance
            }
        };
    }

    function finalizeCloudHumanMove(fallbackObj, sentFEN, depth, duration) {
        if (sentFEN && sentFEN !== state.lastSentFEN) return;
        state.isThinking = false;
        const mpv = state.localMultiPV || {};
        const pv1 = mpv[1] || fallbackObj;
        let chosenMove = pv1?.move;
        let chosenEval = pv1?.evalPawns ?? (pv1 ? (pv1.whiteVal / 100).toFixed(2) : 0);
        let chosenMate = pv1?.mate ?? null;
        let chosenPV = pv1?.continuationArr?.length ? pv1.continuationArr : (pv1?.pv ? pv1.pv.split(" ") : null);
        let chosenWin = pv1?.winChance ?? null;
        let chosenDepth = pv1?.depth || depth;

        if (settings.humanMode && chosenMove) {
            const tr = state.searchTrace;
            if (tr && !tr.tier) {
                tr.tier = tr.onPlannedLine ? "settled_early" : (tr.flipCount > 0 ? "volatile" : "deliberate");
            }
            const decision = computeHumanGradientDecision(chosenMove, mpv, sentFEN, state.localStartClocks);
            chosenMove = decision.move;
            if (decision.pvObj) {
                chosenMate = decision.pvObj.type === "mate" ? decision.pvObj.whiteVal : null;
                chosenEval = decision.pvObj.type === "mate" ? null : (decision.pvObj.whiteVal / 100).toFixed(2);
                chosenWin = decision.pvObj.winChance ?? chosenWin;
                if (decision.pvObj.continuationArr?.length) chosenPV = decision.pvObj.continuationArr;
                else if (decision.pvObj.pv) chosenPV = decision.pvObj.pv.split(" ");
                chosenDepth = decision.pvObj.depth || chosenDepth;
            }
            state.moveTargetTime = state.analysisStartTime + decision.targetTotalMs;
            const remWait = Math.max(0, state.moveTargetTime - performance.now());
            state.calculatedDelay = (remWait / 1000).toFixed(2);
        } else if (!settings.humanMode && chosenMove && settings.engineFocus && settings.engineFocus !== "balanced") {
            const pickedFocus = pickFocusMove(chosenMove, mpv, sentFEN);
            if (pickedFocus && pickedFocus.move) {
                chosenMove = pickedFocus.move;
                chosenMate = pickedFocus.type === "mate" ? pickedFocus.whiteVal : null;
                chosenEval = pickedFocus.type === "mate" ? null : (pickedFocus.whiteVal / 100).toFixed(2);
                chosenWin = pickedFocus.winChance ?? chosenWin;
                if (pickedFocus.continuationArr?.length) chosenPV = pickedFocus.continuationArr;
                else if (pickedFocus.pv) chosenPV = pickedFocus.pv.split(" ");
            }
        }
        state.lastCandidates = buildCandidatesFromMultiPV(mpv, sentFEN);

        processBestMove(chosenMove, chosenEval, chosenMate, chosenPV, chosenWin, duration, chosenDepth, true);
        updateUI();
    }

    function analyzeCloud(finalFEN, depth, isRetry) {
        const ctx = prepareCloudHumanContext(finalFEN, depth, 18);
        const actualDepth = ctx.actualDepth;
        const wantMultiPV = ctx.wantMultiPV;

        state.lastLiveResult = formatLiveResult("...", { text: isRetry ? "Retrying FEN..." : "Cloud Analyzing...", color: "#58a6ff" }, "", "Waiting for API...");
        updateUI();

        if (wantMultiPV > 1 && !state._cloudWsBlocked && typeof WebSocket !== "undefined") {
            analyzeCloudWS(finalFEN, actualDepth, wantMultiPV, isRetry);
        } else {
            analyzeCloudPost(finalFEN, actualDepth, wantMultiPV, isRetry);
        }
    }

    function analyzeCloudWS(finalFEN, actualDepth, wantMultiPV, isRetry) {
        let ws = null;
        let settled = false;
        let gotBestmove = false;
        let connTimer = null;
        let settleTimer = null;
        let totalTimer = null;
        const sideToMove = (finalFEN.split(" ")[1] || "w");
        const taskId = Math.random().toString(36).substring(7);
        const byDepthMoveMap = {};

        const cleanup = () => {
            if (connTimer) { clearTimeout(connTimer); connTimer = null; }
            if (settleTimer) { clearTimeout(settleTimer); settleTimer = null; }
            if (totalTimer) { clearTimeout(totalTimer); totalTimer = null; }
            if (ws) {
                ws.onopen = ws.onmessage = ws.onerror = ws.onclose = null;
                try { if (ws.readyState === 0 || ws.readyState === 1) ws.close(); } catch (_) {}
                ws = null;
            }
        };

        const finishWS = () => {
            if (settled) return;
            settled = true;
            cleanup();
            const byMove = new Map();
            for (const p of Object.values(state.localMultiPV)) {
                if (!p || !p.move) continue;
                const prev = byMove.get(p.move);
                if (!prev || p.depth >= prev.depth) byMove.set(p.move, p);
            }
            const pvList = Array.from(byMove.values()).sort((a, b) => b.cpMover - a.cpMover);
            state.localMultiPV = {};
            pvList.forEach((p, idx) => { state.localMultiPV[idx + 1] = p; });
            const dur = ((performance.now() - state.analysisStartTime) / 1000).toFixed(2);
            finalizeCloudHumanMove(state.localMultiPV[1], finalFEN, actualDepth, dur);
        };

        const fallbackToPost = (markBlocked) => {
            if (settled) return;
            settled = true;
            cleanup();
            if (markBlocked) state._cloudWsBlocked = true;
            if (finalFEN !== state.lastSentFEN || settings.engineMode !== "cloud") return;
            analyzeCloudPost(finalFEN, actualDepth, wantMultiPV, isRetry);
        };

        state.currentCloudRequest = { abort: () => { settled = true; cleanup(); } };

        try {
            ws = new WebSocket("wss://chess-api.com/v1");
        } catch (_) {
            fallbackToPost(true);
            return;
        }

        connTimer = setTimeout(() => fallbackToPost(true), 2200);
        totalTimer = setTimeout(() => {
            if (settled) return;
            if (state.localMultiPV?.[1]?.move) finishWS();
            else fallbackToPost(false);
        }, 10000);

        ws.onopen = () => {
            if (settled) return;
            if (connTimer) { clearTimeout(connTimer); connTimer = null; }
            const payload = {
                fen: finalFEN,
                depth: actualDepth,
                variants: wantMultiPV,
                maxThinkingTime: settings.maxThinkingTime > 0 ? Math.min(settings.maxThinkingTime, 100) : 90,
                taskId
            };
            if (settings.searchMoves.trim()) payload.searchmoves = settings.searchMoves.trim();
            ws.send(JSON.stringify(payload));
        };

        ws.onmessage = (ev) => {
            if (settled || finalFEN !== state.lastSentFEN || settings.engineMode !== "cloud") return;
            let data;
            try { data = JSON.parse(ev.data); } catch (_) { return; }
            if (!data || data.error || data.status === "error") {
                const errText = data?.error || data?.message || "";
                if (errText.includes("HIGH_USAGE")) { settled = true; cleanup(); triggerFallback(); return; }
                fallbackToPost(false);
                return;
            }
            if (data.type === "info") return;
            const parsed = parseCloudResultToPVEntry(data, sideToMove);
            if (!parsed) return;

            const { mpvIdx, entry } = parsed;
            const dNum = entry.depth;
            if (!byDepthMoveMap[dNum]) byDepthMoveMap[dNum] = [];
            let rank = mpvIdx;
            if (!rank) {
                const existingIdx = byDepthMoveMap[dNum].findIndex(m => m === entry.move);
                if (existingIdx !== -1) rank = existingIdx + 1;
                else {
                    byDepthMoveMap[dNum].push(entry.move);
                    rank = byDepthMoveMap[dNum].length;
                }
            }
            if (rank <= wantMultiPV) state.localMultiPV[rank] = entry;

            const tr = state.searchTrace;
            if (tr) {
                if (!tr.snapshotsByDepth[dNum]) tr.snapshotsByDepth[dNum] = {};
                tr.snapshotsByDepth[dNum][rank] = entry;
                if (rank === 1) {
                    let prevMove = null;
                    for (let k = dNum - 1; k >= 1; k--) {
                        if (tr.movesByDepth[k]) { prevMove = tr.movesByDepth[k]; break; }
                    }
                    if (prevMove && prevMove !== entry.move) {
                        tr.flipCount++;
                        tr.lastFlipDepth = dNum;
                    }
                    const prevEval = tr.evalByDepth[dNum - 1];
                    const evalDelta = (typeof prevEval === "number") ? Math.abs(entry.cpMover - prevEval) : 0;
                    const flipAdd = (prevMove && prevMove !== entry.move) ? 35 : 0;
                    tr.volatilityIntegral = (tr.volatilityIntegral || 0) + dNum * (flipAdd + Math.min(200, evalDelta)) * 0.08;
                    tr.movesByDepth[dNum] = entry.move;
                    tr.evalByDepth[dNum] = entry.cpMover;
                    tr.seldepthByDepth[dNum] = entry.seldepth;
                    if (entry.nodes !== null) tr.nodesByDepth[dNum] = entry.nodes;
                    tr.lastCompletedDepth = dNum;
                    const refEval = tr.evalByDepth[Math.max(1, dNum - 3)];
                    if (typeof refEval === "number") {
                        tr.maxEvalSwing = Math.max(tr.maxEvalSwing, Math.abs(entry.cpMover - refEval));
                    }
                }
            }

            if (data.type === "bestmove") {
                gotBestmove = true;
                finishWS();
            } else if (dNum >= actualDepth && Object.keys(state.localMultiPV).length >= wantMultiPV && !settleTimer) {
                settleTimer = setTimeout(() => { if (!settled) { gotBestmove = true; finishWS(); } }, 250);
            }
        };

        ws.onerror = () => {
            if (!gotBestmove) fallbackToPost(true);
        };
        ws.onclose = () => {
            if (!settled && !gotBestmove) {
                if (state.localMultiPV?.[1]?.move) finishWS();
                else fallbackToPost(true);
            }
        };
    }

    function analyzeCloudPost(finalFEN, actualDepth, wantMultiPV, isRetry) {
        let aborted = false;
        let activeReq = null;
        state.currentCloudRequest = {
            abort: () => {
                aborted = true;
                try { activeReq?.abort(); } catch (_) {}
            }
        };

        const payload = {
            fen: finalFEN,
            depth: actualDepth,
            maxThinkingTime: (settings.humanMode && wantMultiPV > 1)
                ? (settings.maxThinkingTime > 0 ? Math.min(settings.maxThinkingTime, 100) : 80)
                : Math.min(settings.maxThinkingTime, CONFIG.API.MAX_TIME),
            taskId: Math.random().toString(36).substring(7),
        };
        if (wantMultiPV > 1) payload.variants = wantMultiPV;
        if (settings.searchMoves.trim()) payload.searchmoves = settings.searchMoves.trim();

        activeReq = GM_xmlhttpRequest({
            method: "POST", url: "https://chess-api.com/v1",
            headers: { "Content-Type": "application/json" },
            data: JSON.stringify(payload), timeout: 15000,
            onload: (res) => {
                if (!aborted) handleCloudResponse(res, finalFEN, actualDepth, isRetry, wantMultiPV, () => aborted, (r) => { activeReq = r; });
            },
            onerror: (err) => { if (!aborted) { handleError("Network Error", err); triggerFallback(); } },
            ontimeout: () => { if (!aborted) { handleError("Timeout (15s)"); triggerFallback(); } },
        });
    }

    function analyzeSFOnline(finalFEN, depth) {
        const ctx = prepareCloudHumanContext(finalFEN, depth, 15);
        const actualDepth = ctx.actualDepth;
        const url = `https://stockfish.online/api/s/v2.php?fen=${encodeURIComponent(finalFEN)}&depth=${actualDepth}&mode=bestmove`;
        state.lastLiveResult = formatLiveResult("...", { text: "Online Analyzing...", color: "#58a6ff" }, "", "Waiting for API...");
        updateUI();

        state.currentCloudRequest = GM_xmlhttpRequest({
            method: "GET", url, timeout: 20000,
            onload: (res) => handleSFOnlineResponse(res, actualDepth, finalFEN),
            onerror: (err) => { handleError("Network Error (SF Online)", err); triggerFallback(); },
            ontimeout: () => { handleError("Timeout (SF Online 20s)"); triggerFallback(); },
        });
    }

    function handleSFOnlineResponse(response, depth, sentFEN) {
        if (sentFEN && sentFEN !== state.lastSentFEN) return;
        if (settings.engineMode !== "sfonline") return;
        try {
            if (response.status !== 200) throw new Error(`HTTP ${response.status}`);
            const data = JSON.parse(response.responseText);
            if (!data.success || !data.bestmove) { state.isThinking = false; triggerFallback(); return; }
            const bestMove = data.bestmove.split(" ")[1] || data.bestmove;
            const duration = ((performance.now() - state.analysisStartTime) / 1000).toFixed(2);
            const sideToMove = (sentFEN.split(" ")[1] || "w");
            const contArr = data.continuation ? data.continuation.split(" ") : [];
            const parsed = parseCloudResultToPVEntry({
                move: bestMove,
                eval: data.evaluation,
                mate: data.mate,
                depth,
                continuationArr: contArr
            }, sideToMove);

            if (settings.humanMode && parsed) {
                state.localMultiPV = { 1: parsed.entry };
                finalizeCloudHumanMove(parsed.entry, sentFEN, depth, duration);
                return;
            }
            state.isThinking = false;
            processBestMove(bestMove, data.evaluation, data.mate, contArr.length ? contArr : null, null, duration, depth, true);
        } catch (e) { state.isThinking = false; triggerFallback(); }
        updateUI();
    }

    function handleCloudResponse(response, sentFEN, depth, isRetry, wantMultiPV = 1, isAborted = () => false, setActiveReq = () => {}) {
        if (isAborted() || (sentFEN && sentFEN !== state.lastSentFEN) || settings.engineMode !== "cloud") return;
        if (response.responseText.includes("HIGH_USAGE") || response.status === 429) { state.isThinking = false; triggerFallback(); return; }
        try {
            if (response.status !== 200) throw new Error(`HTTP ${response.status}`);
            const rawData = JSON.parse(response.responseText);
            const items = Array.isArray(rawData) ? rawData : [rawData];
            const result = items[0];
            if (!result || result.error || result.status === "error") {
                const errText = result?.error || result?.message || "Unknown Error";
                if (errText.includes("HIGH_USAGE")) { state.isThinking = false; triggerFallback(); return; }
                if ((errText.includes("FEN") || errText.includes("VALIDATION")) && !isRetry) {
                    const parts = sentFEN.split(" ");
                    if (parts.length >= 4 && parts[3] !== "-") { parts[3] = "-"; state.isThinking = false; analyze(depth, parts.join(" "), true); return; }
                }
                state.isThinking = false; triggerFallback(); return;
            }
            if (!(result.move || result.bestmove)) { state.isThinking = false; triggerFallback(); return; }

            const sideToMove = (sentFEN.split(" ")[1] || "w");
            const pvEntries = items.map(it => parseCloudResultToPVEntry(it, sideToMove)?.entry).filter(Boolean);
            pvEntries.sort((a, b) => b.cpMover - a.cpMover);
            state.localMultiPV = {};
            pvEntries.forEach((p, idx) => { state.localMultiPV[idx + 1] = p; });

            if (!settings.humanMode && wantMultiPV <= 1) {
                state.isThinking = false;
                state.lastCandidates = buildCandidatesFromMultiPV(state.localMultiPV, sentFEN);
                const duration = ((performance.now() - state.analysisStartTime) / 1000).toFixed(2);
                processBestMove(result.move || result.bestmove, result.eval, result.mate, result.continuationArr, result.winChance, duration, depth, true);
                updateUI();
                return;
            }

            const finishPost = () => {
                if (isAborted() || sentFEN !== state.lastSentFEN || settings.engineMode !== "cloud") return;
                const dur = ((performance.now() - state.analysisStartTime) / 1000).toFixed(2);
                finalizeCloudHumanMove(state.localMultiPV[1] || pvEntries[0], sentFEN, depth, dur);
            };

            if (Object.keys(state.localMultiPV).length < 2 && wantMultiPV > 1 && !settings.searchMoves.trim()) {
                const game = getActiveGame();
                const legalUci = typeof game?.getLegalMoves === "function"
                    ? [...new Set(game.getLegalMoves().map(m => m.from + m.to + (m.promotion || "")))]
                    : [];
                const fetchNextAlt = (rankIdx) => {
                    if (isAborted() || sentFEN !== state.lastSentFEN || settings.engineMode !== "cloud") return;
                    const taken = new Set(Object.values(state.localMultiPV).map(p => p.move));
                    const remaining = legalUci.filter(u => !taken.has(u));
                    if (!remaining.length || rankIdx > Math.min(3, wantMultiPV)) { finishPost(); return; }
                    const altPayload = {
                        fen: sentFEN,
                        depth: Math.min(depth, 12),
                        maxThinkingTime: 50,
                        searchmoves: remaining.slice(0, 26).join(" "),
                        taskId: Math.random().toString(36).substring(7)
                    };
                    const req = GM_xmlhttpRequest({
                        method: "POST", url: "https://chess-api.com/v1",
                        headers: { "Content-Type": "application/json" },
                        data: JSON.stringify(altPayload), timeout: 3500,
                        onload: (r2) => {
                            try {
                                const j2 = JSON.parse(r2.responseText);
                                const it2 = Array.isArray(j2) ? j2[0] : j2;
                                const p2 = parseCloudResultToPVEntry(it2, sideToMove)?.entry;
                                if (p2 && !taken.has(p2.move)) state.localMultiPV[rankIdx] = p2;
                            } catch (_) {}
                            fetchNextAlt(rankIdx + 1);
                        },
                        onerror: () => finishPost(),
                        ontimeout: () => finishPost()
                    });
                    setActiveReq(req);
                };
                fetchNextAlt(2);
            } else {
                finishPost();
            }
        } catch (e) { state.isThinking = false; triggerFallback(); }
        updateUI();
    }

    function parseClockStrMs(txt) {
        if (!txt) return null;
        const clean = String(txt).replace(/\s+/g, "");
        const m = clean.match(/^(?:(\d+):)?(\d{1,2}):(\d{2}(?:\.\d+)?)$/);
        if (m) {
            const hrs = m[1] ? parseInt(m[1], 10) : 0;
            const mins = parseInt(m[2], 10);
            const secs = parseFloat(m[3]);
            return Math.max(100, Math.round((hrs * 3600 + mins * 60 + secs) * 1000));
        }
        if (/^\d{1,2}\.\d$/.test(clean)) {
            return Math.max(100, Math.round(parseFloat(clean) * 1000));
        }
        return null;
    }

    function readRawClocks(game) {
        let wMs = null, bMs = null, metaIncMs = null;
        if (isCgSite()) {
            const init = getCgInitData();
            if (location.pathname === _cgCache.pathAtLoad && typeof init?.data?.clock?.increment === "number") {
                metaIncMs = Math.max(0, Math.round(init.data.clock.increment * 1000));
            }
            const wEl = document.querySelector(".rclock-white .time");
            const bEl = document.querySelector(".rclock-black .time");
            if (wEl) wMs = parseClockStrMs(wEl.textContent);
            if (bEl) bMs = parseClockStrMs(bEl.textContent);
            if ((wMs === null || bMs === null) && _wsState.liveClock) {
                wMs = _wsState.liveClock.wMs;
                bMs = _wsState.liveClock.bMs;
            }
            return (wMs !== null && bMs !== null) ? { wMs, bMs, metaIncMs } : null;
        }

        try {
            if (game?.clocks) {
                const c = game.clocks;
                if (typeof c[1] === "number" && typeof c[2] === "number") { wMs = c[1]; bMs = c[2]; }
                else if (typeof c.white === "number" && typeof c.black === "number") { wMs = c.white; bMs = c.black; }
            }
            const tc = game?.getTimeControl?.() || game?.timeControl;
            if (tc && typeof tc === "object") {
                const rawInc = tc.increment ?? tc.incrementSeconds ?? tc.inc;
                if (typeof rawInc === "number") metaIncMs = Math.max(0, Math.round(rawInc * 1000));
                else if (typeof tc.timeIncrement === "number") metaIncMs = Math.max(0, Math.round(tc.timeIncrement));
            } else if (typeof tc === "string" && tc.includes("+")) {
                const p = parseInt(tc.split("+")[1], 10);
                if (!Number.isNaN(p)) metaIncMs = Math.max(0, p * 1000);
            }
        } catch (_) {}

        if (wMs === null || bMs === null) {
            const wEl = document.querySelector(".clock-white .clock-time-monospace, .clock-white, [data-cy='clock-white']");
            const bEl = document.querySelector(".clock-black .clock-time-monospace, .clock-black, [data-cy='clock-black']");
            if (wEl) wMs = parseClockStrMs(wEl.textContent);
            if (bEl) bMs = parseClockStrMs(bEl.textContent);
        }

        if (wMs === null || bMs === null) {
            const clocks = Array.from(document.querySelectorAll(".clock-component .clock-time-monospace, .clock-component, .clock-time-monospace"))
                .filter(el => el.offsetParent !== null && parseClockStrMs(el.textContent) !== null);
            if (clocks.length >= 2) {
                clocks.sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top);
                const topMs = parseClockStrMs(clocks[0].textContent);
                const botMs = parseClockStrMs(clocks[clocks.length - 1].textContent);
                if (topMs !== null && botMs !== null) {
                    const playingBlack = (state.playingAs === 2);
                    wMs = playingBlack ? botMs : topMs;
                    bMs = playingBlack ? topMs : botMs;
                }
            }
        }

        return (wMs !== null && bMs !== null) ? { wMs, bMs, metaIncMs } : null;
    }

    function getClockTimesMs(game, fen) {
        const raw = readRawClocks(game);
        if (!raw) return null;
        const { wMs, bMs, metaIncMs } = raw;

        const parts = fen ? fen.split(" ") : [];
        const side = parts[1] || "w";
        const moveNum = parseInt(parts[5], 10) || 1;
        const ply = (moveNum - 1) * 2 + (side === "b" ? 1 : 0);

        if (ply === 0) {
            state._detectedIncMs = 0;
            state._prevClockW = wMs;
            state._prevClockB = bMs;
            state._prevClockPly = 0;
        } else {
            if (metaIncMs === null && state._prevClockPly !== undefined && ply > state._prevClockPly) {
                const jumpW = (state._prevClockW !== null && wMs > state._prevClockW) ? (wMs - state._prevClockW) : 0;
                const jumpB = (state._prevClockB !== null && bMs > state._prevClockB) ? (bMs - state._prevClockB) : 0;
                const jump = Math.max(jumpW, jumpB);
                if (jump > 0 && jump <= 30000) {
                    const snapped = Math.max(1000, Math.round(jump / 1000) * 1000);
                    state._detectedIncMs = Math.max(state._detectedIncMs || 0, snapped);
                }
            }
            state._prevClockW = wMs;
            state._prevClockB = bMs;
            state._prevClockPly = ply;
        }

        return { wMs, bMs, incMs: metaIncMs !== null ? metaIncMs : (state._detectedIncMs || 0) };
    }

    function fmtClockMs(ms) {
        const s = ms / 1000;
        const m = Math.floor(s / 60);
        const rem = (s % 60).toFixed(s < 10 ? 1 : 0).padStart(s < 10 ? 4 : 2, "0");
        return `${m}:${rem}`;
    }

    function analyzeLocal(fen, depth) {
        if (!state.localEngine || state.engineStatus !== "ready") {
            state.pendingFen = fen;
            state.pendingDepth = depth;
            if (!state.localEngine && !state.engineLoadingInProgress) loadLocalEngine();
            return;
        }
        if (state.graderSearching && state.graderEngine && !state.graderStopSent) {
            const yieldedFen = state.graderActiveFen;
            state.graderAborted = true;
            state.graderStopSent = true;
            try { state.graderEngine.postMessage("stop"); } catch (_) {}
            if (yieldedFen && !state.gradeSnapshots[yieldedFen]) enqueueGraderFen(yieldedFen, true);
        }
        const m = getEngineById(settings.localModelId);
        if (m.format === "onnx") {
            const ctx = prepareCloudHumanContext(fen, 1, 1);
            const reqId = (state._maiaReqId = (state._maiaReqId || 0) + 1);
            const priorFens = Array.isArray(state.fenHistory)
                ? state.fenHistory.filter(f => f && f !== fen).slice(-7)
                : [];
            const elo = Math.min(2600, Math.max(600, Number(settings.localMaiaElo) || 1500));
            state._maiaSentFen = fen;
            state._maiaClocks = ctx.clocks;
            state.lastLiveResult = formatLiveResult("...", { text: `Maia-3 (${elo}) Thinking...`, color: "#58a6ff" }, "", "Running neural forward pass...");
            updateUI();
            state.localEngine.postMessage({
                type: "predict",
                reqId,
                fen,
                priorFens,
                selfElo: elo,
                oppoElo: elo
            });
            return;
        }
        state.localEval = null; state.localMate = null; state.localPV = null; state.localDepth = null;
        state.localMultiPV = {};
        state.searchTrace = {
            movesByDepth: {},
            evalByDepth: {},
            seldepthByDepth: {},
            nodesByDepth: {},
            wdlByDepth: {},
            snapshotsByDepth: {},
            volatilityIntegral: 0,
            flipCount: 0,
            lastFlipDepth: 0,
            maxEvalSwing: 0,
            lastCompletedDepth: 0,
            stopSent: false,
            tier: null
        };
        const actualDepth = Math.min(depth, m.maxDepth);
        const cmds = [];
        if (state.isLocalSearching) {
            cmds.push("stop");
            state.ignoreLocalBestMoves = (state.ignoreLocalBestMoves || 0) + 1;
        }
        state.isLocalSearching = true;

        const game = getActiveGame();
        const clocks = (settings.autoTimeMgmt || settings.humanMode) ? getClockTimesMs(game, fen) : null;
        state.localStartClocks = clocks;

        const fParts = fen.split(" ");
        const fBoard = fParts[0] || "";
        const sideToMove = fParts[1] || "w";
        const fMoveNum = parseInt(fParts[5], 10) || 1;
        const fPly = (fMoveNum - 1) * 2 + (sideToMove === "b" ? 1 : 0);

        const myMs = clocks ? (sideToMove === "w" ? clocks.wMs : clocks.bMs) : 60000;
        const oppMs = clocks ? (sideToMove === "w" ? clocks.bMs : clocks.wMs) : 60000;
        const incMs = clocks ? clocks.incMs : 0;
        const effectiveMs = myMs + incMs * 16;

        // Check if opponent walked into our calculated PV line or surprised us
        let onPlannedLine = false;
        let plannedReply = null;
        let oppDeviated = false;
        let surpriseBase = 0;
        const b64Now = fenToBoard64(fen);
        const oppRecapturedUs = !!(state.lastOurTo && state.oppLastTo && state.lastOurTo === state.oppLastTo);
        const ourKingIdx = b64Now ? b64Now.indexOf(sideToMove === "w" ? "K" : "k") : -1;
        const oppGaveCheck = ourKingIdx >= 0 && isAttackedBy(b64Now, ourKingIdx, sideToMove !== "w");

        if (settings.humanMode && Array.isArray(state.plannedPV) && state.plannedPV.length >= 2 && state.oppLastUCI) {
            if (state.plannedPV[0].slice(0, 4) === state.oppLastUCI.slice(0, 4)) {
                onPlannedLine = true;
                plannedReply = state.plannedPV[1];
                state.plannedPV = state.plannedPV.slice(2);
            } else {
                oppDeviated = true;
                state.plannedPV = [];
                if (!oppRecapturedUs) {
                    surpriseBase += 0.45;
                    if (oppGaveCheck) surpriseBase += 0.30;
                }
            }
        } else if (settings.humanMode && fPly >= 8 && !oppRecapturedUs && oppGaveCheck) {
            surpriseBase += 0.35;
        }

        const wMap = { q: 4, r: 2, b: 1, n: 1 };
        let mSum = 0;
        for (const ch of fBoard) { const w = wMap[ch.toLowerCase()]; if (w) mSum += w; }
        const matPhase = 1 - Math.min(24, mSum) / 24;
        const isEndgame = matPhase >= 0.72;
        const openingFactor = Math.exp(-Math.pow(fPly / 8, 2));
        // Update 2D Spatial Attention Heatmap (64 squares)
        if (!state.attentionMap || state.attentionMap.length !== 64) state.attentionMap = new Array(64).fill(0);
        for (let i = 0; i < 64; i++) state.attentionMap[i] *= 0.62;
        const spikeHeat = (sq, amt) => {
            if (!sq || sq.length < 2) return;
            const sf = sq.charCodeAt(0) - 97, sr = 8 - parseInt(sq[1], 10);
            for (let dr = -2; dr <= 2; dr++) for (let df = -2; df <= 2; df++) {
                const rr = sr + dr, ff = sf + df;
                if (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                    const dist = Math.abs(dr) + Math.abs(df);
                    state.attentionMap[rr * 8 + ff] = Math.min(2.5, state.attentionMap[rr * 8 + ff] + amt / (1 + dist));
                }
            }
        };
        spikeHeat(state.oppLastTo, 1.2);
        spikeHeat(state.lastOurTo, 0.7);
        state.plannedStreak = onPlannedLine ? (state.plannedStreak || 0) + 1 : 0;

        const paceMs = Math.min(1050, Math.max(180, Math.pow(Math.max(1000, effectiveMs) / 1000, 0.60) * 38));
        const scrambleDrop = effectiveMs < 15000 ? Math.round((15000 - effectiveMs) / 3800) : 0;
        const legalLen = typeof game?.getLegalMoves === "function" ? game.getLegalMoves().length : 20;

        const preset = HUMAN_PRESETS[settings.humanPreset] || HUMAN_PRESETS.master;
        const depthAdj = settings.humanMode ? preset.minDepthAdj : 0;

        const midCeiling = matPhase >= 0.50 ? 20 : 18;
        const tankMaxD = settings.humanMode
            ? Math.min(actualDepth, isEndgame ? 23 : midCeiling)
            : Math.min(actualDepth, isEndgame ? 24 : 20);
        const quickStopD = Math.max(8, Math.min(14, 9 + Math.round(matPhase * 2) + Math.max(0, depthAdj) - (scrambleDrop > 0 ? 1 : 0)));
        const rawBaseD = onPlannedLine
            ? Math.round(10 + 2 * matPhase + Math.max(0, depthAdj - 1) - scrambleDrop)
            : Math.round(12 - 1.5 * openingFactor + 3 * Math.pow(matPhase, 1.3) - scrambleDrop + depthAdj);
        const baseStopD = Math.max(8, Math.min(tankMaxD, rawBaseD));
        const canTank = settings.humanMode && !onPlannedLine && myMs > 18000 && fPly >= 14 && (fPly - (state.lastTankPly ?? -12)) >= 10;
        const tankCapMs = Math.round(Math.min(12500, Math.min(myMs * 0.18, effectiveMs * 0.055 * preset.tankScale * (0.75 + Math.random() * 0.65))));

        const useHistory = state.uciHistoryValid && Array.isArray(state.uciHistory) && state.uciHistory.length === fPly;
        const posCmd = useHistory
            ? (state.uciHistory.length > 0 ? `position startpos moves ${state.uciHistory.join(" ")}` : "position startpos")
            : `position fen ${fen}`;
        const goDeepCmd = (settings.autoTimeMgmt && clocks)
            ? `go wtime ${clocks.wMs} btime ${clocks.bMs} winc ${clocks.incMs} binc ${clocks.incMs}`
            : `go depth ${settings.humanMode ? Math.min(actualDepth, 14) : actualDepth}`;

        const maxPVForPreset = (settings.humanPreset === "hikaru" || settings.humanPreset === "gm" || settings.humanPreset === "stealth") ? 3 : 5;
        const isFastBookOrForced = (fPly <= 2) || legalLen <= 2;
        const needFocusMulti = !settings.humanMode && (settings.showMultiBest || (settings.engineFocus && settings.engineFocus !== "balanced"));
        const wantMultiPV = (!settings.humanMode && !needFocusMulti) || isFastBookOrForced
            ? 1
            : (!settings.humanMode ? 3 : (!settings.autoTimeMgmt ? Math.min(3, maxPVForPreset) : (myMs > 14000 ? maxPVForPreset : (myMs > 9000 ? Math.min(3, maxPVForPreset) : 1))));
        const finalMultiPV = Math.min(wantMultiPV, Math.max(1, legalLen));
        const routineCapMs = settings.humanMode
            ? (onPlannedLine ? Math.min(360, Math.max(140, paceMs * 0.45)) : Math.min(1250, Math.max(300, paceMs * 1.4)))
            : Math.min(7000, Math.max(600, effectiveMs * 0.035));

        if (state._searchCapTimer) { clearTimeout(state._searchCapTimer); state._searchCapTimer = null; }
        const armStopTimer = (ms) => {
            if (state._searchCapTimer) clearTimeout(state._searchCapTimer);
            state._searchCapTimer = setTimeout(() => {
                state._searchCapTimer = null;
                if (state.isLocalSearching && state.localEngine && state.searchTrace && !state.searchTrace.stopSent) {
                    state.searchTrace.stopSent = true;
                    state.localEngine.postMessage("stop");
                }
            }, Math.round(ms));
        };

        const boardGeom = analyzeBoardGeometry(b64Now, sideToMove);

        Object.assign(state.searchTrace, {
            phase: "deep",
            fen,
            posCmd,
            goDeepCmd,
            routineCapMs,
            armStopTimer,
            expectedMultiPV: finalMultiPV,
            quickStopD,
            baseStopD,
            hardStopD: Math.min(tankMaxD, baseStopD + 3),
            tankMaxD,
            paceMs,
            openingFactor,
            matPhase,
            ply: fPly,
            legalCount: legalLen,
            b64: b64Now,
            side: sideToMove,
            myMs,
            oppMs,
            incMs,
            oppThinkMs: state.oppLastThinkMs ?? null,
            boardGeom,
            onPlannedLine,
            plannedReply,
            oppDeviated,
            oppRecapturedUs,
            oppGaveCheck,
            surpriseBase,
            canTank,
            isTank: false,
            tankCapMs
        });

        const wantWDL = Boolean(m.hasWDL && (settings.humanMode || settings.localShowWDL));
        if (m.hasWDL && state._lastShowWDL !== wantWDL) {
            cmds.push(`setoption name UCI_ShowWDL value ${wantWDL}`);
            state._lastShowWDL = wantWDL;
        }
        if (state._lastMultiPV !== finalMultiPV) {
            cmds.push(`setoption name MultiPV value ${finalMultiPV}`);
            state._lastMultiPV = finalMultiPV;
        }
        if (settings.autoTimeMgmt && clocks) armStopTimer(routineCapMs);
        cmds.push(posCmd, goDeepCmd);
        state.lastLiveResult = formatLiveResult("...", { text: "Analyzing...", color: "#58a6ff" }, "", "Calculating...");
        updateUI();
        cmds.forEach((cmd) => state.localEngine.postMessage(cmd));
    }

    function isAttackedBy(b64, sqIdx, attackerIsWhite) {
        if (!b64 || sqIdx < 0 || sqIdx > 63) return false;
        const r = Math.floor(sqIdx / 8), f = sqIdx % 8;
        const isAtk = (ch) => ch !== "." && (attackerIsWhite ? ch === ch.toUpperCase() : ch === ch.toLowerCase());
        const at = (rr, ff) => (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) ? b64[rr * 8 + ff] : ".";

        // Pawns
        const pr = attackerIsWhite ? r + 1 : r - 1;
        const pCh = attackerIsWhite ? "P" : "p";
        if (at(pr, f - 1) === pCh || at(pr, f + 1) === pCh) return true;

        // Knights
        const nCh = attackerIsWhite ? "N" : "n";
        for (const [dr, df] of [[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]]) {
            if (at(r + dr, f + df) === nCh) return true;
        }
        // King
        const kCh = attackerIsWhite ? "K" : "k";
        for (let dr = -1; dr <= 1; dr++) for (let df = -1; df <= 1; df++) {
            if ((dr || df) && at(r + dr, f + df) === kCh) return true;
        }
        // Orthogonal (R / Q)
        for (const [dr, df] of [[-1,0],[1,0],[0,-1],[0,1]]) {
            let rr = r + dr, ff = f + df;
            while (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                const c = b64[rr * 8 + ff];
                if (c !== ".") {
                    if (isAtk(c) && (c.toLowerCase() === "r" || c.toLowerCase() === "q")) return true;
                    break;
                }
                rr += dr; ff += df;
            }
        }
        // Diagonal (B / Q)
        for (const [dr, df] of [[-1,-1],[-1,1],[1,-1],[1,1]]) {
            let rr = r + dr, ff = f + df;
            while (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                const c = b64[rr * 8 + ff];
                if (c !== ".") {
                    if (isAtk(c) && (c.toLowerCase() === "b" || c.toLowerCase() === "q")) return true;
                    break;
                }
                rr += dr; ff += df;
            }
        }
        return false;
    }

    function analyzeMoveFeatures(uci, b64, side, oppLastTo) {
        if (!uci || uci.length < 4 || !b64) return { score: 0, isCapture: false, isSacrifice: false, isRetreat: false, givesCheck: false, isRecapture: false, isQuietKing: false };
        const fromF = uci.charCodeAt(0) - 97, fromR = 8 - parseInt(uci[1], 10);
        const toF = uci.charCodeAt(2) - 97, toR = 8 - parseInt(uci[3], 10);
        const fromIdx = fromR * 8 + fromF, toIdx = toR * 8 + toF;
        if (fromIdx < 0 || fromIdx > 63 || toIdx < 0 || toIdx > 63) return { score: 0 };

        const rawPiece = b64[fromIdx], piece = rawPiece.toLowerCase();
        const capRaw = b64[toIdx], cap = capRaw.toLowerCase();
        const pVal = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
        const isEP = (piece === "p" && fromF !== toF && capRaw === ".");
        const isCapture = (capRaw !== "." || isEP);
        const isRecapture = !!(oppLastTo && uci.slice(2, 4) === oppLastTo && isCapture && state.oppLastWasCapture);
        const isCastling = (piece === "k" && Math.abs(toF - fromF) === 2);
        const isRetreat = (piece === "q" || piece === "b" || piece === "n") && !isCapture &&
            (side === "w" ? toR > fromR : toR < fromR);
        const isEdgePawn = (piece === "p" && (toF === 0 || toF === 7) && !isCapture && Math.abs(toR - fromR) === 1);
        const isQuietKing = (piece === "k" && !isCastling && !isCapture);
        const isCenterDev = (piece === "n" || piece === "b") && (toF >= 2 && toF <= 5) &&
            (side === "w" ? (fromR === 7 && toR <= 5) : (fromR === 0 && toR >= 2));

        // Simulate move to detect checks & sacrifices
        const nextB = b64.slice();
        nextB[toIdx] = uci.length > 4 ? (side === "w" ? uci[4].toUpperCase() : uci[4].toLowerCase()) : rawPiece;
        nextB[fromIdx] = ".";
        if (isEP) nextB[fromR * 8 + toF] = ".";

        const enemyKingChar = side === "w" ? "k" : "K";
        const enemyKingIdx = nextB.indexOf(enemyKingChar);
        const givesCheck = enemyKingIdx >= 0 && isAttackedBy(nextB, enemyKingIdx, side === "w");
        const destDefended = isAttackedBy(nextB, toIdx, side !== "w");
        const capVal = isEP ? 1 : (pVal[cap] || 0);
        const isSacrifice = destDefended && (pVal[piece] || 0) > capVal && piece !== "k";

        const nextKey = nextB.join("") + "|" + (side === "w" ? "b" : "w");
        const repCount = state.posVisitCounts?.[nextKey] || 0;
        const isKingActiveEnd = (piece === "k") && (toF >= 2 && toF <= 5) && (toR >= 2 && toR <= 5);
        const centerDist = (f, r) => Math.abs(f - 3.5) + Math.abs(r - 3.5);
        const movedTowardCenter = centerDist(toF, toR) < centerDist(fromF, fromR);
        const isForward = (side === "w" ? toR < fromR : toR > fromR);

        // Open/semi-open file check for rooks
        let hasFriendlyPawnOnToFile = false;
        const friendlyPawn = side === "w" ? "P" : "p";
        for (let rr = 0; rr < 8; rr++) {
            if (b64[rr * 8 + toF] === friendlyPawn) { hasFriendlyPawnOnToFile = true; break; }
        }
        const isOpenRookFile = (piece === "r") && !hasFriendlyPawnOnToFile;

        // Castled king-shield pawn push check
        const ourKIdx = b64.indexOf(side === "w" ? "K" : "k");
        const ourKF = ourKIdx >= 0 ? (ourKIdx % 8) : -1;
        const weakensCastledShield = (piece === "p") && !isCapture && (
            (ourKF >= 5 && fromF >= 5 && Math.abs(toR - fromR) === 1) ||
            (ourKF <= 2 && fromF <= 2 && Math.abs(toR - fromR) === 1)
        );
        const isCentralPawn = (piece === "p") && (toF >= 2 && toF <= 5) && isForward;
        const isEndgamePawnPush = (piece === "p") && (side === "w" ? toR <= 2 : toR >= 5);
        const ekR = enemyKingIdx >= 0 ? Math.floor(enemyKingIdx / 8) : -1;
        const ekF = enemyKingIdx >= 0 ? (enemyKingIdx % 8) : -1;
        const nearEnemyKing = enemyKingIdx >= 0 && piece !== "k" && (Math.abs(toR - ekR) + Math.abs(toF - ekF)) <= 3 && !isSacrifice;
        const isQueenTrade = (piece === "q" && cap === "q");

        // --- Recurring Human Chess Patterns (non-board-specific) ---
        // 1) Supported Knight Outpost (center/enemy half, pawn-backed, not kickable by adjacent enemy pawns)
        const pawnSupportR = side === "w" ? toR + 1 : toR - 1;
        const enemyPawn = side === "w" ? "p" : "P";
        const inOutpostZone = side === "w" ? (toR >= 2 && toR <= 4) : (toR >= 3 && toR <= 5);
        let isSupportedOutpost = false;
        if (piece === "n" && inOutpostZone && toF >= 1 && toF <= 6 && pawnSupportR >= 0 && pawnSupportR < 8) {
            const hasSupport = (toF > 0 && b64[pawnSupportR * 8 + toF - 1] === friendlyPawn) ||
                               (toF < 7 && b64[pawnSupportR * 8 + toF + 1] === friendlyPawn);
            let kickable = false;
            for (const df of [-1, 1]) {
                const cf = toF + df;
                if (cf < 0 || cf > 7) continue;
                const startR = side === "w" ? 0 : toR + 1;
                const endR   = side === "w" ? toR - 1 : 7;
                for (let rr = startR; rr <= endR; rr++) {
                    if (b64[rr * 8 + cf] === enemyPawn) { kickable = true; break; }
                }
            }
            if (hasSupport && !kickable) isSupportedOutpost = true;
        }

        // 2) Rook on 7th/2nd rank or Doubled Rooks on same file
        const friendlyRook = side === "w" ? "R" : "r";
        const friendlyQueen = side === "w" ? "Q" : "q";
        const friendlyBishop = side === "w" ? "B" : "b";
        let hasOtherRookOnFile = false;
        let hasBattery = false;
        for (let rr = 0; rr < 8; rr++) {
            if (rr !== fromR && b64[rr * 8 + toF] === friendlyRook) hasOtherRookOnFile = true;
        }
        if (piece === "q" || piece === "b") {
            for (const [dr, df] of [[-1,-1],[-1,1],[1,-1],[1,1]]) {
                let rr = toR + dr, ff = toF + df;
                while (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                    const c = b64[rr * 8 + ff];
                    if (c !== ".") {
                        if ((piece === "q" && c === friendlyBishop) || (piece === "b" && c === friendlyQueen)) hasBattery = true;
                        break;
                    }
                    rr += dr; ff += df;
                }
            }
        }
        if (piece === "q" || piece === "r") {
            for (const [dr, df] of [[-1,0],[1,0],[0,-1],[0,1]]) {
                let rr = toR + dr, ff = toF + df;
                while (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                    const c = b64[rr * 8 + ff];
                    if (c !== ".") {
                        if ((piece === "q" && c === friendlyRook) || (piece === "r" && c === friendlyQueen)) hasBattery = true;
                        break;
                    }
                    rr += dr; ff += df;
                }
            }
        }
        const isRook7th = (piece === "r") && (side === "w" ? toR === 1 : toR === 6);
        const isDoubledRooks = (piece === "r") && hasOtherRookOnFile;
        const isBackRankDev = (piece === "n" && (side === "w" ? (fromR === 7 && toR <= 5) : (fromR === 0 && toR >= 2))) ||
                              (piece === "b" && (side === "w" ? (fromR === 7 && toR <= 5) : (fromR === 0 && toR >= 2)));
        const isWeirdRookLift = (piece === "r") && !isCapture && !givesCheck && !isOpenRookFile && !isDoubledRooks &&
                                (toF === 0 || toF === 7) && (side === "w" ? (fromR === 7 && toR === 6) : (fromR === 0 && toR === 1));
        const isPoisonedGrab = (piece === "q") && isCapture && !isRecapture && (toF <= 1 || toF >= 6) && (side === "w" ? toR <= 2 : toR >= 5) && destDefended;

        let score = 0;
        if (isCastling) score += 28;
        if (isSupportedOutpost) score += 18;
        if (isCenterDev) score += 18;
        if (isRook7th || isDoubledRooks) score += 16;
        if (isBackRankDev) score += 14;
        if (hasBattery) score += 12;
        if (movedTowardCenter && !isRetreat && piece !== "k" && piece !== "r") score += 10;
        if (isForward && (piece === "n" || piece === "b" || piece === "q")) score += 8;
        if (isOpenRookFile) score += 16;
        if (isCentralPawn) score += 10;
        if (nearEnemyKing) score += 10;
        if (givesCheck) score += 12;
        if (isRecapture) score += 18;

        if (isWeirdRookLift) score -= 28;
        if (isPoisonedGrab) score -= 18;
        if (isEdgePawn) score -= 22;
        else if (weakensCastledShield) score -= 18;
        if (isRetreat) score -= 20;
        if (isQuietKing && !isKingActiveEnd) score -= 24;
        if (piece === "r" && !isCapture && !isOpenRookFile && !isDoubledRooks && (side === "w" ? (fromR === 7 && toR === 7) : (fromR === 0 && toR === 0))) score -= 12;

        const isFreeCapture = isCapture && (!destDefended || capVal >= (pVal[piece] || 0));
        if (isFreeCapture && !isPoisonedGrab) score += 26 + capVal * 4;
        else if (isCapture && !isSacrifice && !isPoisonedGrab) score += 10 + capVal * 2;

        return { score, isCapture, isFreeCapture, capVal, isSacrifice, isRetreat, givesCheck, isRecapture, isQuietKing, isKingActiveEnd, isEndgamePawnPush, isQueenTrade, nearEnemyKing, repCount, piece, isWeirdRookLift };
    }

    function analyzeBoardGeometry(b64, side) {
        if (!b64) return { tensionPairs: 0, hangingUs: [], hangingThem: [], myKingExposed: 0, oppKingExposed: 0 };
        const pVal = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
        const isWhite = (side === "w");
        const isFriendly = (c) => c !== "." && (isWhite ? c === c.toUpperCase() : c === c.toLowerCase());
        const isEnemy = (c) => c !== "." && !isFriendly(c);

        let tensionPairs = 0;
        const hangingUs = [];
        const hangingThem = [];

        for (let i = 0; i < 64; i++) {
            const c = b64[i];
            if (c === "." || c.toLowerCase() === "k") continue;
            const v = pVal[c.toLowerCase()] || 0;
            const atkByW = isAttackedBy(b64, i, true);
            const atkByB = isAttackedBy(b64, i, false);
            if (isFriendly(c) && atkByB) {
                tensionPairs++;
                if (!atkByW) hangingUs.push({ idx: i, piece: c.toLowerCase(), val: v });
            } else if (isEnemy(c) && atkByW) {
                tensionPairs++;
                if (!atkByB) hangingThem.push({ idx: i, piece: c.toLowerCase(), val: v });
            }
        }

        const kingExposure = (kChar, enemyIsWhite) => {
            const kIdx = b64.indexOf(kChar);
            if (kIdx < 0) return 0;
            const kr = Math.floor(kIdx / 8), kf = kIdx % 8;
            let exp = 0;
            for (let dr = -1; dr <= 1; dr++) {
                for (let df = -1; df <= 1; df++) {
                    const rr = kr + dr, ff = kf + df;
                    if (rr < 0 || rr > 7 || ff < 0 || ff > 7) continue;
                    if (isAttackedBy(b64, rr * 8 + ff, enemyIsWhite)) exp++;
                }
            }
            return exp;
        };

        return {
            tensionPairs,
            hangingUs,
            hangingThem,
            myKingExposed: kingExposure(isWhite ? "K" : "k", !isWhite),
            oppKingExposed: kingExposure(isWhite ? "k" : "K", isWhite)
        };
    }

    function getAttackedSquares(b64, fromIdx) {
        const out = new Set();
        if (!b64 || fromIdx < 0 || fromIdx > 63) return out;
        const raw = b64[fromIdx];
        if (!raw || raw === ".") return out;
        const isWhite = (raw === raw.toUpperCase());
        const p = raw.toLowerCase();
        const r = Math.floor(fromIdx / 8), f = fromIdx % 8;
        const add = (rr, ff) => {
            if (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                const sq = String.fromCharCode(97 + ff) + (8 - rr);
                out.add(sq);
            }
        };
        if (p === "p") {
            const dr = isWhite ? -1 : 1;
            add(r + dr, f - 1); add(r + dr, f + 1);
        } else if (p === "n") {
            for (const [dr, df] of [[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]]) add(r + dr, f + df);
        } else if (p === "k") {
            for (let dr = -1; dr <= 1; dr++) for (let df = -1; df <= 1; df++) if (dr || df) add(r + dr, f + df);
        } else {
            const dirs = [];
            if (p === "b" || p === "q") dirs.push([-1,-1],[-1,1],[1,-1],[1,1]);
            if (p === "r" || p === "q") dirs.push([-1,0],[1,0],[0,-1],[0,1]);
            for (const [dr, df] of dirs) {
                let rr = r + dr, ff = f + df;
                while (rr >= 0 && rr < 8 && ff >= 0 && ff < 8) {
                    add(rr, ff);
                    if (b64[rr * 8 + ff] !== ".") break;
                    rr += dr; ff += df;
                }
            }
        }
        return out;
    }

    function computeCognitiveContext(chosenMove, chosenObj, chosenFeat, landscape, affect, tr) {
        const b64 = tr?.b64;
        const side = tr?.side || "w";
        const ply = tr?.ply || 0;
        const fromSq = chosenMove.slice(0, 2);
        const toSq = chosenMove.slice(2, 4);
        const fromIdx = (8 - parseInt(fromSq[1], 10)) * 8 + (fromSq.charCodeAt(0) - 97);

        // 1) Did WE threaten this exact square/king previously (either last turn OR already sitting on it before opp moved)?
        const ourThreats = state.ourLastThreatenedSet instanceof Set ? state.ourLastThreatenedSet : new Set();
        let wasOurThreatSetup = ourThreats.has(toSq);
        if (!wasOurThreatSetup && state.oppPrevBoard64 && fromIdx >= 0 && fromIdx <= 63) {
            const prevPiece = state.oppPrevBoard64[fromIdx];
            if (prevPiece && prevPiece !== "." && (side === "w" ? prevPiece === prevPiece.toUpperCase() : prevPiece === prevPiece.toLowerCase())) {
                if (getAttackedSquares(state.oppPrevBoard64, fromIdx).has(toSq)) wasOurThreatSetup = true;
            }
        }
        if (!wasOurThreatSetup && b64 && chosenFeat.givesCheck) {
            const ekSqIdx = b64.indexOf(side === "w" ? "k" : "K");
            if (ekSqIdx >= 0) {
                const ekSq = String.fromCharCode(97 + (ekSqIdx % 8)) + (8 - Math.floor(ekSqIdx / 8));
                if (ourThreats.has(ekSq)) wasOurThreatSetup = true;
            }
        }

        // 2) Did opponent's LAST move create a real new threat (ignores routine opening pawn attacks!)
        let oppCreatedThreat = !!tr?.oppGaveCheck;
        if (!oppCreatedThreat && b64 && state.oppLastTo) {
            const oppToIdx = (8 - parseInt(state.oppLastTo[1], 10)) * 8 + (state.oppLastTo.charCodeAt(0) - 97);
            const oppAtk = getAttackedSquares(b64, oppToIdx);
            const pVal = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
            const isFriendly = (c) => c !== "." && (side === "w" ? c === c.toUpperCase() : c === c.toLowerCase());
            for (const sq of oppAtk) {
                const idx = (8 - parseInt(sq[1], 10)) * 8 + (sq.charCodeAt(0) - 97);
                const ch = b64[idx];
                if (isFriendly(ch)) {
                    const val = pVal[ch.toLowerCase()] || 0;
                    const defended = isAttackedBy(b64, idx, side === "w");
                    if (ch.toLowerCase() === "k" || (val >= 3 && !defended) || (val === 1 && !defended && ply > 8)) {
                        oppCreatedThreat = true;
                        break;
                    }
                }
            }
        }

        // 3) Visual Saliency [0..1]
        let moveSaliency = 0.35;
        if (chosenFeat.isRecapture) moveSaliency += 0.45;
        if (state.lastOurTo && fromSq === state.lastOurTo) moveSaliency += 0.25;
        if (wasOurThreatSetup) moveSaliency += 0.25;
        if (chosenFeat.givesCheck && (chosenFeat.piece === "q" || chosenFeat.piece === "r")) moveSaliency += 0.18;
        if (chosenFeat.isCapture && chosenFeat.capVal >= 3) moveSaliency += 0.15;

        const sqXY = (sq) => (sq && sq.length >= 2) ? { f: sq.charCodeAt(0) - 97, r: 8 - parseInt(sq[1], 10) } : null;
        const fXY = sqXY(fromSq), tXY = sqXY(toSq), oXY = sqXY(state.oppLastTo);
        if (fXY && tXY) {
            const span = Math.max(Math.abs(tXY.f - fXY.f), Math.abs(tXY.r - fXY.r));
            if (span >= 5 && !chosenFeat.isRecapture) moveSaliency -= 0.22;
        }
        if (oXY && fXY) {
            const attnDist = Math.max(Math.abs(fXY.f - oXY.f), Math.abs(fXY.r - oXY.r));
            if (attnDist >= 5 && !wasOurThreatSetup) moveSaliency -= 0.18;
        }
        if (chosenFeat.isRetreat && !chosenFeat.givesCheck) moveSaliency -= 0.20;
        if (!chosenFeat.isCapture && !chosenFeat.givesCheck && !chosenFeat.isCastling) moveSaliency -= 0.12;
        moveSaliency = Math.max(0.05, Math.min(1.0, moveSaliency));

        // 4) Expectation Score [0..1]
        const prevMoverCp = typeof tr?.prevExpectedMoverCp === "number" ? tr.prevExpectedMoverCp : (chosenObj?.cpMover || 0);
        const suddenReversal = (prevMoverCp <= -110 && (chosenObj?.cpMover >= 150 || chosenObj?.type === "mate"));
        let expectationScore = 0.52;
        if (tr?.onPlannedLine) expectationScore += 0.34;
        if (chosenFeat.isRecapture) expectationScore += 0.26;
        if (wasOurThreatSetup) expectationScore += 0.24;
        if (affect.bailoutShock && !wasOurThreatSetup) expectationScore -= 0.45;
        if (suddenReversal && !wasOurThreatSetup) expectationScore -= 0.38;
        if (oppCreatedThreat && !tr?.onPlannedLine) expectationScore -= 0.24;
        if (tr?.oppDeviated && !chosenFeat.isRecapture) expectationScore -= 0.16;
        expectationScore = Math.max(0.0, Math.min(1.0, expectationScore));

        const forcedCheckTension = Boolean(tr?.oppGaveCheck && (tr?.legalCount || 20) <= 4 && landscape.gap12 >= 80 && !chosenFeat.isRecapture);

        return { wasOurThreatSetup, oppCreatedThreat, moveSaliency, expectationScore, suddenReversal, forcedCheckTension };
    }

    function computeOpponentFingerprint() {
        const hist = Array.isArray(state.oppThinkHistory) ? state.oppThinkHistory : [];
        if (hist.length < 3) return { meanMs: 1200, stdMs: 800, instantRate: 0, isRobotic: false };
        const n = hist.length;
        const mean = hist.reduce((a, b) => a + b, 0) / n;
        const variance = hist.reduce((a, b) => a + (b - mean) * (b - mean), 0) / n;
        const std = Math.sqrt(variance);
        const instantRate = hist.filter(t => t < 380).length / n;
        const cv = mean > 50 ? (std / mean) : 0;
        const isRobotic = (n >= 4 && (cv < 0.24 || instantRate >= 0.72));
        return { meanMs: mean, stdMs: std, instantRate, isRobotic };
    }

    function computeDepthInversion(move, deepRank, deepCp, tr) {
        const snaps = tr?.snapshotsByDepth || {};
        const depths = Object.keys(snaps).map(Number).filter(n => !Number.isNaN(n)).sort((a, b) => a - b);
        if (depths.length < 2) return { shallowRank: deepRank, rankJump: 0, cpGainFromShallow: 0, isHiddenEngineTactic: false, isPoisonedTrap: false };

        let shallowD = depths.find(d => d >= 4 && d <= 6);
        if (shallowD === undefined) shallowD = depths.find(d => d >= 2 && d <= 7);
        if (shallowD === undefined || shallowD >= depths[depths.length - 1] - 2) {
            return { shallowRank: deepRank, rankJump: 0, cpGainFromShallow: 0, isHiddenEngineTactic: false, isPoisonedTrap: false };
        }

        const sMap = snaps[shallowD] || {};
        const sEntries = Object.entries(sMap)
            .map(([idx, obj]) => ({ rank: parseInt(idx, 10), obj }))
            .filter(x => x.obj && x.obj.move)
            .sort((a, b) => a.rank - b.rank);
        if (sEntries.length < 2) return { shallowRank: deepRank, rankJump: 0, cpGainFromShallow: 0, isHiddenEngineTactic: false, isPoisonedTrap: false };

        const found = sEntries.find(x => x.obj.move === move);
        const shallowRank = found ? found.rank : (sEntries.length + 1);
        const shallowCp = found ? found.obj.cpMover : (sEntries[sEntries.length - 1].obj.cpMover - 35);
        const rankJump = shallowRank - deepRank;
        const cpGainFromShallow = deepCp - shallowCp;

        const isHiddenEngineTactic = (deepRank === 1 && rankJump >= 2 && cpGainFromShallow >= 75);
        const isPoisonedTrap = (shallowRank === 1 && rankJump <= -2 && cpGainFromShallow <= -75);

        return { shallowRank, rankJump, cpGainFromShallow, isHiddenEngineTactic, isPoisonedTrap };
    }

    function computePositionLandscape(mpv, tr) {
        const list = [1, 2, 3, 4, 5].map(i => mpv?.[i]).filter(p => p && p.move);
        const pv1 = list[0] || null;
        const pv2 = list[1] || null;
        const pv3 = list[2] || null;

        let sharpness = 0.25, drawLock = 0.45;
        if (pv1?.wdl && pv1.wdl.length === 3) {
            const [w, d, l] = pv1.wdl;
            drawLock = Math.max(0, Math.min(1, d / 1000));
            sharpness = Math.max(0, Math.min(1, ((2 * Math.min(w, l)) / (w + l + 1)) * (1 - drawLock * 0.65)));
        } else {
            const geom = tr?.boardGeom;
            const vol = Math.min(1, (tr?.volatilityIntegral || 0) / 80);
            const tens = geom ? Math.min(1, geom.tensionPairs / 8) : 0.25;
            sharpness = Math.max(0, Math.min(1, 0.55 * vol + 0.45 * tens));
            drawLock = Math.max(0, Math.min(1, 1 - sharpness - Math.min(0.6, Math.abs(pv1?.cpMover || 0) / 400)));
        }

        let entropy = 0;
        if (list.length > 1 && pv1) {
            const ws = list.map(p => Math.exp(-Math.max(0, pv1.cpMover - p.cpMover) / 26));
            const sum = ws.reduce((a, b) => a + b, 0) || 1;
            for (const w of ws) {
                const pr = w / sum;
                if (pr > 1e-6) entropy -= pr * Math.log(pr);
            }
        }

        const gap12 = (pv1 && pv2) ? Math.max(0, pv1.cpMover - pv2.cpMover) : 0;
        const gap23 = (pv2 && pv3) ? Math.max(0, pv2.cpMover - pv3.cpMover) : 0;

        let cliffType = "NORMAL";
        if (gap12 >= 80) cliffType = "FORCED_ONLY";
        else if (gap12 <= 22 && gap23 >= 65) cliffType = "DUAL_CLIFF";
        else if (entropy >= 1.32 && gap12 <= 18) cliffType = "OPEN_CROSSROADS";

        const lastD = tr?.lastCompletedDepth || (pv1?.depth || 10);
        const selD = pv1?.seldepth || tr?.seldepthByDepth?.[lastD] || lastD;
        const extRatio = lastD > 0 ? (selD / lastD) : 1.0;

        let branchingSpike = 1.0;
        const nPrev = tr?.nodesByDepth?.[lastD - 1];
        const nCurr = tr?.nodesByDepth?.[lastD];
        if (nPrev > 0 && nCurr > 0) branchingSpike = nCurr / nPrev;

        return { sharpness, drawLock, entropy, gap12, gap23, cliffType, extRatio, branchingSpike, lastD };
    }

    function computeAestheticSuspicion(uci, feat, inv, tr, landscape) {
        if (!uci || uci.length < 4) return 0;
        const geom = tr?.boardGeom || { tensionPairs: 0, hangingUs: [], myKingExposed: 0 };
        const fromF = uci.charCodeAt(0) - 97, fromR = 8 - parseInt(uci[1], 10);
        const toF = uci.charCodeAt(2) - 97, toR = 8 - parseInt(uci[3], 10);
        const fromIdx = fromR * 8 + fromF;
        let susp = 0;

        if (inv.isHiddenEngineTactic) susp += 42;
        else if (inv.rankJump >= 2 && inv.cpGainFromShallow >= 45) susp += 22;

        const isEdgePush = (feat.piece === "p") && (toF === 0 || toF === 7) && !feat.isCapture && Math.abs(toR - fromR) === 1;
        if (isEdgePush && geom.tensionPairs >= 2 && !feat.givesCheck) susp += 32;

        if (feat.isWeirdRookLift) susp += 34;

        const bigHanging = (geom.hangingUs || []).find(h => h.val >= 3);
        if (bigHanging && fromIdx !== bigHanging.idx && !feat.isCapture && !feat.givesCheck && inv.rankJump >= 1) {
            susp += 42;
        }

        if (feat.isRetreat && !feat.givesCheck && landscape.sharpness >= 0.45) susp += 26;
        if (feat.isQuietKing && !feat.isKingActiveEnd && (tr?.matPhase || 0) < 0.65 && geom.myKingExposed >= 2) susp += 34;
        if (uci.length > 4 && uci[4] !== "q") susp += 40;

        return susp;
    }

    function computeHumanTiming(chosenMove, chosenObj, chosenFeat, chosenInv, landscape, affect, oppProfile, ctx, tr, myMs, incMs, panic) {
        const matPhase = tr?.matPhase ?? 0.2;
        const openingFactor = tr?.openingFactor ?? 0;
        const legalCount = tr?.legalCount ?? 20;
        const paceMs = tr?.paceMs || 520;
        const ply = tr?.ply || 0;
        const cpNow = chosenObj?.cpMover ?? 0;
        const prevMoverCp = typeof tr?.prevExpectedMoverCp === "number" ? tr.prevExpectedMoverCp : cpNow;
        const mateVal = (chosenObj && chosenObj.type === "mate") ? chosenObj.rawVal : 0;
        const isMateIn1 = (mateVal === 1);
        const isSimpleMate2 = (mateVal === 2 && !chosenFeat.isSacrifice && (tr?.onPlannedLine || ctx.wasOurThreatSetup || chosenFeat.givesCheck));
        const effectiveMs = myMs + incMs * 16;
        const isScramble = effectiveMs < 13500;
        const geomTension = tr?.boardGeom?.tensionPairs || 0;

        const sqXY = (sq) => (sq && sq.length >= 2) ? { f: sq.charCodeAt(0) - 97, r: 8 - parseInt(sq[1], 10) } : null;
        const fromXY = sqXY(chosenMove.slice(0, 2));
        const toXY = sqXY(chosenMove.slice(2, 4));
        const oppXY = sqXY(state.oppLastTo);
        const isCastlingMove = (chosenFeat.piece === "k" && fromXY && toXY && Math.abs(toXY.f - fromXY.f) === 2);

        const recordAndReturn = (ms, lbl) => {
            const actualElapsed = performance.now() - state.analysisStartTime;
            state.lastTelemetryTag = actualElapsed > ms + 90 ? (lbl + "*") : lbl;
            if (!state.recentThinkTimes) state.recentThinkTimes = [];
            state.recentThinkTimes.push(Math.round(Math.max(ms, actualElapsed)));
            if (state.recentThinkTimes.length > 8) state.recentThinkTimes.shift();
            return ms;
        };

        if (legalCount <= 1) {
            return recordAndReturn(Math.round(125 + Math.random() * 175), "ONLY-MOVE");
        }

        if (isMateIn1) {
            const expectedMate = (
                tr?.onPlannedLine ||
                ctx.wasOurThreatSetup ||
                (prevMoverCp >= 220 && ctx.moveSaliency >= 0.55) ||
                (ctx.expectationScore >= 0.65 && ctx.moveSaliency >= 0.70)
            );
            let mateMs, mTag;
            if (isScramble) {
                mateMs = 140 + Math.random() * 210;
                mTag = "SCRAM-M1";
            } else if (expectedMate && !ctx.suddenReversal) {
                mateMs = 175 + Math.random() * 275;
                mTag = "SNAP-M1";
            } else {
                const shockFactor = (ctx.suddenReversal ? 1.35 : 1.0) * (1.28 - ctx.moveSaliency * 0.55);
                mateMs = (1050 + Math.random() * 1350) * shockFactor * (1 - 0.55 * panic);
                mTag = "NOTICE-M1";
            }
            const overhead = Math.max(100, settings.localMoveOverhead || 120);
            const safeCap = Math.max(130, Math.min(myMs * 0.24, myMs - overhead - 250));
            return recordAndReturn(Math.round(Math.min(safeCap, Math.max(120, mateMs))), mTag);
        }

        const bigSurprise = (affect.bailoutShock && !ctx.wasOurThreatSetup) || ctx.suddenReversal;
        const isQuietNonForcing = !chosenFeat.isCapture && !chosenFeat.isRecapture && !chosenFeat.givesCheck && !isCastlingMove && !chosenFeat.isEndgamePawnPush;

        // --- A) Markov Cognitive Regime Update (FLOW <-> EVAL <-> CAUTIOUS) ---
        if (!state.timingRegime) { state.timingRegime = "EVAL"; state.regimeMovesLeft = 2; }
        state.regimeMovesLeft = (state.regimeMovesLeft || 1) - 1;

        if (bigSurprise || ctx.oppCreatedThreat || tr?.isTank || ctx.forcedCheckTension) {
            state.timingRegime = "CAUTIOUS";
            state.regimeMovesLeft = 2 + Math.floor(Math.random() * 2);
        } else if (state.regimeMovesLeft <= 0) {
            const canFlow = (cpNow >= 280 || tr?.onPlannedLine || ctx.expectationScore >= 0.68 || landscape.sharpness < 0.35);
            const r = Math.random();
            if (state.timingRegime === "FLOW") {
                state.timingRegime = r < 0.65 ? "EVAL" : "CAUTIOUS";
                state.regimeMovesLeft = 2 + Math.floor(Math.random() * 2);
            } else if (state.timingRegime === "CAUTIOUS") {
                state.timingRegime = (canFlow && r < 0.45) ? "FLOW" : "EVAL";
                state.regimeMovesLeft = 2 + Math.floor(Math.random() * 3);
            } else {
                if (canFlow && r < 0.48) {
                    state.timingRegime = "FLOW";
                    state.regimeMovesLeft = 2 + Math.floor(Math.random() * 3);
                } else if (landscape.sharpness >= 0.48 && r > 0.72) {
                    state.timingRegime = "CAUTIOUS";
                    state.regimeMovesLeft = 2;
                } else {
                    state.timingRegime = "EVAL";
                    state.regimeMovesLeft = 2 + Math.floor(Math.random() * 2);
                }
            }
        }
        const regimeMult = state.timingRegime === "FLOW" ? 0.58 : (state.timingRegime === "CAUTIOUS" ? 1.30 : 1.0);

        // --- 1) T_saccade ---
        let T_saccade = isScramble ? 40 : 75;
        if (fromXY && toXY) {
            const span = Math.max(Math.abs(toXY.f - fromXY.f), Math.abs(toXY.r - fromXY.r));
            T_saccade += span * (isScramble ? 7 : 12);
            if (oppXY && !chosenFeat.isRecapture) {
                const attnJump = Math.max(Math.abs(fromXY.f - oppXY.f), Math.abs(fromXY.r - oppXY.r));
                T_saccade += attnJump * (isScramble ? 8 : 16);
                const flankSwitch = (oppXY.f <= 2 && fromXY.f >= 5) || (oppXY.f >= 5 && fromXY.f <= 2);
                if (flankSwitch && !isScramble) T_saccade += 105 + Math.random() * 125;
            }
        }
        if (isCastlingMove) T_saccade = Math.max(40, T_saccade - 75);

        // --- 2) T_recognition ---
        let T_recognition = 0;
        let tag = "CALC";
        const oppThink = tr?.oppThinkMs || 0;
        const isPlannedForcingOrSimple = chosenFeat.isCapture || chosenFeat.givesCheck || chosenFeat.isRecapture || (geomTension < 2 && landscape.gap12 < 50);
        const allowSnapAfterLongOpp = (oppThink < 9500) || chosenFeat.isRecapture || chosenFeat.isCapture || chosenFeat.givesCheck || ctx.wasOurThreatSetup;
        const isPlannedFollow = tr?.onPlannedLine && tr?.plannedReply && chosenMove.slice(0, 4) === tr.plannedReply.slice(0, 4) && isPlannedForcingOrSimple && allowSnapAfterLongOpp;
        const expectedTrapHit = ctx.wasOurThreatSetup && (affect.bailoutShock || cpNow >= 220) && !ctx.suddenReversal;
        const isAttackFlow = tr?.onPlannedLine && (cpNow >= 300 || mateVal >= 2) && (chosenFeat.givesCheck || chosenFeat.nearEnemyKing) && !bigSurprise && !chosenFeat.isSacrifice;
        const isEasyWinningConvert = !bigSurprise && !ctx.oppCreatedThreat && (cpNow >= 360 && matPhase >= 0.35 && landscape.sharpness < 0.45 && !chosenInv?.isHiddenEngineTactic && mateVal === 0 && ctx.expectationScore >= 0.48);
        const dueForConvCheck = isEasyWinningConvert && (ply - (state.lastConvCheckPly ?? -10)) >= 8 && Math.random() < 0.55;

        if (isScramble && !bigSurprise && !tr?.isTank) {
            T_recognition = 65 + Math.random() * 145;
            tag = "SCRAMBLE";
        } else if (ply === 0) {
            T_recognition = 65 + Math.random() * 115;
            tag = "BOOK";
        } else if (ctx.forcedCheckTension) {
            T_recognition = 320 + Math.random() * 380;
            tag = "CHK-CHOICE";
        } else if (isSimpleMate2 && !bigSurprise && ctx.expectationScore >= 0.60) {
            T_recognition = 260 + Math.random() * 480;
            tag = "MATE2";
        } else if (isPlannedFollow && !bigSurprise) {
            const seqDrop = Math.min(95, (state.plannedStreak || 1) * 32);
            T_recognition = Math.max(70, 185 - seqDrop + Math.random() * 175);
            tag = chosenFeat.givesCheck ? "CHK-FLOW" : "PV-SNAP";
        } else if (expectedTrapHit) {
            T_recognition = 420 + Math.random() * 680;
            tag = "TRAP-HIT";
        } else if (chosenFeat.isRecapture && !bigSurprise) {
            T_recognition = 85 + Math.random() * 195;
            tag = "RECAP";
        } else if (!bigSurprise && !ctx.oppCreatedThreat && ((ply <= 7 && landscape.gap12 < 75) || (openingFactor > 0.42 && !tr?.oppDeviated && landscape.gap12 < 55))) {
            T_recognition = (ply >= 4 && Math.random() < 0.30)
                ? (520 + Math.random() * 580)
                : (140 + Math.random() * 360);
            tag = "BOOK";
        } else if (isAttackFlow && Math.random() < 0.72) {
            T_recognition = 260 + Math.random() * 620;
            tag = "ATK-FLOW";
        } else if (isEasyWinningConvert && !dueForConvCheck && (state.timingRegime === "FLOW" || Math.random() < 0.68)) {
            T_recognition = (isQuietNonForcing ? 320 : 125) + Math.random() * 320;
            tag = "CONVERT";
        } else {
            T_recognition = 190 + Math.random() * 240;
            if (dueForConvCheck) {
                state.lastConvCheckPly = ply;
                T_recognition += 1100 + Math.random() * 1300;
                tag = "CONV-CHK";
            } else if (!state.hasExitedTheory && ply >= 8 && ((tr?.volatilityIntegral || 0) >= 24 || tr?.oppDeviated || ctx.oppCreatedThreat)) {
                state.hasExitedTheory = true;
                T_recognition += 900 + Math.random() * 1350;
                tag = "THEORY-EXIT";
            }
        }

        // --- 3) T_calc ---
        let T_calc = 0;
        const isFastRoutine = (tag === "SCRAMBLE" || tag === "MATE2" || tag === "PV-SNAP" || tag === "CHK-FLOW" || tag === "TRAP-HIT" || tag === "RECAP" || tag === "BOOK" || tag === "ATK-FLOW" || tag === "CONVERT");
        if (!isFastRoutine) {
            const volNorm = Math.min(1.5, (tr?.volatilityIntegral || 0) / 55);
            const extOver = Math.max(0, landscape.extRatio - 1.22);
            const entNorm = Math.min(1.4, landscape.entropy / 1.35);
            const load = 0.34 * entNorm + 0.32 * landscape.sharpness + 0.22 * volNorm + 0.20 * extOver;

            const tierMultMap = { quick: 0.38, settled_early: 0.60, deliberate: 0.92, volatile: 1.32 };
            const tierMult = tierMultMap[tr?.tier] || 0.76;
            T_calc = paceMs * 0.52 * tierMult * regimeMult * (0.38 + Math.pow(load, 1.2) * 1.12);

            if (ctx.moveSaliency < 0.35) T_calc *= (1.20 + (0.35 - ctx.moveSaliency) * 0.85);
            if (ctx.expectationScore < 0.40) T_calc *= (1.16 + (0.40 - ctx.expectationScore) * 0.75);
            if (ctx.forcedCheckTension) T_calc = Math.max(T_calc, 950 + Math.random() * 1650);

            if (oppThink >= 2500 && !bigSurprise && !tr?.isTank && ctx.expectationScore >= 0.42) {
                const baseCredit = Math.max(0.36, 1 - Math.min(0.64, (oppThink - 1800) / 11000));
                const ponderCredit = tr?.oppDeviated ? (0.48 + 0.52 * baseCredit) : baseCredit;
                T_calc *= ponderCredit;
                if (ponderCredit <= 0.60 && tag === "CALC") tag = "PONDERED";
            } else if (oppThink > 0 && oppThink < 500 && !tr?.isTank && tag === "CALC") {
                T_calc *= (1.15 + Math.random() * 0.25);
            }

            if (chosenFeat.isRetreat && !chosenFeat.givesCheck) T_calc += 260 + Math.random() * 440;
            if (landscape.cliffType === "DUAL_CLIFF") {
                T_calc += 350 + Math.random() * 720;
                if (tag === "CALC") tag = "DUAL";
            } else if (landscape.sharpness >= 0.52 && tag === "CALC") {
                tag = "SHARP";
            }

            if (mateVal >= 2 && !isSimpleMate2) {
                const minMateCalc = (mateVal >= 3 ? 2100 : 1200) + Math.random() * 2400;
                T_calc = Math.max(T_calc, minMateCalc);
                tag = "MATE-CALC";
            }

            if (tr?.isTank) {
                state.lastTankPly = ply;
                const actualElapsed = performance.now() - state.analysisStartTime;
                T_calc = Math.max(T_calc, actualElapsed + 200, 4400 + Math.random() * 3900);
                tag = "TANK";
            }
        }

        // --- 4) T_verify ---
        let T_verify = 0;
        if (bigSurprise && !chosenFeat.isRecapture && !isScramble) {
            const blunderScale = Math.min(1.85, Math.max(1.0, (affect.blunderGain || 150) / 210));
            const salBoost = 1.25 - ctx.moveSaliency * 0.45;
            const minShock = (1650 + Math.random() * 2100) * blunderScale * salBoost * (1 - 0.55 * panic);
            T_verify += minShock;
            tag = "SURPRISE!";
        } else if (ctx.oppCreatedThreat && !tr?.onPlannedLine && !chosenFeat.isRecapture && !isScramble && !isFastRoutine) {
            T_verify += (520 + Math.random() * 800) * (1 - 0.55 * panic);
            if (tag === "CALC") tag = "THREAT-CHK";
        } else if (tr?.oppDeviated && oppThink >= 6500 && !chosenFeat.isRecapture && !isScramble && !isFastRoutine &&
                   ((tr?.maxEvalSwing || 0) >= 40 || landscape.sharpness >= 0.48 || landscape.gap12 >= 50)) {
            T_verify += (420 + Math.random() * 680) * (1 - 0.60 * panic);
            tag = "OPP-TANK";
        }

        if (chosenInv?.isHiddenEngineTactic && panic < 0.45 && myMs > 18000 && !isFastRoutine) {
            const minEureka = 4200 + Math.random() * 2600;
            if ((T_saccade + T_recognition + T_calc + T_verify) < minEureka) {
                T_verify += minEureka - (T_saccade + T_recognition + T_calc + T_verify);
                tag = "EUREKA";
            }
        }

        // --- 5) T_narrative ---
        let narrativeMult = 1.0;
        if (affect.flagMode && !bigSurprise) {
            narrativeMult *= 0.42;
            tag = "FLAG";
        } else if (affect.conversionBias && matPhase >= 0.55 && !chosenInv?.isHiddenEngineTactic && !isFastRoutine && !bigSurprise && tag !== "CONV-CHK") {
            narrativeMult *= (state.timingRegime === "FLOW" ? 0.62 : 0.85);
        }
        if (oppProfile.isRobotic && !isFastRoutine && !affect.flagMode && tag !== "TANK" && tag !== "EUREKA" && !bigSurprise) {
            narrativeMult *= (1.08 + Math.random() * 0.18);
            if (tag === "CALC") tag = "CONTRAST";
        }

        const panicCompress = isScramble ? 0.35 : (1 - 0.58 * panic);
        let rawTotal = (T_saccade + T_recognition + T_calc + T_verify) * narrativeMult * panicCompress;

        // Log-normal jitter applied BEFORE distribution shaper
        const u1 = Math.max(1e-6, Math.random()), u2 = Math.random();
        const zMax = (ply <= 4 && tag === "BOOK") ? 0.65 : 1.9;
        const z = Math.max(-1.6, Math.min(zMax, Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2)));
        rawTotal *= Math.exp(z * 0.28);

        let minFloorMs = ply === 0 ? 110 : 120;
        if (!isScramble && !affect.flagMode && ply >= 10 && isQuietNonForcing && !chosenFeat.isRecapture) {
            minFloorMs = (chosenFeat.isRetreat || chosenFeat.isWeirdRookLift)
                ? (860 + Math.random() * 440)
                : (640 + Math.random() * 340);
            rawTotal = Math.max(rawTotal, minFloorMs);
        } else if (ply === 0) {
            rawTotal = Math.max(rawTotal, minFloorMs);
        }

        // --- 6) Statistical Distribution Shaper (Range-Band Collapse + Rolling CV Enforcer) ---
        const rec = Array.isArray(state.recentThinkTimes) ? state.recentThinkTimes : [];
        if (rec.length >= 3 && !isScramble && !affect.flagMode && tag !== "TANK" && tag !== "EUREKA" && tag !== "CONV-CHK" && !bigSurprise) {
            const win4 = rec.slice(-3).concat([rawTotal]);
            const wMin = Math.min(...win4), wMax = Math.max(...win4);
            const wMean = win4.reduce((a, b) => a + b, 0) / 4;
            const bandCollapsed = (wMax - wMin) <= Math.max(360, wMean * 0.38);

            const recMean = rec.reduce((a, b) => a + b, 0) / rec.length;
            const recVar = rec.reduce((a, b) => a + (b - recMean) * (b - recMean), 0) / rec.length;
            const recCV = recMean > 80 ? (Math.sqrt(recVar) / recMean) : 0;
            const tooMetronomic = (rec.length >= 5 && recCV < 0.44 && Math.abs(rawTotal - recMean) < recMean * 0.35);

            if (bandCollapsed || tooMetronomic) {
                const goFast = (!isQuietNonForcing && (state.timingRegime === "FLOW" || Math.random() < 0.48)) ||
                               (isQuietNonForcing && wMean > 1300 && Math.random() < 0.40);
                if (goFast) {
                    rawTotal = Math.max(minFloorMs, rawTotal * (0.36 + Math.random() * 0.18));
                    state.timingRegime = "FLOW";
                    state.regimeMovesLeft = 2;
                } else {
                    rawTotal = Math.max(rawTotal * (1.58 + Math.random() * 0.55), wMax + 650 + Math.random() * 850);
                    state.timingRegime = "CAUTIOUS";
                    state.regimeMovesLeft = 2;
                }
            }
        }

        const overhead = Math.max(100, settings.localMoveOverhead || 120);
        const safeCapMs = Math.max(130, Math.min(myMs * 0.24, myMs - overhead - 250));
        const targetTotalMs = Math.round(Math.min(safeCapMs, Math.max(minFloorMs, rawTotal)));

        return recordAndReturn(targetTotalMs, tag);
    }

    function computeHumanGradientDecision(bestMove, mpv, fen, clocks) {
        const parts = (fen || "").split(" ");
        const side = parts[1] || "w";
        const tr = state.searchTrace || {};
        const matPhase = tr.matPhase ?? 0.2;
        const endgameFactor = Math.pow(matPhase, 1.35);

        const myMs = clocks ? (side === "w" ? clocks.wMs : clocks.bMs) : 60000;
        const oppMs = clocks ? (side === "w" ? clocks.bMs : clocks.wMs) : 60000;
        const incMs = clocks ? clocks.incMs : 0;
        const effectiveMs = myMs + incMs * 16;
        const panic = 1 / (1 + Math.exp((effectiveMs - 16000) / 5500));

        const legalCount = tr.legalCount ?? 20;
        const pv1 = mpv?.[1] || null;
        const pv2 = mpv?.[2] || null;
        const pv3 = mpv?.[3] || null;
        const pv4 = mpv?.[4] || null;
        const pv5 = mpv?.[5] || null;
        const b64 = tr.b64 || fenToBoard64(fen);

        const landscape = computePositionLandscape(mpv, tr);
        const oppProfile = computeOpponentFingerprint();

        // Update Narrative Affect Vector across last 6 plies
        const currWhiteCpLive = pv1 ? (side === "w" ? pv1.cpMover : -pv1.cpMover) : null;
        if (!state.recentWhiteEvalHistory) state.recentWhiteEvalHistory = [];
        if (currWhiteCpLive !== null) {
            state.recentWhiteEvalHistory.push(currWhiteCpLive);
            if (state.recentWhiteEvalHistory.length > 6) state.recentWhiteEvalHistory.shift();
        }
        const prevWhiteCp = typeof state.lastExpectedWhiteCp === "number" ? state.lastExpectedWhiteCp : currWhiteCpLive;
        tr.prevExpectedMoverCp = (typeof prevWhiteCp === "number") ? (side === "w" ? prevWhiteCp : -prevWhiteCp) : (pv1?.cpMover || 0);
        const oppBlunderGain = (currWhiteCpLive !== null && prevWhiteCp !== null)
            ? ((side === "w" ? 1 : -1) * (currWhiteCpLive - prevWhiteCp)) : 0;
        const peakRecentCp = state.recentWhiteEvalHistory.length
            ? Math.max(...state.recentWhiteEvalHistory.map(c => side === "w" ? c : -c)) : (pv1?.cpMover || 0);
        const cpNow = pv1?.cpMover || 0;

        const affect = {
            bailoutShock: (oppBlunderGain >= 95 && cpNow >= -80),
            blunderGain: oppBlunderGain,
            missedWinTilt: (peakRecentCp >= 200 && (peakRecentCp - cpNow) >= 140),
            conversionBias: (cpNow >= 180),
            flagMode: ((myMs - oppMs) >= 20000 && oppMs <= 25000 && cpNow >= -180)
        };

        let chosenObj = pv1;
        let chosenMove = bestMove;

        const shallowSet = new Set();
        for (const hd of [2, 3, 4, 5]) {
            if (tr.movesByDepth?.[hd]) shallowSet.add(tr.movesByDepth[hd]);
        }
        const depthOk = (p) => p && p.move && Math.abs((p.depth || 0) - (pv1?.depth || 0)) <= 2;

        const preset = HUMAN_PRESETS[settings.humanPreset] || HUMAN_PRESETS.master;
        const suspWeightMap = { beginner: 1.50, novice: 1.40, casual: 1.30, intermediate: 1.22, club: 1.15, expert: 0.95, master: 0.65, hikaru: 0.38, gm: 0.22, stealth: 0.10 };
        const suspWeight = suspWeightMap[settings.humanPreset] ?? 0.65;
        const isHighTier = (settings.humanPreset === "hikaru" || settings.humanPreset === "gm" || settings.humanPreset === "stealth");
        const isLowTier = (settings.humanPreset === "beginner" || settings.humanPreset === "novice" || settings.humanPreset === "casual" || settings.humanPreset === "intermediate");
        const isHikaru = (settings.humanPreset === "hikaru");
        const isImmediateMate = pv1 && pv1.type === "mate" && pv1.rawVal > 0 && (pv1.rawVal === 1 || (pv1.rawVal === 2 && (!pv2 || pv2.cpMover < 450)));

        const sqXY = (sq) => (sq && sq.length >= 2) ? { f: sq.charCodeAt(0) - 97, r: 8 - parseInt(sq[1], 10) } : null;
        const oppXY = sqXY(state.oppLastTo);
        const ourXY = sqXY(state.lastOurTo);

        const selGapEarly = ((tr.seldepthByDepth?.[landscape.lastD]) || landscape.lastD) - landscape.lastD;
        const pv1MissedEarly = pv1 ? !shallowSet.has(pv1.move) : false;
        let mom = state.humanMomentum || 0;
        let streak = state.momentumStreak || 0;

        if (streak >= 3) { mom = -0.35; streak = 0; }
        else if (pv1MissedEarly || selGapEarly >= 8 || (tr.flipCount || 0) >= 2) mom = Math.max(-0.85, mom - 0.35);
        else mom = mom * 0.65;

        const isUncertain = pv1MissedEarly || selGapEarly >= 8 || mom < -0.15;
        const isHotMomentum = !isUncertain && mom > 0.30;

        const scoreHumanIntent = (p, rankIdx, cpRef) => {
            const feat = analyzeMoveFeatures(p.move, b64, side, state.oppLastTo);
            const inv = computeDepthInversion(p.move, rankIdx, p.cpMover, tr);
            const susp = computeAestheticSuspicion(p.move, feat, inv, tr, landscape);

            let h = feat.score - susp * suspWeight;

            // Narrative & Psychological Biases
            if (cpRef > 35 && feat.repCount >= 2) h -= 5000;
            else if (cpRef > 35 && feat.repCount === 1) h -= 180;

            if (affect.flagMode) {
                if (feat.isQueenTrade || (feat.isCapture && feat.capVal >= 5)) h -= 22;
                if (feat.givesCheck || feat.nearEnemyKing) h += 16;
            } else if (affect.conversionBias) {
                if (feat.isCapture) h += (feat.isQueenTrade ? 38 : 24);
                if (p.wdl && p.wdl[2] <= 40) h += 12;
            } else if (Math.abs(cpRef) < 75 && feat.isQueenTrade) {
                h -= (isHikaru ? 20 : 10);
            }

            if (affect.missedWinTilt && (feat.givesCheck || feat.nearEnemyKing || feat.isCapture)) h += 14;
            if (cpRef > 60 && matPhase >= 0.65 && feat.isKingActiveEnd) h += 20;
            if (matPhase >= 0.65 && feat.isEndgamePawnPush) h += 20;
            if (cpRef < -120) {
                if (feat.isCapture && !feat.isRecapture) h -= 14;
                if (feat.givesCheck || feat.nearEnemyKing) h += 18;
            }
            if (isHotMomentum && (feat.givesCheck || feat.nearEnemyKing || feat.isCapture)) h += 12;
            if (isUncertain) {
                if (feat.isSacrifice && !feat.isRecapture) h -= 24;
                if (feat.isCastling || feat.isQueenTrade || (!feat.isCapture && !feat.isRetreat)) h += 10;
            }

            // Horizon Gating: penalize depth-12+ miracles when not in a Tank (except Stealth)
            if (inv.isHiddenEngineTactic && !tr.isTank && settings.humanPreset !== "stealth") {
                h -= 28;
            }
            // Temptation of shallow traps for lower tiers
            if (inv.isPoisonedTrap && (settings.humanPreset === "club" || settings.humanPreset === "expert")) {
                h += 14;
            }

            // 2D Spatial Attention Heatmap + Plan Continuity
            const toXY = sqXY(p.move.slice(2, 4));
            if (toXY && state.attentionMap) {
                const heat = state.attentionMap[toXY.r * 8 + toXY.f] || 0;
                h += heat * 8;
                if (heat < 0.15 && !feat.isCapture && !feat.givesCheck && !feat.nearEnemyKing) h -= 8;
            }
            if (state.lastOurTo && p.move.slice(0, 2) === state.lastOurTo) h += 10;
            if (oppXY && toXY) {
                const dOpp = Math.abs(toXY.f - oppXY.f) + Math.abs(toXY.r - oppXY.r);
                if (dOpp <= 2) h += 9;
                else if (Math.abs(toXY.f - oppXY.f) >= 4 && !feat.isCapture && !feat.givesCheck && !feat.nearEnemyKing) h -= 10;
            }
            if (ourXY && toXY) {
                const dOur = Math.abs(toXY.f - ourXY.f) + Math.abs(toXY.r - ourXY.r);
                if (dOur <= 2 && feat.piece !== "k") h += 6;
            }
            if (shallowSet.has(p.move)) h += 14;
            if (tr.plannedReply && p.move.slice(0, 4) === tr.plannedReply.slice(0, 4)) h += 16;

            return { feat, inv, susp, h };
        };

        const pv1Feat = analyzeMoveFeatures(pv1?.move || bestMove, b64, side, state.oppLastTo);
        const gap12Live = landscape.gap12;
        const curTop1Rate = (state.nonForcedCount || 0) >= 3 ? (state.top1Count / state.nonForcedCount) : preset.targetTop1;
        const top1Excess = Math.max(0, curTop1Rate - preset.targetTop1);

        let chosenInv = { shallowRank: 1, rankJump: 0, cpGainFromShallow: 0, isHiddenEngineTactic: false, isPoisonedTrap: false };

        if (pv1 && pv2 && legalCount > 2 && !isImmediateMate && panic < 0.74) {
            const cp = pv1.cpMover;
            let pickedCritMiss = false;

            // If pv1 is a tricky M3+ mate (not M1/M2) while pv2/pv3 simply wins clean material (+450+ or free R/Q),
            // a human often takes the practical free material instead of calculating the insane mate!
            if (pv1.type === "mate" && pv1.rawVal >= 3 && pv2 && depthOk(pv2) && pv2.cpMover >= 450 && settings.humanPreset !== "stealth") {
                const pracAlts = [pv2, pv3].filter(p => depthOk(p) && p.cpMover >= 450);
                const pracChance = settings.humanPreset === "gm" ? 0.35 : 0.62;
                if (pracAlts.length > 0 && Math.random() < pracChance) {
                    const bestPrac = pracAlts.map(p => ({ p, ...scoreHumanIntent(p, 2, p.cpMover) })).sort((a, b) => b.h - a.h)[0];
                    chosenObj = bestPrac.p;
                    chosenMove = bestPrac.p.move;
                    chosenInv = bestPrac.inv;
                    pickedCritMiss = true;
                }
            }

            const freePieceFloor = (settings.humanPreset === "beginner" || settings.humanPreset === "novice") ? 9 : ((settings.humanPreset === "casual" || settings.humanPreset === "intermediate") ? 5 : 3);
            const isFreeBigPiece = pv1Feat.isFreeCapture && (pv1Feat.capVal || 0) >= freePieceFloor;
            const skipCritMissInOpening = isHighTier && (tr.ply || 0) <= 4;
            if (!pickedCritMiss && gap12Live >= 45 && !pv1Feat.isRecapture && !isFreeBigPiece && !skipCritMissInOpening && preset.critMissRate > 0) {
                let safeFloor, maxLoss, missChance;
                if (cp >= 140) {
                    safeFloor = isHighTier ? Math.max(95, cp - preset.maxCritLoss) : (isLowTier ? Math.max(-100, cp - preset.maxCritLoss) : (cp >= 250 ? 85 : 30));
                    maxLoss = isHighTier ? preset.maxCritLoss : (isUncertain ? (preset.maxCritLoss + 140) : (preset.maxCritLoss + 65));
                    missChance = isHotMomentum ? preset.critMissRate * 0.75 : Math.min(isLowTier ? 0.88 : 0.74, preset.critMissRate + (isHighTier ? 0.03 : 0.16));
                } else if (cp <= -100) {
                    safeFloor = cp - preset.maxCritLoss;
                    maxLoss = preset.maxCritLoss;
                    missChance = preset.critMissRate;
                } else {
                    safeFloor = isHighTier ? preset.minEvenFloor : (isUncertain ? Math.min(-75, preset.minEvenFloor) : preset.minEvenFloor);
                    maxLoss = isHighTier ? preset.maxCritLoss : (isUncertain ? (preset.maxCritLoss + 95) : preset.maxCritLoss);
                    missChance = (isUncertain && !isHighTier)
                        ? Math.min(isLowTier ? 0.90 : 0.78, preset.critMissRate + 0.22)
                        : (isHotMomentum ? preset.critMissRate * 0.70 : preset.critMissRate);
                }
                if (landscape.sharpness >= 0.55 && !isHighTier) missChance = Math.min(isLowTier ? 0.90 : 0.80, missChance + 0.08);

                const critAlts = [pv2, pv3, pv4, pv5]
                    .map((p, i) => ({ p, rank: i + 2 }))
                    .filter(x => depthOk(x.p))
                    .map(x => ({ p: x.p, ...scoreHumanIntent(x.p, x.rank, cp), loss: pv1.cpMover - x.p.cpMover }))
                    .filter(x => x.loss >= 35 && x.loss <= maxLoss && x.p.cpMover >= safeFloor && x.feat.score >= (isLowTier ? -30 : -14) && !(cp > 35 && x.feat.repCount >= 1));

                if (critAlts.length > 0 && Math.random() < missChance) {
                    critAlts.sort((a, b) => b.h - a.h);
                    const pickIdx = isLowTier
                        ? Math.floor(Math.random() * critAlts.length)
                        : ((critAlts.length > 1 && Math.random() < 0.32) ? 1 : 0);
                    chosenObj = critAlts[pickIdx].p;
                    chosenMove = critAlts[pickIdx].p.move;
                    chosenInv = critAlts[pickIdx].inv;
                    pickedCritMiss = true;
                }
            }

            if (!pickedCritMiss) {
                let budgetCp;
                if (cp < -120) budgetCp = Math.round(preset.baseBudget * (isHighTier ? 1.05 : 1.15));
                else if (cp > 140) budgetCp = Math.max(isHighTier ? 22 : 50, Math.round(preset.baseBudget * (isHighTier ? 1.35 : 1.75)));
                else budgetCp = Math.round(preset.baseBudget * (1 - 0.35 * endgameFactor) * (1 - 0.45 * panic) * (1 + (isHighTier ? 0.08 : 0.20) * landscape.sharpness));

                if (isHighTier && (tr.ply || 0) <= 8) budgetCp = Math.min(budgetCp, settings.humanPreset === "hikaru" ? 26 : 16);

                const nonCritFloor = cp >= 140 ? (isHighTier ? Math.max(95, cp - budgetCp) : 40) : (cp <= -100 ? cp - budgetCp : preset.minEvenFloor);
                const cands = [pv1, pv2, pv3, pv4, pv5]
                    .map((p, idx) => ({ p, idx }))
                    .filter(x => x.p && x.p.move && (x.idx === 0 || (depthOk(x.p) && x.p.cpMover >= nonCritFloor)) && (pv1.cpMover - x.p.cpMover) <= budgetCp)
                    .map(x => {
                        const res = scoreHumanIntent(x.p, x.idx + 1, cp);
                        const cpLoss = Math.max(0, pv1.cpMover - x.p.cpMover);
                        return { p: x.p, idx: x.idx, ...res, cpLoss };
                    });

                const hasCleanAlt = cands.some(c => c.idx > 0 && c.feat.score >= -10);
                const lossSlope = isHighTier ? 1.20 : 0.65;
                cands.forEach(c => {
                    const effLoss = Math.max(0, c.cpLoss - (isHighTier ? 5 : 10));
                    const top1Adj = (c.idx === 0 && hasCleanAlt && top1Excess > 0) ? -(top1Excess * (isHighTier ? 45 : 110) + (isHighTier ? 4 : 10)) : 0;
                    const altFloorPenalty = (c.idx > 0 && c.feat.score < -10) ? -22 : 0;
                    c.utility = c.h + top1Adj + altFloorPenalty - effLoss * lossSlope;
                });

                if (cands.length > 1) {
                    const tempBase = Math.max(6, preset.temp || 14);
                    const temp = landscape.cliffType === "OPEN_CROSSROADS" ? tempBase * 1.28 : tempBase;
                    const maxU = Math.max(...cands.map(c => c.utility));
                    const weights = cands.map(c => Math.exp((c.utility - maxU) / temp));
                    const sumW = weights.reduce((a, b) => a + b, 0);
                    let r = Math.random() * sumW;
                    let pick = cands[0];
                    for (let i = 0; i < cands.length; i++) {
                        r -= weights[i];
                        if (r <= 0) { pick = cands[i]; break; }
                    }
                    chosenObj = pick.p;
                    chosenMove = pick.p.move || bestMove;
                    chosenInv = pick.inv;
                } else if (cands.length === 1) {
                    chosenInv = cands[0].inv;
                }
            }

            const finalFeat = analyzeMoveFeatures(chosenMove, b64, side, state.oppLastTo);
            if (chosenMove === pv1.move && (finalFeat.givesCheck || finalFeat.nearEnemyKing || finalFeat.isSacrifice)) {
                state.humanMomentum = Math.min(1.0, mom + 0.42);
                state.momentumStreak = streak + 1;
            } else {
                state.humanMomentum = mom;
                state.momentumStreak = Math.max(0, streak - 1);
            }

            state.nonForcedCount = (state.nonForcedCount || 0) + 1;
            if (chosenMove === pv1.move) state.top1Count = (state.top1Count || 0) + 1;
        } else if (pv1) {
            chosenInv = computeDepthInversion(chosenMove, 1, pv1.cpMover, tr);
        }

        const chosenFeat = analyzeMoveFeatures(chosenMove, b64, side, state.oppLastTo);

        const actualThinkMs = performance.now() - state.analysisStartTime;
        const pvArr = chosenObj?.pv ? chosenObj.pv.split(" ") : null;
        const deviatedFromPlan = tr.onPlannedLine && tr.plannedReply && chosenMove.slice(0, 4) !== tr.plannedReply.slice(0, 4);
        if (pvArr && pvArr.length >= 3 && (tr.isTank || actualThinkMs >= 550 || chosenFeat.givesCheck || chosenFeat.isCapture || deviatedFromPlan)) {
            state.plannedPV = pvArr.slice(1);
        } else if (!tr.onPlannedLine || deviatedFromPlan || !state.plannedPV || state.plannedPV.length < 2) {
            state.plannedPV = [];
        }

        const ctx = computeCognitiveContext(chosenMove, chosenObj, chosenFeat, landscape, affect, tr);
        const targetTotalMs = computeHumanTiming(
            chosenMove, chosenObj, chosenFeat, chosenInv,
            landscape, affect, oppProfile, ctx, tr, myMs, incMs, panic
        );

        const currWhiteCp = chosenObj ? (side === "w" ? chosenObj.cpMover : -chosenObj.cpMover) : null;
        state.lastOurTo = chosenMove.slice(2, 4);
        state.lastExpectedWhiteCp = currWhiteCp;

        return { move: chosenMove, pvObj: chosenObj, targetTotalMs };
    }

    function pickMaiaCandidate(cands, temp, topP = 0.95) {
        if (!Array.isArray(cands) || !cands.length) return null;
        if (!temp || temp <= 0.05) return cands[0];
        let pool = cands;
        if (typeof topP === "number" && topP > 0 && topP < 1.0) {
            let acc = 0;
            pool = [];
            for (const c of cands) {
                pool.push(c);
                acc += (c.probability || 0);
                if (acc >= topP) break;
            }
        }
        if (!pool.length) pool = cands;
        const invT = 1 / Math.max(0.05, temp);
        const weights = pool.map(c => Math.pow(Math.max(1e-7, c.probability || 0), invT));
        const sum = weights.reduce((a, b) => a + b, 0) || 1;
        let r = Math.random() * sum;
        for (let i = 0; i < pool.length; i++) {
            r -= weights[i];
            if (r <= 0) return pool[i];
        }
        return pool[0];
    }

    function handleLocalMessage(e) {
        if (e.data && typeof e.data === "object") {
            const d = e.data;
            const m = getEngineById(settings.localModelId);
            if (d.type === "gm_fetch") {
                const worker = state.localEngine;
                const db = worker?._maiaDb || null;
                const isOnnx = d.url.includes(".onnx");
                const onnxKey = (worker?._maiaModel?.cacheKey || m.cacheKey) + "_onnx";
                const replyBuf = (buf, status = 200) => {
                    if (!worker || state.localEngine !== worker) return;
                    const ab = (buf instanceof Uint8Array) ? buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) : buf;
                    worker.postMessage({ type: "gm_fetch_res", id: d.id, ok: true, status, buffer: ab }, [ab]);
                };
                const fetchRemote = () => {
                    xhrBinary(d.url,
                        (bytes) => {
                            if (db && isOnnx) writeCache(db, onnxKey, bytes);
                            replyBuf(bytes, 200);
                        },
                        (err) => {
                            if (worker && state.localEngine === worker) worker.postMessage({ type: "gm_fetch_res", id: d.id, ok: false, error: err?.message || "Fetch error" });
                        },
                        isOnnx ? (pct, txt) => { if (state.localEngine === worker) updateProgressUI(pct, `Downloading ${getActiveModelTitle()}`, txt); } : null
                    );
                };
                if (db && isOnnx) {
                    readCache(db, onnxKey, (_, cached) => {
                        if (cached) {
                            updateProgressUI(92, "Found ONNX in IndexedDB", "Loading cached weights...");
                            replyBuf(cached, 200);
                        } else {
                            fetchRemote();
                        }
                    });
                } else {
                    fetchRemote();
                }
                return;
            }
            if (d.type === "progress") {
                if (d.total > 0) {
                    const pct = Math.min(99, Math.round((d.loaded / d.total) * 100));
                    const loadedMB = (d.loaded / 1048576).toFixed(2);
                    const totalMB = (d.total / 1048576).toFixed(2);
                    updateProgressUI(pct, `Loading ${getActiveModelTitle()}`, `${loadedMB}/${totalMB} MB (${pct}%)`);
                }
                return;
            }
            if (d.type === "ready") {
                if (_engineInitTimer) { clearTimeout(_engineInitTimer); _engineInitTimer = null; }
                revokeEngineBlobUrls();
                setEngineStatus("ready", "");
                state.lastMoveResult = formatMoveResult(getActiveModelTitle(), `Elo ${settings.localMaiaElo}`, "Ready");
                updateUI();
                if (state.pendingFen) {
                    const pFen = state.pendingFen;
                    state.pendingFen = null;
                    state.pendingDepth = null;
                    state.isThinking = true;
                    state.analysisStartTime = performance.now();
                    analyzeLocal(pFen, 1);
                }
                return;
            }
            if (d.type === "error") {
                if (d.isGrade) return;
                if (_engineInitTimer) { clearTimeout(_engineInitTimer); _engineInitTimer = null; }
                state.isThinking = false;
                state.pendingManualMove = false;
                handleError("Maia-3 Error", d.message || "Worker error");
                if (!d.reqId) {
                    setEngineStatus("error", d.message);
                    state.localEngine = null;
                    state.engineLoadingInProgress = false;
                }
                updateUI();
                updateLocalSettingsUI();
                return;
            }
            if (d.type === "result") {
                if (d.isGrade) {
                    if (d.reqId !== state._maiaGradeReqId || !state._maiaGradeFen) return;
                    const gRes = d.result || {};
                    const gWin = (typeof gRes.winProbability === "number") ? gRes.winProbability : 0.5;
                    const gSide = (state._maiaGradeFen.split(" ")[1] || "w");
                    const gpW = Math.min(0.99, Math.max(0.01, gSide === "b" ? (1 - gWin) : gWin));
                    const gEvalW = (-Math.log(1 / gpW - 1) / 0.368208).toFixed(2);
                    recordGradeSnapshot(state._maiaGradeFen, {
                        bestMove: gRes.bestMove || gRes.candidates?.[0]?.uci || null,
                        evalWhite: gEvalW,
                        mate: null,
                        pv: gRes.bestMove ? [gRes.bestMove] : []
                    });
                    return;
                }
                if (d.reqId !== state._maiaReqId) return;
                if (state._maiaSentFen && state._maiaSentFen !== state.lastSentFEN) return;
                state.isThinking = false;
                const res = d.result || {};
                const cands = Array.isArray(res.candidates) ? res.candidates : [];
                const picked = pickMaiaCandidate(cands, settings.localMaiaTemp, settings.localMaiaTopP) || (res.bestMove ? { uci: res.bestMove, probability: 1 } : null);
                const chosenMove = picked?.uci || res.bestMove;
                if (!chosenMove) {
                    state.lastMoveResult = formatMoveResult(getActiveModelTitle(), "Done", "None");
                    updateUI();
                    return;
                }
                const sideToMove = (state.lastSentFEN?.split(" ")[1]) || "w";
                let winMover = (typeof res.winProbability === "number") ? res.winProbability : 0.5;
                if (picked?.wdl && typeof picked.wdl.win === "number") {
                    winMover = picked.wdl.win + 0.5 * (picked.wdl.draw || 0);
                }
                const pWhite = Math.min(0.99, Math.max(0.01, sideToMove === "b" ? (1 - winMover) : winMover));
                const evalWhitePawns = (-Math.log(1 / pWhite - 1) / 0.368208).toFixed(2);
                const duration = ((performance.now() - state.analysisStartTime) / 1000).toFixed(2);

                if (settings.humanMode) {
                    const tr = state.searchTrace || {};
                    const b64 = tr.b64 || fenToBoard64(state.lastSentFEN);
                    const feat = analyzeMoveFeatures(chosenMove, b64, sideToMove, state.oppLastTo);
                    const clocks = state._maiaClocks;
                    const myMs = clocks ? (sideToMove === "w" ? clocks.wMs : clocks.bMs) : 60000;
                    const oppMs = clocks ? (sideToMove === "w" ? clocks.bMs : clocks.wMs) : 60000;
                    const incMs = clocks ? clocks.incMs : 0;
                    const panic = 1 / (1 + Math.exp(((myMs + incMs * 16) - 16000) / 5500));
                    const cpWhite = Math.round(parseFloat(evalWhitePawns) * 100);
                    const cpMover = sideToMove === "w" ? cpWhite : -cpWhite;
                    const chosenObj = { depth: 1, seldepth: 1, type: "cp", rawVal: cpMover, whiteVal: cpWhite, cpMover, move: chosenMove };
                    const landscape = computePositionLandscape({ 1: chosenObj }, tr);
                    const oppProfile = computeOpponentFingerprint();
                    const affect = {
                        bailoutShock: false, blunderGain: 0, missedWinTilt: false,
                        conversionBias: cpMover >= 180,
                        flagMode: ((myMs - oppMs) >= 20000 && oppMs <= 25000 && cpMover >= -180)
                    };
                    const ctx = computeCognitiveContext(chosenMove, chosenObj, feat, landscape, affect, tr);
                    const targetTotalMs = computeHumanTiming(
                        chosenMove, chosenObj, feat, { shallowRank: 1, rankJump: 0, cpGainFromShallow: 0, isHiddenEngineTactic: false, isPoisonedTrap: false },
                        landscape, affect, oppProfile, ctx, tr, myMs, incMs, panic
                    );
                    state.lastOurTo = chosenMove.slice(2, 4);
                    state.lastExpectedWhiteCp = cpWhite;
                    state.moveTargetTime = state.analysisStartTime + targetTotalMs;
                    state.calculatedDelay = (Math.max(0, state.moveTargetTime - performance.now()) / 1000).toFixed(2);
                }

                state.lastCandidates = [];
                if (settings.showMultiBest) {
                    requestMaiaCandEval(state.lastSentFEN, cands.slice(0, 3).map(c => c.uci));
                }
                const probPct = picked?.probability ? Math.round(picked.probability * 100) : null;
                const candSummary = cands.slice(0, 4).map(c => `${c.uci} (${Math.round((c.probability || 0) * 100)}%)`).join(" · ") || chosenMove;
                processBestMove(chosenMove, evalWhitePawns, null, [chosenMove], winMover * 100, duration, null, true);
                state.lastMoveResult = formatMoveResult(getActiveModelTitle(), `Elo ${settings.localMaiaElo}${probPct !== null ? ` · ${probPct}%` : ""}`, chosenMove);
                const statusData = getEvalStatusData(parseFloat(evalWhitePawns), false);
                const scoreTxt = (parseFloat(evalWhitePawns) > 0 ? "+" : "") + evalWhitePawns;
                if (!(settings.moveGrading && state.graderReady)) {
                    state.hudEvalTxt = scoreTxt;
                    state.hudStatus = statusData;
                }
                state.hudMove = chosenMove;
                state.lastLiveResult = formatLiveResult(scoreTxt, statusData, `(${duration}s)`, candSummary);
                updateUI();
                if (settings.moveGrading) pumpGraderQueue();
            }
            return;
        }
        const msg = typeof e.data === "string" ? e.data : (e.data?.toString ? e.data.toString() : null);
        if (!msg || typeof msg !== "string") return;

        if (msg.startsWith("worker_err:")) {
            const errDetail = msg.substring(11);
            console.error("[Engine Worker Internal Error]", errDetail);
            if (state._searchCapTimer) { clearTimeout(state._searchCapTimer); state._searchCapTimer = null; }
            state.searchTrace = null;
            state.isLocalSearching = false;
            state.isThinking = false;
            setEngineStatus("error", errDetail);
            state.lastMoveResult = "❌ Engine Error: " + errDetail;
            state.localEngine = null;
            state.engineLoadingInProgress = false;
            updateUI();
            updateLocalSettingsUI();
            return;
        }


        if (msg === "uciok" || msg.startsWith("uciok") || msg === "readyok") {
            if (_engineInitTimer) { clearTimeout(_engineInitTimer); _engineInitTimer = null; }
            if (state.engineStatus !== "ready") {
                state.isLocalSearching = false;
                state.ignoreLocalBestMoves = 0;
                revokeEngineBlobUrls();
                setEngineStatus("ready", "");
                state.lastMoveResult = formatMoveResult(getActiveModelTitle(), "Ready", "--");
                updateUI();
                if (state.pendingFen) {
                    const pFen = state.pendingFen;
                    const pDepth = state.pendingDepth || settings.depth;
                    state.pendingFen = null;
                    state.pendingDepth = null;
                    state.isThinking = true;
                    state.analysisStartTime = performance.now();
                    analyzeLocal(pFen, pDepth);
                }
            }
            return;
        }

        if (msg.startsWith("info") && msg.includes("depth") && msg.includes("score")) {
            const depthMatch = msg.match(/depth (\d+)/);
            const scoreMatch = msg.match(/score (cp|mate) (-?\d+)/);
            const pvMatch = msg.match(/ pv (.*)/);
            const mpvMatch = msg.match(/ multipv (\d+)/);
            const pvIdx = mpvMatch ? parseInt(mpvMatch[1], 10) : 1;

            if (depthMatch && scoreMatch) {
                const depth = depthMatch[1];
                const rawVal = parseInt(scoreMatch[2], 10);
                const type = scoreMatch[1];
                const pv = pvMatch ? pvMatch[1].trim() : "";
                const cpMover = (type === "mate")
                    ? (rawVal > 0 ? 30000 - rawVal * 100 : -30000 - rawVal * 100)
                    : rawVal;

                let whiteVal = rawVal;
                const fenParts = state.lastSentFEN ? state.lastSentFEN.split(" ") : [];
                const sideToMove = fenParts.length > 1 ? fenParts[1] : "w";
                if (sideToMove === "b") whiteVal = -whiteVal;

                const dNum = parseInt(depth, 10);
                const firstMove = pv ? pv.split(" ")[0] : null;
                const isBound = msg.includes("upperbound") || msg.includes("lowerbound");
                const headerPart = pvMatch ? msg.slice(0, pvMatch.index) : msg;
                const selM = headerPart.match(/\bseldepth (\d+)/);
                const wdlM = headerPart.match(/\bwdl (\d+) (\d+) (\d+)/);
                const nodesM = headerPart.match(/\bnodes (\d+)/);
                const selD = selM ? parseInt(selM[1], 10) : dNum;
                const wdlArr = wdlM ? [parseInt(wdlM[1], 10), parseInt(wdlM[2], 10), parseInt(wdlM[3], 10)] : null;
                const nodesVal = nodesM ? parseInt(nodesM[1], 10) : null;

                const pvEntry = {
                    depth: dNum,
                    seldepth: selD,
                    type,
                    rawVal,
                    whiteVal,
                    cpMover,
                    wdl: wdlArr,
                    nodes: nodesVal,
                    pv,
                    move: firstMove
                };

                if (!state.localMultiPV) state.localMultiPV = {};
                if (!isBound) state.localMultiPV[pvIdx] = pvEntry;

                const tr = state.searchTrace;
                if (tr && tr.phase === "deep" && !isBound && firstMove) {
                    if (!tr.snapshotsByDepth[dNum]) tr.snapshotsByDepth[dNum] = {};
                    tr.snapshotsByDepth[dNum][pvIdx] = pvEntry;

                    if (pvIdx === 1) {
                        let prevMove = null;
                        for (let k = dNum - 1; k >= 1; k--) {
                            if (tr.movesByDepth[k]) { prevMove = tr.movesByDepth[k]; break; }
                        }
                        if (prevMove && prevMove !== firstMove) {
                            tr.flipCount++;
                            tr.lastFlipDepth = dNum;
                        }
                        const prevEval = tr.evalByDepth[dNum - 1];
                        const evalDelta = (typeof prevEval === "number") ? Math.abs(cpMover - prevEval) : 0;
                        const flipAdd = (prevMove && prevMove !== firstMove) ? 35 : 0;
                        tr.volatilityIntegral = (tr.volatilityIntegral || 0) + dNum * (flipAdd + Math.min(200, evalDelta)) * 0.08;

                        tr.movesByDepth[dNum] = firstMove;
                        tr.evalByDepth[dNum] = cpMover;
                        tr.seldepthByDepth[dNum] = selD;
                        if (nodesVal !== null) tr.nodesByDepth[dNum] = nodesVal;
                        if (wdlArr) tr.wdlByDepth[dNum] = wdlArr;
                        tr.lastCompletedDepth = dNum;

                        const refEval = tr.evalByDepth[Math.max(1, dNum - 3)];
                        if (typeof refEval === "number") {
                            tr.maxEvalSwing = Math.max(tr.maxEvalSwing, Math.abs(cpMover - refEval));
                        }
                    }

                    const mpv1Now = state.localMultiPV?.[1];
                    if (settings.humanMode && settings.autoTimeMgmt && !tr.stopSent &&
                        mpv1Now && mpv1Now.type === "mate" && mpv1Now.rawVal === 1 && dNum >= 4) {
                        tr.stopSent = true;
                        tr.isTank = false;
                        tr.tier = "quick";
                        if (state._searchCapTimer) { clearTimeout(state._searchCapTimer); state._searchCapTimer = null; }
                        state.localEngine.postMessage("stop");
                    }

                    // Live controller: brisk on routine/planned moves, upgrades to a real Tank on turning points
                    if (settings.humanMode && settings.autoTimeMgmt && !tr.stopSent &&
                        tr.lastCompletedDepth === dNum && pvIdx >= (tr.expectedMultiPV || 1)) {
                        let streak = 1;
                        const curM = tr.movesByDepth[dNum];
                        for (let k = dNum - 1; k >= 1; k--) {
                            if (tr.movesByDepth[k] === curM) streak++;
                            else if (tr.movesByDepth[k]) break;
                        }
                        const baseD = tr.baseStopD || 15;
                        const hardD = tr.hardStopD || 19;
                        const selGap = (tr.seldepthByDepth[dNum] || dNum) - dNum;

                        const mpv1 = state.localMultiPV?.[1];
                        const mpv2 = state.localMultiPV?.[2];
                        const liveGap12 = (mpv2 && mpv2.depth === dNum && mpv1)
                            ? (mpv1.cpMover - mpv2.cpMover) : 0;
                        const liveWhiteCp = mpv1 ? (sideToMove === "w" ? mpv1.cpMover : -mpv1.cpMover) : null;
                        const liveSurpriseEval = (liveWhiteCp !== null && typeof state.lastExpectedWhiteCp === "number")
                            ? Math.abs(liveWhiteCp - state.lastExpectedWhiteCp) : 0;

                        const pv1MateVal = (mpv1 && mpv1.type === "mate") ? mpv1.rawVal : 0;
                        const isFastMate = (pv1MateVal >= 1 && pv1MateVal <= 2);
                        const isAlreadyCrushing = mpv1 && (mpv1.cpMover >= 350 || mpv1.cpMover <= -450);
                        const mpv3 = state.localMultiPV?.[3];
                        const isStrategicCrossroads = Boolean(
                            mpv1 && mpv3 && mpv3.depth === dNum &&
                            dNum >= 11 && tr.ply >= 16 &&
                            (tr.ply - (state.lastTankPly ?? -16)) >= 16 &&
                            Math.abs(mpv1.cpMover) <= 185 &&
                            (mpv1.cpMover - mpv3.cpMover) <= 22 &&
                            Math.random() < 0.35
                        );

                        // Upgrade to a real deep Human Tank on genuine turning points or strategic crossroads (NEVER on M1/M2 or +3.5 wins!)
                        if (!isFastMate && !isAlreadyCrushing && !tr.isTank && tr.canTank && (tr.legalCount > 2 || liveGap12 >= 120) && dNum >= 10 && (
                            (tr.surpriseBase || 0) >= 0.65 ||
                            liveSurpriseEval >= 70 ||
                            tr.lastFlipDepth >= 9 ||
                            tr.maxEvalSwing >= 75 ||
                            selGap >= 10 ||
                            liveGap12 >= 95 ||
                            (tr.oppDeviated && selGap >= 6) ||
                            (pv1MateVal >= 4) ||
                            isStrategicCrossroads
                        )) {
                            tr.isTank = true;
                            tr.tier = "volatile";
                            if (tr.armStopTimer && tr.tankCapMs) tr.armStopTimer(tr.tankCapMs);
                        }

                        if (isFastMate && dNum >= 6) {
                            tr.stopSent = true;
                            tr.isTank = false;
                            tr.tier = "quick";
                            if (state._searchCapTimer) { clearTimeout(state._searchCapTimer); state._searchCapTimer = null; }
                            state.localEngine.postMessage("stop");
                        } else if (tr.isTank) {
                            // Respect hard ceiling (<=17-19 midgame, <=22 endgame)
                            if (dNum >= (tr.tankMaxD || 18) || (dNum >= baseD + 3 && streak >= 6)) {
                                tr.stopSent = true;
                                if (state._searchCapTimer) { clearTimeout(state._searchCapTimer); state._searchCapTimer = null; }
                                state.localEngine.postMessage("stop");
                            }
                        } else {
                            const qFeat = analyzeMoveFeatures(curM, tr.b64, tr.side, state.oppLastTo);
                            const weirdSurprise = !tr.onPlannedLine && !qFeat.isRecapture && (liveSurpriseEval >= 70 || (tr.oppDeviated && selGap >= 6));
                            const isQuickFeature = !weirdSurprise && (
                                qFeat.isRecapture ||
                                (qFeat.isFreeCapture && Math.abs(liveGap12) < 50 && !tr.oppDeviated) ||
                                (tr.legalCount <= 2) ||
                                (tr.openingFactor > 0.35 && (qFeat.isCastling || qFeat.isCenterDev))
                            );
                            const isQuietStable = !weirdSurprise && tr.flipCount === 0 && tr.maxEvalSwing < 30 && selGap < 7 && !tr.oppGaveCheck && !qFeat.isSacrifice;
                            const isPlannedMatch = tr.onPlannedLine && tr.plannedReply && curM.slice(0, 4) === tr.plannedReply.slice(0, 4) && tr.maxEvalSwing < 80 &&
                                (qFeat.isCapture || qFeat.givesCheck || qFeat.isRecapture || ((tr.boardGeom?.tensionPairs || 0) < 2 && Math.abs(liveGap12) < 50));

                            let shouldStop = false;
                            let tier = "deliberate";

                            if (tr.legalCount <= 1 && dNum >= 4) {
                                shouldStop = true;
                                tier = "quick";
                            } else if (tr.ply <= 6 && !tr.oppDeviated && liveSurpriseEval < 65 && dNum >= 7) {
                                shouldStop = true;
                                tier = "quick";
                            } else if (isPlannedMatch && dNum >= 6) {
                                shouldStop = true;
                                tier = "quick";
                            } else if (qFeat.isRecapture && !weirdSurprise && liveGap12 >= 90 && dNum >= 7) {
                                shouldStop = true;
                                tier = "quick";
                            } else if ((isQuickFeature || (isQuietStable && liveGap12 < 50)) && dNum >= (tr.quickStopD || 10)) {
                                shouldStop = true;
                                tier = "quick";
                            } else if (dNum >= hardD) {
                                shouldStop = true;
                                tier = tr.lastFlipDepth >= baseD ? "volatile" : "deliberate";
                            } else if (tr.lastFlipDepth <= 2 && streak >= Math.max(4, baseD - 3) && tr.maxEvalSwing < 65 && selGap < 9) {
                                if (dNum >= baseD) { shouldStop = true; tier = "settled_early"; }
                            } else if (tr.lastFlipDepth <= 5 && streak >= Math.max(4, baseD - 5) && tr.maxEvalSwing < 90) {
                                if (dNum >= baseD) { shouldStop = true; tier = "settled_early"; }
                            } else if (streak >= 4 && dNum >= baseD + 1) {
                                shouldStop = true;
                                tier = "deliberate";
                            }

                            if (shouldStop) {
                                tr.stopSent = true;
                                tr.tier = tier;
                                if (state._searchCapTimer) { clearTimeout(state._searchCapTimer); state._searchCapTimer = null; }
                                state.localEngine.postMessage("stop");
                            }
                        }
                    }
                }

                if (pvIdx === 1 && (!tr || tr.phase === "deep")) {
                    if (type === "mate") { state.localMate = whiteVal; state.localEval = null; }
                    else { state.localMate = null; state.localEval = (whiteVal / 100).toFixed(2); }
                    state.localPV = pv; state.localDepth = depth;
                    if (pv) state.currentPV = pv.split(" ");
                    if (!(settings.moveGrading && state.graderReady)) {
                        EvalBar.update(type === "mate" ? null : parseFloat(state.localEval), type === "mate" ? whiteVal : null);
                    }
                    let scoreTxt;
                    if (type === "mate") { scoreTxt = "M" + Math.abs(whiteVal); if (whiteVal < 0) scoreTxt = "-" + scoreTxt; }
                    else { scoreTxt = (whiteVal > 0 ? "+" : "") + (whiteVal / 100).toFixed(2); }
                    const evalVal = type === "mate" ? whiteVal : parseFloat(state.localEval);
                    const statusData = getEvalStatusData(evalVal, type === "mate");
                    const duration = ((performance.now() - state.analysisStartTime) / 1000).toFixed(2);
                    if (!(settings.moveGrading && state.graderReady)) {
                        state.hudEvalTxt = scoreTxt;
                        state.hudStatus = statusData;
                    }
                    if (pv) {
                        const best = pv.split(" ")[0];
                        state.hudMove = best;
                        Visuals.add(best, 'analysis');
                        PV.update(state.currentPV);
                        state.lastMoveResult = formatMoveResult(getActiveModelTitle(), `D${depth}`, best);
                    }
                    const pvStr = pv ? pv.split(" ").slice(0, 10).join(" ") : "None";
                    state.lastLiveResult = formatLiveResult(scoreTxt, statusData, `(${duration}s)`, pvStr);
                    updateUI();
                }
            }
        }
        if (msg.startsWith("bestmove")) {
            if (state.ignoreLocalBestMoves > 0) {
                state.ignoreLocalBestMoves--;
                return;
            }
            if (state._searchCapTimer) { clearTimeout(state._searchCapTimer); state._searchCapTimer = null; }
            state.isLocalSearching = false;
            state.isThinking = false;
            const parts = msg.split(" ");
            const bestMove = parts[1];
            if (bestMove && bestMove !== "(none)") {
                let chosenMove = bestMove;
                let chosenEval = state.localEval;
                let chosenMate = state.localMate;
                let chosenPV = state.localPV ? state.localPV.split(" ") : null;

                if (settings.humanMode) {
                    const decision = computeHumanGradientDecision(bestMove, state.localMultiPV, state.lastSentFEN, state.localStartClocks);
                    chosenMove = decision.move;
                    if (decision.pvObj) {
                        chosenMate = decision.pvObj.type === "mate" ? decision.pvObj.whiteVal : null;
                        chosenEval = decision.pvObj.type === "mate" ? null : (decision.pvObj.whiteVal / 100).toFixed(2);
                        if (decision.pvObj.pv) chosenPV = decision.pvObj.pv.split(" ");
                    }
                    state.moveTargetTime = state.analysisStartTime + decision.targetTotalMs;
                    const remWait = Math.max(0, state.moveTargetTime - performance.now());
                    state.calculatedDelay = (remWait / 1000).toFixed(2);
                } else if (settings.engineFocus && settings.engineFocus !== "balanced") {
                    const pickedFocus = pickFocusMove(bestMove, state.localMultiPV, state.lastSentFEN);
                    if (pickedFocus && pickedFocus.move) {
                        chosenMove = pickedFocus.move;
                        chosenMate = pickedFocus.type === "mate" ? pickedFocus.whiteVal : null;
                        chosenEval = pickedFocus.type === "mate" ? null : (pickedFocus.whiteVal / 100).toFixed(2);
                        if (pickedFocus.pv) chosenPV = pickedFocus.pv.split(" ");
                    }
                }
                state.lastCandidates = buildCandidatesFromMultiPV(state.localMultiPV, state.lastSentFEN);

                const duration = ((performance.now() - state.analysisStartTime) / 1000).toFixed(2);
                processBestMove(chosenMove, chosenEval, chosenMate, chosenPV, null, duration, state.localDepth, true);
            } else {
                state.lastMoveResult = formatMoveResult(getActiveModelTitle(), "Done", "None");
            }
            updateUI();
            if (settings.moveGrading) pumpGraderQueue();
        }
    }

    function getActiveModelTitle() {
        if (settings.engineMode === "local") {
            const m = LOCAL_ENGINES.find(e => e.id === (settings.localModelId || "sf19_lite"));
            return m ? m.label.replace(/\s*\(.*\)/, "").trim() : "Stockfish Local";
        } else if (settings.engineMode === "cloud") {
            return "Stockfish Cloud";
        } else if (settings.engineMode === "sfonline") {
            return "Stockfish Online";
        }
        return "Stockfish";
    }


    function formatMoveResult(activeTitle, statusText, moveText) {
        return `
            <div style="display:flex; justify-content:space-between; align-items:center; gap:8px; height:16px; min-height:16px; max-height:16px; overflow:hidden;">
                <span style="font-size:10px; color:#58a6ff; font-weight:700; letter-spacing:0.04em; text-transform:uppercase; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; min-width:0;">${activeTitle}</span>
                <span style="font-size:11px; color:#8b949e; font-family:monospace; font-variant-numeric:tabular-nums; white-space:nowrap; flex-shrink:0;">${statusText}</span>
            </div>
            <div style="font-size:20px; font-weight:800; color:var(--bot-primary); letter-spacing:0.04em; margin-top:2px; height:24px; min-height:24px; max-height:24px; line-height:24px; font-family:ui-monospace, SFMono-Regular, Menlo, monospace; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
                ${moveText}
            </div>
        `;
    }

    function formatLiveResult(scoreTxt, statusData, durHtml, pvStr) {
        return `
            <div style="display:flex; justify-content:space-between; align-items:center; gap:8px; height:24px; min-height:24px; max-height:24px; overflow:hidden;">
                <div style="display:flex; align-items:center; gap:8px; min-width:0; overflow:hidden;">
                    <span class="score-pill">${scoreTxt}</span>
                    <span style="font-size:12px; color:${statusData.color}; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; min-width:0;">${statusData.text}</span>
                </div>
                <span style="font-size:11px; color:#8b949e; font-variant-numeric:tabular-nums; white-space:nowrap; flex-shrink:0;">${durHtml}</span>
            </div>
            <div style="margin-top:2px; height:18px; min-height:18px; max-height:18px; line-height:18px; font-size:11px; color:#8b949e; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-family:ui-monospace, SFMono-Regular, Menlo, monospace;">
                <span style="color:#6e7681; font-weight:600;">Best line:</span> ${pvStr}
            </div>
        `;
    }

    function updateCalculatedDelay() {
        const min = Math.max(0, parseFloat(settings.minDelay) || 0);
        const max = Math.max(min, parseFloat(settings.maxDelay) || 0);
        if (min === 0 && max === 0) {
            state.calculatedDelay = "0.0";
            if (state.ui.delayDisplay) state.ui.delayDisplay.innerText = "Delay: 0.0s (Instant)";
        } else {
            const d = (Math.random() * (max - min) + min).toFixed(2);
            state.calculatedDelay = d;
            if (state.ui.delayDisplay) state.ui.delayDisplay.innerText = `Next delay: ${d}s`;
        }
    }

    function processBestMove(bestMove, evalScore, mate, continuationArr, winChance, duration, depth = null, isFinal = false) {
        state.currentBestMove = bestMove;
        state.currentPV = continuationArr || (bestMove ? [bestMove] : []);
        if (isFinal || !state.isThinking) Visuals.add(bestMove, 'bestmove');
        else Visuals.add(bestMove, 'analysis');
        if (settings.showPVArrows) PV.update(state.currentPV);
        else PV.clear();
        if (settings.showMultiBest && state.lastCandidates?.length) MultiBest.update(state.lastCandidates, state.lastSentFEN);
        else MultiBest.clear();
        const evalNum = (evalScore !== null && evalScore !== undefined) ? parseFloat(evalScore) : null;
        const mateNum = (mate !== null && mate !== undefined && mate !== 0) ? parseInt(mate) : null;
        if (!(settings.moveGrading && state.graderReady)) {
            EvalBar.update(evalNum, mateNum);
        }
        let scoreTxt = "0.0", pvStr = "None", numericValForStatus = 0, isMate = false;
        if (mateNum !== null) {
            isMate = true; numericValForStatus = mateNum;
            scoreTxt = `M${Math.abs(mateNum)}`; if (mateNum < 0) scoreTxt = "-" + scoreTxt;
        } else if (evalNum !== null && !Number.isNaN(evalNum)) {
            numericValForStatus = evalNum;
            scoreTxt = (evalNum > 0 ? "+" : "") + evalNum;
        }
        if (continuationArr && continuationArr.length) pvStr = continuationArr.slice(0, 10).join(" ");
        const statusData = getEvalStatusData(numericValForStatus, isMate);
        const durHtml = duration ? `(${duration}s)` : "";
        state.lastConcludedDepth = depth || null;
        let wcHtml = "";
        if (depth && winChance) wcHtml = `Depth ${depth} · ${Math.round(winChance)}%`;
        else if (depth) wcHtml = `Depth ${depth}${duration ? ` · ${duration}s` : ""}`;
        else if (winChance) wcHtml = `${Math.round(winChance)}% win`;

        const activeTitle = getActiveModelTitle();
        if (!(settings.moveGrading && state.graderReady)) {
            state.hudEvalTxt = scoreTxt;
            state.hudStatus = statusData;
        }
        state.hudMove = bestMove || "--";
        state.lastMoveResult = formatMoveResult(activeTitle, wcHtml, bestMove || "--");
        state.lastLiveResult = formatLiveResult(scoreTxt, statusData, durHtml, pvStr);

        const minMsFloor = Math.max(0, (parseFloat(settings.minDelay) || 0) * 1000);
        if (!settings.humanMode) {
            state.moveTargetTime = performance.now() + (state._chosenDelayMs || 0);
            state.calculatedDelay = ((state._chosenDelayMs || 0) / 1000).toFixed(2);
        } else if (minMsFloor > 0) {
            state.moveTargetTime = Math.max(state.moveTargetTime, performance.now() + minMsFloor);
            state.calculatedDelay = (Math.max(0, state.moveTargetTime - performance.now()) / 1000).toFixed(2);
        }

        if (settings.autoMove) {
            state.pendingManualMove = false;
            triggerAutoMove();
        } else if (state.pendingManualMove) {
            state.pendingManualMove = false;
            const game = getActiveGame();
            if (game && isUserTurn(game) && state.currentBestMove) playMove(state.currentBestMove);
        }
    }

    function isUserTurn(game) {
        if (!game || state.isBrowsingHistory) return false;
        if (typeof game.isViewingLive === "function" && !game.isViewingLive()) return false;
        let playingAs = null;
        let turn = null;
        try {
            if (typeof game.getPlayingAs === "function") playingAs = game.getPlayingAs();
            if (typeof game.getTurn === "function") turn = game.getTurn();
        } catch (_) { return false; }

        const norm = (v) => {
            if (v === 1 || v === "w" || v === "white") return 1;
            if (v === 2 || v === "b" || v === "black") return 2;
            return null;
        };
        const pNorm = norm(playingAs);
        const tNorm = norm(turn);

        // If player has no assigned playing seat (not in a game, spectator, or waiting screen)
        if (pNorm === null || tNorm === null) return false;
        if (typeof game.isPlaying === "function" && !game.isPlaying()) return false;
        if (typeof game.isGameOver === "function" && game.isGameOver()) return false;

        const gameOverEl = document.querySelector(".game-result-component, .game-over-modal-content, .daily-game-footer-game-over, .result-wrap");
        if (gameOverEl) return false;

        return pNorm === tNorm;
    }

    function triggerAutoMove() {
        const game = getActiveGame();
        if (!settings.autoMove || !state.currentBestMove || !game || !isUserTurn(game)) return;
        const expectedMove = state.currentBestMove;
        const expectedFen = state.lastSentFEN;
        const wait = Math.max(0, state.moveTargetTime - performance.now());
        setTimeout(() => {
            if (!settings.autoMove || !isUserTurn(game)) return;
            if (state.lastSentFEN !== expectedFen || state.currentBestMove !== expectedMove) return;
            playMove(expectedMove);
        }, wait);
    }

    function handleError(type, err) {
        state.isThinking = false;
        state.pendingManualMove = false;
        console.error(type, err);
        state.lastMoveResult = formatMoveResult(getActiveModelTitle(), "Error", "--");
        state.lastLiveResult = formatLiveResult("!", { text: type, color: "#f85149" }, "", err?.message || String(err || "Check console"));
        updateUI();
    }

    function playMove(move) {
        const game = getActiveGame();
        if (!game || !isUserTurn(game)) return;
        const from = move.substring(0, 2), to = move.substring(2, 4);
        const currentRaw = getRawBoardFEN();
        if (currentRaw && sanitizeFEN(currentRaw).split(" ")[0] !== state.lastSentFEN.split(" ")[0]) return;
        if (isCgSite()) {
            const legals = typeof game.getLegalMoves === "function" ? game.getLegalMoves() : [];
            const hasPromoChoice = legals.some(m => m.from === from && m.to === to && m.promotion);
            const promotion = hasPromoChoice ? (move.length > 4 ? move.substring(4, 5).toLowerCase() : "q") : "";
            const uci = from + to + promotion;
            const match = legals.find(m => m.from === from && m.to === to && (!promotion || m.promotion === promotion));
            if (legals.length && !match) return;
            const trySend = (attempt = 0) => {
                if (!isUserTurn(getActiveGame())) return;
                if (_wsState.liveWs && _wsState.liveWs.readyState === 1) {
                    Visuals.onMovePlayed();
                    state.currentBestMove = null;
                    state.pendingManualMove = false;
                    _wsState.ack = (_wsState.ack || 0) + 1;
                    _wsState.liveWs.send(JSON.stringify({ t: "move", d: { u: uci, a: _wsState.ack } }));
                } else if (attempt < 30) {
                    setTimeout(() => trySend(attempt + 1), 100);
                }
            };
            trySend();
            return;
        }
        if (typeof game.getLegalMoves === "function") {
            for (const m of game.getLegalMoves()) {
                if (m.from === from && m.to === to) {
                    Visuals.onMovePlayed();
                    state.currentBestMove = null;
                    state.pendingManualMove = false;
                    const promotion = move.length > 4 ? move.substring(4, 5) : "q";
                    game.move({ ...m, promotion, animate: false, userGenerated: true });
                    return;
                }
            }
        }
    }

    function toggleAutoQueue() {
        if (state.newGameObserver) { state.newGameObserver.disconnect(); state.newGameObserver = null; }
        if (state.queueTimeout) { clearTimeout(state.queueTimeout); state.queueTimeout = null; }
        if (settings.autoQueue && document.body) {
            const qDelayMs = Math.min(60, Math.max(1, parseFloat(settings.autoQueueDelay) || 2)) * 1000;
            state.newGameObserver = new MutationObserver(() => {
                if (isCgSite()) {
                    const btn = document.querySelector(".rcontrols .follow-up button.new-opponent:not(:disabled)");
                    if (btn && btn.offsetParent !== null && !state.queueTimeout && state._lastAutoQueuedPath !== location.pathname) {
                        state.queueTimeout = setTimeout(() => {
                            state._lastAutoQueuedPath = location.pathname;
                            btn.click();
                            state.queueTimeout = null;
                        }, qDelayMs);
                    }
                    return;
                }
                const gameOver = document.querySelector(".game-result-component, .game-over-modal-content, .daily-game-footer-game-over") || state.board?.game?.isGameOver?.();
                if (!gameOver) return;
                const btns = Array.from(document.querySelectorAll("button"));
                const newGameBtn = btns.find((b) => {
                    const txt = b.innerText.toLowerCase().trim();
                    return txt.includes("new") && !txt.includes("rematch") && b.offsetParent !== null;
                });
                if (newGameBtn && !state.queueTimeout) {
                    state.queueTimeout = setTimeout(() => { newGameBtn.click(); state.queueTimeout = null; }, qDelayMs);
                }
            });
            state.newGameObserver.observe(document.body, { childList: true, subtree: true });
        }
    }

    function resetSettings() {
        // 1. Clear all active visuals and native board markings
        Visuals.removeByType('bestmove');
        Visuals.removeByType('analysis');
        PV.clear();
        const board = state.board || document.querySelector(CONFIG.BOARD_SEL);
        if (board?.game?.markings) {
            try {
                if (typeof board.game.markings.removeAll === 'function') board.game.markings.removeAll();
                else if (typeof board.game.markings.clear === 'function') board.game.markings.clear();
            } catch (_) {}
        }

        // 2. Reset EvalBar, MultiBest & Move Grading
        EvalBar.reset();
        MultiBest.clear();
        destroyGraderEngine();
        state.lastUserGrade = null;
        state.lastOppGrade = null;
        state._chosenDelayMs = 0;
        state.gradeSnapshots = {};
        state.gradesByMoveKey = {};
        state.gradeTally = resetGradeTally();
        state.gradeBreakdownOpen = false;
        state.lastCandidates = [];

        // 3. Forcefully override all settings to DEFAULT_SETTINGS
        const site = getSiteKey();
        const siteDefs = getSiteDefaults();
        Object.keys(DEFAULT_SETTINGS).forEach(k => {
            const defVal = SITE_ONLY_KEYS.has(k) && siteDefs[k] !== undefined ? siteDefs[k] : DEFAULT_SETTINGS[k];
            settings[k] = defVal;
            if (MODEL_ONLY_KEYS.has(k)) {
                saveModelSetting(k, defVal, settings.localModelId);
            } else {
                const storageKey = SITE_ONLY_KEYS.has(k) ? `bot_${site}_${k}` : `bot_${k}`;
                try { GM_setValue(storageKey, defVal); } catch(_) {}
                lsSet(storageKey, defVal);
            }
        });
        if (state.localEngine && state.engineStatus === "ready" && getEngineById(settings.localModelId).format !== "onnx") {
            sendEngineInitCommands(settings.localModelId);
        }
        try { GM_setValue(`bot_${site}_menuPosition`, siteDefs.menuPosition); } catch(_) {} lsSet(`bot_${site}_menuPosition`, siteDefs.menuPosition);
        try { GM_setValue(`bot_${site}_pX`, "auto"); } catch(_) {} lsSet(`bot_${site}_pX`, "auto");
        try { GM_setValue(`bot_${site}_pY`, "0"); } catch(_) {} lsSet(`bot_${site}_pY`, "0");
        ["single", "double", "tabs"].forEach(fmt => {
            const def = siteDefs.panel[fmt] || PANEL_LAYOUT_DEFAULTS[fmt];
            try { GM_setValue(`bot_${site}_panelW_${fmt}`, def.w); } catch(_) {} lsSet(`bot_${site}_panelW_${fmt}`, def.w);
            try { GM_setValue(`bot_${site}_panelH_${fmt}`, def.h); } catch(_) {} lsSet(`bot_${site}_panelH_${fmt}`, def.h);
        });
        const tDef = siteDefs.tally;
        try { GM_setValue(`bot_${site}_tallyW`, tDef.w); } catch(_) {} lsSet(`bot_${site}_tallyW`, tDef.w);
        try { GM_setValue(`bot_${site}_tallyH`, tDef.h); } catch(_) {} lsSet(`bot_${site}_tallyH`, tDef.h);
        try { GM_setValue(`bot_${site}_tallyX`, tDef.x); } catch(_) {} lsSet(`bot_${site}_tallyX`, tDef.x);
        try { GM_setValue(`bot_${site}_tallyY`, tDef.y); } catch(_) {} lsSet(`bot_${site}_tallyY`, tDef.y);
        try { GM_setValue(`bot_${site}_isMini`, false); } catch(_) {} lsSet(`bot_${site}_isMini`, false);
        try { GM_setValue("bot_isMini", false); } catch(_) {} lsSet("bot_isMini", false);
        state.activeMainTab = "engine";

        const hsl = rgbToHsl(...Object.values(hexToRgb(settings.highlightColor)));
        state.h = hsl.h; state.s = hsl.s; state.l = hsl.l;

        state.calculatedDelay = "0.0";
        state.uiVisible = true;
        state.hudEvalTxt = "0.0";
        state.hudStatus = { text: "Ready", color: "#8b949e" };
        state.hudMove = "--";
        state.lastMoveResult = formatMoveResult("Stockfish 19 Lite", "Ready", "--");
        state.lastLiveResult = formatLiveResult("0.0", { text: "Ready", color: "#8b949e" }, "", "None");

        // 4. Forcefully destroy and rebuild the UI
        const existingMount = document.querySelector("#shadowMount");
        if (existingMount) existingMount.remove();
        state.shadow = null;
        state.ui = {};

        createUI();
        syncAllUI();
        applyMenuPosition();
        applyTallyPositionAndSize();
        applyTheme();
        applyLanguage();
        if (settings.moveGrading) initGraderEngine();
        toggleAutoQueue();
        updateUI();
    }

    function syncColor() {
        const rgb = hslToRgb(state.h, state.s, state.l);
        const hex = rgbToHex(rgb.r, rgb.g, rgb.b);
        settings.highlightColor = hex;
        saveSetting("highlightColor", hex);
        if (state.ui.inpR) {
            state.ui.inpR.value = rgb.r; state.ui.inpG.value = rgb.g; state.ui.inpB.value = rgb.b;
            state.ui.inpHex.value = hex;
            state.ui.colorPreview.style.background = hex;
            state.ui.sliderH.value = state.h; state.ui.sliderS.value = state.s; state.ui.sliderL.value = state.l;
        }
        Visuals.removeByType('bestmove');
        if (state.currentBestMove) Visuals.add(state.currentBestMove, 'bestmove');
    }

    function applyTheme() {
        if (!state.shadow) return;
        // Dark unless explicitly set to a light background
        const isDark = !(settings.themeBg && (
            settings.themeBg.includes("245, 247, 250") ||
            settings.themeBg.includes("246, 248, 250") ||
            settings.themeBg.includes("255, 255, 255") ||
            settings.themeBg === "rgba(255, 255, 255, 0.96)"
        ));

        const themeVars = isDark ? {
            "--bot-bg": settings.themeBg || "rgba(15, 19, 24, 0.94)",
            "--bot-t": settings.themeText || "#f0f6fc",
            "--bot-t-sec": "#8b949e",
            "--bot-t-sub": "#6e7681",
            "--bot-b": settings.themeBorder || "rgba(255, 255, 255, 0.12)",
            "--bot-p": settings.themePrimary || "#2ea043",
            "--bot-primary": settings.themePrimary || "#2ea043",
            "--bot-accent-blue": "#58a6ff",
            "--bot-card-bg": "rgba(255, 255, 255, 0.04)",
            "--bot-card-b": "rgba(255, 255, 255, 0.08)",
            "--bot-input-bg": "rgba(0, 0, 0, 0.35)",
            "--bot-select-bg": "#1b2028",
            "--bot-select-t": "#f0f6fc",
            "--bot-btn-bg": "rgba(255, 255, 255, 0.06)",
            "--bot-btn-b": "rgba(255, 255, 255, 0.12)",
            "--bot-track-bg": "rgba(255, 255, 255, 0.14)",
            "--bot-pill-bg": "rgba(255, 255, 255, 0.14)",
            "--bot-seg-bg": "rgba(0, 0, 0, 0.3)",
            "--bot-seg-active": "rgba(255, 255, 255, 0.12)",
            "--bot-seg-active-t": "#ffffff",
            "--bot-header-bg": "linear-gradient(180deg, rgba(255,255,255,0.06) 0%, rgba(255,255,255,0.01) 100%)",
            "--bot-info-bg": "rgba(0, 0, 0, 0.3)",
            "--bot-scrollbar-thumb": "rgba(255, 255, 255, 0.22)",
            "--bot-scrollbar-track": "rgba(0, 0, 0, 0.18)",
            "--bot-overlay-bg": "rgba(0, 0, 0, 0.32)",
        } : {
            "--bot-bg": "rgba(255, 255, 255, 0.96)",
            "--bot-t": "#111827",
            "--bot-t-sec": "#374151",
            "--bot-t-sub": "#6b7280",
            "--bot-b": "rgba(0, 0, 0, 0.15)",
            "--bot-p": "#1a7f37",
            "--bot-primary": "#1a7f37",
            "--bot-accent-blue": "#0969da",
            "--bot-card-bg": "rgba(0, 0, 0, 0.03)",
            "--bot-card-b": "rgba(0, 0, 0, 0.08)",
            "--bot-input-bg": "#f3f4f6",
            "--bot-select-bg": "#ffffff",
            "--bot-select-t": "#111827",
            "--bot-btn-bg": "rgba(0, 0, 0, 0.05)",
            "--bot-btn-b": "rgba(0, 0, 0, 0.15)",
            "--bot-track-bg": "rgba(0, 0, 0, 0.14)",
            "--bot-pill-bg": "rgba(0, 0, 0, 0.14)",
            "--bot-seg-bg": "rgba(0, 0, 0, 0.06)",
            "--bot-seg-active": "#ffffff",
            "--bot-seg-active-t": "#111827",
            "--bot-header-bg": "rgba(0, 0, 0, 0.02)",
            "--bot-info-bg": "rgba(0, 0, 0, 0.04)",
            "--bot-scrollbar-thumb": "rgba(0, 0, 0, 0.22)",
            "--bot-scrollbar-track": "rgba(0, 0, 0, 0.05)",
            "--bot-overlay-bg": "rgba(0, 0, 0, 0.18)",
        };

        const host = state.shadow.host;
        if (host) {
            Object.keys(themeVars).forEach(k => host.style.setProperty(k, themeVars[k]));
        }

        const modals = [state.ui.panel, state.ui.modal, state.ui.localModal, state.ui.tallyPanel, state.ui.helpModal, state.ui.langModal, state.ui.advUiModal];
        modals.forEach(m => {
            if (!m) return;
            Object.keys(themeVars).forEach(k => m.style.setProperty(k, themeVars[k]));
            m.style.background = themeVars["--bot-bg"];
            m.style.color = themeVars["--bot-t"];
            m.style.borderColor = themeVars["--bot-b"];
            m.style.opacity = settings.menuOpacity;
        });

        applyAdvancedUI();
        updateUI();
        updateLocalSettingsUI();
    }

    function applyAdvancedUI() {
        if (!state.shadow) return;
        const isAdv = (settings.uiPreset === "advanced");
        const mode = isAdv ? "advanced" : "basic";
        const host = state.shadow.host;
        const targets = [
            state.ui.panel, state.ui.modal, state.ui.localModal,
            state.ui.tallyPanel, state.ui.helpModal, state.ui.langModal, state.ui.advUiModal
        ];
        targets.forEach(el => {
            if (!el) return;
            el.setAttribute("data-ui", mode);
            el.setAttribute("data-card", settings.advCardStyle || "glass");
            el.setAttribute("data-hdr", settings.advHeaderStyle || "gradient");
            el.setAttribute("data-pill", settings.advScorePillStyle || "tinted");
            el.setAttribute("data-anim", settings.advAnimations === false ? "off" : "on");
            el.setAttribute("data-grad", settings.advGradientBg === false ? "off" : "on");
        });

        const densityMap = {
            compact:  { rowH: "24px", gap: "5px", pad: "9px 11px" },
            normal:   { rowH: "28px", gap: "7px", pad: "11px 13px" },
            spacious: { rowH: "32px", gap: "9px", pad: "13px 15px" }
        };
        const dens = isAdv ? (densityMap[settings.advDensity] || densityMap.normal) : { rowH: "28px", gap: "7px", pad: "10px 13px" };
        const acc = settings.advAccentColor || "#58a6ff";
        const rgb = hexToRgb(acc);
        const rad = isAdv ? Math.min(22, Math.max(6, parseInt(settings.advRadius, 10) || 14)) : 14;
        const blur = isAdv ? Math.min(32, Math.max(0, parseInt(settings.advBlur, 10) ?? 22)) : 20;
        const glow = isAdv ? Math.min(100, Math.max(0, parseInt(settings.advGlow, 10) ?? 55)) / 100 : 0;
        const fontScale = isAdv ? Math.min(115, Math.max(90, parseInt(settings.advFontScale, 10) || 100)) / 100 : 1;

        const vars = {
            "--bot-row-h": dens.rowH,
            "--bot-gap": dens.gap,
            "--bot-pad": dens.pad,
            "--adv-accent": acc,
            "--adv-accent-rgb": `${rgb.r}, ${rgb.g}, ${rgb.b}`,
            "--adv-radius": `${rad}px`,
            "--adv-radius-sm": `${Math.max(4, Math.round(rad * 0.55))}px`,
            "--adv-blur": `${blur}px`,
            "--adv-glow": glow.toFixed(2),
            "--adv-font-scale": fontScale.toFixed(2)
        };
        if (host) Object.entries(vars).forEach(([k, v]) => host.style.setProperty(k, v));
        targets.forEach(el => {
            if (!el) return;
            Object.entries(vars).forEach(([k, v]) => el.style.setProperty(k, v));
        });
    }
function applyMenuPosition() {
        const p = state.ui.panel;
        if (!p) return;
        const site = getSiteKey();
        const margin = "12px";
        p.style.transform = "none";
        p.style.top = ""; p.style.bottom = ""; p.style.left = ""; p.style.right = "";
        if (settings.menuPosition === "custom") {
            let savedX; try { savedX = GM_getValue(`bot_${site}_pX`); } catch(_) {} if (savedX === undefined || savedX === null) savedX = lsGet(`bot_${site}_pX`, "auto");
            let savedY; try { savedY = GM_getValue(`bot_${site}_pY`); } catch(_) {} if (savedY === undefined || savedY === null) savedY = lsGet(`bot_${site}_pY`, "0");
            if (savedX === "auto") { p.style.right = margin; p.style.left = "auto"; }
            else p.style.left = savedX + "px";
            p.style.top = savedY + "px";
            const rect = p.getBoundingClientRect();
            if (rect.left < 0) p.style.left = "0px";
            if (rect.top < 0) p.style.top = "0px";
            if (rect.right > window.innerWidth) p.style.left = (window.innerWidth - rect.width) + "px";
            if (rect.bottom > window.innerHeight) p.style.top = (window.innerHeight - rect.height) + "px";
        } else if (settings.menuPosition === "top-left") { p.style.top = margin; p.style.left = margin; }
        else if (settings.menuPosition === "top-right") { p.style.top = margin; p.style.right = margin; }
        else if (settings.menuPosition === "bottom-left") { p.style.bottom = margin; p.style.left = margin; }
        else if (settings.menuPosition === "bottom-right") { p.style.bottom = margin; p.style.right = margin; }
    }

    function syncLocalSettingsInputs() {
        if (!state.shadow) return;
        const g = (id) => state.shadow.getElementById(id);
        const setVal = (id, val) => { const el = g(id); if (el) el.value = val; };
        const setChk = (id, val) => { const el = g(id); if (el) el.checked = !!val; };

        setVal("localHashMB",          settings.localHashMB);
        setVal("localMoveOverhead",    settings.localMoveOverhead);
        setVal("localSkillLevel",      settings.localSkillLevel);
        setVal("localSkillLevelRange", settings.localSkillLevel);
        setChk("localLimitStrength",   settings.localLimitStrength);
        setVal("localElo",             settings.localElo);
        setChk("localShowWDL",         settings.localShowWDL);
        setVal("localMinThinkingTime", settings.localMinThinkTime);
        setVal("localMaiaElo",         settings.localMaiaElo);
        setVal("localMaiaEloRange",    settings.localMaiaElo);
        setVal("localMaiaTemp",        settings.localMaiaTemp);
        const mtLbl = g("localMaiaTempLbl");
        if (mtLbl) mtLbl.textContent = Number(settings.localMaiaTemp || 0).toFixed(1);
        setVal("localMaiaTopP",        settings.localMaiaTopP);
        const mtpLbl = g("localMaiaTopPLbl");
        if (mtpLbl) mtpLbl.textContent = Number(settings.localMaiaTopP ?? 0.95).toFixed(2);

        const eloRow = g("localEloRow");
        if (eloRow) eloRow.style.display = settings.localLimitStrength ? "flex" : "none";
    }

    function updateLocalSettingsUI() {
        if (!state.shadow) return;
        const m = getEngineById(settings.localModelId || "sf19_lite");

        const badgeEl       = state.shadow.getElementById("activeModelBadge");
        const assetJs       = state.shadow.getElementById("assetStatusJs");
        const assetWasm     = state.shadow.getElementById("assetStatusWasm");
        const rowWasm       = state.shadow.getElementById("rowAssetWasm");
        const fillBar       = state.shadow.getElementById("localProgressFill");
        const phaseEl       = state.shadow.getElementById("progressPhaseLabel");
        const detailEl      = state.shadow.getElementById("progressDetailLabel");
        const btnInstall    = state.shadow.getElementById("btnLocalInstall");
        const btnReinstall  = state.shadow.getElementById("btnLocalReinstall");
        const btnUninstall  = state.shadow.getElementById("btnLocalUninstall");

        const isReady     = state.engineStatus === "ready";
        const isError     = state.engineStatus === "error";
        const isLoading   = state.engineStatus === "loading" || state.engineLoadingInProgress;

        if (btnInstall)   btnInstall.disabled   = isReady || isLoading;
        if (btnReinstall) btnReinstall.disabled  = isLoading;
        if (btnUninstall) btnUninstall.disabled  = isLoading;

        if (rowWasm) rowWasm.style.display = m.format === "asmjs" ? "none" : "flex";

        inspectModelStorage(m, (storage) => {
            if (!state.shadow) return;
            if (assetJs) assetJs.textContent = storage.jsStatus;
            if (assetWasm) assetWasm.textContent = storage.wasmStatus;

            if (badgeEl) {
                if (isLoading) {
                    badgeEl.className = "status-badge downloading";
                    badgeEl.textContent = "DOWNLOADING";
                } else if (isError) {
                    badgeEl.className = "status-badge error";
                    badgeEl.textContent = "ERROR";
                } else if (isReady) {
                    badgeEl.className = "status-badge active";
                    badgeEl.textContent = "ACTIVE";
                } else if (storage.isCached) {
                    badgeEl.className = "status-badge cached";
                    badgeEl.textContent = "SAVED";
                } else {
                    badgeEl.className = "status-badge uninstalled";
                    badgeEl.textContent = "NOT INSTALLED";
                }
            }

            if (!isLoading) {
                if (isError) {
                    if (phaseEl) phaseEl.textContent = state.engineErrorDetail || "Initialization failed";
                    if (detailEl) detailEl.textContent = "Failed";
                    if (fillBar) { fillBar.style.width = "100%"; fillBar.style.background = "#f85149"; }
                } else if (isReady) {
                    if (phaseEl) phaseEl.textContent = "Engine Ready";
                    if (detailEl) detailEl.textContent = "Active in Worker";
                    if (fillBar) { fillBar.style.width = "100%"; fillBar.style.background = "linear-gradient(90deg, #238636, #2ea043, #3fb950)"; }
                } else if (storage.isCached) {
                    if (phaseEl) phaseEl.textContent = "Cached (Offline Ready)";
                    if (detailEl) detailEl.textContent = storage.totalMB > 0 ? `${storage.totalMB} MB` : "Ready";
                    if (fillBar) { fillBar.style.width = "100%"; fillBar.style.background = "linear-gradient(90deg, #1f6feb, #388bfd)"; }
                } else {
                    if (phaseEl) phaseEl.textContent = "Not Installed";
                    if (detailEl) detailEl.textContent = "0%";
                    if (fillBar) { fillBar.style.width = "0%"; }
                }
            }
        });

        const show = (id, visible) => {
            const el = state.shadow.getElementById(id);
            if (el) el.style.display = visible ? "" : "none";
        };
        const isMaia = m.format === "onnx";
        show("rowHash",          m.hasHash);
        show("rowMoveOverhead",  m.hasMoveOverhead);
        show("rowSkillLevel",    m.hasSkillLevel);
        show("rowLimitStrength", m.hasNNUE);
        show("rowMinThink",      m.hasMinThink);
        show("rowMaiaElo",       isMaia);
        show("rowMaiaTemp",      isMaia);
        show("rowMaiaTopP",      isMaia);
        const lblParams = state.shadow.getElementById("lblLocalParamsTitle");
        if (lblParams) lblParams.textContent = isMaia ? "Maia-3 Rating & Sampling" : "UCI Parameters & Strength";

        if (state.ui.inpDepth)    state.ui.inpDepth.max = m.maxDepth;
        if (state.ui.lblMaxDepth) state.ui.lblMaxDepth.innerText = m.maxDepth;
    }


    const PANEL_LAYOUT_DEFAULTS = {
        single: { w: "310px", h: "auto", minW: 296 },
        double: { w: "560px", h: "auto", minW: 480 },
        tabs:   { w: "320px", h: "auto", minW: 296 }
    };

    const LANG_LIST = [
        { code: "en", name: "English",    flag: `<svg viewBox="0 0 24 16"><rect width="24" height="16" fill="#b22234"/><path d="M0 2.4h24M0 5.6h24M0 8.8h24M0 12h24M0 15.2h24" stroke="#fff" stroke-width="1.3"/><rect width="10.5" height="8.6" fill="#3c3b6e"/></svg>` },
        { code: "es", name: "Español",    flag: `<svg viewBox="0 0 24 16"><rect width="24" height="16" fill="#aa151b"/><rect y="4" width="24" height="8" fill="#f1bf00"/></svg>` },
        { code: "fr", name: "Français",   flag: `<svg viewBox="0 0 24 16"><rect width="8" height="16" fill="#0055a4"/><rect x="8" width="8" height="16" fill="#fff"/><rect x="16" width="8" height="16" fill="#ef4135"/></svg>` },
        { code: "de", name: "Deutsch",    flag: `<svg viewBox="0 0 24 16"><rect width="24" height="5.33" fill="#000"/><rect y="5.33" width="24" height="5.34" fill="#dd0000"/><rect y="10.67" width="24" height="5.33" fill="#ffce00"/></svg>` },
        { code: "pt", name: "Português",  flag: `<svg viewBox="0 0 24 16"><rect width="24" height="16" fill="#009b3a"/><polygon points="12,2 21,8 12,14 3,8" fill="#fedf00"/><circle cx="12" cy="8" r="3.2" fill="#002776"/></svg>` },
        { code: "ru", name: "Русский",    flag: `<svg viewBox="0 0 24 16"><rect width="24" height="5.33" fill="#fff"/><rect y="5.33" width="24" height="5.34" fill="#0039a6"/><rect y="10.67" width="24" height="5.33" fill="#d52b1e"/></svg>` },
        { code: "zh", name: "中文",       flag: `<svg viewBox="0 0 24 16"><rect width="24" height="16" fill="#de2910"/><polygon points="4.5,2.5 5.2,4.6 7.4,4.6 5.6,5.9 6.3,8 4.5,6.7 2.7,8 3.4,5.9 1.6,4.6 3.8,4.6" fill="#ffde00"/></svg>` },
        { code: "hi", name: "हिन्दी",     flag: `<svg viewBox="0 0 24 16"><rect width="24" height="5.33" fill="#ff9933"/><rect y="5.33" width="24" height="5.34" fill="#fff"/><rect y="10.67" width="24" height="5.33" fill="#138808"/><circle cx="12" cy="8" r="1.8" fill="none" stroke="#000080" stroke-width="0.9"/></svg>` },
        { code: "ar", name: "العربية",    flag: `<svg viewBox="0 0 24 16"><rect width="24" height="16" fill="#006c35"/><rect x="6" y="7" width="12" height="2" rx="1" fill="#fff"/></svg>` },
        { code: "tr", name: "Türkçe",     flag: `<svg viewBox="0 0 24 16"><rect width="24" height="16" fill="#e30a17"/><circle cx="10" cy="8" r="3.8" fill="#fff"/><circle cx="11.2" cy="8" r="3" fill="#e30a17"/><polygon points="15.5,6.3 16.1,7.6 17.5,7.6 16.4,8.5 16.8,9.8 15.5,9 14.2,9.8 14.6,8.5 13.5,7.6 14.9,7.6" fill="#fff"/></svg>` }
    ];

    const HELP_RICH_EN = [
        {
            tag: "start",
            title: "1. Quick Start & How Everything Works Together",
            keywords: "start setup beginner cloud online local auto analyze move pipeline loop",
            beginner: [
                ["How do I start in 10 seconds?", "Open any live match. Auto-Analyze and Auto-Move start enabled in Cloud mode—just play normally, or toggle Auto-Move off to see arrows/highlights only."],
                ["Which engine mode should a beginner choose?", "Start with Cloud (zero downloads). If Cloud hits rate limits or you want offline reliability and full Humanized Mode tuning, click Local Engines → Install / Launch (Stockfish 19 Lite is only 1.8 MB)."],
                ["How the main pieces connect", "The script reads the live board every 15ms, picks a move using your active Engine Mode + Focus/Humanized rules, displays Visuals on the board, and—if enabled—waits out your Delay or Human pace before playing it."]
            ],
            more: [
                ["Execution pipeline under the hood", "1) Board Sync captures live FEN + legal moves (on Lichess via #page-init-data, live WebSocket frames, and SAN replay; on Chess.com via the board controller). 2) Primary Engine computes best move / MultiPV. 3) Move Selector applies either Humanized Mode OR Engine Focus. 4) Output splits cleanly into Visuals, Mini HUD, and Auto-Move/Manual Keybind."],
                ["Why Silent Mode doesn't stop Auto-Move or Grading", "Silent Mode only suppresses visual overlays and eval numbers on screen. Background analysis, Auto-Move, Manual Move Key, and Move Grading keep running independently."],
                ["Two independent engine workers", "When Move Grading is enabled, the script runs a SECOND dedicated Stockfish 19 Lite worker in the background so your primary engine (e.g. Maia-3, Cloud, or Stockfish 19 Full) is never blocked from your main turns."]
            ]
        },
        {
            tag: "interactions",
            title: "2. How Settings Interact (Overrides, Conflicts & Priorities)",
            keywords: "interact conflict override disable why greyed out priority human focus auto time grading silent",
            beginner: [
                ["Why is Engine Focus greyed out?", "Engine Focus automatically disables itself when Humanized Mode is ON, when a Maia-3 model is selected, or when using Online mode (because Online only returns 1 move line)."],
                ["Why did Search Depth disappear?", "Turning Auto Time (Clock) ON hides the manual Search Depth box because the script dynamically adjusts depth and think time from your remaining clock and increment."],
                ["Why did Manual Move Key disappear?", "Manual Move Key is only shown when Auto-Move is OFF—when Auto-Move is ON, the move is played automatically after the delay."]
            ],
            more: [
                ["Humanized Mode vs Engine Focus & Delay Window", "Humanized Mode takes full priority over candidate selection and pacing: it overrides Engine Focus, turns on MultiPV (3–5 lines), and replaces Delay Window with dynamic human timing. However, if you set Min Delay > 0 in Delay Window, that Min Delay still acts as a hard floor!"],
                ["Auto Time (Clock) vs Fixed Depth", "With Auto Time ON, Stockfish receives exact wtime/btime/winc/binc and stops early on obvious recaptures or planned lines (in Humanized Mode) or deeper in endgames. If no clock element is found on the page, it gracefully falls back to your Search Depth."],
                ["Move Grading vs Eval Bar & Primary Engine", "When Move Grading is ON and ready, the dedicated SF19 Lite Grader drives the Evaluation Bar and HUD score (so the bar never jumps wildly when you use low-depth Humanized or Maia-3). Whenever your primary Local engine starts searching on your turn, the Grader yields/pauses immediately so zero CPU is stolen from your move."],
                ["Maia-3 + Show Multi-Best Arrows", "Maia-3 predicts human move probabilities rather than centipawn evals. If Show Multi-Best Arrows is ON while using Maia-3, the script automatically spins up the SF19 Lite helper worker to evaluate Maia's top 3 candidate moves so they get accurate Best/Good/Inaccuracy badges."]
            ]
        },
        {
            tag: "engines",
            title: "3. Engine Modes, Local Stockfish & Maia-3",
            keywords: "cloud online local stockfish maia onnx wasm asmjs hash overhead skill elo temp top-p cache",
            beginner: [
                ["Cloud vs Online vs Local", "Cloud uses chess-api.com (supports MultiPV variants via WebSocket + Auto-Switch fallback). Online uses stockfish.online (1 line fallback). Local runs Stockfish or Maia-3 inside your browser using IndexedDB storage."],
                ["What is Maia-3?", "Maia-3 (5M / 23M / 79M) is a human-tuned neural network trained on millions of human games. Set Target Rating (600–2600) to play authentically like that Elo without robotic tactics."],
                ["What does Auto-Switch do?", "If Cloud or Online returns an error, timeout, or HIGH_USAGE rate limit, Auto-Switch automatically swaps to your Local engine and finishes analyzing the move."]
            ],
            more: [
                ["Stockfish Local models compared", "SF19 Lite (1.8 MB) is the best all-around choice for speed and accuracy. SF19 Full (94.6 MB) uses the full NNUE net for deep tactical precision. SF19/10/9 asm.js run pure JS without WebAssembly for compatibility."],
                ["UCI parameters explained", "Hash Memory (64–128 MB) speeds up transpositions. Move Overhead (ms) reserves lag margin from your clock. Skill Level (0–20) or Elo Cap Limiter weakens Stockfish cleanly. Min Move Time forces a minimum search floor per move."],
                ["Maia-3 sampling: Temp & Top-p", "Move Variety (Temp) = 0.0 always picks Maia's #1 most human move. Raising Temp (0.2–1.0) samples among natural alternatives, while Nucleus Sampling (Top-p, default 0.95) cuts off bizarre low-probability tail moves before sampling."],
                ["IndexedDB Cache & Re-download", "Downloaded JS/WASM/ONNX files stay saved locally across refreshes. If an engine stalls on 'Initializing', click Re-download or Clear Cache in Local Engines."]
            ]
        },
        {
            tag: "humanized",
            title: "4. Humanized Mode, Profiles & Time Management",
            keywords: "humanized profile beginner master hikaru gm stealth tanking timing delay pace",
            beginner: [
                ["Choosing a Human Profile", "Profiles range from Beginner (~600) and Club (~1750) up to Master (~2350), Hikaru (fast Blitz GM), GM (~2650), and Stealth (near-optimal play with natural human pacing)."],
                ["Why does it sometimes pause 4–8 seconds?", "In non-obvious turning points, sharp positions, or when the opponent deviates from your planned line, Humanized Mode triggers a realistic 'Tank' before deciding."],
                ["Does Humanized Mode work in Cloud?", "Yes—Cloud opens a WebSocket stream to collect MultiPV variants and depth snapshots for Humanized selection & pacing, though Local Stockfish provides the richest node/WDL telemetry."]
            ],
            more: [
                ["Candidate selection & blunder/inaccuracy budget", "Humanized Mode scores MultiPV 1–5 candidates using human intent heuristics (recaptures, castling, outposts, doubled rooks, 2D spatial attention near the last move, avoiding weird rook lifts or exposed king pushes). Lower profiles allow higher centipawn budgets and occasional critical misses; Stealth keeps loss near 0 cp."],
                ["Cognitive timing model (6 stages)", "Target move delay combines: Saccade eye-jump time across the board + Pattern Recognition (book, recapture, planned PV snap, M1 notice) + Calculation load (entropy, sharpness, volatility) + Surprise Verification + Narrative Affect (conversion, flag mode) + Distribution Shaper (prevents robotic metronomic timings)."],
                ["Scramble & Flag safety", "Under ~13.5 seconds effective clock, Humanized Mode automatically compresses delays into Scramble pace and respects Move Overhead so it never flags itself."]
            ]
        },
        {
            tag: "visuals",
            title: "5. Engine Focus, Visuals & Multi-Best Arrows",
            keywords: "focus aggressive gambit initiative safety conversion custom visuals outline box arrow native pv multi-best color",
            beginner: [
                ["Style Modes & Highlight Color", "Pick Neon Outline, Soft Gradient Box, Vector Arrow, or Native Board Arrow in Visuals. Customize RGB/HSL/Hex color, arrow thickness, opacity, and fade duration."],
                ["Show Best Line vs Multi-Best Arrows", "Show Best Line Arrows draws the engine's predicted continuation sequence. Show Multi-Best Arrows draws the top 3 candidate moves at once with colored Best/Excellent/Inaccuracy badges."],
                ["Engine Focus presets", "Choose Aggressive (tactics), Gambits & Sacrifices, Initiative, King Safety, Conversion (endgame trades), or Custom sliders while staying within Max Risk (cp)."]
            ],
            more: [
                ["Persist Until Move Played vs Fade Duration", "When Persist is ON, the best-move highlight stays visible until a move is played on the board, THEN waits Fade Duration (with optional Smooth Fade Out) before clearing. When Persist is OFF, the timer starts the moment the move is computed."],
                ["Max Risk (cp) in Engine Focus", "Max Risk (10–80 cp) sets the maximum centipawn drop from the #1 best move that Engine Focus is allowed to accept when preferring attacking, safe, or simplifying moves—preventing unsound blunders."],
                ["Knight L-shaped Vector Arrows", "Vector Arrow and Multi-Best automatically bend knight moves into crisp L-shaped paths instead of cutting diagonally across squares."]
            ]
        },
        {
            tag: "grading",
            title: "6. Move Grading, Evaluation Bar & Tally Panel",
            keywords: "move grading brilliant great best blunder eval bar evaluation tally accuracy window",
            beginner: [
                ["How Move Grading works", "Enable Move Grading to automatically badge each played move on the board (Brilliant !!, Great !, Best ★, Excellent, Good, Inaccuracy, Miss, Mistake, Blunder)."],
                ["Opening the Move Tally & Accuracy window", "Click the Move Grading summary bar on the main panel to open the floating Tally & Accuracy window showing White vs Black accuracy % and move counts. Drag it anywhere or click × to close."],
                ["Evaluation Bar", "Displays a live vertical advantage bar beside the board (automatically flips when playing Black)."]
            ],
            more: [
                ["How Brilliant (!!) and Great (!) are calculated", "Brilliant requires a true material sacrifice (verified via Static Exchange Evaluation, excluding desperados and recaptures) that maintains winning/strong equity when the position wasn't already completely crushing. Great requires finding the sole winning/saving move with a large win-probability gap over the #2 choice."],
                ["Grading Depth (10–20)", "Higher depth improves Brilliant/Blunder accuracy at the cost of slightly longer background calculation per half-move. The queue processes newest positions first (LIFO) so you always see grades for the latest moves."]
            ]
        },
        {
            tag: "ui",
            title: "7. Panel Formats, Basic vs Advanced UI & Gear Panel",
            keywords: "panel format single double two tab basic advanced ui gear theme skin radius blur glow density mini hud",
            beginner: [
                ["Single col / Double col / Two tab", "Switch formats anytime in Visuals → Main Panel. Double col (default) splits Engine and Features side-by-side to keep vertical height compact. Each format remembers its own resized width/height."],
                ["Basic vs Advanced UI + Gear (⚙) button", "In Visuals → Main Panel → UI Style, switch between Basic (classic) and Advanced (modern glassmorphism overhaul). Click the ⚙ button right next to it to customize skins, accent colors, card styles, blur, glow, radius, density, and animations."],
                ["Mini HUD pill", "Click ▼ in the panel header to collapse into a compact draggable pill showing live score, advantage status, best move, timer, and last move grade."]
            ],
            more: [
                ["Independent per-layout sizing & bounds", "Resizing the panel in Double col saves bot_panelW_double without altering Single col or Two tab dimensions. An automatic viewport guard keeps both the main panel and Tally window inside screen bounds if you resize your browser."],
                ["Advanced UI Skins & live preview", "Skins (Midnight Cyber, Obsidian Emerald, Royal Violet, Solar Ember, Frost Light) configure dark/light base, accent color, and glow in one click—and every slider in the Advanced panel updates live across all modals."]
            ]
        },
        {
            tag: "controls",
            title: "8. Delays, Auto-Queue, Keybinds & Troubleshooting",
            keywords: "delay window auto queue keybind manual move toggle ui typing shortcut websocket error troubleshooting",
            beginner: [
                ["Delay Window (0–180s) & Auto-Queue (1–60s)", "Delay Window picks a random wait between Min and Max seconds before Auto-Move plays (0–0 = instant). Auto-Queue waits your chosen Queue Delay (1–60s) after a match ends before clicking New Opponent / New Game."],
                ["Manual Move Key & Toggle UI Key", "Click either keybind button and press any key (press Escape to clear back to None). Toggle UI Key hides/shows all panels and popups without stopping the script."],
                ["Troubleshooting checklist", "If something feels stuck: 1) Check Console for errors. 2) In Local mode, try Re-download in Local Engines. 3) Use Reset Settings in Visuals to restore clean defaults."]
            ],
            more: [
                ["Forceful Keybind & Typing Capture", "The script attaches window capture-phase listeners (keydown/keypress/keyup) so typing numbers into Delay boxes or pressing your script keybinds blocks the host site's own hotkeys (like board flip or move navigation) from triggering."],
                ["Live game move dispatch & @run-at document-start", "On Lichess live games, moves are dispatched directly through the captured game WebSocket with monotonic ack counters. Keeping @run-at document-start in your userscript header ensures the socket is captured from ply 0 before your first click."],
                ["Board overlays missing or misaligned", "Click Analyze Position to force a re-scan. Note that if you scroll back in move history on Chess.com, live games always evaluate the active live turn rather than historical plies."]
            ]
        }
    ];

    const I18N = {
        en: {
            visuals: "Visuals", help: "Help", language: "Language", langTitle: "Select Language", helpTitle: "Help Guide",
            helpSearchPh: "Search anything: e.g. 'humanized delay', 'why greyed out', 'maia', 'glow'...", expandAll: "Expand All", collapseAll: "Collapse All", noHelpMatch: "No matching help topics found. Try fewer keywords or switch filter to All.",
            helpBeginner: "Beginner Guide", helpMore: "More", helpAllTags: "All", helpFound: "matches",
            tabEngine: "Engine", tabFeatures: "Features", engineMode: "Engine Mode", features: "Features",
            autoSwitch: "Auto-Switch", cloud: "Cloud", online: "Online", local: "Local",
            autoTime: "Auto Time (Clock)", searchDepth: "Search Depth", engineFocus: "Engine Focus",
            focusBalanced: "Balanced (#1 Best)", focusAggressive: "Aggressive (Tactics)", focusGambit: "Gambits & Sacrifices",
            focusInitiative: "Initiative / Pressure", focusSafety: "King Safety (Solid)", focusConversion: "Conversion (Endgame)", focusCustom: "Custom...",
            atkTactics: "Attack / Tactics", kingSafety: "King Safety", simplify: "Simplify / Trades", maxRisk: "Max Risk (cp)",
            toggleUiKey: "Toggle UI Key", autoAnalyze: "Auto-Analyze", silentMode: "Silent Mode", moveGrading: "Move Grading",
            gradingDepth: "Grading Depth", autoMove: "Auto-Move", humanMode: "Humanized Mode (Detectable)", humanProfile: "Human Profile",
            autoQueue: "Auto-Queue", queueDelay: "Queue Delay (s)", evalBar: "Evaluation Bar", manualMoveKey: "Manual Move Key",
            delayWindow: "Delay Window (s)", analyzePos: "Analyze Position", localEngines: "Local Engines",
            tallyTitle: "Report", white: "White", black: "Black", tally: "",
            boardHighlights: "Board Highlights", styleMode: "Style Mode", visOutline: "Neon Outline", visBoxes: "Soft Gradient Box",
            visArrow: "Vector Arrow", visNative: "Native Board Arrow", showBestLine: "Show Best Line Arrows",
            showMultiBest: "Show Multi-Best Arrows", arrowWidth: "Arrow Width", arrowOpacity: "Arrow Opacity",
            fadeDuration: "Fade Duration", smoothFade: "Smooth Fade Out", persistMove: "Persist Until Move Played",
            highlightColor: "Highlight Color", hue: "Hue", saturation: "Saturation", brightness: "Brightness", hexCode: "Hex Code",
            mainPanel: "Main Panel", panelFormat: "Panel Format", fmtSingle: "Single col", fmtDouble: "Double col", fmtTabs: "Two tab",
            uiStyle: "UI Style", uiBasic: "Basic", uiAdvanced: "Advanced",
            advUiTitle: "Advanced UI Customization", advSkins: "Quick Style Skins", advSurface: "Surface & Cards",
            advAccent: "Accent Color", advCardStyle: "Card Style", advCardGlass: "Frosted Glass", advCardElev: "Elevated Depth",
            advCardLine: "Crisp Hairline", advCardNeon: "Neon Edge", advGradient: "Ambient Mesh Gradient",
            advRadius: "Corner Radius", advBlur: "Backdrop Blur", advGlow: "Accent Glow",
            advTypography: "Layout & Typography", advDensity: "Row Density", advDensCompact: "Compact", advDensNormal: "Normal", advDensSpacious: "Spacious",
            advFontScale: "Text Scale", advHeaderStyle: "Header Style", advHdrGrad: "Gradient", advHdrMin: "Minimal", advHdrBar: "Accent Strip",
            advScorePill: "Score Pill Style", advPillTint: "Tinted Glow", advPillSolid: "Solid Accent", advPillOut: "Outlined",
            advAnimations: "Smooth Micro-Animations", advReset: "Reset Advanced Style",
            screenAnchor: "Screen Anchor", anchCustom: "Custom (Draggable)", anchTL: "Top Left", anchTR: "Top Right", anchBL: "Bottom Left", anchBR: "Bottom Right",
            glassOpacity: "Glass Opacity", themePresets: "Theme Presets", dark: "Dark", light: "Light", resetSettings: "Reset Settings",
            activeModel: "Active Engine Model", storageInv: "Local Storage Inventory", runnerScript: "Runner Script (JS)", neuralWeights: "Neural Weights (WASM / NNUE)",
            installLaunch: "Install / Launch", redownload: "Re-download", clearCache: "Clear Cache",
            uciParams: "UCI Parameters & Strength", maiaParams: "Maia-3 Rating & Sampling",
            hashMem: "Hash Memory (MB)", moveOverhead: "Move Overhead (ms)", skillLevel: "Skill Level (0–20)",
            eloCap: "Elo Cap Limiter", targetElo: "Target Elo", minMoveTime: "Min Move Time (ms)",
            targetRating: "Target Rating (600–2600)", moveVariety: "Move Variety (Temp)", nucleusSamp: "Nucleus Sampling (Top-p)",
            pressKey: "Press key...", none: "None",
            tt: {
                visuals: "Open appearance, arrow, highlight color, and panel layout settings.",
                help: "Open the searchable beginner-friendly help guide.",
                language: "Switch interface language.",
                minBtn: "Collapse the panel into a compact floating HUD bar.",
                autoSwitch: "Automatically switch to Local mode if Cloud or Online servers fail or rate-limit.",
                mode: "Cloud uses remote servers, Online uses a secondary API, Local runs Stockfish/Maia directly in your browser.",
                autoTime: "Automatically adjusts search time and depth based on your remaining clock time.",
                depth: "How many half-moves ahead the engine calculates when Auto Time is off (higher = stronger, slower).",
                focus: "Steers candidate move selection toward tactics, safety, or endgame trades within a small risk tolerance.",
                uiKey: "Keyboard shortcut to hide or show the entire script panel and overlays.",
                autoRun: "Automatically analyzes every new position when it becomes your turn.",
                silent: "Hides move arrows, highlights, and eval numbers while keeping background analysis active.",
                grade: "Grades played moves (Brilliant, Best, Blunder, etc.) using a separate background Stockfish 19 Lite engine.",
                gradeDepth: "Calculation depth (10–20) used for move grading and the evaluation bar.",
                autoMove: "Automatically plays the chosen move on the board after the configured delay.",
                humanMode: "Picks realistic human-like candidate moves and natural thinking delays (Local/Cloud).",
                humanPreset: "Selects target human skill level and pacing profile.",
                autoQueue: "Automatically clicks New Opponent / New Game when a match finishes.",
                autoQueueDelay: "Wait time (1 to 60 seconds) after a game ends before starting the next game.",
                evalBar: "Displays a vertical evaluation bar beside the board showing who is winning.",
                moveKey: "Press this key on your turn to manually play the recommended move when Auto-Move is off.",
                delayWindow: "Random wait time range in seconds (0 to 180s) before Auto-Move plays.",
                analyze: "Force an immediate analysis of the current board position.",
                localBtn: "Install, switch, or configure local Stockfish and Maia-3 engines.",
                visType: "Choose how the best move is drawn on the board (outline, glowing box, arrow, or native arrow).",
                pv: "Draws arrows showing the engine's predicted best continuation line.",
                multiBest: "Shows up to 3 top candidate moves on the board with move-grade badges.",
                arrowW: "Adjusts arrow thickness on the board.",
                arrowOp: "Adjusts transparency of board arrows.",
                dur: "How long highlights stay visible before disappearing (0 = instant).",
                fade: "Smoothly fades highlights out instead of disappearing instantly.",
                persist: "Keeps highlights visible until a move is actually played on the board.",
                color: "Customize the color used for board highlights and arrows.",
                panelLayout: "Switch the main panel between Single Column, Double Column, or Two Tabs.",
                uiStyle: "Switch between the classic Basic UI and the customizable Advanced glassmorphic UI.",
                advGear: "Open the Advanced UI customization panel.",
                anchor: "Snap the main panel to a screen corner or leave it freely draggable.",
                opacity: "Adjusts overall transparency of the menus.",
                theme: "Switch between Dark and Light color themes.",
                reset: "Resets all settings, panel sizes, and layouts back to factory defaults.",
                modelSel: "Choose which local Stockfish or Maia-3 neural model to install and run.",
                hash: "RAM reserved for engine memory (64–128 MB is ideal for fast play).",
                overhead: "Safety buffer (ms) subtracted from clock calculations to prevent flagging on lag.",
                skill: "Stockfish strength level from 0 (weakest) to 20 (full strength).",
                limitStr: "Caps Stockfish strength to a specific target Elo rating.",
                minThink: "Minimum time (ms) the engine spends thinking on each move.",
                maiaElo: "Conditions Maia-3 to mimic human players at this rating (600–2600).",
                maiaTemp: "0.0 picks the top human move; higher values add natural variety.",
                maiaTopP: "Restricts random sampling to the top probability moves."
            }
        },
        es: {
            visuals: "Visuales", help: "Ayuda", language: "Idioma", langTitle: "Seleccionar Idioma", helpTitle: "Guía de Ayuda",
            helpSearchPh: "Buscar ajustes, interacciones, solución...", expandAll: "Expandir todo", collapseAll: "Contraer todo", noHelpMatch: "No se encontraron temas.",
            helpBeginner: "Guía Básica", helpMore: "Más", helpAllTags: "Todo", helpFound: "resultados",
            tabEngine: "Motor", tabFeatures: "Funciones", engineMode: "Modo de Motor", features: "Funciones",
            autoSwitch: "Cambio Automático", cloud: "Nube", online: "En línea", local: "Local",
            autoTime: "Tiempo Auto (Reloj)", searchDepth: "Profundidad", engineFocus: "Enfoque del Motor",
            focusBalanced: "Equilibrado (#1 Mejor)", focusAggressive: "Agresivo (Táctica)", focusGambit: "Gambito y Sacrificios",
            focusInitiative: "Iniciativa / Presión", focusSafety: "Seguridad del Rey", focusConversion: "Conversión (Final)", focusCustom: "Personalizado...",
            atkTactics: "Ataque / Táctica", kingSafety: "Seguridad del Rey", simplify: "Simplificar / Cambios", maxRisk: "Riesgo Máx (cp)",
            toggleUiKey: "Tecla Mostrar/Ocultar UI", autoAnalyze: "Auto-Analizar", silentMode: "Modo Silencioso", moveGrading: "Calificar Jugadas",
            gradingDepth: "Profundidad Calific.", autoMove: "Auto-Mover", humanMode: "Modo Humano (Detectable)", humanProfile: "Perfil Humano",
            autoQueue: "Auto-Cola", queueDelay: "Espera Cola (s)", evalBar: "Barra de Evaluación", manualMoveKey: "Tecla Jugada Manual",
            delayWindow: "Rango Espera (s)", analyzePos: "Analizar Posición", localEngines: "Motores Locales",
            tallyTitle: "Informe", white: "Blancas", black: "Negras", tally: "",
            boardHighlights: "Resaltado del Tablero", styleMode: "Estilo", visOutline: "Contorno Neón", visBoxes: "Casilla Degradada",
            visArrow: "Flecha Vectorial", visNative: "Flecha Nativa", showBestLine: "Flechas Mejor Línea",
            showMultiBest: "Flechas Multi-Mejor", arrowWidth: "Grosor Flecha", arrowOpacity: "Opacidad Flecha",
            fadeDuration: "Duración Desvanecer", smoothFade: "Desvanecido Suave", persistMove: "Mantener hasta Jugar",
            highlightColor: "Color de Resaltado", hue: "Tono", saturation: "Saturación", brightness: "Brillo", hexCode: "Código Hex",
            mainPanel: "Panel Principal", panelFormat: "Formato del Panel", fmtSingle: "1 Columna", fmtDouble: "2 Columnas", fmtTabs: "2 Pestañas",
            uiStyle: "Estilo UI", uiBasic: "Básico", uiAdvanced: "Avanzado",
            advUiTitle: "Personalización UI Avanzada", advSkins: "Estilos Rápidos", advSurface: "Superficie y Tarjetas",
            advAccent: "Color de Acento", advCardStyle: "Estilo Tarjeta", advCardGlass: "Cristal", advCardElev: "Elevado",
            advCardLine: "Borde Fino", advCardNeon: "Borde Neón", advGradient: "Degradado Ambiental",
            advRadius: "Bordes Redondos", advBlur: "Desenfoque", advGlow: "Brillo de Acento",
            advTypography: "Espaciado y Texto", advDensity: "Densidad", advDensCompact: "Compacto", advDensNormal: "Normal", advDensSpacious: "Espacioso",
            advFontScale: "Tamaño Texto", advHeaderStyle: "Cabecera", advHdrGrad: "Degradado", advHdrMin: "Mínima", advHdrBar: "Barra Acento",
            advScorePill: "Estilo Puntuación", advPillTint: "Tinte Suave", advPillSolid: "Sólido", advPillOut: "Contorno",
            advAnimations: "Micro-Animaciones", advReset: "Restablecer Avanzado",
            screenAnchor: "Anclaje en Pantalla", anchCustom: "Libre (Arrastrable)", anchTL: "Sup. Izquierda", anchTR: "Sup. Derecha", anchBL: "Inf. Izquierda", anchBR: "Inf. Derecha",
            glassOpacity: "Opacidad Cristal", themePresets: "Temas", dark: "Oscuro", light: "Claro", resetSettings: "Restablecer Todo",
            activeModel: "Modelo Local Activo", storageInv: "Almacenamiento Local", runnerScript: "Script Ejecutor (JS)", neuralWeights: "Pesos Neuronales (WASM)",
            installLaunch: "Instalar / Iniciar", redownload: "Re-descargar", clearCache: "Limpiar Caché",
            uciParams: "Parámetros UCI y Fuerza", maiaParams: "Nivel y Muestreo Maia-3",
            hashMem: "Memoria Hash (MB)", moveOverhead: "Margen Red (ms)", skillLevel: "Nivel Habilidad (0–20)",
            eloCap: "Límite de Elo", targetElo: "Elo Objetivo", minMoveTime: "Tiempo Mínimo (ms)",
            targetRating: "Elo Objetivo (600–2600)", moveVariety: "Variedad (Temp)", nucleusSamp: "Muestreo Núcleo (Top-p)",
            pressKey: "Pulsa tecla...", none: "Ninguna",
            tt: {
                visuals: "Abre ajustes de flechas, colores, apariencia y diseño del panel.",
                help: "Abre la guía de ayuda con buscador para principiantes.",
                language: "Cambiar el idioma de la interfaz.",
                minBtn: "Minimiza el panel a una barra flotante compacta.",
                autoSwitch: "Cambia automáticamente al motor Local si los servidores fallan.",
                mode: "Nube/En línea usan servidores; Local ejecuta Stockfish o Maia-3 en tu navegador.",
                autoTime: "Ajusta la profundidad y el tiempo según el reloj restante.",
                depth: "Jugadas por adelantado que calcula el motor sin Tiempo Auto.",
                focus: "Orienta las jugadas candidatas hacia táctica, seguridad o finales.",
                uiKey: "Atajo de teclado para mostrar u ocultar todo el panel.",
                autoRun: "Analiza automáticamente cada posición cuando es tu turno.",
                silent: "Oculta flechas, resaltados y números manteniendo el análisis activo.",
                grade: "Califica jugadas (Brillante, Mejor, Error) con Stockfish 19 Lite en segundo plano.",
                gradeDepth: "Profundidad (10–20) usada para calificar jugadas y la barra.",
                autoMove: "Juega automáticamente la jugada elegida tras el retraso configurado.",
                humanMode: "Elige jugadas y tiempos humanos realistas según el perfil.",
                humanPreset: "Selecciona el nivel y ritmo humano objetivo.",
                autoQueue: "Busca nueva partida automáticamente al terminar la actual.",
                autoQueueDelay: "Espera (1 a 60s) tras finalizar antes de iniciar la siguiente partida.",
                evalBar: "Muestra la barra vertical de evaluación junto al tablero.",
                moveKey: "Pulsa esta tecla en tu turno para jugar manualmente la recomendación.",
                delayWindow: "Tiempo aleatorio en segundos (0 a 180s) antes de Auto-Mover.",
                analyze: "Fuerza un análisis inmediato de la posición actual.",
                localBtn: "Instala, cambia o configura motores Stockfish y Maia-3 locales.",
                visType: "Elige cómo se muestra la mejor jugada en el tablero.",
                pv: "Muestra flechas de la variante principal recomendada.",
                multiBest: "Muestra hasta 3 mejores jugadas candidatas con sus insignias.",
                arrowW: "Ajusta el grosor de las flechas.",
                arrowOp: "Ajusta la transparencia de las flechas.",
                dur: "Tiempo que permanecen visibles los resaltados.",
                fade: "Desvanece suavemente los resaltados en lugar de cortarlos.",
                persist: "Mantiene los resaltados hasta que se juegue en el tablero.",
                color: "Personaliza el color de resaltados y flechas.",
                panelLayout: "Cambia el panel principal entre 1 Columna, 2 Columnas o 2 Pestañas.",
                uiStyle: "Cambia entre la UI Básica y la UI Avanzada personalizable.",
                advGear: "Abre el panel de personalización de la UI Avanzada.",
                anchor: "Fija el panel a una esquina o déjalo libre.",
                opacity: "Ajusta la transparencia de las ventanas.",
                theme: "Cambia entre tema Oscuro y Claro.",
                reset: "Restablece todos los ajustes y tamaños por defecto.",
                modelSel: "Elige qué motor local descargar y usar.",
                hash: "Memoria RAM para el motor (64–128 MB recomendado).",
                overhead: "Margen de seguridad (ms) contra latencia.",
                skill: "Fuerza de Stockfish de 0 a 20.",
                limitStr: "Limita la fuerza de Stockfish a un Elo concreto.",
                minThink: "Tiempo mínimo (ms) por jugada.",
                maiaElo: "Ajusta Maia-3 para jugar como este Elo humano (600–2600).",
                maiaTemp: "0.0 elige siempre la más humana; mayor valor da más variedad.",
                maiaTopP: "Limita el muestreo a las jugadas más probables."
            }
        },
        fr: {
            visuals: "Visuels", help: "Aide", language: "Langue", langTitle: "Choisir la Langue", helpTitle: "Guide d'Aide",
            helpSearchPh: "Rechercher paramètres, interactions...", expandAll: "Tout déplier", collapseAll: "Tout replier", noHelpMatch: "Aucun sujet trouvé.",
            helpBeginner: "Guide Débutant", helpMore: "Plus", helpAllTags: "Tout", helpFound: "résultats",
            tabEngine: "Moteur", tabFeatures: "Options", engineMode: "Mode Moteur", features: "Options",
            autoSwitch: "Bascule Auto", cloud: "Cloud", online: "En ligne", local: "Local",
            autoTime: "Temps Auto (Horloge)", searchDepth: "Profondeur", engineFocus: "Style Moteur",
            focusBalanced: "Équilibré (#1)", focusAggressive: "Agressif (Tactique)", focusGambit: "Gambits & Sacrifices",
            focusInitiative: "Initiative / Pression", focusSafety: "Sécurité du Roi", focusConversion: "Conversion (Finale)", focusCustom: "Personnalisé...",
            atkTactics: "Attaque / Tactique", kingSafety: "Sécurité Roi", simplify: "Simplifier", maxRisk: "Risque Max (cp)",
            toggleUiKey: "Touche Afficher UI", autoAnalyze: "Auto-Analyse", silentMode: "Mode Silencieux", moveGrading: "Notation Coups",
            gradingDepth: "Prof. Notation", autoMove: "Auto-Coup", humanMode: "Mode Humain (Détectable)", humanProfile: "Profil Humain",
            autoQueue: "File Auto", queueDelay: "Délai File (s)", evalBar: "Barre d'Éval", manualMoveKey: "Touche Coup Manuel",
            delayWindow: "Délai Aléatoire (s)", analyzePos: "Analyser Position", localEngines: "Moteurs Locaux",
            tallyTitle: "Rapport", white: "Blancs", black: "Noirs", tally: "",
            boardHighlights: "Surbrillance Échiquier", styleMode: "Style", visOutline: "Contour Néon", visBoxes: "Case Dégradée",
            visArrow: "Flèche Vectorielle", visNative: "Flèche Native", showBestLine: "Flèches Meilleure Ligne",
            showMultiBest: "Flèches Multi-Coups", arrowWidth: "Largeur Flèche", arrowOpacity: "Opacité Flèche",
            fadeDuration: "Durée Fondu", smoothFade: "Fondu Doux", persistMove: "Garder jusqu'au Coup",
            highlightColor: "Couleur", hue: "Teinte", saturation: "Saturation", brightness: "Luminosité", hexCode: "Code Hex",
            mainPanel: "Panneau Principal", panelFormat: "Format Panneau", fmtSingle: "1 Colonne", fmtDouble: "2 Colonnes", fmtTabs: "2 Onglets",
            uiStyle: "Style UI", uiBasic: "Basique", uiAdvanced: "Avancé",
            advUiTitle: "Personnalisation UI Avancée", advSkins: "Thèmes Rapides", advSurface: "Surface & Cartes",
            advAccent: "Couleur d'Accent", advCardStyle: "Style de Carte", advCardGlass: "Verre Dépoli", advCardElev: "Profondeur",
            advCardLine: "Bordure Fine", advCardNeon: "Bord Néon", advGradient: "Dégradé Ambiant",
            advRadius: "Arrondi", advBlur: "Flou Arrière", advGlow: "Lueur d'Accent",
            advTypography: "Densité & Texte", advDensity: "Densité", advDensCompact: "Compact", advDensNormal: "Normal", advDensSpacious: "Aéré",
            advFontScale: "Taille Texte", advHeaderStyle: "En-tête", advHdrGrad: "Dégradé", advHdrMin: "Minimal", advHdrBar: "Barre Accent",
            advScorePill: "Style Score", advPillTint: "Teinté", advPillSolid: "Solide", advPillOut: "Contour",
            advAnimations: "Animations Fluides", advReset: "Réinit. Style Avancé",
            screenAnchor: "Ancrage Écran", anchCustom: "Libre (Déplaçable)", anchTL: "Haut Gauche", anchTR: "Haut Droite", anchBL: "Bas Gauche", anchBR: "Bas Droite",
            glassOpacity: "Opacité Verre", themePresets: "Thèmes", dark: "Sombre", light: "Clair", resetSettings: "Réinitialiser",
            activeModel: "Modèle Local Actif", storageInv: "Stockage Local", runnerScript: "Script (JS)", neuralWeights: "Poids (WASM / NNUE)",
            installLaunch: "Installer / Lancer", redownload: "Retélécharger", clearCache: "Vider Cache",
            uciParams: "Paramètres UCI & Force", maiaParams: "Classement & Échantillonnage Maia-3",
            hashMem: "Mémoire Hash (Mo)", moveOverhead: "Marge Réseau (ms)", skillLevel: "Niveau (0–20)",
            eloCap: "Limiteur Elo", targetElo: "Elo Cible", minMoveTime: "Temps Min (ms)",
            targetRating: "Elo Cible (600–2600)", moveVariety: "Variété (Temp)", nucleusSamp: "Échantillonnage (Top-p)",
            pressKey: "Touche...", none: "Aucune",
            tt: { visuals: "Apparence, flèches, couleurs et format du panneau.", help: "Ouvrir le guide d'aide avec recherche.", language: "Changer la langue.", minBtn: "Réduire en barre compacte.", autoSwitch: "Bascule vers Local en cas d'erreur API.", mode: "Cloud/En ligne via serveur ; Local tourne dans votre navigateur.", autoTime: "Adapte la profondeur à votre pendule.", depth: "Profondeur de calcul sans Temps Auto.", focus: "Oriente les coups candidats selon le style choisi.", uiKey: "Raccourci pour masquer/afficher l'interface.", autoRun: "Analyse automatiquement à votre tour.", silent: "Cache les flèches et scores à l'écran.", grade: "Note chaque coup avec Stockfish 19 Lite en arrière-plan.", gradeDepth: "Profondeur (10–20) de notation et de la barre d'éval.", autoMove: "Joue le coup automatiquement après le délai.", humanMode: "Simule un style et un rythme humains.", humanPreset: "Niveau humain visé.", autoQueue: "Relance une partie automatiquement après la fin.", autoQueueDelay: "Attente (1–60s) avant la partie suivante.", evalBar: "Affiche la barre d'évaluation à côté de l'échiquier.", moveKey: "Touche pour jouer manuellement la recommandation.", delayWindow: "Délai aléatoire (0–180s) avant Auto-Coup.", analyze: "Analyser immédiatement la position.", localBtn: "Installer ou configurer Stockfish / Maia-3 local.", visType: "Mode d'affichage du meilleur coup.", pv: "Affiche la suite principale.", multiBest: "Affiche le top 3 avec notes.", arrowW: "Épaisseur des flèches.", arrowOp: "Transparence des flèches.", dur: "Durée d'affichage.", fade: "Disparition en fondu.", persist: "Reste affiché jusqu'au coup joué.", color: "Couleur des repères.", panelLayout: "1 Colonne, 2 Colonnes ou 2 Onglets.", uiStyle: "Basculer entre l'interface Basique et Avancée.", advGear: "Ouvrir la personnalisation de l'interface Avancée.", anchor: "Position du panneau sur l'écran.", opacity: "Transparence des fenêtres.", theme: "Thème Sombre ou Clair.", reset: "Réinitialise tout par défaut.", modelSel: "Modèle local à charger.", hash: "RAM allouée (64–128 Mo).", overhead: "Tampon anti-lag (ms).", skill: "Force Stockfish (0–20).", limitStr: "Limite à un Elo précis.", minThink: "Temps minimum (ms).", maiaElo: "Niveau humain simulé (600–2600).", maiaTemp: "0.0 = plus probable ; plus élevé = plus varié.", maiaTopP: "Seuil de filtrage des coups." }
        },
        de: {
            visuals: "Optik", help: "Hilfe", language: "Sprache", langTitle: "Sprache wählen", helpTitle: "Hilfe-Anleitung",
            helpSearchPh: "Einstellungen, Wechselwirkungen suchen...", expandAll: "Alle öffnen", collapseAll: "Alle schließen", noHelpMatch: "Keine Treffer gefunden.",
            helpBeginner: "Einsteiger", helpMore: "Mehr", helpAllTags: "Alle", helpFound: "Treffer",
            tabEngine: "Engine", tabFeatures: "Funktionen", engineMode: "Engine-Modus", features: "Funktionen",
            autoSwitch: "Auto-Wechsel", cloud: "Cloud", online: "Online", local: "Lokal",
            autoTime: "Auto-Zeit (Uhr)", searchDepth: "Suchtiefe", engineFocus: "Engine-Fokus",
            focusBalanced: "Ausgewogen (#1)", focusAggressive: "Aggressiv (Taktik)", focusGambit: "Gambits & Opfer",
            focusInitiative: "Initiative / Druck", focusSafety: "Königssicherheit", focusConversion: "Endspiel-Verwertung", focusCustom: "Benutzerdef...",
            atkTactics: "Angriff / Taktik", kingSafety: "Königssicherheit", simplify: "Abtauschen", maxRisk: "Max Risiko (cp)",
            toggleUiKey: "UI-Taste", autoAnalyze: "Auto-Analyse", silentMode: "Stiller Modus", moveGrading: "Zugbewertung",
            gradingDepth: "Bewertungs-Tiefe", autoMove: "Auto-Zug", humanMode: "Human-Modus (Erkennbar)", humanProfile: "Human-Profil",
            autoQueue: "Auto-Suche", queueDelay: "Suche-Pause (s)", evalBar: "Bewertungsbalken", manualMoveKey: "Manuelle Zugtaste",
            delayWindow: "Verzögerung (s)", analyzePos: "Position Analysieren", localEngines: "Lokale Engines",
            tallyTitle: "Bericht", white: "Weiß", black: "Schwarz", tally: "",
            boardHighlights: "Brett-Markierungen", styleMode: "Stil", visOutline: "Neon-Rahmen", visBoxes: "Verlaufs-Feld",
            visArrow: "Vektor-Pfeil", visNative: "Nativer Pfeil", showBestLine: "Beste Variante (Pfeile)",
            showMultiBest: "Multi-Best Pfeile", arrowWidth: "Pfeilbreite", arrowOpacity: "Pfeil-Deckkraft",
            fadeDuration: "Ausblenddauer", smoothFade: "Sanft Ausblenden", persistMove: "Bis zum Zug behalten",
            highlightColor: "Markierungsfarbe", hue: "Farbton", saturation: "Sättigung", brightness: "Helligkeit", hexCode: "Hex-Code",
            mainPanel: "Hauptpanel", panelFormat: "Panel-Format", fmtSingle: "1 Spalte", fmtDouble: "2 Spalten", fmtTabs: "2 Tabs",
            uiStyle: "UI-Stil", uiBasic: "Basis", uiAdvanced: "Erweitert",
            advUiTitle: "Erweiterte UI-Anpassung", advSkins: "Schnell-Skins", advSurface: "Oberfläche & Karten",
            advAccent: "Akzentfarbe", advCardStyle: "Kartenstil", advCardGlass: "Milchglas", advCardElev: "Tiefe",
            advCardLine: "Feinlinie", advCardNeon: "Neon-Rand", advGradient: "Verlauf-Hintergrund",
            advRadius: "Eckenradius", advBlur: "Unschärfe", advGlow: "Akzent-Leuchten",
            advTypography: "Dichte & Schrift", advDensity: "Zeilenabstand", advDensCompact: "Kompakt", advDensNormal: "Normal", advDensSpacious: "Luftig",
            advFontScale: "Schriftgröße", advHeaderStyle: "Kopfzeile", advHdrGrad: "Verlauf", advHdrMin: "Minimal", advHdrBar: "Akzentstreifen",
            advScorePill: "Score-Badge", advPillTint: "Getönt", advPillSolid: "Gefüllt", advPillOut: "Umrandet",
            advAnimations: "Sanfte Animationen", advReset: "Erweitert zurücksetzen",
            screenAnchor: "Position", anchCustom: "Frei (Ziehbar)", anchTL: "Oben Links", anchTR: "Oben Rechts", anchBL: "Unten Links", anchBR: "Unten Rechts",
            glassOpacity: "Transparenz", themePresets: "Designs", dark: "Dunkel", light: "Hell", resetSettings: "Zurücksetzen",
            activeModel: "Aktives Modell", storageInv: "Lokaler Speicher", runnerScript: "Runner-Skript (JS)", neuralWeights: "Gewichte (WASM / NNUE)",
            installLaunch: "Installieren / Starten", redownload: "Neu laden", clearCache: "Cache leeren",
            uciParams: "UCI-Parameter & Stärke", maiaParams: "Maia-3 Elo & Sampling",
            hashMem: "Hash-Speicher (MB)", moveOverhead: "Lag-Puffer (ms)", skillLevel: "Spielstärke (0–20)",
            eloCap: "Elo-Begrenzung", targetElo: "Ziel-Elo", minMoveTime: "Min. Bedenkzeit (ms)",
            targetRating: "Ziel-Elo (600–2600)", moveVariety: "Zugvielfalt (Temp)", nucleusSamp: "Nucleus (Top-p)",
            pressKey: "Taste drücken...", none: "Keine",
            tt: { visuals: "Markierungen, Pfeile, Farben und Panel-Layout.", help: "Durchsuchbare Hilfe öffnen.", language: "Sprache wechseln.", minBtn: "In kompaktes HUD minimieren.", autoSwitch: "Wechselt bei API-Fehlern auf Lokal.", mode: "Cloud/Online über Server; Lokal läuft direkt im Browser.", autoTime: "Passt Tiefe an die Restzeit an.", depth: "Berechnungstiefe ohne Auto-Zeit.", focus: "Lenkt Züge nach Taktik, Sicherheit oder Endspiel.", uiKey: "Tastenkürzel zum Ausblenden der UI.", autoRun: "Analysiert automatisch bei eigenem Zug.", silent: "Versteckt alle visuellen Hinweise.", grade: "Bewertet gespielte Züge mit Stockfish 19 Lite.", gradeDepth: "Tiefe (10–20) für Bewertung & Balken.", autoMove: "Führt den Zug nach Verzögerung automatisch aus.", humanMode: "Menschliche Zugwahl und Bedenkzeit.", humanPreset: "Menschliche Spielstärke wählen.", autoQueue: "Startet nach Spielende automatisch ein neues Spiel.", autoQueueDelay: "Wartezeit (1–60s) vor dem nächsten Spiel.", evalBar: "Zeigt den Bewertungsbalken neben dem Brett.", moveKey: "Taste für manuellen Zug bei deaktiviertem Auto-Zug.", delayWindow: "Zufällige Wartezeit (0–180s) vor Auto-Zug.", analyze: "Aktuelle Stellung sofort analysieren.", localBtn: "Lokale Stockfish/Maia-3 Engines verwalten.", visType: "Art der Zugmarkierung.", pv: "Zeigt Hauptvariante als Pfeile.", multiBest: "Zeigt Top-3-Züge mit Bewertungs-Badges.", arrowW: "Pfeildicke anpassen.", arrowOp: "Pfeildeckkraft anpassen.", dur: "Anzeigedauer der Markierungen.", fade: "Sanftes Ausblenden aktivieren.", persist: "Markierung bis zum nächsten Zug halten.", color: "Farbe der Markierungen ändern.", panelLayout: "Zwischen 1 Spalte, 2 Spalten oder 2 Tabs wechseln.", uiStyle: "Zwischen Basis-UI und Erweitert wechseln.", advGear: "Erweiterte UI-Einstellungen öffnen.", anchor: "Fenster an Ecke anheften oder frei bewegen.", opacity: "Fenster-Transparenz.", theme: "Zwischen Dunkel und Hell wechseln.", reset: "Alle Einstellungen zurücksetzen.", modelSel: "Lokales Engine-Modell wählen.", hash: "RAM-Größe für die Engine.", overhead: "Sicherheitspuffer (ms) gegen Zeitverlust.", skill: "Stockfish-Stärke 0–20.", limitStr: "Auf festen Elo-Wert begrenzen.", minThink: "Mindestzeit pro Zug (ms).", maiaElo: "Maia-3 Zielstärke (600–2600).", maiaTemp: "0.0 = wahrscheinlichster Zug; höher = mehr Variation.", maiaTopP: "Wahrscheinlichkeitsschwelle für Züge." }
        },
        pt: {
            visuals: "Visuais", help: "Ajuda", language: "Idioma", langTitle: "Selecionar Idioma", helpTitle: "Guia de Ajuda",
            helpSearchPh: "Buscar ajustes, interações...", expandAll: "Expandir Tudo", collapseAll: "Recolher Tudo", noHelpMatch: "Nenhum tópico encontrado.",
            helpBeginner: "Iniciante", helpMore: "Mais", helpAllTags: "Tudo", helpFound: "resultados",
            tabEngine: "Motor", tabFeatures: "Recursos", engineMode: "Modo do Motor", features: "Recursos",
            autoSwitch: "Troca Automática", cloud: "Nuvem", online: "Online", local: "Local",
            autoTime: "Tempo Auto (Relógio)", searchDepth: "Profundidade", engineFocus: "Foco do Motor",
            focusBalanced: "Equilibrado (#1)", focusAggressive: "Agressivo (Tática)", focusGambit: "Gambitos & Sacrifícios",
            focusInitiative: "Iniciativa / Pressão", focusSafety: "Segurança do Rei", focusConversion: "Conversão (Final)", focusCustom: "Personalizado...",
            atkTactics: "Ataque / Tática", kingSafety: "Segurança do Rei", simplify: "Simplificar", maxRisk: "Risco Máx (cp)",
            toggleUiKey: "Tecla Mostrar UI", autoAnalyze: "Auto-Analisar", silentMode: "Modo Silencioso", moveGrading: "Avaliar Lances",
            gradingDepth: "Prof. Avaliação", autoMove: "Auto-Mover", humanMode: "Modo Humano (Detectável)", humanProfile: "Perfil Humano",
            autoQueue: "Auto-Fila", queueDelay: "Espera Fila (s)", evalBar: "Barra de Avaliação", manualMoveKey: "Tecla Lance Manual",
            delayWindow: "Atraso (s)", analyzePos: "Analisar Posição", localEngines: "Motores Locais",
            tallyTitle: "Relatório", white: "Brancas", black: "Pretas", tally: "",
            boardHighlights: "Destaques no Tabuleiro", styleMode: "Estilo", visOutline: "Contorno Neon", visBoxes: "Caixa Gradiente",
            visArrow: "Seta Vetorial", visNative: "Seta Nativa", showBestLine: "Setas Melhor Linha",
            showMultiBest: "Setas Multi-Melhor", arrowWidth: "Largura Seta", arrowOpacity: "Opacidade Seta",
            fadeDuration: "Duração Sumir", smoothFade: "Sumir Suavemente", persistMove: "Manter até Jogar",
            highlightColor: "Cor do Destaque", hue: "Matiz", saturation: "Saturação", brightness: "Brilho", hexCode: "Código Hex",
            mainPanel: "Painel Principal", panelFormat: "Formato do Painel", fmtSingle: "1 Coluna", fmtDouble: "2 Colunas", fmtTabs: "2 Abas",
            uiStyle: "Estilo UI", uiBasic: "Básico", uiAdvanced: "Avançado",
            advUiTitle: "Personalização UI Avançada", advSkins: "Temas Rápidos", advSurface: "Superfície e Cartões",
            advAccent: "Cor de Destaque", advCardStyle: "Estilo Cartão", advCardGlass: "Vidro", advCardElev: "Elevado",
            advCardLine: "Linha Fina", advCardNeon: "Borda Neon", advGradient: "Gradiente Ambiente",
            advRadius: "Arredondamento", advBlur: "Desfoque", advGlow: "Brilho de Destaque",
            advTypography: "Layout e Texto", advDensity: "Densidade", advDensCompact: "Compacto", advDensNormal: "Normal", advDensSpacious: "Espaçoso",
            advFontScale: "Escala Texto", advHeaderStyle: "Cabeçalho", advHdrGrad: "Gradiente", advHdrMin: "Mínimo", advHdrBar: "Barra Destaque",
            advScorePill: "Estilo Nota", advPillTint: "Suave", advPillSolid: "Sólido", advPillOut: "Contorno",
            advAnimations: "Animações Suaves", advReset: "Redefinir Avançado",
            screenAnchor: "Posição na Tela", anchCustom: "Livre (Arrastável)", anchTL: "Sup. Esquerda", anchTR: "Sup. Direita", anchBL: "Inf. Esquerda", anchBR: "Inf. Direita",
            glassOpacity: "Opacidade", themePresets: "Temas", dark: "Escuro", light: "Claro", resetSettings: "Redefinir Tudo",
            activeModel: "Modelo Local Ativo", storageInv: "Armazenamento Local", runnerScript: "Script (JS)", neuralWeights: "Pesos (WASM / NNUE)",
            installLaunch: "Instalar / Iniciar", redownload: "Baixar Novamente", clearCache: "Limpar Cache",
            uciParams: "Parâmetros UCI e Força", maiaParams: "Rating e Amostragem Maia-3",
            hashMem: "Memória Hash (MB)", moveOverhead: "Margem Rede (ms)", skillLevel: "Nível (0–20)",
            eloCap: "Limite de Elo", targetElo: "Elo Alvo", minMoveTime: "Tempo Mínimo (ms)",
            targetRating: "Rating Alvo (600–2600)", moveVariety: "Variedade (Temp)", nucleusSamp: "Amostragem (Top-p)",
            pressKey: "Pressione tecla...", none: "Nenhuma",
            tt: { visuals: "Aparência, setas, cores e formato do painel.", help: "Abre o guia de ajuda pesquisável.", language: "Alterar idioma.", minBtn: "Minimiza para barra compacta.", autoSwitch: "Muda para Local se a API falhar.", mode: "Nuvem/Online usam servidores; Local roda no navegador.", autoTime: "Ajusta profundidade pelo relógio.", depth: "Profundidade fixa sem Tempo Auto.", focus: "Direciona o estilo de jogo dentro do risco.", uiKey: "Atalho para ocultar/exibir a interface.", autoRun: "Analisa automaticamente na sua vez.", silent: "Oculta visuais mantendo a análise ativa.", grade: "Avalia lances com Stockfish 19 Lite em segundo plano.", gradeDepth: "Profundidade (10–20) da avaliação e barra.", autoMove: "Joga automaticamente após o atraso.", humanMode: "Simula lances e ritmo humanos.", humanPreset: "Nível humano alvo.", autoQueue: "Inicia nova partida ao terminar.", autoQueueDelay: "Espera (1–60s) antes de iniciar outra partida.", evalBar: "Exibe a barra vertical de avaliação.", moveKey: "Tecla para jogar manualmente a recomendação.", delayWindow: "Atraso aleatório (0–180s) antes de mover.", analyze: "Analisar posição imediatamente.", localBtn: "Gerenciar motores Stockfish e Maia-3 locais.", visType: "Estilo visual do melhor lance.", pv: "Mostra setas da linha principal.", multiBest: "Mostra top 3 lances com notas.", arrowW: "Espessura das setas.", arrowOp: "Transparência das setas.", dur: "Duração do destaque.", fade: "Desaparecer gradualmente.", persist: "Manter até o próximo lance.", color: "Cor de destaque e setas.", panelLayout: "1 Coluna, 2 Colunas ou 2 Abas.", uiStyle: "Alternar entre UI Básica e Avançada.", advGear: "Abrir personalização da UI Avançada.", anchor: "Fixar painel no canto ou livre.", opacity: "Transparência das janelas.", theme: "Tema Escuro ou Claro.", reset: "Restaurar padrões de fábrica.", modelSel: "Modelo local para baixar e usar.", hash: "RAM do motor (64–128 MB).", overhead: "Margem contra lag (ms).", skill: "Nível 0–20.", limitStr: "Limita força a um Elo específico.", minThink: "Tempo mínimo por lance (ms).", maiaElo: "Força humana simulada (600–2600).", maiaTemp: "0.0 = mais provável; maior = mais variado.", maiaTopP: "Limite de probabilidade dos lances." }
        },
        ru: {
            visuals: "Вид", help: "Помощь", language: "Язык", langTitle: "Выбор языка", helpTitle: "Справка",
            helpSearchPh: "Поиск настроек, связей, советов...", expandAll: "Развернуть все", collapseAll: "Свернуть все", noHelpMatch: "Ничего не найдено.",
            helpBeginner: "Для новичков", helpMore: "Подробнее", helpAllTags: "Все", helpFound: "совпад.",
            tabEngine: "Движок", tabFeatures: "Функции", engineMode: "Режим движка", features: "Функции",
            autoSwitch: "Авто-переключение", cloud: "Облако", online: "Онлайн", local: "Локально",
            autoTime: "Авто-время (часы)", searchDepth: "Глубина", engineFocus: "Стиль движка",
            focusBalanced: "Баланс (#1)", focusAggressive: "Агрессия (тактика)", focusGambit: "Гамбиты и жертвы",
            focusInitiative: "Инициатива", focusSafety: "Безопасность короля", focusConversion: "Реализация (эндшпиль)", focusCustom: "Свой...",
            atkTactics: "Атака / Тактика", kingSafety: "Защита короля", simplify: "Упрощение / Размены", maxRisk: "Макс. риск (cp)",
            toggleUiKey: "Клавиша UI", autoAnalyze: "Авто-анализ", silentMode: "Тихий режим", moveGrading: "Оценка ходов",
            gradingDepth: "Глубина оценки", autoMove: "Авто-ход", humanMode: "Человечный режим", humanProfile: "Профиль",
            autoQueue: "Авто-поиск", queueDelay: "Пауза поиска (с)", evalBar: "Шкала оценки", manualMoveKey: "Клавиша хода",
            delayWindow: "Задержка (с)", analyzePos: "Анализировать", localEngines: "Локальные движки",
            tallyTitle: "Отчёт", white: "Белые", black: "Чёрные", tally: "",
            boardHighlights: "Подсветка доски", styleMode: "Стиль", visOutline: "Неон. контур", visBoxes: "Градиент",
            visArrow: "Стрелка", visNative: "Стрелка сайта", showBestLine: "Стрелки лучшей линии",
            showMultiBest: "Топ-3 стрелки", arrowWidth: "Толщина стрел", arrowOpacity: "Прозрачность стрел",
            fadeDuration: "Затухание", smoothFade: "Плавное затухание", persistMove: "Держать до хода",
            highlightColor: "Цвет подсветки", hue: "Тон", saturation: "Насыщ.", brightness: "Яркость", hexCode: "HEX",
            mainPanel: "Главная панель", panelFormat: "Формат панели", fmtSingle: "1 столбец", fmtDouble: "2 столбца", fmtTabs: "2 вкладки",
            uiStyle: "Стиль UI", uiBasic: "Базовый", uiAdvanced: "Продвин.",
            advUiTitle: "Продвинутый дизайн UI", advSkins: "Быстрые стили", advSurface: "Поверхность и блоки",
            advAccent: "Цвет акцента", advCardStyle: "Стиль блоков", advCardGlass: "Стекло", advCardElev: "Объём",
            advCardLine: "Контур", advCardNeon: "Неон", advGradient: "Фоновый градиент",
            advRadius: "Скругление", advBlur: "Размытие", advGlow: "Свечение",
            advTypography: "Плотность и шрифт", advDensity: "Плотность", advDensCompact: "Компакт", advDensNormal: "Обычно", advDensSpacious: "Свободно",
            advFontScale: "Масштаб текста", advHeaderStyle: "Шапка", advHdrGrad: "Градиент", advHdrMin: "Минимум", advHdrBar: "Полоса",
            advScorePill: "Стиль оценки", advPillTint: "Оттенок", advPillSolid: "Заливка", advPillOut: "Рамка",
            advAnimations: "Плавные анимации", advReset: "Сбросить стиль",
            screenAnchor: "Привязка", anchCustom: "Свободно", anchTL: "Сверху слева", anchTR: "Сверху справа", anchBL: "Снизу слева", anchBR: "Снизу справа",
            glassOpacity: "Прозрачность", themePresets: "Темы", dark: "Тёмная", light: "Светлая", resetSettings: "Сброс настроек",
            activeModel: "Активная модель", storageInv: "Локальное хранилище", runnerScript: "Скрипт (JS)", neuralWeights: "Веса (WASM / NNUE)",
            installLaunch: "Установить / Запуск", redownload: "Перекачать", clearCache: "Очистить кэш",
            uciParams: "Параметры UCI и сила", maiaParams: "Рейтинг и сэмплинг Maia-3",
            hashMem: "Хэш-память (МБ)", moveOverhead: "Буфер пинга (мс)", skillLevel: "Уровень (0–20)",
            eloCap: "Лимит Эло", targetElo: "Целевой Эло", minMoveTime: "Мин. время (мс)",
            targetRating: "Рейтинг (600–2600)", moveVariety: "Разнообразие (Temp)", nucleusSamp: "Выборка (Top-p)",
            pressKey: "Нажмите...", none: "Нет",
            tt: { visuals: "Настройки подсветки, стрелок, цветов и формата панели.", help: "Открыть подробную справку с поиском.", language: "Сменить язык интерфейса.", minBtn: "Свернуть в компактную панель.", autoSwitch: "Переключает на локальный движок при ошибке сервера.", mode: "Облако/Онлайн — серверы; Локально — в браузере.", autoTime: "Подбирает время и глубину по часам.", depth: "Глубина расчёта при выкл. Авто-времени.", focus: "Выбирает атакующие, надёжные или эндшпильные ходы.", uiKey: "Клавиша скрытия/показа всей панели.", autoRun: "Автоматически анализирует ваш ход.", silent: "Скрывает стрелки и цифры на экране.", grade: "Оценивает ходы отдельным Stockfish 19 Lite.", gradeDepth: "Глубина (10–20) оценки и шкалы.", autoMove: "Автоматически делает ход после задержки.", humanMode: "Имитирует выбор ходов и паузы человека.", humanPreset: "Целевой уровень игры человека.", autoQueue: "Автоматически ищет новую игру после окончания.", autoQueueDelay: "Пауза (1–60с) перед поиском новой игры.", evalBar: "Показывает вертикальную шкалу оценки.", moveKey: "Клавиша для ручного хода при выкл. Авто-ходе.", delayWindow: "Случайная задержка (0–180с) перед ходом.", analyze: "Запустить анализ текущей позиции.", localBtn: "Установка и настройка Stockfish / Maia-3.", visType: "Вид отображения лучшего хода.", pv: "Стрелки лучшего продолжения.", multiBest: "Топ-3 хода со значками оценки.", arrowW: "Толщина стрелок.", arrowOp: "Прозрачность стрелок.", dur: "Время показа подсветки.", fade: "Плавное исчезновение.", persist: "Показывать до следующего хода.", color: "Цвет подсветки и стрелок.", panelLayout: "1 столбец, 2 столбца или 2 вкладки.", uiStyle: "Переключить между Базовым и Продвинутым UI.", advGear: "Открыть настройки Продвинутого UI.", anchor: "Угол экрана или свободное перетаскивание.", opacity: "Прозрачность окон.", theme: "Тёмная или светлая тема.", reset: "Сбросить все настройки и размеры.", modelSel: "Выбор локальной модели.", hash: "ОЗУ для движка (64–128 МБ).", overhead: "Запас времени (мс) на задержку сети.", skill: "Сила Stockfish от 0 до 20.", limitStr: "Ограничить силу заданным Эло.", minThink: "Минимальное время на ход (мс).", maiaElo: "Стиль игрока с таким Эло (600–2600).", maiaTemp: "0.0 — самый вероятный ход; выше — больше вариаций.", maiaTopP: "Порог вероятности ходов." }
        },
        zh: {
            visuals: "视觉", help: "帮助", language: "语言", langTitle: "选择语言", helpTitle: "帮助指南",
            helpSearchPh: "搜索设置、交互逻辑、问题排查...", expandAll: "全部展开", collapseAll: "全部折叠", noHelpMatch: "未找到匹配项。",
            helpBeginner: "新手指南", helpMore: "深入", helpAllTags: "全部", helpFound: "项匹配",
            tabEngine: "引擎", tabFeatures: "功能", engineMode: "引擎模式", features: "功能设置",
            autoSwitch: "自动切换", cloud: "云端", online: "在线", local: "本地",
            autoTime: "自动计时", searchDepth: "搜索深度", engineFocus: "引擎风格",
            focusBalanced: "均衡 (#1 最佳)", focusAggressive: "激进 (战术)", focusGambit: "弃子进攻",
            focusInitiative: "主动权 / 压迫", focusSafety: "王的安全", focusConversion: "残局简化", focusCustom: "自定义...",
            atkTactics: "进攻 / 战术", kingSafety: "王的安全", simplify: "简化兑子", maxRisk: "最大风险 (cp)",
            toggleUiKey: "显隐面板键", autoAnalyze: "自动分析", silentMode: "静默模式", moveGrading: "着法评分",
            gradingDepth: "评分深度", autoMove: "自动走棋", humanMode: "拟人模式 (可检测)", humanProfile: "拟人水平",
            autoQueue: "自动匹配", queueDelay: "匹配延迟 (秒)", evalBar: "评估条", manualMoveKey: "手动走棋键",
            delayWindow: "延迟范围 (秒)", analyzePos: "分析当前局面", localEngines: "本地引擎",
            tallyTitle: "报告", white: "白方", black: "黑方", tally: "",
            boardHighlights: "棋盘高亮", styleMode: "显示样式", visOutline: "霓虹边框", visBoxes: "渐变方块",
            visArrow: "矢量箭头", visNative: "原生箭头", showBestLine: "显示主变箭头",
            showMultiBest: "显示多选箭头", arrowWidth: "箭头粗细", arrowOpacity: "箭头透明度",
            fadeDuration: "淡出时长", smoothFade: "平滑淡出", persistMove: "保持至走棋",
            highlightColor: "高亮颜色", hue: "色相", saturation: "饱和度", brightness: "亮度", hexCode: "十六进制",
            mainPanel: "主面板", panelFormat: "面板布局", fmtSingle: "单栏", fmtDouble: "双栏", fmtTabs: "双标签",
            uiStyle: "界面风格", uiBasic: "基础", uiAdvanced: "高级",
            advUiTitle: "高级 UI 自定义", advSkins: "快捷皮肤", advSurface: "表面与卡片",
            advAccent: "强调色", advCardStyle: "卡片样式", advCardGlass: "磨砂玻璃", advCardElev: "立体浮层",
            advCardLine: "极简细框", advCardNeon: "霓虹描边", advGradient: "氛围渐变背景",
            advRadius: "圆角大小", advBlur: "背景模糊", advGlow: "强调光晕",
            advTypography: "间距与字体", advDensity: "行间距密度", advDensCompact: "紧凑", advDensNormal: "标准", advDensSpacious: "宽松",
            advFontScale: "文字缩放", advHeaderStyle: "顶栏样式", advHdrGrad: "渐变", advHdrMin: "极简", advHdrBar: "强调条",
            advScorePill: "评分徽章", advPillTint: "柔和微光", advPillSolid: "实心填充", advPillOut: "描边",
            advAnimations: "流畅微动画", advReset: "重置高级样式",
            screenAnchor: "屏幕停靠", anchCustom: "自由拖动", anchTL: "左上角", anchTR: "右上角", anchBL: "左下角", anchBR: "右下角",
            glassOpacity: "玻璃透明度", themePresets: "主题预设", dark: "深色", light: "浅色", resetSettings: "重置设置",
            activeModel: "当前本地模型", storageInv: "本地缓存状态", runnerScript: "运行脚本 (JS)", neuralWeights: "神经网络权重 (WASM)",
            installLaunch: "安装 / 启动", redownload: "重新下载", clearCache: "清除缓存",
            uciParams: "UCI 参数与棋力", maiaParams: "Maia-3 等级分与采样",
            hashMem: "哈希内存 (MB)", moveOverhead: "网络延迟保护 (ms)", skillLevel: "棋力等级 (0–20)",
            eloCap: "限制等级分", targetElo: "目标 Elo", minMoveTime: "最小思考 (ms)",
            targetRating: "模拟等级分 (600–2600)", moveVariety: "着法多样性 (Temp)", nucleusSamp: "核采样 (Top-p)",
            pressKey: "请按键...", none: "无",
            tt: { visuals: "设置棋盘高亮、箭头、颜色和主面板布局。", help: "打开可搜索的新手帮助指南。", language: "切换界面语言。", minBtn: "折叠为紧凑浮动状态栏。", autoSwitch: "云端出错或限流时自动切换为本地引擎。", mode: "云端/在线使用远程服务器;本地在浏览器内离线运行。", autoTime: "根据剩余时间自动调节搜索深度。", depth: "关闭自动计时后的固定搜索深度。", focus: "在风险容忍度内偏向进攻、防守或残局。", uiKey: "显示或隐藏脚本面板的快捷键。", autoRun: "轮到你走棋时自动分析局面。", silent: "隐藏箭头和分数提示,仅后台运行。", grade: "使用独立 Stockfish 19 Lite 引擎评估每步棋。", gradeDepth: "评分和评估条的计算深度 (10–20)。", autoMove: "等待延迟后自动在棋盘上走棋。", humanMode: "模拟人类棋手选招与自然思考节奏。", humanPreset: "选择拟人水平预设。", autoQueue: "对局结束后自动开始下一局。", autoQueueDelay: "对局结束后等待 1–60 秒再开始下一局。", evalBar: "在棋盘左侧显示实时胜率评估条。", moveKey: "关闭自动走棋时按此键手动走出推荐着法。", delayWindow: "自动走棋前的随机延迟范围 (0–180 秒)。", analyze: "立即分析当前局面。", localBtn: "下载、切换和配置本地引擎。", visType: "选择最佳着法的高亮方式。", pv: "绘制引擎预测的后续最佳着法线。", multiBest: "显示前3个候选着法及评分徽章。", arrowW: "调整箭头粗细。", arrowOp: "调整箭头透明度。", dur: "高亮停留时间。", fade: "平滑淡出而非直接消失。", persist: "保持显示直到走棋。", color: "自定义高亮和箭头颜色。", panelLayout: "切换单栏、双栏或双标签布局。", uiStyle: "在经典基础界面和可自定义高级界面间切换。", advGear: "打开高级 UI 自定义面板。", anchor: "固定在屏幕角落或自由拖动。", opacity: "调整面板透明度。", theme: "切换深色或浅色主题。", reset: "恢复所有默认设置和尺寸。", modelSel: "选择要安装的本地模型。", hash: "分配给引擎的内存。", overhead: "预留网络延迟防止超时。", skill: "Stockfish 棋力 0–20。", limitStr: "限制棋力到指定 Elo。", minThink: "每步最少思考毫秒数。", maiaElo: "模拟对应人类 Elo (600–2600)。", maiaTemp: "0.0 选最常见人类走法;越高越多样。", maiaTopP: "过滤低概率着法。" }
        },
        hi: {
            visuals: "विज़ुअल", help: "सहायता", language: "भाषा", langTitle: "भाषा चुनें", helpTitle: "सहायता मार्गदर्शिका",
            helpSearchPh: "सेटिंग्स, नियम या फ़ीचर खोजें...", expandAll: "सभी खोलें", collapseAll: "सभी बंद करें", noHelpMatch: "कोई परिणाम नहीं मिला।",
            helpBeginner: "शुरुआती गाइड", helpMore: "अधिक", helpAllTags: "सभी", helpFound: "परिणाम",
            tabEngine: "इंजन", tabFeatures: "फ़ीचर्स", engineMode: "इंजन मोड", features: "फ़ीचर्स",
            autoSwitch: "ऑटो-स्विच", cloud: "क्लाउड", online: "ऑनलाइन", local: "लोकल",
            autoTime: "ऑटो टाइम (घड़ी)", searchDepth: "सर्च डेप्थ", engineFocus: "इंजन फ़ोकस",
            focusBalanced: "संतुलित (#1)", focusAggressive: "आक्रामक", focusGambit: "गैम्बिट और बलिदान",
            focusInitiative: "पहल / दबाव", focusSafety: "राजा की सुरक्षा", focusConversion: "एंडगेम रूपांतरण", focusCustom: "कस्टम...",
            atkTactics: "हमला / रणनीति", kingSafety: "राजा सुरक्षा", simplify: "सरल करें", maxRisk: "अधिकतम जोखिम (cp)",
            toggleUiKey: "UI टॉगल कुंजी", autoAnalyze: "ऑटो-एनालाइज़", silentMode: "साइलेंट मोड", moveGrading: "चाल ग्रेडिंग",
            gradingDepth: "ग्रेडिंग डेप्थ", autoMove: "ऑटो-मूव", humanMode: "ह्यूमन मोड", humanProfile: "ह्यूमन प्रोफ़ाइल",
            autoQueue: "ऑटो-क्यू", queueDelay: "क्यू देरी (से.)", evalBar: "मूल्यांकन बार", manualMoveKey: "मैनुअल मूव कुंजी",
            delayWindow: "देरी सीमा (से.)", analyzePos: "स्थिति विश्लेषित करें", localEngines: "लोकल इंजन",
            tallyTitle: "रिपोर्ट", white: "सफ़ेद", black: "काला", tally: "",
            boardHighlights: "बोर्ड हाइलाइट", styleMode: "स्टाइल", visOutline: "नियॉन आउटलाइन", visBoxes: "ग्रेडिएंट बॉक्स",
            visArrow: "वेक्टर तीर", visNative: "नेटिव तीर", showBestLine: "बेस्ट लाइन तीर",
            showMultiBest: "मल्टी-बेस्ट तीर", arrowWidth: "तीर चौड़ाई", arrowOpacity: "तीर पारदर्शिता",
            fadeDuration: "फ़ेड अवधि", smoothFade: "स्मूद फ़ेड", persistMove: "चाल चलने तक रखें",
            highlightColor: "हाइलाइट रंग", hue: "रंग (Hue)", saturation: "सैचुरेशन", brightness: "चमक", hexCode: "हेक्स कोड",
            mainPanel: "मुख्य पैनल", panelFormat: "पैनल फ़ॉर्मेट", fmtSingle: "सिंगल कॉलम", fmtDouble: "डबल कॉलम", fmtTabs: "दो टैब",
            uiStyle: "UI स्टाइल", uiBasic: "बेसिक", uiAdvanced: "एडवांस",
            advUiTitle: "एडवांस UI कस्टमाइज़ेशन", advSkins: "क्विक स्किन्स", advSurface: "सतह और कार्ड",
            advAccent: "एक्सेंट रंग", advCardStyle: "कार्ड स्टाइल", advCardGlass: "ग्लास", advCardElev: "उभरा हुआ",
            advCardLine: "आउटलाइन", advCardNeon: "नियॉन", advGradient: "एम्बिएंट ग्रेडिएंट",
            advRadius: "कोना गोलाई", advBlur: "बैकड्रॉप ब्लर", advGlow: "एक्सेंट चमक",
            advTypography: "दूरी और टेक्स्ट", advDensity: "रो डेंसिटी", advDensCompact: "कॉम्पैक्ट", advDensNormal: "सामान्य", advDensSpacious: "खुला",
            advFontScale: "टेक्स्ट स्केल", advHeaderStyle: "हेडर स्टाइल", advHdrGrad: "ग्रेडिएंट", advHdrMin: "मिनिमल", advHdrBar: "एक्सेंट पट्टी",
            advScorePill: "स्कोर पिल", advPillTint: "टिंटेड", advPillSolid: "सॉलिड", advPillOut: "आउटलाइन",
            advAnimations: "स्मूद एनीमेशन", advReset: "एडवांस रीसेट",
            screenAnchor: "स्क्रीन स्थिति", anchCustom: "फ़्री (खींचें)", anchTL: "ऊपर बाएं", anchTR: "ऊपर दाएं", anchBL: "नीचे बाएं", anchBR: "नीचे दाएं",
            glassOpacity: "पारदर्शिता", themePresets: "थीम", dark: "डार्क", light: "लाइट", resetSettings: "रीसेट सेटिंग्स",
            activeModel: "सक्रिय लोकल मॉडल", storageInv: "लोकल स्टोरेज", runnerScript: "रनर स्क्रिप्ट (JS)", neuralWeights: "न्यूरल वेट्स (WASM)",
            installLaunch: "इंस्टॉल / चलाएं", redownload: "पुनः डाउनलोड", clearCache: "कैश साफ़ करें",
            uciParams: "UCI पैरामीटर और शक्ति", maiaParams: "Maia-3 रेटिंग और सैंपलिंग",
            hashMem: "हैश मेमोरी (MB)", moveOverhead: "ओवरहेड (ms)", skillLevel: "कौशल स्तर (0–20)",
            eloCap: "एलो सीमा", targetElo: "लक्ष्य एलो", minMoveTime: "न्यूनतम समय (ms)",
            targetRating: "लक्ष्य रेटिंग (600–2600)", moveVariety: "विविधता (Temp)", nucleusSamp: "सैंपलिंग (Top-p)",
            pressKey: "कुंजी दबाएं...", none: "कोई नहीं",
            tt: { visuals: "तीर, रंग और पैनल लेआउट बदलें।", help: "खोजने योग्य सहायता गाइड खोलें।", language: "भाषा बदलें।", minBtn: "कॉम्पैक्ट HUD में छोटा करें।", autoSwitch: "API विफल होने पर लोकल पर स्विच करें।", mode: "क्लाउड/ऑनलाइन सर्वर से; लोकल ब्राउज़र में चलता है।", autoTime: "घड़ी के अनुसार गहराई समायोजित करें।", depth: "ऑटो टाइम बंद होने पर गहराई।", focus: "खेल की शैली चुनें।", uiKey: "पैनल छिपाने/दिखाने की कुंजी।", autoRun: "आपकी बारी पर स्वतः विश्लेषण।", silent: "विज़ुअल और स्कोर छिपाता है।", grade: "Stockfish 19 Lite से चालें ग्रेड करता है।", gradeDepth: "ग्रेडिंग गहराई (10–20)।", autoMove: "देरी के बाद स्वतः चाल चले।", humanMode: "मानव जैसी चाल और गति।", humanPreset: "मानव कौशल स्तर चुनें।", autoQueue: "खेल समाप्त होने पर नया खेल शुरू करे।", autoQueueDelay: "अगले खेल से पहले प्रतीक्षा (1–60 से.)।", evalBar: "बोर्ड के पास मूल्यांकन बार दिखाए।", moveKey: "मैनुअल रूप से सुझाई चाल चलने की कुंजी।", delayWindow: "ऑटो-मूव देरी (0–180 से.)।", analyze: "तुरंत स्थिति का विश्लेषण करें।", localBtn: "लोकल इंजन इंस्टॉल या सेट करें।", visType: "बोर्ड पर चाल दिखाने का तरीका।", pv: "सर्वोत्तम निरंतरता तीर दिखाएं।", multiBest: "ग्रेड बैज के साथ शीर्ष 3 चालें।", arrowW: "तीर की मोटाई।", arrowOp: "तीर की पारदर्शिता।", dur: "हाइलाइट समय।", fade: "धीरे-धीरे गायब हो।", persist: "अगली चाल तक दिखे।", color: "हाइलाइट रंग चुनें।", panelLayout: "1 कॉलम, 2 कॉलम या 2 टैब चुनें।", uiStyle: "बेसिक और एडवांस UI के बीच बदलें।", advGear: "एडवांस UI सेटिंग्स खोलें।", anchor: "पैनल को कोने में लगाएं या खींचें।", opacity: "मेनू पारदर्शिता।", theme: "डार्क या लाइट थीम।", reset: "सभी सेटिंग्स रीसेट करें।", modelSel: "लोकल मॉडल चुनें।", hash: "इंजन RAM (MB)।", overhead: "लैग बफ़र (ms)।", skill: "ताकत 0–20।", limitStr: "एलो सीमित करें।", minThink: "न्यूनतम समय (ms)।", maiaElo: "मानव रेटिंग (600–2600)।", maiaTemp: "0.0 = सबसे स्वाभाविक।", maiaTopP: "शीर्ष संभाव्यता सीमा।" }
        },
        ar: {
            visuals: "المظهر", help: "مساعدة", language: "اللغة", langTitle: "اختر اللغة", helpTitle: "دليل المساعدة",
            helpSearchPh: "ابحث في الإعدادات والتفاعلات...", expandAll: "توسيع الكل", collapseAll: "طي الكل", noHelpMatch: "لم يتم العثور على نتائج.",
            helpBeginner: "للمبتدئين", helpMore: "المزيد", helpAllTags: "الكل", helpFound: "نتائج",
            tabEngine: "المحرك", tabFeatures: "الميزات", engineMode: "وضع المحرك", features: "الميزات",
            autoSwitch: "تبديل تلقائي", cloud: "سحابي", online: "أونلاين", local: "محلي",
            autoTime: "وقت تلقائي (الساعة)", searchDepth: "عمق البحث", engineFocus: "تركيز المحرك",
            focusBalanced: "متوازن (#1)", focusAggressive: "هجومي (تكتيك)", focusGambit: "غامبيت وتضحيات",
            focusInitiative: "مبادرة / ضغط", focusSafety: "أمان الملك", focusConversion: "حسم النهايات", focusCustom: "مخصص...",
            atkTactics: "هجوم / تكتيك", kingSafety: "أمان الملك", simplify: "تبسيط وتكسير", maxRisk: "أقصى مخاطرة",
            toggleUiKey: "زر إظهار الواجهة", autoAnalyze: "تحليل تلقائي", silentMode: "الوضع الصامت", moveGrading: "تقييم النقلات",
            gradingDepth: "عمق التقييم", autoMove: "لعب تلقائي", humanMode: "الوضع البشري", humanProfile: "المستوى البشري",
            autoQueue: "طابور تلقائي", queueDelay: "تأخير الطابور (ث)", evalBar: "شريط التقييم", manualMoveKey: "زر النقلة اليدوية",
            delayWindow: "نافذة التأخير (ث)", analyzePos: "تحليل الوضع", localEngines: "المحركات المحلية",
            tallyTitle: "التقرير", white: "الأبيض", black: "الأسود", tally: "",
            boardHighlights: "تحديد الرقعة", styleMode: "النمط", visOutline: "إطار نيون", visBoxes: "مربع متدرج",
            visArrow: "سهم متجهي", visNative: "سهم الموقع", showBestLine: "أسهم أفضل خط",
            showMultiBest: "أسهم أفضل 3 نقلات", arrowWidth: "عرض السهم", arrowOpacity: "شفافية السهم",
            fadeDuration: "مدة التلاشي", smoothFade: "تلاشي ناعم", persistMove: "يبقى حتى النقلة",
            highlightColor: "لون التحديد", hue: "الصبغة", saturation: "التشبع", brightness: "السطوع", hexCode: "كود Hex",
            mainPanel: "اللوحة الرئيسية", panelFormat: "تخطيط اللوحة", fmtSingle: "عمود واحد", fmtDouble: "عمودان", fmtTabs: "تبويبان",
            uiStyle: "نمط الواجهة", uiBasic: "أساسي", uiAdvanced: "متقدم",
            advUiTitle: "تخصيص الواجهة المتقدمة", advSkins: "سمات سريعة", advSurface: "السطح والبطاقات",
            advAccent: "اللون الأساسي", advCardStyle: "نمط البطاقة", advCardGlass: "زجاجي", advCardElev: "بارز",
            advCardLine: "إطار دقيق", advCardNeon: "حافة نيون", advGradient: "تدرج خلفي",
            advRadius: "تدوير الحواف", advBlur: "تمويه الخلفية", advGlow: "توهج اللون",
            advTypography: "التباعد والنص", advDensity: "كثافة الصفوف", advDensCompact: "مضغوط", advDensNormal: "عادي", advDensSpacious: "موسع",
            advFontScale: "حجم الخط", advHeaderStyle: "شريط العنوان", advHdrGrad: "متدرج", advHdrMin: "بسيط", advHdrBar: "شريط ملون",
            advScorePill: "شارة التقييم", advPillTint: "مظلل", advPillSolid: "صلب", advPillOut: "محدد",
            advAnimations: "حركات ناعمة", advReset: "إعادة ضبط المتقدم",
            screenAnchor: "موقع الشاشة", anchCustom: "حر (قابل للسحب)", anchTL: "أعلى اليسار", anchTR: "أعلى اليمين", anchBL: "أسفل اليسار", anchBR: "أسفل اليمين",
            glassOpacity: "الشفافية", themePresets: "السمات", dark: "داكن", light: "فاتح", resetSettings: "إعادة ضبط",
            activeModel: "النموذج النشط", storageInv: "التخزين المحلي", runnerScript: "سكربت التشغيل", neuralWeights: "أوزان الشبكة",
            installLaunch: "تثبيت / تشغيل", redownload: "إعادة تنزيل", clearCache: "مسح الكاش",
            uciParams: "إعدادات UCI والقوة", maiaParams: "تقييم وعينات Maia-3",
            hashMem: "ذاكرة Hash (MB)", moveOverhead: "تعويض الشبكة (ms)", skillLevel: "المهارة (0–20)",
            eloCap: "تحديد Elo", targetElo: "Elo المستهدف", minMoveTime: "أقل وقت (ms)",
            targetRating: "التقييم (600–2600)", moveVariety: "التنوع (Temp)", nucleusSamp: "العينة (Top-p)",
            pressKey: "اضغط زراً...", none: "لا شيء",
            tt: { visuals: "إعدادات الأسهم والألوان وتخطيط اللوحة.", help: "فتح دليل المساعدة القابل للبحث.", language: "تغيير لغة الواجهة.", minBtn: "تصغير اللوحة إلى شريط عائم.", autoSwitch: "التحويل للمحرك المحلي عند فشل السحابي.", mode: "السحابي عبر الخادم؛ المحلي يعمل داخل المتصفح.", autoTime: "يضبط العمق تلقائياً حسب الساعة.", depth: "عمق الحساب عند إيقاف الوقت التلقائي.", focus: "يوجه اختيار النقلة نحو الهجوم أو الأمان.", uiKey: "اختصار لإخفاء وإظهار الواجهة.", autoRun: "يحلل تلقائياً عند دورك.", silent: "يخفي الأسهم والأرقام مع استمرار التحليل.", grade: "يقيّم النقلات عبر Stockfish 19 Lite.", gradeDepth: "عمق التقييم (10–20).", autoMove: "ينفذ النقلة تلقائياً بعد التأخير.", humanMode: "يحاكي تفكير وتوقيت البشر.", humanPreset: "اختيار مستوى المحاكاة البشرية.", autoQueue: "يبدأ مباراة جديدة تلقائياً بعد الانتهاء.", autoQueueDelay: "الانتظار (1–60 ث) قبل المباراة التالية.", evalBar: "يعرض شريط التقييم بجانب الرقعة.", moveKey: "زر للعب النقلة المقترحة يدوياً.", delayWindow: "تأخير عشوائي (0–180 ث) قبل اللعب.", analyze: "تحليل الوضع الحالي فوراً.", localBtn: "تثبيت وضبط المحركات المحلية.", visType: "طريقة عرض أفضل نقلة.", pv: "عرض أسهم الخط الرئيسي.", multiBest: "عرض أفضل 3 نقلات مع شاراتها.", arrowW: "سمك الأسهم.", arrowOp: "شفافية الأسهم.", dur: "مدة ظهور التحديد.", fade: "تلاشي تدريجي.", persist: "البقاء حتى تُلعب نقلة.", color: "تخصيص لون التحديد.", panelLayout: "تبديل بين عمود، عمودين، أو تبويبين.", uiStyle: "التبديل بين النمط الأساسي والمتقدم.", advGear: "فتح إعدادات الواجهة المتقدمة.", anchor: "تثبيت اللوحة أو تحريكها بحرية.", opacity: "شفافية القوائم.", theme: "تبديل بين داكن وفاتح.", reset: "استعادة الإعدادات الافتراضية.", modelSel: "اختيار المحرك المحلي.", hash: "حجم الذاكرة.", overhead: "هامش التأخير.", skill: "القوة من 0 إلى 20.", limitStr: "تقييد القوة بتقييم محدد.", minThink: "الحد الأدنى للتفكير.", maiaElo: "مستوى بشري مستهدف.", maiaTemp: "0.0 للأكثر طبيعية.", maiaTopP: "حد الاحتمالية." }
        },
        tr: {
            visuals: "Görünüm", help: "Yardım", language: "Dil", langTitle: "Dil Seçin", helpTitle: "Yardım Rehberi",
            helpSearchPh: "Ayar, etkileşim veya sorun ara...", expandAll: "Tümünü Aç", collapseAll: "Tümünü Kapat", noHelpMatch: "Eşleşen konu yok.",
            helpBeginner: "Başlangıç", helpMore: "Detaylar", helpAllTags: "Tümü", helpFound: "sonuç",
            tabEngine: "Motor", tabFeatures: "Özellikler", engineMode: "Motor Modu", features: "Özellikler",
            autoSwitch: "Oto-Geçiş", cloud: "Bulut", online: "Çevrimiçi", local: "Yerel",
            autoTime: "Oto Süre (Saat)", searchDepth: "Arama Derinliği", engineFocus: "Motor Odağı",
            focusBalanced: "Dengeli (#1 En İyi)", focusAggressive: "Agresif (Taktik)", focusGambit: "Gambit & Fedalar",
            focusInitiative: "İnisiyatif / Baskı", focusSafety: "Şah Güvenliği", focusConversion: "Oyunsonu Dönüşüm", focusCustom: "Özel...",
            atkTactics: "Atak / Taktik", kingSafety: "Şah Güvenliği", simplify: "Sadeleştirme", maxRisk: "Maks Risk (cp)",
            toggleUiKey: "Arayüz Tuşu", autoAnalyze: "Oto-Analiz", silentMode: "Sessiz Mod", moveGrading: "Hamle Puanlama",
            gradingDepth: "Puanlama Derinliği", autoMove: "Oto-Hamle", humanMode: "İnsan Modu (Algılanabilir)", humanProfile: "İnsan Profili",
            autoQueue: "Oto-Sıra", queueDelay: "Sıra Bekleme (sn)", evalBar: "Değerlendirme Çubuğu", manualMoveKey: "Manuel Hamle Tuşu",
            delayWindow: "Gecikme Aralığı (sn)", analyzePos: "Konumu Analiz Et", localEngines: "Yerel Motorlar",
            tallyTitle: "Rapor", white: "Beyaz", black: "Siyah", tally: "",
            boardHighlights: "Tahta Vurguları", styleMode: "Stil", visOutline: "Neon Çerçeve", visBoxes: "Gradyan Kutu",
            visArrow: "Vektör Ok", visNative: "Site Oku", showBestLine: "En İyi Devam Okları",
            showMultiBest: "Çoklu En İyi Oklar", arrowWidth: "Ok Kalınlığı", arrowOpacity: "Ok Saydamlığı",
            fadeDuration: "Solma Süresi", smoothFade: "Yumuşak Solma", persistMove: "Hamleye Kadar Tut",
            highlightColor: "Vurgu Rengi", hue: "Ton", saturation: "Doygunluk", brightness: "Parlaklık", hexCode: "Hex Kodu",
            mainPanel: "Ana Panel", panelFormat: "Panel Düzeni", fmtSingle: "Tek Sütun", fmtDouble: "Çift Sütun", fmtTabs: "İki Sekme",
            uiStyle: "Arayüz Stili", uiBasic: "Temel", uiAdvanced: "Gelişmiş",
            advUiTitle: "Gelişmiş Arayüz Ayarları", advSkins: "Hızlı Temalar", advSurface: "Yüzey ve Kartlar",
            advAccent: "Vurgu Rengi", advCardStyle: "Kart Stili", advCardGlass: "Buzlu Cam", advCardElev: "Derinlik",
            advCardLine: "İnce Çizgi", advCardNeon: "Neon Kenar", advGradient: "Ortam Gradyanı",
            advRadius: "Köşe Ovalliği", advBlur: "Bulanıklık", advGlow: "Vurgu Parlaması",
            advTypography: "Düzen ve Yazı", advDensity: "Satır Sıklığı", advDensCompact: "Sıkı", advDensNormal: "Normal", advDensSpacious: "Geniş",
            advFontScale: "Yazı Boyutu", advHeaderStyle: "Başlık Stili", advHdrGrad: "Gradyan", advHdrMin: "Minimal", advHdrBar: "Vurgu Şeridi",
            advScorePill: "Puan Rozeti", advPillTint: "Yumuşak", advPillSolid: "Dolu", advPillOut: "Çerçeveli",
            advAnimations: "Akıcı Animasyonlar", advReset: "Gelişmiş Stili Sıfırla",
            screenAnchor: "Ekran Konumu", anchCustom: "Serbest (Sürükle)", anchTL: "Sol Üst", anchTR: "Sağ Üst", anchBL: "Sol Alt", anchBR: "Sağ Alt",
            glassOpacity: "Cam Saydamlığı", themePresets: "Temalar", dark: "Koyu", light: "Açık", resetSettings: "Sıfırla",
            activeModel: "Aktif Yerel Model", storageInv: "Yerel Depolama", runnerScript: "Çalıştırıcı (JS)", neuralWeights: "Ağ Ağırlıkları (WASM)",
            installLaunch: "Kur / Başlat", redownload: "Yeniden İndir", clearCache: "Önbelleği Sil",
            uciParams: "UCI Ayarları ve Güç", maiaParams: "Maia-3 Puan ve Örnekleme",
            hashMem: "Hash Belleği (MB)", moveOverhead: "Ağ Payı (ms)", skillLevel: "Yetenek (0–20)",
            eloCap: "Elo Sınırı", targetElo: "Hedef Elo", minMoveTime: "Min Süre (ms)",
            targetRating: "Hedef Puan (600–2600)", moveVariety: "Çeşitlilik (Temp)", nucleusSamp: "Çekirdek (Top-p)",
            pressKey: "Tuşa basın...", none: "Yok",
            tt: { visuals: "Ok, renk ve panel düzeni ayarlarını açar.", help: "Aranabilir yardım rehberini açar.", language: "Arayüz dilini değiştirir.", minBtn: "Paneli kompakt HUD çubuğuna küçültür.", autoSwitch: "API başarısız olursa Yerel motora geçer.", mode: "Bulut/Çevrimiçi sunucu kullanır; Yerel tarayıcıda çalışır.", autoTime: "Saate göre derinliği otomatik ayarlar.", depth: "Oto Süre kapalıyken hesaplama derinliği.", focus: "Hamle seçimini taktik veya güvenliğe yönlendirir.", uiKey: "Paneli gizle/göster kısayolu.", autoRun: "Sıra size gelince otomatik analiz eder.", silent: "Arka planda analiz yaparken görselleri gizler.", grade: "Stockfish 19 Lite ile hamleleri puanlar.", gradeDepth: "Puanlama ve çubuk derinliği (10–20).", autoMove: "Gecikmeden sonra hamleyi otomatik oynar.", humanMode: "İnsan benzeri hamle ve düşünme süresi uygular.", humanPreset: "Hedef insan seviyesi.", autoQueue: "Oyun bitince otomatik yeni rakip arar.", autoQueueDelay: "Yeni oyun öncesi bekleme (1–60 sn).", evalBar: "Tahta yanında değerlendirme çubuğu gösterir.", moveKey: "Oto-Hamle kapalıyken öneriyi oynama tuşu.", delayWindow: "Oto-Hamle öncesi rastgele bekleme (0–180 sn).", analyze: "Mevcut konumu hemen analiz eder.", localBtn: "Yerel Stockfish ve Maia-3 motorlarını yönetir.", visType: "En iyi hamle gösterim biçimi.", pv: "Tahmini en iyi devam yolunu gösterir.", multiBest: "İlk 3 adayı rozetlerle gösterir.", arrowW: "Ok kalınlığı.", arrowOp: "Ok saydamlığı.", dur: "Vurgu görünme süresi.", fade: "Yumuşakça kaybolur.", persist: "Hamle yapılana dek kalır.", color: "Vurgu ve ok rengi.", panelLayout: "Tek Sütun, Çift Sütun veya İki Sekme.", uiStyle: "Temel ve Gelişmiş arayüz arasında geçiş yapın.", advGear: "Gelişmiş arayüz özelleştirme panelini açar.", anchor: "Paneli köşeye sabitle veya serbest bırak.", opacity: "Pencere saydamlığı.", theme: "Koyu veya Açık tema.", reset: "Tüm ayarları varsayılana döndürür.", modelSel: "Kurulacak yerel model.", hash: "Motor RAM boyutu.", overhead: "Gecikme güvenlik payı (ms).", skill: "Stockfish gücü 0–20.", limitStr: "Belirli bir Elo ile sınırlar.", minThink: "Hamle başı en az süre (ms).", maiaElo: "Hedef insan seviyesi (600–2600).", maiaTemp: "0.0 = en olası insan hamlesi.", maiaTopP: "Olasılık eşiği." }
        }
    };

    function t(key) {
        const lang = I18N[settings.language] ? settings.language : "en";
        return I18N[lang][key] ?? I18N.en[key] ?? key;
    }

    function tt(key) {
        const lang = I18N[settings.language] ? settings.language : "en";
        return I18N[lang]?.tt?.[key] ?? I18N.en.tt[key] ?? "";
    }

    function applyLanguage() {
        if (!state.shadow) return;
        const sh = state.shadow;
        sh.querySelectorAll("[data-i18n]").forEach(el => {
            const k = el.getAttribute("data-i18n");
            if (k) el.textContent = t(k);
        });
        sh.querySelectorAll("[data-i18n-title]").forEach(el => {
            const k = el.getAttribute("data-i18n-title");
            if (k) el.setAttribute("title", tt(k));
        });
        sh.querySelectorAll("[data-i18n-ph]").forEach(el => {
            const k = el.getAttribute("data-i18n-ph");
            if (k) el.setAttribute("placeholder", t(k));
        });
        const btnMK = sh.getElementById("btnMoveKeybind");
        if (btnMK && btnMK.textContent !== t("pressKey")) {
            btnMK.textContent = (!settings.moveKeybind || settings.moveKeybind === "None") ? t("none") : settings.moveKeybind;
        }
        const btnUK = sh.getElementById("btnUiKeybind");
        if (btnUK && btnUK.textContent !== t("pressKey")) {
            btnUK.textContent = (!settings.uiKeybind || settings.uiKeybind === "None") ? t("none") : settings.uiKeybind;
        }
        renderHelpChips();
        renderHelpGuide(sh.getElementById("helpSearch")?.value || "");
        renderLangList();
        if (state.ui?.gradeBreakdown) state.ui.gradeBreakdown.dataset.lastHtml = "";
        updateUI();
    }

    function renderLangList() {
        const list = state.shadow?.getElementById("langList");
        if (!list) return;
        const cur = I18N[settings.language] ? settings.language : "en";
        list.innerHTML = LANG_LIST.map(l => `
            <button type="button" class="lang-item ${l.code === cur ? "active" : ""}" data-lang="${l.code}">
                <span class="lang-flag">${l.flag}</span>
                <span class="lang-name">${l.name}</span>
                <span class="lang-check">${l.code === cur ? "✓" : ""}</span>
            </button>
        `).join("");
        list.querySelectorAll(".lang-item").forEach(btn => {
            btn.onclick = () => {
                saveSetting("language", btn.dataset.lang);
                applyLanguage();
                if (state.ui.langModalOv) state.ui.langModalOv.style.display = "none";
            };
        });
    }

    function escapeHtml(s) {
        return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    }

    function highlightTerms(text, tokens) {
        let out = escapeHtml(text);
        if (!tokens || !tokens.length) return out;
        const safe = tokens.filter(Boolean).map(w => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
        if (!safe.length) return out;
        try {
            const re = new RegExp(`(${safe.join("|")})`, "gi");
            out = out.replace(re, `<mark class="help-mark">$1</mark>`);
        } catch (_) {}
        return out;
    }

    function renderHelpChips() {
        const bar = state.shadow?.getElementById("helpChips");
        if (!bar) return;
        const activeTag = state._helpTag || "all";
        const tags = [
            ["all", t("helpAllTags")],
            ["interactions", "Interactions"],
            ["engines", t("engineMode")],
            ["humanized", "Humanized"],
            ["visuals", t("visuals")],
            ["grading", t("moveGrading")],
            ["ui", t("mainPanel")],
            ["controls", "Keys & Delays"]
        ];
        bar.innerHTML = tags.map(([id, lbl]) =>
            `<button type="button" class="help-chip ${activeTag === id ? "active" : ""}" data-tag="${id}">${lbl}</button>`
        ).join("");
        bar.querySelectorAll(".help-chip").forEach(ch => {
            ch.onclick = () => {
                state._helpTag = ch.dataset.tag;
                renderHelpChips();
                renderHelpGuide(state.shadow?.getElementById("helpSearch")?.value || "");
            };
        });
    }

    function renderHelpGuide(filter = "") {
        const body = state.shadow?.getElementById("helpList");
        const countEl = state.shadow?.getElementById("helpStats");
        if (!body) return;
        const tagFilter = state._helpTag || "all";
        const tokens = String(filter || "").trim().toLowerCase().split(/\s+/).filter(Boolean);
        const openState = state._helpOpenMap || {};
        const tabState = state._helpTabMap || {};

        const scored = [];
        HELP_RICH_EN.forEach((sec, idx) => {
            if (tagFilter !== "all" && sec.tag !== tagFilter) return;
            const secHay = (sec.title + " " + (sec.keywords || "")).toLowerCase();
            const matchItem = (item) => {
                if (!tokens.length) return true;
                const h = (secHay + " " + item[0] + " " + item[1]).toLowerCase();
                return tokens.every(tok => h.includes(tok));
            };
            const begMatches = sec.beginner.filter(matchItem);
            const moreMatches = sec.more.filter(matchItem);
            if (tokens.length && !begMatches.length && !moreMatches.length) return;

            let score = 0;
            if (tokens.length) {
                for (const tok of tokens) {
                    if (sec.title.toLowerCase().includes(tok)) score += 6;
                    if ((sec.keywords || "").toLowerCase().includes(tok)) score += 3;
                }
                score += begMatches.length * 4 + moreMatches.length * 4;
            }
            scored.push({ sec, idx, begMatches, moreMatches, score });
        });

        if (tokens.length) scored.sort((a, b) => b.score - a.score);

        let totalItems = 0;
        const html = scored.map(({ sec, idx, begMatches, moreMatches }) => {
            const isOpen = tokens.length ? true : (openState[idx] !== undefined ? openState[idx] : idx === 0);
            let curTab = tabState[idx] || "beginner";
            if (tokens.length) {
                if (curTab === "beginner" && !begMatches.length && moreMatches.length) curTab = "more";
                else if (curTab === "more" && !moreMatches.length && begMatches.length) curTab = "beginner";
            }
            const begList = tokens.length ? (begMatches.length ? begMatches : sec.beginner) : sec.beginner;
            const moreList = tokens.length ? (moreMatches.length ? moreMatches : sec.more) : sec.more;
            totalItems += tokens.length ? (begMatches.length + moreMatches.length) : (sec.beginner.length + sec.more.length);

            const renderItems = (arr) => arr.map(([it, idesc]) => `
                <div class="help-item">
                    <div class="help-item-q">${highlightTerms(it, tokens)}</div>
                    <div class="help-item-a">${highlightTerms(idesc, tokens)}</div>
                </div>
            `).join("");

            return `
                <div class="help-acc ${isOpen ? "open" : ""}" data-hidx="${idx}">
                    <button type="button" class="help-acc-head">
                        <span>${highlightTerms(sec.title, tokens)}</span>
                        <span style="display:inline-flex; align-items:center; gap:6px;">
                            ${tokens.length ? `<span class="help-badge-cnt">${begMatches.length + moreMatches.length}</span>` : ""}
                            <span class="help-acc-arrow">${isOpen ? "▾" : "▸"}</span>
                        </span>
                    </button>
                    <div class="help-acc-body" style="display:${isOpen ? "flex" : "none"};">
                        <div class="seg-control help-subtabs">
                            <button type="button" class="seg-btn help-subtab ${curTab==="beginner"?"active":""}" data-htab="beginner">${t("helpBeginner")}${tokens.length ? ` (${begMatches.length})` : ""}</button>
                            <button type="button" class="seg-btn help-subtab ${curTab==="more"?"active":""}" data-htab="more">${t("helpMore")}${tokens.length ? ` (${moreMatches.length})` : ""}</button>
                        </div>
                        <div class="help-pane" data-pane="beginner" style="display:${curTab==="beginner"?"flex":"none"};">${renderItems(begList)}</div>
                        <div class="help-pane" data-pane="more" style="display:${curTab==="more"?"flex":"none"};">${renderItems(moreList)}</div>
                    </div>
                </div>
            `;
        }).join("");

        if (countEl) {
            countEl.textContent = `${totalItems} ${t("helpFound")} · ${scored.length}/${HELP_RICH_EN.length}`;
        }
        body.innerHTML = scored.length ? html : `<div style="padding:18px; text-align:center; color:var(--bot-t-sec); font-size:12px;">${t("noHelpMatch")}</div>`;
        body.querySelectorAll(".help-acc-head").forEach(btn => {
            btn.onclick = () => {
                const wrap = btn.closest(".help-acc");
                const idx = wrap.dataset.hidx;
                const nowOpen = !wrap.classList.contains("open");
                wrap.classList.toggle("open", nowOpen);
                wrap.querySelector(".help-acc-body").style.display = nowOpen ? "flex" : "none";
                wrap.querySelector(".help-acc-arrow").textContent = nowOpen ? "▾" : "▸";
                if (!state._helpOpenMap) state._helpOpenMap = {};
                state._helpOpenMap[idx] = nowOpen;
            };
        });
        body.querySelectorAll(".help-subtab").forEach(tabBtn => {
            tabBtn.onclick = (e) => {
                e.stopPropagation();
                const wrap = tabBtn.closest(".help-acc");
                const idx = wrap.dataset.hidx;
                const target = tabBtn.dataset.htab;
                if (!state._helpTabMap) state._helpTabMap = {};
                state._helpTabMap[idx] = target;
                wrap.querySelectorAll(".help-subtab").forEach(b => b.classList.toggle("active", b.dataset.htab === target));
                wrap.querySelectorAll(".help-pane").forEach(p => { p.style.display = p.dataset.pane === target ? "flex" : "none"; });
            };
        });
    }

    function getSiteDefaults() {
        return SITE_UI_DEFAULTS[getSiteKey()] || SITE_UI_DEFAULTS.cc;
    }

    function getLayoutStoredSize(fmt) {
        const site = getSiteKey();
        const key = PANEL_LAYOUT_DEFAULTS[fmt] ? fmt : "double";
        const def = getSiteDefaults().panel[key] || PANEL_LAYOUT_DEFAULTS[key];
        let w; try { w = GM_getValue(`bot_${site}_panelW_${key}`); } catch(_) {}
        if (w === undefined || w === null || w === "") w = lsGet(`bot_${site}_panelW_${key}`, def.w);
        let h; try { h = GM_getValue(`bot_${site}_panelH_${key}`); } catch(_) {}
        if (h === undefined || h === null || h === "") h = lsGet(`bot_${site}_panelH_${key}`, def.h);
        return { w: w || def.w, h: h || def.h, minW: def.minW };
    }

    function getReportStoredGeometry() {
        const site = getSiteKey();
        const def = getSiteDefaults().tally;
        const read = (k, d) => {
            let v; try { v = GM_getValue(`bot_${site}_${k}`); } catch(_) {}
            if (v === undefined || v === null || v === "") v = lsGet(`bot_${site}_${k}`, d);
            return (v === undefined || v === null || v === "") ? d : v;
        };
        return {
            w: read("tallyW", def.w),
            h: read("tallyH", def.h),
            x: read("tallyX", def.x),
            y: read("tallyY", def.y),
            minW: def.minW,
            minH: def.minH,
            right: def.right
        };
    }

    function applyTallyPositionAndSize() {
        const tp = state.ui?.tallyPanel;
        if (!tp) return;
        const g = getReportStoredGeometry();
        tp.style.minWidth = g.minW + "px";
        tp.style.minHeight = g.minH + "px";
        tp.style.width = g.w;
        tp.style.height = g.h;
        tp.style.bottom = "";
        if (g.x === "auto") {
            tp.style.left = "auto";
            tp.style.right = g.right + "px";
        } else {
            tp.style.right = "auto";
            tp.style.left = Math.max(0, Number(g.x) || 0) + "px";
        }
        tp.style.top = Math.max(0, Number(g.y) || 0) + "px";
        if (tp.style.display === "flex") {
            const tr = tp.getBoundingClientRect();
            if (tr.right > window.innerWidth) {
                tp.style.right = "auto";
                tp.style.left = Math.max(0, window.innerWidth - tr.width - 12) + "px";
            }
            if (tr.bottom > window.innerHeight) tp.style.top = Math.max(0, window.innerHeight - tr.height - 12) + "px";
        }
    }

    // --- USER INTERFACE ---
    function createUI() {
        if (state.ui.panel) return;

        let shadowMount = document.querySelector("#shadowMount");
        if (!shadowMount) {
            shadowMount = document.createElement("div");
            shadowMount.id = "shadowMount";
            shadowMount.style.cssText = "position:absolute; top:0; left:0; width:0; height:0; border:none; padding:0; margin:0; z-index:2147483647; pointer-events:none;";
            state.shadow = shadowMount.attachShadow({ mode: "closed" });
            (document.fullscreenElement || document.body || document.documentElement).appendChild(shadowMount);
        }

        const shadow = state.shadow;
        const initLayout = PANEL_LAYOUT_DEFAULTS[settings.panelLayout] ? settings.panelLayout : "double";
        const initSize = getLayoutStoredSize(initLayout);
        const savedW = initSize.w;
        const savedH = initSize.h;
        const siteKey = getSiteKey();
        const reportGeom = getReportStoredGeometry();
        let isMini; try { isMini = GM_getValue(`bot_${siteKey}_isMini`); } catch(_) {} if (isMini === undefined || isMini === null) isMini = lsGet(`bot_${siteKey}_isMini`, false);

        const style = `
            :host { all: initial; }
            * {
                box-sizing: border-box;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
                pointer-events: auto;
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
                text-rendering: optimizeLegibility;
            }

            /* Sleek Custom Scrollbars */
            * {
                scrollbar-width: thin;
                scrollbar-color: rgba(255, 255, 255, 0.22) rgba(0, 0, 0, 0.2);
            }
            ::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }
            ::-webkit-scrollbar-track {
                background: rgba(0, 0, 0, 0.18);
                border-radius: 4px;
            }
            ::-webkit-scrollbar-thumb {
                background: rgba(255, 255, 255, 0.18);
                border-radius: 4px;
                border: 1px solid rgba(255, 255, 255, 0.05);
            }
            ::-webkit-scrollbar-thumb:hover {
                background: rgba(255, 255, 255, 0.32);
            }
            ::-webkit-scrollbar-thumb:active {
                background: var(--bot-primary, #388bfd);
            }
            ::-webkit-scrollbar-corner {
                background: transparent;
            }

            #enginePanel, #modal, #localModal {
                --bot-bg: ${settings.themeBg};
                --bot-b: ${settings.themeBorder};
                --bot-p: ${settings.themePrimary};
                --bot-t: ${settings.themeText};
                --bot-primary: ${settings.themePrimary};
            }

            #enginePanel {
                position: fixed;
                width: ${savedW};
                height: ${savedH};
                min-width: ${initSize.minW}px;
                max-width: calc(100vw - 24px);
                max-height: calc(100vh - 24px);
                background: var(--bot-bg);
                border: 1px solid var(--bot-b);
                color: var(--bot-t);
                z-index: 9999;
                font-size: 13px;
                line-height: 1.4;
                box-shadow:
                    0 32px 64px -12px rgba(0,0,0,0.85),
                    0 0 0 1px rgba(255,255,255,0.07) inset,
                    0 1px 0 rgba(255,255,255,0.12) inset;
                display: flex;
                flex-direction: column;
                /* Resize only from bottom — panel grows downward */
                resize: vertical;
                overflow: hidden;
                opacity: ${settings.menuOpacity};
                border-radius: 16px;
                backdrop-filter: blur(28px) saturate(200%);
                transition: box-shadow 0.2s ease, opacity 0.15s ease;
                /* Custom bottom-only resize handle area */
                padding-bottom: 6px;
            }
            #enginePanel::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                width: 36px;
                height: 4px;
                border-radius: 2px;
                background: rgba(255,255,255,0.18);
                pointer-events: none;
                margin-bottom: 2px;
                z-index: 1;
            }
            #enginePanel:hover {
                box-shadow:
                    0 36px 72px -12px rgba(0,0,0,0.90),
                    0 0 0 1px rgba(255,255,255,0.10) inset,
                    0 1px 0 rgba(255,255,255,0.16) inset;
            }

            #enginePanel.ui-hidden {
                display: none !important;
            }
            #enginePanel.minified {
                width: auto !important;
                height: 36px !important;
                resize: none !important;
                min-height: 0 !important;
                min-width: 0 !important;
                max-width: min(94vw, 480px) !important;
                overflow: hidden !important;
                background: var(--bot-bg) !important;
                border: 1px solid var(--bot-b) !important;
                color: var(--bot-t) !important;
                border-radius: 999px !important;
                padding: 0 8px 0 6px !important;
                flex-direction: row !important;
                align-items: center !important;
                box-shadow: 0 10px 28px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(255, 255, 255, 0.06) inset !important;
                backdrop-filter: blur(20px) saturate(180%);
                cursor: grab;
            }
            #enginePanel.minified:active { cursor: grabbing; }
            #enginePanel.minified #panelHeader,
            #enginePanel.minified #panelContent {
                display: none !important;
            }
            #miniHud {
                display: none;
                align-items: center;
                gap: 7px;
                height: 100%;
                white-space: nowrap;
                user-select: none;
                font-size: 11.5px;
            }
            #enginePanel.minified #miniHud {
                display: flex !important;
            }
            #hudIcon {
                width: 20px;
                height: 20px;
                color: var(--bot-primary);
                display: inline-flex;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;
                filter: drop-shadow(0 0 4px rgba(46, 160, 67, 0.45));
            }
            #hudIcon svg { width: 16px; height: 16px; display: block; }
            .hud-sep {
                width: 1px;
                height: 14px;
                background: var(--bot-b);
                flex-shrink: 0;
            }
            .hud-adv {
                font-weight: 600;
                max-width: 115px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            .hud-move {
                font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
                font-weight: 800;
                font-size: 12.5px;
                color: var(--bot-primary);
                letter-spacing: 0.02em;
            }
            .hud-time {
                font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
                font-variant-numeric: tabular-nums;
                font-size: 11px;
                color: var(--bot-accent-blue, #58a6ff);
                min-width: 32px;
                text-align: right;
            }
            .hud-grade {
                display: none;
                width: 18px;
                height: 18px;
                border-radius: 50%;
                color: #fff;
                font-size: 9.5px;
                font-weight: 900;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;
            }
            #hudChevron {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background: rgba(255, 255, 255, 0.08);
                color: var(--bot-t);
                display: inline-flex;
                align-items: center;
                justify-content: center;
                font-size: 9px;
                cursor: pointer;
                flex-shrink: 0;
            }
            #hudChevron:hover {
                background: rgba(255, 255, 255, 0.18);
            }

            #panelHeader {
                background: linear-gradient(135deg,
                    rgba(46,160,67,0.18) 0%,
                    rgba(56,139,253,0.10) 40%,
                    rgba(255,255,255,0.04) 100%);
                border-bottom: 1px solid var(--bot-b);
                color: var(--bot-t);
                padding: 0 14px;
                font-weight: 700;
                font-size: 12.5px;
                letter-spacing: 0.04em;
                display: flex;
                justify-content: space-between;
                align-items: center;
                cursor: move;
                height: 42px;
                flex-shrink: 0;
                user-select: none;
                position: relative;
                overflow: hidden;
            }
            #panelHeader::before {
                content: '';
                position: absolute;
                top: 0; left: 0; right: 0;
                height: 1px;
                background: linear-gradient(90deg,
                    transparent 0%,
                    rgba(46,160,67,0.6) 30%,
                    rgba(56,139,253,0.5) 70%,
                    transparent 100%);
                pointer-events: none;
            }
            #panelHeader .header-left {
                display: flex;
                align-items: center;
                gap: 8px;
            }
            .engine-live-dot {
                width: 8px; height: 8px; border-radius: 50%;
                background: var(--bot-p);
                box-shadow: 0 0 10px var(--bot-p), 0 0 20px rgba(46,160,67,0.3);
                animation: bc-pulse 2.4s ease-in-out infinite;
            }
            @keyframes bc-pulse {
                0%, 100% { box-shadow: 0 0 8px var(--bot-p), 0 0 16px rgba(46,160,67,0.25); opacity: 1; }
                50%       { box-shadow: 0 0 14px var(--bot-p), 0 0 28px rgba(46,160,67,0.45); opacity: 0.85; }
            }
            #minBtn {
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                width: 22px; height: 22px;
                background: rgba(255,255,255,0.08);
                border-radius: 6px;
                font-size: 12px;
                font-weight: 700;
                color: var(--bot-t);
                letter-spacing: 0;
                line-height: 1;
                user-select: none;
                transition: background 0.15s, color 0.15s;
                border: none;
                outline: none;
                padding: 0;
            }
            #minBtn:hover { background: rgba(255,255,255,0.18); }

            #panelContent {
                padding: 10px 13px;
                display: flex;
                flex-direction: column;
                gap: 8px;
                overflow-y: auto;
                flex: 1;
                min-height: 0;
            }

            .hero-card {
                background: linear-gradient(135deg,
                    rgba(46,160,67,0.07) 0%,
                    rgba(255,255,255,0.03) 50%,
                    rgba(56,139,253,0.05) 100%);
                border: 1px solid rgba(255,255,255,0.10);
                border-radius: 12px;
                padding: 7px 12px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                height: 60px;
                min-height: 60px;
                max-height: 60px;
                overflow: hidden;
                flex-shrink: 0;
                min-width: 0;
                box-sizing: border-box;
                transition: border-color 0.2s ease, background 0.2s ease;
                position: relative;
            }
            .hero-card::before {
                content: '';
                position: absolute;
                top: 0; left: 0; right: 0;
                height: 1px;
                background: linear-gradient(90deg,
                    transparent, rgba(46,160,67,0.4), transparent);
                pointer-events: none;
            }
            .hero-card:hover {
                border-color: rgba(46,160,67,0.25);
            }
            #moveResult, #statusBox {
                width: 100%;
                min-width: 0;
                overflow: hidden;
            }
            .score-pill {
                display: inline-flex; align-items: center; justify-content: center;
                padding: 2px 9px; border-radius: 8px;
                background: linear-gradient(135deg, rgba(46,160,67,0.22), rgba(63,185,80,0.12));
                border: 1px solid rgba(46,160,67,0.45);
                color: #3fb950;
                font-size: 12.5px; font-weight: 900;
                font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
                font-variant-numeric: tabular-nums;
                flex-shrink: 0;
                box-shadow: 0 0 10px rgba(46,160,67,0.20), inset 0 1px 0 rgba(255,255,255,0.10);
                letter-spacing: 0.03em;
                transition: box-shadow 0.2s ease;
            }

            .seg-control {
                display: flex; background: rgba(0,0,0,0.3);
                border: 1px solid var(--bot-b); border-radius: 8px;
                padding: 2px; gap: 2px;
            }
            .seg-btn {
                flex: 1; background: transparent; border: none;
                color: #8b949e; font-size: 11.5px; font-weight: 600;
                padding: 5px 0; border-radius: 6px; cursor: pointer;
                transition: all 0.15s ease;
            }
            .seg-btn.active {
                background: linear-gradient(135deg, rgba(46,160,67,0.28), rgba(255,255,255,0.08));
                color: #fff;
                box-shadow: 0 1px 6px rgba(0,0,0,0.5), 0 0 0 1px rgba(46,160,67,0.3);
            }

            .sect {
                border-top: 1px solid var(--bot-b);
                padding-top: 8px;
                display: flex;
                flex-direction: column;
                gap: var(--bot-gap, 7px);
            }
            .sect-title {
                color: var(--bot-t-sec);
                font-size: 10.5px;
                font-weight: 700;
                text-transform: uppercase;
                letter-spacing: 0.06em;
                margin-bottom: 1px;
            }

            .row {
                display: flex;
                justify-content: space-between;
                align-items: center;
                gap: 8px;
                min-height: var(--bot-row-h, 28px);
            }
            .row label {
                font-size: 12px;
                color: var(--bot-t);
                opacity: 0.92;
            }

            input, select {
                background: var(--bot-input-bg);
                color: var(--bot-t);
                border: 1px solid var(--bot-b);
                padding: 3px 8px;
                border-radius: 6px;
                font-size: 12px;
                height: 26px;
                transition: border-color 0.15s;
            }
            select { background-color: var(--bot-select-bg); color: var(--bot-select-t); cursor: pointer; }
            select option { background-color: var(--bot-select-bg); color: var(--bot-select-t); }
            input:focus, select:focus { outline: none; border-color: var(--bot-p); }
            input[type="number"] { width: 56px; text-align: center; }

            .toggle-list {
                display: flex;
                flex-direction: column;
                gap: var(--bot-gap, 7px);
            }
            .switch-row {
                display: flex;
                justify-content: space-between;
                align-items: center;
                gap: 8px;
                min-height: var(--bot-row-h, 28px);
                cursor: pointer;
                user-select: none;
                font-size: 12px;
            }
            .switch-row input { display: none; }
            .switch-pill {
                width: 32px; height: 18px; border-radius: 9px;
                background: var(--bot-track-bg);
                position: relative; transition: all 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
                flex-shrink: 0;
                box-shadow: inset 0 1px 3px rgba(0,0,0,0.3);
            }
            .switch-pill::after {
                content: ""; position: absolute; top: 3px; left: 3px;
                width: 12px; height: 12px; border-radius: 50%;
                background: #ffffff;
                transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
                box-shadow: 0 1px 4px rgba(0,0,0,0.5);
            }
            .switch-row input:checked + .switch-pill {
                background: linear-gradient(135deg, #2ea043, #3fb950);
                box-shadow: 0 0 10px rgba(46,160,67,0.35), inset 0 1px 0 rgba(255,255,255,0.15);
            }
            .switch-row input:checked + .switch-pill::after {
                transform: translateX(14px);
            }

            input[type=range] {
                -webkit-appearance: none;
                width: 100%;
                background: transparent;
                height: 16px;
            }
            input[type=range]::-webkit-slider-runnable-track {
                width: 100%; height: 4px; cursor: pointer;
                background: rgba(255,255,255,0.12); border-radius: 2px;
            }
            input[type=range]::-webkit-slider-thumb {
                height: 14px; width: 14px; border-radius: 50%;
                background: var(--bot-p); cursor: pointer;
                -webkit-appearance: none; margin-top: -5px;
                border: 1px solid rgba(0,0,0,0.4);
                box-shadow: 0 1px 4px rgba(0,0,0,0.4);
            }

            button {
                background: var(--bot-p);
                border: none;
                padding: 0 12px;
                height: 30px;
                color: #ffffff;
                font-weight: 600;
                font-size: 12px;
                cursor: pointer;
                border-radius: 6px;
                transition: filter 0.15s, transform 0.1s;
                white-space: nowrap;
            }
            button:hover { filter: brightness(1.12); }
            button:active { transform: scale(0.98); }
            button:disabled { opacity: 0.45; cursor: not-allowed; filter: none; }

            .btn-action-primary {
                width: 100%; height: 36px; font-size: 12.5px; font-weight: 700; letter-spacing: 0.03em;
                background: linear-gradient(135deg, #1a7f37 0%, #2ea043 50%, #3fb950 100%) !important;
                color: #fff !important;
                border: 1px solid rgba(255,255,255,0.18) !important;
                box-shadow: 0 4px 16px rgba(46,160,67,0.40), inset 0 1px 0 rgba(255,255,255,0.18);
                transition: transform 0.15s ease, box-shadow 0.15s ease !important;
            }
            .btn-action-primary:hover {
                transform: translateY(-1px) !important;
                box-shadow: 0 6px 20px rgba(46,160,67,0.50), inset 0 1px 0 rgba(255,255,255,0.18) !important;
            }
            .btn-action-primary:active { transform: translateY(0) !important; }
            .btn-action-secondary {
                width: 100%; height: 30px; font-size: 12px;
                background: var(--bot-btn-bg) !important;
                color: var(--bot-t) !important;
                border: 1px solid var(--bot-btn-b) !important;
                transition: background 0.15s ease, border-color 0.15s ease !important;
            }
            .btn-action-secondary:hover {
                background: var(--bot-card-b) !important;
                border-color: rgba(46,160,67,0.3) !important;
            }

            .btn-stack { display: flex; flex-direction: column; gap: 6px; margin-top: 2px; }
            .btn-stack > button { width: 100%; height: 34px; box-sizing: border-box; }
            .icon-hdr-btn {
                padding: 0 8px; height: 24px; min-width: 26px; font-size: 11px; font-weight: 700;
                background: rgba(255,255,255,0.08); color: var(--bot-t);
                border: 1px solid rgba(255,255,255,0.12); border-radius: 5px;
                display: inline-flex; align-items: center; justify-content: center; gap: 4px;
            }
            .icon-hdr-btn svg { width: 14px; height: 14px; display: block; }
            .col-features > .sect { border-top: none !important; padding-top: 0 !important; }
            #modal.modal-two-col { width: min(620px, 95vw); }
            #modal.modal-two-col .modal-body {
                display: grid;
                grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
                gap: 16px;
                align-items: start;
            }
            @media (max-width: 540px) {
                #modal.modal-two-col .modal-body { grid-template-columns: minmax(0, 1fr); }
            }
            .modal-col { display: flex; flex-direction: column; gap: 12px; min-width: 0; }
            #helpModal { width: min(590px, 95vw); }
            #advUiModal { width: min(440px, 94vw); }
            #helpChips { display: flex; flex-wrap: wrap; gap: 5px; }
            .help-chip {
                height: 23px; padding: 0 9px; font-size: 11px; font-weight: 600; border-radius: 999px;
                background: var(--bot-btn-bg); color: var(--bot-t-sec); border: 1px solid var(--bot-b);
            }
            .help-chip.active {
                background: rgba(var(--adv-accent-rgb, 88, 166, 255), 0.18);
                color: var(--bot-t);
                border-color: var(--adv-accent, #58a6ff);
            }
            .help-acc { border: 1px solid var(--bot-b); border-radius: 9px; overflow: hidden; background: var(--bot-card-bg); }
            .help-acc-head {
                width: 100%; height: auto; padding: 9px 12px; background: rgba(255,255,255,0.04);
                color: var(--bot-t); display: flex; justify-content: space-between; align-items: center;
                font-size: 12px; font-weight: 700; border-radius: 0; text-align: left; white-space: normal;
            }
            .help-acc-body { flex-direction: column; gap: 9px; padding: 10px 12px; border-top: 1px solid var(--bot-b); }
            .help-subtabs { width: 220px; }
            .help-pane { display: flex; flex-direction: column; gap: 8px; }
            .help-item { padding: 7px 9px; border-radius: 7px; background: rgba(255,255,255,0.025); border: 1px solid rgba(255,255,255,0.05); }
            .help-item-q { font-size: 11.5px; font-weight: 700; color: var(--bot-primary); margin-bottom: 3px; }
            .help-item-a { font-size: 11.5px; color: var(--bot-t-sec); line-height: 1.48; }
            .help-badge-cnt {
                font-size: 10px; font-family: monospace; padding: 1px 6px; border-radius: 999px;
                background: rgba(88,166,255,0.18); color: #58a6ff;
            }
            .help-mark { background: rgba(247, 198, 49, 0.32); color: var(--bot-t); border-radius: 3px; padding: 0 2px; }
            .gear-btn {
                width: 28px; height: 28px; min-width: 28px; padding: 0;
                display: inline-flex; align-items: center; justify-content: center;
                background: var(--bot-btn-bg); color: var(--bot-t);
                border: 1px solid var(--bot-btn-b); border-radius: 7px;
            }
            .gear-btn svg { width: 14px; height: 14px; display: block; }
            .gear-btn.active {
                border-color: var(--adv-accent, #58a6ff);
                color: var(--adv-accent, #58a6ff);
                background: rgba(var(--adv-accent-rgb, 88, 166, 255), 0.16);
            }
            .skin-row { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; }
            .skin-btn {
                height: 30px; padding: 0 6px; font-size: 10.5px; font-weight: 700;
                border-radius: 7px; border: 1px solid var(--bot-b); color: #fff;
            }

            /* === ADVANCED UI THEME OVERHAUL === */
            [data-ui="advanced"] {
                --bot-primary: var(--adv-accent, #58a6ff) !important;
                border-radius: var(--adv-radius, 14px) !important;
                backdrop-filter: blur(var(--adv-blur, 22px)) saturate(190%) !important;
                -webkit-backdrop-filter: blur(var(--adv-blur, 22px)) saturate(190%) !important;
                border-color: rgba(var(--adv-accent-rgb, 88, 166, 255), calc(0.16 + 0.24 * var(--adv-glow, 0.55))) !important;
                box-shadow:
                    0 24px 56px -12px rgba(0, 0, 0, 0.78),
                    0 0 calc(28px * var(--adv-glow, 0.55)) rgba(var(--adv-accent-rgb, 88, 166, 255), calc(0.18 * var(--adv-glow, 0.55))),
                    0 0 0 1px rgba(255, 255, 255, 0.08) inset !important;
                font-size: calc(13px * var(--adv-font-scale, 1));
            }
            [data-ui="advanced"] .row label,
            [data-ui="advanced"] .switch-row,
            [data-ui="advanced"] input,
            [data-ui="advanced"] select,
            [data-ui="advanced"] button {
                font-size: calc(12px * var(--adv-font-scale, 1));
            }
            [data-ui="advanced"] .seg-btn,
            [data-ui="advanced"] .help-item-q,
            [data-ui="advanced"] .help-item-a {
                font-size: calc(11.5px * var(--adv-font-scale, 1));
            }
            [data-ui="advanced"] .sect-title {
                font-size: calc(10.5px * var(--adv-font-scale, 1));
            }
            [data-ui="advanced"][data-grad="on"] {
                background-image:
                    radial-gradient(120% 80% at 10% 0%, rgba(var(--adv-accent-rgb, 88, 166, 255), 0.14) 0%, transparent 55%),
                    radial-gradient(100% 70% at 100% 100%, rgba(var(--adv-accent-rgb, 88, 166, 255), 0.07) 0%, transparent 50%) !important;
            }
            [data-ui="advanced"] #panelContent {
                padding: var(--bot-pad, 11px 13px);
                gap: calc(var(--bot-gap, 7px) + 2px);
            }
            [data-ui="advanced"] #panelHeader,
            [data-ui="advanced"] .modal-header,
            [data-ui="advanced"] #tallyHeader {
                border-bottom-color: rgba(var(--adv-accent-rgb, 88, 166, 255), 0.2);
            }
            [data-ui="advanced"][data-hdr="gradient"] #panelHeader,
            [data-ui="advanced"][data-hdr="gradient"] .modal-header {
                background: linear-gradient(90deg, rgba(var(--adv-accent-rgb, 88, 166, 255), 0.16) 0%, rgba(255,255,255,0.03) 65%, transparent 100%) !important;
            }
            [data-ui="advanced"][data-hdr="minimal"] #panelHeader,
            [data-ui="advanced"][data-hdr="minimal"] .modal-header {
                background: transparent !important;
            }
            [data-ui="advanced"][data-hdr="accentBar"] #panelHeader,
            [data-ui="advanced"][data-hdr="accentBar"] .modal-header {
                box-shadow: inset 0 2px 0 var(--adv-accent, #58a6ff);
                background: rgba(255,255,255,0.03) !important;
            }
            [data-ui="advanced"] .hero-card {
                border-radius: var(--adv-radius-sm, 9px);
                border-color: rgba(var(--adv-accent-rgb, 88, 166, 255), 0.22);
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.22), inset 0 1px 0 rgba(255,255,255,0.07);
            }
            [data-ui="advanced"][data-card="glass"] .hero-card,
            [data-ui="advanced"][data-card="glass"] .help-acc {
                background: linear-gradient(150deg, rgba(255,255,255,0.075) 0%, rgba(255,255,255,0.02) 100%);
            }
            [data-ui="advanced"][data-card="elevated"] .hero-card,
            [data-ui="advanced"][data-card="elevated"] .help-acc {
                background: rgba(255,255,255,0.06);
                box-shadow: 0 8px 22px rgba(0,0,0,0.34), inset 0 1px 0 rgba(255,255,255,0.09);
            }
            [data-ui="advanced"][data-card="outlined"] .hero-card,
            [data-ui="advanced"][data-card="outlined"] .help-acc {
                background: transparent;
                border: 1px solid rgba(var(--adv-accent-rgb, 88, 166, 255), 0.35);
                box-shadow: none;
            }
            [data-ui="advanced"][data-card="neon"] .hero-card,
            [data-ui="advanced"][data-card="neon"] .help-acc {
                background: rgba(var(--adv-accent-rgb, 88, 166, 255), 0.06);
                border: 1px solid rgba(var(--adv-accent-rgb, 88, 166, 255), 0.55);
                box-shadow: 0 0 calc(16px * var(--adv-glow, 0.55)) rgba(var(--adv-accent-rgb, 88, 166, 255), 0.22), inset 0 0 10px rgba(var(--adv-accent-rgb, 88, 166, 255), 0.08);
            }
            [data-ui="advanced"] .engine-live-dot {
                background: var(--adv-accent, #58a6ff);
                box-shadow: 0 0 10px var(--adv-accent, #58a6ff);
            }
            [data-ui="advanced"] .sect-title {
                color: var(--adv-accent, #58a6ff);
                opacity: 0.9;
            }
            [data-ui="advanced"] input,
            [data-ui="advanced"] select,
            [data-ui="advanced"] .seg-control,
            [data-ui="advanced"] .btn-action-secondary,
            [data-ui="advanced"] .icon-hdr-btn {
                border-radius: var(--adv-radius-sm, 7px);
            }
            [data-ui="advanced"] input:focus,
            [data-ui="advanced"] select:focus {
                border-color: var(--adv-accent, #58a6ff);
                box-shadow: 0 0 0 2px rgba(var(--adv-accent-rgb, 88, 166, 255), 0.24);
            }
            [data-ui="advanced"] .seg-btn.active {
                background: linear-gradient(135deg, rgba(var(--adv-accent-rgb, 88, 166, 255), 0.32), rgba(var(--adv-accent-rgb, 88, 166, 255), 0.16));
                color: #fff;
                box-shadow: 0 2px 8px rgba(0,0,0,0.3), inset 0 0 0 1px rgba(var(--adv-accent-rgb, 88, 166, 255), 0.45);
            }
            [data-ui="advanced"] .switch-row input:checked + .switch-pill {
                background: var(--adv-accent, #58a6ff);
                box-shadow: 0 0 calc(10px * var(--adv-glow, 0.55)) rgba(var(--adv-accent-rgb, 88, 166, 255), 0.55);
            }
            [data-ui="advanced"] input[type=range]::-webkit-slider-thumb {
                background: var(--adv-accent, #58a6ff);
                box-shadow: 0 0 calc(8px * var(--adv-glow, 0.55)) rgba(var(--adv-accent-rgb, 88, 166, 255), 0.65);
            }
            [data-ui="advanced"] .btn-action-primary {
                background: linear-gradient(135deg, var(--adv-accent, #58a6ff) 0%, rgba(var(--adv-accent-rgb, 88, 166, 255), 0.72) 100%) !important;
                border-radius: var(--adv-radius-sm, 8px);
                box-shadow: 0 6px 18px rgba(var(--adv-accent-rgb, 88, 166, 255), calc(0.45 * var(--adv-glow, 0.55)));
            }
            [data-ui="advanced"][data-pill="tinted"] .score-pill {
                background: rgba(var(--adv-accent-rgb, 88, 166, 255), 0.18);
                border-color: rgba(var(--adv-accent-rgb, 88, 166, 255), 0.45);
                color: var(--adv-accent, #58a6ff);
            }
            [data-ui="advanced"][data-pill="solid"] .score-pill {
                background: var(--adv-accent, #58a6ff);
                border-color: transparent;
                color: #0b0f14;
            }
            [data-ui="advanced"][data-pill="outline"] .score-pill {
                background: transparent;
                border-color: var(--adv-accent, #58a6ff);
                color: var(--adv-accent, #58a6ff);
            }
            [data-ui="advanced"][data-anim="on"] button,
            [data-ui="advanced"][data-anim="on"] .hero-card,
            [data-ui="advanced"][data-anim="on"] .switch-pill {
                transition: all 0.2s cubic-bezier(0.22, 1, 0.36, 1) !important;
            }
            [data-ui="advanced"][data-anim="on"] .icon-hdr-btn:hover,
            [data-ui="advanced"][data-anim="on"] .btn-action-secondary:hover {
                transform: translateY(-1px);
                border-color: rgba(var(--adv-accent-rgb, 88, 166, 255), 0.45) !important;
            }
            [data-ui="advanced"][data-anim="off"] * {
                transition: none !important;
            }
            #langModal { width: min(320px, 92vw); }
            #langList { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 6px; }
            .lang-item {
                display: flex; align-items: center; gap: 8px; height: 34px; padding: 0 10px;
                background: var(--bot-card-bg); color: var(--bot-t); border: 1px solid var(--bot-b);
                border-radius: 7px; font-size: 12px; font-weight: 600; justify-content: flex-start;
            }
            .lang-item.active { border-color: var(--bot-primary); background: rgba(46, 160, 67, 0.14); }
            .lang-flag { width: 20px; height: 14px; display: inline-flex; flex-shrink: 0; border-radius: 2px; overflow: hidden; box-shadow: 0 0 0 1px rgba(255,255,255,0.18); }
            .lang-flag svg { width: 100%; height: 100%; display: block; }
            .lang-name { flex: 1; text-align: left; overflow: hidden; text-overflow: ellipsis; }
            .lang-check { font-size: 11px; color: var(--bot-primary); font-weight: 800; }
            #heroGrid { display: flex; flex-direction: column; gap: 8px; }
            #panelGrid { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
            .panel-col { display: flex; flex-direction: column; min-width: 0; }
            #panelTabs { display: none; }
            #enginePanel[data-layout="double"] #heroGrid {
                display: grid;
                grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
                gap: 8px;
            }
            #enginePanel[data-layout="double"] #panelGrid {
                display: grid;
                grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
                gap: 12px;
                align-items: start;
            }
            #enginePanel[data-layout="double"] .btn-stack {
                display: grid;
                grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
                gap: 8px;
            }
            #enginePanel[data-layout="tabs"] #panelTabs {
                display: flex;
            }
            #enginePanel[data-layout="tabs"][data-tab="engine"] .col-features {
                display: none !important;
            }
            #enginePanel[data-layout="tabs"][data-tab="features"] .col-engine {
                display: none !important;
            }
            #enginePanel[data-layout="tabs"] .col-features > .sect {
                border-top: none;
                padding-top: 0;
            }
            #tallyPanel {
                position: fixed;
                top: ${reportGeom.y === "auto" ? 64 : reportGeom.y}px;
                right: ${reportGeom.x === "auto" ? reportGeom.right + "px" : "auto"};
                left: ${reportGeom.x === "auto" ? "auto" : reportGeom.x + "px"};
                width: ${reportGeom.w};
                height: ${reportGeom.h};
                min-width: ${reportGeom.minW}px;
                min-height: ${reportGeom.minH}px;
                max-width: calc(100vw - 24px);
                max-height: calc(100vh - 24px);
                background: var(--bot-bg);
                color: var(--bot-t);
                border: 1px solid var(--bot-b);
                border-radius: 12px;
                box-shadow: 0 20px 48px rgba(0,0,0,0.65);
                z-index: 10001;
                display: none;
                flex-direction: column;
                resize: both;
                overflow: hidden;
                backdrop-filter: blur(20px) saturate(180%);
                opacity: ${settings.menuOpacity};
            }
            #tallyHeader {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 8px 12px;
                border-bottom: 1px solid var(--bot-b);
                background: rgba(255,255,255,0.03);
                cursor: move;
                user-select: none;
                font-size: 12px;
                font-weight: 700;
            }

            .modal-overlay {
                position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
                background: rgba(0, 0, 0, 0.25) !important;
                z-index: 10000;
                display: none;
                justify-content: center;
                align-items: center;
                backdrop-filter: blur(2px) !important; -webkit-backdrop-filter: blur(2px) !important;
            }
            .modal-window {
                background: var(--bot-bg);
                color: var(--bot-t);
                border: 1px solid var(--bot-b);
                border-radius: 14px;
                width: min(380px, 94vw);
                height: auto;
                max-height: 92vh;
                display: flex;
                flex-direction: column;
                box-shadow: 0 24px 60px rgba(0,0,0,0.7);
                overflow: hidden;
                transform: translateZ(0);
                contain: paint layout;
                opacity: ${settings.menuOpacity};
                transition: opacity 0.15s ease;
            }
            #localModal {
                width: min(460px, 94vw);
            }
            .modal-header {
                display: flex; justify-content: space-between; align-items: center;
                padding: 10px 16px;
                border-bottom: 1px solid var(--bot-b);
                background: rgba(255,255,255,0.02);
                flex-shrink: 0;
            }
            .modal-header h3 { margin: 0; font-size: 13.5px; font-weight: 700; color: var(--bot-t); }
            .modal-close-btn {
                display: flex; align-items: center; justify-content: center;
                background: transparent; color: var(--bot-t-sec); font-size: 18px; line-height: 1;
                height: 24px; width: 24px; padding: 0; border-radius: 5px;
            }
            .modal-close-btn:hover { background: var(--bot-btn-bg); color: var(--bot-t); }

            .modal-body {
                padding: 14px 16px;
                overflow-y: auto;
                flex: 0 1 auto;
                min-height: 0;
                display: flex;
                flex-direction: column;
                gap: 10px;
                contain: content;
                will-change: scroll-position;
                -webkit-overflow-scrolling: touch;
                overscroll-behavior: contain;
                color: var(--bot-t);
            }
            #sectHighlightColor .row > label {
                min-width: 74px;
            }

            .status-badge {
                padding: 3px 9px;
                border-radius: 20px;
                font-size: 10px;
                font-weight: 700;
                letter-spacing: 0.5px;
                text-transform: uppercase;
                display: inline-flex;
                align-items: center;
                gap: 4px;
            }
            .status-badge.active {
                background: rgba(46, 160, 67, 0.18);
                color: #3fb950;
                border: 1px solid rgba(63, 185, 80, 0.4);
            }
            .status-badge.cached {
                background: rgba(56, 139, 253, 0.18);
                color: #58a6ff;
                border: 1px solid rgba(88, 166, 255, 0.4);
            }
            .status-badge.downloading {
                background: rgba(210, 153, 34, 0.18);
                color: #d29922;
                border: 1px solid rgba(210, 153, 34, 0.4);
            }
            .status-badge.uninstalled {
                background: rgba(139, 148, 158, 0.12);
                color: var(--bot-t-sec);
                border: 1px solid rgba(139, 148, 158, 0.25);
            }
            .status-badge.error {
                background: rgba(248, 81, 73, 0.18);
                color: #f85149;
                border: 1px solid rgba(248, 81, 73, 0.4);
            }
            .progress-track {
                width: 100%; height: 8px; border-radius: 4px;
                background: var(--bot-track-bg); overflow: hidden;
                position: relative; margin-top: 4px;
                border: 1px solid rgba(255,255,255,0.05);
            }
            .progress-fill {
                height: 100%; width: 0%;
                background: linear-gradient(90deg, #1f6feb 0%, #2ea043 50%, #3fb950 100%);
                border-radius: 4px;
                transition: width 0.15s cubic-bezier(0.4, 0, 0.2, 1);
            }
            .slider-group { display: flex; align-items: center; gap: 8px; flex: 1; }
            .slider-group span { font-size: 11px; color: var(--bot-t-sec); min-width: 14px; }
        `;

        const html = `
            <style>${style}</style>
            <div id="enginePanel" data-layout="${initLayout}" data-tab="${state.activeMainTab || "engine"}" class="${isMini ? "minified" : ""}${state.uiVisible ? "" : " ui-hidden"}">
                <div id="miniHud" title="Drag to move · Click to expand">
                    <span id="hudIcon">${STOCKFISH_ICON}</span>
                    <span id="hudScore" class="score-pill">0.0</span>
                    <span id="hudAdv" class="hud-adv">Ready</span>
                    <span class="hud-sep"></span>
                    <span id="hudMove" class="hud-move">--</span>
                    <span class="hud-sep"></span>
                    <span id="hudTime" class="hud-time">0.0s</span>
                    <span id="hudGrade" class="hud-grade"></span>
                    <span id="hudChevron" title="Expand Panel">▲</span>
                </div>
                <div id="panelHeader">
                    <div class="header-left">
                        <span class="engine-live-dot"></span>
                        <span id="minBtn" data-i18n-title="minBtn" title="Collapse to Mini HUD">▼</span>
                    </div>
                    <div style="display:flex; align-items:center; gap:5px;">
                        <button id="btnVisuals" class="icon-hdr-btn" data-i18n="visuals" data-i18n-title="visuals" style="padding:0 10px; font-weight:600;">Visuals</button>
                        <button id="btnDiscord" class="icon-hdr-btn" style="padding:0 10px; font-weight:600; background:rgba(114,137,218,0.18); color:#7289da; border:1px solid rgba(114,137,218,0.35);">Discord</button>
                        <button id="btnHelp" class="icon-hdr-btn" data-i18n-title="help" title="Help Guide">?</button>
                        <button id="btnLang" class="icon-hdr-btn" data-i18n-title="language" title="Language" aria-label="Language"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg></button>
                    </div>
                </div>
                <div id="panelContent">
                    <div id="heroGrid">
                        <!-- Move Recommendation Card -->
                        <div class="hero-card">
                            <div id="moveResult">${state.lastMoveResult}</div>
                        </div>

                        <!-- Live Position & Eval Status Card -->
                        <div class="hero-card">
                            <div id="statusBox">${state.lastLiveResult}</div>
                        </div>
                    </div>
                    <div id="gradeBanner" title="Click to open Report panel" style="display:none; align-items:center; justify-content:space-between; padding:6px 10px; border-radius:8px; background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08); font-size:11.5px; cursor:pointer; user-select:none;"></div>

                    <div id="panelTabs" class="seg-control">
                        <button type="button" id="tabEngine" class="seg-btn ${state.activeMainTab !== "features" ? "active" : ""}" data-i18n="tabEngine">Engine</button>
                        <button type="button" id="tabFeatures" class="seg-btn ${state.activeMainTab === "features" ? "active" : ""}" data-i18n="tabFeatures">Features</button>
                    </div>

                    <div id="panelGrid">
                    <div class="panel-col col-engine">
                    <!-- Engine Mode & Depth Section -->
                    <div class="sect" style="border-top:none; padding-top:0;">
                        <div class="sect-title" data-i18n="engineMode">Engine Mode</div>
                        <label class="switch-row" id="rowAutoFallback" data-i18n-title="autoSwitch">
                            <span data-i18n="autoSwitch">Auto-Switch</span>
                            <input type="checkbox" id="chkAutoFallback" ${settings.autoFallback ? "checked" : ""}>
                            <span class="switch-pill"></span>
                        </label>
                        <div class="seg-control" data-i18n-title="mode">
                            <button id="segCloud" class="seg-btn ${settings.engineMode==='cloud'?'active':''}" data-i18n="cloud">Cloud</button>
                            <button id="segSFOnline" class="seg-btn ${settings.engineMode==='sfonline'?'active':''}" data-i18n="online">Online</button>
                            <button id="segLocal" class="seg-btn ${settings.engineMode==='local'?'active':''}" data-i18n="local">Local</button>
                        </div>
                        <label class="switch-row" id="rowAutoTime" data-i18n-title="autoTime">
                            <span data-i18n="autoTime">Auto Time (Clock)</span>
                            <input type="checkbox" id="chkAutoTime" ${settings.autoTimeMgmt ? "checked" : ""}>
                            <span class="switch-pill"></span>
                        </label>
                        <div id="clockDisplay" style="display:none; font-size:11px; color:#58a6ff; font-family:monospace; font-variant-numeric:tabular-nums; text-align:right; height:16px; line-height:16px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">Clock: Detecting...</div>
                        <div class="row" id="rowDepth" data-i18n-title="depth">
                            <label><span data-i18n="searchDepth">Search Depth</span> <span style="color:var(--bot-t-sec); font-size:11px;">(max <span id="lblMaxDepth">25</span>)</span></label>
                            <input type="number" id="inpDepth" min="1" max="25" value="${settings.depth}">
                        </div>
                        <div class="row" id="rowFocus" data-i18n-title="focus">
                            <label data-i18n="engineFocus">Engine Focus</label>
                            <select id="selFocus" style="width:146px; font-size:11.5px;">
                                <option value="balanced" data-i18n="focusBalanced" ${settings.engineFocus==="balanced"?"selected":""}>Balanced (#1 Best)</option>
                                <option value="aggressive" data-i18n="focusAggressive" ${settings.engineFocus==="aggressive"?"selected":""}>Aggressive (Tactics)</option>
                                <option value="gambit" data-i18n="focusGambit" ${settings.engineFocus==="gambit"?"selected":""}>Gambits &amp; Sacrifices</option>
                                <option value="initiative" data-i18n="focusInitiative" ${settings.engineFocus==="initiative"?"selected":""}>Initiative / Pressure</option>
                                <option value="safety" data-i18n="focusSafety" ${settings.engineFocus==="safety"?"selected":""}>King Safety (Solid)</option>
                                <option value="conversion" data-i18n="focusConversion" ${settings.engineFocus==="conversion"?"selected":""}>Conversion (Endgame)</option>
                                <option value="custom" data-i18n="focusCustom" ${settings.engineFocus==="custom"?"selected":""}>Custom...</option>
                            </select>
                        </div>
                        <div id="lblFocusNote" style="display:none; font-size:10.5px; color:#d29922; text-align:right;"></div>
                        <div id="rowFocusCustom" style="display:${settings.engineFocus==="custom"?"flex":"none"}; flex-direction:column; gap:5px; padding:7px 9px; border-radius:8px; background:var(--bot-card-bg); border:1px solid var(--bot-card-b);">
                            <div class="row"><label style="font-size:11px;" data-i18n="atkTactics">Attack / Tactics</label><div class="slider-group"><input type="range" id="inpFocusAtk" min="0" max="100" step="5" value="${settings.focusAttack}"><span id="lblFocusAtk" style="width:28px; text-align:right; font-family:monospace;">${settings.focusAttack}</span></div></div>
                            <div class="row"><label style="font-size:11px;" data-i18n="kingSafety">King Safety</label><div class="slider-group"><input type="range" id="inpFocusSaf" min="0" max="100" step="5" value="${settings.focusSafety}"><span id="lblFocusSaf" style="width:28px; text-align:right; font-family:monospace;">${settings.focusSafety}</span></div></div>
                            <div class="row"><label style="font-size:11px;" data-i18n="simplify">Simplify / Trades</label><div class="slider-group"><input type="range" id="inpFocusSim" min="0" max="100" step="5" value="${settings.focusSimplify}"><span id="lblFocusSim" style="width:28px; text-align:right; font-family:monospace;">${settings.focusSimplify}</span></div></div>
                            <div class="row"><label style="font-size:11px;" data-i18n="maxRisk">Max Risk (cp)</label><div class="slider-group"><input type="range" id="inpFocusTol" min="10" max="80" step="5" value="${settings.focusTolerance}"><span id="lblFocusTol" style="width:28px; text-align:right; font-family:monospace;">${settings.focusTolerance}</span></div></div>
                        </div>
                        <div class="row" id="rowUiKeybind" data-i18n-title="uiKey">
                            <label data-i18n="toggleUiKey">Toggle UI Key</label>
                            <button id="btnUiKeybind" style="width:90px; height:26px; background:rgba(255,255,255,0.08); color:var(--bot-t); border:1px solid rgba(255,255,255,0.12); font-size:11px;">${settings.uiKeybind || "None"}</button>
                        </div>
                    </div>

                    </div>
                    <div class="panel-col col-features">
                    <!-- Features -->
                    <div class="sect">
                        <div class="sect-title" data-i18n="features">Features</div>
                        <div class="toggle-list">
                            <label class="switch-row" data-i18n-title="autoRun">
                                <span data-i18n="autoAnalyze">Auto-Analyze</span>
                                <input type="checkbox" id="chkRun" ${settings.autoRun ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <label class="switch-row" data-i18n-title="silent">
                                <span data-i18n="silentMode">Silent Mode</span>
                                <input type="checkbox" id="chkSilent" ${settings.silentMode ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <label class="switch-row" data-i18n-title="grade">
                                <span data-i18n="moveGrading">Move Grading</span>
                                <input type="checkbox" id="chkGrade" ${settings.moveGrading ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <div class="row" id="rowGradeDepth" style="display:${settings.moveGrading ? "flex" : "none"};" data-i18n-title="gradeDepth">
                                <label style="color:var(--bot-t-sec); font-size:11.5px;"><span data-i18n="gradingDepth">Grading Depth</span> <span style="font-size:10.5px;">(10–20)</span></label>
                                <input type="number" id="inpGradeDepth" min="10" max="20" value="${settings.gradeDepth || 15}">
                            </div>
                            <label class="switch-row" data-i18n-title="autoMove">
                                <span data-i18n="autoMove">Auto-Move</span>
                                <input type="checkbox" id="chkMove" ${settings.autoMove ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <label class="switch-row" data-i18n-title="humanMode">
                                <span data-i18n="humanMode">Humanized Mode (Detectable)</span>
                                <input type="checkbox" id="chkHumanMode" ${settings.humanMode ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <div class="row" id="rowHumanPreset" style="display:${settings.humanMode ? "flex" : "none"};" data-i18n-title="humanPreset">
                                <label style="color:var(--bot-t-sec); font-size:11.5px;" data-i18n="humanProfile">Human Profile</label>
                                <select id="selHumanPreset" style="width:142px; font-size:11.5px;">
                                    <option value="beginner" ${settings.humanPreset==="beginner"?"selected":""}>Beginner (~600)</option>
                                    <option value="novice" ${settings.humanPreset==="novice"?"selected":""}>Novice (~950)</option>
                                    <option value="casual" ${settings.humanPreset==="casual"?"selected":""}>Casual (~1250)</option>
                                    <option value="intermediate" ${settings.humanPreset==="intermediate"?"selected":""}>Intermediate (~1500)</option>
                                    <option value="club" ${settings.humanPreset==="club"?"selected":""}>Club (~1750)</option>
                                    <option value="expert" ${settings.humanPreset==="expert"?"selected":""}>Expert (~2050)</option>
                                    <option value="master" ${settings.humanPreset==="master"?"selected":""}>Master (~2350)</option>
                                    <option value="hikaru" ${settings.humanPreset==="hikaru"?"selected":""}>Hikaru (Blitz GM)</option>
                                    <option value="gm" ${settings.humanPreset==="gm"?"selected":""}>GM (~2650)</option>
                                    <option value="stealth" ${settings.humanPreset==="stealth"?"selected":""}>Stealth (Max Win)</option>
                                </select>
                            </div>
                            <label class="switch-row" data-i18n-title="autoQueue">
                                <span data-i18n="autoQueue">Auto-Queue</span>
                                <input type="checkbox" id="chkQueue" ${settings.autoQueue ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <div class="row" id="rowQueueDelay" style="display:${settings.autoQueue ? "flex" : "none"};" data-i18n-title="autoQueueDelay">
                                <label style="color:var(--bot-t-sec); font-size:11.5px;"><span data-i18n="queueDelay">Queue Delay (s)</span> <span style="font-size:10.5px;">(1–60)</span></label>
                                <input type="number" id="inpQueueDelay" min="1" max="60" step="1" value="${settings.autoQueueDelay || 2}">
                            </div>
                            <label class="switch-row" data-i18n-title="evalBar">
                                <span data-i18n="evalBar">Evaluation Bar</span>
                                <input type="checkbox" id="chkEvalBar" ${settings.showEvalBar ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <div class="row" id="rowMoveKeybind" style="display:${settings.autoMove ? 'none' : 'flex'};" data-i18n-title="moveKey">
                                <label data-i18n="manualMoveKey">Manual Move Key</label>
                                <button id="btnMoveKeybind" style="width:90px; height:26px; background:rgba(255,255,255,0.08); color:var(--bot-t); border:1px solid rgba(255,255,255,0.12); font-size:11px;">${settings.moveKeybind || "None"}</button>
                            </div>
                            <div class="row" data-i18n-title="delayWindow">
                                <label data-i18n="delayWindow">Delay Window (s)</label>
                                <div style="display:flex; align-items:center; gap:6px;">
                                    <input type="number" id="inpMin" style="width:52px;" min="0" max="180" value="${settings.minDelay}" step="0.1">
                                    <span style="color:var(--bot-t-sec); font-size:11px;">–</span>
                                    <input type="number" id="inpMax" style="width:52px;" min="0" max="180" value="${settings.maxDelay}" step="0.1">
                                </div>
                            </div>
                        </div>
                        <div id="delayDisplay" style="font-size:11px; color:#58a6ff; font-family:monospace; text-align:right;">Next delay: N/A</div>
                    </div>

                    </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="btn-stack" style="margin-top:2px;">
                        <button id="btnAnalyze" class="btn-action-primary" data-i18n="analyzePos" data-i18n-title="analyze">Analyze Position</button>
                        <button id="localBtn" class="btn-action-secondary" data-i18n="localEngines" data-i18n-title="localBtn">Local Engines</button>
                    </div>
                </div>
            </div>

            <!-- Separate Report Panel -->
            <div id="tallyPanel">
                <div id="tallyHeader">
                    <span data-i18n="tallyTitle">Report</span>
                    <button id="tallyCloseBtn" class="modal-close-btn" title="Close">×</button>
                </div>
                <div id="gradeBreakdown" style="display:flex; flex-direction:column; gap:6px; padding:10px 12px; font-size:11.5px; flex:1; min-height:0; overflow-y:auto;"></div>
            </div>

            <!-- Help Guide Modal (Mini Search Engine + Beginner / More Tabs) -->
            <div id="helpModalOv" class="modal-overlay">
                <div id="helpModal" class="modal-window">
                    <div class="modal-header">
                        <h3 data-i18n="helpTitle">Help Guide</h3>
                        <button id="helpModalClose" class="modal-close-btn">×</button>
                    </div>
                    <div class="modal-body">
                        <div style="display:flex; gap:6px; align-items:center;">
                            <input type="text" id="helpSearch" data-i18n-ph="helpSearchPh" placeholder="Search anything..." style="flex:1; height:30px;">
                            <button type="button" id="btnHelpExpand" class="btn-action-secondary" style="width:auto; height:30px; padding:0 10px; font-size:11px;" data-i18n="expandAll">Expand All</button>
                            <button type="button" id="btnHelpCollapse" class="btn-action-secondary" style="width:auto; height:30px; padding:0 10px; font-size:11px;" data-i18n="collapseAll">Collapse All</button>
                        </div>
                        <div style="display:flex; justify-content:space-between; align-items:center; gap:8px; flex-wrap:wrap;">
                            <div id="helpChips"></div>
                            <span id="helpStats" style="font-size:10.5px; color:var(--bot-t-sec); font-family:monospace;"></span>
                        </div>
                        <div id="helpList" style="display:flex; flex-direction:column; gap:8px;"></div>
                    </div>
                </div>
            </div>

            <!-- Language Selector Modal -->
            <div id="langModalOv" class="modal-overlay">
                <div id="langModal" class="modal-window">
                    <div class="modal-header">
                        <h3 data-i18n="langTitle">Select Language</h3>
                        <button id="langModalClose" class="modal-close-btn">×</button>
                    </div>
                    <div class="modal-body">
                        <div id="langList"></div>
                    </div>
                </div>
            </div>

            <!-- Two-Column Visuals Modal -->
            <div id="modalOv" class="modal-overlay">
                <div id="modal" class="modal-window modal-two-col">
                    <div class="modal-header">
                        <h3 data-i18n="visuals">Visuals</h3>
                        <button id="modalClose" class="modal-close-btn">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="modal-col">
                        <div class="sect" style="border:none; padding:0;">
                            <div class="sect-title" data-i18n="boardHighlights">Board Highlights</div>
                            <div class="row" data-i18n-title="visType">
                                <label data-i18n="styleMode">Style Mode</label>
                                <select id="visType" style="width:150px;">
                                    <option value="outline" data-i18n="visOutline">Neon Outline</option>
                                    <option value="boxes" data-i18n="visBoxes">Soft Gradient Box</option>
                                    <option value="arrow" data-i18n="visArrow">Vector Arrow</option>
                                    <option value="nativeArrow" data-i18n="visNative">Native Board Arrow</option>
                                </select>
                            </div>
                            <label class="switch-row" data-i18n-title="pv">
                                <span data-i18n="showBestLine">Show Best Line Arrows</span>
                                <input type="checkbox" id="chkPV" ${settings.showPVArrows ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <label class="switch-row" data-i18n-title="multiBest">
                                <span data-i18n="showMultiBest">Show Multi-Best Arrows</span>
                                <input type="checkbox" id="chkMultiBest" ${settings.showMultiBest ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <div class="row" id="rowArrowWidth" data-i18n-title="arrowW">
                                <label data-i18n="arrowWidth">Arrow Width</label>
                                <div class="slider-group">
                                    <input type="range" id="inpArrowW" min="8" max="45" step="1" value="${settings.arrowWidth || 15}">
                                    <span id="lblArrowW" style="width:32px; text-align:right; font-family:monospace;">${settings.arrowWidth || 15}</span>
                                </div>
                            </div>
                            <div class="row" id="rowArrowOpacity" data-i18n-title="arrowOp">
                                <label data-i18n="arrowOpacity">Arrow Opacity</label>
                                <div class="slider-group">
                                    <input type="range" id="inpArrowOp" min="0.2" max="1" step="0.05" value="${settings.arrowOpacity || 0.85}">
                                    <span id="lblArrowOp" style="width:36px; text-align:right; font-family:monospace;">${Math.round((settings.arrowOpacity || 0.85) * 100)}%</span>
                                </div>
                            </div>
                            <div class="row" id="rowDuration" data-i18n-title="dur">
                                <label data-i18n="fadeDuration">Fade Duration</label>
                                <div class="slider-group">
                                    <input type="range" id="visDuration" min="0" max="5" step="0.1" value="${Math.min(5, Math.max(0, parseFloat(settings.visualDuration) || 0))}">
                                    <span id="visDurationText" style="width:52px; text-align:right; font-family:monospace;">0.6s</span>
                                </div>
                            </div>
                            <label class="switch-row" id="rowFadeOut" data-i18n-title="fade">
                                <span data-i18n="smoothFade">Smooth Fade Out</span>
                                <input type="checkbox" id="chkFadeOut" ${settings.visualFadeOut ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <label class="switch-row" data-i18n-title="persist">
                                <span data-i18n="persistMove">Persist Until Move Played</span>
                                <input type="checkbox" id="chkPersist" ${settings.highlightPersist ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                        </div>

                        <div class="sect" id="sectHighlightColor" data-i18n-title="color">
                            <div class="sect-title" data-i18n="highlightColor">Highlight Color</div>
                            <div class="row">
                                <div id="colorPreview" style="width:32px; height:32px; border-radius:6px; border:1px solid #555; background:${settings.highlightColor}; flex-shrink:0;"></div>
                                <div style="display:flex; gap:6px; flex:1; justify-content:flex-end;">
                                    <input type="number" id="inpR" min="0" max="255" placeholder="R" style="width:48px;">
                                    <input type="number" id="inpG" min="0" max="255" placeholder="G" style="width:48px;">
                                    <input type="number" id="inpB" min="0" max="255" placeholder="B" style="width:48px;">
                                </div>
                            </div>
                            <div class="row"><label data-i18n="hue">Hue</label><div class="slider-group"><input type="range" id="sliderH" min="0" max="360" value="${state.h}"></div></div>
                            <div class="row"><label data-i18n="saturation">Saturation</label><div class="slider-group"><input type="range" id="sliderS" min="0" max="100" value="${state.s}"></div></div>
                            <div class="row"><label data-i18n="brightness">Brightness</label><div class="slider-group"><input type="range" id="sliderL" min="0" max="100" value="${state.l}"></div></div>
                            <div class="row"><label data-i18n="hexCode">Hex Code</label><input type="text" id="inpHex" style="font-family:monospace; text-align:center; width:90px;"></div>
                        </div>
                        </div>

                        <div class="modal-col">
                        <div class="sect" style="border:none; padding:0;">
                            <div class="sect-title" data-i18n="mainPanel">Main Panel</div>
                            <div class="row" data-i18n-title="panelLayout">
                                <label data-i18n="panelFormat">Panel Format</label>
                                <div class="seg-control" id="segPanelLayout" style="width:186px;">
                                    <button type="button" class="seg-btn ${initLayout==="single"?"active":""}" data-layout="single" data-i18n="fmtSingle" style="font-size:10px;">Single col</button>
                                    <button type="button" class="seg-btn ${initLayout==="double"?"active":""}" data-layout="double" data-i18n="fmtDouble" style="font-size:10px;">Double col</button>
                                    <button type="button" class="seg-btn ${initLayout==="tabs"?"active":""}" data-layout="tabs" data-i18n="fmtTabs" style="font-size:10px;">Two tab</button>
                                </div>
                            </div>
                            <div class="row" data-i18n-title="uiStyle">
                                <label data-i18n="uiStyle">UI Style</label>
                                <div style="display:flex; align-items:center; gap:6px; width:186px;">
                                    <div class="seg-control" id="segUiPreset" style="flex:1;">
                                        <button type="button" class="seg-btn ${settings.uiPreset!=="advanced"?"active":""}" data-uipreset="basic" data-i18n="uiBasic" style="font-size:10.5px;">Basic</button>
                                        <button type="button" class="seg-btn ${settings.uiPreset==="advanced"?"active":""}" data-uipreset="advanced" data-i18n="uiAdvanced" style="font-size:10.5px;">Advanced</button>
                                    </div>
                                    <button type="button" id="btnAdvUi" class="gear-btn ${settings.uiPreset==="advanced"?"active":""}" data-i18n-title="advGear" title="Advanced UI Settings" aria-label="Advanced UI Settings"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.77 1 1.42 1H21a2 2 0 1 1 0 4h-.09c-.65 0-1.16.4-1.51 1z"/></svg></button>
                                </div>
                            </div>
                            <div class="row" data-i18n-title="anchor">
                                <label data-i18n="screenAnchor">Screen Anchor</label>
                                <select id="selMenuPos" style="width:150px;">
                                    <option value="custom" data-i18n="anchCustom">Custom (Draggable)</option>
                                    <option value="top-left" data-i18n="anchTL">Top Left</option>
                                    <option value="top-right" data-i18n="anchTR">Top Right</option>
                                    <option value="bottom-left" data-i18n="anchBL">Bottom Left</option>
                                    <option value="bottom-right" data-i18n="anchBR">Bottom Right</option>
                                </select>
                            </div>
                            <div class="row" data-i18n-title="opacity">
                                <label data-i18n="glassOpacity">Glass Opacity</label>
                                <div class="slider-group">
                                    <input type="range" id="inpMenuOp" min="0.2" max="1" step="0.02" value="${settings.menuOpacity}">
                                    <span id="lblMenuOp" style="width:40px; text-align:right;">${Math.round(settings.menuOpacity*100)}%</span>
                                </div>
                            </div>
                            <div class="row" data-i18n-title="theme">
                                <label data-i18n="themePresets">Theme Presets</label>
                                <div style="display:flex; gap:8px;">
                                    <button id="btnThemeDark" class="btn-action-secondary" data-i18n="dark" style="width:auto; padding:0 12px; height:28px;">Dark</button>
                                    <button id="btnThemeLight" class="btn-action-secondary" data-i18n="light" style="width:auto; padding:0 12px; height:28px;">Light</button>
                                </div>
                            </div>
                        </div>

                        <div class="sect" data-i18n-title="reset">
                            <button id="btnReset" class="btn-action-secondary" data-i18n="resetSettings" style="color:#f85149 !important; border-color:rgba(248,81,73,0.3) !important;">Reset Settings</button>
                        </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Advanced UI Customization Modal -->
            <div id="advUiModalOv" class="modal-overlay">
                <div id="advUiModal" class="modal-window">
                    <div class="modal-header">
                        <h3 data-i18n="advUiTitle">Advanced UI Customization</h3>
                        <button id="advUiModalClose" class="modal-close-btn">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="sect" style="border:none; padding:0;">
                            <div class="sect-title" data-i18n="advSkins">Quick Style Skins</div>
                            <div class="skin-row">
                                <button type="button" class="skin-btn" data-skin="cyber" style="background:linear-gradient(135deg,#0d1b2a,#1b4965);">Cyber</button>
                                <button type="button" class="skin-btn" data-skin="emerald" style="background:linear-gradient(135deg,#0f2419,#1b6b3a);">Emerald</button>
                                <button type="button" class="skin-btn" data-skin="violet" style="background:linear-gradient(135deg,#1d1433,#6246ea);">Violet</button>
                                <button type="button" class="skin-btn" data-skin="ember" style="background:linear-gradient(135deg,#2b1410,#c2410c);">Ember</button>
                                <button type="button" class="skin-btn" data-skin="frost" style="background:linear-gradient(135deg,#e2e8f0,#3b82f6); color:#0f172a;">Frost</button>
                            </div>
                        </div>

                        <div class="sect">
                            <div class="sect-title" data-i18n="advSurface">Surface &amp; Cards</div>
                            <div class="row">
                                <label data-i18n="advAccent">Accent Color</label>
                                <div style="display:flex; align-items:center; gap:6px;">
                                    <input type="color" id="advAccentColor" value="${settings.advAccentColor || "#58a6ff"}" style="width:36px; padding:1px; cursor:pointer;">
                                    <input type="text" id="advAccentHex" value="${settings.advAccentColor || "#58a6ff"}" style="width:78px; font-family:monospace; text-align:center;">
                                </div>
                            </div>
                            <div class="row">
                                <label data-i18n="advCardStyle">Card Style</label>
                                <select id="advCardStyle" style="width:146px;">
                                    <option value="glass" data-i18n="advCardGlass">Frosted Glass</option>
                                    <option value="elevated" data-i18n="advCardElev">Elevated Depth</option>
                                    <option value="outlined" data-i18n="advCardLine">Crisp Hairline</option>
                                    <option value="neon" data-i18n="advCardNeon">Neon Edge</option>
                                </select>
                            </div>
                            <label class="switch-row">
                                <span data-i18n="advGradient">Ambient Mesh Gradient</span>
                                <input type="checkbox" id="advGradientBg" ${settings.advGradientBg !== false ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <div class="row">
                                <label data-i18n="advRadius">Corner Radius</label>
                                <div class="slider-group">
                                    <input type="range" id="advRadius" min="6" max="22" step="1" value="${settings.advRadius ?? 14}">
                                    <span id="lblAdvRadius" style="width:34px; text-align:right; font-family:monospace;">${settings.advRadius ?? 14}px</span>
                                </div>
                            </div>
                            <div class="row">
                                <label data-i18n="advBlur">Backdrop Blur</label>
                                <div class="slider-group">
                                    <input type="range" id="advBlur" min="0" max="32" step="1" value="${settings.advBlur ?? 22}">
                                    <span id="lblAdvBlur" style="width:34px; text-align:right; font-family:monospace;">${settings.advBlur ?? 22}px</span>
                                </div>
                            </div>
                            <div class="row">
                                <label data-i18n="advGlow">Accent Glow</label>
                                <div class="slider-group">
                                    <input type="range" id="advGlow" min="0" max="100" step="5" value="${settings.advGlow ?? 55}">
                                    <span id="lblAdvGlow" style="width:34px; text-align:right; font-family:monospace;">${settings.advGlow ?? 55}%</span>
                                </div>
                            </div>
                        </div>

                        <div class="sect">
                            <div class="sect-title" data-i18n="advTypography">Layout &amp; Typography</div>
                            <div class="row">
                                <label data-i18n="advDensity">Row Density</label>
                                <select id="advDensity" style="width:146px;">
                                    <option value="compact" data-i18n="advDensCompact">Compact</option>
                                    <option value="normal" data-i18n="advDensNormal">Normal</option>
                                    <option value="spacious" data-i18n="advDensSpacious">Spacious</option>
                                </select>
                            </div>
                            <div class="row">
                                <label data-i18n="advFontScale">Text Scale</label>
                                <div class="slider-group">
                                    <input type="range" id="advFontScale" min="90" max="115" step="5" value="${settings.advFontScale ?? 100}">
                                    <span id="lblAdvFontScale" style="width:38px; text-align:right; font-family:monospace;">${settings.advFontScale ?? 100}%</span>
                                </div>
                            </div>
                            <div class="row">
                                <label data-i18n="advHeaderStyle">Header Style</label>
                                <select id="advHeaderStyle" style="width:146px;">
                                    <option value="gradient" data-i18n="advHdrGrad">Gradient</option>
                                    <option value="minimal" data-i18n="advHdrMin">Minimal</option>
                                    <option value="accentBar" data-i18n="advHdrBar">Accent Strip</option>
                                </select>
                            </div>
                            <div class="row">
                                <label data-i18n="advScorePill">Score Pill Style</label>
                                <select id="advScorePillStyle" style="width:146px;">
                                    <option value="tinted" data-i18n="advPillTint">Tinted Glow</option>
                                    <option value="solid" data-i18n="advPillSolid">Solid Accent</option>
                                    <option value="outline" data-i18n="advPillOut">Outlined</option>
                                </select>
                            </div>
                            <label class="switch-row">
                                <span data-i18n="advAnimations">Smooth Micro-Animations</span>
                                <input type="checkbox" id="advAnimations" ${settings.advAnimations !== false ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                        </div>

                        <div class="sect">
                            <button type="button" id="btnAdvReset" class="btn-action-secondary" data-i18n="advReset">Reset Advanced Style</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Local Engines Modal -->
            <div id="localModalOv" class="modal-overlay">
                <div id="localModal" class="modal-window">
                    <div class="modal-header">
                        <h3 data-i18n="localEngines">Local Engines</h3>
                        <button id="localModalClose" class="modal-close-btn">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="sect" style="border:none; padding:0;" data-i18n-title="modelSel">
                            <div class="sect-title" style="display:flex; justify-content:space-between; align-items:center;">
                                <span data-i18n="activeModel">Active Engine Model</span>
                                <span id="activeModelBadge" class="status-badge uninstalled">Ready</span>
                            </div>
                            <select id="localModelSel" style="width:100%; height:34px; font-size:12px; font-weight:600; padding:4px 8px; border-radius:6px;">
                                ${LOCAL_ENGINES.map(e => `<option value="${e.id}"${(settings.localModelId||"sf19_lite")===e.id?" selected":""}>${e.label}</option>`).join("")}
                            </select>
                        </div>

                        <div class="sect" style="background:var(--bot-card-bg); border:1px solid var(--bot-card-b); border-radius:8px; padding:12px; gap:8px;">
                            <div class="sect-title" style="display:flex; justify-content:space-between; align-items:center;">
                                <span data-i18n="storageInv">Local Storage Inventory</span>
                                <span style="font-size:11px; color:var(--bot-t-sec);">IndexedDB Cache</span>
                            </div>

                            <div id="localAssetInventory" style="display:flex; flex-direction:column; gap:6px; font-size:11.5px;">
                                <div style="display:flex; justify-content:space-between; align-items:center; gap:8px; padding:7px 10px; background:var(--bot-input-bg); border:1px solid var(--bot-b); border-radius:6px;">
                                    <span style="color:var(--bot-t); font-weight:500;" data-i18n="runnerScript">Runner Script (JS)</span>
                                    <span id="assetStatusJs" style="font-family:monospace; color:var(--bot-t-sec); font-size:11px; white-space:nowrap;">Checking...</span>
                                </div>
                                <div id="rowAssetWasm" style="display:flex; justify-content:space-between; align-items:center; gap:8px; padding:7px 10px; background:var(--bot-input-bg); border:1px solid var(--bot-b); border-radius:6px;">
                                    <span style="color:var(--bot-t); font-weight:500;" data-i18n="neuralWeights">Neural Weights (WASM / NNUE)</span>
                                    <span id="assetStatusWasm" style="font-family:monospace; color:var(--bot-t-sec); font-size:11px; white-space:nowrap;">Checking...</span>
                                </div>
                            </div>

                            <div id="progressContainer">
                                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
                                    <span id="progressPhaseLabel" style="font-size:11.5px; font-weight:600; color:var(--bot-accent-blue);">Ready</span>
                                    <span id="progressDetailLabel" style="font-size:11px; font-family:monospace; color:var(--bot-t-sec);">0%</span>
                                </div>
                                <div class="progress-track">
                                    <div class="progress-fill" id="localProgressFill"></div>
                                </div>
                            </div>

                            <div style="display:flex; gap:8px;">
                                <button id="btnLocalInstall" class="btn-action-primary" data-i18n="installLaunch" style="flex:1.4; height:32px; font-weight:600;">Install / Launch</button>
                                <button id="btnLocalReinstall" class="btn-action-secondary" data-i18n="redownload" style="flex:1; height:32px;">Re-download</button>
                                <button id="btnLocalUninstall" class="btn-action-secondary" data-i18n="clearCache" style="flex:1; height:32px; color:#f85149 !important; border-color:rgba(248,81,73,0.3) !important;">Clear Cache</button>
                            </div>
                        </div>

                        <div class="sect">
                            <div class="sect-title" id="lblLocalParamsTitle" data-i18n="uciParams">UCI Parameters &amp; Strength</div>
                            <div class="row" id="rowHash" data-i18n-title="hash">
                                <label data-i18n="hashMem">Hash Memory (MB)</label>
                                <input type="number" id="localHashMB" min="1" max="2048" value="${settings.localHashMB}">
                            </div>
                            <div class="row" id="rowMoveOverhead" data-i18n-title="overhead">
                                <label data-i18n="moveOverhead">Move Overhead (ms)</label>
                                <input type="number" id="localMoveOverhead" min="0" max="5000" value="${settings.localMoveOverhead}">
                            </div>
                            <div id="rowSkillLevel" style="display:flex; flex-direction:column; gap:4px;" data-i18n-title="skill">
                                <div class="row">
                                    <label data-i18n="skillLevel">Skill Level (0–20)</label>
                                    <input type="number" id="localSkillLevel" min="0" max="20" value="${settings.localSkillLevel}">
                                </div>
                                <input type="range" id="localSkillLevelRange" min="0" max="20" step="1" value="${settings.localSkillLevel}">
                            </div>
                            <div id="rowLimitStrength" style="display:flex; flex-direction:column; gap:6px;" data-i18n-title="limitStr">
                                <label class="switch-row">
                                    <span data-i18n="eloCap">Elo Cap Limiter</span>
                                    <input type="checkbox" id="localLimitStrength" ${settings.localLimitStrength ? "checked" : ""}>
                                    <span class="switch-pill"></span>
                                </label>
                                <div class="row" id="localEloRow" style="${settings.localLimitStrength ? "display:flex;" : "display:none;"}">
                                    <label data-i18n="targetElo">Target Elo</label>
                                    <input type="number" id="localElo" min="1320" max="3190" value="${settings.localElo}">
                                </div>
                            </div>
                            <div class="row" id="rowMinThink" data-i18n-title="minThink">
                                <label data-i18n="minMoveTime">Min Move Time (ms)</label>
                                <input type="number" id="localMinThinkingTime" min="0" max="5000" value="${settings.localMinThinkTime}">
                            </div>
                            <div id="rowMaiaElo" style="display:none; flex-direction:column; gap:4px;" data-i18n-title="maiaElo">
                                <div class="row">
                                    <label data-i18n="targetRating">Target Rating (600–2600)</label>
                                    <input type="number" id="localMaiaElo" min="600" max="2600" step="50" value="${settings.localMaiaElo}">
                                </div>
                                <input type="range" id="localMaiaEloRange" min="600" max="2600" step="50" value="${settings.localMaiaElo}">
                            </div>
                            <div class="row" id="rowMaiaTemp" style="display:none;" data-i18n-title="maiaTemp">
                                <label data-i18n="moveVariety">Move Variety (Temp)</label>
                                <div class="slider-group">
                                    <input type="range" id="localMaiaTemp" min="0" max="1.2" step="0.1" value="${settings.localMaiaTemp}">
                                    <span id="localMaiaTempLbl" style="width:32px; text-align:right; font-family:monospace;">${Number(settings.localMaiaTemp || 0).toFixed(1)}</span>
                                </div>
                            </div>
                            <div class="row" id="rowMaiaTopP" style="display:none;" data-i18n-title="maiaTopP">
                                <label data-i18n="nucleusSamp">Nucleus Sampling (Top-p)</label>
                                <div class="slider-group">
                                    <input type="range" id="localMaiaTopP" min="0.5" max="1.0" step="0.05" value="${settings.localMaiaTopP}">
                                    <span id="localMaiaTopPLbl" style="width:32px; text-align:right; font-family:monospace;">${Number(settings.localMaiaTopP ?? 0.95).toFixed(2)}</span>
                                </div>
                            </div>
                            <label class="switch-row" id="rowWDLHidden" style="display:none;">
                                <span>WDL Output (Win/Draw/Loss)</span>
                                <input type="checkbox" id="localShowWDL" ${settings.localShowWDL ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        `;

        shadow.innerHTML = html;
        const panel = shadow.getElementById("enginePanel");
        if (!isMini) {
            panel.style.width = savedW || initSize.w;
            panel.style.height = savedH || "auto";
        }

        state.ui = {
            panel: panel,
            header: shadow.getElementById("panelHeader"),
            minBtn: shadow.getElementById("minBtn"),
            miniHud: shadow.getElementById("miniHud"),
            hudChevron: shadow.getElementById("hudChevron"),
            hudScore: shadow.getElementById("hudScore"),
            hudAdv: shadow.getElementById("hudAdv"),
            hudMove: shadow.getElementById("hudMove"),
            hudTime: shadow.getElementById("hudTime"),
            hudGrade: shadow.getElementById("hudGrade"),
            moveResult: shadow.getElementById("moveResult"),
            liveOutput: shadow.getElementById("statusBox"),
            gradeBanner: shadow.getElementById("gradeBanner"),
            tallyPanel: shadow.getElementById("tallyPanel"),
            tallyHeader: shadow.getElementById("tallyHeader"),
            tallyCloseBtn: shadow.getElementById("tallyCloseBtn"),
            gradeBreakdown: shadow.getElementById("gradeBreakdown"),
            tabEngine: shadow.getElementById("tabEngine"),
            tabFeatures: shadow.getElementById("tabFeatures"),
            segPanelLayout: shadow.getElementById("segPanelLayout"),
            segUiPreset: shadow.getElementById("segUiPreset"),
            btnAdvUi: shadow.getElementById("btnAdvUi"),
            advUiModalOv: shadow.getElementById("advUiModalOv"),
            advUiModal: shadow.getElementById("advUiModal"),
            advUiModalClose: shadow.getElementById("advUiModalClose"),
            delayDisplay: shadow.getElementById("delayDisplay"),
            btnAnalyze: shadow.getElementById("btnAnalyze"),
            segCloud: shadow.getElementById("segCloud"),
            segSFOnline: shadow.getElementById("segSFOnline"),
            segLocal: shadow.getElementById("segLocal"),
            inpDepth: shadow.getElementById("inpDepth"),
            chkAutoTime: shadow.getElementById("chkAutoTime"),
            rowAutoTime: shadow.getElementById("rowAutoTime"),
            chkAutoFallback: shadow.getElementById("chkAutoFallback"),
            rowAutoFallback: shadow.getElementById("rowAutoFallback"),
            clockDisplay: shadow.getElementById("clockDisplay"),
            rowDepth: shadow.getElementById("rowDepth"),
            rowFocus: shadow.getElementById("rowFocus"),
            selFocus: shadow.getElementById("selFocus"),
            lblFocusNote: shadow.getElementById("lblFocusNote"),
            rowFocusCustom: shadow.getElementById("rowFocusCustom"),
            inpFocusAtk: shadow.getElementById("inpFocusAtk"),
            lblFocusAtk: shadow.getElementById("lblFocusAtk"),
            inpFocusSaf: shadow.getElementById("inpFocusSaf"),
            lblFocusSaf: shadow.getElementById("lblFocusSaf"),
            inpFocusSim: shadow.getElementById("inpFocusSim"),
            lblFocusSim: shadow.getElementById("lblFocusSim"),
            inpFocusTol: shadow.getElementById("inpFocusTol"),
            lblFocusTol: shadow.getElementById("lblFocusTol"),
            chkRun: shadow.getElementById("chkRun"),
            chkSilent: shadow.getElementById("chkSilent"),
            chkGrade: shadow.getElementById("chkGrade"),
            rowGradeDepth: shadow.getElementById("rowGradeDepth"),
            inpGradeDepth: shadow.getElementById("inpGradeDepth"),
            chkMove: shadow.getElementById("chkMove"),
            chkHumanMode: shadow.getElementById("chkHumanMode"),
            rowHumanPreset: shadow.getElementById("rowHumanPreset"),
            selHumanPreset: shadow.getElementById("selHumanPreset"),
            chkEvalBar: shadow.getElementById("chkEvalBar"),
            chkPV: shadow.getElementById("chkPV"),
            chkMultiBest: shadow.getElementById("chkMultiBest"),
            inpArrowW: shadow.getElementById("inpArrowW"),
            lblArrowW: shadow.getElementById("lblArrowW"),
            inpArrowOp: shadow.getElementById("inpArrowOp"),
            lblArrowOp: shadow.getElementById("lblArrowOp"),
            chkQueue: shadow.getElementById("chkQueue"),
            rowQueueDelay: shadow.getElementById("rowQueueDelay"),
            inpQueueDelay: shadow.getElementById("inpQueueDelay"),
            rowMoveKeybind: shadow.getElementById("rowMoveKeybind"),
            btnMoveKeybind: shadow.getElementById("btnMoveKeybind"),
            btnUiKeybind: shadow.getElementById("btnUiKeybind"),
            inpMin: shadow.getElementById("inpMin"),
            inpMax: shadow.getElementById("inpMax"),
            btnReset: shadow.getElementById("btnReset"),
            lblMaxDepth: shadow.getElementById("lblMaxDepth"),
            btnVisuals: shadow.getElementById("btnVisuals"),
            btnHelp: shadow.getElementById("btnHelp"),
            btnLang: shadow.getElementById("btnLang"),
            localBtn: shadow.getElementById("localBtn"),
            modalOv: shadow.getElementById("modalOv"),
            modal: shadow.getElementById("modal"),
            modalClose: shadow.getElementById("modalClose"),
            helpModalOv: shadow.getElementById("helpModalOv"),
            helpModal: shadow.getElementById("helpModal"),
            helpModalClose: shadow.getElementById("helpModalClose"),
            helpSearch: shadow.getElementById("helpSearch"),
            btnHelpExpand: shadow.getElementById("btnHelpExpand"),
            btnHelpCollapse: shadow.getElementById("btnHelpCollapse"),
            langModalOv: shadow.getElementById("langModalOv"),
            langModal: shadow.getElementById("langModal"),
            langModalClose: shadow.getElementById("langModalClose"),
            localModalOv: shadow.getElementById("localModalOv"),
            localModal: shadow.getElementById("localModal"),
            localModalClose: shadow.getElementById("localModalClose"),
            visType: shadow.getElementById("visType"),
            sliderH: shadow.getElementById("sliderH"),
            sliderS: shadow.getElementById("sliderS"),
            sliderL: shadow.getElementById("sliderL"),
            colorPreview: shadow.getElementById("colorPreview"),
            inpR: shadow.getElementById("inpR"),
            inpG: shadow.getElementById("inpG"),
            inpB: shadow.getElementById("inpB"),
            inpHex: shadow.getElementById("inpHex"),
            btnThemeDark: shadow.getElementById("btnThemeDark"),
            btnThemeLight: shadow.getElementById("btnThemeLight"),
            inpMenuOp: shadow.getElementById("inpMenuOp"),
            lblMenuOp: shadow.getElementById("lblMenuOp"),
            selMenuPos: shadow.getElementById("selMenuPos")
        };

        applyMenuPosition();
        applyTallyPositionAndSize();
        applyTheme();
        applyLanguage();
        if (settings.moveGrading) initGraderEngine();

        if (state.localEngine) {
            setEngineStatus("ready", "");
        } else {
            updateLocalSettingsUI();
            if (settings.engineMode === "local" && !state.engineLoadingInProgress) {
                loadLocalEngine();
            }
        }

        // MODE SWITCHER
        const setMode = (m) => {
            saveSetting("engineMode", m);
            state.ui.segCloud.classList.toggle("active", m === "cloud");
            state.ui.segSFOnline.classList.toggle("active", m === "sfonline");
            state.ui.segLocal.classList.toggle("active", m === "local");
            state.isThinking = false;
            if (m === "local") {
                if (!state.localEngine && !state.engineLoadingInProgress) loadLocalEngine();
            } else {
                if (state.currentCloudRequest) {
                    try { state.currentCloudRequest.abort(); } catch(_) {}
                    state.currentCloudRequest = null;
                }
            }
            updateUI();
        };
        state.ui.segCloud.onclick    = () => setMode("cloud");
        state.ui.segSFOnline.onclick = () => setMode("sfonline");
        state.ui.segLocal.onclick    = () => setMode("local");

        state.ui.selMenuPos.value = settings.menuPosition;
        state.ui.btnAnalyze.onclick = () => {
            state.isThinking = false;
            analyze(settings.depth, null, true);
        };
        state.ui.btnReset.onclick = resetSettings;
        state.ui.btnVisuals.onclick = () => { if (state.ui.modalOv) { state.ui.modalOv.style.display = "flex"; syncColor(); } };
        const _dBtn = shadow.getElementById("btnDiscord");
        if (_dBtn) _dBtn.onclick = () => window.open(DISCORD_URL, "_blank");
        state.ui.modalClose.onclick = () => { if (state.ui.modalOv) state.ui.modalOv.style.display = "none"; };
        if (state.ui.btnHelp) {
            state.ui.btnHelp.onclick = () => {
                if (state.ui.helpModalOv) {
                    renderHelpChips();
                    renderHelpGuide(state.ui.helpSearch?.value || "");
                    state.ui.helpModalOv.style.display = "flex";
                }
            };
        }
        if (state.ui.helpModalClose) state.ui.helpModalClose.onclick = () => { if (state.ui.helpModalOv) state.ui.helpModalOv.style.display = "none"; };
        if (state.ui.helpModalOv) state.ui.helpModalOv.onclick = (e) => { if (e.target === state.ui.helpModalOv) state.ui.helpModalOv.style.display = "none"; };
        if (state.ui.helpSearch) state.ui.helpSearch.oninput = (e) => renderHelpGuide(e.target.value);
        if (state.ui.btnHelpExpand) state.ui.btnHelpExpand.onclick = () => {
            state._helpOpenMap = {};
            HELP_RICH_EN.forEach((_, i) => { state._helpOpenMap[i] = true; });
            renderHelpGuide(state.ui.helpSearch?.value || "");
        };
        if (state.ui.btnHelpCollapse) state.ui.btnHelpCollapse.onclick = () => {
            state._helpOpenMap = {};
            HELP_RICH_EN.forEach((_, i) => { state._helpOpenMap[i] = false; });
            renderHelpGuide(state.ui.helpSearch?.value || "");
        };
        if (state.ui.btnLang) {
            state.ui.btnLang.onclick = () => {
                if (state.ui.langModalOv) {
                    renderLangList();
                    state.ui.langModalOv.style.display = "flex";
                }
            };
        }
        if (state.ui.langModalClose) state.ui.langModalClose.onclick = () => { if (state.ui.langModalOv) state.ui.langModalOv.style.display = "none"; };
        if (state.ui.langModalOv) state.ui.langModalOv.onclick = (e) => { if (e.target === state.ui.langModalOv) state.ui.langModalOv.style.display = "none"; };
        state.ui.localBtn.onclick = () => {
            loadModelSettings(settings.localModelId);
            syncLocalSettingsInputs();
            updateLocalSettingsUI();
            if (state.ui.localModalOv) state.ui.localModalOv.style.display = "flex";
        };
        state.ui.localModalClose.onclick = () => { if (state.ui.localModalOv) state.ui.localModalOv.style.display = "none"; };
        if (state.ui.modalOv) {
            state.ui.modalOv.onclick = (e) => { if (e.target === state.ui.modalOv) state.ui.modalOv.style.display = "none"; };
        }
        if (state.ui.localModalOv) {
            state.ui.localModalOv.onclick = (e) => { if (e.target === state.ui.localModalOv) state.ui.localModalOv.style.display = "none"; };
        }

        shadow.getElementById("btnLocalInstall").onclick   = () => { loadLocalEngine(); updateLocalSettingsUI(); };
        shadow.getElementById("btnLocalReinstall").onclick = () => reinstallEngine();
        shadow.getElementById("btnLocalUninstall").onclick = () => { if (confirm("Uninstall local engine and clear cache?")) uninstallEngine(); };

        const localModelSel = shadow.getElementById("localModelSel");
        localModelSel.onchange = (e) => {
            const newId = e.target.value;
            if (state.localEngine) {
                try { state.localEngine.terminate(); } catch(_) {}
                state.localEngine = null;
            }
            state.engineLoadingInProgress = false;
            saveSetting("localModelId", newId);
            loadModelSettings(newId);
            const m = getEngineById(newId);
            if (settings.depth > m.maxDepth) {
                settings.depth = m.maxDepth;
                saveSetting("depth", m.maxDepth);
                if (state.ui.inpDepth) state.ui.inpDepth.value = m.maxDepth;
            }
            syncLocalSettingsInputs();
            setEngineStatus("not_installed", "");
            updateLocalSettingsUI();
            loadLocalEngine();
        };

        syncLocalSettingsInputs();
        updateLocalSettingsUI();

        const sendOpt = (name, val) => {
            if (state.localEngine) state.localEngine.postMessage(`setoption name ${name} value ${val}`);
        };
        const ms = (key, val) => saveModelSetting(key, val);

        shadow.getElementById("localHashMB").onchange = (e) => {
            const v = Math.min(2048, Math.max(1, parseInt(e.target.value) || 64));
            e.target.value = v;
            ms("localHashMB", v); sendOpt("Hash", v);
        };
        shadow.getElementById("localMoveOverhead").oninput = (e) => {
            const raw = parseInt(e.target.value, 10);
            const v = Number.isNaN(raw) ? 100 : Math.max(0, raw);
            ms("localMoveOverhead", v); sendOpt("Move Overhead", v);
        };
        const skillNum   = shadow.getElementById("localSkillLevel");
        const skillRange = shadow.getElementById("localSkillLevelRange");
        const applySkill = (v) => { ms("localSkillLevel", v); sendOpt("Skill Level", v); };
        skillNum.oninput   = (e) => { const v = Math.min(20, Math.max(0, parseInt(e.target.value)||0)); skillRange.value = v; applySkill(v); };
        skillRange.oninput = (e) => { skillNum.value = e.target.value; applySkill(parseInt(e.target.value)); };

        const limitChk = shadow.getElementById("localLimitStrength");
        const eloRow   = shadow.getElementById("localEloRow");
        const eloInp   = shadow.getElementById("localElo");
        limitChk.onchange = (e) => {
            ms("localLimitStrength", e.target.checked);
            eloRow.style.display = e.target.checked ? "flex" : "none";
            sendOpt("UCI_LimitStrength", e.target.checked);
        };
        eloInp.oninput = (e) => {
            const v = Math.min(3190, Math.max(1320, parseInt(e.target.value)||1320));
            ms("localElo", v); sendOpt("UCI_Elo", v);
        };
        shadow.getElementById("localShowWDL").onchange = (e) => {
            ms("localShowWDL", e.target.checked); sendOpt("UCI_ShowWDL", e.target.checked);
        };
        shadow.getElementById("localMinThinkingTime").oninput = (e) => {
            const raw = parseInt(e.target.value, 10);
            const v = Number.isNaN(raw) ? 20 : Math.max(0, raw);
            ms("localMinThinkTime", v); sendOpt("Minimum Thinking Time", v);
        };
        const maiaEloNum   = shadow.getElementById("localMaiaElo");
        const maiaEloRange = shadow.getElementById("localMaiaEloRange");
        if (maiaEloNum && maiaEloRange) {
            maiaEloNum.oninput = (e) => {
                const v = Math.min(2600, Math.max(600, parseInt(e.target.value, 10) || 1500));
                maiaEloRange.value = v;
                ms("localMaiaElo", v);
            };
            maiaEloRange.oninput = (e) => {
                const v = parseInt(e.target.value, 10) || 1500;
                maiaEloNum.value = v;
                ms("localMaiaElo", v);
            };
        }
        const maiaTempEl  = shadow.getElementById("localMaiaTemp");
        const maiaTempLbl = shadow.getElementById("localMaiaTempLbl");
        if (maiaTempEl) {
            maiaTempEl.oninput = (e) => {
                const v = Math.min(1.5, Math.max(0, parseFloat(e.target.value) || 0));
                if (maiaTempLbl) maiaTempLbl.textContent = v.toFixed(1);
                ms("localMaiaTemp", v);
            };
        }
        const maiaTopPEl  = shadow.getElementById("localMaiaTopP");
        const maiaTopPLbl = shadow.getElementById("localMaiaTopPLbl");
        if (maiaTopPEl) {
            maiaTopPEl.oninput = (e) => {
                const v = Math.min(1.0, Math.max(0.1, parseFloat(e.target.value) || 0.95));
                if (maiaTopPLbl) maiaTopPLbl.textContent = v.toFixed(2);
                ms("localMaiaTopP", v);
            };
        }

        const applyPanelLayout = (fmt) => {
            const layout = PANEL_LAYOUT_DEFAULTS[fmt] ? fmt : "double";
            saveSetting("panelLayout", layout);
            state.ui.panel.dataset.layout = layout;
            const sz = getLayoutStoredSize(layout);
            state.ui.panel.style.minWidth = sz.minW + "px";
            if (!state.ui.panel.classList.contains("minified")) {
                state.ui.panel.style.width = sz.w;
                state.ui.panel.style.height = sz.h;
            }
            if (state.ui.segPanelLayout) {
                state.ui.segPanelLayout.querySelectorAll(".seg-btn").forEach(b => b.classList.toggle("active", b.dataset.layout === layout));
            }
            applyMenuPosition();
        };
        if (state.ui.segPanelLayout) {
            state.ui.segPanelLayout.querySelectorAll(".seg-btn").forEach(btn => {
                btn.onclick = () => applyPanelLayout(btn.dataset.layout);
            });
        }
        const applyUiPreset = (preset) => {
            const val = preset === "advanced" ? "advanced" : "basic";
            saveSetting("uiPreset", val);
            if (state.ui.segUiPreset) {
                state.ui.segUiPreset.querySelectorAll(".seg-btn").forEach(b => b.classList.toggle("active", b.dataset.uipreset === val));
            }
            if (state.ui.btnAdvUi) state.ui.btnAdvUi.classList.toggle("active", val === "advanced");
            applyAdvancedUI();
        };
        if (state.ui.segUiPreset) {
            state.ui.segUiPreset.querySelectorAll(".seg-btn").forEach(btn => {
                btn.onclick = () => applyUiPreset(btn.dataset.uipreset);
            });
        }
        if (state.ui.btnAdvUi) {
            state.ui.btnAdvUi.onclick = () => {
                if (settings.uiPreset !== "advanced") applyUiPreset("advanced");
                if (state.ui.advUiModalOv) state.ui.advUiModalOv.style.display = "flex";
            };
        }
        if (state.ui.advUiModalClose) state.ui.advUiModalClose.onclick = () => { if (state.ui.advUiModalOv) state.ui.advUiModalOv.style.display = "none"; };
        if (state.ui.advUiModalOv) state.ui.advUiModalOv.onclick = (e) => { if (e.target === state.ui.advUiModalOv) state.ui.advUiModalOv.style.display = "none"; };

        const syncAdvControls = () => {
            const g = (id) => shadow.getElementById(id);
            if (g("advAccentColor")) g("advAccentColor").value = settings.advAccentColor || "#58a6ff";
            if (g("advAccentHex")) g("advAccentHex").value = settings.advAccentColor || "#58a6ff";
            if (g("advCardStyle")) g("advCardStyle").value = settings.advCardStyle || "glass";
            if (g("advGradientBg")) g("advGradientBg").checked = settings.advGradientBg !== false;
            if (g("advRadius")) g("advRadius").value = settings.advRadius ?? 14;
            if (g("lblAdvRadius")) g("lblAdvRadius").textContent = (settings.advRadius ?? 14) + "px";
            if (g("advBlur")) g("advBlur").value = settings.advBlur ?? 22;
            if (g("lblAdvBlur")) g("lblAdvBlur").textContent = (settings.advBlur ?? 22) + "px";
            if (g("advGlow")) g("advGlow").value = settings.advGlow ?? 55;
            if (g("lblAdvGlow")) g("lblAdvGlow").textContent = (settings.advGlow ?? 55) + "%";
            if (g("advDensity")) g("advDensity").value = settings.advDensity || "normal";
            if (g("advFontScale")) g("advFontScale").value = settings.advFontScale ?? 100;
            if (g("lblAdvFontScale")) g("lblAdvFontScale").textContent = (settings.advFontScale ?? 100) + "%";
            if (g("advHeaderStyle")) g("advHeaderStyle").value = settings.advHeaderStyle || "gradient";
            if (g("advScorePillStyle")) g("advScorePillStyle").value = settings.advScorePillStyle || "tinted";
            if (g("advAnimations")) g("advAnimations").checked = settings.advAnimations !== false;
        };
        const bindAdv = (id, key, type, suffix = "", lblId = null) => {
            const el = shadow.getElementById(id);
            if (!el) return;
            el.addEventListener(type === "chk" || type === "sel" ? "change" : "input", (e) => {
                const v = type === "chk" ? e.target.checked : type === "num" ? parseInt(e.target.value, 10) : e.target.value;
                saveSetting(key, v);
                if (lblId) { const l = shadow.getElementById(lblId); if (l) l.textContent = v + suffix; }
                applyAdvancedUI();
            });
        };
        const advCol = shadow.getElementById("advAccentColor");
        const advHex = shadow.getElementById("advAccentHex");
        if (advCol) advCol.oninput = (e) => {
            saveSetting("advAccentColor", e.target.value);
            if (advHex) advHex.value = e.target.value;
            applyAdvancedUI();
        };
        if (advHex) advHex.oninput = (e) => {
            if (/^#?[0-9A-F]{6}$/i.test(e.target.value)) {
                const hx = e.target.value.startsWith("#") ? e.target.value : "#" + e.target.value;
                saveSetting("advAccentColor", hx);
                if (advCol) advCol.value = hx;
                applyAdvancedUI();
            }
        };
        bindAdv("advCardStyle", "advCardStyle", "sel");
        bindAdv("advGradientBg", "advGradientBg", "chk");
        bindAdv("advRadius", "advRadius", "num", "px", "lblAdvRadius");
        bindAdv("advBlur", "advBlur", "num", "px", "lblAdvBlur");
        bindAdv("advGlow", "advGlow", "num", "%", "lblAdvGlow");
        bindAdv("advDensity", "advDensity", "sel");
        bindAdv("advFontScale", "advFontScale", "num", "%", "lblAdvFontScale");
        bindAdv("advHeaderStyle", "advHeaderStyle", "sel");
        bindAdv("advScorePillStyle", "advScorePillStyle", "sel");
        bindAdv("advAnimations", "advAnimations", "chk");
        shadow.querySelectorAll(".skin-btn").forEach(btn => {
            btn.onclick = () => {
                const skins = {
                    cyber:   { acc: "#38bdf8", glow: 65, card: "glass", dark: true },
                    emerald: { acc: "#3fb950", glow: 55, card: "glass", dark: true },
                    violet:  { acc: "#a78bfa", glow: 70, card: "neon",  dark: true },
                    ember:   { acc: "#fb923c", glow: 60, card: "elevated", dark: true },
                    frost:   { acc: "#2563eb", glow: 35, card: "glass", dark: false }
                };
                const sk = skins[btn.dataset.skin];
                if (!sk) return;
                saveSetting("advAccentColor", sk.acc);
                saveSetting("advGlow", sk.glow);
                saveSetting("advCardStyle", sk.card);
                if (sk.dark) {
                    saveSetting("themeBg", "rgba(15, 19, 24, 0.94)");
                    saveSetting("themeText", "#f0f6fc");
                    saveSetting("themeBorder", "rgba(255, 255, 255, 0.12)");
                } else {
                    saveSetting("themeBg", "rgba(255, 255, 255, 0.96)");
                    saveSetting("themeText", "#111827");
                    saveSetting("themeBorder", "rgba(0, 0, 0, 0.15)");
                }
                syncAdvControls();
                applyTheme();
            };
        });
        const btnAdvReset = shadow.getElementById("btnAdvReset");
        if (btnAdvReset) {
            btnAdvReset.onclick = () => {
                ["advAccentColor","advCardStyle","advGradientBg","advRadius","advBlur","advGlow","advDensity","advFontScale","advHeaderStyle","advAnimations","advScorePillStyle"]
                    .forEach(k => saveSetting(k, DEFAULT_SETTINGS[k]));
                syncAdvControls();
                applyAdvancedUI();
            };
        }
        syncAdvControls();
        const setMainTab = (tab) => {
            state.activeMainTab = tab;
            state.ui.panel.dataset.tab = tab;
            if (state.ui.tabEngine) state.ui.tabEngine.classList.toggle("active", tab === "engine");
            if (state.ui.tabFeatures) state.ui.tabFeatures.classList.toggle("active", tab === "features");
        };
        if (state.ui.tabEngine) state.ui.tabEngine.onclick = () => setMainTab("engine");
        if (state.ui.tabFeatures) state.ui.tabFeatures.onclick = () => setMainTab("features");

        const toggleMin = () => {
            const isMiniNow = state.ui.panel.classList.toggle("minified");
            const sKey = getSiteKey();
            try { GM_setValue(`bot_${sKey}_isMini`, isMiniNow); } catch(_) {}
            lsSet(`bot_${sKey}_isMini`, isMiniNow);
            if (!isMiniNow) {
                const sz = getLayoutStoredSize(settings.panelLayout || "double");
                state.ui.panel.style.minWidth = sz.minW + "px";
                state.ui.panel.style.width = sz.w;
                state.ui.panel.style.height = sz.h;
                applyMenuPosition();
            }
        };
        state.ui.minBtn.onclick = (e) => { e.stopPropagation(); toggleMin(); };
        if (state.ui.miniHud) {
            state.ui.miniHud.onmousedown = (e) => {
                if (e.button !== 0) return;
                if (settings.menuPosition !== "custom") { saveSetting("menuPosition", "custom"); state.ui.selMenuPos.value = "custom"; }
                e.preventDefault();
                const startClientX = e.clientX, startClientY = e.clientY;
                const startX = e.clientX - state.ui.panel.offsetLeft;
                const startY = e.clientY - state.ui.panel.offsetTop;
                let moved = false;
                const onMove = (mv) => {
                    if (Math.hypot(mv.clientX - startClientX, mv.clientY - startClientY) > 4) moved = true;
                    if (!moved) return;
                    let x = mv.clientX - startX, y = mv.clientY - startY;
                    x = Math.max(0, Math.min(x, window.innerWidth - state.ui.panel.offsetWidth));
                    y = Math.max(0, Math.min(y, window.innerHeight - state.ui.panel.offsetHeight));
                    state.ui.panel.style.left = x + "px"; state.ui.panel.style.top = y + "px";
                    state.ui.panel.style.right = "auto"; state.ui.panel.style.bottom = "auto";
                    const sKey = getSiteKey();
                    try { GM_setValue(`bot_${sKey}_pX`, x); GM_setValue(`bot_${sKey}_pY`, y); } catch(_) {}
                    lsSet(`bot_${sKey}_pX`, x); lsSet(`bot_${sKey}_pY`, y);
                };
                const onUp = () => {
                    document.removeEventListener("mousemove", onMove);
                    document.removeEventListener("mouseup", onUp);
                    if (!moved) toggleMin();
                };
                document.addEventListener("mousemove", onMove);
                document.addEventListener("mouseup", onUp);
            };
        }

        const bind = (el, key, type = "val") => {
            if (!el) return;
            el.addEventListener(type === "chk" ? "change" : "input", (e) => {
                let val = type === "chk" ? e.target.checked : type === "num" ? parseFloat(e.target.value) : e.target.value;
                if (type === "num") {
                    if (Number.isNaN(val)) return;
                    if (key === "depth") {
                        const maxD = parseInt(state.ui.inpDepth?.max) || 25;
                        val = Math.min(maxD, Math.max(1, Math.round(val)));
                    } else if (key === "minDelay" || key === "maxDelay") {
                        val = Math.min(180, Math.max(0, val));
                        if (String(e.target.value) !== "" && parseFloat(e.target.value) !== val) e.target.value = val;
                    } else if (key === "autoQueueDelay") {
                        val = Math.min(60, Math.max(1, Math.round(val)));
                        if (String(e.target.value) !== "" && parseInt(e.target.value, 10) !== val) e.target.value = val;
                    }
                }
                saveSetting(key, val);
                if (key === "autoMove" && val === true) triggerAutoMove();
                if (key === "autoQueue") toggleAutoQueue();
                if (key === "showEvalBar") {
                    if (val) EvalBar.create();
                    else EvalBar.destroy();
                }
                if (key === "showPVArrows") {
                    if (val && !settings.silentMode) PV.update(state.currentPV);
                    else PV.clear();
                }
                if (key === "showMultiBest") {
                    if (val && !settings.silentMode) {
                        if (isMaiaLocalActive()) initGraderEngine();
                        if (state.lastCandidates?.length) MultiBest.update(state.lastCandidates, state.lastSentFEN);
                    } else {
                        MultiBest.clear();
                        state.pendingCandEval = null;
                        if (!settings.moveGrading) destroyGraderEngine();
                    }
                }
                if (key === "silentMode") {
                    if (val) {
                        Visuals.removeByType('bestmove');
                        Visuals.removeByType('analysis');
                        PV.clear();
                        MultiBest.clear();
                    } else {
                        if (state.currentBestMove) Visuals.add(state.currentBestMove, 'bestmove');
                        if (settings.showPVArrows) PV.update(state.currentPV);
                        if (settings.showMultiBest && state.lastCandidates?.length) MultiBest.update(state.lastCandidates, state.lastSentFEN);
                    }
                }
                if (key === "moveGrading") {
                    if (val) {
                        initGraderEngine();
                        if (state.lastSeenFEN) enqueueGraderFen(state.lastSeenFEN);
                    } else {
                        GradeVisual.clear();
                        state.lastGrade = null;
                        state.lastUserGrade = null;
                        state.lastOppGrade = null;
                        state.pendingGrades = [];
                        state.graderQueue = [];
                        if (!(settings.showMultiBest && isMaiaLocalActive())) destroyGraderEngine();
                    }
                }
                updateUI();
            });
        };

        state.ui.selMenuPos.onchange = (e) => { saveSetting("menuPosition", e.target.value); applyMenuPosition(); };

        state.ui.header.onmousedown = (e) => {
            if (e.target.id === "minBtn" || e.target.id === "btnVisuals") return;
            if (state.ui.panel.classList.contains("minified")) return;
            if (settings.menuPosition !== 'custom') { saveSetting("menuPosition", 'custom'); state.ui.selMenuPos.value = 'custom'; }
            e.preventDefault();
            const startX = e.clientX - state.ui.panel.offsetLeft;
            const startY = e.clientY - state.ui.panel.offsetTop;
            const onMove = (mv) => {
                let x = mv.clientX - startX, y = mv.clientY - startY;
                x = Math.max(0, Math.min(x, window.innerWidth - state.ui.panel.offsetWidth));
                y = Math.max(0, Math.min(y, window.innerHeight - state.ui.panel.offsetHeight));
                state.ui.panel.style.left = x + "px"; state.ui.panel.style.top = y + "px";
                state.ui.panel.style.right = "auto"; state.ui.panel.style.bottom = "auto";
                const sKey = getSiteKey();
                try { GM_setValue(`bot_${sKey}_pX`, x); GM_setValue(`bot_${sKey}_pY`, y); } catch(_) {}
                lsSet(`bot_${sKey}_pX`, x); lsSet(`bot_${sKey}_pY`, y);
            };
            const onUp = () => {
                document.removeEventListener("mousemove", onMove);
                document.removeEventListener("mouseup", onUp);
            };
            document.addEventListener("mousemove", onMove);
            document.addEventListener("mouseup", onUp);
        };

        new ResizeObserver(() => {
            if (!state.ui.panel.classList.contains("minified")) {
                const sKey = getSiteKey();
                const fmt = PANEL_LAYOUT_DEFAULTS[settings.panelLayout] ? settings.panelLayout : "double";
                if (state.ui.panel.style.width) {
                    try { GM_setValue(`bot_${sKey}_panelW_${fmt}`, state.ui.panel.style.width); } catch(_) {}
                    lsSet(`bot_${sKey}_panelW_${fmt}`, state.ui.panel.style.width);
                }
                if (state.ui.panel.style.height) {
                    try { GM_setValue(`bot_${sKey}_panelH_${fmt}`, state.ui.panel.style.height); } catch(_) {}
                    lsSet(`bot_${sKey}_panelH_${fmt}`, state.ui.panel.style.height);
                }
            }
        }).observe(state.ui.panel);

        const durSlider = shadow.getElementById("visDuration");
        const durText = shadow.getElementById("visDurationText");
        const rowFade = shadow.getElementById("rowFadeOut");
        const chkFade = shadow.getElementById("chkFadeOut");

        const initDur = Math.min(5, Math.max(0, parseFloat(settings.visualDuration) || 0));
        durSlider.value = initDur;
        chkFade.checked = settings.visualFadeOut;
        const updateDurUI = () => {
            const secs = Math.min(5, Math.max(0, Math.round((parseFloat(durSlider.value) || 0) * 10) / 10));
            saveSetting("visualDuration", secs);
            if (secs <= 0) {
                durText.innerText = "0.0s";
                if (rowFade) rowFade.style.display = "none";
            } else {
                durText.innerText = secs.toFixed(1) + "s";
                if (rowFade) rowFade.style.display = "flex";
            }
        };
        durSlider.oninput = updateDurUI;
        chkFade.onchange = (e) => saveSetting("visualFadeOut", e.target.checked);
        const chkPersist = shadow.getElementById("chkPersist");
        if (chkPersist) { chkPersist.checked = settings.highlightPersist; chkPersist.onchange = (e) => saveSetting("highlightPersist", e.target.checked); }
        updateDurUI();

        state.ui.visType.onchange = (e) => {
            saveSetting("visualType", e.target.value);
            const isNative = settings.visualType === "nativeArrow";
            const rowDur = shadow.getElementById("rowDuration");
            const sectColor = shadow.getElementById("sectHighlightColor");
            if (rowDur) rowDur.style.display = "flex";
            if (sectColor) sectColor.style.display = isNative ? "none" : "flex";
            updateDurUI();
            Visuals.removeByType('bestmove');
            if (state.currentBestMove) Visuals.add(state.currentBestMove, 'bestmove');
        };
        state.ui.visType.value = settings.visualType;

        state.ui.btnThemeDark.onclick = () => {
            settings.themeBg = "rgba(15, 19, 24, 0.94)";
            settings.themeText = "#f0f6fc";
            settings.themeBorder = "rgba(255, 255, 255, 0.12)";
            settings.themePrimary = "#2ea043";
            settings.menuOpacity = 0.94;
            saveSetting("themeBg", settings.themeBg);
            saveSetting("themeText", settings.themeText);
            saveSetting("themeBorder", settings.themeBorder);
            saveSetting("themePrimary", settings.themePrimary);
            saveSetting("menuOpacity", settings.menuOpacity);
            if (state.ui.inpMenuOp) state.ui.inpMenuOp.value = settings.menuOpacity;
            if (state.ui.lblMenuOp) state.ui.lblMenuOp.innerText = Math.round(settings.menuOpacity * 100) + "%";
            applyTheme();
        };
        state.ui.btnThemeLight.onclick = () => {
            settings.themeBg = "rgba(255, 255, 255, 0.96)";
            settings.themeText = "#111827";
            settings.themeBorder = "rgba(0, 0, 0, 0.15)";
            settings.themePrimary = "#1a7f37";
            settings.menuOpacity = 0.96;
            saveSetting("themeBg", settings.themeBg);
            saveSetting("themeText", settings.themeText);
            saveSetting("themeBorder", settings.themeBorder);
            saveSetting("themePrimary", settings.themePrimary);
            saveSetting("menuOpacity", settings.menuOpacity);
            if (state.ui.inpMenuOp) state.ui.inpMenuOp.value = settings.menuOpacity;
            if (state.ui.lblMenuOp) state.ui.lblMenuOp.innerText = Math.round(settings.menuOpacity * 100) + "%";
            applyTheme();
        };

        state.ui.inpMenuOp.oninput = (e) => {
            const op = parseFloat(e.target.value);
            saveSetting("menuOpacity", op);
            state.ui.lblMenuOp.innerText = Math.round(op * 100) + "%";
            applyTheme();
        };

        bind(state.ui.inpDepth, "depth", "num");
        bind(state.ui.chkAutoTime, "autoTimeMgmt", "chk");
        bind(state.ui.chkAutoFallback, "autoFallback", "chk");
        bind(state.ui.chkRun, "autoRun", "chk");
        bind(state.ui.chkSilent, "silentMode", "chk");
        bind(state.ui.chkGrade, "moveGrading", "chk");
        if (state.ui.inpGradeDepth) {
            state.ui.inpGradeDepth.addEventListener("change", (e) => {
                const v = Math.min(20, Math.max(10, parseInt(e.target.value, 10) || 15));
                e.target.value = v;
                saveSetting("gradeDepth", v);
                state.gradeSnapshots = {};
                if (settings.moveGrading && state.lastSeenFEN) enqueueGraderFen(state.lastSeenFEN);
            });
        }
        bind(state.ui.chkMove, "autoMove", "chk");
        bind(state.ui.chkHumanMode, "humanMode", "chk");
        bind(state.ui.selHumanPreset, "humanPreset", "val");
        bind(state.ui.chkEvalBar, "showEvalBar", "chk");
        bind(state.ui.selFocus, "engineFocus", "val");
        const bindFocusRange = (el, lbl, key, minV, maxV) => {
            if (!el) return;
            el.oninput = (e) => {
                const v = Math.min(maxV, Math.max(minV, parseInt(e.target.value, 10) || 0));
                if (lbl) lbl.textContent = v;
                saveSetting(key, v);
            };
        };
        bindFocusRange(state.ui.inpFocusAtk, state.ui.lblFocusAtk, "focusAttack", 0, 100);
        bindFocusRange(state.ui.inpFocusSaf, state.ui.lblFocusSaf, "focusSafety", 0, 100);
        bindFocusRange(state.ui.inpFocusSim, state.ui.lblFocusSim, "focusSimplify", 0, 100);
        bindFocusRange(state.ui.inpFocusTol, state.ui.lblFocusTol, "focusTolerance", 10, 80);
        bind(state.ui.chkPV, "showPVArrows", "chk");
        bind(state.ui.chkMultiBest, "showMultiBest", "chk");
        if (state.ui.inpArrowW) {
            state.ui.inpArrowW.oninput = (e) => {
                const v = Math.min(45, Math.max(8, parseInt(e.target.value, 10) || 15));
                saveSetting("arrowWidth", v);
                if (state.ui.lblArrowW) state.ui.lblArrowW.textContent = v;
                if (settings.visualType === "arrow" && state.currentBestMove) { Visuals.removeByType("bestmove"); Visuals.add(state.currentBestMove, "bestmove"); }
                if (settings.showPVArrows) { PV.clear(); PV.update(state.currentPV); }
                if (settings.showMultiBest) { MultiBest.draw(); }
            };
        }
        if (state.ui.inpArrowOp) {
            state.ui.inpArrowOp.oninput = (e) => {
                const v = Math.min(1, Math.max(0.2, parseFloat(e.target.value) || 0.85));
                saveSetting("arrowOpacity", v);
                if (state.ui.lblArrowOp) state.ui.lblArrowOp.textContent = Math.round(v * 100) + "%";
                if (settings.visualType === "arrow" && state.currentBestMove) { Visuals.removeByType("bestmove"); Visuals.add(state.currentBestMove, "bestmove"); }
                if (settings.showPVArrows) { PV.clear(); PV.update(state.currentPV); }
                if (settings.showMultiBest) { MultiBest.draw(); }
            };
        }
        if (state.ui.gradeBanner) {
            state.ui.gradeBanner.onclick = () => {
                state.gradeBreakdownOpen = !state.gradeBreakdownOpen;
                updateUI();
                if (state.gradeBreakdownOpen) applyTallyPositionAndSize();
            };
        }
        if (state.ui.tallyCloseBtn) {
            state.ui.tallyCloseBtn.onclick = (e) => {
                e.stopPropagation();
                state.gradeBreakdownOpen = false;
                updateUI();
            };
        }
        if (state.ui.tallyHeader && state.ui.tallyPanel) {
            state.ui.tallyHeader.onmousedown = (e) => {
                if (e.target === state.ui.tallyCloseBtn) return;
                e.preventDefault();
                const startX = e.clientX - state.ui.tallyPanel.offsetLeft;
                const startY = e.clientY - state.ui.tallyPanel.offsetTop;
                const onMove = (mv) => {
                    const x = Math.max(0, Math.min(mv.clientX - startX, window.innerWidth - state.ui.tallyPanel.offsetWidth));
                    const y = Math.max(0, Math.min(mv.clientY - startY, window.innerHeight - state.ui.tallyPanel.offsetHeight));
                    state.ui.tallyPanel.style.left = x + "px";
                    state.ui.tallyPanel.style.top = y + "px";
                    state.ui.tallyPanel.style.right = "auto";
                    const sKey = getSiteKey();
                    try { GM_setValue(`bot_${sKey}_tallyX`, x); GM_setValue(`bot_${sKey}_tallyY`, y); } catch(_) {}
                    lsSet(`bot_${sKey}_tallyX`, x); lsSet(`bot_${sKey}_tallyY`, y);
                };
                const onUp = () => {
                    document.removeEventListener("mousemove", onMove);
                    document.removeEventListener("mouseup", onUp);
                };
                document.addEventListener("mousemove", onMove);
                document.addEventListener("mouseup", onUp);
            };
            new ResizeObserver(() => {
                const tp = state.ui?.tallyPanel;
                if (!tp || tp.style.display !== "flex") return;
                const sKey = getSiteKey();
                if (tp.style.width) {
                    try { GM_setValue(`bot_${sKey}_tallyW`, tp.style.width); } catch(_) {}
                    lsSet(`bot_${sKey}_tallyW`, tp.style.width);
                }
                if (tp.style.height) {
                    try { GM_setValue(`bot_${sKey}_tallyH`, tp.style.height); } catch(_) {}
                    lsSet(`bot_${sKey}_tallyH`, tp.style.height);
                }
            }).observe(state.ui.tallyPanel);
        }
        bind(state.ui.chkQueue, "autoQueue", "chk");
        if (state.ui.inpQueueDelay) {
            state.ui.inpQueueDelay.addEventListener("change", (e) => {
                const v = Math.min(60, Math.max(1, Math.round(parseFloat(e.target.value) || 2)));
                e.target.value = v;
                saveSetting("autoQueueDelay", v);
                if (settings.autoQueue) toggleAutoQueue();
            });
        }
        bind(state.ui.inpMin, "minDelay", "num");
        bind(state.ui.inpMax, "maxDelay", "num");
        state.ui.inpMin.addEventListener("input", updateCalculatedDelay);
        state.ui.inpMax.addEventListener("input", updateCalculatedDelay);
        state.ui.inpMin.addEventListener("change", () => {
            const minV = Math.min(180, Math.max(0, parseFloat(settings.minDelay) || 0));
            saveSetting("minDelay", minV);
            state.ui.inpMin.value = minV;
            if (minV > (parseFloat(settings.maxDelay) || 0)) {
                saveSetting("maxDelay", minV);
                state.ui.inpMax.value = minV;
            }
            updateCalculatedDelay();
        });
        state.ui.inpMax.addEventListener("change", () => {
            const maxV = Math.min(180, Math.max(0, parseFloat(settings.maxDelay) || 0));
            const clampedMax = Math.max(parseFloat(settings.minDelay) || 0, maxV);
            saveSetting("maxDelay", clampedMax);
            state.ui.inpMax.value = clampedMax;
            updateCalculatedDelay();
        });
        updateCalculatedDelay();

        state.ui.chkMove.addEventListener("change", (e) => {
            state.ui.rowMoveKeybind.style.display = e.target.checked ? "none" : "flex";
        });

        const bindKeyButton = (btn, key) => {
            if (!btn) return;
            btn.onclick = (e) => {
                e.stopPropagation();
                btn.innerText = "Press key...";
                const keyHandler = (ev) => {
                    ev.preventDefault(); ev.stopPropagation();
                    document.removeEventListener("keydown", keyHandler, true);
                    const keyName = ev.key === " " ? "Space" : ev.key;
                    settings[key] = (keyName === "Escape") ? "None" : keyName;
                    saveSetting(key, settings[key]);
                    btn.innerText = settings[key];
                };
                document.addEventListener("keydown", keyHandler, true);
            };
        };
        bindKeyButton(state.ui.btnMoveKeybind, "moveKeybind");
        bindKeyButton(state.ui.btnUiKeybind, "uiKeybind");

        [state.ui.sliderH, state.ui.sliderS, state.ui.sliderL].forEach(el => {
            el.oninput = () => {
                state.h = parseFloat(state.ui.sliderH.value);
                state.s = parseFloat(state.ui.sliderS.value);
                state.l = parseFloat(state.ui.sliderL.value);
                syncColor();
            };
        });

        const applyRgb = () => {
            const r = Math.min(255, Math.max(0, parseInt(state.ui.inpR.value) || 0));
            const g = Math.min(255, Math.max(0, parseInt(state.ui.inpG.value) || 0));
            const b = Math.min(255, Math.max(0, parseInt(state.ui.inpB.value) || 0));
            const hsl = rgbToHsl(r, g, b);
            state.h = hsl.h; state.s = hsl.s; state.l = hsl.l;
            syncColor();
        };
        if (state.ui.inpR) state.ui.inpR.oninput = applyRgb;
        if (state.ui.inpG) state.ui.inpG.oninput = applyRgb;
        if (state.ui.inpB) state.ui.inpB.oninput = applyRgb;

        state.ui.inpHex.oninput = (e) => {
            if (/^#?[0-9A-F]{6}$/i.test(e.target.value)) {
                const hex = e.target.value.startsWith("#") ? e.target.value : "#" + e.target.value;
                const rgb = hexToRgb(hex);
                const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
                state.h = hsl.h; state.s = hsl.s; state.l = hsl.l;
                syncColor();
            }
        };
    }

    function enforceBounds() {
        if (state.ui?.panel && !state.ui.panel.classList.contains("ui-hidden")) {
            const rect = state.ui.panel.getBoundingClientRect();
            if (state.ui.panel.classList.contains("minified")) {
                if (settings.menuPosition === "custom") {
                    if (rect.right > window.innerWidth + 1) state.ui.panel.style.left = Math.max(0, window.innerWidth - rect.width) + "px";
                    if (rect.bottom > window.innerHeight + 1) state.ui.panel.style.top = Math.max(0, window.innerHeight - rect.height) + "px";
                    if (rect.left < 0) state.ui.panel.style.left = "0px";
                    if (rect.top < 0) state.ui.panel.style.top = "0px";
                }
            } else {
                const minW = (getSiteDefaults().panel[settings.panelLayout]?.minW) || 296;
                if (rect.right > window.innerWidth + 1) state.ui.panel.style.width = Math.max(minW, window.innerWidth - rect.left) + "px";
                if (rect.bottom > window.innerHeight + 1) state.ui.panel.style.height = Math.max(200, window.innerHeight - rect.top) + "px";
                if (rect.left < 0) state.ui.panel.style.left = "0px";
                if (rect.top < 0) state.ui.panel.style.top = "0px";
            }
        }
        if (state.ui?.tallyPanel && state.ui.tallyPanel.style.display === "flex") {
            const tr = state.ui.tallyPanel.getBoundingClientRect();
            const td = getSiteDefaults().tally;
            if (tr.right > window.innerWidth + 1) state.ui.tallyPanel.style.width = Math.max(td.minW, window.innerWidth - tr.left) + "px";
            if (tr.bottom > window.innerHeight + 1) state.ui.tallyPanel.style.height = Math.max(td.minH, window.innerHeight - tr.top) + "px";
            if (tr.left < 0) { state.ui.tallyPanel.style.right = "auto"; state.ui.tallyPanel.style.left = "0px"; }
            if (tr.top < 0) state.ui.tallyPanel.style.top = "0px";
        }
        requestAnimationFrame(enforceBounds);
    }
    requestAnimationFrame(enforceBounds);

    function syncAllUI() {
        if (!state.shadow) return;
        const g = (id) => state.shadow.getElementById(id);
        const setVal = (id, val) => { const el = g(id); if (el) el.value = val; };
        const setChk = (id, val) => { const el = g(id); if (el) el.checked = !!val; };

        // Main panel inputs
        setVal("inpDepth",     settings.depth);
        setChk("chkAutoTime",     settings.autoTimeMgmt);
        setChk("chkAutoFallback", settings.autoFallback);
        setChk("chkRun",       settings.autoRun);
        setChk("chkSilent",    settings.silentMode);
        setChk("chkGrade",     settings.moveGrading);
        setVal("inpGradeDepth", settings.gradeDepth || 15);
        if (g("rowGradeDepth")) g("rowGradeDepth").style.display = settings.moveGrading ? "flex" : "none";
        setChk("chkMove",      settings.autoMove);
        setChk("chkHumanMode", settings.humanMode);
        setVal("selHumanPreset", settings.humanPreset || "master");
        setChk("chkEvalBar",   settings.showEvalBar);
        setVal("selFocus",     settings.engineFocus || "balanced");
        setVal("inpFocusAtk",  settings.focusAttack ?? 50);
        if (g("lblFocusAtk")) g("lblFocusAtk").textContent = settings.focusAttack ?? 50;
        setVal("inpFocusSaf",  settings.focusSafety ?? 50);
        if (g("lblFocusSaf")) g("lblFocusSaf").textContent = settings.focusSafety ?? 50;
        setVal("inpFocusSim",  settings.focusSimplify ?? 50);
        if (g("lblFocusSim")) g("lblFocusSim").textContent = settings.focusSimplify ?? 50;
        setVal("inpFocusTol",  settings.focusTolerance ?? 35);
        if (g("lblFocusTol")) g("lblFocusTol").textContent = settings.focusTolerance ?? 35;
        setChk("chkPV",        settings.showPVArrows);
        setChk("chkMultiBest", settings.showMultiBest);
        setVal("inpArrowW",    settings.arrowWidth || 15);
        if (g("lblArrowW")) g("lblArrowW").textContent = settings.arrowWidth || 15;
        setVal("inpArrowOp",   settings.arrowOpacity || 0.85);
        if (g("lblArrowOp")) g("lblArrowOp").textContent = Math.round((settings.arrowOpacity || 0.85) * 100) + "%";
        setChk("chkQueue",     settings.autoQueue);
        setVal("inpQueueDelay", settings.autoQueueDelay || 2);
        if (g("rowQueueDelay")) g("rowQueueDelay").style.display = settings.autoQueue ? "flex" : "none";
        setVal("inpMin",       settings.minDelay);
        setVal("inpMax",       settings.maxDelay);

        // Engine mode segments
        const modes = { cloud: g("segCloud"), sfonline: g("segSFOnline"), local: g("segLocal") };
        Object.entries(modes).forEach(([m, el]) => { if (el) el.classList.toggle("active", settings.engineMode === m); });

        // Visuals modal inputs
        const visType = g("visType");
        if (visType) visType.value = settings.visualType;

        // Fade duration slider
        const durSlider = g("visDuration");
        const durText = g("visDurationText");
        if (durSlider) {
            const sv = Math.min(5, Math.max(0, parseFloat(settings.visualDuration) || 0));
            durSlider.value = sv;
            if (durText) durText.innerText = sv.toFixed(1) + "s";
            const rowFadeEl = g("rowFadeOut");
            if (rowFadeEl) rowFadeEl.style.display = sv <= 0 ? "none" : "flex";
        }
        setChk("chkFadeOut",   settings.visualFadeOut);
        setChk("chkPersist",   settings.highlightPersist);

        // Highlight color — inline DOM-only sync (no save, no visual mutation)
        try {
            const _rgb = hslToRgb(state.h, state.s, state.l);
            const _hex = rgbToHex(_rgb.r, _rgb.g, _rgb.b);
            if (g("inpR")) { g("inpR").value = _rgb.r; g("inpG").value = _rgb.g; g("inpB").value = _rgb.b; }
            if (g("inpHex")) g("inpHex").value = _hex;
            if (g("colorPreview")) g("colorPreview").style.background = _hex;
            if (g("sliderH")) { g("sliderH").value = state.h; g("sliderS").value = state.s; g("sliderL").value = state.l; }
        } catch(_) {}

        // Appearance
        const segLayout = g("segPanelLayout");
        if (segLayout) {
            const fmt = PANEL_LAYOUT_DEFAULTS[settings.panelLayout] ? settings.panelLayout : "double";
            segLayout.querySelectorAll(".seg-btn").forEach(b => b.classList.toggle("active", b.dataset.layout === fmt));
        }
        const segUi = g("segUiPreset");
        if (segUi) {
            const uip = settings.uiPreset === "advanced" ? "advanced" : "basic";
            segUi.querySelectorAll(".seg-btn").forEach(b => b.classList.toggle("active", b.dataset.uipreset === uip));
            if (g("btnAdvUi")) g("btnAdvUi").classList.toggle("active", uip === "advanced");
        }
        const selMenuPos = g("selMenuPos");
        if (selMenuPos) selMenuPos.value = settings.menuPosition;

        const inpMenuOp = g("inpMenuOp");
        const lblMenuOp = g("lblMenuOp");
        if (inpMenuOp) { inpMenuOp.value = settings.menuOpacity; if (lblMenuOp) lblMenuOp.innerText = Math.round(settings.menuOpacity * 100) + "%"; }

        // Keybind button labels
        const btnMK = g("btnMoveKeybind");
        if (btnMK) btnMK.innerText = settings.moveKeybind || "None";
        const btnUK = g("btnUiKeybind");
        if (btnUK) btnUK.innerText = settings.uiKeybind || "None";

        // Show/hide move keybind row
        const rowMK = g("rowMoveKeybind");
        if (rowMK) rowMK.style.display = settings.autoMove ? "none" : "flex";

        // Fade/color section visibility when nativeArrow selected
        const isNative = settings.visualType === "nativeArrow";
        const sectColor = g("sectHighlightColor");
        if (sectColor) sectColor.style.display = isNative ? "none" : "flex";

        // Local model settings
        syncLocalSettingsInputs();
    }

    function updateUI() {
        if (!state.ui?.panel) return;
        let maxD = 18;
        if (settings.engineMode === "local") maxD = getEngineById(settings.localModelId || "sf19_lite").maxDepth;
        else if (settings.engineMode === "sfonline") maxD = 15;
        if (state.ui.lblMaxDepth) state.ui.lblMaxDepth.innerText = maxD;
        if (state.ui.inpDepth) {
            state.ui.inpDepth.max = maxD;
            const isMaiaLocal = (settings.engineMode === "local" && getEngineById(settings.localModelId || "sf19_lite").format === "onnx");
            const usingClock = Boolean(settings.autoTimeMgmt);
            if (state.ui.rowDepth) state.ui.rowDepth.style.display = (usingClock || isMaiaLocal) ? "none" : "flex";
        }
        if (state.ui.rowAutoTime) {
            state.ui.rowAutoTime.style.display = "flex";
        }
        if (state.ui.rowHumanPreset) {
            state.ui.rowHumanPreset.style.display = settings.humanMode ? "flex" : "none";
        }
        if (state.ui.rowFocus) {
            const isMaiaLocal = (settings.engineMode === "local" && getEngineById(settings.localModelId || "sf19_lite").format === "onnx");
            let reason = "";
            if (settings.humanMode) reason = "Off: disable Humanized Mode to use";
            else if (isMaiaLocal) reason = "Off: unavailable with Maia-3 models";
            else if (settings.engineMode === "sfonline") reason = "Off: Online mode returns 1 line only";
            const focusDisabled = Boolean(reason);
            state.ui.rowFocus.style.display = "flex";
            state.ui.rowFocus.style.opacity = focusDisabled ? "0.45" : "1";
            if (state.ui.selFocus) state.ui.selFocus.disabled = focusDisabled;
            if (state.ui.lblFocusNote) {
                state.ui.lblFocusNote.style.display = focusDisabled ? "block" : "none";
                if (focusDisabled) state.ui.lblFocusNote.textContent = reason;
            }
            if (state.ui.rowFocusCustom) {
                state.ui.rowFocusCustom.style.display = (!focusDisabled && settings.engineFocus === "custom") ? "flex" : "none";
            }
        }
        if (state.ui.rowGradeDepth) {
            state.ui.rowGradeDepth.style.display = settings.moveGrading ? "flex" : "none";
        }
        if (state.ui.rowQueueDelay) {
            state.ui.rowQueueDelay.style.display = settings.autoQueue ? "flex" : "none";
        }
        if (state.ui.clockDisplay) {
            const showClk = Boolean(settings.autoTimeMgmt);
            state.ui.clockDisplay.style.display = showClk ? "block" : "none";
            const nowClk = performance.now();
            if (showClk && (!state._lastClockUiTick || nowClk - state._lastClockUiTick >= 200)) {
                state._lastClockUiTick = nowClk;
                const g = getActiveGame();
                const raw = readRawClocks(g);
                let txt;
                if (raw) {
                    const incSec = Math.round((raw.metaIncMs !== null ? raw.metaIncMs : (state._detectedIncMs || 0)) / 1000);
                    const dTxt = state.lastConcludedDepth ? ` · D${state.lastConcludedDepth}` : "";
                    txt = `W ${fmtClockMs(raw.wMs)} · B ${fmtClockMs(raw.bMs)} · +${incSec}s${dTxt}`;
                } else {
                    txt = "Clock: Not found (using depth)";
                }
                if (state.ui.clockDisplay.innerText !== txt) state.ui.clockDisplay.innerText = txt;
            }
        }
        const isErrOrDl = (state.lastLiveResult || "").includes("#f85149") || (state.lastLiveResult || "").includes("#d29922");
        const displayMoveHtml = (settings.silentMode && !isErrOrDl)
            ? formatMoveResult(getActiveModelTitle(), state.isThinking ? "Thinking..." : (state.currentBestMove ? "Armed" : "Standby"), "Silent Mode")
            : state.lastMoveResult;
        const displayLiveHtml = (settings.silentMode && !isErrOrDl)
            ? formatLiveResult("•", {
                text: state.isThinking ? "Silent background analysis..." : (state.currentBestMove ? (settings.autoMove ? "Auto-move armed" : "Move ready (press key)") : "Waiting for turn..."),
                color: state.currentBestMove && !state.isThinking ? "#3fb950" : "#8b949e"
            }, "", "Visuals hidden")
            : state.lastLiveResult;

        if (state.ui.moveResult && state.ui.moveResult.dataset.lastHtml !== displayMoveHtml) {
            state.ui.moveResult.dataset.lastHtml = displayMoveHtml;
            state.ui.moveResult.innerHTML = displayMoveHtml;
        }
        if (state.ui.liveOutput && state.ui.liveOutput.dataset.lastHtml !== displayLiveHtml) {
            state.ui.liveOutput.dataset.lastHtml = displayLiveHtml;
            state.ui.liveOutput.innerHTML = displayLiveHtml;
        }
        if (state.ui.gradeBanner) {
            if (settings.moveGrading) {
                let gHtml;
                const accBadge = (state.gradeTally && (state.gradeTally.w.moves || state.gradeTally.b.moves))
                    ? `<span style="font-size:10px; color:var(--bot-t-sec); font-family:monospace; margin-left:4px;">W:${getTallyAccText("w")} B:${getTallyAccText("b")} ${state.gradeBreakdownOpen ? "▲" : "▾"}</span>`
                    : "";
                if (state.lastUserGrade && state.lastOppGrade) {
                    const u = state.lastUserGrade, o = state.lastOppGrade;
                    const chip = (g) => `<span style="display:inline-flex; align-items:center; gap:4px; min-width:0;"><span style="display:inline-flex; align-items:center; justify-content:center; width:17px; height:17px; border-radius:50%; background:${g.meta.color}; color:#fff; font-weight:900; font-size:9px; flex-shrink:0;">${gradeBadgeInnerHtml(g.meta, 10)}</span><span style="color:var(--bot-t-sec); font-weight:600; font-size:11px;">${g.who}:<span style="color:var(--bot-t); font-family:monospace; margin-left:2px;">${g.uci}</span></span></span>`;
                    gHtml = `<span style="display:inline-flex; align-items:center; gap:7px; min-width:0; overflow:hidden;">${chip(u)}<span style="color:var(--bot-t-sub);">·</span>${chip(o)}</span><span style="flex-shrink:0;">${accBadge}</span>`;
                } else if (state.lastGrade) {
                    const g = state.lastGrade;
                    const lossTxt = parseFloat(g.winLoss) > 0.2 ? `-${g.winLoss}%` : `D${g.depth || getTargetGradeDepth()}`;
                    gHtml = `<span style="display:inline-flex; align-items:center; gap:6px; min-width:0;"><span style="display:inline-flex; align-items:center; justify-content:center; width:20px; height:20px; border-radius:50%; background:${g.meta.color}; color:#fff; font-weight:900; font-size:10px; flex-shrink:0;">${gradeBadgeInnerHtml(g.meta, 12)}</span><span style="color:var(--bot-t-sec); font-weight:600;">${g.who}: <span style="color:var(--bot-t); font-family:monospace;">${g.uci}</span></span></span><span style="display:inline-flex; align-items:center; gap:5px; font-weight:700; color:${g.meta.color}; flex-shrink:0;"><span>${g.meta.label}</span><span style="font-size:10.5px; opacity:0.8; font-family:monospace;">${lossTxt}</span>${accBadge}</span>`;
                } else {
                    const stTxt = state.graderLoading ? "Loading SF19 Grader..." : `SF19 D${getTargetGradeDepth()} Ready`;
                    gHtml = `<span style="color:var(--bot-t-sec); font-weight:600;">Move Grading</span><span style="color:#58a6ff; font-family:monospace; font-size:11px;">${stTxt}${accBadge}</span>`;
                }
                if (state.ui.gradeBanner.dataset.lastHtml !== gHtml) {
                    state.ui.gradeBanner.dataset.lastHtml = gHtml;
                    state.ui.gradeBanner.innerHTML = gHtml;
                }
                state.ui.gradeBanner.style.display = "flex";
            } else {
                state.ui.gradeBanner.style.display = "none";
            }
        }
        if (state.ui.tallyPanel && state.ui.gradeBreakdown) {
            if (settings.moveGrading && state.gradeBreakdownOpen && state.uiVisible) {
                const tallyData = state.gradeTally || resetGradeTally();
                const rows = ["brilliant", "great", "best", "excellent", "good", "inaccuracy", "mistake", "miss", "blunder"].map(k => {
                    const m = GRADE_META[k];
                    return `<div style="display:flex; align-items:center; justify-content:space-between; padding:2px 0;">
                        <span style="font-family:monospace; font-weight:700; min-width:24px; text-align:center;">${tallyData.w[k]}</span>
                        <span style="display:inline-flex; align-items:center; gap:6px; color:${m.color}; font-weight:600;"><span style="display:inline-flex; width:17px; height:17px; border-radius:50%; background:${m.color}; color:#fff; font-size:8.5px; font-weight:900; align-items:center; justify-content:center;">${gradeBadgeInnerHtml(m, 10)}</span>${m.label}</span>
                        <span style="font-family:monospace; font-weight:700; min-width:24px; text-align:center;">${tallyData.b[k]}</span>
                    </div>`;
                }).join("");
                const bdHtml = `<div style="display:flex; justify-content:space-between; align-items:center; font-weight:700; border-bottom:1px solid var(--bot-b); padding-bottom:5px; margin-bottom:2px;"><span>${t("white")} (${getTallyAccText("w")})</span><span>${t("black")} (${getTallyAccText("b")})</span></div>${rows}`;
                if (state.ui.gradeBreakdown.dataset.lastHtml !== bdHtml) {
                    state.ui.gradeBreakdown.dataset.lastHtml = bdHtml;
                    state.ui.gradeBreakdown.innerHTML = bdHtml;
                }
                state.ui.tallyPanel.style.display = "flex";
            } else {
                state.ui.tallyPanel.style.display = "none";
            }
        }
        if (state.ui.delayDisplay) {
            const min = Math.max(0, parseFloat(settings.minDelay) || 0);
            const max = Math.max(min, parseFloat(settings.maxDelay) || 0);
            const isHumanActive = Boolean(settings.humanMode);
            const tagTxt = state.lastTelemetryTag ? ` [${state.lastTelemetryTag}]` : "";
            const txt = isHumanActive
                ? `Human pace: ${state.calculatedDelay || "0.0"}s${tagTxt}`
                : ((min === 0 && max === 0) ? "Delay: 0.0s (Instant)" : `Next delay: ${state.calculatedDelay}s`);
            if (state.ui.delayDisplay.innerText !== txt) state.ui.delayDisplay.innerText = txt;
        }
        if (state.ui.miniHud && state.ui.panel.classList.contains("minified")) {
            const hudScoreTxt = settings.silentMode ? "•" : (state.hudEvalTxt || "0.0");
            const hudAdvObj = settings.silentMode
                ? { text: state.isThinking ? "Thinking..." : (state.currentBestMove ? (settings.autoMove ? "Armed" : "Ready") : "Silent"), color: state.currentBestMove && !state.isThinking ? "#3fb950" : "#8b949e" }
                : (state.isThinking ? { text: "Thinking...", color: "#58a6ff" } : (state.hudStatus || { text: "Ready", color: "#8b949e" }));
            const hudMoveTxt = settings.silentMode ? "Silent" : (state.isThinking && !state.currentBestMove ? "..." : (state.hudMove || "--"));

            const nowMs = performance.now();
            let hudTimeTxt;
            if (state.isThinking) {
                hudTimeTxt = `${((nowMs - state.analysisStartTime) / 1000).toFixed(1)}s`;
            } else if (settings.autoMove && state.currentBestMove && state.moveTargetTime > nowMs) {
                hudTimeTxt = `${Math.max(0, (state.moveTargetTime - nowMs) / 1000).toFixed(1)}s`;
            } else {
                hudTimeTxt = `${state.calculatedDelay || "0.0"}s`;
            }

            if (state.ui.hudScore && state.ui.hudScore.textContent !== hudScoreTxt) state.ui.hudScore.textContent = hudScoreTxt;
            if (state.ui.hudAdv) {
                if (state.ui.hudAdv.textContent !== hudAdvObj.text) state.ui.hudAdv.textContent = hudAdvObj.text;
                if (state.ui.hudAdv.style.color !== hudAdvObj.color) state.ui.hudAdv.style.color = hudAdvObj.color;
            }
            if (state.ui.hudMove && state.ui.hudMove.textContent !== hudMoveTxt) state.ui.hudMove.textContent = hudMoveTxt;
            if (state.ui.hudTime && state.ui.hudTime.textContent !== hudTimeTxt) state.ui.hudTime.textContent = hudTimeTxt;
            if (state.ui.hudGrade) {
                if (settings.moveGrading && state.lastGrade) {
                    const gm = state.lastGrade.meta;
                    const gInner = gradeBadgeInnerHtml(gm, 11);
                    state.ui.hudGrade.style.display = "inline-flex";
                    if (state.ui.hudGrade.dataset.code !== gm.code) {
                        state.ui.hudGrade.dataset.code = gm.code;
                        state.ui.hudGrade.innerHTML = gInner;
                    }
                    state.ui.hudGrade.style.background = gm.color;
                    state.ui.hudGrade.title = `${state.lastGrade.who}: ${state.lastGrade.uci} · ${gm.label}`;
                } else {
                    state.ui.hudGrade.style.display = "none";
                }
            }
        }
        if (document.activeElement !== state.ui.inpDepth && state.shadow && state.shadow.activeElement !== state.ui.inpDepth) {
            state.ui.inpDepth.value = settings.depth;
        }
    }

    function fenToBoard64(fen) {
        if (!fen) return null;
        const rows = fen.split(" ")[0].split("/");
        if (rows.length !== 8) return null;
        const out = [];
        for (const r of rows) {
            for (const ch of r) {
                if (ch >= "1" && ch <= "8") {
                    for (let k = 0; k < parseInt(ch, 10); k++) out.push(".");
                } else {
                    out.push(ch);
                }
            }
        }
        return out.length === 64 ? out : null;
    }

    function detectMoveBetweenFens(prevFen, currFen) {
        const a = fenToBoard64(prevFen), b = fenToBoard64(currFen);
        if (!a || !b) return { to: null, uci: null, singleHalfMove: false };
        const prevSide = (prevFen.split(" ")[1] || "w");
        const currSide = (currFen.split(" ")[1] || "w");
        if (prevSide === currSide) return { to: null, uci: null, singleHalfMove: false };

        const moverIsWhite = (prevSide === "w");
        const isMoverPiece = (ch) => ch !== "." && (moverIsWhite ? ch === ch.toUpperCase() : ch === ch.toLowerCase());
        const froms = [], tos = [];
        const sqOf = (i) => String.fromCharCode(97 + (i % 8)) + (8 - Math.floor(i / 8));
        for (let i = 0; i < 64; i++) {
            if (a[i] !== b[i]) {
                if (isMoverPiece(a[i]) && b[i] === ".") froms.push({ idx: i, sq: sqOf(i), piece: a[i].toLowerCase(), raw: a[i] });
                if (isMoverPiece(b[i])) tos.push({ idx: i, sq: sqOf(i), piece: b[i].toLowerCase(), raw: b[i] });
            }
        }
        if (!tos.length || !froms.length) return { to: null, uci: null, singleHalfMove: false };
        const toObj = tos.find(c => c.piece === "k") || tos[0];
        // Handle pawn promotion (froms has 'p', tos has 'q'/'r'/'b'/'n')
        const fromObj = froms.find(c => c.piece === toObj.piece) || froms.find(c => c.piece === "p") || froms[0];
        let promo = "";
        if (fromObj.piece === "p" && toObj.piece !== "p") {
            const toRank = Math.floor(toObj.idx / 8);
            if (toRank === 0 || toRank === 7) promo = toObj.piece;
        }
        const fromF = fromObj.idx % 8, toF = toObj.idx % 8;
        const wasCapture = (a[toObj.idx] !== ".") || (fromObj.piece === "p" && fromF !== toF && a[toObj.idx] === ".");
        return { from: fromObj.sq, to: toObj.sq, uci: fromObj.sq + toObj.sq + promo, singleHalfMove: true, wasCapture };
    }

    // --- MAIN TICK LOOP ---
    function mainLoop() {
        if (!document.body) return;
        if (settings.autoQueue && !state.newGameObserver) toggleAutoQueue();
        if (isCgSite()) {
            state.board = document.querySelector(".round__app__board cg-container") || document.querySelector(".round__app__board cg-board");
        } else {
            const customBoard = document.querySelector("chess-board, wc-chess-board");
            state.board = (customBoard && customBoard.game) ? customBoard : (document.querySelector(CONFIG.BOARD_SEL) || customBoard);
        }
        const game = getActiveGame();

        if (settings.showEvalBar) {
            EvalBar.create();
        } else {
            EvalBar.destroy();
        }

        if (game?.getPlayingAs) {
            try {
                const pa = game.getPlayingAs();
                if (pa === 1 || pa === 2 || pa === "w" || pa === "b") state.playingAs = (pa === 2 || pa === "b") ? 2 : 1;
            } catch (e) {}
        }

        const resetForNewGameState = (initFen, nowMs) => {
            Visuals.removeByType('bestmove');
            Visuals.removeByType('analysis');
            EvalBar.reset();
            GradeVisual.clear();
            state.lastGrade = null;
            state.lastUserGrade = null;
            state.lastOppGrade = null;
            state.gradeSnapshots = {};
            state.gradesByMoveKey = {};
            state.gradeTally = resetGradeTally();
            state.pendingGrades = [];
            MultiBest.clear();
            state.graderQueue = [];
            if (state.graderSearching && state.graderEngine && !state.graderStopSent) {
                state.graderAborted = true;
                state.graderStopSent = true;
                try { state.graderEngine.postMessage("stop"); } catch (_) {}
            }
            if (settings.moveGrading && initFen) enqueueGraderFen(initFen);
            state.currentBestMove = null;
            state.currentPV = [];
            state.lastSanitizedBoardFEN = "";
            state.hudEvalTxt = "0.0";
            state.hudStatus = { text: "Ready", color: "#8b949e" };
            state.hudMove = "--";
            state.plannedPV = [];
            state.lastTankPly = -10;
            state.oppLastTo = null;
            state.oppLastUCI = null;
            state.oppLastWasCapture = false;
            state.oppPrevBoard64 = null;
            state.ourLastMoveTo = null;
            state.ourLastThreatenedSet = new Set();
            state.lastConcludedDepth = null;
            state.top1Count = 0;
            state.nonForcedCount = 0;
            state.humanMomentum = 0;
            state.momentumStreak = 0;
            state.attentionMap = new Array(64).fill(0);
            state.plannedStreak = 0;
            state.lastOurTo = null;
            state.lastExpectedWhiteCp = null;
            state.turnStartedAt = nowMs;
            state.oppLastThinkMs = null;
            state.oppThinkHistory = [];
            state.recentThinkTimes = [];
            state.recentWhiteEvalHistory = [];
            state.timingRegime = "EVAL";
            state.regimeMovesLeft = 2;
            state.lastConvCheckPly = -10;
            state.hasExitedTheory = false;
            state.lastTelemetryTag = "";
            state.fenHistory = initFen ? [initFen] : [];
            state.uciHistory = [];
            state.uciHistoryValid = true;
            const initKey = (fenToBoard64(initFen)?.join("") || "") + "|w";
            state.posVisitCounts = initFen ? { [initKey]: 1 } : {};
        };

        if (location.pathname !== state.lastPagePath) {
            state.lastPagePath = location.pathname;
            state.lastSeenFEN = "";
            state.ccTimeline = [];
            state.ccActiveIdx = 0;
            state._cgTimelineStartFen = null;
            state._cgLastLatestPly = 0;
            state.isBrowsingHistory = false;
        }

        if (game) {
            const raw = getRawBoardFEN();
            if (raw) {
                const clean = sanitizeFEN(raw);
                const nowMs = performance.now();
                const isCg = isCgSite();

                if (isCg) {
                    const isNewCgGame = Boolean(!state.lastSeenFEN || (state._cgTimelineStartFen && _cgCache.startFen !== state._cgTimelineStartFen));
                    const isTakeback = Boolean(!isNewCgGame && state._cgLastLatestPly && _cgCache.latestPly < state._cgLastLatestPly);
                    state._cgTimelineStartFen = _cgCache.startFen;
                    state._cgLastLatestPly = _cgCache.latestPly;
                    state.isBrowsingHistory = (_cgCache.viewedPly < _cgCache.latestPly);

                    if (isNewCgGame) {
                        resetForNewGameState(clean, nowMs);
                        if (clean.startsWith("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR")) {
                            state.uciHistory = _cgCache.timeline.slice(1).map(x => x.mvInfo?.uci).filter(Boolean);
                            state.uciHistoryValid = (state.uciHistory.length === _cgCache.timeline.length - 1);
                        }
                        state.lastSeenFEN = clean;
                        const entry = _cgCache.viewedPly >= 1 ? _cgCache.timeline[_cgCache.viewedPly] : null;
                        syncGradingToViewedState(clean, entry);
                    } else if (clean !== state.lastSeenFEN || isTakeback) {
                        const prevFen = state.lastSeenFEN;
                        const mvInfo = detectMoveBetweenFens(prevFen, clean);
                        const prevParts = prevFen.split(" ");
                        const currParts = clean.split(" ");
                        const myChar = (state.playingAs === 2) ? "b" : "w";

                        if (!state.isBrowsingHistory && !isTakeback) {
                            if (prevParts[1] === myChar && mvInfo.to) {
                                state.ourLastMoveTo = mvInfo.to;
                                state.lastOurTo = mvInfo.to;
                                const bAfterUs = fenToBoard64(clean);
                                const sqToIdx = (8 - parseInt(mvInfo.to[1], 10)) * 8 + (mvInfo.to.charCodeAt(0) - 97);
                                state.ourLastThreatenedSet = bAfterUs ? getAttackedSquares(bAfterUs, sqToIdx) : new Set();
                            } else if (mvInfo.uci) {
                                state.oppLastTo = mvInfo.to;
                                state.oppLastUCI = mvInfo.uci;
                                state.oppLastWasCapture = !!mvInfo.wasCapture;
                                state.oppPrevBoard64 = fenToBoard64(prevFen);
                            }
                            if (prevParts[1] !== currParts[1] && currParts[1] === myChar && typeof state.turnStartedAt === "number") {
                                const oppElapsed = Math.max(0, nowMs - state.turnStartedAt);
                                state.oppLastThinkMs = oppElapsed;
                                if (!Array.isArray(state.oppThinkHistory)) state.oppThinkHistory = [];
                                state.oppThinkHistory.push(oppElapsed);
                                if (state.oppThinkHistory.length > 12) state.oppThinkHistory.shift();
                            }
                            if (!Array.isArray(state.fenHistory)) state.fenHistory = [];
                            if (state.fenHistory[state.fenHistory.length - 1] !== clean) {
                                state.fenHistory.push(clean);
                                if (state.fenHistory.length > 10) state.fenHistory.shift();
                            }
                            state.turnStartedAt = nowMs;
                            if (!state.posVisitCounts) state.posVisitCounts = {};
                            const pKey = (fenToBoard64(clean)?.join("") || clean.split(" ")[0]) + "|" + (currParts[1] || "w");
                            state.posVisitCounts[pKey] = (state.posVisitCounts[pKey] || 0) + 1;
                        }
                        state.uciHistory = _cgCache.timeline.slice(1).map(x => x.mvInfo?.uci).filter(Boolean);
                        state.uciHistoryValid = (state.uciHistory.length === _cgCache.timeline.length - 1);

                        state.isThinking = false;
                        state.currentBestMove = null;
                        state.currentPV = [];
                        state.lastCandidates = [];
                        state.pendingCandEval = null;
                        state.pendingManualMove = false;
                        if (state.currentCloudRequest) {
                            try { state.currentCloudRequest.abort(); } catch (_) {}
                            state.currentCloudRequest = null;
                        }
                        if (settings.autoTimeMgmt || settings.humanMode) getClockTimesMs(game, clean);
                        if (state.isBrowsingHistory) {
                            Visuals.removeByType('bestmove');
                            Visuals.removeByType('analysis');
                            state.lastSanitizedBoardFEN = "";
                        } else {
                            Visuals.onMovePlayed();
                        }
                        PV.clear();
                        MultiBest.clear();
                        state.lastSeenFEN = clean;
                        const entry = _cgCache.viewedPly >= 1 ? _cgCache.timeline[_cgCache.viewedPly] : null;
                        syncGradingToViewedState(clean, entry);
                    }
                } else {
                    const domMoveCount = document.querySelectorAll(".move-list [data-ply], wc-simple-move-list .node, wc-simple-move-list [data-node], .vertical-move-list .node, .move-text-component, [data-whole-move-number]").length;
                    const isStartFen = clean.startsWith("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");
                    const foundIdx = state.ccTimeline.findIndex(item => item.fen === clean);
                    const currParts = clean.split(" ");
                    const currPly = ((parseInt(currParts[5], 10) || 1) - 1) * 2 + (currParts[1] === "b" ? 1 : 0);
                    const isNewCcGame = Boolean(
                        !state.lastSeenFEN ||
                        !state.ccTimeline.length ||
                        (isStartFen && foundIdx === -1 && state.ccTimeline.length > 1) ||
                        (isStartFen && foundIdx === 0 && state.ccTimeline.length > 1 && domMoveCount === 0) ||
                        (currPly <= 1 && state.ccTimeline.length > 3 && domMoveCount <= 1)
                    );

                    if (isNewCcGame) {
                        resetForNewGameState(clean, nowMs);
                        state.ccTimeline = [{ fen: clean, prevFen: null, mvInfo: null }];
                        state.ccActiveIdx = 0;
                        state.isBrowsingHistory = false;
                        state.lastSeenFEN = clean;
                        syncGradingToViewedState(clean, null);
                    } else if (clean !== state.lastSeenFEN) {
                        const prevFen = state.lastSeenFEN;
                        const mvInfo = detectMoveBetweenFens(prevFen, clean);
                        const prevParts = prevFen.split(" ");
                        const prevPly = ((parseInt(prevParts[5], 10) || 1) - 1) * 2 + (prevParts[1] === "b" ? 1 : 0);
                        const myChar = (state.playingAs === 2) ? "b" : "w";

                        if (foundIdx !== -1) {
                            state.ccActiveIdx = foundIdx;
                            state.isBrowsingHistory = (foundIdx < state.ccTimeline.length - 1);
                        } else if (currPly < prevPly) {
                            const fwdMv = detectMoveBetweenFens(clean, state.ccTimeline[0].fen);
                            if (fwdMv.singleHalfMove && fwdMv.uci) {
                                state.ccTimeline[0].prevFen = clean;
                                state.ccTimeline[0].mvInfo = fwdMv;
                            }
                            state.ccTimeline.unshift({ fen: clean, prevFen: null, mvInfo: null });
                            state.ccActiveIdx = 0;
                            state.isBrowsingHistory = (state.ccTimeline.length > 1);
                        } else if (mvInfo.singleHalfMove && mvInfo.uci) {
                            if (state.ccActiveIdx < state.ccTimeline.length - 1) {
                                state.ccTimeline = state.ccTimeline.slice(0, state.ccActiveIdx + 1);
                            }
                            state.ccTimeline.push({ fen: clean, prevFen, mvInfo });
                            state.ccActiveIdx = state.ccTimeline.length - 1;
                            state.isBrowsingHistory = false;
                        } else {
                            state.ccTimeline.push({ fen: clean, prevFen: null, mvInfo: null });
                            state.ccActiveIdx = state.ccTimeline.length - 1;
                            state.isBrowsingHistory = false;
                        }

                        if (!state.isBrowsingHistory) {
                            if (prevParts[1] === myChar && mvInfo.to) {
                                state.ourLastMoveTo = mvInfo.to;
                                state.lastOurTo = mvInfo.to;
                                const bAfterUs = fenToBoard64(clean);
                                const sqToIdx = (8 - parseInt(mvInfo.to[1], 10)) * 8 + (mvInfo.to.charCodeAt(0) - 97);
                                state.ourLastThreatenedSet = bAfterUs ? getAttackedSquares(bAfterUs, sqToIdx) : new Set();
                            } else if (mvInfo.uci) {
                                state.oppLastTo = mvInfo.to;
                                state.oppLastUCI = mvInfo.uci;
                                state.oppLastWasCapture = !!mvInfo.wasCapture;
                                state.oppPrevBoard64 = fenToBoard64(prevFen);
                            }
                            if (prevParts[1] !== currParts[1] && currParts[1] === myChar && typeof state.turnStartedAt === "number") {
                                const oppElapsed = Math.max(0, nowMs - state.turnStartedAt);
                                state.oppLastThinkMs = oppElapsed;
                                if (!Array.isArray(state.oppThinkHistory)) state.oppThinkHistory = [];
                                state.oppThinkHistory.push(oppElapsed);
                                if (state.oppThinkHistory.length > 12) state.oppThinkHistory.shift();
                            }
                            if (!Array.isArray(state.fenHistory)) state.fenHistory = [];
                            if (state.fenHistory[state.fenHistory.length - 1] !== clean) {
                                state.fenHistory.push(clean);
                                if (state.fenHistory.length > 10) state.fenHistory.shift();
                            }
                            state.turnStartedAt = nowMs;
                            if (!state.posVisitCounts) state.posVisitCounts = {};
                            const pKey = (fenToBoard64(clean)?.join("") || clean.split(" ")[0]) + "|" + (currParts[1] || "w");
                            state.posVisitCounts[pKey] = (state.posVisitCounts[pKey] || 0) + 1;
                            if (state.uciHistoryValid && mvInfo.singleHalfMove && mvInfo.uci) {
                                state.uciHistory.push(mvInfo.uci);
                            } else {
                                state.uciHistoryValid = false;
                            }
                        }

                        state.isThinking = false;
                        state.currentBestMove = null;
                        state.currentPV = [];
                        state.lastCandidates = [];
                        state.pendingCandEval = null;
                        state.pendingManualMove = false;
                        if (state.currentCloudRequest) {
                            try { state.currentCloudRequest.abort(); } catch (_) {}
                            state.currentCloudRequest = null;
                        }
                        if (settings.autoTimeMgmt || settings.humanMode) getClockTimesMs(game, clean);
                        if (state.isBrowsingHistory) {
                            Visuals.removeByType('bestmove');
                            Visuals.removeByType('analysis');
                            state.lastSanitizedBoardFEN = "";
                        } else {
                            Visuals.onMovePlayed();
                        }
                        PV.clear();
                        MultiBest.clear();
                        state.lastSeenFEN = clean;
                        const entry = state.ccActiveIdx >= 1 ? state.ccTimeline[state.ccActiveIdx] : null;
                        syncGradingToViewedState(clean, entry);
                    }
                }

                if (settings.moveGrading && state.graderReady && !state.graderSearching && state.graderQueue.length) {
                    pumpGraderQueue();
                }
                const isTurn = isUserTurn(game);
                if (settings.autoRun && isTurn && !state.isBrowsingHistory && clean !== state.lastSanitizedBoardFEN) analyze(settings.depth);
            }
        }

        if (!state.ui?.panel) { createUI(); syncAllUI(); }

        updateUI();
    }

    // --- GLOBAL KEYBIND & PANEL INPUT CAPTURE ---
    function isTypingInScriptPanel(e) {
        const path = typeof e.composedPath === "function" ? e.composedPath() : [];
        for (const n of path) {
            if (n && n.id === "shadowMount") return true;
        }
        const shadowEl = state.shadow?.activeElement;
        if (shadowEl && (shadowEl.tagName === "INPUT" || shadowEl.tagName === "TEXTAREA" || shadowEl.tagName === "SELECT")) return true;
        if (e.target && e.target.id === "shadowMount") return true;
        return false;
    }

    function isScriptShortcutKey(e) {
        const keyName = e.key === " " ? "Space" : e.key;
        const low = String(keyName || "").toLowerCase();
        if (!low) return false;
        if (settings.uiKeybind && settings.uiKeybind !== "None" && low === settings.uiKeybind.toLowerCase()) return "ui";
        if (!settings.autoMove && settings.moveKeybind && settings.moveKeybind !== "None" && low === settings.moveKeybind.toLowerCase()) return "move";
        return false;
    }

    window.addEventListener("keydown", (e) => {
        if (isTypingInScriptPanel(e)) {
            if (e.key === "Escape") {
                if (state.ui.advUiModalOv?.style.display === "flex") { state.ui.advUiModalOv.style.display = "none"; e.stopImmediatePropagation(); return; }
                if (state.ui.helpModalOv?.style.display === "flex") { state.ui.helpModalOv.style.display = "none"; e.stopImmediatePropagation(); return; }
                if (state.ui.langModalOv?.style.display === "flex") { state.ui.langModalOv.style.display = "none"; e.stopImmediatePropagation(); return; }
                if (state.ui.modalOv?.style.display === "flex") { state.ui.modalOv.style.display = "none"; e.stopImmediatePropagation(); return; }
                if (state.ui.localModalOv?.style.display === "flex") { state.ui.localModalOv.style.display = "none"; e.stopImmediatePropagation(); return; }
            }
            // Forcefully stop site shortcuts (e.g. f, space, arrow keys, numbers) while typing inside our shadow panel
            e.stopPropagation();
            if (typeof e.stopImmediatePropagation === "function") e.stopImmediatePropagation();
            return;
        }
        if (e.key === "Escape") {
            if (state.ui.advUiModalOv?.style.display === "flex") { state.ui.advUiModalOv.style.display = "none"; return; }
            if (state.ui.helpModalOv?.style.display === "flex") { state.ui.helpModalOv.style.display = "none"; return; }
            if (state.ui.langModalOv?.style.display === "flex") { state.ui.langModalOv.style.display = "none"; return; }
            if (state.ui.modalOv?.style.display === "flex") { state.ui.modalOv.style.display = "none"; return; }
            if (state.ui.localModalOv?.style.display === "flex") { state.ui.localModalOv.style.display = "none"; return; }
            if (state.gradeBreakdownOpen) { state.gradeBreakdownOpen = false; updateUI(); return; }
        }
        if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA" || e.target.isContentEditable) return;

        const kind = isScriptShortcutKey(e);
        if (kind === "ui") {
            e.preventDefault();
            e.stopPropagation();
            if (typeof e.stopImmediatePropagation === "function") e.stopImmediatePropagation();
            state.uiVisible = !state.uiVisible;
            if (state.ui?.panel) state.ui.panel.classList.toggle("ui-hidden", !state.uiVisible);
            if (!state.uiVisible) {
                if (state.ui?.modalOv) state.ui.modalOv.style.display = "none";
                if (state.ui?.localModalOv) state.ui.localModalOv.style.display = "none";
                if (state.ui?.advUiModalOv) state.ui.advUiModalOv.style.display = "none";
                if (state.ui?.helpModalOv) state.ui.helpModalOv.style.display = "none";
                if (state.ui?.langModalOv) state.ui.langModalOv.style.display = "none";
                if (state.ui?.tallyPanel) state.ui.tallyPanel.style.display = "none";
            } else {
                updateUI();
            }
            return;
        }
        if (kind === "move") {
            e.preventDefault();
            e.stopPropagation();
            if (typeof e.stopImmediatePropagation === "function") e.stopImmediatePropagation();
            const game = getActiveGame();
            if (!game || !isUserTurn(game)) return;
            const currentRaw = getRawBoardFEN();
            const cleanNow = currentRaw ? sanitizeFEN(currentRaw) : "";
            const fenMatches = Boolean(cleanNow && state.lastSanitizedBoardFEN && cleanNow === state.lastSanitizedBoardFEN);

            if (state.currentBestMove && fenMatches && !state.isThinking) {
                state.pendingManualMove = false;
                playMove(state.currentBestMove);
            } else if (state.isThinking && fenMatches) {
                state.pendingManualMove = true;
                updateUI();
            } else if (cleanNow) {
                state.isThinking = false;
                analyze(settings.depth);
                state.pendingManualMove = true;
                updateUI();
            }
        }
    }, true);

    ["keypress", "keyup"].forEach(evType => {
        window.addEventListener(evType, (e) => {
            if (isTypingInScriptPanel(e)) {
                e.stopPropagation();
                if (typeof e.stopImmediatePropagation === "function") e.stopImmediatePropagation();
                return;
            }
            if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA" || e.target.isContentEditable) return;
            if (isScriptShortcutKey(e)) {
                e.preventDefault();
                e.stopPropagation();
                if (typeof e.stopImmediatePropagation === "function") e.stopImmediatePropagation();
            }
        }, true);
    });

    _runKeyGate(function() {
        loadSettings();
        if (document.body) toggleAutoQueue();
        else document.addEventListener("DOMContentLoaded", () => toggleAutoQueue(), { once: true });
        setInterval(mainLoop, CONFIG.LOOP_MS);
    });
})();