import * as htmlparser2 from "htmlparser2";

import type { Mention, Tag } from "@/lib/api/entities/activity";
import type { CustomEmoji } from "@/lib/api/entities/custom_emoji";
import { Text, type ChildNode, Element } from "domhandler";

interface Props {
	content: string;
	emoji: CustomEmoji[];
	tags?: Tag[];
	mentions?: Mention[];
}

const parser = new DOMParser();

export default function HTMLContent(props: Props) {
	let { content } = props;
	// emoji are always in their shortcode form
	props.emoji.forEach((emoji) => {
		content = content.replace(new RegExp(`:${emoji.shortcode}:`, "g"), customEmojiElement(emoji));
	});

	const dom = htmlparser2.parseDocument(content);
	const elements = parseElement(dom.children);

	console.log(dom);

	return elements;
}

const customEmojiElement = (emoji: CustomEmoji) => {
	const elem = document.createElement("x-emoji");
	elem.setAttribute("emoji", emoji.shortcode);
	return elem.outerHTML;
};

function parseElement(elems: ChildNode[]) {
	const out = [];
	for (const elem of elems) {
		if (elem instanceof Text) out.push(<>{elem.data}</>);
	}
}
