// assets/js/users.js
import { requireSession, apiFetch, getQueryParam } from "../app.js";

// LABEL TEKS (single language / Indonesia saja)
const TEXT = {
  dropdownTheme: "Tema",
  dropdownLogout: "Keluar",

  menuDashboard: "Dashboard",
  menuGlobalSheets: "Global Sheets",
  menuBrandMeta: "Brand Meta",
  menuProfiles: "Profiles",
  menuProses: "Proses",
  depBank: "Catat Bank",
  depEwallet: "Catat Ewallet",
  depPulsa: "Catat Pulsa",
  depWD: "Catat Withdraw",

  // ✅ NEW: Notifikasi
  menuNotifikasi: "Notifikasi",
  notifBank: "Bank",
  notifEwallet: "Ewallet",

  menuLaporan: "Laporan",
  repPendingan: "Pendingan",
  repMistake: "Mistake",
  menuAutoWD: "Auto Withdraw",
  awdWithdraw: "Withdraw",
  menuAdmin: "Admin",
  menuUsers: "Users",

  usersDesc: "Kelola akun superadmin/admin. Global untuk TIARA, TTS & TTM.",
  onlySuperMsg: "Hanya superadmin yang boleh mengakses halaman ini.",
  listCaption: "Daftar user aktif",
  btnNewUser: "+ User Baru",

  thUsername: "Username",
  thRole: "Role",
  thStatus: "Status",
  thAccess: "Akses",
  thActions: "Aksi",
  statusActive: "aktif",
  statusInactive: "nonaktif",
  btnEdit: "Edit",
  btnDelete: "Hapus",
  emptyMessage: "Belum ada user. Klik + User Baru untuk membuat superadmin/admin.",

  modalNewTitle: "User Baru",
  modalEditPrefix: "Edit: ",
  lblUsername: "Username",
  lblPassword: "Password",
  pwdHintEdit: "(kosongkan kalau tidak ganti)",
  lblRole: "Role",
  lblScopes: "Akses Sidebar",
  lblActive: "Aktif",
  scopeBrand: "Brand",
  scopeProses: "Proses",
  scopeLaporan: "Laporan",
  scopeAutoWD: "Auto Withdraw",

  // ✅ NEW: label scope Notifikasi
  scopeNotifikasi: "Notifikasi",

  btnCancel: "Batal",
  btnSave: "Simpan",

  alertSaveFail: "Gagal simpan",
  alertDeleteFail: "Gagal hapus",
  confirmDelete: "Hapus user {username}?",
  accessAll: "Semua",
  accessDash: "—",
};

function T(key) {
  return TEXT[key] || key;
}

// RBAC default scopes (fallback)
// ✅ tambah notifikasi:false
const DEFAULT_SCOPES = { brand: true, proses: true, laporan: true, autowd: false, notifikasi: false };

// STATE
const activeBrand = (getQueryParam("brand") || "tiara").toLowerCase();
const brandLogoMap = {
  tiara: "assets/img/tiaratoto.png",
  tts: "assets/img/totosakti.png",
  ttm: "assets/img/totomantap.png", // pastikan file ini ada
};

// --- ICONS ---
function iconSVG(name, highlight = false) {
  const base = highlight ? "text-blue-500 dark:text-blue-400" : "text-slate-500 dark:text-slate-400";
  const svg = (p) => `<span class="${base}">${p}</span>`;
  if (name === "home")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M3 12L12 3l9 9"/><path d="M9 21V12h6v9"/></svg>`
    );
  if (name === "sheets")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="9" y1="4" x2="9" y2="22"/></svg>`
    );
  if (name === "brand")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><circle cx="19" cy="12" r="3"/><circle cx="5" cy="12" r="3"/></svg>`
    );
  if (name === "profile")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>`
    );
  if (name === "chat")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M21 15a4 4 0 0 1-4 4H7l-4 4V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"/></svg>`
    );
  if (name === "users")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>`
    );
  if (name === "report")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M9 3h6a2 2 0 0 1 2 2v16l-5-3-5 3V5a2 2 0 0 1 2-2z"/></svg>`
    );
  if (name === "zap")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><polyline points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`
    );

  // ✅ NEW: Notifikasi icon
  if (name === "bank")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M3 10h18"/><path d="M5 10v10"/><path d="M9 10v10"/><path d="M15 10v10"/><path d="M19 10v10"/><path d="M4 20h16"/><path d="M12 3l9 5H3l9-5z"/></svg>`
    );
  if (name === "wallet")
    return svg(
      `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3"/><path d="M21 12h-7a2 2 0 0 0 0 4h7v-4z"/><circle cx="16" cy="14" r="1"/></svg>`
    );

  return "";
}

// sidebar clock card
function sidebarClockCard(prefix) {
  return `
  <div class="mb-4">
    <div class="rounded-lg border border-slate-300 dark:border-[#3f3f46] bg-slate-50 dark:bg-[#2a2a2a] text-[12px] p-3">
      <div class="grid grid-cols-[max-content_1ch_1fr] gap-x-2 gap-y-1">
        <div class="text-slate-500 font-medium">Tanggal</div><div class="text-slate-500">:</div><div id="sidebarDate${prefix}" class="font-semibold">-</div>
        <div class="text-slate-500 font-medium">Waktu</div><div class="text-slate-500">:</div><div id="sidebarTime${prefix}" class="font-semibold">-</div>
      </div>
    </div>
  </div>`;
}

// brandMap (identik index) + item Users aktif
// Tambah kunci "scope" per-section agar bisa difilter oleh RBAC.
const brandMap = {
  tiara: {
    badge: "TIARATOTO",
    sections: [
      { labelKey: "menuDashboard", items: [{ textKey: "menuDashboard", href: `index.html?brand=tiara`, icon: "home", active: false }] },
      {
        labelKey: null, brandBadge: "TIARATOTO", scope: "brand",
        items: [
          { textKey: "menuGlobalSheets", href: `global.html?brand=tiara`, icon: "sheets", active: false },
          { textKey: "menuBrandMeta", href: `brand.html?brand=tiara`, icon: "brand", active: false },
          {
            textKey: "menuProfiles", href: null, icon: "profile", active: false,
            submenu: [
              { textKey: "depBank", channel: "bank" },
              { textKey: "depEwallet", channel: "ewallet" },
              { textKey: "depPulsa", channel: "pulsa" },
              { textKey: "depWD", channel: "wd" },
            ],
          },
        ]
      },
      {
        labelKey: "menuProses", scope: "proses",
        items: [
          { textKey: "depBank", href: `bank.html?brand=tiara`, icon: "chat", active: false },
          { textKey: "depEwallet", href: `ewallet.html?brand=tiara`, icon: "chat", active: false },
          { textKey: "depPulsa", href: `pulsa.html?brand=tiara`, icon: "chat", active: false },
          { textKey: "depWD", href: `wd.html?brand=tiara`, icon: "chat", active: false },
        ]
      },

      // ✅ NEW: NOTIFIKASI
      {
        labelKey: "menuNotifikasi", scope: "notifikasi",
        items: [
          { textKey: "notifBank", href: `notifbank.html?brand=tiara`, icon: "bank", active: false },
          { textKey: "notifEwallet", href: `notifewallet.html?brand=tiara`, icon: "wallet", active: false },
        ]
      },

      {
        labelKey: "menuLaporan", scope: "laporan",
        items: [
          { textKey: "repPendingan", href: `pendingan.html?brand=tiara`, icon: "report", active: false },
          { textKey: "repMistake", href: `mistake.html?brand=tiara`, icon: "report", active: false },
        ]
      },
      {
        labelKey: "menuAutoWD", scope: "autowd",
        items: [{ textKey: "awdWithdraw", href: `withdraw-awd.html?brand=tiara`, icon: "zap", active: false }]
      },
      {
        labelKey: "menuAdmin",
        items: [{ textKey: "menuUsers", href: `users.html?brand=tiara`, icon: "users", active: true, requireSuperadmin: true }]
      },
    ],
  },
  tts: {
    badge: "TOTOSAKTI",
    sections: [
      { labelKey: "menuDashboard", items: [{ textKey: "menuDashboard", href: `index.html?brand=tts`, icon: "home", active: false }] },
      {
        labelKey: null, brandBadge: "TOTOSAKTI", scope: "brand",
        items: [
          { textKey: "menuGlobalSheets", href: `global.html?brand=tts`, icon: "sheets", active: false },
          { textKey: "menuBrandMeta", href: `brand.html?brand=tts`, icon: "brand", active: false },
          {
            textKey: "menuProfiles", href: null, icon: "profile", active: false,
            submenu: [
              { textKey: "depBank", channel: "bank" },
              { textKey: "depEwallet", channel: "ewallet" },
              { textKey: "depPulsa", channel: "pulsa" },
              { textKey: "depWD", channel: "wd" },
            ],
          },
        ]
      },
      {
        labelKey: "menuProses", scope: "proses",
        items: [
          { textKey: "depBank", href: `bank.html?brand=tts`, icon: "chat", active: false },
          { textKey: "depEwallet", href: `ewallet.html?brand=tts`, icon: "chat", active: false },
          { textKey: "depPulsa", href: `pulsa.html?brand=tts`, icon: "chat", active: false },
          { textKey: "depWD", href: `wd.html?brand=tts`, icon: "chat", active: false },
        ]
      },

      // ✅ NEW: NOTIFIKASI
      {
        labelKey: "menuNotifikasi", scope: "notifikasi",
        items: [
          { textKey: "notifBank", href: `notifbank.html?brand=tts`, icon: "bank", active: false },
          { textKey: "notifEwallet", href: `notifewallet.html?brand=tts`, icon: "wallet", active: false },
        ]
      },

      {
        labelKey: "menuLaporan", scope: "laporan",
        items: [
          { textKey: "repPendingan", href: `pendingan.html?brand=tts`, icon: "report", active: false },
          { textKey: "repMistake", href: `mistake.html?brand=tts`, icon: "report", active: false },
        ]
      },
      {
        labelKey: "menuAutoWD", scope: "autowd",
        items: [{ textKey: "awdWithdraw", href: `withdraw-awd.html?brand=tts`, icon: "zap", active: false }]
      },
      {
        labelKey: "menuAdmin",
        items: [{ textKey: "menuUsers", href: `users.html?brand=tts`, icon: "users", active: true, requireSuperadmin: true }]
      },
    ],
  },
  ttm: {
    badge: "TOTOMANTAP",
    sections: [
      { labelKey: "menuDashboard", items: [{ textKey: "menuDashboard", href: `index.html?brand=ttm`, icon: "home", active: false }] },
      {
        labelKey: null, brandBadge: "TOTOMANTAP", scope: "brand",
        items: [
          { textKey: "menuGlobalSheets", href: `global.html?brand=ttm`, icon: "sheets", active: false },
          { textKey: "menuBrandMeta", href: `brand.html?brand=ttm`, icon: "brand", active: false },
          {
            textKey: "menuProfiles", href: null, icon: "profile", active: false,
            submenu: [
              { textKey: "depBank", channel: "bank" },
              { textKey: "depEwallet", channel: "ewallet" },
              { textKey: "depPulsa", channel: "pulsa" },
              { textKey: "depWD", channel: "wd" },
            ],
          },
        ]
      },
      {
        labelKey: "menuProses", scope: "proses",
        items: [
          { textKey: "depBank", href: `bank.html?brand=ttm`, icon: "chat", active: false },
          { textKey: "depEwallet", href: `ewallet.html?brand=ttm`, icon: "chat", active: false },
          { textKey: "depPulsa", href: `pulsa.html?brand=ttm`, icon: "chat", active: false },
          { textKey: "depWD", href: `wd.html?brand=ttm`, icon: "chat", active: false },
        ]
      },

      // ✅ NEW: NOTIFIKASI
      {
        labelKey: "menuNotifikasi", scope: "notifikasi",
        items: [
          { textKey: "notifBank", href: `notifbank.html?brand=ttm`, icon: "bank", active: false },
          { textKey: "notifEwallet", href: `notifewallet.html?brand=ttm`, icon: "wallet", active: false },
        ]
      },

      {
        labelKey: "menuLaporan", scope: "laporan",
        items: [
          { textKey: "repPendingan", href: `pendingan.html?brand=ttm`, icon: "report", active: false },
          { textKey: "repMistake", href: `mistake.html?brand=ttm`, icon: "report", active: false },
        ]
      },
      {
        labelKey: "menuAutoWD", scope: "autowd",
        items: [{ textKey: "awdWithdraw", href: `withdraw-awd.html?brand=ttm`, icon: "zap", active: false }]
      },
      {
        labelKey: "menuAdmin",
        items: [{ textKey: "menuUsers", href: `users.html?brand=ttm`, icon: "users", active: true, requireSuperadmin: true }]
      },
    ],
  },
};

// Render sidebar dengan filter RBAC per-section.
function renderSidebar(brandKey, prefix, isSuperadmin, scopes) {
  const cfg = brandMap[brandKey] || brandMap["tiara"];
  const parentActiveCls = "bg-blue-50 text-blue-600 border-blue-200 dark:bg-blue-950/40 dark:text-blue-400 dark:border-blue-800";
  const parentNormalCls =
    "hover:bg-slate-100 hover:text-blue-600 border-transparent text-slate-700 dark:text-slate-200 dark:hover:bg-[#2a2a2a] dark:hover:text-blue-400";
  let html = sidebarClockCard(prefix);

  cfg.sections.forEach((section) => {
    const allowByScope = isSuperadmin || !section.scope || (scopes && scopes[section.scope]);
    if (!allowByScope) return;

    const sectionTitle = section.labelKey ? T(section.labelKey).toUpperCase() : cfg.badge;

    let itemsHTML = "";
    section.items.forEach((item) => {
      if (item.requireSuperadmin && !isSuperadmin) return;

      if (item.icon === "profile") {
        const btnCls = parentNormalCls;
        itemsHTML += `
          <li>
            <button id="profilesToggle${prefix}" class="w-full flex items-center justify-between px-3 py-2 rounded-md font-medium border ${btnCls}">
              <span class="flex items-center gap-2">${iconSVG(item.icon,false)}<span>${T("menuProfiles")}</span></span>
              <span class="text-slate-500 dark:text-slate-400"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24" class="transition-transform" data-chevron><polyline points="6 9 12 15 18 9"/></svg></span>
            </button>
            <ul id="profilesSub${prefix}" class="mt-1 ml-6 space-y-1 hidden">
              <li><a href="profile-edit.html?brand=${brandKey}&channel=bank" class="flex items-center gap-2 px-3 py-2 rounded-md font-medium border text-[12px] leading-tight ${parentNormalCls}"><span class="w-2 h-2 rounded-full bg-current"></span><span>${T("depBank")}</span></a></li>
              <li><a href="profile-edit.html?brand=${brandKey}&channel=ewallet" class="flex items-center gap-2 px-3 py-2 rounded-md font-medium border text-[12px] leading-tight ${parentNormalCls}"><span class="w-2 h-2 rounded-full bg-current"></span><span>${T("depEwallet")}</span></a></li>
              <li><a href="profile-edit.html?brand=${brandKey}&channel=pulsa" class="flex items-center gap-2 px-3 py-2 rounded-md font-medium border text-[12px] leading-tight ${parentNormalCls}"><span class="w-2 h-2 rounded-full bg-current"></span><span>${T("depPulsa")}</span></a></li>
              <li><a href="profile-edit.html?brand=${brandKey}&channel=wd" class="flex items-center gap-2 px-3 py-2 rounded-md font-medium border text-[12px] leading-tight ${parentNormalCls}"><span class="w-2 h-2 rounded-full bg-current"></span><span>${T("depWD")}</span></a></li>
            </ul>
          </li>
        `;
      } else {
        const isUsersItem = item.icon === "users";
        const linkCls = isUsersItem ? parentActiveCls : parentNormalCls;
        itemsHTML += `<li><a href="${item.href}" class="flex items-center gap-2 px-3 py-2 rounded-md font-medium border ${linkCls}">${iconSVG(item.icon, isUsersItem)}<span>${T(item.textKey)}</span></a></li>`;
      }
    });

    if (!itemsHTML) return;

    html += `<div class="mb-4"><div class="text-[11px] uppercase font-semibold text-slate-400 dark:text-slate-500 tracking-wide mb-2">${sectionTitle}</div><ul class="space-y-1">${itemsHTML}</ul></div>`;
  });

  return html;
}

function attachSidebarToggle(prefix) {
  const btn = document.getElementById("profilesToggle" + prefix);
  const sub = document.getElementById("profilesSub" + prefix);
  if (!btn || !sub) return;
  btn.addEventListener("click", () => {
    sub.classList.toggle("hidden");
    const chev = btn.querySelector("[data-chevron]");
    if (chev) chev.classList.toggle("rotate-180");
  });
}

function updateSidebarClock() {
  const now = new Date();
  const weekdayId = new Intl.DateTimeFormat("id-ID", { timeZone: "Asia/Jakarta", weekday: "long" }).format(now);
  const parts = new Intl.DateTimeFormat("en-US", {
    timeZone: "Asia/Jakarta",
    year: "numeric",
    month: "numeric",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: false,
  }).formatToParts(now);
  const m = Object.fromEntries(parts.map((x) => [x.type, x.value]));
  const bulanShort = ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des"];
  const tanggalStr = `${weekdayId}, ${m.day} ${bulanShort[parseInt(m.month, 10) - 1]} ${m.year}`;
  const waktuStr = `${m.hour}:${m.minute}:${m.second}`;
  ["Desktop", "Mobile"].forEach((p) => {
    const d = document.getElementById("sidebarDate" + p),
      t = document.getElementById("sidebarTime" + p);
    if (d) d.textContent = tanggalStr;
    if (t) t.textContent = waktuStr;
  });
}

// DOM refs
const brandBtn = document.getElementById("brandBtn");
const brandDropdown = document.getElementById("brandDropdown");
const userMenuBtn = document.getElementById("userMenuBtn");
const userDropdown = document.getElementById("userDropdown");
const themeToggleBtn = document.getElementById("themeToggleBtn");
const hamburgerBtn = document.getElementById("hamburgerBtn");
const mobileSidebar = document.getElementById("mobileSidebar");
const closeSidebarBtn = document.getElementById("closeSidebarBtn");
const sidebarOverlay = document.getElementById("sidebarOverlay");
const logoutBtn = document.getElementById("logoutBtn");

// USERS UI refs
const onlySuperEl = document.getElementById("onlySuperadmin");
const actionsBar = document.getElementById("actionsBar");
const usersWrap = document.getElementById("usersWrap");
const emptyWrap = document.getElementById("emptyWrap");
const tbody = document.getElementById("usersTbody");

const modal = document.getElementById("userModal");
const fUsername = document.getElementById("fUsername");
const fPassword = document.getElementById("fPassword");
const fRole = document.getElementById("fRole");
const fActive = document.getElementById("fActive");
const pwdHint = document.getElementById("pwdHint");
const modalTitle = document.getElementById("modalTitle");

// SCOPES (base dari HTML)
const scopesWrap = document.getElementById("scopesWrap");
const fScopeBrand = document.getElementById("fScopeBrand");
const fScopeProses = document.getElementById("fScopeProses");
const fScopeLaporan = document.getElementById("fScopeLaporan");
const fScopeAutoWD = document.getElementById("fScopeAutoWD");

// ✅ NEW: Notifikasi scope (akan di-inject, tanpa ubah HTML)
let fScopeNotifikasi = null;

let editMode = null; // null | username

function ensureNotifikasiScopeControl() {
  if (!scopesWrap) return;
  if (document.getElementById("fScopeNotifikasi")) {
    fScopeNotifikasi = document.getElementById("fScopeNotifikasi");
    return;
  }
  const container = scopesWrap.querySelector("div.flex.flex-wrap.gap-4");
  if (!container) return;

  const label = document.createElement("label");
  label.className = "inline-flex items-center gap-2 text-[13px]";
  label.innerHTML = `
    <input id="fScopeNotifikasi" type="checkbox" class="rounded border-slate-300 text-blue-600 focus:ring-blue-500/60">
    <span id="lblScopeNotifikasi" class="text-slate-700 dark:text-slate-200">${T("scopeNotifikasi")}</span>
  `;
  container.appendChild(label);

  fScopeNotifikasi = document.getElementById("fScopeNotifikasi");
}

function showScopesUI(role) {
  if (role === "admin") {
    scopesWrap.classList.remove("hidden");
  } else {
    scopesWrap.classList.add("hidden");
  }
}
function setScopesValues(scopes) {
  const s = scopes || { brand: true, proses: true, laporan: true, autowd: false, notifikasi: false };
  fScopeBrand.checked = !!s.brand;
  fScopeProses.checked = !!s.proses;
  fScopeLaporan.checked = !!s.laporan;
  if (fScopeAutoWD) fScopeAutoWD.checked = !!s.autowd;
  if (fScopeNotifikasi) fScopeNotifikasi.checked = !!s.notifikasi;
}

function openModal(edit, row) {
  ensureNotifikasiScopeControl();

  editMode = edit ? row.username : null;
  modalTitle.textContent = edit ? `${T("modalEditPrefix")}${row.username}` : T("modalNewTitle");
  fUsername.value = edit ? row.username : "";
  fUsername.disabled = !!edit;
  fPassword.value = "";
  pwdHint.textContent = edit ? T("pwdHintEdit") : "";
  fRole.value = edit ? row.role : "admin";
  fActive.checked = edit ? row.active !== false : true;

  // scopes (only for admin)
  setScopesValues(
    edit
      ? row.scopes || { brand: true, proses: true, laporan: true, autowd: false, notifikasi: false }
      : { brand: true, proses: true, laporan: true, autowd: false, notifikasi: false }
  );
  showScopesUI(fRole.value);

  modal.classList.remove("hidden");
}
function closeModal() {
  modal.classList.add("hidden");
}

// THEME toggle
if (themeToggleBtn) {
  themeToggleBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    const root = document.documentElement;
    const isDarkNow = root.classList.toggle("dark");
    localStorage.setItem("theme", isDarkNow ? "dark" : "light");
  });
}

// DROPDOWNS
if (brandBtn) {
  brandBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    brandDropdown.classList.toggle("hidden");
    if (!userDropdown.classList.contains("hidden")) {
      userDropdown.classList.add("hidden");
    }
  });
}
if (userMenuBtn) {
  userMenuBtn.addEventListener("click", (e) => {
    e.stopPropagation();
    userDropdown.classList.toggle("hidden");
    if (!brandDropdown.classList.contains("hidden")) {
      brandDropdown.classList.add("hidden");
    }
  });
}
document.addEventListener("click", (e) => {
  if (!brandDropdown.classList.contains("hidden")) {
    const wrap = document.getElementById("brandPickerWrap");
    if (wrap && !wrap.contains(e.target)) brandDropdown.classList.add("hidden");
  }
  if (!userDropdown.classList.contains("hidden")) {
    if (!userMenuBtn.contains(e.target) && !userDropdown.contains(e.target)) {
      userDropdown.classList.add("hidden");
    }
  }
});

// SIDEBAR mobile
function openMobileSidebar() {
  mobileSidebar.classList.remove("-translate-x-full");
  sidebarOverlay.classList.remove("hidden");
}
function closeMobileSidebar() {
  mobileSidebar.classList.add("-translate-x-full");
  sidebarOverlay.classList.add("hidden");
}
if (hamburgerBtn) hamburgerBtn.addEventListener("click", (e) => { e.stopPropagation(); openMobileSidebar(); });
if (closeSidebarBtn) closeSidebarBtn.addEventListener("click", closeMobileSidebar);
if (sidebarOverlay) sidebarOverlay.addEventListener("click", closeMobileSidebar);

// LOGOUT
if (logoutBtn) logoutBtn.addEventListener("click", async (e) => { e.preventDefault(); await apiFetch("/api/logout", { method: "POST" }); window.location = "login.html"; });

// USERS TABLE helpers
function scopesBadges(s) {
  if (!s) return `<span class="text-slate-400">${T("accessAll")}</span>`;
  const chips = [];
  if (s.brand) chips.push(`<span class="px-2 py-[2px] rounded-full text-[11px] bg-sky-100 dark:bg-sky-900/40 text-sky-700 dark:text-sky-300">${T("scopeBrand")}</span>`);
  if (s.proses) chips.push(`<span class="px-2 py-[2px] rounded-full text-[11px] bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300">${T("scopeProses")}</span>`);
  if (s.laporan) chips.push(`<span class="px-2 py-[2px] rounded-full text-[11px] bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300">${T("scopeLaporan")}</span>`);
  if (s.autowd) chips.push(`<span class="px-2 py-[2px] rounded-full text-[11px] bg-violet-100 dark:bg-violet-900/40 text-violet-700 dark:text-violet-300">${T("scopeAutoWD")}</span>`);
  if (s.notifikasi) chips.push(`<span class="px-2 py-[2px] rounded-full text-[11px] bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300">${T("scopeNotifikasi")}</span>`);
  return chips.join(" ");
}

function rowHTML(u) {
  const badge =
    u.role === "superadmin"
      ? "bg-purple-100 text-purple-700 dark:bg-purple-950/40 dark:text-purple-300"
      : "bg-slate-100 text-slate-700 dark:bg-[#222] dark:text-slate-300";

  const st =
    u.active !== false
      ? `<span class="inline-flex items-center gap-1 text-emerald-600 text-[12px] font-medium"><span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span><span>${T("statusActive")}</span></span>`
      : `<span class="inline-flex items-center gap-1 text-slate-400 text-[12px] font-medium"><span class="w-1.5 h-1.5 rounded-full bg-slate-400"></span><span>${T("statusInactive")}</span></span>`;

  const accessCol = u.role === "superadmin" ? `<span class="text-slate-400">${T("accessDash")}</span>` : scopesBadges(u.scopes || DEFAULT_SCOPES);

  return `<tr class="hover:bg-slate-50 dark:hover:bg-[#161616] transition-colors">
    <td class="px-4 py-3 font-semibold text-slate-800 dark:text-slate-100 whitespace-nowrap">${u.username}</td>
    <td class="px-4 py-3">
      <span class="inline-flex items-center px-2.5 py-[3px] rounded-full text-[11px] font-medium ${badge}">
        <span class="w-1.5 h-1.5 rounded-full bg-current mr-1"></span>
        <span class="uppercase tracking-wide">${u.role}</span>
      </span>
    </td>
    <td class="px-4 py-3">${st}</td>
    <td class="px-4 py-3">${accessCol}</td>
    <td class="px-4 py-3 text-right whitespace-nowrap">
      <button data-edit="${u.username}" class="inline-flex items-center justify-center px-2.5 py-1.5 rounded-md border border-slate-300 dark:border-[#3f3f46] text-[12px] text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-[#252525] mr-2">${T("btnEdit")}</button>
      <button data-del="${u.username}" class="inline-flex items-center justify-center px-2.5 py-1.5 rounded-md text-[12px] bg-red-600 hover:bg-red-700 text-white shadow-sm">${T("btnDelete")}</button>
    </td>
  </tr>`;
}

function hookRowButtons(list) {
  tbody.querySelectorAll("[data-edit]").forEach((btn) => {
    const un = btn.getAttribute("data-edit");
    const row = list.find((x) => x.username === un);
    btn.addEventListener("click", () => openModal(true, row));
  });
  tbody.querySelectorAll("[data-del]").forEach((btn) => {
    const un = btn.getAttribute("data-del");
    btn.addEventListener("click", async () => {
      if (!confirm(T("confirmDelete").replace("{username}", un))) return;
      const res = await apiFetch(`/api/users/${encodeURIComponent(un)}`, { method: "DELETE" });
      if (res.ok) renderTable(res.users || []);
      else alert(res.error || T("alertDeleteFail"));
    });
  });
}

function renderTable(list) {
  if (!list || list.length === 0) {
    usersWrap.classList.add("hidden");
    emptyWrap.classList.remove("hidden");
    emptyWrap.textContent = T("emptyMessage");
    return;
  }
  emptyWrap.classList.add("hidden");
  usersWrap.classList.remove("hidden");
  tbody.innerHTML = list.map(rowHTML).join("");
  hookRowButtons(list);
}

// MODAL buttons
document.getElementById("btnCancel").addEventListener("click", closeModal);
document.getElementById("btnSave").addEventListener("click", async () => {
  ensureNotifikasiScopeControl();

  const payload = {
    username: editMode ? fUsername.value : (fUsername.value || "").trim(),
    role: fRole.value,
    active: fActive.checked,
  };
  if (!editMode || fPassword.value) payload.password = fPassword.value;

  // kirim scopes hanya bila role=admin
  if (fRole.value === "admin") {
    payload.scopes = {
      brand: !!fScopeBrand.checked,
      proses: !!fScopeProses.checked,
      laporan: !!fScopeLaporan.checked,
      autowd: !!fScopeAutoWD.checked,
      notifikasi: !!(fScopeNotifikasi ? fScopeNotifikasi.checked : false),
    };
  }

  const res = await apiFetch("/api/users", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(payload),
  });

  if (res.ok) {
    closeModal();
    renderTable(res.users || []);
  } else {
    alert(res.error || T("alertSaveFail"));
  }
});

// role change -> tampil/sembunyi scopes
fRole.addEventListener("change", () => {
  showScopesUI(fRole.value);
});

document.getElementById("newUserBtn").addEventListener("click", () => openModal(false, {}));

// Apply static texts on page
function applyI18nStatic() {
  // header dropdown texts
  const themeTextEl = document.getElementById("ddThemeText");
  if (themeTextEl) themeTextEl.textContent = T("dropdownTheme");
  const logoutTextEl = document.getElementById("ddLogoutText");
  if (logoutTextEl) logoutTextEl.textContent = T("dropdownLogout");

  // page head
  const pageTitleEl = document.getElementById("pageTitle");
  if (pageTitleEl) pageTitleEl.textContent = T("menuUsers");
  const pageDescEl = document.getElementById("pageDesc");
  if (pageDescEl) pageDescEl.textContent = T("usersDesc");

  // table head
  const thUsernameEl = document.getElementById("thUsername");
  if (thUsernameEl) thUsernameEl.textContent = T("thUsername");
  const thRoleEl = document.getElementById("thRole");
  if (thRoleEl) thRoleEl.textContent = T("thRole");
  const thStatusEl = document.getElementById("thStatus");
  if (thStatusEl) thStatusEl.textContent = T("thStatus");
  const thAccessEl = document.getElementById("thAccess");
  if (thAccessEl) thAccessEl.textContent = T("thAccess");
  const thActionsEl = document.getElementById("thActions");
  if (thActionsEl) thActionsEl.textContent = T("thActions");

  // actions bar
  const listCaptionEl = document.getElementById("listCaption");
  if (listCaptionEl) listCaptionEl.textContent = T("listCaption");
  const newUserBtnEl = document.getElementById("newUserBtn");
  if (newUserBtnEl) newUserBtnEl.textContent = T("btnNewUser");

  // modal labels/buttons
  const lblUsernameEl = document.getElementById("lblUsername");
  if (lblUsernameEl) lblUsernameEl.textContent = T("lblUsername");
  const lblPasswordEl = document.getElementById("lblPassword");
  if (lblPasswordEl) lblPasswordEl.textContent = T("lblPassword");
  const lblRoleEl = document.getElementById("lblRole");
  if (lblRoleEl) lblRoleEl.textContent = T("lblRole");
  const lblScopesEl = document.getElementById("lblScopes");
  if (lblScopesEl) lblScopesEl.textContent = T("lblScopes");
  const lblScopeBrandEl = document.getElementById("lblScopeBrand");
  if (lblScopeBrandEl) lblScopeBrandEl.textContent = T("scopeBrand");
  const lblScopeProsesEl = document.getElementById("lblScopeProses");
  if (lblScopeProsesEl) lblScopeProsesEl.textContent = T("scopeProses");
  const lblScopeLaporanEl = document.getElementById("lblScopeLaporan");
  if (lblScopeLaporanEl) lblScopeLaporanEl.textContent = T("scopeLaporan");
  const lblScopeAutoWDEl = document.getElementById("lblScopeAutoWD");
  if (lblScopeAutoWDEl) lblScopeAutoWDEl.textContent = T("scopeAutoWD");

  // ✅ NEW: label notifikasi (kalau sudah di-inject)
  const lblScopeNotifEl = document.getElementById("lblScopeNotifikasi");
  if (lblScopeNotifEl) lblScopeNotifEl.textContent = T("scopeNotifikasi");

  const lblActiveEl = document.getElementById("lblActive");
  if (lblActiveEl) lblActiveEl.textContent = T("lblActive");
  const btnCancelEl = document.getElementById("btnCancel");
  if (btnCancelEl) btnCancelEl.textContent = T("btnCancel");
  const btnSaveEl = document.getElementById("btnSave");
  if (btnSaveEl) btnSaveEl.textContent = T("btnSave");

  // only superadmin msg
  const onlySuperElLocal = document.getElementById("onlySuperadmin");
  if (onlySuperElLocal) onlySuperElLocal.textContent = T("onlySuperMsg");
}

// clock
function runClock() {
  updateSidebarClock();
  setInterval(updateSidebarClock, 1000);
}

async function init() {
  // session
  const sess = await requireSession();
  document.getElementById("topUser").textContent = sess.username || "admin";

  // brand visuals
  const badgeText = (brandMap[activeBrand] || brandMap["tiara"]).badge;
  document.getElementById("brandLabel").textContent = badgeText;
  document.getElementById("brandBadge").textContent = badgeText;

  const logoSrc = brandLogoMap[activeBrand] || brandLogoMap.tiara;
  const desktopLogo = document.getElementById("desktopBrandLogo");
  const mobileLogo = document.getElementById("mobileBrandLogo");
  if (desktopLogo) {
    desktopLogo.src = logoSrc;
    desktopLogo.alt = badgeText;
  }
  if (mobileLogo) {
    mobileLogo.src = logoSrc;
    mobileLogo.alt = badgeText;
  }

  // texts
  applyI18nStatic();

  // render sidebar (Users = active)
  const isSuperadmin = sess.role === "superadmin";

  // superadmin melihat SEMUA scope (termasuk notifikasi)
  const userScopes = isSuperadmin
    ? { brand: true, proses: true, laporan: true, autowd: true, notifikasi: true }
    : (sess.scopes || DEFAULT_SCOPES);

  document.getElementById("sideMenuDesktop").innerHTML = renderSidebar(activeBrand, "Desktop", isSuperadmin, userScopes);
  document.getElementById("sideMenuMobile").innerHTML = renderSidebar(activeBrand, "Mobile", isSuperadmin, userScopes);
  attachSidebarToggle("Desktop");
  attachSidebarToggle("Mobile");

  // start clock
  runClock();

  // gate by role
  if (!isSuperadmin) {
    onlySuperEl.classList.remove("hidden");
    return;
  }

  // show UI
  onlySuperEl.classList.add("hidden");
  actionsBar.classList.remove("hidden");

  // load users
  const res = await apiFetch("/api/users");
  if (res.ok) renderTable(res.users || []);
  else alert(res.error || T("alertSaveFail"));
}

// Run
init();