import React, { FC, ReactChild, useEffect, useMemo, useRef } from 'react';

export interface IProps {
  onEnter?: () => void;
  onLeave?: () => void;
  threshold?: number;
  rootMargin?: string | number;
  children?: ReactChild;
}

export const ReactSign: FC<IProps> = ({
  onEnter,
  onLeave,
  children,
  threshold = 0,
  rootMargin = '0px',
}) => {
  const isInitializeToggle = useRef(true);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const observerRef = useRef<IntersectionObserver>();
  const rootMarginStringValue = useMemo(
    () => (typeof rootMargin === 'number' ? `${rootMargin}px` : rootMargin),
    [rootMargin]
  );

  const handleIntersect = (
    entries: IntersectionObserverEntry[]
    // observer: IntersectionObserver
  ) => {
    if (entries[0].isIntersecting) {
      onEnter && onEnter();
    } else {
      onLeave && !isInitializeToggle.current && onLeave();
    }
    if (isInitializeToggle.current) {
      isInitializeToggle.current = false;
    }
  };

  useEffect(() => {
    if (wrapperRef.current) {
      const options = {
        root: null,
        rootMarginStringValue,
        threshold,
      };

      observerRef.current = new IntersectionObserver(handleIntersect, options);
      observerRef.current.observe(wrapperRef.current);
    }
    return () => {
      if (wrapperRef.current)
        observerRef.current?.unobserve(wrapperRef.current);
    };
  }, []);

  return <div ref={wrapperRef}>{children}</div>;
};

export default ReactSign;
