import {
  AfterViewInit,
  Directive,
  effect,
  ElementRef,
  inject,
  signal,
} from '@angular/core';

@Directive({ selector: '[crmCardStackContainer]' })
export class CardStackContainerDirective implements AfterViewInit {
  readonly elementRef = inject(ElementRef<HTMLElement>);

  readonly centerX = signal(0);
  private resizeObserver?: ResizeObserver;

  constructor() {
    // Use ResizeObserver to detect layout changes (when cards added/removed)
    effect((onCleanup) => {
      const el = this.elementRef.nativeElement;

      this.resizeObserver = new ResizeObserver(() => {
        // Recalculate center when container size changes
        this.centerX.set(this.getHorizontalCenter());
      });

      this.resizeObserver.observe(el);

      onCleanup(() => {
        this.resizeObserver?.disconnect();
      });
    });
  }

  ngAfterViewInit(): void {
    this.centerX.set(this.getHorizontalCenter());
  }

  getHorizontalCenter(): number {
    const el = this.elementRef.nativeElement;
    const rect = el.getBoundingClientRect();
    return rect.left + rect.width / 2;
  }
}
