export const htmlSmallResults = `
<div class="small-results-container">
  <h4 id="smallResultsTitle">RESULTS</h4>
  <table class="table table-sm" id="smallResultsTable">
	<thead>
	  <tr>
		<th>#</th>
		<th>Athlete</th>
		<th>Score</th>
	  </tr>
	</thead>
	<tbody id="smallResultsTbody">
	  <!-- Filled dynamically -->
	</tbody>
  </table>
</div>
`;

export function initSmallResults() {
  console.log("[smallResults.js] initSmallResults() called.");

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

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

  // 3) We'll store the last results JSON to see if anything changed
  let prevResultsJson = null;

  function fetchAndRender() {
	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("[smallResults] fetch error:", res.status, res.statusText);
		  return null;
		}
		return res.json();
	  })
	  .then((json) => {
		if (!json || !json.data) {
		  console.warn("[smallResults] invalid JSON from results API");
		  return;
		}
		const { data } = json;
		if (!data.runs) {
		  console.warn("[smallResults] No .runs array in data => no scoreboard");
		  return;
		}

		// Possibly check "active group" or "previous group"
		// For brevity: we just show data.runs as is
		const scoreboardRuns = data.runs;
		const scoreboardGroup = data.active_group || {};

		const newResults = { scoreboardRuns, scoreboardGroup };
		const newJson = JSON.stringify(newResults);
		if (newJson !== prevResultsJson) {
		  prevResultsJson = newJson;
		  buildSmallResults(scoreboardRuns, scoreboardGroup);
		} else {
		  // unchanged => skip
		}
	  })
	  .catch((err) => {
		console.error("[smallResults] error fetching results:", err);
	  });
  }

  // 4) fetch right away, then poll every 2s
  fetchAndRender();
  setInterval(fetchAndRender, 2000);
}

/**
 * buildSmallResults(runs, groupInfo)
 *  - draws just rank, name, final/best score in a minimal table
 */
function buildSmallResults(runs, groupInfo) {
  const titleEl = document.getElementById("smallResultsTitle");
  const tbodyEl = document.getElementById("smallResultsTbody");
  if (!tbodyEl) {
	console.warn("[smallResults] #smallResultsTbody not found");
	return;
  }

  // e.g. show “WS Open Ladies Qualifications (Group 1)”
  let displayName = (groupInfo.event_name || "") + " " + (groupInfo.group_name || "");
  displayName = displayName.trim() || "Live Results";
  titleEl.textContent = displayName.toUpperCase();

  // Clear
  tbodyEl.innerHTML = "";

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

  // For a minimal scoreboard, we’ll combine run1 & run2 => best
  runs.forEach((ath) => {
	const rank    = ath.placement || "";
	const athName = ath.athlete_name || "Unknown";
	let bestScore = 0;

	if (Array.isArray(ath.runs)) {
	  ath.runs.forEach((r) => {
		// If numeric => update bestScore if higher
		if (typeof r.score === "number" && r.score > bestScore) {
		  bestScore = r.score;
		}
	  });
	}

	const row = document.createElement("tr");
	row.innerHTML = `
	  <td>${rank}</td>
	  <td>${athName}</td>
	  <td>${bestScore > 0 ? bestScore.toFixed(2) : "-"}</td>
	`;
	tbodyEl.appendChild(row);
  });
}