document.addEventListener("DOMContentLoaded", function () {

  /*******************************************************
   * 1) Inject basic CSS for table & icons
   *******************************************************/
  const style = document.createElement("style");
  style.textContent = `
	.card-header {
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  padding: 0.5rem 1rem;
	}
	.card-body {
	  padding: 1rem;
	}
	.table {
	  width: 100%;
	  text-align: center;
	  border-collapse: collapse;
	}
	.table th {
	  font-weight: bold;
	}
	.table th,
	.table td {
	  padding: 0.75rem;
	  border-bottom: 1px solid #ddd;
	}
	.table tr.active-row {
	  background-color: #d1ecf1;
	}
	.bold-score {
	  font-weight: bold;
	}
	.q-badge {
	  display: inline-block;
	  background-color: #28a745;
	  color: white;
	  padding: 0.2rem 0.4rem;
	  font-size: 0.8rem;
	  border-radius: 5px;
	  font-weight: bold;
	}
	.badge-frs {
	  background-color: #ffc107;
	  color: black;
	  padding: 0.2rem 0.4rem;
	  font-size: 0.8rem;
	  border-radius: 5px;
	  font-weight: bold;
	}
	.badge-dns {
	  background-color: #007bff;
	  color: white;
	  padding: 0.2rem 0.4rem;
	  font-size: 0.8rem;
	  border-radius: 5px;
	  font-weight: bold;
	}
	.badge-dsq {
	  background-color: #dc3545;
	  color: white;
	  padding: 0.2rem 0.4rem;
	  font-size: 0.8rem;
	  border-radius: 5px;
	  font-weight: bold;
	}
	.bib-number {
	  font-size: 0.6em;
	  color: #666;
	  margin-left: 4px;
	}
	.cards-row {
	  display: flex;
	  flex-wrap: wrap;
	  gap: 1rem;
	  margin-top: 1rem;
	}
	/* Small note under the table */
	.qualify-note {
	  margin-top: 0.5rem;
	  font-weight: bold;
	  color: #6c757d; /* a dark gray or similar */
	}
	/* Success alert styling (optional) */
	.alert {
	  padding: 1rem;
	  margin: 1rem;
	  border-radius: 4px;
	}
	.alert-success {
	  background-color: #d4edda;
	  color: #155724;
	}
  `;
  document.head.appendChild(style);

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

  /*******************************************************
   * 2) Grab competition code from localStorage OR from 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.");
	  return;
	}
  }
  const competitionCode = storedCompetition.code;

  const localUser = JSON.parse(localStorage.getItem("user")) || {};
  const previousDataMap = new Map();
  const judgeContainerMap = new Map();

  /*******************************************************
   * 2A) Check if the entire competition is completed
   *******************************************************/
  async function checkCompetitionComplete() {
	try {
	  // If your endpoint returns every group's runs in a single response:
	  const url = `${API_BASE_URL}?api=results&competitionCode=${encodeURIComponent(
		competitionCode
	  )}&public=false`;

	  const resp = await fetch(url, { headers: getAuthHeaders() });
	  if (!resp.ok) {
		throw new Error(`HTTP error ${resp.status}`);
	  }
	  const data = await resp.json();
	  if (!data || !data.data || !data.data.runs) {
		console.warn("No runs array found in results data. Assuming not complete.");
		return false;
	  }

	  // allRuns is an array of athlete-level data with sub-runs. If grouped, flatten if needed.
	  const allRuns = data.data.runs;

	  // If ANY run has status=0 => not complete
	  const anyRunInProgress = allRuns.some((ath) =>
		ath.runs && ath.runs.some((r) => r.status === 0)
	  );
	  return !anyRunInProgress; // true if fully complete
	} catch (err) {
	  console.error("Error in checkCompetitionComplete:", err);
	  // If an error occurs, assume not complete (so we keep rendering).
	  return false;
	}
  }

  /*******************************************************
   * 3) Main function fetchAndRenderResultsForSection
   *******************************************************/
  function fetchAndRenderResultsForSection(container) {
	const section     = container.getAttribute("data-section") || "0";
	const publicFlag  = container.getAttribute("data-public")  || "false";
	const scheduleId  = container.getAttribute("data-schedule") || null;
	const groupNumber = container.getAttribute("data-group")    || null;

	// 1) If data-schedule & data-group => direct approach
	if (scheduleId && groupNumber) {
	  const directUrl = `${API_BASE_URL}?api=results&competitionCode=${encodeURIComponent(
		competitionCode
	  )}&scheduleId=${encodeURIComponent(scheduleId)}&group=${encodeURIComponent(groupNumber)}&public=${publicFlag}`;

	  fetch(directUrl, { method: "GET", headers: getAuthHeaders() })
		.then(resp => {
		  if (!resp.ok) {
			throw new Error("HTTP error " + resp.status);
		  }
		  return resp.json();
		})
		.then(data => {
		  if (!data || !data.data || !data.data.runs) {
			console.warn("No runs found for schedule/group =>", scheduleId, groupNumber);
			container.innerHTML = `<p>No results for schedule ${scheduleId}, group ${groupNumber}.</p>`;
			return;
		  }
		  const newDataStr = JSON.stringify(data.data.runs);
		  const oldDataStr = previousDataMap.get(container.id);

		  if (newDataStr !== oldDataStr) {
			renderResultsCard(
			  container,
			  data.data.active_group,
			  data.data.active_athlete,
			  data.data.runs,
			  null
			);
			previousDataMap.set(container.id, newDataStr);
		  }
		})
		.catch(err => {
		  console.error("Error fetching direct schedule/group results:", err);
		  container.innerHTML = `<p class="text-danger">Error loading direct results for Schedule #${scheduleId}, Group #${groupNumber}.</p>`;
		});
	  return; 
	}

	// 2) If schedule/group not present => fallback logic
	if (section === "1") {
	  let parentDiv = container.querySelector(".cards-row");
	  if (!parentDiv) {
		container.innerHTML = "";
		parentDiv = document.createElement("div");
		parentDiv.classList.add("cards-row");
		container.appendChild(parentDiv);
	  }

	  fetchActiveRunOfficials(competitionCode)
		.then((judgeIds) => {
		  judgeIds.sort((a, b) => a - b);
		  if (!judgeIds || judgeIds.length === 0) {
			console.warn("No officials found => skipping scoreboard fetch for data-section=1.");
			return;
		  }
		  judgeIds.forEach((judgeId) => {
			const key = `${container.id}_${judgeId}`;
			const fetchUrl = `${API_BASE_URL}?api=results&competitionCode=${encodeURIComponent(
			  competitionCode
			)}&public=false&judgeId=${judgeId}`;

			fetch(fetchUrl, { 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 || !data.data.runs) {
				  console.warn("No runs for judge iwwf_id=", judgeId);
				  return;
				}
				const newDataStr = JSON.stringify(data.data.runs);
				const oldDataStr = previousDataMap.get(key);

				if (!judgeContainerMap.has(judgeId)) {
				  const subContainer = document.createElement("div");
				  parentDiv.appendChild(subContainer);
				  judgeContainerMap.set(judgeId, subContainer);
				}
				const subCardContainer = judgeContainerMap.get(judgeId);

				if (newDataStr !== oldDataStr) {
				  renderResultsCard(
					subCardContainer,
					data.data.active_group,
					data.data.active_athlete,
					data.data.runs,
					judgeId
				  );
				  previousDataMap.set(key, newDataStr);
				}
			  })
			  .catch(err => {
				console.error("Error fetching scoreboard data for judge=", judgeId, err);
			  });
		  });
		})
		.catch(err => {
		  console.error("Error in fetchActiveRunOfficials:", err);
		});
	} else {
	  // data-section != "1" => normal single scoreboard approach
	  let judgeId = null;
	  if (section === "2") {
		judgeId = localUser.iwwf_id || null;
	  } else if (section !== "0") {
		judgeId = parseInt(section, 10);
	  }

	  const type = judgeId ? "judge" : "overall";
	  let url = `${API_BASE_URL}?api=results&competitionCode=${encodeURIComponent(
		competitionCode
	  )}&public=${publicFlag}`;
	  if (type === "judge") {
		url += `&judgeId=${judgeId}`;
	  }

	  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 || !data.data.runs) {
			console.error("No runs found for scoreboard data.");
			return;
		  }
		  const key = container.id;
		  const newDataStr = JSON.stringify(data.data.runs);
		  const oldDataStr = previousDataMap.get(key);

		  if (newDataStr !== oldDataStr) {
			renderResultsCard(
			  container,
			  data.data.active_group,
			  data.data.active_athlete,
			  data.data.runs,
			  judgeId
			);
			previousDataMap.set(key, newDataStr);
		  }
		})
		.catch(error => {
		  console.error("Error fetching scoreboard data:", error);
		});
	}
  }

  /*******************************************************
   * fetchActiveRunOfficials => returns judge iwwf_ids
   *******************************************************/
  function fetchActiveRunOfficials(competitionCode) {
	return fetch(`${API_BASE_URL}?api=schedule&competitionCode=${encodeURIComponent(competitionCode)}&public=false&scores=true`, {
	  method: "GET",
	  headers: getAuthHeaders()
	})
	  .then(res => {
		if (!res.ok) {
		  throw new Error("HTTP error " + res.status);
		}
		return res.json();
	  })
	  .then(data => {
		if (!data || !Array.isArray(data.data)) {
		  console.warn("Invalid schedule data or no .data");
		  return [];
		}
		// find item with active run
		const activeSched = data.data.find(s => s.runs && s.runs.some(r => r.active === 1));
		if (!activeSched || !Array.isArray(activeSched.officials)) {
		  console.warn("No active schedule item with officials array.");
		  return [];
		}
		const judgeIds = activeSched.officials
		  .map(off => off.iwwf_id)
		  .filter(id => id && id.length > 0);
		return judgeIds;
	  })
	  .catch(err => {
		console.error("Error in fetchActiveRunOfficials:", err);
		return [];
	  });
  }

  /*******************************************************
   * 4) Renders a single results card in container
   *******************************************************/
  function renderResultsCard(container, activeGroup, activeAthlete, runs, judgeId = null) {
	container.innerHTML = "";

	// If ANY athlete_id is null => show an alert & skip
	const anyNullAthlete = runs.some(a => a.athlete_id === null);
	if (anyNullAthlete) {
	  container.innerHTML = `
		<div class="alert-primary">
		  Startlists will be visible after finishing the previous round.
		</div>
	  `;
	  return;
	}

	const card = document.createElement("div");
	card.classList.add("card", "mb-4", "mobile-optimized-card");

	let judgeDisplayName = "Unknown Judge";
	let judgeNumber      = "??";
	if (judgeId && activeGroup?.officials?.length) {
	  const foundOfficial = activeGroup.officials.find((off) => off.iwwf_id === judgeId);
	  if (foundOfficial && foundOfficial.official_name) {
		judgeDisplayName = foundOfficial.official_name;
		judgeNumber      = foundOfficial.judge_number;
	  }
	}
	
	// Decide the badge for event_name
	let event_name = (activeGroup?.event_name || "UN");
	let eventBadge = "";
	if (event_name === "Wakeboard") {
	  eventBadge = `<span class="badge bg-primary me-2">WB</span>`;
	} else if (event_name === "Wakeskate") {
	  eventBadge = `<span class="badge bg-danger me-2">WS</span>`;
	}else if (event_name === "Wakeboard Seated") {
	  eventBadge = `<span class="badge bg-warning me-2">ST</span>`;
	}

	const liveBadge = `<span class="badge bg-danger me-2">LIVE</span>`;
	const title = judgeId 
	  ? `Judge ${judgeNumber}`
	  : `${eventBadge} ${activeGroup?.group_name || "No Group"}`;

	const groupTitle = judgeId
	  ? judgeDisplayName
	  : activeGroup
		? `${liveBadge}Group ${activeGroup.group}`
		: `${liveBadge}No Group Info`;

	const qualifyLimit = activeGroup?.qualify || 0;

	// Build the table
	const tableHTML = `
	  <table class="table table-striped table-hover table-sm">
		<thead>
		  <tr>
			<th>P</th>
			<th class="text-start">Nat</th>
			<th class="text-start">Athlete</th>
			<th>Run 1</th>
			<th>Run 2</th>
			<th></th>
		  </tr>
		</thead>
		<tbody>
		  ${generateRunsRows(runs, activeAthlete?.id || null, qualifyLimit)}
		</tbody>
	  </table>
	`;

	// Possibly add the "Top X" or "All" note
	let qualifyNote = "";
	if (qualifyLimit > 0) {
	  const totalAthletes = runs.length;
	  if (qualifyLimit === totalAthletes) {
		qualifyNote = `<div class="qualify-note">All into next round</div>`;
	  } else {
		qualifyNote = `<div class="qualify-note">Top ${qualifyLimit} into next round</div>`;
	  }
	}

	card.innerHTML = `
	  <div class="card-header">
		<h3 class="flex-column align-items-start card-title">
		  <span class="fw-bold text-dark card-label">${title}</span>
		  <span class="fw-semibold text-muted mt-1 fs-7">${groupTitle}</span>
		</h3>
	  </div>
	  <div class="card-body">
		${tableHTML}
		${qualifyNote}
	  </div>
	`;

	container.appendChild(card);
  }

  /*******************************************************
   * 5) Build row HTML
   *******************************************************/
  function generateRunsRows(runs, activeAthleteId, qualifyLimit) {
	const scoresWithPlacements = runs.map((athlete) => {
	  const run1 = athlete.runs.find(r => r.run_number === 1);
	  let run2   = athlete.runs.find(r => r.run_number === 2);

	  if (athlete.athlete_id === null && run2 && run2.run_number === 2) {
		run2 = null;
	  }
	  const isDSQ = (run1 && run1.status === 4) || (run2 && run2.status === 4);

	  const validScores = isDSQ
		? []
		: athlete.runs
			.filter(r => !(athlete.athlete_id === null && r.run_number === 2))
			.map(r => (r.score !== null ? r.score : 0));

	  const highestScore = validScores.length > 0 ? Math.max(...validScores) : null;
	  return {
		athlete_id:   athlete.athlete_id,
		athlete_name: athlete.athlete_name,
		bib:          athlete.bib,
		country:      athlete.country,
		highestScore,
		isDSQ,
		run1,
		run2
	  };
	});

	// Sort desc, DSQ last
	scoresWithPlacements.sort((a,b) => {
	  if (a.isDSQ && !b.isDSQ) return 1;
	  if (!a.isDSQ && b.isDSQ) return -1;
	  if (a.highestScore === null) return 1;
	  if (b.highestScore === null) return -1;
	  return b.highestScore - a.highestScore;
	});

	// Assign placements
	const athletePlacements = {};
	let currentPlacement = 1;
	for (let i = 0; i < scoresWithPlacements.length; i++) {
	  const cur  = scoresWithPlacements[i];
	  const prev = scoresWithPlacements[i - 1];
	  if (cur.isDSQ || cur.highestScore === null) {
		athletePlacements[cur.athlete_id] = null;
		continue;
	  }
	  if (prev && cur.highestScore === prev.highestScore) {
		athletePlacements[cur.athlete_id] = athletePlacements[prev.athlete_id];
	  } else {
		athletePlacements[cur.athlete_id] = currentPlacement;
	  }
	  currentPlacement++;
	}

	// Build table rows
	return scoresWithPlacements
	  .map(item => {
		const rowClass  = (item.athlete_id === activeAthleteId) ? "active-row" : "";
		const placement = athletePlacements[item.athlete_id] || "-";

		const run1Display = buildRunDisplay(item.run1);
		const run2Display = buildRunDisplay(item.run2);
		const qualifies   = (placement !== "-") && (placement <= qualifyLimit);
		const bibNumber   = item.bib ? `<span class="bib-number">(${item.bib})</span>` : "";

		return `
		  <tr class="${rowClass}">
			<td>${placement}</td>
			<td class="text-start">${item.country}</td>
			<td class="text-start">${item.athlete_name || "Unknown"}${bibNumber}
			</td>
			<td>${run1Display}</td>
			<td>${run2Display}</td>
			<td>${qualifies ? '<span class="q-badge">Q</span>' : ''}</td>
		  </tr>
		`;
	  })
	  .join("");
  }

  /*******************************************************
   * buildRunDisplay
   *******************************************************/
  function buildRunDisplay(run) {
	if (!run) return "-";
	if (run.status === null) return "-";

	if (run.status === 2) return `<span class="badge-frs">FRS</span>`;
	if (run.status === 3) return `<span class="badge-dns">DNS</span>`;
	if (run.status === 4) return `<span class="badge-dsq">DSQ</span>`;
	return run.score !== null ? run.score : "-";
  }

  /*******************************************************
   * 7) fetchAndRenderAllResults => finds containers & calls
   *******************************************************/
  async function fetchAndRenderAllResults() {
	// 1) Check if competition is complete
	const isComplete = await checkCompetitionComplete();
	const resultContainers = document.querySelectorAll('[data-type="kt_app_content_container_results"]');
	
	if (isComplete) {
	  // 2) If complete => STILL show containers with direct approach
	  //    Hide all the other scoreboard containers
	  resultContainers.forEach((container) => {
		const scheduleId  = container.getAttribute("data-schedule");
		const groupNumber = container.getAttribute("data-group");
		
		if (scheduleId && groupNumber) {
		  // Direct approach container => always show & render results
		  container.style.display = "block";
		  fetchAndRenderResultsForSection(container);
		} else {
		  // Normal container => hide
		  container.style.display = "none";
		}
	  });
	  return; 
	}

	// 3) If not complete, do your normal scoreboard rendering
	resultContainers.forEach((container) => {
	  container.style.display = "block";
	  fetchAndRenderResultsForSection(container);
	});
  }

  // Auto-refresh every 2 seconds
  setInterval(fetchAndRenderAllResults, 2000);

  // Initial call
  fetchAndRenderAllResults();
});