document.addEventListener("DOMContentLoaded", function () {

  // Inject minimal CSS for table/card (adjust as needed)
  const style = document.createElement("style");
  style.textContent = `
	.card-header {
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  padding: 0.5rem 1rem;
	}
	.card-body { padding: 1rem; }
	.table { width: 100%; text-align: center; border-collapse: collapse; }
	.table th { font-weight: bold; }
	.table th, .table td { padding: 0.75rem; border-bottom: 1px solid #ddd; }
  `;
  document.head.appendChild(style);

  function getAuthHeaders() {
	return {
	  "Content-Type": "application/json",
	  "Authorization": "Bearer 50afb255cfa3a36834e0a51185b1eb09"
	};
  }

  // Get comp code from storage or URL
  let storedCompetition = JSON.parse(localStorage.getItem("activeCompetition"));
  if (!storedCompetition || !storedCompetition.code) {
	const urlParams = new URLSearchParams(window.location.search);
	const competitionCodeFromURL = urlParams.get("CompetitionCode");
	if (competitionCodeFromURL) {
	  storedCompetition = { code: competitionCodeFromURL };
	} else {
	  console.error("No competition code found. Cannot proceed.");
	  return;
	}
  }

  // Error handling
  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";
  }

  // Container for officials card
  const container = document.getElementById("container-officials");
  if (!container) {
	console.error("No container element with ID 'container-officials' found!");
	return;
  }

  const competitionCode = storedCompetition.code;

  // Fetch officials data
  fetchOfficialsData(competitionCode);

  function fetchOfficialsData(code) {
	fetch(
	  `${API_BASE_URL}?api=officials&competitionCode=${encodeURIComponent(code)}`,
	  { method: "GET", headers: getAuthHeaders() }
	)
	  .then(response => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null;
		}
		return response.json();
	  })
	  .then(data => {
		if (!data) return;
		if (data.success) {
		  renderOfficialsCard(data.officials);
		} else {
		  console.error("Failed to fetch officials:", data.error);
		  container.innerHTML = `<div class="alert alert-info">No officials found for this competition.</div>`;
		}
	  })
	  .catch(error => {
		console.error("Error fetching officials:", error);
		container.innerHTML = `<div class="alert alert-danger">Could not load officials.</div>`;
	  });
  }

  function renderOfficialsCard(officials) {
	container.innerHTML = ""; // clear

	const card = document.createElement("div");
	card.classList.add("card", "mb-4");

	card.innerHTML = `
	  <div class="card-header">
		<h3 class="flex-column align-items-start card-title">
		  <span class="fw-bold text-dark card-label">Officials</span>
		</h3>
	  </div>
	  <div class="card-body">
		${
		  !officials || officials.length === 0
			? `<div class="alert alert-info">No officials found for this competition.</div>`
			: `
			  <table class="table table-striped table-hover table-sm">
				<thead>
				  <tr>
					<th class="text-start">Nat</th>
					<th class="text-start">Name</th>
					<th class="text-start">Function</th>
				  </tr>
				</thead>
				<tbody>
				  ${officials
					.map(
					  o => `
						<tr>
						  <td class="text-start">${o.country || ""}</td>
						  <td class="text-start">${(o.first_name || "") + " " + (o.last_name || "")}</td>
						  <td class="text-start">${o.position || o.function || ""}</td>
						</tr>
					  `
					)
					.join("")}
				</tbody>
			  </table>
			`
		}
	  </div>
	`;
	container.appendChild(card);
  }
});