export const htmlResults = `
<div class="main d-flex items-center p-40 py-60">
  <div class="content_box">
	<div class="content r_space">
	  <!-- We'll place "EVENT + GROUP" in #resultsEventTitle below: -->
	  <p class="sub_title" id="resultsEventTitle">WORLD CHAMPIONSHIP OPEN MEN 2023</p>
	  <h2 class="title f_kazer_outline">RESULTS</h2>
	  <div class="wrap_table">
		<table class="table table_ranking table_ranking_r">
		  <thead>
			<tr>
			  <th>RANKING</th>
			  <th>SURNAME</th>
			  <th>NAME</th>
			  <th>BIRTHYEAR</th>
			  <th>COUNTRY</th>
			  <th>RUN 1</th>
			  <th>RUN 2</th>
			  <th></th>
			</tr>
		  </thead>
		  <tbody id="resultsTableBody">
			<!-- We'll fill these rows dynamically -->
		  </tbody>
		</table>
	  </div>
	  <p class="text_white fs_14 table_b_text">
		<span class="me-10">FRS = First Run Scores</span>
		<img width="15" src="img/tick-arrow.svg" alt="" /> = Qualified
	  </p>
	</div>
	<div class="sidebar">
	  <div>
		<img src="img/iwwf.png" alt="" />
	  </div>
	  <div>
		<img src="img/score.png" alt="" />
		<p class="text_royalblue fw_700" id="resultsClock">12:34:34</p>
	  </div>
	</div>
  </div>
</div>
`;

/**
 * initResults():
 *   - Called after the snippet is inserted by tv.js
 *   - Re-fetches the results API every 2s => re-render if changed
 *   - Possibly starts a live clock
 */
export function initResults() {
  console.log("[results.js] initResults() called.");

  // 1) Grab competitionCode from URL
  const urlParams = new URLSearchParams(window.location.search);
  const competitionCode = urlParams.get("competitionCode");
  if (!competitionCode) {
	console.warn("[results.js] No competitionCode => skipping results fetch.");
	return;
  }

  // 2) Hardcoded token for demonstration
  const STATIC_BEARER_TOKEN = "50afb255cfa3a36834e0a51185b1eb09";
  function getAuthHeaders() {
	return {
	  "Content-Type": "application/json",
	  "Authorization": `Bearer ${STATIC_BEARER_TOKEN}`,
	};
  }

  // Optionally start a clock for #resultsClock
  startLiveClock();

  // We'll store the old scoreboard data (as JSON string) to compare
  let previousScoreboardJson = null;

  /**
   * fetchAndRenderResults => calls the results API => compares => re-render if changed
   */
  function fetchAndRenderResults() {
	const resultsUrl = `
	  ${API_BASE_URL}?api=results
	  &competitionCode=${encodeURIComponent(competitionCode)}
	  &public=true
	`.replace(/\s+/g, "");

	fetch(resultsUrl, { headers: getAuthHeaders() })
	  .then((res) => {
		if (!res.ok) {
		  console.error("[results.js] Results API error", res.status, res.statusText);
		  return null;
		}
		return res.json();
	  })
	  .then((jsonData) => {
		if (!jsonData) {
		  console.warn("[results.js] No JSON data returned.");
		  return;
		}
		if (!jsonData.data || !jsonData.data.success) {
		  console.warn("[results.js] Unexpected or invalid results from API:", jsonData?.data?.error);
		  return;
		}

		const { data } = jsonData;

		// -----------------------------
		// 1) Check the active group
		// -----------------------------
		const activeRuns   = data.runs || [];
		const activeGroup  = data.active_group || {};

		// We'll define a helper to check if there's ANY actual score
		function hasAnyScore(runs) {
		  for (const ath of runs) {
			if (Array.isArray(ath.runs)) {
			  // if ANY run object has a numeric score > 0 => return true
			  for (const r of ath.runs) {
				if (typeof r.score === "number" && r.score > 0) {
				  return true;
				}
			  }
			}
		  }
		  return false;
		}

		const activeHasScores = hasAnyScore(activeRuns);

		// ---------------------------------------------
		// 2) If active group has NO scores,
		//    and previous_group_data exists => show it
		// ---------------------------------------------
		let scoreboardRuns  = activeRuns;
		let scoreboardGroup = activeGroup;

		if (!activeHasScores && data.previous_group_data) {
		  console.log("[results.js] Active group has NO scores => show PREVIOUS group instead!");
		  scoreboardRuns  = data.previous_group_data.runs || [];
		  scoreboardGroup = data.previous_group_data.previous_group || {};
		}

		// We'll need the group "qualify" to decide how many get the qualified icon
		const qualifyCount = (typeof scoreboardGroup.qualify === "number")
		  ? scoreboardGroup.qualify
		  : 0;

		// Build a title e.g. "WAKEBOARD GROUP 2"
		const eventTitleEl = document.getElementById("resultsEventTitle");
		if (eventTitleEl) {
		  const eventName = scoreboardGroup.event_name  || "";
		  const groupName = scoreboardGroup.group_name  || "";
		  eventTitleEl.textContent = (eventName + " " + groupName).toUpperCase();
		}

		// Convert scoreboardRuns plus qualifyCount to a string to compare
		const scoreboardObj = { scoreboardRuns, qualifyCount };
		const newScoreboardJson = JSON.stringify(scoreboardObj);

		if (newScoreboardJson !== previousScoreboardJson) {
		  console.log("[results.js] Scoreboard changed => re-rendering table.");
		  previousScoreboardJson = newScoreboardJson;
		  buildResultsTable(scoreboardRuns, qualifyCount);
		} else {
		  console.log("[results.js] Scoreboard unchanged => skip re-render.");
		}
	  })
	  .catch((err) => {
		console.error("[results.js] Error fetching results data:", err);
	  });
  }

  // 3) Immediately fetch => render
  fetchAndRenderResults();

  // 4) Then poll every 2s => compare
  setInterval(fetchAndRenderResults, 2000);
}

/**
 * startLiveClock():
 *   - Show the local time in #resultsClock
 */
function startLiveClock() {
  const clockEl = document.getElementById("resultsClock");
  if (!clockEl) {
	console.warn("[results.js] #resultsClock not found => no clock.");
	return;
  }
  function updateClock() {
	clockEl.textContent = new Date().toLocaleTimeString([], { hour12: false });
  }
  updateClock();
  setInterval(updateClock, 1000);
}

/**
 * buildResultsTable(runs, qualifyCount):
 *   - runs is an array of objects, each representing an athlete's final info
 *     e.g. { athlete_name, birthyear, country, placement, runs: [ {run_number, status, score}, ... ] }
 *   - qualifyCount is the integer => top X get the qualified icon
 */
function buildResultsTable(runs, qualifyCount) {
  const tbody = document.getElementById("resultsTableBody");
  if (!tbody) {
	console.warn("[results.js] #resultsTableBody not found => cannot fill table rows.");
	return;
  }
  // Clear existing rows
  tbody.innerHTML = "";

  // Sort by placement ascending
  runs.sort((a, b) => (a.placement || 9999) - (b.placement || 9999));

  runs.forEach((ath) => {
	const rank     = ath.placement || "";
	const athlete  = ath.athlete_name || "Unknown";
	const splitted = athlete.trim().split(" ");
	let lastName   = splitted.pop() || "";
	let firstName  = splitted.join(" ");
	if (!firstName) {
	  firstName = lastName;
	  lastName  = "";
	}

	const year     = ath.birthyear || "";
	const country  = ath.country   || "";
	let score1 = "", score2 = "";
	let arrowHTML  = ""; // We'll set this if rank <= qualifyCount

	// parse runs => get score1, score2 from run_number=1 or run_number=2
	if (Array.isArray(ath.runs)) {
	  ath.runs.forEach((r) => {
		if (r.run_number === 1) {
		  // If status=2 => "FRS"
		  if (r.status === 2) {
			score1 = "FRS";
		  } else if (r.score != null) {
			score1 = r.score.toFixed(2);
		  }
		} else if (r.run_number === 2) {
		  if (r.status === 2) {
			score2 = "FRS";
		  } else if (r.score != null) {
			score2 = r.score.toFixed(2);
		  }
		}
	  });
	}

	// If athlete’s placement is 1..qualifyCount => show arrow
	// e.g. if qualifyCount=2 => ranks 1 and 2 get arrow
	if (qualifyCount > 0 && rank > 0 && rank <= qualifyCount) {
	  arrowHTML = `<img src="img/tick-arrow.svg" alt="" />`;
	}

	const row = document.createElement("tr");
	row.innerHTML = `
	  <td>${rank}</td>
	  <td>${lastName}</td>
	  <td>${firstName}</td>
	  <td>${year}</td>
	  <td>${country}</td>
	  <td>${score1}</td>
	  <td>${score2}</td>
	  <td>${arrowHTML}</td>
	`;
	tbody.appendChild(row);
  });
}