import { escapeHtml, whenReady } from "./dom.js";

const container = document.getElementById("d2h-container");
const output = document.getElementById("d2h-output");
const emptyEl = document.getElementById("d2h-empty");

function render() {
	if (!container || !output || !emptyEl) return;
	const diffB64 = container.getAttribute("data-diff-b64");
	const hasDiff = container.getAttribute("data-has-diff") === "true";
	const emptyText = container.getAttribute("data-empty-text") || "";

	if (!hasDiff || !diffB64) {
		emptyEl.textContent = emptyText;
		emptyEl.style.display = "block";
		return;
	}
	try {
		const raw = atob(diffB64);
		if (!raw) {
			emptyEl.textContent = emptyText;
			emptyEl.style.display = "block";
			return;
		}
		const diffStr = (typeof TextDecoder !== "undefined")
			? new TextDecoder("utf-8").decode(Uint8Array.from(raw, (c) => c.charCodeAt(0)))
			: raw;
		if (typeof Diff2HtmlUI === "undefined") {
			output.innerHTML = '<p class="text-warning">Diff2HtmlUI not loaded.</p>';
			return;
		}
		const config = {
			drawFileList: true,
			matching: "lines",
			outputFormat: "side-by-side",
			synchronisedScroll: true,
			highlight: true,
		};
		const diff2htmlUi = new Diff2HtmlUI(output, diffStr, config);
		diff2htmlUi.draw();
		diff2htmlUi.highlightCode();
	} catch (e) {
		output.innerHTML = '<p class="text-danger">Failed to render diff: ' + escapeHtml(e.message || e) + "</p>";
	}
}

whenReady("diff2html-script", "Diff2HtmlUI", render);