export default function initTextToggle({
   buttonSelector,
   cardSelector,
   textSelector,
   btnTextSelector,
   lines = null,
   openText = "свернуть",
   closeText = "читать полностью",
   marginBottom = null,
}) {
   const buttons = document.querySelectorAll(buttonSelector);
   if (!buttons.length) return;

   buttons.forEach((button) => {
      const card = button.closest(cardSelector);
      const text = card.querySelector(textSelector);
      const btnText = button.querySelector(btnTextSelector);

      const lineHeight = parseFloat(getComputedStyle(text).lineHeight);
      const collapsedHeight = lineHeight * lines;

      if (text.scrollHeight <= collapsedHeight) {
         button.style.display = "none";
         return;
      }

      text.style.maxHeight = collapsedHeight + "px";
      text.style.overflow = "hidden";

      button.addEventListener("click", () => {
         const isOpen = card.classList.contains("active");

         card.classList.toggle("active");
         button.classList.toggle("open");

         if (!isOpen) {
            text.style.maxHeight = text.scrollHeight + "px";
            if (marginBottom) text.style.marginBottom = marginBottom + "px";
            if (btnText) btnText.textContent = openText;
         } else {
            text.style.maxHeight = collapsedHeight + "px";
            if (marginBottom) text.style.marginBottom = "0px";
            if (btnText) btnText.textContent = closeText;
         }
      });
   });
}
