import {
  getSafeLocalStorageItem,
  getDeviceInfo,
  removeSafeLocalStorageItem,
} from "../col_script/common/device_info.js";
import { bind_btnLogout } from "../col_script/essential/user_helper.js";

import { setHeaderMenu } from "../col_script/common/router_helper.js";

export async function checkSession(IsRedirect = true) {
  try {
    const token = getSafeLocalStorageItem("token");
    const uid = getSafeLocalStorageItem("uid");
    const type = getSafeLocalStorageItem("type");
    const device_info = getDeviceInfo();

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

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

    const formData = new FormData();
    formData.append("p_action", "check_session");
    formData.append("p_type", "user");
    formData.append("IDUser", uid);
    formData.append("Token", token);
    formData.append("device_info", JSON.stringify(device_info));

    const response = await fetch("backend/rest_api/main_data.php", {
      method: "POST",
      body: formData,
    });

    const text = await response.text();
   // console.log("Raw checkSession:", text);

    const json = JSON.parse(text);

    if (json.Status == 0) {
      if (IsRedirect) {
        await handleSessionExpired("login:sesi_invalid");
      }
      return false;
    }

    return json;
  } catch (err) {
    console.log("Error checkSession:", err);
  }
}

export function toggleContentOverlay(mode, targetId = "content-overlay") {
  const el = document.getElementById(targetId);
  if (!el) {
    console.warn(`[Overlay] Elemen dengan id "${targetId}" tidak ditemukan`);
    return;
  }

  if (mode === "on") {
    el.classList.add("blur-content");
    el.classList.remove("d-none");
  } else if (mode === "off") {
    el.classList.remove("blur-content");
    el.classList.add("d-none");
  } else {
    console.warn(
      `[Overlay] Mode tidak dikenal: "${mode}". Gunakan "on" atau "off".`
    );
  }
}

async function handleSessionExpired(messageKey) {
  removeSafeLocalStorageItem("uid");
  removeSafeLocalStorageItem("type");
  removeSafeLocalStorageItem("token");
  removeSafeLocalStorageItem("d_id");

  const defaultTitle = "Session Invalid";
  const defaultText = "Session expired or invalid. Please login again.";

  await Swal.fire({
    title:
      typeof i18next !== "undefined"
        ? i18next.t("login:sesi_invalid")
        : defaultTitle,
    icon: "warning",
    confirmButtonText: "OK",
    buttonsStyling: false,
    customClass: { confirmButton: "btn btn-primary" },
  }).then(() => {
    window.location.href = "login.php";
  });
}

// assets/js/headerUser.js

export function updateHeaderUser(listUser, listAkses) {
  const container = document.getElementById("kt_header_user_menu_toggle");
  if (!container) return;

  // Reset konten dulu
  container.innerHTML = ""; 
  setHeaderMenu("#kt_header_tabs ul", "#tab_content_header", listAkses);

  // Jika user belum login atau data tidak valid
  if (!listUser || Object.keys(listUser).length === 0) {
    container.innerHTML = `
      <div class="d-flex align-items-center gap-2">
        <a href="register.php" class="btn btn-light btn-sm fw-bold">Daftar</a>
        <a href="login.php" class="btn btn-primary btn-sm fw-bold">Login</a>
      </div>
    `;
    return;
  }

  // Kalau user sudah login
  //const avatar = listUser.Avatar || "https://placehold.co/300";
  const avatar = listUser.Avatar
    ? `attachments/user/${listUser.IDUser}/${listUser.Avatar}`
    : 'https://placehold.co/300';
  const nama = listUser.NamaLengkap || "-";
  const jabatan = listUser.NamaGroup || "-";
  const email = listUser.Email || "-";

  var header_html = `
    <!--begin::User info-->
        <div class="btn btn-flex align-items-center bg-hover-white bg-hover-opacity-10 py-2 ps-2 pe-2 me-n2"
            data-kt-menu-trigger="click" data-kt-menu-attach="parent" data-kt-menu-placement="bottom-end">

            <!--begin::Name-->
            <div class="d-none d-md-flex flex-column align-items-end justify-content-center me-2 me-md-4">
                <span class="text-white opacity-75 fs-8 fw-semibold lh-1 mb-1"
                    data-header-element="Name">${nama}</span>
                <span class="text-white fs-8 fw-bold lh-1" data-header-element="Akses">${jabatan}</span>
            </div>
            <!--end::Name-->

            <!--begin::Symbol-->
            <div class="symbol symbol-30px symbol-md-40px">
                <img src="${avatar}" alt="image" />
            </div>
            <!--end::Symbol-->
        </div>
        <!--end::User info-->


        <!--begin::User account menu-->
        <div class="menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-800 menu-state-bg menu-state-color fw-semibold py-4 fs-6 w-275px"
            data-kt-menu="true">
            <!--begin::Menu item-->
            <div class="menu-item px-3">
                <div class="menu-content d-flex align-items-center px-3">
                    <!--begin::Avatar-->
                    <div class="symbol symbol-50px me-5">
                        <img alt="Logo" src="${avatar}" />
                    </div>
                    <!--end::Avatar-->

                    <!--begin::Username-->
                    <div class="d-flex flex-column">
                        <div class="fw-bold d-flex align-items-center fs-5"
                            data-header-element="Name_Dropdown">
                            ${nama}
                        </div>

                        <a href="#" class="fw-semibold text-muted text-hover-primary fs-7"
                            data-header-element="Email_Dropdown">
                            ${email} </a>
                    </div>
                    <!--end::Username-->
                </div>
            </div>
            <!--end::Menu item-->

            <!--begin::Menu separator-->
            <div class="separator my-2"></div>
            <!--end::Menu separator-->

            <!--begin::Menu item-->
            <div class="menu-item px-5">
                <a href="m_profile.php" class="menu-link px-5" data-header-element="h_myprofile">
                    My Profile
                </a>
            </div>
            <!--end::Menu item-->

            

            {{ MenuAdmin }} 



            <!--begin::Menu separator-->
            <div class="separator my-2"></div>
            <!--end::Menu separator-->


            <!--begin::Menu item-->
            <div class="menu-item px-5 d-none" data-kt-menu-trigger="{default: 'click', lg: 'hover'}"
                data-kt-menu-placement="left-start" data-kt-menu-offset="-15px, 0">
                <a href="#" class="menu-link px-5">
                    <span class="menu-title position-relative">
                        Language

                        <span
                            class="fs-8 rounded bg-light px-3 py-2 position-absolute translate-middle-y top-50 end-0">
                            <span data-kt-element="current-lang-name">English</span>

                            <img data-kt-element="current-lang-flag" class="w-15px h-15px rounded-1 ms-2"
                                src="assets/media/flags/united-states.svg" alt="" />
                        </span>


                    </span>
                </a>

                <!--begin::Menu sub-->
                <div class="menu-sub menu-sub-dropdown w-175px py-4">
                    <!--begin::Menu item-->
                    <div class="menu-item px-3">
                        <a href="#" data-kt-lang="English" class="menu-link d-flex px-5">
                            <span class="symbol symbol-20px me-4">
                                <img class="rounded-1" src="assets/media/flags/united-states.svg" alt="" />
                            </span>
                            English
                        </a>
                    </div>
                    <!--end::Menu item-->

                    <!--begin::Menu item-->
                    <div class="menu-item px-3">
                        <a href="#" data-kt-lang="Indonesia" class="menu-link d-flex px-5">
                            <span class="symbol symbol-20px me-4">
                                <img class="rounded-1" src="assets/media/flags/indonesia.svg" alt="" />
                            </span>
                            Indonesia
                        </a>
                    </div>
                    <!--end::Menu item--> 


                </div>
                <!--end::Menu sub-->
            </div>
            <!--end::Menu item-->

            <!--begin::Menu item-->
            <div class="menu-item px-5 my-1">
                <a href="m_change_password.php" class="menu-link px-5" >
                    Ubah Password
                </a>
            </div>
            <!--end::Menu item-->

            <!--begin::Menu item-->
            <div class="menu-item px-5">
                <a href="#" class="menu-link px-5" data-header-element="btn_sign_out">
                    Sign Out
                </a>
            </div>
            <!--end::Menu item-->
        </div>
        <!--end::User account menu-->
  `;

  const aksesNames = listAkses.map((a) => a.AksesName);
  if (aksesNames.includes("Administrator.Access")) {
    header_html = header_html.replace(
      "{{ MenuAdmin }}",
      `
      <!--begin::Menu item-->
      <div class="menu-item px-5">
          <a href="index.php" class="menu-link px-5" data-header-element="h_menu_admin">
              Administrator Menu
          </a>
      </div>
      <!--end::Menu item-->
    `
    );
  } else {
    header_html = header_html.replace("{{ MenuAdmin }}", ``);
  }

  container.innerHTML = header_html;

  // 🔁 re-initialize dropdown/menu behavior
  if (typeof KTMenu !== "undefined" && KTMenu.createInstances) {
    KTMenu.createInstances();
  }

  // Bind ulang tombol sign out
  bind_btnLogout('[data-header-element="btn_sign_out"]');
}

/**
 * Sign out function
 * - Bisa disesuaikan panggil API logout atau hapus token
 */
export function signOut() {
  console.log("Signing out...");

  // Contoh: hapus token dari localStorage
  localStorage.removeItem("auth_token");

  // Redirect ke login page
  window.location.href = "login.php";
}
