/*
 * SPDX-FileCopyrightText: 2023 Kristóf Marussy
 *
 * SPDX-License-Identifier: MIT
 */

import { type ReactNode, useEffect, useCallback, useRef } from 'react';

import { useActiveSection } from './ActiveSectionProvider';

export default function TrackActiveSection({
  children,
}: {
  children: ReactNode;
}) {
  const { setHash } = useActiveSection();
  const elementRef = useRef<HTMLDivElement | null>(null);
  const callback = useCallback(() => {
    const { current: element } = elementRef;
    if (!element) {
      return;
    }
    const currentID = Array.from(element.children)
      .reverse()
      .find((child) => child.getBoundingClientRect().top <= 60)?.id;
    const currentHash =
      currentID === undefined || currentID === '' ? '' : `#${currentID}`;
    setHash(currentHash);
  }, [setHash]);
  const setElement = useCallback(
    (element: HTMLDivElement | null) => {
      elementRef.current = element;
      if (element) {
        callback();
      } else {
        setHash(undefined);
      }
    },
    [setHash],
  );
  useEffect(() => {
    window.addEventListener('scroll', callback);
    return () => window.removeEventListener('scroll', callback);
  });

  return <div ref={setElement}>{children}</div>;
}
