import { useLocation } from "wouter";
import { cx } from "../class-names.ts";
import type { TrustedHtml } from "../types.ts";
import { content } from "./style.css.ts";

// export { richTextTheme } from "./style.css.ts";

export function RichText(props: {
  trustedHtml: TrustedHtml;
  className?: string;
}) {
  const [_, navigate] = useLocation();

  return (
    <div
      {...cx(props, content)}
      dangerouslySetInnerHTML={{ __html: props.trustedHtml }}
      onClick={(event) => {
        if (!(event.target instanceof HTMLElement)) {
          return;
        }

        const anchor = event.target.closest("a");
        if (!anchor) {
          return;
        }

        // The actual value in the HTML
        const href = anchor.getAttribute("href");
        if (!href) {
          return;
        }

        if (href.startsWith("#")) {
          return;
        }

        if (href.startsWith("/")) {
          event.preventDefault();
          event.stopPropagation();
          navigate(`~${href}`);
          return;
        }

        event.preventDefault();
        event.stopPropagation();
        const tempLink = document.createElement("a");
        tempLink.href = anchor.href;
        tempLink.target = "_blank";
        tempLink.rel = "noopener noreferrer";
        tempLink.click();
      }}
    />
  );
}
