document.addEventListener("DOMContentLoaded", function () {
	
  /*************************************************************
   * 0) Retrieve bearer token from localStorage user
   *************************************************************/
  const storedUser    = JSON.parse(localStorage.getItem("user")) || {};
  const bearerToken   = storedUser.bearer || null;
  if (!bearerToken) {
	console.error("No bearer token found in local storage!");
	localStorage.removeItem("user");
	window.location.href = "index.html";
	return;
  }

  /**
   * Helper: Build fetch headers with Bearer token & JSON content.
   */
  function getAuthHeaders(isJson = true) {
	const base = isJson ? { "Content-Type": "application/json" } : {};
	base["Authorization"] = `Bearer ${bearerToken}`;
	return base;
  }

  /**
   * If response is not ok => sign out user & redirect.
   */
  function handleNotOkResponse(response) {
	console.error(`API response not OK: ${response.status} - ${response.statusText}`);
	alert("Session expired or invalid. You will be signed out.");
	localStorage.removeItem("user");
	window.location.href = "index.html";
  }

  // 1) The container for the schedule settings
  const scheduleContainer = document.getElementById("schedule-container");
  if (!scheduleContainer) {
	console.error("No element with ID 'settings-container-schedule' found!");
	return;
  }

  // 2) Grab competition code from localStorage
  const competitionCode = JSON.parse(localStorage.getItem("activeCompetition"))?.code;
  if (!competitionCode) {
	console.error("No active competition found in localStorage!");
	return;
  }

  // 3) Fetch the schedule settings from the server
  fetchScheduleSettings(competitionCode);

  /**
   * GET the schedule settings from the server.
   */
  function fetchScheduleSettings(code) {
	fetch(
	  `${API_BASE_URL}?api=settings&competitionCode=${encodeURIComponent(code)}`,
	  {
		method: "GET",
		headers: getAuthHeaders(true),
	  }
	)
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null; // short-circuit
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return; // short-circuit
		if (data.success) {
		  renderScheduleSettingsCard(data.live_schedule, data.entries);
		} else {
		  console.error("Failed to fetch schedule settings:", data.error || "Unknown error");
		  if (String(data.error || "").toLowerCase().includes("invalid")) {
			alert("Session invalid. Signing out...");
			localStorage.removeItem("user");
			window.location.href = "index.html";
		  }
		}
	  })
	  .catch((error) => console.error("Error fetching schedule settings:", error));
  }

  /**
   * 4) Render the main "Schedule Settings" card
   */
  function renderScheduleSettingsCard(useLiveSchedule, scheduleEntries) {
	scheduleContainer.innerHTML = ""; // Clear existing content

	const card = document.createElement("div");
	card.classList.add("card", "mb-5");

	card.innerHTML = `
	  <div class="card-header">
		<div class="fs-3 fw-bold card-title"><span>Schedule Settings</span></div>
	  </div>
	  <div class="card-body p-9">

		<!-- USE LIVE SCHEDULE CHECKBOX -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3">
			  <span>Live Schedule</span>
			</div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<div class="form-check form-check-custom form-check-solid">
			  <input
				class="form-check-input"
				type="checkbox"
				name="use_live_schedule"
				id="useLiveScheduleCheckbox"
				${parseInt(useLiveSchedule) === 1 ? "checked" : ""}
			  />
			  <label class="form-check-label ms-2" for="useLiveScheduleCheckbox">
				If activated, the schedule will update times in real-time.
			  </label>
			</div>
		  </div>
		</div>

		<!-- RENDER EACH SCHEDULE ENTRY -->
		<div id="schedule-entries-container">
		  ${
			scheduleEntries?.map((entry) => `
			  <div class="row mb-8 schedule-entry-row" data-schedule-id="${entry.schedule_id}">
				<div class="col-xl-3">
				  <div class="fs-6 fw-semibold mt-2 mb-3">
					<span>${entry.name}</span>
				  </div>
				</div>
				<div class="col-xl-9 fv-row">

				  <!-- RUNTIME Input -->
				  <div class="d-flex align-items-center mb-2">
					<label class="me-2">Runtime (MM:SS):</label>
					<input 
					  type="text"
					  class="form-control form-control-sm form-control-solid w-100 entry-runtime"
					  placeholder="MM:SS"
					  value="${convertRuntimeToTime(entry.runtime)}"
					  style="max-width:120px"
					/>
				  </div>

				  <!-- ENABLE TIMES CHECKBOX -->
				  <div class="form-check form-check-custom form-check-solid">
					<input
					  class="form-check-input entry-enable-times"
					  type="checkbox"
					  ${parseInt(entry.enable_times) === 1 ? "checked" : ""}
					/>
					<label class="form-check-label ms-2" for="enableTimes${entry.schedule_id}">
					  Enable times for each run
					</label>
				  </div>

				</div>
			  </div>
			`).join("") || ""
		  }
		</div>
	  </div>
	`;

	scheduleContainer.appendChild(card);

	// 2) Attach event listeners for dynamic saving
	attachScheduleListeners(card, scheduleEntries);
  }

  /**
   * 5) Attach event listeners for the "Use Live Schedule" checkbox
   *    and each schedule entry changes.
   */
  function attachScheduleListeners(card, scheduleEntries) {
	// A) Listen for changes on the "use_live_schedule" checkbox
	const liveScheduleCheckbox = card.querySelector('#useLiveScheduleCheckbox');
	if (liveScheduleCheckbox) {
	  liveScheduleCheckbox.addEventListener('change', () => {
		saveUpdatedSettings(card, scheduleEntries);
	  });
	}

	// B) For each schedule entry row, we watch changes in runtime or enable_times
	const entryRows = card.querySelectorAll('.schedule-entry-row');
	entryRows.forEach((row) => {
	  const runtimeInput = row.querySelector('.entry-runtime');
	  const enableTimesCheckbox = row.querySelector('.entry-enable-times');

	  runtimeInput?.addEventListener('blur', () => {
		saveUpdatedSettings(card, scheduleEntries);
	  });
	  enableTimesCheckbox?.addEventListener('change', () => {
		saveUpdatedSettings(card, scheduleEntries);
	  });
	});
  }

  /**
   * 6) Gather changes from the card & send to the server.
   */
  function saveUpdatedSettings(card, originalEntries) {
	// 1) use_live_schedule
	const liveScheduleCheckbox = card.querySelector('#useLiveScheduleCheckbox');
	const useLiveVal = liveScheduleCheckbox?.checked ? 1 : 0;

	// 2) Build updated entries array
	const updatedEntries = originalEntries.map((entry) => {
	  const rowEl = card.querySelector(`.schedule-entry-row[data-schedule-id="${entry.schedule_id}"]`);
	  if (!rowEl) return entry; // Shouldn't happen, but fallback

	  const runtimeInput = rowEl.querySelector('.entry-runtime');
	  const enableTimesCheckbox = rowEl.querySelector('.entry-enable-times');

	  return {
		schedule_id:   entry.schedule_id,
		name:          entry.name, // not strictly needed for saving, if ID is enough
		runtime:       convertTimeToRuntime(runtimeInput?.value || "0"),
		enable_times:  enableTimesCheckbox?.checked ? 1 : 0
	  };
	});

	// 3) POST to server
	const payload = {
	  use_live_schedule: useLiveVal,
	  entries: updatedEntries
	};

	console.log("Saving schedule settings =>", payload);
	fetch(
	  `${API_BASE_URL}?api=schedule_settings&competitionCode=${encodeURIComponent(competitionCode)}`,
	  {
		method: "POST",
		headers: getAuthHeaders(true),
		body: JSON.stringify(payload),
	  }
	)
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null; // short-circuit
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return; // short-circuit
		if (data.success) {
		  console.log("Schedule settings updated successfully.");
		} else {
		  console.error("Error updating schedule settings:", data.error);
		  if (String(data.error || "").toLowerCase().includes("invalid")) {
			alert("Session invalid. Signing out...");
			localStorage.removeItem("user");
			window.location.href = "index.html";
		  }
		}
	  })
	  .catch((error) => console.error("Error saving schedule settings:", error));
  }

  /**
   * Utility to convert an integer "runtime" (seconds) into "MM:SS"
   */
  function convertRuntimeToTime(runtime) {
	if (!runtime) return "00:00";
	const minutes = Math.floor(runtime / 60).toString().padStart(2, "0");
	const seconds = (runtime % 60).toString().padStart(2, "0");
	return `${minutes}:${seconds}`;
  }

  /**
   * Utility to convert "MM:SS" back to integer seconds
   */
  function convertTimeToRuntime(time) {
	if (!time || !/^(\d{1,2}):(\d{2})$/.test(time)) return 0;
	const [minutes, seconds] = time.split(":").map(Number);
	return minutes * 60 + seconds;
  }
});