import {
  getSafeLocalStorageItem,
  getDeviceInfo,
  removeSafeLocalStorageItem,
} from "./device_info.js";

export async function checkSession(IsRedirect = true) {
  if (typeof window.i18nReady !== "undefined") {
    try {
      await window.i18nReady;
    } catch (e) {
      console.warn("⚠️ Gagal inisialisasi i18n, lanjutkan tanpa translasi.");
    }
  } else {
    console.warn("⚠️ i18nReady tidak ditemukan. Lanjut tanpa translasi.");
  }

  document.getElementById("content-overlay").classList.add("blur-content");
  document.getElementById("content-overlay").classList.remove("d-none");

  const token = getSafeLocalStorageItem("token");
  const uid = getSafeLocalStorageItem("uid");
  const type = getSafeLocalStorageItem("type");
  const device_info = getDeviceInfo();

  if (!uid || !token || !type || !device_info) {
    await handleSessionExpired("login:sesi_invalid");
    return false;
  }

  const formData = new URLSearchParams();
  formData.append("action", "check_sesi");
  formData.append("u_token", token);
  formData.append("ID", uid);
  formData.append("type", type);
  formData.append("device_info", JSON.stringify(device_info));

  try {
    const response = await fetch("proxy/user_proxy.php", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: formData.toString(),
    });

    const rawText = await response.text();
    console.log("Check Sesi Raw Response:", rawText);
    const result = JSON.parse(rawText);

    if (result.Status === 1) {
      return result;
    } else {
      if (IsRedirect) {
        await handleSessionExpired("login:" + result.Keterangan);
      }
      return false;
    }
  } catch (err) {
    console.error("checkSession error", err);
    if (IsRedirect) {
      await handleSessionExpired("login:session_check_failed");
    }
    return false;
  }
}
