Mudanças entre as edições de "Widget:Character.Skills"

De Wiki Gla
Ir para navegação Ir para pesquisar
m
m
Linha 1: Linha 1:
<!-- SUBSKILLS SYSTEM -->
<!-- MAIN SKILLS SYSTEM -->
<script>
<script>
     (function () {
     (function () {
         const api = (window.__subskills ||= {});
         const $ = (s, root = document) => root.querySelector(s);
         const subCache = new Map();
        const $$ = (s, root = document) => Array.from(root.querySelectorAll(s));
         const imagePreloadCache = new Map();
        const ensureRemoved = sel => {
         let subRail, subBar, spacer;
            Array.from(document.querySelectorAll(sel)).forEach(n => n.remove());
        };
        const onceFlag = (el, key) => {
            if (!el) return false;
            if (el.dataset[key]) return false;
            el.dataset[key] = '1';
            return true;
        };
        const addOnce = (el, ev, fn) => {
            if (!el) return;
            const attr = `data-wired-${ev}`;
            if (el.hasAttribute(attr)) return;
            el.addEventListener(ev, fn);
            el.setAttribute(attr, '1');
        };
        const FLAG_ICON_FILES = {
            aggro: 'Enemyaggro-icon.png', bridge: 'Bridgemaker-icon.png', wall: 'Destroywall-icon.png', quickcast: 'Quickcast-icon.png'
        };
        const subBarTemplateCache = window.__skillSubBarTemplateCache || (window.__skillSubBarTemplateCache = new Map());
        const imagePreloadCache = window.__skillImagePreloadCache || (window.__skillImagePreloadCache = new Map());
        const videoPreloadCache = window.__skillVideoPreloadCache || (window.__skillVideoPreloadCache = new Set());
         const flagRowCache = window.__skillFlagRowCache || (window.__skillFlagRowCache = new Map());
         const flagIconURLCache = window.__skillFlagIconURLCache || (window.__skillFlagIconURLCache = new Map());
         function filePathURL(fileName) {
            const f = encodeURIComponent((fileName || 'Nada.png').replace(/^Arquivo:|^File:/, ''));
            const base = (window.mw && mw.util && typeof mw.util.wikiScript === 'function') ? mw.util.wikiScript() : (window.mw && window.mw.config ? (mw.config.get('wgScript') || '/index.php') : '/index.php');
            return `${base}?title=Especial:FilePath/${f}`;
        } function slugify(s) {
            if (!s) return '';
            return String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^\w\s-]/g, '').replace(/[\s:/\-]+/g, '-').replace(/^-+|-+$/g, '').replace(/-+/g, '-');
        } window.__skillSlugify = slugify;
        function getLangKey() {
            const skillsRoot = document.getElementById('skills');
            const raw = (document.documentElement.lang || skillsRoot?.dataset.i18nDefault || 'pt').toLowerCase();
            return raw === 'pt-br' ? 'pt' : (raw.split('-')[0] || 'pt');
        } function chooseDescFrom(obj) {
            const lang = getLangKey();
            // Aceita tanto desc_i18n quanto desc para compatibilidade
            const pack = obj.desc_i18n || obj.desc || {
                pt: obj.descPt, en: obj.descEn, es: obj.descEs, pl: obj.descPl
            };
            return (pack && (pack[lang] || pack.pt || pack.en || pack.es || pack.pl)) || '';
        } function renderSubAttributesFromObj(s, L) {
            const chip = (label, val) => (val ? `<div class="attr-row"><span class="attr-label">${label}</span><span class="attr-value">${val}</span></div>` : '');
            const pve = (s.powerpve || '').toString().trim();
            const pvp = (s.powerpvp || '').toString().trim();
            const en = (s.energy || '').toString().trim();
            const cd = (s.cooldown || '').toString().trim();
            const rows = [cd ? chip(L.cooldown, cd) : '', en ? chip((en.startsWith('-') ? L.energy_cost : L.energy_gain), en.startsWith('-') ? en.replace(/^-/, '') : en.replace(/^\+?/, '')) : '', pve ? chip(L.power, pve) : '', pvp ? chip(L.power_pvp, pvp) : '',].filter(Boolean);
            return rows.length ? `<div class="attr-list">${rows.join('')}</div>` : '';
        } function getFlagIconURL(key) {
            if (!FLAG_ICON_FILES[key]) return '';
            if (!flagIconURLCache.has(key)) {
                flagIconURLCache.set(key, filePathURL(FLAG_ICON_FILES[key]));
            } return flagIconURLCache.get(key);
        } function renderFlagsRow(flags) {
            const arr = (flags || []).filter(Boolean);
            if (!arr.length) return '';
            const cacheKey = arr.join('|');
            if (flagRowCache.has(cacheKey)) {
                return flagRowCache.get(cacheKey);
            } const items = arr.map(k => {
                const url = getFlagIconURL(k);
                return url ? `<img class="skill-flag" data-flag="${k}" alt="" src="${url}">` : '';
            }).join('');
            const html = items ? `<div class="skill-flags" role="group" aria-label="Características">${items}</div>` : '';
            if (html) flagRowCache.set(cacheKey, html);
            return html;
        } function applyFlagTooltips(container) {
            const skillsRoot = document.getElementById('skills');
            if (!skillsRoot) return;
            let pack = {
            };
            try {
                pack = JSON.parse(skillsRoot.dataset.i18nFlags || '{}');
            } catch (e) {
            } const lang = getLangKey();
            const dict = pack[lang] || pack.pt || {
            };
            const flags = container.querySelectorAll('.skill-flags .skill-flag[data-flag]');
            const tooltip = window.__globalSkillTooltip;
            if (!tooltip) return;
            flags.forEach(el => {
                const key = el.getAttribute('data-flag');
                const tip = (dict && dict[key]) || '';
                if (!tip) return;
                if (el.dataset.flagTipWired) return;
                el.dataset.flagTipWired = '1';
                el.setAttribute('aria-label', tip);
                if (el.hasAttribute('title')) el.removeAttribute('title');
                el.addEventListener('mouseenter', () => {
                    const tipEl = document.querySelector('.skill-tooltip');
                    if (tipEl) tipEl.classList.add('flag-tooltip');
                    tooltip.show(el, tip);
                });
                el.addEventListener('mousemove', () => {
                    if (performance.now() >= tooltip.lockUntil.value) {
                        tooltip.measureAndPos(el);
                    }
                });
                el.addEventListener('click', () => {
                    tooltip.lockUntil.value = performance.now() + 240;
                    tooltip.measureAndPos(el);
                });
                el.addEventListener('mouseleave', () => {
                    const tipEl = document.querySelector('.skill-tooltip');
                    if (tipEl) tipEl.classList.remove('flag-tooltip');
                    tooltip.hide();
                });
            });
        }


         // Cache das skills principais (capturado na carga da página)
         // ====== Skill/Subskill inheritance helpers ======
         let cachedMainSkills = null;
        const mainSkillsMeta = {
            byIndex: new Map(),
            byName: new Map(),
            ready: false
         };
 
        function normalizeFileURL(raw, fallback = '') {
            if (!raw) return fallback;
            const val = String(raw).trim();
            if (!val) return fallback;
            if (/^(https?:)?\/\//i.test(val) || val.startsWith('data:') || val.includes('Especial:FilePath/')) {
                return val;
            } return filePathURL(val);
        }


        // ===== HERANÇA DE ATRIBUTOS: busca dados das skills principais =====
         function extractFileNameFromURL(url) {
         function getMainSkillsMap() {
             if (!url) return '';
             // Retorna cache se já foi construído E tem dados
            const match = String(url).match(/(?:FilePath\/)([^&?]+)/i);
            if (cachedMainSkills && cachedMainSkills.byIndex.size > 0) {
            return match ? decodeURIComponent(match[1]) : '';
                return cachedMainSkills;
        }
            }


             const maps = {
        function parseAttrString(raw) {
                 byName: new Map(),
            const parts = (raw || '').split(',').map(v => v.trim());
                 byIndex: new Map()
             const safe = idx => {
                 const val = parts[idx] || '';
                return (val && val !== '-') ? val : '';
            };
            return {
                powerpve: safe(0),
                powerpvp: safe(1),
                energy: safe(2),
                 cooldown: safe(3)
             };
             };
        }


            // Busca skills com data-index (skills principais, não subskills)
        function hasText(value) {
             const icons = document.querySelectorAll('.icon-bar .skill-icon[data-index][data-nome]');
             return typeof value === 'string' ? value.trim() !== '' : value !== undefined && value !== null;
        }


             icons.forEach(icon => {
        function pickFilled(current, fallback) {
                const name = (icon.dataset.nome || '').trim();
             if (current === 0 || current === '0') return current;
                if (!name) return;
            if (!hasText(current)) return fallback;
            return current;
        }


                // Extrai atributos do data-atr (formato: "pve, pvp, energy, cd")
        function buildMainSkillsMeta(nodes) {
                 const atrRaw = icon.dataset.atr || '';
            if (mainSkillsMeta.ready) {
                const parts = atrRaw.split(',').map(x => (x || '').trim());
                 return mainSkillsMeta;
                 const powerpve = parts[0] && parts[0] !== '-' ? parts[0] : '';
            }
                 const powerpvp = parts[1] && parts[1] !== '-' ? parts[1] : '';
            (nodes || []).forEach(icon => {
                 const energy = parts[2] && parts[2] !== '-' ? parts[2] : '';
                const index = (icon.dataset.index || '').trim();
                const cooldown = parts[3] && parts[3] !== '-' ? parts[3] : '';
                 if (!index) return;
 
                 const name = (icon.dataset.nome || icon.dataset.name || '').trim();
                // Nome original do arquivo de ícone (armazenado no dataset pelo widget de skills)
                 const attrs = parseAttrString(icon.dataset.atr || '');
                 let iconFile = (icon.dataset.iconFile || '').trim();
                 let iconFile = (icon.dataset.iconFile || '').trim();
                 if (!iconFile) {
                 if (!iconFile) {
Linha 44: Linha 178:
                     iconFile = iconMatch ? decodeURIComponent(iconMatch[1]) : '';
                     iconFile = iconMatch ? decodeURIComponent(iconMatch[1]) : '';
                 }
                 }
                // Nome original do arquivo de vídeo (caso exista)
                 let videoFile = (icon.dataset.videoFile || '').trim();
                 let videoFile = (icon.dataset.videoFile || '').trim();
                 if (!videoFile) {
                 if (!videoFile) {
                     const videoUrl = icon.dataset.video || '';
                     videoFile = extractFileNameFromURL(icon.dataset.video || '');
                    const videoMatch = videoUrl.match(/FilePath\/([^&?]+)/);
                    videoFile = videoMatch ? decodeURIComponent(videoMatch[1]) : '';
                 }
                 }
 
                 const meta = {
                 const index = (icon.dataset.index || '').trim();
                    index,
 
                     name,
                const data = {
                     icon: iconFile || 'Nada.png',
                     name: name, // Inclui o nome para herança completa
                     icon: iconFile,
                     level: icon.dataset.level || '',
                     level: icon.dataset.level || '',
                     video: videoFile,
                     video: videoFile || '',
                     powerpve: powerpve,
                     powerpve: attrs.powerpve || '',
                     powerpvp: powerpvp,
                     powerpvp: attrs.powerpvp || '',
                     cooldown: cooldown,
                    energy: attrs.energy || '',
                     energy: energy
                     cooldown: attrs.cooldown || '',
                    desc: icon.dataset.desc || '',
                    descPt: icon.dataset.descPt || '',
                    descEn: icon.dataset.descEn || '',
                    descEs: icon.dataset.descEs || '',
                     descPl: icon.dataset.descPl || ''
                 };
                 };
 
                 mainSkillsMeta.byIndex.set(index, meta);
                 // Mantém descrições caso precise como fallback extra
                 mainSkillsMeta.byIndex.set(parseInt(index, 10), meta);
                if (icon.dataset.descPt) data.descPt = icon.dataset.descPt;
                 if (name) {
                 if (icon.dataset.descEn) data.descEn = icon.dataset.descEn;
                     mainSkillsMeta.byName.set(name, meta);
                if (icon.dataset.descEs) data.descEs = icon.dataset.descEs;
                if (icon.dataset.descPl) data.descPl = icon.dataset.descPl;
 
                maps.byName.set(name, data);
                 if (index) {
                     // Guarda tanto como string quanto como número para compatibilidade
                    maps.byIndex.set(index, data);
                    maps.byIndex.set(parseInt(index, 10), data);
                 }
                 }
             });
             });
 
             mainSkillsMeta.ready = true;
            // Cacheia para uso futuro (importante: as skills principais não mudam)
             return mainSkillsMeta;
             cachedMainSkills = maps;
             return maps;
         }
         }


         // Aplica herança COMPLETA: se subskill só tem refM, busca TUDO da skill principal
         function inheritSubskillFromMain(sub, meta) {
        function applyInheritance(sub, mainSkills) {
            if (!sub || !meta) return sub;
            // Suporta refS (novo) e refM (legado)
            const refS = ((sub.refS || sub.S || sub.s || '') + '').trim();
            const refIndex = ((sub.refM || sub.M || sub.m || '') + '').trim();
             let name = (sub.name || sub.n || '').trim();
             let name = (sub.name || sub.n || '').trim();
             const refIndex = ((sub.refM || sub.m || sub.M || '') + '').trim();
             let main = null;




            let main = null;
             // Primeiro tenta por refS
             // Tenta como string
             if (refS) {
             if (refIndex && mainSkills.byIndex.has(refIndex)) {
                 main = meta.byIndex.get(refS) || meta.byIndex.get(parseInt(refS, 10));
                 main = mainSkills.byIndex.get(refIndex);
             }
             }
             // Tenta como número
             // Depois por refM
             if (!main && refIndex) {
             if (!main && refIndex) {
                 const numIndex = parseInt(refIndex, 10);
                 main = meta.byIndex.get(refIndex) || meta.byIndex.get(parseInt(refIndex, 10));
                if (!isNaN(numIndex) && mainSkills.byIndex.has(numIndex)) {
                    main = mainSkills.byIndex.get(numIndex);
                }
             }
             }
             if (!main && name && mainSkills.byName.has(name)) {
            // Por último pelo nome
                 main = mainSkills.byName.get(name);
             if (!main && name) {
                 main = meta.byName.get(name);
             }
             }
            // Se não tem main skill para herdar, retorna como está
             if (!main) {
             if (!main) {
                 return sub;
                 return sub;
             }
             }


             // Se não tem nome mas tem refM, herda o nome da skill principal
             const hydrated = { ...sub };
             if (!name && refIndex && main.name) {
             if (!name && main.name) {
                 name = main.name;
                 name = main.name;
             }
             }
            hydrated.name = name || hydrated.name || main.name || '';
            hydrated.icon = pickFilled(hydrated.icon, main.icon || 'Nada.png');
            hydrated.level = pickFilled(hydrated.level, main.level || '');
            hydrated.video = pickFilled(hydrated.video, main.video || '');
            hydrated.powerpve = pickFilled(hydrated.powerpve, main.powerpve || '');
            hydrated.powerpvp = pickFilled(hydrated.powerpvp, main.powerpvp || '');
            hydrated.energy = pickFilled(hydrated.energy, main.energy || '');
            hydrated.cooldown = pickFilled(hydrated.cooldown, main.cooldown || '');


             return {
             if (!hasText(hydrated.descPt) && hasText(main.descPt)) hydrated.descPt = main.descPt;
                ...sub,
            if (!hasText(hydrated.descEn) && hasText(main.descEn)) hydrated.descEn = main.descEn;
                name: name || main.name || sub.name,
            if (!hasText(hydrated.descEs) && hasText(main.descEs)) hydrated.descEs = main.descEs;
                icon: (sub.icon && sub.icon !== 'Nada.png' && sub.icon !== '') ? sub.icon : (main.icon || 'Nada.png'),
            if (!hasText(hydrated.descPl) && hasText(main.descPl)) hydrated.descPl = main.descPl;
                level: sub.level || main.level,
            if (!hasText(hydrated.desc) && hasText(main.desc)) hydrated.desc = main.desc;
                video: sub.video || main.video,
 
                powerpve: sub.powerpve || main.powerpve,
            if (!hydrated.desc_i18n && (hydrated.descPt || hydrated.descEn || hydrated.descEs || hydrated.descPl)) {
                powerpvp: sub.powerpvp || main.powerpvp,
                 hydrated.desc_i18n = {
                cooldown: sub.cooldown || main.cooldown,
                    pt: hydrated.descPt || '',
                 energy: sub.energy || main.energy,
                    en: hydrated.descEn || '',
                descPt: sub.descPt || (sub.desc_i18n?.pt) || main.descPt,
                    es: hydrated.descEs || '',
                descEn: sub.descEn || (sub.desc_i18n?.en) || main.descEn,
                    pl: hydrated.descPl || ''
                descEs: sub.descEs || (sub.desc_i18n?.es) || main.descEs,
                };
                descPl: sub.descPl || (sub.desc_i18n?.pl) || main.descPl
            }
            };
        }


        function filePathURL(fileName) {
             return hydrated;
            const f = encodeURIComponent((fileName || 'Nada.png').replace(/^Arquivo:|^File:/, ''));
            const base = (window.mw && mw.util && typeof mw.util.wikiScript === 'function')
                ? mw.util.wikiScript()
                : (window.mw && mw.config ? (mw.config.get('wgScript') || '/index.php') : '/index.php');
             return `${base}?title=Especial:FilePath/${f}`;
         }
         }


         function normalizeFileURL(raw, fallback = '') {
         function inheritSubskillTree(subs, meta) {
             if (!raw) return fallback;
             if (!Array.isArray(subs)) return [];
             const val = String(raw).trim();
             return subs.map(sub => {
            if (!val) return fallback;
                const hydrated = inheritSubskillFromMain(sub, meta);
            if (/^(https?:)?\/\//i.test(val) || val.startsWith('data:') || val.includes('Especial:FilePath/')) {
                if (Array.isArray(hydrated.subs)) {
                 return val;
                    hydrated.subs = inheritSubskillTree(hydrated.subs, meta);
             }
                }
            return filePathURL(val);
                 return hydrated;
             });
         }
         }


         function preloadImage(iconFile) {
         function collectAssetsFromSubs(subs, iconsSet, videosSet, flagsSet) {
             const url = filePathURL(iconFile || 'Nada.png');
             if (!Array.isArray(subs)) return;
            if (imagePreloadCache.has(url)) {
            subs.forEach(sub => {
                 return imagePreloadCache.get(url);
                const iconURL = normalizeFileURL(sub.icon || 'Nada.png', filePathURL('Nada.png'));
             }
                if (iconURL) iconsSet.add(iconURL);
             const promise = new Promise((resolve, reject) => {
                if (sub.video) {
                    const videoURL = normalizeFileURL(sub.video);
                    if (videoURL) videosSet.add(videoURL);
                } if (Array.isArray(sub.flags)) {
                    sub.flags.forEach(flagKey => {
                        const url = getFlagIconURL(flagKey);
                        if (url) flagsSet.add(url);
                    });
                } if (Array.isArray(sub.subs)) {
                    collectAssetsFromSubs(sub.subs, iconsSet, videosSet, flagsSet);
                }
            });
        } function buildAssetManifest() {
            if (window.__skillAssetManifest && window.__skillAssetManifest.ready) {
                 return window.__skillAssetManifest;
            } const iconsSet = new Set();
            const videosSet = new Set();
            const flagsSet = new Set();
            iconItems.forEach(el => {
                const img = el.querySelector('img');
                if (img && img.src) {
                    iconsSet.add(img.src);
                } else if (el.dataset.icon) {
                    iconsSet.add(normalizeFileURL(el.dataset.icon));
                } const videoRaw = (el.dataset.video || '').trim();
                if (videoRaw) {
                    videosSet.add(normalizeFileURL(videoRaw));
                } if (el.dataset.flags) {
                    try {
                        const parsedFlags = JSON.parse(el.dataset.flags);
                        (parsedFlags || []).forEach(flagKey => {
                            const url = getFlagIconURL(flagKey);
                            if (url) flagsSet.add(url);
                        });
                    } catch (e) {
                    }
                } if (el.dataset.subs) {
                    try {
                        const subs = JSON.parse(el.dataset.subs);
                        collectAssetsFromSubs(subs, iconsSet, videosSet, flagsSet);
                    } catch (e) {
                    }
                }
             });
             Object.keys(FLAG_ICON_FILES).forEach(flagKey => {
                const url = getFlagIconURL(flagKey);
                if (url) flagsSet.add(url);
            });
            const manifest = {
                icons: iconsSet, videos: videosSet, flags: flagsSet, ready: true
            };
            window.__skillAssetManifest = manifest;
            return manifest;
        } function preloadImagesFromSet(set) {
            if (!set || !set.size) return;
            set.forEach(url => {
                if (!url || imagePreloadCache.has(url)) return;
                 const img = new Image();
                 const img = new Image();
                 img.onload = () => resolve(url);
                 img.decoding = 'async';
                 img.onerror = () => resolve(url);
                img.loading = 'eager';
                 img.referrerPolicy = 'same-origin';
                 img.src = url;
                 img.src = url;
                imagePreloadCache.set(url, img);
            });
        } function preloadVideosFromSet(set) {
            if (!set || !set.size) return;
            const head = document.head || document.getElementsByTagName('head')[0];
            set.forEach(url => {
                if (!url || videoPreloadCache.has(url)) return;
                const link = document.createElement('link');
                link.rel = 'preload';
                link.as = 'video';
                link.href = url;
                link.crossOrigin = 'anonymous';
                head.appendChild(link);
                videoPreloadCache.add(url);
             });
             });
             imagePreloadCache.set(url, promise);
        } const subskillVideosCache = new Map();
             return promise;
        window.__subskillVideosCache = subskillVideosCache;
        let assetManifest = null;
        const skillsTab = $('#skills');
        const skinsTab = $('#skins');
        ensureRemoved('.top-rail');
        ensureRemoved('.content-card');
        ensureRemoved('.video-placeholder');
        Array.from(document.querySelectorAll('.card-skins-title, .card-skins .card-skins-title, .cardskins-title, .rail-title')).forEach(t => {
            if ((t.textContent || '').trim().toLowerCase().includes('skins')) {
                t.remove();
            }
        });
        if (skillsTab) {
            const iconBar = skillsTab.querySelector('.icon-bar');
            if (iconBar) {
                const rail = document.createElement('div');
                rail.className = 'top-rail skills';
                rail.appendChild(iconBar);
                skillsTab.prepend(rail);
            } const details = skillsTab.querySelector('.skills-details');
            const videoContainer = skillsTab.querySelector('.video-container');
            const card = document.createElement('div');
            card.className = 'content-card skills-grid';
            if (details) card.appendChild(details);
            if (videoContainer) card.appendChild(videoContainer);
            skillsTab.appendChild(card);
        } if (skinsTab) {
            const wrapper = skinsTab.querySelector('.skins-carousel-wrapper');
            const rail = document.createElement('div');
            rail.className = 'top-rail skins';
            const title = document.createElement('div');
            title.className = 'rail-title';
            title.textContent = 'Skins & Spotlights';
            rail.appendChild(title);
            if (wrapper) {
                const card = document.createElement('div');
                card.className = 'content-card';
                card.appendChild(wrapper);
                skinsTab.prepend(rail);
                skinsTab.appendChild(card);
             } else {
                skinsTab.prepend(rail);
            }
        } const iconsBar = $('#skills') ? $('.icon-bar', $('#skills')) : null;
        const skillsTopRail = iconsBar ? iconsBar.closest('.top-rail.skills') : null;
        const iconItems = iconsBar ? Array.from(iconsBar.querySelectorAll('.skill-icon')) : [];
        buildMainSkillsMeta(iconItems);
        // Verifica se há weapon em skills principais OU em subskills
        function checkHasAnyWeapon() {
            // Verifica skills principais
            if (iconItems.some(el => !!el.dataset.weapon)) {
                return true;
             }
            // Verifica subskills
            for (const el of iconItems) {
                const subsRaw = el.getAttribute('data-subs');
                if (!subsRaw) continue;
                try {
                    const subs = JSON.parse(subsRaw);
                    if (Array.isArray(subs) && subs.some(s => s && s.weapon)) {
                        return true;
                    }
                } catch (e) { }
            }
            return false;
        }
        const hasWeaponSkillAvailable = checkHasAnyWeapon();
        let weaponToggleBtn = null;
        if (!assetManifest) {
            assetManifest = buildAssetManifest();
            preloadImagesFromSet(assetManifest.icons);
            preloadImagesFromSet(assetManifest.flags);
            preloadVideosFromSet(assetManifest.videos);
        } const descBox = $('#skills') ? $('.desc-box', $('#skills')) : null;
        const videoBox = $('#skills') ? $('.video-container', $('#skills')) : null;
        const videosCache = new Map();
        const nestedVideoElByIcon = new WeakMap();
        const barStack = [];
        window.__barStack = barStack;
        let initialBarSnapshot = null;
        let totalVideos = 0, loadedVideos = 0, autoplay = false;
        window.__lastActiveSkillIcon = null;
        let userHasInteracted = false;
        let globalWeaponEnabled = false;
        try {
            if (localStorage.getItem('glaWeaponEnabled') === '1') {
                globalWeaponEnabled = true;
            }
        } catch (err) {
         }
         }
 
         const weaponStateListeners = new Set();
         function getLabels() {
        let showWeaponPopupFn = null;
            const skillsRoot = document.getElementById('skills');
        let popupShouldOpen = false;
            const i18nMap = skillsRoot ? JSON.parse(skillsRoot.dataset.i18nAttrs || '{}') : {};
        function attachWeaponPopupFn(fn) {
             const raw = (document.documentElement.lang || skillsRoot?.dataset.i18nDefault || 'pt').toLowerCase();
             if (typeof fn !== 'function') return;
             const lang = raw === 'pt-br' ? 'pt' : (raw.split('-')[0] || 'pt');
             showWeaponPopupFn = fn;
             return i18nMap[lang] || i18nMap.pt || {
             if (popupShouldOpen) {
                 cooldown: 'Recarga',
                 popupShouldOpen = false;
                 energy_gain: 'Ganho de energia',
                 try {
                energy_cost: 'Custo de energia',
                    showWeaponPopupFn();
                 power: 'Poder',
                 } catch (err) {
                 power_pvp: 'Poder PvP',
                 }
                level: 'Nível'
             }
             };
         }
         }
 
         attachWeaponPopupFn(window.__glaWeaponShowPopup);
         // Verifica se o modo weapon está ativo
         function requestWeaponPopupDisplay() {
         function isWeaponModeOn() {
             try {
             try {
                 return localStorage.getItem('glaWeaponEnabled') === '1';
                 if (localStorage.getItem('glaWeaponPopupDismissed') === '1') return;
             } catch (e) {
             } catch (err) {
                 return false;
            }
            if (typeof showWeaponPopupFn === 'function') {
                showWeaponPopupFn();
                 return;
             }
             }
            popupShouldOpen = true;
        }
        function onWeaponStateChange(fn) {
            if (typeof fn !== 'function') return;
            weaponStateListeners.add(fn);
        }
        function syncWeaponButtonState(enabled) {
            if (!weaponToggleBtn || !weaponToggleBtn.isConnected) return;
            // Usa .weapon-active em vez de .active para não conflitar com skills
            weaponToggleBtn.classList.toggle('weapon-active', !!enabled);
            weaponToggleBtn.classList.remove('active'); // Garante que .active nunca seja aplicado
            weaponToggleBtn.setAttribute('aria-pressed', enabled ? 'true' : 'false');
            weaponToggleBtn.setAttribute('aria-label', enabled ? 'Desativar Arma Especial' : 'Ativar Arma Especial');
         }
         }
 
         function syncWeaponRailState(enabled) {
        // Retorna os atributos corretos (weapon ou normal)
             if (skillsTopRail) {
         function getEffectiveAttrs(s) {
                 skillsTopRail.classList.toggle('weapon-mode-on', !!enabled);
            const weaponOn = isWeaponModeOn();
             if (weaponOn && s.weapon) {
                 return {
                    powerpve: s.weapon.powerpve || s.powerpve,
                    powerpvp: s.weapon.powerpvp || s.powerpvp,
                    energy: s.weapon.energy || s.energy,
                    cooldown: s.weapon.cooldown || s.cooldown
                };
             }
             }
            return {
                powerpve: s.powerpve,
                powerpvp: s.powerpvp,
                energy: s.energy,
                cooldown: s.cooldown
            };
         }
         }
 
         function notifyWeaponStateListeners(enabled) {
        // Retorna a descrição correta (weapon ou normal)
             weaponStateListeners.forEach(listener => {
        // Aceita tanto desc_i18n quanto desc para compatibilidade
                try {
         function getEffectiveDesc(s) {
                    listener(enabled);
             const weaponOn = isWeaponModeOn();
                 } catch (err) {
            const raw = (document.documentElement.lang || 'pt').toLowerCase();
            const lang = raw === 'pt-br' ? 'pt' : (raw.split('-')[0] || 'pt');
 
            // Para weapon: aceita tanto desc_i18n quanto desc
            if (weaponOn && s.weapon) {
                const wDesc = s.weapon.desc_i18n || s.weapon.desc;
                 if (wDesc) {
                    return wDesc[lang] || wDesc.pt || wDesc.en || '';
                 }
                 }
            });
        }
        let pendingWeaponState = null;
        window.addEventListener('weapon:ready', (ev) => {
            if (ev && ev.detail && ev.detail.showPopup) {
                attachWeaponPopupFn(ev.detail.showPopup);
             }
             }
 
             if (pendingWeaponState === null) return;
             // Para descrição base: aceita tanto desc_i18n quanto desc
             if (typeof window.__applyWeaponState === 'function') {
            const base = s.desc_i18n || s.desc;
                 const target = pendingWeaponState;
             if (base) {
                pendingWeaponState = null;
                 return base[lang] || base.pt || base.en || '';
                window.__applyWeaponState(target);
             }
             }
 
        });
            // Fallback para campos individuais (compatibilidade)
        window.__setGlobalWeaponEnabled = (enabled) => {
            const descI18n = {
             globalWeaponEnabled = enabled;
                pt: s.descPt || '',
             notifyWeaponStateListeners(enabled);
                en: s.descEn || '',
         };
                es: s.descEs || '',
         function requestWeaponState(targetState) {
                pl: s.descPl || ''
             if (typeof window.__applyWeaponState === 'function') {
             };
                pendingWeaponState = null;
             return descI18n[lang] || descI18n.pt || '';
                window.__applyWeaponState(targetState);
         }
                 return;
 
        // Retorna o vídeo correto (weapon ou normal)
         function getEffectiveVideo(s) {
            const weaponOn = isWeaponModeOn();
             if (weaponOn && s.weapon && s.weapon.video && s.weapon.video.trim() !== '') {
                 return s.weapon.video;
             }
             }
             return s.video || '';
             pendingWeaponState = targetState;
         }
         }
 
        onWeaponStateChange(syncWeaponButtonState);
         function renderSubAttrs(s, L) {
         function reapplyWeaponClassesToBar() {
             const chip = (label, val) => (val ? `<div class="attr-row"><span class="attr-label">${label}</span><span class="attr-value">${val}</span></div>` : '');
             if (!globalWeaponEnabled) return;
             const pve = (s.powerpve || '').toString().trim();
            // SISTEMA UNIFICADO: Aplica em skills E subskills
            const pvp = (s.powerpvp || '').toString().trim();
             iconsBar.querySelectorAll('.skill-icon[data-weapon], .subicon[data-weapon]').forEach(el => {
            const en = (s.energy || '').toString().trim();
                if (!el.classList.contains('has-weapon-available')) {
            const cd = (s.cooldown || '').toString().trim();
                    el.classList.add('has-weapon-available');
            const rows = [
                 }
                 cd ? chip(L.cooldown, cd) : '',
                 if (!el.querySelector('.weapon-indicator')) {
                 en ? chip((en.startsWith('-') ? L.energy_cost : L.energy_gain), en.startsWith('-') ? en.replace(/^-/, '') : en.replace(/^\+?/, '')) : '',
                    const ind = document.createElement('div');
                pve ? chip(L.power, pve) : '',
                    ind.className = 'weapon-indicator';
                pvp ? chip(L.power_pvp, pvp) : '',
                    el.appendChild(ind);
            ].filter(Boolean);
                }
             return rows.length ? `<div class="attr-list">${rows.join('')}</div>` : '';
             });
         }
         }
 
         function setupWeaponBarToggle(shouldShow) {
         function renderFlagsRow(flags) {
             if (!shouldShow || !iconsBar) return;
             const map = {
            if (iconsBar.querySelector('.weapon-bar-toggle')) return;
                aggro: 'Enemyaggro-icon.png',
            const btn = document.createElement('button');
                bridge: 'Bridgemaker-icon.png',
            btn.type = 'button';
                wall: 'Destroywall-icon.png',
            btn.className = 'skill-icon weapon-bar-toggle';
                quickcast: 'Quickcast-icon.png'
            btn.dataset.weaponToggle = '1';
             };
             btn.dataset.nome = 'Arma Especial';
             const arr = (flags || []).filter(Boolean);
             btn.setAttribute('aria-pressed', 'false');
             if (!arr.length) return '';
             btn.setAttribute('aria-label', 'Arma Especial');
             const items = arr.map(k => `<img class="skill-flag" data-flag="${k}" alt="" src="${filePathURL(map[k])}">`).join('');
             btn.innerHTML = '<svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path fill="currentColor" d="M19.14 12.94c.04-.31.06-.63.06-.94s-.02-.63-.06-.94l2.03-1.58a.5.5 0 00.12-.62l-1.92-3.32a.5.5 0 00-.61-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.37-2.48a.55.55 0 00-.55-.5h-3.82a.55.55 0 00-.55.5l-.37 2.48c-.59.24-1.12.56-1.62.94l-2.39-.96a.5.5 0 00-.61.22L3.13 8.5a.5.5 0 00.12.62l2.03 1.58c-.04.31-.06.63-.06.94s.02.63.06.94l-2.03 1.58a.5.5 0 00-.12.62l1.92 3.32a.5.5 0 00.61.22l2.39-.96c.5.38 1.03.7 1.62.94l.37 2.48a.55.55 0 00.55.5h3.82a.55.55 0 00.55-.5l.37-2.48c.59-.24 1.12-.56 1.62-.94l2.39.96a.5.5 0 00.61-.22l1.92-3.32a.5.5 0 00-.12-.62zM12 15.6a3.6 3.6 0 110-7.2 3.6 3.6 0 010 7.2z"></path></svg>';
            return `<div class="skill-flags" role="group" aria-label="Características">${items}</div>`;
            iconsBar.appendChild(btn);
        }
             weaponToggleBtn = btn;
 
             syncWeaponButtonState(globalWeaponEnabled);
        function applyFlagTooltips(container) {
             btn.addEventListener('click', () => {
             const skillsRoot = document.getElementById('skills');
                const nextState = !globalWeaponEnabled;
             if (!skillsRoot) return;
                if (nextState) {
             let pack = {};
                    requestWeaponPopupDisplay();
            try { pack = JSON.parse(skillsRoot.dataset.i18nFlags || '{}'); } catch (e) { }
                }
            const raw = (document.documentElement.lang || 'pt').toLowerCase();
                requestWeaponState(nextState);
            const lang = raw === 'pt-br' ? 'pt' : (raw.split('-')[0] || 'pt');
             });
             const dict = pack[lang] || pack.pt || {};
             // Wire tooltip for weapon toggle
             const flags = container.querySelectorAll('.skill-flags .skill-flag[data-flag]');
             const tooltip = window.__globalSkillTooltip;
             const tooltip = window.__globalSkillTooltip;
             if (!tooltip) return;
             if (tooltip) {
 
                 btn.addEventListener('mouseenter', () => {
            flags.forEach(el => {
                     const tip = document.querySelector('.skill-tooltip');
                 const key = el.getAttribute('data-flag');
                     if (tip) tip.classList.add('weapon-tooltip');
                const tip = (dict && dict[key]) || '';
                     tooltip.show(btn, globalWeaponEnabled ? 'Desativar Arma Especial' : 'Ativar Arma Especial');
                if (!tip) return;
                if (el.dataset.flagTipWired) return;
                el.dataset.flagTipWired = '1';
                el.setAttribute('aria-label', tip);
                if (el.hasAttribute('title')) el.removeAttribute('title');
 
                el.addEventListener('mouseenter', () => {
                     const tipEl = document.querySelector('.skill-tooltip');
                     if (tipEl) tipEl.classList.add('flag-tooltip');
                     tooltip.show(el, tip);
                });
                el.addEventListener('mousemove', () => {
                    if (performance.now() >= tooltip.lockUntil.value) {
                        tooltip.measureAndPos(el);
                    }
                });
                el.addEventListener('click', () => {
                    tooltip.lockUntil.value = performance.now() + 240;
                    tooltip.measureAndPos(el);
                 });
                 });
                 el.addEventListener('mouseleave', () => {
                 btn.addEventListener('mouseleave', () => {
                     const tipEl = document.querySelector('.skill-tooltip');
                     const tip = document.querySelector('.skill-tooltip');
                     if (tipEl) tipEl.classList.remove('flag-tooltip');
                     if (tip) tip.classList.remove('weapon-tooltip');
                     tooltip.hide();
                     tooltip.hide();
                 });
                 });
             });
             }
            reapplyWeaponClassesToBar();
         }
         }
 
        onWeaponStateChange(syncWeaponRailState);
         function ensureRail(iconsBar) {
        syncWeaponRailState(globalWeaponEnabled);
             console.log('[DEBUG Subskills] ensureRail chamado, iconsBar:', iconsBar);
         setupWeaponBarToggle(hasWeaponSkillAvailable);
             const rail = iconsBar.closest('.top-rail');
        (function injectWeaponStyles() {
            if (!rail) {
             if (document.getElementById('weapon-toggle-styles')) return;
                 console.error('[DEBUG Subskills] ensureRail: .top-rail não encontrado! iconsBar:', iconsBar);
             const style = document.createElement('style');
                 return null;
            style.id = 'weapon-toggle-styles';
            style.textContent = `
                /* Animação da borda nos ícones */
                @keyframes weapon-icon-border-scan {
                    0% { background-position: 0% 0%; }
                    100% { background-position: 400% 0%; }
                }
                @keyframes weapon-icon-pulse {
                    0%, 100% {
                        opacity: 0.5;
                        box-shadow: 0 0 8px rgba(255, 80, 80, 0.25);
                    }
                    50% {
                        opacity: 1;
                        box-shadow: 0 0 16px rgba(255, 80, 80, 0.45);
                    }
                }
                /* Skills com arma disponível - borda vermelha quando inativa */
                .skill-icon.has-weapon-available:not(.weapon-bar-toggle):not(.active)::after {
                    box-shadow: inset 0 0 0 var(--icon-ring-w) rgba(220, 70, 70, 0.8) !important;
                }
                /* Skill com arma ATIVA - laranja/coral vibrante */
                .skill-icon.has-weapon-available:not(.weapon-bar-toggle).active::after {
                    box-shadow: inset 0 0 0 var(--icon-ring-w) #FF7043 !important;
                }
                .skill-icon.has-weapon-available:not(.weapon-bar-toggle).active::before {
                    box-shadow: 0 0 12px 3px rgba(255, 112, 67, 0.35), 0 0 0 4px rgba(255, 112, 67, 0.25) !important;
                }
                /* Modo arma ON - efeito animado nos ícones */
                .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle) {
                    position: relative;
                }
                .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle)::after {
                    box-shadow: none !important;
                    background: linear-gradient(90deg,
                        rgba(255, 80, 80, 0.9) 0%,
                        rgba(255, 120, 60, 1) 25%,
                        rgba(255, 80, 80, 0.9) 50%,
                        rgba(255, 120, 60, 1) 75%,
                        rgba(255, 80, 80, 0.9) 100%
                    ) !important;
                    background-size: 400% 100% !important;
                    animation: weapon-icon-border-scan 4s linear infinite !important;
                    -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0) !important;
                    mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0) !important;
                    -webkit-mask-composite: xor !important;
                    mask-composite: exclude !important;
                    padding: var(--icon-ring-w) !important;
                }
                .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle)::before {
                    animation: weapon-icon-pulse 3s ease-in-out infinite !important;
                }
                /* Skill ativa com arma - mais intenso */
                 .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle).active::after {
                    background: linear-gradient(90deg,
                        rgba(255, 87, 34, 1) 0%,
                        rgba(255, 140, 60, 1) 25%,
                        rgba(255, 87, 34, 1) 50%,
                        rgba(255, 140, 60, 1) 75%,
                        rgba(255, 87, 34, 1) 100%
                    ) !important;
                }
                .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle).active::before {
                    box-shadow: 0 0 14px 4px rgba(255, 87, 34, 0.4), 0 0 0 4px rgba(255, 87, 34, 0.3) !important;
                    animation: weapon-icon-pulse 2.5s ease-in-out infinite !important;
                }
                .skill-icon .weapon-indicator {
                    display: none;
                }
                /* Variáveis de cor vermelha para skill ativa com arma equipada */
                .skill-icon.weapon-equipped {
                    --icon-active: #FF6B6B;
                    --icon-active-ring: rgba(255, 100, 100, 0.6);
                    --icon-active-glow: rgba(255, 90, 90, 0.45);
                }
                /* Badge de arma no canto inferior direito */
                .skill-icon .weapon-badge {
                    position: absolute;
                    bottom: 3px;
                    right: 3px;
                    width: 16px;
                    height: 16px;
                    background: var(--weapon-badge-url) center/contain no-repeat;
                    filter: drop-shadow(0 1px 2px rgba(0,0,0,0.6));
                    pointer-events: none;
                    z-index: 10;
                    border-radius: 3px;
                    display: none;
                }
                .skill-icon.weapon-equipped .weapon-badge {
                    display: block;
                }
            `.replace(/\s+/g, ' ').trim();
            document.head.appendChild(style);
        })();
        function applyWeaponBadge(el, weaponData, equipped) {
            // Encontrar ou criar o badge
            let badge = el.querySelector('.weapon-badge');
            if (!badge) {
                badge = document.createElement('div');
                badge.className = 'weapon-badge';
                 el.appendChild(badge);
             }
             }
            console.log('[DEBUG Subskills] ensureRail: rail encontrado:', rail);


             if (!subRail) {
             if (equipped && weaponData) {
                 subRail = document.createElement('div');
                 el.classList.add('weapon-equipped');
                 subRail.className = 'subskills-rail collapsed hidden';
                 el.style.setProperty('--weapon-badge-url', `url('${filePathURL(weaponData.icon || 'Nada.png')}')`);
                rail.appendChild(subRail);
                console.log('[DEBUG Subskills] ensureRail: subRail criado e anexado:', subRail);
             } else {
             } else {
                 console.log('[DEBUG Subskills] ensureRail: subRail já existe:', subRail);
                 el.classList.remove('weapon-equipped');
                el.style.removeProperty('--weapon-badge-url');
             }
             }
 
        } function getWeaponKey(el) {
            if (!subBar) {
            return (el.dataset.index || '') + ':' + (el.dataset.nome || el.dataset.name || '');
                subBar = document.createElement('div');
        } function isWeaponModeOn() {
                subBar.className = 'subicon-bar';
            try {
                subRail.appendChild(subBar);
                 return localStorage.getItem('glaWeaponEnabled') === '1';
                 console.log('[DEBUG Subskills] ensureRail: subBar criado e anexado:', subBar);
             } catch (e) {
             } else {
                 return false;
                 console.log('[DEBUG Subskills] ensureRail: subBar já existe:', subBar);
             }
             }
 
        } function getWeaponDataForIcon(iconEl) {
             if (!spacer) {
             if (!iconEl || !iconEl.dataset.weapon) return null;
                spacer = document.createElement('div');
            try {
                spacer.className = 'subskills-spacer';
                 return JSON.parse(iconEl.dataset.weapon);
                 rail.parentNode.insertBefore(spacer, rail.nextSibling);
            } catch (e) {
                console.log('[DEBUG Subskills] ensureRail: spacer criado e anexado:', spacer);
                return null;
             }
             }
        } function getEffectiveSkillVideoFromIcon(iconEl) {
            const weaponOn = globalWeaponEnabled;
            const weaponData = getWeaponDataForIcon(iconEl);
            const baseVideoFile = (iconEl.dataset.videoFile || '').trim();
            const baseVideoURL = (iconEl.dataset.video || '').trim();


             return rail;
             console.log('[Skills DEBUG]', {
        }
                skillName: iconEl.dataset.nome || iconEl.dataset.name,
                weaponOn,
                hasWeaponData: !!weaponData,
                weaponData: weaponData,
                baseVideoFile,
                baseVideoURL
            });


        function ensureSubVideoCached(s, parentIdx, videoBox) {
             if (weaponOn && weaponData && weaponData.video && weaponData.video.trim() !== '') {
            const key = `sub:${parentIdx}:${(s.name || s.n || '').trim()}`;
                 console.log('[Skills] video escolhido (weapon)', iconEl.dataset.nome || iconEl.dataset.name, weaponData.video);
             if (window.__subskillVideosCache && window.__subskillVideosCache.has(key)) {
                return weaponData.video.trim();
                 const precreated = window.__subskillVideosCache.get(key);
                if (!subCache.has(key)) {
                    subCache.set(key, precreated);
                }
                return key;
            }
            if (subCache.has(key)) return key;
            if (!s.video || s.video.trim() === '') return key;
            const videoFileName = s.video.trim();
            if (videoFileName === 'Nada.png' || videoFileName.toLowerCase().includes('nada.png')) {
                return key;
             }
             }
 
            const result = baseVideoFile || baseVideoURL || '';
            console.log('[Skills] video escolhido (base)', iconEl.dataset.nome || iconEl.dataset.name, result);
            return result;
        } function createVideoElement(videoURL, extraAttrs = {
        }) {
             const v = document.createElement('video');
             const v = document.createElement('video');
             v.className = 'skill-video';
             v.className = 'skill-video';
            v.dataset.sub = '1';
             v.setAttribute('controls', '');
             v.setAttribute('controls', '');
             v.setAttribute('preload', 'auto');
             v.setAttribute('preload', 'metadata');
             v.setAttribute('playsinline', '');
             v.setAttribute('playsinline', '');
             Object.assign(v.style, { display: 'none', width: '100%', height: 'auto', aspectRatio: '16/9', objectFit: 'cover' });
             v.style.display = 'none';
 
            v.style.width = '100%';
             const videoURL = normalizeFileURL(videoFileName);
            v.style.height = 'auto';
            if (!videoURL || videoURL.trim() === '') return key;
            v.style.aspectRatio = '16/9';
            v.style.objectFit = 'cover';
             Object.keys(extraAttrs).forEach(k => {
                v.dataset[k] = extraAttrs[k];
            });
             // Detectar formato do vídeo pela extensão
             // Detectar formato do vídeo pela extensão
             const ext = (videoURL.split('.').pop() || '').toLowerCase().split('?')[0];
             const ext = (videoURL.split('.').pop() || '').toLowerCase().split('?')[0];
Linha 405: Linha 764:
             v.setAttribute('webkit-playsinline', '');
             v.setAttribute('webkit-playsinline', '');
             v.setAttribute('x-webkit-airplay', 'allow');
             v.setAttribute('x-webkit-airplay', 'allow');
            videoBox.appendChild(v);
            subCache.set(key, v);
            if (window.__subskillVideosCache) {
                window.__subskillVideosCache.set(key, v);
            }
            v.load();
            return key;
        }


         // Cria vídeo de weapon em cache (para subskills com weapon) - lógica do arquivo antigo
            return v;
        function ensureSubVideoInCache(videoFileName, key, videoBox) {
         } function precreateSubskillVideos() {
             if (subCache.has(key)) return key;
            if (!videoBox) return;
             if (!videoFileName || videoFileName.trim() === '') return key;
            iconItems.forEach(parentIcon => {
            const videoFile = videoFileName.trim();
                const subsRaw = parentIcon.dataset.subs || parentIcon.getAttribute('data-subs');
            if (videoFile === 'Nada.png' || videoFile.toLowerCase().includes('nada.png')) {
                if (!subsRaw) return;
                 return key;
                try {
                    const subs = JSON.parse(subsRaw);
                    if (!Array.isArray(subs)) return;
                    const parentIdx = parentIcon.dataset.index || '';
                    subs.forEach(s => {
                        if (!s.video || s.video.trim() === '' || s.video === 'Nada.png' || s.video.toLowerCase().includes('nada.png')) return;
                        const subName = (s.name || s.n || '').trim();
                        const key = `sub:${parentIdx}:${subName}`;
                        if (subskillVideosCache.has(key)) return;
                        const videoURL = normalizeFileURL(s.video);
                        if (!videoURL || videoURL.trim() === '') return;
                        const v = createVideoElement(videoURL, {
                            sub: '1', parentIndex: parentIdx, subName: subName
                        });
                        videoBox.appendChild(v);
                        subskillVideosCache.set(key, v);
                    });
                } catch (e) {
                }
            });
        } setTimeout(precreateSubskillVideos, 500);
        if (iconItems.length && videoBox) {
             iconItems.forEach(el => {
                const src = (el.dataset.video || '').trim();
                const idx = el.dataset.index || '';
                if (!src || videosCache.has(idx)) return;
                totalVideos++;
                const v = createVideoElement(src, {
                    index: idx
                });
                v.style.maxWidth = '100%';
                v.addEventListener('canplaythrough', () => {
                    loadedVideos++;
                    if (!userHasInteracted && loadedVideos === 1) {
                        try {
                            v.pause();
                            v.currentTime = 0;
                        } catch (e) {
                        }
                    } if (loadedVideos === totalVideos) autoplay = true;
                }, {
                    once: true
                });
                v.addEventListener('error', () => {
                    loadedVideos++;
                    if (loadedVideos === totalVideos) autoplay = true;
                }, {
                    once: true
                });
                videoBox.appendChild(v);
                videosCache.set(idx, v);
            });
        } function wireTooltipsForNewIcons() {
            const tip = document.querySelector('.skill-tooltip');
             if (!tip) return;
            let lockUntil2 = 0;
            Array.from(document.querySelectorAll('.icon-bar .skill-icon')).forEach(icon => {
                if (icon.dataset.weaponToggle === '1' || icon.classList.contains('weapon-bar-toggle')) return;
                if (icon.dataset.tipwired) return;
                icon.dataset.tipwired = '1';
                const label = icon.dataset.nome || icon.dataset.name || icon.title || '';
                if (label && !icon.hasAttribute('aria-label')) icon.setAttribute('aria-label', label);
                if (icon.hasAttribute('title')) icon.removeAttribute('title');
                const img = icon.querySelector('img');
                if (img) {
                    const imgAlt = img.getAttribute('alt') || '';
                    const imgTitle = img.getAttribute('title') || '';
                    if (!label && (imgAlt || imgTitle)) icon.setAttribute('aria-label', imgAlt || imgTitle);
                    img.setAttribute('alt', '');
                    if (img.hasAttribute('title')) img.removeAttribute('title');
                } const measureAndPos = (el) => {
                    if (!el || tip.getAttribute('aria-hidden') === 'true') return;
                    tip.style.left = '0px';
                    tip.style.top = '0px';
                    const rect = el.getBoundingClientRect();
                    const tr = tip.getBoundingClientRect();
                    let left = Math.round(rect.left + (rect.width - tr.width) / 2);
                    left = Math.max(8, Math.min(left, window.innerWidth - tr.width - 8));
                    const coarse = (window.matchMedia && matchMedia('(pointer: coarse)').matches) || (window.innerWidth <= 600);
                    let top = coarse ? Math.round(rect.bottom + 10) : Math.round(rect.top - tr.height - 8);
                    if (top < 8) top = Math.round(rect.bottom + 10);
                    tip.style.left = left + 'px';
                    tip.style.top = top + 'px';
                };
                const show = (el, text) => {
                    tip.textContent = text || '';
                    tip.setAttribute('aria-hidden', 'false');
                    measureAndPos(el);
                    tip.style.opacity = '1';
                };
                const hide = () => {
                    tip.setAttribute('aria-hidden', 'true');
                    tip.style.opacity = '0';
                    tip.style.left = '-9999px';
                    tip.style.top = '-9999px';
                };
                icon.addEventListener('mouseenter', () => show(icon, (icon.dataset.nome || icon.dataset.name || '')));
                icon.addEventListener('mousemove', () => {
                    if (performance.now() >= lockUntil2) measureAndPos(icon);
                });
                icon.addEventListener('click', () => {
                    lockUntil2 = performance.now() + 240;
                    measureAndPos(icon);
                });
                icon.addEventListener('mouseleave', hide);
            });
        } function showVideoForIcon(el) {
            userHasInteracted = true;
            if (!videoBox) return;
            const effectiveVideo = getEffectiveSkillVideoFromIcon(el);
            if (!effectiveVideo || effectiveVideo.trim() === '') {
                videoBox.style.display = 'none';
                 return;
             }
             }
 
             const videoURL = normalizeFileURL(effectiveVideo);
            const v = document.createElement('video');
             if (!videoURL || videoURL.trim() === '') {
            v.className = 'skill-video';
                 videoBox.style.display = 'none';
            v.dataset.sub = '1';
                 return;
            v.dataset.weapon = '1';
            v.setAttribute('controls', '');
            v.setAttribute('preload', 'auto');
            v.setAttribute('playsinline', '');
            Object.assign(v.style, { display: 'none', width: '100%', height: 'auto', aspectRatio: '16/9', objectFit: 'cover' });
 
             const videoURL = normalizeFileURL(videoFile);
             if (!videoURL || videoURL.trim() === '') return key;
            const ext = (videoURL.split('.').pop() || '').toLowerCase().split('?')[0];
            const mimeTypes = {
                 'mp4': 'video/mp4',
                'm4v': 'video/mp4',
                'webm': 'video/webm',
                'ogv': 'video/ogg',
                'ogg': 'video/ogg',
                'mov': 'video/quicktime'
            };
            const mimeType = mimeTypes[ext] || 'video/mp4';
 
            const src = document.createElement('source');
            src.src = videoURL;
            src.type = mimeType;
            v.appendChild(src);
 
            v.setAttribute('webkit-playsinline', '');
            v.setAttribute('x-webkit-airplay', 'allow');
            videoBox.appendChild(v);
            subCache.set(key, v);
            if (window.__subskillVideosCache) {
                 window.__subskillVideosCache.set(key, v);
             }
             }
             v.load();
             Array.from(videoBox.querySelectorAll('video.skill-video')).forEach(v => {
            return key;
        }
 
        function showSubVideo(key, videoBox) {
            if (!videoBox) return;
            videoBox.querySelectorAll('.skill-video').forEach(v => {
                 try {
                 try {
                     v.pause();
                     v.pause();
Linha 470: Linha 897:
                 v.style.display = 'none';
                 v.style.display = 'none';
             });
             });
            if (window.__subskills) window.__subskills.hideAll?.(videoBox);
            const hasIdx = !!el.dataset.index;
            const weaponOn = globalWeaponEnabled;
            const weaponData = getWeaponDataForIcon(el);
            const isWeaponVideo = weaponOn && weaponData && weaponData.video && weaponData.video.trim() !== '';
            console.log('[Skills] showVideoForIcon chamado', {
                skillName: el.dataset.nome || el.dataset.name,
                weaponOn,
                isWeaponVideo,
                effectiveVideo: getEffectiveSkillVideoFromIcon(el)
            });
            const videoKey = isWeaponVideo ? `weapon:${getWeaponKey(el)}` : (el.dataset.index || '');
            if (hasIdx && !isWeaponVideo && videosCache.has(el.dataset.index)) {
                const v = videosCache.get(el.dataset.index);
                videoBox.style.display = 'block';
                v.style.display = 'block';
                try {
                    v.currentTime = 0;
                } catch (e) {
                }
                const suppress = document.body.dataset.suppressSkillPlay === '1';
                if (!suppress) {
                    v.play().catch(() => {
                    });
                } else {
                    try {
                        v.pause();
                    } catch (e) {
                    }
                }
                return;
            }
             let v = null;
             let v = null;
             if (window.__subskillVideosCache && window.__subskillVideosCache.has(key)) {
             if (isWeaponVideo) {
                 v = window.__subskillVideosCache.get(key);
                v = videoBox.querySelector(`video[data-weapon-key="${videoKey}"]`);
            } else {
                 v = nestedVideoElByIcon.get(el);
             }
             }
             if (!v) {
             if (!v) {
                 v = subCache.get(key);
                 v = createVideoElement(videoURL, isWeaponVideo ? {
            }
                    weaponKey: videoKey
            if (!v) {
                } : {});
                 videoBox.style.display = 'none';
                if (isWeaponVideo) {
                 return;
                    videoBox.appendChild(v);
                } else {
                    videoBox.appendChild(v);
                    nestedVideoElByIcon.set(el, v);
                }
            } else {
                 const src = v.querySelector('source');
                 if (src && src.src !== videoURL) {
                    src.src = videoURL;
                    v.load();
                }
             }
             }
             videoBox.style.display = 'block';
             videoBox.style.display = 'block';
Linha 489: Linha 961:
             const suppress = document.body.dataset.suppressSkillPlay === '1';
             const suppress = document.body.dataset.suppressSkillPlay === '1';
             if (!suppress) {
             if (!suppress) {
                 v.play?.().catch(() => {
                 v.play().catch(() => {
                 });
                 });
            } else {
                try {
                    v.pause();
                } catch (e) {
                }
             }
             }
         }
         } function activateSkill(el, options = {
 
         }) {
         api.refreshCurrentSubSafe = function () {
             const {
             const btn = document.querySelector('.subskills-rail .subicon.active');
                openSubs = true
             if (!btn) return false;
            } = options;
            const had = document.body.dataset.suppressSkillPlay;
            const tip = document.querySelector('.skill-tooltip');
            document.body.dataset.suppressSkillPlay = '1';
             if (tip) {
            try {
                 tip.setAttribute('aria-hidden', 'true');
                 btn.dispatchEvent(new Event('click', { bubbles: true }));
                 tip.style.opacity = '0';
            } finally {
                 tip.style.left = '-9999px';
                 if (had) document.body.dataset.suppressSkillPlay = had;
                tip.style.top = '-9999px';
                 else delete document.body.dataset.suppressSkillPlay;
             } const skillsRoot = document.getElementById('skills');
            }
             const i18nMap = skillsRoot ? JSON.parse(skillsRoot.dataset.i18nAttrs || '{}') : {
            return true;
            };
        };
             const L = i18nMap[getLangKey()] || i18nMap.pt || {
 
                 cooldown: 'Recarga', energy_gain: 'Ganho de energia', energy_cost: 'Custo de energia', power: 'Poder', power_pvp: 'Poder PvP', level: 'Nível'
        // Função auxiliar para aplicar classes de weapon nas subskills renderizadas
            };
        // PADRONIZADO: usa data-weapon (igual a Character.Skills.html)
            const name = el.dataset.nome || el.dataset.name || '';
        const applyWeaponClassesToSubskills = () => {
            const level = (el.dataset.level || '').trim();
             const weaponOn = isWeaponModeOn();
            let weaponData = null;
             // Busca TODAS as subskills com weapon usando o seletor correto
            if (el.dataset.weapon) {
            // Tenta múltiplos seletores para garantir que encontra
                try {
            let weaponSubs = document.querySelectorAll('.subicon[data-weapon]');
                    weaponData = JSON.parse(el.dataset.weapon);
             if (weaponSubs.length === 0) {
                } catch (e) {
                 // Tenta buscar em todas as subbars
                     weaponData = null;
                const allSubbars = document.querySelectorAll('.subicon-bar');
                if (allSubbars.length > 0) {
                    console.log('[Subskills] Nenhuma subskill encontrada com .subicon[data-weapon], tentando buscar em todas as subbars:', allSubbars.length);
                    allSubbars.forEach(bar => {
                        const subsInBar = bar.querySelectorAll('.subicon[data-weapon]');
                        if (subsInBar.length > 0) {
                            console.log('[Subskills] Subbar encontrada com', subsInBar.length, 'subskills com weapon');
                            weaponSubs = Array.from(weaponSubs).concat(Array.from(subsInBar));
                        }
                     });
                 }
                 }
             }
             } const hasWeapon = !!weaponData;
 
             const weaponEquipped = hasWeapon && globalWeaponEnabled;
             // Remove duplicatas
             const lang = getLangKey();
             weaponSubs = Array.from(new Set(Array.from(weaponSubs)));
             const baseDescPack = {
 
                 pt: el.dataset.descPt || '', en: el.dataset.descEn || '', es: el.dataset.descEs || '', pl: el.dataset.descPl || ''
             if (weaponSubs.length > 0) {
             };
                 console.log('[Subskills] applyWeaponClassesToSubskills chamado, weaponOn:', weaponOn, 'subskills com weapon:', weaponSubs.length);
             const baseDesc = baseDescPack[lang] || baseDescPack.pt || baseDescPack.en || baseDescPack.es || baseDescPack.pl || el.dataset.desc || '';
             }
            // Aceita tanto desc_i18n quanto desc para compatibilidade
 
            let weaponDescPack = {};
            // Só faz log detalhado se realmente encontrou subskills
             if (weaponData) {
             if (weaponSubs.length === 0 && document.querySelectorAll('.subicon').length > 0) {
                 if (weaponData.desc_i18n) {
                // Log adicional para debug apenas se há subicons mas nenhum com weapon
                     weaponDescPack = weaponData.desc_i18n;
                const allSubicons = document.querySelectorAll('.subicon');
                } else if (weaponData.desc) {
                console.log('[Subskills] Total de subicons no DOM:', allSubicons.length);
                    weaponDescPack = weaponData.desc;
                allSubicons.forEach((icon, idx) => {
                    const hasData = icon.hasAttribute('data-weapon');
                    const title = icon.title || icon.dataset.slug || `subicon-${idx}`;
                    console.log(`[Subskills] Subicon ${idx} "${title}": data-weapon=${hasData}`);
                });
             }
 
            weaponSubs.forEach(el => {
                 if (weaponOn) {
                     el.classList.add('has-weapon-available');
                    if (el.classList.contains('active')) {
                        el.classList.add('weapon-equipped');
                        // Só log se há subskill ativa
                        console.log('[Subskills] Subskill ativa marcada como weapon-equipped:', el.title || el.dataset.slug);
                    }
                 } else {
                 } else {
                     el.classList.remove('has-weapon-available');
                     weaponDescPack = {
                    el.classList.remove('weapon-equipped');
                        pt: weaponData.descPt || '', en: weaponData.descEn || '', es: weaponData.descEs || '', pl: weaponData.descPl || ''
                    };
                 }
                 }
            });
        };
        api.renderBarFrom = function (el, { iconsBar, descBox, videoBox }) {
            console.log('[DEBUG Subskills] renderBarFrom chamado, iconsBar:', iconsBar);
            const rail = ensureRail(iconsBar);
            if (!rail) {
                console.error('[DEBUG Subskills] ensureRail retornou null! iconsBar:', iconsBar);
                return;
             }
             }
 
            const weaponDesc = weaponDescPack[lang] || weaponDescPack.pt || weaponDescPack.en || weaponDescPack.es || weaponDescPack.pl || '';
             console.log('[DEBUG Subskills] rail encontrado:', rail, 'subRail:', subRail, 'subBar:', subBar);
             const chosenDesc = (weaponEquipped && weaponDesc) ? weaponDesc : baseDesc;
 
            const descHtml = chosenDesc.replace(/'''(.*?)'''/g, '<b>$1</b>');
             const rawSubs = el.getAttribute('data-subs') || '';
            let attrsHTML = '';
             const rawOrder = el.getAttribute('data-suborder') || '';
             if (weaponEquipped && weaponData) {
             const parentIdx = el.dataset.index || '';
                const wPve = (weaponData.powerpve || '').toString().trim();
 
                const wPvp = (weaponData.powerpvp || '').toString().trim();
             if (!rawSubs.trim()) {
                const wEnergy = (weaponData.energy || '').toString().trim();
                 console.log('[DEBUG Subskills] Sem data-subs, ocultando subskills');
                const wCd = (weaponData.cooldown || '').toString().trim();
                if (subRail) subRail.classList.add('collapsed');
                const weaponAttrs = [wPve, wPvp, wEnergy, wCd].join(',');
                if (subRail) subRail.classList.add('hidden');
                attrsHTML = renderAttributes(weaponAttrs);
                 if (subBar) subBar.innerHTML = '';
             } else {
                 if (spacer) spacer.style.height = '0px';
                attrsHTML = el.dataset.atr ? renderAttributes(el.dataset.atr) : (el.dataset.subattrs ? renderSubAttributesFromObj(JSON.parse(el.dataset.subattrs), L) : '');
            } let flagsHTML = '';
             if (el.dataset.flags) {
                try {
                    const flags = JSON.parse(el.dataset.flags);
                    flagsHTML = renderFlagsRow(flags);
                } catch (e) {
                }
            } if (descBox) {
                descBox.innerHTML = `<div class="skill-title"><h3>${name}</h3></div>${level ? `<div class="skill-level-line"><span class="attr-label">${L.level} ${level}</span></div>` : ''}${attrsHTML}<div class="desc">${descHtml}</div>`;
            } if (hasWeapon) {
                applyWeaponBadge(el, weaponData, weaponEquipped);
             } if (videoBox) {
                const oldFlags = videoBox.querySelector('.skill-flags');
                if (oldFlags) oldFlags.remove();
                if (flagsHTML) {
                    videoBox.insertAdjacentHTML('beforeend', flagsHTML);
                    applyFlagTooltips(videoBox);
                 }
            } const currIcons = Array.from(iconsBar.querySelectorAll('.skill-icon'));
            currIcons.forEach(i => i.classList.remove('active'));
            el.classList.add('active');
            if (!autoplay && loadedVideos > 0) autoplay = true;
            window.__lastActiveSkillIcon = el;
            // Lógica de vídeo: usa função centralizada que já considera weapon
            showVideoForIcon(el);
            const subsRaw = el.dataset.subs || el.getAttribute('data-subs');
            const isBack = el.dataset.back === 'true' || el.getAttribute('data-back') === 'true' || el.dataset.back === 'yes' || el.getAttribute('data-back') === 'yes' || el.dataset.back === '1' || el.getAttribute('data-back') === '1';
            if (isBack && barStack.length) {
                 const prev = barStack.pop();
                renderBarFromItems(prev.items);
                const btn = document.querySelector('.skills-back-wrapper');
                 if (btn) btn.style.display = barStack.length ? 'block' : 'none';
                 return;
                 return;
            } if (openSubs && subsRaw && subsRaw.trim() !== '') {
                if (barStack.length && barStack[barStack.length - 1].parentIcon === el) return;
                try {
                    const subs = JSON.parse(subsRaw);
                    pushSubBarFrom(subs, el);
                } catch {
                }
             }
             }
 
        } function wireClicksForCurrentBar() {
             let subs;
             const currIcons = Array.from(iconsBar.querySelectorAll('.skill-icon'));
            try { subs = JSON.parse(rawSubs); } catch { subs = []; }
             currIcons.forEach(el => {
 
                if (el.dataset.weaponToggle === '1' || el.classList.contains('weapon-bar-toggle')) return;
            // DEBUG: Verifica se weapon está presente no JSON do Lua
                if (el.dataset.wired) return;
            console.log('[Subskills] Total de subskills recebidas:', subs.length);
                el.dataset.wired = '1';
             console.log('[Subskills] JSON completo recebido do Lua:', JSON.stringify(subs, null, 2));
                 const label = el.dataset.nome || el.dataset.name || '';
            subs.forEach((sub, idx) => {
                el.setAttribute('aria-label', label);
                 const subName = (sub.name || sub.n || '').trim();
                 if (el.hasAttribute('title')) el.removeAttribute('title');
                 if (subName === 'Karmic Jishin') {
                const img = el.querySelector('img');
                     console.log('[Subskills] Karmic Jishin do JSON Lua:', {
                if (img) {
                        index: idx,
                     img.setAttribute('alt', '');
                        name: subName,
                    if (img.hasAttribute('title')) img.removeAttribute('title');
                        weapon: sub.weapon,
                } el.addEventListener('click', () => {
                        weaponType: typeof sub.weapon,
                    activateSkill(el, {
                        weaponKeys: sub.weapon ? Object.keys(sub.weapon) : null,
                         openSubs: true
                        hasDesc_i18n: !!(sub.weapon && sub.weapon.desc_i18n),
                        hasDesc: !!(sub.weapon && sub.weapon.desc),
                         fullSub: JSON.stringify(sub, null, 2)
                     });
                     });
                 }
                 });
                // Log todas as subskills com weapon
            });
                if (sub.weapon) {
            wireTooltipsForNewIcons();
                    console.log(`[Subskills] Subskill "${subName}" TEM WEAPON:`, {
        } function animateIconsBarEntrance() {
                        weapon: sub.weapon,
            Array.from(iconsBar.children).forEach((c, i) => {
                        keys: Object.keys(sub.weapon),
                c.style.opacity = '0';
                         hasDesc_i18n: !!sub.weapon.desc_i18n,
                c.style.transform = 'translateY(6px)';
                         hasDesc: !!sub.weapon.desc
                requestAnimationFrame(() => {
                    });
                    setTimeout(() => {
                } else {
                         c.style.transition = 'opacity .18s ease, transform .18s ease';
                     console.log(`[Subskills] Subskill "${subName}" SEM WEAPON`);
                         c.style.opacity = '1';
                 }
                        c.style.transform = 'translateY(0)';
                     }, i * 24);
                 });
             });
             });
 
        } function snapshotCurrentBarItemsFromDOM() {
            // NORMALIZADOR: Converte weaponPacked para weapon se necessário (fallback para dados legados)
             return Array.from(iconsBar.querySelectorAll('.skill-icon')).filter(el => el.dataset.weaponToggle !== '1').map(el => {
             subs = subs.map(sub => {
                const img = el.querySelector('img');
                // Se tem weaponPacked mas não tem weapon, tenta parsear
                const iconURL = img ? img.src : '';
                if (sub.weaponPacked && !sub.weapon && typeof sub.weaponPacked === 'string' && sub.weaponPacked.trim() !== '') {
                const subsRaw = el.dataset.subs || el.getAttribute('data-subs') || '';
                    const parts = sub.weaponPacked.split('~');
                let subs = null;
                    if (parts.length >= 2) {
                try {
                        sub.weapon = {
                    subs = subsRaw ? JSON.parse(subsRaw) : null;
                            icon: parts[0] || 'Nada.png',
                } catch {
                            powerpve: parts[1] || null,
                    subs = null;
                            powerpvp: parts[2] || null,
                } const subattrsRaw = el.dataset.subattrs || '';
                            cooldown: parts[3] || null,
                let flags = null;
                            video: parts[4] || '',
                if (el.dataset.flags) {
                            energy: parts[5] || null
                    try {
                        };
                        flags = JSON.parse(el.dataset.flags);
                        // Remove valores vazios
                    } catch (e) {
                        Object.keys(sub.weapon).forEach(k => {
                            if (sub.weapon[k] === '' || sub.weapon[k] === null) {
                                delete sub.weapon[k];
                            }
                        });
                     }
                     }
                 }
                 } let weapon = null;
                // Garante que weapon seja objeto válido
                 if (el.dataset.weapon) {
                 if (sub.weapon && typeof sub.weapon === 'string') {
                    // Tenta parsear como JSON primeiro
                     try {
                     try {
                         sub.weapon = JSON.parse(sub.weapon);
                         weapon = JSON.parse(el.dataset.weapon);
                     } catch {
                     } catch (e) {
                        // Se falhar, tenta formato ~
                        const parts = sub.weapon.split('~');
                        if (parts.length >= 2) {
                            sub.weapon = {
                                icon: parts[0] || 'Nada.png',
                                powerpve: parts[1] || null,
                                powerpvp: parts[2] || null,
                                cooldown: parts[3] || null,
                                video: parts[4] || '',
                                energy: parts[5] || null
                            };
                            Object.keys(sub.weapon).forEach(k => {
                                if (sub.weapon[k] === '' || sub.weapon[k] === null) {
                                    delete sub.weapon[k];
                                }
                            });
                        } else {
                            sub.weapon = null;
                        }
                     }
                     }
                 }
                 } return {
                 return sub;
                    name: el.dataset.nome || el.dataset.name || '', index: el.dataset.index || '', level: el.dataset.level || '', desc: el.dataset.desc || '', descPt: el.dataset.descPt || '', descEn: el.dataset.descEn || '', descEs: el.dataset.descEs || '', descPl: el.dataset.descPl || '', attrs: el.dataset.atr || el.dataset.attrs || '', video: el.dataset.video || '', iconURL, subs, subattrsStr: subattrsRaw, flags: flags, weapon: weapon
                };
            });
        } function ensureBackButton() {
            const rail = iconsBar.closest('.top-rail.skills');
            if (!rail) return null;
            let wrap = rail.parentElement;
            if (!wrap || !wrap.classList || !wrap.classList.contains('skills-rail-wrap')) {
                const parentNode = rail.parentNode;
                const newWrap = document.createElement('div');
                newWrap.className = 'skills-rail-wrap';
                parentNode.insertBefore(newWrap, rail);
                newWrap.appendChild(rail);
                wrap = newWrap;
            } let backWrap = wrap.querySelector('.skills-back-wrapper');
            if (!backWrap) {
                backWrap = document.createElement('div');
                backWrap.className = 'skills-back-wrapper';
                const btnInner = document.createElement('button');
                btnInner.className = 'skills-back';
                btnInner.type = 'button';
                btnInner.setAttribute('aria-label', 'Voltar');
                 btnInner.innerHTML = '<svg class="back-chevron" width="100%" height="100%" viewBox="0 0 36 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" preserveAspectRatio="xMidYMid meet"><path d="M10 2L4 16L10 30" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/><path d="M20 2L14 16L20 30" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/><path d="M30 2L24 16L30 30" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
                backWrap.appendChild(btnInner);
                wrap.insertBefore(backWrap, rail);
                btnInner.addEventListener('click', () => {
                    if (!barStack.length) return;
                    const prev = barStack.pop();
                    renderBarFromItems(prev.items);
                    backWrap.style.display = barStack.length ? 'block' : 'none';
                    wrap.classList.toggle('has-sub-bar', barStack.length > 0);
                    if (!barStack.length) btnInner.classList.remove('peek');
                });
            } backWrap.style.display = barStack.length ? 'block' : 'none';
            wrap.classList.toggle('has-sub-bar', barStack.length > 0);
            const btnInner = backWrap.querySelector('.skills-back');
            return btnInner;
        } function renderBarFromItems(items) {
            const tip = document.querySelector('.skill-tooltip');
            if (tip) {
                tip.setAttribute('aria-hidden', 'true');
                tip.style.opacity = '0';
                tip.style.left = '-9999px';
                tip.style.top = '-9999px';
            } iconsBar.innerHTML = '';
            items.forEach((it, idx) => {
                const node = document.createElement('div');
                node.className = 'skill-icon';
                node.dataset.nome = it.name || '';
                if (it.index) node.dataset.index = it.index;
                if (it.level) node.dataset.level = it.level;
                if (it.desc) node.dataset.desc = it.desc;
                if (it.descPt) node.dataset.descPt = it.descPt;
                if (it.descEn) node.dataset.descEn = it.descEn;
                if (it.descEs) node.dataset.descEs = it.descEs;
                if (it.descPl) node.dataset.descPl = it.descPl;
                if (it.attrs) node.dataset.atr = it.attrs;
                if (it.video) node.dataset.video = it.video;
                if (it.subs) node.dataset.subs = JSON.stringify(it.subs);
                if (it.subattrsStr) node.dataset.subattrs = it.subattrsStr;
                if (it.flags) node.dataset.flags = JSON.stringify(it.flags);
                if (it.weapon) node.dataset.weapon = JSON.stringify(it.weapon);
                if (!it.index) node.dataset.nested = '1';
                const img = document.createElement('img');
                img.alt = '';
                img.src = it.iconURL || (it.icon ? filePathURL(it.icon) : '');
                node.appendChild(img);
                iconsBar.appendChild(node);
            });
            animateIconsBarEntrance();
            wireClicksForCurrentBar();
            setupWeaponBarToggle(hasWeaponSkillAvailable);
            const b = ensureBackButton();
            if (b) b.classList.add('peek');
        } function pushSubBarFrom(subs, parentIconEl) {
            const tip = document.querySelector('.skill-tooltip');
            if (tip) {
                tip.setAttribute('aria-hidden', 'true');
                tip.style.opacity = '0';
                tip.style.left = '-9999px';
                tip.style.top = '-9999px';
            } const parentNameSnapshot = parentIconEl ? (parentIconEl.dataset.nome || parentIconEl.dataset.name || '') : '';
            const parentIndexSnapshot = parentIconEl ? (parentIconEl.dataset.index || '') : '';
            barStack.push({
                items: snapshotCurrentBarItemsFromDOM(), parentIcon: parentIconEl, parentName: parentNameSnapshot, parentIndex: parentIndexSnapshot
             });
             });
 
            ensureBackButton();
             if (!Array.isArray(subs) || subs.length === 0) {
             const langKey = getLangKey();
                 subRail.classList.add('collapsed');
            let cacheKey = null;
                 subRail.classList.add('hidden');
            if (parentIconEl) {
                subBar.innerHTML = '';
                 cacheKey = parentIconEl.dataset.subCacheKey || null;
                if (spacer) spacer.style.height = '0px';
                 if (!cacheKey) {
                return;
                    if (parentIconEl.dataset.index) {
            }
                        cacheKey = `idx:${parentIconEl.dataset.index}`;
 
                    } else {
            // Busca mapa das skills principais para herança
                        const slug = slugify(parentIconEl.dataset.nome || parentIconEl.dataset.name || '');
            const mainSkills = getMainSkillsMap();
                        if (slug) cacheKey = `slug:${slug}`;
 
                    } if (cacheKey) parentIconEl.dataset.subCacheKey = cacheKey;
 
 
            // Aplica herança ANTES de processar - isso resolve nome, icon, etc.
            subs = subs.map(sub => applyInheritance(sub, mainSkills));
 
 
            // Verifica weapon nas subskills
            subs.forEach((s, i) => {
                if (s.weapon) {
                    console.log(`[Subskills] Sub ${i} TEM WEAPON:`, JSON.stringify(s.weapon));
                 }
                 }
             });
             } if (cacheKey) {
 
                const cached = subBarTemplateCache.get(cacheKey);
            // Remove subskills que ficaram sem nome após herança (herança falhou)
                if (cached && cached.lang === langKey) {
            subs = subs.filter(s => (s.name || s.n || '').trim() !== '');
                    iconsBar.innerHTML = '';
 
                    const clone = cached.template.cloneNode(true);
 
                    iconsBar.appendChild(clone);
            subRail.classList.add('hidden');
                     animateIconsBarEntrance();
            subBar.innerHTML = '';
                     wireClicksForCurrentBar();
 
                    setupWeaponBarToggle(hasWeaponSkillAvailable);
            // Usa a ordem natural das subskills após herança
                     const cachedBtn = ensureBackButton();
            let order = subs.map(s => s.name || s.n || '');
                    if (cachedBtn) cachedBtn.classList.add('peek');
            if (rawOrder.trim()) {
                     return;
                try {
                     const preferred = JSON.parse(rawOrder);
                     if (Array.isArray(preferred) && preferred.length) {
                        const byName = new Map(subs.map(s => [(s.name || s.n || ''), s]));
                        order = preferred.filter(n => byName.has(n));
                     }
                } catch { }
            }
 
            order.forEach(nm => {
                const s = subs.find(x => (x.name || x.n || '') === nm);
                if (s) {
                    if (s.video) ensureSubVideoCached(s, parentIdx, videoBox);
                     if (s.icon) preloadImage(s.icon);
                 }
                 }
            } const skillsRoot = document.getElementById('skills');
            const i18nMap = skillsRoot ? JSON.parse(skillsRoot.dataset.i18nAttrs || '{}') : {
            };
            const L = i18nMap[getLangKey()] || i18nMap.pt || {
                cooldown: 'Recarga', energy_gain: 'Ganho de energia', energy_cost: 'Custo de energia', power: 'Poder', power_pvp: 'Poder PvP', level: 'Nível'
            };
            const hydratedSubs = inheritSubskillTree(subs, mainSkillsMeta);
            const items = (hydratedSubs || []).filter(s => {
                // Filtra só se não tem nada útil
                const hasName = (s.name || s.n || '').trim() !== '';
                const hasIcon = (s.icon || '').trim() !== '' && s.icon !== 'Nada.png';
                const hasRef = (s.refS || s.refM || '').toString().trim() !== '';
                return hasName || hasIcon || hasRef;
            }).map(s => {
                const name = (s.name || s.n || '').trim();
                const desc = chooseDescFrom(s).replace(/'''(.*?)'''/g, '<b>$1</b>');
                const attrsHTML = renderSubAttributesFromObj(s, L);
                return {
                    name, level: (s.level || '').toString().trim(), desc, descPt: (s.descPt || (s.desc_i18n && s.desc_i18n.pt) || ''), descEn: (s.descEn || (s.desc_i18n && s.desc_i18n.en) || ''), descEs: (s.descEs || (s.desc_i18n && s.desc_i18n.es) || ''), descPl: (s.descPl || (s.desc_i18n && s.desc_i18n.pl) || ''), attrs: '', icon: (s.icon || 'Nada.png'), iconURL: filePathURL(s.icon || 'Nada.png'), video: s.video ? filePathURL(s.video) : '', subs: Array.isArray(s.subs) ? s.subs : null, subattrs: s, flags: Array.isArray(s.flags) ? s.flags : null, back: (s.back === true || s.back === 'true' || s.back === 'yes' || s.back === '1') ? 'true' : null, weapon: s.weapon || null
                };
             });
             });
 
            const fragment = document.createDocumentFragment();
             // DEBUG: Log todas as subskills ANTES de renderizar
             items.forEach((it, iIdx) => {
            console.log('[Subskills] Renderizando', subs.length, 'subskills. Verificando weapon...');
                const node = document.createElement('div');
            subs.forEach((sub, idx) => {
                node.className = 'skill-icon';
                 const subName = (sub.name || sub.n || '').trim();
                node.dataset.nested = '1';
                 if (sub.weapon) {
                node.dataset.nome = it.name || '';
                    console.log(`[Subskills] Subskill ${idx} "${subName}" TEM WEAPON antes de renderizar:`, {
                node.dataset.parentIndex = parentIndexSnapshot;
                        weapon: sub.weapon,
                 node.dataset.subName = it.name || '';
                        weaponType: typeof sub.weapon,
                const subSlug = slugify(it.name || '');
                        weaponKeys: typeof sub.weapon === 'object' ? Object.keys(sub.weapon) : null
                if (subSlug) node.dataset.slug = subSlug;
                    });
                if (it.level) node.dataset.level = it.level;
                 } else {
                if (it.desc) node.dataset.desc = it.desc;
                     if (subName === 'Karmic Jishin') {
                 if (it.descPt) node.dataset.descPt = it.descPt;
                         console.warn(`[Subskills] Subskill ${idx} "${subName}" SEM WEAPON antes de renderizar!`, sub);
                if (it.descEn) node.dataset.descEn = it.descEn;
                if (it.descEs) node.dataset.descEs = it.descEs;
                if (it.descPl) node.dataset.descPl = it.descPl;
                if (it.video) node.dataset.video = it.video;
                if (it.subs) node.dataset.subs = JSON.stringify(it.subs);
                if (it.subattrs) node.dataset.subattrs = JSON.stringify(it.subattrs);
                if (it.flags) node.dataset.flags = JSON.stringify(it.flags);
                if (it.back) node.dataset.back = it.back;
                 if (it.weapon) {
                    try {
                        node.dataset.weapon = JSON.stringify(it.weapon);
                     } catch (e) {
                         console.error('[Skills] Erro ao serializar weapon de subskill', it.name, e);
                     }
                     }
                 }
                 }
            });
            console.log('[DEBUG Subskills] Iniciando criação de subicons, order.length:', order.length, 'subs.length:', subs.length);
            order.forEach(nm => {
                const s = subs.find(x => (x.name || x.n || '') === nm);
                if (!s) {
                    console.warn('[DEBUG Subskills] Subskill não encontrada para nome:', nm);
                    return;
                }
                console.log('[DEBUG Subskills] Criando subicon:', s.name || s.n || nm);
                const item = document.createElement('div');
                item.className = 'subicon';
                item.title = s.name || nm;
                const slugify = window.__skillSlugify || ((str) => (str || '').toLowerCase().replace(/[^\w]+/g, '-').replace(/^-+|-+$/g, ''));
                item.dataset.slug = slugify(s.name || nm);
                 const img = document.createElement('img');
                 const img = document.createElement('img');
                 img.alt = '';
                 img.alt = '';
                 img.src = filePathURL(s.icon || 'Nada.png');
                 img.src = it.iconURL;
                 item.appendChild(img);
                 node.appendChild(img);
 
                 fragment.appendChild(node);
                // PADRONIZADO: usa data-weapon (igual a Character.Skills.html)
            });
                 // Verifica weapon de forma mais robusta
            const templateClone = fragment.cloneNode(true);
                const hasWeapon = s.weapon && (
            iconsBar.innerHTML = '';
                    (typeof s.weapon === 'object' && Object.keys(s.weapon).length > 0) ||
            iconsBar.appendChild(fragment);
                    (typeof s.weapon === 'string' && s.weapon.trim() !== '')
            animateIconsBarEntrance();
                );
            wireClicksForCurrentBar();
 
            setupWeaponBarToggle(hasWeaponSkillAvailable);
                const subName = (s.name || s.n || '').trim();
            const b2 = ensureBackButton();
 
            if (b2) b2.classList.add('peek');
                if (hasWeapon) {
            if (cacheKey) {
                    // Normaliza weapon se for string
                subBarTemplateCache.set(cacheKey, {
                    let weaponObj = s.weapon;
                    template: templateClone, lang: langKey
                    if (typeof weaponObj === 'string') {
                });
                        try {
            }
                            weaponObj = JSON.parse(weaponObj);
        } window.addEventListener('gla:langChanged', () => {
                        } catch {
            subBarTemplateCache.clear();
                            // Se falhar, tenta formato ~
            const skillsRoot = document.getElementById('skills');
                            const parts = weaponObj.split('~');
            const i18nMap = skillsRoot ? JSON.parse(skillsRoot.dataset.i18nAttrs || '{}') : {
                            if (parts.length >= 2) {
            };
                                weaponObj = {
            const lang = getLangKey();
                                    icon: parts[0] || 'Nada.png',
            Array.from(iconsBar.querySelectorAll('.skill-icon')).forEach(icon => {
                                    powerpve: parts[1] || null,
                const pack = {
                                    powerpvp: parts[2] || null,
                    pt: icon.dataset.descPt || '', en: icon.dataset.descEn || '', es: icon.dataset.descEs || '', pl: icon.dataset.descPl || ''
                                    cooldown: parts[3] || null,
                };
                                    video: parts[4] || '',
                const chosen = (pack[lang] || pack.pt || pack.en || pack.es || pack.pl || icon.dataset.desc || '').trim();
                                    energy: parts[5] || null
                if (chosen) icon.dataset.desc = chosen;
                                };
            });
                                Object.keys(weaponObj).forEach(k => {
            barStack.forEach(frame => {
                                    if (weaponObj[k] === '' || weaponObj[k] === null) {
                (frame.items || []).forEach(it => {
                                        delete weaponObj[k];
                     const pack = {
                                    }
                         pt: it.descPt, en: it.descEn, es: it.descEs, pl: it.descPl
                                });
                            } else {
                                weaponObj = null;
                            }
                        }
                    }
 
                    if (weaponObj && typeof weaponObj === 'object' && Object.keys(weaponObj).length > 0) {
                        try {
                            item.dataset.weapon = JSON.stringify(weaponObj);
                            console.log(`[Subskills] "${subName}" - data-weapon definido, weapon:`, weaponObj);
                        } catch (e) {
                            console.error('[Subskills] Erro ao serializar weapon de subskill', subName, e);
                        }
 
                        // Aplica classe inicial se o toggle já está ativo
                        if (isWeaponModeOn()) {
                            item.classList.add('has-weapon-available');
                        }
                    } else {
                        console.warn(`[Subskills] "${subName}" - weapon inválido após normalização:`, weaponObj);
                    }
                } else {
                    if (subName === 'Karmic Jishin') {
                        console.warn('[Subskills] Karmic Jishin - SEM WEAPON!', {
                            s: s,
                            weapon: s.weapon,
                            weaponType: typeof s.weapon,
                            weaponKeys: s.weapon ? Object.keys(s.weapon) : null
                        });
                    }
                }
 
                item.addEventListener('click', () => {
                    const L = getLabels();
                    const subName = (s.name || s.n || '').trim();
 
                    // PADRONIZADO: lê weapon diretamente do atributo data-weapon (igual a Character.Skills.html)
                    let subWeaponData = null;
                    if (item.dataset.weapon) {
                        try {
                            subWeaponData = JSON.parse(item.dataset.weapon);
                        } catch (e) {
                            console.warn('[Subskills] Erro ao parsear data-weapon:', e);
                            subWeaponData = null;
                        }
                    }
                    const hasSubWeapon = !!subWeaponData;
 
                    const weaponOn = isWeaponModeOn();
                    const weaponEquipped = weaponOn && hasSubWeapon && subWeaponData;
 
                    console.log('[Subskills] click handler debug:', {
                        subName,
                        weaponOn,
                        hasSubWeapon,
                        weaponEquipped,
                        subWeaponData: subWeaponData
                    });
 
                    // DEBUG: Log para Karmic Jishin
                    if (subName === 'Karmic Jishin') {
                        console.log('[Subskills Click] Karmic Jishin:', {
                            weaponOn,
                            hasSubWeapon,
                            weaponEquipped,
                            subWeaponData: subWeaponData
                        });
                    }
 
                    // Determina descrição (weapon ou normal)
                    const raw = (document.documentElement.lang || 'pt').toLowerCase();
                    const lang = raw === 'pt-br' ? 'pt' : (raw.split('-')[0] || 'pt');
 
                    let chosen = '';
                    if (weaponEquipped && subWeaponData) {
                        // Descrição do weapon
                        const weaponDescPack = subWeaponData.desc_i18n || subWeaponData.desc || {};
                        chosen = weaponDescPack[lang] || weaponDescPack.pt || weaponDescPack.en || '';
                    } else {
                        // Descrição normal
                        const base = s.desc_i18n || s.desc || {};
                        chosen = base[lang] || base.pt || base.en || (s.descPt || '');
                    }
 
                    // Determina atributos (weapon ou normal)
                     let attrsObj = {
                         powerpve: s.powerpve,
                        powerpvp: s.powerpvp,
                        energy: s.energy,
                        cooldown: s.cooldown
                     };
                     };
                     if (weaponEquipped && subWeaponData) {
                     const chosen = (pack[lang] || pack.pt || pack.en || pack.es || pack.pl || it.desc || '');
                        attrsObj = {
                     it.desc = chosen;
                            powerpve: subWeaponData.powerpve || s.powerpve,
                            powerpvp: subWeaponData.powerpvp || s.powerpvp,
                            energy: subWeaponData.energy || s.energy,
                            cooldown: subWeaponData.cooldown || s.cooldown
                        };
                    }
 
                    // Level (weapon ou normal)
                    const level = (weaponEquipped && subWeaponData && subWeaponData.level)
                        ? subWeaponData.level.toString().trim()
                        : (s.level || '').toString().trim();
 
                    let flagsHTML = '';
                    if (Array.isArray(s.flags) && s.flags.length > 0) {
                        flagsHTML = renderFlagsRow(s.flags);
                    }
 
                    if (descBox) {
                        descBox.innerHTML = `<div class="skill-title"><h3>${s.name || nm}</h3></div>${level ? `<div class="skill-level-line"><span class="attr-label">${L.level} ${level}</span></div>` : ''}${renderSubAttrs(attrsObj, L)}<div class="desc">${chosen.replace(/'''(.*?)'''/g, '<b>$1</b>')}</div>`;
                    }
 
                    if (videoBox) {
                        const oldFlags = videoBox.querySelector('.skill-flags');
                        if (oldFlags) oldFlags.remove();
                        if (flagsHTML) {
                            videoBox.insertAdjacentHTML('beforeend', flagsHTML);
                            applyFlagTooltips(videoBox);
                        }
                    }
 
                    // Vídeo (weapon ou normal) - usa valores explícitos do módulo Lua
                    const effectiveVideo = getEffectiveVideo(s);
                    console.log('[Subskills] effectiveVideo calculado:', {
                        subName,
                        weaponOn: weaponEquipped,
                        hasWeaponData: !!subWeaponData,
                        weaponVideo: subWeaponData?.video,
                        baseVideo: s.video,
                        effectiveVideo
                    });
 
                    if (!effectiveVideo || effectiveVideo.trim() === '' || effectiveVideo === 'Nada.png' || effectiveVideo.toLowerCase().includes('nada.png')) {
                        if (videoBox) videoBox.style.display = 'none';
                        console.log('[Subskills] video escolhido (nenhum)', parentIdx, subName, weaponOn, 'sem vídeo');
                     } else {
                        const videoKey = (weaponEquipped && subWeaponData && subWeaponData.video && subWeaponData.video.trim() !== '')
                            ? `sub:${parentIdx}:${subName}:weapon`
                            : `sub:${parentIdx}:${subName}`;
 
                        console.log('[Subskills] video escolhido', parentIdx, subName, weaponOn, effectiveVideo);
 
                        // Se tem weapon video e está ativo, precisa criar/mostrar esse vídeo
                        if (weaponEquipped && subWeaponData && subWeaponData.video && subWeaponData.video.trim() !== '' && subWeaponData.video !== 'Nada.png') {
                            ensureSubVideoInCache(subWeaponData.video, videoKey, videoBox);
                        } else if (s.video && s.video.trim() !== '' && s.video !== 'Nada.png') {
                            ensureSubVideoCached(s, parentIdx, videoBox);
                        }
 
                        showSubVideo(videoKey, videoBox);
                    }
                    Array.from(subBar.children).forEach(c => {
                        c.classList.remove('active');
                        c.classList.remove('weapon-equipped');
                    });
                    item.classList.add('active');
                    // Aplica weapon-equipped se tem weapon e está ativo (SISTEMA SEPARADO)
                    if (weaponEquipped) {
                        item.classList.add('weapon-equipped');
                    }
                    window.__lastActiveSkillIcon = item;
                 });
                 });
                if (window.__globalSkillTooltip) {
                    const { show, hide, measureAndPos, lockUntil } = window.__globalSkillTooltip;
                    const label = item.title || '';
                    item.setAttribute('aria-label', label);
                    if (item.hasAttribute('title')) item.removeAttribute('title');
                    item.addEventListener('mouseenter', () => show(item, label));
                    item.addEventListener('mousemove', () => { if (performance.now() >= lockUntil.value) measureAndPos(item); });
                    item.addEventListener('click', () => { lockUntil.value = performance.now() + 240; measureAndPos(item); });
                    item.addEventListener('mouseleave', hide);
                }
                console.log('[DEBUG Subskills] Anexando subicon ao subBar:', item.title, 'subBar:', subBar);
                subBar.appendChild(item);
             });
             });
 
             if (descBox) {
             // DEBUG: Verifica quantos subicons foram criados
                applyFlagTooltips(descBox);
            const totalSubicons = subBar.querySelectorAll('.subicon').length;
             } const activeIcon = window.__lastActiveSkillIcon;
             console.log('[DEBUG Subskills] Total de subicons criados e anexados:', totalSubicons);
             if (activeIcon && activeIcon.dataset.weapon) {
 
                 activateSkill(activeIcon, {
             if (totalSubicons === 0) {
                    openSubs: false
                 console.error('[DEBUG Subskills] ERRO: Nenhum subicon foi criado! subBar:', subBar, 'subBar.innerHTML:', subBar.innerHTML);
                });
             }
             }
 
        });
             // Aplica classes de weapon nas subskills recém-renderizadas se o toggle estiver ativo
        wireClicksForCurrentBar();
             // Aplica classes de weapon DEPOIS que todos os items foram adicionados ao DOM
        const b0 = ensureBackButton();
             setTimeout(() => {
        if (b0) {
                 const finalCount = document.querySelectorAll('.subicon').length;
             b0.classList.add('peek');
                 console.log('[DEBUG Subskills] Total de subicons no DOM após timeout:', finalCount);
            b0.style.alignSelf = 'stretch';
                 applyWeaponClassesToSubskills();
        } (function initSkillTooltip() {
 
            if (document.querySelector('.skill-tooltip')) return;
                 // Dispara evento para notificar que subskills estão prontas
            const tip = document.createElement('div');
                 window.dispatchEvent(new CustomEvent('gla:subskills:ready', { detail: { count: finalCount } }));
            tip.className = 'skill-tooltip';
 
            tip.setAttribute('role', 'tooltip');
                 // REGISTRA LISTENER DO EVENTO DENTRO DO renderBarFrom (após renderizar)
            tip.setAttribute('aria-hidden', 'true');
                 // Remove listener anterior se existir (evita duplicação)
            document.body.appendChild(tip);
                 if (subBar._weaponToggleListener) {
            const lockUntilRef = {
                     window.removeEventListener('gla:weaponToggled', subBar._weaponToggleListener);
                value: 0
            };
            function measureAndPos(el) {
                if (!el || tip.getAttribute('aria-hidden') === 'true') return;
                tip.style.left = '0px';
                tip.style.top = '0px';
                const rect = el.getBoundingClientRect();
                const tr = tip.getBoundingClientRect();
                let left = Math.round(rect.left + (rect.width - tr.width) / 2);
                left = Math.max(8, Math.min(left, window.innerWidth - tr.width - 8));
                const coarse = (window.matchMedia && matchMedia('(pointer: coarse)').matches) || (window.innerWidth <= 600);
                let top = coarse ? Math.round(rect.bottom + 10) : Math.round(rect.top - tr.height - 8);
                if (top < 8) top = Math.round(rect.bottom + 10);
                tip.style.left = left + 'px';
                tip.style.top = top + 'px';
            } function show(el, text) {
                tip.textContent = text || '';
                tip.setAttribute('aria-hidden', 'false');
                measureAndPos(el);
                tip.style.opacity = '1';
            } function hide() {
                tip.setAttribute('aria-hidden', 'true');
                tip.style.opacity = '0';
                tip.style.left = '-9999px';
                tip.style.top = '-9999px';
            } window.__globalSkillTooltip = {
                show, hide, measureAndPos, lockUntil: lockUntilRef
             };
             Array.from(document.querySelectorAll('.icon-bar .skill-icon')).forEach(icon => {
                 if (icon.dataset.weaponToggle === '1' || icon.classList.contains('weapon-bar-toggle')) return;
                if (icon.dataset.tipwired) return;
                icon.dataset.tipwired = '1';
                const label = icon.dataset.nome || icon.dataset.name || icon.title || '';
                if (label && !icon.hasAttribute('aria-label')) icon.setAttribute('aria-label', label);
                if (icon.hasAttribute('title')) icon.removeAttribute('title');
                const img = icon.querySelector('img');
                if (img) {
                    const imgAlt = img.getAttribute('alt') || '';
                    const imgTitle = img.getAttribute('title') || '';
                    if (!label && (imgAlt || imgTitle)) icon.setAttribute('aria-label', imgAlt || imgTitle);
                    img.setAttribute('alt', '');
                    if (img.hasAttribute('title')) img.removeAttribute('title');
                } icon.addEventListener('mouseenter', () => show(icon, label));
                icon.addEventListener('mousemove', () => {
                    if (performance.now() >= lockUntilRef.value) measureAndPos(icon);
                });
                icon.addEventListener('click', () => {
                    lockUntilRef.value = performance.now() + 240;
                    measureAndPos(icon);
                });
                icon.addEventListener('mouseleave', hide);
            });
            Array.from(document.querySelectorAll('.subskills-rail .subicon')).forEach(sub => {
                if (sub.dataset.tipwired) return;
                sub.dataset.tipwired = '1';
                const label = sub.getAttribute('title') || sub.getAttribute('aria-label') || '';
                if (label && !sub.hasAttribute('aria-label')) sub.setAttribute('aria-label', label);
                if (sub.hasAttribute('title')) sub.removeAttribute('title');
                sub.addEventListener('mouseenter', () => show(sub, label));
                 sub.addEventListener('mousemove', () => {
                    if (performance.now() >= lockUntilRef.value) measureAndPos(sub);
                 });
                sub.addEventListener('click', () => {
                    lockUntilRef.value = performance.now() + 240;
                    measureAndPos(sub);
                 });
                 sub.addEventListener('mouseleave', hide);
            });
            window.addEventListener('scroll', () => {
                const visible = document.querySelector('.skill-tooltip[aria-hidden="false"]');
                if (!visible) return;
                const target = document.querySelector('.subskills-rail .subicon:hover') || document.querySelector('.subskills-rail .subicon.active') || document.querySelector('.icon-bar .skill-icon:hover') || document.querySelector('.icon-bar .skill-icon.active');
                measureAndPos(target);
            }, true);
            window.addEventListener('resize', () => {
                const target = document.querySelector('.subskills-rail .subicon:hover') || document.querySelector('.subskills-rail .subicon.active') || document.querySelector('.icon-bar .skill-icon:hover') || document.querySelector('.icon-bar .skill-icon.active');
                measureAndPos(target);
            });
        })();
        (function initTabs() {
            const tabs = Array.from(document.querySelectorAll('.tab-btn'));
            if (!tabs.length) return;
            const contents = Array.from(document.querySelectorAll('.tab-content'));
            const characterBox = document.querySelector('.character-box');
            let wrapper = characterBox.querySelector('.tabs-height-wrapper');
            if (!wrapper) {
                wrapper = document.createElement('div');
                 wrapper.className = 'tabs-height-wrapper';
                contents.forEach(c => {
                    wrapper.appendChild(c);
                 });
                const tabsElement = characterBox.querySelector('.character-tabs');
                 if (tabsElement && tabsElement.nextSibling) {
                     characterBox.insertBefore(wrapper, tabsElement.nextSibling);
                } else {
                    characterBox.appendChild(wrapper);
                 }
                 }
 
            } async function smoothHeightTransition(fromTab, toTab) {
                 // Cria novo listener que opera no subBar atual
                 if (!wrapper) return Promise.resolve();
                 subBar._weaponToggleListener = (e) => {
                 const scrollY = window.scrollY;
                     const enabled = e.detail?.enabled ?? false;
                const currentHeight = wrapper.getBoundingClientRect().height;
                     console.log('[Subskills] Evento gla:weaponToggled recebido (dentro de renderBarFrom):', enabled);
                await new Promise((resolve) => {
 
                     const videoContainers = toTab.querySelectorAll('.video-container');
                     // Aplica classes usando a função auxiliar
                     const contentCard = toTab.querySelector('.content-card');
                    applyWeaponClassesToSubskills();
                     if (videoContainers.length === 0) {
 
                        requestAnimationFrame(() => {
                    // Atualiza a subskill ativa se houver (recarrega descrição/atributos)
                            requestAnimationFrame(() => {
                    setTimeout(() => {
                                requestAnimationFrame(() => resolve());
                        const activeSub = subBar.querySelector('.subicon[data-weapon].active')
                             });
                             || subBar.querySelector('.subicon.active');
                        });
                         console.log('[Subskills] Atualizando subskill ativa:', activeSub ? (activeSub.title || activeSub.dataset.slug) : 'nenhuma');
                        return;
                         if (activeSub) {
                    } let lastHeight = 0;
                             activeSub.dispatchEvent(new Event('click', { bubbles: true }));
                    let stableCount = 0;
                    const checksNeeded = 3;
                    let totalChecks = 0;
                    const maxChecks = 15;
                    function checkStability() {
                        totalChecks++;
                         const currentTabHeight = toTab.scrollHeight;
                        if (Math.abs(currentTabHeight - lastHeight) < 5) {
                            stableCount++;
                        } else {
                            stableCount = 0;
                        } lastHeight = currentTabHeight;
                         if (stableCount >= checksNeeded || totalChecks >= maxChecks) {
                             resolve();
                         } else {
                         } else {
                             api.refreshCurrentSubSafe();
                             setTimeout(checkStability, 50);
                         }
                         }
                     }, 50);
                     } setTimeout(checkStability, 50);
                 };
                 });
 
                const nextHeight = toTab.getBoundingClientRect().height;
                 window.addEventListener('gla:weaponToggled', subBar._weaponToggleListener);
                 const finalHeight = Math.max(nextHeight, 100);
 
                if (Math.abs(finalHeight - currentHeight) < 30) {
                    wrapper.style.height = '';
                    return Promise.resolve();
                } wrapper.style.overflow = 'hidden';
                wrapper.style.height = currentHeight + 'px';
                wrapper.offsetHeight;
                wrapper.style.transition = 'height 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
                 requestAnimationFrame(() => {
                 requestAnimationFrame(() => {
                     subRail.classList.remove('collapsed');
                     wrapper.style.height = finalHeight + 'px';
                     subRail.classList.remove('hidden');
                });
                    const h = subRail.offsetHeight || 48;
                return new Promise(resolve => {
                    if (spacer) spacer.style.height = h + 'px';
                     setTimeout(() => {
                        wrapper.style.height = '';
                        wrapper.style.transition = '';
                        wrapper.style.overflow = '';
                        resolve();
                    }, 320);
                 });
                 });
             }, 10);
             } tabs.forEach(btn => {
        };
                 if (btn.dataset.wiredTab) return;
 
                 btn.dataset.wiredTab = '1';
        api.hideAll = function (videoBox) {
                btn.addEventListener('click', () => {
            videoBox?.querySelectorAll('.skill-video[data-sub="1"]').forEach(v => {
                    const target = btn.getAttribute('data-tab');
                 try { v.pause(); } catch { }
                    const currentActive = contents.find(c => c.classList.contains('active'));
                 v.style.display = 'none';
                     const nextActive = contents.find(c => c.id === target);
            });
                     if (currentActive === nextActive) return;
        };
                     document.body.classList.add('transitioning-tabs');
 
                     if (currentActive) {
        window.renderSubskillsBarFrom = function (el, ctx) { api.renderBarFrom(el, ctx); };
                        currentActive.style.opacity = '0';
 
                        currentActive.style.transform = 'translateY(-8px)';
        api.preloadAllSubskillImages = function () {
                    } setTimeout(async () => {
            const allSkillIcons = document.querySelectorAll('.icon-bar .skill-icon[data-subs]');
                        contents.forEach(c => {
            const preloadPromises = [];
                            if (c !== nextActive) {
            let totalImages = 0;
                                c.style.display = 'none';
 
                                c.classList.remove('active');
            allSkillIcons.forEach(icon => {
                             }
                try {
                         });
                     const subsRaw = icon.getAttribute('data-subs');
                         tabs.forEach(b => b.classList.toggle('active', b === btn));
                     if (!subsRaw) return;
                        if (nextActive) {
                     const subs = JSON.parse(subsRaw);
                             nextActive.classList.add('active');
                     if (!Array.isArray(subs)) return;
                            nextActive.style.display = 'block';
 
                            nextActive.style.opacity = '0';
                    subs.forEach(s => {
                            nextActive.style.visibility = 'hidden';
                        if (s && s.icon) {
                            nextActive.offsetHeight;
                            preloadPromises.push(preloadImage(s.icon));
                            try {
                             totalImages++;
                                 if (target === 'skills') {
                         }
                                    const tabEl = document.getElementById(target);
                         if (s && Array.isArray(s.subs)) {
                                    if (tabEl) {
                             s.subs.forEach(nested => {
                                        const activeIcon = tabEl.querySelector('.icon-bar .skill-icon.active');
                                 if (nested && nested.icon) {
                                        const firstIcon = tabEl.querySelector('.icon-bar .skill-icon');
                                    preloadPromises.push(preloadImage(nested.icon));
                                        const toClick = activeIcon || firstIcon;
                                     totalImages++;
                                        if (toClick) {
                                            const had = document.body.dataset.suppressSkillPlay;
                                            document.body.dataset.suppressSkillPlay = '1';
                                            toClick.click();
                                            if (had) document.body.dataset.suppressSkillPlay = had;
                                        }
                                     }
                                 }
                                 }
                            } catch (e) {
                            }
                        } if (currentActive && nextActive) {
                            await smoothHeightTransition(currentActive, nextActive);
                        } if (nextActive) {
                            nextActive.style.visibility = '';
                            nextActive.style.transform = 'translateY(12px)';
                            requestAnimationFrame(() => {
                                nextActive.style.opacity = '1';
                                nextActive.style.transform = 'translateY(0)';
                                setTimeout(() => {
                                    nextActive.style.opacity = '';
                                    nextActive.style.transform = '';
                                    document.body.classList.remove('transitioning-tabs');
                                    try {
                                        delete document.body.dataset.suppressSkillPlay;
                                    } catch {
                                    }
                                }, 300);
                             });
                             });
                         }
                         }
                    });
                     }, 120);
                } catch (e) {
                }
            });
 
            if (totalImages > 0) {
                return Promise.all(preloadPromises).then(() => {
                });
            }
            return Promise.resolve();
        };
 
        // Inicialização: constrói cache das skills principais e pré-carrega imagens
        function init() {
            // Constrói cache das skills principais ANTES de qualquer interação
            getMainSkillsMap();
            // Pré-carrega imagens das subskills
            api.preloadAllSubskillImages();
 
            // Escuta mudanças no localStorage para atualizar subskill ativa
            window.addEventListener('storage', (e) => {
                if (e.key === 'glaWeaponEnabled') {
                    setTimeout(() => api.refreshCurrentSubSafe(), 50);
                }
            });
 
            // LISTENER GLOBAL: Escuta evento de toggle e aplica em todas as subskills
            // Este listener SEMPRE funciona, mesmo se as subskills ainda não foram renderizadas
            window.addEventListener('gla:weaponToggled', (e) => {
                const enabled = e.detail?.enabled ?? false;
                console.log('[Subskills] Evento gla:weaponToggled recebido (global):', enabled);
 
                // Tenta aplicar classes imediatamente
                applyWeaponClassesToSubskills();
 
                // Se não encontrou subskills, tenta novamente após um delay (caso ainda estejam sendo renderizadas)
                const weaponSubs = document.querySelectorAll('.subicon[data-subweapon]');
                if (weaponSubs.length === 0) {
                    console.log('[Subskills] Nenhuma subskill encontrada, tentando novamente após delay...');
                    setTimeout(() => {
                        applyWeaponClassesToSubskills();
                        const activeSub = document.querySelector('.subicon[data-subweapon].active')
                            || document.querySelector('.subicon.active');
                        if (activeSub) {
                            activeSub.dispatchEvent(new Event('click', { bubbles: true }));
                        }
                     }, 200);
                } else {
                    // Atualiza a subskill ativa se houver
                     setTimeout(() => {
                     setTimeout(() => {
                         const activeSub = document.querySelector('.subicon[data-weapon].active')
                         syncDescHeight();
                             || document.querySelector('.subicon.active');
                        if (target === 'skins') {
                        console.log('[Subskills] Atualizando subskill ativa:', activeSub ? (activeSub.title || activeSub.dataset.slug) : 'nenhuma');
                            videosCache.forEach(v => {
                        if (activeSub) {
                                try {
                            activeSub.dispatchEvent(new Event('click', { bubbles: true }));
                                    v.pause();
                                } catch (e) {
                                } v.style.display = 'none';
                            });
                             if (videoBox) {
                                videoBox.querySelectorAll('video.skill-video').forEach(v => {
                                    try {
                                        v.pause();
                                    } catch (e) {
                                    } v.style.display = 'none';
                                });
                            } if (window.__subskills) window.__subskills.hideAll?.(videoBox);
                            if (videoBox && placeholder) {
                                placeholder.style.display = 'none';
                                placeholder.classList.add('fade-out');
                            }
                         } else {
                         } else {
                             api.refreshCurrentSubSafe();
                             const activeIcon = document.querySelector('.icon-bar .skill-icon.active');
                            if (activeIcon) activeIcon.click();
                         }
                         }
                     }, 50);
                     }, 450);
                 }
                 });
            });
        })();
        (function initSkinsArrows() {
            const carousel = $('.skins-carousel');
            const wrapper = $('.skins-carousel-wrapper');
            const left = $('.skins-arrow.left');
            const right = $('.skins-arrow.right');
            if (!carousel || !left || !right || !wrapper) return;
            if (wrapper.dataset.wired) return;
            wrapper.dataset.wired = '1';
            const scrollAmt = () => Math.round(carousel.clientWidth * 0.6);
            function setState() {
                const max = carousel.scrollWidth - carousel.clientWidth;
                const x = carousel.scrollLeft;
                const hasLeft = x > 5, hasRight = x < max - 5;
                left.style.display = hasLeft ? 'inline-block' : 'none';
                right.style.display = hasRight ? 'inline-block' : 'none';
                wrapper.classList.toggle('has-left', hasLeft);
                wrapper.classList.toggle('has-right', hasRight);
                carousel.style.justifyContent = (!hasLeft && !hasRight) ? 'center' : '';
            } function go(dir) {
                const max = carousel.scrollWidth - carousel.clientWidth;
                const next = dir < 0 ? Math.max(0, carousel.scrollLeft - scrollAmt()) : Math.min(max, carousel.scrollLeft + scrollAmt());
                carousel.scrollTo({
                    left: next, behavior: 'smooth'
                });
            } left.addEventListener('click', () => go(-1));
            right.addEventListener('click', () => go(1));
            carousel.addEventListener('scroll', setState);
            new ResizeObserver(setState).observe(carousel);
            setState();
        })();
        function renderAttributes(str) {
            const skillsRoot = document.getElementById('skills');
            const i18nMap = skillsRoot ? JSON.parse(skillsRoot.dataset.i18nAttrs || '{}') : {
            };
            const langRaw = (document.documentElement.lang || skillsRoot?.dataset.i18nDefault || 'pt').toLowerCase();
            const langKey = i18nMap[langRaw] ? langRaw : (i18nMap[langRaw.split('-')[0]] ? langRaw.split('-')[0] : 'pt');
            const L = i18nMap[langKey] || i18nMap.pt || {
                cooldown: 'Recarga', energy_gain: 'Ganho de energia', energy_cost: 'Custo de energia', power: 'Poder', power_pvp: 'Poder PvP', level: 'Nível'
            };
            const vals = (str || '').split(',').map(v => v.trim());
            const pve = parseFloat(vals[0]);
            const pvp = parseFloat(vals[1]);
            const ene = parseFloat(vals[2]);
            const cd = parseFloat(vals[3]);
            const rows = [];
            if (!isNaN(cd)) rows.push([L.cooldown, cd]);
            if (!isNaN(ene) && ene !== 0) {
                const label = ene > 0 ? L.energy_gain : L.energy_cost;
                rows.push([label, Math.abs(ene)]);
            } if (!isNaN(pve)) rows.push([L.power, pve]);
            if (!isNaN(pvp)) rows.push([L.power_pvp, pvp]);
            if (!rows.length) return '';
            const html = rows.map(([label, value]) => `<div class="attr-row"><span class="attr-label">${label}</span><span class="attr-value">${value}</span></div>`).join('');
            return `<div class="attr-list">${html}</div>`;
        } function syncDescHeight() {
        } window.addEventListener('resize', syncDescHeight);
        if (videoBox) new ResizeObserver(syncDescHeight).observe(videoBox);
        iconItems.forEach(el => {
            const wired = !!el.dataset._sync_wired;
            if (wired) return;
            el.dataset._sync_wired = '1';
            el.addEventListener('click', () => {
                Promise.resolve().then(syncDescHeight);
             });
             });
 
        });
            // LISTENER: Escuta quando subskills estão prontas e aplica classes de weapon
        if (iconsBar) addOnce(iconsBar, 'wheel', (e) => {
            window.addEventListener('gla:subskills:ready', (e) => {
            if (e.deltaY) {
                 console.log('[Subskills] Evento gla:subskills:ready recebido, count:', e.detail?.count);
                 e.preventDefault();
                 // Aplica classes de weapon se o toggle estiver ativo
                iconsBar.scrollLeft += e.deltaY;
                 applyWeaponClassesToSubskills();
            }
        });
        wireClicksForCurrentBar();
        if (iconItems.length) {
            const first = iconItems[0];
            if (first) {
                 activateSkill(first, {
                    openSubs: false
                 });
            }
        } setTimeout(() => {
            Array.from(document.querySelectorAll('.skill-icon')).forEach(el => {
             });
             });
        }
            videosCache.forEach((v, idx) => {
 
                const src = v.querySelector('source') ? v.querySelector('source').src : v.src;
        if (document.readyState === 'loading') {
                v.addEventListener('error', (ev) => {
            document.addEventListener('DOMContentLoaded', () => {
                 });
                 setTimeout(init, 100);
                v.addEventListener('loadedmetadata', () => {
                });
             });
             });
         } else {
         }, 600);
            setTimeout(init, 100);
        }
     })();
     })();
</script>
</script>
<style>
    .subicon-bar {
        display: flex;
        gap: 10px;
        padding: 6px 6px;
        overflow-x: auto;
        /* Firefox */
        scrollbar-width: thin;
        scrollbar-color: #ababab transparent;
    }
    .subicon-bar::-webkit-scrollbar {
        height: 6px;
    }
    .subicon-bar::-webkit-scrollbar-thumb {
        background: #151515;
        border-radius: 3px;
    }
    .subicon {
        width: var(--icon-size, 42px);
        height: var(--icon-size, 42px);
        border-radius: var(--icon-radius, 10px);
        overflow: hidden;
        position: relative;
        flex: 0 0 auto;
        cursor: pointer;
        isolation: isolate;
    }
    .subicon img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
        border-radius: inherit;
    }
    .subicon::after {
        content: "";
        position: absolute;
        inset: 0;
        border-radius: inherit;
        box-shadow: inset 0 0 0 var(--icon-ring-w, 2px) var(--icon-idle, #cfcfcf);
        pointer-events: none;
        z-index: 2;
        transition: box-shadow .12s ease;
    }
    .subicon:hover::after {
        box-shadow: inset 0 0 0 var(--icon-ring-w, 2px) #e6e6e6;
    }
    .subicon.active::after {
        box-shadow: inset 0 0 0 var(--icon-ring-w, 2px) var(--icon-active, #FFD95A);
    }
    .subicon.active::before {
        content: "";
        position: absolute;
        inset: -4px;
        border-radius: calc(var(--icon-radius, 10px) + 4px);
        pointer-events: none;
        z-index: 1;
        opacity: 1;
        box-shadow: 0 0 12px 3px var(--icon-active-glow, rgba(255, 217, 90, .30)),
            0 0 0 calc(var(--icon-ring-w, 2px) * 2) var(--icon-active-ring, rgba(255, 217, 90, .50));
    }
    .top-rail.skills {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow: visible;
    }
    .top-rail.skills .icon-bar {
        margin-bottom: 0;
        position: relative;
        z-index: 2;
    }
    .subskills-rail {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        top: calc(100% - 1px);
        z-index: 3;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        width: auto;
        max-width: 100%;
        padding: 3px 5px;
        background: rgba(0, 0, 0, .38);
        border: 1px solid rgba(255, 255, 255, .10);
        border-top: 1px solid rgba(255, 255, 255, .08);
        border-radius: 0 0 10px 10px;
        box-shadow: 0 3px 9px rgba(0, 0, 0, .22);
        -webkit-backdrop-filter: blur(2px);
        backdrop-filter: blur(2px);
        overflow: hidden;
        transition: opacity .14s ease, transform .14s ease;
        opacity: 1;
    }
    .subskills-rail::before {
        content: "";
        position: absolute;
        top: -6px;
        left: 0;
        right: 0;
        height: 6px;
        background: linear-gradient(to bottom, rgba(0, 0, 0, .20), rgba(0, 0, 0, 0));
        pointer-events: none;
    }
    .subskills-rail.collapsed {
        opacity: 0;
        pointer-events: none;
        transform: translate(-50%, -6px);
    }
    .subskills-rail.hidden {
        visibility: hidden;
    }
    .subskills-spacer {
        height: 0;
        transition: height .2s ease;
    }
    .subskills-rail .subicon-bar {
        display: inline-flex;
        align-items: center;
        gap: 0;
        overflow-x: auto;
        /* Firefox */
        scrollbar-width: thin;
        scrollbar-color: #ababab transparent;
    }
    .subskills-rail .subicon-bar::-webkit-scrollbar {
        height: 6px;
    }
    .subskills-rail .subicon-bar::-webkit-scrollbar-thumb {
        background: #151515;
        border-radius: 3px;
    }
    .subskills-rail .subicon {
        width: 42px;
        height: 42px;
        border-radius: 6px;
        position: relative;
        overflow: hidden;
        flex: 0 0 auto;
        cursor: pointer;
        isolation: isolate;
        -webkit-backface-visibility: hidden;
        backface-visibility: hidden;
        transform: translateZ(0);
    }
    .subskills-rail .subicon+.subicon {
        margin-left: 4px;
    }
    .subskills-rail .subicon img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
        border-radius: inherit;
    }
    .subskills-rail .subicon::after {
        content: "";
        position: absolute;
        inset: 0;
        border-radius: inherit;
        box-shadow: inset 0 0 0 2px var(--icon-idle, #cfcfcf);
        pointer-events: none;
        z-index: 2;
        transition: box-shadow .12s ease;
    }
    .subskills-rail .subicon:hover::after {
        box-shadow: inset 0 0 0 2px #e6e6e6;
    }
    .subskills-rail .subicon.active::after {
        box-shadow: inset 0 0 0 2px var(--icon-active, #FFD95A);
    }
    .video-container .skill-video {
        width: 100%;
        height: auto;
        aspect-ratio: 16 / 9;
        object-fit: cover;
        background: #000;
        border-radius: 10px;
    }
    @media (max-width: 900px) {
        .subskills-rail {
            position: static;
            transform: none;
            margin-top: -2px;
            border-top: 0;
            border-radius: 0 0 10px 10px;
        }
        .subskills-spacer {
            height: 0 !important;
        }
    }
    .skills-rail-wrap {
        position: relative;
        display: block;
        width: max-content;
        margin: 0 auto;
    }
    /* Subskills com arma disponível - borda vermelha quando inativa */
    .subicon.has-weapon-available:not(.active)::after {
        box-shadow: inset 0 0 0 2px rgba(220, 70, 70, 0.8) !important;
    }
    /* Subskill com arma ATIVA - laranja/coral vibrante */
    .subicon.has-weapon-available.active::after {
        box-shadow: inset 0 0 0 2px #FF7043 !important;
    }
    .subicon.has-weapon-available.active::before {
        box-shadow: 0 0 12px 3px rgba(255, 112, 67, 0.35), 0 0 0 4px rgba(255, 112, 67, 0.25) !important;
    }
    /* Modo arma ON - efeito animado nos subicons */
    .top-rail.skills.weapon-mode-on .subicon.has-weapon-available {
        position: relative;
    }
    .top-rail.skills.weapon-mode-on .subicon.has-weapon-available::after {
        box-shadow: none !important;
        background: linear-gradient(90deg,
                rgba(255, 80, 80, 0.9) 0%,
                rgba(255, 120, 60, 1) 25%,
                rgba(255, 80, 80, 0.9) 50%,
                rgba(255, 120, 60, 1) 75%,
                rgba(255, 80, 80, 0.9) 100%) !important;
        background-size: 400% 100% !important;
        animation: weapon-subicon-border-scan 4s linear infinite !important;
        -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0) !important;
        mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0) !important;
        -webkit-mask-composite: xor !important;
        mask-composite: exclude !important;
        padding: 2px !important;
    }
    .top-rail.skills.weapon-mode-on .subicon.has-weapon-available::before {
        content: "";
        position: absolute;
        inset: -4px;
        border-radius: calc(6px + 4px);
        pointer-events: none;
        z-index: 1;
        animation: weapon-subicon-pulse 3s ease-in-out infinite !important;
    }
    /* Subskill ativa com arma - mais intenso */
    .top-rail.skills.weapon-mode-on .subicon.has-weapon-available.active::after {
        background: linear-gradient(90deg,
                rgba(255, 87, 34, 1) 0%,
                rgba(255, 140, 60, 1) 25%,
                rgba(255, 87, 34, 1) 50%,
                rgba(255, 140, 60, 1) 75%,
                rgba(255, 87, 34, 1) 100%) !important;
    }
    .top-rail.skills.weapon-mode-on .subicon.has-weapon-available.active::before {
        box-shadow: 0 0 14px 4px rgba(255, 87, 34, 0.4), 0 0 0 4px rgba(255, 87, 34, 0.3) !important;
        animation: weapon-subicon-pulse 2.5s ease-in-out infinite !important;
    }
    @keyframes weapon-subicon-border-scan {
        0% {
            background-position: 0% 50%;
        }
        100% {
            background-position: 400% 50%;
        }
    }
    @keyframes weapon-subicon-pulse {
        0%,
        100% {
            opacity: 0.5;
            box-shadow: 0 0 8px rgba(255, 80, 80, 0.25);
        }
        50% {
            opacity: 1;
            box-shadow: 0 0 16px rgba(255, 80, 80, 0.45);
        }
    }
</style>

Edição das 14h37min de 4 de dezembro de 2025

<script>

   (function () {
       const $ = (s, root = document) => root.querySelector(s);
       const $$ = (s, root = document) => Array.from(root.querySelectorAll(s));
       const ensureRemoved = sel => {
           Array.from(document.querySelectorAll(sel)).forEach(n => n.remove());
       };
       const onceFlag = (el, key) => {
           if (!el) return false;
           if (el.dataset[key]) return false;
           el.dataset[key] = '1';
           return true;
       };
       const addOnce = (el, ev, fn) => {
           if (!el) return;
           const attr = `data-wired-${ev}`;
           if (el.hasAttribute(attr)) return;
           el.addEventListener(ev, fn);
           el.setAttribute(attr, '1');
       };
       const FLAG_ICON_FILES = {
           aggro: 'Enemyaggro-icon.png', bridge: 'Bridgemaker-icon.png', wall: 'Destroywall-icon.png', quickcast: 'Quickcast-icon.png'
       };
       const subBarTemplateCache = window.__skillSubBarTemplateCache || (window.__skillSubBarTemplateCache = new Map());
       const imagePreloadCache = window.__skillImagePreloadCache || (window.__skillImagePreloadCache = new Map());
       const videoPreloadCache = window.__skillVideoPreloadCache || (window.__skillVideoPreloadCache = new Set());
       const flagRowCache = window.__skillFlagRowCache || (window.__skillFlagRowCache = new Map());
       const flagIconURLCache = window.__skillFlagIconURLCache || (window.__skillFlagIconURLCache = new Map());
       function filePathURL(fileName) {
           const f = encodeURIComponent((fileName || 'Nada.png').replace(/^Arquivo:|^File:/, ));
           const base = (window.mw && mw.util && typeof mw.util.wikiScript === 'function') ? mw.util.wikiScript() : (window.mw && window.mw.config ? (mw.config.get('wgScript') || '/index.php') : '/index.php');
           return `${base}?title=Especial:FilePath/${f}`;
       } function slugify(s) {
           if (!s) return ;
           return String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, ).replace(/[^\w\s-]/g, ).replace(/[\s:/\-]+/g, '-').replace(/^-+|-+$/g, ).replace(/-+/g, '-');
       } window.__skillSlugify = slugify;
       function getLangKey() {
           const skillsRoot = document.getElementById('skills');
           const raw = (document.documentElement.lang || skillsRoot?.dataset.i18nDefault || 'pt').toLowerCase();
           return raw === 'pt-br' ? 'pt' : (raw.split('-')[0] || 'pt');
       } function chooseDescFrom(obj) {
           const lang = getLangKey();
           // Aceita tanto desc_i18n quanto desc para compatibilidade
           const pack = obj.desc_i18n || obj.desc || {
               pt: obj.descPt, en: obj.descEn, es: obj.descEs, pl: obj.descPl
           };
           return (pack && (pack[lang] || pack.pt || pack.en || pack.es || pack.pl)) || ;
       } function renderSubAttributesFromObj(s, L) {

const chip = (label, val) => (val ? `

${label}${val}

` : );

           const pve = (s.powerpve || ).toString().trim();
           const pvp = (s.powerpvp || ).toString().trim();
           const en = (s.energy || ).toString().trim();
           const cd = (s.cooldown || ).toString().trim();
           const rows = [cd ? chip(L.cooldown, cd) : , en ? chip((en.startsWith('-') ? L.energy_cost : L.energy_gain), en.startsWith('-') ? en.replace(/^-/, ) : en.replace(/^\+?/, )) : , pve ? chip(L.power, pve) : , pvp ? chip(L.power_pvp, pvp) : ,].filter(Boolean);

return rows.length ? `

${rows.join()}

` : ;

       } function getFlagIconURL(key) {
           if (!FLAG_ICON_FILES[key]) return ;
           if (!flagIconURLCache.has(key)) {
               flagIconURLCache.set(key, filePathURL(FLAG_ICON_FILES[key]));
           } return flagIconURLCache.get(key);
       } function renderFlagsRow(flags) {
           const arr = (flags || []).filter(Boolean);
           if (!arr.length) return ;
           const cacheKey = arr.join('|');
           if (flagRowCache.has(cacheKey)) {
               return flagRowCache.get(cacheKey);
           } const items = arr.map(k => {
               const url = getFlagIconURL(k);
               return url ? `<img class="skill-flag" data-flag="${k}" alt="" src="${url}">` : ;
           }).join();

const html = items ? `

${items}

` : ;

           if (html) flagRowCache.set(cacheKey, html);
           return html;
       } function applyFlagTooltips(container) {
           const skillsRoot = document.getElementById('skills');
           if (!skillsRoot) return;
           let pack = {
           };
           try {
               pack = JSON.parse(skillsRoot.dataset.i18nFlags || '{}');
           } catch (e) {
           } const lang = getLangKey();
           const dict = pack[lang] || pack.pt || {
           };
           const flags = container.querySelectorAll('.skill-flags .skill-flag[data-flag]');
           const tooltip = window.__globalSkillTooltip;
           if (!tooltip) return;
           flags.forEach(el => {
               const key = el.getAttribute('data-flag');
               const tip = (dict && dict[key]) || ;
               if (!tip) return;
               if (el.dataset.flagTipWired) return;
               el.dataset.flagTipWired = '1';
               el.setAttribute('aria-label', tip);
               if (el.hasAttribute('title')) el.removeAttribute('title');
               el.addEventListener('mouseenter', () => {
                   const tipEl = document.querySelector('.skill-tooltip');
                   if (tipEl) tipEl.classList.add('flag-tooltip');
                   tooltip.show(el, tip);
               });
               el.addEventListener('mousemove', () => {
                   if (performance.now() >= tooltip.lockUntil.value) {
                       tooltip.measureAndPos(el);
                   }
               });
               el.addEventListener('click', () => {
                   tooltip.lockUntil.value = performance.now() + 240;
                   tooltip.measureAndPos(el);
               });
               el.addEventListener('mouseleave', () => {
                   const tipEl = document.querySelector('.skill-tooltip');
                   if (tipEl) tipEl.classList.remove('flag-tooltip');
                   tooltip.hide();
               });
           });
       }
       // ====== Skill/Subskill inheritance helpers ======
       const mainSkillsMeta = {
           byIndex: new Map(),
           byName: new Map(),
           ready: false
       };
       function normalizeFileURL(raw, fallback = ) {
           if (!raw) return fallback;
           const val = String(raw).trim();
           if (!val) return fallback;
           if (/^(https?:)?\/\//i.test(val) || val.startsWith('data:') || val.includes('Especial:FilePath/')) {
               return val;
           } return filePathURL(val);
       }
       function extractFileNameFromURL(url) {
           if (!url) return ;
           const match = String(url).match(/(?:FilePath\/)([^&?]+)/i);
           return match ? decodeURIComponent(match[1]) : ;
       }
       function parseAttrString(raw) {
           const parts = (raw || ).split(',').map(v => v.trim());
           const safe = idx => {
               const val = parts[idx] || ;
               return (val && val !== '-') ? val : ;
           };
           return {
               powerpve: safe(0),
               powerpvp: safe(1),
               energy: safe(2),
               cooldown: safe(3)
           };
       }
       function hasText(value) {
           return typeof value === 'string' ? value.trim() !==  : value !== undefined && value !== null;
       }
       function pickFilled(current, fallback) {
           if (current === 0 || current === '0') return current;
           if (!hasText(current)) return fallback;
           return current;
       }
       function buildMainSkillsMeta(nodes) {
           if (mainSkillsMeta.ready) {
               return mainSkillsMeta;
           }
           (nodes || []).forEach(icon => {
               const index = (icon.dataset.index || ).trim();
               if (!index) return;
               const name = (icon.dataset.nome || icon.dataset.name || ).trim();
               const attrs = parseAttrString(icon.dataset.atr || );
               let iconFile = (icon.dataset.iconFile || ).trim();
               if (!iconFile) {
                   const imgSrc = icon.querySelector('img')?.src || ;
                   const iconMatch = imgSrc.match(/(?:FilePath|images)\/([^\/?]+)$/);
                   iconFile = iconMatch ? decodeURIComponent(iconMatch[1]) : ;
               }
               let videoFile = (icon.dataset.videoFile || ).trim();
               if (!videoFile) {
                   videoFile = extractFileNameFromURL(icon.dataset.video || );
               }
               const meta = {
                   index,
                   name,
                   icon: iconFile || 'Nada.png',
                   level: icon.dataset.level || ,
                   video: videoFile || ,
                   powerpve: attrs.powerpve || ,
                   powerpvp: attrs.powerpvp || ,
                   energy: attrs.energy || ,
                   cooldown: attrs.cooldown || ,
                   desc: icon.dataset.desc || ,
                   descPt: icon.dataset.descPt || ,
                   descEn: icon.dataset.descEn || ,
                   descEs: icon.dataset.descEs || ,
                   descPl: icon.dataset.descPl || 
               };
               mainSkillsMeta.byIndex.set(index, meta);
               mainSkillsMeta.byIndex.set(parseInt(index, 10), meta);
               if (name) {
                   mainSkillsMeta.byName.set(name, meta);
               }
           });
           mainSkillsMeta.ready = true;
           return mainSkillsMeta;
       }
       function inheritSubskillFromMain(sub, meta) {
           if (!sub || !meta) return sub;
           // Suporta refS (novo) e refM (legado)
           const refS = ((sub.refS || sub.S || sub.s || ) + ).trim();
           const refIndex = ((sub.refM || sub.M || sub.m || ) + ).trim();
           let name = (sub.name || sub.n || ).trim();
           let main = null;


           // Primeiro tenta por refS
           if (refS) {
               main = meta.byIndex.get(refS) || meta.byIndex.get(parseInt(refS, 10));
           }
           // Depois por refM
           if (!main && refIndex) {
               main = meta.byIndex.get(refIndex) || meta.byIndex.get(parseInt(refIndex, 10));
           }
           // Por último pelo nome
           if (!main && name) {
               main = meta.byName.get(name);
           }
           if (!main) {
               return sub;
           }
           const hydrated = { ...sub };
           if (!name && main.name) {
               name = main.name;
           }
           hydrated.name = name || hydrated.name || main.name || ;
           hydrated.icon = pickFilled(hydrated.icon, main.icon || 'Nada.png');
           hydrated.level = pickFilled(hydrated.level, main.level || );
           hydrated.video = pickFilled(hydrated.video, main.video || );
           hydrated.powerpve = pickFilled(hydrated.powerpve, main.powerpve || );
           hydrated.powerpvp = pickFilled(hydrated.powerpvp, main.powerpvp || );
           hydrated.energy = pickFilled(hydrated.energy, main.energy || );
           hydrated.cooldown = pickFilled(hydrated.cooldown, main.cooldown || );
           if (!hasText(hydrated.descPt) && hasText(main.descPt)) hydrated.descPt = main.descPt;
           if (!hasText(hydrated.descEn) && hasText(main.descEn)) hydrated.descEn = main.descEn;
           if (!hasText(hydrated.descEs) && hasText(main.descEs)) hydrated.descEs = main.descEs;
           if (!hasText(hydrated.descPl) && hasText(main.descPl)) hydrated.descPl = main.descPl;
           if (!hasText(hydrated.desc) && hasText(main.desc)) hydrated.desc = main.desc;
           if (!hydrated.desc_i18n && (hydrated.descPt || hydrated.descEn || hydrated.descEs || hydrated.descPl)) {
               hydrated.desc_i18n = {
                   pt: hydrated.descPt || ,
                   en: hydrated.descEn || ,
                   es: hydrated.descEs || ,
                   pl: hydrated.descPl || 
               };
           }
           return hydrated;
       }
       function inheritSubskillTree(subs, meta) {
           if (!Array.isArray(subs)) return [];
           return subs.map(sub => {
               const hydrated = inheritSubskillFromMain(sub, meta);
               if (Array.isArray(hydrated.subs)) {
                   hydrated.subs = inheritSubskillTree(hydrated.subs, meta);
               }
               return hydrated;
           });
       }
       function collectAssetsFromSubs(subs, iconsSet, videosSet, flagsSet) {
           if (!Array.isArray(subs)) return;
           subs.forEach(sub => {
               const iconURL = normalizeFileURL(sub.icon || 'Nada.png', filePathURL('Nada.png'));
               if (iconURL) iconsSet.add(iconURL);
               if (sub.video) {
                   const videoURL = normalizeFileURL(sub.video);
                   if (videoURL) videosSet.add(videoURL);
               } if (Array.isArray(sub.flags)) {
                   sub.flags.forEach(flagKey => {
                       const url = getFlagIconURL(flagKey);
                       if (url) flagsSet.add(url);
                   });
               } if (Array.isArray(sub.subs)) {
                   collectAssetsFromSubs(sub.subs, iconsSet, videosSet, flagsSet);
               }
           });
       } function buildAssetManifest() {
           if (window.__skillAssetManifest && window.__skillAssetManifest.ready) {
               return window.__skillAssetManifest;
           } const iconsSet = new Set();
           const videosSet = new Set();
           const flagsSet = new Set();
           iconItems.forEach(el => {
               const img = el.querySelector('img');
               if (img && img.src) {
                   iconsSet.add(img.src);
               } else if (el.dataset.icon) {
                   iconsSet.add(normalizeFileURL(el.dataset.icon));
               } const videoRaw = (el.dataset.video || ).trim();
               if (videoRaw) {
                   videosSet.add(normalizeFileURL(videoRaw));
               } if (el.dataset.flags) {
                   try {
                       const parsedFlags = JSON.parse(el.dataset.flags);
                       (parsedFlags || []).forEach(flagKey => {
                           const url = getFlagIconURL(flagKey);
                           if (url) flagsSet.add(url);
                       });
                   } catch (e) {
                   }
               } if (el.dataset.subs) {
                   try {
                       const subs = JSON.parse(el.dataset.subs);
                       collectAssetsFromSubs(subs, iconsSet, videosSet, flagsSet);
                   } catch (e) {
                   }
               }
           });
           Object.keys(FLAG_ICON_FILES).forEach(flagKey => {
               const url = getFlagIconURL(flagKey);
               if (url) flagsSet.add(url);
           });
           const manifest = {
               icons: iconsSet, videos: videosSet, flags: flagsSet, ready: true
           };
           window.__skillAssetManifest = manifest;
           return manifest;
       } function preloadImagesFromSet(set) {
           if (!set || !set.size) return;
           set.forEach(url => {
               if (!url || imagePreloadCache.has(url)) return;
               const img = new Image();
               img.decoding = 'async';
               img.loading = 'eager';
               img.referrerPolicy = 'same-origin';
               img.src = url;
               imagePreloadCache.set(url, img);
           });
       } function preloadVideosFromSet(set) {
           if (!set || !set.size) return;
           const head = document.head || document.getElementsByTagName('head')[0];
           set.forEach(url => {
               if (!url || videoPreloadCache.has(url)) return;
               const link = document.createElement('link');
               link.rel = 'preload';
               link.as = 'video';
               link.href = url;
               link.crossOrigin = 'anonymous';
               head.appendChild(link);
               videoPreloadCache.add(url);
           });
       } const subskillVideosCache = new Map();
       window.__subskillVideosCache = subskillVideosCache;
       let assetManifest = null;
       const skillsTab = $('#skills');
       const skinsTab = $('#skins');
       ensureRemoved('.top-rail');
       ensureRemoved('.content-card');
       ensureRemoved('.video-placeholder');
       Array.from(document.querySelectorAll('.card-skins-title, .card-skins .card-skins-title, .cardskins-title, .rail-title')).forEach(t => {
           if ((t.textContent || ).trim().toLowerCase().includes('skins')) {
               t.remove();
           }
       });
       if (skillsTab) {
           const iconBar = skillsTab.querySelector('.icon-bar');
           if (iconBar) {
               const rail = document.createElement('div');
               rail.className = 'top-rail skills';
               rail.appendChild(iconBar);
               skillsTab.prepend(rail);
           } const details = skillsTab.querySelector('.skills-details');
           const videoContainer = skillsTab.querySelector('.video-container');
           const card = document.createElement('div');
           card.className = 'content-card skills-grid';
           if (details) card.appendChild(details);
           if (videoContainer) card.appendChild(videoContainer);
           skillsTab.appendChild(card);
       } if (skinsTab) {
           const wrapper = skinsTab.querySelector('.skins-carousel-wrapper');
           const rail = document.createElement('div');
           rail.className = 'top-rail skins';
           const title = document.createElement('div');
           title.className = 'rail-title';
           title.textContent = 'Skins & Spotlights';
           rail.appendChild(title);
           if (wrapper) {
               const card = document.createElement('div');
               card.className = 'content-card';
               card.appendChild(wrapper);
               skinsTab.prepend(rail);
               skinsTab.appendChild(card);
           } else {
               skinsTab.prepend(rail);
           }
       } const iconsBar = $('#skills') ? $('.icon-bar', $('#skills')) : null;
       const skillsTopRail = iconsBar ? iconsBar.closest('.top-rail.skills') : null;
       const iconItems = iconsBar ? Array.from(iconsBar.querySelectorAll('.skill-icon')) : [];
       buildMainSkillsMeta(iconItems);
       // Verifica se há weapon em skills principais OU em subskills
       function checkHasAnyWeapon() {
           // Verifica skills principais
           if (iconItems.some(el => !!el.dataset.weapon)) {
               return true;
           }
           // Verifica subskills
           for (const el of iconItems) {
               const subsRaw = el.getAttribute('data-subs');
               if (!subsRaw) continue;
               try {
                   const subs = JSON.parse(subsRaw);
                   if (Array.isArray(subs) && subs.some(s => s && s.weapon)) {
                       return true;
                   }
               } catch (e) { }
           }
           return false;
       }
       const hasWeaponSkillAvailable = checkHasAnyWeapon();
       let weaponToggleBtn = null;
       if (!assetManifest) {
           assetManifest = buildAssetManifest();
           preloadImagesFromSet(assetManifest.icons);
           preloadImagesFromSet(assetManifest.flags);
           preloadVideosFromSet(assetManifest.videos);
       } const descBox = $('#skills') ? $('.desc-box', $('#skills')) : null;
       const videoBox = $('#skills') ? $('.video-container', $('#skills')) : null;
       const videosCache = new Map();
       const nestedVideoElByIcon = new WeakMap();
       const barStack = [];
       window.__barStack = barStack;
       let initialBarSnapshot = null;
       let totalVideos = 0, loadedVideos = 0, autoplay = false;
       window.__lastActiveSkillIcon = null;
       let userHasInteracted = false;
       let globalWeaponEnabled = false;
       try {
           if (localStorage.getItem('glaWeaponEnabled') === '1') {
               globalWeaponEnabled = true;
           }
       } catch (err) {
       }
       const weaponStateListeners = new Set();
       let showWeaponPopupFn = null;
       let popupShouldOpen = false;
       function attachWeaponPopupFn(fn) {
           if (typeof fn !== 'function') return;
           showWeaponPopupFn = fn;
           if (popupShouldOpen) {
               popupShouldOpen = false;
               try {
                   showWeaponPopupFn();
               } catch (err) {
               }
           }
       }
       attachWeaponPopupFn(window.__glaWeaponShowPopup);
       function requestWeaponPopupDisplay() {
           try {
               if (localStorage.getItem('glaWeaponPopupDismissed') === '1') return;
           } catch (err) {
           }
           if (typeof showWeaponPopupFn === 'function') {
               showWeaponPopupFn();
               return;
           }
           popupShouldOpen = true;
       }
       function onWeaponStateChange(fn) {
           if (typeof fn !== 'function') return;
           weaponStateListeners.add(fn);
       }
       function syncWeaponButtonState(enabled) {
           if (!weaponToggleBtn || !weaponToggleBtn.isConnected) return;
           // Usa .weapon-active em vez de .active para não conflitar com skills
           weaponToggleBtn.classList.toggle('weapon-active', !!enabled);
           weaponToggleBtn.classList.remove('active'); // Garante que .active nunca seja aplicado
           weaponToggleBtn.setAttribute('aria-pressed', enabled ? 'true' : 'false');
           weaponToggleBtn.setAttribute('aria-label', enabled ? 'Desativar Arma Especial' : 'Ativar Arma Especial');
       }
       function syncWeaponRailState(enabled) {
           if (skillsTopRail) {
               skillsTopRail.classList.toggle('weapon-mode-on', !!enabled);
           }
       }
       function notifyWeaponStateListeners(enabled) {
           weaponStateListeners.forEach(listener => {
               try {
                   listener(enabled);
               } catch (err) {
               }
           });
       }
       let pendingWeaponState = null;
       window.addEventListener('weapon:ready', (ev) => {
           if (ev && ev.detail && ev.detail.showPopup) {
               attachWeaponPopupFn(ev.detail.showPopup);
           }
           if (pendingWeaponState === null) return;
           if (typeof window.__applyWeaponState === 'function') {
               const target = pendingWeaponState;
               pendingWeaponState = null;
               window.__applyWeaponState(target);
           }
       });
       window.__setGlobalWeaponEnabled = (enabled) => {
           globalWeaponEnabled = enabled;
           notifyWeaponStateListeners(enabled);
       };
       function requestWeaponState(targetState) {
           if (typeof window.__applyWeaponState === 'function') {
               pendingWeaponState = null;
               window.__applyWeaponState(targetState);
               return;
           }
           pendingWeaponState = targetState;
       }
       onWeaponStateChange(syncWeaponButtonState);
       function reapplyWeaponClassesToBar() {
           if (!globalWeaponEnabled) return;
           // SISTEMA UNIFICADO: Aplica em skills E subskills
           iconsBar.querySelectorAll('.skill-icon[data-weapon], .subicon[data-weapon]').forEach(el => {
               if (!el.classList.contains('has-weapon-available')) {
                   el.classList.add('has-weapon-available');
               }
               if (!el.querySelector('.weapon-indicator')) {
                   const ind = document.createElement('div');
                   ind.className = 'weapon-indicator';
                   el.appendChild(ind);
               }
           });
       }
       function setupWeaponBarToggle(shouldShow) {
           if (!shouldShow || !iconsBar) return;
           if (iconsBar.querySelector('.weapon-bar-toggle')) return;
           const btn = document.createElement('button');
           btn.type = 'button';
           btn.className = 'skill-icon weapon-bar-toggle';
           btn.dataset.weaponToggle = '1';
           btn.dataset.nome = 'Arma Especial';
           btn.setAttribute('aria-pressed', 'false');
           btn.setAttribute('aria-label', 'Arma Especial');
           btn.innerHTML = '<svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path fill="currentColor" d="M19.14 12.94c.04-.31.06-.63.06-.94s-.02-.63-.06-.94l2.03-1.58a.5.5 0 00.12-.62l-1.92-3.32a.5.5 0 00-.61-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.37-2.48a.55.55 0 00-.55-.5h-3.82a.55.55 0 00-.55.5l-.37 2.48c-.59.24-1.12.56-1.62.94l-2.39-.96a.5.5 0 00-.61.22L3.13 8.5a.5.5 0 00.12.62l2.03 1.58c-.04.31-.06.63-.06.94s.02.63.06.94l-2.03 1.58a.5.5 0 00-.12.62l1.92 3.32a.5.5 0 00.61.22l2.39-.96c.5.38 1.03.7 1.62.94l.37 2.48a.55.55 0 00.55.5h3.82a.55.55 0 00.55-.5l.37-2.48c.59-.24 1.12-.56 1.62-.94l2.39.96a.5.5 0 00.61-.22l1.92-3.32a.5.5 0 00-.12-.62zM12 15.6a3.6 3.6 0 110-7.2 3.6 3.6 0 010 7.2z"></path></svg>';
           iconsBar.appendChild(btn);
           weaponToggleBtn = btn;
           syncWeaponButtonState(globalWeaponEnabled);
           btn.addEventListener('click', () => {
               const nextState = !globalWeaponEnabled;
               if (nextState) {
                   requestWeaponPopupDisplay();
               }
               requestWeaponState(nextState);
           });
           // Wire tooltip for weapon toggle
           const tooltip = window.__globalSkillTooltip;
           if (tooltip) {
               btn.addEventListener('mouseenter', () => {
                   const tip = document.querySelector('.skill-tooltip');
                   if (tip) tip.classList.add('weapon-tooltip');
                   tooltip.show(btn, globalWeaponEnabled ? 'Desativar Arma Especial' : 'Ativar Arma Especial');
               });
               btn.addEventListener('mouseleave', () => {
                   const tip = document.querySelector('.skill-tooltip');
                   if (tip) tip.classList.remove('weapon-tooltip');
                   tooltip.hide();
               });
           }
           reapplyWeaponClassesToBar();
       }
       onWeaponStateChange(syncWeaponRailState);
       syncWeaponRailState(globalWeaponEnabled);
       setupWeaponBarToggle(hasWeaponSkillAvailable);
       (function injectWeaponStyles() {
           if (document.getElementById('weapon-toggle-styles')) return;
           const style = document.createElement('style');
           style.id = 'weapon-toggle-styles';
           style.textContent = `
               /* Animação da borda nos ícones */
               @keyframes weapon-icon-border-scan {
                   0% { background-position: 0% 0%; }
                   100% { background-position: 400% 0%; }
               }
               @keyframes weapon-icon-pulse {
                   0%, 100% { 
                       opacity: 0.5;
                       box-shadow: 0 0 8px rgba(255, 80, 80, 0.25);
                   }
                   50% { 
                       opacity: 1;
                       box-shadow: 0 0 16px rgba(255, 80, 80, 0.45);
                   }
               }
               /* Skills com arma disponível - borda vermelha quando inativa */
               .skill-icon.has-weapon-available:not(.weapon-bar-toggle):not(.active)::after {
                   box-shadow: inset 0 0 0 var(--icon-ring-w) rgba(220, 70, 70, 0.8) !important;
               }
               /* Skill com arma ATIVA - laranja/coral vibrante */
               .skill-icon.has-weapon-available:not(.weapon-bar-toggle).active::after {
                   box-shadow: inset 0 0 0 var(--icon-ring-w) #FF7043 !important;
               }
               .skill-icon.has-weapon-available:not(.weapon-bar-toggle).active::before {
                   box-shadow: 0 0 12px 3px rgba(255, 112, 67, 0.35), 0 0 0 4px rgba(255, 112, 67, 0.25) !important;
               }
               /* Modo arma ON - efeito animado nos ícones */
               .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle) {
                   position: relative;
               }
               .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle)::after {
                   box-shadow: none !important;
                   background: linear-gradient(90deg, 
                       rgba(255, 80, 80, 0.9) 0%,
                       rgba(255, 120, 60, 1) 25%,
                       rgba(255, 80, 80, 0.9) 50%,
                       rgba(255, 120, 60, 1) 75%,
                       rgba(255, 80, 80, 0.9) 100%
                   ) !important;
                   background-size: 400% 100% !important;
                   animation: weapon-icon-border-scan 4s linear infinite !important;
                   -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0) !important;
                   mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0) !important;
                   -webkit-mask-composite: xor !important;
                   mask-composite: exclude !important;
                   padding: var(--icon-ring-w) !important;
               }
               .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle)::before {
                   animation: weapon-icon-pulse 3s ease-in-out infinite !important;
               }
               /* Skill ativa com arma - mais intenso */
               .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle).active::after {
                   background: linear-gradient(90deg, 
                       rgba(255, 87, 34, 1) 0%,
                       rgba(255, 140, 60, 1) 25%,
                       rgba(255, 87, 34, 1) 50%,
                       rgba(255, 140, 60, 1) 75%,
                       rgba(255, 87, 34, 1) 100%
                   ) !important;
               }
               .top-rail.skills.weapon-mode-on .skill-icon.has-weapon-available:not(.weapon-bar-toggle).active::before {
                   box-shadow: 0 0 14px 4px rgba(255, 87, 34, 0.4), 0 0 0 4px rgba(255, 87, 34, 0.3) !important;
                   animation: weapon-icon-pulse 2.5s ease-in-out infinite !important;
               }
               .skill-icon .weapon-indicator {
                   display: none;
               }
               /* Variáveis de cor vermelha para skill ativa com arma equipada */
               .skill-icon.weapon-equipped {
                   --icon-active: #FF6B6B;
                   --icon-active-ring: rgba(255, 100, 100, 0.6);
                   --icon-active-glow: rgba(255, 90, 90, 0.45);
               }
               /* Badge de arma no canto inferior direito */
               .skill-icon .weapon-badge {
                   position: absolute;
                   bottom: 3px;
                   right: 3px;
                   width: 16px;
                   height: 16px;
                   background: var(--weapon-badge-url) center/contain no-repeat;
                   filter: drop-shadow(0 1px 2px rgba(0,0,0,0.6));
                   pointer-events: none;
                   z-index: 10;
                   border-radius: 3px;
                   display: none;
               }
               .skill-icon.weapon-equipped .weapon-badge {
                   display: block;
               }
           `.replace(/\s+/g, ' ').trim();
           document.head.appendChild(style);
       })();
       function applyWeaponBadge(el, weaponData, equipped) {
           // Encontrar ou criar o badge
           let badge = el.querySelector('.weapon-badge');
           if (!badge) {
               badge = document.createElement('div');
               badge.className = 'weapon-badge';
               el.appendChild(badge);
           }
           if (equipped && weaponData) {
               el.classList.add('weapon-equipped');
               el.style.setProperty('--weapon-badge-url', `url('${filePathURL(weaponData.icon || 'Nada.png')}')`);
           } else {
               el.classList.remove('weapon-equipped');
               el.style.removeProperty('--weapon-badge-url');
           }
       } function getWeaponKey(el) {
           return (el.dataset.index || ) + ':' + (el.dataset.nome || el.dataset.name || );
       } function isWeaponModeOn() {
           try {
               return localStorage.getItem('glaWeaponEnabled') === '1';
           } catch (e) {
               return false;
           }
       } function getWeaponDataForIcon(iconEl) {
           if (!iconEl || !iconEl.dataset.weapon) return null;
           try {
               return JSON.parse(iconEl.dataset.weapon);
           } catch (e) {
               return null;
           }
       } function getEffectiveSkillVideoFromIcon(iconEl) {
           const weaponOn = globalWeaponEnabled;
           const weaponData = getWeaponDataForIcon(iconEl);
           const baseVideoFile = (iconEl.dataset.videoFile || ).trim();
           const baseVideoURL = (iconEl.dataset.video || ).trim();
           console.log('[Skills DEBUG]', {
               skillName: iconEl.dataset.nome || iconEl.dataset.name,
               weaponOn,
               hasWeaponData: !!weaponData,
               weaponData: weaponData,
               baseVideoFile,
               baseVideoURL
           });
           if (weaponOn && weaponData && weaponData.video && weaponData.video.trim() !== ) {
               console.log('[Skills] video escolhido (weapon)', iconEl.dataset.nome || iconEl.dataset.name, weaponData.video);
               return weaponData.video.trim();
           }
           const result = baseVideoFile || baseVideoURL || ;
           console.log('[Skills] video escolhido (base)', iconEl.dataset.nome || iconEl.dataset.name, result);
           return result;
       } function createVideoElement(videoURL, extraAttrs = {
       }) {
           const v = document.createElement('video');
           v.className = 'skill-video';
           v.setAttribute('controls', );
           v.setAttribute('preload', 'metadata');
           v.setAttribute('playsinline', );
           v.style.display = 'none';
           v.style.width = '100%';
           v.style.height = 'auto';
           v.style.aspectRatio = '16/9';
           v.style.objectFit = 'cover';
           Object.keys(extraAttrs).forEach(k => {
               v.dataset[k] = extraAttrs[k];
           });
           // Detectar formato do vídeo pela extensão
           const ext = (videoURL.split('.').pop() || ).toLowerCase().split('?')[0];
           const mimeTypes = {
               'mp4': 'video/mp4',
               'm4v': 'video/mp4',
               'webm': 'video/webm',
               'ogv': 'video/ogg',
               'ogg': 'video/ogg',
               'mov': 'video/quicktime'
           };
           const mimeType = mimeTypes[ext] || 'video/mp4';
           const src = document.createElement('source');
           src.src = videoURL;
           src.type = mimeType;
           v.appendChild(src);
           // Fallback para Safari/iOS mais antigos
           v.setAttribute('webkit-playsinline', );
           v.setAttribute('x-webkit-airplay', 'allow');
           return v;
       } function precreateSubskillVideos() {
           if (!videoBox) return;
           iconItems.forEach(parentIcon => {
               const subsRaw = parentIcon.dataset.subs || parentIcon.getAttribute('data-subs');
               if (!subsRaw) return;
               try {
                   const subs = JSON.parse(subsRaw);
                   if (!Array.isArray(subs)) return;
                   const parentIdx = parentIcon.dataset.index || ;
                   subs.forEach(s => {
                       if (!s.video || s.video.trim() ===  || s.video === 'Nada.png' || s.video.toLowerCase().includes('nada.png')) return;
                       const subName = (s.name || s.n || ).trim();
                       const key = `sub:${parentIdx}:${subName}`;
                       if (subskillVideosCache.has(key)) return;
                       const videoURL = normalizeFileURL(s.video);
                       if (!videoURL || videoURL.trim() === ) return;
                       const v = createVideoElement(videoURL, {
                           sub: '1', parentIndex: parentIdx, subName: subName
                       });
                       videoBox.appendChild(v);
                       subskillVideosCache.set(key, v);
                   });
               } catch (e) {
               }
           });
       } setTimeout(precreateSubskillVideos, 500);
       if (iconItems.length && videoBox) {
           iconItems.forEach(el => {
               const src = (el.dataset.video || ).trim();
               const idx = el.dataset.index || ;
               if (!src || videosCache.has(idx)) return;
               totalVideos++;
               const v = createVideoElement(src, {
                   index: idx
               });
               v.style.maxWidth = '100%';
               v.addEventListener('canplaythrough', () => {
                   loadedVideos++;
                   if (!userHasInteracted && loadedVideos === 1) {
                       try {
                           v.pause();
                           v.currentTime = 0;
                       } catch (e) {
                       }
                   } if (loadedVideos === totalVideos) autoplay = true;
               }, {
                   once: true
               });
               v.addEventListener('error', () => {
                   loadedVideos++;
                   if (loadedVideos === totalVideos) autoplay = true;
               }, {
                   once: true
               });
               videoBox.appendChild(v);
               videosCache.set(idx, v);
           });
       } function wireTooltipsForNewIcons() {
           const tip = document.querySelector('.skill-tooltip');
           if (!tip) return;
           let lockUntil2 = 0;
           Array.from(document.querySelectorAll('.icon-bar .skill-icon')).forEach(icon => {
               if (icon.dataset.weaponToggle === '1' || icon.classList.contains('weapon-bar-toggle')) return;
               if (icon.dataset.tipwired) return;
               icon.dataset.tipwired = '1';
               const label = icon.dataset.nome || icon.dataset.name || icon.title || ;
               if (label && !icon.hasAttribute('aria-label')) icon.setAttribute('aria-label', label);
               if (icon.hasAttribute('title')) icon.removeAttribute('title');
               const img = icon.querySelector('img');
               if (img) {
                   const imgAlt = img.getAttribute('alt') || ;
                   const imgTitle = img.getAttribute('title') || ;
                   if (!label && (imgAlt || imgTitle)) icon.setAttribute('aria-label', imgAlt || imgTitle);
                   img.setAttribute('alt', );
                   if (img.hasAttribute('title')) img.removeAttribute('title');
               } const measureAndPos = (el) => {
                   if (!el || tip.getAttribute('aria-hidden') === 'true') return;
                   tip.style.left = '0px';
                   tip.style.top = '0px';
                   const rect = el.getBoundingClientRect();
                   const tr = tip.getBoundingClientRect();
                   let left = Math.round(rect.left + (rect.width - tr.width) / 2);
                   left = Math.max(8, Math.min(left, window.innerWidth - tr.width - 8));
                   const coarse = (window.matchMedia && matchMedia('(pointer: coarse)').matches) || (window.innerWidth <= 600);
                   let top = coarse ? Math.round(rect.bottom + 10) : Math.round(rect.top - tr.height - 8);
                   if (top < 8) top = Math.round(rect.bottom + 10);
                   tip.style.left = left + 'px';
                   tip.style.top = top + 'px';
               };
               const show = (el, text) => {
                   tip.textContent = text || ;
                   tip.setAttribute('aria-hidden', 'false');
                   measureAndPos(el);
                   tip.style.opacity = '1';
               };
               const hide = () => {
                   tip.setAttribute('aria-hidden', 'true');
                   tip.style.opacity = '0';
                   tip.style.left = '-9999px';
                   tip.style.top = '-9999px';
               };
               icon.addEventListener('mouseenter', () => show(icon, (icon.dataset.nome || icon.dataset.name || )));
               icon.addEventListener('mousemove', () => {
                   if (performance.now() >= lockUntil2) measureAndPos(icon);
               });
               icon.addEventListener('click', () => {
                   lockUntil2 = performance.now() + 240;
                   measureAndPos(icon);
               });
               icon.addEventListener('mouseleave', hide);
           });
       } function showVideoForIcon(el) {
           userHasInteracted = true;
           if (!videoBox) return;
           const effectiveVideo = getEffectiveSkillVideoFromIcon(el);
           if (!effectiveVideo || effectiveVideo.trim() === ) {
               videoBox.style.display = 'none';
               return;
           }
           const videoURL = normalizeFileURL(effectiveVideo);
           if (!videoURL || videoURL.trim() === ) {
               videoBox.style.display = 'none';
               return;
           }
           Array.from(videoBox.querySelectorAll('video.skill-video')).forEach(v => {
               try {
                   v.pause();
               } catch (e) {
               }
               v.style.display = 'none';
           });
           if (window.__subskills) window.__subskills.hideAll?.(videoBox);
           const hasIdx = !!el.dataset.index;
           const weaponOn = globalWeaponEnabled;
           const weaponData = getWeaponDataForIcon(el);
           const isWeaponVideo = weaponOn && weaponData && weaponData.video && weaponData.video.trim() !== ;
           console.log('[Skills] showVideoForIcon chamado', {
               skillName: el.dataset.nome || el.dataset.name,
               weaponOn,
               isWeaponVideo,
               effectiveVideo: getEffectiveSkillVideoFromIcon(el)
           });
           const videoKey = isWeaponVideo ? `weapon:${getWeaponKey(el)}` : (el.dataset.index || );
           if (hasIdx && !isWeaponVideo && videosCache.has(el.dataset.index)) {
               const v = videosCache.get(el.dataset.index);
               videoBox.style.display = 'block';
               v.style.display = 'block';
               try {
                   v.currentTime = 0;
               } catch (e) {
               }
               const suppress = document.body.dataset.suppressSkillPlay === '1';
               if (!suppress) {
                   v.play().catch(() => {
                   });
               } else {
                   try {
                       v.pause();
                   } catch (e) {
                   }
               }
               return;
           }
           let v = null;
           if (isWeaponVideo) {
               v = videoBox.querySelector(`video[data-weapon-key="${videoKey}"]`);
           } else {
               v = nestedVideoElByIcon.get(el);
           }
           if (!v) {
               v = createVideoElement(videoURL, isWeaponVideo ? {
                   weaponKey: videoKey
               } : {});
               if (isWeaponVideo) {
                   videoBox.appendChild(v);
               } else {
                   videoBox.appendChild(v);
                   nestedVideoElByIcon.set(el, v);
               }
           } else {
               const src = v.querySelector('source');
               if (src && src.src !== videoURL) {
                   src.src = videoURL;
                   v.load();
               }
           }
           videoBox.style.display = 'block';
           v.style.display = 'block';
           try {
               v.currentTime = 0;
           } catch (e) {
           }
           const suppress = document.body.dataset.suppressSkillPlay === '1';
           if (!suppress) {
               v.play().catch(() => {
               });
           } else {
               try {
                   v.pause();
               } catch (e) {
               }
           }
       } function activateSkill(el, options = {
       }) {
           const {
               openSubs = true
           } = options;
           const tip = document.querySelector('.skill-tooltip');
           if (tip) {
               tip.setAttribute('aria-hidden', 'true');
               tip.style.opacity = '0';
               tip.style.left = '-9999px';
               tip.style.top = '-9999px';
           } const skillsRoot = document.getElementById('skills');
           const i18nMap = skillsRoot ? JSON.parse(skillsRoot.dataset.i18nAttrs || '{}') : {
           };
           const L = i18nMap[getLangKey()] || i18nMap.pt || {
               cooldown: 'Recarga', energy_gain: 'Ganho de energia', energy_cost: 'Custo de energia', power: 'Poder', power_pvp: 'Poder PvP', level: 'Nível'
           };
           const name = el.dataset.nome || el.dataset.name || ;
           const level = (el.dataset.level || ).trim();
           let weaponData = null;
           if (el.dataset.weapon) {
               try {
                   weaponData = JSON.parse(el.dataset.weapon);
               } catch (e) {
                   weaponData = null;
               }
           } const hasWeapon = !!weaponData;
           const weaponEquipped = hasWeapon && globalWeaponEnabled;
           const lang = getLangKey();
           const baseDescPack = {
               pt: el.dataset.descPt || , en: el.dataset.descEn || , es: el.dataset.descEs || , pl: el.dataset.descPl || 
           };
           const baseDesc = baseDescPack[lang] || baseDescPack.pt || baseDescPack.en || baseDescPack.es || baseDescPack.pl || el.dataset.desc || ;
           // Aceita tanto desc_i18n quanto desc para compatibilidade
           let weaponDescPack = {};
           if (weaponData) {
               if (weaponData.desc_i18n) {
                   weaponDescPack = weaponData.desc_i18n;
               } else if (weaponData.desc) {
                   weaponDescPack = weaponData.desc;
               } else {
                   weaponDescPack = {
                       pt: weaponData.descPt || , en: weaponData.descEn || , es: weaponData.descEs || , pl: weaponData.descPl || 
                   };
               }
           }
           const weaponDesc = weaponDescPack[lang] || weaponDescPack.pt || weaponDescPack.en || weaponDescPack.es || weaponDescPack.pl || ;
           const chosenDesc = (weaponEquipped && weaponDesc) ? weaponDesc : baseDesc;
           const descHtml = chosenDesc.replace(/(.*?)/g, '$1');
           let attrsHTML = ;
           if (weaponEquipped && weaponData) {
               const wPve = (weaponData.powerpve || ).toString().trim();
               const wPvp = (weaponData.powerpvp || ).toString().trim();
               const wEnergy = (weaponData.energy || ).toString().trim();
               const wCd = (weaponData.cooldown || ).toString().trim();
               const weaponAttrs = [wPve, wPvp, wEnergy, wCd].join(',');
               attrsHTML = renderAttributes(weaponAttrs);
           } else {
               attrsHTML = el.dataset.atr ? renderAttributes(el.dataset.atr) : (el.dataset.subattrs ? renderSubAttributesFromObj(JSON.parse(el.dataset.subattrs), L) : );
           } let flagsHTML = ;
           if (el.dataset.flags) {
               try {
                   const flags = JSON.parse(el.dataset.flags);
                   flagsHTML = renderFlagsRow(flags);
               } catch (e) {
               }
           } if (descBox) {

descBox.innerHTML = `

${name}

${level ? `

${L.level} ${level}

` : }${attrsHTML}

${descHtml}

`;

           } if (hasWeapon) {
               applyWeaponBadge(el, weaponData, weaponEquipped);
           } if (videoBox) {
               const oldFlags = videoBox.querySelector('.skill-flags');
               if (oldFlags) oldFlags.remove();
               if (flagsHTML) {
                   videoBox.insertAdjacentHTML('beforeend', flagsHTML);
                   applyFlagTooltips(videoBox);
               }
           } const currIcons = Array.from(iconsBar.querySelectorAll('.skill-icon'));
           currIcons.forEach(i => i.classList.remove('active'));
           el.classList.add('active');
           if (!autoplay && loadedVideos > 0) autoplay = true;
           window.__lastActiveSkillIcon = el;
           // Lógica de vídeo: usa função centralizada que já considera weapon
           showVideoForIcon(el);
           const subsRaw = el.dataset.subs || el.getAttribute('data-subs');
           const isBack = el.dataset.back === 'true' || el.getAttribute('data-back') === 'true' || el.dataset.back === 'yes' || el.getAttribute('data-back') === 'yes' || el.dataset.back === '1' || el.getAttribute('data-back') === '1';
           if (isBack && barStack.length) {
               const prev = barStack.pop();
               renderBarFromItems(prev.items);
               const btn = document.querySelector('.skills-back-wrapper');
               if (btn) btn.style.display = barStack.length ? 'block' : 'none';
               return;
           } if (openSubs && subsRaw && subsRaw.trim() !== ) {
               if (barStack.length && barStack[barStack.length - 1].parentIcon === el) return;
               try {
                   const subs = JSON.parse(subsRaw);
                   pushSubBarFrom(subs, el);
               } catch {
               }
           }
       } function wireClicksForCurrentBar() {
           const currIcons = Array.from(iconsBar.querySelectorAll('.skill-icon'));
           currIcons.forEach(el => {
               if (el.dataset.weaponToggle === '1' || el.classList.contains('weapon-bar-toggle')) return;
               if (el.dataset.wired) return;
               el.dataset.wired = '1';
               const label = el.dataset.nome || el.dataset.name || ;
               el.setAttribute('aria-label', label);
               if (el.hasAttribute('title')) el.removeAttribute('title');
               const img = el.querySelector('img');
               if (img) {
                   img.setAttribute('alt', );
                   if (img.hasAttribute('title')) img.removeAttribute('title');
               } el.addEventListener('click', () => {
                   activateSkill(el, {
                       openSubs: true
                   });
               });
           });
           wireTooltipsForNewIcons();
       } function animateIconsBarEntrance() {
           Array.from(iconsBar.children).forEach((c, i) => {
               c.style.opacity = '0';
               c.style.transform = 'translateY(6px)';
               requestAnimationFrame(() => {
                   setTimeout(() => {
                       c.style.transition = 'opacity .18s ease, transform .18s ease';
                       c.style.opacity = '1';
                       c.style.transform = 'translateY(0)';
                   }, i * 24);
               });
           });
       } function snapshotCurrentBarItemsFromDOM() {
           return Array.from(iconsBar.querySelectorAll('.skill-icon')).filter(el => el.dataset.weaponToggle !== '1').map(el => {
               const img = el.querySelector('img');
               const iconURL = img ? img.src : ;
               const subsRaw = el.dataset.subs || el.getAttribute('data-subs') || ;
               let subs = null;
               try {
                   subs = subsRaw ? JSON.parse(subsRaw) : null;
               } catch {
                   subs = null;
               } const subattrsRaw = el.dataset.subattrs || ;
               let flags = null;
               if (el.dataset.flags) {
                   try {
                       flags = JSON.parse(el.dataset.flags);
                   } catch (e) {
                   }
               } let weapon = null;
               if (el.dataset.weapon) {
                   try {
                       weapon = JSON.parse(el.dataset.weapon);
                   } catch (e) {
                   }
               } return {
                   name: el.dataset.nome || el.dataset.name || , index: el.dataset.index || , level: el.dataset.level || , desc: el.dataset.desc || , descPt: el.dataset.descPt || , descEn: el.dataset.descEn || , descEs: el.dataset.descEs || , descPl: el.dataset.descPl || , attrs: el.dataset.atr || el.dataset.attrs || , video: el.dataset.video || , iconURL, subs, subattrsStr: subattrsRaw, flags: flags, weapon: weapon
               };
           });
       } function ensureBackButton() {
           const rail = iconsBar.closest('.top-rail.skills');
           if (!rail) return null;
           let wrap = rail.parentElement;
           if (!wrap || !wrap.classList || !wrap.classList.contains('skills-rail-wrap')) {
               const parentNode = rail.parentNode;
               const newWrap = document.createElement('div');
               newWrap.className = 'skills-rail-wrap';
               parentNode.insertBefore(newWrap, rail);
               newWrap.appendChild(rail);
               wrap = newWrap;
           } let backWrap = wrap.querySelector('.skills-back-wrapper');
           if (!backWrap) {
               backWrap = document.createElement('div');
               backWrap.className = 'skills-back-wrapper';
               const btnInner = document.createElement('button');
               btnInner.className = 'skills-back';
               btnInner.type = 'button';
               btnInner.setAttribute('aria-label', 'Voltar');
               btnInner.innerHTML = '<svg class="back-chevron" width="100%" height="100%" viewBox="0 0 36 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" preserveAspectRatio="xMidYMid meet"><path d="M10 2L4 16L10 30" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/><path d="M20 2L14 16L20 30" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/><path d="M30 2L24 16L30 30" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
               backWrap.appendChild(btnInner);
               wrap.insertBefore(backWrap, rail);
               btnInner.addEventListener('click', () => {
                   if (!barStack.length) return;
                   const prev = barStack.pop();
                   renderBarFromItems(prev.items);
                   backWrap.style.display = barStack.length ? 'block' : 'none';
                   wrap.classList.toggle('has-sub-bar', barStack.length > 0);
                   if (!barStack.length) btnInner.classList.remove('peek');
               });
           } backWrap.style.display = barStack.length ? 'block' : 'none';
           wrap.classList.toggle('has-sub-bar', barStack.length > 0);
           const btnInner = backWrap.querySelector('.skills-back');
           return btnInner;
       } function renderBarFromItems(items) {
           const tip = document.querySelector('.skill-tooltip');
           if (tip) {
               tip.setAttribute('aria-hidden', 'true');
               tip.style.opacity = '0';
               tip.style.left = '-9999px';
               tip.style.top = '-9999px';
           } iconsBar.innerHTML = ;
           items.forEach((it, idx) => {
               const node = document.createElement('div');
               node.className = 'skill-icon';
               node.dataset.nome = it.name || ;
               if (it.index) node.dataset.index = it.index;
               if (it.level) node.dataset.level = it.level;
               if (it.desc) node.dataset.desc = it.desc;
               if (it.descPt) node.dataset.descPt = it.descPt;
               if (it.descEn) node.dataset.descEn = it.descEn;
               if (it.descEs) node.dataset.descEs = it.descEs;
               if (it.descPl) node.dataset.descPl = it.descPl;
               if (it.attrs) node.dataset.atr = it.attrs;
               if (it.video) node.dataset.video = it.video;
               if (it.subs) node.dataset.subs = JSON.stringify(it.subs);
               if (it.subattrsStr) node.dataset.subattrs = it.subattrsStr;
               if (it.flags) node.dataset.flags = JSON.stringify(it.flags);
               if (it.weapon) node.dataset.weapon = JSON.stringify(it.weapon);
               if (!it.index) node.dataset.nested = '1';
               const img = document.createElement('img');
               img.alt = ;
               img.src = it.iconURL || (it.icon ? filePathURL(it.icon) : );
               node.appendChild(img);
               iconsBar.appendChild(node);
           });
           animateIconsBarEntrance();
           wireClicksForCurrentBar();
           setupWeaponBarToggle(hasWeaponSkillAvailable);
           const b = ensureBackButton();
           if (b) b.classList.add('peek');
       } function pushSubBarFrom(subs, parentIconEl) {
           const tip = document.querySelector('.skill-tooltip');
           if (tip) {
               tip.setAttribute('aria-hidden', 'true');
               tip.style.opacity = '0';
               tip.style.left = '-9999px';
               tip.style.top = '-9999px';
           } const parentNameSnapshot = parentIconEl ? (parentIconEl.dataset.nome || parentIconEl.dataset.name || ) : ;
           const parentIndexSnapshot = parentIconEl ? (parentIconEl.dataset.index || ) : ;
           barStack.push({
               items: snapshotCurrentBarItemsFromDOM(), parentIcon: parentIconEl, parentName: parentNameSnapshot, parentIndex: parentIndexSnapshot
           });
           ensureBackButton();
           const langKey = getLangKey();
           let cacheKey = null;
           if (parentIconEl) {
               cacheKey = parentIconEl.dataset.subCacheKey || null;
               if (!cacheKey) {
                   if (parentIconEl.dataset.index) {
                       cacheKey = `idx:${parentIconEl.dataset.index}`;
                   } else {
                       const slug = slugify(parentIconEl.dataset.nome || parentIconEl.dataset.name || );
                       if (slug) cacheKey = `slug:${slug}`;
                   } if (cacheKey) parentIconEl.dataset.subCacheKey = cacheKey;
               }
           } if (cacheKey) {
               const cached = subBarTemplateCache.get(cacheKey);
               if (cached && cached.lang === langKey) {
                   iconsBar.innerHTML = ;
                   const clone = cached.template.cloneNode(true);
                   iconsBar.appendChild(clone);
                   animateIconsBarEntrance();
                   wireClicksForCurrentBar();
                   setupWeaponBarToggle(hasWeaponSkillAvailable);
                   const cachedBtn = ensureBackButton();
                   if (cachedBtn) cachedBtn.classList.add('peek');
                   return;
               }
           } const skillsRoot = document.getElementById('skills');
           const i18nMap = skillsRoot ? JSON.parse(skillsRoot.dataset.i18nAttrs || '{}') : {
           };
           const L = i18nMap[getLangKey()] || i18nMap.pt || {
               cooldown: 'Recarga', energy_gain: 'Ganho de energia', energy_cost: 'Custo de energia', power: 'Poder', power_pvp: 'Poder PvP', level: 'Nível'
           };
           const hydratedSubs = inheritSubskillTree(subs, mainSkillsMeta);
           const items = (hydratedSubs || []).filter(s => {
               // Filtra só se não tem nada útil
               const hasName = (s.name || s.n || ).trim() !== ;
               const hasIcon = (s.icon || ).trim() !==  && s.icon !== 'Nada.png';
               const hasRef = (s.refS || s.refM || ).toString().trim() !== ;
               return hasName || hasIcon || hasRef;
           }).map(s => {
               const name = (s.name || s.n || ).trim();
               const desc = chooseDescFrom(s).replace(/(.*?)/g, '$1');
               const attrsHTML = renderSubAttributesFromObj(s, L);
               return {
                   name, level: (s.level || ).toString().trim(), desc, descPt: (s.descPt || (s.desc_i18n && s.desc_i18n.pt) || ), descEn: (s.descEn || (s.desc_i18n && s.desc_i18n.en) || ), descEs: (s.descEs || (s.desc_i18n && s.desc_i18n.es) || ), descPl: (s.descPl || (s.desc_i18n && s.desc_i18n.pl) || ), attrs: , icon: (s.icon || 'Nada.png'), iconURL: filePathURL(s.icon || 'Nada.png'), video: s.video ? filePathURL(s.video) : , subs: Array.isArray(s.subs) ? s.subs : null, subattrs: s, flags: Array.isArray(s.flags) ? s.flags : null, back: (s.back === true || s.back === 'true' || s.back === 'yes' || s.back === '1') ? 'true' : null, weapon: s.weapon || null
               };
           });
           const fragment = document.createDocumentFragment();
           items.forEach((it, iIdx) => {
               const node = document.createElement('div');
               node.className = 'skill-icon';
               node.dataset.nested = '1';
               node.dataset.nome = it.name || ;
               node.dataset.parentIndex = parentIndexSnapshot;
               node.dataset.subName = it.name || ;
               const subSlug = slugify(it.name || );
               if (subSlug) node.dataset.slug = subSlug;
               if (it.level) node.dataset.level = it.level;
               if (it.desc) node.dataset.desc = it.desc;
               if (it.descPt) node.dataset.descPt = it.descPt;
               if (it.descEn) node.dataset.descEn = it.descEn;
               if (it.descEs) node.dataset.descEs = it.descEs;
               if (it.descPl) node.dataset.descPl = it.descPl;
               if (it.video) node.dataset.video = it.video;
               if (it.subs) node.dataset.subs = JSON.stringify(it.subs);
               if (it.subattrs) node.dataset.subattrs = JSON.stringify(it.subattrs);
               if (it.flags) node.dataset.flags = JSON.stringify(it.flags);
               if (it.back) node.dataset.back = it.back;
               if (it.weapon) {
                   try {
                       node.dataset.weapon = JSON.stringify(it.weapon);
                   } catch (e) {
                       console.error('[Skills] Erro ao serializar weapon de subskill', it.name, e);
                   }
               }
               const img = document.createElement('img');
               img.alt = ;
               img.src = it.iconURL;
               node.appendChild(img);
               fragment.appendChild(node);
           });
           const templateClone = fragment.cloneNode(true);
           iconsBar.innerHTML = ;
           iconsBar.appendChild(fragment);
           animateIconsBarEntrance();
           wireClicksForCurrentBar();
           setupWeaponBarToggle(hasWeaponSkillAvailable);
           const b2 = ensureBackButton();
           if (b2) b2.classList.add('peek');
           if (cacheKey) {
               subBarTemplateCache.set(cacheKey, {
                   template: templateClone, lang: langKey
               });
           }
       } window.addEventListener('gla:langChanged', () => {
           subBarTemplateCache.clear();
           const skillsRoot = document.getElementById('skills');
           const i18nMap = skillsRoot ? JSON.parse(skillsRoot.dataset.i18nAttrs || '{}') : {
           };
           const lang = getLangKey();
           Array.from(iconsBar.querySelectorAll('.skill-icon')).forEach(icon => {
               const pack = {
                   pt: icon.dataset.descPt || , en: icon.dataset.descEn || , es: icon.dataset.descEs || , pl: icon.dataset.descPl || 
               };
               const chosen = (pack[lang] || pack.pt || pack.en || pack.es || pack.pl || icon.dataset.desc || ).trim();
               if (chosen) icon.dataset.desc = chosen;
           });
           barStack.forEach(frame => {
               (frame.items || []).forEach(it => {
                   const pack = {
                       pt: it.descPt, en: it.descEn, es: it.descEs, pl: it.descPl
                   };
                   const chosen = (pack[lang] || pack.pt || pack.en || pack.es || pack.pl || it.desc || );
                   it.desc = chosen;
               });
           });
           if (descBox) {
               applyFlagTooltips(descBox);
           } const activeIcon = window.__lastActiveSkillIcon;
           if (activeIcon && activeIcon.dataset.weapon) {
               activateSkill(activeIcon, {
                   openSubs: false
               });
           }
       });
       wireClicksForCurrentBar();
       const b0 = ensureBackButton();
       if (b0) {
           b0.classList.add('peek');
           b0.style.alignSelf = 'stretch';
       } (function initSkillTooltip() {
           if (document.querySelector('.skill-tooltip')) return;
           const tip = document.createElement('div');
           tip.className = 'skill-tooltip';
           tip.setAttribute('role', 'tooltip');
           tip.setAttribute('aria-hidden', 'true');
           document.body.appendChild(tip);
           const lockUntilRef = {
               value: 0
           };
           function measureAndPos(el) {
               if (!el || tip.getAttribute('aria-hidden') === 'true') return;
               tip.style.left = '0px';
               tip.style.top = '0px';
               const rect = el.getBoundingClientRect();
               const tr = tip.getBoundingClientRect();
               let left = Math.round(rect.left + (rect.width - tr.width) / 2);
               left = Math.max(8, Math.min(left, window.innerWidth - tr.width - 8));
               const coarse = (window.matchMedia && matchMedia('(pointer: coarse)').matches) || (window.innerWidth <= 600);
               let top = coarse ? Math.round(rect.bottom + 10) : Math.round(rect.top - tr.height - 8);
               if (top < 8) top = Math.round(rect.bottom + 10);
               tip.style.left = left + 'px';
               tip.style.top = top + 'px';
           } function show(el, text) {
               tip.textContent = text || ;
               tip.setAttribute('aria-hidden', 'false');
               measureAndPos(el);
               tip.style.opacity = '1';
           } function hide() {
               tip.setAttribute('aria-hidden', 'true');
               tip.style.opacity = '0';
               tip.style.left = '-9999px';
               tip.style.top = '-9999px';
           } window.__globalSkillTooltip = {
               show, hide, measureAndPos, lockUntil: lockUntilRef
           };
           Array.from(document.querySelectorAll('.icon-bar .skill-icon')).forEach(icon => {
               if (icon.dataset.weaponToggle === '1' || icon.classList.contains('weapon-bar-toggle')) return;
               if (icon.dataset.tipwired) return;
               icon.dataset.tipwired = '1';
               const label = icon.dataset.nome || icon.dataset.name || icon.title || ;
               if (label && !icon.hasAttribute('aria-label')) icon.setAttribute('aria-label', label);
               if (icon.hasAttribute('title')) icon.removeAttribute('title');
               const img = icon.querySelector('img');
               if (img) {
                   const imgAlt = img.getAttribute('alt') || ;
                   const imgTitle = img.getAttribute('title') || ;
                   if (!label && (imgAlt || imgTitle)) icon.setAttribute('aria-label', imgAlt || imgTitle);
                   img.setAttribute('alt', );
                   if (img.hasAttribute('title')) img.removeAttribute('title');
               } icon.addEventListener('mouseenter', () => show(icon, label));
               icon.addEventListener('mousemove', () => {
                   if (performance.now() >= lockUntilRef.value) measureAndPos(icon);
               });
               icon.addEventListener('click', () => {
                   lockUntilRef.value = performance.now() + 240;
                   measureAndPos(icon);
               });
               icon.addEventListener('mouseleave', hide);
           });
           Array.from(document.querySelectorAll('.subskills-rail .subicon')).forEach(sub => {
               if (sub.dataset.tipwired) return;
               sub.dataset.tipwired = '1';
               const label = sub.getAttribute('title') || sub.getAttribute('aria-label') || ;
               if (label && !sub.hasAttribute('aria-label')) sub.setAttribute('aria-label', label);
               if (sub.hasAttribute('title')) sub.removeAttribute('title');
               sub.addEventListener('mouseenter', () => show(sub, label));
               sub.addEventListener('mousemove', () => {
                   if (performance.now() >= lockUntilRef.value) measureAndPos(sub);
               });
               sub.addEventListener('click', () => {
                   lockUntilRef.value = performance.now() + 240;
                   measureAndPos(sub);
               });
               sub.addEventListener('mouseleave', hide);
           });
           window.addEventListener('scroll', () => {
               const visible = document.querySelector('.skill-tooltip[aria-hidden="false"]');
               if (!visible) return;
               const target = document.querySelector('.subskills-rail .subicon:hover') || document.querySelector('.subskills-rail .subicon.active') || document.querySelector('.icon-bar .skill-icon:hover') || document.querySelector('.icon-bar .skill-icon.active');
               measureAndPos(target);
           }, true);
           window.addEventListener('resize', () => {
               const target = document.querySelector('.subskills-rail .subicon:hover') || document.querySelector('.subskills-rail .subicon.active') || document.querySelector('.icon-bar .skill-icon:hover') || document.querySelector('.icon-bar .skill-icon.active');
               measureAndPos(target);
           });
       })();
       (function initTabs() {
           const tabs = Array.from(document.querySelectorAll('.tab-btn'));
           if (!tabs.length) return;
           const contents = Array.from(document.querySelectorAll('.tab-content'));
           const characterBox = document.querySelector('.character-box');
           let wrapper = characterBox.querySelector('.tabs-height-wrapper');
           if (!wrapper) {
               wrapper = document.createElement('div');
               wrapper.className = 'tabs-height-wrapper';
               contents.forEach(c => {
                   wrapper.appendChild(c);
               });
               const tabsElement = characterBox.querySelector('.character-tabs');
               if (tabsElement && tabsElement.nextSibling) {
                   characterBox.insertBefore(wrapper, tabsElement.nextSibling);
               } else {
                   characterBox.appendChild(wrapper);
               }
           } async function smoothHeightTransition(fromTab, toTab) {
               if (!wrapper) return Promise.resolve();
               const scrollY = window.scrollY;
               const currentHeight = wrapper.getBoundingClientRect().height;
               await new Promise((resolve) => {
                   const videoContainers = toTab.querySelectorAll('.video-container');
                   const contentCard = toTab.querySelector('.content-card');
                   if (videoContainers.length === 0) {
                       requestAnimationFrame(() => {
                           requestAnimationFrame(() => {
                               requestAnimationFrame(() => resolve());
                           });
                       });
                       return;
                   } let lastHeight = 0;
                   let stableCount = 0;
                   const checksNeeded = 3;
                   let totalChecks = 0;
                   const maxChecks = 15;
                   function checkStability() {
                       totalChecks++;
                       const currentTabHeight = toTab.scrollHeight;
                       if (Math.abs(currentTabHeight - lastHeight) < 5) {
                           stableCount++;
                       } else {
                           stableCount = 0;
                       } lastHeight = currentTabHeight;
                       if (stableCount >= checksNeeded || totalChecks >= maxChecks) {
                           resolve();
                       } else {
                           setTimeout(checkStability, 50);
                       }
                   } setTimeout(checkStability, 50);
               });
               const nextHeight = toTab.getBoundingClientRect().height;
               const finalHeight = Math.max(nextHeight, 100);
               if (Math.abs(finalHeight - currentHeight) < 30) {
                   wrapper.style.height = ;
                   return Promise.resolve();
               } wrapper.style.overflow = 'hidden';
               wrapper.style.height = currentHeight + 'px';
               wrapper.offsetHeight;
               wrapper.style.transition = 'height 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
               requestAnimationFrame(() => {
                   wrapper.style.height = finalHeight + 'px';
               });
               return new Promise(resolve => {
                   setTimeout(() => {
                       wrapper.style.height = ;
                       wrapper.style.transition = ;
                       wrapper.style.overflow = ;
                       resolve();
                   }, 320);
               });
           } tabs.forEach(btn => {
               if (btn.dataset.wiredTab) return;
               btn.dataset.wiredTab = '1';
               btn.addEventListener('click', () => {
                   const target = btn.getAttribute('data-tab');
                   const currentActive = contents.find(c => c.classList.contains('active'));
                   const nextActive = contents.find(c => c.id === target);
                   if (currentActive === nextActive) return;
                   document.body.classList.add('transitioning-tabs');
                   if (currentActive) {
                       currentActive.style.opacity = '0';
                       currentActive.style.transform = 'translateY(-8px)';
                   } setTimeout(async () => {
                       contents.forEach(c => {
                           if (c !== nextActive) {
                               c.style.display = 'none';
                               c.classList.remove('active');
                           }
                       });
                       tabs.forEach(b => b.classList.toggle('active', b === btn));
                       if (nextActive) {
                           nextActive.classList.add('active');
                           nextActive.style.display = 'block';
                           nextActive.style.opacity = '0';
                           nextActive.style.visibility = 'hidden';
                           nextActive.offsetHeight;
                           try {
                               if (target === 'skills') {
                                   const tabEl = document.getElementById(target);
                                   if (tabEl) {
                                       const activeIcon = tabEl.querySelector('.icon-bar .skill-icon.active');
                                       const firstIcon = tabEl.querySelector('.icon-bar .skill-icon');
                                       const toClick = activeIcon || firstIcon;
                                       if (toClick) {
                                           const had = document.body.dataset.suppressSkillPlay;
                                           document.body.dataset.suppressSkillPlay = '1';
                                           toClick.click();
                                           if (had) document.body.dataset.suppressSkillPlay = had;
                                       }
                                   }
                               }
                           } catch (e) {
                           }
                       } if (currentActive && nextActive) {
                           await smoothHeightTransition(currentActive, nextActive);
                       } if (nextActive) {
                           nextActive.style.visibility = ;
                           nextActive.style.transform = 'translateY(12px)';
                           requestAnimationFrame(() => {
                               nextActive.style.opacity = '1';
                               nextActive.style.transform = 'translateY(0)';
                               setTimeout(() => {
                                   nextActive.style.opacity = ;
                                   nextActive.style.transform = ;
                                   document.body.classList.remove('transitioning-tabs');
                                   try {
                                       delete document.body.dataset.suppressSkillPlay;
                                   } catch {
                                   }
                               }, 300);
                           });
                       }
                   }, 120);
                   setTimeout(() => {
                       syncDescHeight();
                       if (target === 'skins') {
                           videosCache.forEach(v => {
                               try {
                                   v.pause();
                               } catch (e) {
                               } v.style.display = 'none';
                           });
                           if (videoBox) {
                               videoBox.querySelectorAll('video.skill-video').forEach(v => {
                                   try {
                                       v.pause();
                                   } catch (e) {
                                   } v.style.display = 'none';
                               });
                           } if (window.__subskills) window.__subskills.hideAll?.(videoBox);
                           if (videoBox && placeholder) {
                               placeholder.style.display = 'none';
                               placeholder.classList.add('fade-out');
                           }
                       } else {
                           const activeIcon = document.querySelector('.icon-bar .skill-icon.active');
                           if (activeIcon) activeIcon.click();
                       }
                   }, 450);
               });
           });
       })();
       (function initSkinsArrows() {
           const carousel = $('.skins-carousel');
           const wrapper = $('.skins-carousel-wrapper');
           const left = $('.skins-arrow.left');
           const right = $('.skins-arrow.right');
           if (!carousel || !left || !right || !wrapper) return;
           if (wrapper.dataset.wired) return;
           wrapper.dataset.wired = '1';
           const scrollAmt = () => Math.round(carousel.clientWidth * 0.6);
           function setState() {
               const max = carousel.scrollWidth - carousel.clientWidth;
               const x = carousel.scrollLeft;
               const hasLeft = x > 5, hasRight = x < max - 5;
               left.style.display = hasLeft ? 'inline-block' : 'none';
               right.style.display = hasRight ? 'inline-block' : 'none';
               wrapper.classList.toggle('has-left', hasLeft);
               wrapper.classList.toggle('has-right', hasRight);
               carousel.style.justifyContent = (!hasLeft && !hasRight) ? 'center' : ;
           } function go(dir) {
               const max = carousel.scrollWidth - carousel.clientWidth;
               const next = dir < 0 ? Math.max(0, carousel.scrollLeft - scrollAmt()) : Math.min(max, carousel.scrollLeft + scrollAmt());
               carousel.scrollTo({
                   left: next, behavior: 'smooth'
               });
           } left.addEventListener('click', () => go(-1));
           right.addEventListener('click', () => go(1));
           carousel.addEventListener('scroll', setState);
           new ResizeObserver(setState).observe(carousel);
           setState();
       })();
       function renderAttributes(str) {
           const skillsRoot = document.getElementById('skills');
           const i18nMap = skillsRoot ? JSON.parse(skillsRoot.dataset.i18nAttrs || '{}') : {
           };
           const langRaw = (document.documentElement.lang || skillsRoot?.dataset.i18nDefault || 'pt').toLowerCase();
           const langKey = i18nMap[langRaw] ? langRaw : (i18nMap[langRaw.split('-')[0]] ? langRaw.split('-')[0] : 'pt');
           const L = i18nMap[langKey] || i18nMap.pt || {
               cooldown: 'Recarga', energy_gain: 'Ganho de energia', energy_cost: 'Custo de energia', power: 'Poder', power_pvp: 'Poder PvP', level: 'Nível'
           };
           const vals = (str || ).split(',').map(v => v.trim());
           const pve = parseFloat(vals[0]);
           const pvp = parseFloat(vals[1]);
           const ene = parseFloat(vals[2]);
           const cd = parseFloat(vals[3]);
           const rows = [];
           if (!isNaN(cd)) rows.push([L.cooldown, cd]);
           if (!isNaN(ene) && ene !== 0) {
               const label = ene > 0 ? L.energy_gain : L.energy_cost;
               rows.push([label, Math.abs(ene)]);
           } if (!isNaN(pve)) rows.push([L.power, pve]);
           if (!isNaN(pvp)) rows.push([L.power_pvp, pvp]);
           if (!rows.length) return ;

const html = rows.map(([label, value]) => `

${label}${value}

`).join(); return `

${html}

`;

       } function syncDescHeight() {
       } window.addEventListener('resize', syncDescHeight);
       if (videoBox) new ResizeObserver(syncDescHeight).observe(videoBox);
       iconItems.forEach(el => {
           const wired = !!el.dataset._sync_wired;
           if (wired) return;
           el.dataset._sync_wired = '1';
           el.addEventListener('click', () => {
               Promise.resolve().then(syncDescHeight);
           });
       });
       if (iconsBar) addOnce(iconsBar, 'wheel', (e) => {
           if (e.deltaY) {
               e.preventDefault();
               iconsBar.scrollLeft += e.deltaY;
           }
       });
       wireClicksForCurrentBar();
       if (iconItems.length) {
           const first = iconItems[0];
           if (first) {
               activateSkill(first, {
                   openSubs: false
               });
           }
       } setTimeout(() => {
           Array.from(document.querySelectorAll('.skill-icon')).forEach(el => {
           });
           videosCache.forEach((v, idx) => {
               const src = v.querySelector('source') ? v.querySelector('source').src : v.src;
               v.addEventListener('error', (ev) => {
               });
               v.addEventListener('loadedmetadata', () => {
               });
           });
       }, 600);
   })();

</script>