Wolf_ Tools 3.0

Script for smoother gameplay on Kour.io

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

You will need to install an extension such as Tampermonkey or Violentmonkey to install this 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         Wolf_ Tools 3.0
// @namespace    http://tampermonkey.net/
// @version      3.0
// @description  Script for smoother gameplay on Kour.io
// @author       Wolf_
// @match        *://kour.io/*
// @grant        none
// @inject-into  page
// @run-at       document-start
// ==/UserScript==
(function () {
    'use strict';
    if (document.getElementById('wolf-menu')) return;
    const realWindow = (typeof unsafeWindow !== 'undefined' && unsafeWindow) ? unsafeWindow : window;

    // =========================
    // MENU INPUT GUARD
    // =========================

    function wolfInputGuard(e) {
        const t = e.target;
        if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA') && t.closest && t.closest('#wolf-menu')) {
            e.stopImmediatePropagation();
        }
    }

    ['keydown','keyup','keypress'].forEach(ev => {
        window.addEventListener(ev, wolfInputGuard, true);
    });
    // =========================
    // STORAGE HELPERS
    // =========================
    const getStored = (key, def) => {
        const v = localStorage.getItem(key);
        return v === null ? def : v;
    };
    let savedTop  = getStored('wolf_top',  '20px');
    let savedLeft = getStored('wolf_left', '20px');
    let states = {
        arms:            getStored('wolf_hide_arms','false') === 'true',
        weapon:          getStored('wolf_hide_weapon','false') === 'true',
        crossVisible:    getStored('wolf_cross_visible','true')  === 'true',
        glow:            getStored('wolf_glow','true')  === 'true',
        customCross:     getStored('wolf_custom_cross','myrrr'),
        crossColor:      getStored('wolf_cross_color','#ffffff'),
        crossScale:      getStored('wolf_cross_scale','1.0'),
        hideGameCross:   getStored('wolf_hide_game_cross','false') === 'true',
        crossTransparent:getStored('wolf_cross_transparent','true')  === 'true',
        rainbow:         getStored('wolf_cross_rainbow','false') === 'true',
        offlineMode:     getStored('wolf_offline_mode','false') === 'true',
        rainbowName:     getStored('wolf_rainbow_name','false') === 'true',
        rgb:             getStored('wolf_rgb','false') === 'true',
        rainbowGunCamo:  getStored('wolf_rainbow_gun_camo','false') === 'true',
        blockInvites:    getStored('wolf_block_invites','false') === 'true',
        resetClass:      getStored('wolf_reset_class','false') === 'true',
        hideMelee:       getStored('wolf_hide_melee','false') === 'true',
        customName:      getStored('wolf_custom_name_toggle','false') === 'true',
        hideSkins:       getStored('wolf_hide_skins','false') === 'true',
        customRank:      getStored('wolf_custom_rank','false') === 'true',
        fovCircle:       getStored('wolf_fov_circle','false') === 'true',
        customArms:      getStored('wolf_custom_arms','false') === 'true',
        customProfile:   getStored('wolf_custom_profile','false') === 'true',
        keyVisualizer:   getStored('wolf_key_visualizer','false') === 'true',
        pcStats:         getStored('wolf_pc_stats','false') === 'true',
        airStrafe:       getStored('wolf_air_strafe','false') === 'true',
        armsV2:          getStored('wolf_arms_v2','false') === 'true',
        hidePersonality: getStored('wolf_hide_personality','false') === 'true',
        gunGlow:         getStored('wolf_gun_glow','false') === 'true',
        raveMode:        getStored('wolf_rave_mode','false') === 'true',
    };
    let skinColor  = getStored('wolf_skin_color', '#ff0000');
    let armColor   = getStored('wolf_arm_color', '#ffffff');
    let _cachedArmRgb = null;
    let titleStyle = getStored('wolf_title_style', 'yor');
    let menuKey    = getStored('wolf_menu_key', 'm');
    let resetClassKey = getStored('wolf_reset_class_key', 'g');
    const KEY_DISPLAY_NAMES={' ':'SPACE',arrowup:'↑',arrowdown:'↓',arrowleft:'←',arrowright:'→',control:'CTRL',alt:'ALT',shift:'SHIFT',tab:'TAB',capslock:'CAPS LOCK',enter:'ENTER',backspace:'BACKSPACE',escape:'ESC'};
    function displayKeyName(k){if(k===' ')return'SPACE';return KEY_DISPLAY_NAMES[k]||k.toUpperCase();}
    let gunGlowMode  = getStored('wolf_gun_glow_mode', 'rainbow');   // 'rainbow' | 'inferno' | 'vaporwave'
    let gunGlowBlend = getStored('wolf_gun_glow_blend', 'glow');     // 'glow' | 'paint'

    // =========================
    // THEME PALETTES
    // =========================
    const THEME_PALETTE = {
        yor:    { accent:'#ff8c00', accentFaint:'rgba(255,140,0,0.45)', accentDim:'rgba(255,140,0,0.25)',
                  text:'#ffcc66',   textDim:'rgba(255,180,80,0.55)',   labelAfter:'rgba(255,140,0,0.22)' },
        green:  { accent:'#c8a040', accentFaint:'rgba(200,160,64,0.45)', accentDim:'rgba(200,160,64,0.25)',
                  text:'#fcf6ba',   textDim:'rgba(200,160,64,0.55)',  labelAfter:'rgba(200,160,64,0.22)' },
        bw:     { accent:'#ffffff', accentFaint:'rgba(255,255,255,0.35)', accentDim:'rgba(255,255,255,0.15)',
                  text:'#ffffff',   textDim:'rgba(255,255,255,0.45)',  labelAfter:'rgba(255,255,255,0.12)' },
        aurora: { accent:'#6a5cff', accentFaint:'rgba(106,92,255,0.45)', accentDim:'rgba(106,92,255,0.25)',
                  text:'#c0b0ff',   textDim:'rgba(160,140,255,0.55)',  labelAfter:'rgba(106,92,255,0.22)' },
        goldpremium: { accent:'#c8a040', accentFaint:'rgba(200,160,64,0.45)', accentDim:'rgba(200,160,64,0.25)',
                  text:'#fff8c0',   textDim:'rgba(255,248,192,0.55)',  labelAfter:'rgba(200,160,64,0.22)' },
        skyblue: { accent:'#00bfff', accentFaint:'rgba(0,191,255,0.45)', accentDim:'rgba(0,191,255,0.25)',
                  text:'#b8eeff',   textDim:'rgba(100,180,255,0.55)',  labelAfter:'rgba(0,191,255,0.22)' },
    };
    const THEME_BODY_TEXT = {
        yor:         '#ffffff',
        green:       '#fcf6ba',
        bw:          '#ffffff',
        aurora:      '#fcf6ba',
        goldpremium: '#2c1a00',
        skyblue:     '#c8f0ff',
    };

    let resetClassId = Number(localStorage.getItem('wolf_reset_class_id') || '6');
    let fovValue     = Number(localStorage.getItem('wolf_fov_value') || '50');
    let cpSettings = JSON.parse(getStored('wolf_cp_settings', JSON.stringify({
        clanTag: '[TTEM]', username: 'wolf_', clanColor: '#8A0000', iconId: 2
    })));
    let mapColorSettings = JSON.parse(getStored('wolf_map_color_settings', JSON.stringify({
        overlay:     '#6617fd',
        fontColor:   '#ffffff',
        fontShadow:  '#000000',
        lightColor:  '#807b7a',
        weaponChams: '#000000',
        skyTop:      '#415f7d',
        skyBottom:   '#c4f1ff',
        sunColor:    '#ffffff',
    })));
    states.mapColorMod = getStored('wolf_map_color_mod','false') === 'true';

    // =========================
    // INVITE TRACKER DATA
    // =========================
    let roomInvites = {}, uidNickname = {};
    const inviteTimes = {};
    let blockedUsers = [], inviteUpdateTimer = null;
    let currentContextUid = null, currentContextData = null;
    function loadInviteData() {
        try { blockedUsers = JSON.parse(localStorage.getItem('wolf_blocked_users') || '[]'); } catch { blockedUsers = []; }
        try {
            const raw = JSON.parse(localStorage.getItem('wolf_invites') || '{}');
            const now = Date.now(), four = 4*60*60*1000;
            roomInvites = {}; uidNickname = {};
            for (const uid in (raw.inviteTimes || {})) {
                if (now - raw.inviteTimes[uid] < four) {
                    roomInvites[uid] = raw.roomInvites[uid];
                    uidNickname[uid] = raw.uidNickname[uid];
                    inviteTimes[uid] = raw.inviteTimes[uid];
                }
            }
        } catch { roomInvites = {}; uidNickname = {}; }
    }
    function saveInviteData() {
        localStorage.setItem('wolf_invites', JSON.stringify({ roomInvites, uidNickname, inviteTimes }));
        localStorage.setItem('wolf_blocked_users', JSON.stringify(blockedUsers));
    }
    loadInviteData();

    // =========================
    // TOAST NOTIFICATIONS
    // =========================
    function showToast(msg, type = 'success') {
        const colors = {
            success: { bg:'linear-gradient(135deg,#00c853,#00e676)', border:'#00e676' },
            error:   { bg:'linear-gradient(135deg,#ff4d4d,#ff6b6b)', border:'#ff6b6b' },
            info:    { bg:'linear-gradient(135deg,#2196f3,#42a5f5)', border:'#42a5f5' },
        };
        const c = colors[type] || colors.info;
        const toast = document.createElement('div');
        Object.assign(toast.style, {
            position:'fixed', right:'20px', padding:'10px 18px',
            background:c.bg, border:'1px solid '+c.border,
            borderRadius:'8px', color:'#fff', fontFamily:'Arial,sans-serif',
            fontSize:'13px', fontWeight:'500', zIndex:'10020',
            boxShadow:'0 4px 12px rgba(0,0,0,0.3)',
            transition:'opacity .3s ease, transform .3s ease',
            opacity:'0', transform:'translateX(100%)'
        });
        toast.innerText = msg;
        const existing = document.querySelectorAll('.wolf-toast');
        let top = 20;
        existing.forEach(t => { top = Math.max(top, t.getBoundingClientRect().bottom + 8); });
        toast.style.top = top + 'px';
        toast.classList.add('wolf-toast');
        document.body.appendChild(toast);
        requestAnimationFrame(() => { toast.style.opacity='1'; toast.style.transform='translateX(0)'; });
        setTimeout(() => { toast.style.opacity='0'; toast.style.transform='translateX(100%)'; setTimeout(()=>toast.remove(),300); }, 2500);
    }
    function timeAgo(ts) {
        const d = Math.floor((Date.now()-ts)/1000);
        if (d<5) return 'just now'; if (d<60) return d+'s ago';
        const m = Math.floor(d/60); if (m<60) return m+'m ago';
        const h = Math.floor(m/60); if (h<24) return h+'h ago';
        return Math.floor(h/24)+'d ago';
    }
    function processNickname(nickname) {
        let p = nickname.replace(/<sprite=1>/g,'__TICK_Y__').replace(/<sprite=2>/g,'__TICK_G__').replace(/<sprite=0>/g,'__TICK_B__');
        p = p.replace(/&lt;color=([^&]+)&gt;/g,'<span style="color:$1">').replace(/&lt;\/color&gt;/g,'</span>')
             .replace(/<color\s*=\s*([^>]+)>/g,'<span style="color:$1">').replace(/<\/color\s*>/g,'</span>');
        p = p.replace(/__TICK_Y__/g,'<span class="wolf-tick wolf-tick-y"></span>')
             .replace(/__TICK_G__/g,'<span class="wolf-tick wolf-tick-g"></span>')
             .replace(/__TICK_B__/g,'<span class="wolf-tick wolf-tick-b"></span>');
        return p;
    }

    // =========================
    // OFFLINE MODE
    // =========================
    function updateOfflineMode() {
        try {
            if (states.offlineMode) { if (typeof tearDownOnlineStatusTracking==='function') tearDownOnlineStatusTracking(); }
            else { if (typeof setupOnlineStatusTracking==='function') setupOnlineStatusTracking(); }
        } catch(err) { console.error('Offline Mode Error:',err); }
    }
    updateOfflineMode();

    // =========================
    // RAINBOW NAME
    // =========================
    let rainbowInterval;
    function handleRainbowName(userName) {
        if (rainbowInterval) clearInterval(rainbowInterval);
        if (!states.rainbowName) return;
        if (!userName) userName = 'wolf_';
        let hue = 0, lastColor = '';
        function hsvToHex(h) {
            const f=(n,k=(n+h/60)%6)=>255*(1-Math.max(Math.min(k,4-k,1),0));
            return '#'+[Math.round(f(5)),Math.round(f(3)),Math.round(f(1))].map(x=>x.toString(16).padStart(2,'0')).join('');
        }
        let _rnPending=false;
        const waitForUnity = cb => { const c=setInterval(()=>{ if(typeof unityInstance!=='undefined'){clearInterval(c);cb();} },500); };
        waitForUnity(() => {
            rainbowInterval = setInterval(() => {
                const color = hsvToHex(hue);
                if (color===lastColor) return;
                lastColor = color;
                if(!_rnPending){_rnPending=true;requestAnimationFrame(()=>{_rnPending=false;try{unityInstance.SendMessage('MapScripts','SetNickname',`<color=${color}>${userName}</color>`);}catch(e){}});}
                hue = (hue+rainbowNameSpeed)%360;
            }, 200);
        });
    }

    // =========================
    // FIREBASE HELPERS
    // =========================
    function getFirebaseUser() { try { return firebase?.auth()?.currentUser; } catch(e) { return null; } }
    function setSecondaryWeapon(id) {
        const u=getFirebaseUser(); if(!u){showToast('Not logged in','error');return;}
        try { firebase.database().ref('users/'+u.uid).update({overrideWeaponIndexes1:id}); showToast('Secondary weapon set!'); }
        catch(e){showToast('Failed to set weapon','error');}
    }
    function setMeleeWeapon(id) {
        const u=getFirebaseUser(); if(!u){showToast('Not logged in','error');return;}
        try { firebase.database().ref('users/'+u.uid).child('overrideWeaponIndexes2').set(id); showToast('Melee weapon set!'); }
        catch(e){showToast('Failed to set weapon','error');}
    }
    function setSkin(id) {
        const u=getFirebaseUser(); if(!u){showToast('Not logged in','error');return;}
        try { firebase.database().ref('users/'+u.uid).update({skin:id}); showToast('Skin applied!'); }
        catch(e){showToast('Failed to set skin','error');}
    }

    // =========================
    // WEAPON & SKIN DATA
    // =========================
    const weaponList = [
        {name:'AK-47',id:'0'},{name:'Deagle',id:'1'},{name:'AWP',id:'2'},
        {name:'Bayonet',id:'3'},{name:'Uzi',id:'4'},{name:'PKM',id:'5'},
        {name:'Revolver',id:'6'},{name:'RPG',id:'7'},{name:'USPS',id:'8'},
        {name:'MP5',id:'9'},{name:'Shotgun',id:'10'},{name:'Glock',id:'11'},
        {name:'Karambit',id:'12'},{name:'Knife',id:'13'},{name:'Scar',id:'14'},
        {name:'Minigun',id:'15'},{name:'Famas',id:'16'},{name:'Vector',id:'17'},
        {name:'Flamethrower',id:'18'},{name:'Kar98k',id:'19'},{name:'M4A4',id:'20'},
        {name:'Tec-9',id:'21'},{name:'CZ',id:'22'},{name:'Beretta 92fs',id:'23'},
        {name:'AK-109',id:'24'},{name:'P90',id:'25'},{name:'Thompson',id:'26'},
        {name:'UMP45',id:'27'},{name:'XM1014',id:'28'},{name:'Butterfly',id:'29'},
        {name:'Laser Gun',id:'30'},{name:'Bomb',id:'31'},{name:'Smoke Grenade',id:'32'},
        {name:'Molotov',id:'33'},{name:'Grenade',id:'34'},{name:'Flashbang',id:'35'},
        {name:'Glizzy',id:'36'},{name:'Axe',id:'37'},{name:'Bare Fists',id:'38'},
    ];
    const skinList = [
        {name:'KBI Agent',id:'12'},{name:'James Kour',id:'13'},{name:'President',id:'14'},
        {name:'Doctor',id:'15'},{name:'Trickster',id:'16'},{name:'Royal Guard',id:'17'},
        {name:'Xmas',id:'18'},{name:'Kelvis',id:'19'},{name:'Princess Pink',id:'20'},
        {name:'Princess White',id:'21'},{name:'Princess Bee',id:'22'},{name:'Princess Leaf',id:'23'},
        {name:'Koura Kraft',id:'24'},{name:'Green Hologram',id:'25'},{name:'Hologrape',id:'26'},
        {name:'Peter',id:'27'},{name:'Chicken',id:'28'},{name:'Chickoletta',id:'29'},
        {name:'Kyle',id:'30'},{name:'Shadowgram',id:'32'},{name:'IceBunny',id:'33'},
        {name:'CocoBunny',id:'34'},{name:'Kourean',id:'35'},{name:'KourG',id:'36'},
        {name:'Hackour',id:'37'},{name:'Golden Hackour',id:'38'},{name:'Gas Man',id:'39'},
        {name:'Terrorist',id:'40'},{name:'Counter Terrorist',id:'41'},{name:'Ambush',id:'42'},
        {name:'Baby Kour',id:'43'},{name:'Poacher',id:'44'},{name:'Astronaut',id:'45'},
        {name:'Kour Parrot',id:'46'},{name:'Kour Pirate',id:'47'},{name:'Legionaut',id:'48'},
        {name:'Blue Hologram',id:'49'},{name:'Mr Wireframe',id:'50'},{name:'Mythian',id:'51'},
        {name:'Kour Trooper',id:'52'},{name:'Kour Craft',id:'53'},{name:'Kour Green Soldier',id:'54'},
        {name:'Yellow Astronaut',id:'55'},{name:'Orange Astronaut',id:'56'},{name:'Red Astronaut',id:'57'},
        {name:'Blue Astronaut',id:'58'},{name:'Kour Banana',id:'59'},{name:'Mrs Kour',id:'60'},
        {name:'Investor Inverted',id:'61'},{name:'Kour Jungler',id:'62'},{name:'Skinny Baby',id:'63'},
        {name:'KourTuber',id:'64'},{name:'Red Hologram',id:'65'},{name:'White Hologram',id:'66'},
        {name:'Orange Hologram',id:'67'},{name:'Dark Blue Hologram',id:'68'},{name:'Brown Hologram',id:'69'},
        {name:'Yellow Hologram',id:'70'},{name:'Dark Red Hologram',id:'71'},{name:'Kourist',id:'72'},
        {name:'Firefighter',id:'73'},{name:'FireKour',id:'74'},{name:'Kour Thief',id:'75'},
        {name:'Kour Burger',id:'76'},{name:'Kour Fan',id:'77'},{name:'Kour Brady',id:'78'},
        {name:'LeKour James',id:'79'},{name:'Uncle Kour',id:'80'},{name:'Chef',id:'81'},
        {name:'KourObby',id:'82'},{name:'Legionary',id:'83'},{name:'Kitty Kour One',id:'84'},
        {name:'Kitty Kour Two',id:'85'},{name:'Kitty Kour Three',id:'86'},{name:'Kour Crafter',id:'87'},
        {name:'RTX',id:'88'},{name:'Loony Kour',id:'89'},{name:'Kour Shocker',id:'90'},
        {name:'Kourkin',id:'91'},{name:'Forest Kour',id:'92'},{name:'Slender Kour',id:'93'},
        {name:'Drakour',id:'94'},{name:'Christmas 2024',id:'95'},{name:'Deer 2024',id:'96'},
    ];

     // =========================
    // RESET CLASS OPTIONS
    // =========================
       const RESET_CLASS_OPTIONS = [
        {name:'Soldier',    id:0},
        {name:'Hitman',     id:1},
        {name:'Gunner',     id:2},
        {name:'Heavy',      id:3},
        {name:'Rocketeer',  id:4},
        {name:'Agent',      id:5},
        {name:'Brawler',    id:6},
        {name:'Investor',   id:7},
        {name:'Assassin',   id:8},
        {name:'Juggernaut', id:9},
        {name:'Recon',      id:10},
        {name:'Pyro',       id:11},
        {name:'Ray Blader', id:12},
    ];

    // =========================
    // WEBGL ARM / GUN COLOR
    // =========================
    const WEBGL_ARM_COUNTS    = new Set([1098,3216]);
    const WEBGL_WEAPON_COUNTS = new Set([14862,14526,8553]);
    const WEBGL_MELEE_COUNTS  = new Set([1884,1116,5808,2502]);
    const WEBGL_CROSS_COUNTS  = new Set([300]);
    const GUN_IDS             = new Set([7092,1998,2118,1746,1884,1116,5808,2502,14862,14526,8533]);
    const WEBGL_GUN_GLOW_COUNTS = new Set([
        1884,1116,5808,2502,                                       // melee
        7092,1998,2118,1746,1884,1116,5808,2502,14862,14526,8533,  // guns
        3624,3816,4284,                                            // xm
    ]);
    function hexToRgb01(hex) {
        return [parseInt(hex.slice(1,3),16)/255, parseInt(hex.slice(3,5),16)/255, parseInt(hex.slice(5,7),16)/255];
    }
    function refreshCachedArmRgb() { _cachedArmRgb = hexToRgb01(armColor); }
    refreshCachedArmRgb(); // initialize on load
    let gunHue=0, armsV2Hue=0;
    function hslToRgb01(h) {
        const h6=h/60;
        const r=Math.min(Math.max(Math.abs(h6-3)-1,0),1);
        const g=Math.min(Math.max(2-Math.abs(h6-2),0),1);
        const b=Math.min(Math.max(2-Math.abs(h6-4),0),1);
        return [0.1+r*0.9,0.1+g*0.9,0.1+b*0.9];
    }

    function infernoRgb(phase) {
        const stops=[[0.05,0.02,0.0],[0.55,0.05,0.0],[0.95,0.35,0.0],[1.0,0.75,0.1],[1.0,1.0,0.6],[0.55,0.05,0.0]];
        const n=stops.length-1, scaled=((phase%1)+1)%1*n, i=Math.floor(scaled), f=scaled-i;
        const a=stops[i], b=stops[Math.min(i+1,n)];
        return [a[0]+(b[0]-a[0])*f, a[1]+(b[1]-a[1])*f, a[2]+(b[2]-a[2])*f];
    }
    function vaporwaveRgb(phase) {
        const stops=[[1.0,0.43,0.78],[0.5,0.35,0.94],[0.0,0.80,1.0],[0.02,1.0,0.63],[1.0,0.43,0.78]];
        const n=stops.length-1, scaled=((phase%1)+1)%1*n, i=Math.floor(scaled), f=scaled-i;
        const a=stops[i], b=stops[Math.min(i+1,n)];
        return [a[0]+(b[0]-a[0])*f, a[1]+(b[1]-a[1])*f, a[2]+(b[2]-a[2])*f];
    }
    function gunGlowRgbForPhase(mode, phase) {
        if (mode==='inferno')   return infernoRgb(phase);
        if (mode==='vaporwave') return vaporwaveRgb(phase);
        return hslToRgb01((((phase%1)+1)%1)*360); // rainbow
    }
    let gunGlowPhase=0;
    let _gunGlowRgb=gunGlowRgbForPhase(gunGlowMode, 0);
    let gunGlowSpeed = Number(localStorage.getItem('wolf_gun_glow_speed') || '0.6');
    let raveSpeed = Number(localStorage.getItem('wolf_rave_speed') || '1.0');
    let _gunRgb=hslToRgb01(0), _armsV2Rgb=hslToRgb01(0);
    function tickRainbowHues() {
        if (states.rainbowGunCamo) { gunHue=(gunHue+rainbowGunSpeed)%360; _gunRgb=hslToRgb01(gunHue); }
        if (states.armsV2)         { armsV2Hue=(armsV2Hue+1.8)%360; _armsV2Rgb=hslToRgb01(armsV2Hue); }
        if (states.gunGlow)        { gunGlowPhase=(gunGlowPhase+0.0025*gunGlowSpeed)%1; _gunGlowRgb=gunGlowRgbForPhase(gunGlowMode, gunGlowPhase); }
    }
    let _webglAnyActive = states.customArms || states.rainbowGunCamo || states.armsV2 || states.gunGlow;
    function refreshWebglFlag() { _webglAnyActive = states.customArms || states.rainbowGunCamo || states.armsV2 || states.gunGlow; }
    let _hideAnyActive = states.arms || states.weapon || states.hideMelee || states.hideGameCross;
    function refreshHideFlag() { _hideAnyActive = states.arms || states.weapon || states.hideMelee || states.hideGameCross; }
    let rainbowGunSpeed = Number(localStorage.getItem('wolf_rainbow_gun_speed') || '0.6');
    let rainbowNameSpeed = Number(localStorage.getItem('wolf_rainbow_name_speed') || '6');

    const rainbowDrawHandler = {
        apply(target, thisArgs, args) {
            if (!_webglAnyActive) return Reflect.apply(target, thisArgs, args);
            const count = args[1]!==undefined ? args[1] : args[0];
            if (states.armsV2 && WEBGL_ARM_COUNTS.has(count)) {
                const result = Reflect.apply(target, thisArgs, args);
                const gl=thisArgs, rgb=_armsV2Rgb, [mode,cnt,type,offset]=args;
                gl.enable(gl.BLEND); gl.blendFunc(gl.CONSTANT_COLOR,gl.ZERO); gl.blendColor(rgb[0],rgb[1],rgb[2],1.0);
                try { gl.lineWidth(1.5); Function.prototype.apply.call(target,gl,[gl.LINES,cnt,type,offset]); } catch(e){}
                gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA); gl.disable(gl.BLEND);
                return result;
            }
            if (states.customArms && WEBGL_ARM_COUNTS.has(count)) {
                const rgb=_cachedArmRgb;
                thisArgs.enable(thisArgs.BLEND); thisArgs.blendFunc(thisArgs.CONSTANT_COLOR,thisArgs.ZERO);
                thisArgs.blendColor(rgb[0],rgb[1],rgb[2],1.0);
                const result=Reflect.apply(target,thisArgs,args);
                thisArgs.blendFunc(thisArgs.SRC_ALPHA,thisArgs.ONE_MINUS_SRC_ALPHA); thisArgs.disable(thisArgs.BLEND);
                return result;
            }
            if (states.gunGlow && WEBGL_GUN_GLOW_COUNTS.has(count)) {
                const rgb=_gunGlowRgb;
                thisArgs.enable(thisArgs.BLEND);
                if (gunGlowBlend==='glow') thisArgs.blendFunc(thisArgs.ZERO,thisArgs.CONSTANT_COLOR);
                else thisArgs.blendFunc(thisArgs.CONSTANT_COLOR,thisArgs.ZERO);
                thisArgs.blendColor(rgb[0],rgb[1],rgb[2],1.0);
                const result=Reflect.apply(target,thisArgs,args);
                thisArgs.blendFunc(thisArgs.SRC_ALPHA,thisArgs.ONE_MINUS_SRC_ALPHA); thisArgs.disable(thisArgs.BLEND);
                return result;
            }
            if (states.rainbowGunCamo && GUN_IDS.has(count)) {
                const rgb=_gunRgb;
                thisArgs.enable(thisArgs.BLEND); thisArgs.blendFunc(thisArgs.CONSTANT_COLOR,thisArgs.ZERO);
                thisArgs.blendColor(rgb[0],rgb[1],rgb[2],1.0);
                const result=Reflect.apply(target,thisArgs,args);
                thisArgs.blendFunc(thisArgs.SRC_ALPHA,thisArgs.ONE_MINUS_SRC_ALPHA); thisArgs.disable(thisArgs.BLEND);
                return result;
            }
            return Reflect.apply(target, thisArgs, args);
        }
    };
    const WebGLProto = realWindow.WebGL2RenderingContext.prototype;
    function wolfWrapDraw(original) {
        return function(...args) { return rainbowDrawHandler.apply(original, this, args); };
    }
    if (WebGLProto.drawElements)          WebGLProto.drawElements          = wolfWrapDraw(WebGLProto.drawElements);
    if (WebGLProto.drawElementsInstanced) WebGLProto.drawElementsInstanced = wolfWrapDraw(WebGLProto.drawElementsInstanced);

    // =========================
    // CUSTOM PROFILE
    // =========================
    let _cpCapturedInstance = null;
    try {
        const _uw = typeof unsafeWindow!=='undefined' ? unsafeWindow : window;
        Object.defineProperty(_uw,'unityInstance',{
            get() { return this._wolf_unityInstance; },
            set(v) {
                this._wolf_unityInstance=v; _cpCapturedInstance=v;
                if (states.customProfile) { setTimeout(sendProfileNow,200); setTimeout(sendProfileNow,1500); }
            },
            configurable:true
        });
    } catch(e){}
    function buildProfileNickname() {
        return `<color=${cpSettings.clanColor}>${cpSettings.clanTag}</color><sprite=${cpSettings.iconId}>${cpSettings.username}`;
    }
    function sendProfileNow() {
        const game = _cpCapturedInstance
            || (typeof unsafeWindow!=='undefined' ? unsafeWindow.unityInstance : null)
            || window.unityInstance || window.gameInstance || window.kourInstance;
        if (game && typeof game.SendMessage==='function') {
            try { game.SendMessage('MapScripts','SetNickname',buildProfileNickname()); return true; } catch(e){}
        }
        return false;
    }
    let cpInterval = null;
    function applyCustomProfile() {
        if (cpInterval) { clearInterval(cpInterval); cpInterval=null; }
        if (!states.customProfile) return;
        localStorage.setItem('playerNickname', buildProfileNickname());
        sendProfileNow();
        cpInterval = setInterval(()=>{
            if (!states.customProfile) { clearInterval(cpInterval); cpInterval=null; return; }
            localStorage.setItem('playerNickname', buildProfileNickname());
            sendProfileNow();
        }, 3000);
    }
    if (states.customProfile) applyCustomProfile();

    function buildHiddenNickname() {
        return '<color=#00000000>ㅤ</color>';
    }
    let hidePersonalityInterval = null;
    function applyHidePersonality() {
        if (hidePersonalityInterval) { clearInterval(hidePersonalityInterval); hidePersonalityInterval=null; }
        if (!states.hidePersonality) return;
        localStorage.setItem('playerNickname', buildHiddenNickname());
        sendProfileNow.call ? null : null; // no-op guard, ignore
        const game = _cpCapturedInstance || (typeof unsafeWindow!=='undefined' ? unsafeWindow.unityInstance : null) || window.unityInstance || window.gameInstance || window.kourInstance;
        if (game && typeof game.SendMessage==='function') { try { game.SendMessage('MapScripts','SetNickname',buildHiddenNickname()); } catch(e){} }
        hidePersonalityInterval = setInterval(()=>{
            if (!states.hidePersonality) { clearInterval(hidePersonalityInterval); hidePersonalityInterval=null; return; }
            localStorage.setItem('playerNickname', buildHiddenNickname());
            const g = _cpCapturedInstance || (typeof unsafeWindow!=='undefined' ? unsafeWindow.unityInstance : null) || window.unityInstance || window.gameInstance || window.kourInstance;
            if (g && typeof g.SendMessage==='function') { try { g.SendMessage('MapScripts','SetNickname',buildHiddenNickname()); } catch(e){} }
        }, 3000);
    }
    if (states.hidePersonality) applyHidePersonality();

    // =========================
    // KEY VISUALIZER
    // =========================
    let keyVisCanvas=null, keyVisCtx=null, pressedKeys={}, keyVisAnimFrame=null;
    const KEY_LAYOUT = [
        {key:'W',row:0,col:1},{key:'A',row:1,col:0},{key:'S',row:1,col:1},
        {key:'D',row:1,col:2},{key:'SPACE',row:2,col:0,wide:true},
    ];
    function initKeyVisualizer() {
        if (keyVisCanvas) return;
        keyVisCanvas = document.createElement('canvas');
        keyVisCanvas.id='wolf-key-vis';
        Object.assign(keyVisCanvas.style,{position:'fixed',bottom:'20px',left:'20px',pointerEvents:'none',zIndex:'9999'});
        keyVisCanvas.width=130; keyVisCanvas.height=95;
        document.body.appendChild(keyVisCanvas);
        keyVisCtx = keyVisCanvas.getContext('2d');
        startSharedRaf();
    }
    function destroyKeyVisualizer() {
        if (keyVisAnimFrame){cancelAnimationFrame(keyVisAnimFrame);keyVisAnimFrame=null;}
        if (keyVisCanvas){keyVisCanvas.remove();keyVisCanvas=null;keyVisCtx=null;}
        pressedKeys={}; _keyVisDirty=true;
    }
    let _keyVisDirty=true;
    function drawKeyVisFrame() {
        if (!keyVisCtx) return;
        keyVisCtx.clearRect(0,0,130,95);
        const keyW=34,keyH=28,gap=4,startX=4,startY=4;
        KEY_LAYOUT.forEach(k=>{
            const x=startX+k.col*(keyW+gap), y=startY+k.row*(keyH+gap), w=k.wide?(keyW*3+gap*2):keyW;
            const pressed=!!pressedKeys[k.key];
            keyVisCtx.beginPath(); keyVisCtx.roundRect(x,y,w,keyH,5);
            if (pressed) {
                const g=keyVisCtx.createLinearGradient(x,y,x,y+keyH);
                g.addColorStop(0,'rgba(200,160,64,0.95)'); g.addColorStop(1,'rgba(150,110,30,0.9)');
                keyVisCtx.fillStyle=g;
            } else {
                const g=keyVisCtx.createLinearGradient(x,y,x,y+keyH);
                g.addColorStop(0,'rgba(30,30,30,0.95)'); g.addColorStop(1,'rgba(15,15,15,0.95)');
                keyVisCtx.fillStyle=g;
            }
            keyVisCtx.fill();
            keyVisCtx.strokeStyle=pressed?'rgba(255,220,80,0.9)':'rgba(200,160,64,0.3)';
            keyVisCtx.lineWidth=pressed?1.5:1; keyVisCtx.stroke();
            if (pressed) {
                keyVisCtx.beginPath(); keyVisCtx.roundRect(x+2,y+2,w-4,keyH-4,3);
                keyVisCtx.strokeStyle='rgba(255,240,150,0.25)'; keyVisCtx.lineWidth=1; keyVisCtx.stroke();
            }
            keyVisCtx.fillStyle=pressed?'#000':'rgba(200,160,64,0.9)';
            keyVisCtx.font=`bold ${k.wide?9:11}px "Segoe UI",Arial,sans-serif`;
            keyVisCtx.textAlign='center'; keyVisCtx.textBaseline='middle';
            keyVisCtx.fillText(k.key, x+w/2, y+keyH/2+0.5);
        });
    }
    function onKeyDown(e) {
        const k=e.key.toUpperCase();
        if (k===' '){if(!pressedKeys['SPACE']){pressedKeys['SPACE']=true;_keyVisDirty=true;}}
        else if(['W','A','S','D'].includes(k)){if(!pressedKeys[k]){pressedKeys[k]=true;_keyVisDirty=true;}}
    }
    function onKeyUp(e) {
        const k=e.key.toUpperCase();
        if (k===' '){if(pressedKeys['SPACE']){pressedKeys['SPACE']=false;_keyVisDirty=true;}}
        else if(['W','A','S','D'].includes(k)){if(pressedKeys[k]){pressedKeys[k]=false;_keyVisDirty=true;}}
    }
    function startKeyVisualizer() {
        if (!states.keyVisualizer) return;
        initKeyVisualizer();
        window.addEventListener('keydown',onKeyDown,true);
        window.addEventListener('keyup',onKeyUp,true);
    }
    function stopKeyVisualizer() {
        destroyKeyVisualizer();
        window.removeEventListener('keydown',onKeyDown,true);
        window.removeEventListener('keyup',onKeyUp,true);
    }
    if (states.keyVisualizer) startKeyVisualizer();

    // =========================
    // SHARED RAF + PC STATS
    // =========================
    let pcStatsPanel=null, pcStatsInterval=null, pcStatsFrames=0, pcStatsFps=0;
    let pcStatsLastFpsTime=performance.now(), pcStatsStartTime=Date.now();
    let pcStatsBatteryText='Unavailable', pcStatsThermalText=null;
    let _sharedRafId=null;
    function _sharedRafLoop() {
        _sharedRafId=requestAnimationFrame(_sharedRafLoop);
        if (_webglAnyActive) tickRainbowHues();
        if (states.raveMode) tickRaveMode();
        if (keyVisCtx&&_keyVisDirty) {
            _keyVisDirty=false;
            if (states.keyVisualizer) drawKeyVisFrame();
            else keyVisCtx.clearRect(0,0,130,95);
        }
    }
    function startSharedRaf() { if (!_sharedRafId) _sharedRafId=requestAnimationFrame(_sharedRafLoop); }
    let pcStatsRafId=null;
    function pcStatsFpsLoop() {
        pcStatsRafId=requestAnimationFrame(pcStatsFpsLoop);
        pcStatsFrames++;
        const now=performance.now();
        if (now-pcStatsLastFpsTime>=1000){pcStatsFps=pcStatsFrames;pcStatsFrames=0;pcStatsLastFpsTime=now;}
    }
    function initBatteryTracking() {
        if (!navigator.getBattery){pcStatsBatteryText='Not supported';return;}
        navigator.getBattery().then(b=>{
            const update=()=>{pcStatsBatteryText=Math.round(b.level*100)+'%'+(b.charging?' (charging)':'');};
            update(); b.addEventListener('levelchange',update); b.addEventListener('chargingchange',update);
        }).catch(()=>{pcStatsBatteryText='Unavailable';});
    }
    initBatteryTracking();
    function initThermalTracking() {
        if (typeof navigator.thermal==='undefined'){pcStatsThermalText='Unsupported';return;}
        const map={nominal:'Normal 🟢',fair:'Warm 🟡',serious:'Hot 🔴',critical:'Critical 🔥'};
        navigator.thermal.addEventListener('change',()=>{pcStatsThermalText=map[navigator.thermal.state]||navigator.thermal.state;});
        pcStatsThermalText=map[navigator.thermal.state]||navigator.thermal.state;
    }
    initThermalTracking();
    function formatUptime(ms) {
        const t=Math.floor(ms/1000),h=Math.floor(t/3600),m=Math.floor((t%3600)/60),s=t%60;
        if(h>0)return`${h}h ${m}m ${s}s`; if(m>0)return`${m}m ${s}s`; return`${s}s`;
    }
    function getNetworkInfo() {
        const c=navigator.connection||navigator.mozConnection||navigator.webkitConnection;
        if(!c)return'Not supported';
        const type=c.effectiveType?c.effectiveType.toUpperCase():'Unknown';
        const down=typeof c.downlink==='number'?c.downlink+' Mbps':'';
        return down?`${type} · ${down}`:type;
    }
    function getLocalDateTime() {
        const now=new Date();
        return {
            date:now.toLocaleDateString(undefined,{day:'2-digit',month:'2-digit',year:'numeric'}),
            time:now.toLocaleTimeString(undefined,{hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:false}),
            tz:now.toLocaleTimeString('en',{timeZoneName:'short'}).split(' ').pop()
        };
    }
    function buildPcStatsRow(label,valueId) {
        const row=document.createElement('div');
        Object.assign(row.style,{display:'flex',flexDirection:'column',gap:'2px',padding:'7px 9px',borderRadius:'8px',background:'rgba(0,0,0,0.35)',border:'1px solid rgba(200,160,64,0.16)',fontSize:'11px'});
        const lbl=document.createElement('span');
        lbl.innerText=label;
        Object.assign(lbl.style,{color:'rgba(200,160,64,0.7)',fontWeight:'700',letterSpacing:'0.04em',fontSize:'9px',textTransform:'uppercase'});
        const val=document.createElement('span'); val.id=valueId; val.innerText='—';
        Object.assign(val.style,{color:'#fcf6ba',fontWeight:'800',fontSize:'12px'});
        row.append(lbl,val); return row;
    }
    function buildPcStatsPanel() {
        if (pcStatsPanel) return pcStatsPanel;
        const panel=document.createElement('div');
        panel.id='wolf-pc-stats-panel';
        Object.assign(panel.style,{marginTop:'7px',padding:'9px',borderRadius:'9px',background:'rgba(0,0,0,0.3)',border:'1px solid rgba(200,160,64,0.22)',display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:'6px'});
        panel.append(
            buildPcStatsRow('Date','wolf-stat-date'),buildPcStatsRow('Time','wolf-stat-time'),
            buildPcStatsRow('Timezone','wolf-stat-tz'),buildPcStatsRow('FPS','wolf-stat-fps'),
            buildPcStatsRow('CPU Temp','wolf-stat-temp'),buildPcStatsRow('Battery','wolf-stat-battery'),
            buildPcStatsRow('Network','wolf-stat-network'),buildPcStatsRow('Connection','wolf-stat-online'),
            buildPcStatsRow('Session Uptime','wolf-stat-uptime'),buildPcStatsRow('Resolution','wolf-stat-resolution'),
            buildPcStatsRow('Pixel Ratio','wolf-stat-dpr'),buildPcStatsRow('CPU Cores','wolf-stat-cores')
        );
        pcStatsPanel=panel; return panel;
    }
    function refreshPcStatsPanel() {
        if (!pcStatsPanel||!states.pcStats) return;
        const sv=(id,text,color)=>{const el=document.getElementById(id);if(el){el.innerText=text;el.style.color=color||'#fcf6ba';}};
        const dt=getLocalDateTime();
        sv('wolf-stat-date',dt.date); sv('wolf-stat-time',dt.time); sv('wolf-stat-tz',dt.tz);
        sv('wolf-stat-fps',String(pcStatsFps),pcStatsFps<30?'#ff4444':pcStatsFps<60?'#ffaa00':'#00e676');
        const tt=pcStatsThermalText||'Checking...';
        sv('wolf-stat-temp',tt,tt.includes('🔴')||tt.includes('🔥')?'#ff4444':tt.includes('🟡')?'#ffaa00':tt.includes('🟢')?'#00e676':'#fcf6ba');
        sv('wolf-stat-battery',pcStatsBatteryText,pcStatsBatteryText.includes('charging')?'#00e676':(pcStatsBatteryText!=='Unavailable'&&parseInt(pcStatsBatteryText)<20)?'#ff4444':'#fcf6ba');
        sv('wolf-stat-network',getNetworkInfo());
        sv('wolf-stat-online',navigator.onLine?'Online ✓':'Offline ✗',navigator.onLine?'#00e676':'#ff4444');
        sv('wolf-stat-uptime',formatUptime(Date.now()-pcStatsStartTime));
        sv('wolf-stat-resolution',`${window.screen.width}×${window.screen.height}`);
        sv('wolf-stat-dpr',String(window.devicePixelRatio||1));
        sv('wolf-stat-cores',String(navigator.hardwareConcurrency||'Unknown'));
    }
    function startPcStats() {
        if (!pcStatsRafId) pcStatsFpsLoop();
        if (pcStatsPanel) pcStatsPanel.style.display='block';
        refreshPcStatsPanel();
        if (!pcStatsInterval) pcStatsInterval=setInterval(refreshPcStatsPanel,1000);
    }
    function stopPcStats() {
        if (pcStatsPanel) pcStatsPanel.style.display='none';
        if (pcStatsInterval){clearInterval(pcStatsInterval);pcStatsInterval=null;}
    }

    // =========================
    // AIR STRAFING
    // =========================
    let asSpaceHeld=false,asTurningLeft=false,asTurningRight=false,asLastMoveTime=0,asAHeld=false,asDHeld=false,asRafId=null;
    const AS_ACTIVE_TIMEOUT=150;
    function asSimulateKey(code,down) {
        const kc=code==='KeyA'?'a':'d';
        document.dispatchEvent(new KeyboardEvent(down?'keydown':'keyup',{code,key:kc,keyCode:code==='KeyA'?65:68,which:code==='KeyA'?65:68,bubbles:true,cancelable:true}));
    }
    function asOnMouseMove(e) {
        if(e.movementX<0){asTurningLeft=true;asTurningRight=false;}
        else if(e.movementX>0){asTurningRight=true;asTurningLeft=false;}
        asLastMoveTime=Date.now(); asUpdate(); _scheduleAsIdle();
    }
    function asOnKeyDown(e){if(e.code==='Space'){asSpaceHeld=true;asUpdate();}}
    function asOnKeyUp(e){if(e.code==='Space'){asSpaceHeld=false;asUpdate();}}
    function asReleaseAll(){if(asAHeld){asSimulateKey('KeyA',false);asAHeld=false;}if(asDHeld){asSimulateKey('KeyD',false);asDHeld=false;}}
    function asUpdate() {
        const ma=(Date.now()-asLastMoveTime)<AS_ACTIVE_TIMEOUT;
        if(asSpaceHeld&&ma){
            if(asTurningLeft&&!asAHeld){asSimulateKey('KeyA',true);asAHeld=true;}
            else if(!asTurningLeft&&asAHeld){asSimulateKey('KeyA',false);asAHeld=false;}
            if(asTurningRight&&!asDHeld){asSimulateKey('KeyD',true);asDHeld=true;}
            else if(!asTurningRight&&asDHeld){asSimulateKey('KeyD',false);asDHeld=false;}
        } else asReleaseAll();
    }
    let _asIdleTimer=null;
    function _scheduleAsIdle(){if(_asIdleTimer)clearTimeout(_asIdleTimer);_asIdleTimer=setTimeout(()=>{asReleaseAll();_asIdleTimer=null;},AS_ACTIVE_TIMEOUT+16);}
    function startAirStrafe(){if(asRafId)return;asRafId=true;asSpaceHeld=asTurningLeft=asTurningRight=false;asLastMoveTime=0;document.addEventListener('mousemove',asOnMouseMove);document.addEventListener('keydown',asOnKeyDown);document.addEventListener('keyup',asOnKeyUp);}
    function stopAirStrafe(){asRafId=null;if(_asIdleTimer){clearTimeout(_asIdleTimer);_asIdleTimer=null;}document.removeEventListener('mousemove',asOnMouseMove);document.removeEventListener('keydown',asOnKeyDown);document.removeEventListener('keyup',asOnKeyUp);asReleaseAll();asSpaceHeld=asTurningLeft=asTurningRight=false;}




    // =========================
    // STYLES
    // =========================
    const globalStyle = document.createElement('style');
    globalStyle.innerHTML = `
        @keyframes wolfShine { from{background-position:0% center} to{background-position:200% center} }
        .wolf-title-anim {
            background:linear-gradient(90deg,#ffd700,#ffb300,#ff8c00,#ff4500,#ff0000,#ff4500,#ff8c00,#ffb300,#ffd700);
            background-size:200% auto; color:transparent; -webkit-background-clip:text; background-clip:text;
            animation:wolfShine 6s linear infinite; font-size:38px; font-weight:900;
            letter-spacing:3px; text-transform:uppercase;
            text-shadow:0 0 8px rgba(255,120,0,0.4),0 0 16px rgba(255,80,0,0.3),0 0 24px rgba(255,0,0,0.2);
        }
        .wolf-title-goldpremium { animation:none!important; background:none!important; -webkit-background-clip:unset!important; background-clip:unset!important; color:#000000!important; text-shadow:none!important; }
        @keyframes wolfRainbow {
            0%{background:#ff0000;border-color:#ff0000}17%{background:#ffa500;border-color:#ffa500}
            33%{background:#ffff00;border-color:#ffff00}50%{background:#008000;border-color:#008000}
            67%{background:#0000ff;border-color:#0000ff}83%{background:#4b0082;border-color:#4b0082}
            100%{background:#ee82ee;border-color:#ee82ee}
        }
        @keyframes wolfRainbowBorderOnly {
            0%{border-color:#ff0000}17%{border-color:#ffa500}33%{border-color:#ffff00}
            50%{border-color:#008000}67%{border-color:#0000ff}83%{border-color:#4b0082}100%{border-color:#ee82ee}
        }
        .wolf-rainbow-active { animation:wolfRainbow 4s linear infinite!important; }
        .wolf-rainbow-border-active { animation:wolfRainbowBorderOnly 4s linear infinite!important; }

        @keyframes wolfShineGreen { 0%{background-position:0% center} 100%{background-position:300% center} }
        .wolf-title-green {
            background:linear-gradient(#00c853,#00e676)!important; background-size:300% auto!important;
            color:transparent!important; -webkit-background-clip:text!important; background-clip:text!important;
            animation:wolfShineGreen 8s linear infinite!important;
            text-shadow:0 0 10px rgba(0,200,83,0.35),0 0 18px rgba(0,230,118,0.22)!important;
            filter:drop-shadow(0 0 10px rgba(0,200,83,0.25))!important;
        }
        @keyframes wolfShineBW { from{background-position:0% center} to{background-position:200% center} }
        .wolf-title-bw {
            background:linear-gradient(90deg,#ffffff,#aaaaaa,#ffffff,#666666,#ffffff,#aaaaaa,#ffffff)!important;
            background-size:300% auto!important; color:transparent!important;
            -webkit-background-clip:text!important; background-clip:text!important;
            animation:wolfShineBW 4s linear infinite!important; text-shadow:none!important;
            filter:drop-shadow(0 0 6px rgba(255,255,255,0.5))!important;
        }
        @keyframes wolfShineAurora { 0%{background-position:0% center} 100%{background-position:300% center} }
        .wolf-title-aurora {
            background:linear-gradient(90deg,#00f7ff,#6a5cff,#c93bff,#6a5cff,#00f7ff)!important;
            background-size:300% auto!important; color:transparent!important;
            -webkit-background-clip:text!important; background-clip:text!important;
            animation:wolfShineAurora 7s linear infinite!important;
            text-shadow:0 0 10px rgba(0,247,255,0.35),0 0 20px rgba(106,92,255,0.28)!important;
            filter:drop-shadow(0 0 10px rgba(106,92,255,0.3))!important;
        }
        @keyframes wolfShineSkyblue { 0%{background-position:0% center} 100%{background-position:300% center} }
        .wolf-title-skyblue {
            background:linear-gradient(90deg,#b8eeff,#00bfff,#0090cc,#00bfff,#b8eeff)!important;
            background-size:300% auto!important; color:transparent!important;
            -webkit-background-clip:text!important; background-clip:text!important;
            animation:wolfShineSkyblue 6s linear infinite!important; text-shadow:none!important;
            filter:drop-shadow(0 0 12px rgba(30,144,255,0.55))!important;
        }
        @keyframes wolfTabAurora { from{background-position:0% center} to{background-position:200% center} }
        .wolf-tab-aurora {
            background:linear-gradient(90deg,#00f7ff,#6a5cff,#c93bff,#6a5cff,#00f7ff)!important;
            background-size:200% auto!important; -webkit-background-clip:text!important;
            background-clip:text!important; color:transparent!important;
            animation:wolfTabAurora 7s linear infinite!important; border-bottom-color:transparent!important;
        }
        @keyframes wolfMetalSweep {
    0%   { background-position: -150% 0; }
    100% { background-position: 250% 0; }
}
.wolf-metal-sweep {
    background:linear-gradient(100deg, transparent 40%, rgba(255,255,255,0.35) 50%, transparent 60%)!important;
    background-size:250% 100%!important;
    animation:wolfMetalSweep 4.5s ease-in-out infinite!important;
}
        .wolf-tab-aurora-active { border-bottom-color:#6a5cff!important; }
        .wolf-menu-aurora-border {
            background:linear-gradient(180deg,#0a0d1f,#120a24) padding-box,
                        linear-gradient(160deg,#00f7ff 0%,#6a5cff 45%,#c93bff 75%,#1a0a3a 100%) border-box!important;
        }
        .wolf-menu-aurora-bg {
            background-image:radial-gradient(circle at 15% 10%,rgba(0,247,255,0.16),transparent 32%),
                radial-gradient(circle at 85% 0%,rgba(201,59,255,0.14),transparent 30%),
                radial-gradient(circle at 50% 100%,rgba(106,92,255,0.12),transparent 40%)!important;
        }
        .wolf-tab-skyblue { color:rgba(0,191,255,0.38)!important; border-bottom-color:transparent!important; background:none!important; animation:none!important; }
        .wolf-tab-skyblue-active { color:#b8eeff!important; border-bottom-color:#00bfff!important; text-shadow:0 0 8px rgba(0,191,255,0.6)!important; }
        .wolf-tab-skyblue:hover:not(.wolf-tab-skyblue-active) { color:#00bfff!important; }
        .wolf-menu-skyblue-border {
            background:linear-gradient(#030d14,#030d14) padding-box,
                        linear-gradient(160deg,#b8eeff 0%,#00bfff 45%,#0080c0 75%,#030d14 100%) border-box!important;
        }
        .wolf-menu-skyblue-bg {
            background-image:radial-gradient(circle at 15% 10%,rgba(0,191,255,0.13),transparent 32%),
                radial-gradient(circle at 85% 0%,rgba(0,170,255,0.10),transparent 30%),
                radial-gradient(circle at 50% 100%,rgba(0,150,210,0.09),transparent 40%)!important;
        }
        .wolf-tab-yor { background:none!important; -webkit-background-clip:unset!important; background-clip:unset!important; color:rgba(255,255,255,0.42)!important; animation:none!important; border-bottom-color:transparent!important; }
        .wolf-tab-yor-active { color:#ffffff!important; border-bottom-color:rgba(255,255,255,0.55)!important; }
        .wolf-tab-yor:hover:not(.wolf-tab-yor-active) { color:rgba(255,255,255,0.72)!important; }
        .wolf-tab-green { color:rgba(200,160,64,0.5)!important; border-bottom-color:transparent!important; background:none!important; animation:none!important; }
        .wolf-tab-green-active { color:#fcf6ba!important; border-bottom-color:#c8a040!important; }
        .wolf-tab-green:hover:not(.wolf-tab-green-active) { color:#c8a040!important; }
        .wolf-tab-bw { color:rgba(255,255,255,0.35)!important; border-bottom-color:transparent!important; }
        .wolf-tab-bw-active { color:#ffffff!important; border-bottom-color:#ffffff!important; text-shadow:0 0 8px rgba(255,255,255,0.7)!important; }
        .wolf-tab-bw:hover:not(.wolf-tab-bw-active) { color:rgba(255,255,255,0.7)!important; }
        .wolf-tab-goldpremium { color:rgba(44,26,0,0.45)!important; border-bottom-color:transparent!important; background:none!important; animation:none!important; }
        .wolf-tab-goldpremium-active { color:#2c1a00!important; border-bottom-color:#7a5200!important; }
        .wolf-tab-goldpremium:hover:not(.wolf-tab-goldpremium-active) { color:#5d3a00!important; }
        @keyframes wolfGoldPremiumShimmer { 0%{background-position:0% 50%} 100%{background-position:200% 50%} }
        .wolf-menu-goldpremium-bg {
    background:linear-gradient(135deg,#bf953f 0%,#fcf6ba 45%,#b38728 100%)!important;
    background-size:100% 100%!important; animation:none!important;
    border:2px solid #5d4037!important;
    box-shadow:inset 0 1px 0 rgba(255,255,255,0.5), inset 0 -2px 6px rgba(70,50,10,0.35), 0 8px 24px rgba(0,0,0,0.5)!important;
}

        .wolf-menu-goldpremium-bg .wolf-row { background:none!important; border:none!important; box-shadow:none!important; padding:3px 0!important; margin-bottom:4px!important; }
        .wolf-menu-goldpremium-bg .wolf-row span { color:#2c1a00!important; }
        @keyframes wolfBWBorderShimmer { 0%{background-position:0% 50%} 100%{background-position:200% 50%} }
        .wolf-menu-bw-border {
            background:linear-gradient(#0a0a0a,#0a0a0a) padding-box,
                        linear-gradient(90deg,#ffffff,#555555,#cccccc,#222222,#ffffff,#555555,#cccccc) border-box!important;
            background-size:auto,300% auto!important; animation:wolfBWBorderShimmer 4s linear infinite!important;
        }
        .wolf-menu-yor-border {
            background:linear-gradient(#0a0a0a,#0a0a0a) padding-box,
                        linear-gradient(160deg,#222222 0%,#000000 50%,#111111 100%) border-box!important;
        }
        .wolf-tick{width:1em;height:1em;border-radius:50%;display:inline-flex;justify-content:center;align-items:center;position:relative;font-size:1em;vertical-align:middle;}
        .wolf-tick::after{content:"";width:.5em;height:.25em;border-left:.15em solid white;border-bottom:.15em solid white;transform:rotate(-45deg);}
        .wolf-tick-y{background:#ffd400;} .wolf-tick-g{background:#00c853;} .wolf-tick-b{background:#2962ff;}
        #wolf-invite-list::-webkit-scrollbar{width:6px;}
        #wolf-invite-list::-webkit-scrollbar-track{background:rgba(0,0,0,0.4);border-radius:3px;}
        #wolf-invite-list::-webkit-scrollbar-thumb{background:#c8a040;border-radius:3px;}
        .wolf-content-scroll::-webkit-scrollbar{width:5px;}
        .wolf-content-scroll::-webkit-scrollbar-track{background:rgba(0,0,0,0.3);border-radius:3px;}
        .wolf-content-scroll::-webkit-scrollbar-thumb{background:rgba(200,160,64,0.5);border-radius:3px;}
        #wolf-ctx-menu{position:fixed;background:#080808;border:1px solid #c8a040;border-radius:8px;padding:4px 0;min-width:160px;box-shadow:0 4px 16px rgba(0,0,0,0.9);z-index:10010;display:none;font-family:Arial,sans-serif;font-size:12px;}
        .wolf-ctx-item{padding:7px 14px;cursor:pointer;color:#fcf6ba;transition:background .15s;}
        .wolf-ctx-item:hover{background:#1a1a1a;color:#ffe566;}
        .wolf-ctx-item.danger{color:#ff6b6b;} .wolf-ctx-item.danger:hover{background:#1a0808;color:#ff8888;}
        .wolf-ctx-divider{height:1px;background:#c8a040;margin:3px 0;opacity:.3;}
        #wolf-rank-input-row{display:none;margin-bottom:8px;}
        #wolf-rank-input-row.visible{display:flex;flex-direction:column;gap:4px;}
        #wolf-rank-value{width:100%;box-sizing:border-box;padding:5px 6px;background:rgba(0,0,0,0.6);color:#fcf6ba;border:1px solid rgba(200,160,64,0.4);border-radius:6px;font-size:11px;font-family:monospace;resize:vertical;min-height:48px;}
        #wolf-rank-value:focus{outline:none;border-color:rgba(200,160,64,0.7);}
        .wolf-armory-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:5px;margin-bottom:5px;}

        /* ── IMPROVED GOLD BUTTONS ── */
        .wolf-weapon-btn {
    padding:7px 8px; border-radius:7px;
    border:1px solid rgba(200,160,64,0.42);
    background:linear-gradient(180deg,rgba(255,240,180,0.22) 0%,rgba(200,160,64,0.14) 45%,rgba(120,85,15,0.10) 100%);
            color:#fcf6ba; font-size:10px; font-weight:700; cursor:pointer; text-align:center; font-family:inherit;
            transition:background .15s ease,border-color .15s ease,color .15s ease,transform .1s ease,box-shadow .15s ease;
            white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
            box-shadow:inset 0 1px 0 rgba(255,220,80,0.13),0 1px 4px rgba(0,0,0,0.45);
        }
        .wolf-weapon-btn:hover {
            background:linear-gradient(180deg,rgba(220,175,64,0.30) 0%,rgba(180,130,20,0.12) 100%);
            border-color:rgba(255,215,80,0.68); color:#ffe566;
            box-shadow:inset 0 1px 0 rgba(255,230,100,0.22),0 0 10px rgba(200,160,64,0.28),0 1px 4px rgba(0,0,0,0.45);
        }
        .wolf-weapon-btn:active{transform:scale(0.96);box-shadow:inset 0 2px 5px rgba(0,0,0,0.45);}
        .wolf-weapon-btn.active-sel {
            background:linear-gradient(180deg,rgba(200,160,64,0.28) 0%,rgba(160,120,30,0.14) 100%);
            border-color:rgba(255,215,80,0.72); color:#ffe566;
            box-shadow:inset 0 0 10px rgba(200,160,64,0.25),0 0 12px rgba(200,160,64,0.22);
        }
        .wolf-skin-btn {
            padding:7px 8px; border-radius:7px;
            border:1px solid rgba(200,160,64,0.42);
            background:linear-gradient(180deg,rgba(200,160,64,0.15) 0%,rgba(160,120,30,0.06) 100%);
            color:#fcf6ba; font-size:10px; font-weight:700; cursor:pointer; text-align:center; font-family:inherit;
            transition:background .15s ease,border-color .15s ease,color .15s ease,transform .1s ease,box-shadow .15s ease;
            white-space:nowrap; overflow:hidden; text-overflow:ellipsis; display:block; width:100%; margin-bottom:4px;
            box-shadow:inset 0 1px 0 rgba(255,220,80,0.13),0 1px 4px rgba(0,0,0,0.45);
        }
        .wolf-skin-btn:hover {
            background:linear-gradient(180deg,rgba(220,175,64,0.30) 0%,rgba(180,130,20,0.12) 100%);
            border-color:rgba(255,215,80,0.68); color:#ffe566;
            box-shadow:inset 0 1px 0 rgba(255,230,100,0.22),0 0 10px rgba(200,160,64,0.28),0 1px 4px rgba(0,0,0,0.45);
        }
        .wolf-skin-btn:active{transform:scale(0.98);}
        .wolf-section-label{font-size:9px;font-weight:900;letter-spacing:0.14em;text-transform:uppercase;color:#c8a040;margin:9px 0 5px;display:flex;align-items:center;gap:7px;}
        .wolf-section-label::after{content:'';flex:1;height:1px;background:rgba(200,160,64,0.25);}

        /* ── IMPROVED GOLD TOGGLES ── */
        .wolf-toggle-switch{position:relative;width:38px;height:21px;flex-shrink:0;cursor:pointer;}
        .wolf-toggle-switch input{opacity:0;width:0;height:0;position:absolute;}
        .wolf-toggle-slider {
            position:absolute; inset:0; border-radius:21px;
            background:rgba(28,28,36,0.98);
            border:1.5px solid rgba(200,160,64,0.28);
            transition:background .22s ease,border-color .22s ease,box-shadow .22s ease;
            box-shadow:inset 0 1px 4px rgba(0,0,0,0.55),0 0 0 0.5px rgba(0,0,0,0.2);
        }
        .wolf-toggle-slider::before {
            content:''; position:absolute; width:17px; height:17px; border-radius:50%;
            background:linear-gradient(180deg,#c0c0c0 0%,#888 100%);
            top:1px; left:1px; box-shadow:0 1px 5px rgba(0,0,0,0.7);
            transition:transform .22s cubic-bezier(.4,0,.2,1),background .22s ease,box-shadow .22s ease;
        }
        .wolf-toggle-switch:hover .wolf-toggle-slider {
            border-color:rgba(200,160,64,0.50);
            box-shadow:inset 0 1px 4px rgba(0,0,0,0.45),0 0 5px rgba(200,160,64,0.18);
        }
        .wolf-toggle-switch input:checked + .wolf-toggle-slider {
            background:linear-gradient(135deg,rgba(225,180,60,0.90),rgba(175,125,25,0.80));
            border-color:rgba(255,218,80,0.70);
            box-shadow:inset 0 1px 3px rgba(0,0,0,0.3),0 0 10px rgba(200,160,64,0.38);
        }
        .wolf-toggle-switch input:checked + .wolf-toggle-slider::before {
    transform:translateX(17px);
    background:radial-gradient(circle at 30% 25%, #fffbe6 0%, #ffe050 30%, #c89010 65%, #6b4a00 100%);
    box-shadow:0 1px 6px rgba(0,0,0,0.65),0 0 5px rgba(255,220,80,0.55), inset 0 1px 1px rgba(255,255,255,0.6);
}
        .wolf-menu-hidden{display:none!important;} .wolf-gear-hidden{display:none!important;}
        #wolf-gear-btn:hover svg{transform:rotate(90deg);} #wolf-gear-btn svg{transition:transform 0.4s ease;}
        .wolf-profile-preview{padding:8px 10px;border-radius:8px;background:rgba(0,0,0,0.5);border:1px solid rgba(200,160,64,0.3);font-size:12px;font-weight:700;text-align:center;margin-bottom:8px;min-height:28px;word-break:break-all;}
        .wolf-phrase-btn {
            flex:1; padding:8px 10px; border-radius:7px;
            border:1px solid rgba(200,160,64,0.38);
            background:linear-gradient(180deg,rgba(200,160,64,0.13) 0%,rgba(160,120,30,0.05) 100%);
            color:#fcf6ba; font-size:11px; font-weight:700; cursor:pointer; text-align:left; font-family:inherit;
            transition:all .15s; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
            box-shadow:inset 0 1px 0 rgba(255,220,80,0.10),0 1px 3px rgba(0,0,0,0.4);
        }
        .wolf-phrase-btn:hover {
            background:linear-gradient(180deg,rgba(220,175,64,0.28) 0%,rgba(180,130,20,0.10) 100%);
            border-color:rgba(255,215,80,0.65); color:#ffe566;
            box-shadow:inset 0 1px 0 rgba(255,230,100,0.20),0 0 8px rgba(200,160,64,0.22);
        }
        .wolf-phrase-del{background:#1a0000;color:#f44;border:1px solid #400;padding:6px 10px;border-radius:6px;cursor:pointer;font-weight:900;font-size:13px;flex-shrink:0;transition:background .12s;}
        .wolf-phrase-del:hover{background:#300;}
        div>img[src*="youtube"],div>img[src=""],div>img:not([src]),div[style*="position:absolute"]>img:first-child,span+img{display:none!important;}
    `;
    (document.head||document.documentElement).appendChild(globalStyle);

    // =========================
    // CUSTOM RANK — WebSocket hook
    // =========================
    const _enc=new TextEncoder(), TYPE_STRING=0x07, RANK_KEY=_enc.encode('rank');
    function replaceStringField(u8,keyBytes,newValue) {
        const newBytes=_enc.encode(newValue), newLen=newBytes.length;
        for (let i=0;i<u8.length-keyBytes.length-2;i++) {
            if (u8[i]===TYPE_STRING&&u8[i+1]===keyBytes.length&&u8.slice(i+2,i+2+keyBytes.length).every((b,idx)=>b===keyBytes[idx])) {
                if (u8[i+2+keyBytes.length]!==TYPE_STRING) return u8;
                const oldLen=u8[i+3+keyBytes.length], valStart=i+4+keyBytes.length;
                const before=u8.slice(0,i+3+keyBytes.length), after=u8.slice(valStart+oldLen);
                const result=new Uint8Array(before.length+1+newLen+after.length);
                let p=0; result.set(before,p); p+=before.length; result[p++]=newLen; result.set(newBytes,p); p+=newLen; result.set(after,p);
                return result;
            }
        }
        return u8;
    }
    let _rankInputEl = null;
function getRankInputEl() {
    if (!_rankInputEl || !document.body.contains(_rankInputEl)) {
        _rankInputEl = document.getElementById('wolf-rank-value');
    }
    return _rankInputEl;
}
function applyRankMod(u8) {
    if (!states.customRank) return u8;
    const el = getRankInputEl();
    if (!el || !el.value) return u8;
    return replaceStringField(u8,RANK_KEY,el.value);
}
    const OrigWS=realWindow.WebSocket;
    function makeInterceptingWebSocket(url,protocols) {
        const ws=protocols!==undefined?new OrigWS(url,protocols):new OrigWS(url);
        const origSend=ws.send;
        ws.send=function(data){
            if (!states.customRank) return origSend.apply(this,arguments);
            let u8;
            if(typeof data==='string') u8=_enc.encode(data);
            else if(data instanceof ArrayBuffer) u8=new Uint8Array(data);
            else if(ArrayBuffer.isView(data)) u8=new Uint8Array(data.buffer.slice(data.byteOffset,data.byteOffset+data.byteLength));
            else return origSend.apply(this,arguments);
            origSend.call(ws,applyRankMod(u8));
        };
        return ws;
    }
    realWindow.WebSocket=function(url,protocols){return makeInterceptingWebSocket(url,protocols);};

    // =========================
    // CUSTOM NAME
    // =========================
    function handleCustomName(userName) {
        if (!states.customName||!userName) return;
        const check=setInterval(()=>{
            if(typeof window.unityInstance!=='undefined'&&window.unityInstance.SendMessage){
                clearInterval(check);
                try{window.unityInstance.SendMessage('MapScripts','SetNickname',userName);}catch(e){console.error('Custom name failed:',e);}
            }
        },500);
    }
    if (states.customName) handleCustomName(localStorage.getItem('wolf_custom_name_value')||'wolf_');

    // =========================
    // SKIN / WEAPON ASSET HOOKS
    // =========================
    function isSkinAsset(url){return typeof url==='string'&&url.includes('content/stream/characters/textures');}
    function makeSolidColorBlob(originalUrl,color){
        return new Promise((resolve,reject)=>{
            const img=new Image(); img.crossOrigin='anonymous';
            img.onload=()=>{const c=document.createElement('canvas');c.width=img.width;c.height=img.height;const ctx=c.getContext('2d');ctx.fillStyle=color;ctx.fillRect(0,0,img.width,img.height);c.toBlob(blob=>resolve(blob),'image/png');};
            img.onerror=reject; img.src=originalUrl;
        });
    }
    const weaponAssetPaths=['/StreamingAssets/awp','/StreamingAssets/usps','/StreamingAssets/deagle','/StreamingAssets/uzi','/StreamingAssets/pkm','/StreamingAssets/revolver','/StreamingAssets/mp5','/StreamingAssets/scar','/StreamingAssets/minigun','/StreamingAssets/famas','/StreamingAssets/vector1','/StreamingAssets/vector2','/StreamingAssets/vector3','/StreamingAssets/flamethrower','/StreamingAssets/kar98','/StreamingAssets/m4a4','/StreamingAssets/tec9','/StreamingAssets/beretta','/StreamingAssets/cz','/StreamingAssets/ak109','/StreamingAssets/p90','/StreamingAssets/thompson','/StreamingAssets/ump45','/StreamingAssets/xm1014','/StreamingAssets/lasergun1','/StreamingAssets/lasergun2','/StreamingAssets/grenade','/StreamingAssets/knife','/StreamingAssets/butterfly','/StreamingAssets/bayonet','/StreamingAssets/karambit'];
    function isWeaponAsset(url){return weaponAssetPaths.some(p=>url.includes(p));}
    const originalXHROpen=realWindow.XMLHttpRequest.prototype.open;
    realWindow.XMLHttpRequest.prototype.open=function(method,url,...args){
        if(states.weapon&&isWeaponAsset(url)){this.send=function(){if(this.onload)this.onload();};return;}
        if(states.hideSkins&&isSkinAsset(url)&&url.endsWith('.png')){this.send=function(){if(this.onload)this.onload();};return;}
        return originalXHROpen.apply(this,[method,url,...args]);
    };
    const originalFetch=realWindow.fetch;
    realWindow.fetch=function(url,options){
        const ru=typeof url==='string'?url:(url&&url.url?url.url:'');
        if(states.weapon&&isWeaponAsset(ru)) return Promise.resolve(new Response('',{status:200}));
        if(states.hideSkins&&isSkinAsset(ru)&&ru.endsWith('.png')) return makeSolidColorBlob(ru,skinColor).then(blob=>new Response(blob,{headers:{'Content-Type':'image/png'}}));
        return originalFetch.apply(this,arguments);
    };

    // =========================
    // WEBGL BLOCKER
    // =========================
    let glPatched=false;
    function patchWebGL(){
        if(glPatched)return; glPatched=true;
        const origGetContext=realWindow.HTMLCanvasElement.prototype.getContext;
        realWindow.HTMLCanvasElement.prototype.getContext=function(type,attrs){
            const gl=origGetContext.call(this,type,attrs);
            if(!gl||(type!=='webgl2'&&type!=='webgl'))return gl;
            function shouldBlock(count){
                if(!_hideAnyActive) return false;
                if(states.arms&&WEBGL_ARM_COUNTS.has(count))return true;
                if(states.weapon&&WEBGL_WEAPON_COUNTS.has(count))return true;
                if(states.hideMelee&&WEBGL_MELEE_COUNTS.has(count))return true;
                if(states.hideGameCross&&WEBGL_CROSS_COUNTS.has(count))return true;
                return false;
            }
            const origDE=gl.drawElements.bind(gl),origDEI=gl.drawElementsInstanced?.bind(gl),origDA=gl.drawArrays.bind(gl),origDAI=gl.drawArraysInstanced?.bind(gl);
            gl.drawElements=function(m,c,t,o){if(shouldBlock(c))return;return origDE(m,c,t,o);};
            if(origDEI) gl.drawElementsInstanced=function(m,c,t,o,p){if(shouldBlock(c))return;return origDEI(m,c,t,o,p);};
            gl.drawArrays=function(m,f,c){if(shouldBlock(c))return;return origDA(m,f,c);};
            if(origDAI) gl.drawArraysInstanced=function(m,f,c,i){if(shouldBlock(c))return;return origDAI(m,f,c,i);};
            return gl;
        };
    }
    patchWebGL();

    // =========================
    // MAP COLOR MOD — WebGL uniform hook
    // =========================
    const MAP_COLOR_TARGETS = {
        overlay:     { uniform:'_UnderlayColor',    settingsKey:'overlay' },
        fontColor:   { uniform:'_FaceColor',        settingsKey:'fontColor' },
        fontShadow:  { uniform:'_OutlineColor',     settingsKey:'fontShadow' },
        lightColor:  { uniform:'_LightColor0',      settingsKey:'lightColor' },
        weaponChams: { uniform:'_EmissionColor',    settingsKey:'weaponChams' },
        skyTop:      { uniform:'_SkyGradientTop',   settingsKey:'skyTop' },
        skyBottom:   { uniform:'_SkyGradientBottom',settingsKey:'skyBottom' },
        sunColor:    { uniform:'_SunDiscColor',     settingsKey:'sunColor' },
    };
    function mapColorHexToRgb01(hex){return [parseInt(hex.slice(1,3),16)/255,parseInt(hex.slice(3,5),16)/255,parseInt(hex.slice(5,7),16)/255];}
    function findMapColorTarget(uniformName){return Object.values(MAP_COLOR_TARGETS).find(t=>t.uniform===uniformName);}
    let mapColorHookInstalled=false;
    function installMapColorHook(){
        if(mapColorHookInstalled)return; mapColorHookInstalled=true;
        const proto=realWindow.WebGL2RenderingContext.prototype;
        const origGetUniformLocation=proto.getUniformLocation;
        proto.getUniformLocation=new Proxy(origGetUniformLocation,{
            apply(target,thisArg,args){
                const location=Reflect.apply(target,thisArg,args);
                if(location) location.wolfUniformName=args[1];
                return location;
            }
        });
        const origUniform3fv=proto.uniform3fv;
        proto.uniform3fv=new Proxy(origUniform3fv,{
            apply(target,thisArg,args){
                const[location]=args;
                if(states.mapColorMod&&location){
                    const match=findMapColorTarget(location.wolfUniformName);
                    if(match){
                        const[r,g,b]=mapColorHexToRgb01(mapColorSettings[match.settingsKey]);
                        return Reflect.apply(target,thisArg,[location,[r,g,b]]);
                    }
                }
                return Reflect.apply(target,thisArg,args);
            }
        });
        const origUniform4fv=proto.uniform4fv;
        proto.uniform4fv=new Proxy(origUniform4fv,{
            apply(target,thisArg,args){
                const[location]=args;
                if(states.mapColorMod&&location){
                    const match=findMapColorTarget(location.wolfUniformName);
                    if(match){
                        const[r,g,b]=mapColorHexToRgb01(mapColorSettings[match.settingsKey]);
                        return Reflect.apply(target,thisArg,[location,[r,g,b,1]]);
                    }
                }
                return Reflect.apply(target,thisArg,args);
            }
        });
    }
    installMapColorHook();

    // =========================
    // FOV CIRCLE
    // =========================
    let fovCanvas,fovCtx;
    function initFovCanvas(){
        if(fovCanvas)return;
        fovCanvas=document.createElement('canvas');
        fovCanvas.id='wolf-fov-overlay';
        Object.assign(fovCanvas.style,{position:'fixed',top:'0',left:'0',width:'100vw',height:'100vh',pointerEvents:'none',zIndex:'9998'});
        document.body.appendChild(fovCanvas); fovCtx=fovCanvas.getContext('2d');
        function resize(){fovCanvas.width=window.innerWidth;fovCanvas.height=window.innerHeight;}
        resize(); window.addEventListener('resize',resize); drawFovLoop();
    }
    function drawFovLoop(){
        requestAnimationFrame(drawFovLoop);
        if(!fovCtx)return;
        fovCtx.clearRect(0,0,fovCanvas.width,fovCanvas.height);
        if(!states.fovCircle)return;
        const cx=fovCanvas.width/2,cy=fovCanvas.height/2,minDim=Math.min(fovCanvas.width,fovCanvas.height);
        const radius=Math.max(1,(fovValue/100)*(minDim*0.48));
        fovCtx.beginPath();fovCtx.arc(cx,cy,radius,0,Math.PI*2);fovCtx.strokeStyle='rgba(15,40,110,0.3)';fovCtx.lineWidth=16;fovCtx.stroke();
        fovCtx.beginPath();fovCtx.arc(cx,cy,radius,0,Math.PI*2);fovCtx.strokeStyle='rgba(25,55,140,0.5)';fovCtx.lineWidth=7;fovCtx.stroke();
        fovCtx.beginPath();fovCtx.arc(cx,cy,radius,0,Math.PI*2);fovCtx.strokeStyle='rgba(30,65,160,0.95)';fovCtx.lineWidth=2.5;fovCtx.stroke();
        fovCtx.beginPath();fovCtx.arc(cx,cy,3,0,Math.PI*2);fovCtx.fillStyle='rgba(30,65,160,0.9)';fovCtx.fill();
    }

    // =========================
    // RAVE MODE
    // =========================
    let raveOverlay, raveHue=0;
    function initRaveOverlay(){
        if(raveOverlay)return;
        raveOverlay=document.createElement('div');
        raveOverlay.id='wolf-rave-overlay';
        Object.assign(raveOverlay.style,{
            position:'fixed',top:'0',left:'0',width:'100vw',height:'100vh',
            pointerEvents:'none',zIndex:'9997',
            display:'none',transition:'background .05s linear'
        });
        document.body.appendChild(raveOverlay);
    }
    function tickRaveMode(){
        if(!states.raveMode)return;
        raveHue=(raveHue+raveSpeed*1.2)%360;
        if(raveOverlay) raveOverlay.style.background=`hsla(${raveHue},100%,50%,0.4)`;
    }
    function startRaveMode(){initRaveOverlay();raveOverlay.style.display='block';}
    function stopRaveMode(){if(raveOverlay)raveOverlay.style.display='none';}

    // =========================
    // CROSSHAIR
    // =========================
    const styleEl=document.createElement('style');
    (document.head||document.documentElement).appendChild(styleEl);
    function updateGameCrosshairVisibility(){
        styleEl.innerHTML=states.hideGameCross?`.crosshair,#crosshair,[class*="crosshair"],[id*="crosshair"],#unity-container canvas+div,.game-crosshair,unity-canvas-crosshair{display:none!important;opacity:0!important;visibility:hidden!important;}`:'';
    }
    updateGameCrosshairVisibility();
    const crossContainer=document.createElement('div');
    Object.assign(crossContainer.style,{position:'fixed',top:'50%',left:'50%',zIndex:'10000',pointerEvents:'none',display:'none'});
    function applyCross(){
        crossContainer.innerHTML='';
        if(!states.crossVisible||states.customCross==='none'){crossContainer.style.display='none';return;}
        crossContainer.style.display='flex'; crossContainer.style.alignItems='center'; crossContainer.style.justifyContent='center';
        crossContainer.style.transform=`translate(-50%,-50%) scale(${states.crossScale})`;
        const color=states.crossColor,glowStyle=states.glow?`0 0 8px ${color}`:'none',opacity=states.crossTransparent?'0.7':'1.0';
        const blendMode=(states.crossTransparent&&!states.rainbow)?'difference':'normal';
        const base={position:'absolute',background:color,borderRadius:'1px',boxShadow:glowStyle,mixBlendMode:blendMode,opacity};
        if(states.customCross==='myrrr'){
            const h=document.createElement('div'),v=document.createElement('div');
            Object.assign(h.style,base,{width:'18px',height:'3px'}); Object.assign(v.style,base,{width:'3px',height:'18px'});
            if(states.rainbow){h.classList.add('wolf-rainbow-active');v.classList.add('wolf-rainbow-active');}
            crossContainer.append(h,v);
        } else if(states.customCross==='invert'){
            const s={position:'absolute',background:'transparent',zIndex:'999999',pointerEvents:'none',backdropFilter:'invert(100%)'};
            const h=document.createElement('div'),v=document.createElement('div');
            Object.assign(h.style,s,{width:'20px',height:'4px',left:'-10px',top:'-2px'});
            Object.assign(v.style,s,{width:'4px',height:'20px',left:'-2px',top:'-10px'});
            crossContainer.append(h,v);
        } else if(states.customCross==='dot'){
            const dot=document.createElement('div');
            Object.assign(dot.style,base,{width:'7px',height:'7px',borderRadius:'50%'});
            if(states.rainbow) dot.classList.add('wolf-rainbow-active');
            crossContainer.appendChild(dot);
        } else if(states.customCross==='shotgun'){
            const circle=document.createElement('div');
            Object.assign(circle.style,base,{width:'40px',height:'40px',border:`4px solid ${color}`,background:'transparent',borderRadius:'50%'});
            if(states.rainbow) circle.classList.add('wolf-rainbow-border-active');
            crossContainer.appendChild(circle);
        }
    }

    // =========================
    // MENU SKELETON
    // =========================
    const menu=document.createElement('div');
    menu.id='wolf-menu';
    Object.assign(menu.style,{
        position:'fixed',top:savedTop,left:savedLeft,width:'420px',borderRadius:'14px',
        border:'2px solid transparent',
        background:'linear-gradient(#0a0a0a,#0a0a0a) padding-box,linear-gradient(155deg,#fff9d0 0%,#d4af37 10%,#7a5a12 22%,#fff4b0 34%,#8a6a1f 46%,#ffe89a 58%,#5c3d00 72%,#d4af37 86%,#fff9d0 100%) border-box',
        zIndex:'10001',fontFamily:'Inter,Arial,sans-serif',textAlign:'center',userSelect:'none',
        boxShadow:'0 1px 0 rgba(255,255,255,0.06) inset,0 0 0 1px rgba(0,0,0,0.5),0 6px 0 #3a2800,0 7px 2px rgba(0,0,0,0.55),0 16px 44px rgba(0,0,0,0.8)',
        overflow:'hidden', willChange:'transform'
    });
    const menuBg=document.createElement('div');
    menuBg.id='wolf-menu-bg-layer';
    Object.assign(menuBg.style,{position:'absolute',inset:'0',zIndex:'0',background:'#0a0a0a'});
    const menuGloss=document.createElement('div');
    Object.assign(menuGloss.style,{position:'absolute',top:'0',left:'0',right:'0',height:'3px',zIndex:'1',background:'linear-gradient(90deg,transparent,rgba(200,160,64,0.6),transparent)',pointerEvents:'none'});
    menu.appendChild(menuBg); menu.appendChild(menuGloss);
    const menuInner=document.createElement('div');
    Object.assign(menuInner.style,{position:'relative',zIndex:'2'});
    menu.appendChild(menuInner);

    menuGloss.classList.add('wolf-metal-sweep');

    // HEADER
    const header=document.createElement('div');
    Object.assign(header.style,{padding:'11px 14px 10px',background:'rgba(200,160,64,0.07)',borderBottom:'1px solid rgba(200,160,64,0.22)',display:'flex',alignItems:'center',justifyContent:'space-between',cursor:'move',position:'relative'});
    const headerLeft=document.createElement('div');
    Object.assign(headerLeft.style,{display:'flex',alignItems:'center',gap:'8px'});
    const wolfImg=document.createElement('span');
    wolfImg.id='wolf-logo-img'; wolfImg.innerText='🐺';
    Object.assign(wolfImg.style,{fontSize:'22px',lineHeight:'1',flexShrink:'0',userSelect:'none'});
    const headerCenter=document.createElement('div');
    Object.assign(headerCenter.style,{position:'absolute',left:'50%',transform:'translateX(-50%)',display:'flex',flexDirection:'column',alignItems:'center',gap:'2px',pointerEvents:'none'});
    const titleEl=document.createElement('span');
    titleEl.innerText='Wolf_ Tools'; titleEl.classList.add('wolf-title-anim');
    Object.assign(titleEl.style,{fontSize:'13px',fontWeight:'900',letterSpacing:'0.09em',textTransform:'uppercase',lineHeight:'1'});
    const ytLink=document.createElement('a');
    ytLink.href='https://www.youtube.com/@grgZach'; ytLink.target='_blank'; ytLink.innerText='YOUTUBE';
    Object.assign(ytLink.style,{fontSize:'9px',color:'#cc0000',textDecoration:'underline',fontWeight:'700',letterSpacing:'0.05em',lineHeight:'1',cursor:'pointer',pointerEvents:'auto'});
    ytLink.addEventListener('mousedown',e=>e.stopPropagation());
    headerCenter.append(titleEl,ytLink); headerLeft.append(wolfImg);
    const badge=document.createElement('span');
badge.innerText='v3.0';
Object.assign(badge.style,{fontSize:'9px',fontWeight:'900',letterSpacing:'0.1em',textTransform:'uppercase',color:'#c8a040',padding:'3px 9px',borderRadius:'20px',background:'rgba(200,160,64,0.12)',border:'1px solid rgba(200,160,64,0.3)',marginLeft:'auto',flexShrink:'0'});
    const closeBtn=document.createElement('div');
closeBtn.id='wolf-close-btn';
closeBtn.title='Close menu';
closeBtn.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><line x1="4" y1="4" x2="20" y2="20"/><line x1="20" y1="4" x2="4" y2="20"/></svg>';
Object.assign(closeBtn.style,{
    display:'flex',alignItems:'center',justifyContent:'center',
    width:'22px',height:'22px',borderRadius:'50%',flexShrink:'0',marginLeft:'8px',
    background:'rgba(255,80,80,0.10)',color:'#ff5c5c',cursor:'pointer',
    transition:'background .15s ease,color .15s ease,transform .1s ease'
});
closeBtn.onmouseenter=()=>{closeBtn.style.background='#ff3b3b';closeBtn.style.color='#fff';closeBtn.style.transform='scale(1.08)';};
closeBtn.onmouseleave=()=>{closeBtn.style.background='rgba(255,80,80,0.10)';closeBtn.style.color='#ff5c5c';closeBtn.style.transform='scale(1)';};
closeBtn.onmousedown=e=>{e.stopPropagation();}; // don't trigger header drag
closeBtn.onclick=e=>{e.stopPropagation();toggleWolfMenu();};
header.append(headerLeft,headerCenter,badge,closeBtn);
    menuInner.appendChild(header);

    // TAB BAR
    const tabBar=document.createElement('div');
    Object.assign(tabBar.style,{display:'flex',background:'rgba(0,0,0,0.38)',borderBottom:'1px solid rgba(200,160,64,0.2)'});
    const TAB_NAMES=['Gameplay','Crosshairs','Status','Armory','Skins','Map Color','Settings','Info'];
    const tabBtns={}, tabDivs={};
    TAB_NAMES.forEach(name=>{
        const btn=document.createElement('button');
        btn.innerText=name;
        Object.assign(btn.style,{flex:'1',padding:'9px 2px 8px',fontSize:'9px',fontWeight:'900',letterSpacing:'0.06em',textTransform:'uppercase',color:'rgba(200,160,64,0.45)',background:'none',border:'none',borderBottom:'2.5px solid transparent',marginBottom:'-1px',cursor:'pointer',transition:'color .15s ease,border-color .15s ease,background .15s ease',fontFamily:'inherit'});
        btn.onmouseenter=()=>{if(!btn._active){btn.style.color='#c8a040';btn.style.background='rgba(200,160,64,0.05)';}};
        btn.onmouseleave=()=>{if(!btn._active){btn.style.color='rgba(200,160,64,0.45)';btn.style.background='none';}};
        tabBtns[name]=btn; tabBar.appendChild(btn);
    });
    menuInner.appendChild(tabBar);

    const contentWrap=document.createElement('div');
    Object.assign(contentWrap.style,{padding:'11px 12px 13px',maxHeight:'370px',overflowY:'auto'});
    contentWrap.classList.add('wolf-content-scroll');
    menuInner.appendChild(contentWrap);
    TAB_NAMES.forEach(name=>{const d=document.createElement('div');d.style.display='none';tabDivs[name]=d;contentWrap.appendChild(d);});

    function showTab(name){
        TAB_NAMES.forEach(n=>{
            tabDivs[n].style.display='none'; tabBtns[n]._active=false;
            tabBtns[n].classList.remove('wolf-tab-green-active','wolf-tab-yor-active','wolf-tab-bw-active','wolf-tab-aurora-active','wolf-tab-skyblue-active','wolf-tab-goldpremium-active');
            const p=THEME_PALETTE[titleStyle]||THEME_PALETTE.yor;
            tabBtns[n].style.color=p.accentFaint; tabBtns[n].style.borderBottomColor='transparent';
        });
        tabDivs[name].style.display='block'; tabBtns[name]._active=true;
        const p=THEME_PALETTE[titleStyle]||THEME_PALETTE.yor;
        tabBtns[name].style.color=p.text; tabBtns[name].style.borderBottomColor=p.accent;
        if(name==='Status') startInviteUpdater(); else stopInviteUpdater();
    }
    TAB_NAMES.forEach(name=>{tabBtns[name].onclick=()=>showTab(name);});
    showTab('Gameplay');

    const footer=document.createElement('div');
    Object.assign(footer.style,{borderTop:'1px solid rgba(200,160,64,0.15)',background:'rgba(0,0,0,0.3)',padding:'6px 12px 9px',textAlign:'center',fontSize:'10px',color:'rgba(200,160,64,0.4)',letterSpacing:'0.04em',fontWeight:'600'});
    function updateFooterHint(){footer.innerText="Toggle menu with '"+(menuKey===' '?'SPACE':menuKey.toUpperCase())+"'";}
    updateFooterHint();
    menuInner.appendChild(footer);

    // =========================
    // ROW CREATOR
    // =========================
    function createRow(text,key,storageKey){
        const row=document.createElement('div');
        row.className='wolf-row';
        Object.assign(row.style,{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'6px',padding:'6px 9px',borderRadius:'8px',background:'rgba(200,160,64,0.045)',transition:'background .15s'});
        row.onmouseenter=()=>{if(titleStyle!=='goldpremium')row.style.background='rgba(200,160,64,0.08)';};
        row.onmouseleave=()=>{if(titleStyle!=='goldpremium')row.style.background='rgba(200,160,64,0.045)';};
        let isActive=states[key]; if(key==='hideGameCross') isActive=!states[key];
        const toggleLabel=document.createElement('label'); toggleLabel.className='wolf-toggle-switch';
        const toggleInput=document.createElement('input'); toggleInput.type='checkbox'; toggleInput.checked=isActive;
        const toggleSlider=document.createElement('span'); toggleSlider.className='wolf-toggle-slider';
        toggleLabel.append(toggleInput,toggleSlider);
        const btn=document.createElement('button');
        const label=()=>{
            if(key==='glow') return 'Crosshair Glow';
            if(key==='offlineMode') return states[key]?'Disable Offline Mode':'Enable Offline Mode';
            if(key==='rainbowName') return states[key]?'Disable Rainbow Name':'Enable Rainbow Name';
            if(key==='rgb') return states[key]?'Disable RGB Crosshair':'Enable RGB Crosshair';
            if(key==='rainbowGunCamo') return states[key]?'Disable Rainbow Gun Camo':'Enable Rainbow Gun Camo';
            if(key==='blockInvites') return states[key]?'Disable Invite Blocker':'Enable Invite Blocker';
            if(key==='hideMelee') return states[key]?'Show Melee':'Hide Melee';
            if(key==='resetClass') return states[key]?`Disable Reset Class (${displayKeyName(resetClassKey)})`:`Enable Reset Class (${displayKeyName(resetClassKey)})`;
            if(key==='hideSkins') return states[key]?'Disable Hide Skins':'Enable Hide Skins';
            if(key==='customRank') return states[key]?'Disable Custom Rank':'Enable Custom Rank';
            if(key==='fovCircle') return states[key]?'Disable FOV Circle':'Enable FOV Circle';
            if(key==='customArms') return states[key]?'Disable Custom Arms':'Enable Custom Arms';
            if(key==='customProfile') return states[key]?'Disable Custom Profile':'Enable Custom Profile';
            if(key==='keyVisualizer') return states[key]?'Disable Key Visualizer':'Enable Key Visualizer';
            if(key==='pcStats') return states[key]?'Disable PC Stats':'Enable PC Stats';
            if(key==='airStrafe') return states[key]?'Disable Air Strafing':'Enable Air Strafing';
            if(key==='armsV2') return states[key]?'Disable Custom Arms V2':'Custom Arms V2';
            if(key==='gunGlow') return states[key]?'Disable Gun Glow':'Enable Gun Glow';
            if(key==='gunGlow') return states[key]?'Disable Gun Glow':'Enable Gun Glow';
            if(key==='raveMode') return states[key]?'Disable Rave Mode':'Enable Rave Mode';
            if(key==='hidePersonality') return states[key]?'Disable Hide Personality':'Enable Hide Personality';
            if(key==='mapColorMod') return states[key]?'Disable Map Color Mod':'Enable Map Color Mod';
            if(key==='chickenSpawner') return states[key]?'Disable Chicken Spawner':'Enable Chicken Spawner';
            return (states[key]?'Show ':'Hide ')+text;
        };
        btn.innerText=label();
        Object.assign(btn.style,{flex:'1',padding:'7px 10px',background:'linear-gradient(180deg,rgba(200,160,64,0.14) 0%,rgba(160,120,30,0.05) 100%)',color:'#fcf6ba',border:'1px solid rgba(200,160,64,0.30)',borderRadius:'8px',cursor:'pointer',fontWeight:'700',fontSize:'11px',marginRight:'7px',fontFamily:'inherit',textAlign:'left',boxShadow:'inset 0 1px 0 rgba(255,220,80,0.10),0 1px 3px rgba(0,0,0,0.4)',transition:'all .12s'});
        btn.onmouseenter=()=>{btn.style.background='linear-gradient(180deg,rgba(220,175,64,0.28) 0%,rgba(180,130,20,0.10) 100%)';btn.style.borderColor='rgba(255,215,80,0.62)';btn.style.color='#ffe566';btn.style.boxShadow='inset 0 1px 0 rgba(255,230,100,0.18),0 0 8px rgba(200,160,64,0.22),0 1px 3px rgba(0,0,0,0.4)';};
        btn.onmouseleave=()=>{btn.style.background='linear-gradient(180deg,rgba(200,160,64,0.14) 0%,rgba(160,120,30,0.05) 100%)';btn.style.borderColor='rgba(200,160,64,0.30)';btn.style.color=THEME_BODY_TEXT[titleStyle]||'#fcf6ba';btn.style.boxShadow='inset 0 1px 0 rgba(255,220,80,0.10),0 1px 3px rgba(0,0,0,0.4)';};
        const doToggle=()=>{
            states[key]=!states[key]; localStorage.setItem(storageKey,states[key]);
            if(key==='arms'||key==='weapon'||key==='hideMelee'||key==='hideGameCross') refreshHideFlag();
            if(key==='resetClass'){resetClassSelectGroup.style.display=states.resetClass?'block':'none';}
            if(key==='hideGameCross') updateGameCrosshairVisibility();
            if(key==='offlineMode') updateOfflineMode();
            if(key==='customRank') rankInputRow.classList.toggle('visible',states.customRank);
            if(key==='fovCircle'){if(states.fovCircle)initFovCanvas();fovSliderGroup.style.display=states.fovCircle?'block':'none';}
            if(key==='customArms'){syncArmUI();if(!states.customArms){armColor='#ffffff';localStorage.setItem('wolf_arm_color','#ffffff');}refreshCachedArmRgb();refreshWebglFlag();}
            if(key==='rainbowGunCamo'){refreshWebglFlag();startSharedRaf();}
            if(key==='armsV2'){armsV2Hint.style.display=states.armsV2?'block':'none';refreshWebglFlag();startSharedRaf();}
            if(key==='gunGlow'){refreshWebglFlag();startSharedRaf();}
            if(key==='rainbowName'){if(states[key]){const n=prompt('Enter your nickname for rainbow effect:','wolf_');handleRainbowName(n);}else{if(rainbowInterval)clearInterval(rainbowInterval);}}
            if(key==='customName'){if(states[key]){const n=prompt('Enter your custom nickname:',localStorage.getItem('wolf_custom_name_value')||'wolf_');if(n!==null&&n.trim()!==''){localStorage.setItem('wolf_custom_name_value',n);if(states.rainbowName){states.rainbowName=false;localStorage.setItem('wolf_rainbow_name','false');if(rainbowInterval)clearInterval(rainbowInterval);}{const _cn=(typeof customNameColor!=='undefined'&&customNameColor!=='#ffffff')?`<color=${customNameColor}>${n}</color>`:n;handleCustomName(_cn);}}else{states[key]=false;localStorage.setItem(storageKey,'false');}}}
            if(key==='hideSkins'){location.reload();return;}
            if(key==='weapon'){location.reload();return;}
            if(key==='rgb'){states.crossColor=states.rgb?'#ffffff':'#ff0000';applyCross();}
             if(key==='customProfile'){cpPanel.style.display=states[key]?'block':'none';if(states[key]){applyCustomProfile();}else{if(cpInterval){clearInterval(cpInterval);cpInterval=null;}localStorage.removeItem('playerNickname');}}
            if(key==='hidePersonality'){
                if(states[key]){
                    ['customProfile','customName','rainbowName'].forEach(k=>{
                        if(states[k]){states[k]=false;localStorage.setItem('wolf_'+(k==='customProfile'?'custom_profile':k==='customName'?'custom_name_toggle':'rainbow_name'),'false');}
                    });
                    if(cpInterval){clearInterval(cpInterval);cpInterval=null;}
                    if(rainbowInterval){clearInterval(rainbowInterval);rainbowInterval=null;}
                    cpPanel.style.display='none';
                    applyHidePersonality();
                } else {
                    if(hidePersonalityInterval){clearInterval(hidePersonalityInterval);hidePersonalityInterval=null;}
                    localStorage.removeItem('playerNickname');
                }
            }
            if(key==='keyVisualizer'){if(states[key])startKeyVisualizer();else stopKeyVisualizer();}
            if(key==='pcStats'){if(states[key])startPcStats();else stopPcStats();}
            if(key==='pcStats'){if(states[key])startPcStats();else stopPcStats();}
            if(key==='raveMode'){if(states[key])startRaveMode();else stopRaveMode();}
            if(key==='airStrafe'){if(states[key])startAirStrafe();else stopAirStrafe();}
            if(key==='chickenSpawner'){chickenSpawnGroup.style.display=states.chickenSpawner?'block':'none';}
            btn.innerText=label();
            const nowActive=key==='hideGameCross'?!states[key]:states[key];
            toggleInput.checked=nowActive; applyCross();
        };
        btn.onclick=doToggle; toggleInput.onchange=doToggle;
        row.append(btn,toggleLabel); return row;
    }
    function makeSectionLabel(text){const el=document.createElement('div');el.className='wolf-section-label';el.innerText=text;return el;}
    function makeColorRow(labelText,currentVal,onChange){
        const row=document.createElement('div'); row.className='wolf-row wolf-color-row';
        Object.assign(row.style,{display:'flex',justifyContent:'space-between',alignItems:'center',margin:'9px 0 5px',fontSize:'10px',fontWeight:'900',letterSpacing:'0.1em',textTransform:'uppercase'});
        const lbl=document.createElement('span'); lbl.innerText=labelText; lbl.className='wolf-color-row-label'; lbl.style.color='rgba(200,160,64,1.0)';
        const inp=document.createElement('input'); inp.type='color'; inp.value=currentVal;
        Object.assign(inp.style,{width:'46px',height:'24px',padding:'1px 2px',cursor:'pointer',border:'1px solid rgba(200,160,64,0.40)',borderRadius:'6px',background:'rgba(0,0,0,0.5)',boxShadow:'0 0 0 1px rgba(200,160,64,0.15)'});
        inp.oninput=()=>onChange(inp.value); row.append(lbl,inp); return row;
    }

    // =========================
    // AD BLOCKER
    // =========================

    (function(){
    const block=()=>document.querySelectorAll('[id^="kour-io"],[id^="nitro-kour"]').forEach(el=>el.remove());
    block();
    let _adBlockScheduled=false;
    const scheduleBlock=()=>{
        if(_adBlockScheduled)return;
        _adBlockScheduled=true;
        requestAnimationFrame(()=>{_adBlockScheduled=false;block();});
    };
    new MutationObserver(scheduleBlock).observe(document.documentElement,{childList:true,subtree:true});
})();

    // =========================
    // GAMEPLAY TAB
    // =========================
    const gpDiv=tabDivs['Gameplay'];
    gpDiv.append(makeSectionLabel('Visuals'),createRow('arms','arms','wolf_hide_arms'),createRow('weapon','weapon','wolf_hide_weapon'),createRow('melee','hideMelee','wolf_hide_melee'),makeSectionLabel('Cosmetics'),createRow('Rainbow Gun Camo','rainbowGunCamo','wolf_rainbow_gun_camo'));
    const rainbowSpeedRow=document.createElement('div'); rainbowSpeedRow.className='wolf-row';
    const rainbowSpeedText=document.createElement('span'); rainbowSpeedText.innerText=`Rainbow Speed: ${rainbowGunSpeed.toFixed(1)}`; rainbowSpeedText.style.color = THEME_BODY_TEXT[titleStyle] || '#FFB347';
    const rainbowSpeedSlider=document.createElement('input'); rainbowSpeedSlider.type='range'; rainbowSpeedSlider.min='0.1'; rainbowSpeedSlider.max='5'; rainbowSpeedSlider.step='0.1'; rainbowSpeedSlider.value=rainbowGunSpeed;
    rainbowSpeedSlider.oninput=()=>{rainbowGunSpeed=Number(rainbowSpeedSlider.value);localStorage.setItem('wolf_rainbow_gun_speed',rainbowGunSpeed);rainbowSpeedText.innerText=`Rainbow Speed: ${rainbowGunSpeed.toFixed(1)}`;};
    rainbowSpeedRow.append(rainbowSpeedText,rainbowSpeedSlider); gpDiv.appendChild(rainbowSpeedRow);
    gpDiv.appendChild(createRow('Gun Glow','gunGlow','wolf_gun_glow'));

    const glowModeSelect=document.createElement('select');
    Object.assign(glowModeSelect.style,{width:'100%',padding:'7px 28px 7px 10px',fontSize:'11px',fontWeight:'700',fontFamily:'inherit',color:'#fcf6ba',cursor:'pointer',appearance:'none',background:'#111',border:'1px solid rgba(200,160,64,0.40)',borderRadius:'8px',backgroundImage:'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'10\' height=\'6\'%3E%3Cpath d=\'M0 0l5 6 5-6z\' fill=\'%23c8a040\'/%3E%3C/svg%3E")',backgroundRepeat:'no-repeat',backgroundPosition:'right 9px center',marginBottom:'8px',boxShadow:'0 0 0 1px rgba(200,160,64,0.12)'});
    [['rainbow','Rainbow'],['inferno','Inferno'],['vaporwave','Vaporwave']].forEach(([v,label])=>{
        const o=document.createElement('option'); o.value=v; o.innerText=label; o.style.background='#111';
        if(gunGlowMode===v) o.selected=true;
        glowModeSelect.appendChild(o);
    });
    glowModeSelect.onchange=()=>{gunGlowMode=glowModeSelect.value;localStorage.setItem('wolf_gun_glow_mode',gunGlowMode);};
    gpDiv.appendChild(glowModeSelect);

    const glowBlendRow=document.createElement('div');
    Object.assign(glowBlendRow.style,{display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:'5px',marginBottom:'8px'});
    [['glow','Glow'],['paint','Paint']].forEach(([v,label])=>{
        const b=document.createElement('button'); b.innerText=label; b.dataset.blend=v;
        Object.assign(b.style,{padding:'6px 4px',borderRadius:'6px',border:'1px solid rgba(200,160,64,0.35)',background:gunGlowBlend===v?'rgba(200,160,64,0.28)':'rgba(200,160,64,0.06)',color:gunGlowBlend===v?'#ffe566':'#fcf6ba',fontSize:'10px',fontWeight:'800',letterSpacing:'0.05em',textTransform:'uppercase',cursor:'pointer',fontFamily:'inherit',transition:'all .12s'});
        b.onclick=()=>{
            gunGlowBlend=v; localStorage.setItem('wolf_gun_glow_blend',v);
            glowBlendRow.querySelectorAll('button').forEach(x=>{
                const a=x.dataset.blend===v;
                x.style.background=a?'rgba(200,160,64,0.28)':'rgba(200,160,64,0.06)';
                x.style.color=a?'#ffe566':'#fcf6ba';
            });
        };
        glowBlendRow.appendChild(b);
    });
    gpDiv.appendChild(glowBlendRow);
    gpDiv.append(createRow('Hide Skins','hideSkins','wolf_hide_skins'),makeColorRow('Skin Color',skinColor,v=>{skinColor=v;localStorage.setItem('wolf_skin_color',v);}));
    gpDiv.appendChild(makeSectionLabel('Arms'));
    gpDiv.appendChild(createRow('Custom Arms','customArms','wolf_custom_arms'));
    const armColorRow=makeColorRow('Arms Color',armColor,v=>{armColor=v;localStorage.setItem('wolf_arm_color',v);refreshCachedArmRgb();});
    armColorRow.style.display=states.customArms?'flex':'none'; gpDiv.appendChild(armColorRow);
    gpDiv.appendChild(createRow('Custom Arms V2','armsV2','wolf_arms_v2'));
    const armsV2Hint=document.createElement('div');
    Object.assign(armsV2Hint.style,{fontSize:'9px',color:'rgba(200,160,64,0.5)',fontWeight:'600',letterSpacing:'0.03em',lineHeight:'1.4',marginBottom:'6px',display:states.armsV2?'block':'none'});
    armsV2Hint.innerText='🌈 Neon rainbow wireframe overlay on arms'; gpDiv.appendChild(armsV2Hint);
    const armPresetLabel=document.createElement('div');
    Object.assign(armPresetLabel.style,{fontSize:'9px',color:'rgba(200,160,64,0.55)',fontWeight:'800',letterSpacing:'0.07em',textTransform:'uppercase',marginTop:'4px',marginBottom:'4px',display:states.customArms?'block':'none'});
    armPresetLabel.id='wolf-arm-preset-label'; armPresetLabel.innerText='Presets'; gpDiv.appendChild(armPresetLabel);
    const armPresets=[{name:'⬜ White',color:'#ffffff'},{name:'🟫 Brown',color:'#8B5C2A'},{name:'🟧 Tan',color:'#D2956A'},{name:'⬛ Black',color:'#1a1a1a'},{name:'🟥 Red',color:'#ff2222'},{name:'🟦 Blue',color:'#2255ff'},{name:'🟩 Green',color:'#22cc44'},{name:'🟨 Yellow',color:'#ffee00'}];
    const armPresetGrid=document.createElement('div'); armPresetGrid.id='wolf-arm-preset-grid'; armPresetGrid.style.display=states.customArms?'grid':'none';
    Object.assign(armPresetGrid.style,{gridTemplateColumns:'repeat(4,1fr)',gap:'4px',marginBottom:'6px'});
    armPresets.forEach(preset=>{
        const btn=document.createElement('button');
        btn.innerText=preset.name;
        Object.assign(btn.style,{padding:'5px 4px',borderRadius:'6px',border:'1px solid rgba(200,160,64,0.35)',background:'linear-gradient(180deg,rgba(200,160,64,0.12) 0%,rgba(160,120,30,0.04) 100%)',color:'#fcf6ba',fontSize:'9px',fontWeight:'700',cursor:'pointer',fontFamily:'inherit',transition:'all .12s',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',boxShadow:'inset 0 1px 0 rgba(255,220,80,0.08)'});
        btn.onmouseenter=()=>{btn.style.background='linear-gradient(180deg,rgba(220,175,64,0.28) 0%,rgba(180,130,20,0.10) 100%)';btn.style.borderColor='rgba(255,215,80,0.65)';btn.style.color='#ffe566';};
        btn.onmouseleave=()=>{btn.style.background='linear-gradient(180deg,rgba(200,160,64,0.12) 0%,rgba(160,120,30,0.04) 100%)';btn.style.borderColor='rgba(200,160,64,0.35)';btn.style.color=THEME_BODY_TEXT[titleStyle]||'#fcf6ba';};
        btn.onclick=()=>{armColor=preset.color;localStorage.setItem('wolf_arm_color',armColor);refreshCachedArmRgb();const inp=armColorRow.querySelector('input[type=color]');if(inp)inp.value=armColor;showToast('Arm color: '+preset.name.split(' ')[1],'info');};
        armPresetGrid.appendChild(btn);
    });
    gpDiv.appendChild(armPresetGrid);
    function syncArmUI(){armColorRow.style.display=states.customArms?'flex':'none';armPresetLabel.style.display=states.customArms?'block':'none';armPresetGrid.style.display=states.customArms?'grid':'none';}
    syncArmUI();
    gpDiv.appendChild(makeSectionLabel('Misc'));
    const resetClassRow=createRow('Reset Class','resetClass','wolf_reset_class');
    const resetClassRowBtn=resetClassRow.querySelector('button');
    gpDiv.appendChild(resetClassRow);
    const resetClassSelectGroup=document.createElement('div');
    resetClassSelectGroup.style.display=states.resetClass?'block':'none';
    Object.assign(resetClassSelectGroup.style,{marginBottom:'8px'});
    const resetClassLbl=document.createElement('div');
    Object.assign(resetClassLbl.style,{fontSize:'10px',fontWeight:'800',letterSpacing:'0.07em',textTransform:'uppercase',color:'rgba(200,160,64,0.7)',marginBottom:'4px',textAlign:'left'});
    resetClassLbl.innerText='Class to reset into';
    const resetClassSelect=document.createElement('select');
    Object.assign(resetClassSelect.style,{width:'100%',padding:'7px 28px 7px 10px',fontSize:'11px',fontWeight:'700',fontFamily:'inherit',color:'#fcf6ba',cursor:'pointer',appearance:'none',background:'#111',border:'1px solid rgba(200,160,64,0.40)',borderRadius:'8px',backgroundImage:'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'10\' height=\'6\'%3E%3Cpath d=\'M0 0l5 6 5-6z\' fill=\'%23c8a040\'/%3E%3C/svg%3E")',backgroundRepeat:'no-repeat',backgroundPosition:'right 9px center',boxShadow:'0 0 0 1px rgba(200,160,64,0.12)'});
    RESET_CLASS_OPTIONS.forEach(opt=>{
        const o=document.createElement('option'); o.value=opt.id; o.innerText=opt.name; o.style.background='#111';
        if(resetClassId===opt.id) o.selected=true;
        resetClassSelect.appendChild(o);
    });
    resetClassSelect.onchange=()=>{
        resetClassId=Number(resetClassSelect.value);
        localStorage.setItem('wolf_reset_class_id',resetClassId);
        const picked=RESET_CLASS_OPTIONS.find(o=>o.id===resetClassId);
        showToast('Reset class set to '+(picked?picked.name:resetClassId),'info');
    };

    // ── Custom Reset Class Keybind ──
    const resetClassKeyLbl=document.createElement('div');
    Object.assign(resetClassKeyLbl.style,{fontSize:'10px',fontWeight:'800',letterSpacing:'0.07em',textTransform:'uppercase',color:'rgba(200,160,64,0.7)',margin:'10px 0 4px',textAlign:'left'});
    resetClassKeyLbl.innerText='Reset Class Keybind';
    const resetClassKeyRow=document.createElement('div');
    Object.assign(resetClassKeyRow.style,{display:'flex',alignItems:'center',gap:'8px'});
    const resetClassKeyBtn=document.createElement('button'); resetClassKeyBtn.className='wolf-weapon-btn';
    Object.assign(resetClassKeyBtn.style,{flex:'1',padding:'9px 10px',background:'linear-gradient(180deg,rgba(200,160,64,0.14) 0%,rgba(160,120,30,0.05) 100%)',color:'#fcf6ba',border:'1px solid rgba(200,160,64,0.30)',borderRadius:'8px',cursor:'pointer',fontWeight:'800',fontSize:'12px',textAlign:'center',fontFamily:'inherit',letterSpacing:'0.04em',transition:'all .12s'});
    function refreshResetClassRowLabel(){resetClassRowBtn.innerText=(states.resetClass?'Disable Reset Class (':'Enable Reset Class (')+displayKeyName(resetClassKey)+')';}
    function renderResetClassKeyBtn(){resetClassKeyBtn.innerText='Current Key: '+displayKeyName(resetClassKey);}
    renderResetClassKeyBtn();
    let listeningForResetClassKey=false;
    function startListeningResetClass(){if(listeningForResetClassKey)return;listeningForResetClassKey=true;resetClassKeyBtn.innerText='Press any key…';resetClassKeyBtn.style.borderColor='rgba(200,160,64,0.7)';resetClassKeyBtn.style.background='linear-gradient(180deg,rgba(200,160,64,0.28) 0%,rgba(200,160,64,0.12) 100%)';}
    function stopListeningResetClass(cancelled){listeningForResetClassKey=false;resetClassKeyBtn.style.borderColor='rgba(200,160,64,0.30)';resetClassKeyBtn.style.background='linear-gradient(180deg,rgba(200,160,64,0.14) 0%,rgba(160,120,30,0.05) 100%)';renderResetClassKeyBtn();if(!cancelled)showToast('Reset Class key set to '+displayKeyName(resetClassKey),'success');}
    resetClassKeyBtn.onclick=()=>{if(listeningForResetClassKey){stopListeningResetClass(true);return;}startListeningResetClass();};
    const resetClassKeyResetBtn=document.createElement('button'); resetClassKeyResetBtn.innerText='Reset';
    Object.assign(resetClassKeyResetBtn.style,{padding:'9px 12px',borderRadius:'8px',border:'1px solid rgba(200,160,64,0.25)',background:'rgba(20,20,20,0.8)',color:'rgba(200,160,64,0.55)',font:'700 10px inherit',cursor:'pointer',transition:'all .12s'});
    resetClassKeyResetBtn.onmouseenter=()=>{resetClassKeyResetBtn.style.color='#ffe566';resetClassKeyResetBtn.style.borderColor='rgba(200,160,64,0.5)';};
    resetClassKeyResetBtn.onmouseleave=()=>{resetClassKeyResetBtn.style.color='rgba(200,160,64,0.55)';resetClassKeyResetBtn.style.borderColor='rgba(200,160,64,0.25)';};
    resetClassKeyResetBtn.onclick=()=>{
        if(listeningForResetClassKey)stopListeningResetClass(true);
        resetClassKey='g'; localStorage.setItem('wolf_reset_class_key',resetClassKey);
        renderResetClassKeyBtn(); refreshResetClassRowLabel();
        showToast('Reset Class key reset to G','info');
    };
    resetClassKeyRow.append(resetClassKeyBtn,resetClassKeyResetBtn);
    window.addEventListener('keydown',e=>{
        if(!listeningForResetClassKey)return;
        e.preventDefault();e.stopImmediatePropagation();
        const nk=e.key.toLowerCase();
        if(nk==='escape'){stopListeningResetClass(true);return;}
        if(nk===menuKey){showToast('That key is used for the menu toggle, pick another','error');return;}
        resetClassKey=nk; localStorage.setItem('wolf_reset_class_key',resetClassKey);
        renderResetClassKeyBtn(); refreshResetClassRowLabel();
        stopListeningResetClass(false);
    },true);

    resetClassSelectGroup.append(resetClassLbl,resetClassSelect,resetClassKeyLbl,resetClassKeyRow);
    gpDiv.appendChild(resetClassSelectGroup);
    gpDiv.append(createRow('FOV Circle','fovCircle','wolf_fov_circle'),createRow('Air Strafing','airStrafe','wolf_air_strafe'));
    const fovSliderGroup=document.createElement('div'); fovSliderGroup.style.display=states.fovCircle?'block':'none';
    const fovLabelRow=document.createElement('div');
    Object.assign(fovLabelRow.style,{display:'flex',justifyContent:'space-between',alignItems:'center',fontSize:'10px',fontWeight:'800',letterSpacing:'0.07em',textTransform:'uppercase',color:'rgba(200,160,64,0.7)',marginBottom:'3px'});
    const fovLbl=document.createElement('span'); fovLbl.innerText='FOV Radius'; fovLbl.style.color='#c8a040';
    const fovValDisp=document.createElement('span'); fovValDisp.innerText=fovValue; Object.assign(fovValDisp.style,{fontWeight:'900',color:'#fcf6ba'});
    fovLabelRow.append(fovLbl,fovValDisp);
    const fovSlider=document.createElement('input'); fovSlider.type='range'; fovSlider.min=1; fovSlider.max=100; fovSlider.value=fovValue;
    Object.assign(fovSlider.style,{width:'100%',accentColor:'#c8a040',height:'3px',cursor:'pointer'});
    fovSlider.oninput=()=>{fovValue=parseInt(fovSlider.value,10);fovValDisp.innerText=fovValue;localStorage.setItem('wolf_fov_value',fovValue);};
    fovSliderGroup.append(fovLabelRow,fovSlider); gpDiv.appendChild(fovSliderGroup);
    if(states.fovCircle) initFovCanvas();
    gpDiv.append(makeSectionLabel('Overlay'),createRow('Key Visualizer','keyVisualizer','wolf_key_visualizer'));
    gpDiv.appendChild(makeSectionLabel('Quick Phrases'));
    let savedPhrases=JSON.parse(getStored('wolf_phrases',JSON.stringify(["GG!","well played","xD","𝐄𝐀𝐒𝐘"])));
    const phraseContainer=document.createElement('div');
    Object.assign(phraseContainer.style,{display:'flex',flexDirection:'column',gap:'5px',marginTop:'4px'});
    gpDiv.appendChild(phraseContainer);
    const phraseAddBtn=document.createElement('button'); phraseAddBtn.innerText='+ Add Phrase';
    Object.assign(phraseAddBtn.style,{width:'100%',padding:'7px 10px',marginTop:'4px',borderRadius:'7px',border:'1px solid rgba(100,200,100,0.35)',background:'linear-gradient(180deg,rgba(60,140,60,0.15) 0%,rgba(30,80,30,0.08) 100%)',color:'#7fff7f',font:'700 11px inherit',cursor:'pointer',transition:'all .12s'});
    phraseAddBtn.onmouseenter=()=>{phraseAddBtn.style.background='rgba(60,140,60,0.25)';};
    phraseAddBtn.onmouseleave=()=>{phraseAddBtn.style.background='linear-gradient(180deg,rgba(60,140,60,0.15) 0%,rgba(30,80,30,0.08) 100%)';};
    gpDiv.appendChild(phraseAddBtn);
    const phraseClearBtn=document.createElement('button'); phraseClearBtn.innerText='Clear All Phrases';
    Object.assign(phraseClearBtn.style,{width:'100%',padding:'5px 10px',marginTop:'3px',borderRadius:'7px',border:'1px solid rgba(200,160,64,0.2)',background:'rgba(20,20,20,0.8)',color:'rgba(200,160,64,0.4)',font:'700 9px inherit',cursor:'pointer',transition:'all .12s'});
    phraseClearBtn.onmouseenter=()=>{phraseClearBtn.style.color='#ff6b6b';phraseClearBtn.style.borderColor='#500';};
    phraseClearBtn.onmouseleave=()=>{phraseClearBtn.style.color='rgba(200,160,64,0.4)';phraseClearBtn.style.borderColor='rgba(200,160,64,0.2)';};
    gpDiv.appendChild(phraseClearBtn);
    function renderPhrases(){
        phraseContainer.innerHTML='';
        savedPhrases.forEach((phrase,i)=>{
            const row=document.createElement('div'); Object.assign(row.style,{display:'flex',gap:'5px',alignItems:'center'});
            const copyBtn=document.createElement('button'); copyBtn.className='wolf-phrase-btn'; copyBtn.innerText=phrase;
            copyBtn.onclick=()=>{navigator.clipboard.writeText('ㅤ'+phrase);const orig=copyBtn.innerText;copyBtn.innerText='✓ COPIED!';setTimeout(()=>{copyBtn.innerText=orig;},800);};
            const delBtn=document.createElement('button'); delBtn.className='wolf-phrase-del'; delBtn.innerText='✕';
            delBtn.onclick=()=>{savedPhrases.splice(i,1);localStorage.setItem('wolf_phrases',JSON.stringify(savedPhrases));renderPhrases();};
            row.append(copyBtn,delBtn); phraseContainer.appendChild(row);
        });
    }
    phraseAddBtn.onclick=()=>{const p=prompt('New phrase:');if(p&&p.trim()){savedPhrases.push(p.trim());localStorage.setItem('wolf_phrases',JSON.stringify(savedPhrases));renderPhrases();}};
    phraseClearBtn.onclick=()=>{if(!confirm('Clear all phrases?'))return;savedPhrases=[];localStorage.setItem('wolf_phrases',JSON.stringify(savedPhrases));renderPhrases();};
    renderPhrases();

    // ── Chicken Spawner ──
    gpDiv.appendChild(makeSectionLabel('Spawner'));
    gpDiv.appendChild(createRow('Chicken Spawner','chickenSpawner','wolf_chicken_spawn'));
    const chickenSpawnGroup=document.createElement('div');
    chickenSpawnGroup.style.display=states.chickenSpawner?'block':'none';
    Object.assign(chickenSpawnGroup.style,{marginBottom:'8px'});
    const chickenCountLbl=document.createElement('div');
    Object.assign(chickenCountLbl.style,{fontSize:'10px',fontWeight:'800',letterSpacing:'0.07em',textTransform:'uppercase',color:'rgba(200,160,64,0.7)',marginBottom:'4px',textAlign:'left'});
    chickenCountLbl.innerText='Chickens per map';
    const chickenCountInput=document.createElement('input');
    chickenCountInput.type='number'; chickenCountInput.min='1'; chickenCountInput.step='1'; chickenCountInput.placeholder='e.g. 1, 50, 250…';
    chickenCountInput.value=localStorage.getItem('wolf_chicken_count')||'1';
    Object.assign(chickenCountInput.style,{width:'100%',boxSizing:'border-box',padding:'7px 9px',background:'rgba(0,0,0,0.6)',color:'#fcf6ba',border:'1px solid rgba(200,160,64,0.40)',borderRadius:'8px',fontSize:'12px',fontFamily:'inherit',outline:'none',marginBottom:'8px'});
    ['keydown','keypress','keyup','beforeinput','input'].forEach(ev=>chickenCountInput.addEventListener(ev,e=>e.stopImmediatePropagation(),true));
    chickenCountInput.addEventListener('focus',()=>chickenCountInput.style.borderColor='rgba(200,160,64,0.7)');
    chickenCountInput.addEventListener('blur',()=>chickenCountInput.style.borderColor='rgba(200,160,64,0.40)');
    chickenCountInput.oninput=()=>{
        let v=parseInt(chickenCountInput.value,10);
        if(isNaN(v)||v<1) v=1;
        localStorage.setItem('wolf_chicken_count',v);
    };
    const chickenSpawnBtn=document.createElement('button');
    chickenSpawnBtn.innerText='🐔 Spawn Chickens';
    Object.assign(chickenSpawnBtn.style,{width:'100%',padding:'8px',borderRadius:'7px',border:'1px solid rgba(200,160,64,0.5)',background:'linear-gradient(180deg,rgba(200,160,64,0.22) 0%,rgba(200,160,64,0.08) 100%)',color:'#fcf6ba',font:'700 11px inherit',cursor:'pointer',transition:'all .15s'});
    chickenSpawnBtn.onmouseenter=()=>{chickenSpawnBtn.style.background='rgba(200,160,64,0.32)';chickenSpawnBtn.style.color='#ffe566';};
    chickenSpawnBtn.onmouseleave=()=>{chickenSpawnBtn.style.background='linear-gradient(180deg,rgba(200,160,64,0.22) 0%,rgba(200,160,64,0.08) 100%)';chickenSpawnBtn.style.color=THEME_BODY_TEXT[titleStyle]||'#fcf6ba';};
    chickenSpawnBtn.onclick=()=>{
        const game=(typeof unityInstance!=='undefined'&&unityInstance)
            ||(typeof unsafeWindow!=='undefined'&&unsafeWindow.unityInstance)
            ||window.unityInstance;
        if(!game||typeof game.SendMessage!=='function'){showToast('Game not ready yet','error');return;}
        let count=parseInt(chickenCountInput.value,10);
        if(isNaN(count)||count<1) count=1;
        localStorage.setItem('wolf_chicken_count',count);
        for(let idx=0;idx<11;idx++){
            for(let i=0;i<count;i++){
                game.SendMessage('MapScripts','SpawnChicken',idx);
            }
        }
        showToast(`Spawned ${count*11} chickens!`,'success');
    };
    chickenSpawnGroup.append(chickenCountLbl,chickenCountInput,chickenSpawnBtn);
    gpDiv.appendChild(chickenSpawnGroup);

    // ── Rave Mode ──
    gpDiv.appendChild(makeSectionLabel('Party'));
    gpDiv.appendChild(createRow('Rave Mode','raveMode','wolf_rave_mode'));
    const raveSpeedRow=document.createElement('div'); raveSpeedRow.className='wolf-row';
    const raveSpeedText=document.createElement('span'); raveSpeedText.innerText=`Rave Speed: ${raveSpeed.toFixed(1)}`; raveSpeedText.style.color = THEME_BODY_TEXT[titleStyle] || '#fcf6ba';
    const raveSpeedSlider=document.createElement('input'); raveSpeedSlider.type='range'; raveSpeedSlider.min='0.2'; raveSpeedSlider.max='5'; raveSpeedSlider.step='0.1'; raveSpeedSlider.value=raveSpeed;
    Object.assign(raveSpeedSlider.style,{width:'100%',accentColor:'#c8a040',height:'3px',cursor:'pointer'});
    raveSpeedSlider.oninput=()=>{raveSpeed=Number(raveSpeedSlider.value);localStorage.setItem('wolf_rave_speed',raveSpeed);raveSpeedText.innerText=`Rave Speed: ${raveSpeed.toFixed(1)}`;};
    raveSpeedRow.append(raveSpeedText,raveSpeedSlider); gpDiv.appendChild(raveSpeedRow);

    // =========================
    // SCOPE DATA
    // =========================
    const SCOPE_LIST = [
        {name:'Scope 1',      url:'https://i.imgur.com/War3c9fg.jpg'},
        {name:'Scope 2',      url:'https://art.pixilart.com/1120b202cd3ff29.png'},
        {name:'Scope 3',      url:'https://i.imgur.com/Oi36Fc0.png'},
        {name:'Scope 4',      url:'https://i.imgur.com/wZ1DGLN.png'},
        {name:'Scope 5',      url:'https://i.imgur.com/HKDotWT.jpg'},
        {name:'Scope 6',      url:'https://i.redd.it/9hpat5kb1ox21.png'},
        {name:'Scope 7',      url:'https://i.imgur.com/SDujBy5g.jpg'},
        {name:'Scope 8',      url:'https://cdn.discordapp.com/attachments/1224140110778601512/1497598074606850251/scope.png?ex=6a539de5&is=6a524c65&hm=66d80fd8e1c83c8c795de60cd7770cda41d6e5ef1693a162ee54537788a1c736&'},
        {name:'Scope 9',      url:'https://i.ibb.co/QM99D4R/THing.png'},
        {name:'Scope 10',     url:'https://i.imgur.com/9wjXyx9.png'},
        {name:'Grey Scope',   url:'https://cdn.discordapp.com/attachments/1507740414235639978/1507760566020735096/grey_scope.png?ex=6a53ac73&is=6a525af3&hm=ec28d731e2f0d68a7514032a4528e6a1672acda12a08ca0e012bdc7d4042891b&'},
        {name:'Half Scope',   url:'https://cdn.discordapp.com/attachments/1507740414235639978/1507760198826070116/HalfScope_2.png?ex=6a53ac1c&is=6a525a9c&hm=626357419dc4f834cf2c78e72f940264a52c387812ec43b02939538da32e827a&'},
        {name:'RIP Scope',    url:'https://i0.wp.com//i.redd.it/iwuys4vcbn831.png'},
        {name:'Anime Scope',  url:'https://i.redd.it/apparently-alot-of-people-really-like-my-scopes-so-heres-v0-wnkar0ztz1981.png?width=900&format=png&auto=webp&s=d9634e7d7d4638b903214668bc955acbda3c05b7'},
        {name:'Hell Scope',   url:'https://cdn.discordapp.com/attachments/1507740414235639978/1507760652414877736/ezgif-4-839dfec0b6.webp?ex=6a53ac88&is=6a525b08&hm=7a2c0795aea693f24240aa728028cb3aa3afd758d17d2fe079e4b0c2888c179f&'},
    ];

    // =========================
    // CROSSHAIRS TAB
    // =========================
    const crossDiv=tabDivs['Crosshairs'];
    crossDiv.append(makeSectionLabel('Display'),createRow('crosshair','crossVisible','wolf_cross_visible'),createRow('glow','glow','wolf_glow'),createRow('game crosshair','hideGameCross','wolf_hide_game_cross'),createRow('crosshair opacity','crossTransparent','wolf_cross_transparent'),createRow('rainbow crosshair','rainbow','wolf_cross_rainbow'),makeSectionLabel('Customize'));
    const sel=document.createElement('select');
    Object.assign(sel.style,{width:'100%',padding:'7px 28px 7px 10px',fontSize:'11px',fontWeight:'700',fontFamily:'inherit',color:'#fcf6ba',cursor:'pointer',appearance:'none',background:'#111',border:'1px solid rgba(200,160,64,0.40)',borderRadius:'8px',backgroundImage:'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'10\' height=\'6\'%3E%3Cpath d=\'M0 0l5 6 5-6z\' fill=\'%23c8a040\'/%3E%3C/svg%3E")',backgroundRepeat:'no-repeat',backgroundPosition:'right 9px center',marginBottom:'6px',boxShadow:'0 0 0 1px rgba(200,160,64,0.12)'});
    ['myrrr','invert','dot','shotgun','none'].forEach(v=>{const o=document.createElement('option');o.value=v;o.innerText=v;o.style.background='#111';if(states.customCross===v)o.selected=true;sel.appendChild(o);});
    sel.onchange=()=>{states.customCross=sel.value;localStorage.setItem('wolf_custom_cross',sel.value);applyCross();};
    crossDiv.appendChild(sel);
    crossDiv.appendChild(makeColorRow('Crosshair Color',states.crossColor,v=>{states.crossColor=v;localStorage.setItem('wolf_cross_color',v);applyCross();}));
    const scaleRow=document.createElement('div');
    Object.assign(scaleRow.style,{display:'flex',justifyContent:'space-between',alignItems:'center',margin:'8px 0 4px',fontSize:'10px',fontWeight:'800',letterSpacing:'0.07em',textTransform:'uppercase',color:'rgba(200,160,64,0.7)'});
    const scaleLabel=document.createElement('span'); scaleLabel.innerText='Scale'; scaleLabel.style.color='#c8a040';
    const scaleValDisp=document.createElement('span'); scaleValDisp.innerText=parseFloat(states.crossScale).toFixed(2); Object.assign(scaleValDisp.style,{fontWeight:'900',color:'#fcf6ba'});
    scaleRow.append(scaleLabel,scaleValDisp);
    const scaleInput=document.createElement('input'); scaleInput.type='range'; scaleInput.min=0.2; scaleInput.max=2; scaleInput.step=0.05; scaleInput.value=states.crossScale;
    Object.assign(scaleInput.style,{width:'100%',accentColor:'#c8a040',height:'3px',cursor:'pointer',marginTop:'4px'});
    scaleInput.oninput=()=>{states.crossScale=scaleInput.value;scaleValDisp.innerText=parseFloat(scaleInput.value).toFixed(2);localStorage.setItem('wolf_cross_scale',scaleInput.value);applyCross();};
    crossDiv.append(scaleRow,scaleInput);

    // ── SCOPES ──
    crossDiv.appendChild(makeSectionLabel('Scopes'));

    const scopeGrid = document.createElement('div');
    Object.assign(scopeGrid.style, {
        display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:'6px', marginBottom:'8px'
    });

    SCOPE_LIST.forEach(function(scope) {
        const wrap = document.createElement('div');
        Object.assign(wrap.style, {
            position:'relative', borderRadius:'7px', overflow:'hidden',
            border:'2px solid rgba(200,160,64,0.25)',
            cursor:'pointer', aspectRatio:'1/1',
            background:'rgba(0,0,0,0.4)',
            transition:'border-color 0.12s, box-shadow 0.12s, transform 0.1s',
        });

        const img = document.createElement('img');
        img.src = scope.url;
        img.alt = scope.name;
        img.loading = 'lazy';
        Object.assign(img.style, {
            width:'100%', height:'100%', objectFit:'cover', display:'block', borderRadius:'5px',
        });
        img.onerror = function() { wrap.style.background = 'rgba(0,0,0,0.6)'; };

        const label = document.createElement('div');
        Object.assign(label.style, {
            position:'absolute', bottom:'0', left:'0', right:'0',
            background:'rgba(0,0,0,0.6)', color:'#fcf6ba',
            fontSize:'8px', fontWeight:'700', textAlign:'center',
            padding:'2px 3px', letterSpacing:'0.03em', pointerEvents:'none',
        });
        label.innerText = scope.name;

        wrap.append(img, label);

        wrap.onclick = function() {
            navigator.clipboard.writeText(scope.url).then(function() {
                showToast('URL copied! Paste it in game settings.', 'success');
                // Flash border to confirm
                wrap.style.border = '2px solid rgba(0,200,80,0.9)';
                wrap.style.boxShadow = '0 0 12px rgba(0,200,80,0.4)';
                setTimeout(function() {
                    wrap.style.border = '2px solid rgba(200,160,64,0.25)';
                    wrap.style.boxShadow = 'none';
                }, 1000);
            }).catch(function() {
                showToast('Copy failed — try again', 'error');
            });
        };

        wrap.onmouseenter = function() {
            wrap.style.borderColor = 'rgba(200,160,64,0.7)';
            wrap.style.boxShadow = '0 0 8px rgba(200,160,64,0.3)';
            wrap.style.transform = 'scale(1.04)';
        };
        wrap.onmouseleave = function() {
            wrap.style.borderColor = 'rgba(200,160,64,0.25)';
            wrap.style.boxShadow = 'none';
            wrap.style.transform = 'scale(1)';
        };

        scopeGrid.appendChild(wrap);
    });

    crossDiv.appendChild(scopeGrid);

    // Instruction text
    const scopeHint = document.createElement('div');
    scopeHint.innerText = '🖱 Press any scope you like so you can copy the URL, then go to Settings in the game section in Scopes to paste the link';
    Object.assign(scopeHint.style, {
        fontSize:'9px', color:'rgba(200,160,64,0.65)', fontWeight:'600',
        lineHeight:'1.5', letterSpacing:'0.02em', textAlign:'center',
        padding:'6px 8px', borderRadius:'7px',
        background:'rgba(200,160,64,0.06)',
        border:'1px solid rgba(200,160,64,0.15)',
        marginBottom:'4px',
    });
    crossDiv.appendChild(scopeHint);

    // =========================
    // STATUS TAB
    // =========================
    let customNameColor=getStored('wolf_custom_name_color','#ffffff'); // name color (declared early for closure capture)
    const statusDiv=tabDivs['Status'];
    statusDiv.append(makeSectionLabel('Identity'),createRow('Offline Mode','offlineMode','wolf_offline_mode'),createRow('Rainbow Name','rainbowName','wolf_rainbow_name'));
    // ── Name Rainbow Speed (under Rainbow Name) ──
    const rainbowNameSpeedRow=document.createElement('div'); rainbowNameSpeedRow.className='wolf-row';
    const rainbowNameSpeedText=document.createElement('span');
    rainbowNameSpeedText.innerText=`Name Rainbow Speed: ${rainbowNameSpeed.toFixed(1)}`;
    rainbowNameSpeedText.style.color=THEME_BODY_TEXT[titleStyle]||'#fcf6ba';
    const rainbowNameSpeedSlider=document.createElement('input');
    rainbowNameSpeedSlider.type='range'; rainbowNameSpeedSlider.min='1'; rainbowNameSpeedSlider.max='30'; rainbowNameSpeedSlider.step='0.5'; rainbowNameSpeedSlider.value=rainbowNameSpeed; Object.assign(rainbowNameSpeedSlider.style,{width:'100%',accentColor:'#c8a040',height:'3px',cursor:'pointer'});
    rainbowNameSpeedSlider.oninput=()=>{
        rainbowNameSpeed=Number(rainbowNameSpeedSlider.value);
        localStorage.setItem('wolf_rainbow_name_speed',rainbowNameSpeed);
        rainbowNameSpeedText.innerText=`Name Rainbow Speed: ${rainbowNameSpeed.toFixed(1)}`;
    };
    rainbowNameSpeedRow.append(rainbowNameSpeedText,rainbowNameSpeedSlider);
    statusDiv.appendChild(rainbowNameSpeedRow);
    statusDiv.append(createRow('Custom Name','customName','wolf_custom_name_toggle'),createRow('Custom Rank','customRank','wolf_custom_rank'));
    const nameColorRow=document.createElement('div');
    Object.assign(nameColorRow.style,{display:'flex',justifyContent:'space-between',alignItems:'center',margin:'0 0 6px',padding:'6px 9px',borderRadius:'8px',background:'rgba(200,160,64,0.045)'});
    const nameColorLbl=document.createElement('span');
    nameColorLbl.innerText='Custom Name Color';
    Object.assign(nameColorLbl.style,{fontSize:'11px',fontWeight:'700',color:THEME_BODY_TEXT[titleStyle]||'#fcf6ba'});
    const nameColorPicker=document.createElement('input');
    nameColorPicker.type='color'; nameColorPicker.value=customNameColor;
    Object.assign(nameColorPicker.style,{width:'46px',height:'24px',padding:'1px 2px',cursor:'pointer',border:'1px solid rgba(200,160,64,0.40)',borderRadius:'6px',background:'rgba(0,0,0,0.5)',boxShadow:'0 0 0 1px rgba(200,160,64,0.15)'});
    nameColorPicker.oninput=()=>{
        customNameColor=nameColorPicker.value;
        localStorage.setItem('wolf_custom_name_color',customNameColor);
        if(states.customName){
            const rawName=localStorage.getItem('wolf_custom_name_value')||'wolf_';
            const coloredName=`<color=${customNameColor}>${rawName}</color>`;
            handleCustomName(coloredName);
        }
    };
    nameColorRow.append(nameColorLbl,nameColorPicker);
    statusDiv.appendChild(nameColorRow);

    const rankInputRow=document.createElement('div'); rankInputRow.id='wolf-rank-input-row';
    if(states.customRank) rankInputRow.classList.add('visible');
    const rankLabel=document.createElement('div');
    Object.assign(rankLabel.style,{fontSize:'10px',color:'rgba(200,160,64,0.7)',fontWeight:'800',marginBottom:'3px',textAlign:'left',letterSpacing:'0.07em',textTransform:'uppercase'});
    rankLabel.innerText='Rank text:';
    const rankValueInput=document.createElement('textarea'); rankValueInput.id='wolf-rank-value'; rankValueInput.rows=2;
    rankValueInput.value=localStorage.getItem('wolf_custom_rank_value')||''; rankValueInput.placeholder='e.g. <#FF8C00>Top Player';
    ['keydown','keypress','keyup','beforeinput','input'].forEach(ev=>rankValueInput.addEventListener(ev,e=>e.stopImmediatePropagation(),true));
    rankValueInput.oninput=()=>localStorage.setItem('wolf_custom_rank_value',rankValueInput.value);
    rankInputRow.append(rankLabel,rankValueInput); statusDiv.appendChild(rankInputRow);
    // ── Name Color picker (under Custom Name) ──
    Object.assign(nameColorPicker.style,{width:'46px',height:'24px',padding:'1px 2px',cursor:'pointer',border:'1px solid rgba(200,160,64,0.40)',borderRadius:'6px',background:'rgba(0,0,0,0.5)',boxShadow:'0 0 0 1px rgba(200,160,64,0.15)'});
    nameColorPicker.oninput=()=>{
        customNameColor=nameColorPicker.value;
        localStorage.setItem('wolf_custom_name_color',customNameColor);
        if(states.customName){
            const rawName=localStorage.getItem('wolf_custom_name_value')||'wolf_';
            handleCustomName(`<color=${customNameColor}>${rawName}</color>`);
        }
    };
    nameColorRow.append(nameColorLbl,nameColorPicker);
    statusDiv.appendChild(nameColorRow);
    statusDiv.appendChild(makeSectionLabel('Visual Profile'));
    statusDiv.appendChild(createRow('Custom Profile','customProfile','wolf_custom_profile'));
    statusDiv.appendChild(createRow('Hide Personality','hidePersonality','wolf_hide_personality'));
    const cpPanel=document.createElement('div');
    Object.assign(cpPanel.style,{display:states.customProfile?'block':'none',marginTop:'6px',padding:'10px',borderRadius:'9px',background:'rgba(0,0,0,0.5)',border:'1px solid rgba(200,160,64,0.25)'});
    const cpPreview=document.createElement('div'); cpPreview.className='wolf-profile-preview'; cpPreview.innerText='Preview'; cpPanel.appendChild(cpPreview);
    function updateCpPreview(){const icons=['🟦','🌟','✅'];cpPreview.innerHTML=`<span style="color:${cpSettings.clanColor}">${cpSettings.clanTag}</span>${icons[cpSettings.iconId]||'✅'} <span style="color:#fcf6ba">${cpSettings.username}</span>`;}
    updateCpPreview();
    function makeCpField(labelTxt,val,onChange){
        const wrap=document.createElement('div'); Object.assign(wrap.style,{marginBottom:'6px'});
        const lbl=document.createElement('div'); Object.assign(lbl.style,{fontSize:'9px',color:'rgba(200,160,64,0.6)',fontWeight:'800',textTransform:'uppercase',letterSpacing:'0.07em',marginBottom:'3px'}); lbl.innerText=labelTxt;
        const inp=document.createElement('input'); inp.type='text'; inp.value=val;
        Object.assign(inp.style,{width:'100%',boxSizing:'border-box',padding:'5px 7px',background:'rgba(0,0,0,0.7)',color:'#fcf6ba',border:'1px solid rgba(200,160,64,0.35)',borderRadius:'6px',fontSize:'11px',fontFamily:'monospace',outline:'none'});
        inp.addEventListener('focus',()=>inp.style.borderColor='rgba(200,160,64,0.7)');
        inp.addEventListener('blur',()=>inp.style.borderColor='rgba(200,160,64,0.35)');
        ['keydown','keypress','keyup','beforeinput'].forEach(ev=>inp.addEventListener(ev,e=>e.stopImmediatePropagation(),true));
        inp.addEventListener('input',()=>{onChange(inp.value);updateCpPreview();}); wrap.append(lbl,inp); return wrap;
    }
    function saveCpSettings(){localStorage.setItem('wolf_cp_settings',JSON.stringify(cpSettings));if(states.customProfile){localStorage.setItem('playerNickname',buildProfileNickname());sendProfileNow();}}
    cpPanel.appendChild(makeCpField('Clan Tag',cpSettings.clanTag,v=>{cpSettings.clanTag=v;saveCpSettings();}));
    cpPanel.appendChild(makeCpField('Username',cpSettings.username,v=>{cpSettings.username=v;saveCpSettings();}));
    const cpColorRow=document.createElement('div'); Object.assign(cpColorRow.style,{display:'flex',alignItems:'center',gap:'10px',marginBottom:'7px'});
    const cpColorLbl=document.createElement('div'); Object.assign(cpColorLbl.style,{fontSize:'9px',color:'rgba(200,160,64,0.6)',fontWeight:'800',textTransform:'uppercase',letterSpacing:'0.07em',flex:'1'}); cpColorLbl.innerText='Clan Color';
    const cpColorPicker=document.createElement('input'); cpColorPicker.type='color'; cpColorPicker.value=cpSettings.clanColor;
    Object.assign(cpColorPicker.style,{width:'48px',height:'24px',padding:'1px 2px',cursor:'pointer',border:'1px solid rgba(200,160,64,0.35)',borderRadius:'6px',background:'rgba(0,0,0,0.6)'});
    cpColorPicker.oninput=()=>{cpSettings.clanColor=cpColorPicker.value;saveCpSettings();updateCpPreview();};
    cpColorRow.append(cpColorLbl,cpColorPicker); cpPanel.appendChild(cpColorRow);
    const cpIconLbl=document.createElement('div'); Object.assign(cpIconLbl.style,{fontSize:'9px',color:'rgba(200,160,64,0.6)',fontWeight:'800',textTransform:'uppercase',letterSpacing:'0.07em',marginBottom:'4px'}); cpIconLbl.innerText='Badge Icon'; cpPanel.appendChild(cpIconLbl);
    const cpIconGrid=document.createElement('div'); Object.assign(cpIconGrid.style,{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:'4px',marginBottom:'8px'});
    [{id:0,label:'🟦 Blue'},{id:1,label:'🌟 Gold'},{id:2,label:'✅ Green'}].forEach(ic=>{
        const btn=document.createElement('button');
        Object.assign(btn.style,{padding:'6px 4px',borderRadius:'6px',fontSize:'10px',fontWeight:'700',cursor:'pointer',fontFamily:'inherit',transition:'all .12s',border:cpSettings.iconId===ic.id?'1px solid rgba(200,160,64,0.8)':'1px solid rgba(200,160,64,0.25)',background:cpSettings.iconId===ic.id?'rgba(200,160,64,0.25)':'rgba(20,20,20,0.8)',color:cpSettings.iconId===ic.id?'#ffe566':'#fcf6ba'});
        btn.innerText=ic.label;
        btn.onclick=()=>{cpSettings.iconId=ic.id;saveCpSettings();updateCpPreview();cpIconGrid.querySelectorAll('button').forEach((b,i)=>{const a=i===ic.id;b.style.border=a?'1px solid rgba(200,160,64,0.8)':'1px solid rgba(200,160,64,0.25)';b.style.background=a?'rgba(200,160,64,0.25)':'rgba(20,20,20,0.8)';b.style.color=a?'#ffe566':'#fcf6ba';});};
        cpIconGrid.appendChild(btn);
    });
    cpPanel.appendChild(cpIconGrid);
    const cpApplyBtn=document.createElement('button'); cpApplyBtn.innerText='⚡ Apply Profile Now';
    Object.assign(cpApplyBtn.style,{width:'100%',padding:'8px',borderRadius:'7px',border:'1px solid rgba(200,160,64,0.5)',background:'linear-gradient(180deg,rgba(200,160,64,0.22) 0%,rgba(200,160,64,0.08) 100%)',color:'#fcf6ba',font:'700 11px inherit',cursor:'pointer',transition:'all .15s'});
    cpApplyBtn.onmouseenter=()=>{cpApplyBtn.style.background='rgba(200,160,64,0.32)';cpApplyBtn.style.color='#ffe566';};
    cpApplyBtn.onmouseleave=()=>{cpApplyBtn.style.background='linear-gradient(180deg,rgba(200,160,64,0.22) 0%,rgba(200,160,64,0.08) 100%)';cpApplyBtn.style.color=THEME_BODY_TEXT[titleStyle]||'#fcf6ba';};
    cpApplyBtn.onclick=()=>{applyCustomProfile();showToast('Profile applied!','success');};
    cpPanel.appendChild(cpApplyBtn);
    const fastRedBtn=document.createElement('button'); fastRedBtn.innerText='🔴 Fast Red No-Name';
    Object.assign(fastRedBtn.style,{width:'100%',padding:'7px',marginTop:'6px',borderRadius:'7px',border:'1px solid #600',background:'rgba(60,0,0,0.8)',color:'#ff5555',font:'700 11px inherit',cursor:'pointer',transition:'all .12s'});
    fastRedBtn.onmouseenter=()=>{fastRedBtn.style.background='rgba(80,0,0,0.9)';fastRedBtn.style.color='#ff8888';};
    fastRedBtn.onmouseleave=()=>{fastRedBtn.style.background='rgba(60,0,0,0.8)';fastRedBtn.style.color='#ff5555';};
    fastRedBtn.onclick=()=>{const fn='<color=#FF0000>ㅤ</color>';localStorage.setItem('playerNickname',fn);window.unityInstance?.SendMessage('MapScripts','SetNickname',fn);showToast('Red no-name applied!','success');};
    cpPanel.appendChild(fastRedBtn);
    statusDiv.appendChild(cpPanel);
    // cpPanel visibility is handled by the customProfile doToggle callback
    statusDiv.append(makeSectionLabel('Social'),createRow('Invite Blocker','blockInvites','wolf_block_invites'));
    statusDiv.appendChild(makeSectionLabel('System'));
    statusDiv.appendChild(createRow('PC Stats','pcStats','wolf_pc_stats'));
    const pcStatsPanelEl=buildPcStatsPanel(); pcStatsPanelEl.style.display=states.pcStats?'block':'none'; statusDiv.appendChild(pcStatsPanelEl);
    const inviteDivider=document.createElement('div');
    Object.assign(inviteDivider.style,{height:'1px',background:'linear-gradient(90deg,transparent,rgba(200,160,64,0.3),transparent)',margin:'7px 0'});
    statusDiv.appendChild(inviteDivider);
    const inviteHeader=document.createElement('div'); Object.assign(inviteHeader.style,{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'6px'});
    const inviteTitle=document.createElement('span'); Object.assign(inviteTitle.style,{fontSize:'9px',fontWeight:'900',letterSpacing:'0.14em',textTransform:'uppercase',color:'rgba(200,160,64,1.0)'}); inviteTitle.className='wolf-invite-title'; inviteTitle.innerText='Invites';
    const clearAllBtn=document.createElement('button'); clearAllBtn.innerText='Clear all';
    Object.assign(clearAllBtn.style,{fontSize:'10px',padding:'3px 9px',fontFamily:'inherit',color:'#fcf6ba',cursor:'pointer',background:'rgba(200,160,64,0.1)',border:'1px solid rgba(200,160,64,0.3)',borderRadius:'6px'});
    clearAllBtn.onclick=()=>{if(!confirm('Clear all saved invites?'))return;Object.keys(uidNickname).forEach(uid=>{delete roomInvites[uid];delete uidNickname[uid];delete inviteTimes[uid];});saveInviteData();renderInviteList();};
    inviteHeader.append(inviteTitle,clearAllBtn); statusDiv.appendChild(inviteHeader);
    const inviteList=document.createElement('div'); inviteList.id='wolf-invite-list';
    Object.assign(inviteList.style,{maxHeight:'180px',overflowY:'auto',display:'flex',flexDirection:'column',gap:'4px'});
    statusDiv.appendChild(inviteList);
    const inviteEmpty=document.createElement('div'); Object.assign(inviteEmpty.style,{fontSize:'11px',color:'rgba(200,160,64,0.4)',textAlign:'center',padding:'10px 0'}); inviteEmpty.innerText='No invites yet';
    function renderInviteList(){
        inviteList.innerHTML='';
        const uids=Object.keys(uidNickname).filter(u=>uidNickname[u]&&roomInvites[u]);
        if(!uids.length){inviteList.appendChild(inviteEmpty);return;}
        uids.sort((a,b)=>(inviteTimes[b]||0)-(inviteTimes[a]||0));
        uids.forEach(uid=>{
            const nickname=uidNickname[uid],room=roomInvites[uid],isBlocked=blockedUsers.includes(uid);
            const card=document.createElement('div');
            Object.assign(card.style,{background:isBlocked?'rgba(130,30,30,0.2)':'rgba(200,160,64,0.08)',border:`1px solid ${isBlocked?'rgba(160,40,40,0.4)':'rgba(200,160,64,0.2)'}`,borderRadius:'8px',padding:'8px 10px',cursor:'pointer',transition:'background .12s',position:'relative',textAlign:'left'});
            const nameEl=document.createElement('div'); nameEl.innerHTML=processNickname(nickname);
            Object.assign(nameEl.style,{fontSize:'11px',fontWeight:'800',color:'#fcf6ba',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',marginBottom:'3px',maxWidth:'160px',display:'inline-block'});
            if(isBlocked) nameEl.style.textDecoration='line-through';
            const meta=document.createElement('div'); Object.assign(meta.style,{display:'flex',justifyContent:'space-between',alignItems:'center'});
            const roomEl=document.createElement('span'); Object.assign(roomEl.style,{fontSize:'10px',color:'rgba(200,160,64,0.6)'}); roomEl.innerText='Room: '+room;
            const timeEl=document.createElement('span'); Object.assign(timeEl.style,{fontSize:'10px',color:'rgba(200,160,64,0.45)'}); timeEl.dataset.ts=inviteTimes[uid]||0; timeEl.innerText=timeAgo(inviteTimes[uid]||0);
            meta.append(roomEl,timeEl);
            const delBtn=document.createElement('span'); delBtn.innerText='×'; Object.assign(delBtn.style,{position:'absolute',top:'4px',right:'7px',color:'#ff6b6b',fontWeight:'900',fontSize:'15px',cursor:'pointer',lineHeight:'1'});
            delBtn.onclick=e=>{e.stopPropagation();delete uidNickname[uid];delete roomInvites[uid];delete inviteTimes[uid];saveInviteData();renderInviteList();};
            if(isBlocked){const b2=document.createElement('span');b2.innerText='BLOCKED';Object.assign(b2.style,{position:'absolute',top:'4px',right:'24px',background:'rgba(160,40,40,0.3)',color:'#ff8888',fontSize:'8px',padding:'1px 4px',borderRadius:'3px',fontWeight:'900',letterSpacing:'0.1em'});card.appendChild(b2);}
            card.append(nameEl,meta,delBtn);
            card.onmouseenter=()=>card.style.background=isBlocked?'rgba(140,35,35,0.3)':'rgba(200,160,64,0.15)';
            card.onmouseleave=()=>card.style.background=isBlocked?'rgba(130,30,30,0.2)':'rgba(200,160,64,0.08)';
            nameEl.onclick=e=>{e.stopPropagation();navigator.clipboard.writeText(room).then(()=>showToast('Room ID copied!'));};
            card.onclick=e=>{if(e.target===delBtn||nameEl.contains(e.target))return;navigator.clipboard.writeText(room).then(()=>showToast('Room ID copied!'));};
            card.oncontextmenu=e=>{e.preventDefault();e.stopPropagation();showCtxMenu(e.clientX,e.clientY,uid,nickname,room);};
            inviteList.appendChild(card);
        });
    }
    function tickInviteTimes(){inviteList.querySelectorAll('[data-ts]').forEach(el=>{const ts=Number(el.dataset.ts);if(ts)el.innerText=timeAgo(ts);});}
    function startInviteUpdater(){renderInviteList();if(!inviteUpdateTimer)inviteUpdateTimer=setInterval(tickInviteTimes,10000);}
    function stopInviteUpdater(){if(inviteUpdateTimer){clearInterval(inviteUpdateTimer);inviteUpdateTimer=null;}}

    // =========================
    // ARMORY TAB
    // =========================
    const armoryDiv=tabDivs['Armory'];
    function buildWeaponGrid(list,clickHandler,label){
        const grid=document.createElement('div'); grid.className='wolf-armory-grid';
        list.forEach(w=>{
            const btn=document.createElement('button'); btn.className='wolf-weapon-btn'; btn.innerText=w.name; btn.dataset.id=w.id;
            btn.onclick=()=>{clickHandler(w.id);btn.classList.add('active-sel');showToast((label||'Weapon')+' set! Reloading...','info');setTimeout(()=>location.reload(),800);};
            grid.appendChild(btn);
        });
        return grid;
    }
    armoryDiv.appendChild(makeSectionLabel('Secondary Weapons'));
    armoryDiv.appendChild(buildWeaponGrid(weaponList,id=>setSecondaryWeapon(id),'Secondary'));
    armoryDiv.appendChild(makeSectionLabel('Melee Weapons'));
    armoryDiv.appendChild(buildWeaponGrid(weaponList,id=>setMeleeWeapon(id),'Melee'));

    // =========================
    // SKINS TAB
    // =========================
    const classMap={Soldier:'class0kills',Hitman:'class1kills',Gunner:'class2kills',Heavy:'class3kills',Rocketeer:'class4kills',Agent:'class5kills',Brawler:'class6kills',Investor:'class7kills',Assassin:'class8kills',Juggernaut:'class9kills',Recon:'class10kills',Pyro:'class11kills',Rayblader:'class15kills'};
    function setClassKills(cls,count){const u=getFirebaseUser();if(!u){showToast('Not logged in','error');return;}const field=classMap[cls];if(!field){showToast('Unknown class','error');return;}try{firebase.database().ref('users/'+u.uid).update({[field]:parseInt(count)});showToast(cls+' kills set!');}catch(e){showToast('Failed to set kills','error');}}
    const skinsDiv=tabDivs['Skins'];
    skinsDiv.appendChild(makeSectionLabel('Apply Skin'));
    const autoSkinBtn=document.createElement('button'); autoSkinBtn.className='wolf-weapon-btn'; autoSkinBtn.innerText='Auto Skin: OFF';
    let autoSkinEnabled=false,autoSkinInterval=null;
    autoSkinBtn.onclick=()=>{autoSkinEnabled=!autoSkinEnabled;if(autoSkinEnabled){autoSkinBtn.innerText='Auto Skin: ON';autoSkinInterval=setInterval(()=>{const s=skinList[Math.floor(Math.random()*skinList.length)];setSkin(s.id);},250);}else{autoSkinBtn.innerText='Auto Skin: OFF';clearInterval(autoSkinInterval);autoSkinInterval=null;}};
    skinsDiv.appendChild(autoSkinBtn);
    const skinGrid=document.createElement('div'); skinGrid.className='wolf-armory-grid'; skinsDiv.appendChild(skinGrid);
    skinList.forEach(s=>{const btn=document.createElement('button');btn.className='wolf-weapon-btn';btn.innerText=s.name;btn.onclick=()=>{setSkin(s.id);btn.classList.add('active-sel');showToast('Skin applied! Reloading...','info');setTimeout(()=>location.reload(),800);};skinGrid.appendChild(btn);});
    skinsDiv.appendChild(makeSectionLabel('Class Lvl'));
    const classLvlRow=document.createElement('div'); Object.assign(classLvlRow.style,{display:'flex',gap:'5px',marginBottom:'6px',alignItems:'center'});
    const classSelect=document.createElement('select');
    Object.assign(classSelect.style,{flex:'1',padding:'6px 8px',fontSize:'11px',fontWeight:'700',fontFamily:'inherit',color:'#fcf6ba',cursor:'pointer',appearance:'none',background:'#111',border:'1px solid rgba(200,160,64,0.40)',borderRadius:'8px',backgroundImage:'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'10\' height=\'6\'%3E%3Cpath d=\'M0 0l5 6 5-6z\' fill=\'%23c8a040\'/%3E%3C/svg%3E")',backgroundRepeat:'no-repeat',backgroundPosition:'right 8px center',boxShadow:'0 0 0 1px rgba(200,160,64,0.12)'});
    Object.keys(classMap).forEach(cls=>{const o=document.createElement('option');o.value=cls;o.innerText=cls;o.style.background='#111';classSelect.appendChild(o);});
    const classKillsInput=document.createElement('input'); classKillsInput.type='number'; classKillsInput.min='0'; classKillsInput.placeholder='Kills';
    Object.assign(classKillsInput.style,{width:'72px',padding:'6px 8px',fontSize:'11px',fontWeight:'700',fontFamily:'inherit',color:'#fcf6ba',background:'#111',border:'1px solid rgba(200,160,64,0.40)',borderRadius:'8px',outline:'none'});
    ['keydown','keypress','keyup','beforeinput','input'].forEach(ev=>classKillsInput.addEventListener(ev,e=>e.stopImmediatePropagation(),true));
    let classKillsDebounce=null;
    const autoUploadKills=()=>{clearTimeout(classKillsDebounce);classKillsDebounce=setTimeout(()=>{const cls=classSelect.value,kills=parseInt(classKillsInput.value);if(isNaN(kills)||kills<0)return;setClassKills(cls,kills);},600);};
    classKillsInput.oninput=autoUploadKills; classSelect.onchange=autoUploadKills;
    classLvlRow.append(classSelect,classKillsInput); skinsDiv.appendChild(classLvlRow);

    // =========================
    // MAP COLOR TAB
    // =========================
    const mapColorDiv=tabDivs['Map Color'];
    mapColorDiv.appendChild(makeSectionLabel('Map Color Mod'));
    mapColorDiv.appendChild(createRow('Map Color Mod','mapColorMod','wolf_map_color_mod'));
    mapColorDiv.appendChild(makeSectionLabel('Colors'));
    function saveMapColorSettings(){localStorage.setItem('wolf_map_color_settings',JSON.stringify(mapColorSettings));}
    const MAP_COLOR_ROWS=[
        {key:'overlay',     label:'Overlay'},
        {key:'fontColor',   label:'Font Color'},
        {key:'fontShadow',  label:'Font Shadow'},
        {key:'lightColor',  label:'Light Color'},
        {key:'weaponChams', label:'Weapon Chams'},
        {key:'skyTop',      label:'Sky Top'},
        {key:'skyBottom',   label:'Sky Bottom'},
        {key:'sunColor',    label:'Sun Color'},
    ];
    MAP_COLOR_ROWS.forEach(({key,label})=>{
        mapColorDiv.appendChild(makeColorRow(label,mapColorSettings[key],v=>{mapColorSettings[key]=v;saveMapColorSettings();}));
    });
    const mapColorHint=document.createElement('div');
    Object.assign(mapColorHint.style,{fontSize:'9px',color:'rgba(200,160,64,0.55)',fontWeight:'600',lineHeight:'1.5',letterSpacing:'0.02em',textAlign:'center',padding:'8px 8px 2px',marginTop:'6px'});
    mapColorHint.innerText='Recolors the map\u2019s overlay, sky, lighting, weapon chams, and font. Turn on Map Color Mod above to apply your picks.';
    mapColorDiv.appendChild(mapColorHint);

    // =========================
    // SETTINGS TAB
    // =========================
    const settingsDiv=tabDivs['Settings'];
    settingsDiv.appendChild(makeSectionLabel('Menu Toggle Key'));
    const menuKeyHint=document.createElement('div');
    Object.assign(menuKeyHint.style,{fontSize:'10px',fontWeight:'600',letterSpacing:'0.02em',color:'rgba(200,160,64,0.55)',marginBottom:'7px',lineHeight:'1.4'});
    menuKeyHint.innerText='Choose which key opens and closes this menu.'; settingsDiv.appendChild(menuKeyHint);
    const menuKeyRow=document.createElement('div'); Object.assign(menuKeyRow.style,{display:'flex',alignItems:'center',gap:'8px',marginBottom:'10px'});
    const menuKeyBtn=document.createElement('button'); menuKeyBtn.className='wolf-weapon-btn';
    Object.assign(menuKeyBtn.style,{flex:'1',padding:'9px 10px',background:'linear-gradient(180deg,rgba(200,160,64,0.14) 0%,rgba(160,120,30,0.05) 100%)',color:'#fcf6ba',border:'1px solid rgba(200,160,64,0.30)',borderRadius:'8px',cursor:'pointer',fontWeight:'800',fontSize:'12px',textAlign:'center',fontFamily:'inherit',letterSpacing:'0.04em',transition:'all .12s'});
    function renderMenuKeyBtn(){menuKeyBtn.innerText='Current Key: '+displayKeyName(menuKey);}
    renderMenuKeyBtn();
    let listeningForKey=false;
    function startListening(){if(listeningForKey)return;listeningForKey=true;menuKeyBtn.innerText='Press any key…';menuKeyBtn.style.borderColor='rgba(200,160,64,0.7)';menuKeyBtn.style.background='linear-gradient(180deg,rgba(200,160,64,0.28) 0%,rgba(200,160,64,0.12) 100%)';}
    function stopListening(cancelled){listeningForKey=false;menuKeyBtn.style.borderColor='rgba(200,160,64,0.30)';menuKeyBtn.style.background='linear-gradient(180deg,rgba(200,160,64,0.14) 0%,rgba(160,120,30,0.05) 100%)';renderMenuKeyBtn();if(!cancelled)showToast('Menu key set to '+displayKeyName(menuKey),'success');}
    menuKeyBtn.onclick=()=>{if(listeningForKey){stopListening(true);return;}startListening();};
    const menuKeyResetBtn=document.createElement('button'); menuKeyResetBtn.innerText='Reset';
    Object.assign(menuKeyResetBtn.style,{padding:'9px 12px',borderRadius:'8px',border:'1px solid rgba(200,160,64,0.25)',background:'rgba(20,20,20,0.8)',color:'rgba(200,160,64,0.55)',font:'700 10px inherit',cursor:'pointer',transition:'all .12s'});
    menuKeyResetBtn.onmouseenter=()=>{menuKeyResetBtn.style.color='#ffe566';menuKeyResetBtn.style.borderColor='rgba(200,160,64,0.5)';};
    menuKeyResetBtn.onmouseleave=()=>{menuKeyResetBtn.style.color='rgba(200,160,64,0.55)';menuKeyResetBtn.style.borderColor='rgba(200,160,64,0.25)';};
    menuKeyResetBtn.onclick=()=>{if(listeningForKey)stopListening(true);menuKey='m';localStorage.setItem('wolf_menu_key',menuKey);renderMenuKeyBtn();updateFooterHint();showToast('Menu key reset to M','info');};
    menuKeyRow.append(menuKeyBtn,menuKeyResetBtn); settingsDiv.appendChild(menuKeyRow);
    const RESERVED_MENU_KEYS=['r','escape'];
    window.addEventListener('keydown',e=>{
        if(!listeningForKey)return;
        e.preventDefault();e.stopImmediatePropagation();
        const nk=e.key.toLowerCase();
        if(nk==='escape'){stopListening(true);return;}
        if(RESERVED_MENU_KEYS.includes(nk)){showToast('"'+displayKeyName(nk)+'" is reserved, pick another key','error');return;}
        menuKey=nk;localStorage.setItem('wolf_menu_key',menuKey);updateFooterHint();stopListening(false);
    },true);

    // Change Title toggle
    const changeTitleRow=document.createElement('div');
    Object.assign(changeTitleRow.style,{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'6px',padding:'6px 9px',borderRadius:'8px',background:'rgba(200,160,64,0.045)',transition:'background .15s'});
    changeTitleRow.onmouseenter=()=>{changeTitleRow.style.background='rgba(200,160,64,0.08)';};
    changeTitleRow.onmouseleave=()=>{changeTitleRow.style.background='rgba(200,160,64,0.045)';};
    const changeTitleBtn=document.createElement('button'); changeTitleBtn.innerText='Change Title';
    Object.assign(changeTitleBtn.style,{flex:'1',padding:'7px 10px',background:'linear-gradient(180deg,rgba(200,160,64,0.14) 0%,rgba(160,120,30,0.05) 100%)',color:'#fcf6ba',border:'1px solid rgba(200,160,64,0.30)',borderRadius:'8px',cursor:'pointer',fontWeight:'700',fontSize:'11px',marginRight:'7px',fontFamily:'inherit',textAlign:'left',boxShadow:'inset 0 1px 0 rgba(255,220,80,0.10),0 1px 3px rgba(0,0,0,0.4)',transition:'all .12s'});
    changeTitleBtn.onmouseenter=()=>{changeTitleBtn.style.background='linear-gradient(180deg,rgba(220,175,64,0.28) 0%,rgba(180,130,20,0.10) 100%)';changeTitleBtn.style.borderColor='rgba(255,215,80,0.62)';changeTitleBtn.style.color='#ffe566';};
    changeTitleBtn.onmouseleave=()=>{changeTitleBtn.style.background='linear-gradient(180deg,rgba(200,160,64,0.14) 0%,rgba(160,120,30,0.05) 100%)';changeTitleBtn.style.borderColor='rgba(200,160,64,0.30)';changeTitleBtn.style.color=THEME_BODY_TEXT[titleStyle]||'#fcf6ba';};
    const changeTitleToggle=document.createElement('label'); changeTitleToggle.className='wolf-toggle-switch';
    const changeTitleInput=document.createElement('input'); changeTitleInput.type='checkbox'; changeTitleInput.checked=false;
    const changeTitleSlider=document.createElement('span'); changeTitleSlider.className='wolf-toggle-slider';
    changeTitleToggle.append(changeTitleInput,changeTitleSlider);
    changeTitleRow.append(changeTitleBtn,changeTitleToggle); settingsDiv.appendChild(changeTitleRow);

    settingsDiv.appendChild(makeSectionLabel('Title Color'));
    const tsOptions=[
        {key:'yor',         swatch:'linear-gradient(90deg,#ffd700,#ff8c00,#ff4500)', label:'Fire'},
        {key:'green',       swatch:'#00c853',                                         label:'Green'},
        {key:'bw',          swatch:'linear-gradient(90deg,#ffffff,#888888)',           label:'Black & White'},
        {key:'aurora',      swatch:'linear-gradient(90deg,#00f7ff,#6a5cff,#c93bff)', label:'Aurora'},
        {key:'skyblue',      swatch:'linear-gradient(90deg,#b8eeff,#00bfff,#0080c0)', label:'Sky Blue'},
        {key:'goldpremium', swatch:'linear-gradient(90deg,#fff8c0,#c8a040,#7a5200)', label:'Gold Premium'},
    ];
    const tsWrap=document.createElement('div'); Object.assign(tsWrap.style,{display:'flex',flexDirection:'column',gap:'5px',marginBottom:'6px'});
    tsOptions.forEach(opt=>{
        const row=document.createElement('div');
        Object.assign(row.style,{display:'flex',alignItems:'center',gap:'9px',padding:'7px 10px',borderRadius:'8px',cursor:'pointer',transition:'background .15s ease,border-color .15s ease',border:'1px solid rgba(200,160,64,0.22)',background:'linear-gradient(180deg,rgba(200,160,64,0.07) 0%,rgba(200,160,64,0.02) 100%)'});
        const radio=document.createElement('input'); radio.type='radio'; radio.name='wolf_ts'; radio.value=opt.key; radio.checked=(titleStyle===opt.key);
        Object.assign(radio.style,{accentColor:'#c8a040',cursor:'pointer',flexShrink:'0'});
        const swatch=document.createElement('span');
        Object.assign(swatch.style,{width:'14px',height:'14px',borderRadius:'50%',flexShrink:'0',background:opt.swatch,border:'1px solid rgba(255,255,255,0.25)'});
        const lbl=document.createElement('span'); lbl.innerText=opt.label;
        Object.assign(lbl.style,{fontSize:'11px',fontWeight:'700',color:'#fcf6ba',flex:'1',textAlign:'left'});
        function highlight(){
            const on=(titleStyle===opt.key);
            row.style.borderColor=on?'rgba(200,160,64,0.60)':'rgba(200,160,64,0.22)';
            row.style.background=on?'linear-gradient(180deg,rgba(200,160,64,0.18) 0%,rgba(200,160,64,0.07) 100%)':'linear-gradient(180deg,rgba(200,160,64,0.07) 0%,rgba(200,160,64,0.02) 100%)';
            row.style.boxShadow=on?'inset 0 1px 0 rgba(255,220,80,0.12),0 0 8px rgba(200,160,64,0.15)':'none';
            radio.checked=on;
        }
        opt.highlight=highlight;
        radio.onchange=()=>{applyTitleStyle(opt.key);tsOptions.forEach(o=>o.highlight());};
        row.onclick=()=>{radio.checked=true;radio.onchange();};
        row.append(radio,swatch,lbl); tsWrap.appendChild(row);
    });
    settingsDiv.appendChild(tsWrap);
    tsWrap.style.display='none';
    let titlePickerOpen=false;
    function toggleTitlePicker(){titlePickerOpen=!titlePickerOpen;changeTitleInput.checked=titlePickerOpen;tsWrap.style.display=titlePickerOpen?'flex':'none';}
    changeTitleBtn.onclick=toggleTitlePicker; changeTitleInput.onchange=toggleTitlePicker;
    settingsDiv.appendChild(makeSectionLabel('Reset'));
const resetAllBtn=document.createElement('button');
resetAllBtn.innerText='⚠️ Reset All Settings';
Object.assign(resetAllBtn.style,{
    width:'100%',padding:'9px',marginBottom:'6px',borderRadius:'8px',
    border:'1px solid #600',background:'rgba(60,0,0,0.8)',color:'#ff5555',
    font:'800 12px inherit',letterSpacing:'0.04em',cursor:'pointer',transition:'all .12s'
});
resetAllBtn.onmouseenter=()=>{resetAllBtn.style.background='rgba(80,0,0,0.9)';resetAllBtn.style.color='#ff8888';};
resetAllBtn.onmouseleave=()=>{resetAllBtn.style.background='rgba(60,0,0,0.8)';resetAllBtn.style.color='#ff5555';};
resetAllBtn.onclick=()=>{
    if(!confirm('Reset ALL Wolf_ Tools settings to default? This reloads the page and cannot be undone.'))return;
    Object.keys(localStorage).forEach(k=>{ if(k.startsWith('wolf_')) localStorage.removeItem(k); });
    showToast('Settings reset! Reloading...','info');
    setTimeout(()=>location.reload(),600);
};
settingsDiv.appendChild(resetAllBtn);
const resetAllHint=document.createElement('div');
Object.assign(resetAllHint.style,{fontSize:'9px',color:'rgba(200,160,64,0.5)',fontWeight:'600',lineHeight:'1.4',textAlign:'center',marginBottom:'4px'});
resetAllHint.innerText='Clears every saved Wolf_ Tools option (toggles, colors, keybinds, phrases) and reloads the page.';
settingsDiv.appendChild(resetAllHint);

    // =========================
    // INFO TAB
    // =========================
    const infoDiv=tabDivs['Info'];
    const infoCard=document.createElement('div');
    Object.assign(infoCard.style,{
        marginTop:'10px', padding:'16px', borderRadius:'10px',
        background:'rgba(200,160,64,0.07)', border:'1px solid rgba(200,160,64,0.2)',
        textAlign:'center'
    });

    const infoText=document.createElement('div');
    infoText.innerText='Hello everyone, George here! I designed this script to enhance the gameplay experience for Kour.io, without providing any cheats. To be clear: this is not a hack menu and should not be used as one. This script was created purely to make Kour.io a better, more enjoyable game for all players! Feel free to try it out, and let me know if you have any feedback! Furthermore, dont copy or edit this script! If you want any change or addition feel free to contact me on Discord [ _george_31337]. Also, dont forget to like & sub to my YT channel!';
    Object.assign(infoText.style,{
        fontSize:'13px', fontWeight:'700', color:'#fcf6ba',
        letterSpacing:'0.03em', lineHeight:'1.6'
    });
    const infoSub=document.createElement('div');
    infoSub.innerText='Wolf_ Tools v3.0';
    Object.assign(infoSub.style,{
        fontSize:'10px', color:'rgba(200,160,64,0.5)',
        marginTop:'6px', fontWeight:'600', letterSpacing:'0.05em'
    });
    const infoYT=document.createElement('a');
    infoYT.href='https://www.youtube.com/@grgZach?sub_confirmation=1';
    infoYT.target='_blank';
    infoYT.innerText='▶ youtube.com/@grgZach';
    Object.assign(infoYT.style,{
        display:'block', marginTop:'10px', fontSize:'10px',
        color:'#cc0000', fontWeight:'700', textDecoration:'none',
        letterSpacing:'0.03em'
    });
    infoCard.append(infoText,infoSub,infoYT);
    infoDiv.appendChild(infoCard);

    // =========================
    // CONTEXT MENU
    // =========================
    const ctxMenu=document.createElement('div'); ctxMenu.id='wolf-ctx-menu';
    ctxMenu.innerHTML=`<div class="wolf-ctx-item" data-action="copy-room">📋 Copy Room ID</div><div class="wolf-ctx-item" data-action="copy-name">👤 Copy Nickname</div><div class="wolf-ctx-divider"></div><div class="wolf-ctx-item" data-action="remove-friend">👋 Remove Friend</div><div class="wolf-ctx-item" data-action="block-user">🚫 Block User</div><div class="wolf-ctx-item" data-action="unblock-user">✅ Unblock User</div><div class="wolf-ctx-divider"></div><div class="wolf-ctx-item danger" data-action="delete-invite">🗑️ Delete Invite</div>`;
    function showCtxMenu(x,y,uid,nickname,room){currentContextUid=uid;currentContextData={uid,nickname,room};const isBlocked=blockedUsers.includes(uid);ctxMenu.querySelector('[data-action="block-user"]').style.display=isBlocked?'none':'block';ctxMenu.querySelector('[data-action="unblock-user"]').style.display=isBlocked?'block':'none';ctxMenu.style.left=(x+8)+'px';ctxMenu.style.top=(y+8)+'px';ctxMenu.style.display='block';}
    function hideCtxMenu(){ctxMenu.style.display='none';currentContextUid=null;currentContextData=null;}
    ctxMenu.addEventListener('click',e=>{
        e.stopPropagation();
        const action=e.target.closest('[data-action]')?.dataset.action;
        if(!action||!currentContextData)return;
        const{uid,nickname,room}=currentContextData;
        if(action==='copy-room')navigator.clipboard.writeText(room).then(()=>showToast('Room ID copied!'));
        if(action==='copy-name')navigator.clipboard.writeText(nickname.replace(/<[^>]*>/g,'')).then(()=>showToast('Nickname copied!'));
        if(action==='block-user'){if(!blockedUsers.includes(uid))blockedUsers.push(uid);saveInviteData();renderInviteList();}
        if(action==='unblock-user'){blockedUsers=blockedUsers.filter(u=>u!==uid);saveInviteData();renderInviteList();}
        if(action==='remove-friend'){delete uidNickname[uid];delete roomInvites[uid];delete inviteTimes[uid];blockedUsers=blockedUsers.filter(u=>u!==uid);saveInviteData();renderInviteList();try{firebase.auth().currentUser&&window.removeFriend&&window.removeFriend(firebase.auth().currentUser.uid,uid);}catch(e){}}
        if(action==='delete-invite'){delete uidNickname[uid];delete roomInvites[uid];delete inviteTimes[uid];saveInviteData();renderInviteList();}
        hideCtxMenu();
    });
    document.addEventListener('click',hideCtxMenu);
    document.addEventListener('keydown',e=>{if(e.key==='Escape')hideCtxMenu();});

    // =========================
    // KEYBOARD SHORTCUT (G = reset class)
    // =========================
    let resetClassCooldown=true;
    document.addEventListener('keydown',e=>{
        const tag=document.activeElement?.tagName;
        if(tag==='INPUT'||tag==='TEXTAREA')return;
        if(e.key.toLowerCase()===resetClassKey&&states.resetClass&&resetClassCooldown){
            resetClassCooldown=false;
            try{window.unityInstance.SendMessage('MapScripts','ChangeClassTo',resetClassId);}catch(err){console.log('[Wolf Tools] Reset Class failed',err);}
            setTimeout(()=>{resetClassCooldown=true;},500);
        }
    });

    // =========================
    // INIT UI
    // =========================
    function loadWolfLogo(){
        const imgEl=document.getElementById('wolf-logo-img'); if(!imgEl)return;
        const canvas=document.createElement('canvas'); canvas.width=44; canvas.height=44;
        const ctx2=canvas.getContext('2d'); ctx2.font='36px serif'; ctx2.textAlign='center'; ctx2.textBaseline='middle'; ctx2.fillText('🐺',22,22);
        imgEl.src=canvas.toDataURL();
    }
    function initUI(){
        document.body.appendChild(menu); document.body.appendChild(crossContainer); document.body.appendChild(ctxMenu);
        applyCross(); setTimeout(clampMenu,0); loadWolfLogo();
        if(states.pcStats)startPcStats(); if(states.airStrafe)startAirStrafe(); if(states.raveMode)startRaveMode();
    }
    if(document.body)initUI(); else window.addEventListener('DOMContentLoaded',initUI);

    // =========================
    // DRAGGABLE MENU
    // =========================
    const SNAP_MARGIN=16;
    let isDragging=false,dragOffsetX=0,dragOffsetY=0,hasDragged=false;
    function menuSetTransition(on){menu.style.transition=on?'left .22s cubic-bezier(.4,0,.2,1),top .22s cubic-bezier(.4,0,.2,1)':'none';}
    function clampMenu(){const mw=menu.offsetWidth||350,mh=menu.offsetHeight||400;let l=parseFloat(menu.style.left)||0,t=parseFloat(menu.style.top)||0;l=Math.max(0,Math.min(l,window.innerWidth-mw));t=Math.max(0,Math.min(t,window.innerHeight-mh));menu.style.left=l+'px';menu.style.top=t+'px';}
    function onDragStart(cx,cy){menuSetTransition(false);isDragging=true;hasDragged=false;dragOffsetX=cx-menu.offsetLeft;dragOffsetY=cy-menu.offsetTop;header.style.cursor='grabbing';}
    function onDragMove(cx,cy){if(!isDragging)return;hasDragged=true;const mw=menu.offsetWidth||350,mh=menu.offsetHeight||400,l=Math.max(0,Math.min(cx-dragOffsetX,window.innerWidth-mw)),t=Math.max(0,Math.min(cy-dragOffsetY,window.innerHeight-mh));menu.style.left=l+'px';menu.style.top=t+'px';}
    function onDragEnd(){if(!isDragging)return;isDragging=false;header.style.cursor='grab';if(hasDragged){localStorage.setItem('wolf_left',menu.style.left);localStorage.setItem('wolf_top',menu.style.top);}}
    header.style.cursor='grab';
    header.addEventListener('mousedown',e=>{if(e.button!==0)return;e.preventDefault();onDragStart(e.clientX,e.clientY);});
    document.addEventListener('mousemove',e=>onDragMove(e.clientX,e.clientY));
    document.addEventListener('mouseup',()=>onDragEnd());
    header.addEventListener('touchstart',e=>{const t=e.touches[0];onDragStart(t.clientX,t.clientY);},{passive:true});
    document.addEventListener('touchmove',e=>{if(!isDragging)return;e.preventDefault();const t=e.touches[0];onDragMove(t.clientX,t.clientY);},{passive:false});
    document.addEventListener('touchend',()=>onDragEnd());
    window.addEventListener('resize',()=>{menuSetTransition(false);clampMenu();});
    function resetMenu(){menuSetTransition(true);menu.style.top=SNAP_MARGIN+'px';menu.style.left=SNAP_MARGIN+'px';localStorage.setItem('wolf_top',SNAP_MARGIN+'px');localStorage.setItem('wolf_left',SNAP_MARGIN+'px');setTimeout(()=>menuSetTransition(false),250);}

    // =========================
    // UNITY INVITE HOOK
    // =========================
    let waitingForName=[];
    function hook_unity(instance){
        const origSend=instance.SendMessage;
        instance.SendMessage=function(obj,method,param){
            if(obj==='FirebasePlayerPrefs2023'&&method==='OnInvite'){const[uid,room]=param.split(':');roomInvites[uid]=room;inviteTimes[uid]=Date.now();saveInviteData();waitingForName.push(uid);window.getUserData(uid+'/public/myUsername',uid);if(states.blockInvites||blockedUsers.includes(uid))return;}
            if(obj==='FirebasePlayerPrefs2023'&&method==='OnGotData'){let[value,key]=param.split('&');value=value.replace(/^"|"$/g,'');if(waitingForName.includes(key)){uidNickname[key]=value;saveInviteData();waitingForName.splice(waitingForName.indexOf(key),1);if(tabDivs['Status'].style.display!=='none')renderInviteList();}}
            return origSend.call(this,obj,method,param);
        };
    }
    function wait_for_unity(){if(window.unityInstance&&typeof window.unityInstance.SendMessage==='function'){hook_unity(window.unityInstance);}else{setTimeout(wait_for_unity,200);}}
    wait_for_unity();

    // =========================
    // GEAR BUTTON
    // =========================
    let savedGearTop=getStored('wolf_gear_top','20px'),savedGearLeft=getStored('wolf_gear_left','20px');
    menu.classList.add('wolf-menu-hidden');
    const gearBtn=document.createElement('div'); gearBtn.id='wolf-gear-btn';
    gearBtn.innerHTML=`<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#5d4037" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>`;
    Object.assign(gearBtn.style,{position:'fixed',top:savedGearTop,left:savedGearLeft,width:'40px',height:'40px',background:'linear-gradient(135deg,#bf953f,#fcf6ba,#b38728)',border:'2px solid #5d4037',borderRadius:'8px',zIndex:'10002',cursor:'move',display:'flex',alignItems:'center',justifyContent:'center',boxShadow:'0 6px 16px rgba(0,0,0,0.6)',userSelect:'none',transition:'background .2s ease,transform .1s ease'});
    gearBtn.addEventListener('mousedown',()=>{gearBtn.style.transform='scale(0.95)';});
    gearBtn.addEventListener('mouseup',()=>{gearBtn.style.transform='scale(1)';});
    if(document.body)document.body.appendChild(gearBtn); else window.addEventListener('DOMContentLoaded',()=>document.body.appendChild(gearBtn));
    function clampGear(){const rect=gearBtn.getBoundingClientRect();gearBtn.style.left=Math.max(0,Math.min(parseFloat(gearBtn.style.left)||20,window.innerWidth-rect.width))+'px';gearBtn.style.top=Math.max(0,Math.min(parseFloat(gearBtn.style.top)||20,window.innerHeight-rect.height))+'px';}
    function resetGear(){gearBtn.style.top='20px';gearBtn.style.left='20px';localStorage.setItem('wolf_gear_top','20px');localStorage.setItem('wolf_gear_left','20px');}
    let gearDragging=false,gearX=0,gearY=0,gearHasDragged=false,gearDownX=0,gearDownY=0;
    function toggleWolfMenu(){
        if(menu.classList.contains('wolf-menu-hidden')){menu.classList.remove('wolf-menu-hidden');gearBtn.classList.add('wolf-gear-hidden');clampMenu();}
        else{menu.classList.add('wolf-menu-hidden');gearBtn.classList.remove('wolf-gear-hidden');clampGear();}
    }
    gearBtn.onmousedown=e=>{gearDragging=true;gearHasDragged=false;gearDownX=e.clientX;gearDownY=e.clientY;gearX=e.clientX-gearBtn.offsetLeft;gearY=e.clientY-gearBtn.offsetTop;};
    document.addEventListener('mouseup',()=>{if(!gearDragging)return;gearDragging=false;clampGear();localStorage.setItem('wolf_gear_top',gearBtn.style.top);localStorage.setItem('wolf_gear_left',gearBtn.style.left);});
    document.addEventListener('mousemove',e=>{if(!gearDragging)return;if(Math.abs(e.clientX-gearDownX)>3||Math.abs(e.clientY-gearDownY)>3)gearHasDragged=true;const rect=gearBtn.getBoundingClientRect();gearBtn.style.left=Math.max(0,Math.min(e.clientX-gearX,window.innerWidth-rect.width))+'px';gearBtn.style.top=Math.max(0,Math.min(e.clientY-gearY,window.innerHeight-rect.height))+'px';});
    gearBtn.onclick=e=>{e.preventDefault();if(gearHasDragged)return;toggleWolfMenu();};
    window.addEventListener('keydown',e=>{
        const k=e.key.toLowerCase();
        const tag=document.activeElement&&document.activeElement.tagName;
        const isTyping=tag==='INPUT'||tag==='TEXTAREA'||tag==='SELECT'||(document.activeElement&&document.activeElement.isContentEditable);
        if(k===menuKey&&!isTyping){
            e.preventDefault();e.stopImmediatePropagation();
            toggleWolfMenu();
        }
        if(k==='r'&&!isTyping){resetMenu();clampMenu();resetGear();clampGear();}
    },true);

    // =========================
    // THEME APPLIER
    // =========================
    function applyThemeChrome(style){
        const p=THEME_PALETTE[style]||THEME_PALETTE.yor;
        const isGold=style==='goldpremium', isSkyblue=style==='skyblue';
        const labelColor=style==='yor'?'#ffffff':isGold?'#8a6020':isSkyblue?'#5ab0ff':p.accent;
        const labelWeight=style==='yor'?'400':'900', labelTracking=style==='yor'?'0.06em':'0.14em';
        (_themeLabelEls||document.querySelectorAll('.wolf-section-label')).forEach(el=>{el.style.color=labelColor;el.style.fontWeight=labelWeight;el.style.letterSpacing=labelTracking;el.style.textShadow=style==='yor'?'none':'';});
        footer.style.color=isGold?'rgba(44,26,0,0.5)':isSkyblue?'rgba(100,180,255,0.45)':p.textDim;
        footer.style.borderTopColor=isGold?'rgba(122,82,0,0.3)':isSkyblue?'rgba(30,144,255,0.2)':p.accentDim;
        badge.style.color=isGold?'#7a5200':p.accent;
        badge.style.background=isGold?'rgba(122,82,0,0.12)':isSkyblue?'rgba(30,144,255,0.12)':`rgba(${style==='bw'?'180,180,180':style==='green'?'0,180,70':style==='aurora'?'106,92,255':'200,120,0'},0.1)`;
        badge.style.borderColor=isGold?'rgba(122,82,0,0.25)':p.accentDim;
        header.style.borderBottomColor=isGold?'rgba(122,82,0,0.25)':p.accentDim;
        header.style.background=isGold?'rgba(0,0,0,0.06)':isSkyblue?'rgba(0,191,255,0.07)':`rgba(${style==='bw'?'180,180,180':style==='green'?'0,180,70':style==='aurora'?'106,92,255':'200,160,64'},0.07)`;
        tabBar.style.borderBottomColor=isGold?'rgba(122,82,0,0.25)':p.accentDim;
        menuGloss.style.background=isGold?'linear-gradient(90deg,transparent,rgba(255,255,255,0.18),transparent)':isSkyblue?'linear-gradient(90deg,transparent,rgba(0,191,255,0.5),transparent)':`linear-gradient(90deg,transparent,${p.accentFaint},transparent)`;
        const _bodyEls=_themeBodyEls||Array.from(menuInner.querySelectorAll(_BODY_TEXT_SELECTOR)).filter(el=>el!==ytLink&&!(el.classList&&el.classList.contains('wolf-phrase-del'))&&el.id!=='wolf-gear-btn');
        const _bodyColor=style==='yor'?'#ffffff':isGold?'#2c1a00':isSkyblue?'#d0eaff':'';
        _bodyEls.forEach(el=>{el.style.color=_bodyColor;});
        if(typeof rainbowSpeedText!=='undefined'&&rainbowSpeedText)rainbowSpeedText.style.color=THEME_BODY_TEXT[style]||'#FFB347';
        let tss=document.getElementById('wolf-theme-scroll-style');
        if(!tss){tss=document.createElement('style');tss.id='wolf-theme-scroll-style';document.head&&document.head.appendChild(tss);}
        const yorOver=style==='yor'?`.wolf-tab-yor{color:rgba(255,255,255,0.42)!important;animation:none!important;background:none!important;}.wolf-tab-yor-active{color:#ffffff!important;border-bottom-color:rgba(255,255,255,0.55)!important;}.wolf-section-label{color:#ffffff!important;font-weight:400!important;letter-spacing:0.06em!important;text-shadow:none!important;}.wolf-section-label::after{background:rgba(255,255,255,0.10)!important;}`:'';
        const goldOver=isGold?`.wolf-tab-goldpremium{color:rgba(44,26,0,0.45)!important;animation:none!important;background:none!important;}.wolf-tab-goldpremium-active{color:#2c1a00!important;border-bottom-color:#7a5200!important;}.wolf-section-label{color:#7a4f00!important;font-weight:900!important;letter-spacing:0.14em!important;}.wolf-section-label::after{background:rgba(93,64,55,0.3)!important;}.wolf-toggle-switch input:checked+.wolf-toggle-slider{background:rgba(52,199,89,0.85)!important;}.wolf-toggle-slider{border-color:rgba(93,64,55,0.18)!important;background:rgba(200,160,64,0.2)!important;}.wolf-weapon-btn,.wolf-skin-btn{color:#2c1a00!important;background:rgba(255,255,255,0.18)!important;border:1px solid rgba(150,100,0,0.16)!important;border-radius:8px!important;box-shadow:0 1px 2px rgba(0,0,0,0.08),inset 0 1px 0 rgba(255,255,255,0.80)!important;font-weight:600!important;text-shadow:none!important;}select,option{background:#f5e070!important;color:#2c1a00!important;}.wolf-menu-goldpremium-bg .wolf-row{background:none!important;border:none!important;box-shadow:none!important;padding:3px 0!important;margin-bottom:4px!important;}.wolf-menu-goldpremium-bg .wolf-row span,.wolf-menu-goldpremium-bg .wolf-color-row-label,.wolf-menu-goldpremium-bg .wolf-invite-title{color:#2c1a00!important;}.wolf-menu-goldpremium-bg button:not(.wolf-phrase-del):not(.wolf-tab-goldpremium):not(.wolf-tab-goldpremium-active){background:rgba(255,255,255,0.18)!important;color:#2c1a00!important;border:1px solid rgba(150,100,0,0.16)!important;border-radius:8px!important;box-shadow:0 1px 2px rgba(0,0,0,0.08),inset 0 1px 0 rgba(255,255,255,0.80)!important;font-weight:600!important;text-shadow:none!important;padding:8px 12px!important;}.wolf-menu-goldpremium-bg button:not(.wolf-phrase-del):hover{background:rgba(255,255,255,0.20)!important;box-shadow:0 1px 3px rgba(0,0,0,0.12),inset 0 1px 0 rgba(255,255,255,0.95)!important;}`:'';
        const skyblueOver=isSkyblue?`.wolf-tab-skyblue{color:rgba(0,191,255,0.38)!important;animation:none!important;background:none!important;}.wolf-tab-skyblue-active{color:#b8eeff!important;border-bottom-color:#00bfff!important;text-shadow:0 0 8px rgba(0,191,255,0.6)!important;}.wolf-section-label{color:#5ab0ff!important;font-weight:900!important;letter-spacing:0.14em!important;}.wolf-section-label::after{background:rgba(0,191,255,0.22)!important;}.wolf-toggle-switch input:checked+.wolf-toggle-slider{background:linear-gradient(135deg,rgba(0,191,255,0.88),rgba(0,155,220,0.78))!important;border-color:rgba(0,210,255,0.65)!important;box-shadow:inset 0 1px 3px rgba(0,0,0,0.3),0 0 10px rgba(0,191,255,0.38)!important;}.wolf-toggle-switch input:checked+.wolf-toggle-slider::before{background:linear-gradient(180deg,#c8f4ff 0%,#00d0ff 50%,#0090cc 100%)!important;box-shadow:0 1px 6px rgba(0,0,0,0.65),0 0 5px rgba(0,210,255,0.55)!important;}.wolf-toggle-slider{border-color:rgba(0,191,255,0.28)!important;}.wolf-weapon-btn,.wolf-skin-btn{border-color:rgba(0,191,255,0.38)!important;}.wolf-weapon-btn:hover,.wolf-skin-btn:hover{border-color:rgba(0,210,255,0.65)!important;color:#b8eeff!important;}select,option{background:#030d14!important;color:#b8eeff!important;border-color:rgba(30,144,255,0.4)!important;}.wolf-row{background:rgba(0,191,255,0.04)!important;}.wolf-row:hover{background:rgba(0,191,255,0.09)!important;}`:'';
        tss.innerHTML=`
            .wolf-content-scroll::-webkit-scrollbar-thumb{background:${isGold?'rgba(122,82,0,0.35)':isSkyblue?'rgba(0,191,255,0.45)':p.accentFaint}!important;}
            #wolf-invite-list::-webkit-scrollbar-thumb{background:${isGold?'#b38728':isSkyblue?'#00bfff':p.accent}!important;}
            .wolf-section-label{color:${labelColor}!important;font-weight:${labelWeight}!important;letter-spacing:${labelTracking}!important;}
            .wolf-section-label::after{background:${style==='yor'?'rgba(255,255,255,0.18)':isGold?'rgba(93,64,55,0.25)':isSkyblue?'rgba(0,191,255,0.22)':p.labelAfter}!important;}
            .wolf-toggle-switch input:checked+.wolf-toggle-slider{background:${isGold?'rgba(52,199,89,0.85)':isSkyblue?'linear-gradient(135deg,rgba(0,191,255,0.88),rgba(0,155,220,0.78))':'linear-gradient(135deg,rgba(225,180,60,0.90),rgba(175,125,25,0.80))'}!important;}
            .wolf-toggle-switch input:checked+.wolf-toggle-slider::before{background:linear-gradient(180deg,${isGold?'#ffffff':isSkyblue?'#c8f4ff':p.text} 60%,${isGold?'#e0e0e0':isSkyblue?'#00bfff':p.accent} 100%)!important;}
            .wolf-toggle-slider{border-color:${isGold?'rgba(93,64,55,0.22)':isSkyblue?'rgba(0,191,255,0.28)':p.accentDim}!important;}
            input[type=range]{accent-color:${isGold?'#b38728':isSkyblue?'#00bfff':p.accent}!important;}
            .wolf-weapon-btn,.wolf-phrase-btn,.wolf-profile-preview,select,option{color:${THEME_BODY_TEXT[style]||'#fcf6ba'}!important;}
            ${yorOver}${goldOver}${skyblueOver}
        `;
    }

    function applyTitleStyle(style){
        titleStyle = style; localStorage.setItem('wolf_title_style',style);
        titleEl.classList.remove('wolf-title-green','wolf-title-bw','wolf-title-aurora','wolf-title-goldpremium','wolf-title-skyblue');
        if(style==='green')titleEl.classList.add('wolf-title-green');
        if(style==='bw')titleEl.classList.add('wolf-title-bw');
        if(style==='aurora')titleEl.classList.add('wolf-title-aurora');
        if(style==='goldpremium')titleEl.classList.add('wolf-title-goldpremium');
        if(style==='skyblue')titleEl.classList.add('wolf-title-skyblue');
        titleEl.style.color='';
        menu.classList.remove('wolf-menu-bw-border','wolf-menu-yor-border','wolf-menu-aurora-border','wolf-menu-goldpremium-bg','wolf-menu-skyblue-border');
        menuBg.classList.remove('wolf-menu-aurora-bg','wolf-menu-skyblue-bg');
        menu.style.background=''; menu.style.border='';
        if(style==='bw'){menu.classList.add('wolf-menu-bw-border');menuBg.style.background='#0a0a0a';}
        else if(style==='yor'){menu.classList.add('wolf-menu-yor-border');menuBg.style.background='#0a0a0a';}
        else if(style==='aurora'){menu.classList.add('wolf-menu-aurora-border');menuBg.classList.add('wolf-menu-aurora-bg');menuBg.style.background='#0a0d1f';}
        else if(style==='skyblue'){menu.classList.add('wolf-menu-skyblue-border');menuBg.classList.add('wolf-menu-skyblue-bg');menuBg.style.background='#030d14';}
        else if(style==='goldpremium'){menu.classList.add('wolf-menu-goldpremium-bg');menuBg.style.background='transparent';}
        else{menu.style.background='linear-gradient(#0a0a0a,#0a0a0a) padding-box,linear-gradient(160deg,#fff8c0 0%,#b38728 40%,#fffacc 60%,#7a5200 100%) border-box';menuBg.style.background='#0a0a0a';}
        const ALL_TAB_CLS=['wolf-tab-yor','wolf-tab-yor-active','wolf-tab-bw','wolf-tab-bw-active','wolf-tab-aurora','wolf-tab-aurora-active','wolf-tab-green','wolf-tab-green-active','wolf-tab-goldpremium','wolf-tab-goldpremium-active','wolf-tab-skyblue','wolf-tab-skyblue-active'];
        TAB_NAMES.forEach(n=>{
            const btn=tabBtns[n],isActive=!!btn._active;
            btn.classList.remove(...ALL_TAB_CLS); btn.style.opacity=''; btn.style.color=''; btn.style.borderBottomColor=''; btn.onmouseenter=()=>{}; btn.onmouseleave=()=>{};
            if(style==='yor'){btn.classList.add('wolf-tab-yor');if(isActive)btn.classList.add('wolf-tab-yor-active');}
            else if(style==='bw'){btn.classList.add('wolf-tab-bw');if(isActive)btn.classList.add('wolf-tab-bw-active');}
            else if(style==='aurora'){btn.classList.add('wolf-tab-aurora');if(isActive)btn.classList.add('wolf-tab-aurora-active');}
            else if(style==='skyblue'){btn.classList.add('wolf-tab-skyblue');if(isActive)btn.classList.add('wolf-tab-skyblue-active');}
            else if(style==='goldpremium'){btn.classList.add('wolf-tab-goldpremium');if(isActive)btn.classList.add('wolf-tab-goldpremium-active');}
            else{btn.classList.add('wolf-tab-green');if(isActive)btn.classList.add('wolf-tab-green-active');}
        });
        applyThemeChrome(style);
    }

    // Patch showTab to re-apply tab classes after style resets
    const _origShowTab=showTab;
    showTab=function(name){
        _origShowTab(name);
        const ALL_TAB_CLS=['wolf-tab-yor','wolf-tab-yor-active','wolf-tab-bw','wolf-tab-bw-active','wolf-tab-aurora','wolf-tab-aurora-active','wolf-tab-green','wolf-tab-green-active','wolf-tab-goldpremium','wolf-tab-goldpremium-active','wolf-tab-skyblue','wolf-tab-skyblue-active'];
        TAB_NAMES.forEach(n=>{
            const btn=tabBtns[n],isActive=!!btn._active;
            btn.classList.remove(...ALL_TAB_CLS); btn.style.color=''; btn.style.borderBottomColor='';
            if(titleStyle==='yor'){btn.classList.add('wolf-tab-yor');if(isActive)btn.classList.add('wolf-tab-yor-active');}
            else if(titleStyle==='bw'){btn.classList.add('wolf-tab-bw');if(isActive)btn.classList.add('wolf-tab-bw-active');}
            else if(titleStyle==='aurora'){btn.classList.add('wolf-tab-aurora');if(isActive)btn.classList.add('wolf-tab-aurora-active');}
            else if(titleStyle==='skyblue'){btn.classList.add('wolf-tab-skyblue');if(isActive)btn.classList.add('wolf-tab-skyblue-active');}
            else if(titleStyle==='goldpremium'){btn.classList.add('wolf-tab-goldpremium');if(isActive)btn.classList.add('wolf-tab-goldpremium-active');}
            else{btn.classList.add('wolf-tab-green');if(isActive)btn.classList.add('wolf-tab-green-active');}
        });
    };

    // Cache element lists for theme applier
    const _BODY_TEXT_SELECTOR='.wolf-weapon-btn,.wolf-phrase-btn,button,select,option,.wolf-profile-preview,label span,.wolf-toggle-switch + span,[data-wolf-body-text]';
    let _themeBodyEls=null,_themeLabelEls=null;
    function _cacheThemeEls(){
        _themeBodyEls=Array.from(menuInner.querySelectorAll(_BODY_TEXT_SELECTOR)).filter(el=>el!==ytLink&&!(el.classList&&el.classList.contains('wolf-phrase-del'))&&el.id!=='wolf-gear-btn');
        _themeLabelEls=Array.from(document.querySelectorAll('.wolf-section-label'));
    }
    _cacheThemeEls();
    tsOptions.forEach(o=>{if(o.highlight)o.highlight();});
    applyTitleStyle(titleStyle);
})();