
  /************************************************************
   * 0) Retrieve bearer token from localStorage user
   ************************************************************/
  const storedUser = JSON.parse(localStorage.getItem("user")) || {};
  const bearerToken = storedUser.bearer || null;

  /**
   * Build fetch headers with Bearer token
   */
  function getAuthHeaders() {
	return {
	  "Content-Type": "application/json",
	  "Authorization": `Bearer ${bearerToken}`
	};
  }

  /**
   * If response is not OK => sign out
   */
  function handleNotOkResponse(response) {
	console.error(`API response not OK (${response.status} ${response.statusText}). Logging out...`);
	alert("Session expired or invalid. Signing out...");
	localStorage.removeItem("user");
	window.location.href = "index.html";
  }

  // Container for the UI
  const container = document.getElementById("sheets-container");

  // Insert a header with a container for buttons
  container.innerHTML = `
	<div class="alert alert-success" role="alert">
	  <h4 class="alert-heading">Scoring Sheets (Judge-Specific)</h4>
	  <p>Below are buttons for each judge. Click one to open a new window with the sheets for that judge.</p>
	  <hr>
	  <div id="judgeButtonsContainer"></div>
	</div>
  `;
  const judgeButtonsContainer = document.getElementById("judgeButtonsContainer");

  // Retrieve competition info from localStorage
  const storedCompetition = JSON.parse(localStorage.getItem("activeCompetition")) || {};
  const competitionCode = storedCompetition.code || null;
  const competitionName = storedCompetition.name || "Unknown Competition";


  // We'll store data from /panel & /schedule
  let globalPanelOfficials = [];
  let globalScheduleData = [];

  /**
   * 1) Fetch the panel => fetch the schedule => build judge buttons
   */
  fetchPanelData()
	.then(() => fetchScheduleData())
	.then(() => {
	  buildJudgeButtons();
	})
	.catch(err => {
	  console.error("Error in fetching data for judge sheets:", err);
	  alert("Error fetching data. Check console for details.");
	});

  /**
   * fetchPanelData => sets globalPanelOfficials
   */
  function fetchPanelData() {
	const url = `${API_BASE_URL}?api=panel&competitionCode=${encodeURIComponent(competitionCode)}`;
	return fetch(url, {
	  method: "GET",
	  headers: getAuthHeaders()
	})
	  .then(resp => {
		if (!resp.ok) {
		  handleNotOkResponse(resp);
		  return null;
		}
		return resp.json();
	  })
	  .then(data => {
		if (!data) return;
		if (!data.success) {
		  console.error("Panel API not success =>", data.error);
		  throw new Error(data.error || "Panel API error");
		}
		// data.officials => array of { official_id, name, country, etc. }
		globalPanelOfficials = data.officials || [];
	  });
  }

  /**
   * fetchScheduleData => sets globalScheduleData
   */
  function fetchScheduleData() {
	const url = `${API_BASE_URL}?api=schedule&competitionCode=${encodeURIComponent(competitionCode)}`;
	return fetch(url, {
	  method: "GET",
	  headers: getAuthHeaders()
	})
	  .then(resp => {
		if (!resp.ok) {
		  handleNotOkResponse(resp);
		  return null;
		}
		return resp.json();
	  })
	  .then(data => {
		if (!data) return;
		if (!Array.isArray(data.data)) {
		  console.error("Schedule data invalid =>", data);
		  throw new Error("Schedule data invalid format");
		}
		globalScheduleData = data.data;
	  });
  }

  /**
   * 2) Build judge buttons.
   * If data-section is 1 then only show the button for the current judge
   * (i.e. where official_id === storedUser.iwwf_id). Otherwise, show all buttons.
   */
  function buildJudgeButtons() {
	judgeButtonsContainer.innerHTML = "";

	let officialsToShow;
	if (parseInt(container.getAttribute("data-section"), 10) === 1) {
	  // Show only my button (using iwwf_id from storedUser)
	  officialsToShow = globalPanelOfficials.filter(o => o.iwwf_id === storedUser.iwwf_id);
	} else {
	  // Judging mode: show buttons for all officials.
	  officialsToShow = globalPanelOfficials;
	}

	officialsToShow.forEach(official => {
	  const jNumber = official.official_id;
	  const jName = official.name || "Judge";

	  // Create a button for each official.
	  const btn = document.createElement("button");
	  btn.classList.add("btn", "btn-primary", "m-2");
	  btn.textContent = `Sheets: ${jName}`;
	  btn.addEventListener("click", () => {
		openSheetsForJudge(jNumber, jName);
	  });
	  judgeButtonsContainer.appendChild(btn);
	});
  }

  // open new window => build the HTML for that judge
  function openSheetsForJudge(jNumber, jName) {
	const finalHTML = buildJudgeHTML(jNumber, jName);
	if (!finalHTML) {
	  alert(`No runs/groups found for judge ID #${jNumber}.`);
	  return;
	}
	const newWin = window.open("", "_blank", "width=900,height=900");
	if (!newWin) {
	  alert("Pop-up blocked or can't open new window.");
	  return;
	}
	newWin.document.write(finalHTML);
	newWin.document.close();
  }

  /**
   * 3) buildJudgeHTML => Group schedule items by event -> category -> round -> group.
   * Only include schedule items where sched.officials has an official with official_id === jNumber.
   * Then produce two side-by-side columns for Run 1 & Run 2.
   * This version mimics the old sheets.
   */
  function buildJudgeHTML(jNumber, jName) {
	if (!globalScheduleData || !globalScheduleData.length) {
	  return "";
	}

	// Group schedule items by event, category, round, then group.
	const grouping = {};
	const judgeEventNames = new Set();

	globalScheduleData.forEach(sched => {
	  if (!sched.officials) return;
	  const assigned = sched.officials.some(o => o.official_id === jNumber);
	  if (!assigned) return;

	  const evName = sched.event_name || "UnknownEvent";
	  const catName = sched.category_name || "Uncategorized";
	  const roundName = sched.heatsystem_name || "No Round";

	  if (!grouping[evName]) grouping[evName] = {};
	  if (!grouping[evName][catName]) grouping[evName][catName] = {};
	  if (!grouping[evName][catName][roundName]) grouping[evName][catName][roundName] = {};

	  if (Array.isArray(sched.runs)) {
		sched.runs.forEach(run => {
		  const groupNum = run.group || 0;
		  if (!grouping[evName][catName][roundName][groupNum]) {
			grouping[evName][catName][roundName][groupNum] = [];
		  }
		  grouping[evName][catName][roundName][groupNum].push(run);
		});
	  }

	  judgeEventNames.add(evName);
	});

	if (Object.keys(grouping).length === 0) {
	  return "";
	}

	let docEventName = "Multiple Events";
	if (judgeEventNames.size === 1) {
	  docEventName = Array.from(judgeEventNames)[0];
	}
	const docTitle = `${docEventName} - ${competitionName} - Sheets for Judge #${jNumber} (${jName})`;

	const currentDate = new Date();
	const formattedDate =
	  currentDate.getDate().toString().padStart(2, "0") +
	  "-" +
	  (currentDate.getMonth() + 1).toString().padStart(2, "0") +
	  "-" +
	  currentDate.getFullYear();

	let html = `
	  <html>
	  <head>
		<title>${docTitle}</title>
		<style>
		  .page-break {
			page-break-after: always;
			margin-top: 40px;
		  }
		  table { border-collapse: collapse; }
		</style>
	  </head>
	  <body>
		<div style="padding: 10px;">
	`;

	// Loop over each grouping (event -> category -> round -> group)
	Object.keys(grouping).forEach(evName => {
	  const catMap = grouping[evName];
	  Object.keys(catMap).forEach(catName => {
		const roundMap = catMap[catName];
		Object.keys(roundMap).forEach(roundName => {
		  const groupMap = roundMap[roundName];
		  const groupNums = Object.keys(groupMap).sort((a, b) => parseInt(a) - parseInt(b));
		  const totalGroups = groupNums.length;

		  groupNums.forEach(gKey => {
			const groupNum = parseInt(gKey, 10);
			const runList = groupMap[gKey];

			// Build athlete => runs array for this group.
			const athleteMap = new Map();
			runList.forEach(r => {
			  // Use athlete name if available; otherwise create a key with run id.
			  const key = r.athlete ? `athlete-${r.athlete}` : `unknown-run-${r.run_id}`;
			  if (!athleteMap.has(key)) {
				athleteMap.set(key, []);
			  }
			  athleteMap.get(key).push(r);
			});
			
			// Reset numbering for each group
			let counter = 1;

			html += `
			  <div class="group-section">
			  <table border='0' cellpadding='0' cellspacing='0'>
				<tr>
				  <td width='360' valign='top'><font size='2'><b>${competitionName}</b></font></td>
				  <td width='270' valign='top'><font size='2'><b>Scorer:</b> ${jName}</font></td>
				  <td width='90' valign='top'><font size='2'><b>Date:</b> ${formattedDate}</font></td>
				</tr>
			  </table>
			`;

			// Convert athleteMap to an array and loop in pairs for left/right columns.
			const athleteEntries = Array.from(athleteMap.entries());
			for (let i = 0; i < athleteEntries.length; i += 2) {
			  const leftEntry = athleteEntries[i];
			  const leftRuns = leftEntry[1];
			  leftRuns.sort((a, b) => a.run - b.run);
			  const athleteName1 = (leftRuns[0] && leftRuns[0].athlete_name) || "Unknown Athlete";
			  const label1 = counter;
			  counter++;
			
			  let athleteName2 = "";
			  let label2 = "";
			  if (i + 1 < athleteEntries.length) {
				const rightEntry = athleteEntries[i + 1];
				const rightRuns = rightEntry[1];
				rightRuns.sort((a, b) => a.run - b.run);
				athleteName2 = (rightRuns[0] && rightRuns[0].athlete_name) || "Unknown Athlete";
				label2 = counter;
				counter++;
			  }
			
			  html += `
				<table border='1' cellpadding='0' cellspacing='0' height='40'>
				  <tr>
					<td width='90' valign='top'><font size='1'>1st Run<br></font></td>
					<td width='180' valign='top'>
					  <font size='1'>Name</font>
					  <div align='center'>${label1} - ${athleteName1}</div>
					</td>
					<td width='90' valign='top'><font size='1'>2nd Run<br></font></td>
					<td width='90' valign='top'><font size='1'>1st Run<br></font></td>
					<td width='180' valign='top'>
					  <font size='1'>Name</font>
					  <div align='center'>${label2 ? label2 + " - " + athleteName2 : ""}</div>
					</td>
					<td width='90' valign='top'><font size='1'>2nd Run<br></font></td>
				  </tr>
				</table>
				<table border='1' cellpadding='0' cellspacing='0' height='260'>
				  <tr>
					<td width='181'>&nbsp;</td>
					<td width='181'>&nbsp;</td>
					<td width='181'>&nbsp;</td>
					<td width='181'>&nbsp;</td>				  
				</tr>
				</table>
			  `;
			}

			html += `
			  </div>
			  <br>
			  <table border='0' cellpadding='0' cellspacing='0'>
				<tr>
				  <td width='360' valign='top'><font size='2'><b>Event:</b> ${catName} - ${roundName} - Group ${groupNum} of ${totalGroups}</font></td>
				  <td width='270' valign='top'><font size='2'><b>Judge: ${jName}</b></font></td>
				  <td width='90' valign='top'><font size='2'><b>Number: ${jNumber}</b></font></td>
				</tr>
			  </table>
			  <div class="page-break"></div>
			`;
		  });
		});
	  });
	});

	html += `
		</div>
	  </body>
	  </html>
	`;
	return html;
  }