document.addEventListener("DOMContentLoaded", function () {
  // 1) Grab or fallback competitionCode
  let competitionCode;
  const storedCompetition = JSON.parse(localStorage.getItem("activeCompetition"));
  if (storedCompetition && storedCompetition.code) {
	competitionCode = storedCompetition.code;
  } else {
	const urlParams = new URLSearchParams(window.location.search);
	competitionCode = urlParams.get("CompetitionCode");
  }

  if (!competitionCode) {
	console.error("No competition code found in local storage or GET parameter.");
	return;
  }

  // 2) Fetch all athletes from your results (or a dedicated endpoint).
  //    We'll assume `results.php` returns something like { data: { athletes: [...] } } 
  //    where each athlete object includes { event_name, category_name, gender, athlete_name, country, ... }
  fetch(`https://php.score-now.com/results.php?competitionCode=${competitionCode}&allAthletes=true`)
	.then((res) => res.json())
	.then((apiResponse) => {
	  const { data } = apiResponse || {};
	  if (!data || !Array.isArray(data.athletes)) {
		console.error("Invalid data or data.athletes is not an array.");
		return;
	  }

	  // data.athletes is presumably an array of objects:
	  // {
	  //   event_name: "Wakeboard",
	  //   category_name: "Open",
	  //   gender: "F",
	  //   athlete_name: "Jane Doe",
	  //   country: "USA",
	  //   ...
	  // }

	  // 3) Group them by (event_name, category_name, gender)
	  const grouped = groupByEventCategoryGender(data.athletes);

	  // 4) Render them in sub-sections
	  renderGroupedAthletes(grouped);
	})
	.catch((err) => {
	  console.error("Error fetching athletes:", err);
	});

  /**
   * Groups the athlete array by event_name, category_name, and gender.
   * Returns an object like:
   * {
   *   [event_name]: {
   *     [category_name]: {
   *       [gender]: [ array of athletes ]
   *     }
   *   }
   * }
   */
  function groupByEventCategoryGender(athletes) {
	const grouped = {};

	for (const ath of athletes) {
	  const eventName    = ath.event_name    || "Unknown Event";
	  const categoryName = ath.category_name || "Unknown Category";
	  const gender       = ath.gender        || "U";  // "M", "F", or "U"

	  if (!grouped[eventName]) {
		grouped[eventName] = {};
	  }
	  if (!grouped[eventName][categoryName]) {
		grouped[eventName][categoryName] = {};
	  }
	  if (!grouped[eventName][categoryName][gender]) {
		grouped[eventName][categoryName][gender] = [];
	  }
	  grouped[eventName][categoryName][gender].push(ath);
	}

	return grouped;
  }

  /**
   * Renders a card for each (event -> category -> gender) group.
   */
  function renderGroupedAthletes(grouped) {
	const container = document.getElementById("container-lists");
	if (!container) {
	  console.error("No container-lists element found!");
	  return;
	}
	container.innerHTML = "";

	// We'll iterate over eventName keys, then categoryName keys, then gender keys
	for (const eventName of Object.keys(grouped).sort()) {
	  const categoriesObj = grouped[eventName];

	  for (const categoryName of Object.keys(categoriesObj).sort()) {
		const gendersObj = categoriesObj[categoryName];

		for (const gender of Object.keys(gendersObj).sort()) {
		  // Build the sub-list or table for these athletes
		  const subAthletes = gendersObj[gender];

		  // Create a card for these subAthletes
		  const card = document.createElement("div");
		  card.classList.add("card", "mb-3");

		  // Card header with "Competition results" or dynamic text
		  card.innerHTML = `
			<div class="card-header">
			  <h3 class="card-title">Competition Results</h3>
			  <h5 class="card-subtitle text-muted">
				Event: ${eventName} - ${categoryName} - ${gender === "M" ? "Men" : gender === "F" ? "Women" : gender}
			  </h5>
			</div>
		  `;

		  // Now build a table
		  const table = document.createElement("table");
		  table.classList.add("table", "table-striped", "table-sm");
		  table.innerHTML = `
			<thead>
			  <tr>
				<th>Athlete</th>
				<th>Country</th>
				<!-- add more columns as you need, e.g. Score, Placement, etc. -->
			  </tr>
			</thead>
			<tbody>
			  ${subAthletes
				.map((ath) => {
				  return `
					<tr>
					  <td>${ath.athlete_name || "Unknown Athlete"}</td>
					  <td>${ath.country || "N/A"}</td>
					</tr>
				  `;
				})
				.join("")}
			</tbody>
		  `;

		  const cardBody = document.createElement("div");
		  cardBody.classList.add("card-body");
		  cardBody.appendChild(table);

		  card.appendChild(cardBody);
		  container.appendChild(card);
		}
	  }
	}
  }
});