Difference between revisions of "MediaWiki:Common.css"

From XilePK - Ragnarok Online Server
Jump to navigation Jump to search
Line 1: Line 1:
/* CSS placed here will be applied to all skins */
+
/* Auto-expand sections when clicking anchored links */
/* body.page-Main_Page h1.firstHeading { display:none; } */
+
$(function() {
/* { font-family: courier new } */
+
  // Função principal para executar quando a página terminar de carregar
 +
  function initializeAnchorExpansion() {
 +
    // Se existir um hash na URL quando a página carrega
 +
    if (window.location.hash) {
 +
      var hash = window.location.hash;
 +
      console.log("Página carregada com hash: " + hash);
 +
      expandSectionForAnchor(hash);
 +
    }
 +
   
 +
    // Lidar com cliques em links âncora dentro da página
 +
    $(document).on('click', 'a[href^="#"]', function(event) {
 +
      var hash = $(this).attr('href');
 +
      console.log("Clique em link interno: " + hash);
 +
      expandSectionForAnchor(hash);
 +
    });
 +
  }
 +
 
 +
  // Função para expandir seções contendo uma âncora específica
 +
  function expandSectionForAnchor(hash) {
 +
    // Remover qualquer caractere # do início do hash se existir
 +
    if (hash.startsWith('#')) {
 +
      hash = hash.substring(1);
 +
    }
 +
   
 +
    console.log("Procurando elemento com ID: " + hash);
 +
   
 +
    // Tentar encontrar o elemento com o ID especificado
 +
    var targetElement = $('#' + hash);
 +
    if (targetElement.length) {
 +
      console.log("Elemento encontrado!");
 +
     
 +
      // Encontrar todas as seções colapsáveis que contêm o elemento
 +
      var collapsibleSections = targetElement.parents('.mw-collapsible.mw-collapsed');
 +
      console.log("Seções colapsáveis encontradas: " + collapsibleSections.length);
 +
     
 +
      // Se o elemento estiver dentro de seções colapsáveis
 +
      if (collapsibleSections.length > 0) {
 +
        // Expandir cada seção de fora para dentro
 +
        collapsibleSections.each(function() {
 +
          var $section = $(this);
 +
          console.log("Expandindo seção");
 +
          $section.removeClass('mw-collapsed');
 +
         
 +
          // Clicar no botão de expansão ou mudar diretamente a classe
 +
          var $toggle = $section.find('.mw-collapsible-toggle').first();
 +
          if ($toggle.length) {
 +
            $toggle.click();
 +
          } else {
 +
            // Tentar forçar a expansão manipulando classes diretamente
 +
            $section.find('.mw-collapsible-content').show();
 +
          }
 +
        });
 +
       
 +
        // Também verificar se o próprio elemento está em um colapsível
 +
        var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
 +
        if (directCollapsible.length) {
 +
          console.log("Expandindo o contêiner direto");
 +
          directCollapsible.removeClass('mw-collapsed');
 +
          var $toggle = directCollapsible.find('.mw-collapsible-toggle').first();
 +
          if ($toggle.length) {
 +
            $toggle.click();
 +
          } else {
 +
            directCollapsible.find('.mw-collapsible-content').show();
 +
          }
 +
        }
 +
      }
 +
     
 +
      // Rolar até o elemento imediatamente
 +
      console.log("Rolando até o elemento");
 +
      $('html, body').animate({
 +
        scrollTop: targetElement.offset().top - 100
 +
      }, 200);
 +
    } else {
 +
      console.log("Elemento com ID '" + hash + "' não encontrado");
 +
    }
 +
  }
  
/* Estilo para os elementos clicáveis */
+
  // Inicializar na carga da página
.warp-copy {
+
  initializeAnchorExpansion();
    color: #0000FF; /* Cor original dos links */
+
 
    cursor: pointer;
+
  // Também adicionar um observador para o evento mw.hook que é disparado quando o conteúdo é atualizado
     text-decoration: underline; /* Usa sublinhado normal como links padrão */
+
  if (typeof mw !== 'undefined' && mw.hook) {
    position: relative;
+
     mw.hook('wikipage.content').add(function() {
    display: inline-block;
+
      console.log("Conteúdo da Wiki atualizado, reinicializando manipuladores de âncora");
    border-bottom: none;
+
      initializeAnchorExpansion();
    /* Removido o sublinhado pontilhado para manter aparência original */
+
     
    font-family: inherit; /* Mantém a fonte igual à do texto ao redor */
+
      // Se houver um hash, tentar expandir após o conteúdo ter sido carregado
     font-weight: inherit; /* Mantém o peso da fonte igual ao texto ao redor */
+
      if (window.location.hash) {
}
+
        expandSectionForAnchor(window.location.hash);
 +
      }
 +
     });
 +
  }
 +
});
  
/* Tooltip personalizado */
+
/* JavaScript melhorado para funcionalidade de cópia */
.warp-copy::after {
+
$(document).ready(function() {
     content: "Clique para Copiar";
+
     // Adicionar CSS personalizado inline para forçar os tooltips
     position: absolute;
+
     $('<style>')
    bottom: calc(100% + 5px);
+
        .text(`
    left: 50%;
+
            .warp-copy:hover::after,
    transform: translateX(-50%);
+
            .warp-copy:hover::before {
    background-color: #333;
+
                opacity: 1 !important;
    color: white;
+
                visibility: visible !important;
    padding: 3px 8px;
+
                display: block !important;
    border-radius: 3px;
+
            }
    font-size: 12px;
+
            .warp-copy.copied::after {
    white-space: nowrap;
+
                content: "Copiado!" !important;
    opacity: 0;
+
                background-color: #4CAF50 !important;
    visibility: hidden;
+
                display: block !important;
    transition: opacity 0.15s, visibility 0.15s; /* Transição mais rápida */
+
            }
    pointer-events: none;
+
        `)
    z-index: 1000;
+
        .appendTo('head');
    font-family: Arial, sans-serif; /* Fonte padrão para o tooltip */
+
});
    font-weight: normal;
 
}
 
  
/* Seta do tooltip */
+
mw.hook('wikipage.content').add(function ($content) {
.warp-copy::before {
+
    // Função para inicializar todos os elementos .warp-copy
    content: "";
+
    function initWarpCopy() {
    position: absolute;
+
        console.log("Inicializando elementos .warp-copy");
    bottom: 100%;
+
       
    left: 50%;
+
        // Remove manipuladores de eventos anteriores para evitar duplicações
    transform: translateX(-50%);
+
        $content.find('.warp-copy').off('click');
    border-width: 4px;
+
       
    border-style: solid;
+
        // Adiciona o manipulador de clique
    border-color: #333 transparent transparent transparent;
+
        $content.find('.warp-copy').on('click', function (event) {
    opacity: 0;
+
            event.preventDefault();
    visibility: hidden;
+
            event.stopPropagation();
    transition: opacity 0.15s, visibility 0.15s; /* Transição mais rápida */
+
           
    pointer-events: none;
+
            var $this = $(this);
    z-index: 1000;
+
            var textToCopy = $this.attr('data-copy');
}
+
           
 
+
            if (!textToCopy) {
/* Mostrar tooltip ao passar o mouse */
+
                console.warn("Elemento .warp-copy sem atributo data-copy encontrado");
.warp-copy:hover::after,
+
                return;
.warp-copy:hover::before {
+
            }
    opacity: 1;
+
           
    visibility: visible;
+
            console.log("Copiando texto: " + textToCopy);
}
+
           
 
+
            // Usa a API Clipboard moderna quando disponível
/* Estilo adicional para feedback de cópia */
+
            if (navigator.clipboard && navigator.clipboard.writeText) {
.warp-copy.copied::after {
+
                navigator.clipboard.writeText(textToCopy)
    content: "Copiado!";
+
                    .then(function() {
    background-color: #4CAF50; /* Verde para indicar sucesso */
+
                        console.log('Texto copiado com sucesso usando Clipboard API');
}
+
                        showCopiedFeedback($this);
 
+
                    })
/* Opcional: um pequeno efeito visual quando clicado */
+
                    .catch(function(err) {
.warp-copy:active {
+
                        console.error('Falha ao copiar texto: ', err);
    opacity: 0.7;
+
                        // Tenta o método de fallback
}
+
                        fallbackCopyText(textToCopy, $this);
 
+
                    });
/* Mantém o estilo padrão dos links */
+
            } else {
a {
+
                // Método de fallback para navegadores que não suportam a API Clipboard
    /* Não alteramos o estilo padrão dos links */
+
                fallbackCopyText(textToCopy, $this);
    text-underline-offset: 0px;
+
            }
}
+
        });
 
+
     }
.external {
+
      
    background: none !important;
+
     // Função de fallback para copiar texto
    padding-right: 0 !important;
+
     function fallbackCopyText(text, $element) {
}
+
        // Cria um elemento de texto temporário
 
+
        var tempInput = document.createElement('textarea');
/* Tabelas */
+
        tempInput.value = text;
.tile-row {
+
        tempInput.style.position = 'fixed';
    display: flex;
+
        tempInput.style.opacity = '0';
    flex-flow: row wrap;
+
        document.body.appendChild(tempInput);
    margin-bottom: 1em;
+
       
}
+
        // Seleciona e copia
 
+
        tempInput.select();
.tile-halves {
+
        tempInput.setSelectionRange(0, 99999); // Para dispositivos móveis
    display: flex;
+
       
     flex-flow: row wrap;
+
        try {
     border: 1px solid #e4eaee;
+
            var successful = document.execCommand('copy');
     background: #ffffff;
+
            if (successful) {
     box-shadow: 0 0.25rem 0.35rem -0.25rem rgba(0, 0, 0, 0.1);
+
                console.log('Texto copiado com sucesso usando execCommand');
}
+
                showCopiedFeedback($element);
 
+
            } else {
.tile-halves h2 {
+
                console.error('Falha ao copiar texto com execCommand');
    font-size: 1.4em;
+
            }
    font-weight: bold;
+
        } catch (err) {
    border: none;
+
            console.error('Erro ao copiar texto: ', err);
    margin: 0 0 0.4em;
+
        }
}
+
       
 
+
        // Remove o elemento temporário
.tile-halves .byline + h2 {
+
        document.body.removeChild(tempInput);
    margin-top: -0.5em;
+
     }
}
+
      
 
+
     // Função para mostrar feedback visual de cópia
.tile-top {
+
     function showCopiedFeedback($element) {
    width: 100%;
+
        // Adiciona classe para feedback visual
    padding: 1.3rem 1.5rem 0.6rem;
+
        $element.addClass('copied');
}
+
       
 
+
        // Remove a classe após um breve período
.tile-top.tile-image {
+
        setTimeout(function() {
    display: flex;
+
            $element.removeClass('copied');
    align-items: center;
+
        }, 1500);
    justify-content: center;
+
       
    background-color: #949eaa;
+
        // Opcional: mostrar um popup de notificação
    overflow: visible;
+
        $('<div class="copy-notification" style="position:fixed;bottom:20px;right:20px;background:#4CAF50;color:white;padding:10px;border-radius:5px;z-index:9999;">Copiado: ' + $element.attr('data-copy') + '</div>')
    padding: 0;
+
            .appendTo('body')
    height: auto;
+
            .delay(1500)
    width: 100%;
+
            .fadeOut(300, function() { $(this).remove(); });
    box-sizing: border-box;
+
     }
}
+
      
 
+
     // Script para imagens dos NPCs
.tile-top.tile-image a {
+
     function initNPCImageCopy() {
    width: 100%;
+
        $content.find('.contents-equipment .tile-top.tile-image a').each(function() {
     height: 100%;
+
            var $link = $(this);
     display: flex;
+
            var linkHref = $link.attr('href') || '';
     justify-content: center;
+
           
     align-items: center;
+
            // Extrai o ID do NPC do link
}
+
            var npcId = linkHref.startsWith('#') ? linkHref.substring(1) : linkHref;
 
+
           
.tile-top.tile-image img {
+
            if (npcId) {
    display: block;
+
                $link.off('mousedown').on('mousedown', function(e) {
    width: auto;
+
                    // Texto a ser copiado
    height: auto;
+
                    var textToCopy = "@warp " + npcId;
    margin: 0;
+
                   
    transition: 0.4s ease-out;
+
                    // Tenta usar a API Clipboard moderna
}
+
                    if (navigator.clipboard && navigator.clipboard.writeText) {
 
+
                        navigator.clipboard.writeText(textToCopy)
.tile-bottom {
+
                            .then(function() {
    background: #ffffff;
+
                                console.log('Comando @warp copiado com sucesso');
    border-top: 1px solid #e4eaee;
+
                                showCopiedNotification(textToCopy);
    width: 100%;
+
                            })
    padding: 1rem 1.5rem 0.6rem;
+
                            .catch(function(err) {
}
+
                                console.error('Falha ao copiar comando @warp: ', err);
 
+
                                // Usa o método de fallback
.tile-bottom.link-button {
+
                                fallbackCopyText(textToCopy, $link);
    align-self: center;
+
                            });
    padding: 0;
+
                    } else {
    width: auto;
+
                        // Método de fallback
    margin: 0 auto;
+
                        fallbackCopyNPCCommand(textToCopy);
    max-width: fit-content;
+
                    }
}
+
                   
 
+
                    // Permite que o evento continue
.tile-bottom.link-button a {
+
                    return true;
    display: block;
+
                });
    text-align: center;
+
            }
    padding: 0.75em 0.6em 0.8em;
+
        });
    text-decoration: none;
+
     }
}
+
      
 
+
     // Função de fallback para copiar comando de NPC
.mainpage-contents .tile-halves {
+
    function fallbackCopyNPCCommand(text) {
     display: inline-block;
+
        var tempInput = document.createElement('textarea');
     flex: 0 0 auto;
+
        tempInput.value = text;
     margin-right: 0.9rem;
+
        tempInput.style.position = 'fixed';
     width: auto;
+
        tempInput.style.opacity = '0';
    max-width: max-content;
+
        document.body.appendChild(tempInput);
}
+
       
 
+
        tempInput.select();
.mainpage-contents .tile-halves:hover .tile-top img {
+
        tempInput.setSelectionRange(0, 99999); // Para dispositivos móveis
    transform: scale(1.04);
+
       
}
+
        try {
 
+
            document.execCommand('copy');
.mainpage-contents .tile-halves:last-child {
+
            showCopiedNotification(text);
    margin-right: 0;
+
        } catch (err) {
}
+
            console.error('Erro ao copiar comando @warp: ', err);
 
+
        }
.mainpage-contents .tile-top {
+
       
    height: auto;
+
        document.body.removeChild(tempInput);
    min-height: auto;
+
     }
    position: relative;
+
   
}
+
    // Função para mostrar notificação de cópia
 
+
    function showCopiedNotification(text) {
.mainpage-contents .tile-top h2 a {
+
        $('<div class="copy-notification" style="position:fixed;bottom:20px;right:20px;background:#4CAF50;color:white;padding:10px;border-radius:5px;z-index:9999;">Copiado: ' + text + '</div>')
    display: block;
+
            .appendTo('body')
    text-align: center;
+
            .delay(1500)
    text-decoration: none;
+
            .fadeOut(300, function() { $(this).remove(); });
    line-height: 4.5rem;
+
     }
    padding-left: 0.45rem;
+
      
}
+
     // Inicializa todas as funções
 
+
     initWarpCopy();
.mainpage-contents h2 {
+
     initNPCImageCopy();
    margin: 0;
+
   
    padding: 0;
+
    // Forçar a atualização dos tooltips (hack)
}
+
    setTimeout(function() {
 
+
        $content.find('.warp-copy').each(function() {
.tile-bottom.link-button h2 {
+
            var $this = $(this);
    width: max-content;
+
            $this.attr('title', 'Clique para Copiar');
    margin: 0 auto;
+
        });
    padding: 0;
+
    }, 500);
    white-space: nowrap;
+
   
}
+
    // Observador para alterações no DOM
 
+
    var observer = new MutationObserver(function(mutations) {
/* Estilo para o subtítulo do NPC */
+
        var needsReinit = false;
.npc-subtitle {
+
       
    font-size: 0.8em;
+
        mutations.forEach(function(mutation) {
    color: #666;
+
            if (mutation.addedNodes && mutation.addedNodes.length > 0) {
    margin-top: -5px;
+
                needsReinit = true;
    text-align: center;
+
            }
    font-style: italic;
+
        });
    line-height: 1.2;
+
       
}
+
        if (needsReinit) {
 
+
            initWarpCopy();
/* Ajustes para garantir que os NPCs fiquem lado a lado corretamente */
+
            initNPCImageCopy();
.mainpage-contents.tile-row {
+
        }
    display: flex;
+
     });
     flex-flow: row wrap;
+
      
     gap: 15px;
+
     // Configura o observador
     justify-content: flex-start;
+
     observer.observe($content[0], { childList: true, subtree: true });
}
+
});
 
 
/* Cada NPC - ajuste a largura conforme necessário */
 
.mainpage-contents .contents-equipment.tile-halves {
 
    margin-right: 0;
 
    flex: 0 0 auto;
 
    min-width: 150px;
 
    max-width: 200px;
 
}
 
 
 
/* Estilo específico para os títulos dos NPCs */
 
.tile-bottom.link-button h2 .warp-copy {
 
    position: relative !important;
 
    display: inline-block !important;
 
    cursor: pointer !important;
 
    color: #0000FF !important; /* Cor azul padrão dos links da MediaWiki */
 
    text-decoration: none !important;
 
    border-bottom: none !important;
 
    font-family: inherit !important; /* Mantém a fonte padrão */
 
    font-weight: bold !important; /* Mantém em negrito como no h2 original */
 
}
 
 
 
/* Efeito hover para links nos títulos dos NPCs */
 
.tile-bottom.link-button h2 .warp-copy:hover {
 
    color: #000080 !important; /* Azul escuro ao passar o mouse */
 
     text-decoration: underline !important; /* Sublinha ao passar o mouse */
 
}
 
 
 
/* Override específico para o tooltip nos títulos dos NPCs */
 
.tile-bottom.link-button h2 .warp-copy::after {
 
    content: "Clique para Copiar" !important;
 
    position: absolute !important;
 
    bottom: 100% !important;
 
    left: 50% !important;
 
    transform: translateX(-50%) !important;
 
    background-color: #333 !important;
 
    color: white !important;
 
    padding: 3px 8px !important;
 
    border-radius: 3px !important;
 
    font-size: 12px !important;
 
    font-weight: normal !important;
 
    white-space: nowrap !important;
 
     opacity: 0 !important;
 
     visibility: hidden !important;
 
     transition: opacity 0.15s, visibility 0.15s !important; /* Transição mais rápida */
 
     pointer-events: none !important;
 
     z-index: 1000 !important;
 
}
 
 
 
/* Mostrar tooltip ao passar o mouse - com alta especificidade */
 
.tile-bottom.link-button h2 .warp-copy:hover::after {
 
    opacity: 1 !important;
 
    visibility: visible !important;
 
}
 
 
 
/* Estilo para quando copiado */
 
.tile-bottom.link-button h2 .warp-copy.copied::after {
 
    content: "Copiado!" !important;
 
    background-color: #4CAF50 !important;
 
}
 
 
 
/* Seta do tooltip com alta especificidade */
 
.tile-bottom.link-button h2 .warp-copy::before {
 
    content: "" !important;
 
    position: absolute !important;
 
    bottom: 100% !important;
 
    left: 50% !important;
 
    transform: translateX(-50%) !important;
 
    border-width: 4px !important;
 
    border-style: solid !important;
 
    border-color: #333 transparent transparent transparent !important;
 
     opacity: 0 !important;
 
     visibility: hidden !important;
 
     transition: opacity 0.15s, visibility 0.15s !important; /* Transição mais rápida */
 
     pointer-events: none !important;
 
    z-index: 1000 !important;
 
}
 

Revision as of 16:01, 29 April 2025

/* Auto-expand sections when clicking anchored links */
$(function() {
  // Função principal para executar quando a página terminar de carregar
  function initializeAnchorExpansion() {
    // Se existir um hash na URL quando a página carrega
    if (window.location.hash) {
      var hash = window.location.hash;
      console.log("Página carregada com hash: " + hash);
      expandSectionForAnchor(hash);
    }
    
    // Lidar com cliques em links âncora dentro da página
    $(document).on('click', 'a[href^="#"]', function(event) {
      var hash = $(this).attr('href');
      console.log("Clique em link interno: " + hash);
      expandSectionForAnchor(hash);
    });
  }
  
  // Função para expandir seções contendo uma âncora específica
  function expandSectionForAnchor(hash) {
    // Remover qualquer caractere # do início do hash se existir
    if (hash.startsWith('#')) {
      hash = hash.substring(1);
    }
    
    console.log("Procurando elemento com ID: " + hash);
    
    // Tentar encontrar o elemento com o ID especificado
    var targetElement = $('#' + hash);
    if (targetElement.length) {
      console.log("Elemento encontrado!");
      
      // Encontrar todas as seções colapsáveis que contêm o elemento
      var collapsibleSections = targetElement.parents('.mw-collapsible.mw-collapsed');
      console.log("Seções colapsáveis encontradas: " + collapsibleSections.length);
      
      // Se o elemento estiver dentro de seções colapsáveis
      if (collapsibleSections.length > 0) {
        // Expandir cada seção de fora para dentro
        collapsibleSections.each(function() {
          var $section = $(this);
          console.log("Expandindo seção");
          $section.removeClass('mw-collapsed');
          
          // Clicar no botão de expansão ou mudar diretamente a classe
          var $toggle = $section.find('.mw-collapsible-toggle').first();
          if ($toggle.length) {
            $toggle.click();
          } else {
            // Tentar forçar a expansão manipulando classes diretamente
            $section.find('.mw-collapsible-content').show();
          }
        });
        
        // Também verificar se o próprio elemento está em um colapsível
        var directCollapsible = targetElement.closest('.mw-collapsible.mw-collapsed');
        if (directCollapsible.length) {
          console.log("Expandindo o contêiner direto");
          directCollapsible.removeClass('mw-collapsed');
          var $toggle = directCollapsible.find('.mw-collapsible-toggle').first();
          if ($toggle.length) {
            $toggle.click();
          } else {
            directCollapsible.find('.mw-collapsible-content').show();
          }
        }
      }
      
      // Rolar até o elemento imediatamente
      console.log("Rolando até o elemento");
      $('html, body').animate({
        scrollTop: targetElement.offset().top - 100
      }, 200);
    } else {
      console.log("Elemento com ID '" + hash + "' não encontrado");
    }
  }

  // Inicializar na carga da página
  initializeAnchorExpansion();
  
  // Também adicionar um observador para o evento mw.hook que é disparado quando o conteúdo é atualizado
  if (typeof mw !== 'undefined' && mw.hook) {
    mw.hook('wikipage.content').add(function() {
      console.log("Conteúdo da Wiki atualizado, reinicializando manipuladores de âncora");
      initializeAnchorExpansion();
      
      // Se houver um hash, tentar expandir após o conteúdo ter sido carregado
      if (window.location.hash) {
        expandSectionForAnchor(window.location.hash);
      }
    });
  }
});

/* JavaScript melhorado para funcionalidade de cópia */
$(document).ready(function() {
    // Adicionar CSS personalizado inline para forçar os tooltips
    $('<style>')
        .text(`
            .warp-copy:hover::after,
            .warp-copy:hover::before {
                opacity: 1 !important;
                visibility: visible !important;
                display: block !important;
            }
            .warp-copy.copied::after {
                content: "Copiado!" !important;
                background-color: #4CAF50 !important;
                display: block !important;
            }
        `)
        .appendTo('head');
});

mw.hook('wikipage.content').add(function ($content) {
    // Função para inicializar todos os elementos .warp-copy
    function initWarpCopy() {
        console.log("Inicializando elementos .warp-copy");
        
        // Remove manipuladores de eventos anteriores para evitar duplicações
        $content.find('.warp-copy').off('click');
        
        // Adiciona o manipulador de clique
        $content.find('.warp-copy').on('click', function (event) {
            event.preventDefault();
            event.stopPropagation();
            
            var $this = $(this);
            var textToCopy = $this.attr('data-copy');
            
            if (!textToCopy) {
                console.warn("Elemento .warp-copy sem atributo data-copy encontrado");
                return;
            }
            
            console.log("Copiando texto: " + textToCopy);
            
            // Usa a API Clipboard moderna quando disponível
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(textToCopy)
                    .then(function() {
                        console.log('Texto copiado com sucesso usando Clipboard API');
                        showCopiedFeedback($this);
                    })
                    .catch(function(err) {
                        console.error('Falha ao copiar texto: ', err);
                        // Tenta o método de fallback
                        fallbackCopyText(textToCopy, $this);
                    });
            } else {
                // Método de fallback para navegadores que não suportam a API Clipboard
                fallbackCopyText(textToCopy, $this);
            }
        });
    }
    
    // Função de fallback para copiar texto
    function fallbackCopyText(text, $element) {
        // Cria um elemento de texto temporário
        var tempInput = document.createElement('textarea');
        tempInput.value = text;
        tempInput.style.position = 'fixed';
        tempInput.style.opacity = '0';
        document.body.appendChild(tempInput);
        
        // Seleciona e copia
        tempInput.select();
        tempInput.setSelectionRange(0, 99999); // Para dispositivos móveis
        
        try {
            var successful = document.execCommand('copy');
            if (successful) {
                console.log('Texto copiado com sucesso usando execCommand');
                showCopiedFeedback($element);
            } else {
                console.error('Falha ao copiar texto com execCommand');
            }
        } catch (err) {
            console.error('Erro ao copiar texto: ', err);
        }
        
        // Remove o elemento temporário
        document.body.removeChild(tempInput);
    }
    
    // Função para mostrar feedback visual de cópia
    function showCopiedFeedback($element) {
        // Adiciona classe para feedback visual
        $element.addClass('copied');
        
        // Remove a classe após um breve período
        setTimeout(function() {
            $element.removeClass('copied');
        }, 1500);
        
        // Opcional: mostrar um popup de notificação
        $('<div class="copy-notification" style="position:fixed;bottom:20px;right:20px;background:#4CAF50;color:white;padding:10px;border-radius:5px;z-index:9999;">Copiado: ' + $element.attr('data-copy') + '</div>')
            .appendTo('body')
            .delay(1500)
            .fadeOut(300, function() { $(this).remove(); });
    }
    
    // Script para imagens dos NPCs
    function initNPCImageCopy() {
        $content.find('.contents-equipment .tile-top.tile-image a').each(function() {
            var $link = $(this);
            var linkHref = $link.attr('href') || '';
            
            // Extrai o ID do NPC do link
            var npcId = linkHref.startsWith('#') ? linkHref.substring(1) : linkHref;
            
            if (npcId) {
                $link.off('mousedown').on('mousedown', function(e) {
                    // Texto a ser copiado
                    var textToCopy = "@warp " + npcId;
                    
                    // Tenta usar a API Clipboard moderna
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(textToCopy)
                            .then(function() {
                                console.log('Comando @warp copiado com sucesso');
                                showCopiedNotification(textToCopy);
                            })
                            .catch(function(err) {
                                console.error('Falha ao copiar comando @warp: ', err);
                                // Usa o método de fallback
                                fallbackCopyText(textToCopy, $link);
                            });
                    } else {
                        // Método de fallback
                        fallbackCopyNPCCommand(textToCopy);
                    }
                    
                    // Permite que o evento continue
                    return true;
                });
            }
        });
    }
    
    // Função de fallback para copiar comando de NPC
    function fallbackCopyNPCCommand(text) {
        var tempInput = document.createElement('textarea');
        tempInput.value = text;
        tempInput.style.position = 'fixed';
        tempInput.style.opacity = '0';
        document.body.appendChild(tempInput);
        
        tempInput.select();
        tempInput.setSelectionRange(0, 99999); // Para dispositivos móveis
        
        try {
            document.execCommand('copy');
            showCopiedNotification(text);
        } catch (err) {
            console.error('Erro ao copiar comando @warp: ', err);
        }
        
        document.body.removeChild(tempInput);
    }
    
    // Função para mostrar notificação de cópia
    function showCopiedNotification(text) {
        $('<div class="copy-notification" style="position:fixed;bottom:20px;right:20px;background:#4CAF50;color:white;padding:10px;border-radius:5px;z-index:9999;">Copiado: ' + text + '</div>')
            .appendTo('body')
            .delay(1500)
            .fadeOut(300, function() { $(this).remove(); });
    }
    
    // Inicializa todas as funções
    initWarpCopy();
    initNPCImageCopy();
    
    // Forçar a atualização dos tooltips (hack)
    setTimeout(function() {
        $content.find('.warp-copy').each(function() {
            var $this = $(this);
            $this.attr('title', 'Clique para Copiar');
        });
    }, 500);
    
    // Observador para alterações no DOM
    var observer = new MutationObserver(function(mutations) {
        var needsReinit = false;
        
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes && mutation.addedNodes.length > 0) {
                needsReinit = true;
            }
        });
        
        if (needsReinit) {
            initWarpCopy();
            initNPCImageCopy();
        }
    });
    
    // Configura o observador
    observer.observe($content[0], { childList: true, subtree: true });
});