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 user!");
	localStorage.removeItem("user");
	window.location.href = "index.html";
	return;
  }

  /**
   * Helper function to build the headers for fetch calls,
   * including the Bearer token if available.
   */
  function getAuthHeaders() {
	return {
	  "Content-Type": "application/json",
	  "Authorization": `Bearer ${bearerToken}`
	};
  }

  /**
   * If fetch response is not OK => we sign out the user and 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 BIB settings page
  const container = document.getElementById("bib-container");
  if (!container) {
	console.error("No container element with ID 'settings-container-bibs' 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 the athlete list with their bib + gender
  fetchBibsData(competitionCode);

  /**
   * Fetch the athlete list from the server (with Bearer).
   */
  function fetchBibsData(code) {
	fetch(
	  `${API_BASE_URL}?api=bibs&competitionCode=${encodeURIComponent(code)}`, 
	  { method: "GET", headers: getAuthHeaders() }
	)
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null;
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return; // short circuit if handleNotOkResponse triggered
		if (data.success) {
		  renderBibsCard(data.athletes);
		} else {
		  console.error("Failed to fetch bibs data:", data.error || "Unknown error");
		  // If the API specifically indicates an auth error => handle sign-out
		  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 bibs:", error));
  }

  /**
   * Render the "Bibs" card with a list of athletes + input to edit their bib number.
   * Also show gender icon (male=blue, female=red).
   */
  function renderBibsCard(athletes) {
	container.innerHTML = ""; // Clear any existing content

	// Create a main card
	const card = document.createElement("div");
	card.classList.add("card");

	card.innerHTML = `
	  <div class="card-header">
		<div class="fs-3 fw-bold card-title"><span>Bib Settings</span></div>
	  </div>
	  <div class="card-body p-9">
		<div id="bibs-list-container"></div>
	  </div>
	`;

	container.appendChild(card);

	const bibsListContainer = card.querySelector("#bibs-list-container");

	if (!athletes || athletes.length === 0) {
	  bibsListContainer.innerHTML = `<p>No athletes found for this competition.</p>`;
	  return;
	}

	// Build a table
	const table = document.createElement("table");
	table.classList.add("table", "table-hover", "table-sm");

	// Table head
	table.innerHTML = `
	  <thead>
		<tr>
		  <th><b>Athlete Name</b></th>
		  <th><b>Bib Number</b></th>
		</tr>
	  </thead>
	  <tbody></tbody>
	`;
	const tbody = table.querySelector("tbody");

	// Populate rows for each athlete
	athletes.forEach((athlete) => {
	  const tr = document.createElement("tr");

	  // Full name cell with gender icon
	  const nameTd = document.createElement("td");

	  // Determine icon based on athlete.gender
	  let genderIcon = "";
	  if (athlete.gender === "M") {
		genderIcon = `<i class="bi bi-gender-male text-primary" style="margin-left: 6px;"></i>`;
	  } else if (athlete.gender === "F") {
		genderIcon = `<i class="bi bi-gender-female text-danger" style="margin-left: 6px;"></i>`;
	  }

	  nameTd.innerHTML = `
		${athlete.full_name || "Unknown Athlete"}
		${genderIcon}
	  `;
	  tr.appendChild(nameTd);

	  // Bib input cell
	  const bibTd = document.createElement("td");
	  bibTd.innerHTML = `
		<input 
		  type="number" 
		  class="form-control form-control-sm bib-input" 
		  data-athlete-id="${athlete.id}" 
		  value="${athlete.bib ?? ""}"
		  min="0" 
		  style="width: 80px;" 
		/>
	  `;
	  tr.appendChild(bibTd);

	  tbody.appendChild(tr);
	});

	bibsListContainer.appendChild(table);

	// Now attach event listeners for each bib-input
	const bibInputs = table.querySelectorAll(".bib-input");
	bibInputs.forEach((input) => {
	  let timer;
	  input.addEventListener("input", (event) => {
		const athleteId = parseInt(event.target.getAttribute("data-athlete-id"), 10);
		const bibValue = parseInt(event.target.value, 10) || 0;

		// Debounce
		clearTimeout(timer);
		timer = setTimeout(() => {
		  updateBibNumber(athleteId, bibValue);
		}, 500);
	  });
	});
  }

  /**
   * Update the bib number in DB by sending a POST request with Bearer.
   * If there's a duplicate, highlight the input in red.
   */
  function updateBibNumber(athleteId, bibValue) {
	// Find the input element in the DOM
	const inputElement = document.querySelector(
	  `.bib-input[data-athlete-id="${athleteId}"]`
	);

	fetch(`${API_BASE_URL}?api=bibs`, {
	  method: "POST",
	  headers: getAuthHeaders(), // <--- Bearer token
	  body: JSON.stringify({
		athlete_id: athleteId,
		bib: bibValue
	  }),
	})
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null;
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return; // short-circuit from handleNotOkResponse
		if (data.success) {
		  console.log(`Bib number for athlete ${athleteId} updated to ${bibValue}`);
		  // Remove any error styling
		  inputElement?.classList.remove("border-danger");
		} else {
		  console.error("Failed to update bib:", data.error);

		  // If there's a duplicate or any error => highlight the input
		  if (String(data.error || "").toLowerCase().includes("already in use")) {
			inputElement?.classList.add("border-danger");
		  }
		  // If it's specifically an auth error => remove user, redirect
		  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 updating bib:", error);
		alert("Failed to update bib. Please try again or sign in again.");
	  });
  }
});