/**
 * HR Pro theme: localStorage hrpro_theme = 'dark' | 'light'
 * If unset, follows prefers-color-scheme.
 */
(function () {
  var STORAGE = "hrpro_theme";

  function getStored() {
    try {
      return localStorage.getItem(STORAGE);
    } catch (e) {
      return null;
    }
  }

  function resolveDark() {
    var v = getStored();
    if (v === "dark") return true;
    if (v === "light") return false;
    try {
      return window.matchMedia("(prefers-color-scheme: dark)").matches;
    } catch (e2) {
      return true;
    }
  }

  function applyTheme() {
    var dark = resolveDark();
    if (!document.body) return;
    document.body.classList.remove("theme-light", "theme-dark");
    if (dark) document.body.classList.add("theme-dark");
    else document.body.classList.add("theme-light");
    var meta = document.querySelector('meta[name="theme-color"]');
    if (meta) meta.setAttribute("content", dark ? "#0b1220" : "#f8fafc");
    try {
      document.documentElement.style.colorScheme = dark ? "dark" : "light";
    } catch (e) {}
    syncToggleUi();
  }

  function syncToggleUi() {
    var dark = document.body.classList.contains("theme-dark");
    document.querySelectorAll(".theme-toggle").forEach(function (btn) {
      btn.setAttribute("aria-pressed", dark ? "true" : "false");
      btn.setAttribute("title", dark ? "الوضع الفاتح / Light mode" : "الوضع الداكن / Dark mode");
      btn.setAttribute(
        "aria-label",
        dark ? "Switch to light mode" : "Switch to dark mode"
      );
    });
  }

  window.hrproApplyTheme = applyTheme;

  window.hrproToggleTheme = function () {
    var isDark = document.body.classList.contains("theme-dark");
    try {
      localStorage.setItem(STORAGE, isDark ? "light" : "dark");
    } catch (e) {}
    applyTheme();
  };

  try {
    var mq = window.matchMedia("(prefers-color-scheme: dark)");
    if (mq && mq.addEventListener) {
      mq.addEventListener("change", function () {
        if (getStored() === null) applyTheme();
      });
    }
  } catch (e) {}

  if (document.body) applyTheme();
  else
    document.addEventListener("DOMContentLoaded", applyTheme, { once: true });

  document.addEventListener("DOMContentLoaded", function () {
    syncToggleUi();
  });

  /** Resolve relative upload paths (e.g. uploads/selfies/...) against the current page URL (e.g. /hr/admin.html → /hr/uploads/...). */
  window.hrproResolveUploadUrl = function (path) {
    if (!path || typeof path !== "string") return "";
    var p = path.trim().replace(/\\/g, "/");
    if (p.indexOf("..") !== -1) return "";
    if (/^https?:\/\//i.test(p) || p.indexOf("data:") === 0) return p;
    p = p.replace(/^\/+/, "");
    if (!/^uploads\//i.test(p) && /^(selfies\/|employees\/|branches\/)/i.test(p)) {
      p = "uploads/" + p;
    }
    if (p.charAt(0) === "/") return p;
    try {
      return new URL(p, window.location.href).href;
    } catch (e) {
      return p;
    }
  };
})();
