export const htmlResultsSmall = `
<div class="main p-40 py-40 content_end ps-0">
  <div class="content_box">
	<div class="page10_bottom_box">
	  <div class="left_box">
		<div class="bg_royalblue text_white page10_padding_box">
		  <div class="page16_bottom_grid page16_bottom_grid2">
			<div class="box_1">
			  <h3 class="fs_48 f_kazer_outline">RESULTS</h3>
			</div>
			<div class="box_2" id="resultsSmallContainer">
			  <!-- We'll dynamically fill these columns/rows for up to 8 athletes -->
			</div>
		  </div>
		</div>
		<div class="bg_cyan page10_padding_box">
		  <p class="fw_700 text_royalblue" id="resultsSmallTitle">WORLD CHAMPIONSHIP OPEN MEN 2023</p>
		</div>
	  </div>
	  <div class="right_box">
		<div class="box">
		  <img src="img/iwwf.png" class="page16_b_img" alt="">
		</div>
		<div class="bottom_box">
		  <p class="fw_700 text_royalblue" id="resultsSmallClock">12:34:34</p>
		</div>
	  </div>
	</div>
  </div>
</div>
`;

/**
 * initResultsSmall():
 *  1) Read competitionCode from URL
 *  2) Fetch ?api=results&competitionCode=...&public=true
 *  3) Sort data by placement
 *  4) Show up to 8 athletes, splitted into left column (4) & right column (4)
 *  5) For each athlete => display name + arrow if rank <= qualify, and "SCORE 1 / SCORE 2"
 */
export function initResultsSmall() {
  console.log("[results_small.js] initResultsSmall() called.");

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

  // Start the small clock
  startLiveClock();

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

  // 3) Fetch the results data
  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_small.js] Results API error", res.status, res.statusText);
		return null;
	  }
	  return res.json();
	})
	.then((jsonData) => {
	  if (!jsonData) {
		console.warn("[results_small.js] No JSON data returned.");
		return;
	  }
	  if (!jsonData.data || !jsonData.data.success) {
		console.warn("[results_small.js] Unexpected or invalid results from API:", jsonData?.data?.error);
		return;
	  }

	  const { data } = jsonData;
	  const scoreboardRuns = data.runs || [];
	  
	  // Check how many qualify
	  let qualifyCount = 0;
	  if (data.active_group && typeof data.active_group.qualify === "number") {
		qualifyCount = data.active_group.qualify;
	  }

	  // Possibly set the #resultsSmallTitle to event + group
	  const titleEl = document.getElementById("resultsSmallTitle");
	  if (titleEl && data.active_group) {
		const evName  = data.active_group.event_name  || "";
		const grpName = data.active_group.group_name || "";
		titleEl.textContent = (evName + " " + grpName).toUpperCase();
	  }

	  // Build out the custom layout
	  buildResultsSmallLayout(scoreboardRuns, qualifyCount);
	})
	.catch((err) => {
	  console.error("[results_small.js] Error fetching results data:", err);
	});
}

/**
 * startLiveClock():
 *  - updates #resultsSmallClock with local time
 */
function startLiveClock() {
  const clockEl = document.getElementById("resultsSmallClock");
  if (!clockEl) {
	console.warn("[results_small.js] #resultsSmallClock not found => no clock.");
	return;
  }

  function updateClock() {
	clockEl.textContent = new Date().toLocaleTimeString([], { hour12: false });
  }
  updateClock();
  setInterval(updateClock, 1000);
}

/**
 * buildResultsSmallLayout(runs, qualifyCount):
 *  - We'll sort by placement, show up to 8 athletes in two sets of columns (4 left, 4 right).
 *  - Each athlete => "Name + arrow if qualified" => "Scores: run1 / run2"
 */
function buildResultsSmallLayout(runs, qualifyCount) {
  // Sort by placement
  runs.sort((a, b) => (a.placement || 9999) - (b.placement || 9999));

  // We'll take up to 8
  const top8 = runs.slice(0, 8);

  // Container
  const containerEl = document.getElementById("resultsSmallContainer");
  if (!containerEl) {
	console.warn("[results_small.js] #resultsSmallContainer not found => cannot build layout.");
	return;
  }

  // Clear
  containerEl.innerHTML = "";

  // We want 2 sets: left(4), right(4)
  const first4 = top8.slice(0, 4);
  const next4  = top8.slice(4, 8);

  // We will create:
  //  <div class="inner_box_1" id="leftNamesScores"></div>
  //  <div class="inner_box_1" id="rightNamesScores"></div>
  // to replicate your snippet style
  const leftNamesScores  = document.createElement("div");
  leftNamesScores.classList.add("inner_box_1");
  const rightNamesScores = document.createElement("div");
  rightNamesScores.classList.add("inner_box_1");

  //
  // Fill the first 4 => leftNamesScores
  //
  first4.forEach((ath) => {
	// parse name
	const splitted = (ath.athlete_name || "Unknown").trim().split(" ");
	let lastName   = splitted.pop() || "";
	let firstName  = splitted.join(" ");
	if (!firstName) {
	  firstName = lastName;
	  lastName  = "";
	}
	let arrowStr = "";
	if (ath.placement && ath.placement <= qualifyCount) {
	  arrowStr = " <img src='img/tick-arrow.svg' style='height:12px;' />";
	}
	const displayName = (firstName + " " + lastName + arrowStr).trim();

	// gather run1 + run2 => e.g. "SCORE 85.00 / 90.00"
	let run1Score = "", run2Score = "";
	if (Array.isArray(ath.runs)) {
	  const r1 = ath.runs.find((r) => r.run_number === 1);
	  const r2 = ath.runs.find((r) => r.run_number === 2);

	  if (r1) {
		if (r1.status === 2) run1Score = "FRS";
		else if (r1.score != null) run1Score = r1.score.toFixed(2);
	  }
	  if (r2) {
		if (r2.status === 2) run2Score = "FRS";
		else if (r2.score != null) run2Score = r2.score.toFixed(2);
	  }
	}
	let scoreStr = "SCORE ";
	if (run1Score || run2Score) {
	  scoreStr += (run1Score || "--") + " / " + (run2Score || "--");
	} else {
	  scoreStr += "-- / --";
	}

	// Add <p> lines for name + score
	leftNamesScores.innerHTML += `
	  <p>${displayName}</p>
	  <p>${scoreStr}</p>
	`;
  });

  //
  // Fill next 4 => rightNamesScores
  //
  next4.forEach((ath) => {
	const splitted = (ath.athlete_name || "Unknown").trim().split(" ");
	let lastName   = splitted.pop() || "";
	let firstName  = splitted.join(" ");
	if (!firstName) {
	  firstName = lastName;
	  lastName  = "";
	}
	let arrowStr = "";
	if (ath.placement && ath.placement <= qualifyCount) {
	  arrowStr = " <img src='img/tick-arrow.svg' style='height:12px;' />";
	}
	const displayName = (firstName + " " + lastName + arrowStr).trim();

	let run1Score = "", run2Score = "";
	if (Array.isArray(ath.runs)) {
	  const r1 = ath.runs.find((r) => r.run_number === 1);
	  const r2 = ath.runs.find((r) => r.run_number === 2);

	  if (r1) {
		if (r1.status === 2) run1Score = "FRS";
		else if (r1.score != null) run1Score = r1.score.toFixed(2);
	  }
	  if (r2) {
		if (r2.status === 2) run2Score = "FRS";
		else if (r2.score != null) run2Score = r2.score.toFixed(2);
	  }
	}
	let scoreStr = "SCORE ";
	if (run1Score || run2Score) {
	  scoreStr += (run1Score || "--") + " / " + (run2Score || "--");
	} else {
	  scoreStr += "-- / --";
	}

	// Add <p> lines
	rightNamesScores.innerHTML += `
	  <p>${displayName}</p>
	  <p>${scoreStr}</p>
	`;
  });

  // Finally add them to container
  containerEl.appendChild(leftNamesScores);
  containerEl.appendChild(rightNamesScores);
}