import { global_navigator } from "filesystem/FSNavigator"
import { current_page_store } from "wrap/RouterStore"

export const highlight_current_page = (node: HTMLAnchorElement) => {
	const set_highlight = () => {
		const currentpath = window.location.pathname + "/"
		const hrefpath = URL.parse(node.href).pathname + "/"
		if (
			currentpath === hrefpath ||
			(hrefpath !== "" && hrefpath !== "/" && currentpath.startsWith(hrefpath))
		) {
			node.classList.add("button_highlight")
		} else {
			node.classList.remove("button_highlight")
		}
	}

	// Initialize the status with the current page path
	set_highlight()

	// Set up a listener with the page router to catch navigation events
	const unsub = current_page_store.subscribe(() => { set_highlight() })
	const unsub2 = global_navigator.subscribe(() => { set_highlight() })
	return {
		destroy() {
			unsub()
			unsub2()
		}
	}
}
