import {
  afterNextRender,
  computed,
  Directive,
  ElementRef,
  inject,
  OnDestroy,
  signal,
} from '@angular/core';
import { CardStackContainerDirective } from './card-stack-container.directive';

@Directive({
  selector: '[crmCardStackDistance]',
  host: {
    '[style.--distance-to-center.px]': 'distanceToCenter()',
    // Disable ALL transforms until we've measured the natural position
    '[style.transform]': 'ready() ? null : "none"',
  },
})
export class CardStackDistanceDirective implements OnDestroy {
  readonly container = inject(CardStackContainerDirective, { host: true });
  readonly elementRef = inject(ElementRef<HTMLElement>);

  /** True once we've measured the card's natural position */
  readonly ready = signal(false);

  distanceToCenter = computed(() => {
    const containerCenterX = this.container.centerX();
    const centerX = this.centerX();
    return containerCenterX - centerX;
  });

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

  constructor() {
    // Wait for Angular to complete rendering and layout before calculating position
    afterNextRender(() => {
      // Measure natural position (with --distance-to-center: 0, card is in natural spot)
      this.centerX.set(this.getHorizontalCenter());
      // Now enable the transform
      this.ready.set(true);

      // Watch for this card's size changes
      this.resizeObserver = new ResizeObserver(() => {
        this.centerX.set(this.getHorizontalCenter());
      });
      this.resizeObserver.observe(this.elementRef.nativeElement);
    });
  }

  ngOnDestroy(): void {
    this.resizeObserver?.disconnect();
  }

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