import { watch, toValue, type MaybeRefOrGetter } from 'vue';
import useDJSSRContext from "@/useDJSSRContext.ts";
import { h } from "@/util.ts";

export default function useHead(params: {
    title: MaybeRefOrGetter<string>,
    metatags?: MaybeRefOrGetter<Array<{ name: string, content: string }>>
}) {
    const context = useDJSSRContext();

    if (context) {
        context.head.title = params.title;
        context.head.metatags = params.metatags ?? [];
    } else {
        watch([() => toValue(params.title), () => toValue(params.metatags) ?? []], ([newTitle, newMetatags]) => {
            if (newTitle) {
                document.title = newTitle;
            }
            const currMetatags = document.head.querySelectorAll('meta');
            const existing = new Set<string>();
            for (const currMetatag of currMetatags) {
                const match = newMetatags.find(_ => _.name === currMetatag.name);
                if (!match) {
                    currMetatag.remove();
                } else {
                    existing.add(match.name);
                    currMetatag.content = match.content;
                }
            }
            for (const newMetatag of newMetatags) {
                if (!existing.has(newMetatag.name)) {
                    document.head.appendChild(h('meta', newMetatag));
                }
            }
        }, { immediate: true });
    }
}