document.addEventListener('DOMContentLoaded', function () {
  function copyContent(text) {
    const textarea = document.createElement("textarea");
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand("copy");
    document.body.removeChild(textarea);
  }

  function ativarCopia() {
    const botoes = document.querySelectorAll('.js-copy-action');

    botoes.forEach(botao => {
      botao.replaceWith(botao.cloneNode(true));
    });

    document.querySelectorAll('.js-copy-action').forEach(botao => {
      botao.style.cursor = 'pointer';
      botao.title = 'Copiar';

      botao.addEventListener('click', function () {
        const conteudo = this.closest('.row').querySelector('.js-copy-content');
        if (conteudo) {
          copyContent(conteudo.textContent);

          const feedback = document.createElement('span');
          feedback.className = 'js-copy-feedback';
          feedback.textContent = 'COPIADO';

          Object.assign(feedback.style, {
            fontFamily: 'sans-serif',
            whiteSpace: 'nowrap',
            fontSize: '9px',
            letterSpacing: '1px',
            padding: '8px',
            position: 'absolute',
            zIndex: '10',
            background: 'rgba(0,0,0,.8)',
            color: '#fff',
            left: '50%',
            transform: 'translateX(-50%)',
            bottom: '-23px'
          });

          this.style.position = 'relative';
          this.appendChild(feedback);

          setTimeout(() => feedback.remove(), 1000);
        }
      });
    });
  }

  function updatePdfLinks(links) {
    const container = document.getElementById("pdf-links-container");
    const list = document.getElementById("pdf-links-list");
    const noResults = document.getElementById("no-results-message");

    list.innerHTML = "";

    if (links.length > 0) {
      container.style.display = "block";
      noResults.style.display = "none";

      links.forEach(item => {
        const link = item.linkdireto;

        const row = document.createElement("div");
        row.className = "content-box background-white bottom-border-gray padding-medium";

        row.innerHTML = `
          <div class="row no-space-xs middle-xs">
            <div class="col-xs-11">
              <span class="text-small text-dark js-copy-content">${link}</span>
            </div>
            <div class="col-xs-1 text-right">
              <i class="far fa-clone js-copy-action"></i>
            </div>
          </div>
        `;

        list.appendChild(row);
      });

      ativarCopia();

    } else {
      container.style.display = "none";
      noResults.style.display = "block";
    }
  }

  if (Array.isArray(DATA) && DATA.length > 0) {
    updatePdfLinks(DATA);
  } else {
    updatePdfLinks([]);
  }

  window.addEventListener("pdfUploaded", function (event) {
    const previous = Array.isArray(window.DATA) ? window.DATA : [];
  
    if (event.detail && Array.isArray(event.detail.newFiles)) {
      const { newFiles, original } = event.detail;
  
      if (original) {
        // rename de arquivo
        const filtered = previous.filter(item => item.linkdireto !== original.linkdireto);
        const existingLinks = new Set(filtered.map(item => item.linkdireto));
        const filteredNew = newFiles.filter(item => !existingLinks.has(item.linkdireto));
        window.DATA = filtered.concat(filteredNew);
      } else {
        // rename de pasta: substitui toda a lista
        window.DATA = newFiles;
      }
  
      updatePdfLinks(window.DATA);
    } else {
      console.warn("evento 'pdfUploaded' sem newFiles ou malformado:", event.detail);
    }
  });
  
  document.querySelectorAll('.js-open-file-manager').forEach(button => {
    button.addEventListener('click', () => {
      window.dispatchEvent(
        new CustomEvent('vue-file-manager', {
          detail: {
            // callbackFunction: file => {}
          },
        })
      );
    });
  });
});