(() => {
	const selectEl = document.getElementById("summary-ref-select");
	const commitLinkEl = document.getElementById("summary-ref-commit-link");
	const browseLinkEl = document.getElementById("summary-ref-browse-link");
	const logLinkEl = document.getElementById("summary-ref-log-link");
	const shortlogLinkEl = document.getElementById("summary-ref-shortlog-link");
	const readmeContainerEl = document.getElementById("summary-readme-container");
	if (!selectEl || !commitLinkEl || !browseLinkEl || !readmeContainerEl) {
		return;
	}

	const project = readmeContainerEl.dataset.project;
	if (!project) {
		return;
	}

	const projectApiBase = () =>
		"/project/" + project.split("/").map((segment) => encodeURIComponent(segment)).join("/");

	const rerunScripts = () => {
		for (const oldScript of readmeContainerEl.querySelectorAll("script")) {
			const scriptEl = document.createElement("script");
			if (oldScript.src) {
				scriptEl.src = oldScript.src;
			} else if (oldScript.textContent) {
				scriptEl.textContent = oldScript.textContent;
			}
			oldScript.replaceWith(scriptEl);
		}
	};

	const loadState = async (ref) => {
		const response = await fetch(
			`${projectApiBase()}/summary-ref-state?ref=${encodeURIComponent(ref)}`,
		);
		if (!response.ok) {
			return;
		}
		const state = await response.json();
		commitLinkEl.href = state.commit_href;
		commitLinkEl.textContent = state.display;
		browseLinkEl.href = state.browse_href;
		if (logLinkEl) {
			logLinkEl.href = state.log_href;
		}
		if (shortlogLinkEl) {
			shortlogLinkEl.href = state.shortlog_href;
		}
		readmeContainerEl.innerHTML = state.readme_html || "";
		if (state.readme_html) {
			rerunScripts();
		}
	};

	const loadOptions = async () => {
		const response = await fetch(`${projectApiBase()}/summary-refs`);
		if (!response.ok) {
			return;
		}
		const data = await response.json();
		for (const optionData of data.options || []) {
			const optionEl = document.createElement("option");
			optionEl.value = optionData.value;
			optionEl.textContent = `${optionData.kind}: ${optionData.label}`;
			selectEl.appendChild(optionEl);
		}
	};

	selectEl.addEventListener("change", () => {
		void loadState(selectEl.value);
	});
	void loadOptions();
})();