export const htmlProfile = `
<style>
  /* Force the profile image to 150×250 px, with object-fit for better scaling */
  #profilePhoto {
	width: 150px;
	height: 250px;
	object-fit: cover;
  }
</style>

<div class="main p-40 py-60">
  <div class="content_box">
	<div class="w_box_md">
	  <div class="box8_inner_box mb_10">
		<div class="flex_between text_white mb_20">
		  <!-- We'll fill these in dynamically -->
		  <h3 class="fw_700 fs_28" id="profileName"></h3>
		  <h3 class="fs_78 f_kazer_outline" id="profileBib"></h3>
		</div>

		<div class="mb_30">
		  <div class="flex">
			<div class="w_50">
			  <p class="fw_700 text_cyan">YEAR OF BIRTH</p>
			</div>
			<div class="w_50">
			  <p class="text_white" id="profileYear"></p>
			</div>
		  </div>
		  <div class="flex">
			<div class="w_50">
			  <p class="fw_700 text_cyan">COUNTRY</p>
			</div>
			<div class="w_50">
			  <p class="text_white" id="profileCountry"></p>
			</div>
		  </div>
		  <div class="flex">
			<div class="w_50">
			  <p class="fw_700 text_cyan">HOMECABLE</p>
			</div>
			<div class="w_50">
			  <p class="text_white" id="profileCable"></p>
			</div>
		  </div>
		</div>

		<div class="mb_30">
		  <p class="fw_700 text_cyan">RANKING</p>
		  <p class="text_white" id="ranking"></p>
		</div>
		
		<div class="mb_50">
		  <p class="fw_700 text_cyan">SPONSORS</p>
		  <p class="text_white" id="sponsors"></p>
		</div>
		
		<div>
		  <div class="w_50">
			<!-- We use id="profilePhoto" for dynamic image from athlete_id -->
			<img id="profilePhoto"
				 src=""
				 class="w_100 page8_img"
				 alt="Athlete Photo">
		  </div>
		</div>
	  </div>

	  <div class="box8_bottom_box">
		<!-- We'll dynamically update the clock here, or any other text -->
		<p class="fw_700 text_royalblue" id="profileTime">12:34:34</p>
	  </div>
	</div>
  </div>
</div>
`;

/**
 * initProfile():
 *   - Called after snippet is inserted into the DOM.
 *   - We fetch the results API every 2 seconds => re-render if changed
 *   - Start the clock
 */
export function initProfile() {
  console.log("[profile.js] initProfile() called.");

  // (A) parse competitionCode from URL
  const urlParams = new URLSearchParams(window.location.search);
  const competitionCode = urlParams.get("competitionCode");
  if (!competitionCode) {
	console.warn("[profile.js] No competitionCode => can't fetch dynamic data.");
	startProfileClock();
	return;
  }

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

  // (C) Start the clock
  startProfileClock();

  // We'll store the old athlete data (JSON string) to compare
  let previousAthleteJson = null;

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

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

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

		const { data } = jsonData;
		const activeAthlete = data.active_athlete;
		if (!activeAthlete) {
		  console.log("[profile.js] No active_athlete => no changes to show.");
		  return;
		}

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

  // 1) Immediately call fetchAndRenderProfile
  fetchAndRenderProfile();

  // 2) Then poll every 2 seconds => re-check
  setInterval(fetchAndRenderProfile, 2000);
}

/**
 * updateProfileUI(athlete):
 *   fill in #profileName, #profileBib, #profileCountry, #profileYear, #profileCable,
 *   #sponsors, #ranking, and update #profilePhoto => "img/athletes/{athlete_id}.png"
 */
function updateProfileUI(athlete) {
  const nameEl       = document.getElementById("profileName");
  const bibEl        = document.getElementById("profileBib");
  const countryEl    = document.getElementById("profileCountry");
  const yearEl       = document.getElementById("profileYear");
  const cableEl      = document.getElementById("profileCable");
  const sponsorsEl   = document.getElementById("sponsors");
  const rankingEl    = document.getElementById("ranking");
  const photoEl      = document.getElementById("profilePhoto");

  // 1) Name
  if (nameEl && athlete.name) {
	const splitted = athlete.name.trim().split(" ");
	if (splitted.length >= 2) {
	  const first = splitted[0].toUpperCase();
	  const rest  = splitted.slice(1).join(" ").toUpperCase();
	  nameEl.innerHTML = `${first}<br>${rest}`;
	} else {
	  nameEl.textContent = athlete.name.toUpperCase();
	}
  }

  // 2) If athlete has a numeric bib or placement => #5
  if (bibEl && athlete.placement != null) {
	bibEl.textContent = `#${athlete.placement}`;
  }

  // 3) Country
  if (countryEl && athlete.country) {
	countryEl.textContent = athlete.country_name || athlete.country;
  }

  // 4) Birthyear
  if (yearEl && athlete.birthyear) {
	yearEl.textContent = athlete.birthyear;
  }

  // 5) Home cable => if empty or missing, show ""
  if (cableEl) {
	if (athlete.homecable && athlete.homecable.trim() !== "") {
	  cableEl.textContent = athlete.homecable.trim();
	} else {
	  cableEl.textContent = "Secret";
	}
  }

  // 6) Sponsors => if empty or missing, show ""
  if (sponsorsEl) {
	const sponsorString = (athlete.sponsors || "").trim();
	sponsorsEl.textContent = sponsorString !== "" ? sponsorString : "sponsors needed";
  }

  // 7) Ranking
  if (rankingEl && typeof athlete.ranking_place === "number") {
	if (athlete.ranking_place === 0) {
	  rankingEl.textContent = "Not ranked in World Ranking";
	} else {
	  rankingEl.textContent = `${athlete.ranking_place}. Place in World Ranking`;
	}
  }

  // 8) Photo => "img/athletes/{athlete_id}.png" or fallback
  if (photoEl) {
	if (athlete.id) {
	  photoEl.src = `img/athletes/${athlete.id}.png`;
	} else {
	  // fallback default
	  photoEl.src = "";
	}
  }
}

/**
 * startProfileClock():
 *   - updates the #profileTime element every second with current local time
 */
function startProfileClock() {
  const timeEl = document.getElementById("profileTime");
  if (!timeEl) {
	console.warn("[profile.js] #profileTime not found => can't start live clock.");
	return;
  }

  function updateClock() {
	const now = new Date().toLocaleTimeString([], { hour12: false });
	timeEl.textContent = now;
  }
  updateClock();
  setInterval(updateClock, 1000);
}