const className = document.currentScript.getAttribute("video-class")
window.addEventListener("load", () => {
	const allVideos = document.getElementsByClassName(className)
	let queue = []

	for (const v of allVideos) {
		const dearrowIcon = v.querySelector(".dearrow-button-list.loading")
		if (dearrowIcon)
			queue.push(v)
	}

	new Promise(async resolve => {
		for (const v of queue) {
			const id = v.querySelector(".info .title .title-link").getAttribute("href").split("?v=")[1]
			const dearrowIcon = v.querySelector(".dearrow-button-list.loading")
			const titleAlt = v.querySelector(".info .title.alt a")
			const thumbAlt = v.querySelector(".thumbnail .thumbnail__link.alt img")

			const response = await fetch(`/getDeArrow?v=${id}`)
			if (response.status == 404) {
				newToast("red", "x", `Failed to load DeArrow for ${id} (404)`)
				continue
			}
			const j = await response.json()
			if (j.title)
				titleAlt.innerText = j.title
			if (j.thumbnail)
				thumbAlt.setAttribute("src", dearrow_thumbnail_instance + (dearrow_thumbnail_instance.endsWith("/") ? "" : "/") + j.thumbnail)
			dearrowIcon.classList.remove("loading")

			if (!j.title && !j.thumbnail) {
				dearrowIcon.remove()
				titleAlt.remove()
				thumbAlt.remove()
			}
		}
		resolve()
	})
})
