export default function setupCopyButtonListener(containerElement) {
  const copyButton = containerElement.querySelector(
    ".firevert-promo-time-widget__copy-button"
  );

  if (!copyButton) {
    console.log("Copy button not found");
    return;
  }

  copyButton.addEventListener("click", async (event) => {
    event.preventDefault();
    event.stopPropagation();

    const codeToCopy = copyButton.getAttribute("data-copy");
    const buttonText = copyButton.querySelector(
      ".firevert-promo-time-widget__copy-button-text"
    );
    const svgIcon = copyButton.querySelector("svg");

    if (!codeToCopy || !buttonText || !svgIcon) {
      console.log("Missing data:", { codeToCopy, buttonText, svgIcon });
      return;
    }

    try {
      if (!navigator.clipboard) {
        const textArea = document.createElement("textarea");
        textArea.value = codeToCopy;
        textArea.style.position = "fixed";
        textArea.style.left = "-999999px";
        textArea.style.top = "-999999px";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        document.execCommand("copy");
        document.body.removeChild(textArea);
      } else {
        await navigator.clipboard.writeText(codeToCopy);
      }

      const originalSvg = svgIcon.outerHTML;

      svgIcon.outerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
          <path d="M0,0H24V24H0Z" fill="none"/>
          <path d="M9,16.17L4.83,12l-1.42,1.41L9,19L21,7l-1.41-1.41L9,16.17z" fill="#fff"/>
        </svg>
      `;

      setTimeout(() => {
        const currentSvg = copyButton.querySelector("svg");
        if (currentSvg) {
          currentSvg.outerHTML = originalSvg;
        }
      }, 2000);
    } catch (error) {
      console.error("Błąd podczas kopiowania:", error);
    }
  });
}
