document.addEventListener("DOMContentLoaded", function () {
  /*******************************************************
   * 1) Inject “results”-style CSS for participation
   *******************************************************/
  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;
	}

	.clickable-row { cursor: pointer; }
	.clickable-row:hover { background: #e6f0fa; }

	.group-details-row { display: none; }
	.group-details-row > td {
	  padding: 0;
	  border: none;
	}

	.detail-container {
	  margin: 0.5rem 0;
	  padding: 0.5rem;
	  border: 1px dashed #ccc;
	  border-radius: 4px;
	}
	.detail-container .table-striped tbody tr:hover {
	  background-color: transparent;
	}

	.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; }

	.category-divider {
	  background: #e9ecef;
	  height: 1px;
	}

	.table th,
	.table td {
	  border-bottom: 1px solid #ddd;
	}
	
	/* ==== MOBILE ADJUSTMENTS ==== */
	@media (max-width: 576px) {
	  /* slightly larger font for readability */
	  .card-body,
	  .table th,
	  .table td {
		font-size: 0.9rem;
	  }
	  /* tighter padding in table cells */
	  .table th,
	  .table td {
		padding: 0.4rem 0.5rem;
	  }
	  /* shrink badges */
	  .badge {
		padding: 0.2rem 0.4rem;
		font-size: 0.65rem;
		margin-right: 0.2rem;
	  }
	  /* reduce detail-container padding & margin */
	  .detail-container {
		margin: 0.25rem 0;
		padding: 0.3rem;
		border-width: 1px;
	  }
	}
  `;
  document.head.appendChild(style);

  /*******************************************************
   * 2) Setup & fetch participation data
   *******************************************************/
  function getAuthHeaders() {
	return {
	  "Content-Type": "application/json",
	  "Authorization": "Bearer 50afb255cfa3a36834e0a51185b1eb09"
	};
  }

  let stored = JSON.parse(localStorage.getItem("activeCompetition")) || {};
  if (!stored.code) {
	const code = new URLSearchParams(window.location.search).get("CompetitionCode");
	if (!code) return console.error("No competition code!");
	stored.code = code;
  }
  const competitionCode = stored.code;
  const container = document.getElementById("container-participation");
  if (!container) return console.error("Missing #container-participation");

  fetch(`${API_BASE_URL}?api=participations&competitionCode=${encodeURIComponent(competitionCode)}`, {
	headers: getAuthHeaders()
  })
	.then(r => {
	  if (!r.ok) throw new Error(r.statusText);
	  return r.json();
	})
	.then(json => {
	  if (!json.success || !json.events) {
		container.innerHTML = `<p class="text-warning">No partipications imported.</p>`;
	  } else {
		renderParticipation(json.events);
	  }
	})
	.catch(err => {
	  console.error(err);
	  container.innerHTML = `<p class="text-danger">Couldn't load participations. Try again later.</p>`;
	});

  /*******************************************************
   * 3) Render with grouping by base category but no header
   *******************************************************/
  function getBadge(code) {
	if (code === "E703") return `<span class="badge bg-primary">WB</span>`;
	if (code === "E704") return `<span class="badge bg-danger">WS</span>`;
	if (code === "E705") return `<span class="badge bg-warning">ST</span>`;
	return "";
  }

function renderParticipation(events) {
	// build a map: baseCat → [{ evCode, sub, list, fullCat }, …]
	const baseMap = {};
	Object.entries(events).forEach(([evCode, cats]) => {
	  Object.entries(cats).forEach(([fullCatRaw, list]) => {
		const fullCat = fullCatRaw.trim();
		const lastSpace = fullCat.lastIndexOf(" ");
		const base  = fullCat.slice(0, lastSpace);
		const sub   = fullCat.slice(lastSpace + 1);
  
		baseMap[base] = baseMap[base] || [];
		baseMap[base].push({ evCode, sub, list, fullCat });
	  });
	});

	let html = `
	  <div class="card mb-4">
		<div class="card-header">
		  <h3 class="card-title">Participations</h3>
		</div>
		<div class="card-body">
		  <table class="table table-hover table-sm">
			<thead>
			  <tr>
				<th>Event</th>
				<th class="text-start">Category</th>
				<th>Entered</th>
			  </tr>
			</thead>
			<tbody>
	`;

	// iterate base categories in sorted order
	Object.keys(baseMap).sort().forEach(baseCat => {
	  const entries = baseMap[baseCat];

	  // for each subcategory in fixed order
	  ["Ladies","Men"].forEach(sub => {
		const items = entries.filter(e => e.sub === sub);
		if (!items.length) return;

		const total  = items.reduce((sum,i)=> sum+i.list.length, 0);
		const badges = items.map(i=> getBadge(i.evCode)).join(" ");
		const detailId = `detail-${baseCat.replace(/\s+/g,"")}-${sub}`;

		// overview row
		html += `
		  <tr class="clickable-row" data-target="${detailId}">
			<td>${badges}</td>
			<td class="text-start">${baseCat} ${sub}</td>
			<td>${total}</td>
		  </tr>
		  <tr id="${detailId}" class="group-details-row">
			<td colspan="3">
			  <div class="detail-container">
				${items.map(i => `
				  <div style="margin-bottom: .25rem">
					<strong>${getBadge(i.evCode)} ${i.fullCat} (${i.list.length})</strong>
				  </div>
				  <table class="table table-striped table-sm mb-2">
					<thead>
					  <tr>
						<th>Nat</th>
						<th>Bib</th>
						<th class="text-start">Athlete</th>
						<th>Placement</th>
					  </tr>
					</thead>
					<tbody>
					  ${i.list.map(p => `
						<tr>
						  <td>${p.country||"IWWF"}</td>
						  <td>${p.bib   || "-"}</td>
						  <td class="text-start">${p.athlete|| "-"}</td>
						  <td>${p.placement!=null? p.placement : "-"}</td>
						</tr>
					  `).join("")}
					</tbody>
				  </table>
				`).join("")}
			  </div>
			</td>
		  </tr>
		`;
	  });

	  // add a divider row after each base category
	  html += `
		<tr><td colspan="3" class="category-divider"></td></tr>
	  `;
	});

	html += `
			</tbody>
		  </table>
		</div>
	  </div>
	`;
	container.innerHTML = html;

	// attach toggle handlers
	container.querySelectorAll(".clickable-row").forEach(row => {
	  row.addEventListener("click", () => {
		const det = document.getElementById(row.dataset.target);
		det.style.display = (det.style.display === "table-row") ? "none" : "table-row";
	  });
	});
  }
});