import Taro, { useReady } from "@tarojs/taro";
import { useState } from "react";

const useObserve = (bindObject: any, initial: boolean) => {
  const [visible, setVisible] = useState(initial);
  const handleObserveScrollAction = () => {
    Taro.nextTick(() => {
      Taro.createSelectorQuery()
        .select("#leaf-nav-bar")
        .boundingClientRect()
        .exec((boundings) => {
          const bounding = boundings[0];
          console.log("navbar bounding >>", bounding);
          const paddingTop = 40;
          console.log("paddingTop >>", paddingTop);
          const top = -(bounding.height + paddingTop);
          Taro.createIntersectionObserver(bindObject)
            .relativeToViewport({ top: top })
            .observe("#user-name", (observer) => {
              console.log("username observer >>", observer);
              const _visible = observer.intersectionRatio > 0;
              console.log("visible >>", _visible);
              setVisible(_visible);
            });
        });
    });
  };

  useReady(() => {
    handleObserveScrollAction();
  });

  return {
    visible,
  };
};

export default useObserve;
