import { useEffect } from 'react';
import { useAnchorContext } from './AnchorContext';
import { refactorAnchorId } from './refactorAnchorId';

interface AnchorSectionProps {
  as?: React.ElementType;
  id: string;
  index: number;
  children: React.ReactNode;
}

export const AnchorSection = ({
  as = 'div',
  id,
  index,
  ...props
}: AnchorSectionProps) => {
  const { observe, unobserve } = useAnchorContext();

  const anchorId = refactorAnchorId(id);

  useEffect(() => {
    if (anchorId) {
      const target = document.getElementById(anchorId);
      if (target) {
        observe(target, index);
        return () => {
          unobserve(target);
        };
      }
    }
  }, [anchorId, observe, unobserve, index]);

  // TODO useRef
  const Element = as;
  return <Element id={anchorId} {...props} />;
};
