import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[msfaAnchorLink]',
})
export class AnchorLinkDirective {
  @HostListener('click', ['$event'])
  onClick(event: MouseEvent): void {
    const target = event.target as HTMLElement;
    const link = target.tagName === 'a' ? target : target.closest('a');
    const href = link?.getAttribute('href');
    const elementId = href?.trim().replace('#', '');
    const element = document.getElementById(elementId);

    if (element) {
      const elementPosition: DOMRect = element.getBoundingClientRect();
      const absoluteElementPosition = elementPosition.top + window.scrollY;
      const newPosition = absoluteElementPosition - window.innerHeight / 2;

      if (element.focus) {
        element.tabIndex = -1;
        element.focus();
        window.scrollTo(0, newPosition);
        element.tabIndex = 0;
      }
    }

    event.stopPropagation();
    event.preventDefault();
  }
}
