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

  // Build fetch headers
  function getAuthHeaders(isJson = true) {
	const base = isJson ? { "Content-Type": "application/json" } : {};
	if (bearerToken) {
	  base["Authorization"] = `Bearer ${bearerToken}`;
	}
	return base;
  }

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

  // 2) Admin container
  const container = document.getElementById("admin-container");
  if (!container) {
	console.error("No container #admin-container found!");
	return;
  }

  // 3) Fetch the JSON => containing users + countries
  fetch(`${API_BASE_URL}?api=admin`, {
	method: "GET",
	headers: getAuthHeaders(true)
  })
	.then((response) => {
	  if (!response.ok) {
		handleNotOkResponse(response);
		return null;
	  }
	  return response.json();
	})
	.then((data) => {
	  if (!data) return;
	  if (data.status === "success") {
		renderUsers(data.users, data.countries);
	  } else {
		console.error("Fetching users failed:", data.error || "Unknown");
	  }
	})
	.catch((err) => console.error("Error fetching user data:", err));

  /**
   * Render each user in a separate card,
   * with a <select> for fed_admin => country code
   */
  function renderUsers(users, countries) {
	container.innerHTML = "";

	if (!users || users.length === 0) {
	  container.innerHTML = `<div class="alert alert-info">No users found!</div>`;
	  return;
	}

	let html = ``;
	users.forEach((user, index) => {
	  const userId         = user.user_id       || "";
	  const userIwwf       = user.iwwf_id       || "";
	  const userEmail      = user.email         || "";
	  const userFirstName  = user.first_name    || "";
	  const userLastName   = user.last_name     || "";
	  const fedAdmin       = user.fed_admin     || ""; // code
	  const councilAdmin   = user.council_admin ? "Yes" : "No";
	  const userTimestamp  = user.timestamp     || "";
	  const officialStatus = user.official_status || 0; 

	  // Icon for official_status
	  let statusIcon = `<i class="bi bi-x-circle text-danger ms-2"></i>`; 
	  if (officialStatus === 1) {
		statusIcon = `<i class="bi bi-check-circle text-success ms-2"></i>`;
	  }

	  // Build <select> from countries => pass fedAdmin
	  const countryDropdown = buildCountryDropdown(
		countries, 
		fedAdmin, 
		userId            // We pass userId so we can store data-user-id
	  );

	  // Build subtable for officials
	  let officialsHtml = "";
	  if (Array.isArray(user.officials) && user.officials.length > 0) {
		officialsHtml = `
		  <table class="table table-responsive table-striped table-hover table-sm mt-2">
			<thead>
			  <tr>
				<th><b>Code</b></th>
				<th><b>Country</b></th>
				<th><b>Competition</b></th>
				<th><b>Venue</b></th>
				<th><b>Date</b></th>
				<th><b>Position</b></th>
			  </tr>
			</thead>
			<tbody>
		`;
		user.officials.forEach((off) => {
		  const offComp        = off.competition_code    || "";
		  const offCompName    = off.competition_name    || "";
		  const offCompCountry = off.competition_country || "";
		  const offCompVenue   = off.competition_venue   || "";
		  const offCompDate    = off.beginning_date      || "";
		  const offPos         = off.official_position   || "";
		  officialsHtml += `
			<tr>
			  <td>${offComp}</td>
			  <td>${offCompCountry}</td>
			  <td>${offCompName}</td>
			  <td>${offCompVenue}</td>
			  <td>${offCompDate}</td>
			  <td>${offPos}</td>
			</tr>
		  `;
		});
		officialsHtml += `</tbody></table>`;
	  } else {
		officialsHtml = `<div class="text-muted">No roles for this user.</div>`;
	  }

	  // Unique collapse ID
	  const collapseId = `collapse-user-${userId}-${index}`;

	  html += `
		<div class="card mb-4">
		  <div class="card-header d-flex justify-content-between align-items-center">
			<h5 class="mb-0">
			  ${userFirstName} ${userLastName}
			  ${statusIcon}
			</h5>
			<button 
			  class="btn btn-sm btn-primary role-toggle-btn"
			  type="button" 
			  data-bs-toggle="collapse"
			  data-bs-target="#${collapseId}"
			  aria-expanded="false"
			  aria-controls="${collapseId}">
			  Show Roles
			</button>
		  </div>

		  <div class="card-body">
			<div class="row mb-2">
			  <div class="col-lg-4">
				<p class="mb-1"><strong>IWWF ID:</strong> ${userIwwf}</p>
				<p class="mb-1"><strong>Email:</strong> ${userEmail}</p>
			  </div>
			  <div class="col-lg-4">
				<label class="mb-1"><strong>Federation Admin (country):</strong></label>
				${countryDropdown}
			  </div>
			  <div class="col-lg-4">
				<p class="mb-1"><strong>Council Admin:</strong> ${councilAdmin}</p>
				<p class="mb-1"><strong>Last active:</strong> ${userTimestamp}</p>
			  </div>
			</div>

			<div class="collapse" id="${collapseId}">
			  <hr class="my-2" />
			  ${officialsHtml}
			</div>
		  </div>
		</div>
	  `;
	});

	container.innerHTML = html;
	attachCollapseListeners();
	attachCountryChangeListeners();
  }

  /**
   * Build <select> for countries with data-user-id to identify user.
   */
  function buildCountryDropdown(countries, selectedCode, userId) {
	let options = "";
	countries.forEach((c) => {
	  const isSelected = (c.code === selectedCode) ? "selected" : "";
	  options += `<option value="${c.code}" ${isSelected}>${c.name}</option>`;
	});

	return `
	  <select 
		class="form-select form-select-sm country-dropdown" 
		data-user-id="${userId}"
	  >
		<option value="">(Select a federation/country)</option>
		${options}
	  </select>
	`;
  }

  /**
   * When "Show Roles" => expand => hide button
   */
  function attachCollapseListeners() {
	const toggleButtons = container.querySelectorAll(".role-toggle-btn");
	toggleButtons.forEach((btn) => {
	  const collapseSelector = btn.getAttribute("data-bs-target");
	  const collapseEl       = document.querySelector(collapseSelector);
	  if (!collapseEl) return;

	  collapseEl.addEventListener("shown.bs.collapse", function () {
		btn.style.display = "none";
	  });
	});
  }

  /**
   * attachCountryChangeListeners => for each .country-dropdown, 
   * when user changes => update fed_admin over the API.
   */
  function attachCountryChangeListeners() {
	const dropdowns = container.querySelectorAll(".country-dropdown");
	dropdowns.forEach((ddl) => {
	  ddl.addEventListener("change", function (event) {
		const newCode = ddl.value; // the new fed_admin code
		const userId  = ddl.getAttribute("data-user-id");
		if (!userId) {
		  console.warn("No user-id found on dropdown!");
		  return;
		}

		// call function to POST an update
		updateFedAdmin(userId, newCode);
	  });
	});
  }

  /**
   * updateFedAdmin => POST to an endpoint, e.g. ?api=update_fed_admin
   */
  function updateFedAdmin(userId, fedAdminCode) {
	console.log(`updateFedAdmin => user=${userId}, country=${fedAdminCode}`);

	fetch(`${API_BASE_URL}?api=admin`, {
	  method: "POST",
	  headers: getAuthHeaders(true),
	  body: JSON.stringify({
		user_id: userId,
		fed_admin: fedAdminCode
	  })
	})
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null;
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return;
		if (data.success) {
		  // optional success message
		  console.log("Fed admin updated successfully:", data.message);
		  // You could show a toast or small alert
		} else {
		  console.error("Failed to update fed_admin:", data.error || "Unknown error");
		  alert("Could not update country. " + (data.error || ""));
		}
	  })
	  .catch((err) => console.error("Error updating fed_admin:", err));
  }
});