import { TypographyDynamicHeadingLevel } from '@af/digi-ng/_typography/typography-dynamic-heading';
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';

export interface ValidationErrorLink {
  elementId: string;
  text: string;
}

@Component({
  selector: 'msfa-error-list',
  templateUrl: './error-list.component.html',
  styleUrls: ['./error-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ErrorListComponent {
  @Input() validationErrorLinks: ValidationErrorLink[] = [];
  @Input() headingText: string;
  @Input() headingLevel: TypographyDynamicHeadingLevel = TypographyDynamicHeadingLevel.H3;

  setFocusOnFormElement(element: HTMLElement): void {
    const id = element.getAttribute('href').replace('#', '');
    const target = document.getElementById(id);

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

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