document.addEventListener("DOMContentLoaded", function () {
  /*************************************************************
   * 0) Retrieve bearer token from localStorage user
   *************************************************************/
  const storedUser  = JSON.parse(localStorage.getItem("user")) || {};
  const bearerToken = storedUser.bearer || null;
  if (!bearerToken) {
	console.error("No bearer token found in local storage!");
	localStorage.removeItem("user");
	window.location.href = "index.html";
	return;
  }

  /**
   * Helper: Build fetch headers with Bearer token & JSON content.
   */
  function getAuthHeaders(isJson = true) {
	const base = isJson ? { "Content-Type": "application/json" } : {};
	base["Authorization"] = `Bearer ${bearerToken}`;
	return base;
  }

  /**
   * If response is not ok => sign out user & redirect.
   */
  function handleNotOkResponse(response) {
	console.error(`API response not OK: ${response.status} - ${response.statusText}`);
	alert("Session expired or invalid. You will be signed out.");
	localStorage.removeItem("user");
	window.location.href = "index.html";
  }

  // 1) Grab competition code from localStorage
  const competitionCode = JSON.parse(localStorage.getItem("activeCompetition"))?.code;
  if (!competitionCode) {
	console.error("No active competition found in localStorage!");
	return;
  }

  // 2) Fetch current settings from the server to decide which sheets file to load
  fetch(`${API_BASE_URL}?api=settings&competitionCode=${encodeURIComponent(competitionCode)}`, {
	method: "GET",
	headers: getAuthHeaders(true),
  })
	.then((response) => {
	  if (!response.ok) {
		handleNotOkResponse(response);
		return null;
	  }
	  return response.json();
	})
	.then((data) => {
	  if (!data) return;
	  if (data.success) {
		// Retrieve the sheets setting (e.g. 0 or 1)
		const sheetsSetting = parseInt(data.settings.sheets, 10);
		let scriptUrl = "";
		if (sheetsSetting === 1) {
		  scriptUrl = "js/sheets_1.js";
		} else if (sheetsSetting === 2) {
		  scriptUrl = "js/sheets_2.js";
		} else {
		  // Default to sheets_0.js if not set or sheetsSetting is 0 or any unexpected value.
		  scriptUrl = "js/sheets_0.js";
		}
		// Dynamically load the appropriate sheets file.
		const script = document.createElement("script");
		script.src = scriptUrl;
		script.type = "text/javascript";
		script.onload = () => {
		  console.log(`Loaded ${scriptUrl} successfully.`);
		};
		script.onerror = () => {
		  console.error(`Failed to load ${scriptUrl}`);
		};
		document.body.appendChild(script);
	  } else {
		console.error("Failed to fetch settings:", data.error || "Unknown error");
		if (String(data.error || "").toLowerCase().includes("invalid")) {
		  alert("Session invalid. Signing out...");
		  localStorage.removeItem("user");
		  window.location.href = "index.html";
		}
	  }
	})
	.catch((error) => console.error("Error fetching settings:", error));
});