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

/* ===== I18N singkat ===== */
const i18n = {
  id: {
    pageTitle:"Auto Withdraw", pageDescPrefix:"Form input Auto WD untuk brand ", ddTheme:"Tema", ddLanguage:"Bahasa", ddLogout:"Keluar",
    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",
    sheetBankLabel:"Bank", sheetLabel:"Bank aktif", sending:"Mengirim...", hello:"Halo",
    forbiddenTitle:"Akses Ditolak", forbiddenDesc:"Halaman ini memerlukan scope: auto_wd.", goHome:"Ke Dashboard",
  },
  en: {
    pageTitle:"Auto Withdraw", pageDescPrefix:"Auto WD input form for brand ", ddTheme:"Theme", ddLanguage:"Language", ddLogout:"Logout",
    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",
    sheetBankLabel:"Active bank", sheetLabel:"Active bank", sending:"Sending...", hello:"Hello",
    forbiddenTitle:"Access Denied", forbiddenDesc:"This page requires scope: auto_wd.", goHome:"Go to Dashboard",
  },
  km: {
    pageTitle:"Auto Withdraw", pageDescPrefix:"ទម្រង់បញ្ចូល Auto WD សម្រាប់ម៉ាក ", ddTheme:"Theme", ddLanguage:"ភាសា", ddLogout:"ចេញ",
    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",
    sheetBankLabel:"ធនាគារ", sheetLabel:"ធនាគារកម្មវិធី", sending:"កំពុងផ្ញើ...", hello:"សួស្តី",
    forbiddenTitle:"ត្រូវបានបដិសេធ", forbiddenDesc:"ទំព័រនេះទាមទារ scope: auto_wd.", goHome:"ទៅ Dashboard",
  }
};
const lang = (localStorage.getItem("lang") || "id").toLowerCase();
const T = (k)=> (i18n[lang] && i18n[lang][k]) || i18n.id[k] || k;

/* ===== BRAND / STATE ===== */
const activeBrand = (getQueryParam("brand") || "tiara").toLowerCase();
const REQUIRED_SCOPE_PAGE = "auto_wd";
const brandLogoMap  = {
  tiara: "assets/img/tiaratoto.png",
  tts:  "assets/img/totosakti.png",
  ttm:  "assets/img/totomantap.png", // pastikan file ini ada
};
const brandBadgeMap = {
  tiara:"TIARATOTO",
  tts:"TOTOSAKTI",
  ttm:"TOTOMANTAP",
};
const brandBadgeText= brandBadgeMap[activeBrand] || "BRAND";
const BANKS = new Set(["BCA","BNI","BRI","MANDIRI","DANA","OVO","GOPAY","SEABANK","LINKAJA"]);

/* ===== Utils ===== */
function escapeHTML(s){ return (s||"").replace(/[&<>"']/g, c=>({ "&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#39;" }[c])); }
function wibStamp(ts=null){
  const d = ts ? new Date(ts) : new Date();
  return new Intl.DateTimeFormat('id-ID',{ timeZone:'Asia/Jakarta', hour:'2-digit', minute:'2-digit', second:'2-digit', hour12:false }).format(d);
}
function autoGrow(el){ const MIN=120, MAX=320; el.style.height='auto'; const h=Math.max(Math.min(el.scrollHeight,MAX),MIN); el.style.height=h+'px'; el.style.overflowY=(el.scrollHeight>MAX)?'auto':'hidden'; }
function looksExactly8Lines(text){ return (text||"").split("\n").map(s=>s.trim()).filter(Boolean).length === 8; }

/* ===== DOM ===== */
const els = {
  desktopLogo: document.getElementById("desktopBrandLogo"),
  mobileLogo:  document.getElementById("mobileBrandLogo"),
  sideMenuDesktop: document.getElementById("sideMenuDesktop"),
  sideMenuMobile:  document.getElementById("sideMenuMobile"),
  brandLabel: document.getElementById("brandLabel"),
  brandDropdown: document.getElementById("brandDropdown"),
  brandBtn: document.getElementById("brandBtn"),
  userBtn: document.getElementById("userMenuBtn"),
  userDropdown: document.getElementById("userDropdown"),
  topUser: document.getElementById("topUser"),
  themeToggleBtn: document.getElementById("themeToggleBtn"),
  langBtn: document.getElementById("langBtn"),
  langOptions: document.getElementById("langOptions"),
  currentLangFlag: document.getElementById("currentLangFlag"),
  ddThemeText: document.getElementById("ddThemeText"),
  ddLangText: document.getElementById("ddLangText"),
  ddLogoutText: document.getElementById("ddLogoutText"),
  logoutBtn: document.getElementById("logoutBtn"),
  hamburgerBtn: document.getElementById("hamburgerBtn"),
  mobileSidebar: document.getElementById("mobileSidebar"),
  closeSidebarBtn: document.getElementById("closeSidebarBtn"),
  sidebarOverlay: document.getElementById("sidebarOverlay"),
  pageTitle: document.getElementById("pageTitle"),
  brandBadge: document.getElementById("brandBadge"),
  pageDesc: document.getElementById("pageDesc"),

  // form
  sheetSelect: document.getElementById("sheetSelect"),
  layananSelect: document.getElementById("layananSelect"),
  sheetStatus: document.getElementById("sheetStatus"), // hidden

  // card content
  chatInput: document.getElementById("chatInput"),
  parseHint: document.getElementById("parseHint"),
  composerNote: document.getElementById("composerNote"),
  sendBtn: document.getElementById("sendBtn"),    // dipakai untuk "Simpan"
  btnCancel: document.getElementById("btnCancel"),
  flashBox: document.getElementById("flashBox"),
  greetBox: document.getElementById("greetBox"),

  // dummy elemen agar logic lama gak error (tetap dipetakan)
  chatList: document.getElementById("chatList"),
  chatScroll: document.getElementById("chatScroll"),
  pasteBtn: document.getElementById("pasteBtn"),
  clearHistory: document.getElementById("clearHistory"),
  refreshSheets: document.getElementById("refreshSheets"),

  // modal
  confirmModal: document.getElementById("confirmModal"),
  cmText: document.getElementById("cmText"),
  cmOk: document.getElementById("cmOk"),
  cmCancel: document.getElementById("cmCancel"),
  cmCheck: document.getElementById("cmCheck"),
  cmX: document.getElementById("cmX"),

  forbiddenOverlay: document.getElementById("forbiddenOverlay"),
  brandPickerWrap: document.getElementById("brandPickerWrap"),
};

/* ===== Flash helper (gantikan bubble bot) ===== */
function flashHtml(html, type="ok"){
  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-3 rounded-md border px-3 py-2 text-[13px]">${html}</div>`;
  const box = els.flashBox.firstElementChild;
  if (box) box.classList.add(...cls.split(" "));
  setTimeout(()=>{ els.flashBox.innerHTML=""; }, 3000);
}

/* ===== “Bubble” kompatibel (redirect ke flash) ===== */
function renderUserBubble(){ /* tak dipakai lagi, dibiarkan no-op */ }
function renderBotBubble(html){ flashHtml(html, html.includes("❌")?"err":"ok"); }

/* ===== Sidebar builder (sama seperti versi sebelumnya) ===== */
function iconSVG(name, hl=false){
  const cls = hl ? "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: {
    sections: [
      { labelKey:"menuDashboard", items:[{ textKey:"menuDashboard", href:`index.html?brand=tiara`, icon:"home" }]},
      { labelKey:null, items:[
        { textKey:"menuGlobalSheets", href:`global.html?brand=tiara`, icon:"sheets" },
        { textKey:"menuBrandMeta",   href:`brand.html?brand=tiara`,  icon:"brand"  },
        { textKey:"menuProfiles",    href:`profile-edit.html?brand=tiara&channel=bank`, icon:"profile" },
      ]},
      { labelKey:"menuProses", items:[
        { textKey:"depBank",    href:`bank.html?brand=tiara`,    icon:"chat" },
        { textKey:"depEwallet", href:`ewallet.html?brand=tiara`, icon:"chat" },
        { textKey:"depPulsa",   href:`pulsa.html?brand=tiara`,   icon:"chat" },
        { textKey:"depWD",      href:`wd.html?brand=tiara`,      icon:"chat" },
      ]},

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

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

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

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

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

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

function renderSidebar(brandKey, prefix, opts = {}){
  const cfg = brandMap[brandKey] || brandMap.tiara;

  const isSuperadmin = !!opts.isSuperadmin;
  const scopes = Array.isArray(opts.scopes) ? opts.scopes : [];
  const hasScope = (name) => isSuperadmin || !name || scopes.includes(String(name).toLowerCase());

  let html = sidebarClockCard(prefix);

  cfg.sections.forEach(section=>{
    // ✅ RBAC: hanya berlaku untuk section yang punya `scope`
    if (!hasScope(section.scope)) return;

    const title = section.labelKey ? T(section.labelKey).toUpperCase() : "MENU";
    html += `<div class="mb-4"><div class="text-[11px] uppercase font-semibold text-slate-400 dark:text-slate-500 tracking-wide mb-2">${title}</div><ul class="space-y-1">`;
    section.items.forEach(item=>{
      html += `<li>
        <a href="${item.href}" class="flex items-center gap-2 px-3 py-2 rounded-md font-medium border 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">
          ${iconSVG(item.icon,false)}<span>${T(item.textKey)}</span>
        </a>
      </li>`;
    });
    html += `</ul></div>`;
  });

  return html;
}

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;
  });
}

/* ===== Parser 8 baris (tetap) ===== */
function parse8Lines(raw){
  const lines = (raw||"").split("\n").map(s=>s.trim()).filter(Boolean);
  if (lines.length !== 8) return { ok:false, err:"len" };

  const userId   = lines[0].toUpperCase();               // baris 1
  const amount   = parseInt((lines[3]||"").replace(/\D+/g, ""), 10); // baris 4
  const tanggal  = lines[4];                              // baris 5
  const bankDst  = (lines[5]||"").toUpperCase();          // baris 6
  const nameDst  = (lines[6]||"").toUpperCase();          // baris 7
  const noDst    = (lines[7]||"").replace(/\s+/g,"");     // baris 8

  if (!userId || !Number.isFinite(amount) || amount<=0 || !BANKS.has(bankDst) || !nameDst || !noDst || !tanggal) {
    return { ok:false, err:"shape" };
  }
  return { ok:true, data:{ userId, amount, tanggal, bankDst, nameDst, noDst } };
}

/* ===== Preview Rute & ADM (tetap) ===== */
const EWALLET_1000 = new Set(["GOPAY","LINKAJA"]);
const EWALLET_ZERO  = new Set(["OVO","DANA"]);
const SERVICE_FEE = { bifast: 2500, realtime: 6500 };
function up(s){ return String(s||"").toUpperCase(); }

let ACCOUNTS = [];
let ACC_INDEX = {};
function selectedAccount(){ const id = els.sheetSelect?.value || ""; return ACC_INDEX[id] || null; }
function selectedSrcBank(){ const acc = selectedAccount(); return acc ? up(acc.bank) : ""; }

function computeRouteFee(srcBank, dstBank, layanan, admOverride){
  if (admOverride !== null && admOverride !== undefined) {
    return { type:"override", fee:admOverride, label:"Override", explain:`Akun dipaksa ADM ${admOverride}` };
  }
  if(!srcBank || !dstBank) return { type:null, fee:null, label:"", explain:"" };
  if(srcBank === dstBank) return { type:"intrabank", fee:0, label:"Intra-bank", explain:"Layanan diabaikan (ADM 0)" };
  if (EWALLET_ZERO.has(dstBank))  return { type:"ewallet", fee:0,    label:"E-wallet", explain:"Layanan diabaikan (ADM 0)" };
  if (EWALLET_1000.has(dstBank))  return { type:"ewallet", fee:1000, label:"E-wallet", explain:"Layanan diabaikan (ADM 1000)" };
  const fee = SERVICE_FEE[String(layanan||"").toLowerCase()] ?? 2500;
  return { type:"interbank", fee, label:(layanan==="realtime"?"REALTIME":"BI FAST"), explain:`Inter-bank (${(layanan||"bifast").toUpperCase()})` };
}

function previewChip(html){
  return `<span class="inline-flex items-center gap-1 px-2 py-[2px] rounded-full border text-[11px] bg-slate-50 dark:bg-[#161616] border-slate-200 dark:border-[#2a2a2a]">${html}</span>`;
}
function setLayananDisabled(disabled){
  els.layananSelect.disabled = !!disabled;
  els.layananSelect.classList.toggle("opacity-60", !!disabled);
  els.layananSelect.classList.toggle("cursor-not-allowed", !!disabled);
}

function updateComposerPreview(){
  const raw = els.chatInput.value || "";
  const parsed = parse8Lines(raw);

  if(!parsed.ok){
    setLayananDisabled(false);
    els.composerNote.innerHTML = "";
    els.parseHint.textContent = looksExactly8Lines(raw) ? "Terdeteksi: WD 8 baris (siap kirim)." : "Format: auto-detect.";
    return;
  }

  const { userId, amount, bankDst } = parsed.data;
  const acc      = selectedAccount();
  const srcBank  = acc ? up(acc.bank) : selectedSrcBank();
  const layanan  = els.layananSelect.value || "bifast";
  const route    = computeRouteFee(srcBank, bankDst, layanan, (acc?.admOverride ?? null));

  const chips = [
    previewChip(`<b>${escapeHTML(srcBank||"-")}</b> → <b>${escapeHTML(bankDst||"-")}</b>`),
    previewChip(route.type ? route.type.replace("-", "-") : "—"),
    previewChip(route.label || "—"),
    previewChip(`ADM <b>${route.fee ?? "—"}</b>`)
  ].join(" ");

  els.composerNote.innerHTML = chips + (
    (route.type==="intrabank" || route.type==="ewallet")
      ? ` <span class="text-[11px] text-slate-500 dark:text-slate-400 ml-1">(layanan diabaikan)</span>`
      : ""
  );
  els.parseHint.textContent = `User: ${userId} • Nominal: ${amount.toLocaleString("id-ID")}`;
  setLayananDisabled(route.type==="intrabank" || route.type==="ewallet" || route.type==="override");
}

/* ===== API: load bank online (tetap) ===== */
async function loadBanksOnline(){
  const url = `/api/awd/accounts?brand=${encodeURIComponent(activeBrand)}&status=online`;
  const res = await apiFetch(url, {
    method:"GET",
    headers: { "x-panel-user": (els.topUser?.textContent || "").trim() }
  });
  const accounts = (res?.accounts || []).filter(a => a.status === "online");

  ACCOUNTS = accounts;
  ACC_INDEX = Object.fromEntries(accounts.map(a => [a.id, a]));

  if (!accounts.length){
    els.sheetSelect.innerHTML = `<option value="">(Tidak ada bank online)</option>`;
    return { accounts:[], selected:null };
  }

  const lastId = localStorage.getItem(`panel:last_sheet_${activeBrand}:awd`);
  let selectedId = lastId && accounts.some(a=>a.id===lastId) ? lastId : accounts[0].id;

  els.sheetSelect.innerHTML = accounts
    .map(a => `<option value="${a.id}" ${a.id===selectedId?'selected':''}>${a.bank} • ${a.name}</option>`)
    .join("");

  const sel = accounts.find(a=>a.id===selectedId) || accounts[0];
  // update preview
  updateComposerPreview?.();

  return { accounts, selected: sel };
}

/* ===== Kirim (tetap), dipanggil setelah konfirmasi ===== */
async function doSend(){
  const text      = els.chatInput.value || "";
  const accountId = els.sheetSelect.value || "";
  const layanan   = els.layananSelect.value || "bifast";

  if (!accountId){ renderBotBubble(`<div class="text-red-600 dark:text-red-400">Pilih Bank dulu ya.</div>`); return; }
  if (!text.trim()){ renderBotBubble(`<div class="text-red-600 dark:text-red-400">Teks masih kosong.</div>`); return; }

  const parsed = parse8Lines(text);
  if (!parsed.ok){ renderBotBubble(`<div>❌ Silahkan masukan format yang benar</div>`); return; }

  const { userId, amount, tanggal, bankDst, nameDst, noDst } = parsed.data;

  const ts = Date.now();
  renderUserBubble(text, ts);
  els.sendBtn.disabled = true;
  const prev = els.sendBtn.textContent;
  els.sendBtn.textContent = T("sending");

  try {
    const body = {
      brand: activeBrand,
      accountId,
      layanan,
      userId,
      bankDst,
      nameDst,
      noDst,
      amount,
      tanggal,
      raw: text
    };

    const res = await apiFetch("/api/awd/tx", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "x-panel-user": (els.topUser?.textContent || "").trim()
      },
      body: JSON.stringify(body)
    });

    if (!res || res.ok === false) {
      const code = (res?.error || "").toLowerCase();
      let msg = "❌ " + (res?.error || "Gagal menyimpan");
      if (code === "duplicate_tx")         msg = "❌ Duplikat, data sudah pernah dicatat.";
      else if (code === "account_offline") msg = "❌ Akun bank sedang OFFLINE. Pilih akun ONLINE.";
      else if (code === "account_not_found") msg = "❌ Akun tidak ditemukan / brand tidak cocok.";
      else if (code === "bankdst invalid")   msg = "❌ Bank tujuan tidak valid.";
      renderBotBubble(`<div class="text-red-600 dark:text-red-400">${escapeHTML(msg)}</div>`);
    } else {
      const label = els.sheetSelect.options[els.sheetSelect.selectedIndex]?.textContent || "-";
      renderBotBubble(`<div>✅ Dicatat ke tabel <b>Auto Withdraw</b> untuk <b>${escapeHTML(label)}</b> — layanan <b>${layanan.toUpperCase()}</b>. Status awal: <b>PENDING</b>.</div>`);
      localStorage.setItem(`panel:last_sheet_${activeBrand}:awd`, accountId);
      localStorage.setItem(`panel:last_layanan_${activeBrand}:awd`, layanan);
      els.chatInput.value = "";
      autoGrow(els.chatInput);
      els.parseHint.textContent = "Format: auto-detect.";
      els.composerNote.innerHTML = "";
    }
  } catch (e) {
    renderBotBubble(`<div class="text-red-600 dark:text-red-400">❌ ${escapeHTML(e?.message || String(e))}</div>`);
  } finally {
    els.sendBtn.textContent = prev;
    els.sendBtn.disabled = false;
  }
}

/* ===== Modal konfirmasi ===== */
function openConfirmSave(){
  els.confirmModal.classList.remove("hidden");
  // icon check (hijau)
  els.cmX.classList.add("hidden");
  els.cmCheck.classList.remove("hidden");
  // teks sesuai request
  els.cmText.textContent = "Apa kamu ingin simpan data?";

  const onOk = ()=>{
    closeConfirm();
    doSend();
  };
  const onCancel = ()=> closeConfirm();

  // cleanup dan pasang handler baru
  els.cmOk.onclick = null; els.cmCancel.onclick = null;
  els.cmOk.onclick = onOk;
  els.cmCancel.onclick = onCancel;

  // ENTER / SPACE = Iya
  bindConfirmHotkeys(onOk);
}
function closeConfirm(){
  els.confirmModal.classList.add("hidden");
  unbindConfirmHotkeys();
}

let confirmKeyHandler = null;
function bindConfirmHotkeys(onOk){
  confirmKeyHandler = (e)=>{
    if (e.key === "Enter" || e.key === " " || e.code === "Space") {
      e.preventDefault();
      onOk();
    }
  };
  document.addEventListener("keydown", confirmKeyHandler);
}
function unbindConfirmHotkeys(){
  if (confirmKeyHandler){
    document.removeEventListener("keydown", confirmKeyHandler);
    confirmKeyHandler = null;
  }
}

/* ===== INIT ===== */
(async function init(){
  const session = await requireSession();
  els.topUser.textContent = session?.username || "admin";

  // RBAC
  const rawScopes = session?.scopes ?? session?.permissions ?? [];
  const scopes = Array.isArray(rawScopes)
    ? rawScopes.map(s=>String(s).toLowerCase())
    : (rawScopes && typeof rawScopes === "object")
      ? Object.keys(rawScopes).filter(k=>!!rawScopes[k]).map(k=>String(k).toLowerCase())
      : [];

  const isSuperadmin = session?.role === "superadmin";
  const hasScopePage = (isSuperadmin || scopes.includes(REQUIRED_SCOPE_PAGE));

  // header static
  els.brandLabel.textContent = brandBadgeText;
  els.brandBadge.textContent = brandBadgeText;
  els.pageTitle.textContent  = T("pageTitle");
  els.pageDesc.textContent   = T("pageDescPrefix") + brandDisplayName(activeBrand) + ".";
  const logo = brandLogoMap[activeBrand] || brandLogoMap.tiara;
  els.desktopLogo.src = logo; els.desktopLogo.alt = brandBadgeText;
  els.mobileLogo.src  = logo; els.mobileLogo.alt  = brandBadgeText;

  // i18n dropdown texts & flag
  els.ddThemeText.textContent  = T("ddTheme");
  els.ddLangText.textContent   = T("ddLanguage");
  els.ddLogoutText.textContent = T("ddLogout");
  const flagMap = { id:"assets/img/indo.png", en:"assets/img/eng.png", km:"assets/img/kmhr.png" };
  document.getElementById("currentLangFlag").src = flagMap[lang] || flagMap.id;
  document.getElementById("currentLangFlag").alt = (lang==="en"?"English":lang==="km"?"Cambodia":"Indonesia");

  // render sidebar & clock
  els.sideMenuDesktop.innerHTML = renderSidebar(activeBrand, "Desktop", { isSuperadmin, scopes });
  els.sideMenuMobile.innerHTML  = renderSidebar(activeBrand, "Mobile",  { isSuperadmin, scopes });
  updateSidebarClock(); setInterval(updateSidebarClock, 1000);

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

  // mobile sidebar
  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"); }
  document.getElementById("hamburgerBtn").addEventListener("click",(e)=>{ e.stopPropagation(); openMobile(); });
  document.getElementById("closeSidebarBtn").addEventListener("click", closeMobile);
  document.getElementById("sidebarOverlay").addEventListener("click", closeMobile);

  if (!hasScopePage) {
    document.getElementById("forbiddenOverlay").classList.remove("hidden");
    document.getElementById("forbiddenTitle").textContent = T("forbiddenTitle");
    document.getElementById("forbiddenDesc").textContent  = T("forbiddenDesc");
    document.getElementById("goHomeBtnText").textContent  = T("goHome");
    return;
  }

  // load bank online
  await loadBanksOnline();

  // layanan terakhir
  const lastLayanan = localStorage.getItem(`panel:last_layanan_${activeBrand}:awd`);
  if (lastLayanan) els.layananSelect.value = lastLayanan;

  // greet
  els.greetBox.innerHTML = `<strong>${T("hello")} ${escapeHTML(els.topUser.textContent)}!</strong> Silakan tempel format WD (8 baris).`;

  // events
  // ENTER di textarea => buka popup Simpan
  els.chatInput.addEventListener("keydown", (e)=>{
    if(e.key==="Enter" && !e.shiftKey){ e.preventDefault(); openConfirmSave(); }
  });

  // Klik Simpan => popup Simpan
  els.sendBtn.addEventListener("click", ()=> openConfirmSave());

  // Klik Batal => langsung ke halaman withdraw-awd.html (tanpa popup)
  els.btnCancel.addEventListener("click", ()=>{
    window.location = `withdraw-awd.html?brand=${activeBrand}`;
  });

  els.chatInput.addEventListener("input", ()=>{ autoGrow(els.chatInput); updateComposerPreview(); });
  els.sheetSelect.addEventListener("change", ()=>{ const id = els.sheetSelect.value || ""; if (id) localStorage.setItem(`panel:last_sheet_${activeBrand}:awd`, id); updateComposerPreview(); });
  els.layananSelect.addEventListener("change", ()=>{ localStorage.setItem(`panel:last_layanan_${activeBrand}:awd`, els.layananSelect.value); updateComposerPreview(); });

  // initial preview
  updateComposerPreview();
})();