import { watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';


export function useEmphasizeHashElement() {
    const route = useRoute(), router = useRouter();
    watch(() => route.hash, async () => {
        if(!route.hash) return;
        await nextTick();
        const id = route.hash.slice(1);
        const elem = document.getElementById(id);
        if(!elem) return;
        const original = elem.style.backgroundColor;
        elem.style.backgroundColor = 'yellow';
        setTimeout(() => {
            elem.scrollIntoView({ behavior: 'smooth', block: "center" });
            document.body.addEventListener('click', e => {
                elem.style.backgroundColor = original;
                if(e.target.tagName.toLowerCase() !== 'a')
                    router.replace({path: route.path, query: route.query});
            }, { once: true });
        }, 100);
        return;
    }, { immediate: true });
}
