import { Controller } from '@hotwired/stimulus';
import { wpjFunction } from '@assets/components/util.event';

export default class extends Controller<HTMLAnchorElement> {

   header = document.querySelector(COMPONENTS['Header'].selector);
   headerSticky = document.querySelector(COMPONENTS['Header:Sticky'].selector);

   navigateTo(e) {
      e.preventDefault();
      const targetElem: HTMLElement = document.querySelector(this.element.dataset.target);
      const dataOffset = Number(this.element.dataset?.offset);
      let offsetScroll = dataOffset || 16; // 1rem

      if (!targetElem) {
         return;
      }

      if (this.headerSticky && this.header) {
         offsetScroll += this.header.offsetHeight;
      }

      if (!wpjFunction.isInViewport(targetElem)) {
         wpjFunction.scrollTo(targetElem, -offsetScroll);
      }
   }
}
