// athlete.js

export const htmlAthlete = `
<style>
  /* Force the athlete photo to 175×225 px, with object-fit for better scaling */
  #athletePhoto {
	width: 175px;
	height: 240px;
	object-fit: cover; /* ensures the image scales nicely without distortion */
  }
</style>

<div class="main p-40 py-40 content_end ps-0">
  <div class="content_box">
	<div class="page10_bottom_box">
	  <div class="left_box">
		<div class="bg_royalblue text_white page10_padding_box">
		  <div class="flex gap_30">
			<div>
			  <p>CURRENT RIDER</p>
			  <!-- We'll insert the athlete name dynamically -->
			  <h3 class="fs_28" id="athleteName"></h3>
			  <!-- Add birthyear below if you want -->
			  <p id="athleteBirthyear" class="fw_700 fs_16 mt_5"></p>
			</div>
			<div class="flex items_center flag_box">
			  <!-- We'll insert the country code dynamically in JS -->
			  <p id="athleteCountryCode"></p>
			  <img id="athleteFlag" src="" alt="Flag" />
			</div>
		  </div>
		</div>
		<div class="bg_cyan page10_padding_box">
		  <!-- Possibly display sponsor info, home cable, or placement here -->
		  <p class="fw_700 text_royalblue" id="athleteSponsors"></p>
		  <!-- Add a separate element for home cable, if desired -->
		  <p class="fw_700 text_royalblue" id="athleteHomecable"></p>
		</div>
	  </div>

	  <div class="right_box">
		<!-- ID for dynamic athlete photo -->
		<img id="athletePhoto" src="" alt="Athlete Photo">
	  </div>
	</div>
  </div>
</div>
`;

/**
 * initAthlete():
 *   - Called after snippet is inserted into the DOM by tv.js.
 *   - Fetch the results API every 2 seconds => re-render if changed
 */
export function initAthlete() {
  console.log("[athlete.js] initAthlete() called.");

  // 1) Parse competitionCode from URL
  const urlParams = new URLSearchParams(window.location.search);
  const competitionCode = urlParams.get("competitionCode");
  if (!competitionCode) {
	console.warn("[athlete.js] No competitionCode => can't fetch results for athlete snippet.");
	return;
  }

  // 2) Prepare Bearer token (hardcoded for demonstration)
  const STATIC_BEARER_TOKEN = "50afb255cfa3a36834e0a51185b1eb09";
  function getAuthHeaders() {
	return {
	  "Content-Type": "application/json",
	  "Authorization": `Bearer ${STATIC_BEARER_TOKEN}`,
	};
  }

  // Keep the old athlete JSON to compare
  let previousAthleteJson = null;

  /**
   * fetchAndRenderAthlete => calls results API => compares => re-render if changed
   */
  function fetchAndRenderAthlete() {
	const resultsUrl = `${API_BASE_URL}?api=results&competitionCode=${encodeURIComponent(
	  competitionCode
	)}&public=true`;

	fetch(resultsUrl, { headers: getAuthHeaders() })
	  .then((res) => {
		if (!res.ok) {
		  console.error("[athlete.js] Results API responded with", res.status, res.statusText);
		  return null;
		}
		return res.json();
	  })
	  .then((jsonData) => {
		if (!jsonData) {
		  console.warn("[athlete.js] No jsonData at all!");
		  return;
		}

		// Check if API says success
		if (!jsonData.data || !jsonData.data.success) {
		  console.warn("[athlete.js] Unexpected or invalid results from API:", jsonData?.data?.error);
		  return;
		}

		// Access your nested data
		const { data } = jsonData;
		const activeAthlete = data.active_athlete;
		if (!activeAthlete) {
		  console.log("[athlete.js] No active_athlete => no update to snippet.");
		  return;
		}

		// Compare with previous
		const currentAthleteStr = JSON.stringify(activeAthlete);
		if (currentAthleteStr !== previousAthleteJson) {
		  console.log("[athlete.js] Active athlete changed => updating UI.");
		  previousAthleteJson = currentAthleteStr;
		  updateAthleteUI(activeAthlete);
		} else {
		  console.log("[athlete.js] Active athlete unchanged => skip re-render.");
		}
	  })
	  .catch((err) => {
		console.error("[athlete.js] Error calling results API for athlete snippet:", err);
	  });
  }

  // Call once initially
  fetchAndRenderAthlete();

  // Then poll every 2s
  setInterval(fetchAndRenderAthlete, 2000);
}

/**
 * updateAthleteUI(athlete):
 *   - Fills in #athleteName, #athletePhoto, #athleteFlag, #athleteCountryCode,
 *     #athleteBirthyear, #athleteSponsors, #athleteHomecable, #athletePlacement, etc.
 */
function updateAthleteUI(athlete) {
  // DOM elements by ID
  const nameEl           = document.getElementById("athleteName");
  const photoEl          = document.getElementById("athletePhoto");
  const countryCodeEl    = document.getElementById("athleteCountryCode");
  const flagImgEl        = document.getElementById("athleteFlag");
  const sponsorsEl       = document.getElementById("athleteSponsors");
  const birthyearEl      = document.getElementById("athleteBirthyear");
  const homecableEl      = document.getElementById("athleteHomecable");
  const placementEl      = document.getElementById("athletePlacement");

  // athlete.name => e.g. "Oliver Orban"
  if (nameEl && athlete.name) {
	nameEl.textContent = athlete.name.toUpperCase();
  }

  // athlete.athlete_id => dynamic image e.g. img/athletes/123.png
  if (photoEl) {
	if (athlete.id) {
	  photoEl.src = `img/athletes/${athlete.id}.png`;
	} else {
	  // fallback
	  photoEl.src = "";
	}
  }

  // athlete.country => e.g. "HUN"
  if (countryCodeEl && athlete.country) {
	countryCodeEl.textContent = athlete.country.toUpperCase();
	if (flagImgEl) {
	  flagImgEl.src = `img/svg/${athlete.country.toLowerCase()}.svg`;
	}
  }

  // If sponsor is empty or missing, show empty string
  if (sponsorsEl) {
	if (athlete.sponsors && athlete.sponsors.trim() !== "") {
	  sponsorsEl.textContent = athlete.sponsors;
	} else {
	  sponsorsEl.textContent = "";
	}
  }

  // athlete.birthyear => e.g. "2001"
  if (birthyearEl && athlete.birthyear) {
	birthyearEl.textContent = athlete.birthyear;
  }

  // If home cable is empty or missing, show empty string
  if (homecableEl) {
	if (athlete.homecable && athlete.homecable.trim() !== "") {
	  homecableEl.textContent = `Home Cable: ${athlete.homecable}`;
	} else {
	  homecableEl.textContent = "";
	}
  }

  // athlete.placement => e.g. 2
  if (placementEl && athlete.placement != null) {
	placementEl.textContent = `Placement: #${athlete.placement}`;
  }
}