export default class ButtonScroll {
  element;

  constructor() {
    this.render();
  }

  get template() {
    return `
    <button
    class="btn-toggle-round scroll-top js-scroll-top"
    type="button"
    title="scroll_to_top"
    data-scroll
  >
    <svg
      xmlns="http://www.w3.org/2000/svg"
      class="icon icon-tabler icon-tabler-arrow-up"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      stroke-width=""
      stroke="cuurentColor"
      fill="none"
      stroke-linecap="round"
      stroke-linejoin="round"
    >
      <path stroke="none" d="M0 0h24v24H0z" fill="none" />
      <line x1="12" y1="5" x2="12" y2="19" />
      <line x1="18" y1="11" x2="12" y2="5" />
      <line x1="6" y1="11" x2="12" y2="5" />
    </svg>
  </button>
      `;
  }

  initialize() {
    this.initEventListeners();
  }

  initEventListeners() {
    const offset = 200;

    window.addEventListener("scroll", () => {
      const scrollPos =
        window.scrollY ||
        window.scrollTop ||
        document.getElementsByTagName("html")[0].scrollTop;
      scrollPos > offset
        ? this.element.classList.add("is-active")
        : this.element.classList.remove("is-active");
    });

    this.element.addEventListener("click", (event) => {
      const isScroll = event.target.closest("[data-scroll]");
      if (isScroll) {
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    });
  }

  render() {
    const divElement = document.createElement("div");
    divElement.innerHTML = this.template;
    this.element = divElement.firstElementChild;
    this.initialize();
  }

  remove() {
    if (this.element) {
      this.element.remove();
      destroyEventListeners();
    }
  }

  destroy() {
    this.remove();
    this.element = null;
  }
}
