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

De Wiki Gla
Ir para navegação Ir para pesquisar
m
Etiqueta: Reversão manual
m (new wptoggle 2)
Linha 249: Linha 249:
         });
         });


         // Função para aplicar o ícone global ao botão de toggle se existir
         // Função para obter o nome da arma
         function applyGlobalWeaponIcon() {
        function getWeaponName() {
             const toggleBtn = document.querySelector('.weapon-bar-toggle');
            let weaponName = 'Arma Especial';
             if (!toggleBtn) {
            try {
                console.log('[WeaponToggle] Botão não encontrado ainda');
                const firstWithWeapon = document.querySelector('.skill-icon[data-weapon]');
                return;
                if (firstWithWeapon) {
             }
                    const raw = firstWithWeapon.getAttribute('data-weapon');
                    const obj = JSON.parse(raw || '{}');
                    if (obj && obj.name) {
                        weaponName = String(obj.name).trim();
                    }
                }
            } catch (e) { }
            return weaponName;
        }
 
        // Função para criar o novo toggle abaixo do char-translator
         function createWeaponToggle() {
            // Remove toggle antigo se existir
             const oldToggle = document.querySelector('.weapon-bar-toggle');
             if (oldToggle) oldToggle.remove();
 
            const existingContainer = document.querySelector('.weapon-toggle-container');
            if (existingContainer) return existingContainer;
 
            const characterHeader = document.querySelector('.character-header');
             if (!characterHeader) return null;


             // Re-resolve o ícone caso tenha mudado
             // Resolve o ícone
             resolveCharacterWeaponIcon();
             resolveCharacterWeaponIcon();
            const weaponName = getWeaponName();


             // Se não tem ícone global, não faz nada (deixa o que já está no botão)
             // Cria o container do toggle
             if (!globalWeaponToggleIcon) {
            const container = document.createElement('div');
                console.log('[WeaponToggle] Nenhum weaponicon global encontrado');
            container.className = 'weapon-toggle-container';
                return;
             container.setAttribute('role', 'button');
             }
            container.setAttribute('aria-pressed', 'false');
            container.setAttribute('aria-label', weaponName);
 
            // Cria o sprite (círculo com imagem)
             const sprite = document.createElement('div');
            sprite.className = 'weapon-toggle-sprite';


             // Verifica se já tem o ícone aplicado corretamente
             if (globalWeaponToggleIcon) {
            const existingImg = toggleBtn.querySelector('img.weapon-toggle-icon');
                const img = document.createElement('img');
            if (existingImg && existingImg.src === globalWeaponToggleIcon) {
                img.src = globalWeaponToggleIcon;
                console.log('[WeaponToggle] Ícone já aplicado corretamente');
                img.alt = weaponName;
                 return;
                img.className = 'weapon-toggle-icon';
                img.onerror = function () {
                    console.error('[WeaponToggle] Erro ao carregar imagem:', globalWeaponToggleIcon);
                };
                img.onload = function () {
                    console.log('[WeaponToggle] Imagem carregada com sucesso:', globalWeaponToggleIcon);
                 };
                sprite.appendChild(img);
             }
             }


             console.log('[WeaponToggle] Aplicando ícone global:', globalWeaponToggleIcon);
             // Cria a barra com texto
            const bar = document.createElement('div');
            bar.className = 'weapon-toggle-bar';
            const nameSpan = document.createElement('span');
            nameSpan.className = 'weapon-toggle-name';
            nameSpan.setAttribute('data-lang', getCurrentLang());
            bar.appendChild(nameSpan);


             // Limpa todo o conteúdo do botão
             container.appendChild(sprite);
             toggleBtn.innerHTML = '';
             container.appendChild(bar);


             // Insere nova imagem (mesmo comportamento dos ícones de skills)
             // Adiciona evento de clique
            const img = document.createElement('img');
            container.addEventListener('click', () => {
            img.src = globalWeaponToggleIcon;
                let currentState = false;
            img.alt = toggleBtn.dataset.nome || 'Arma Especial';
                try {
            img.className = 'weapon-toggle-icon';
                    currentState = localStorage.getItem('glaWeaponEnabled') === '1';
             // Não aplica estilos inline - deixa o CSS fazer o trabalho
                } catch (e) { }
                const nextState = !currentState;
                if (nextState) {
                    if (typeof window.__glaWeaponShowPopup === 'function') {
                        window.__glaWeaponShowPopup();
                    }
                }
                if (typeof window.__applyWeaponState === 'function') {
                    window.__applyWeaponState(nextState);
                }
            });
 
             // Insere abaixo do char-translator
            characterHeader.appendChild(container);


             // Adiciona handler de erro para debug
             // Atualiza estado visual inicial
             img.onerror = function () {
             updateToggleVisualState();
                console.error('[WeaponToggle] Erro ao carregar imagem:', globalWeaponToggleIcon);
            };
            img.onload = function () {
                console.log('[WeaponToggle] Imagem carregada com sucesso:', globalWeaponToggleIcon);
            };


             toggleBtn.appendChild(img);
             return container;
         }
         }


         // Observa quando o botão de toggle é criado
         // Função para atualizar o estado visual do toggle
         function observeWeaponToggleButton() {
         function updateToggleVisualState() {
             // Tenta aplicar imediatamente se o botão já existe
             const container = document.querySelector('.weapon-toggle-container');
             if (document.querySelector('.weapon-bar-toggle')) {
             if (!container) return;
                 applyGlobalWeaponIcon();
 
            let isEnabled = false;
            try {
                isEnabled = localStorage.getItem('glaWeaponEnabled') === '1';
            } catch (e) { }
 
            if (isEnabled) {
                container.classList.add('weapon-active');
                container.setAttribute('aria-pressed', 'true');
            } else {
                container.classList.remove('weapon-active');
                 container.setAttribute('aria-pressed', 'false');
             }
             }


             // Tenta novamente após delays para garantir que o botão foi criado
             // Atualiza idioma do texto
             setTimeout(() => {
             const nameSpan = container.querySelector('.weapon-toggle-name');
                 applyGlobalWeaponIcon();
            if (nameSpan) {
             }, 100);
                 nameSpan.setAttribute('data-lang', getCurrentLang());
             }
        }


             setTimeout(() => {
        // Observa quando o char-translator é criado para posicionar o toggle
                 applyGlobalWeaponIcon();
        function observeCharacterHeader() {
             }, 500);
             const characterHeader = document.querySelector('.character-header');
            if (characterHeader) {
                 createWeaponToggle();
             } else {
                // Tenta novamente após um delay
                setTimeout(observeCharacterHeader, 100);
            }
        }


            // Observa mudanças no DOM para detectar quando o botão é criado
        // Observa mudanças no DOM para detectar quando o character-header é criado
        function observeDOMForHeader() {
             const observer = new MutationObserver((mutations) => {
             const observer = new MutationObserver((mutations) => {
                 mutations.forEach((mutation) => {
                 mutations.forEach((mutation) => {
                     mutation.addedNodes.forEach((node) => {
                     mutation.addedNodes.forEach((node) => {
                         if (node.nodeType === 1) {
                         if (node.nodeType === 1) {
                            // Verifica se o nó adicionado é o botão ou contém o botão
                             if (node.classList && node.classList.contains('character-header')) {
                             if (node.classList && node.classList.contains('weapon-bar-toggle')) {
                                 setTimeout(() => createWeaponToggle(), 10);
                                 setTimeout(() => applyGlobalWeaponIcon(), 10);
                             } else if (node.querySelector && node.querySelector('.character-header')) {
                             } else if (node.querySelector && node.querySelector('.weapon-bar-toggle')) {
                                 setTimeout(() => createWeaponToggle(), 10);
                                 setTimeout(() => applyGlobalWeaponIcon(), 10);
                             }
                             }
                         }
                         }
Linha 328: Linha 395:
             });
             });


             const iconBar = document.querySelector('.icon-bar');
             observer.observe(document.body, { childList: true, subtree: true });
            if (iconBar) {
                observer.observe(iconBar, { childList: true, subtree: true });
            }
         }
         }


Linha 337: Linha 401:
             // Resolve o ícone do character antes de tudo
             // Resolve o ícone do character antes de tudo
             resolveCharacterWeaponIcon();
             resolveCharacterWeaponIcon();
            // Observa criação do botão de toggle
            observeWeaponToggleButton();


             // Verificar se existe alguma skill ou subskill com arma
             // Verificar se existe alguma skill ou subskill com arma
Linha 374: Linha 435:
                     if (ind) ind.remove();
                     if (ind) ind.remove();
                 });
                 });
                 // Remover botão de toggle se existir
                 // Remover toggle se existir
                 const toggleBtn = document.querySelector('.weapon-bar-toggle');
                 const toggleContainer = document.querySelector('.weapon-toggle-container');
                 if (toggleBtn) toggleBtn.remove();
                 if (toggleContainer) toggleContainer.remove();
                 // Atualizar estado global para desligado
                 // Atualizar estado global para desligado
                 if (typeof window.__setGlobalWeaponEnabled === 'function') {
                 if (typeof window.__setGlobalWeaponEnabled === 'function') {
Linha 385: Linha 446:


             ensureModal();
             ensureModal();
            // Cria o novo toggle
            observeCharacterHeader();
            observeDOMForHeader();
            // Escuta mudanças no estado do weapon para atualizar visual
            window.addEventListener('gla:weaponToggled', () => {
                setTimeout(updateToggleVisualState, 50);
            });
            // Escuta mudanças de idioma
            window.addEventListener('gla:langChanged', () => {
                updateToggleVisualState();
            });


             // Estado inicial do toggle
             // Estado inicial do toggle
Linha 391: Linha 466:
                 if (localStorage.getItem('glaWeaponEnabled') === '1') init = true;
                 if (localStorage.getItem('glaWeaponEnabled') === '1') init = true;
             } catch (x) { }
             } catch (x) { }
             setTimeout(() => applyWeaponState(init), 150);
             setTimeout(() => {
                applyWeaponState(init);
                updateToggleVisualState();
            }, 150);
         };
         };


Linha 427: Linha 505:
         inset: 0;
         inset: 0;
         background: rgba(0, 0, 0, .65);
         background: rgba(0, 0, 0, .65);
        -webkit-backdrop-filter: blur(4px);
         backdrop-filter: blur(4px);
         backdrop-filter: blur(4px);
        -webkit-backdrop-filter: blur(4px);
         opacity: 0;
         opacity: 0;
         transition: opacity .15s ease;
         transition: opacity .15s ease;
Linha 612: Linha 690:
             width: 100%;
             width: 100%;
         }
         }
    }
    /* =========================== NOVO WEAPON TOGGLE =========================== */
    .weapon-toggle-container {
        position: absolute;
        top: 50px;
        /* Abaixo do char-translator */
        right: 8px;
        display: flex;
        align-items: center;
        z-index: 10;
        background: transparent;
        padding: 0;
        border-radius: 0;
        border: none;
        box-shadow: none;
        cursor: pointer;
        transition: transform .08s ease;
        overflow: visible;
        height: 44px;
        box-sizing: border-box;
    }
    .weapon-toggle-container:hover {
        transform: translateY(-1px);
    }
    .weapon-toggle-sprite {
        width: 44px;
        height: 44px;
        flex-shrink: 0;
        border-radius: 50%;
        overflow: visible;
        position: relative;
        background: rgb(40, 40, 48);
        border: 2px solid rgba(255, 255, 255, 0.15);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 2;
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        box-shadow: 0 4px 12px rgba(0, 0, 0, .4);
        transition: background 0.1s ease, border-color 0.1s ease, box-shadow 0.1s ease;
    }
    .weapon-toggle-sprite img {
        width: 50px;
        height: 50px;
        display: block;
        image-rendering: -webkit-optimize-contrast;
        image-rendering: pixelated;
        object-fit: contain;
    }
    .weapon-toggle-bar {
        background: rgb(40, 40, 48);
        padding: 5px 14px 5px 28px;
        border-radius: 0 7px 7px 0;
        border: 2px solid rgba(255, 255, 255, 0.15);
        border-left: none;
        display: flex;
        align-items: center;
        width: 180px;
        position: relative;
        overflow: hidden;
        margin: 0;
        margin-left: -22px;
        height: 34px;
        box-sizing: border-box;
        box-shadow: 0 4px 12px rgba(0, 0, 0, .4);
        transition: background 0.1s ease, border-color 0.1s ease;
    }
    .weapon-toggle-name {
        color: #fff;
        font-size: 14px;
        font-weight: 600;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        position: relative;
        z-index: 2;
        letter-spacing: 0.3px;
        display: inline-block;
    }
    /* Textos i18n - usando ::after para mostrar o texto baseado no data-lang e estado */
    .weapon-toggle-name::after {
        content: "Equipar Arma";
        /* Default PT */
    }
    .weapon-toggle-name[data-lang="pt"]::after {
        content: "Equipar Arma";
    }
    .weapon-toggle-name[data-lang="en"]::after {
        content: "Equip Weapon";
    }
    .weapon-toggle-name[data-lang="es"]::after {
        content: "Equipar Arma";
    }
    .weapon-toggle-name[data-lang="pl"]::after {
        content: "Wyposaż Broń";
    }
    /* Estado ATIVO (arma equipada) - muda o texto */
    .weapon-toggle-container.weapon-active .weapon-toggle-name::after {
        content: "Desequipar Arma";
        /* Default PT */
    }
    .weapon-toggle-container.weapon-active .weapon-toggle-name[data-lang="pt"]::after {
        content: "Desequipar Arma";
    }
    .weapon-toggle-container.weapon-active .weapon-toggle-name[data-lang="en"]::after {
        content: "Unequip Weapon";
    }
    .weapon-toggle-container.weapon-active .weapon-toggle-name[data-lang="es"]::after {
        content: "Desequipar Arma";
    }
    .weapon-toggle-container.weapon-active .weapon-toggle-name[data-lang="pl"]::after {
        content: "Zdjęć Broń";
    }
    /* Estado ativo - destaque vermelho */
    .weapon-toggle-container.weapon-active .weapon-toggle-sprite {
        background: rgb(200, 60, 40);
        border: 2px solid rgba(255, 255, 255, 0.15);
        box-shadow: 0 4px 12px rgba(0, 0, 0, .4);
    }
    .weapon-toggle-container.weapon-active .weapon-toggle-bar {
        background: linear-gradient(135deg, rgb(200, 60, 40), rgb(160, 45, 30));
        border-color: rgba(255, 87, 34, 0.3);
        border-left: none;
        border-radius: 0 7px 7px 0;
    }
    .weapon-toggle-container.weapon-active .weapon-toggle-name {
        color: #fff;
        text-shadow: 0 0 4px rgba(255, 87, 34, 0.5);
     }
     }
</style>
</style>

Edição das 09h13min de 22 de dezembro de 2025

<script>

   (() => {
       let modalListenersBound = false;
       // Variável global para o ícone do weapon toggle
       let globalWeaponToggleIcon = null;
       // Função helper para construir URL de arquivo (mesmo sistema usado em Character.Skills.html)
       function filePathURL(fileName) {
           if (!fileName) return ;
           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}`;
       }
       // Função para resolver o ícone do weapon toggle do character-box
       function resolveCharacterWeaponIcon() {
           const root = document.querySelector('.character-box');
           if (!root) return;
           const raw = root.dataset.weaponicon;
           if (!raw || raw.trim() ===  || raw === 'Nada.png') {
               globalWeaponToggleIcon = null;
               return;
           }
           globalWeaponToggleIcon = filePathURL(raw.trim());
           console.log('[WeaponToggle] Resolved weaponicon:', raw, '->', globalWeaponToggleIcon);
       }
       // Textos i18n para o popup
       const i18nTexts = {
           pt: {
               title: 'Visualização com Arma Especial',
               body1: 'Este modo ativa a visualização do personagem equipado com sua arma especial.',
               body2: 'Algumas habilidades são diferentes enquanto estão com a arma equipada, essas habilidades ficam destacadas com borda vermelha.',
               dontShow: 'Não mostrar novamente',
               ok: 'Entendi',
               weaponLink: 'Ver página da arma:'
           },
           en: {
               title: 'Special Weapon View',
               body1: 'This mode activates the view of the character equipped with their special weapon.',
               body2: 'Some abilities are different while equipped with the weapon, these abilities are highlighted with a red border.',
               dontShow: "Don't show again",
               ok: 'Got it',
               weaponLink: 'View weapon page:'
           },
           es: {
               title: 'Visualización con Arma Especial',
               body1: 'Este modo activa la visualización del personaje equipado con su arma especial.',
               body2: 'Algunas habilidades son diferentes mientras están con el arma equipada, estas habilidades quedan destacadas con borde rojo.',
               dontShow: 'No mostrar de nuevo',
               ok: 'Entendido',
               weaponLink: 'Ver página del arma:'
           },
           pl: {
               title: 'Widok z Bronią Specjalną',
               body1: 'Ten tryb aktywuje widok postaci wyposażonej w broń specjalną.',
               body2: 'Niektóre umiejętności różnią się podczas posiadania broni, te umiejętności są podświetlone czerwoną obwódką.',
               dontShow: 'Nie pokazuj ponownie',
               ok: 'Rozumiem',
               weaponLink: 'Zobacz stronę broni:'
           }
       };
       const getCurrentLang = () => {
           const html = document.documentElement.lang || 'pt-br';
           const norm = html.toLowerCase().split('-')[0];
           return i18nTexts[norm] ? norm : 'pt';
       };
       const bindModalEvents = () => {
           if (modalListenersBound) return;
           modalListenersBound = true;
           document.addEventListener('click', (ev) => {
               if (ev.target.closest('.weapon-modal-close') || ev.target.closest('.weapon-modal-btn')) {
                   const checkbox = document.getElementById('weapon-dont-show');
                   if (checkbox && checkbox.checked) {
                       try { localStorage.setItem('glaWeaponPopupDismissed', '1'); } catch (x) { }
                   }
                   hidePopup();
                   return;
               }
               if (ev.target.classList.contains('weapon-modal-overlay')) {
                   hidePopup();
               }
           });
       };
       const applyWeaponState = (enabled) => {
           if (typeof window.__setGlobalWeaponEnabled === 'function') {
               window.__setGlobalWeaponEnabled(enabled);
           }
           try {
               localStorage.setItem('glaWeaponEnabled', enabled ? '1' : '0');
           } catch (x) { }
           // Dispara evento para atualizar subskills
           window.dispatchEvent(new CustomEvent('gla:weaponToggled', { detail: { enabled } }));
           // SISTEMA UNIFICADO: Aplica toggle em skills E subskills
           // Skills principais e subskills usam data-weapon (padronizado)
           document.querySelectorAll('.skill-icon[data-weapon], .subicon[data-weapon]').forEach(el => {
               if (enabled) {
                   el.classList.add('has-weapon-available');
               } else {
                   el.classList.remove('has-weapon-available');
                   el.classList.remove('weapon-equipped');
                   el.style.removeProperty('--weapon-badge-url');
                   const ind = el.querySelector('.weapon-indicator');
                   if (ind) ind.remove();
               }
           });
           // Atualiza descrição da skill/subskill selecionada (se houver) para refletir estado da arma
           // Aguarda um pouco mais para garantir que o estado global foi sincronizado
           setTimeout(() => {
               // Atualiza skill principal se houver - força reativação completa incluindo vídeo
               const sel = document.querySelector('.skill-icon.active:not(.weapon-bar-toggle)');
               if (sel) {
                   // Força uma reativação completa da skill para garantir que vídeo seja atualizado
                   if (typeof window.__subskills !== 'undefined' && window.__subskills.hideAll) {
                       const videoBox = document.querySelector('.video-container') || document.querySelector('.skills-video-box');
                       if (videoBox) window.__subskills.hideAll(videoBox);
                   }
                   // Reativa a skill para atualizar vídeo, descrição e atributos
                   if (typeof window.__lastActiveSkillIcon !== 'undefined' && window.__lastActiveSkillIcon === sel) {
                       sel.dispatchEvent(new Event('click', { bubbles: true }));
                   } else {
                       sel.dispatchEvent(new Event('click', { bubbles: true }));
                   }
               }
               // Atualiza subskill ativa se houver - força reativação completa incluindo vídeo
               const activeSub = document.querySelector('.subicon.active');
               if (activeSub) {
                   activeSub.dispatchEvent(new Event('click', { bubbles: true }));
               }
           }, 100);
       };
       const updateModalTexts = (modal) => {
           const lang = getCurrentLang();
           const t = i18nTexts[lang];
           const title = modal.querySelector('.weapon-modal-header h3');
           if (title) title.textContent = t.title;
           const body = modal.querySelector('.weapon-modal-body');
           if (body) {
               const p1 = body.querySelector('p:first-child');
               const p2 = body.querySelector('p:nth-child(2)');
               if (p1) p1.innerHTML = t.body1;
               if (p2) p2.innerHTML = t.body2;
           }
           const checkbox = modal.querySelector('.weapon-modal-checkbox span');
           if (checkbox) checkbox.textContent = t.dontShow;
           const btn = modal.querySelector('.weapon-modal-btn');
           if (btn) btn.textContent = t.ok;
           // Atualiza link da arma se existir
           try {
               const firstWithWeapon = document.querySelector('.skill-icon[data-weapon]');
               if (firstWithWeapon) {
                   const raw = firstWithWeapon.getAttribute('data-weapon');
                   const obj = JSON.parse(raw || '{}');
                   const nm = (obj && obj.name) ? String(obj.name).trim() : ;
                   if (nm) {
                       const linkHost = (window.mw && mw.util && typeof mw.util.getUrl === 'function') ? mw.util.getUrl(nm) : ('/index.php?title=' + encodeURIComponent(nm));
                       const holder = modal.querySelector('.weapon-info-link');
                       if (holder) {
                           holder.style.display = 'block';
                           holder.innerHTML = `<a href="${linkHost}">${t.weaponLink} ${nm}</a>`;
                       }
                   }
               }
           } catch (_) { }
       };
       const ensureModal = () => {
           let modal = document.getElementById('weapon-info-modal');
           if (modal) {
               updateModalTexts(modal);
               return modal;
           }
           // Insere dentro da character-box para isolar completamente
           const container = document.querySelector('.character-box') || document.querySelector('#mw-content-text') || document.body;
           modal = document.createElement('div');
           modal.id = 'weapon-info-modal';
           modal.className = 'weapon-modal';
           modal.innerHTML = `

                   <button class="weapon-modal-close" type="button" aria-label="Fechar">×</button>

       `;
           container.appendChild(modal);
           updateModalTexts(modal);
           bindModalEvents();
           return modal;
       };
       const showPopup = () => {
           const modal = ensureModal();
           if (modal) {
               updateModalTexts(modal);
               // Força reflow antes de adicionar classe para garantir transição
               void modal.offsetHeight;
               modal.classList.add('show');
           }
       };
       const hidePopup = () => {
           const m = document.getElementById('weapon-info-modal');
           if (m) m.classList.remove('show');
       };
       window.__applyWeaponState = applyWeaponState;
       window.__glaWeaponShowPopup = showPopup;
       window.__glaWeaponHidePopup = hidePopup;
       try {
           window.dispatchEvent(new CustomEvent('weapon:ready', { detail: { applyWeaponState, showPopup, hidePopup } }));
       } catch (err) {
       }
       // Escuta mudanças de idioma
       window.addEventListener('gla:langChanged', () => {
           const modal = document.getElementById('weapon-info-modal');
           if (modal) updateModalTexts(modal);
       });
       // Função para obter o nome da arma
       function getWeaponName() {
           let weaponName = 'Arma Especial';
           try {
               const firstWithWeapon = document.querySelector('.skill-icon[data-weapon]');
               if (firstWithWeapon) {
                   const raw = firstWithWeapon.getAttribute('data-weapon');
                   const obj = JSON.parse(raw || '{}');
                   if (obj && obj.name) {
                       weaponName = String(obj.name).trim();
                   }
               }
           } catch (e) { }
           return weaponName;
       }
       // Função para criar o novo toggle abaixo do char-translator
       function createWeaponToggle() {
           // Remove toggle antigo se existir
           const oldToggle = document.querySelector('.weapon-bar-toggle');
           if (oldToggle) oldToggle.remove();
           const existingContainer = document.querySelector('.weapon-toggle-container');
           if (existingContainer) return existingContainer;
           const characterHeader = document.querySelector('.character-header');
           if (!characterHeader) return null;
           // Resolve o ícone
           resolveCharacterWeaponIcon();
           const weaponName = getWeaponName();
           // Cria o container do toggle
           const container = document.createElement('div');
           container.className = 'weapon-toggle-container';
           container.setAttribute('role', 'button');
           container.setAttribute('aria-pressed', 'false');
           container.setAttribute('aria-label', weaponName);
           // Cria o sprite (círculo com imagem)
           const sprite = document.createElement('div');
           sprite.className = 'weapon-toggle-sprite';
           if (globalWeaponToggleIcon) {
               const img = document.createElement('img');
               img.src = globalWeaponToggleIcon;
               img.alt = weaponName;
               img.className = 'weapon-toggle-icon';
               img.onerror = function () {
                   console.error('[WeaponToggle] Erro ao carregar imagem:', globalWeaponToggleIcon);
               };
               img.onload = function () {
                   console.log('[WeaponToggle] Imagem carregada com sucesso:', globalWeaponToggleIcon);
               };
               sprite.appendChild(img);
           }
           // Cria a barra com texto
           const bar = document.createElement('div');
           bar.className = 'weapon-toggle-bar';
           const nameSpan = document.createElement('span');
           nameSpan.className = 'weapon-toggle-name';
           nameSpan.setAttribute('data-lang', getCurrentLang());
           bar.appendChild(nameSpan);
           container.appendChild(sprite);
           container.appendChild(bar);
           // Adiciona evento de clique
           container.addEventListener('click', () => {
               let currentState = false;
               try {
                   currentState = localStorage.getItem('glaWeaponEnabled') === '1';
               } catch (e) { }
               const nextState = !currentState;
               if (nextState) {
                   if (typeof window.__glaWeaponShowPopup === 'function') {
                       window.__glaWeaponShowPopup();
                   }
               }
               if (typeof window.__applyWeaponState === 'function') {
                   window.__applyWeaponState(nextState);
               }
           });
           // Insere abaixo do char-translator
           characterHeader.appendChild(container);
           // Atualiza estado visual inicial
           updateToggleVisualState();
           return container;
       }
       // Função para atualizar o estado visual do toggle
       function updateToggleVisualState() {
           const container = document.querySelector('.weapon-toggle-container');
           if (!container) return;
           let isEnabled = false;
           try {
               isEnabled = localStorage.getItem('glaWeaponEnabled') === '1';
           } catch (e) { }
           if (isEnabled) {
               container.classList.add('weapon-active');
               container.setAttribute('aria-pressed', 'true');
           } else {
               container.classList.remove('weapon-active');
               container.setAttribute('aria-pressed', 'false');
           }
           // Atualiza idioma do texto
           const nameSpan = container.querySelector('.weapon-toggle-name');
           if (nameSpan) {
               nameSpan.setAttribute('data-lang', getCurrentLang());
           }
       }
       // Observa quando o char-translator é criado para posicionar o toggle
       function observeCharacterHeader() {
           const characterHeader = document.querySelector('.character-header');
           if (characterHeader) {
               createWeaponToggle();
           } else {
               // Tenta novamente após um delay
               setTimeout(observeCharacterHeader, 100);
           }
       }
       // Observa mudanças no DOM para detectar quando o character-header é criado
       function observeDOMForHeader() {
           const observer = new MutationObserver((mutations) => {
               mutations.forEach((mutation) => {
                   mutation.addedNodes.forEach((node) => {
                       if (node.nodeType === 1) {
                           if (node.classList && node.classList.contains('character-header')) {
                               setTimeout(() => createWeaponToggle(), 10);
                           } else if (node.querySelector && node.querySelector('.character-header')) {
                               setTimeout(() => createWeaponToggle(), 10);
                           }
                       }
                   });
               });
           });
           observer.observe(document.body, { childList: true, subtree: true });
       }
       const boot = () => {
           // Resolve o ícone do character antes de tudo
           resolveCharacterWeaponIcon();
           // Verificar se existe alguma skill ou subskill com arma
           function checkHasAnyWeapon() {
               // Verifica skills principais
               if (document.querySelectorAll('.skill-icon[data-weapon]').length > 0) {
                   return true;
               }
               // Verifica subskills
               const skillIcons = document.querySelectorAll('.skill-icon[data-subs]');
               for (const el of skillIcons) {
                   try {
                       const subs = JSON.parse(el.getAttribute('data-subs') || '[]');
                       if (Array.isArray(subs) && subs.some(s => s && s.weapon)) {
                           return true;
                       }
                   } catch (e) { }
               }
               return false;
           }
           const hasAnyWeapon = checkHasAnyWeapon();
           if (!hasAnyWeapon) {
               // Limpar estado visual para chars sem arma (previne cache entre páginas)
               const topRail = document.querySelector('.top-rail.skills');
               if (topRail) {
                   topRail.classList.remove('weapon-mode-on');
               }
               document.querySelectorAll('.skill-icon.has-weapon-available').forEach(el => {
                   el.classList.remove('has-weapon-available');
                   el.classList.remove('weapon-equipped');
                   el.style.removeProperty('--weapon-badge-url');
                   const ind = el.querySelector('.weapon-indicator');
                   if (ind) ind.remove();
               });
               // Remover toggle se existir
               const toggleContainer = document.querySelector('.weapon-toggle-container');
               if (toggleContainer) toggleContainer.remove();
               // Atualizar estado global para desligado
               if (typeof window.__setGlobalWeaponEnabled === 'function') {
                   window.__setGlobalWeaponEnabled(false);
               }
               return;
           }
           ensureModal();
           // Cria o novo toggle
           observeCharacterHeader();
           observeDOMForHeader();
           // Escuta mudanças no estado do weapon para atualizar visual
           window.addEventListener('gla:weaponToggled', () => {
               setTimeout(updateToggleVisualState, 50);
           });
           // Escuta mudanças de idioma
           window.addEventListener('gla:langChanged', () => {
               updateToggleVisualState();
           });
           // Estado inicial do toggle
           let init = false;
           try {
               if (localStorage.getItem('glaWeaponEnabled') === '1') init = true;
           } catch (x) { }
           setTimeout(() => {
               applyWeaponState(init);
               updateToggleVisualState();
           }, 150);
       };
       if (document.readyState === 'loading') {
           document.addEventListener('DOMContentLoaded', boot);
       } else {
           boot();
       }
   })();

</script> <style>

   /* Character-box precisa de position relative para conter o modal */
   .character-box {
       position: relative;
   }
   /* Modal posicionado dentro da character-box */
   .weapon-modal {
       position: absolute;
       inset: 0;
       z-index: 100;
       display: flex;
       align-items: center;
       justify-content: center;
       pointer-events: none;
   }
   .weapon-modal.show {
       pointer-events: all;
   }
   /* Overlay escurece apenas a character-box - aparece PRIMEIRO */
   .weapon-modal-overlay {
       position: absolute;
       inset: 0;
       background: rgba(0, 0, 0, .65);
       -webkit-backdrop-filter: blur(4px);
       backdrop-filter: blur(4px);
       opacity: 0;
       transition: opacity .15s ease;
   }
   .weapon-modal.show .weapon-modal-overlay {
       opacity: 1;
   }
   /* Conteúdo aparece DEPOIS do overlay */
   .weapon-modal-content {
       position: relative;
       z-index: 1;
       transform: scale(0.96);
       background: linear-gradient(145deg, #2d1a1a, #1e1212);
       border: 1px solid rgba(255, 100, 100, .2);
       border-radius: 14px;
       max-width: 420px;
       width: 90%;
       opacity: 0;
       transition: transform .18s ease .08s, opacity .15s ease .08s;
       overflow: hidden;
   }
   .weapon-modal.show .weapon-modal-content {
       transform: scale(1);
       opacity: 1;
   }
   .weapon-modal-header {
       display: flex;
       align-items: center;
       justify-content: space-between;
       padding: 16px 20px;
       border-bottom: 1px solid rgba(255, 100, 100, .12);
       background: linear-gradient(90deg, rgba(255, 80, 80, .06), transparent);
   }
   .weapon-modal-header h3 {
       margin: 0;
       font-size: 16px;
       font-weight: 600;
       color: #fff;
   }
   .weapon-modal-close {
       background: transparent;
       border: 1px solid rgba(255, 255, 255, .1);
       color: rgba(255, 255, 255, .5);
       font-size: 18px;
       font-family: Arial, sans-serif;
       line-height: 1;
       cursor: pointer;
       padding: 0;
       width: 28px;
       height: 28px;
       display: inline-flex;
       align-items: center;
       justify-content: center;
       text-align: center;
       border-radius: 6px;
       transition: background .15s, color .15s, border-color .15s;
   }
   .weapon-modal-close:hover {
       background: rgba(255, 80, 80, .15);
       border-color: rgba(255, 80, 80, .3);
       color: #FF7043;
   }
   .weapon-modal-body {
       padding: 20px;
       color: rgba(255, 255, 255, .85);
       line-height: 1.65;
       font-size: 14px;
   }
   .weapon-modal-body p {
       margin: 0 0 12px;
       display: block !important;
   }
   .weapon-modal-body p:last-child,
   .weapon-modal-body p.weapon-info-link {
       margin: 0;
   }
   .weapon-modal-body p.weapon-info-link:empty {
       display: none !important;
   }
   .weapon-modal-body strong {
       color: #FF7043;
       font-weight: 600;
   }
   .weapon-modal-body .weapon-info-link a {
       color: #FF7043;
       text-decoration: none;
       font-weight: 600;
   }
   .weapon-modal-body .weapon-info-link a:hover {
       text-decoration: underline;
   }
   .weapon-modal-footer {
       display: flex;
       align-items: center;
       justify-content: space-between;
       padding: 14px 20px;
       border-top: 1px solid rgba(255, 100, 100, .1);
       background: rgba(0, 0, 0, .1);
       gap: 12px;
   }
   .weapon-modal-checkbox {
       display: inline-flex;
       align-items: center;
       gap: 6px;
       font-size: 12px;
       color: rgba(255, 255, 255, .5);
       cursor: pointer;
       transition: color .15s;
   }
   .weapon-modal-checkbox:hover {
       color: rgba(255, 255, 255, .75);
   }
   .weapon-modal-checkbox input[type="checkbox"] {
       accent-color: #FF5722;
       margin: 0;
       flex-shrink: 0;
   }
   .weapon-modal-checkbox span {
       line-height: 1;
   }
   .weapon-modal-btn {
       background: #BF360C;
       border: none;
       color: #fff;
       padding: 10px 24px;
       border-radius: 6px;
       font-weight: 600;
       font-size: 13px;
       line-height: 1;
       cursor: pointer;
       transition: background .15s;
       display: inline-flex;
       align-items: center;
       justify-content: center;
   }
   .weapon-modal-btn:hover {
       background: #D84315;
   }
   .weapon-modal-btn:active {
       background: #A52714;
   }
   @media (max-width: 600px) {
       .weapon-modal-content {
           width: 92%;
           max-width: none;
       }
       .weapon-modal-header,
       .weapon-modal-body,
       .weapon-modal-footer {
           padding: 14px 16px;
       }
       .weapon-modal-footer {
           flex-direction: column;
           gap: 12px;
       }
       .weapon-modal-btn {
           width: 100%;
       }
   }
   /* =========================== NOVO WEAPON TOGGLE =========================== */
   .weapon-toggle-container {
       position: absolute;
       top: 50px;
       /* Abaixo do char-translator */
       right: 8px;
       display: flex;
       align-items: center;
       z-index: 10;
       background: transparent;
       padding: 0;
       border-radius: 0;
       border: none;
       box-shadow: none;
       cursor: pointer;
       transition: transform .08s ease;
       overflow: visible;
       height: 44px;
       box-sizing: border-box;
   }
   .weapon-toggle-container:hover {
       transform: translateY(-1px);
   }
   .weapon-toggle-sprite {
       width: 44px;
       height: 44px;
       flex-shrink: 0;
       border-radius: 50%;
       overflow: visible;
       position: relative;
       background: rgb(40, 40, 48);
       border: 2px solid rgba(255, 255, 255, 0.15);
       display: flex;
       align-items: center;
       justify-content: center;
       z-index: 2;
       margin: 0;
       padding: 0;
       box-sizing: border-box;
       box-shadow: 0 4px 12px rgba(0, 0, 0, .4);
       transition: background 0.1s ease, border-color 0.1s ease, box-shadow 0.1s ease;
   }
   .weapon-toggle-sprite img {
       width: 50px;
       height: 50px;
       display: block;
       image-rendering: -webkit-optimize-contrast;
       image-rendering: pixelated;
       object-fit: contain;
   }
   .weapon-toggle-bar {
       background: rgb(40, 40, 48);
       padding: 5px 14px 5px 28px;
       border-radius: 0 7px 7px 0;
       border: 2px solid rgba(255, 255, 255, 0.15);
       border-left: none;
       display: flex;
       align-items: center;
       width: 180px;
       position: relative;
       overflow: hidden;
       margin: 0;
       margin-left: -22px;
       height: 34px;
       box-sizing: border-box;
       box-shadow: 0 4px 12px rgba(0, 0, 0, .4);
       transition: background 0.1s ease, border-color 0.1s ease;
   }
   .weapon-toggle-name {
       color: #fff;
       font-size: 14px;
       font-weight: 600;
       white-space: nowrap;
       text-overflow: ellipsis;
       overflow: hidden;
       position: relative;
       z-index: 2;
       letter-spacing: 0.3px;
       display: inline-block;
   }
   /* Textos i18n - usando ::after para mostrar o texto baseado no data-lang e estado */
   .weapon-toggle-name::after {
       content: "Equipar Arma";
       /* Default PT */
   }
   .weapon-toggle-name[data-lang="pt"]::after {
       content: "Equipar Arma";
   }
   .weapon-toggle-name[data-lang="en"]::after {
       content: "Equip Weapon";
   }
   .weapon-toggle-name[data-lang="es"]::after {
       content: "Equipar Arma";
   }
   .weapon-toggle-name[data-lang="pl"]::after {
       content: "Wyposaż Broń";
   }
   /* Estado ATIVO (arma equipada) - muda o texto */
   .weapon-toggle-container.weapon-active .weapon-toggle-name::after {
       content: "Desequipar Arma";
       /* Default PT */
   }
   .weapon-toggle-container.weapon-active .weapon-toggle-name[data-lang="pt"]::after {
       content: "Desequipar Arma";
   }
   .weapon-toggle-container.weapon-active .weapon-toggle-name[data-lang="en"]::after {
       content: "Unequip Weapon";
   }
   .weapon-toggle-container.weapon-active .weapon-toggle-name[data-lang="es"]::after {
       content: "Desequipar Arma";
   }
   .weapon-toggle-container.weapon-active .weapon-toggle-name[data-lang="pl"]::after {
       content: "Zdjęć Broń";
   }
   /* Estado ativo - destaque vermelho */
   .weapon-toggle-container.weapon-active .weapon-toggle-sprite {
       background: rgb(200, 60, 40);
       border: 2px solid rgba(255, 255, 255, 0.15);
       box-shadow: 0 4px 12px rgba(0, 0, 0, .4);
   }
   .weapon-toggle-container.weapon-active .weapon-toggle-bar {
       background: linear-gradient(135deg, rgb(200, 60, 40), rgb(160, 45, 30));
       border-color: rgba(255, 87, 34, 0.3);
       border-left: none;
       border-radius: 0 7px 7px 0;
   }
   .weapon-toggle-container.weapon-active .weapon-toggle-name {
       color: #fff;
       text-shadow: 0 0 4px rgba(255, 87, 34, 0.5);
   }

</style>