export const htmlScheduleSmall = `
<div 
  class="main p-40 py-40 ps-0 d-flex"
  style="
	/* example inline style for a background image; remove if you have global CSS */
	background: url('img/your-mountain-background.jpg') no-repeat center center; 
	background-size: cover;
  "
>
  <div class="content_box ms_0">
	<div class="page10_bottom_box">
	  <div class="left_box">
		<!-- Dark bar container -->
		<div class="bg_royalblue text_white page10_padding_box" style="opacity: 0.9;">
		  <div class="page16_bottom_grid page22_bottom_grid" id="smallScheduleGrid">
			<!-- We will dynamically insert rows for each group in a 2-column layout below -->
			<!-- 
			  Example structure (2 columns):
			  <div class="box_1">
				<h3 class="fs_48 f_kazer_outline">TIMETABLE</h3>
			  </div>
			  <div class="box_2 flex gap_0">
				... etc ...
			  </div>
			-->
		  </div>
		</div>

		<!-- Teal bar under the dark bar -->
		<div class="bg_cyan page10_padding_box" style="opacity: 0.9;">
		  <p class="fw_700 text_royalblue" id="smallScheduleTitle">WORLD CHAMPIONSHIP OPEN MEN 2023</p>
		</div>
	  </div>

	  <div class="right_box">
		<!-- Logo area (right side) -->
		<div class="box box3">
		  <!-- Adjust your sponsor or event logo paths here -->
		  <img src="img/iwwf.png" class="page16_b_img" alt="">
		</div>
		<div class="bottom_box">
		  <!-- Clock at bottom-right corner -->
		  <p class="fw_700 text_royalblue" id="smallScheduleClock">12:34:34</p>
		</div>
	  </div>
	</div>
  </div>
</div>
`;

/**
 * initScheduleSmall():
 *   - Called after this snippet is inserted by tv.js
 *   - 1) Parse competitionCode from URL
 *   - 2) Call the schedule API with ?next=2 => active group + 2 after
 *   - 3) Dynamically fill in the snippet’s HTML
 *   - 4) Layout in two columns if you want (dark bar with times)
 */
export function initScheduleSmall() {
  console.log("[schedule_small.js] initScheduleSmall() called.");

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

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

  // 3) Optionally start a live clock
  startLiveClock();

  // 4) Fetch schedule with ?next=2 => active group + 2 subsequent
  const scheduleUrl = `
	${API_BASE_URL}?api=schedule
	&competitionCode=${encodeURIComponent(competitionCode)}
	&public=true
	&scores=false
	&next=2
  `.replace(/\s+/g, ""); // remove line breaks for a clean URL

  fetch(scheduleUrl, { headers: getAuthHeaders() })
	.then((res) => {
	  if (!res.ok) {
		console.error("[schedule_small.js] Schedule API responded with", res.status, res.statusText);
		return null;
	  }
	  return res.json();
	})
	.then((jsonData) => {
	  if (!jsonData) {
		console.warn("[schedule_small.js] No schedule data returned.");
		return;
	  }
	  if (!Array.isArray(jsonData.data)) {
		console.warn("[schedule_small.js] schedule API returned unexpected format:", jsonData);
		return;
	  }
	  const schedules = jsonData.data;
	  if (schedules.length === 0) {
		console.log("[schedule_small.js] No schedules => nothing to display.");
		return;
	  }

	  // If you want to show the event_name from the first schedule in #smallScheduleTitle
	  const titleEl = document.getElementById("smallScheduleTitle");
	  if (titleEl && schedules[0].competition_name) {
		titleEl.textContent = schedules[0].competition_name.toUpperCase();
	  }

	  // Build the layout
	  buildSmallSchedule(schedules);
	})
	.catch((err) => {
	  console.error("[schedule_small.js] Error fetching schedule data:", err);
	});
}

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

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

/**
 * buildSmallSchedule(schedules):
 *   - We have at most 3 groups total (active + 2 after).
 *   - Layout them in a 2-col style. 
 */
function buildSmallSchedule(schedules) {
  const gridEl = document.getElementById("smallScheduleGrid");
  if (!gridEl) {
	console.warn("[schedule_small.js] #smallScheduleGrid not found => cannot build layout.");
	return;
  }

  // Clear existing
  gridEl.innerHTML = `
	<div class="box_1">
	  <h3 class="fs_48 f_kazer_outline">TIMETABLE</h3>
	</div>
	<div class="box_2 flex gap_0" id="smallScheduleCols"></div>
  `;

  const columnsWrapper = document.getElementById("smallScheduleCols");
  if (!columnsWrapper) return;

  // Flatten group data
  const groupItems = gatherGroups(schedules);

  // 2 columns
  const leftColDiv  = document.createElement("div");
  const rightColDiv = document.createElement("div");
  leftColDiv.classList.add("w_50");
  rightColDiv.classList.add("w_50");

  const leftFlex  = document.createElement("div");
  leftFlex.classList.add("flex");
  leftColDiv.appendChild(leftFlex);

  const rightFlex = document.createElement("div");
  rightFlex.classList.add("flex");
  rightColDiv.appendChild(rightFlex);

  columnsWrapper.appendChild(leftColDiv);
  columnsWrapper.appendChild(rightColDiv);

  // Distribute each group item
  groupItems.forEach((grp, idx) => {
	const col = idx < 2 ? leftFlex : rightFlex; 
	const timesDiv = document.createElement("div");
	timesDiv.classList.add("item1");
	const labelDiv = document.createElement("div");
	labelDiv.classList.add("item2");

	const plannedStr = grp.plannedTimeSec ? formatTimeHHMM(grp.plannedTimeSec) : "--:--";
	const actualStr  = grp.actualTimeSec  ? formatTimeHHMM(grp.actualTimeSec)  : "--:--";

	timesDiv.innerHTML = `
	  <p class="fw_700">${plannedStr}</p>
	  <p>${actualStr}</p>
	`;
	labelDiv.innerHTML = `<p class="fw_700">${grp.groupLabel}</p>`;

	const outerFlex = document.createElement("div");
	outerFlex.classList.add("flex");
	outerFlex.appendChild(timesDiv);
	outerFlex.appendChild(labelDiv);

	col.appendChild(outerFlex);
  });
}

/**
 * gatherGroups(schedules):
 *   - Return array of { plannedTimeSec, actualTimeSec, groupLabel }
 */
function gatherGroups(schedules) {
  const result = [];
  schedules.forEach((sched) => {
	const roundStr = `${sched.event_name || ""} ${sched.category_name || ""} ${sched.heatsystem_name || ""}`
	  .trim()
	  .toUpperCase();
	const runs = sched.runs || [];
	// group runs => groupMap
	const groupMap = {};
	runs.forEach((r) => {
	  const g = r.group;
	  if (!groupMap[g]) groupMap[g] = [];
	  groupMap[g].push(r);
	});
	// build an item per group
	Object.keys(groupMap).forEach((gKey) => {
	  const groupRuns = groupMap[gKey];
	  let minPlan = null;
	  let minReal = null;
	  groupRuns.forEach((r) => {
		if (r.calculated_planned_time && (minPlan === null || r.calculated_planned_time < minPlan)) {
		  minPlan = r.calculated_planned_time;
		}
		const realTime = r.real_time ? parseInt(r.real_time, 10) : 0;
		if (realTime > 0 && (minReal === null || realTime < minReal)) {
		  minReal = realTime;
		}
	  });
	  result.push({
		plannedTimeSec: minPlan,
		actualTimeSec:  minReal,
		groupLabel:     `${roundStr} (Group ${gKey})`
	  });
	});
  });
  return result;
}

/**
 * formatTimeHHMM(seconds):
 */
function formatTimeHHMM(seconds) {
  if (!seconds || seconds <= 0) return "--:--";
  const d = new Date(seconds * 1000);
  const parts = d.toLocaleTimeString([], { hour12: false }).split(":");
  return `${parts[0]}:${parts[1]}`;
}