<template>
	<template v-if="content && content.length > 0">
		<div><MarkdownRenderer #default v-if="data" :node="data" :proses="proses"></MarkdownRenderer></div>
	</template>
</template>

<script setup lang="ts">
import type { Component } from 'vue';
import { heading } from 'hast-util-heading';
import { headingRank } from 'hast-util-heading-rank';
import { parseId } from '~/shared/general.utils';
import type { Root } from 'hast';

const { content, proses, filter } = defineProps<{
	content: string
	proses?: Array<string | Component>
	filter?: string
}>();

const parser = useMarkdown(), data = ref<Root>();
const node = computed(() => content ? parser(content) : undefined);
watch([node], () => {
	if(!node.value)
		data.value = undefined;
	else if(!filter)
	{
		data.value = node.value;
	}
	else
	{
		const start = node.value?.children.findIndex(e => heading(e) && parseId(e.properties.id as string | undefined) === filter) ?? -1;

		if(start === -1)
			data.value = node.value;
		else
		{
			let end = start;
			const rank = headingRank(node.value.children[start])!;
			while(end < node.value.children.length)
			{
				end++;
				if(heading(node.value.children[end]) && headingRank(node.value.children[end])! >= rank)
					break;
			}
			data.value = { ...node.value, children: node.value.children.slice(start, end) };
		}
	}
}, { immediate: true, });
</script>