// assets/js/profile-edit.js
import {
  requireSession,
  apiFetch,
  getQueryParam,
  brandDisplayName,
  showFlash
} from "../app.js";

//
// --- I18N MAP ---
//
const i18nMap = {
  id: {
    dropdownTheme: "Tema",
    dropdownLanguage: "Bahasa",
    dropdownLogout: "Keluar",

    menuDashboard: "Dashboard",
    menuGlobalSheets: "Global Sheets",
    menuBrandMeta: "Brand Meta",
    menuProfiles: "Profiles",

    // NEW: label section Proses (untuk sidebar)
    menuProses: "Proses",

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

    submenuProfilesBank: "Edit Bank",
    submenuProfilesEwallet: "Edit Ewallet",
    submenuProfilesPulsa: "Edit Pulsa",
    submenuProfilesWD: "Edit Withdraw",

    pageTitleProfileEditPrefix: "Edit Profile ",
    pageDescProfileEditPrefix1: "Atur perilaku bot untuk channel ",
    pageDescProfileEditPrefix2: " di brand ",

    kvIntroSuffix:
      'Paste JSON lengkap di bawah, lalu Simpan.<br/>Hati-hati: harus valid JSON (pakai tanda kutip "<code class="bg-slate-800 dark:bg-black/50 text-slate-50 dark:text-white text-[12px] px-1 py-[1px] rounded">&quot;</code>", koma bener, dsb).',

    btnSave: "Simpan",
    menuDeposit: "Deposit",
    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",
  },
  en: {
    dropdownTheme: "Theme",
    dropdownLanguage: "Language",
    dropdownLogout: "Logout",

    menuDashboard: "Dashboard",
    menuGlobalSheets: "Global Sheets",
    menuBrandMeta: "Brand Meta",
    menuProfiles: "Profiles",

    // NEW
    menuProses: "Process",

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

    submenuProfilesBank: "Edit Bank",
    submenuProfilesEwallet: "Edit Ewallet",
    submenuProfilesPulsa: "Edit Phone Credit",
    submenuProfilesWD: "Edit Withdraw",

    pageTitleProfileEditPrefix: "Edit Profile ",
    pageDescProfileEditPrefix1: "Configure bot behavior for channel ",
    pageDescProfileEditPrefix2: " in brand ",

    kvIntroSuffix:
      'Paste full JSON below, then Save.<br/>Careful: must be valid JSON (use quotes "<code class="bg-slate-800 dark:bg-black/50 text-slate-50 dark:text-white text-[12px] px-1 py-[1px] rounded">&quot;</code>", commas correct, etc).',

    btnSave: "Save",
    menuDeposit: "Deposit",
    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",
  },
  km: {
    dropdownTheme: "Theme",
    dropdownLanguage: "ភាសា",
    dropdownLogout: "ចេញ",

    menuDashboard: "Dashboard",
    menuGlobalSheets: "Global Sheets",
    menuBrandMeta: "Brand Meta",
    menuProfiles: "Profiles",

    // NEW
    menuProses: "ដំណើរការ",

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

    submenuProfilesBank: "កែប្រែ Bank",
    submenuProfilesEwallet: "កែប្រែ Ewallet",
    submenuProfilesPulsa: "កែប្រែ Pulsa",
    submenuProfilesWD: "កែប្រែ Withdraw",

    pageTitleProfileEditPrefix: "កែប្រែ Profile ",
    pageDescProfileEditPrefix1: "កំណត់អាកប្បកិរិយា bot សម្រាប់ channel ",
    pageDescProfileEditPrefix2: " របស់ម៉ាក ",

    kvIntroSuffix:
      'Paste JSON ពេញខ្លួនខាងក្រោម ហើយចុចរក្សាទុក។<br/>ប្រុងប្រយ័ត្ន: ត្រូវតែជា JSON ត្រឹមត្រូវ (ប្រើសញ្ញាដកឃ្លា "<code class="bg-slate-800 dark:bg-black/50 text-slate-50 dark:text-white text-[12px] px-1 py-[1px] rounded">&quot;</code>", ក្បៀស (,), ល។)',

    btnSave: "រក្សាទុក",
    menuDeposit: "Deposit",
    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",
  }
};

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

// DEFAULT scopes jika admin biasa belum di-set, samakan dengan brand.html
// ✅ tambah notifikasi:false
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;
}

function channelSlugUpper(){ return (activeChannel || "").toUpperCase(); }

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

//
// 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 text-slate-700 dark:text-slate-200 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 text-slate-800 dark:text-slate-100">-</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 text-slate-800 dark:text-slate-100">-</div>
        </div>
      </div>
    </div>
  `;
}

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);
  let dd="", mm="", yyyy="", hh="", mi="", ss="";
  parts.forEach(p=>{ if(p.type==="day") dd=p.value; if(p.type==="month") mm=p.value; if(p.type==="year") yyyy=p.value; if(p.type==="hour") hh=p.value; if(p.type==="minute") mi=p.value; if(p.type==="second") ss=p.value; });
  const bulanShort = ["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des"];
  const tanggalStr = `${weekdayId}, ${dd} ${bulanShort[parseInt(mm,10)-1] || mm} ${yyyy}`;
  const waktuStr   = `${hh}:${mi}:${ss}`;
  const dateDesktop = document.getElementById("sidebarDateDesktop");
  const timeDesktop = document.getElementById("sidebarTimeDesktop");
  const dateMobile  = document.getElementById("sidebarDateMobile");
  const timeMobile  = document.getElementById("sidebarTimeMobile");
  if (dateDesktop) dateDesktop.textContent = tanggalStr;
  if (timeDesktop) timeDesktop.textContent = waktuStr;
  if (dateMobile)  dateMobile.textContent  = tanggalStr;
  if (timeMobile)  timeMobile.textContent  = waktuStr;
}

//
// BRAND MAP + SCOPES (RBAC)
//
const brandMap = {
  tiara: {
    badge: "TIARATOTO",
    sections: [
      {
        labelKey: "menuDashboard",
        items: [
          { textKey: "menuDashboard", href: `index.html?brand=tiara`, icon: "home", active: false },
        ],
      },
      {
        labelKey: null,
        brandBadge: "TIARATOTO",
        scope: "brand",
        items: [
          { textKey: "menuGlobalSheets", href: `global.html?brand=tiara`, icon: "sheets", active: false },
          { textKey: "menuBrandMeta",   href: `brand.html?brand=tiara`,  icon: "brand",  active: false },
          {
            textKey: "menuProfiles",
            href: null,
            icon: "profile",
            active: true,
            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 (scope: 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: true,
            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 (scope: 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: true,
            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 (scope: 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 },
        ],
      },
    ],
  },
};

//
// helper icon svg mini
//
function iconSVG(name, highlight=false){
  const baseColor = highlight
    ? "text-blue-500 dark:text-blue-400"
    : "text-slate-500 dark:text-slate-400";

  if (name === "home") {
    return `
      <span class="${highlight ? "text-blue-500 dark:text-blue-400" : "text-slate-500 dark:text-slate-400"}">
        <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>
      </span>
    `;
  }
  if (name === "sheets") {
    return `
      <span class="${baseColor}">
        <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>
      </span>
    `;
  }
  if (name === "brand") {
    return `
      <span class="${baseColor}">
        <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>
      </span>
    `;
  }
  if (name === "profile") {
    return `
      <span class="${baseColor}">
        <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>
      </span>
    `;
  }
  if (name === "chat") {
    return `
      <span class="${highlight ? "text-blue-500 dark:text-blue-400" : "text-slate-500 dark:text-slate-400"}">
        <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>
      </span>
    `;
  }
  if (name === "users") {
    return `
      <span class="${baseColor}">
        <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>
      </span>
    `;
  }
  if (name === "report") {
    return `
      <span class="${baseColor}">
        <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>
      </span>
    `;
  }
  if (name === "zap") {
    return `
      <span class="${baseColor}">
        <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>
      </span>
    `;
  }

  // ✅ NEW: icon Notifikasi
  if (name === "bank") {
    return `
      <span class="${baseColor}">
        <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="${baseColor}">
        <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 renderSidebar(brandKey, prefix, { isSuperadmin, scopes }, activeChannel) {
  const cfg = brandMap[brandKey] || brandMap["tiara"];
  const parentActiveCls = "bg-blue-50 text-blue-600 border-blue-200 dark:bg-blue-950/40 dark:text-blue-400 dark:border-blue-800";
  const parentNormalCls = "hover:bg-slate-100 hover:text-blue-600 border-transparent text-slate-700 dark:text-slate-200 dark:hover:bg-[#2a2a2a] dark:hover:text-blue-400";

  let html = sidebarClockCard(prefix);

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

    const sectionTitle = section.labelKey
      ? 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 = parentActiveCls;
        const openSub = true;
        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, true)}
                <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 ${openSub ? "rotate-180" : ""}"
                  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 ${openSub ? "" : "hidden"}">
        `;

        (item.submenu || []).forEach(sub=>{
          const isActiveSub = (sub.channel === activeChannel);
          const subCls = isActiveSub ? parentActiveCls : parentNormalCls;
          html += `
            <li>
              <a
                href="profile-edit.html?brand=${brandKey}&channel=${sub.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(sub.textKey)}</span>
              </a>
            </li>
          `;
        });

        html += `
            </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");
  });
}

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("profileForm");
const textareaEl        = document.getElementById("profile_json");

// =======================================
// JSON Editor Helpers / State
// =======================================
let lastLoadedText = "";
let dirty = false;
const draftKey = `profile:${activeBrand}:${activeChannel}:draft`;

const btnFormat   = document.getElementById("btnFormat");
const btnMinify   = document.getElementById("btnMinify");
const btnLint     = document.getElementById("btnLint");
const btnSample   = document.getElementById("btnSample");
const btnSheets   = document.getElementById("btnSheets");
const btnDownload = document.getElementById("btnDownload");
const btnUpload   = document.getElementById("btnUpload");
const fileUpload  = document.getElementById("fileUpload");
const btnRevert   = document.getElementById("btnRevert");
const btnCopyKV   = document.getElementById("btnCopyKV");
const lintBox     = document.getElementById("lintBox");
const counterEl   = document.getElementById("counter");
const dirtyMark   = document.getElementById("dirtyMark");

function updateCounter() {
  const txt = textareaEl.value || "";
  const lines = txt.split(/\r?\n/).length;
  counterEl.textContent = `${txt.length} chars • ${lines} lines`;
}
function setDirty(v) {
  dirty = !!v;
  dirtyMark.classList.toggle("hidden", !dirty);
}
function saveDraft() { localStorage.setItem(draftKey, textareaEl.value || ""); }
function clearDraft() { localStorage.removeItem(draftKey); }

function errorPositionFromMessage(msg) {
  const m = msg && msg.match(/position\s+(\d+)/i);
  if (!m) return null;
  const pos = parseInt(m[1], 10);
  const text = textareaEl.value || "";
  const pre = text.slice(0, pos);
  const line = pre.split(/\n/).length;
  const col  = pos - (pre.lastIndexOf("\n") + 1) + 1;
  return { pos, line, col };
}

function lintJSON() {
  lintBox.classList.add("hidden");
  lintBox.textContent = "";
  try {
    JSON.parse(textareaEl.value);
    showFlash("ok", "JSON valid ✅");
  } catch (e) {
    const p = errorPositionFromMessage(e.message || "");
    const where = p ? ` (baris ${p.line}, kolom ${p.col})` : "";
    lintBox.textContent = `❌ ${e.message}${where}`;
    lintBox.classList.remove("hidden");
    showFlash("err", "JSON tidak valid.");
  }
}

function formatJSON() {
  try {
    const obj = JSON.parse(textareaEl.value);
    textareaEl.value = JSON.stringify(obj, null, 2);
    updateCounter();
    setDirty(true);
  } catch (e) {
    lintJSON();
  }
}

function minifyJSON() {
  try {
    const obj = JSON.parse(textareaEl.value);
    textareaEl.value = JSON.stringify(obj);
    updateCounter();
    setDirty(true);
  } catch (e) {
    lintJSON();
  }
}

function sampleForChannel(ch) {
  const base = {
    allowed_sheets: ["BCA1_RINI"],
    username_map: { "rini": "RINI" },
    username_op_map: { "ambyah": "AMBYAH" },
    commands: {
      help:   { aliases: ["/help","help"],     enabled: true },
      submit: { aliases: ["ok","done","push"], enabled: true }
    },
    parse_rules: {
      amount_patterns: ["Rp\\s?([\\d\\.]+)", "(\\d{3,})"],
      date_formats: ["dddd, DD MMM YYYY - HH:mm:ss"]
    }
  };
  if (ch === "wd") {
    base.require_account_name = true;
    base.commands.withdraw = { aliases: ["/wd","tarik"], enabled: true };
  } else if (ch === "pulsa") {
    base.commands.topup = { aliases: ["/pulsa","pulsa"], enabled: true };
  } else if (ch === "ewallet") {
    base.commands.topup = { aliases: ["/ewallet","ewallet"], enabled: true };
  } else {
    base.commands.mutasi = { aliases: ["/mutasi","mutasi"], enabled: true };
  }
  base.channel = ch;
  return base;
}

function insertSample() {
  textareaEl.value = JSON.stringify(sampleForChannel(activeChannel), null, 2);
  updateCounter();
  setDirty(true);
  showFlash("ok", "Contoh JSON dimuat.");
}

async function insertAllowedSheetsFromMeta() {
  const data = await apiFetch(`/api/brand/${activeBrand}`);
  if (!data.ok) { showFlash("err", data.error || "Gagal load brand meta."); return; }
  const meta = data.meta || {};
  const arr = (activeChannel === "wd") ? (meta.wd_sources || []) : (meta.dp_sources || []);
  if (!arr.length) { showFlash("err", "Brand belum punya sumber untuk channel ini."); return; }
  try {
    const obj = JSON.parse(textareaEl.value || "{}");
    const now = new Set([...(obj.allowed_sheets || [])]);
    arr.forEach(s => now.add(s));
    obj.allowed_sheets = Array.from(now).sort();
    textareaEl.value = JSON.stringify(obj, null, 2);
    updateCounter();
    setDirty(true);
    showFlash("ok", `allowed_sheets terisi (${arr.length} sumber).`);
  } catch (e) {
    lintJSON();
  }
}

function downloadJSON() {
  const blob = new Blob([textareaEl.value || ""], { type: "application/json" });
  const a = document.createElement("a");
  a.href = URL.createObjectURL(blob);
  a.download = `profile-${activeBrand}-${activeChannel}.json`;
  a.click();
  URL.revokeObjectURL(a.href);
}

function copyKVKey() {
  const kvKey = `profile:${activeBrand}:${activeChannel}`;
  navigator.clipboard.writeText(kvKey).then(
    ()=>showFlash("ok","KV key dicopy."),
    ()=>showFlash("err","Gagal copy KV key.")
  );
}

function attachUpload() {
  btnUpload?.addEventListener("click", ()=> fileUpload.click());
  fileUpload?.addEventListener("change", ()=>{
    const file = fileUpload.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      textareaEl.value = String(reader.result || "");
      updateCounter();
      setDirty(true);
      showFlash("ok", "File dimuat ke editor (belum disimpan).");
    };
    reader.readAsText(file, "utf-8");
    fileUpload.value = "";
  });
}

document.addEventListener("keydown", (e)=>{
  if ((e.ctrlKey || e.metaKey) && !e.shiftKey) {
    if (e.key.toLowerCase() === "s") {
      e.preventDefault();
      formEl?.dispatchEvent(new Event("submit", {cancelable:true}));
    }
    if (e.key.toLowerCase() === "b") { e.preventDefault(); formatJSON(); }
    if (e.key.toLowerCase() === "m") { e.preventDefault(); minifyJSON(); }
    if (e.key.toLowerCase() === "l") { e.preventDefault(); lintJSON(); }
  }
});

textareaEl.addEventListener("input", ()=>{
  updateCounter();
  setDirty(textareaEl.value !== lastLoadedText);
  saveDraft();
});

btnFormat?.addEventListener("click", formatJSON);
btnMinify?.addEventListener("click", minifyJSON);
btnLint?.addEventListener("click", lintJSON);
btnSample?.addEventListener("click", insertSample);
btnSheets?.addEventListener("click", insertAllowedSheetsFromMeta);
btnDownload?.addEventListener("click", downloadJSON);
btnRevert?.addEventListener("click", async ()=>{
  await loadProfile();
  showFlash("ok","Dikembalikan ke versi server.");
});
btnCopyKV?.addEventListener("click", copyKVKey);
attachUpload();

window.addEventListener("beforeunload", (e)=>{
  if (dirty) { e.preventDefault(); e.returnValue = ""; }
});

function fixBrandDropdownLinks() {
  const dd = document.getElementById("brandDropdown");
  if (!dd) return;
  dd.querySelectorAll("a[href*='brand=tiara'], a[href*='brand=tts'], a[href*='brand=ttm']").forEach(a=>{
    const url = new URL(a.href, location.href);
    url.searchParams.set("channel", activeChannel);
    a.href = url.toString();
  });
}
fixBrandDropdownLinks();

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

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();
      const newLang = btn.getAttribute("data-lang");
      localStorage.setItem("lang", newLang);
      window.location.reload();
    });
  });
}

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

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

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

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

async function loadProfile() {
  const data = await apiFetch(`/api/profile/${activeBrand}/${activeChannel}`);
  if (!data.ok) { showFlash("err", data.error || "Gagal load profile."); return; }
  showFlash("", "");
  lastLoadedText = JSON.stringify(data.profile || {}, null, 2);

  const draft = localStorage.getItem(draftKey);
  if (draft && draft !== lastLoadedText) {
    textareaEl.value = draft;
    showFlash("ok", "Draft lokal dipulihkan (belum disimpan).");
    setDirty(true);
  } else {
    textareaEl.value = lastLoadedText;
    setDirty(false);
  }
  updateCounter();
}

if (formEl) {
  formEl.addEventListener("submit", async (e) => {
    e.preventDefault();

    const raw = textareaEl.value || "";
    try { JSON.parse(raw); }
    catch (err) { lintJSON(); return; }

    const fd = new FormData();
    fd.set("profile_json", raw);

    const out = await apiFetch(`/api/profile/${activeBrand}/${activeChannel}`, {
      method: "POST",
      body: fd
    });

    if (out.ok) {
      showFlash("ok", out.message || "Berhasil disimpan.");
      clearDraft();
      await loadProfile();
    } else {
      showFlash("err", out.error || "JSON tidak valid / gagal simpan.");
      lintJSON();
    }
  });
}

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("pageTitleProfileEditPrefix") + channelSlugUpper();

  const descEl = document.getElementById("pageDesc");
  descEl.textContent =
    getT("pageDescProfileEditPrefix1") +
    `"${activeChannel}"` +
    getT("pageDescProfileEditPrefix2") +
    brandDisplayName(activeBrand) +
    ".";

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

  const profHeadEl = document.getElementById("profileHead");
  profHeadEl.textContent =
    `Profile ${brandDisplayName(activeBrand)} / ${channelSlugUpper()}`;

  const kvIntroEl = document.getElementById("kvIntroWrap");
  const kvKey = `profile:${activeBrand}:${activeChannel}`;
  kvIntroEl.innerHTML = `
    Key KV:
    <code class="bg-slate-800 dark:bg-black/50 text-slate-50 dark:text-white text-[12px] px-1.5 py-[2px] rounded">${kvKey}</code><br/>
    ${getT("kvIntroSuffix")}
  `;

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

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

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

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

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

  const brandInfo      = brandMap[activeBrand] || brandMap["tiara"];
  const brandNameBadge = brandInfo.badge;
  document.getElementById("brandLabel").textContent = brandNameBadge;

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

  applyI18nStaticTexts();

  const ctx = { isSuperadmin, scopes: userScopes };
  document.getElementById("sideMenuDesktop").innerHTML =
    renderSidebar(activeBrand, "Desktop", ctx, activeChannel);
  document.getElementById("sideMenuMobile").innerHTML  =
    renderSidebar(activeBrand, "Mobile",  ctx, activeChannel);

  attachSidebarToggle("Desktop");
  attachSidebarToggle("Mobile");

  updateSidebarClock();
  setInterval(updateSidebarClock, 1000);

  await loadProfile();
}

init();