  document.addEventListener("DOMContentLoaded", function () {
	  
	/*******************************************************
	 * 1) Basic CSS injection (optional)
	 *******************************************************/
	const style = document.createElement("style");
	style.textContent = `
	  .mobile-optimized-card {
		margin-bottom: 1rem;
	  }
	  .badge {
		display: inline-block;
		padding: 0.25em 0.4em;
		font-size: 75%;
		font-weight: 700;
		line-height: 1;
		text-align: center;
		white-space: nowrap;
		vertical-align: middle;
		border-radius: 0.375rem;
	  }
	  .bg-primary {
		background-color: #0d6efd !important;
		color: #fff !important;
	  }
	  .bg-danger {
		background-color: #dc3545 !important;
		color: #fff !important;
	  }
	  .me-2 {
		margin-right: 0.5rem !important;
	  }
	  /* Optionally highlight the user's own judge name */
	  .current-user-judge {
		font-weight: bold;
		color: #2a2a2a;
	  }
	  /* The dimmed style for schedules without this judge */
	  .dimmed {
		opacity: 0.4;
		pointer-events: none; /* optional if you want to disable interaction */
	  }
	`;
	document.head.appendChild(style);

	/*******************************************************
	 * 2) Competition code + user info
	 *******************************************************/
	let storedCompetition = JSON.parse(localStorage.getItem("activeCompetition"));
	if (!storedCompetition || !storedCompetition.code) {
	  const urlParams = new URLSearchParams(window.location.search);
	  const codeFromUrl = urlParams.get("CompetitionCode");
	  if (codeFromUrl) {
		storedCompetition = { code: codeFromUrl };
		console.log("CompetitionCode from URL:", codeFromUrl);
	  } else {
		console.error("No competition code found. Cannot proceed.");
		return;
	  }
	}
	const competitionCode = storedCompetition.code;

	// If you’re highlighting the user’s assigned schedules => parse localUser
	let localUserData = null;
	try {
	  localUserData = JSON.parse(localStorage.getItem("user"));
	} catch (e) {
	  console.warn("Failed to parse local user data:", e);
	}
	const userIwwfId = localUserData?.iwwf_id || null;
	if (!userIwwfId) {
	  console.warn("User has no iwwf_id => might not highlight schedules properly.");
	}

	/*******************************************************
	 * 3) Keep track of previously rendered data
	 *******************************************************/
	let previousScheduleData = null;

	/*******************************************************
	 * 4) Fetch schedule + auto-refresh
	 *******************************************************/
	fetchAndRenderSchedule();
	setInterval(fetchAndRenderSchedule, 30_000); // every 30s (adjust if desired)

	function fetchAndRenderSchedule() {
	  const url = `${API_BASE_URL}?api=schedule&competitionCode=${encodeURIComponent(
		competitionCode
	  )}&scores=true&public=false`;

	  fetch(url, {
		headers: {
		  "Content-Type": "application/json",
		  // Hard-coded token for demonstration:
		  "Authorization": "Bearer 50afb255cfa3a36834e0a51185b1eb09"
		}
	  })
		.then((res) => {
		  if (!res.ok) {
			console.error("Schedule fetch error:", res.status, res.statusText);
			return null;
		  }
		  return res.json();
		})
		.then((json) => {
		  if (!json || !Array.isArray(json.data)) {
			return;
		  }
		  const newData = json.data;

		  const oldStr = JSON.stringify(previousScheduleData);
		  const newStr = JSON.stringify(newData);
		  if (oldStr !== newStr) {
			previousScheduleData = newData;
			renderSchedule(newData);
		  } else {
		  }
		})
		.catch((err) => {
		  console.error("Error fetching schedule data:", err);
		});
	}

	/*******************************************************
	 * 5) Display all schedules, but dim those not containing the user
	 *******************************************************/
	function renderSchedule(scheduleData) {
	  const container = document.getElementById("container-schedule");
	  if (!container) {
		console.error("#container-schedule not found");
		return;
	  }
	  container.innerHTML = "";

	  // Instead of filtering, we show them all
	  // We'll group them by day:
	  const grouped = groupByDay(scheduleData);

	  // For each day => create a card
	  Object.keys(grouped).forEach((day) => {
		const dayCard = document.createElement("div");
		dayCard.className = "card mobile-optimized-card mb-3";

		const dayCardHeader = document.createElement("div");
		dayCardHeader.className = "card-header";
		dayCardHeader.innerHTML = `<h3 class="card-title mb-0">${day}</h3>`;

		const dayCardBody = document.createElement("div");
		dayCardBody.className = "card-body";

		// Sort by schedule.order
		grouped[day].sort((a, b) => (a.order || 0) - (b.order || 0));

		grouped[day].forEach((schedItem) => {
		  // We'll check if user is included
		  const userIncluded = Array.isArray(schedItem.officials)
			? schedItem.officials.some((off) => off.iwwf_id === userIwwfId)
			: false;

		  // Build schedule info
		  const itemHtml = buildScheduleHeaderHtml(schedItem);
		  // Wrap in a div so we can apply `.dimmed` if user not included
		  const wrapper = document.createElement("div");
		  wrapper.innerHTML = itemHtml;

		  if (!userIncluded) {
			// apply the "dimmed" style
			wrapper.classList.add("dimmed");
		  }

		  dayCardBody.appendChild(wrapper);
		});

		dayCard.appendChild(dayCardHeader);
		dayCard.appendChild(dayCardBody);
		container.appendChild(dayCard);
	  });
	}

	function groupByDay(schedules) {
	  return schedules.reduce((acc, sched) => {
		let dayLabel = "No Planned Date";
		if (sched.time_planned) {
		  const dateObj = new Date(sched.time_planned * 1000);
		  dayLabel = dateObj.toLocaleDateString();
		}
		if (!acc[dayLabel]) acc[dayLabel] = [];
		acc[dayLabel].push(sched);
		return acc;
	  }, {});
	}

	/*******************************************************
	 * 6) Build schedule header => plus a line with judges
	 *******************************************************/
	function buildScheduleHeaderHtml(scheduleItem) {
	  const {
		time_planned,
		event_name,
		category_name,
		heatsystem_name,
		officials,
		delay // <-- Make sure your backend sets this property
	  } = scheduleItem;

	  // Format the time
	  const localTime = time_planned
		? new Date(time_planned * 1000).toLocaleTimeString([], {
			hour: "2-digit",
			minute: "2-digit",
		  })
		: "N/A";

	  // Convert delay (in seconds?) to a display string
	  let delayStr = "";
	  if (typeof delay === "number" && delay !== 0) {
		// Example: show as “(Delay +5m)” if positive, “(Delay -3m)” if negative
		const sign = delay > 0 ? "+" : "";
		// Convert from seconds => minutes if needed
		const minutes = Math.round(delay / 60);
		delayStr = ` (Delay ${sign}${minutes}m)`;
	  }

	  let eventBadge = "";
	  if (event_name === "Wakeboard") {
		eventBadge = `<span class="badge bg-primary me-2">WB</span>`;
	  } else if (event_name === "Wakeskate") {
		eventBadge = `<span class="badge bg-danger me-2">WS</span>`;
	  }else if (event_name === "Wakeboard Seated") {
		eventBadge = `<span class="badge bg-warning me-2">ST</span>`;
	  }

	  // Sort the 'officials'
	  if (Array.isArray(officials)) {
		officials.sort((a, b) => (a.judge_number || 0) - (b.judge_number || 0));
	  }

	  // Build the judges line
	  let judgesLine = "";
	  if (Array.isArray(officials) && officials.length > 0) {
		const judgeStrings = officials.map((off) => {
		  const judgeNum = off.judge_number ? `${off.judge_number}` : "";
		  const offName  = off.official_name || "Judge";
		  const iwwfIdStr= off.iwwf_id ? `(${off.iwwf_id})` : "";
		  const display  = `Judge ${judgeNum}: ${offName}`.trim();

		  // highlight current user
		  if (off.iwwf_id === userIwwfId) {
			return `<span class="current-user-judge">${display}</span>`;
		  }
		  return display;
		});
		judgesLine = `<div class="text-muted">${judgeStrings.join(" | ")}</div>`;
	  } else {
		judgesLine = `<div class="text-muted">No judges assigned</div>`;
	  }

	  return `
		<div class="mb-4">
		  <h4 class="fw-bold d-flex justify-content-between align-items-center flex-wrap">
			<div>
			  <!-- Notice the delayStr appended here -->
			  <span>${localTime}${delayStr}</span>
			  ${eventBadge}${category_name || "Unknown Category"} ${heatsystem_name || ""}
			</div>
		  </h4>
		  ${judgesLine}
		</div>
	  `;
	}
  });