☰

Sleazy Fork is available in English.

Best Cheat on Chess

The best chess cheat on Chess.com. Powered by Stockfish 18 — real-time best moves, Elo control, auto-move, random delay. Free key on Discord: discord.gg/9eSM5dhdnv. By Bayarsaikhan Enhtulga.

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

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

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

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

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

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name        Best Cheat on Chess
// @namespace   enhtulgaa
// @version     7.2
// @description The best chess cheat on Chess.com. Powered by Stockfish 18 — real-time best moves, Elo control, auto-move, random delay. Free key on Discord: discord.gg/9eSM5dhdnv. By Bayarsaikhan Enhtulga.
// @match       https://www.chess.com/play/*
// @match       https://www.chess.com/game/*
// @match       https://www.chess.com/analysis
// @match       https://www.chess.com/analysis/*
// @match       https://www.chess.com/puzzles/*
// @match       https://www.chess.com/daily
// @match       https://www.chess.com/live/game/*
// @match       https://www.chess.com/live/*
// @license     MIT
// @author      Bayarsaikhan Enhtulga
// @grant       GM_xmlhttpRequest
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       unsafeWindow
// @connect     unpkg.com
// @run-at      document-start
// ==/UserScript==

(function () {
    'use strict';

    // =========================================================
    //  KEY SYSTEM — SF18 Lite by Enhee Tulgaa
    //  DISCORD: https://discord.gg/9eSM5dhdnv
    //  1-day  : BC20261202-xxxxxxxxxxxxxxxx
    //  Lifetime: BCL-N-xxxxxxxxxxxxxxxx  (N = any number)
    //  Console : await generateKey("20261202")  → 1-day
    //            await generateKey(1)            → lifetime #1
    // =========================================================
    const _KEY_SECRET  = "sf18lite-enhtulgaa-2026";
    const _DISCORD_URL = "https://discord.gg/9eSM5dhdnv";

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

    async function generateKey(input) {
        const isLT = typeof input === "number" || (/^\d+$/.test(String(input)) && !String(input).includes("-"));
        const seed  = isLT ? `LIFETIME${parseInt(input,10)}` : String(input);
        const mac   = await _hmac(_KEY_SECRET, seed);
        const short = mac.replace(/[^a-zA-Z0-9]/g,"").slice(0,16).toLowerCase();
        if (isLT) return `BCL-${parseInt(input,10)}-${short}`;
        return `BC${input}-${short}`;
    }
    try { unsafeWindow.generateKey = generateKey; } catch(_) { try { window.generateKey = generateKey; } catch(__) {} }

    async function _validateKey(key) {
        if (!key || typeof key !== "string") return false;
        const lt = key.match(/^BCL-(\d+)-([a-z0-9]{16})$/);
        if (lt) {
            const mac   = await _hmac(_KEY_SECRET, `LIFETIME${lt[1]}`);
            const short = mac.replace(/[^a-zA-Z0-9]/g,"").slice(0,16).toLowerCase();
            return lt[2] === short;
        }
        const m = key.match(/^BC(\d{8})-([a-z0-9]{16})$/);
        if (!m) return false;
        const ds = m[1];
        const keyDate  = new Date(Date.UTC(+ds.slice(0,4), +ds.slice(4,6)-1, +ds.slice(6,8)));
        const now      = new Date();
        const today    = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
        if (keyDate.getTime() !== today.getTime()) return false;
        const exp = await generateKey(ds);
        return m[2] === exp.split("-")[1];
    }

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

    function _showKeyScreen(onUnlock) {
        const waitBody = (cb) => { if (document.body){cb();return;} const o=new MutationObserver(()=>{if(document.body){o.disconnect();cb();}}); o.observe(document.documentElement,{childList:true}); };
        waitBody(() => {
            const mount = document.createElement("div");
            mount.id = "sf18KeyMount";
            mount.style.cssText = "position:fixed;top:0;left:0;width:0;height:0;z-index:2147483647;";
            const sh = mount.attachShadow({ mode:"closed" });
            document.body.appendChild(mount);
            sh.innerHTML = `<style>
                :host{all:initial;}
                *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;}
                .ov{position:fixed;inset:0;background:rgba(0,0,0,0.90);display:flex;align-items:center;justify-content:center;z-index:2147483647;backdrop-filter:blur(12px);pointer-events:all;}
                .card{background:rgba(13,17,23,0.98);border:1px solid rgba(255,255,255,0.12);border-radius:18px;padding:36px 30px;width:min(380px,92vw);display:flex;flex-direction:column;gap:16px;box-shadow:0 28px 70px rgba(0,0,0,0.9);color:#f0f6fc;}
                .logo{text-align:center;font-size:24px;font-weight:900;letter-spacing:-0.5px;}
                .logo span{color:#27ae60;}
                .sub{text-align:center;font-size:12px;color:#8b949e;line-height:1.7;margin-top:-4px;}
                .sub a{color:#7289da;text-decoration:none;}
                .sub a:hover{text-decoration:underline;}
                input{width:100%;height:44px;padding:0 14px;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.14);border-radius:9px;color:#f0f6fc;font-size:13px;font-family:monospace;outline:none;transition:border-color 0.2s;}
                input:focus{border-color:rgba(39,174,96,0.6);}
                input.err{border-color:rgba(248,81,73,0.7);}
                .btn{width:100%;height:44px;border-radius:9px;font-size:13.5px;font-weight:700;cursor:pointer;border:none;transition:opacity 0.15s,transform 0.1s;}
                .btn:active{transform:scale(0.98);}
                .btn-primary{background:linear-gradient(135deg,#1e8449,#27ae60);color:#fff;}
                .btn-primary:hover{opacity:0.88;}
                .btn-discord{background:rgba(88,101,242,0.15);color:#7289da;border:1px solid rgba(114,137,218,0.35);font-size:12.5px;height:40px;}
                .btn-discord:hover{background:rgba(88,101,242,0.28);}
                .err-msg{font-size:11.5px;color:#f85149;text-align:center;min-height:16px;}
                .divider{border:none;border-top:1px solid rgba(255,255,255,0.08);margin:0;}
                .note{font-size:11px;color:#484f58;text-align:center;line-height:1.5;}
            </style>
            <div class="ov"><div class="card">
                <div class="logo">SF18 <span>Lite</span></div>
                <div class="sub">Enter your key to unlock.<br>Get a <strong style="color:#f0f6fc">free key</strong> on Discord:<br><a href="https://discord.gg/9eSM5dhdnv" target="_blank">discord.gg/9eSM5dhdnv</a></div>
                <input type="text" id="ki" placeholder="BCL-1-xxxxxxxxxxxxxxxx" autocomplete="off" spellcheck="false">
                <div class="err-msg" id="em"></div>
                <button class="btn btn-primary" id="ub">Unlock</button>
                <hr class="divider">
                <button class="btn btn-discord" id="db">🔗 Join Discord — get a free key</button>
                <div class="note">Unlocked once → opens automatically every visit.</div>
            </div></div>`;
            const inp=sh.getElementById("ki"), em=sh.getElementById("em"), ub=sh.getElementById("ub");
            sh.getElementById("db").onclick=()=>window.open(_DISCORD_URL,"_blank");
            const go=async()=>{
                const v=inp.value.trim();
                if(!v){em.textContent="Please enter a key.";inp.classList.add("err");return;}
                ub.textContent="Verifying..."; ub.disabled=true;
                if(await _validateKey(v)){_setKey(v);mount.remove();onUnlock();}
                else{em.textContent="Invalid or expired key.";inp.classList.add("err");ub.textContent="Unlock";ub.disabled=false;}
            };
            ub.onclick=go;
            inp.addEventListener("keydown",e=>{if(e.key==="Enter")go();});
            inp.oninput=()=>{inp.classList.remove("err");em.textContent="";};
        });
    }

    async function _runKeyGate(onUnlock) {
        const stored = _getKey();
        if (stored) { if (await _validateKey(stored)){onUnlock();return;} _clearKey(); }
        _showKeyScreen(onUnlock);
    }


    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  CONFIG
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    const STORAGE_KEY = 'chess_bot_v7_2';
    const ELO_MIN = 1350;
    const ELO_MAX = 2850;

    const ENGINE = {
        label: 'Stockfish 18 Lite',
        jsUrl: 'https://unpkg.com/[email protected]/src/stockfish-18-lite-single.js',
        wasmUrl: 'https://unpkg.com/[email protected]/src/stockfish-18-lite-single.wasm',
        cacheKeyJs: 'sf18lite_js',
        cacheKeyWasm: 'sf18lite_wasm',
    };

    const DEFAULTS = {
        hackEnabled: false,
        autoRun: true,
        autoMovePiece: false,
        humanDelay: true,
        delayMin: 0.5,
        delayMax: 2.5,
        uciElo: 2000,
        movetime: 2000,
        showPV: true,
        colors: {
            move1: 'rgba(235,97,80,0.7)',
            move2: 'rgba(255,165,0,0.6)',
            move3: 'rgba(255,255,0,0.5)',
        },
        highlightMs: 1400,
        showMove1: true,
        showMove2: true,
        showMove3: true,
        panicMode: false,
    };

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  STATE
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    let settings = Object.assign({}, DEFAULTS, loadSettings());
    settings.autoMovePiece = false;
    window.hackEnabled = settings.hackEnabled ? 1 : 0;

    let board = null;
    let engineWorker = null;
    let engineReady = false;
    let engineLoading = false;
    let candidateMoves = [];
    let isThinking = false;
    let lastFen = '';
    let updateBotRunning = false;

    // Canvas
    let botCanvas = null;
    let botCanvasCtx = null;
    let pendingArrows = [];
    let rafId = null;

    // Cached board geometry (avoid getBoundingClientRect per frame)
    let cachedBoardRect = null;
    let cachedFlipped = false;
    let cachedSquareSize = 0;

    // Object pool for highlight overlays
    const hlPool = [];
    const hlActive = [];

    // Debounced save
    let saveTimer = null;

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  UTILITIES
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function debounce(fn, wait) {
        let t;
        return function (...a) { clearTimeout(t); t = setTimeout(() => fn.apply(this, a), wait); };
    }

    function throttle(fn, limit) {
        let last = 0;
        return function (...a) {
            const now = Date.now();
            if (now - last >= limit) { last = now; fn.apply(this, a); }
        };
    }

    function scheduleSave() {
        clearTimeout(saveTimer);
        saveTimer = setTimeout(() => {
            try { GM_setValue(STORAGE_KEY, JSON.stringify(settings)); } catch (e) {}
        }, 300);
    }

    function findBoard() {
        return document.querySelector('chess-board') ||
               document.querySelector('wc-chess-board') ||
               document.querySelector('[data-cy="board"]') || null;
    }

    function updateBoardReference() {
        let b = findBoard();
        if (b && !b.game && window.unsafeWindow) {
            const ub = unsafeWindow.document.querySelector('wc-chess-board') ||
                       unsafeWindow.document.querySelector('chess-board');
            if (ub && ub.game) b = ub;
        }
        if (b && b !== board) {
            board = b;
            invalidateBoardCache();
            if (window.hackEnabled) ensureCanvas();
        }
    }

    function invalidateBoardCache() {
        cachedBoardRect = null;
        cachedFlipped = false;
        cachedSquareSize = 0;
    }

    function refreshBoardCache() {
        if (!board) return;
        cachedBoardRect = board.getBoundingClientRect();
        cachedFlipped = board.classList.contains('flipped');
        cachedSquareSize = cachedBoardRect.width / 8;
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  PERSISTENCE
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function loadSettings() {
        try {
            const raw = GM_getValue(STORAGE_KEY, null);
            return raw ? JSON.parse(raw) : {};
        } catch (e) { return {}; }
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  FEN VALIDATION (Single-pass optimized)
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function cleanAndValidateFen(fen) {
        if (!fen) return null;
        const clean = fen.replace(/\{[^}]*\}|\$\d+/g, '').trim();
        const seg = clean.split(/\s+/);
        if (!seg[0]) return null;

        const ranks = seg[0].split('/');
        if (ranks.length !== 8) return null;

        // Single-pass: expand + validate + count kings
        let wk = 0, bk = 0;
        const flatBoard = [];
        for (let r = 0; r < 8; r++) {
            const row = [];
            const rank = ranks[r];
            for (let i = 0, len = rank.length; i < len; i++) {
                const ch = rank[i];
                if (ch >= '1' && ch <= '8') {
                    const n = ch | 0;
                    for (let j = 0; j < n; j++) row.push('.');
                } else {
                    row.push(ch);
                    if (ch === 'K') wk++;
                    else if (ch === 'k') bk++;
                }
            }
            if (row.length !== 8) return null;
            flatBoard.push(row);
        }
        if (wk !== 1 || bk !== 1) return null;

        const active = (seg[1] === 'w' || seg[1] === 'b') ? seg[1] : 'w';

        let castling = seg[2] || '-';
        let vc = '';
        if (castling !== '-') {
            const r7 = flatBoard[7], r0 = flatBoard[0];
            if (r7[4] === 'K') {
                if (castling.indexOf('K') >= 0 && r7[7] === 'R') vc += 'K';
                if (castling.indexOf('Q') >= 0 && r7[0] === 'R') vc += 'Q';
            }
            if (r0[4] === 'k') {
                if (castling.indexOf('k') >= 0 && r0[7] === 'r') vc += 'k';
                if (castling.indexOf('q') >= 0 && r0[0] === 'r') vc += 'q';
            }
        }

        let ep = '-';
        const rawEp = seg[3];
        if (rawEp && rawEp.length === 2 && rawEp[0] >= 'a' && rawEp[0] <= 'h') {
            const fi = rawEp.charCodeAt(0) - 97;
            if (rawEp[1] === '6' && active === 'b' && flatBoard[4][fi] === 'P') ep = rawEp;
            else if (rawEp[1] === '3' && active === 'w' && flatBoard[3][fi] === 'p') ep = rawEp;
        }

        const hm = /^\d+$/.test(seg[4]) ? seg[4] : '0';
        const fm = /^[1-9]\d*$/.test(seg[5]) ? seg[5] : '1';

        return seg[0] + ' ' + active + ' ' + (vc || '-') + ' ' + ep + ' ' + hm + ' ' + fm;
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  IndexedDB CACHE
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function openCache(cb) {
        const req = indexedDB.open('sfEngineCache_v7', 1);
        req.onupgradeneeded = (e) => {
            if (!e.target.result.objectStoreNames.contains('engines'))
                e.target.result.createObjectStore('engines');
        };
        req.onsuccess = (e) => cb(null, e.target.result);
        req.onerror = () => cb(new Error('IDB fail'), null);
    }

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

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

    function xhrText(url, cb, err) {
        GM_xmlhttpRequest({
            method: 'GET', url, timeout: 30000,
            onload: (r) => r.status >= 400 ? err(new Error('HTTP ' + r.status)) : cb(r.responseText),
            onerror: () => err(new Error('Net: ' + url)),
            ontimeout: () => err(new Error('Timeout')),
        });
    }

    function xhrBinary(url, cb, err) {
        GM_xmlhttpRequest({
            method: 'GET', url, responseType: 'arraybuffer', timeout: 60000,
            onload: (r) => r.status >= 400 ? err(new Error('HTTP ' + r.status)) : cb(new Uint8Array(r.response)),
            onerror: () => err(new Error('Bin fail')),
            ontimeout: () => err(new Error('Bin timeout')),
        });
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  ENGINE BUILDER
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function buildWasmWorker(jsCode, wasmBytes) {
        let bin = '';
        const len = wasmBytes.length;
        for (let i = 0; i < len; i += 8192) {
            bin += String.fromCharCode.apply(null, wasmBytes.subarray(i, Math.min(i + 8192, len)));
        }
        const b64 = btoa(bin);
        const patch =
            'var _wB="' + b64 + '";' +
            'var _wA=(function(){var b=atob(_wB),a=new Uint8Array(b.length);for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);return a;})();' +
            'self.fetch=function(){return Promise.resolve({ok:true,status:200,arrayBuffer:function(){return Promise.resolve(_wA.buffer);},text:function(){return Promise.resolve("");}});};';
        return new Worker(URL.createObjectURL(new Blob([patch + jsCode], { type: 'application/javascript' })));
    }

    function createStockfishWorker() {
        if (engineWorker || engineLoading) return;
        engineLoading = true;
        engineReady = false;

        openCache((_, db) => {
            const launch = (js, wasm) => {
                try {
                    if (engineWorker) engineWorker.terminate();
                    engineWorker = buildWasmWorker(js, wasm);
                    engineWorker.onerror = () => { engineLoading = false; engineWorker = null; };
                    engineWorker.onmessage = (e) => {
                        const msg = typeof e.data === 'string' ? e.data : String(e.data);
                        if (msg.length < 5) return; // skip empty/trivial messages

                        if (msg.charCodeAt(0) === 117 && msg.indexOf('uciok') === 0) {
                            engineWorker.postMessage('setoption name MultiPV value 1');
                            engineWorker.postMessage('setoption name Move Overhead value 100');
                            engineWorker.postMessage('isready');
                        } else if (msg.indexOf('readyok') === 0) {
                            engineReady = true;
                            engineLoading = false;
                            applyElo();
                        } else if (msg.charCodeAt(0) === 105 || msg.charCodeAt(0) === 98) {
                            // 'i' for info, 'b' for bestmove — skip everything else
                            handleEngineMessage(msg);
                        }
                    };
                    engineWorker.postMessage('uci');
                } catch (e) { engineLoading = false; engineWorker = null; }
            };

            const getJs = (cb) => {
                if (db) {
                    readCache(db, ENGINE.cacheKeyJs, (_, c) => {
                        if (c) return cb(c);
                        xhrText(ENGINE.jsUrl, (j) => { writeCache(db, ENGINE.cacheKeyJs, j); cb(j); }, () => { engineLoading = false; });
                    });
                } else {
                    xhrText(ENGINE.jsUrl, cb, () => { engineLoading = false; });
                }
            };

            const getWasm = (js, cb) => {
                if (db) {
                    readCache(db, ENGINE.cacheKeyWasm, (_, c) => {
                        if (c) return cb(js, c);
                        xhrBinary(ENGINE.wasmUrl, (b) => { writeCache(db, ENGINE.cacheKeyWasm, b); cb(js, b); }, () => { engineLoading = false; });
                    });
                } else {
                    xhrBinary(ENGINE.wasmUrl, (b) => cb(js, b), () => { engineLoading = false; });
                }
            };

            getJs((js) => { if (js) getWasm(js, launch); });
        });
    }

    function applyElo() {
        if (!engineWorker) return;
        // Always limit strength
        engineWorker.postMessage('setoption name UCI_LimitStrength value true');
        engineWorker.postMessage('setoption name UCI_Elo value ' + settings.uciElo);
    }

    function safeRestartEngine() {
        isThinking = false;
        engineReady = false;
        if (engineWorker) engineWorker.terminate();
        engineWorker = null;
        engineLoading = false;
        createStockfishWorker();
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  CANVAS — rAF batched, cached geometry
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function ensureCanvas() {
        updateBoardReference();
        if (!board || !window.hackEnabled) return;
        if (botCanvas) { botCanvas.remove(); botCanvas = null; botCanvasCtx = null; }

        botCanvas = document.createElement('canvas');
        botCanvas.id = 'botCanvas';
        botCanvas.style.cssText = 'position:absolute;top:0;left:0;pointer-events:none;z-index:50;contain:strict;';
        refreshBoardCache();
        botCanvas.width = cachedBoardRect.width;
        botCanvas.height = cachedBoardRect.height;
        board.appendChild(botCanvas);
        botCanvasCtx = botCanvas.getContext('2d');
    }

    function clearVisuals() {
        pendingArrows.length = 0;
        if (botCanvasCtx) botCanvasCtx.clearRect(0, 0, botCanvas.width, botCanvas.height);
        if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
        releaseHighlights();
    }

    function renderArrows() {
        rafId = null;
        if (!botCanvasCtx || !board) return;

        refreshBoardCache();
        const sz = cachedSquareSize;
        const fl = cachedFlipped;
        const ctx = botCanvasCtx;

        ctx.clearRect(0, 0, botCanvas.width, botCanvas.height);

        for (let i = 0, len = pendingArrows.length; i < len; i++) {
            const a = pendingArrows[i];
            const ff = a.from.charCodeAt(0) - 97;
            const fr = (a.from.charCodeAt(1) - 49); // '1' = 0
            const tf = a.to.charCodeAt(0) - 97;
            const tr = (a.to.charCodeAt(1) - 49);

            const fx = (fl ? 7 - ff : ff) * sz + sz * 0.5;
            const fy = (fl ? fr : 7 - fr) * sz + sz * 0.5;
            const tx = (fl ? 7 - tf : tf) * sz + sz * 0.5;
            const ty = (fl ? tr : 7 - tr) * sz + sz * 0.5;

            ctx.strokeStyle = a.color;
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.moveTo(fx, fy);
            ctx.lineTo(tx, ty);
            ctx.stroke();

            const ang = Math.atan2(ty - fy, tx - fx);
            const c1 = Math.cos(ang - 0.5236), s1 = Math.sin(ang - 0.5236); // PI/6
            const c2 = Math.cos(ang + 0.5236), s2 = Math.sin(ang + 0.5236);
            ctx.beginPath();
            ctx.moveTo(tx, ty);
            ctx.lineTo(tx - 15 * c1, ty - 15 * s1);
            ctx.moveTo(tx, ty);
            ctx.lineTo(tx - 15 * c2, ty - 15 * s2);
            ctx.stroke();
        }
    }

    function scheduleRender() {
        if (!rafId) rafId = requestAnimationFrame(renderArrows);
    }

    function updateVisuals() {
        if (!window.hackEnabled || !botCanvasCtx || settings.panicMode) return;
        pendingArrows.length = 0;

        const colors = [settings.colors.move1, settings.colors.move2, settings.colors.move3];
        const flags = [settings.showMove1, settings.showMove2, settings.showMove3];

        for (let i = 0; i < candidateMoves.length && i < 3; i++) {
            if (flags[i]) {
                pendingArrows.push({
                    from: candidateMoves[i].move.slice(0, 2),
                    to: candidateMoves[i].move.slice(2, 4),
                    color: colors[i],
                });
            }
        }
        scheduleRender();
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  HIGHLIGHT OBJECT POOL
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function getHighlight() {
        if (hlPool.length > 0) {
            const el = hlPool.pop();
            el.style.display = '';
            return el;
        }
        const el = document.createElement('div');
        el.className = 'botHL';
        el.style.cssText = 'position:absolute;inset:0;pointer-events:none;z-index:60;contain:strict;';
        return el;
    }

    function releaseHighlights() {
        for (let i = hlActive.length - 1; i >= 0; i--) {
            const item = hlActive[i];
            clearTimeout(item.timer);
            item.el.style.display = 'none';
            hlPool.push(item.el);
        }
        hlActive.length = 0;
    }

    function placeHighlight(sq, color) {
        if (!board) return;
        const el = board.querySelector('[data-square="' + sq + '"]');
        if (!el) return;

        const ov = getHighlight();
        ov.style.backgroundColor = color;
        el.appendChild(ov);

        const entry = {
            el: ov,
            timer: setTimeout(() => {
                const idx = hlActive.indexOf(entry);
                if (idx >= 0) hlActive.splice(idx, 1);
                ov.style.display = 'none';
                hlPool.push(ov);
            }, settings.highlightMs),
        };
        hlActive.push(entry);
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  ENGINE MESSAGE PARSING (Early-exit optimized)
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function handleEngineMessage(msg) {
        // Fast path: only process 'info' and 'bestmove'
        if (msg.indexOf('info') === 0) {
            if (msg.indexOf(' pv ') === -1) return;
            const pvIdx = msg.indexOf(' pv ') + 4;
            const pvStr = msg.slice(pvIdx);
            const pvTokens = pvStr.trim().split(/\s+/);
            if (!pvTokens.length) return;

            const move = pvTokens[0];
            const scoreIdx = msg.indexOf('score ');
            if (scoreIdx === -1) return;

            const afterScore = msg.slice(scoreIdx + 6);
            const isMate = afterScore.charCodeAt(0) === 109; // 'm'
            const valStr = afterScore.match(/(-?\d+)/);
            if (!valStr) return;

            const val = parseInt(valStr[1], 10);
            let rawCp = null, rawMate = null, score = 0;

            if (isMate) {
                rawMate = val;
                score = val > 0 ? 100000 - val : -100000 - val;
            } else {
                rawCp = val;
                score = val;
            }

            const depthIdx = msg.indexOf('depth ');
            let depth = 0;
            if (depthIdx >= 0) {
                const dm = msg.slice(depthIdx + 6).match(/^(\d+)/);
                if (dm) depth = parseInt(dm[1], 10);
            }

            // Update or insert candidate
            let found = false;
            for (let i = 0; i < candidateMoves.length; i++) {
                if (candidateMoves[i].move === move) {
                    if (depth > candidateMoves[i].depth) {
                        candidateMoves[i].score = score;
                        candidateMoves[i].depth = depth;
                        candidateMoves[i].pv = pvTokens;
                        candidateMoves[i].rawCp = rawCp;
                        candidateMoves[i].rawMate = rawMate;
                    }
                    found = true;
                    break;
                }
            }
            if (!found) {
                candidateMoves.push({ move, score, depth, pv: pvTokens, rawCp, rawMate });
            }

        } else if (msg.indexOf('bestmove') === 0) {
            candidateMoves.sort((a, b) => b.score - a.score);
            if (candidateMoves.length > 3) candidateMoves.length = 3;

            updateVisuals();
            showTopMoves();

            const parts = msg.split(' ');
            const bestMove = parts[1];
            if (settings.autoMovePiece && bestMove && bestMove !== '(none)') {
                performMove(bestMove);
            }
            isThinking = false;
        }
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  BOARD SQUARE MAPPING (Cached)
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    const sqCache = new Map();

    function mapSquare(sq) {
        if (!cachedFlipped) return sq;
        let r = sqCache.get(sq);
        if (r !== undefined) return r;
        r = String.fromCharCode(104 - (sq.charCodeAt(0) - 97)) + (9 - (sq.charCodeAt(1) - 48));
        sqCache.set(sq, r);
        return r;
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  SHOW TOP MOVES + PV NOTES
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function showTopMoves() {
        updateBoardReference();
        if (!board || !board.game || !window.hackEnabled || settings.panicMode) return;

        releaseHighlights();
        refreshBoardCache();

        const flags = [settings.showMove1, settings.showMove2, settings.showMove3];
        const colors = [settings.colors.move1, settings.colors.move2, settings.colors.move3];

        for (let i = 0; i < candidateMoves.length && i < 3; i++) {
            if (!flags[i]) continue;
            const cm = candidateMoves[i];
            const from = mapSquare(cm.move.slice(0, 2));
            const to = mapSquare(cm.move.slice(2, 4));
            placeHighlight(from, colors[i]);
            placeHighlight(to, colors[i]);

            if (settings.showPV && cm.pv && cm.pv.length) {
                addPVNote(cm, i);
            }
        }
    }

    function addPVNote(cm, idx) {
        const id = 'pvN' + idx;
        let note = document.getElementById(id);
        if (!note) {
            note = document.createElement('div');
            note.id = id;
            note.style.cssText = 'position:absolute;right:6px;top:' + (6 + idx * 26) + 'px;padding:4px 6px;background:#333;color:#eee;z-index:120;font-size:11px;border:1px solid #555;';
            board.parentElement.appendChild(note);
        }
        const sc = cm.rawMate != null
            ? (cm.rawMate > 0 ? 'M+' + cm.rawMate : 'M' + cm.rawMate)
            : ((cm.rawCp != null ? cm.rawCp : cm.score) / 100).toFixed(2);
        note.textContent = '#' + (idx + 1) + ' ' + cm.move + ' (' + sc + ') ' + cm.pv.slice(0, 5).join(' ');
        setTimeout(() => { if (note && note.parentElement) note.parentElement.removeChild(note); }, settings.highlightMs + 5000);
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  MOVE EXECUTION
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function performMove(uci) {
        updateBoardReference();
        if (!board || !board.game || !window.hackEnabled) return;

        const from = uci.slice(0, 2);
        const to = uci.slice(2, 4);
        const promo = uci.length > 4 ? uci[4] : null;
        const legal = board.game.getLegalMoves();

        for (let i = 0, len = legal.length; i < len; i++) {
            const m = legal[i];
            if (m.from === from && m.to === to) {
                if (m.promotion && promo) m.promotion = promo;
                else if (m.promotion) m.promotion = 'q';
                board.game.move(Object.assign({}, m, { animate: false, userGenerated: true }));
                return;
            }
        }
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  ENGINE RUNNER — UCI_Elo + movetime
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function runChessEngine() {
        updateBoardReference();
        if (!board || !engineWorker || !engineReady || !board.game || !window.hackEnabled || settings.panicMode) return;

        try {
            const rawFen = board.game.getFEN();
            const fen = cleanAndValidateFen(rawFen) || rawFen;
            if (isThinking && fen === lastFen) return;

            lastFen = fen;
            candidateMoves.length = 0;
            isThinking = true;

            applyElo();
            engineWorker.postMessage('position fen ' + fen);
            engineWorker.postMessage('go movetime ' + settings.movetime);
        } catch (e) {}
    }

    const debouncedRun = debounce(runChessEngine, 300);

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  SINGLE CONSOLIDATED LOOP
    //  (replaces separate setInterval timers)
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    let lastMoveCount = -1;
    let loopTick = 0;

    function mainLoop() {
        if (!updateBotRunning) return;
        loopTick++;

        try {
            updateBoardReference();
            if (!board || !board.game || !window.hackEnabled || settings.panicMode) {
                setTimeout(mainLoop, 500);
                return;
            }

            // Every tick (500ms): check turn + auto-run
            const isMyTurn = board.game.getTurn() === board.game.getPlayingAs();
            if (isMyTurn && !isThinking && settings.autoRun) {
                const delay = settings.humanDelay
                    ? (Math.random() * (settings.delayMax - settings.delayMin) + settings.delayMin) * 1000
                    : 0;
                setTimeout(debouncedRun, Math.max(0, delay));
            }

            // Every 2nd tick (~1s): check for new moves
            if (loopTick % 2 === 0) {
                const moves = board.game.getMoveHistory
                    ? board.game.getMoveHistory().length
                    : (board.game.history ? board.game.history.length : 0);

                if (lastMoveCount === -1) lastMoveCount = moves;
                else if (moves !== lastMoveCount) {
                    lastMoveCount = moves;
                    if (settings.autoRun) debouncedRun();
                }
            }

            // Every 4th tick (~2s): check canvas size
            if (loopTick % 4 === 0 && botCanvas && board) {
                const r = board.getBoundingClientRect();
                if (botCanvas.width !== r.width || botCanvas.height !== r.height) {
                    ensureCanvas();
                }
            }
        } catch (e) {}

        setTimeout(mainLoop, 500);
    }

    function startBotLoop() {
        if (updateBotRunning) return;
        updateBotRunning = true;
        loopTick = 0;
        mainLoop();
    }

    function stopBotLoop() {
        updateBotRunning = false;
        isThinking = false;
        clearVisuals();
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  GUI — FLAT DESIGN (No eval bar, no manual, no threats)
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function initGUI() {
        updateBoardReference();
        if (!board || document.getElementById('botGUI_v7')) return true;

        const w = document.createElement('div');
        w.id = 'botGUI_v7';

        Object.assign(w.style, {
            position: 'fixed', top: '20px', right: '20px', zIndex: '999999',
            width: '290px', fontFamily: 'system-ui,sans-serif', fontSize: '13px',
            background: '#1e1e1e', color: '#ddd', border: '1px solid #444',
            boxShadow: '0 4px 12px rgba(0,0,0,0.4)',
        });

        w.innerHTML =
            '<div id="guiHdr" style="padding:8px 10px;background:#2a2a2a;cursor:move;border-bottom:1px solid #444;display:flex;justify-content:space-between;align-items:center;">' +
                '<b style="color:#fff;">♟ Best Cheat on Chess</b>' +
                '<div style="display:flex;align-items:center;gap:6px;">' +
                    '<button id="btnDiscordSF" style="padding:0 8px;height:22px;font-size:10px;font-weight:700;background:rgba(114,137,218,0.2);color:#7289da;border:1px solid rgba(114,137,218,0.4);border-radius:4px;cursor:pointer;">Discord</button>' +
                    '<span style="color:#888;font-size:11px;">drag</span>' +
                '</div>' +
            '</div>' +
            '<div style="padding:10px;">' +
                '<label style="display:block;margin-bottom:8px;">' +
                    '<input type="checkbox" id="cbEnable"' + (window.hackEnabled ? ' checked' : '') + '> ' +
                    '<b style="color:#e74c3c;">Enable Bot</b>' +
                '</label>' +

                '<div style="margin-bottom:10px;padding:8px;background:#252525;border:1px solid #3a3a3a;">' +
                    '<label style="display:block;font-weight:600;margin-bottom:4px;">Strength (Elo)</label>' +
                    '<div style="display:flex;align-items:center;gap:6px;">' +
                        '<input id="inElo" type="range" min="' + ELO_MIN + '" max="' + ELO_MAX + '" step="50" value="' + settings.uciElo + '" style="flex:1;">' +
                        '<input id="inEloNum" type="number" min="' + ELO_MIN + '" max="' + ELO_MAX + '" value="' + settings.uciElo + '" style="width:60px;background:#333;color:#fff;border:1px solid #555;padding:2px 4px;">' +
                    '</div>' +
                '</div>' +

                '<div style="margin-bottom:10px;">' +
                    '<label style="display:block;margin-bottom:2px;">Think time (ms)</label>' +
                    '<input id="inTime" type="number" min="100" max="30000" step="100" value="' + settings.movetime + '" style="width:100%;background:#333;color:#fff;border:1px solid #555;padding:4px;box-sizing:border-box;">' +
                '</div>' +

                '<div style="margin-bottom:10px;padding:8px;background:#252525;border:1px solid #3a3a3a;">' +
                    '<div style="font-weight:600;margin-bottom:4px;">Delay</div>' +
                    '<label style="font-size:12px;"><input type="checkbox" id="cbDelay"' + (settings.humanDelay ? ' checked' : '') + '> Random delay</label>' +
                    '<div style="display:flex;gap:6px;margin-top:4px;">' +
                        '<label style="font-size:11px;">Min: <input id="inDMin" type="number" step="0.1" value="' + settings.delayMin + '" style="width:45px;background:#333;color:#fff;border:1px solid #555;padding:1px 3px;"></label>' +
                        '<label style="font-size:11px;">Max: <input id="inDMax" type="number" step="0.1" value="' + settings.delayMax + '" style="width:45px;background:#333;color:#fff;border:1px solid #555;padding:1px 3px;"></label>' +
                    '</div>' +
                '</div>' +

                '<div style="margin-bottom:8px;">' +
                    '<label><input type="checkbox" id="cbAuto"' + (settings.autoRun ? ' checked' : '') + '> Auto run</label>' +
                    '<label style="margin-left:8px;"><input type="checkbox" id="cbMove"' + (settings.autoMovePiece ? ' checked' : '') + '> Auto move</label>' +
                '</div>' +

                '<div style="margin-bottom:10px;padding:8px;background:#252525;border:1px solid #3a3a3a;">' +
                    '<div style="font-weight:600;margin-bottom:4px;">Show</div>' +
                    '<div style="display:grid;grid-template-columns:1fr 1fr;gap:2px;font-size:12px;">' +
                        '<label><input type="checkbox" id="cbM1"' + (settings.showMove1 ? ' checked' : '') + '> Move 1</label>' +
                        '<label><input type="checkbox" id="cbM2"' + (settings.showMove2 ? ' checked' : '') + '> Move 2</label>' +
                        '<label><input type="checkbox" id="cbM3"' + (settings.showMove3 ? ' checked' : '') + '> Move 3</label>' +
                        '<label><input type="checkbox" id="cbPV"' + (settings.showPV ? ' checked' : '') + '> PV lines</label>' +
                    '</div>' +
                    '<div style="margin-top:4px;font-size:10px;color:#888;">Alt+Q: panic · Alt+A: analyse</div>' +
                '</div>' +

                '<div style="display:flex;gap:6px;">' +
                    '<button id="btnReload" style="flex:1;padding:6px;background:#444;color:#fff;border:1px solid #666;cursor:pointer;">Reload</button>' +
                    '<button id="btnGo" style="flex:1;padding:6px;background:#27ae60;color:#fff;border:none;cursor:pointer;font-weight:600;">Analyse</button>' +
                '</div>' +
            '</div>';

        document.body.appendChild(w);

        // Drag
        const _dSF = document.getElementById('btnDiscordSF');
        if (_dSF) _dSF.onclick = (e) => { e.stopPropagation(); window.open(_DISCORD_URL, '_blank'); };

        const hdr = document.getElementById('guiHdr');
        let drag = false, ox = 0, oy = 0;
        hdr.addEventListener('mousedown', (e) => {
            drag = true;
            const r = w.getBoundingClientRect();
            ox = e.clientX - r.left;
            oy = e.clientY - r.top;
        }, { passive: true });

        document.addEventListener('mouseup', () => { drag = false; }, { passive: true });
        document.addEventListener('mousemove', (e) => {
            if (!drag) return;
            w.style.left = (e.clientX - ox) + 'px';
            w.style.top = (e.clientY - oy) + 'px';
            w.style.right = 'auto';
        }, { passive: true });

        // Events
        const $ = (id) => document.getElementById(id);

        $('cbEnable').onchange = (e) => {
            window.hackEnabled = e.target.checked ? 1 : 0;
            settings.hackEnabled = e.target.checked;
            scheduleSave();
            if (e.target.checked) { ensureCanvas(); startBotLoop(); }
            else { stopBotLoop(); }
        };

        const syncElo = (v) => {
            v = Math.max(ELO_MIN, Math.min(ELO_MAX, parseInt(v, 10) || ELO_MIN));
            settings.uciElo = v;
            $('inElo').value = v;
            $('inEloNum').value = v;
            scheduleSave();
            if (engineReady) applyElo();
        };
        $('inElo').oninput = (e) => syncElo(e.target.value);
        $('inEloNum').onchange = (e) => syncElo(e.target.value);
        $('inTime').onchange = (e) => { settings.movetime = Math.max(100, parseInt(e.target.value, 10) || 2000); scheduleSave(); };
        $('cbDelay').onchange = (e) => { settings.humanDelay = e.target.checked; scheduleSave(); };

        $('inDMin').onchange = (e) => {
            settings.delayMin = parseFloat(e.target.value) || 0;
            if (settings.delayMin > settings.delayMax) { settings.delayMax = settings.delayMin; $('inDMax').value = settings.delayMax; }
            scheduleSave();
        };
        $('inDMax').onchange = (e) => {
            settings.delayMax = parseFloat(e.target.value) || 0;
            if (settings.delayMax < settings.delayMin) { settings.delayMin = settings.delayMax; $('inDMin').value = settings.delayMin; }
            scheduleSave();
        };

        $('cbAuto').onchange = (e) => { settings.autoRun = e.target.checked; scheduleSave(); };
        $('cbMove').onchange = (e) => { settings.autoMovePiece = e.target.checked; scheduleSave(); };
        $('cbM1').onchange = (e) => { settings.showMove1 = e.target.checked; scheduleSave(); updateVisuals(); showTopMoves(); };
        $('cbM2').onchange = (e) => { settings.showMove2 = e.target.checked; scheduleSave(); updateVisuals(); showTopMoves(); };
        $('cbM3').onchange = (e) => { settings.showMove3 = e.target.checked; scheduleSave(); updateVisuals(); showTopMoves(); };
        $('cbPV').onchange = (e) => { settings.showPV = e.target.checked; scheduleSave(); };

        $('btnReload').onclick = safeRestartEngine;
        $('btnGo').onclick = () => { if (window.hackEnabled) debouncedRun(); };

        if (window.hackEnabled) { ensureCanvas(); startBotLoop(); }
        return true;
    }

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  HOTKEYS (Passive listener)
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function togglePanic() {
        settings.panicMode = !settings.panicMode;
        scheduleSave();
        const w = document.getElementById('botGUI_v7');

        if (settings.panicMode) {
            if (w) w.style.display = 'none';
            clearVisuals();
            document.querySelectorAll('[id^="pvN"]').forEach((n) => n.remove());
        } else {
            if (w) w.style.display = 'block';
            updateVisuals();
            showTopMoves();
        }
    }

    document.addEventListener('keydown', (e) => {
        if (!e.altKey) return;
        if (e.code === 'KeyQ') { e.preventDefault(); togglePanic(); }
        else if (e.code === 'KeyA') {
            e.preventDefault();
            if (!settings.panicMode && window.hackEnabled && board && board.game) debouncedRun();
        }
    }, { passive: false });

    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    //  INIT
    // 8XkABnXEYCgUBFAN2oyjC9M4uF1JqisFK9Sf8JpN4Cdr
    function waitUntil(fn, ms) {
        return new Promise((res) => {
            const t = setInterval(() => { try { if (fn()) { clearInterval(t); res(); } } catch (e) {} }, ms || 100);
        });
    }

    _runKeyGate(async function() {
        await waitUntil(findBoard);
        updateBoardReference();
        await waitUntil(() => { board = findBoard(); return board && board.game; });

        createStockfishWorker();
        initGUI();

        if (window.hackEnabled) startBotLoop();
    });
})();