window.appAuthPostJson = async function (url, body) {
  let response;
  try {
    response = await fetch(url, {
      method: "POST",
      credentials: "same-origin",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body)
    });
  } catch (error) {
    return {
      ok: false,
      status: 0,
      data: {
        error: "No se ha podido conectar con el servidor de la aplicacion. " + (error?.message ?? "")
      }
    };
  }

  let data = null;
  try {
    data = await response.json();
  } catch {
    data = null;
  }

  return {
    ok: response.ok,
    status: response.status,
    data
  };
};

window.appAuthPost = async function (url) {
  let response;
  try {
    response = await fetch(url, {
      method: "POST",
      credentials: "same-origin"
    });
  } catch (error) {
    return {
      ok: false,
      status: 0,
      data: {
        error: "No se ha podido conectar con el servidor de la aplicacion. " + (error?.message ?? "")
      }
    };
  }

  let data = null;
  try {
    data = await response.json();
  } catch {
    data = null;
  }

  return {
    ok: response.ok,
    status: response.status,
    data
  };
};

window.appSetBodyScrollLock = function (locked) {
  document.documentElement.classList.toggle("app-scroll-locked", Boolean(locked));
  document.body.classList.toggle("app-scroll-locked", Boolean(locked));
};

window.appGlobalLeaksActivity = (function () {
  const storageKey = "gestiona-denuncias:last-user-activity";
  const events = ["pointerdown", "pointermove", "keydown", "touchstart", "scroll"];
  let lastActivity = Date.now();
  let tracking = false;

  function readSharedActivity() {
    try {
      const stored = Number(window.localStorage.getItem(storageKey));
      return Number.isFinite(stored) && stored > 0 ? stored : 0;
    } catch {
      return 0;
    }
  }

  function markActivity() {
    lastActivity = Date.now();
    try {
      window.localStorage.setItem(storageKey, String(lastActivity));
    } catch {
      // The in-memory timestamp still works when local storage is unavailable.
    }
  }

  function start() {
    if (tracking) {
      return;
    }

    tracking = true;
    markActivity();
    for (const eventName of events) {
      window.addEventListener(eventName, markActivity, { passive: true });
    }
  }

  function stop() {
    if (!tracking) {
      return;
    }

    tracking = false;
    for (const eventName of events) {
      window.removeEventListener(eventName, markActivity);
    }
  }

  function getIdleMilliseconds() {
    const latestActivity = Math.max(lastActivity, readSharedActivity());
    return Math.max(0, Date.now() - latestActivity);
  }

  return {
    start,
    stop,
    getIdleMilliseconds
  };
})();
