const fs = require('fs');

const backupPath = 'dist/assets/index-D9sWWWv_.js.bak-before-owner-mode-fix';
const filePath = 'dist/assets/index-D9sWWWv_.js';

// Copy clean backup to filePath first to ensure 100% idempotency and prevent recursive/duplicate inserts
if (!fs.existsSync(backupPath)) {
  console.error(`Backup file not found at ${backupPath}! Cannot continue.`);
  process.exit(1);
}
fs.copyFileSync(backupPath, filePath);

let content = fs.readFileSync(filePath, 'utf8');

const replacements = [
  // 1. Update initial tenant array lists with expired_at
  {
    target: '[{id:"sa-admin",name:"Super Admin Pemilik Web",email:"admin@mikrobil.com",password:"admin",phone:"085299887766",location:"Kantor Pusat MikRobiL",plan:"Owner",routers:999,status:"active",joined:"2026-01-01"},{id:"TNT-001",name:"DELITUA NET (Delvi)",email:"delvi24102000@gmail.com",password:"password",phone:"081234567890",location:"Delitua, Sumut",plan:"Platinum",routers:3,status:"active",joined:"2026-01-05"},{id:"TNT-002",name:"Medan Digital Wi-Fi",email:"medan_admin@gmail.com",password:"password",phone:"082345678901",location:"Medan, Sumut",plan:"Gold",routers:2,status:"active",joined:"2026-02-14"},{id:"TNT-003",name:"Binjai Cyber Speed",email:"bcs_info@yahoo.com",password:"password",phone:"083456789012",location:"Binjai, Sumut",plan:"Silver",routers:1,status:"active",joined:"2026-03-20"},{id:"TNT-004",name:"Kios Kampung Net",email:"kampungnet@gmail.com",password:"password",phone:"084567890123",location:"Deli Serdang",plan:"Bronze",routers:1,status:"suspended",joined:"2026-04-01"}]',
    replacement: '[{id:"sa-admin",name:"Super Admin Pemilik Web",email:"admin@mikrobil.com",password:"admin",phone:"085299887766",location:"Kantor Pusat MikRobiL",plan:"Owner",routers:999,status:"active",joined:"2026-01-01",expired_at:"2099-12-31"},{id:"TNT-001",name:"DELITUA NET (Delvi)",email:"delvi24102000@gmail.com",password:"password",phone:"081234567890",location:"Delitua, Sumut",plan:"Platinum",routers:3,status:"active",joined:"2026-01-05",expired_at:"2027-01-05"},{id:"TNT-002",name:"Medan Digital Wi-Fi",email:"medan_admin@gmail.com",password:"password",phone:"082345678901",location:"Medan, Sumut",plan:"Gold",routers:2,status:"active",joined:"2026-02-14",expired_at:"2026-12-14"},{id:"TNT-003",name:"Binjai Cyber Speed",email:"bcs_info@yahoo.com",password:"password",phone:"083456789012",location:"Binjai, Sumut",plan:"Silver",routers:1,status:"active",joined:"2026-03-20",expired_at:"2026-09-20"},{id:"TNT-004",name:"Kios Kampung Net",email:"kampungnet@gmail.com",password:"password",phone:"084567890123",location:"Deli Serdang",plan:"Bronze",routers:1,status:"suspended",joined:"2026-04-01",expired_at:"2026-05-01"}]'
  },
  {
    target: 'S=[{id:"sa-admin",name:"Super Admin Pemilik Web",email:"admin@mikrobil.com",password:"admin",phone:"085299887766",location:"Kantor Pusat MikRobiL",plan:"Owner",routers:999,status:"active",joined:"2026-01-01"}]',
    replacement: 'S=[{id:"sa-admin",name:"Super Admin Pemilik Web",email:"admin@mikrobil.com",password:"admin",phone:"085299887766",location:"Kantor Pusat MikRobiL",plan:"Owner",routers:999,status:"active",joined:"2026-01-01",expired_at:"2099-12-31"}]'
  },
  {
    target: 'M=[{id:"sa-admin",name:"Super Admin Pemilik Web",email:"admin@mikrobil.com",password:"admin",phone:"085299887766",location:"Kantor Pusat MikRobiL",plan:"Owner",routers:999,status:"active",joined:"2026-01-01"}]',
    replacement: 'M=[{id:"sa-admin",name:"Super Admin Pemilik Web",email:"admin@mikrobil.com",password:"admin",phone:"085299887766",location:"Kantor Pusat MikRobiL",plan:"Owner",routers:999,status:"active",joined:"2026-01-01",expired_at:"2099-12-31"}]'
  },

  // 2. Add expired Edit state values in SaaS component
  {
    target: '[Ns,Vl]=C.useState(!1),[Cr,wa]=C.useState({name:"",email:"",location:"",plan:"Bronze"}),[at,At]=C.useState(null)',
    replacement: '[Ns,Vl]=C.useState(!1),[Cr,wa]=C.useState({name:"",email:"",location:"",plan:"Bronze",expired_at:new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]}),[at,At]=C.useState(null),[expiredEditId,setExpiredEditId]=C.useState(null),[expiredEditDate,setExpiredEditDate]=C.useState(""),[saasWaBotEnabled,setSaasWaBotEnabled]=C.useState(()=>ze("saas_wa_bot_enabled",!1)),[saasWaBotToken,setSaasWaBotToken]=C.useState(()=>ze("saas_wa_bot_token","")),[saasWaBotPhone,setSaasWaBotPhone]=C.useState(()=>ze("saas_wa_bot_phone","")),[saasTeleBotEnabled,setSaasTeleBotEnabled]=C.useState(()=>ze("saas_tele_bot_enabled",!1)),[saasTeleBotToken,setSaasTeleBotToken]=C.useState(()=>ze("saas_tele_bot_token","")),[saasTeleBotChatId,setSaasTeleBotChatId]=C.useState(()=>ze("saas_tele_bot_chat_id",""))'
  },

  // 3. Reset form with expired_at default value too
  {
    target: 'wa({name:"",email:"",location:"",plan:"Bronze"}),Vl(!1);',
    replacement: 'wa({name:"",email:"",location:"",plan:"Bronze",expired_at:new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]}),Vl(!1);'
  },

  // 4. Update the 3 dynamic/manual tenant creators to include expired_at field
  {
    target: 'O={id:`TNT-${Date.now()}`,name:y.split("@")[0].toUpperCase()+" NET",email:y,password:_,phone:"081234567890",location:"Indonesia",plan:"Gold",routers:1,status:"active",joined:new Date().toISOString().split("T")[0]}',
    replacement: 'O={id:`TNT-${Date.now()}`,name:y.split("@")[0].toUpperCase()+" NET",email:y,password:_,phone:"081234567890",location:"Indonesia",plan:"Gold",routers:1,status:"active",joined:new Date().toISOString().split("T")[0],expired_at:new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]}'
  },
  {
    target: 'F={id:`TNT-${Date.now()}`,name:r.trim(),email:O,password:d,phone:l.trim(),location:"Indonesia",plan:I,routers:0,status:"pending_payment",joined:new Date().toISOString().split("T")[0]}',
    replacement: 'F={id:`TNT-${Date.now()}`,name:r.trim(),email:O,password:d,phone:l.trim(),location:"Indonesia",plan:I,routers:0,status:"pending_payment",joined:new Date().toISOString().split("T")[0],expired_at:new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]}'
  },
  {
    target: 'const $={id:`TNT-${String(tr.length+1).padStart(3,"0")}`,name:Cr.name,email:Cr.email,location:Cr.location||"Indonesia",plan:Cr.plan,routers:1,status:"active",joined:new Date().toISOString().split("T")[0]};',
    replacement: 'const $={id:`TNT-${String(tr.length+1).padStart(3,"0")}`,name:Cr.name,email:Cr.email,location:Cr.location||"Indonesia",plan:Cr.plan,routers:1,status:"active",joined:new Date().toISOString().split("T")[0],expired_at:Cr.expired_at||new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]};'
  },

  // 5. Add input field to register operator form
  {
    target: 'a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Paket Langganan"}),a.jsx("select",{value:Cr.plan,onChange:E=>wa({...Cr,plan:E.target.value}),className:"block w-full px-3 py-2 bg-[#05060b] border border-purple-950/40 rounded-xl text-gray-200 focus:outline-none cursor-pointer",children:Tn.map(E=>a.jsxs("option",{value:E.name,children:[E.name," Plan (Rp ",Number(E.price).toLocaleString(),"/bln)"]},E.id))})]})',
    replacement: 'a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Paket Langganan"}),a.jsx("select",{value:Cr.plan,onChange:E=>wa({...Cr,plan:E.target.value}),className:"block w-full px-3 py-2 bg-[#05060b] border border-purple-950/40 rounded-xl text-gray-200 focus:outline-none cursor-pointer",children:Tn.map(E=>a.jsxs("option",{value:E.name,children:[E.name," Plan (Rp ",Number(E.price).toLocaleString(),"/bln)"]},E.id))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Masa Aktif / Tanggal Kadaluarsa"}),a.jsx("input",{type:"date",required:!0,value:Cr.expired_at,onChange:E=>wa({...Cr,expired_at:E.target.value}),className:"block w-full px-3 py-2 bg-[#05060b] border border-purple-950/40 rounded-xl text-gray-200 focus:outline-none cursor-pointer"})]})'
  },

  // 6. Add "Masa Aktif" table header
  {
    target: 'a.jsx("th",{className:"p-3",children:"ID Tenant"}),a.jsx("th",{className:"p-3",children:"Operator"}),a.jsx("th",{className:"p-3",children:"Kontak Email"}),a.jsx("th",{className:"p-3",children:"Lokasi"}),a.jsx("th",{className:"p-3",children:"Tier Paket"}),a.jsx("th",{className:"p-3",children:"Connected Router"}),a.jsx("th",{className:"p-3",children:"Status"}),a.jsx("th",{className:"p-3 text-center",children:"Aksi"})',
    replacement: 'a.jsx("th",{className:"p-3",children:"ID Tenant"}),a.jsx("th",{className:"p-3",children:"Operator"}),a.jsx("th",{className:"p-3",children:"Kontak Email"}),a.jsx("th",{className:"p-3",children:"Lokasi"}),a.jsx("th",{className:"p-3",children:"Tier Paket"}),a.jsx("th",{className:"p-3",children:"Connected Router"}),a.jsx("th",{className:"p-3",children:"Masa Aktif"}),a.jsx("th",{className:"p-3",children:"Status"}),a.jsx("th",{className:"p-3 text-center",children:"Aksi"})'
  },

  // 7. Render Masa Aktif value & ✏️ button on table row, with dynamic active status expiration check
  {
    target: 'a.jsxs("td",{className:"p-3 font-semibold font-mono text-center text-purple-300",children:[E.routers," Router"]}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`px-2 py-0.5 rounded-full text-[9px] font-bold \${E.status==="active"?"bg-[#064e3b] text-emerald-400":($=E.status)!=null&&$.startsWith("pending")?"bg-amber-950 text-amber-400 animate-pulse":"bg-red-950 text-red-400"}\`,children:E.status==="pending_payment"?"BELUM BAYAR":E.status==="pending_approval"?"MENUNGGU ACC":E.status.toUpperCase()})})',
    replacement: 'a.jsxs("td",{className:"p-3 font-semibold font-mono text-center text-purple-300",children:[E.routers," Router"]}),a.jsxs("td",{className:"p-3 font-semibold font-mono text-gray-300 flex items-center justify-center gap-1.5",children:[a.jsx("span",{children:E.expired_at || (E.joined ? new Date(new Date(E.joined).getTime() + 365*24*60*60*1000).toISOString().split("T")[0] : "2026-12-31")}),a.jsx("button",{type:"button",onClick:()=>{setExpiredEditId(E.id);setExpiredEditDate(E.expired_at || (E.joined ? new Date(new Date(E.joined).getTime() + 365*24*60*60*1000).toISOString().split("T")[0] : "2026-12-31"))},className:"text-purple-400 hover:text-purple-300 cursor-pointer p-0.5",title:"Ubah Masa Aktif",children:a.jsx("span",{children:"✏️"})})]}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`px-2 py-0.5 rounded-full text-[9px] font-bold \${E.expired_at&&E.expired_at<new Date().toISOString().split("T")[0]?"bg-red-950 text-red-400":E.status==="active"?"bg-[#064e3b] text-emerald-400":($=E.status)!=null&&$.startsWith("pending")?"bg-amber-950 text-amber-400 animate-pulse":"bg-red-950 text-red-400"}\`,children:E.expired_at&&E.expired_at<new Date().toISOString().split("T")[0]?"KADALUARSA":E.status==="pending_payment"?"BELUM BAYAR":E.status==="pending_approval"?"MENUNGGU ACC":E.status.toUpperCase()})})'
  },

  // 8. Append expired edit modal at the end of saas-tenants section
  {
    target: 'a.jsx("button",{type:"button",onClick:()=>N(E.id),className:"p-1 text-gray-500 hover:text-red-400 transition-colors cursor-pointer",title:"Hapus Tenant",children:a.jsx(mr,{className:"w-4 h-4"})})]})]},E.id)})})]})_2', // wait, target string is very specific
    target: 'a.jsx("button",{type:"button",onClick:()=>N(E.id),className:"p-1 text-gray-500 hover:text-red-400 transition-colors cursor-pointer",title:"Hapus Tenant",children:a.jsx(mr,{className:"w-4 h-4"})})]})]},E.id)})})]})})})]}),Nn==="saas-billing"',
    replacement: 'a.jsx("button",{type:"button",onClick:()=>N(E.id),className:"p-1 text-gray-500 hover:text-red-400 transition-colors cursor-pointer",title:"Hapus Tenant",children:a.jsx(mr,{className:"w-4 h-4"})})]})]},E.id)})})]})})}),expiredEditId&&a.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4 font-sans",children:a.jsxs("div",{className:"w-full max-w-sm bg-[#0a0b14] border border-purple-900/40 p-6 rounded-2xl shadow-2xl space-y-4 text-xs text-gray-300",children:[a.jsxs("div",{className:"flex justify-between items-center border-b border-purple-950/20 pb-3",children:[a.jsx("h3",{className:"text-sm font-black text-white uppercase tracking-wider",children:"✏️ Ubah Masa Aktif Tenant"}),a.jsx("button",{type:"button",onClick:()=>setExpiredEditId(null),className:"text-gray-400 hover:text-white cursor-pointer font-bold text-base",children:"✕"})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-gray-400 block",children:"Operator / Tenant ID:"}),a.jsx("span",{className:"text-white font-bold block",children:(()=> {const tnt=tr.find(x=>x.id===expiredEditId);return tnt?tnt.name+" ("+tnt.id+")" : ""})()})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Tanggal Kadaluarsa Baru"}),a.jsx("input",{type:"date",value:expiredEditDate,onChange:e=>setExpiredEditDate(e.target.value),className:"block w-full px-3 py-2 bg-[#05060b] border border-purple-950/40 rounded-xl text-gray-200 focus:outline-none cursor-pointer"})]}),a.jsxs("div",{className:"flex justify-end gap-3 pt-3 border-t border-purple-950/20",children:[a.jsx("button",{type:"button",onClick:()=>setExpiredEditId(null),className:"px-4 py-2 font-semibold border border-purple-950/40 rounded-xl text-gray-400 cursor-pointer",children:"Batal"}),a.jsx("button",{type:"button",onClick:()=>{const updated=tr.map(x=>x.id===expiredEditId?Object.assign({},x,{expired_at:expiredEditDate}):x);Hn(updated);setExpiredEditId(null);const editTnt=tr.find(x=>x.id===expiredEditId);const logEntry={id:"saas-act-"+Date.now(),timestamp:new Date().toLocaleString("id-ID"),email:editTnt?editTnt.email:"system",name:editTnt?editTnt.name:"System",action:"Ubah Masa Aktif",details:"Masa aktif diubah secara manual oleh Super Admin menjadi "+expiredEditDate,ip:"127.0.0.1"};No(logs=>[logEntry,...logs]);if(editTnt){typeof window.sendSaaSSystemNotification==="function"&&window.sendSaaSSystemNotification(`🔔 *PERUBAHAN MASA AKTIF TENANT*\\n\\nSuper Admin telah mengubah tanggal kadaluarsa tenant:\\n- *Nama*: ${editTnt.name}\\n- *Email*: ${editTnt.email}\\n- *Masa Aktif Baru*: ${expiredEditDate}`)}},className:"px-5 py-2 font-bold bg-purple-700 hover:bg-purple-600 text-white rounded-xl shadow-md cursor-pointer",children:"Simpan"})]})]})})]}),Nn==="saas-billing"'
  },

  // 9. Force pending screen if account's expired_at has passed
  {
    target: 'const Hi=tr.find(p=>p.email.trim().toLowerCase()===e.trim().toLowerCase());if(Hi&&Hi.status!=="active"&&e.toLowerCase()!=="admin@mikrobil.com"&&e.toLowerCase()!=="admin@mikrobil.net")',
    replacement: 'const Hi=tr.find(p=>p.email.trim().toLowerCase()===e.trim().toLowerCase());if(Hi&&(Hi.status!=="active"||(Hi.expired_at&&Hi.expired_at<new Date().toISOString().split("T")[0]))&&e.toLowerCase()!=="admin@mikrobil.com"&&e.toLowerCase()!=="admin@mikrobil.net")'
  },

  // 10. Update billing success handler to set/extend expiration to 30 days
  {
    target: 'const p=()=>{const D=tr.map($=>$.email.trim().toLowerCase()===e.trim().toLowerCase()?{...$,status:"active"}:$);Hn(D);',
    replacement: 'const p=()=>{const D=tr.map($=>$.email.trim().toLowerCase()===e.trim().toLowerCase()?{...$,status:"active",expired_at:new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]}:$);Hn(D);'
  },

  // 11. Custom pending screen status if account is expired
  {
    target: 'a.jsx("span",{className:"text-amber-400 font-bold",children:Hi.status==="pending_payment"?"Menunggu Pembayaran":"Menunggu Approval Admin"})',
    replacement: 'a.jsx("span",{className:"text-amber-400 font-bold",children:(Hi.expired_at&&Hi.expired_at<new Date().toISOString().split("T")[0])?"Masa Aktif Berakhir":Hi.status==="pending_payment"?"Menunggu Pembayaran":"Menunggu Approval Admin"})'
  },

  // 12. Display expiration date inside the pending approval screen
  {
    target: 'a.jsxs("div",{children:[a.jsx("span",{className:"text-gray-400",children:"Tanggal Daftar:"})," ",a.jsx("span",{className:"text-white font-mono",children:Hi.joined||"-"})]})',
    replacement: 'a.jsxs("div",{children:[a.jsx("span",{className:"text-gray-400",children:"Tanggal Daftar:"})," ",a.jsx("span",{className:"text-white font-mono",children:Hi.joined||"-"})]}),Hi.expired_at&&a.jsxs("div",{children:[a.jsx("span",{className:"text-rose-400",children:"Masa Aktif Habis:"})," ",a.jsx("span",{className:"text-rose-300 font-mono font-bold",children:Hi.expired_at})]})'
  },

  // 13. Display remaining active days on tenant dashboard sidebar
  {
    target: 'e.trim().toLowerCase()==="admin@mikrobil.com"?a.jsx("span",{className:"text-[10px] text-purple-400 block font-mono font-bold",children:"ROLE: SUPER ADMIN"}):a.jsx("span",{className:"text-[10px] text-emerald-400 block font-mono font-bold",children:"ROLE: TENANT ADMIN"})',
    replacement: 'e.trim().toLowerCase()==="admin@mikrobil.com"?a.jsx("span",{className:"text-[10px] text-purple-400 block font-mono font-bold",children:"ROLE: SUPER ADMIN"}):a.jsxs("div",{children:[a.jsx("span",{className:"text-[10px] text-emerald-400 block font-mono font-bold",children:"ROLE: TENANT ADMIN"}),(() => { const curT = tr.find(x => x.email.trim().toLowerCase() === e.trim().toLowerCase()); return curT && curT.expired_at ? a.jsx("span",{className:"text-[9px] text-gray-400 block mt-0.5",children:"Masa Aktif: " + curT.expired_at}) : null; })()]})'
  },

  // 14. Update operator approval (ACC Manual) to set expired_at if it is not set
  {
    target: 'const z=tr.map(X=>X.id===E.id?{...X,status:"active"}:X);Hn(z);',
    replacement: 'const z=tr.map(X=>X.id===E.id?{...X,status:"active",expired_at:X.expired_at||new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]}:X);Hn(z);const approvedTenant=tr.find(X=>X.id===E.id);if(approvedTenant){const nextExp=approvedTenant.expired_at||new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0];typeof window.sendSaaSSystemNotification==="function"&&window.sendSaaSSystemNotification(`🔔 *PERSETUJUAN MANUAL TENANT (ACC)*\\n\\nSuper Admin telah menyetujui & mengaktifkan tenant secara manual:\\n- *Nama*: ${approvedTenant.name}\\n- *Email*: ${approvedTenant.email}\\n- *Paket*: ${approvedTenant.plan} Plan\\n- *Status Akun*: AKTIF (Sewa s.d ${nextExp})`)}'
  },

  // 15. Enhance KI payment callback function to also activate / extend SaaS operators
  {
    target: 'W(E=>[...D,...E]),alert(`Simulasi Callback Tripay [${b.toUpperCase()}] Berhasil Diproses!`)},',
    replacement: 'const saasTenant=tr.find(x=>N.description.toLowerCase().includes(x.email.trim().toLowerCase())||N.description.toLowerCase().includes(x.name.trim().toLowerCase()));if(saasTenant){let curExp=saasTenant.expired_at?new Date(saasTenant.expired_at).getTime():Date.now();if(isNaN(curExp)||curExp<Date.now())curExp=Date.now();const nextExp=new Date(curExp+30*24*60*60*1e3).toISOString().split("T")[0];Hn(z=>z.map(x=>x.id===saasTenant.id?{...x,status:"active",expired_at:nextExp}:x));D.push({id:`saas-act-${Date.now()}`,timestamp:new Date().toLocaleTimeString(),source:"System",type:"success",message:`SaaS Tenant ${saasTenant.name} (${saasTenant.email}) berhasil diaktivasi/diperpanjang s.d \${nextExp}!`});typeof window.sendSaaSSystemNotification==="function"&&window.sendSaaSSystemNotification(`🔔 *PEMBAYARAN SAAS BERHASIL (WEBHOOK)*\\n\\nPembayaran iuran / sewa lisensi SaaS telah diterima otomatis:\\n- *Nama Tenant*: ${saasTenant.name}\\n- *Email*: ${saasTenant.email}\\n- *Keterangan*: ${N.description}\\n- *Jumlah*: Rp ${Number(N.amount).toLocaleString("id-ID")}\\n- *Metode*: ${N.paymentMethod}\\n- *Status Akun*: AKTIF (Sewa Diperpanjang s.d ${nextExp})`)}W(E=>[...D,...E]),alert(`Simulasi Callback Tripay [${b.toUpperCase()}] Berhasil Diproses!`)},'
  },

  // 16. Convert static invoice amount dropdown to a flexible input field that auto-fills based on selected tenant's plan price
  {
    target: 'a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Pilih Tenant Mitra (Email)"}),a.jsx("select",{id:"saas-inv-email",className:"block w-full px-3 py-2 bg-[#05060b] border border-purple-950/40 rounded-xl focus:outline-none text-gray-300",children:tr.filter(E=>E.id!=="sa-admin").map(E=>a.jsxs("option",{value:E.email,children:[E.name," (",E.email,")"]},E.id))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Jumlah Tagihan (Sewa/Top-Up)"}),a.jsxs("select",{id:"saas-inv-amount",className:"block w-full px-3 py-2 bg-[#05060b] border border-purple-950/40 rounded-xl focus:outline-none text-gray-300",children:[a.jsx("option",{value:"50000",children:"Rp 50.000"}),a.jsx("option",{value:"100000",children:"Rp 100.000"}),a.jsx("option",{value:"150000",children:"Rp 150.000"}),a.jsx("option",{value:"250000",children:"Rp 250.000"}),a.jsx("option",{value:"500000",children:"Rp 500.000"})]})]})',
    replacement: 'a.jsx(a.Fragment,{children:(() => { const getPrice = (em) => { const tnt = tr.find(x => x.email === em); if (!tnt) return 50000; const p = (tnt.plan || "").toLowerCase(); const matched = (Tn || []).find(x => x.id === p || x.name.toLowerCase() === p); if (matched) return matched.price; if (p.includes("bronze")) return 50000; if (p.includes("silver")) return 100000; if (p.includes("gold")) return 175000; if (p.includes("platinum")) return 250000; return 50000; }; const initTenant = tr.filter(E => E.id !== "sa-admin")[0]; const initPrice = initTenant ? getPrice(initTenant.email) : 50000; return [a.jsxs("div", { children: [a.jsx("label", { className: "block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2", children: "Pilih Tenant Mitra (Email)" }), a.jsx("select", { id: "saas-inv-email", onChange: (e) => { const amtInput = document.getElementById("saas-inv-amount"); if (amtInput) amtInput.value = getPrice(e.target.value); }, className: "block w-full px-3 py-2 bg-[#05060b] border border-purple-950/40 rounded-xl focus:outline-none text-gray-300", children: tr.filter(E => E.id !== "sa-admin").length === 0 ? [a.jsx("option", { value: "", disabled: true, children: "Belum ada tenant terdaftar" })] : tr.filter(E => E.id !== "sa-admin").map(E => a.jsxs("option", { value: E.email, children: [E.name, " (", E.email, ")"] }, E.id)) }) ] }, "col-email"), a.jsxs("div", { children: [a.jsx("label", { className: "block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2", children: "Jumlah Tagihan (Sewa/Top-Up)" }), a.jsx("input", { type: "number", id: "saas-inv-amount", defaultValue: initPrice, className: "block w-full px-3 py-2 bg-[#05060b] border border-purple-950/40 rounded-xl focus:outline-none text-gray-300" }) ] }, "col-amount")]; })()})'
  },

  // 17. Add Aksi column header to SaaS Invoices Table
  {
    target: 'children:[a.jsx("th",{className:"p-3",children:"ID Invoice"}),a.jsx("th",{className:"p-3",children:"Keterangan Tagihan"}),a.jsx("th",{className:"p-3",children:"Jumlah"}),a.jsx("th",{className:"p-3",children:"Metode Pembayaran"}),a.jsx("th",{className:"p-3",children:"Tanggal Terbit"}),a.jsx("th",{className:"p-3",children:"Status"})]',
    replacement: 'children:[a.jsx("th",{className:"p-3",children:"ID Invoice"}),a.jsx("th",{className:"p-3",children:"Keterangan Tagihan"}),a.jsx("th",{className:"p-3",children:"Jumlah"}),a.jsx("th",{className:"p-3",children:"Metode Pembayaran"}),a.jsx("th",{className:"p-3",children:"Tanggal Terbit"}),a.jsx("th",{className:"p-3",children:"Status"}),a.jsx("th",{className:"p-3 text-center",children:"Aksi"})]'
  },

  // 18. Add Action td with "Lunas Manual" and "Hapus" buttons to SaaS Invoices Table Rows
  {
    target: 'children:[a.jsx("td",{className:"p-3 font-mono font-bold text-gray-400",children:E.code}),a.jsx("td",{className:"p-3 text-white font-semibold",children:E.description}),a.jsxs("td",{className:"p-3 font-bold text-purple-400",children:["Rp ",E.amount.toLocaleString()]}),a.jsx("td",{className:"p-3 text-gray-400",children:E.paymentMethod}),a.jsx("td",{className:"p-3 font-mono text-gray-500 text-[10px]",children:E.date}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`px-2 py-0.5 rounded-full text-[9px] font-bold \${E.status==="success"?"bg-[#064e3b] text-emerald-400":"bg-[#78350f] text-amber-400"}\`,children:E.status.toUpperCase()})})]',
    replacement: 'children:[a.jsx("td",{className:"p-3 font-mono font-bold text-gray-400",children:E.code}),a.jsx("td",{className:"p-3 text-white font-semibold",children:E.description}),a.jsxs("td",{className:"p-3 font-bold text-purple-400",children:["Rp ",E.amount.toLocaleString()]}),a.jsx("td",{className:"p-3 text-gray-400",children:E.paymentMethod}),a.jsx("td",{className:"p-3 font-mono text-gray-500 text-[10px]",children:E.date}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`px-2 py-0.5 rounded-full text-[9px] font-bold \${E.status==="success"?"bg-[#064e3b] text-emerald-400":"bg-[#78350f] text-amber-400"}\`,children:E.status.toUpperCase()})}),a.jsx("td",{className:"p-3 text-center",children:a.jsxs("div",{className:"flex items-center justify-center gap-1.5",children:[E.status!=="success"&&a.jsx("button",{type:"button",onClick:()=>{KI(E.id,"success")},className:"px-2 py-0.5 bg-emerald-950/80 hover:bg-emerald-900 border border-emerald-800/40 text-emerald-400 font-semibold rounded text-[10px] cursor-pointer transition-colors",children:"Lunas"}),a.jsx("button",{type:"button",onClick:()=>{G(prev=>prev.filter(x=>x.id!==E.id))},className:"px-2 py-0.5 bg-rose-950/80 hover:bg-rose-900 border border-rose-900/40 text-rose-400 font-semibold rounded text-[10px] cursor-pointer transition-colors",children:"Hapus"})]})})]'
  },

  // 19. Define PaymentSelector component for selecting payment method on activation screen
  {
    target: 'function qle({userEmail:e,onLogout:t}){',
    replacement: `function PaymentSelector({onPay, onContact, planFee}) {
  const getSuperAdminTripayKey = () => {
    const keys = [
      "mikrobil_real_admin@mikrobil.com_tripay_api_key",
      "mikrobil_real_admin@mikrobil.net_tripay_api_key"
    ];
    for (const k of keys) {
      const val = localStorage.getItem(k);
      if (val) {
        try {
          const parsed = JSON.parse(val);
          if (parsed && parsed.trim() !== "" && !parsed.includes("DEV_TRIPAY_API_KEY")) return parsed;
        } catch {
          if (val.trim() !== "" && val !== '""' && !val.includes("DEV_TRIPAY_API_KEY")) return val;
        }
      }
    }
    return "";
  };
  const getSuperAdminTripayMerchant = () => {
    const keys = [
      "mikrobil_real_admin@mikrobil.com_tripay_merchant_code",
      "mikrobil_real_admin@mikrobil.net_tripay_merchant_code"
    ];
    for (const k of keys) {
      const val = localStorage.getItem(k);
      if (val) {
        try {
          const parsed = JSON.parse(val);
          if (parsed && parsed.trim() !== "" && parsed !== "T19920") return parsed;
        } catch {
          if (val.trim() !== "" && val !== '""' && val !== "T19920") return val;
        }
      }
    }
    return "";
  };

  const tripayKey = getSuperAdminTripayKey();
  const tripayMerchant = getSuperAdminTripayMerchant();
  const isConfigured = !!tripayKey && !!tripayMerchant;

  const [selectedMethod, setSelectedMethod] = C.useState(isConfigured ? "tripay" : "manual");

  return a.jsxs("div", {
    className: "p-5 bg-[#0a0f1d]/50 border border-emerald-950/40 rounded-2xl space-y-4 text-left w-full max-w-lg mx-auto",
    children: [
      a.jsxs("div", {
        className: "space-y-1.5",
        children: [
          a.jsx("label", {
            className: "block text-xs font-bold text-gray-400 uppercase tracking-wider",
            children: "Pilih Metode Aktivasi Akun:"
          }),
          a.jsxs("select", {
            value: selectedMethod,
            onChange: (e) => setSelectedMethod(e.target.value),
            className: "block w-full px-3 py-2.5 bg-[#070b14] border border-emerald-950/60 rounded-xl text-gray-200 focus:outline-none cursor-pointer text-xs font-semibold",
            children: [
              isConfigured && a.jsx("option", { value: "tripay", children: "Metode 1: Otomatis (QRIS / Virtual Account / Alfamart)" }),
              a.jsx("option", { value: "manual", children: "Metode 2: Konfirmasi Manual (Hubungi Admin / Transfer)" })
            ].filter(Boolean)
          })
        ]
      }),
      selectedMethod === "tripay" && isConfigured ? (
        a.jsxs("div", {
          className: "p-4 bg-emerald-950/10 border border-emerald-850/20 rounded-xl space-y-3",
          children: [
            a.jsxs("div", {
              className: "flex items-center gap-2",
              children: [
                a.jsx("div", {
                  className: "p-1.5 bg-emerald-950 border border-emerald-800 rounded-lg text-emerald-400",
                  children: a.jsx(qb, { className: "w-4 h-4" })
                }),
                a.jsx("span", {
                  className: "text-xs font-bold text-white",
                  children: "Pembayaran Otomatis (Instan)"
                })
              ]
            }),
            a.jsx("p", {
              className: "text-[11px] text-gray-400 leading-relaxed",
              children: "Pembayaran langsung menggunakan QRIS, Virtual Account (BCA, Mandiri, BNI, BRI), atau Alfamart. Akun SaaS Anda akan aktif secara instan & otomatis setelah pembayaran berhasil."
            }),
            a.jsxs("button", {
              onClick: onPay,
              className: "w-full py-2.5 px-4 bg-emerald-600 hover:bg-emerald-500 active:bg-emerald-700 text-white font-bold rounded-xl text-xs transition-all flex items-center justify-center gap-1.5 cursor-pointer",
              children: [a.jsx(en, { className: "w-3.5 h-3.5" }), "Bayar Iuran Sekarang"]
            })
          ]
        })
      ) : (
        a.jsxs("div", {
          className: "p-4 bg-blue-950/10 border border-blue-900/20 rounded-xl space-y-3",
          children: [
            a.jsxs("div", {
              className: "flex items-center gap-2",
              children: [
                a.jsx("div", {
                  className: "p-1.5 bg-blue-950 border border-blue-900 rounded-lg text-blue-400",
                  children: a.jsx(kr, { className: "w-4 h-4" })
                }),
                a.jsx("span", {
                  className: "text-xs font-bold text-white",
                  children: "Aktivasi / Konfirmasi Manual"
                })
              ]
            }),
            !isConfigured && a.jsx("p", {
              className: "text-[11px] text-amber-400 font-medium leading-relaxed mb-1",
              children: "⚠️ Catatan: Pembayaran otomatis (QRIS / VA) belum dikonfigurasi oleh Pemilik Web / Admin Utama."
            }),
            a.jsx("p", {
              className: "text-[11px] text-gray-400 leading-relaxed",
              children: "Silakan hubungi Pemilik Web/Admin Utama untuk persetujuan akun manual, atau transfer manual tanpa payment gateway. Admin dapat langsung menyetujui di panel pusat."
            }),
            a.jsxs("button", {
              onClick: onContact,
              className: "w-full py-2.5 px-4 bg-blue-600 hover:bg-blue-500 active:bg-blue-700 text-white font-bold rounded-xl text-xs transition-all flex items-center justify-center gap-1.5 cursor-pointer",
              children: [a.jsx(tl, { className: "w-3.5 h-3.5" }), "Hubungi Admin Web"]
            })
          ]
        })
      )
    ]
  });
}
function qle({userEmail:e,onLogout:t}){`
  },

  // 20. Replace Pilih Metode Aktivasi Akun details with PaymentSelector
  {
    target: 'a.jsxs("div",{className:"mt-8 space-y-4",children:[a.jsx("h3",{className:"text-xs font-bold text-white uppercase tracking-wider border-b border-emerald-950/20 pb-2",children:"Pilih Metode Aktivasi Akun"}),a.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[a.jsxs("div",{className:"p-4 bg-emerald-950/10 border border-emerald-800/20 hover:border-emerald-500/40 rounded-2xl transition-all flex flex-col justify-between",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"p-1.5 bg-emerald-950 border border-emerald-800 rounded-lg text-emerald-400",children:a.jsx(qb,{className:"w-4 h-4"})}),a.jsx("span",{className:"text-xs font-bold text-white",children:"Metode 1: Tripay Gateway"})]}),a.jsx("p",{className:"text-[10px] text-gray-400 mt-2 leading-relaxed",children:"Pembayaran langsung menggunakan QRIS, Virtual Account, atau Alfamart. Akun SaaS Anda akan aktif secara instan otomatis setelah bayar sukses."})]}),a.jsxs("button",{onClick:()=>ys(!0),className:"mt-4 w-full py-2.5 px-4 bg-emerald-600 hover:bg-emerald-500 active:bg-emerald-700 text-white font-bold rounded-xl text-xs transition-all flex items-center justify-center gap-1 cursor-pointer",children:[a.jsx(en,{className:"w-3.5 h-3.5"}),"Bayar Iuran Sekarang"]})]}),a.jsxs("div",{className:"p-4 bg-blue-950/10 border border-blue-900/20 hover:border-blue-500/40 rounded-2xl transition-all flex flex-col justify-between",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"p-1.5 bg-blue-950 border border-blue-900 rounded-lg text-blue-400",children:a.jsx(kr,{className:"w-4 h-4"})}),a.jsx("span",{className:"text-xs font-bold text-white",children:"Metode 2: ACC Manual Admin"})]}),a.jsx("p",{className:"text-[10px] text-gray-400 mt-2 leading-relaxed",children:"Hubungi Pemilik Web/Admin Utama untuk persetujuan akun manual tanpa transfer payment gateway. Admin dapat langsung menyetujui di panel pusat."})]}),a.jsxs("button",{onClick:b,className:"mt-4 w-full py-2.5 px-4 bg-blue-600 hover:bg-blue-500 active:bg-blue-700 text-white font-bold rounded-xl text-xs transition-all flex items-center justify-center gap-1 cursor-pointer",children:[a.jsx(tl,{className:"w-3.5 h-3.5"}),"Hubungi Admin Web"]})]})]})]})',
    replacement: 'a.jsxs("div",{className:"mt-8 space-y-4",children:[a.jsx("h3",{className:"text-xs font-bold text-white uppercase tracking-wider border-b border-emerald-950/20 pb-2",children:"Pilih Metode Aktivasi Akun"}),a.jsx(PaymentSelector,{onPay:()=>ys(!0),onContact:b,planFee:N})]})'
  },

  // 21. Rename modal header from Tripay Payment Gateway to Pembayaran Otomatis
  {
    target: 'a.jsxs("div",{className:"flex items-center gap-3 border-b border-emerald-950/30 pb-4",children:[a.jsx("div",{className:"p-2 bg-emerald-950 border border-emerald-800 rounded-xl text-emerald-400",children:a.jsx(en,{className:"w-5 h-5 animate-spin"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-bold text-white",children:"Tripay Payment Gateway"}),a.jsx("p",{className:"text-[10px] text-gray-500",children:"Simulasi Transaksi Realtime"})]})]})',
    replacement: 'a.jsxs("div",{className:"flex items-center gap-3 border-b border-emerald-950/30 pb-4",children:[a.jsx("div",{className:"p-2 bg-emerald-950 border border-emerald-800 rounded-xl text-emerald-400",children:a.jsx(en,{className:"w-5 h-5 animate-spin"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-bold text-white",children:"Pembayaran Otomatis"}),a.jsx("p",{className:"text-[10px] text-gray-500",children:"Konfirmasi Instan Terverifikasi"})]})]})'
  },

  // 22. Rename modal QRIS scan text
  {
    target: 'a.jsx("div",{className:"text-[10px] font-mono text-emerald-400 font-bold",children:"SCAN QRIS MIKROBIL SAAS"})',
    replacement: 'a.jsx("div",{className:"text-[10px] font-mono text-emerald-400 font-bold",children:"SCAN QRIS UNTUK PEMBAYARAN"})'
  },

  // 23. Rename modal billing bank account holder text
  {
    target: 'a.jsx("div",{className:"text-[9px] text-gray-500",children:"Nama Rekening: MIKROBIL SAAS BILLING"})',
    replacement: 'a.jsx("div",{className:"text-[9px] text-gray-500",children:"Nama Rekening: MIKROBIL SAAS"})'
  },

  // 24. Rename modal admin fee text
  {
    target: 'a.jsx("div",{className:"text-[9px] text-gray-500 mt-0.5",children:"Termasuk biaya admin gateway Rp 1.500"})',
    replacement: 'a.jsx("div",{className:"text-[9px] text-gray-500 mt-0.5",children:"Termasuk biaya admin Rp 1.500"})'
  },

  // 25. Rename modal button label
  {
    target: 'children:[a.jsx(Ks,{className:"w-4 h-4"}),"Simulasi Bayar Sukses"]})',
    replacement: 'children:[a.jsx(Ks,{className:"w-4 h-4"}),"Konfirmasi Pembayaran"]})'
  },

  // 26. Bypass landing page Demo Dashboard redirect to login and go straight to panel with admin@mikrobil.net
  {
    target: 'a.jsx("button",{onClick:()=>e("login"),className:"px-8 py-4 text-base font-semibold border border-emerald-800 rounded-2xl bg-emerald-950/10 hover:bg-emerald-950/40 transition-colors",children:"Demo Dashboard"})',
    replacement: 'a.jsx("button",{onClick:()=>e("demo_login"),className:"px-8 py-4 text-base font-semibold border border-emerald-800 rounded-2xl bg-emerald-950/10 hover:bg-emerald-950/40 transition-colors",children:"Demo Dashboard"})'
  },

  // 27. Catch demo_login inside Gme and auto-login with admin@mikrobil.net
  {
    target: 'e==="landing"&&a.jsx(Y9,{onNavigate:t})',
    replacement: 'e==="landing"&&a.jsx(Y9,{onNavigate:x=>x==="demo_login"?i("admin@mikrobil.net"):t(x)})'
  },

  // 28. Block deleting routers in demo mode
  {
    target: 'nI=p=>{confirm("Apakah Anda yakin ingin menghapus router ini dari database?")&&S(b=>b.filter(N=>N.id!==p))}',
    replacement: 'nI=p=>{if(e.trim().toLowerCase()==="admin@mikrobil.net"){alert("Mode Demo: Anda tidak diizinkan untuk menghapus Router MikroTik di akun uji coba ini.");return}confirm("Apakah Anda yakin ingin menghapus router ini dari database?")&&S(b=>b.filter(N=>N.id!==p))}'
  },

  // 29. Block adding/registering new customers in demo mode (onSubmit of registration form)
  {
    target: 'onSubmit:p=>{var $;if(p.preventDefault(),!ct.pppoeUsername){',
    replacement: 'onSubmit:p=>{if(p.preventDefault(),e.trim().toLowerCase()==="admin@mikrobil.net"){alert("Mode Demo: Anda tidak diizinkan untuk menambahkan pelanggan di akun uji coba ini.");return}var $;if(!ct.pppoeUsername){'
  },

  // 30. Block editing/updating existing customers in demo mode (onSubmit of edit form)
  {
    target: 'jt&&a.jsxs("form",{onSubmit:p=>{p.preventDefault(),K(N=>N.map(D=>D.id===jt.id?jt:D))',
    replacement: 'jt&&a.jsxs("form",{onSubmit:p=>{if(p.preventDefault(),e.trim().toLowerCase()==="admin@mikrobil.net"){alert("Mode Demo: Anda tidak diizinkan untuk mengubah data pelanggan di akun uji coba ini.");return}K(N=>N.map(D=>D.id===jt.id?jt:D))'
  },

  // 31. Block deleting customers in demo mode (onClick of delete button)
  {
    target: 'a.jsx("button",{onClick:()=>{if(confirm(`Apakah Anda yakin ingin menghapus pelanggan \'${b.name}\' dari database? Akun PPPoE di Mikrotik tidak akan terhapus secara otomatis.`)){K($=>$.filter(B=>B.id!==b.id));const E={id:`log-cust-del-${Date.now()}`,timestamp:new Date().toLocaleTimeString(),source:"System",type:"warning",message:`Pelanggan \'${b.name}\' dihapus dari database.`};W($=>[E,...$]),alert("Pelanggan berhasil dihapus.")}},className:"p-1.5 bg-red-950/40 hover:bg-red-900/50 border border-red-950/40 text-red-400 rounded-lg cursor-pointer transition-colors",title:"Hapus Pelanggan"',
    replacement: 'a.jsx("button",{onClick:()=>{if(e.trim().toLowerCase()==="admin@mikrobil.net"){alert("Mode Demo: Anda tidak diizinkan untuk menghapus pelanggan di akun uji coba ini.");return}if(confirm(`Apakah Anda yakin ingin menghapus pelanggan \'${b.name}\' dari database? Akun PPPoE di Mikrotik tidak akan terhapus secara otomatis.`)){K($=>$.filter(B=>B.id!==b.id));const E={id:`log-cust-del-${Date.now()}`,timestamp:new Date().toLocaleTimeString(),source:"System",type:"warning",message:`Pelanggan \'${b.name}\' dihapus dari database.`};W($=>[E,...$]),alert("Pelanggan berhasil dihapus.")}},className:"p-1.5 bg-red-950/40 hover:bg-red-900/50 border border-red-950/40 text-red-400 rounded-lg cursor-pointer transition-colors",title:"Hapus Pelanggan"'
  },

  // 32. Block deleting vouchers in demo mode
  {
    target: 'onConfirm:async()=>{if(O(B=>B.filter(z=>z.code!==p)),!E&&D)try{',
    replacement: 'onConfirm:async()=>{if(e.trim().toLowerCase()==="admin@mikrobil.net"){alert("Mode Demo: Anda tidak diizinkan untuk menghapus Voucher di akun uji coba ini.");return}if(O(B=>B.filter(z=>z.code!==p)),!E&&D)try{'
  },

  // 33. Block deleting agents in demo mode
  {
    target: 'cD=p=>{const b=j.find(N=>N.id===p);b&&confirm(`Apakah Anda yakin ingin menghapus Agen \'${b.name}\'? Seluruh data penjualan dan saldo akan diarsipkan.`)&&(P(N=>N.filter(D=>D.id!==p)),Pf===p&&Af(null),W(N=>[',
    replacement: 'cD=p=>{const b=j.find(N=>N.id===p);if(e.trim().toLowerCase()==="admin@mikrobil.net"){alert("Mode Demo: Anda tidak diizinkan untuk menghapus Agen di akun uji coba ini.");return}b&&confirm(`Apakah Anda yakin ingin menghapus Agen \'${b.name}\'? Seluruh data penjualan dan saldo akan diarsipkan.`)&&(P(N=>N.filter(D=>D.id!==p)),Pf===p&&Af(null),W(N=>['
  },

  // 34. Block adding agents in demo mode
  {
    target: 'onSubmit:p=>{p.preventDefault();const b=p.currentTarget.elements.namedItem("an").value',
    replacement: 'onSubmit:p=>{if(p.preventDefault(),e.trim().toLowerCase()==="admin@mikrobil.net"){alert("Mode Demo: Anda tidak diizinkan untuk mendaftarkan Agen baru di akun uji coba ini.");return}const b=p.currentTarget.elements.namedItem("an").value'
  },

  // 35. Add Description field to the Router add/edit form
  {
    target: 'a.jsx("div",{children:a.jsx("input",{type:"text",required:!0,placeholder:"Nama Router",value:we.name,onChange:p=>oi({...we,name:p.target.value}),className:"w-full px-4 py-3 bg-[#070c16]/80 border border-slate-700/60 rounded-xl text-gray-200 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 text-xs font-sans"})}),',
    replacement: 'a.jsx("div",{children:a.jsx("input",{type:"text",required:!0,placeholder:"Nama Router",value:we.name,onChange:p=>oi({...we,name:p.target.value}),className:"w-full px-4 py-3 bg-[#070c16]/80 border border-slate-700/60 rounded-xl text-gray-200 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 text-xs font-sans"})}),a.jsx("div",{children:a.jsx("input",{type:"text",placeholder:"Deskripsi Router (cth: Mikrotik hAP ac2 untuk hotspot cabang warkop)",value:we.description,onChange:p=>oi({...we,description:p.target.value}),className:"w-full px-4 py-3 bg-[#070c16]/80 border border-slate-700/60 rounded-xl text-gray-200 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 text-xs font-sans"})}),'
  },

  // 36. Block SaaS invoice generation when no SaaS tenants are registered
  {
    target: 'D=E=>{var Ce,Oe,Ue;E.preventDefault();const $=((Ce=document.getElementById("saas-inv-amount"))==null?void 0:Ce.value)||"100000",B=((Oe=document.getElementById("saas-inv-email"))==null?void 0:Oe.value)||"delvi24102000@gmail.com",z=((Ue=document.getElementById("saas-inv-method"))==null?void 0:Ue.value)||"Tripay QRIS",se=Math.floor(1e5+Math.random()*9e5),X={id:`inv-${Date.now()}`,code:`TRX-${se}`,description:`Top Up / Sewa Lisensi SaaS (${B})`,amount:Number($),paymentMethod:z,status:"pending",date:new Date().toISOString().replace("T"," ").substring(0,16)};G(bt=>[X,...bt]);const de={id:`saas-log-${Date.now()}`,timestamp:new Date().toLocaleTimeString(),source:"Tripay",type:"info",message:`Tagihan SaaS baru diterbitkan untuk ${B} sebesar Rp ${Number($).toLocaleString()}`};W(bt=>[de,...bt])};',
    replacement: 'D=E=>{var Ce,Oe,Ue;E.preventDefault();if(tr.filter(x=>x.id!=="sa-admin").length===0){alert("Gagal menerbitkan invoice: Belum ada tenant operator SaaS yang terdaftar di database. Silakan daftarkan Tenant Baru terlebih dahulu.");return}const B=((Oe=document.getElementById("saas-inv-email"))==null?void 0:Oe.value);if(!B||B.trim()===""){alert("Gagal: Silakan pilih email tenant yang valid.");return}const $=((Ce=document.getElementById("saas-inv-amount"))==null?void 0:Ce.value)||"100000",z=((Ue=document.getElementById("saas-inv-method"))==null?void 0:Ue.value)||"Tripay QRIS",se=Math.floor(1e5+Math.random()*9e5),X={id:`inv-${Date.now()}`,code:`TRX-${se}`,description:`Top Up / Sewa Lisensi SaaS (${B})`,amount:Number($),paymentMethod:z,status:"pending",date:new Date().toISOString().replace("T"," ").substring(0,16)};G(bt=>[X,...bt]);const de={id:`saas-log-${Date.now()}`,timestamp:new Date().toLocaleTimeString(),source:"Tripay",type:"info",message:`Tagihan SaaS baru diterbitkan untuk ${B} sebesar Rp ${Number($).toLocaleString()}`};W(bt=>[de,...bt])};'
  },

  // 37. Add notification hook on pendaftaran operator baru (client login/register page)
  {
    target: 'M.push(F),localStorage.setItem("mikrobil_global_saas_tenants",JSON.stringify(M))',
    replacement: 'M.push(F),localStorage.setItem("mikrobil_global_saas_tenants",JSON.stringify(M)),typeof window.sendSaaSSystemNotification==="function"&&window.sendSaaSSystemNotification(`🔔 *PENDAFTARAN TENANT BARU*\\n\\nTelah terdaftar tenant baru di platform MikRobiL SaaS:\\n- *Nama*: ${r.trim()}\\n- *Email*: ${O}\\n- *No. HP*: ${l.trim()}\\n- *Paket*: ${I} Plan\\n- *Status*: Pending Payment\\n- *Masa Aktif*: ${F.expired_at || "30 Hari"}`)'
  },

  // 38. Add notification hook on manual tenant registration by Super Admin
  {
    target: 'Hn(z=>[...z,$]),wa({name:"",email:"",location:"",plan:"Bronze"',
    replacement: 'Hn(z=>[...z,$]),typeof window.sendSaaSSystemNotification==="function"&&window.sendSaaSSystemNotification(`🔔 *PENDAFTARAN TENANT BARU (MANUAL BY ADMIN)*\\n\\nSuper Admin telah mendaftarkan tenant baru secara manual:\\n- *Nama*: ${$.name}\\n- *Email*: ${$.email}\\n- *Paket*: ${$.plan} Plan\\n- *Status*: AKTIF\\n- *Masa Aktif*: ${$.expired_at}`),wa({name:"",email:"",location:"",plan:"Bronze"'
  },

  // 39. Auto-persist notification bot state variables & expose window function
  {
    target: 'C.useEffect(()=>{Ve("wa_template_balance",Yl)},[Yl]),',
    replacement: 'C.useEffect(()=>{Ve("wa_template_balance",Yl)},[Yl]),C.useEffect(()=>{Ve("saas_wa_bot_enabled",saasWaBotEnabled)},[saasWaBotEnabled]),C.useEffect(()=>{Ve("saas_wa_bot_token",saasWaBotToken)},[saasWaBotToken]),C.useEffect(()=>{Ve("saas_wa_bot_phone",saasWaBotPhone)},[saasWaBotPhone]),C.useEffect(()=>{Ve("saas_tele_bot_enabled",saasTeleBotEnabled)},[saasTeleBotEnabled]),C.useEffect(()=>{Ve("saas_tele_bot_token",saasTeleBotToken)},[saasTeleBotToken]),C.useEffect(()=>{Ve("saas_tele_bot_chat_id",saasTeleBotChatId)},[saasTeleBotChatId]),C.useEffect(()=>{window.sendSaaSSystemNotification=(E)=>{const l=(localStorage.getItem("mikrobil_logged_in_user")||"").trim().toLowerCase(),c=l==="admin@mikrobil.net"?"mikrobil_demo_":"mikrobil_real_admin@mikrobil.com_",d=m=>{let u=c+m,f=localStorage.getItem(u);if(!f&&l==="admin@mikrobil.net"&&(f=localStorage.getItem("mikrobil_real_admin@mikrobil.com_"+m)),f){try{return JSON.parse(f)}catch{return f}}return""};const o=d("saas_wa_bot_enabled")===!0,S=d("saas_wa_bot_token"),_=d("saas_wa_bot_phone");if(o&&S&&_){const m=new FormData();m.append("target",_),m.append("message",E),fetch("https://api.fonnte.com/send",{method:"POST",headers:{Authorization:S},body:m}).then(u=>u.json()).then(u=>console.log("WA notification response:",u)).catch(u=>console.error("WA notification error:",u))}const a=d("saas_tele_bot_enabled")===!0,h=d("saas_tele_bot_token"),g=d("saas_tele_bot_chat_id");if(a&&h&&g){fetch("https://api.telegram.org/bot"+h+"/sendMessage",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:g,text:E,parse_mode:"Markdown"})}).then(m=>m.json()).then(m=>console.log("Telegram notification response:",m)).catch(m=>console.error("Telegram notification error:",m))}}},[]),'
  },

  // 40. Hotspot package state initialization
  {
    target: '[ft,Is]=C.useState({name:"",duration:"5 Hours",price:5e3,speedLimit:"3Mbps/3Mbps"})',
    replacement: '[ft,Is]=C.useState({name:"",duration:"5 Hours",price:5e3,speedLimit:"3Mbps/3Mbps",sharedUsers:1,expiredMode:"sapu_rekam",lockUser:"disable"})'
  },

  // 41. Hotspot package edit useEffect populator
  {
    target: 'C.useEffect(()=>{sr&&Is({name:sr.name,duration:sr.duration==="Unlimited"?"":sr.duration,price:sr.price,speedLimit:sr.speedLimit})},[sr]);',
    replacement: 'C.useEffect(()=>{sr&&Is({name:sr.name,duration:sr.duration==="Unlimited"?"":sr.duration,price:sr.price,speedLimit:sr.speedLimit,sharedUsers:sr.sharedUsers||1,expiredMode:sr.expiredMode||"sapu_rekam",lockUser:sr.lockUser||"disable"})},[sr]);'
  },

  // 42. Hotspot package update submission success resetting
  {
    target: 'Fi(null),Aa(!1),Is({name:"",duration:"5 Hours",price:5e3,speedLimit:"3Mbps/3Mbps"}),alert("Berhasil menyimpan perubahan profil hotspot!")',
    replacement: 'Fi(null),Aa(!1),Is({name:"",duration:"5 Hours",price:5e3,speedLimit:"3Mbps/3Mbps",sharedUsers:1,expiredMode:"sapu_rekam",lockUser:"disable"}),alert("Berhasil menyimpan perubahan profil hotspot!")'
  },

  // 43. Hotspot package add submission success resetting
  {
    target: 'Is({name:"",duration:"5 Hours",price:5e3,speedLimit:"3Mbps/3Mbps"}),Aa(!1),W(B=>[{id:`log-${Date.now()}`',
    replacement: 'Is({name:"",duration:"5 Hours",price:5e3,speedLimit:"3Mbps/3Mbps",sharedUsers:1,expiredMode:"sapu_rekam",lockUser:"disable"}),Aa(!1),W(B=>[{id:`log-${Date.now()}`'
  },

  // 44. Hotspot package form Batal/Cancel click resetting
  {
    target: 'onClick:()=>{Fi(null),Aa(!1),Is({name:"",duration:"5 Hours",price:5e3,speedLimit:"3Mbps/3Mbps"})}',
    replacement: 'onClick:()=>{Fi(null),Aa(!1),Is({name:"",duration:"5 Hours",price:5e3,speedLimit:"3Mbps/3Mbps",sharedUsers:1,expiredMode:"sapu_rekam",lockUser:"disable"})}'
  },

  // 45. Hotspot package update submission API call payload enrichment
  {
    target: 'const z=await(await fetch("/api/mikrotik/update-hotspot-profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({host:D.host,port:D.port,user:D.user,pass:D.pass,id:sr.id,name:ft.name,duration:b,price:Number(ft.price),speedLimit:ft.speedLimit})})).json();',
    replacement: 'const z=await(await fetch("/api/mikrotik/update-hotspot-profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({host:D.host,port:D.port,user:D.user,pass:D.pass,id:sr.id,name:ft.name,duration:b,price:Number(ft.price),speedLimit:ft.speedLimit,expiredMode:ft.expiredMode,sharedUsers:ft.sharedUsers,lockUser:ft.lockUser})})).json();'
  },

  // 46. Hotspot package update state (Kn) payload enrichment
  {
    target: 'Kn(B=>B.map(z=>z.id===sr.id?{...z,name:ft.name,duration:b,price:Number(ft.price),speedLimit:ft.speedLimit}:z))',
    replacement: 'Kn(B=>B.map(z=>z.id===sr.id?{...z,name:ft.name,duration:b,price:Number(ft.price),speedLimit:ft.speedLimit,expiredMode:ft.expiredMode,sharedUsers:ft.sharedUsers,lockUser:ft.lockUser}:z))'
  },

  // 47. Hotspot package add submission API call payload enrichment
  {
    target: 'const z=await(await fetch("/api/mikrotik/add-hotspot-profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({host:D.host,port:D.port,user:D.user,pass:D.pass,name:ft.name,duration:b,price:Number(ft.price),speedLimit:ft.speedLimit})})).json();',
    replacement: 'const z=await(await fetch("/api/mikrotik/add-hotspot-profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({host:D.host,port:D.port,user:D.user,pass:D.pass,name:ft.name,duration:b,price:Number(ft.price),speedLimit:ft.speedLimit,expiredMode:ft.expiredMode,sharedUsers:ft.sharedUsers,lockUser:ft.lockUser})})).json();'
  },

  // 48. Hotspot package add state (Kn) payload enrichment
  {
    target: 'else{const B={id:`prof-${Date.now().toString().slice(-4)}`,name:ft.name,duration:b,price:Number(ft.price),speedLimit:ft.speedLimit};Kn(z=>[...z,B])}',
    replacement: 'else{const B={id:`prof-${Date.now().toString().slice(-4)}`,name:ft.name,duration:b,price:Number(ft.price),speedLimit:ft.speedLimit,expiredMode:ft.expiredMode,sharedUsers:ft.sharedUsers,lockUser:ft.lockUser};Kn(z=>[...z,B])}'
  },

  // 49. Hotspot package input fields injection (Rate-Limit field addition)
  {
    target: 'a.jsxs("div",{children:[a.jsx("label",{className:"block font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Batas Kecepatan (Rate-Limit)"}),a.jsx("input",{type:"text",required:!0,placeholder:"e.g. 3Mbps/3Mbps, 5M/5M",value:ft.speedLimit,onChange:p=>Is({...ft,speedLimit:p.target.value}),className:"block w-full px-3 py-2.5 bg-[#0b1220] border border-emerald-950/40 rounded-xl focus:outline-none focus:ring-1 focus:ring-emerald-500 text-gray-200 font-mono"}),a.jsx("span",{className:"text-[10px] text-gray-500 mt-1 block",children:"Format: download/upload (e.g. 1M/1M, 5M/10M)"})]})',
    replacement: 'a.jsxs("div",{children:[a.jsx("label",{className:"block font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Batas Kecepatan (Rate-Limit)"}),a.jsx("input",{type:"text",required:!0,placeholder:"e.g. 3Mbps/3Mbps, 5M/5M",value:ft.speedLimit,onChange:p=>Is({...ft,speedLimit:p.target.value}),className:"block w-full px-3 py-2.5 bg-[#0b1220] border border-emerald-950/40 rounded-xl focus:outline-none focus:ring-1 focus:ring-emerald-500 text-gray-200 font-mono"}),a.jsx("span",{className:"text-[10px] text-gray-500 mt-1 block",children:"Format: download/upload (e.g. 1M/1M, 5M/10M)"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Shared Users"}),a.jsx("select",{value:ft.sharedUsers||1,onChange:p=>Is({...ft,sharedUsers:parseInt(p.target.value)||1}),className:"block w-full px-3 py-2.5 bg-[#0b1220] border border-emerald-950/40 rounded-xl focus:outline-none focus:ring-1 focus:ring-emerald-500 text-gray-200 cursor-pointer",children:[1,2,3,4,5,6,7,8,9,10].map(u=>a.jsx("option",{value:u,children:`\${u} Device`},u))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Lock User"}),a.jsx("select",{value:ft.lockUser||"disable",onChange:p=>Is({...ft,lockUser:p.target.value}),className:"block w-full px-3 py-2.5 bg-[#0b1220] border border-emerald-950/40 rounded-xl focus:outline-none focus:ring-1 focus:ring-emerald-500 text-gray-200 cursor-pointer",children:[a.jsx("option",{value:"disable",children:"Disable (Bebas)"}),a.jsx("option",{value:"enable",children:"Enable (Lock MAC: 1)"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Expired Mode"}),a.jsx("select",{value:ft.expiredMode||"sapu_rekam",onChange:p=>Is({...ft,expiredMode:p.target.value}),className:"block w-full px-3 py-2.5 bg-[#0b1220] border border-emerald-950/40 rounded-xl focus:outline-none focus:ring-1 focus:ring-emerald-500 text-gray-200 cursor-pointer",children:[a.jsx("option",{value:"sapu_rekam",children:"Remove & Record (Hapus & Catat)"}),a.jsx("option",{value:"notice",children:"Notice Only (Tampilkan Peringatan)"})]})]})'
  },

  // 50. Hotspot package table header columns injection
  {
    target: 'a.jsx("th",{className:"p-3",children:"ID Paket"}),a.jsx("th",{className:"p-3",children:"Nama Paket"}),a.jsx("th",{className:"p-3",children:"Masa Aktif"}),a.jsx("th",{className:"p-3",children:"Batas Bandwidth"}),a.jsx("th",{className:"p-3",children:"Harga Jual"}),a.jsx("th",{className:"p-3 text-right",children:"Aksi"})',
    replacement: 'a.jsx("th",{className:"p-3",children:"ID Paket"}),a.jsx("th",{className:"p-3",children:"Nama Paket"}),a.jsx("th",{className:"p-3",children:"Masa Aktif"}),a.jsx("th",{className:"p-3",children:"Batas Bandwidth"}),a.jsx("th",{className:"p-3",children:"Shared Users"}),a.jsx("th",{className:"p-3",children:"Expired Mode"}),a.jsx("th",{className:"p-3",children:"Lock User"}),a.jsx("th",{className:"p-3",children:"Harga Jual"}),a.jsx("th",{className:"p-3 text-right",children:"Aksi"})'
  },

  // 51. Hotspot package table cell data injection
  {
    target: 'a.jsx("td",{className:"p-3 font-mono text-gray-500 font-bold",children:p.id}),a.jsx("td",{className:"p-3 font-bold text-gray-200",children:p.name}),a.jsx("td",{className:"p-3 text-gray-400",children:p.duration}),a.jsx("td",{className:"p-3 font-mono text-emerald-400",children:p.speedLimit}),a.jsxs("td",{className:"p-3 font-semibold text-white",children:["Rp ",p.price.toLocaleString()]})',
    replacement: 'a.jsx("td",{className:"p-3 font-mono text-gray-500 font-bold",children:p.id}),a.jsx("td",{className:"p-3 font-bold text-gray-200",children:p.name}),a.jsx("td",{className:"p-3 text-gray-400",children:p.duration}),a.jsx("td",{className:"p-3 font-mono text-emerald-400",children:p.speedLimit}),a.jsx("td",{className:"p-3 text-gray-300",children:`\${p.sharedUsers||1} Device`}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold \${p.expiredMode==="notice"?"bg-amber-950/60 text-amber-400":"bg-rose-950/60 text-rose-400"}\`,children:p.expiredMode==="notice"?"Notice":"Remove"})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold \${p.lockUser==="enable"?"bg-blue-950/60 text-blue-400":"bg-slate-900 text-gray-500"}\`,children:p.lockUser==="enable"?"Locked":"No Lock"})}),a.jsxs("td",{className:"p-3 font-semibold text-white",children:["Rp ",p.price.toLocaleString()]})'
  },

  // 52. Code character state default value update to 5aB2c34D (standard mixed alphanum)
  {
    target: '[gf,iI]=C.useState("prof-5h"),[bf,sI]=C.useState(10),[Qg,oI]=C.useState("mix")',
    replacement: '[gf,iI]=C.useState("prof-5h"),[bf,sI]=C.useState(10),[Qg,oI]=C.useState("5aB2c34D")'
  },

  // 53. Alphanumeric/Letter random generator pool mapping for all 6 Mikrotik standard styles
  {
    target: 'const pb=Qg==="alpha"?E:Qg==="num"?$:B;',
    replacement: 'const pb=Qg==="abcd"?"abcdefghijklmnopqrstuvwxyz":Qg==="ABCD"?"ABCDEFGHIJKLMNOPQRSTUVWXYZ":Qg==="aBcD"?"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":Qg==="5ab2c34d"?"23456789abcdefghjkmnpqrstuvwxyz":Qg==="5AB2C34D"?"23456789ABCDEFGHJKLMNPQRSTUVWXYZ":Qg==="5aB2c34D"?"23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ":Qg==="alpha"?E:Qg==="num"?$:B;'
  },

  // 54. UI Select element replacement for Karakter Kode with comprehensive options
  {
    target: 'a.jsxs("select",{value:Qg,onChange:p=>oI(p.target.value),className:"block w-full px-3 py-2 bg-[#0b1220] border border-emerald-950/40 rounded-xl focus:outline-none",children:[a.jsx("option",{value:"mix",children:"Alfanumerik"}),a.jsx("option",{value:"num",children:"Angka Saja"}),a.jsx("option",{value:"alpha",children:"Huruf Saja"})]})',
    replacement: 'a.jsxs("select",{value:Qg,onChange:p=>oI(p.target.value),className:"block w-full px-3 py-2 bg-[#0b1220] border border-emerald-950/40 rounded-xl focus:outline-none",children:[a.jsx("option",{value:"abcd",children:"Random abcd"}),a.jsx("option",{value:"ABCD",children:"Random ABCD"}),a.jsx("option",{value:"aBcD",children:"Random aBcD"}),a.jsx("option",{value:"5ab2c34d",children:"Random 5ab2c34d"}),a.jsx("option",{value:"5AB2C34D",children:"Random 5AB2C34D"}),a.jsx("option",{value:"5aB2c34D",children:"Random 5aB2c34D"})]})'
  }
];

let appliedCount = 0;
replacements.forEach(({ target, replacement }, index) => {
  if (content.includes(target)) {
    content = content.replace(target, replacement);
    console.log(`Success applying replacement #${index + 1}`);
    appliedCount++;
  } else {
    console.warn(`Warning: Target #${index + 1} not found!`);
  }
});

// Remove cPanel Deployment Instructions card dynamically to prevent quote escaping fragility
const cpanelCardPrefix = 'a.jsx("div",{className:"pt-6 border-t border-purple-950/15 space-y-4"';
const cardIndex = content.indexOf(cpanelCardPrefix);
if (cardIndex !== -1) {
  let parenCount = 0;
  let i = cardIndex;
  while (content[i] !== "(") i++;
  parenCount = 1;
  i++;
  while (parenCount > 0 && i < content.length) {
    if (content[i] === "(") parenCount++;
    else if (content[i] === ")") parenCount--;
    i++;
  }
  const fullCardBlock = content.substring(cardIndex, i);
  const botCardContent = `a.jsx("div",{className:"pt-6 border-t border-purple-950/15 space-y-4",children:a.jsxs("div",{className:"p-5 bg-gradient-to-r from-purple-950/10 to-indigo-950/10 border border-purple-900/30 rounded-2xl space-y-4",children:[a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx("div",{className:"p-2 bg-purple-950 border border-purple-800 rounded-lg text-purple-400",children:a.jsx("span",{className:"text-lg",children:"🤖"})}),a.jsxs("div",{children:[a.jsx("h4",{className:"text-sm font-bold text-white uppercase tracking-wider font-sans",children:"Bot Notifikasi WhatsApp & Telegram"}),a.jsx("p",{className:"text-[11px] text-gray-400 mt-0.5 font-sans",children:"Kirim notifikasi otomatis ke WhatsApp & Telegram Super Admin saat ada pendaftaran atau pembayaran SaaS."})]})]}),a.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 text-xs",children:[a.jsxs("div",{className:"p-4 bg-[#05060b] border border-purple-950/20 rounded-xl space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between border-b border-purple-950/20 pb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-sm",children:"💬"}),a.jsx("span",{className:"font-bold text-white",children:"WhatsApp Gateway (Fonnte)"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:saasWaBotEnabled,onChange:E=>setSaasWaBotEnabled(E.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-7 h-4 bg-gray-700 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[\\x27\\x27] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-emerald-600"})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-[10px] text-gray-400 font-semibold mb-1",children:"FONNTE API TOKEN"}),a.jsx("input",{type:"password",placeholder:"Masukkan Token Fonnte",value:saasWaBotToken,onChange:E=>setSaasWaBotToken(E.target.value),className:"w-full px-3 py-1.5 bg-[#090e1a] border border-purple-950/40 rounded-lg text-gray-200 text-xs focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-[10px] text-gray-400 font-semibold mb-1",children:"NOMOR TARGET (WA RECEIVER)"}),a.jsx("input",{type:"text",placeholder:"Contoh: 081234567890",value:saasWaBotPhone,onChange:E=>setSaasWaBotPhone(E.target.value),className:"w-full px-3 py-1.5 bg-[#090e1a] border border-purple-950/40 rounded-lg text-gray-200 text-xs focus:outline-none"})]}),a.jsx("button",{type:"button",onClick:()=>{if(!saasWaBotToken||!saasWaBotPhone){alert("Harap isi Token Fonnte dan Nomor Target terlebih dahulu.");return}const E="🔔 *TES KONEKSI WHATSAPP BOT*\\\\n\\\\nKoneksi WhatsApp Bot dari platform MikRobiL SaaS terhubung dengan sukses ke nomor Anda!";const $=new FormData();$.append("target",saasWaBotPhone),$.append("message",E),fetch("https://api.fonnte.com/send",{method:"POST",headers:{Authorization:saasWaBotToken},body:$}).then(B=>B.json()).then(B=>{B.status?alert("Sukses! Tes kirim WhatsApp berhasil dikirim via Fonnte."):alert("Gagal: "+(B.reason||JSON.stringify(B)))}).catch(B=>alert("Error kirim WhatsApp: "+B.message))},className:"w-full py-1.5 bg-emerald-950 hover:bg-emerald-900 border border-emerald-800 text-emerald-400 font-bold rounded-lg transition-all text-[10px] cursor-pointer",children:"Tes Kirim WhatsApp"})]})]}),a.jsxs("div",{className:"p-4 bg-[#05060b] border border-purple-950/20 rounded-xl space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between border-b border-purple-950/20 pb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-sm",children:"✈️"}),a.jsx("span",{className:"font-bold text-white",children:"Telegram Bot API"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:saasTeleBotEnabled,onChange:E=>setSaasTeleBotEnabled(E.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-7 h-4 bg-gray-700 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[\\x27\\x27] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-purple-600"})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-[10px] text-gray-400 font-semibold mb-1",children:"TELEGRAM BOT TOKEN"}),a.jsx("input",{type:"password",placeholder:"Masukkan Token Bot Telegram",value:saasTeleBotToken,onChange:E=>setSaasTeleBotToken(E.target.value),className:"w-full px-3 py-1.5 bg-[#090e1a] border border-purple-950/40 rounded-lg text-gray-200 text-xs focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-[10px] text-gray-400 font-semibold mb-1",children:"TELEGRAM CHAT ID"}),a.jsx("input",{type:"text",placeholder:"Contoh: -10012345678",value:saasTeleBotChatId,onChange:E=>setSaasTeleBotChatId(E.target.value),className:"w-full px-3 py-1.5 bg-[#090e1a] border border-purple-950/40 rounded-lg text-gray-200 text-xs focus:outline-none"})]}),a.jsx("button",{type:"button",onClick:()=>{if(!saasTeleBotToken||!saasTeleBotChatId){alert("Harap isi Bot Token dan Chat ID terlebih dahulu.");return}const E="🔔 *TES KONEKSI TELEGRAM BOT*\\\\n\\\\nKoneksi Telegram Bot dari platform MikRobiL SaaS terhubung dengan sukses ke Chat ID Anda!";fetch("https://api.telegram.org/bot" + saasTeleBotToken + "/sendMessage",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:saasTeleBotChatId,text:E,parse_mode:"Markdown"})}).then(B=>B.json()).then(B=>{B.ok?alert("Sukses! Tes kirim Telegram berhasil."):alert("Gagal: "+(B.description||JSON.stringify(B)))}).catch(B=>alert("Error kirim Telegram: "+B.message))},className:"w-full py-1.5 bg-purple-950 hover:bg-purple-900 border border-purple-800 text-purple-300 font-bold rounded-lg transition-all text-[10px] cursor-pointer",children:"Tes Kirim Telegram"})]})]})],filter(Boolean)}),a.jsxs("div",{className:"pt-4 border-t border-purple-950/20 space-y-3 text-xs sm:col-span-2",children:[a.jsxs("div",{children:[a.jsx("h5",{className:"font-bold text-purple-300 uppercase tracking-wider flex items-center gap-1.5",children:"📢 Pusat Kontrol Manual Broadcast Notifikasi"}),a.jsx("p",{className:"text-[10px] text-gray-400 font-sans mt-0.5",children:"Kirim rekap tagihan pending atau daftar tenant kadaluarsa langsung ke bot Telegram/WhatsApp Anda secara instant."})]}),a.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[a.jsx("button",{type:"button",onClick:()=>{const today=new Date().toISOString().split("T")[0];const threeDays=new Date(Date.now()+3*24*60*60*1e3).toISOString().split("T")[0];const items=tr.filter(x=>x.id!=="sa-admin"&&(x.expired_at&&x.expired_at<=threeDays));if(items.length===0){alert("Sempurna! Tidak ada tenant operator yang kadaluarsa atau mendekati jatuh tempo (<= 3 hari) saat ini.");return}let msg=`⚠️ *LAPORAN JATUH TEMPO TENANT SAAS*\\\\n\\\\nBerikut daftar mitra operator yang telah kadaluarsa atau akan berakhir dalam 3 hari:\\\\n`;items.forEach((x,idx)=>{const isExp=x.expired_at<today;msg+=`\\\\n\${idx+1}. *\${x.name}* (\${x.email})\\\\n   - Masa Aktif: *\${x.expired_at}* \${isExp?"🔴 (KADALUARSA)":"🟡 (Hampir Habis)"}\\\\n   - Paket: \${x.plan} Plan\\\\n   - Kontak: \${x.phone}\\\\n`});if(typeof window.sendSaaSSystemNotification==="function"){window.sendSaaSSystemNotification(msg);alert(`Sukses! Mengirim rekap jatuh tempo (\${items.length} tenant) ke bot notifikasi Anda.`)}else{alert("Error: sendSaaSSystemNotification tidak terdefinisi.")},className:"w-full py-2 bg-purple-950/60 hover:bg-purple-900/60 text-purple-300 font-bold rounded-xl border border-purple-800/30 transition-all cursor-pointer text-center",children:"📅 Broadcast Alert Jatuh Tempo"}),a.jsx("button",{type:"button",onClick:()=>{const items=q.filter(x=>x.status==="pending");if(items.length===0){alert("Sempurna! Tidak ada invoice/tagihan yang berstatus PENDING saat ini.");return}let msg=`🔔 *LAPORAN TAGIHAN PENDING SAAS*\\\\n\\\\nBerikut daftar invoice sewa/top-up SaaS yang masih dalam status PENDING (belum dibayar):\\\\n`;items.forEach((x,idx)=>{msg+=`\\\\n\${idx+1}. *\${x.code}*\\\\n   - Mitra: \${x.description}\\\\n   - Jumlah: *Rp \${Number(x.amount).toLocaleString("id-ID")}*\\\\n   - Tgl Terbit: \${x.date}\\\\n   - Metode: \${x.paymentMethod}\\\\n`});if(typeof window.sendSaaSSystemNotification==="function"){window.sendSaaSSystemNotification(msg);alert(`Sukses! Mengirim rekap tagihan pending (\${items.length} invoice) ke bot notifikasi Anda.`)}else{alert("Error: sendSaaSSystemNotification tidak terdefinisi.")},className:"w-full py-2 bg-emerald-950/60 hover:bg-emerald-900/60 text-emerald-400 font-bold rounded-xl border border-emerald-800/30 transition-all cursor-pointer text-center",children:"💰 Broadcast Pengingat Tagihan"})]})]})]})})`;
  content = content.replace(fullCardBlock, botCardContent);
  console.log("Success dynamically replacing cPanel Deployment Instructions card with WhatsApp & Telegram Bot Notification Card!");
} else {
  console.warn("Warning: cPanel Deployment Instructions card prefix not found!");
}

fs.writeFileSync(filePath, content, 'utf8');
console.log(`Completed editing bundle. Applied ${appliedCount} out of ${replacements.length} replacements.`);
