import { useCallback, useEffect, useRef } from "react";

import { Job } from "@enact/core/util";
import { scaleH } from "../utils/helperMethods";

export default function useScrollTopByDistance() {
  const jobRef = useRef(new Job((func) => func(), 0));

  useEffect(() => {
    return () => jobRef.current.stop();
  }, []);

  const scrollTopByDistance = useCallback(
    (markerSelector, targetSelector, scrollTop, gap = 0) => {
      try {
        const marker = document.querySelector(markerSelector);
        const target = document.querySelector(targetSelector);

        if (!marker || !target) {
          throw new Error("marker or target not found");
        }

        const markerRect = marker.getBoundingClientRect();
        const targetRect = target.getBoundingClientRect();

        const distance = targetRect.top - markerRect.top - scaleH(gap);

        jobRef.current.start(() => scrollTop({ y: distance >=0 ? distance : 0 }));
      } catch (error) {
        console.error(error.message);
      }
    },
    []
  );

  return { scrollTopByDistance };
}
