document.addEventListener("DOMContentLoaded", async function () {
	
  // We'll keep a "lastSnippet" variable in top-level scope so we can compare.
  let lastSnippet = null;

  // 1) We'll define a function that does the dynamic loading based on `contentType`.
  async function loadSnippet(contentType, mainEl) {
	if (contentType === lastSnippet) {
	  // If it's the same as last time, we can skip re-render to avoid flicker:
	  console.log(`[tv.js] snippet '${contentType}' is already loaded => skipping reload.`);
	  return;
	}

	console.log(`[tv.js] Loading snippet '${contentType}' ...`);

	let snippetHTML = "";
	try {
	  switch (contentType) {
		case "profile": {
		  const module = await import("/tv/js/profile.js");
		  snippetHTML = module.htmlProfile;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initProfile === "function") {
			module.initProfile();
		  }
		  break;
		}

		case "athlete": {
		  const module = await import("/tv/js/athlete.js");
		  snippetHTML = module.htmlAthlete;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initAthlete === "function") {
			module.initAthlete();
		  }
		  break;
		}

		case "startlist": {
		  const module = await import("/tv/js/startlist.js");
		  snippetHTML = module.htmlStartlist;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initStartlist === "function") {
			module.initStartlist();
		  }
		  break;
		}

		case "results": {
		  const module = await import("/tv/js/results.js");
		  snippetHTML = module.htmlResults;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initResults === "function") {
			module.initResults();
		  }
		  break;
		}

		case "results_left": {
		  const module = await import("/tv/js/results_left.js");
		  snippetHTML = module.htmlResultsSmall;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initResultsSmall === "function") {
			module.initResultsSmall();
		  }
		  break;
		}
		
		case "results_small": {
		  const module = await import("/tv/js/results_small.js");
		  snippetHTML = module.htmlResultsSmall;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initResultsSmall === "function") {
			module.initResultsSmall();
		  }
		  break;
		}

		case "schedule": {
		  const module = await import("/tv/js/schedule.js");
		  snippetHTML = module.htmlSchedule;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initSchedule === "function") {
			module.initSchedule();
		  }
		  break;
		}

		case "schedule_small": {
		  const module = await import("/tv/js/schedule_small.js");
		  snippetHTML = module.htmlScheduleSmall;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initScheduleSmall === "function") {
			module.initScheduleSmall();
		  }
		  break;
		}

		case "info": {
		  const module = await import("/tv/js/info.js");
		  snippetHTML = module.htmlInfo;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initInfo === "function") {
			module.initInfo();
		  }
		  break;
		}

		case "info_small": {
		  const module = await import("/tv/js/info_small.js");
		  snippetHTML = module.htmlInfoSmall;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initInfoSmall === "function") {
			module.initInfoSmall();
		  }
		  break;
		}

		case "info_left": {
		  const module = await import("/tv/js/info_left.js");
		  snippetHTML = module.htmlInfoLeft;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initInfoLeft === "function") {
			module.initInfoLeft();
		  }
		  break;
		}
		
		case "index": {
		  const module = await import("/tv/js/index.js");
		  snippetHTML = module.htmlIndex;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initInfoLeft === "function") {
			module.initIndex();
		  }
		  break;
		}

		default: {
		  // fallback to "index" if unknown
		  const module = await import("/tv/js/index.js");
		  snippetHTML = module.htmlProfile;
		  mainEl.innerHTML = snippetHTML;
		  if (typeof module.initProfile === "function") {
			module.initProfile();
		  }
		  break;
		}
	  }

	  // (Optional) animate => if .slide-target is present
	  const slideTarget = mainEl.querySelector(".slide-target");
	  if (slideTarget) {
		setTimeout(() => {
		  slideTarget.classList.add("slide-in");
		}, 50);
	  }

	  // Update lastSnippet
	  lastSnippet = contentType;
	} catch (err) {
	  console.error("Error importing snippet module:", err);
	}
  }

  // 2) Our main function that checks the URL param or calls the TV API
  async function checkAndRenderSnippet() {
	// Parse content from URL
	const urlParams   = new URLSearchParams(window.location.search);
	let contentType   = urlParams.get("content") || "index";

	// If contentType is "index" => call the TV API to see which snippet to show
	if (contentType === "index") {
	  try {
		const competitionCode = urlParams.get("competitionCode") || "25GER013";
		const tvUrl = `${API_BASE_URL}?api=tv&competitionCode=${encodeURIComponent(competitionCode)}`;
		const tvRes = await fetch(tvUrl, {
		  headers: {
			"Content-Type": "application/json",
			"Authorization": "Bearer 50afb255cfa3a36834e0a51185b1eb09",
		  },
		});
		if (tvRes.ok) {
		  const tvJson = await tvRes.json();
		  if (tvJson && tvJson.data) {
			const d = tvJson.data;
			// Decide which snippet to show
			if (d.athlete === 1) contentType = "athlete";
			else if (d.results === 1) contentType = "results";
			else if (d.profile === 1) contentType = "profile";
			else if (d.startlist === 1) contentType = "startlist";
			else if (d.schedule === 1) contentType = "schedule";
			else contentType = "index"; // fallback
		  } else {
			contentType = "index"; 
		  }
		} else {
		  console.warn(`[tv.js] TV API error ${tvRes.status}`);
		  contentType = "index";
		}
	  } catch (err) {
		console.error("[tv.js] Error calling TV API:", err);
		contentType = "index";
	  }
	}

	// Now we do the dynamic import
	const mainEl = document.querySelector(".main");
	if (!mainEl) {
	  console.error("No .main element found => can't render snippet.");
	  return;
	}
	await loadSnippet(contentType, mainEl);
  }

  // 3) We'll run checkAndRenderSnippet() initially
  await checkAndRenderSnippet();

  // 4) Additionally, if you want to poll the TV API every X seconds to see if it changed:
  setInterval(() => {
	checkAndRenderSnippet();
  }, 2000);  // e.g. every 2 seconds
});