/******************************************************
 * protestCheck.js
 *
 * 1) Checks for open/other protests for a given 
 *    competition code (status=0,3,4).
 * 2) Displays them in an alert:
 *    - If status=3 => "alert-warning" & "DNS requested" (+ Close button)
 *    - If status=4 => "alert-primary" & "Delay submitted" (+ Close button)
 *    - Otherwise => "alert-danger" & "Protest" for status=0 (+ Accept/Decline buttons)
 * 3) If data-section=0 => hide ALL buttons
 *    If data-section≠0 => show Accept/Decline for status=0,
 *                         show Close for status=3 or 4
 * 4) Updates protest status via an API call; includes iwwf_id if available.
 * 5) Refreshes automatically every 5 seconds, re-renders if there's a difference.
 ******************************************************/

document.addEventListener("DOMContentLoaded", function () {
		
  // -------------------------
  // 1) Get user & bearer token
  // -------------------------
  const storedUser = JSON.parse(localStorage.getItem("user")) || {};
  const bearerToken = storedUser.bearer || null;

  // If no bearer => sign out
  if (!bearerToken) {
	console.error("No bearer token found in local storage user!");
	localStorage.removeItem("user");
	window.location.href = "index.html";
	return;
  }

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

  // Helper to handle non-OK responses => sign out
  function handleNotOkResponse(response) {
	console.error(
	  `API response not OK (${response.status} ${response.statusText}). Signing out...`
	);
	//alert("Session expired or invalid. Signing out...");
	localStorage.removeItem("user");
	window.location.href = "index.html";
  }

  // 1) Locate the container for protest alerts
  const protestContainer = document.getElementById("protest-container");
  if (!protestContainer) {
	console.error("No #protest-container found in DOM. Aborting protest check.");
	return;
  }

  // 1A) Also parse data-section
  const dataSection = parseInt(protestContainer.getAttribute("data-section") || "1", 10);

  // 2) Retrieve competition code from localStorage
  const storedEvent = JSON.parse(localStorage.getItem("activeCompetition")) || {};
  const competitionCode = storedEvent.code || null;
  if (!competitionCode) {
	console.warn("No competition code in localStorage. Skipping protest check.");
	return;
  }

  // 2A) Retrieve the current user object for iwwf_id
  const iwwfId = storedUser.iwwf_id || null;

  // 2B) Keep track of last known protest data
  let lastOpenProtestsJSON = ""; // We'll store a JSON string for easy comparison

  // 3) A function to fetch & render protests
  function fetchAndRenderProtests() {
	// We load protests with status ∈ {0,3,4}, shown with different alert colors
	const url = `${API_BASE_URL}?api=protests&competitionCode=${encodeURIComponent(
	  competitionCode
	)}`;

	fetch(url, {
	  method: "GET",
	  headers: getAuthHeaders(),
	})
	  .then((response) => {
		if (!response.ok) {
		  handleNotOkResponse(response);
		  return null; // stop further .then
		}
		return response.json();
	  })
	  .then((json) => {
		if (!json) return; // means handleNotOkResponse triggered

		if (!json.success) {
		  console.warn("Failed to fetch protests:", json.error);
		  protestContainer.innerHTML = "";
		  return;
		}

		const allProtests = json.data || [];
		// Filter for relevant statuses
		const relevantProtests = allProtests.filter(
		  (p) => p.status === 0 || p.status === 3 || p.status === 4
		);

		// Compare newly fetched protests to last known
		const currentProtestsJSON = JSON.stringify(relevantProtests);
		if (currentProtestsJSON === lastOpenProtestsJSON) {
		  // No change => do nothing
		  return;
		}
		// Otherwise => store new string & re-render
		lastOpenProtestsJSON = currentProtestsJSON;

		if (relevantProtests.length === 0) {
		  // None to show => clear container
		  protestContainer.innerHTML = "";
		  return;
		}

		// Build the HTML
		let html = "";
		relevantProtests.forEach((protest) => {
		  const protestId = protest.id;
		  const runId = protest.run_id;
		  const remark = protest.remark || "(no remark)";
		  const official = protest.official || "(unknown official)";
		  const athleteName = protest.athlete_name || "(unknown athlete)";
		  const runNumber = protest.run_number || "?";

		  // Determine alert color class & header text
		  let alertClass = "alert-danger";
		  let headerText = "Protest"; // default for status=0
		  if (protest.status === 3) {
			alertClass = "alert-warning";
			headerText = "DNS requested";
		  } else if (protest.status === 4) {
			alertClass = "alert-primary";
			headerText = "Delay submitted";
		  }

		  // Buttons
		  let buttonsHTML = "";
		  if (dataSection !== 0) {
			// If status=0 => Accept & Decline
			// else if status=3 or 4 => "Close"
			if (protest.status === 0) {
			  buttonsHTML = `
				<button class="btn btn-sm btn-success protest-accept-btn me-2">Accept</button>
				<button class="btn btn-sm btn-secondary protest-decline-btn">Decline</button>
			  `;
			} else if (protest.status === 3 || protest.status === 4) {
			  buttonsHTML = `
				<button class="btn btn-sm btn-success protest-accept-btn me-2">Close</button>
			  `;
			}
		  }

		  html += `
			<div class="alert ${alertClass} p-3 mb-3" data-protest-id="${protestId}">
			  <div class="d-flex justify-content-between align-items-start">
				<div class="flex-grow-1">
				  <strong>${headerText}</strong><br>
				  Athlete: <em>${athleteName}</em>, 
				  Run: <em>${runNumber}</em>, 
				  Official: <em>${official}</em>
				</div>
				<div>
				  ${buttonsHTML}
				</div>
			  </div>
			  <div class="mt-2">
				<strong>Reason:</strong> ${remark}
			  </div>
			</div>
		  `;
		});

		protestContainer.innerHTML = html;

		// Handle Accept/Decline/Close
		const acceptButtons = protestContainer.querySelectorAll(".protest-accept-btn");
		const declineButtons = protestContainer.querySelectorAll(".protest-decline-btn");

		acceptButtons.forEach((btn) => {
		  btn.addEventListener("click", function () {
			const parentAlert = btn.closest(".alert");
			const pId = parentAlert?.getAttribute("data-protest-id");
			if (!pId) return;

			// "Accept" or "Close" => set status=1
			updateProtestStatus(pId, 1).then((ok) => {
			  if (ok) parentAlert.remove();
			});
		  });
		});

		declineButtons.forEach((btn) => {
		  btn.addEventListener("click", function () {
			const parentAlert = btn.closest(".alert");
			const pId = parentAlert?.getAttribute("data-protest-id");
			if (!pId) return;

			// Decline => set status=2
			updateProtestStatus(pId, 2).then((ok) => {
			  if (ok) parentAlert.remove();
			});
		  });
		});
	  })
	  .catch((err) => {
		console.error("Error fetching protests:", err);
		protestContainer.innerHTML = "";
	  });
  }

  // 4) Update protest status
  function updateProtestStatus(protestId, status) {
	const bodyObj = { id: protestId, status: status };
	if (iwwfId) {
	  bodyObj.iwwf_id = iwwfId;
	}

	return fetch(`${API_BASE_URL}?api=protests`, {
	  method: "POST",
	  headers: getAuthHeaders(),
	  body: JSON.stringify(bodyObj),
	})
	  .then((res) => {
		if (!res.ok) {
		  handleNotOkResponse(res);
		  return null;
		}
		return res.json();
	  })
	  .then((json) => {
		if (!json) return false; // handleNotOkResponse triggered
		if (!json.success) {
		  //alert("Failed to update protest status: " + (json.error || "Unknown error"));
		  return false;
		}
		return true;
	  })
	  .catch((err) => {
		console.error("Error updating protest status:", err);
		//alert("Error updating protest status: " + err);
		return false;
	  });
  }

  // 5) Call fetchAndRenderProtests initially
  fetchAndRenderProtests();

  // 6) Refresh every 5 seconds => compare + re-render if changed
  setInterval(fetchAndRenderProtests, 5000);
});