☰

best cheat chess

The most powerful Chess.com assistant — Stockfish 19–90, humanized play, PV arrows, eval bar, auto-move, key-gated access. Join our Discord for keys and updates.

Vous devrez installer une extension telle que Tampermonkey, Greasemonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Userscripts pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey pour installer ce script.

Vous devrez installer une extension de gestionnaire de script utilisateur pour installer ce script.

(J'ai déjà un gestionnaire de scripts utilisateur, laissez-moi l'installer !)

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

(J'ai déjà un gestionnaire de style utilisateur, laissez-moi l'installer!)

// ==UserScript==
// @name          best cheat chess
// @namespace     http://tampermonkey.net/
// @version       2.0.0
// @description   The most powerful Chess.com assistant — Stockfish 19–90, humanized play, PV arrows, eval bar, auto-move, key-gated access. Join our Discord for keys and updates.
// @author        Enhee Tulgaa
// @copyright     2026, Enhee Tulgaa
// @license       MIT
// @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
// @connect       chess-api.com
// @connect       stockfish.online
// @connect       unpkg.com
// @connect       cdnjs.cloudflare.com
// @connect       *
// @grant         GM_getResourceText
// @grant         GM_getValue
// @grant         GM_setValue
// @grant         GM_xmlhttpRequest
// @resource      stockfish.js https://unpkg.com/[email protected]/bin/stockfish-19-lite-single.js
// @run-at        document-idle
// ==/UserScript==
(function () {
    "use strict";

    // ─── KEY GATE SYSTEM ──────────────────────────────────────────────
    const KEY_DISCORD  = "https://discord.gg/HKv6bGcWQ";
    const KEY_DURATION = 24 * 60 * 60 * 1000;
    const VALID_KEYS   = {
        "83W3-MCUA-LPFX-GEYK": 1795865161615,
    };
    const KS_KEY = "cheat_active_key", KS_EXP = "cheat_key_expiry";
    function ksGet(k){try{return GM_getValue(k);}catch(_){return localStorage.getItem(k);}}
    function ksSet(k,v){try{GM_setValue(k,v);}catch(_){localStorage.setItem(k,String(v));}}
    function validateKey(input){
        const k=input.trim().toUpperCase();
        if(!(k in VALID_KEYS))return{ok:false,reason:"Invalid key."};
        const exp=VALID_KEYS[k];
        if(exp!==0&&Date.now()>exp)return{ok:false,reason:"Key expired."};
        return{ok:true,expiry:exp};
    }
    function isSessionValid(){
        const k=ksGet(KS_KEY);
        if(!k||k.trim()==="")return false;
        const kUpper=k.trim().toUpperCase();
        if(!(kUpper in VALID_KEYS))return false;
        const meta=VALID_KEYS[kUpper];
        if(meta!==0&&Date.now()>meta)return false;
        const expRaw=ksGet(KS_EXP);
        if(!expRaw||expRaw==="0"||expRaw==="")return false;
        const exp=parseInt(expRaw,10);
        if(isNaN(exp)||exp===0)return false;
        if(Date.now()>exp)return false;
        return true;
    }
    function activateKey(key,expiry){
        const sessionExp=expiry===0?Date.now()+KEY_DURATION:Math.min(expiry,Date.now()+KEY_DURATION);
        ksSet(KS_KEY,key.trim().toUpperCase());
        ksSet(KS_EXP,String(sessionExp));
    }
    function clearKey(){ksSet(KS_KEY,"");ksSet(KS_EXP,"");}
    window.generateKey=function(permanent=false){
        const seg=()=>Math.random().toString(36).substring(2,6).toUpperCase().padEnd(4,"X");
        const key=`${seg()}-${seg()}-${seg()}-${seg()}`;
        const exp=permanent?0:Date.now()+KEY_DURATION;
        VALID_KEYS[key]=exp;
        console.log(`%c[KEY] ${key}  expires: ${permanent?"never":new Date(exp).toLocaleString()}\nAdd to VALID_KEYS: "${key}": ${exp},`,"color:#3fb950;font-weight:700");
        return key;
    };
    function showKeyGate(){
        const ov=document.createElement("div");
        ov.id="cheat-gate";
        ov.style.cssText="position:fixed;inset:0;z-index:2147483647;background:rgba(0,0,0,0.88);backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;";
        ov.innerHTML=`<div style="background:#0d1117;border:1px solid rgba(255,255,255,0.12);border-radius:16px;padding:32px 28px;width:min(380px,90vw);display:flex;flex-direction:column;gap:18px;box-shadow:0 24px 60px rgba(0,0,0,0.8);">
        <div style="font-size:22px;font-weight:800;color:#f0f6fc;">&#128273; Access Required</div>
        <div style="font-size:13px;color:#8b949e;line-height:1.5;">Enter your 24-hour access key.<br>No key? Grab one from Discord.</div>
        <input id="gate-inp" type="text" placeholder="XXXX-XXXX-XXXX-XXXX" style="background:#161b22;border:1px solid rgba(255,255,255,0.14);border-radius:8px;color:#f0f6fc;font-size:15px;font-weight:700;letter-spacing:0.08em;padding:12px 14px;outline:none;text-align:center;text-transform:uppercase;font-family:ui-monospace,Menlo,monospace;width:100%;box-sizing:border-box;"/>
        <div id="gate-err" style="display:none;color:#f85149;font-size:12px;text-align:center;padding:8px;background:rgba(248,81,73,0.1);border-radius:6px;border:1px solid rgba(248,81,73,0.25);"></div>
        <button id="gate-ok" style="background:linear-gradient(135deg,#2ea043,#238636);color:#fff;font-weight:700;font-size:14px;border:none;border-radius:8px;padding:12px;cursor:pointer;width:100%;">Activate Key</button>
        <a href="${KEY_DISCORD}" target="_blank" style="display:flex;align-items:center;justify-content:center;gap:8px;background:rgba(88,101,242,0.15);border:1px solid rgba(88,101,242,0.35);color:#7289da;font-size:13px;font-weight:600;border-radius:8px;padding:10px;text-decoration:none;">
            <svg width="18" height="14" viewBox="0 0 71 55" fill="currentColor"><path d="M60.1 4.9A58.5 58.5 0 0 0 45.5.9a.2.2 0 0 0-.2.1 40.7 40.7 0 0 0-1.8 3.7 54 54 0 0 0-16.2 0A37.6 37.6 0 0 0 25.5 1a.2.2 0 0 0-.2-.1A58.4 58.4 0 0 0 10.9 4.9a.2.2 0 0 0-.1.1C1.6 18.7-.9 32.1.3 45.3a.2.2 0 0 0 .1.2 58.8 58.8 0 0 0 17.7 8.9.2.2 0 0 0 .2-.1 42 42 0 0 0 3.6-5.9.2.2 0 0 0-.1-.3 38.7 38.7 0 0 1-5.5-2.6.2.2 0 0 1 0-.4l1.1-.8a.2.2 0 0 1 .2 0c11.5 5.3 24 5.3 35.4 0a.2.2 0 0 1 .2 0l1.1.8a.2.2 0 0 1 0 .4 36.1 36.1 0 0 1-5.5 2.6.2.2 0 0 0-.1.3 47.1 47.1 0 0 0 3.6 5.9.2.2 0 0 0 .2.1 58.6 58.6 0 0 0 17.7-8.9.2.2 0 0 0 .1-.2c1.4-15.1-2.4-28.4-10-40.3a.2.2 0 0 0-.1-.1zM23.7 37.3c-3.5 0-6.4-3.2-6.4-7.1s2.8-7.1 6.4-7.1c3.6 0 6.5 3.2 6.4 7.1 0 3.9-2.9 7.1-6.4 7.1zm23.6 0c-3.5 0-6.4-3.2-6.4-7.1s2.8-7.1 6.4-7.1c3.6 0 6.5 3.2 6.4 7.1 0 3.9-2.8 7.1-6.4 7.1z"/></svg>
            Get a Key on Discord
        </a>
        <div style="font-size:11px;color:#6e7681;text-align:center;">Keys are valid for 24 hours.</div></div>`;
        document.documentElement.appendChild(ov);
        const inp=ov.querySelector("#gate-inp"),err=ov.querySelector("#gate-err"),btn=ov.querySelector("#gate-ok");
        const attempt=()=>{
            const res=validateKey(inp.value);
            if(!res.ok){err.style.display="block";err.textContent=res.reason+" Join Discord for a valid key.";inp.style.borderColor="rgba(248,81,73,0.6)";return;}
            activateKey(inp.value.trim().toUpperCase(),res.expiry);
            ov.remove();
            mainInit();
        };
        btn.onclick=attempt;
        inp.addEventListener("keydown",e=>{if(e.key==="Enter")attempt();});
        inp.addEventListener("input",()=>{inp.style.borderColor="rgba(255,255,255,0.14)";err.style.display="none";});
        inp.focus();
    }
    function startExpiryWatchdog(){
        setInterval(()=>{
            if(!isSessionValid()){clearKey();document.getElementById("shadowMount")?.remove();showKeyGate();}
        },60000);
    }
    // Force-clear any stale session stored before v2.0 key system
    (function migrateLegacySession(){
        const k=ksGet(KS_KEY);
        if(k&&!(k.trim().toUpperCase()in VALID_KEYS)){clearKey();}
        const expRaw=ksGet(KS_EXP);
        if(!expRaw||expRaw==="0"){clearKey();}
    })();
    if(isSessionValid()){startExpiryWatchdog();mainInit();}
    else{clearKey();showKeyGate();}
    // ─── END KEY GATE SYSTEM ──────────────────────────────────────────

    function mainInit(){

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

    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>`;
    const DISCORD_ICON = `<svg width="16" height="12" viewBox="0 0 71 55" fill="currentColor"><path d="M60.1 4.9A58.5 58.5 0 0 0 45.5.9a.2.2 0 0 0-.2.1 40.7 40.7 0 0 0-1.8 3.7 54 54 0 0 0-16.2 0A37.6 37.6 0 0 0 25.5 1a.2.2 0 0 0-.2-.1A58.4 58.4 0 0 0 10.9 4.9a.2.2 0 0 0-.1.1C1.6 18.7-.9 32.1.3 45.3a.2.2 0 0 0 .1.2 58.8 58.8 0 0 0 17.7 8.9.2.2 0 0 0 .2-.1 42 42 0 0 0 3.6-5.9.2.2 0 0 0-.1-.3 38.7 38.7 0 0 1-5.5-2.6.2.2 0 0 1 0-.4l1.1-.8a.2.2 0 0 1 .2 0c11.5 5.3 24 5.3 35.4 0a.2.2 0 0 1 .2 0l1.1.8a.2.2 0 0 1 0 .4 36.1 36.1 0 0 1-5.5 2.6.2.2 0 0 0-.1.3 47.1 47.1 0 0 0 3.6 5.9.2.2 0 0 0 .2.1 58.6 58.6 0 0 0 17.7-8.9.2.2 0 0 0 .1-.2c1.4-15.1-2.4-28.4-10-40.3a.2.2 0 0 0-.1-.1zM23.7 37.3c-3.5 0-6.4-3.2-6.4-7.1s2.8-7.1 6.4-7.1c3.6 0 6.5 3.2 6.4 7.1 0 3.9-2.9 7.1-6.4 7.1zm23.6 0c-3.5 0-6.4-3.2-6.4-7.1s2.8-7.1 6.4-7.1c3.6 0 6.5 3.2 6.4 7.1 0 3.9-2.8 7.1-6.4 7.1z"/></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 },
        },
    ];

    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,
        visuals: [],
        shadow: null
    };

    const HUMAN_PRESETS = {
        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,
        humanMode: false,
        humanPreset: "master",
        moveKeybind: "None",
        maxThinkingTime: 0,
        searchMoves: "",
        autoRun: true,
        autoMove: true,
        autoQueue: false,
        showEvalBar: true,
        showPVArrows: false,
        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: false,
        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,
    };
    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 saveSetting(key, val) {
        settings[key] = val;
        // Model-specific settings are saved exclusively via saveModelSetting
        if (MODEL_ONLY_KEYS.has(key)) return;
        try { GM_setValue(`bot_${key}`, val); } catch(_) {}
        lsSet(`bot_${key}`, 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;
    }

    // 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"
    ]);

    function loadSettings() {
        Object.keys(DEFAULT_SETTINGS).forEach((k) => {
            // Skip model-specific keys — loadModelSettings() handles them
            if (MODEL_ONLY_KEYS.has(k)) return;
            let saved;
            // Try GM storage first
            try { saved = GM_getValue(`bot_${k}`); } 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(`bot_${k}`); 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(`bot_${k}`, saved);
            }
        });
        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 = state.board?.game || document.querySelector("chess-board, wc-chess-board")?.game;
        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 (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") {
                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 existing = document.querySelector(`.${id}`);
            if (existing) {
                if (!state.board.contains(existing)) existing.remove();
                else return;
            }
            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}`;
                    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;`;
                    }
                    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}`).forEach(el => el.remove());

            if (vis?.isNative || settings.visualType === "nativeArrow") {
                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));
        }
    };

    // --- PV MANAGER ---
    const PV = {
        interval: null,
        lastMoves: [],
        update: (pvMoves) => {
            PV.lastMoves = pvMoves || [];
            if (!settings.showPVArrows) { 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;
        let isFlipped = state.board.classList.contains("flipped");
        if (!isFlipped && state.board.game && state.board.game.getPlayingAs) {
            const pa = state.board.game.getPlayingAs();
            if (pa === "b" || pa === 2 || pa === "black") isFlipped = true;
        }
        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 = 4 * scale, headWidth = 3 * scale, lineWidth = 1.0 * scale;
        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;
        let isFlipped = state.board.classList.contains("flipped");
        if (!isFlipped && state.board.game && state.board.game.getPlayingAs) {
            const pa = state.board.game.getPlayingAs();
            if (pa === "b" || pa === 2 || pa === "black") isFlipped = true;
        }
        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 = 4 * scale, headWidth = 3 * scale, lineWidth = 1.2 * scale;
        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-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, "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", opacity);
        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);
    }

    // --- 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;
            }
            /* 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;
                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 boardLayout = document.querySelector('.board-layout-chessboard');
            if (!boardLayout) return;

            // 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 = '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: () => {
            // 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);
            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) {
        state.engineStatus = status;
        if (status === "error") {
            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}`)); 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 === "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
                        });
                    });
                });
            }
        });
    }

    // --- 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 === "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, () => 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, () =>
                        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;
        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;
        let finalFEN = fenOverride || sanitizeFEN(getRawBoardFEN());
        if (!finalFEN) return;
        state.lastSentFEN = finalFEN;
        if (!fenOverride) state.lastSanitizedBoardFEN = finalFEN;
        state.isThinking = true;
        state.analysisStartTime = performance.now();
        const minMs = settings.minDelay * 1000, maxMs = settings.maxDelay * 1000;
        const delay = Math.random() * (maxMs - minMs) + minMs;
        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 analyzeCloud(finalFEN, depth, isRetry) {
        const actualDepth = Math.min(depth, 18);
        const payload = {
            fen: finalFEN,
            depth: actualDepth,
            maxThinkingTime: Math.min(settings.maxThinkingTime, CONFIG.API.MAX_TIME),
            taskId: Math.random().toString(36).substring(7),
        };
        if (settings.searchMoves.trim()) payload.searchmoves = settings.searchMoves.trim();
        state.lastLiveResult = formatLiveResult("...", { text: isRetry ? "Retrying FEN..." : "Cloud Analyzing...", color: "#58a6ff" }, "", "Waiting for API...");
        updateUI();

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

    function analyzeSFOnline(finalFEN, depth) {
        const actualDepth = Math.min(depth, 15);
        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) {
        state.isThinking = false;
        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) { triggerFallback(); return; }
            const bestMove = data.bestmove.split(" ")[1] || data.bestmove;
            const duration = ((performance.now() - state.analysisStartTime) / 1000).toFixed(2);
            processBestMove(bestMove, data.evaluation, data.mate, data.continuation ? data.continuation.split(" ") : null, null, duration, depth, true);
        } catch (e) { triggerFallback(); }
        updateUI();
    }

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

        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;
        }
        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 m = getEngineById(settings.localModelId);
        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 = state.board?.game || document.querySelector("chess-board, wc-chess-board")?.game;
        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 wantMultiPV = (!settings.humanMode || isFastBookOrForced)
            ? 1
            : (!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 = { 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 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 isFreeBigPiece = pv1Feat.isFreeCapture && (pv1Feat.capVal || 0) >= 3;
            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) : (cp >= 250 ? 85 : 30);
                    maxLoss = isHighTier ? preset.maxCritLoss : (isUncertain ? (preset.maxCritLoss + 140) : (preset.maxCritLoss + 65));
                    missChance = isHotMomentum ? preset.critMissRate * 0.75 : Math.min(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(0.78, preset.critMissRate + 0.22)
                        : (isHotMomentum ? preset.critMissRate * 0.70 : preset.critMissRate);
                }
                if (landscape.sharpness >= 0.55 && !isHighTier) missChance = Math.min(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 >= -14 && !(cp > 35 && x.feat.repCount >= 1));

                if (critAlts.length > 0 && Math.random() < missChance) {
                    critAlts.sort((a, b) => b.h - a.h);
                    const pickIdx = (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 handleLocalMessage(e) {
        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(" ");
                    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 (pv) {
                        const best = pv.split(" ")[0];
                        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);
                }

                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();
        }
    }

    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:4px; 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();
        const evalNum = (evalScore !== null && evalScore !== undefined) ? parseFloat(evalScore) : null;
        const mateNum = (mate !== null && mate !== undefined && mate !== 0) ? parseInt(mate) : null;
        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();
        state.lastMoveResult = formatMoveResult(activeTitle, wcHtml, bestMove || "--");
        state.lastLiveResult = formatLiveResult(scoreTxt, statusData, durHtml, pvStr);

        if (settings.autoMove) triggerAutoMove();
    }

    function isUserTurn(game) {
        if (!game) 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");
        if (gameOverEl) return false;

        return pNorm === tNorm;
    }

    function triggerAutoMove() {
        const game = state.board?.game || document.querySelector("chess-board, wc-chess-board")?.game;
        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;
        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 = state.board?.game || document.querySelector("chess-board, wc-chess-board")?.game;
        if (!game || !isUserTurn(game)) return;
        Visuals.onMovePlayed();
        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 (typeof game.getLegalMoves === "function") {
            for (const m of game.getLegalMoves()) {
                if (m.from === from && m.to === to) {
                    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) {
            state.newGameObserver = new MutationObserver(() => {
                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; }, 250);
                }
            });
            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
        EvalBar.reset();

        // 3. Forcefully override all settings to DEFAULT_SETTINGS
        Object.keys(DEFAULT_SETTINGS).forEach(k => {
            settings[k] = DEFAULT_SETTINGS[k];
            if (MODEL_ONLY_KEYS.has(k)) {
                saveModelSetting(k, DEFAULT_SETTINGS[k], settings.localModelId);
            } else {
                try { GM_setValue(`bot_${k}`, DEFAULT_SETTINGS[k]); } catch(_) {}
                lsSet(`bot_${k}`, DEFAULT_SETTINGS[k]);
            }
        });
        if (state.localEngine && state.engineStatus === "ready") {
            sendEngineInitCommands(settings.localModelId);
        }
        try { GM_setValue("bot_menuPosition", "top-right"); } catch(_) {} lsSet("bot_menuPosition", "top-right");
        try { GM_setValue("bot_pX", "auto"); } catch(_) {} lsSet("bot_pX", "auto");
        try { GM_setValue("bot_pY", "0"); } catch(_) {} lsSet("bot_pY", "0");
        try { GM_setValue("bot_panelW", "296px"); } catch(_) {} lsSet("bot_panelW", "296px");
        try { GM_setValue("bot_panelH", "auto"); } catch(_) {} lsSet("bot_panelH", "auto");
        try { GM_setValue("bot_isMini", false); } catch(_) {} lsSet("bot_isMini", false);

        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.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();
        applyTheme();
        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];
        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;
        });

        updateUI();
        updateLocalSettingsUI();
    }
function applyMenuPosition() {
        const p = state.ui.panel;
        if (!p) return;
        const margin = "0px";
        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_pX"); } catch(_) {} if (savedX === undefined || savedX === null) savedX = lsGet("bot_pX", "auto");
            let savedY; try { savedY = GM_getValue("bot_pY"); } catch(_) {} if (savedY === undefined || savedY === null) savedY = lsGet("bot_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);

        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 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 (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 (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";
        };
        show("rowMoveOverhead",  m.hasMoveOverhead);
        show("rowSkillLevel",    m.hasSkillLevel);
        show("rowLimitStrength", m.hasNNUE);

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


    // --- 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;
        let savedW; try { savedW = GM_getValue("bot_panelW"); } catch(_) {} if (savedW === undefined || savedW === null || savedW === "") savedW = lsGet("bot_panelW", "296px");
        let savedH; try { savedH = GM_getValue("bot_panelH"); } catch(_) {} if (savedH === undefined || savedH === null || savedH === "") savedH = lsGet("bot_panelH", "auto");
        let isMini; try { isMini = GM_getValue("bot_isMini"); } catch(_) {} if (isMini === undefined || isMini === null) isMini = lsGet("bot_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: 288px;
                max-height: 100vh;
                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 20px 48px -8px rgba(0,0,0,0.75), 0 0 0 1px rgba(255,255,255,0.06) inset;
                display: flex;
                flex-direction: column;
                resize: both;
                overflow: hidden;
                opacity: ${settings.menuOpacity};
                border-radius: 14px;
                backdrop-filter: blur(20px) saturate(180%);
            }

            #enginePanel.minified {
                width: 42px !important;
                height: 42px !important;
                resize: none;
                min-height: 0 !important;
                min-width: 0 !important;
                overflow: hidden !important;
                background: var(--bot-bg) !important;
                border: 1px solid var(--bot-b) !important;
                color: var(--bot-t) !important;
                border-radius: 50% !important;
                padding: 0 !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
                cursor: pointer;
                box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3), 0 0 12px rgba(46, 160, 67, 0.35) !important;
                backdrop-filter: blur(16px);
                transition: transform 0.2s ease, border-color 0.2s ease;
            }
            #enginePanel.minified:hover {
                transform: scale(1.08);
                border-color: var(--bot-p) !important;
            }
            #enginePanel.minified #panelContent,
            #enginePanel.minified #panelHeader > *:not(.header-left),
            #enginePanel.minified .header-left > *:not(#minBtn) {
                display: none !important;
            }
            #enginePanel.minified #panelHeader {
                width: 100% !important;
                height: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
                border: none !important;
                background: transparent !important;
                justify-content: center !important;
                cursor: pointer !important;
            }
            #enginePanel.minified .header-left {
                width: 100% !important;
                height: 100% !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
                gap: 0 !important;
            }
            #enginePanel.minified #minBtn {
                width: 100% !important;
                height: 100% !important;
                display: flex !important;
                justify-content: center !important;
                align-items: center !important;
                padding: 0 !important;
                margin: 0 !important;
                background: transparent !important;
                color: var(--bot-t) !important;
            }
            #enginePanel.minified #minBtn svg {
                width: 22px !important;
                height: 22px !important;
                display: block;
                filter: drop-shadow(0 0 4px rgba(63,185,80,0.45));
            }

            #panelHeader {
                background: linear-gradient(180deg, rgba(255,255,255,0.06) 0%, rgba(255,255,255,0.01) 100%);
                border-bottom: 1px solid var(--bot-b);
                color: var(--bot-t);
                padding: 0 14px;
                font-weight: 600;
                font-size: 12.5px;
                letter-spacing: 0.03em;
                display: flex;
                justify-content: space-between;
                align-items: center;
                cursor: move;
                height: 40px;
                flex-shrink: 0;
                user-select: 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 8px var(--bot-p);
            }
            #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: 12px 14px;
                display: flex;
                flex-direction: column;
                gap: 10px;
                overflow-y: auto;
                flex: 1;
                min-height: 0;
            }

            .hero-card {
                background: linear-gradient(180deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.01) 100%);
                border: 1px solid rgba(255,255,255,0.08);
                border-radius: 10px;
                padding: 8px 12px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                height: 64px;
                min-height: 64px;
                max-height: 64px;
                overflow: hidden;
                flex-shrink: 0;
                min-width: 0;
                box-sizing: border-box;
            }
            #moveResult, #statusBox {
                width: 100%;
                min-width: 0;
                overflow: hidden;
            }
            .score-pill {
                display: inline-flex; align-items: center; justify-content: center;
                padding: 1px 7px; border-radius: 6px;
                background: rgba(46, 160, 67, 0.15); border: 1px solid rgba(46, 160, 67, 0.3);
                color: var(--bot-primary); font-size: 12.5px; font-weight: 800;
                font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
                font-variant-numeric: tabular-nums;
                flex-shrink: 0;
            }

            .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: rgba(255,255,255,0.1); color: #fff;
                box-shadow: 0 1px 4px rgba(0,0,0,0.4);
            }

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

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

            input, select {
                background: var(--bot-input-bg);
                color: var(--bot-t);
                border: 1px solid var(--bot-b);
                padding: 4px 8px;
                border-radius: 6px;
                font-size: 12px;
                height: 28px;
                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: 8px;
            }
            .switch-row {
                display: flex;
                justify-content: space-between;
                align-items: center;
                cursor: pointer;
                user-select: none;
                font-size: 12px;
            }
            .switch-row input { display: none; }
            .switch-pill {
                width: 30px; height: 16px; border-radius: 8px;
                background: var(--bot-track-bg);
                position: relative; transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
                flex-shrink: 0;
            }
            .switch-pill::after {
                content: ""; position: absolute; top: 2px; left: 2px;
                width: 12px; height: 12px; border-radius: 50%;
                background: #ffffff;
                transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
                box-shadow: 0 1px 3px rgba(0,0,0,0.4);
            }
            .switch-row input:checked + .switch-pill {
                background: var(--bot-p);
            }
            .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: 34px; font-size: 12.5px;
                background: linear-gradient(135deg, #2ea043 0%, #238636 100%) !important;
                color: #fff !important;
                border: 1px solid rgba(255,255,255,0.15) !important;
                box-shadow: 0 4px 14px rgba(46, 160, 67, 0.35);
            }
            .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;
            }
            .btn-action-secondary:hover { background: var(--bot-card-b) !important; }

            .btn-stack { display: flex; flex-direction: column; gap: 6px; margin-top: 2px; }

            .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);
            }
            .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" class="${isMini ? "minified" : ""}">
                <div id="panelHeader">
                    <div class="header-left">
                        <span class="engine-live-dot"></span>
                        <span style="font-weight:700; letter-spacing:0.02em;">Stockfish</span>
                        <span id="minBtn">${isMini ? STOCKFISH_ICON : "▼"}</span>
                    </div>
                    <div style="display:flex; align-items:center; gap:6px;">
                        <a id="btnDiscord" href="https://discord.gg/HKv6bGcWQ" target="_blank" style="display:inline-flex;align-items:center;gap:5px;padding:0 8px;height:24px;font-size:11px;font-weight:600;background:rgba(88,101,242,0.18);color:#7289da;border:1px solid rgba(88,101,242,0.35);border-radius:5px;text-decoration:none;white-space:nowrap;">${DISCORD_ICON} Discord</a>
                        <button id="btnVisuals" style="padding:0 10px; height:24px; font-size:11px; font-weight:600; background:rgba(255,255,255,0.08); color:var(--bot-t); border:1px solid rgba(255,255,255,0.12); border-radius:5px;">Visuals</button>
                    </div>
                </div>
                <div id="panelContent">
                    <!-- 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>

                    <!-- Engine Mode & Depth Section -->
                    <div class="sect">
                        <div class="sect-title">Engine Mode</div>
                        <div class="seg-control">
                            <button id="segCloud" class="seg-btn ${settings.engineMode==='cloud'?'active':''}">Cloud</button>
                            <button id="segSFOnline" class="seg-btn ${settings.engineMode==='sfonline'?'active':''}">Online</button>
                            <button id="segLocal" class="seg-btn ${settings.engineMode==='local'?'active':''}">Local</button>
                        </div>
                        <label class="switch-row" id="rowAutoTime" style="margin-top:6px;">
                            <span>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" style="margin-top:4px;">
                            <label>Search Depth <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>

                    <!-- Features -->
                    <div class="sect">
                        <div class="sect-title">Features</div>
                        <div class="toggle-list">
                            <label class="switch-row">
                                <span>Auto-Analyze</span>
                                <input type="checkbox" id="chkRun" ${settings.autoRun ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <label class="switch-row">
                                <span>Auto-Move</span>
                                <input type="checkbox" id="chkMove" ${settings.autoMove ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <label class="switch-row" title="Uses material phase, clock gradient, recapture detection, and MultiPV variance to play like a strong human.">
                                <span>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"}; margin-top:-2px;">
                                <label style="color:var(--bot-t-sec); font-size:11.5px;">Human Profile</label>
                                <select id="selHumanPreset" style="width:142px; height:26px; font-size:11.5px;">
                                    <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">
                                <span>Auto-Queue</span>
                                <input type="checkbox" id="chkQueue" ${settings.autoQueue ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <label class="switch-row">
                                <span>Evaluation Bar</span>
                                <input type="checkbox" id="chkEvalBar" ${settings.showEvalBar ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                        </div>

                        <!-- Automation Parameters -->
                        <div class="row" id="rowMoveKeybind" style="display:${settings.autoMove ? 'none' : 'flex'}; margin-top:4px;">
                            <label>Manual Move Key</label>
                            <button id="btnMoveKeybind" style="width:90px; 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" style="margin-top:4px;">
                            <label>Delay Window (s)</label>
                            <div style="display:flex; align-items:center; gap:6px;">
                                <input type="number" id="inpMin" style="width:48px;" value="${settings.minDelay}" step="0.1">
                                <span style="color:var(--bot-t-sec); font-size:11px;">–</span>
                                <input type="number" id="inpMax" style="width:48px;" value="${settings.maxDelay}" step="0.1">
                            </div>
                        </div>
                        <div id="delayDisplay" style="font-size:11px; color:#58a6ff; font-family:monospace; text-align:right;">Next delay: N/A</div>
                    </div>

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

            <!-- Single-View Visuals Modal -->
            <div id="modalOv" class="modal-overlay">
                <div id="modal" class="modal-window">
                    <div class="modal-header">
                        <h3>Visuals</h3>
                        <button id="modalClose" class="modal-close-btn">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="sect" style="border:none; padding:0;">
                            <div class="sect-title">Board Highlights</div>
                            <div class="row">
                                <label>Style Mode</label>
                                <select id="visType" style="width:165px;">
                                    <option value="outline">Neon Outline</option>
                                    <option value="boxes">Soft Gradient Box</option>
                                    <option value="arrow">Vector Arrow</option>
                                    <option value="nativeArrow">Chess.com Native Arrow</option>
                                </select>
                            </div>
                            <label class="switch-row">
                                <span>Show Best Line Arrows</span>
                                <input type="checkbox" id="chkPV" ${settings.showPVArrows ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <div class="row" id="rowDuration">
                                <label>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">
                                <span>Smooth Fade Out</span>
                                <input type="checkbox" id="chkFadeOut" ${settings.visualFadeOut ? "checked" : ""}>
                                <span class="switch-pill"></span>
                            </label>
                            <label class="switch-row">
                                <span>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">
                            <div class="sect-title">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>Hue</label><div class="slider-group"><input type="range" id="sliderH" min="0" max="360" value="${state.h}"></div></div>
                            <div class="row"><label>Saturation</label><div class="slider-group"><input type="range" id="sliderS" min="0" max="100" value="${state.s}"></div></div>
                            <div class="row"><label>Brightness</label><div class="slider-group"><input type="range" id="sliderL" min="0" max="100" value="${state.l}"></div></div>
                            <div class="row"><label>Hex Code</label><input type="text" id="inpHex" style="font-family:monospace; text-align:center; width:90px;"></div>
                        </div>

                        <div class="sect">
                            <div class="sect-title">Appearance</div>
                            <div class="row">
                                <label>Screen Anchor</label>
                                <select id="selMenuPos" style="width:155px;">
                                    <option value="custom">Custom (Draggable)</option>
                                    <option value="top-left">Top Left</option>
                                    <option value="top-right">Top Right</option>
                                    <option value="bottom-left">Bottom Left</option>
                                    <option value="bottom-right">Bottom Right</option>
                                </select>
                            </div>
                            <div class="row">
                                <label>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">
                                <label>Theme Presets</label>
                                <div style="display:flex; gap:8px;">
                                    <button id="btnThemeDark" class="btn-action-secondary" style="width:auto; padding:0 12px; height:28px;">Dark</button>
                                    <button id="btnThemeLight" class="btn-action-secondary" style="width:auto; padding:0 12px; height:28px;">Light</button>
                                </div>
                            </div>
                        </div>

                        <div class="sect">
                            <button id="btnReset" class="btn-action-secondary" style="color:#f85149 !important; border-color:rgba(248,81,73,0.3) !important;">Reset Settings</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>Local Engines</h3>
                        <button id="localModalClose" class="modal-close-btn">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="sect" style="border:none; padding:0;">
                            <div class="sect-title" style="display:flex; justify-content:space-between; align-items:center;">
                                <span>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>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;">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;">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" style="flex:1.4; height:32px; font-weight:600;">Install / Launch</button>
                                <button id="btnLocalReinstall" class="btn-action-secondary" style="flex:1; height:32px;">Re-download</button>
                                <button id="btnLocalUninstall" class="btn-action-secondary" 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">UCI Parameters &amp; Strength</div>
                            <div class="row" id="rowHash" title="Transposition table size in RAM. 64–128 MB is ideal for bullet/blitz.">
                                <label>Hash Memory (MB)</label>
                                <input type="number" id="localHashMB" min="1" max="2048" value="${settings.localHashMB}">
                            </div>
                            <div class="row" id="rowMoveOverhead" title="Lag safety buffer (ms) reserved for browser/network delay so you don't flag.">
                                <label>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;">
                                <div class="row">
                                    <label>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;">
                                <label class="switch-row">
                                    <span>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>Target Elo</label>
                                    <input type="number" id="localElo" min="1320" max="3190" value="${settings.localElo}">
                                </div>
                            </div>
                            <div class="row" title="Minimum think time per move in ms (set 0 for fastest bullet play).">
                                <label>Min Move Time (ms)</label>
                                <input type="number" id="localMinThinkingTime" min="0" max="5000" value="${settings.localMinThinkTime}">
                            </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 || "296px";
            panel.style.height = savedH || "auto";
        }

        state.ui = {
            panel: panel,
            header: shadow.getElementById("panelHeader"),
            minBtn: shadow.getElementById("minBtn"),
            moveResult: shadow.getElementById("moveResult"),
            liveOutput: shadow.getElementById("statusBox"),
            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"),
            clockDisplay: shadow.getElementById("clockDisplay"),
            rowDepth: shadow.getElementById("rowDepth"),
            chkRun: shadow.getElementById("chkRun"),
            chkMove: shadow.getElementById("chkMove"),
            chkHumanMode: shadow.getElementById("chkHumanMode"),
            rowHumanPreset: shadow.getElementById("rowHumanPreset"),
            selHumanPreset: shadow.getElementById("selHumanPreset"),
            chkEvalBar: shadow.getElementById("chkEvalBar"),
            chkPV: shadow.getElementById("chkPV"),
            chkQueue: shadow.getElementById("chkQueue"),
            rowMoveKeybind: shadow.getElementById("rowMoveKeybind"),
            btnMoveKeybind: shadow.getElementById("btnMoveKeybind"),
            inpMin: shadow.getElementById("inpMin"),
            inpMax: shadow.getElementById("inpMax"),
            btnReset: shadow.getElementById("btnReset"),
            lblMaxDepth: shadow.getElementById("lblMaxDepth"),
            btnVisuals: shadow.getElementById("btnVisuals"),
            localBtn: shadow.getElementById("localBtn"),
            modalOv: shadow.getElementById("modalOv"),
            modal: shadow.getElementById("modal"),
            modalClose: shadow.getElementById("modalClose"),
            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();
        applyTheme();

        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(); } };
        state.ui.modalClose.onclick = () => { if (state.ui.modalOv) state.ui.modalOv.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 toggleMin = () => {
            const isMini = state.ui.panel.classList.toggle("minified");
            saveSetting("isMini", isMini);
            if (!isMini && !state.ui.panel.style.width) {
                state.ui.panel.style.width = savedW;
                state.ui.panel.style.height = savedH;
            }
            state.ui.minBtn.innerHTML = isMini ? STOCKFISH_ICON : "▼";
        };
        state.ui.minBtn.onclick = (e) => { e.stopPropagation(); toggleMin(); };
        state.ui.panel.onclick = () => { if (state.ui.panel.classList.contains("minified")) toggleMin(); };
        if (isMini) state.ui.minBtn.innerHTML = STOCKFISH_ICON;

        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.max(0, 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) PV.update(state.currentPV);
                    else PV.clear();
                }
                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";
                saveSetting("pX", x); saveSetting("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")) {
                if (state.ui.panel.style.width) saveSetting("panelW", state.ui.panel.style.width);
                if (state.ui.panel.style.height) saveSetting("panelH", 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.chkRun, "autoRun", "chk");
        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.chkPV, "showPVArrows", "chk");
        bind(state.ui.chkQueue, "autoQueue", "chk");
        bind(state.ui.inpMin, "minDelay", "num");
        bind(state.ui.inpMax, "maxDelay", "num");
        state.ui.inpMin.addEventListener("input", updateCalculatedDelay);
        state.ui.inpMax.addEventListener("input", updateCalculatedDelay);
        updateCalculatedDelay();

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

        if (state.ui.btnMoveKeybind) {
            state.ui.btnMoveKeybind.onclick = (e) => {
                e.stopPropagation();
                state.ui.btnMoveKeybind.innerText = "Press key...";
                const keyHandler = (ev) => {
                    ev.preventDefault(); ev.stopPropagation();
                    document.removeEventListener("keydown", keyHandler, true);
                    let keyName = ev.key === " " ? "Space" : ev.key;
                    if (keyName === "Escape") settings.moveKeybind = "None";
                    else settings.moveKeybind = keyName;
                    saveSetting("moveKeybind", settings.moveKeybind);
                    state.ui.btnMoveKeybind.innerText = settings.moveKeybind;
                };
                document.addEventListener("keydown", keyHandler, true);
            };
        }

        [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("minified")) {
            const rect = state.ui.panel.getBoundingClientRect();
            if (rect.right > window.innerWidth + 1) state.ui.panel.style.width = Math.max(288, 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";
        }
        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("chkRun",       settings.autoRun);
        setChk("chkMove",      settings.autoMove);
        setChk("chkHumanMode", settings.humanMode);
        setVal("selHumanPreset", settings.humanPreset || "master");
        setChk("chkEvalBar",   settings.showEvalBar);
        setChk("chkPV",        settings.showPVArrows);
        setChk("chkQueue",     settings.autoQueue);
        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 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) + "%"; }

        // Move keybind button label
        const btnMK = g("btnMoveKeybind");
        if (btnMK) btnMK.innerText = settings.moveKeybind || "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 usingClock = (settings.engineMode === "local" && settings.autoTimeMgmt);
            if (state.ui.rowDepth) state.ui.rowDepth.style.display = usingClock ? "none" : "flex";
        }
        if (state.ui.rowAutoTime) {
            state.ui.rowAutoTime.style.display = settings.engineMode === "local" ? "flex" : "none";
        }
        if (state.ui.rowHumanPreset) {
            state.ui.rowHumanPreset.style.display = settings.humanMode ? "flex" : "none";
        }
        if (state.ui.clockDisplay) {
            const showClk = (settings.engineMode === "local" && 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 = state.board?.game || document.querySelector("chess-board, wc-chess-board")?.game;
                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;
            }
        }
        if (state.ui.moveResult && state.ui.moveResult.dataset.lastHtml !== state.lastMoveResult) {
            state.ui.moveResult.dataset.lastHtml = state.lastMoveResult;
            state.ui.moveResult.innerHTML = state.lastMoveResult;
        }
        if (state.ui.liveOutput && state.ui.liveOutput.dataset.lastHtml !== state.lastLiveResult) {
            state.ui.liveOutput.dataset.lastHtml = state.lastLiveResult;
            state.ui.liveOutput.innerHTML = state.lastLiveResult;
        }
        if (state.ui.delayDisplay) {
            const min = Math.max(0, parseFloat(settings.minDelay) || 0);
            const max = Math.max(min, parseFloat(settings.maxDelay) || 0);
            const isHumanLocal = (settings.humanMode && settings.engineMode === "local");
            const tagTxt = state.lastTelemetryTag ? ` [${state.lastTelemetryTag}]` : "";
            const txt = isHumanLocal
                ? `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 (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() {
        const customBoard = document.querySelector("chess-board, wc-chess-board");
        state.board = (customBoard && customBoard.game) ? customBoard : (document.querySelector(CONFIG.BOARD_SEL) || customBoard);
        const game = state.board?.game || customBoard?.game;

        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) {}
        }

        if (game && settings.autoRun) {
            const raw = getRawBoardFEN();
            if (raw) {
                const clean = sanitizeFEN(raw);
                if (!state.lastSeenFEN && clean.startsWith("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR")) {
                    state.uciHistory = [];
                    state.uciHistoryValid = true;
                    const initKey = (fenToBoard64(clean)?.join("") || "") + "|w";
                    state.posVisitCounts = { [initKey]: 1 };
                }
                if (state.lastSeenFEN && clean !== state.lastSeenFEN) {
                    const mvInfo = detectMoveBetweenFens(state.lastSeenFEN, clean);
                    const prevPartsMove = state.lastSeenFEN.split(" ");
                    const currPartsMove = clean.split(" ");
                    const moverJustMoved = prevPartsMove[1];
                    const myCharMove = (state.playingAs === 2) ? "b" : "w";

                    if (moverJustMoved === myCharMove && 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 {
                        state.oppLastTo = mvInfo.to;
                        state.oppLastUCI = mvInfo.uci;
                        state.oppLastWasCapture = !!mvInfo.wasCapture;
                        state.oppPrevBoard64 = fenToBoard64(state.lastSeenFEN);
                    }
                    if (settings.engineMode === "local" && settings.autoTimeMgmt) getClockTimesMs(game, clean);
                    Visuals.onMovePlayed();
                    PV.clear();

                    const prevParts = state.lastSeenFEN.split(" ");
                    const currParts = clean.split(" ");
                    const prevPly = ((parseInt(prevParts[5], 10) || 1) - 1) * 2 + (prevParts[1] === "b" ? 1 : 0);
                    const currPly = ((parseInt(currParts[5], 10) || 1) - 1) * 2 + (currParts[1] === "b" ? 1 : 0);
                    const nowMs = performance.now();
                    const myChar = (state.playingAs === 2) ? "b" : "w";

                    if (clean.startsWith("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR") || currPly < prevPly) {
                        Visuals.removeByType('bestmove');
                        Visuals.removeByType('analysis');
                        EvalBar.reset();
                        state.currentBestMove = null;
                        state.currentPV = [];
                        state.lastSanitizedBoardFEN = "";
                        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.uciHistory = [];
                        state.uciHistoryValid = true;
                        const initKey = (fenToBoard64(clean)?.join("") || "") + "|w";
                        state.posVisitCounts = { [initKey]: 1 };
                    } else {
                        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();
                        }
                        state.turnStartedAt = nowMs;
                        if (!state.posVisitCounts) state.posVisitCounts = {};
                        const pKey = (fenToBoard64(clean)?.join("") || clean.split(" ")[0]) + "|" + (clean.split(" ")[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.lastSeenFEN = clean;
                const isTurn = isUserTurn(game);
                if (isTurn && clean !== state.lastSanitizedBoardFEN) analyze(settings.depth);
            }
        }

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

        updateUI();
    }

    // --- GLOBAL KEYBIND LISTENER ---
    document.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            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 (settings.autoMove || !settings.moveKeybind || settings.moveKeybind === "None") return;
        if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA" || e.target.isContentEditable) return;
        const shadowEl = state.shadow?.activeElement;
        if (shadowEl && (shadowEl.tagName === "INPUT" || shadowEl.tagName === "TEXTAREA" || shadowEl.tagName === "SELECT")) return;
        let keyName = e.key === " " ? "Space" : e.key;
        if (keyName.toLowerCase() === settings.moveKeybind.toLowerCase()) {
            if (!state.board?.game || !state.currentBestMove) return;
            if (isUserTurn(state.board.game)) {
                e.preventDefault();
                playMove(state.currentBestMove);
            }
        }
    });

    loadSettings();
    toggleAutoQueue();
    setInterval(mainLoop, CONFIG.LOOP_MS);
    } // end mainInit

})();