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

// ===============================
// I18N (identik subset global.html)
// ===============================
const i18nMap = {
  id: {
    dropdownTheme: "Tema",
    dropdownLanguage: "Bahasa",
    dropdownLogout: "Keluar",
    pageTitle: "Setting Auto Withdraw",
    brandDescPrefix: "Kelola rekening Auto WD untuk brand ",
    menuDashboard: "Dashboard",
    menuGlobalSheets: "Global Sheets",
    menuBrandMeta: "Brand Meta",
    menuProfiles: "Profiles",
    submenuProfilesBank: "Edit Bank",
    submenuProfilesEwallet: "Edit Ewallet",
    submenuProfilesPulsa: "Edit Pulsa",
    submenuProfilesWD: "Edit Withdraw",
    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",
  },
  en: {
    dropdownTheme: "Theme",
    dropdownLanguage: "Language",
    dropdownLogout: "Logout",
    pageTitle: "Auto Withdraw Settings",
    brandDescPrefix: "Manage Auto WD accounts for brand ",
    menuDashboard: "Dashboard",
    menuGlobalSheets: "Global Sheets",
    menuBrandMeta: "Brand Meta",
    menuProfiles: "Profiles",
    submenuProfilesBank: "Edit Bank",
    submenuProfilesEwallet: "Edit Ewallet",
    submenuProfilesPulsa: "Edit Phone Credit",
    submenuProfilesWD: "Edit Withdraw",
    menuProses: "Proses",
    depBank: "Record Bank",
    depEwallet: "Record Ewallet",
    depPulsa: "Record Phone Credit",
    depWD: "Record Withdraw",

    // ✅ NEW: Notifikasi
    menuNotifikasi: "Notifications",
    notifBank: "Bank",
    notifEwallet: "E-wallet",

    menuLaporan: "Reports",
    repPendingan: "Pending",
    repMistake: "Mistakes",
    menuAutoWD: "Auto Withdraw",
    awdWithdraw: "Withdraw",
    menuAdmin: "Admin",
    menuUsers: "Users",
  },
  km: {
    dropdownTheme: "Theme",
    dropdownLanguage: "ភាសា",
    dropdownLogout: "ចេញ",
    pageTitle: "ការកំណត់ Auto Withdraw",
    brandDescPrefix: "គ្រប់គ្រងគណនី Auto WD សម្រាប់ម៉ាក ",
    menuDashboard: "Dashboard",
    menuGlobalSheets: "Global Sheets",
    menuBrandMeta: "Brand Meta",
    menuProfiles: "Profiles",
    submenuProfilesBank: "កែប្រែ Bank",
    submenuProfilesEwallet: "កែប្រែ Ewallet",
    submenuProfilesPulsa: "កែប្រែ Pulsa",
    submenuProfilesWD: "កែប្រែ Withdraw",
    menuProses: "Proses",
    depBank: "Catat Bank",
    depEwallet: "Catat Ewallet",
    depPulsa: "Catat Pulsa",
    depWD: "Catat Withdraw",

    // ✅ NEW: Notifikasi
    menuNotifikasi: "ការជូនដំណឹង",
    notifBank: "Bank",
    notifEwallet: "Ewallet",

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

const activeBrand = (getQueryParam("brand") || "tiara").toLowerCase();
const currentLang = (localStorage.getItem("lang") || "id").toLowerCase();
const getT = (k)=> (i18nMap[currentLang]?.[k] ?? i18nMap.id[k] ?? k);

// ===============================
// ICONS & SIDEBAR (identik pola global.html)
// ===============================
function iconSVG(name, highlight=false){
  const cls = highlight ? "text-blue-500 dark:text-blue-400" : "text-slate-500 dark:text-slate-400";
  if(name==="home")return `<span class="${cls}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path d="M3 12L12 3l9 9"/><path d="M9 21V12h6v9"/></svg></span>`;
  if(name==="sheets")return `<span class="${cls}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="9" y1="4" x2="9" y2="22"/></svg></span>`;
  if(name==="brand") return `<span class="${cls}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" 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></span>`;
  if(name==="profile")return `<span class="${cls}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" 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></span>`;
  if(name==="chat")   return `<span class="${cls}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" 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></span>`;
  if(name==="users")  return `<span class="${cls}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" 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></span>`;
  if(name==="report") return `<span class="${cls}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" 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></span>`;
  if(name==="zap")    return `<span class="${cls}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><polyline points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg></span>`;

  // ✅ NEW: icon Notifikasi
  if(name==="bank")   return `<span class="${cls}"><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></span>`;
  if(name==="wallet") return `<span class="${cls}"><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></span>`;

  return "";
}

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] leading-tight p-3">
        <div class="grid grid-cols-[max-content_1ch_1fr] items-baseline gap-x-2 gap-y-1">
          <div class="text-slate-500 dark:text-slate-400 font-medium">Tanggal</div>
          <div class="text-slate-500 dark:text-slate-400">:</div>
          <div id="sidebarDate${prefix}" class="font-semibold">-</div>
          <div class="text-slate-500 dark:text-slate-400 font-medium">Waktu</div>
          <div class="text-slate-500 dark:text-slate-400">:</div>
          <div id="sidebarTime${prefix}" class="font-semibold">-</div>
        </div>
      </div>
    </div>`;
}

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:"submenuProfilesBank",    channel:"bank" },
            { textKey:"submenuProfilesEwallet", channel:"ewallet" },
            { textKey:"submenuProfilesPulsa",   channel:"pulsa" },
            { textKey:"submenuProfilesWD",      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", scope:"users",
        items: [{ textKey:"menuUsers", href:`users.html?brand=tiara`, icon:"users", active:false }]},
    ],
  },
  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:"submenuProfilesBank",    channel:"bank" },
            { textKey:"submenuProfilesEwallet", channel:"ewallet" },
            { textKey:"submenuProfilesPulsa",   channel:"pulsa" },
            { textKey:"submenuProfilesWD",      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", scope:"users",
        items: [{ textKey:"menuUsers", href:`users.html?brand=tts`, icon:"users", active:false }]},
    ],
  },
  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:"submenuProfilesBank",    channel:"bank" },
            { textKey:"submenuProfilesEwallet", channel:"ewallet" },
            { textKey:"submenuProfilesPulsa",   channel:"pulsa" },
            { textKey:"submenuProfilesWD",      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", scope:"users",
        items: [{ textKey:"menuUsers", href:`users.html?brand=ttm`, icon:"users", active:false }]},
    ],
  },
};

const brandLogoMap = {
  tiara: "assets/img/tiaratoto.png",
  tts:  "assets/img/totosakti.png",
  ttm:  "assets/img/totomantap.png", // pastikan file ini ada
};

// ✅ tambah notifikasi:false
const DEFAULT_SCOPES = { brand:true, proses:true, laporan:true, autowd:false, users:false, notifikasi:false };

function renderSidebar(brandKey, prefix, activeChannel, opts = {}){
  const isSuperadmin = !!opts.isSuperadmin;
  const scopes       = opts.scopes || DEFAULT_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 allow = isSuperadmin || !section.scope || (scopes && scopes[section.scope]);
    if(!allow) return;
    const sectionTitle = section.labelKey ? getT(section.labelKey).toUpperCase() : section.brandBadge;
    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">`;
    section.items.forEach(item=>{
      if(item.icon==="profile"){
        const btnCls=parentNormalCls;
        html+=`
          <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>${getT(item.textKey)}</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" stroke-linecap="round" stroke-linejoin="round" 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">
              ${(item.submenu||[]).map(s=>{
                const activeSub = (s.channel===activeChannel);
                const subCls = activeSub?parentActiveCls:parentNormalCls;
                return `<li><a href="profile-edit.html?brand=${brandKey}&channel=${s.channel}" class="flex items-center gap-2 px-3 py-2 rounded-md font-medium border text-[12px] leading-tight ${subCls}"><span class="w-2 h-2 rounded-full bg-current"></span><span>${getT(s.textKey)}</span></a></li>`;
              }).join("")}
            </ul>
          </li>`;
      }else{
        const linkCls = item.active?parentActiveCls:parentNormalCls;
        html+=`<li><a href="${item.href}" class="flex items-center gap-2 px-3 py-2 rounded-md font-medium border ${linkCls}">${iconSVG(item.icon,item.active)}<span>${getT(item.textKey)}</span></a></li>`;
      }
    });
    html += `</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 p=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);
  let d="",m="",y="",h="",mi="",s=""; p.forEach(x=>{if(x.type==="day")d=x.value;if(x.type==="month")m=x.value;if(x.type==="year")y=x.value;if(x.type==="hour")h=x.value;if(x.type==="minute")mi=x.value;if(x.type==="second")s=x.value;});
  const mon=["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des"][parseInt(m,10)-1]||m;
  const tanggal=`${weekdayId}, ${d} ${mon} ${y}`, waktu=`${h}:${mi}:${s}`;
  ["Desktop","Mobile"].forEach(pref=>{
    const dd=document.getElementById("sidebarDate"+pref);
    const tt=document.getElementById("sidebarTime"+pref);
    if(dd) dd.textContent=tanggal; if(tt) tt.textContent=waktu;
  });
}

// ===============================
// STATE & DOM
// ===============================
const BRAND_BADGE = { tiara:"TIARATOTO", tts:"TOTOSAKTI", ttm:"TOTOMANTAP" }[activeBrand] || "BRAND";
const els = {
  sideDesktop: document.getElementById("sideMenuDesktop"),
  sideMobile:  document.getElementById("sideMenuMobile"),
  desktopLogo: document.getElementById("desktopBrandLogo"),
  mobileLogo:  document.getElementById("mobileBrandLogo"),
  hamburgerBtn: document.getElementById("hamburgerBtn"),
  mobileSidebar: document.getElementById("mobileSidebar"),
  sidebarOverlay: document.getElementById("sidebarOverlay"),
  closeSidebarBtn: document.getElementById("closeSidebarBtn"),
  brandBtn: document.getElementById("brandBtn"),
  brandDropdown: document.getElementById("brandDropdown"),
  userBtn: document.getElementById("userMenuBtn"),
  userDropdown: document.getElementById("userDropdown"),
  themeToggleBtn: document.getElementById("themeToggleBtn"),
  logoutBtn: document.getElementById("logoutBtn"),
  topUser: document.getElementById("topUser"),
  brandLabel: document.getElementById("brandLabel"),
  brandBadge: document.getElementById("brandBadge"),
  pageDesc: document.getElementById("pageDesc"),
  langBtn: document.getElementById("langBtn"),
  langOptions: document.getElementById("langOptions"),
  // form
  fBank: document.getElementById("fBank"),
  fNama: document.getElementById("fNama"),
  fPass: document.getElementById("fPass"),
  fDevice: document.getElementById("fDevice"),
  fSheet: document.getElementById("fSheet"),
  fStatus: document.getElementById("fStatus"),
  btnSave: document.getElementById("btnSave"),
  btnClear: document.getElementById("btnClear"),
  formAwd: document.getElementById("formAwd"),
  toggleFPwd: document.getElementById("toggleFPwd"),
  // table
  tbody: document.getElementById("banksRows"),
  // modal
  editOverlay: document.getElementById("editOverlay"),
  modalCloseBtn: document.getElementById("modalCloseBtn"),
  modalCancelBtn: document.getElementById("modalCancelBtn"),
  modalSaveBtn: document.getElementById("modalSaveBtn"),
  eId: document.getElementById("eId"),
  eBank: document.getElementById("eBank"),
  eNama: document.getElementById("eNama"),
  ePass: document.getElementById("ePass"),
  eDevice: document.getElementById("eDevice"),
  eSheet: document.getElementById("eSheet"),
  eStatus: document.getElementById("eStatus"),
  toggleEPwd: document.getElementById("toggleEPwd"),
  ePassNote: document.getElementById("ePassNote"),
  // flash
  flashBox: document.getElementById("flashBox"),
};

const state = {
  rows: [],
  saving: false,
  deleting: false,
  allowedSheets: [],
};

// ===============================
// Flash helper
// ===============================
function flash(type, msg) {
  const cls = type === "err"
    ? "bg-red-50 border-red-300 text-red-700 dark:bg-red-900/30 dark:border-red-700 dark:text-red-300"
    : "bg-emerald-50 border-emerald-300 text-emerald-700 dark:bg-emerald-900/30 dark:border-emerald-700 dark:text-emerald-300";
  els.flashBox.innerHTML = `
    <div class="mb-4 rounded-md border px-3 py-2 text-[13px] ${cls}">
      ${msg}
    </div>`;
  setTimeout(()=>{ els.flashBox.innerHTML = ""; }, 3000);
}

// ===============================
// API helpers
// ===============================
const BANKS = ["BCA","BNI","BRI","MANDIRI"];

async function loadAllowedSheets(){
  try{
    const res = await apiFetch(`/api/awd/profile-sheets?brand=${encodeURIComponent(activeBrand)}`);
    const arr = Array.isArray(res?.allowedSheets) ? res.allowedSheets : [];
    state.allowedSheets = arr;
    if (!arr.length) {
      flash("err", "Allowed Sheets kosong. Set dulu via PUT /api/awd/profile-sheets.");
    }
    populateSheetSelect(els.fSheet, arr);
    populateSheetSelect(els.eSheet, arr);
  }catch(e){
    console.error("loadAllowedSheets error:", e);
    state.allowedSheets = [];
    populateSheetSelect(els.fSheet, []);
    populateSheetSelect(els.eSheet, []);
  }
}
function populateSheetSelect(selectEl, list){
  if(!selectEl) return;
  const cur = selectEl.value;
  selectEl.innerHTML = `<option value="">— pilih sheet —</option>` + (list||[]).map(s=>`<option value="${s}">${s}</option>`).join("");
  if (list && list.includes(cur)) selectEl.value = cur;
}

async function fetchAccountSecret(id){
  try{
    const r = await apiFetch(`/api/awd/accounts/${encodeURIComponent(id)}/secret`);
    return r || {};
  }catch(e){
    return { error: String(e?.message||e) };
  }
}

async function loadAccounts(){
  try {
    const res = await apiFetch(`/api/awd/accounts?brand=${encodeURIComponent(activeBrand)}`);
    state.rows = Array.isArray(res?.accounts) ? res.accounts : [];
    renderTable();
  } catch (e) {
    console.error("AWD/accounts error:", e);
    flash("err", "Gagal load data: " + (e?.message || e));
  }
}

async function createAccount(payload){
  return await apiFetch(`/api/awd/accounts`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(payload)
  });
}

async function updateAccount(id, payload){
  return await apiFetch(`/api/awd/accounts/${encodeURIComponent(id)}`, {
    method: "PUT",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(payload)
  });
}

async function deleteAccount(id){
  return await apiFetch(`/api/awd/accounts/${encodeURIComponent(id)}`, { method: "DELETE" });
}

// ===============================
// UI helpers
// ===============================
function statusBadge(st){
  const on = st==="online";
  return `<span class="px-2 py-[2px] rounded-full text-[11px] font-semibold ${on?'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300':'bg-slate-100 text-slate-700 dark:bg-slate-800/60 dark:text-slate-300'}">${on?'Online':'Offline'}</span>`;
}

function renderTable(){
  if (!state.rows.length){
    els.tbody.innerHTML = `
      <tr class="border-b border-slate-200 dark:border-[#2a2a2a] odd:bg-white even:bg-slate-50 dark:odd:bg-[#1e1e1e] dark:even:bg-[#1a1a1a]">
        <td colspan="5" class="text-center text-slate-500 dark:text-slate-400 py-6 text-[13px] bg-white dark:bg-[#1e1e1e]">Belum ada data.</td>
      </tr>`;
    return;
  }
  els.tbody.innerHTML = state.rows.map(r=>`
    <tr class="border-b border-slate-200 dark:border-[#2a2a2a] odd:bg-white even:bg-slate-50 dark:odd:bg-[#1e1e1e] dark:even:bg-[#1a1a1a] align-top">
      <td class="p-3">${r.bank}</td>
      <td class="p-3">${r.name}</td>
      <td class="p-3">${r.sheet || ""}</td>
      <td class="p-3">${statusBadge(r.status)}</td>
      <td class="p-3">
        <div class="flex gap-2">
          <button data-edit="${r.id}" class="p-1 rounded-md bg-blue-50 dark:bg-blue-900/30 border border-blue-300 dark:border-blue-700 text-blue-600 dark:text-blue-400" title="Edit" aria-label="Edit">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>
          </button>
          <button data-del="${r.id}" class="p-1 rounded-md bg-red-50 dark:bg-red-900/30 border border-red-300 dark:border-red-700 text-red-600 dark:text-red-400" title="Hapus" aria-label="Hapus">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>
          </button>
        </div>
      </td>
    </tr>`).join("");

  els.tbody.querySelectorAll("button[data-edit]").forEach(b=>{
    b.addEventListener("click", ()=>openEdit(b.getAttribute("data-edit")));
  });
  els.tbody.querySelectorAll("button[data-del]").forEach(b=>{
    b.addEventListener("click", async ()=>{
      if (state.deleting) return;
      const id=b.getAttribute("data-del");
      if (!confirm("Hapus data ini?")) return;
      try{
        state.deleting = true;
        await deleteAccount(id);
        await loadAccounts();
        flash("ok", "Data dihapus.");
      }catch(e){
        flash("err", "Gagal menghapus.");
      }finally{
        state.deleting = false;
      }
    });
  });
}

function clearForm(){
  els.fBank.value="BCA";
  els.fNama.value="";
  els.fPass.value="";
  els.fDevice.value="";
  els.fSheet.value="";
  els.fStatus.value="online";
}

function normalizeNom(text){ return (text||"").trim(); }

// ===============================
// SAVE (Create)
// ===============================
async function saveForm(e){
  e.preventDefault();
  if (state.saving) return;
  const bank = els.fBank.value;
  const nama = normalizeNom(els.fNama.value).toUpperCase();
  const pass = normalizeNom(els.fPass.value); // case-sensitive
  const device = normalizeNom(els.fDevice.value);
  const sheet = normalizeNom(els.fSheet.value);
  const status = els.fStatus.value;

  // Validasi minimal
  if (!BANKS.includes(bank)) { flash("err", "Bank tidak valid."); return; }
  if (!nama) { flash("err", "Nama rekening wajib diisi."); return; }
  if (!device) { flash("err", "ID Device wajib diisi."); return; }
  if (!["online","offline"].includes(status)) { flash("err", "Status tidak valid."); return; }
  if (!sheet) { flash("err", "Google Sheet wajib dipilih."); return; }

  // Password TF: alfanumerik 4–32 (BNI boleh huruf+angka, case-sensitive)
  if (pass && !/^[A-Za-z0-9]{4,32}$/.test(pass)) {
    flash("err", "Password transfer harus 4–32 karakter (huruf/angka, case-sensitive).");
    return;
  }

  const payload = {
    brand: activeBrand,
    bank,
    name: nama,
    deviceId: device,
    sheet,
    status,
    password: pass || null
  };

  try{
    state.saving = true;
    await createAccount(payload);
    await loadAccounts();
    clearForm();
    flash("ok","Disimpan.");
    } catch (e) {
      const err = (e && (e.data?.error || e.error || e.message)) || "";
      if (String(err).includes("already_exists")) {
        flash("err", "Duplikat: kombinasi Brand+Bank+Nama sudah ada.");
      } else if (String(err).includes("bank invalid")) {
        flash("err", "Bank tidak dikenali server.");
      } else if (String(err).includes("status invalid")) {
        flash("err", "Status tidak valid.");
      } else {
        flash("err", "Gagal menyimpan.");
      }
    } finally {
    state.saving = false;
  }
}

// ===============================
// EDIT modal
// ===============================
async function openEdit(id){
  const r = state.rows.find(x=>x.id===id);
  if(!r) return;
  els.eId.value = r.id;
  els.eBank.value = r.bank;
  els.eNama.value = r.name;
  els.ePass.value = "";            // akan diisi setelah fetch secret
  els.eDevice.value = r.deviceId || "";
  // set options dulu, lalu set value
  populateSheetSelect(els.eSheet, state.allowedSheets);
  els.eSheet.value = r.sheet || "";
  els.eStatus.value = r.status || "online";
  els.ePassNote.classList.add("hidden");
  els.editOverlay.classList.remove("hidden");

  // ambil password terenkripsi (dekripsi di server) → prefill (masked)
  const sec = await fetchAccountSecret(id);
  const hasPlain = sec && typeof sec.password === "string" && sec.password !== null;
  if (hasPlain) {
    els.ePass.value = sec.password; // tetap masked
  } else {
    els.ePass.value = "";
    els.ePassNote.classList.remove("hidden"); // tampilkan note saat ok:false / no key / null
  }
}
function closeEdit(){ els.editOverlay.classList.add("hidden"); }

async function saveEdit(){
  const id = els.eId.value;
  const bank = els.eBank.value;
  const nama = normalizeNom(els.eNama.value).toUpperCase();
  const pass = normalizeNom(els.ePass.value); // optional update (case-sensitive)
  const device = normalizeNom(els.eDevice.value);
  const sheet = normalizeNom(els.eSheet.value);
  const status = els.eStatus.value;

  if (!BANKS.includes(bank)) { flash("err", "Bank tidak valid."); return; }
  if (!nama) { flash("err", "Nama rekening wajib diisi."); return; }
  if (!device) { flash("err", "ID Device wajib diisi."); return; }
  if (!["online","offline"].includes(status)) { flash("err", "Status tidak valid."); return; }
  if (!sheet) { flash("err", "Google Sheet wajib dipilih."); return; }
  if (pass && !/^[A-Za-z0-9]{4,32}$/.test(pass)) { flash("err", "Password transfer harus 4–32 karakter (huruf/angka)."); return; }

  const payload = { bank, name: nama, deviceId: device, sheet, status };
  // kirim password hanya jika user isi (boleh sama, server akan overwrite)
  if (pass) payload.password = pass;

  try{
    await updateAccount(id, payload);
    await loadAccounts();
    closeEdit();
    flash("ok", "Perubahan disimpan.");
    } catch (e) {
      const err = (e && (e.data?.error || e.error || e.message)) || "";
      if (String(err).includes("already_exists")) {
        flash("err", "Duplikat: kombinasi Brand+Bank+Nama sudah ada.");
      } else {
        flash("err", "Gagal menyimpan perubahan.");
      }
    }
}

// ===============================
// Password show/hide
// ===============================
function wirePasswordToggle(inputEl, btnEl){
  if(!inputEl || !btnEl) return;
  const eye     = btnEl.querySelector("[data-eye]");
  const eyeOff  = btnEl.querySelector("[data-eyeoff]");
  const setUI = (show)=>{
    inputEl.type = show ? "text" : "password";
    btnEl.setAttribute("aria-pressed", String(show));
    if(eye) eye.classList.toggle("hidden", show);
    if(eyeOff) eyeOff.classList.toggle("hidden", !show);
  };
  btnEl.addEventListener("click", ()=> setUI(inputEl.type === "password"));
}

// ===============================
// Header & dropdowns (identik global.html)
// ===============================
function openMobile(){ els.mobileSidebar.classList.remove("-translate-x-full"); els.sidebarOverlay.classList.remove("hidden"); }
function closeMobile(){ els.mobileSidebar.classList.add("-translate-x-full"); els.sidebarOverlay.classList.add("hidden"); }

// ===============================
// INIT
// ===============================
(async function init(){
  const session = await requireSession();
  const isSuperadmin = (session?.role === "superadmin");
  const scopesArr = Array.isArray(session?.scopes)
    ? session.scopes.map(s => String(s).toLowerCase())
    : Array.isArray(session?.permissions)
      ? session.permissions.map(s => String(s).toLowerCase())
      : [];
  const hasScope = (k) => isSuperadmin || scopesArr.includes(String(k).toLowerCase());

  if (!hasScope('auto_wd')) {
    window.location = `index.html?brand=${activeBrand}`;
    return;
  }

  // header, brand logo, i18n
  const logo = brandLogoMap[activeBrand] || brandLogoMap.tiara;
  document.getElementById("desktopBrandLogo").src = logo;
  document.getElementById("mobileBrandLogo").src  = logo;
  document.getElementById("brandLabel").textContent = BRAND_BADGE;
  document.getElementById("brandBadge").textContent = BRAND_BADGE;
  document.getElementById("pageTitle").textContent = getT("pageTitle");
  document.getElementById("pageDesc").textContent = getT("brandDescPrefix") + brandDisplayName(activeBrand) + ".";
  document.getElementById("topUser").textContent = session?.username || "admin";
  document.getElementById("btnBackToWD").href = `withdraw-awd.html?brand=${activeBrand}`;

  const scopesObj = {
    brand:  hasScope('brand'),
    proses: hasScope('proses'),
    laporan:hasScope('laporan'),
    autowd: hasScope('auto_wd'),
    users:  hasScope('users'),
    // ✅ NEW
    notifikasi: hasScope('notifikasi'),
  };

  // sidebar & header interactions
  document.getElementById("sideMenuDesktop").innerHTML = renderSidebar(activeBrand, "Desktop", null, { isSuperadmin, scopes: scopesObj });
  document.getElementById("sideMenuMobile").innerHTML  = renderSidebar(activeBrand, "Mobile",  null, { isSuperadmin, scopes: scopesObj });
  document.querySelectorAll('#sideMenuDesktop a, #sideMenuMobile a').forEach(a=>{
    if (a.getAttribute('href')?.startsWith(`withdraw-awd.html?brand=${activeBrand}`)) {
      a.classList.add("bg-blue-50","text-blue-600","border-blue-200","dark:bg-blue-950/40","dark:text-blue-400","dark:border-blue-800");
    }
  });
  attachSidebarToggle("Desktop"); attachSidebarToggle("Mobile");
  updateSidebarClock(); setInterval(updateSidebarClock,1000);

  const brandBtn = document.getElementById("brandBtn");
  const brandDropdown = document.getElementById("brandDropdown");
  const userBtn = document.getElementById("userMenuBtn");
  const userDropdown = document.getElementById("userDropdown");
  const themeToggleBtn = document.getElementById("themeToggleBtn");
  const langBtn = document.getElementById("langBtn");
  const langOptions = document.getElementById("langOptions");
  const logoutBtn = document.getElementById("logoutBtn");
  const hamburgerBtn = document.getElementById("hamburgerBtn");
  const closeSidebarBtn = document.getElementById("closeSidebarBtn");
  const sidebarOverlay = document.getElementById("sidebarOverlay");

  brandBtn.addEventListener("click",(e)=>{ e.stopPropagation(); brandDropdown.classList.toggle("hidden"); if(!userDropdown.classList.contains("hidden")) userDropdown.classList.add("hidden"); });
  userBtn.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.contains(e.target)) brandDropdown.classList.add("hidden");
    }
    if(!userDropdown.classList.contains("hidden") && !userBtn.contains(e.target) && !userDropdown.contains(e.target)){
      userDropdown.classList.add("hidden");
      langOptions.classList.add("hidden");
    }
  });
  themeToggleBtn?.addEventListener("click", ()=>{
    const root=document.documentElement; const dark=root.classList.toggle("dark");
    localStorage.setItem("theme", dark?"dark":"light");
  });
  langBtn?.addEventListener("click",(e)=>{ e.stopPropagation(); langOptions.classList.toggle("hidden"); });
  langOptions?.querySelectorAll("button[data-lang]").forEach(btn=>{
    btn.addEventListener("click", ()=>{
      localStorage.setItem("lang", btn.getAttribute("data-lang"));
      window.location.reload();
    });
  });
  logoutBtn?.addEventListener("click", async ()=>{
    try{ await apiFetch("/api/logout",{method:"POST"});}catch{}
    window.location="login.html";
  });

  hamburgerBtn.addEventListener("click",(e)=>{ e.stopPropagation(); openMobile(); });
  closeSidebarBtn.addEventListener("click", closeMobile);
  sidebarOverlay.addEventListener("click", closeMobile);

  // load dropdown sheets dulu, baru wire form
  await loadAllowedSheets();

  // form actions
  document.getElementById("formAwd").addEventListener("submit", saveForm);
  document.getElementById("btnClear").addEventListener("click", clearForm);
  clearForm();

  // modal
  document.getElementById("modalCloseBtn").addEventListener("click", closeEdit);
  document.getElementById("modalCancelBtn").addEventListener("click", closeEdit);
  document.getElementById("modalSaveBtn").addEventListener("click", saveEdit);

  // password toggles
  wirePasswordToggle(els.fPass, els.toggleFPwd);
  wirePasswordToggle(els.ePass, els.toggleEPwd);

  // load data dari server
  await loadAccounts();
})();