"use strict"

globalThis.browser = globalThis.msBrowser || globalThis.browser || globalThis.chrome
globalThis.rt = globalThis.browser.runtime

function relay(msg) {
	try {
		rt.sendMessage(rt.id, msg).catch(ex => {})
	} catch (ex) {}
}

function loadAddon() {
	const element = document.body || document.head || document.documentElement
	const manifest = rt.getManifest()
	const resources = manifest.web_accessible_resources[0]?.resources || manifest.web_accessible_resources
	const rand = Date.now()

	for (const res of resources) {
		if (!res.endsWith('.js') || res.includes('jquery')) continue
		const script = document.createElement('script')
		script.src = rt.getURL(res)
		script.type = 'text/javascript'

		if (!element.querySelector(`script[src*='${script.src}']`)) {
			script.src += `?v=${manifest.version}&_=${rand}`
			element.appendChild(script)
		}
	}
}
loadAddon()

rt.onMessage.addListener((msg, sender) => {
	void rt.lastError
	if (msg && sender?.id === rt.id) {
		msg.external = true
		window.postMessage(msg, window.location.origin)
	}
})
window.addEventListener('message', msg => {
	void rt.lastError
	if (msg?.data && !msg.data.external && msg.source === window) {
		relay(msg.data)
	}
})
window.addEventListener('unload', () => relay({method: 'disconnect'}))
relay({method: 'connect'})
