export const htmlStartlist = `
<div class="main d-flex items-center p-40 py-60">
  <div class="content_box">
	<div class="content r_space">
	  <p class="sub_title" id="startlistEventTitle">WORLD CHAMPIONSHIP OPEN MEN 2023</p>
	  <h2 class="title f_kazer_outline" id="startlistGroupName">STARTING LIST</h2>
	  <div class="wrap_table">
		<table class="table table_ranking">
		  <thead>
			<tr>
			  <th>ORDER</th>
			  <th class="text-start">SURNAME</th>
			  <th class="text-start">NAME</th>
			  <th>BIRTHYEAR</th>
			  <th>COUNTRY</th>
			  <th></th>
			</tr>
		  </thead>
		  <tbody id="startlistTableBody">
			<!-- We will dynamically fill these rows from the schedule API -->
		  </tbody>
		</table>
	  </div>
	</div>
	<div class="sidebar">
	  <div>
		<img src="img/iwwf.png" alt="" />
	  </div>
	  <div>
		<img src="img/score.png" alt="" />
		<!-- Optionally a clock or any info can go here -->
		<p class="text_royalblue fw_700" id="startlistClock">12:34:34</p>
	  </div>
	</div>
  </div>
</div>
`;

/**
 * initStartlist():
 *   - Called after this snippet is inserted by tv.js
 *   - Re-fetches the schedule API every 2s => re-render if changed
 *   - Finds the "active" group's run=1 => builds table
 *   - Starts a live clock if wanted
 */
export function initStartlist() {
  console.log("[startlist.js] initStartlist() called.");

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

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

  // 3) Start a live clock for #startlistClock
  startLiveClock();

  // We'll track the old data (startlist runs) to compare
  let previousStartlistJson = null;

  /**
   * fetchAndRenderStartlist => calls schedule API => finds active group => run=1 => re-render if changed
   */
  function fetchAndRenderStartlist() {
	const scheduleUrl = `${API_BASE_URL}?api=schedule&competitionCode=${encodeURIComponent(
	  competitionCode
	)}&public=true&scores=false`;

	fetch(scheduleUrl, { headers: getAuthHeaders() })
	  .then((res) => {
		if (!res.ok) {
		  console.error("[startlist.js] Schedule API responded with", res.status, res.statusText);
		  return null;
		}
		return res.json();
	  })
	  .then((jsonData) => {
		if (!jsonData) {
		  console.warn("[startlist.js] No schedule data returned.");
		  return;
		}

		if (!Array.isArray(jsonData.data)) {
		  console.warn("[startlist.js] schedule API returned unexpected format:", jsonData);
		  return;
		}

		const schedules = jsonData.data;
		if (!schedules.length) {
		  console.log("[startlist.js] No schedules found => nothing to display.");
		  return;
		}

		// Find a schedule with an active run (r.active === 1)
		let chosenSchedule = null;
		for (const sched of schedules) {
		  if (sched.runs && sched.runs.some((r) => r.active === 1)) {
			chosenSchedule = sched;
			break;
		  }
		}
		// If we still don’t find any => fallback to the first
		if (!chosenSchedule) {
		  [chosenSchedule] = schedules;
		}

		// Update #startlistEventTitle / #startlistGroupName
		const eventTitleEl = document.getElementById("startlistEventTitle");
		const groupNameEl  = document.getElementById("startlistGroupName");
		if (eventTitleEl && chosenSchedule.event_name) {
		  eventTitleEl.textContent = chosenSchedule.event_name.toUpperCase();
		}
		if (groupNameEl && chosenSchedule.category_name && chosenSchedule.heatsystem_name) {
		  const cat  = chosenSchedule.category_name;
		  const heat = chosenSchedule.heatsystem_name;
		  groupNameEl.textContent = `${cat} ${heat} STARTLIST`.toUpperCase();
		}

		// Find the active group
		let activeGroupId = null;
		if (chosenSchedule.runs) {
		  const foundActiveRun = chosenSchedule.runs.find((r) => r.active === 1);
		  if (foundActiveRun) {
			activeGroupId = foundActiveRun.group;
		  }
		}

		// If no active group => fallback or skip
		if (!activeGroupId) {
		  console.warn("[startlist.js] No active group found => fallback or skip rendering...");
		  // If you want to skip rendering => return;
		  // Or fallback to the first run's group or all run=1
		}

		// Filter the schedule’s runs => only active group & run=1
		const relevantRuns = (chosenSchedule.runs || []).filter(
		  (r) => r.run === 1 && r.group === activeGroupId
		);

		// Convert to JSON to compare
		const newRunsJson = JSON.stringify({
		  scheduleId: chosenSchedule.schedule_id,
		  relevantRuns
		});

		if (newRunsJson !== previousStartlistJson) {
		  console.log("[startlist.js] Startlist changed => re-rendering table.");
		  previousStartlistJson = newRunsJson;
		  buildStartlistTable(relevantRuns);
		} else {
		  console.log("[startlist.js] Startlist unchanged => skip re-render.");
		}
	  })
	  .catch((err) => {
		console.error("[startlist.js] Error fetching schedule data:", err);
	  });
  }

  // First call
  fetchAndRenderStartlist();

  // Poll every 2 seconds => re-check
  setInterval(fetchAndRenderStartlist, 2000);
}

/**
 * startLiveClock():
 *   - updates #startlistClock every second with current local time
 */
function startLiveClock() {
  const clockEl = document.getElementById("startlistClock");
  if (!clockEl) {
	console.warn("[startlist.js] #startlistClock not found => skipping clock.");
	return;
  }

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

/**
 * buildStartlistTable(runs):
 *   - Accepts an array of run objects (from the chosen schedule).
 *   - We simply display them in order with start number (1..X).
 */
function buildStartlistTable(runs) {
  const tableBody = document.getElementById("startlistTableBody");
  if (!tableBody) {
	console.warn("[startlist.js] #startlistTableBody not found => cannot build table rows.");
	return;
  }

  // Clear existing rows
  tableBody.innerHTML = "";

  // Enumerate them from 1..X in the order they're found
  runs.forEach((run, index) => {
	// The "start number" => index+1
	const startNumber = index + 1;

	// Suppose the run has athlete_name, birthyear, country, active, qualified, bib, etc.
	const athleteName = run.athlete_name || "Unknown Athlete";
	const splitted    = athleteName.trim().split(" ");
	let lastName      = splitted.pop() || "";
	let firstName     = splitted.join(" ");
	if (!firstName) {
	  firstName = lastName;
	  lastName  = "";
	}

	const birthyear   = run.year_of_birth || "";
	const country     = run.country       || "";
	const isActive    = run.active === 1;
	const isQualified = !!run.qualified; // or your logic

	// Potential "tick arrow" if qualified
	const tickHTML = isQualified ? `<img src="img/tick-arrow.svg" alt="" />` : "";

	// BIB can appear behind the last name in small text
	let bibSpan = "";
	if (run.bib) {
	  bibSpan = ` <span style="font-size:0.75em;">(${run.bib})</span>`;
	}

	// Create a <tr> row
	const tr = document.createElement("tr");
	if (isActive) {
	  tr.classList.add("active");
	}

	tr.innerHTML = `
	  <td>${startNumber}</td>
	  <td class="text-start">${lastName}</td>
	  <td class="text-start">${firstName}${bibSpan}</td>
	  <td>${birthyear}</td>
	  <td>${country}</td>
	  <td>${tickHTML}</td>
	`;

	tableBody.appendChild(tr);
  });
}