document.addEventListener("DOMContentLoaded", function () {
  // 1) Public bearer token used for 'public=true' APIs
  const PUBLIC_BEARER_TOKEN = "Bearer 50afb255cfa3a36834e0a51185b1eb09";

  // 2) Retrieve competition code, either from localStorage or URL
  let storedCompetition = JSON.parse(localStorage.getItem("activeCompetition"));
  if (!storedCompetition || !storedCompetition.code) {
	console.warn("No active competition found in localStorage. Checking URL...");
	const urlParams = new URLSearchParams(window.location.search);
	const competitionCodeFromUrl = urlParams.get("CompetitionCode");
	if (competitionCodeFromUrl) {
	  storedCompetition = { code: competitionCodeFromUrl };
	  console.log("Using competitionCode from URL:", competitionCodeFromUrl);
	} else {
	  console.error("No competition code found. Cannot proceed with livestream.");
	  return;
	}
  }
  const competitionCode = storedCompetition.code;

  // 3) Build the URL for the settings API (with public=true)
  const settingsUrl = `${API_BASE_URL}?api=settings&competitionCode=${encodeURIComponent(
	competitionCode
  )}&public=true`;

  // 4) Fetch the settings
  fetch(settingsUrl, {
	method: "GET",
	headers: {
	  "Content-Type": "application/json",
	  "Authorization": PUBLIC_BEARER_TOKEN
	}
  })
	.then(response => {
	  if (!response.ok) {
		throw new Error(`Settings API error: ${response.status}`);
	  }
	  return response.json();
	})
	.then(data => {
	  /*
	   * Expecting data structure like:
	   * {
	   *   "success": true,
	   *   "settings": {
	   *     ...,
	   *     "livestream": "https://www.youtube.com/live/..."
	   *   },
	   *   "heatsystems": [...],
	   *   "events": [...]
	   * }
	   */
	  if (!data || !data.settings) {
		console.warn("No valid settings data found.");
		return;
	  }

	  // 5) Check for 'livestream' key under data.settings
	  const livestreamURL = data.settings.livestream;
	  if (!livestreamURL) {
		console.log("No 'livestream' URL found in settings data.");
		return;
	  }
	  
	  let embedURL = livestreamURL;
	  	  
	  // Convert to embed format if needed
	  if (embedURL.includes("watch?v=")) {
		// Example: https://www.youtube.com/watch?v=abcdefg
		const vid = embedURL.split("watch?v=")[1].split("&")[0];
		embedURL = `https://www.youtube.com/embed/${vid}?controls=0`;
	  
	  } else if (embedURL.includes("/live/")) {
		// Example: https://www.youtube.com/live/abcdefg
		const vid = embedURL.split("/live/")[1].split("?")[0];
		embedURL = `https://www.youtube.com/embed/${vid}?controls=0`;
	  
	  } else if (embedURL.includes("youtu.be/")) {
		// Example: https://youtu.be/abcdefg
		const vid = embedURL.split("youtu.be/")[1].split("?")[0];
		embedURL = `https://www.youtube.com/embed/${vid}?controls=0`;
	  
	  } else if (embedURL.includes("youtube.com/embed/")) {
		// Already embed
		if (!embedURL.includes("controls=")) {
		  embedURL += embedURL.includes("?") ? "&controls=0" : "?controls=0";
		}
	  }

	  // 6) Find the container in your HTML
	  const container = document.getElementById("container-livestream");
	  if (!container) {
		console.error("#container-livestream not found in DOM!");
		return;
	  }

	  // 7) Build a card with an embedded <iframe>
	  //    (You can style or rename classes as you like.)
const cardHTML = `
<div class="card mb-4">
  <div class="card-header">
	<h3 class="card-title mb-0">Livestream</h3>
  </div>
  <div class="card-body">
	<div class="ratio ratio-16x9">
	  <iframe src="${embedURL}"
		title="YouTube video player"
		allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
		allowfullscreen></iframe>
	</div>
  </div>
</div>
	  `;
	  
	  // 8) Insert into the container
	  container.innerHTML = cardHTML;
	})
	.catch(err => {
	  console.error("Error fetching livestream settings:", err);
	});
});