/*******************************************************
 * teams_results.js
 * Example code for generating an "Overall Team Results"
 * card grouped by country, with final placements & points,
 * now respecting athlete.status:
 *  - If status=1 => add points to team total
 *  - If status=0 => visually lighten the row using opacity,
 *    and do not count those points in the team total.
 *******************************************************/
document.addEventListener("DOMContentLoaded", function () {
	  
  /*******************************************************
   * 1) Inject basic CSS for table & styling
   *******************************************************/
  const style = document.createElement("style");
  style.textContent = `
	.card {
	  border: 1px solid #ddd;
	  border-radius: 4px;
	  margin-bottom: 1rem;
	}
	.card-header {
	  display: flex;
	  align-items: center;
	  background-color: #f5f5f5;
	  padding: 0.5rem 1rem;
	  border-bottom: 1px solid #ddd;
	}
	.card-title {
	  margin: 0;
	  font-size: 1.25rem;
	}
	.card-body {
	  padding: 1rem;
	}
	.table {
	  width: 100%;
	  text-align: center;
	  border-collapse: collapse;
	  margin-bottom: 0;
	}
	.table th {
	  font-weight: bold;
	  background-color: #fafafa;
	}
	.table th,
	.table td {
	  padding: 0.6rem;
	  border-bottom: 1px solid #ddd;
	}
	.table .country-row {
	  background-color: #eef;
	  font-weight: bold;
	}
	.table .total-row {
	  background-color: #f9f9f9;
	  font-style: italic;
	}
	.bold-score {
	  font-weight: bold;
	}
	/* Additional badges if needed */
	.badge {
	  display: inline-block;
	  padding: 0.2rem 0.4rem;
	  font-size: 0.75rem;
	  border-radius: 4px;
	}
	.badge-gold {
	  background-color: #ffd700;
	  color: #000;
	}
	.badge-silver {
	  background-color: #c0c0c0;
	  color: #000;
	}
	.badge-bronze {
	  background-color: #cd7f32;
	  color: #000;
	}
	/* A container to place the card */
	.teams-result-container {
	  margin-top: 1rem;
	}
	/* Use opacity for status=0 rows */
	.status-zero {
	  opacity: 0.3;
	}
  `;
  document.head.appendChild(style);

  /*******************************************************
   * 2) Helper: produce static Bearer token in fetch
   *******************************************************/
  function getAuthHeaders() {
	return {
	  "Content-Type": "application/json",
	  "Authorization": "Bearer 50afb255cfa3a36834e0a51185b1eb09"
	};
  }

  /*******************************************************
   * 3) Get the competition code (from localStorage or URL)
   *******************************************************/
  let storedCompetition = JSON.parse(localStorage.getItem("activeCompetition"));
  if (!storedCompetition || !storedCompetition.code) {
	console.warn("No active competition found in localStorage. Checking URL...");
	const urlParams = new URLSearchParams(window.location.search);
	const competitionCodeFromURL = urlParams.get("CompetitionCode");
	if (competitionCodeFromURL) {
	  storedCompetition = { code: competitionCodeFromURL };
	  console.log("Using competitionCode from URL:", competitionCodeFromURL);
	} else {
	  console.error("No competition code found. Cannot proceed to fetch team results.");
	  return;
	}
  }
  const competitionCode = storedCompetition.code;

  /*******************************************************
   * 4) Where to render the results?
   *******************************************************/
  const container = document.getElementById("team-container");
  if (!container) {
	console.error('No element with id="team-container" found. Exiting.');
	return;
  }

  /*******************************************************
   * 5) Main fetch function => get team results
   *******************************************************/
  function fetchTeamResults() {
	const url = `${API_BASE_URL}?api=teamResults&competitionCode=${encodeURIComponent(
	  competitionCode
	)}`;

	fetch(url, { method: "GET", headers: getAuthHeaders() })
	  .then(response => {
		if (!response.ok) {
		  throw new Error("HTTP error " + response.status);
		}
		return response.json();
	  })
	  .then(data => {
		if (!data || !data.data || !Array.isArray(data.data)) {
		  console.error("No valid team results found. Data:", data);
		  container.innerHTML = `<p class="text-danger">No team results available.</p>`;
		  return;
		}
		// Render the card with the fetched data
		renderTeamResultsCard(container, data.data);
	  })
	  .catch(error => {
		console.error("Error fetching team results:", error);
		container.innerHTML = `<p class="text-danger">Error loading team results.</p>`;
	  });
  }

  /*******************************************************
   * 6) Render function => build a card with a table
   *******************************************************/
  function renderTeamResultsCard(parentEl, teamData) {
	parentEl.innerHTML = ""; // clear old content

	const card = document.createElement("div");
	card.classList.add("card", "teams-result-container");

	// Card Header
	const header = document.createElement("div");
	header.classList.add("card-header");
	header.innerHTML = `<h3 class="card-title">Overall Team Results</h3>`;

	// Card Body
	const body = document.createElement("div");
	body.classList.add("card-body");

	// We'll compute a local "team_points" ourselves:
	teamData.forEach(team => {
	  // Sum only status=1 athlete points
	  let localSum = 0;
	  if (team.athletes && Array.isArray(team.athletes)) {
		team.athletes.forEach(ath => {
		  if (ath.status === 1) {
			localSum += (ath.ranking_points || 0);
		  }
		});
	  }
	  // Store in a new property => local_computed_points
	  team.local_computed_points = localSum;
	});

	// 1) Sort teams by local_computed_points descending
	teamData.sort((a, b) => (b.local_computed_points || 0) - (a.local_computed_points || 0));

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

	// Table Head (includes "Event" & "Category")
	table.innerHTML = `
	  <thead>
		<tr>
		  <th>#</th>
		  <th class="text-start">Country</th>
		  <th class="text-start">Athlete</th>
		  <th>Event</th>
		  <th>Category</th>
		  <th>Final Placement</th>
		  <th>Points</th>
		</tr>
	  </thead>
	  <tbody></tbody>
	`;
	const tbody = table.querySelector("tbody");

	let rank = 1;
	// 2) Render each team block
	teamData.forEach(team => {
	  // Team row
	  const countryRow = document.createElement("tr");
	  countryRow.classList.add("country-row");
	  // We'll use our computed sum
	  countryRow.innerHTML = `
		<td>${rank}</td>
		<td class="text-start">${team.country_name || "Unknown"}</td>
		<td colspan="5">Team Total Points: ${team.local_computed_points || 0}</td>
	  `;
	  tbody.appendChild(countryRow);
	
	  // Sort the athletes within this team by ranking_points descending
	  const athletesCopy = (team.athletes || []).slice();
	  athletesCopy.sort((a, b) => (b.ranking_points || 0) - (a.ranking_points || 0));
	
	  // For each athlete => add row
	  athletesCopy.forEach(ath => {
		const tr = document.createElement("tr");
	
		if (ath.status === 0) {
		  // Instead of coloring, we use an opacity
		  tr.style.opacity = "0.3";
		}
	
		tr.innerHTML = `
		  <td></td>
		  <td class="text-start">${team.country_name || "Unknown"}</td>
		  <td class="text-start">${ath.athlete_name || "N/A"}</td>
		  <td>${ath.event_name || "N/A"}</td>
		  <td>${ath.category_name || "N/A"}</td>
		  <td>${ath.final_placement || "-"}</td>
		  <td>${ath.ranking_points || 0}</td>
		`;
		tbody.appendChild(tr);
	  });
	
	  rank++;
	});

	body.appendChild(table);
	card.appendChild(header);
	card.appendChild(body);
	parentEl.appendChild(card);
  }

  /*******************************************************
   * 7) Fetch the team results (no auto-refresh)
   *******************************************************/
  fetchTeamResults();
});