document.addEventListener("DOMContentLoaded", function () {
  // --------------------------
  // 1) Retrieve Bearer token from localStorage user
  // --------------------------
  const localUser = JSON.parse(localStorage.getItem("user")) || {};
  const bearerToken = localUser.bearer || null;

  // We'll define a small helper so we don't repeat code:
  function getHeaders(isJson = true) {
	const headers = isJson ? { "Content-Type": "application/json" } : {};
	if (bearerToken) {
	  headers["Authorization"] = `Bearer ${bearerToken}`;
	}
	return headers;
  }

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

  // --------------------------
  // 2) Helper Functions
  // --------------------------

  /**
   * Nicely format the JSON response from import_xml
   * into a multiline string for the alert message.
   */
  function formatImportResponse(data) {
	// Example input JSON:
	// {
	//   "status": "success",
	//   "message": "Data processed successfully",
	//   "Competition Code:": "23EURO11",
	//   ...
	// }

	let result = "Import successful:\n\n";

	if (data.status) {
	  result += `Status: ${data.status}\n`;
	}
	if (data.message) {
	  result += `Message: ${data.message}\n`;
	}

	if (data["Competition Code:"]) {
	  result += `Competition Code: ${data["Competition Code:"]}\n`;
	}
	if (typeof data["Imported athletes:"] !== "undefined") {
	  result += `Imported athletes: ${data["Imported athletes:"]}\n`;
	}
	if (typeof data["Updated athletes:"] !== "undefined") {
	  result += `Updated athletes: ${data["Updated athletes:"]}\n`;
	}
	if (typeof data["Deleted athletes:"] !== "undefined") {
	  result += `Deleted athletes: ${data["Deleted athletes:"]}\n`;
	}
	if (typeof data["New athletes:"] !== "undefined") {
	  result += `New athletes: ${data["New athletes:"]}\n`;
	}

	if (data["Schedule information"]) {
	  result += `\nSchedule information:\n${data["Schedule information"]}\n`;
	}

	return result;
  }

  function generateTimelineItem(label, content) {
	return `
	  <div class="timeline-item">
		<div class="fs-6 fw-bold timeline-label text-gray-800" style="width: 90px;">
		  <span>${label}</span>
		</div>
		<div class="timeline-badge">
		  <i class="fa fa-genderless fs-1 text-secondary"></i>
		</div>
		<div class="timeline-content text-gray-800 ps-3">
		  <span>${content}</span>
		</div>
	  </div>`;
  }

function xmlToJson(xml) {
	  // Create the return object or string
	  let obj = {};
	
	  // Element node
	  if (xml.nodeType === 1) {
		// 1) process attributes
		if (xml.attributes.length > 0) {
		  for (let j = 0; j < xml.attributes.length; j++) {
			let attribute = xml.attributes.item(j);
			obj[attribute.nodeName] = attribute.nodeValue;
		  }
		}
	
		// 2) process child nodes
		if (xml.hasChildNodes()) {
		  for (let i = 0; i < xml.childNodes.length; i++) {
			let item = xml.childNodes.item(i);
	
			// Skip empty text nodes
			if (item.nodeType === 3 && item.nodeValue.trim() === "") {
			  continue;
			}
	
			// Text node: accumulate into _text
			if (item.nodeType === 3) {
			  obj._text = (obj._text || "") + item.nodeValue.trim();
			  continue;
			}
	
			// Element node: recurse
			let nodeName = item.nodeName;
			let value = xmlToJson(item);
	
			// Handle arrays when same nodeName appears multiple times
			if (obj[nodeName] === undefined) {
			  obj[nodeName] = value;
			} else if (Array.isArray(obj[nodeName])) {
			  obj[nodeName].push(value);
			} else {
			  obj[nodeName] = [obj[nodeName], value];
			}
		  }
		}
	  }
	  // Text node fallback
	  else if (xml.nodeType === 3) {
		return xml.nodeValue.trim();
	  }
	
	  return obj;
	}

  // --------------------------
  // 3) sendJsonToPhp => POST import_xml with Bearer
  // --------------------------
  function sendJsonToPhp(jsonData) {
	fetch(`${API_BASE_URL}?api=import_xml`, {
	  method: "POST",
	  headers: getHeaders(true),
	  body: JSON.stringify(jsonData),
	})
	  .then((response) => {
		// Check for 401
		if (!response.ok) {
		  if (response.status === 401) {
			localStorage.removeItem("user");
			window.location.href = "index.html";
			return;
		  }
		}
		return response.json();
	  })
	  .then((data) => {
		if (!data) return;
		const formattedMessage = formatImportResponse(data);
		alert(formattedMessage);

		// After successful import => re-fetch the dashboard
		fetchDashboard();
	  })
	  .catch((error) => {
		console.error("Error:", error);
		alert("Error: " + error.message);
	  });
  }

  // --------------------------
  // 4) Create the XML Import Card
  // --------------------------
  function createXmlImportCard() {
	const cardHTML = `
	  <div class="card" style="margin-bottom: 20px;">
		<div class="card-header border-0 pt-5" style="margin-bottom: -10px;">
		  <h3 class="flex-column align-items-start card-title">
			<span class="fw-bold text-dark card-label">Import EMS xml file</span>
		  </h3>
		</div>
		<div class="card-body text-center" style="padding: 10px;">
		  <form id="xmlForm">
			<label for="xmlFile" class="btn btn-primary">Import EMS xml file</label>
			<input type="file" id="xmlFile" name="xmlFile" accept=".xml" style="display: none;">
			<button type="submit" class="btn btn-secondary">Upload and Send</button>
		  </form>
		</div>
	  </div>
	`;

	const targetContainer = document.getElementById("importxml-container");
	if (!targetContainer) {
	  console.error("Target container not found!");
	  return;
	}

	targetContainer.insertAdjacentHTML("beforeend", cardHTML);

	const xmlForm = document.getElementById("xmlForm");
	if (!xmlForm) {
	  console.error("xmlForm element not found!");
	  return;
	}

	xmlForm.addEventListener("submit", function (event) {
	  event.preventDefault();
	  const file = document.getElementById("xmlFile").files[0];

	  if (!file) {
		alert("Please select an XML file.");
		return;
	  }

	  const reader = new FileReader();
	  reader.onload = function (e) {
		const xmlContent = e.target.result;
		const parser = new DOMParser();
		const xmlDoc = parser.parseFromString(xmlContent, "text/xml");

		if (xmlDoc.querySelector("parsererror")) {
		  console.error(
			"XML Parsing Error:",
			xmlDoc.querySelector("parsererror").textContent
		  );
		  alert("Error: Invalid XML file.");
		  return;
		}

		const json = xmlToJson(xmlDoc.documentElement);
		console.log("Converted JSON:", json);
		sendJsonToPhp(json);
	  };
	  reader.readAsText(file);
	});
  }

  // --------------------------
  // 5) Dashboard fetch
  // --------------------------
function fetchDashboard() {
	  let iwwfParam = "";
	  if (localUser && localUser.iwwf_id) {
		  iwwfParam = `&iwwf_id=${encodeURIComponent(localUser.iwwf_id)}`;
	  }
  
	  fetch(`${API_BASE_URL}?api=dashboard${iwwfParam}`, {
		  method: "GET",
		  headers: getHeaders(true),
	  })
		  .then((response) => {
			  if (!response.ok) {
				  if (response.status === 401) {
					  localStorage.removeItem("user");
					  window.location.href = "index.html";
					  return;
				  }
			  }
			  return response.json();
		  })
		  .then((data) => {
			  if (!data) return;
  
			  const eventsContainer = document.getElementById("events-container");
			  if (!eventsContainer) {
				  console.error("eventsContainer element not found!");
				  return;
			  }
  
			  if (!Array.isArray(data)) {
				  console.error("API returned data in an unexpected format, expected an array.");
				  return;
			  }
  
			  // Clear existing
			  eventsContainer.innerHTML = "";
  
			  // Grab any previously selected competition from localStorage
			  const storedEvent = JSON.parse(localStorage.getItem("activeCompetition"));
  
			  // Sort so that selected competition comes first
			  if (storedEvent && storedEvent.code) {
				  data.sort((a, b) => {
					  if (a.event.code === storedEvent.code) return -1;
					  if (b.event.code === storedEvent.code) return 1;
					  return 0;
				  });
			  }
  
			  data.forEach((item) => {
				  const event = item.event;
				  const isSelected = storedEvent && storedEvent.code === event.code;
  
				  const eventCard = document.createElement("div");
				  eventCard.classList.add("col");
				  eventCard.style.marginBottom = "20px";
  
				  let categoriesHtml = "Unknown";
				  if (Array.isArray(event.categories)) {
					  categoriesHtml = event.categories.join(", ");
				  } else if (typeof event.categories === "string") {
					  categoriesHtml = event.categories;
				  }
  
				  const btnClass = isSelected ? "btn btn-success" : "btn btn-primary";
				  const btnText = isSelected ? "Selected" : "Select";
				  const btnDisabled = isSelected ? "disabled" : "";
  
				  const exportEnabled = event.export_results === 1;
				  const exportBtnClass = exportEnabled
					  ? "btn btn-danger btn-sm float-end ms-md-6 export-event"
					  : "btn btn-danger btn-sm disabled float-end ms-md-6";
				  const exportBtnDisabled = exportEnabled ? "" : "disabled";
  
				  const cardHtml = `
					  <div class="card">
						  <div class="card-header">
							  <h3 class="flex-column align-items-start card-title">
								  <span class="fw-bold text-dark card-label">${event.name || "No Name"}</span>
								  <span class="fw-semibold text-muted mt-1 fs-7">
									  ${event.dates || "No Date Available"}
								  </span>
							  </h3>
						  </div>
						  <div class="card-body text-center pt-5">
							  <div class="text-start timeline-label">
								  ${generateTimelineItem("Location", event.location || "Unknown")}
								  ${generateTimelineItem("Type", event.type || "Unknown")}
								  ${generateTimelineItem(
									  "Disciplines",
									  Array.isArray(event.disciplines)
										  ? event.disciplines.join(", ")
										  : event.disciplines || "Unknown"
								  )}
								  ${generateTimelineItem("Categories", categoriesHtml)}
								  ${generateTimelineItem("Athletes", event.athletes_registered || "Unknown")}
								  ${generateTimelineItem("Last Import", event.last_import || "Unknown")}
								  ${generateTimelineItem("My Role", event.my_role || "Viewer")}
							  </div>
						  </div>
						  <div class="card-footer btn-group">
							  <button
								  class="${btnClass} btn-sm me-md-6 select-event"
								  data-event-id="${event.id}"
								  data-event-name="${event.name || "No Name"}"
								  data-event-code="${event.code || ""}"
								  data-event-role="${event.my_role || "Viewer"}"
								  ${btnDisabled}
								  type="button">
								  ${btnText}
							  </button>
							  <button
								  class="btn btn-warning btn-sm"
								  onclick="window.open('competition.html?CompetitionCode=${event.code}', '_blank')">
								  Public
							  </button>
							  <button
								  class="${exportBtnClass}"
								  data-export-code="${event.code}"
								  type="button"
								  ${exportBtnDisabled}>
								  Export Results
							  </button>
						  </div>
					  </div>
				  `;
  
				  eventCard.innerHTML = cardHtml;
				  eventsContainer.appendChild(eventCard);
			  });
  
			  // Attach listeners for "Select"
			  document.querySelectorAll(".select-event").forEach((button) => {
				  button.addEventListener("click", function () {
					  const eventId = this.getAttribute("data-event-id");
					  const eventName = this.getAttribute("data-event-name");
					  const eventCode = this.getAttribute("data-event-code") || "";
					  const eventRole = this.getAttribute("data-event-role") || "Viewer";
  
					  if (!eventCode) {
						  console.warn("No event.code found for event ID:", eventId);
					  }
  
					  localStorage.setItem(
						  "activeCompetition",
						  JSON.stringify({
							  id: eventId,
							  name: eventName,
							  code: eventCode,
							  role: eventRole
						  })
					  );
  
					  location.reload();
				  });
			  });
  
			  // Updated “Export Results” listener: force a download named “[competitionCode].xml”
			  document.querySelectorAll(".export-event").forEach((button) => {
				button.addEventListener("click", async function () {
				  const eventCode = this.getAttribute("data-export-code");
				  const url = `${API_BASE_URL}?api=export_xml&competitionCode=${encodeURIComponent(eventCode)}`;
			  
				  try {
					const response = await fetch(url, {
					  method: "GET",
					  headers: getHeaders(true)
					});
					if (!response.ok) {
					  console.error("Failed to fetch export XML", response.status);
					  return;
					}
			  
					const blob = await response.blob();
					const blobUrl = window.URL.createObjectURL(blob);
			  
					// Create a temporary <a> tag to trigger download:
					const a = document.createElement("a");
					a.href = blobUrl;
					a.download = `${eventCode}.xml`;
					document.body.appendChild(a);
					a.click();
					document.body.removeChild(a);
			  
					// Cleanup
					window.URL.revokeObjectURL(blobUrl);
				  } catch (error) {
					console.error("Error fetching export XML:", error);
				  }
				});
			  });
		  })
		  .catch((error) => {
			  console.error("Error fetching event data:", error);
			  localStorage.removeItem("user");
			  window.location.href = "index.html";
		  });
  }

  // Create the XML Import Card
  createXmlImportCard();
  // Fetch and display events on initial load
  fetchDashboard();
});