frappe.pages["custom_ui"].on_page_load = async (wrapper) => {
	// Create root div for spa if it doesn't exist
	const appRootId = "custom-ui-app";
	if (!document.getElementById(appRootId)) {
		$(wrapper).html('<div id="custom-ui-app"></div>');
		console.log("App root div created");
	}

	// Attempt to load the manifest file
	try {
		// Cache busting by appending a timestamp
		const manifestUrl = `/assets/custom_ui/dist/.vite/manifest.json?v=${Date.now()}`;
		manifest = await fetch(manifestUrl).then((res) => res.json());
		console.log("Fetched manifest:", manifest);

		// Check existence of old script and link elements and remove them
		const existingScript = document.getElementById("custom-ui-main-js");
		if (existingScript) existingScript.remove();

		const existingLink = document.getElementById("custom-ui-main-css");
		if (existingLink) existingLink.remove();

		// Append new script and link elements
		const cssHref = manifest["src/main.js"]["css"]?.[0];
		if (cssHref) {
			const link = document.createElement("link");
			link.id = "custom-ui-main-css";
			link.rel = "stylesheet";
			link.href = `/assets/custom_ui/dist/${cssHref}`;
			document.head.appendChild(link);
			console.log("Appended stylesheet:", link.href);
		}

		const jsFile = manifest["src/main.js"]["file"];
		if (jsFile) {
			const script = document.createElement("script");
			script.id = "custom-ui-main-js";
			script.type = "module";
			script.src = `/assets/custom_ui/dist/${jsFile}`;
			document.body.appendChild(script);
			console.log("Appended script:", script.src);
		}

	} catch (error) {
		console.error("Error loading manifest or app resources:", error);
	}
};
