let storedCompetition; // Declare globally

document.addEventListener("DOMContentLoaded", function () {
  const localUser = JSON.parse(localStorage.getItem("user")) || {};
  const bearerToken = localUser.bearer || null;

  // If there's no bearer token, sign out immediately
  if (!bearerToken) {
	console.error("No bearer token found in localUser. Signing out...");
	localStorage.removeItem("user");
	window.location.href = "index.html";
	return;
  }

  function getAuthHeaders() {
	return {
	  "Content-Type": "application/json",
	  "Authorization": `Bearer ${bearerToken}`
	};
  }

  function handleNotOkResponse(response) {
	console.error(
	  `API response not OK (${response.status} ${response.statusText}). Signing out...`
	);
	localStorage.removeItem("user");
	window.location.href = "index.html";
  }

  // -------------------------
  // 2) Inject basic CSS
  // -------------------------
  const style = document.createElement("style");
  style.type = "text/css";
  style.innerHTML = `
	.bib-number {
	  font-size: 0.8em;
	  color: #666;
	  margin-left: 4px;
	}
	.highlight-row {
	  background-color: #f1f1f1;
	}
	/* Simple modal styling for "Request Protest" */
	#protest-modal {
	  position: fixed;
	  top: 0;
	  left: 0;
	  width: 100%;
	  height: 100%;
	  background: rgba(0,0,0,0.5);
	  display: none; /* hidden by default */
	  z-index: 9999;
	}
	#protest-modal .modal-content {
	  background: #fff;
	  padding: 1rem;
	  margin: 10% auto;
	  max-width: 400px;
	  border-radius: 5px;
	}
	#protest-modal .modal-content h4 {
	  margin-top: 0;
	}
	#protest-modal .modal-content .modal-actions {
	  display: flex;
	  justify-content: flex-end;
	  gap: 0.5rem;
	  margin-top: 1rem;
	}

	/* Badges for different events */
	.badge {
	  display: inline-flex;
	  align-items: center;
	  vertical-align: middle;
	  padding: 0.3rem 0.5rem;
	  border-radius: 0.3rem;
	  font-size: 0.75rem;
	  font-weight: 600;
	  margin-right: 0.5rem;
	  color: #fff;
	}
	.bg-primary { background-color: #0d6efd; }
	.bg-danger  { background-color: #dc3545; }

	/* A simple success alert */
	.alert {
	  padding: 1rem;
	  margin: 1rem 0;
	  border: 1px solid transparent;
	  border-radius: 0.25rem;
	}
	.alert-success {
	  color: #0f5132;
	  background-color: #d1e7dd;
	  border-color: #badbcc;
	}
  `;
  document.head.appendChild(style);

  // -------------------------
  // 3) Retrieve competition
  // -------------------------
  storedCompetition = JSON.parse(localStorage.getItem("activeCompetition"));
  if (!storedCompetition || !storedCompetition.code) {
	console.error("No active competition found in local storage!");
	return;
  }

  const officialId      = localUser.id || null;
  const iwwfId          = localUser.iwwf_id || null;
  const competitionCode = storedCompetition.code;

  // 4) Fetch schedule data
  fetchScheduleData(competitionCode);

  // 5) Prepare "Request Protest" modal
  const protestModalHTML = `
	<div id="protest-modal">
	  <div class="modal-content">
		<h4 id="protest-modal-title">Request Protest</h4>
		<textarea id="protest-remark" rows="3" placeholder="Enter your remark..."></textarea>
		<div class="modal-actions">
		  <button id="protest-cancel" class="btn btn-secondary">Cancel</button>
		  <button id="protest-submit" class="btn btn-primary">Submit</button>
		</div>
	  </div>
	</div>
  `;
  document.body.insertAdjacentHTML("beforeend", protestModalHTML);

  const protestModal      = document.getElementById("protest-modal");
  const protestModalTitle = document.getElementById("protest-modal-title");
  const protestRemark     = document.getElementById("protest-remark");
  const protestCancel     = document.getElementById("protest-cancel");
  const protestSubmit     = document.getElementById("protest-submit");
  let protestRunId        = null;
  let protestStatus       = null; // e.g. 3 (FRS) or 4 (DNS)

  protestCancel.addEventListener("click", function() {
	protestModal.style.display = "none";
  });

  protestSubmit.addEventListener("click", function() {
	const remarkText = protestRemark.value.trim();
	if (!remarkText) {
	  alert("Please enter a remark for this action.");
	  return;
	}
	if (!protestRunId || !officialId) {
	  alert("Missing run or official info!");
	  return;
	}

	const payload = {
	  officialId:       iwwfId,
	  competitionCode:  competitionCode,
	  runId:            protestRunId,
	  status:           protestStatus,
	  remark:           remarkText
	};

	fetch(`${API_BASE_URL}?api=protests`, {
	  method: "POST",
	  headers: getAuthHeaders(),
	  body: JSON.stringify(payload)
	})
	.then(res => {
	  if (!res.ok) {
		handleNotOkResponse(res);
		return null; // stop further .then
	  }
	  return res.json();
	})
	.then(() => {
	  if (!protestModal.style.display) return;
	  protestModal.style.display = "none";
	  fetchScheduleData(competitionCode);
	})
	.catch(err => {
	  console.error("Error submitting protest:", err);
	  alert("Error submitting protest");
	  protestModal.style.display = "none";
	});
  });

  // 6) fetchScheduleData
  function fetchScheduleData(competitionCode) {
	fetch(`${API_BASE_URL}?api=schedule&competitionCode=${competitionCode}`, {
	  method: "GET",
	  headers: getAuthHeaders()
	})
	.then((response) => {
	  if (!response.ok) {
		handleNotOkResponse(response);
		return null;
	  }
	  return response.json();
	})
	.then((data) => {
	  if (!data) return;
	  if (!data || !Array.isArray(data.data)) {
		console.error("Unexpected API response format.");
		return;
	  }

	  const allRuns = data.data.flatMap((schedule) => {
		const eventName = schedule.event_name || "";
		return schedule.runs.map((run) => ({
		  ...run,
		  eventName,
		  groupName: buildGroupName(schedule, run, eventName),
		}));
	  });

	  // If no runs at all
	  if (allRuns.length === 0) {
		console.warn("No runs available for this competition.");
		showEmptyCard("No runs available.");
		return;
	  }

	  // Attempt to find the active run
	  let activeRunIndex = allRuns.findIndex((run) => run.active === 1);

	  // If none found => show final "Competition done" alert
	  if (activeRunIndex === -1) {
		console.warn("No active run found => competition is presumably done.");
		showCompetitionDone();
		return;
	  }

	  // Skip "riding" runs => (status=0 && real_time>0)
	  while (
		activeRunIndex < allRuns.length &&
		allRuns[activeRunIndex].status === 0 &&
		allRuns[activeRunIndex].real_time > 0
	  ) {
		activeRunIndex++;
	  }

	  // If we've run beyond the array => also show "done"
	  if (activeRunIndex >= allRuns.length) {
		console.warn("All possible runs are done => competition presumably finished.");
		showCompetitionDone();
		return;
	  }

	  // Now figure out prev/active/next
	  const prevRun   = allRuns[activeRunIndex - 1] || null;
	  const activeRun = allRuns[activeRunIndex]     || null;
	  const nextRun   = allRuns[activeRunIndex + 1] || null;

	  generateCard(prevRun, activeRun, nextRun);
	})
	.catch((error) => {
	  console.error("Error fetching schedule data:", error);
	  alert("Error fetching schedule data: " + error);
	});
  }

  /**
   * Build group name with optional badges
   */
  function buildGroupName(schedule, run, eventName) {
	let eventBadge = "";
	const lowered = (eventName || "").toLowerCase();
	if (lowered.includes("wakeboard")) {
	  eventBadge = `<span class="badge bg-primary me-1">WB</span>`;
	} else if (lowered.includes("wakeskate")) {
	  eventBadge = `<span class="badge bg-danger me-1">WS</span>`;
	}

	return `
	  ${eventBadge}
	  ${schedule.category_name || "Unknown Category"}
	  ${schedule.heatsystem_name || "Unknown Round"}
	  Group ${run.group}
	`;
  }

  /**
   * If no active run => we show a success alert
   */
  function showCompetitionDone() {
	const container = document.getElementById("kt_app_content_container_dock");
	if (!container) return;

	container.innerHTML = `
	  <div class="alert alert-success">
		<h4>Congratulations!</h4>
		<p>The competition is finished. No more active runs.</p>
	  </div>
	`;
  }

  function generateCard(prevRun, activeRun, nextRun) {
	console.log("Generating card with:", { prevRun, activeRun, nextRun });

	const container = document.getElementById("kt_app_content_container_dock");
	if (!container) {
	  console.error("Container element not found!");
	  return;
	}
	container.innerHTML = "";

	const groupTitle = activeRun ? activeRun.groupName : "Unknown Group";

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

	card.innerHTML = `
	  <div class="card-header">
		<h3 class="card-title">${groupTitle}</h3>
	  </div>
	  <div class="card-body">
		<table class="table table-hover">
		  <tbody>
			${generateRunRow(prevRun, "Riding Athlete")}
			${generateRunRow(activeRun, "Ready Athlete", true)}
			${generateRunRow(nextRun, "Next Athlete")}
		  </tbody>
		</table>
	  </div>
	  <div class="card-footer d-flex flex-column">
		<div class="d-flex justify-content-between">
		  <button class="btn btn-success" id="startRunBtn"  ${!activeRun ? "disabled" : ""}>Start</button>
		  <button class="btn btn-warning" id="frsRunBtn"    ${!activeRun ? "disabled" : ""}>DNS</button>
		  <button class="btn btn-primary" id="dnsRunBtn"    ${!activeRun ? "disabled" : ""}>Delay</button>
		</div>
		<hr>
		<div class="mt-3 text-center">
		  <p id="timeUntilNext" class="fw-bold">Time until next athlete: Calculating...</p>
		</div>
	  </div>
	`;
	container.appendChild(card);

	if (activeRun) {
	  document.getElementById("startRunBtn")?.addEventListener("click", function () {
		saveTimestamp(activeRun.run_id, "start", refreshActiveCard);
	  });
	  // DNS button => protestStatus=4
	  document.getElementById("dnsRunBtn")?.addEventListener("click", function () {
		protestRunId  = activeRun.run_id;
		protestStatus = 4;  // DNS
		protestRemark.value = "";
		protestModalTitle.textContent = "Request Delay";
		protestModal.style.display = "block";
	  });
	  // FRS button => protestStatus=3
	  document.getElementById("frsRunBtn")?.addEventListener("click", function () {
		protestRunId  = activeRun.run_id;
		protestStatus = 3;  // FRS
		protestRemark.value = "";
		protestModalTitle.textContent = "Request DNS";
		protestModal.style.display = "block";
	  });

	  updateTimeUntilNext(activeRun);
	} else {
	  const timeElem = document.getElementById("timeUntilNext");
	  if (timeElem) {
		timeElem.textContent = "No active athlete currently selected.";
	  }
	}
  }

  /**
   * If container not found or no data => we show an empty card
   */
  function showEmptyCard(message) {
	const container = document.getElementById("kt_app_content_container_dock");
	if (!container) return;

	container.innerHTML = `
	  <div class="card mb-3 mobile-optimized-card">
		<div class="card-header">
		  <h3 class="card-title">No Active Run</h3>
		</div>
		<div class="card-body">
		  <p>${message}</p>
		</div>
	  </div>
	`;
  }

  function refreshActiveCard() {
	console.log("Refreshing active card...");
	if (!storedCompetition || !storedCompetition.code) {
	  console.error("No active competition found in local storage during refresh.");
	  return;
	}
	fetchScheduleData(storedCompetition.code);
  }

  function generateRunRow(run, label, isActive = false) {
	if (!run) {
	  return `
		<tr>
		  <td>${label}</td>
		  <td>N/A</td>
		  <td>N/A</td>
		  <td></td>
		</tr>
	  `;
	}

	let displayTimeSeconds = 0;
	if (run.real_time && run.real_time > 0) {
	  displayTimeSeconds = run.real_time;
	} else if ((!run.real_time || run.real_time === 0) && run.delay && run.delay !== 0) {
	  displayTimeSeconds = (run.calculated_planned_time ?? 0) + run.delay;
	} else {
	  displayTimeSeconds = run.calculated_planned_time ?? 0;
	}

	const displayTime = formatTime(displayTimeSeconds);
	const name        = `${run.athlete_name || "Unknown Athlete"} - Run ${run.run || "N/A"}`;
	const bibNumber   = run.bib ? `<span class="bib-number">(${run.bib})</span>` : "";
	const statusIcon  = getStatusIcon(run.status);

	return `
	  <tr class="${isActive ? "highlight-row" : ""}">
		<td>${label}</td>
		<td>${displayTime}</td>
		<td>${name}${bibNumber}</td>
		<td class="text-end">${statusIcon}</td>
	  </tr>
	`;
  }

  function getStatusIcon(status) {
	switch (status) {
	  case 0:
		return `<i class="bi bi-pause-circle-fill text-warning" title="Pending"></i>`;
	  case 1:
		return `<i class="bi bi-check-circle-fill text-success" title="Completed"></i>`;
	  case 2:
		return `<i class="bi bi-play-circle-fill text-primary" title="In Progress"></i>`;
	  default:
		return `<i class="bi bi-question-circle-fill text-muted" title="Unknown"></i>`;
	}
  }

  function saveTimestamp(runId, action, callback) {
	if (!runId) {
	  console.error("Run ID is missing.");
	  return;
	}
	const timestamp = Math.floor(Date.now() / 1000);

	fetch(`${API_BASE_URL}?api=updateRunTimestamp`, {
	  method: "POST",
	  headers: getAuthHeaders(),
	  body: JSON.stringify({ run_id: runId, timestamp, action }),
	})
	.then((res) => {
	  if (!res.ok) {
		handleNotOkResponse(res);
		return null;
	  }
	  return res.json();
	})
	.then((data) => {
	  if (!data) return;
	  if (data.success) {
		console.log(`Timestamp saved successfully for Run ID ${runId}. Action: ${action}`);
		if (callback) callback();
	  } else {
		console.error(`Failed to save timestamp for Run ID ${runId}.`);
	  }
	})
	.catch((error) => {
	  console.error("Error saving timestamp:", error);
	  alert("Error saving timestamp: " + error);
	});
  }

  function formatTime(timestamp) {
	if (!timestamp) return "N/A";
	const dateObj = new Date(timestamp * 1000);
	return dateObj.toLocaleTimeString([], {
	  hour: "2-digit",
	  minute: "2-digit",
	  second: "2-digit",
	});
  }

  function updateTimeUntilNext(activeRun) {
	const timeUntilNextElement = document.getElementById("timeUntilNext");
	if (!timeUntilNextElement) return;
	if (!activeRun) {
	  timeUntilNextElement.textContent = "Time until next athlete: N/A";
	  return;
	}

	let targetSeconds = 0;
	if (activeRun.real_time && activeRun.real_time > 0) {
	  targetSeconds = activeRun.real_time;
	} else if (
	  (!activeRun.real_time || activeRun.real_time === 0) &&
	  activeRun.delay &&
	  activeRun.delay !== 0
	) {
	  targetSeconds = (activeRun.calculated_planned_time ?? 0) + activeRun.delay;
	} else {
	  targetSeconds = activeRun.calculated_planned_time ?? 0;
	}

	if (!targetSeconds) {
	  timeUntilNextElement.textContent = "Time until next athlete: N/A";
	  return;
	}

	function updateCountdown() {
	  const now = Math.floor(Date.now() / 1000);
	  let diff = targetSeconds - now;

	  const absDiff = Math.abs(diff);
	  const minutes = Math.floor(absDiff / 60);
	  const seconds = absDiff % 60;

	  timeUntilNextElement.classList.remove("text-success","text-warning","text-danger");

	  if (absDiff <= 15) {
		timeUntilNextElement.classList.add("text-success");
	  } else if (absDiff <= 60) {
		timeUntilNextElement.classList.add("text-warning");
	  } else {
		timeUntilNextElement.classList.add("text-danger");
	  }

	  let formattedTime = diff >= 0
		? `${minutes}:${seconds.toString().padStart(2, "0")}`
		: `-${minutes}:${seconds.toString().padStart(2, "0")}`;

	  timeUntilNextElement.textContent = `Time until next athlete: ${formattedTime}`;
	}

	updateCountdown();
	setInterval(updateCountdown, 1000);
  }
});