import { action, makeObservable, observable } from 'mobx';

export class IntersectionObserverState {
  intersectionRatio: number = 1;

  observer?: IntersectionObserver;

  constructor() {
    makeObservable(this, {
      intersectionRatio: observable.ref,
    });
  }

  dispose = () => {
    this.observer?.disconnect();
  };

  init({
    root,
    target,
    rootMargin,
  }: {
    target?: Element | null;
    root?: Element | Document | null;
    rootMargin?: string;
  }) {
    if (target == null || typeof IntersectionObserver === 'undefined') {
      return;
    }

    const observer = new IntersectionObserver(
      action(([{ intersectionRatio }]) => {
        this.intersectionRatio = intersectionRatio;
      }),
      {
        root,
        rootMargin,
      },
    );

    observer.observe(target);

    this.observer = observer;

    return this.dispose;
  }
}
