document.addEventListener("DOMContentLoaded", function () {
  /*******************************************************
   * 1) Minimal CSS injection
   *******************************************************/
  const style = document.createElement("style");
  style.textContent = `
	.card-header {
	  display: flex;
	  align-items: center;
	  justify-content: space-between;
	  padding: 0.5rem 1rem;
	}
	.card-body {
	  padding: 1rem;
	}
	.group-details-row {
	  display: none;
	}
	.group-details-cell {
	  background: #f9f9f9;
	  padding: 0.75rem;
	}
	.badge {
	  display: inline-block;
	  padding: 0.3rem 0.5rem;
	  font-size: 0.75rem;
	  font-weight: 600;
	  border-radius: 0.25rem;
	  color: #fff;
	  margin-right: 0.3rem;
	}
	.bg-primary { background-color: #0d6efd; }
	.bg-danger  { background-color: #dc3545; }

	/* optional "divider" row styling */
	.category-divider {
	  background: #e9ecef;
	  height: 1px;
	}
  `;
  document.head.appendChild(style);

  /*******************************************************
   * 2) Parse competition code from URL
   *******************************************************/
  const urlParams = new URLSearchParams(window.location.search);
  const competitionCode = urlParams.get("CompetitionCode");
  if (!competitionCode) {
	console.error("No CompetitionCode in the URL!");
	const eventsContainer = document.getElementById("events-container");
	if (eventsContainer) {
	  eventsContainer.innerHTML = `<p class="text-danger">Error: CompetitionCode missing in URL.</p>`;
	}
	return;
  }
  
  // 2A) Helper: produce timeline items
	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>`;
	}

  // Minimal helper for Authorization
  function getAuthHeaders() {
	return {
	  "Content-Type": "application/json",
	  "Authorization": "Bearer 50afb255cfa3a36834e0a51185b1eb09"
	};
  }

  /*******************************************************
   * 3) Possibly fetch & show the "event dashboard" (optional)
   *******************************************************/
 // 3) Old "dashboard" card from `dashboard.php` => "viewer" iwwf_id
fetch(API_BASE_URL + "?api=dashboard&iwwf_id=viewer", {
   method: "GET",
   headers: getAuthHeaders()
 })
	 .then(resp => {
	   if (!resp.ok) {
		 alert(`Error fetching dashboard data: ${resp.status} ${resp.statusText}`);
		 throw new Error("HTTP error " + resp.status);
	   }
	   return resp.json();
	 })
	 .then(data => {
	   const eventsContainer = document.getElementById("events-container");
	   if (!eventsContainer) return;
 
	   if (!Array.isArray(data)) {
		 eventsContainer.innerHTML = `<p class="text-danger">Unexpected data format from API.</p>`;
		 return;
	   }
 
	   eventsContainer.innerHTML = ""; // Clear old content
 
	   // Find matching event:
	   const matchingEvent = data.find(e => e.event && e.event.code === competitionCode);
	   if (!matchingEvent) {
		 eventsContainer.innerHTML = `<p class="text-warning">No event found for ${competitionCode}.</p>`;
		 return;
	   }
	   const event = matchingEvent.event;
 
	   // Build a small "dashboard" card with timeline items
	   const dashCard = document.createElement("div");
	   dashCard.classList.add("card");
	   dashCard.style.marginBottom = "20px";
 
	   dashCard.innerHTML = `
		 <div class="card-header" style="justify-content:center;">
		   <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",
			   Array.isArray(event.categories)
				 ? event.categories.join(", ")
				 : (event.categories || "Unknown")
			 )}
			 ${generateTimelineItem("Athletes", event.athletes_registered || "Unknown")}
			 ${generateTimelineItem("Last Import", event.last_import || "Unknown")}
			 ${generateTimelineItem("My Role", event.my_role || "Unknown")}
		   </div>
		 </div>
	   `;
	   eventsContainer.appendChild(dashCard);
	 })
	 .catch(err => {
	   console.error("Error fetching dashboard data:", err);
	   const evC = document.getElementById("events-container");
	   if (evC) {
		 evC.innerHTML = `<p class="text-danger">Error fetching dashboard data (see console).</p>`;
	   }
	 });
  /*******************************************************
   * 4) The schedule + results card
   *******************************************************/
  const containerLists = document.getElementById("container-lists");
  if (!containerLists) {
	console.warn("No #container-lists => skipping second card.");
	return;
  }

  fetch(`${API_BASE_URL}?api=schedule&competitionCode=${encodeURIComponent(competitionCode)}`, {
	method: "GET",
	headers: getAuthHeaders()
  })
	.then(resp => {
	  if (!resp.ok) throw new Error(`HTTP error: ${resp.status}`);
	  return resp.json();
	})
	.then(scheduleData => {
	  if (!scheduleData || !Array.isArray(scheduleData.data)) {
		throw new Error("Invalid schedule data or no .data array.");
	  }

	  // 4A) Create card container
	  const resultCard = document.createElement("div");
	  resultCard.classList.add("card");
	  resultCard.style.marginBottom = "20px";

	  // Notice: We **removed** the "Download All" button
	  resultCard.innerHTML = `
		<div class="card-header">
		  <h3 class="card-title">Competition Startlists &amp; Results</h3>
		</div>
		<div class="card-body">
		  <p>Loading schedule data...</p>
		</div>
	  `;
	  containerLists.appendChild(resultCard);

	  const cardBodyEl = resultCard.querySelector(".card-body");
	  if (!cardBodyEl) return;

	  // If no schedule data
	  if (scheduleData.data.length === 0) {
		cardBodyEl.innerHTML = `<p>No schedule data found for this competition.</p>`;
		return;
	  }

	  // 4B) Group by event_name => then category_name
	  const eventMap = {};
	  scheduleData.data.forEach(item => {
		const evName = item.event_name || "No Event";
		if (!eventMap[evName]) {
		  eventMap[evName] = {};
		}
		const catName = item.category_name || "No Category";
		if (!eventMap[evName][catName]) {
		  eventMap[evName][catName] = [];
		}
		eventMap[evName][catName].push(item);
	  });

	  // 4C) Build the table
	  let tableHTML = `
		<table class="table table-hover table-sm" id="resultsTable">
		  <thead>
			<tr>
			  <th>Event</th>
			  <th class="text-start">Category</th>
			  <th class="text-start">Round</th>
			  <th>Groups</th>
			</tr>
		  </thead>
		  <tbody>
	  `;

	  // For each event => for each category => schedules
	  Object.keys(eventMap).forEach(evKey => {
		const categoryMap = eventMap[evKey];

		// Go through each category
		Object.keys(categoryMap).forEach(catKey => {
		  // **Sort schedules ascending** by order (instead of descending)
		  categoryMap[catKey].sort((a,b) => (a.order || 0) - (b.order || 0));

		  // For each schedule item in (evKey -> catKey)
		  categoryMap[catKey].forEach(item => {
			const schedId   = item.schedule_id;
			const roundName = item.heatsystem_name || "N/A";

			let eventBadge = "";
			if (evKey === "Wakeboard") {
			  eventBadge = `<span class="badge bg-primary">WB</span>`;
			} else if (evKey === "Wakeskate") {
			  eventBadge = `<span class="badge bg-danger">WS</span>`;
			}

			// Count groups
			const groupNumbers = new Set();
			(item.runs || []).forEach(runObj => {
			  groupNumbers.add(runObj.group || 0);
			});
			const groupsCount = groupNumbers.size;

			// Prepare hidden group info row
			const runsByGroup = {};
			(item.runs || []).forEach(runObj => {
			  const g = runObj.group || 0;
			  if (!runsByGroup[g]) runsByGroup[g] = [];
			  runsByGroup[g].push(runObj);
			});

			let groupInfo = "";
			Object.keys(runsByGroup).forEach(gNum => {
			  groupInfo += `
				<div
				  data-type="kt_app_content_container_results"
				  data-section="0"
				  data-public="true"
				  data-schedule="${schedId}"
				  data-group="${gNum}"
				  style="margin-bottom: 1rem; border: 1px dashed #ccc; padding: 0.5rem;"
				>
				  <!-- results auto-loaded by results code -->
				</div>
			  `;
			});

			const detailRowId = `detailRow-${schedId}-${roundName.replace(/\s+/g, '')}`;

			tableHTML += `
			  <!-- Main row -->
			  <tr class="clickable-row" data-target="${detailRowId}">
				<td>${eventBadge}</td>
				<td class="text-start">${catKey}</td>
				<td class="text-start">${roundName}</td>
				<td>${groupsCount}</td>
			  </tr>
			  <!-- Hidden detail row -->
			  <tr id="${detailRowId}" class="group-details-row">
				<td colspan="4" class="group-details-cell">
				  ${groupInfo || "<em>No runs</em>"}
				</td>
			  </tr>
			`;
		  }); // end of schedules in category

		  // After finishing the category => add a "divider" row
		  tableHTML += `
			<tr>
			  <td colspan="4" class="category-divider"></td>
			</tr>
		  `;
		}); // end of categories
	  }); // end of events

	  tableHTML += `</tbody></table>`;
	  cardBodyEl.innerHTML = tableHTML;

	  // 4D) Click handlers to toggle detail rows
	  const clickableRows = cardBodyEl.querySelectorAll(".clickable-row");
	  clickableRows.forEach(row => {
		row.addEventListener("click", function() {
		  const targetId = row.getAttribute("data-target");
		  const detailRow = document.getElementById(targetId);
		  if (!detailRow) return;
		  // Toggle display
		  if (!detailRow.style.display || detailRow.style.display === "none") {
			detailRow.style.display = "table-row";
		  } else {
			detailRow.style.display = "none";
		  }
		});
	  });
	})
	.catch(err => {
	  console.error("Error fetching schedule data:", err);
	  containerLists.innerHTML = `
		<div class="card" style="margin-bottom: 20px;">
		  <div class="card-header">
			<h3 class="card-title">Competition Results</h3>
		  </div>
		  <div class="card-body text-danger">
			Failed to load results data. Check console logs.
		  </div>
		</div>
	  `;
	});
});