document.addEventListener("DOMContentLoaded", function () {

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

  // If no bearer token => sign out immediately
  if (!bearerToken) {
	console.error("No bearer token found in local storage — signing out.");
	localStorage.removeItem("user");
	window.location.href = "index.html";
	return;
  }

  /**
   * Build fetch headers with Bearer token + (optionally) JSON
   */
  function getAuthHeaders(isJson = true) {
	const headers = isJson ? { "Content-Type": "application/json" } : {};
	headers["Authorization"] = `Bearer ${bearerToken}`;
	return headers;
  }

  /**
   * If response not OK => sign out user & redirect
   */
  function handleNotOkResponse(response) {
	console.error(`API response not OK: ${response.status} - ${response.statusText}`);
	alert("Session expired or invalid. You will be signed out.");
	localStorage.removeItem("user");
	window.location.href = "index.html";
  }

  /**
   * If the server’s JSON indicates an invalid/expired session => sign out
   */
  function checkSessionError(data) {
	if (!data) return;
	const errStr = String(data.error || "").toLowerCase();
	if (errStr.includes("invalid") || errStr.includes("session")) {
	  alert("Session invalid or expired. Signing out...");
	  localStorage.removeItem("user");
	  window.location.href = "index.html";
	}
  }

  /************************************************************
   * 1) Inject responsive-iframe CSS dynamically
   ************************************************************/
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  styleEl.innerHTML = `
	.responsive-iframe-container {
	  position: relative;
	  padding-top: 56.25%; /* 16:9 aspect ratio, can adjust if needed */
	  height: 0;
	  overflow: hidden;
	}
	.responsive-iframe-container iframe {
	  position: absolute;
	  top: 0;
	  left: 0;
	  width: 100%;
	  height: 100%;
	  border: 1; /* or 0 if you prefer no border */
	}
	.m-2 {
	  margin: 0.5rem;
	}
  `;
  document.head.appendChild(styleEl);

  /************************************************************
   * 2) Find competition code from localStorage
   ************************************************************/
  const storedEvent = JSON.parse(localStorage.getItem("activeCompetition")) || {};
  const competitionCode = storedEvent.code || null;
  if (!competitionCode) {
	console.error("No competition code in localStorage. Aborting.");
	return;
  }

  /************************************************************
   * 3) Grab #tv-container in DOM
   ************************************************************/
  const container = document.getElementById("tv-container");
  if (!container) {
	console.error("No #tv-container found in the DOM!");
	return;
  }

  /************************************************************
   * 4) Insert the IFRAME Card with "Open in New Tab"
   ************************************************************/
  const iframeCardHTML = `
	<div class="card mb-4">
	  <div class="card-header d-flex justify-content-between align-items-center">
		<h3 class="card-title m-0">Current TV Output</h3>
		<a 
		  class="btn btn-sm btn-primary"
		  target="_blank"
		  href="tv/index.html?competitionCode=${encodeURIComponent(
			competitionCode
		  )}"
		>
		  Open in New Tab
		</a>
	  </div>
	  <div class="card-body">
		<div class="responsive-iframe-container">
		  <iframe
			src="tv/index.html?competitionCode=${encodeURIComponent(
			  competitionCode
			)}"
			allowfullscreen
		  ></iframe>
		</div>
	  </div>
	</div>
  `;
  container.innerHTML = iframeCardHTML;

  /************************************************************
   * 5) Main function: fetch toggles, render toggles card
   ************************************************************/
  function fetchTogglesAndRender() {
	fetch(
	  `${API_BASE_URL}?api=tv&competitionCode=${encodeURIComponent(
		competitionCode
	  )}`,
	  {
		method: "GET",
		headers: getAuthHeaders(true),
	  }
	)
	  .then((res) => {
		if (!res.ok) {
		  handleNotOkResponse(res);
		  return null;
		}
		return res.json();
	  })
	  .then((tvData) => {
		if (!tvData) return; // short-circuit if null

		checkSessionError(tvData);

		if (!tvData.success) {
		  console.warn("Failed to load TV data:", tvData.error);
		  return;
		}

		// Remove old toggles card if it exists
		const oldTogglesCard = document.getElementById("tv-toggles-card");
		if (oldTogglesCard) {
		  oldTogglesCard.remove();
		}

		// Destructure row: athlete, results, startlist, profile, schedule, automate
		const {
		  athlete,
		  results,
		  startlist,
		  profile,
		  schedule,
		  automate,
		} = tvData.data;

		// Build array describing toggles
		const toggles = [
		  { key: "athlete",   label: "Athlete",   value: athlete   },
		  { key: "results",   label: "Results",   value: results   },
		  { key: "startlist", label: "Startlist", value: startlist },
		  { key: "profile",   label: "Profile",   value: profile   },
		  { key: "schedule",  label: "Schedule",  value: schedule  },
		  { key: "automate",  label: "Automate",  value: automate  },
		];

		// Build the toggles card
		let togglesCardHTML = `
		  <div class="card mb-3" id="tv-toggles-card">
			<div class="card-header">
			  <h3 class="card-title m-0">TV Control Center</h3>
			</div>
			<div class="card-body">
		`;

		toggles.forEach((t) => {
		  const isActive = t.value === 1;
		  const btnClass = isActive ? "btn-success" : "btn-secondary";
		  togglesCardHTML += `
			<button 
			  class="btn ${btnClass} tv-toggle-btn m-2"
			  data-key="${t.key}"
			  data-value="${t.value}"
			>
			  ${t.label}
			</button>
		  `;
		});

		togglesCardHTML += `</div></div>`;
		container.insertAdjacentHTML("beforeend", togglesCardHTML);

		// Now handle the "disable-other" logic if automate=1
		handleAutomateState(automate);

		// Attach event listeners
		const toggleButtons = document.querySelectorAll(".tv-toggle-btn");
		toggleButtons.forEach((btn) => {
		  btn.addEventListener("click", function () {
			const key    = btn.getAttribute("data-key");
			const oldVal = parseInt(btn.getAttribute("data-value"), 10);
			const newVal = oldVal === 1 ? 0 : 1;

			updateTvValue(competitionCode, key, newVal)
			  .then((ok) => {
				if (ok) {
				  // Re-fetch => see if other toggles got zeroed
				  fetchTogglesAndRender();
				}
			  })
			  .catch((err) => console.error("Update TV Value error:", err));
		  });
		});
	  })
	  .catch((err) => {
		console.error("Error loading TV data:", err);
	  });
  }

  // Call it initially
  fetchTogglesAndRender();
  // Then auto-update every 5 seconds
  setInterval(fetchTogglesAndRender, 5000);

  /************************************************************
   * 6) If automate=1 => disable all others, if automate=0 => normal
   ************************************************************/
  function handleAutomateState(automateVal) {
	const toggleButtons = document.querySelectorAll(".tv-toggle-btn");
	toggleButtons.forEach((btn) => {
	  const k = btn.getAttribute("data-key");
	  if (k !== "automate") {
		btn.disabled = automateVal === 1;
	  }
	});
  }

  /************************************************************
   * 7) Helper to POST changes to tv.php (with Bearer)
   ************************************************************/
  function updateTvValue(competitionCode, key, value) {
	return fetch(`${API_BASE_URL}?api=tv`, {
	  method: "POST",
	  headers: getAuthHeaders(true),
	  body: JSON.stringify({ competitionCode, key, value }),
	})
	  .then((res) => {
		if (!res.ok) {
		  handleNotOkResponse(res);
		  return null;
		}
		return res.json();
	  })
	  .then((json) => {
		if (!json) return false;
		checkSessionError(json);
		if (!json.success) {
		  throw new Error(json.error || "Failed to update");
		}
		return true;
	  });
  }
});