import type { mastodon } from "masto";
import {
  splitProps,
  type Component,
  type JSX,
  createRenderEffect,
  createMemo,
} from "solid-js";
import { resolveCustomEmoji } from "../../masto/toot.js";
import { makeAcctText, useDefaultSession } from "../../masto/clients";
import "./TootContent.css";

function preventDefault(event: Event) {
  event.preventDefault();
}

export type TootContentProps = {
  source?: string;
  emojis?: mastodon.v1.CustomEmoji[];
  mentions: mastodon.v1.StatusMention[];
} & JSX.HTMLAttributes<HTMLDivElement>;

const TootContent: Component<TootContentProps> = (oprops) => {
  const session = useDefaultSession();
  const [props, rest] = splitProps(oprops, [
    "source",
    "emojis",
    "mentions",
    "class",
  ]);

  const clientFinder = createMemo(() =>
    session() ? makeAcctText(session()!) : undefined,
  );

  return (
    <div
      ref={(ref) => {
        createRenderEffect(() => {
          ref.innerHTML = props.source
            ? props.emojis
              ? resolveCustomEmoji(props.source, props.emojis)
              : props.source
            : "";
        });

        createRenderEffect(() => {
          const finder = clientFinder();
          for (const mention of props.mentions) {
            const elements = ref.querySelectorAll<HTMLAnchorElement>(
              `a[href='${mention.url}']`,
            );
            for (const e of elements) {
              e.onclick = preventDefault;
              e.dataset.action = "acct";
              e.dataset.client = finder;
              e.dataset.acctId = mention.id.toString();
            }
          }
        });
      }}
      class={`TootContent ${props.class || ""}`}
      {...rest}
    ></div>
  );
};

export default TootContent;
