import innerText from "react-innertext";
import clsx from "clsx";
import HeadingAnchor from "../HeadingAnchor";
import type { JSX, ComponentPropsWithoutRef } from "react";

import styles from "./Heading.module.css";

export type HeadingProps = ComponentPropsWithoutRef<"h1"> & {
  level: 1 | 2 | 3 | 4 | 5 | 6;
  divider?: boolean;
};

const Heading = ({ level, id, divider, className, children, ...rest }: HeadingProps) => {
  const HWild: keyof JSX.IntrinsicElements = `h${level}`;

  return (
    <HWild id={id} className={clsx(styles.h, (divider || level === 2) && styles.divider, className)} {...rest}>
      {children}

      {/* add anchor link to H2s and H3s. ID is either provided or automatically generated by rehype-slug. */}
      {id && (level === 2 || level === 3) && (
        <HeadingAnchor id={id} title={innerText(children)} className={styles.anchor} />
      )}
    </HWild>
  );
};

export const H1 = (props: Omit<HeadingProps, "level">) => <Heading level={1} {...props} />;
export const H2 = (props: Omit<HeadingProps, "level">) => <Heading level={2} {...props} />;
export const H3 = (props: Omit<HeadingProps, "level">) => <Heading level={3} {...props} />;
export const H4 = (props: Omit<HeadingProps, "level">) => <Heading level={4} {...props} />;
export const H5 = (props: Omit<HeadingProps, "level">) => <Heading level={5} {...props} />;
export const H6 = (props: Omit<HeadingProps, "level">) => <Heading level={6} {...props} />;

export default Heading;
