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

// --- I18N ---
const i18nMap = {
  id: {
    dropdownTheme: "Tema", dropdownLanguage: "Bahasa", dropdownLogout: "Keluar",
    menuDashboard: "Dashboard", menuGlobalSheets: "Global Sheets", menuBrandMeta: "Brand Meta", menuProfiles: "Profiles",
    submenuProfilesBank: "Edit Bank", submenuProfilesEwallet: "Edit Ewallet", submenuProfilesPulsa: "Edit Pulsa", submenuProfilesWD: "Edit Withdraw",
    pageTitleBrandMeta: "Brand Meta", brandDescPrefixBrand: "Konfigurasi lokasi sheet Pendingan & Mistake brand ",
    sectionTitle: "Detail Brand & Target Sheet", btnSave: "Simpan",
    menuProses: "Proses", depBank: "Catat Bank", depEwallet: "Catat Ewallet", depPulsa: "Catat Pulsa", depWD: "Catat Withdraw",
    menuUsers: "Users", menuLaporan: "Laporan", repPendingan: "Pendingan", repMistake: "Mistake", menuAutoWD: "Auto Withdraw", awdWithdraw: "Withdraw", menuAdmin: "Admin",

    // ✅ NEW: Notifikasi
    menuNotifikasi: "Notifikasi",
    notifBank: "Bank",
    notifEwallet: "Ewallet",
  },
  en: {
    dropdownTheme: "Theme", dropdownLanguage: "Language", dropdownLogout: "Logout",
    menuDashboard: "Dashboard", menuGlobalSheets: "Global Sheets", menuBrandMeta: "Brand Meta", menuProfiles: "Profiles",
    submenuProfilesBank: "Edit Bank", submenuProfilesEwallet: "Edit Ewallet", submenuProfilesPulsa: "Edit Phone Credit", submenuProfilesWD: "Edit Withdraw",
    pageTitleBrandMeta: "Brand Meta", brandDescPrefixBrand: "Configure Pending / Mistake sheets for brand ",
    sectionTitle: "Brand Details & Target Sheets", btnSave: "Save",
    menuProses: "Proses", depBank: "Record Bank", depEwallet: "Record Ewallet", depPulsa: "Record Phone Credit", depWD: "Record Withdraw",
    menuUsers: "Users", menuLaporan: "Reports", repPendingan: "Pending", repMistake: "Mistakes", menuAutoWD: "Auto Withdraw", awdWithdraw: "Withdraw", menuAdmin: "Admin",

    // ✅ NEW: Notifications
    menuNotifikasi: "Notifications",
    notifBank: "Bank",
    notifEwallet: "Ewallet",
  },
  km: {
    dropdownTheme: "Theme", dropdownLanguage: "ភាសា", dropdownLogout: "ចេញ",
    menuDashboard: "Dashboard", menuGlobalSheets: "Global Sheets", menuBrandMeta: "Brand Meta", menuProfiles: "Profiles",
    submenuProfilesBank: "កែប្រែ Bank", submenuProfilesEwallet: "កែប្រែ Ewallet", submenuProfilesPulsa: "កែប្រែ Pulsa", submenuProfilesWD: "កែប្រែ Withdraw",
    pageTitleBrandMeta: "Brand Meta", brandDescPrefixBrand: "កំណត់ទីតាំងសន្លឹក Pending / Mistake សម្រាប់ម៉ាក ",
    sectionTitle: "ព័ត៌មានម៉ាក និងសន្លឹកគោលដៅ", btnSave: "រក្សាទុក",
    menuProses: "Proses", depBank: "Catat Bank", depEwallet: "Catat Ewallet", depPulsa: "Catat Pulsa", depWD: "Catat Withdraw",
    menuUsers: "Users", menuLaporan: "Laporan", repPendingan: "Pending", repMistake: "Mistake", menuAutoWD: "Auto Withdraw", awdWithdraw: "Withdraw", menuAdmin: "Admin",

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

// --- STATE ---
const activeBrand = (getQueryParam("brand") || "tiara").toLowerCase();
const currentLang = (localStorage.getItem("lang") || "id").toLowerCase();

// ✅ NEW: tambah scope notifikasi (default off)
const DEFAULT_SCOPES = { brand:true, proses:true, laporan:true, autowd:false, users:false, notifikasi:false };

function getT(key){
  const lang = i18nMap[currentLang] ? currentLang : "id";
  return i18nMap[lang][key] || i18nMap["id"][key] || key;
}

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

// 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] 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>
  `;
}

// Mini icons
function iconSVG(name, highlight=false){
  const base = highlight ? "text-blue-500 dark:text-blue-400" : "text-slate-500 dark:text-slate-400";
  const wrap = (svg)=>`<span class="${base}">${svg}</span>`;
  if(name==="home")   return wrap(`<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 wrap(`<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 wrap(`<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 wrap(`<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 wrap(`<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 wrap(`<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 wrap(`<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 wrap(`<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: icon BANK & EWALLET (notifikasi)
  if(name==="bank")   return wrap(`<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 wrap(`<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 "";
}

// brandMap + RBAC scopes per section
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: true },
        { 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: true },
        { 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: true },
        { 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 },
      ]},
    ],
  },
};

// Render sidebar sesuai RBAC
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;

    let itemsHTML = "";
    section.items.forEach(item => {
      const linkCls = item.active ? parentActiveCls : parentNormalCls;

      if (item.icon === "profile") {
        itemsHTML += `
          <li>
            <button id="profilesToggle${prefix}" class="w-full flex items-center justify-between px-3 py-2 rounded-md font-medium border ${parentNormalCls}">
              <span class="flex items-center gap-2">${iconSVG("profile", false)}<span>${getT("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" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" data-chevron class="transition-transform"><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>${getT("submenuProfilesBank")}</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>${getT("submenuProfilesEwallet")}</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>${getT("submenuProfilesPulsa")}</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>${getT("submenuProfilesWD")}</span></a></li>
            </ul>
          </li>
        `;
      } else {
        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, !!item.active)}<span>${getT(item.textKey)}</span></a></li>`;
      }
    });

    if (!itemsHTML) return;
    const sectionTitle = section.labelKey ? getT(section.labelKey).toUpperCase() : cfg.badge;
    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");
  });
}

// WIB Clock
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(p=>[p.type,p.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(pref=>{
    const d=document.getElementById("sidebarDate"+pref), t=document.getElementById("sidebarTime"+pref);
    if(d) d.textContent=tanggalStr; if(t) t.textContent=waktuStr;
  });
}

// DOM refs
const brandBtn          = document.getElementById("brandBtn");
const brandDropdown     = document.getElementById("brandDropdown");
const menuBtn           = document.getElementById("userMenuBtn");
const userDropdown      = document.getElementById("userDropdown");
const themeToggleBtn    = document.getElementById("themeToggleBtn");
const langBtn           = document.getElementById("langBtn");
const langOptions       = document.getElementById("langOptions");
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");
const formEl            = document.getElementById("brandForm");

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

// Language
if (langBtn) langBtn.addEventListener("click",(e)=>{ e.stopPropagation(); langOptions.classList.toggle("hidden"); });
if (langOptions) langOptions.querySelectorAll("button[data-lang]").forEach(btn=>{
  btn.addEventListener("click",(e)=>{ e.stopPropagation(); localStorage.setItem("lang", btn.getAttribute("data-lang")); window.location.reload(); });
});

// Dropdowns
if (brandBtn) brandBtn.addEventListener("click",(e)=>{ e.stopPropagation(); brandDropdown.classList.toggle("hidden"); if(!userDropdown.classList.contains("hidden")){ userDropdown.classList.add("hidden"); langOptions.classList.add("hidden"); }});
if (menuBtn)  menuBtn.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")) { if (!menuBtn.contains(e.target) && !userDropdown.contains(e.target)) { userDropdown.classList.add("hidden"); langOptions.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"; });

// Load & save form
async function loadMeta() {
  const data = await apiFetch(`/api/brand/${activeBrand}`);
  if (!data.ok) { showFlash("err", data.error || "Gagal load meta."); return; }
  showFlash("", "");
  const meta = data.meta || {};
  formEl.group_push_chat_id.value      = meta.group_push_chat_id || "";
  formEl.dp_sources.value              = (meta.dp_sources || []).join(", ");
  formEl.wd_sources.value              = (meta.wd_sources || []).join(", ");
  formEl.pendingan_dp_sheet_id.value   = meta.pendingan_dp_sheet_id || "";
  formEl.pendingan_wd_sheet_id.value   = meta.pendingan_wd_sheet_id || "";
  formEl.mistake_dp_sheet_id.value     = meta.mistake_dp_sheet_id || "";
  formEl.mistake_wd_sheet_id.value     = meta.mistake_wd_sheet_id || "";
}

if (formEl) {
  formEl.addEventListener("submit", async (e)=>{
    e.preventDefault();
    const fd = new FormData(formEl);
    const out = await apiFetch(`/api/brand/${activeBrand}`, { method:"POST", body: fd });
    if (out.ok) { showFlash("ok", out.message || "Berhasil disimpan."); await loadMeta(); }
    else { showFlash("err", out.error || "Gagal simpan."); }
  });
}

// i18n static
function applyI18nStaticTexts(){
  document.getElementById("ddThemeText").textContent  = getT("dropdownTheme");
  document.getElementById("ddLangText").textContent   = getT("dropdownLanguage");
  document.getElementById("ddLogoutText").textContent = getT("dropdownLogout");
  document.getElementById("pageTitle").textContent    = getT("pageTitleBrandMeta");
  const descEl = document.getElementById("pageDesc");
  descEl.textContent = getT("brandDescPrefixBrand") + brandDisplayName(activeBrand) + ".";
  document.getElementById("formSectionTitle").textContent = getT("sectionTitle");
  document.getElementById("btnSaveText").textContent  = getT("btnSave");
  const flagImg = document.getElementById("currentLangFlag");
  if (flagImg) {
    if (currentLang === "id") { flagImg.src="assets/img/indo.png"; flagImg.alt="Indonesia"; }
    else if (currentLang === "en") { flagImg.src="assets/img/eng.png"; flagImg.alt="English"; }
    else if (currentLang === "km") { flagImg.src="assets/img/kmhr.png"; flagImg.alt="Cambodia"; }
    else { flagImg.src="assets/img/eng.png"; flagImg.alt="Language"; }
  }
}

// Init
async function init(){
  const session = await requireSession();
  const usernameText = session.username || "admin";
  const isSuperadmin = (session.role === "superadmin");

  // ✅ NEW: superadmin otomatis dapat semua scope termasuk notifikasi
  const userScopes   = isSuperadmin
    ? { brand:true, proses:true, laporan:true, autowd:true, users:true, notifikasi:true }
    : (session.scopes || DEFAULT_SCOPES);

  // Route-guard: halaman Brand butuh scope "brand"
  if (!isSuperadmin && !userScopes.brand) {
    showFlash("err", "Akses ditolak: Anda tidak memiliki scope 'brand'.");
    setTimeout(()=>{ window.location = `index.html?brand=${activeBrand}`; }, 1200);
    return; // stop init
  }

  document.getElementById("topUser").textContent = usernameText;

  // badges & logos
  const brandInfo = brandMap[activeBrand] || brandMap["tiara"];
  const badgeText = brandInfo.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; }

  // i18n
  applyI18nStaticTexts();

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

  // data form
  await loadMeta();

  // clock
  updateSidebarClock();
  setInterval(updateSidebarClock, 1000);
}

init();