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; // stop here
  }

  /**
   * 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 the container for the Officials page
  const container = document.getElementById("officials-container");
  if (!container) {
	console.error("No container element with ID 'officials-container' found!");
	return;
  }

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

  // 3) Fetch officials for the competition
  fetchOfficials(competitionCode);

  /**
   * fetchOfficials => uses Bearer token in headers
   */
  function fetchOfficials(code) {
	fetch(
	  `${API_BASE_URL}?api=officials&competitionCode=${encodeURIComponent(code)}`,
	  {
		method: "GET",
		headers: getAuthHeaders(true),
	  }
	)
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null; // short-circuit
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return; // from short-circuit
		if (data.success) {
		  renderOfficialsCard(data.officials, code);
		} else {
		  console.error("Failed to fetch officials:", data.error || "Unknown error");

		  // If specifically an invalid session => sign out
		  const errLower = String(data.error || "").toLowerCase();
		  if (errLower.includes("invalid") || errLower.includes("session")) {
			alert("Session invalid. Signing out...");
			localStorage.removeItem("user");
			window.location.href = "index.html";
			return;
		  }

		  // If the error message is "No officials found for the specified competition."
		  // show the alert in the card body.
		  if (data.error === "No officials found for the specified competition.") {
			renderOfficialsCard([], code, true);
		  }
		}
	  })
	  .catch((error) => console.error("Error fetching officials:", error));
  }

  /**
   * renderOfficialsCard => displays a table (or an alert if no officials).
   */
  function renderOfficialsCard(officials, competitionCode, noOfficialsError = false) {
	container.innerHTML = ""; // Clear any existing content

	const card = document.createElement("div");
	card.classList.add("card");

	let cardBodyContent = "";

	// If noOfficialsError or no officials => show alert
	if (noOfficialsError || !officials || officials.length === 0) {
	  cardBodyContent = `
		<div class="card-body p-9">
		  <div class="alert alert-info" role="alert">
			No officials found for the specified competition.
		  </div>
		</div>
	  `;
	} else {
	  // Officials exist, show the table
	  cardBodyContent = `
		<div class="card-body p-9">
		  <table class="table table-striped">
			<thead>
			  <tr>
				<th><b>Name</b></th>
				<th><b>Position</b></th>
				<th><b>Country</b></th>
			  </tr>
			</thead>
			<tbody>
			  ${officials
				.map(
				  (official) => `
					<tr>
					  <td>${official.first_name} ${official.last_name}</td>
					  <td>${official.position}</td>
					  <td>${official.country}</td>
					</tr>
					<tr>
					  <td colspan="3">
						<div class="input-group">
						  <input 
							type="text" 
							class="form-control form-control-sm email-input ${
							  !official.email ? "is-invalid" : ""
							}" 
							value="${official.email || ''}" 
							placeholder="Enter email to invite Official"
							data-original-email="${official.email || ''}"
							${official.password_set ? "disabled" : ""}
						  />
						  ${
							official.password_set
							  ? `<span class="input-group-text text-success">Registered</span>`
							  : `<button 
								  class="btn btn-sm ${
									!official.email ? "btn-danger" : "btn-primary"
								  } save-email-btn" 
								  title="${
									!official.email
									  ? "Enter email to send invite"
									  : "Send invite"
								  }" 
								  data-id="${official.iwwf_id}">
								  <i class="bi bi-arrow-right"></i>
								</button>`
						  }
						</div>
						<div class="mt-2 email-success-message d-none text-success">
						  Verification email sent successfully!
						</div>
					  </td>
					</tr>`
				)
				.join("")}
			</tbody>
		  </table>
		</div>
	  `;
	}

	card.innerHTML = `
	  <div class="card-header">
		<div class="fs-3 fw-bold card-title"><span>Competition Officials</span></div>
	  </div>
	  ${cardBodyContent}
	`;

	container.appendChild(card);

	// If there are officials, attach event listeners
	if (officials && officials.length > 0 && !noOfficialsError) {
	  // 1) Attach event listeners to email inputs
	  const emailInputs = container.querySelectorAll(".email-input");
	  emailInputs.forEach((input) => {
		input.addEventListener("input", function () {
		  const originalEmail = input.getAttribute("data-original-email").trim();
		  const currentEmail = input.value.trim();
		  const saveButton = input
			.closest(".input-group")
			.querySelector(".save-email-btn");

		  if (saveButton) {
			// Show button if changed, hide if unchanged
			if (currentEmail !== originalEmail) {
			  saveButton.classList.remove("d-none");
			} else {
			  saveButton.classList.add("d-none");
			}
		  }
		});
	  });

	  // 2) Attach event listeners to save buttons
	  const saveButtons = container.querySelectorAll(".save-email-btn");
	  saveButtons.forEach((button) =>
		button.addEventListener("click", function () {
		  const iwwf_id = button.getAttribute("data-id"); // changed name
		  const emailInput = button
			.closest(".input-group")
			.querySelector(".email-input");
		  const email = emailInput.value.trim();
		  const successMessage = button
			.closest(".input-group")
			.nextElementSibling; // .email-success-message

		  if (!email) {
			// highlight the text field in warning state if empty
			emailInput.classList.add("is-invalid");
			emailInput.setAttribute("placeholder", "Email required");
		  } else {
			emailInput.classList.remove("is-invalid");
			saveEmail(competitionCode, iwwf_id, email, successMessage, hostname);
		  }
		})
	  );
	}
  }

  /**
   * saveEmail => updates the official's email, sends an invite, etc.
   */
  function saveEmail(competitionCode, iwwf_id, email, successMessage, host) {
	fetch(`${API_BASE_URL}?api=save-email`, {
	  method: "POST",
	  headers: getAuthHeaders(true), // Bearer token
	  body: JSON.stringify({ competitionCode, iwwf_id, email, host }), // changed property name here
	})
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null; 
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return; // short-circuit from handleNotOkResponse
		if (data.success) {
		  // Show success message
		  successMessage.classList.remove("d-none");
		} else {
		  console.error("Failed to save email:", data.error || "Unknown error");

		}
	  })
	  .catch((error) => console.error("Error saving email:", error));
  }
});