import {
  AfterViewInit,
  Directive,
  ElementRef,
  inject,
  input
} from '@angular/core';
import type { AngularVirtualizer } from '@tanstack/angular-virtual';

/**
 * Attaches a virtual row to TanStack's `measureElement` so that variable
 * row heights are observed via `ResizeObserver` and the virtualizer
 * recalculates its size cache automatically (handles late image loads,
 * code-block highlighting, reactions added, etc.).
 *
 * Used internally by `VirtualListComponent`; not exported as a public
 * API on the shared barrel.
 */
@Directive({
  selector: '[appVirtualRowMeasure]',
  standalone: true
})
export class VirtualRowMeasureDirective implements AfterViewInit {
  readonly appVirtualRowMeasure = input.required<AngularVirtualizer<HTMLElement, HTMLElement>>();
  readonly virtualRowIndex = input.required<number>();

  private readonly hostRef = inject<ElementRef<HTMLElement>>(ElementRef);

  ngAfterViewInit(): void {
    const element = this.hostRef.nativeElement;

    element.dataset['index'] = String(this.virtualRowIndex());
    this.appVirtualRowMeasure()().measureElement(element);
  }
}
