browser.runtime.onMessage.addListener((message) => {
	if (message.type === "MY_GET_URL_R") {
		window.postMessage(message);
	} else if (message.type === "GET_DATA_FROM_PAGE") {
        // Parse things for linkedin
        if (window.location.host.includes("linkedin")) {
            if (window.location.host.includes("merchantpool1")) {
                return;
            }
		    const jobTitle = document.querySelector('h1').textContent;
            const company = document.querySelector('.relative a[target="_self"]').textContent;
            const money = document.querySelector('ul li div div div li-icon[type="job"]')?.parentNode?.parentNode?.parentNode?.parentNode?.children[1]?.children[0]?.textContent?.replaceAll(/\s{2,}/g, '') ?? '';
            const description = document.querySelector('article').textContent;

		    browser.runtime.sendMessage({ type: "GOT_INFO_R", company, jobTitle, money, description });
            return;
        }
        // Ignore everything that is no glassdoor
        if (!window.location.host.includes("glassdoor")) return;
		const company = document.querySelector('header[data-test="job-details-header"]')
			.children[0].children[0].querySelector("h4").innerHTML;
		const jobTitle = document
			.querySelector('header[data-test="job-details-header"]')
			.querySelector("h1").innerHTML;

        const description = [...document.querySelector('header[data-test="job-details-header"]').parentNode.querySelectorAll('button')].filter(a => a.textContent == "Show more")[0]?.parentNode?.parentNode?.textContent;

        let money = ""

        const moneySectionNode = document.querySelector('section>section');
        if (moneySectionNode && ["Base pay range", "Base pay"].includes(moneySectionNode.querySelector('h2').textContent)) {
            money = moneySectionNode.querySelector("div>div>div").children[1]?.textContent ?? ''
        }

		browser.runtime.sendMessage({ type: "GOT_INFO_R", company, jobTitle, money, description });
	} else if (message.type === "GOT_INFO_R") {
		window.postMessage(message);
	}
});

window.addEventListener("message", (e) => {
	if (e.data.type === "MY_GET_URL") {
		browser.runtime.sendMessage({ type: "MY_GET_URL" });
	} else if (e.data.type === "HAS_EXTENSION_Q") {
		window.postMessage({ type: "HAS_EXTENSION" });
	} else if (e.data.type === "REGISTER_INTEREST") {
		browser.runtime.sendMessage({ type: "REGISTER_INTEREST" });
	} else if (e.data.type === "R_GET_DATA_FROM_PAGE") {
		browser.runtime.sendMessage({ type: "R_GET_DATA_FROM_PAGE" });
    }
});
