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

  //------------------------------------------------
  // 1) Retrieve Bearer token from localStorage user
  //------------------------------------------------
  const localUser = JSON.parse(localStorage.getItem("user")) || {};
  const bearerToken = localUser.bearer || null;

  function getHeaders(isJson = true) {
	const headers = isJson ? { "Content-Type": "application/json" } : {};
	if (bearerToken) {
	  headers["Authorization"] = `Bearer ${bearerToken}`;
	}
	return headers;
  }

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

  //------------------------------------------------
  // 2) Insert CSS for menu styling
  //------------------------------------------------
  const style = document.createElement("style");
  style.type = "text/css";
  style.innerHTML = `
	/* Active menu highlight */
	.menu-item.active > a .menu-link,
	.menu-item.active .menu-link {
	  font-weight: 600;
	  background-color: #f0f0f0; /* example highlight color */
	}

	/* Hidden menu items */
	.menu-item.hidden {
	  display: none !important;
	}
  `;
  document.head.appendChild(style);

  //------------------------------------------------
  // 3) Load Header and Initialize User Data
  //------------------------------------------------
  loadHeader(() => {
	initializeUserData();
  });

  let lastRoleDataCache = null;

  /**
   * loadHeader => inserts your HTML for the header into #header-container.
   * Then runs the callback and initializes the menu library.
   */
  function loadHeader(callback) {
	const headerHTML = `
	  <div class="container-xxl d-flex justify-content-between align-items-stretch app-container" id="kt_app_header_container">
		<div class="d-flex flex-grow-1 align-items-center flex-lg-grow-0 me-lg-15">
		  <a href="https://score-now.com/dashboard.html">
			<img class="h-50px h-lg-50px app-sidebar-logo-default theme-light-show" alt="Logo" src="assets/img/logos/logo-180.png" width="125" height="50">
			<img class="h-50px h-lg-50px app-sidebar-logo-default theme-dark-show" alt="Logo" src="assets/img/logos/logo-180-w.png" width="125" height="50">
		  </a>
		</div>
		<div class="d-flex justify-content-between align-items-stretch flex-lg-grow-1" id="kt_app_header_wrapper">
		  <div class="align-items-stretch app-header-menu app-header-mobile-drawer"
			   data-kt-drawer="true"
			   data-kt-drawer-name="app-header-menu"
			   data-kt-drawer-activate="{default: true, lg: false}"
			   data-kt-drawer-overlay="true"
			   data-kt-drawer-width="250px"
			   data-kt-drawer-direction="end"
			   data-kt-drawer-toggle="#kt_app_header_menu_toggle"
			   data-kt-swapper="true"
			   data-kt-swapper-mode="{default: 'append', lg: 'prepend'}"
			   data-kt-swapper-parent="{default: '#kt_app_body', lg: '#kt_app_header_wrapper'}">

			<div class="align-items-stretch menu menu-rounded menu-column menu-lg-row my-5 my-lg-0 fw-semibold px-2 px-lg-0"
				 id="kt_app_header_menu"
				 data-kt-menu="true">
			  <div class="menu-item"><a href="dashboard.html" target=""><span class="menu-link"><span class="menu-title">Dashboard</span></span></a></div>
			  <div class="menu-item"><a href="schedule.html" target=""><span class="menu-link"><span class="menu-title">Schedule</span></span></a></div>
			  <div class="menu-item"><a href="schedule_officials.html" target=""><span class="menu-link"><span class="menu-title">My Schedule</span></span></a></div>
			  <div class="menu-item"><a href="dock.html" target=""><span class="menu-link"><span class="menu-title">Dock</span></span></a></div>

			  <!-- Scoring menu item -->
			  <div class="menu-item"><a href="scoring.html" target=""><span class="menu-link"><span class="menu-title">Scoring</span></span></a></div>

			  <!-- Judging menu item -->
			  <div class="menu-item"><a href="judging.html" target=""><span class="menu-link"><span class="menu-title">Judging</span></span></a></div>

			  <div class="menu-item"><a href="scoreboard/index.html" target="_blank"><span class="menu-link"><span class="menu-title">Scoreboard</span><i class="bi bi-box-arrow-up-right ms-2" aria-hidden="true"></i></span></a></div>
			  <div class="menu-item"><a href="competition.html" target="_blank"><span class="menu-link"><span class="menu-title">Public</span><i class="bi bi-box-arrow-up-right ms-2" aria-hidden="true"></i></span></a></div>
			  <div class="menu-item"><a href="tv.html" target=""><span class="menu-link"><span class="menu-title">TV</span></span></a></div>
			  <div class="menu-item"><a href="teamscoring.html" target=""><span class="menu-link"><span class="menu-title">Team Results</span></span></a></div>
			  <div class="menu-item"><a href="settings.html" target=""><span class="menu-link"><span class="menu-title">Settings</span></span></a></div>
			</div>
		  </div>

		  <div class="flex-shrink-0 app-navbar">
			<div class="app-navbar-item ms-1 ms-md-3">
			  <a class="btn btn-icon btn-custom btn-icon-muted btn-active-light btn-active-color-primary w-30px h-30px w-md-40px h-md-40px"
				 role="button"
				 href="#"
				 data-kt-menu-trigger="{default:'click', lg: 'hover'}"
				 data-kt-menu-attach="parent"
				 data-kt-menu-placement="bottom-end">
				<span class="theme-light-show"><i class="bi bi-sun-fill fs-4"></i></span>
				<span class="theme-dark-show"><i class="bi bi-moon-fill fs-4"></i></span>
			  </a>

			  <div class="fw-semibold menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-title-gray-700 menu-icon-muted menu-active-bg menu-state-color py-4 fs-base w-150px"
				   data-kt-menu="true"
				   data-kt-element="theme-mode-menu">
				<div class="menu-item px-3 my-0">
				  <a href="#" class="menu-link px-3 py-2" data-kt-element="mode" data-kt-value="light">
					<span class="menu-icon" data-kt-element="icon"><i class="bi bi-sun-fill"></i></span>
					<span class="menu-title">Light</span>
				  </a>
				</div>
				<div class="menu-item px-3 my-0">
				  <a href="#" class="menu-link px-3 py-2" data-kt-element="mode" data-kt-value="dark">
					<span class="menu-icon" data-kt-element="icon"><i class="bi bi-moon-fill"></i></span>
					<span class="menu-title">Dark</span>
				  </a>
				</div>
				<div class="menu-item px-3 my-0">
				  <a href="#" class="menu-link px-3 py-2" data-kt-element="mode" data-kt-value="system">
					<span class="menu-icon" data-kt-element="icon"><i class="bi bi-laptop"></i></span>
					<span class="menu-title">System</span>
				  </a>
				</div>
			  </div>
			</div>

			<div class="app-navbar-item ms-1 ms-md-3" id="kt_header_user_menu_toggle">
			  <div class="cursor-pointer symbol symbol-30px symbol-md-40px"
				   data-kt-menu-trigger="{default: 'click', lg: 'hover'}"
				   data-kt-menu-attach="parent"
				   data-kt-menu-placement="bottom-end">
				<img src="img/avatar.png" alt="user">
			  </div>

			  <div class="fs-6 fw-semibold menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-800 menu-state-bg menu-state-color py-4 w-275px" data-kt-menu="true">
				<div class="menu-item px-3">
				  <div class="d-flex align-items-center menu-content px-3">
					<div class="symbol symbol-50px me-5"><img alt="Logo" src="img/avatar.png"></div>
					<div class="d-flex flex-column">
					  <div class="fs-5 fw-bold d-flex align-items-center">
						<span id="user-name"></span>
						<span class="badge fw-bold badge-light-success fs-8 px-2 py-1 ms-2">Official</span>
					  </div>
					  <a class="fw-semibold text-muted text-hover-primary fs-7" href="#" id="user-email"></a>
					</div>
				  </div>
				</div>

				<div class="separator my-2"></div>

				<div class="menu-item px-5">
				  <a id="admin-btn" href="admin.html" class="menu-link px-5">Administration</a>
				</div>
				<div class="menu-item px-5">
				  <a id="sign-out-btn" href="#" class="menu-link px-5">Sign Out</a>
				</div>
			  </div>
			</div>

			<div class="d-lg-none app-navbar-item ms-2 me-n3" title="Show header menu">
			  <div class="btn btn-icon btn-active-color-primary w-30px h-30px w-md-35px h-md-35px" id="kt_app_header_menu_toggle">
				<i class="bi bi-list fs-4"></i>
			  </div>
			</div>
		  </div>
		</div>
	  </div>
	`;

	const headerContainer = document.getElementById("header-container");
	if (headerContainer) {
	  headerContainer.innerHTML = headerHTML;
	  if (typeof callback === "function") callback();
	  // Initialize the menu library (e.g., KTMenu for Metronic)
	  if (typeof KTMenu !== 'undefined' && typeof KTMenu.init === 'function') {
		KTMenu.init(); // This ensures the menu interactions are set up
	  } else {
		console.warn("KTMenu library is not loaded or init function is missing.");
	  }
	} else {
	  console.error("Header container element not found!");
	}
  }

  // Once the header is loaded, init user data => name, email, sign-out, etc.
  function initializeUserData() {
	const userData = getUserData();

	const userNameEl = document.getElementById("user-name");
	if (userNameEl) {
	  userNameEl.textContent = `${userData.first_name || "Guest"} ${userData.last_name || ""}`;
	}

	const userEmailEl = document.getElementById("user-email");
	if (userEmailEl) {
	  userEmailEl.textContent = userData.email || "No Email";
	}

	const signOutBtn = document.getElementById("sign-out-btn");
	if (signOutBtn) {
	  signOutBtn.addEventListener("click", (event) => {
		event.preventDefault();
		localStorage.removeItem("user");
		window.location.href = "index.html";
	  });
	}

	toggleMenuLinks();
  }

  function getUserData() {
	try {
	  return JSON.parse(localStorage.getItem("user")) || { name: "Guest", email: null };
	} catch (error) {
	  console.error("Error parsing user data:", error);
	  return { name: "Guest", email: null };
	}
  }

  //------------------------------------------------
  // 4) Fetch Role & Access Data => /roles
  //------------------------------------------------
  function fetchUserRoles(competitionCode) {
	const url = `${API_BASE_URL}?api=roles&competitionCode=${encodeURIComponent(competitionCode)}`;
	return fetch(url, {
	  method: "GET",
	  headers: getHeaders(),
	})
	  .then((res) => res.json())
	  .then((data) => {
		if (!data || !data.status) {
		  console.warn("No role data found:", data);
		  return null;
		}
		return data;
	  })
	  .catch((err) => {
		console.error("Error fetching user roles:", err);
		return null;
	  });
  }

  //------------------------------------------------
  // 5) Hide or Show Menu Items
  //------------------------------------------------
  function toggleMenuLinks() {
	const storedCompetition = JSON.parse(localStorage.getItem("activeCompetition"));
	if (!storedCompetition || !storedCompetition.code) {
	  hideAllMenuItems();
	  return;
	}

	const competitionCode = storedCompetition.code;
	fetchUserRoles(competitionCode).then((data) => {
	  if (!data) {
		hideAllMenuItems();
		return;
	  }

	  const roleDataStr = JSON.stringify(data);
	  if (roleDataStr === lastRoleDataCache) {
		return;
	  }
	  lastRoleDataCache = roleDataStr;

	  const { access } = data;
	  if (!access) {
		hideAllMenuItems();
		return;
	  }

	  // Show all first, then selectively hide
	  showAllMenuItems();

	  if (!access.schedule)       hideMenuItem("schedule.html");
	  if (!access.my_schedule)    hideMenuItem("schedule_officials.html");
	  if (!access.dock)          hideMenuItem("dock.html");
	  if (!access.scoring)       hideMenuItem("scoring.html");
	  if (!access.judging)       hideMenuItem("judging.html");
	  if (!access.tv)            hideMenuItem("tv.html");
	  hideMenuItem("teamscoring.html");
	  if (!access.settings)      hideMenuItem("settings.html");
	  if (!access.admin)         hideMenuItem("admin.html");

	  updateCompetitionLinks();
	});
  }

  /**
   * hideMenuItem => For anchors that start with "hrefFileName",
   * hide the entire .menu-item if found, else just the anchor.
   */
  function hideMenuItem(hrefFileName) {
	const allLinks = document.querySelectorAll(`a[href="${hrefFileName}"]`);
	allLinks.forEach((link) => {
	  // If the link is the sign-out => skip (always show sign-out).
	  if (link.id === "sign-out-btn") return;

	  const parentItem = link.closest(".menu-item");
	  if (parentItem) {
		parentItem.classList.add("hidden");
	  } else {
		// not inside a .menu-item => hide the link itself
		link.style.display = "none";
	  }
	});
  }

  function showAllMenuItems() {
	// Show main nav items
	document.querySelectorAll("#kt_app_header_menu .menu-item").forEach((item) => {
	  item.classList.remove("hidden");
	});
	// Also re-show user dropdown links if we had hidden them
	document.querySelectorAll('.menu-sub.menu-sub-dropdown a[style*="display: none"]').forEach((link) => {
	  // For sign-out etc., re-show
	  link.style.display = "";
	});
  }

  function hideAllMenuItems() {
	// Hide everything except "Dashboard" in main nav
	const allItems = document.querySelectorAll("#kt_app_header_menu .menu-item");
	allItems.forEach((item) => {
	  const dashLink = item.querySelector('a[href="dashboard.html"]');
	  if (!dashLink) {
		item.classList.add("hidden");
	  }
	});

	// Also hide user dropdown links except sign-out
	const userMenuLinks = document.querySelectorAll('.menu-sub.menu-sub-dropdown a[href]');
	userMenuLinks.forEach((link) => {
	  // If it's not sign-out => hide it
	  if (link.id !== "sign-out-btn") {
		link.style.display = "none";
	  }
	});
  }

  /** Example: add competitionCode to scoreboard/index.html + competition.html */
  function updateCompetitionLinks() {
	const storedCompetition = JSON.parse(localStorage.getItem("activeCompetition"));
	if (storedCompetition && storedCompetition.code) {
	  const competitionCode = storedCompetition.code;

	  // Scoreboard link
	  const scoreboardLink = document.querySelector('#kt_app_header_menu a[href="scoreboard/index.html"]');
	  if (scoreboardLink) {
		scoreboardLink.href = `scoreboard/index.html?competitionCode=${encodeURIComponent(competitionCode)}`;
	  }

	  // Public competition link
	  const competitionPageLink = document.querySelector('#kt_app_header_menu a[href="competition.html"]');
	  if (competitionPageLink) {
		competitionPageLink.href = `competition.html?CompetitionCode=${encodeURIComponent(competitionCode)}`;
	  }
	}
  }

  // Re-check roles every 3 seconds
  setInterval(toggleMenuLinks, 3000);
});