
  /************************************************************
   * 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 jPosition = official.judge; 
	  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, jPosition);
	  });
	  judgeButtonsContainer.appendChild(btn);
	});
  }
  
  /**
   * 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.
   */
  // Replace openSheetsForJudge + buildJudgeHTML with this:
  async function openSheetsForJudge(jNumber, jName, jPosition) {
	  
	// — 0) Your static header/footer values —
	const scorerVal = 'Aaron Armborst';
	const today   = new Date();
	const dateVal = today.toISOString().slice(0, 10);  // “YYYY-MM-DD”
	const judgePosition   = jPosition || "";
  
	// — 1) Build grouping (as before) —
	const grouping = {};
	globalScheduleData.forEach(sched => {
	  if (!sched.officials?.some(o => o.official_id === jNumber)) return;
	  const ev  = sched.event_name      || "UnknownEvent";
	  const cat = sched.category_name   || "Uncategorized";
	  const rnd = sched.heatsystem_name || "No Round";
	  grouping[ev]      ??= {};
	  grouping[ev][cat] ??= {};
	  grouping[ev][cat][rnd] ??= [];
	  if (Array.isArray(sched.runs)) {
		sched.runs.forEach(run => grouping[ev][cat][rnd].push(run));
	  }
	});
	if (!Object.keys(grouping).length) {
	  return alert(`No runs/groups for judge #${jNumber}.`);
	}
  
	// — 2) Preload both templates —  
	const { PDFDocument, rgb } = PDFLib;
	const fontkit = window.fontkit;
  
	const [bytes6, bytes8] = await Promise.all([
	  fetch('/js/old_sheets_6.pdf').then(r=>r.arrayBuffer()),
	  fetch('/js/old_sheets_8.pdf').then(r=>r.arrayBuffer())
	]);
	const tpl6 = await PDFDocument.load(bytes6);
	const tpl8 = await PDFDocument.load(bytes8);
  
	// — 3) Prepare new PDF + font —
	const pdfDoc = await PDFDocument.create();
	pdfDoc.registerFontkit(fontkit);
  
	const fontBytes = await fetch('/js/NotoSans-Regular.ttf').then(r=>r.arrayBuffer());
	const font      = await pdfDoc.embedFont(fontBytes);
	const black     = rgb(0,0,0);
	const fontSize  = 10;
  
	// coordinate sets:
	const coords6 = [
	  { x:95,  yOffset:71  }, { x:377, yOffset:71  },
	  { x:95,  yOffset:320 }, { x:377, yOffset:320 },
	  { x:95,  yOffset:568 }, { x:377, yOffset:568 },
	];
	const coords8 = [
	  { x:95,  yOffset:71  }, { x:377, yOffset:71  },
	  { x:95,  yOffset:258 }, { x:377, yOffset:258 },
	  { x:95,  yOffset:444 }, { x:377, yOffset:444 },
	  { x:95,  yOffset:631 }, { x:377, yOffset:631 },
	];
  
	// — 4) Loop per group, choose correct template & coords —
	for (const [evName, catMap] of Object.entries(grouping)) {
	  for (const [catName, rndMap] of Object.entries(catMap)) {
		for (const [rndName, runs] of Object.entries(rndMap)) {
		  // take only Run-1 athletes for this group:
		  const run1 = runs.filter(r=>r.run===1).map(r=>r.athlete_name);
		  const use8 = run1.length > 6;
  
		  // copy from correct template:
		  const [page] = await pdfDoc.copyPages(use8 ? tpl8 : tpl6, [0]);
		  pdfDoc.addPage(page);
		  const { height } = page.getSize();
  
		  // HEADER
		  page.drawText(competitionName,   { x: 25,  y: height-37,  size: fontSize, font, color: black });
		  page.drawText(scorerVal, { x: 232, y: height-37,  size: fontSize, font, color: black });
		  page.drawText(dateVal,   { x: 445, y: height-37,  size: fontSize, font, color: black });
  
		  // ATHLETES (1–6 or 1–8)
		  const coords = use8 ? coords8 : coords6;
		  run1.slice(0, coords.length).forEach((name, i) => {
			const pos = coords[i];
			page.drawText(`${i+1} – ${name}`, {
			  x:        pos.x,
			  y:        height - pos.yOffset,
			  size:     fontSize,
			  font,
			  color:    black
			});
		  });
  
		  // FOOTER
		  page.drawText(`${evName} – ${catName} - ${rndName}`,  { x: 25,  y: height-816, size: fontSize, font, color: black });
		  page.drawText(jName, { x: 232, y: height-816, size: fontSize, font, color: black });
		  page.drawText(judgePosition, { x: 450, y: height-816, size: fontSize, font, color: black });
		}
	  }
	}
  
	// — 5) Download —
	const pdfBytes = await pdfDoc.save();
	const link     = document.createElement('a');
	link.href      = URL.createObjectURL(new Blob([pdfBytes], {type:'application/pdf'}));
	link.download  = `Sheets_Judge${jNumber}.pdf`;
	link.click();
  }