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

interface AnchorLinkProps {
  id: string;
  className: string;
  activeClassName?: string;
  children: React.ReactNode;
}

export const AnchorLink = ({
  id,
  className,
  activeClassName = 'active',
  children,
}: AnchorLinkProps) => {
  const { active, scrollTo } = useAnchorContext();

  const anchorId = refactorAnchorId(id);

  const cn = [className, active === anchorId ? activeClassName : '']
    .join(' ')
    .trim();

  return (
    <a
      className={cn}
      href={`#${anchorId}`}
      onClick={(ev) => scrollTo(anchorId)}
    >
      {children}
    </a>
  );
};
