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

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

  /**
   * If response is not OK => sign out user & redirect to index.html.
   */
  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";
  }

  /**
   * After we receive JSON from the server, if it has an error 
   * containing "invalid" or "session" => sign out & redirect.
   */
  function checkSessionError(data) {
	if (!data) return;
	const errStr = String(data.error || "").toLowerCase();
	if (errStr.includes("invalid") || errStr.includes("session")) {
	  alert("Session invalid or expired. Signing out...");
	  localStorage.removeItem("user");
	  window.location.href = "index.html";
	}
  }

  const container = document.getElementById("panel-container");
  if (!container) {
	console.error("panel-container not found in DOM!");
	return;
  }

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

  /**
   * 1) We'll define a single function to fetch the panel data
   *    and then build the stats block + the main panel
   */
  function fetchAndRenderPanel() {
	fetch(
	  `${API_BASE_URL}?api=panel&competitionCode=${encodeURIComponent(
		competitionCode
	  )}`,
	  {
		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

		checkSessionError(data); // if server says “session invalid,” sign out

		if (data.success) {
		  // Suppose we have `runtime` from the server or define a fallback:
		  const fallbackRuntime = 180; // 180 seconds, for example
		  const runtime = data.runtime || fallbackRuntime;

		  // Build & show the officials stats block
		  buildOfficialsStatsBlock(data.events, data.officials, runtime);

		  // Then render the main panel card
		  renderJudgesCard(
			data.events,
			data.officials,
			data.number_of_judges,
			competitionCode,
			runtime
		  );
		} else {
		  console.error("Failed to fetch panel data:", data.error || "Unknown error");
		}
	  })
	  .catch((error) => {
		console.error("Error fetching data:", error);
	  });
  }

  // 2) Start everything by calling fetchAndRenderPanel() once
  fetchAndRenderPanel();

  // Helper to format seconds => "HH:MM:SS"
  function formatHMS(totalSeconds) {
	const hours   = Math.floor(totalSeconds / 3600);
	const remain  = totalSeconds % 3600;
	const minutes = Math.floor(remain / 60);
	const seconds = remain % 60;

	// zero‐pad each to 2 digits
	const hh = String(hours).padStart(2, "0");
	const mm = String(minutes).padStart(2, "0");
	const ss = String(seconds).padStart(2, "0");

	//return `${hh}:${mm}:${ss}`;
	return `${hh}:${mm}`;
  }

  /**
   * Build a stats block at the top for each official
   */
  function buildOfficialsStatsBlock(events, allOfficials, runtime) {
	// 1) Initialize stats: official_id => { name: "...", runs: 0 }
	const officialStats = {};
	allOfficials.forEach((off) => {
	  officialStats[off.official_id] = {
		name: off.name,
		country: off.country,
		runs: 0
	  };
	});

	// 2) For each category in each event, look at category.officials array
	//    If an official is assigned there, add category.category_runs to that official
	events.forEach((ev) => {
	  ev.categories_in_competition.forEach((cat) => {
		const catRuns = cat.category_runs || 0;
		cat.officials.forEach((catOff) => {
		  const offId = catOff.official_id;
		  if (officialStats[offId]) {
			officialStats[offId].runs += catRuns;
		  }
		});
	  });
	});

	// 3) We want the sum of runs across ALL officials
	let totalRunsAll = 0;
	Object.values(officialStats).forEach((st) => {
	  totalRunsAll += st.runs;
	});

	// We'll do totalTimeAll as well
	const totalTimeAll = totalRunsAll * runtime;

	// 4) Build a small HTML block with these stats
	// We'll add an extra column for the "percentage"
	// plus a totals row at the bottom
	let statsHtml = `
	  <div class="card mb-4">
		<div class="card-header">
		  <h3 class="card-title fw-bold">Officials Overview</h3>
		</div>
		<div class="card-body">
		  <table class="table table-sm table-hover">
			<thead>
			  <tr>
				<th><b>Official</b></th>
				<th><b>Country</b></th>
				<th><b>Runs</b></th>
				<th><b>%</b></th>
				<th><b>Total Time</b></th>
			  </tr>
			</thead>
			<tbody>
	`;

	// 5) For each official => compute totalTime => format => do the row
	Object.keys(officialStats).forEach((offId) => {
	  const { name, country, runs } = officialStats[offId];
	  const totalTime    = runs * runtime; // in seconds
	  const totalTimeHMS = formatHMS(totalTime);

	  // Percentage of total
	  let pct = "0.0";
	  if (totalRunsAll > 0 && runs > 0) {
		pct = ((runs / totalRunsAll) * 100).toFixed(1);
	  }

	  statsHtml += `
		<tr>
		  <td>${name}</td>
		  <td>${country}</td>
		  <td>${runs}</td>
		  <td>${pct}%</td>
		  <td>${totalTimeHMS}</td>
		</tr>
	  `;
	});

	// 6) Add a final "Totals" row
	const totalTimeHMS = formatHMS(totalTimeAll);
	statsHtml += `
			</tbody>
			<tfoot>
			  <tr class="table-active fw-bold">
				<td>TOTAL</td>
				<td></td>
				<td>${totalRunsAll}</td>
				<td>100%</td>
				<td>${totalTimeHMS}</td>
			  </tr>
			</tfoot>
		  </table>
		</div>
	  </div>
	`;

	// 7) Insert the stats block at top of #panel-container
	container.innerHTML = statsHtml;
  }

  /**
   * Render the "Officials Panel" card
   */
  function renderJudgesCard(events, officials, numberOfJudges, competitionCode, runtime) {
	// We keep the stats block at the top, so "append" the new card 
	// rather than clearing container entirely.
	const card = document.createElement("div");
	card.classList.add("card");

	card.innerHTML = `
	  <div class="card-header">
		<div class="fs-3 fw-bold card-title text-center text-lg-start">
		  <span>Officials Panel</span>
		</div>
	  </div>
	  <div class="card-body">
		${
		  events
			.map(
			  (event) => `
			  <div class="event-section mb-5">
				<h4 class="text-dark fw-bold text-center text-lg-start">${event.name}</h4>
				<div class="list-group list-group-flush">
				  ${
					event.categories_in_competition
					  .map(
						(category) => `
						  <div class="list-group-item border-0">
							<h5 class="mb-3">${category.category_name}</h5>
							${Array.from({ length: numberOfJudges })
							  .map(
								(_, index) => `
								<div class="d-flex align-items-center mb-3">
								  <label 
									for="judge${index + 1}-category-${category.category_id}"
									class="form-label me-4 mb-0 text-nowrap">
									Judge ${index + 1}:
								  </label>
								  <select 
									class="form-control form-control-sm form-control-solid judge-select"
									data-category-id="${category.category_id}"
									data-event-id="${event.id}"
									data-judge-index="${index + 1}"
									id="judge${index + 1}-category-${category.category_id}">
									<option value="" disabled ${
									  !category.officials.some((o) => o.judge === index + 1)
										? "selected"
										: ""
									}>
									  Select Judge
									</option>
									${officials
									  .map(
										(official) => `
										  <option value="${official.official_id}"
											${
											  category.officials.some(
												(panelOfficial) =>
												  panelOfficial.official_id ===
													official.official_id &&
												  panelOfficial.judge === index + 1
											  )
												? "selected"
												: ""
											}>
											${official.name} (${official.country})
										  </option>`
									  )
									  .join("")}
								  </select>
								</div>`
							  )
							  .join("")}
						  </div>`
					  )
					  .join("")
				  }
				</div>
			  </div>`
			)
			.join("")
		}
	  </div>
	`;

	container.appendChild(card);

	// Initialize dropdown states
	initializeDropdowns();

	// Add event listeners to each .judge-select
	const dropdowns = container.querySelectorAll(".judge-select");
	dropdowns.forEach((dropdown) => {
	  dropdown.addEventListener("change", function () {
		const categoryId = dropdown.getAttribute("data-category-id");
		const eventId    = dropdown.getAttribute("data-event-id");
		const judgeIndex = dropdown.getAttribute("data-judge-index");
		const officialId = dropdown.value;

		// Save the judge selection => POST to server
		saveJudge(competitionCode, categoryId, eventId, judgeIndex, officialId);

		// Update the dropdown visuals => disable duplicates
		updateDropdownOptions(categoryId, eventId);
		validateDropdown(dropdown);
	  });

	  // Validate each dropdown on page load
	  validateDropdown(dropdown);
	});
  }

  /**
   * Initialize dropdowns => disable duplicates within the same category & event.
   */
  function initializeDropdowns() {
	const categoryDropdowns = container.querySelectorAll(".judge-select");
	categoryDropdowns.forEach((dropdown) => {
	  const categoryId = dropdown.getAttribute("data-category-id");
	  const eventId    = dropdown.getAttribute("data-event-id");
	  updateDropdownOptions(categoryId, eventId);
	});
  }

  /**
   * updateDropdownOptions => within same category & event => disable duplicates
   */
  function updateDropdownOptions(categoryId, eventId) {
	const eventDropdowns = document.querySelectorAll(
	  `[data-event-id="${eventId}"][data-category-id="${categoryId}"]`
	);

	const selectedValues = Array.from(eventDropdowns)
	  .map((dropdown) => dropdown.value)
	  .filter((value) => value);

	eventDropdowns.forEach((dropdown) => {
	  const options = dropdown.querySelectorAll("option");
	  options.forEach((option) => {
		if (selectedValues.includes(option.value) && dropdown.value !== option.value) {
		  option.disabled = true;
		} else {
		  option.disabled = false;
		}
	  });
	});
  }

  /**
   * Basic validation => if no value => add .border-danger
   */
  function validateDropdown(dropdown) {
	if (!dropdown.value) {
	  dropdown.classList.add("border-danger");
	} else {
	  dropdown.classList.remove("border-danger");
	}
  }

  /**
   * Save the judge selection to the server => POST with Bearer
   * Then re-fetch the panel data to re-render stats & panel.
   */
  function saveJudge(competitionCode, categoryId, eventId, judgeIndex, officialId) {
	const judgeData = {
	  competitionCode,
	  judges: [
		{
		  category_id: categoryId,
		  event_id: eventId,
		  judge_index: judgeIndex,
		  official_id: officialId,
		},
	  ],
	};

	fetch(`${API_BASE_URL}?api=panel`, {
	  method: "POST",
	  headers: getAuthHeaders(true),
	  body: JSON.stringify(judgeData),
	})
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null;
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return; // from short-circuit
		checkSessionError(data);

		if (data.success) {
		  console.log("Judge assigned successfully!");
		  // Re-render the entire panel data => stats block + panel
		  fetchAndRenderPanel();
		} else {
		  console.error("Failed to save judge:", data.error || "Unknown error");
		}
	  })
	  .catch((error) => {
		console.error("Error saving judge:", error);
	  });
  }
});