export const htmlSchedule = `
<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="scheduleEventTitle"></p>
	  <h2 class="title f_kazer_outline">TIMETABLE</h2>
	  <div class="wrap_table">
		<table class="table table_timetable">
		  <thead>
			<tr>
			  <th class="text-start">DATE</th>
			  <th class="text-start">TIME</th>
			  <th class="text-start">GROUP / ROUND</th>
			</tr>
		  </thead>
		  <tbody id="scheduleTableBody">
			<!-- 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="scheduleClock">12:34:34</p>
	  </div>
	</div>
  </div>
</div>
`;

/**
 * initSchedule():
 *   - Called after this snippet is inserted by tv.js
 *   - Re-fetches the schedule data every 2s, checks if changed => re-render
 *   - Finds all groups across all schedules, sorts them, then finds the active group
 *     and shows that group + the next 9 rows (so total 10).
 */
export function initSchedule() {
  console.log("[schedule.js] initSchedule() called.");

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

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

  // Optionally start a live clock
  startLiveClock();

  // We'll store the old data in JSON format
  let previousScheduleJson = null;

  /**
   * fetchAndRenderSchedule => calls schedule API => build row objects => find active => slice => build table
   */
  function fetchAndRenderSchedule() {
	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("[schedule.js] Schedule API error", res.status, res.statusText);
		  return null;
		}
		return res.json();
	  })
	  .then((jsonData) => {
		if (!jsonData) {
		  console.warn("[schedule.js] No schedule data returned.");
		  return;
		}
		if (!Array.isArray(jsonData.data)) {
		  console.warn("[schedule.js] Unexpected schedule format:", jsonData);
		  return;
		}

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

		// Build an array of "group rows" => each item is {
		//   planned: #,
		//   actual:  #,
		//   label:   "Open Men Finals (Group 2)",
		//   isActive: bool
		// }
		const allGroupRows = buildGroupRows(schedules);

		// Convert to JSON => compare
		const newScheduleJson = JSON.stringify(allGroupRows);
		if (newScheduleJson !== previousScheduleJson) {
		  console.log("[schedule.js] Schedule changed => re-rendering table.");
		  previousScheduleJson = newScheduleJson;

		  // Now find the active group index => slice 10
		  // If no active => fallback to start from index 0
		  let activeIndex = allGroupRows.findIndex(r => r.isActive);
		  if (activeIndex < 0) activeIndex = 0;

		  // Slice 10 from activeIndex
		  const rowsToShow = allGroupRows.slice(activeIndex, activeIndex + 10);

		  // Build the table
		  buildScheduleTable(rowsToShow);
		} else {
		  console.log("[schedule.js] Schedule unchanged => skip re-render.");
		}
	  })
	  .catch((err) => {
		console.error("[schedule.js] Error fetching schedule data:", err);
	  });
  }

  // First call
  fetchAndRenderSchedule();

  // Poll every 2s
  setInterval(fetchAndRenderSchedule, 2000);
}

/**
 * buildGroupRows(schedules): returns an array of objects:
 *   [
 *     {
 *       planned:  1679991000, // integer timestamp
 *       actual:   1679991300, // or null
 *       label:    "Open Men Finals (Group 2)",
 *       isActive: true/false
 *     },
 *     { ... },
 *     ...
 *   ]
 * We sort them by planned ascending (like you normally do).
 */
function buildGroupRows(schedules) {
  const rows = [];

  schedules.forEach((sched) => {
	// Some base label => e.g. "Open Men Finals"
	const catName   = sched.category_name    || "";
	const roundName = sched.heatsystem_name  || "";
	const baseLabel = (catName + " " + roundName).trim();
	
	
	const competitionTitleEl = document.getElementById("scheduleEventTitle");
	if (competitionTitleEl) {
	  const compName = schedules[0].competition_name || "Unnamed Event";
	  competitionTitleEl.textContent = compName.toUpperCase();
	}
		
	// Build a map group => runs
	const runsArr = sched.runs || [];
	const groupMap = {};
	runsArr.forEach(r => {
	  const g = r.group || 0;
	  if (!groupMap[g]) groupMap[g] = [];
	  groupMap[g].push(r);
	});

	// For each group => produce 1 row
	Object.keys(groupMap).forEach((grpKey) => {
	  const groupRuns = groupMap[grpKey];

	  // min planned
	  let minPlanned = null;
	  // min real
	  let minReal = null;
	  // isActive => if any run isActive
	  let isActive = false;

	  groupRuns.forEach(r => {
		const plan = parseInt(r.calculated_planned_time || 0, 10);
		if (plan > 0 && (minPlanned === null || plan < minPlanned)) {
		  minPlanned = plan;
		}
		const real = parseInt(r.real_time || 0, 10);
		if (real > 0 && (minReal === null || real < minReal)) {
		  minReal = real;
		}
		if (r.active === 1) {
		  isActive = true;
		}
	  });

	  rows.push({
		planned:  minPlanned,
		actual:   minReal,
		label:    `${baseLabel} (Group ${grpKey})`.toUpperCase(),
		isActive
	  });
	});
  });

  // Sort by planned ascending
  rows.sort((a,b)=> {
	const A = a.planned || 9999999999;
	const B = b.planned || 9999999999;
	return A - B;
  });

  return rows;
}

/**
 * buildScheduleTable(rows):
 *   - we just build <tr> for each row => [PLANNED, ACTUAL, label]
 */
function buildScheduleTable(rows) {
   const tableBody = document.getElementById("scheduleTableBody");
   if (!tableBody) {
	 console.warn("[schedule.js] #scheduleTableBody not found => can't build rows.");
	 return;
   }
   tableBody.innerHTML = "";
 
   rows.forEach((row) => {
	 // Break out the planned timestamp into date + time
	 const plannedDateStr = row.planned ? formatDate(row.planned) : "--";
	 const plannedTimeStr = row.planned ? formatTimeHHMM(row.planned) : "--:--";
 
	 const tr = document.createElement("tr");
	 if (row.isActive) {
	   tr.classList.add("active"); // highlight the row if you want
	 }
	 tr.innerHTML = `
	   <td>${plannedDateStr}</td>
	   <td>${plannedTimeStr}</td>
	   <td>${row.label}</td>
	 `;
	 tableBody.appendChild(tr);
   });
 }
 
 
 /**
  * formatDate(timestampSeconds) => "YYYY-MM-DD"
  * e.g. 1679991300 -> "2023-06-28"
  */
 function formatDate(timestampSeconds) {
   const d = new Date(timestampSeconds * 1000);
   const year = d.getFullYear();
   const month = String(d.getMonth() + 1).padStart(2, "0");
   const day = String(d.getDate()).padStart(2, "0");
   return `${year}-${month}-${day}`;
 }

/**
 * formatTimeHHMM(timestampSeconds) => "HH:MM" in 24-hour format
 */
function formatTimeHHMM(timestampSeconds) {
  const d = new Date(timestampSeconds * 1000);
  const parts = d.toLocaleTimeString([], { hour12: false }).split(":");
  return `${parts[0]}:${parts[1]}`;
}

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

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