
  /************************************************************
   * 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
   * We expect each official to have { official_id, name, etc. }
   */
  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.
   */
  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})`;
  
	let html = `
	  <html>
	  <head>
		<title>${docTitle}</title>
		<style>
		  body {
			font-family: sans-serif;
			margin: 0px;
			font-size: 12px;
		  }
		  .page-break {
			page-break-after: always;
			margin-top: 40px;
		  }
		  .group-section {
			padding: 5px;
			margin-bottom: 40px;
		  }
		  .athlete-card {
			border: 1px solid #aaa;
			padding: 8px;
			margin: 8px 0;
			border-radius: 5px;
		  }
		  .athlete-card h4 {
			margin: 0 0 4px 0;
			font-size: 1em;
		  }
		  .runs-row {
			display: flex;
			gap: 10px;
		  }
		  .run-col {
			flex: 1;
			border: 1px dashed #bbb;
			padding: 4px;
			min-height: 90px;
			position: relative;
		  }
		  .run-title {
			position: absolute;
			top: 4px;
			left: 6px;
			font-weight: bold;
		  }
		</style>
	  </head>
	  <body>
		<div style="padding: 10px;">
	`;
  
	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
			const athleteMap = new Map();
			runList.forEach(r => {
			  const aKey = r.athlete ? `athlete-${r.athlete}` : `unknown-run-${r.run_id}`;
			  if (!athleteMap.has(aKey)) {
				athleteMap.set(aKey, []);
			  }
			  athleteMap.get(aKey).push(r);
			});
  
			html += `
			  <div class="group-section">
				<h3>${evName} - ${catName} - ${roundName} - Group ${groupNum} of ${totalGroups} / Judge #${jNumber} (${jName})</h3>
			`;
  
			athleteMap.forEach(runsArray => {
			  runsArray.sort((a,b) => a.run - b.run);
  
			  let run1col = "";
			  let run2col = "";
			  runsArray.forEach(r => {
				if (r.run === 1) {
				  run1col = `
					<div class="run-col">
					  <span class="run-title">Run 1</span>
					</div>
				  `;
				} else if (r.run === 2) {
				  run2col = `
					<div class="run-col">
					  <span class="run-title">Run 2</span>
					</div>
				  `;
				}
			  });
			  if (!run1col) {
				run1col = `
				  <div class="run-col">
					<span class="run-title">Run 1</span>
				  </div>
				`;
			  }
			  if (!run2col) {
				run2col = `
				  <div class="run-col">
					<span class="run-title">Run 2</span>
				  </div>
				`;
			  }
			  const firstRun = runsArray[0] || {};
			  const athleteName = firstRun.athlete_name || "Unknown Athlete";
			  const runsHTML = `
				<div class="runs-row">
				  ${run1col}
				  ${run2col}
				</div>
			  `;
			  html += `
				<div class="athlete-card">
				  <h4>${athleteName}</h4>
				  ${runsHTML}
				</div>
			  `;
			});
  
			html += `
			  </div>
			  <div class="page-break"></div>
			`;
		  });
		});
	  });
	});
  
	html += `
		</div>
	  </body>
	  </html>
	`;
	return html;
  }