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) Find container for general settings
  const container = document.getElementById("settings-container-general");
  if (!container) {
	console.error("No element with ID 'settings-container-general' 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 current settings from the server
  fetchSettings(competitionCode);

  /**
   * Fetch existing settings from server (with Bearer).
   */
  function fetchSettings(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; // from short-circuit
		if (data.success) {
		  renderSettingsCard(data.settings, data.events, data.heatsystems);
		} else {
		  console.error("Failed to fetch settings:", data.error || "Unknown error");
		  // If specifically an invalid session => sign out
		  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 settings:", error));
  }

  /**
   * Converts ISO or "YYYY-MM-DD HH:mm" to "YYYY-MM-DDTHH:mm" for input[type="datetime-local"]
   */
  function convertDatetime(dt) {
	if (!dt) return "";
	// Accept both "YYYY-MM-DD HH:mm" and "YYYY-MM-DDTHH:mm" or "YYYY-MM-DDTHH:mm:ss"
	let val = dt.replace(" ", "T").substring(0, 16);
	// Remove seconds if present (datetime-local doesn't accept them)
	if (val.length > 16) val = val.substring(0, 16);
	return val;
  }

  /**
   * Render the main "General Settings" card
   */
  function renderSettingsCard(settings, events, heatSystems) {
	container.innerHTML = ""; // Clear existing

	const card = document.createElement("div");
	card.classList.add("card");

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

		<!-- COMPETITION CODE -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3"><span>Competition Code</span></div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<input class="form-control form-control-solid form-control-sm" 
				   type="text" 
				   name="competition_code" 
				   value="${settings.competition_code || ""}" 
				   readonly>
		  </div>
		</div>

		<!-- EVENTS -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3"><span>Events</span></div>
		  </div>
		  <div class="col-xl-9 fv-row">
			${
			  events?.map((event) => `
				<div class="form-check form-check-sm form-check-custom form-check-solid mb-3">
				  <input
					type="checkbox"
					class="form-check-input event-checkbox"
					id="event-${event.id}"
					name="events"
					value="${event.id}"
					checked
					disabled
				  />
				  <label class="form-label form-check-label ms-3" for="event-${event.id}">
					${event.event_name}
				  </label>
				</div>
			  `).join("") || ""
			}
		  </div>
		</div>

		<!-- HEAT SYSTEM -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3"><span>Heat System</span></div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<select class="form-control form-control-solid form-control-sm" name="heatsystem" disabled>
			  ${
				heatSystems?.map(heatSystem => `
				  <option value="${heatSystem.id}"
					${settings.heatsystem == heatSystem.id ? "selected" : ""}>
					${heatSystem.name}
				  </option>
				`).join("") || ""
			  }
			</select>
		  </div>
		</div>

		<!-- NUMBER OF JUDGES -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3"><span>Number of Judges</span></div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<select class="form-control form-control-solid form-control-sm" name="judges">
			  ${Array.from({ length: 7 }, (_, i) => i + 1)
				.map(num => `
				  <option value="${num}"
					${settings.judges == num ? "selected" : ""}>
					${num} Judges
				  </option>
				`).join("")}
			</select>
		  </div>
		</div>

		<!-- JUDGING METHOD -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3"><span>Judging Method</span></div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<select class="form-control form-control-sm form-control-solid" name="judging">
			  <option value="1" ${settings.judging == 1 ? "selected" : ""}>Average Judging</option>
			  <option value="2" ${settings.judging == 2 ? "selected" : ""}disabled>Median Judging (coming soon)</option>
			  <option value="3" ${settings.judging == 3 ? "selected" : ""}disabled>Highest and Lowest Out Judging (coming soon)</option>
			</select>
		  </div>
		</div>

		<!-- MODE -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3"><span>Mode</span></div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<select class="form-control form-control-solid form-control-sm" name="mode">
			  <option value="1" ${settings.mode == 1 ? "selected" : ""}>Scorer Mode</option>
			  <option value="2" ${settings.mode == 2 ? "selected" : ""}>Judges Mode</option>
			</select>
		  </div>
		</div>

		<!-- RUNTIME -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3">
			  <span>Runtime (MM:SS)</span>
			</div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<input 
			  class="form-control form-control-solid form-control-sm" 
			  type="text" 
			  name="runtime" 
			  pattern="^\\d{1,2}:\\d{2}$" 
			  placeholder="MM:SS"
			  value="${convertRuntimeToTime(settings.runtime)}">
		  </div>
		</div>

		<!-- SCHEDULE PUBLISH DATETIME PICKER -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3">
			  <span>Go Live</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="publish"
				id="publishCheckbox"
				${parseInt(settings.publish) === 1 ? "checked" : ""}
			  />
			  <label class="form-check-label ms-2" for="publishCheckbox">
				If activated the system will show the Schedule, Live Results and Competiton Startlists and Results. 
			  </label>
			</div>
		  </div>
		</div>

		<!-- SHEETS -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3"><span>Judging Sheets</span></div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<select class="form-control form-control-solid form-control-sm" name="sheets">
			  <option value="0" ${settings.sheets == 0 ? "selected" : ""}>New School Sheets</option>
			  <option value="1" ${settings.sheets == 1 ? "selected" : ""}>Old School Sheets</option>
			  <option value="2" ${settings.sheets == 2 ? "selected" : ""}>PDF Sheets (beta)</option>
			</select>
		  </div>
		</div>

		<!-- SCORE DIFFERENCE TOLERANCE -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3">
			  <span>Allowed Score Difference</span>
			</div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<select class="form-control form-control-solid form-control-sm" name="score_diff">
			  ${[0,10,20,30,40,50,60,70,80,90,100]
				.map(diff => `
				  <option value="${diff}" ${
					(settings.score_difference && parseInt(settings.score_difference) === diff)
					  ? "selected"
					  : ""
				  }>${diff} Points</option>
				`).join("")}
			</select>
		  </div>
		</div>

		<!-- PLACE DIFFERENCE TOLERANCE -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3">
			  <span>Allowed Place Difference</span>
			</div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<select class="form-control form-control-solid form-control-sm" name="place_diff">
			  ${[0,1,2,3,4,5,6,7,8,9,10]
				.map(pdiff => `
				  <option value="${pdiff}" ${
					(settings.place_difference && parseInt(settings.place_difference) === pdiff)
					  ? "selected"
					  : ""
				  }>${pdiff} Place${pdiff===1?"":"s"}</option>
				`).join("")}
			</select>
		  </div>
		</div>

		<!-- OVERRULING OPTION (CHECKBOX) -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3">
			  <span>Overruling</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="overruling"
				id="overrulingCheckbox"
				${parseInt(settings.overruling) === 1 ? "checked" : ""}
			  />
			  <label class="form-check-label ms-2" for="overrulingCheckbox">
				If activated the system will detect overruling issues.
			  </label>
			</div>
		  </div>
		</div>
		
		<!-- Livestream -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3">
			  <span>Livestream URL (only Youtube)</span>
			</div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<input 
			  type="text" 
			  class="form-control form-control-sm bib-input" 
			  value="${settings.livestream ?? ""}"
			  name="livestream"
			  min="0" 
			/>
		  </div>
		</div>
		
		<!-- Team Results -->
		<div class="row mb-8">
		  <div class="col-xl-3">
			<div class="fs-6 fw-semibold mt-2 mb-3"><span>Team Results</span></div>
		  </div>
		  <div class="col-xl-9 fv-row">
			<select class="form-control form-control-solid form-control-sm" name="team_results">
			  <option value="0" ${settings.team_results == 0 ? "selected" : ""}disabled>No Team Results</option>
			  <option value="1" ${settings.team_results == 1 ? "selected" : ""}disabled>Teams by country</option>
			  <option value="2" ${settings.team_results == 2 ? "selected" : ""}disabled>Teams by region</option>
			  <option value="3" ${settings.team_results == 3 ? "selected" : ""}disabled>Teams by homecable</option>
			</select>
		  </div>
		</div>
		
	  </div>
	`;

	container.appendChild(card);

	// 2) Attach change listeners for dynamic saving
	attachDynamicListeners(card, competitionCode);
  }

  function attachDynamicListeners(card, competitionCode) {
	const inputs = card.querySelectorAll("select, input");
	inputs.forEach((input) => {
	  input.addEventListener("change", function () {
		// Build the object to send to the server
		const updatedSettings = {
		  competition_code:   card.querySelector('input[name="competition_code"]').value,
		  heatsystem:         card.querySelector('select[name="heatsystem"]').value,
		  judges:             card.querySelector('select[name="judges"]').value,
		  judging:            card.querySelector('select[name="judging"]').value,
		  mode:               card.querySelector('select[name="mode"]').value,
		  sheets:             card.querySelector('select[name="sheets"]').value,
		  runtime:            convertTimeToRuntime(card.querySelector('input[name="runtime"]').value),
		  score_difference:   card.querySelector('select[name="score_diff"]').value,
		  place_difference:   card.querySelector('select[name="place_diff"]').value,
		  overruling:         card.querySelector('input[name="overruling"]').checked ? '1' : '0',
		  publish:            card.querySelector('input[name="publish"]').checked ? '1' : '0',
		  livestream:         card.querySelector('input[name="livestream"]').value,
		  team_results:       card.querySelector('select[name="team_results"]').value
		};

		updateSettings(competitionCode, updatedSettings);
	  });
	});
  }

  /**
   * Sends the updated settings back to the server (with Bearer).
   */
  function updateSettings(code, settings) {
	fetch(
	  `${API_BASE_URL}?api=settings&competitionCode=${encodeURIComponent(code)}`,
	  {
		method: "POST",
		headers: getAuthHeaders(true), // add Bearer
		body: JSON.stringify({ competitionCode: code, settings }),
	  }
	)
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null; 
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return; // short-circuit
		if (data.success) {
		  console.log("Settings updated successfully.");
		} else {
		  console.error("Error updating settings:", data.error);
		  // If specifically an invalid session => sign out
		  if (String(data.error || "").toLowerCase().includes("invalid")) {
			alert("Session invalid. Signing out...");
			localStorage.removeItem("user");
			window.location.href = "index.html";
		  }
		}
	  })
	  .catch((error) => console.error("Fetch error updating 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;
  }
});