const fs = require('fs');

const filePath = 'dist/assets/index-D9sWWWv_.js';
if (!fs.existsSync(filePath)) {
  console.error("Error: bundle file does not exist at " + filePath);
  process.exit(1);
}

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

function apply(target, replacement, desc) {
  if (content.includes(target)) {
    content = content.replace(target, replacement);
    console.log(`[SUCCESS] ${desc}`);
    appliedCount++;
  } else {
    console.warn(`[WARNING] NOT FOUND: ${desc}`);
  }
}

// 1. Update initial tenant array lists with expired_at
const t1 = '[{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"}]';
const r1 = '[{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"}]';
apply(t1, r1, "Initial tenant array lists with expired_at");

const t2 = '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"}]';
const r2 = '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"}]';
apply(t2, r2, "Super admin login fallback array");

const t3 = '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"}]';
const r3 = '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"}]';
apply(t3, r3, "Super admin signup fallback array");

// 2. Add expired Edit state values in SaaS component
const t4 = '[Ns,Vl]=C.useState(!1),[Cr,wa]=C.useState({name:"",email:"",location:"",plan:"Bronze"}),[at,At]=C.useState(null)';
const r4 = '[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("")';
apply(t4, r4, "SaaS component state variables");

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

// 4. Update the 3 dynamic/manual tenant creators to include expired_at field
const t4a_part1 = 'O={id:`TNT-${Date.now()}`';
const t4a_part2 = ',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]}';
const t4a = t4a_part1 + t4a_part2;
const r4a = t4a_part1 + t4a_part2.slice(0, -1) + ',expired_at:new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]}';
apply(t4a, r4a, "Creator 1: Dynamic login fallback");

const t4b_part1 = 'F={id:`TNT-${Date.now()}`';
const t4b_part2 = ',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]}';
const t4b = t4b_part1 + t4b_part2;
const r4b = t4b_part1 + t4b_part2.slice(0, -1) + ',expired_at:new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]}';
apply(t4b, r4b, "Creator 2: signup operator registration");

const t4c_part1 = 'const $={id:`TNT-${String(tr.length+1).padStart(3,"0")}`';
const t4c_part2 = ',name:Cr.name,email:Cr.email,location:Cr.location||"Indonesia",plan:Cr.plan,routers:1,status:"active",joined:new Date().toISOString().split("T")[0]};';
const t4c = t4c_part1 + t4c_part2;
const r4c = t4c_part1 + t4c_part2.slice(0, -2) + ',expired_at:Cr.expired_at||new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]};';
apply(t4c, r4c, "Creator 3: super admin panel registration form");

// 5. Add input field to register operator form
const t5a = '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))})]})';
const r5a = '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"})]})';
apply(t5a, r5a, "Add expired_at input field to operator form");

// 6. Add "Masa Aktif" table header
const t6 = '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"})';
const r6 = '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"})';
apply(t6, r6, "Add Masa Aktif table header");

// 7. Render Masa Aktif value & ✏️ button on table row, with dynamic active status expiration check
const t7_part1 = '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:';
const backtick = '`';
const t7_part2 = '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"}';
const t7_part3 = '`,children:E.status==="pending_payment"?"BELUM BAYAR":E.status==="pending_approval"?"MENUNGGU ACC":E.status.toUpperCase()})})';
const t7 = t7_part1 + backtick + t7_part2 + t7_part3;

const r7 = '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:' + backtick + '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"}' + backtick + ',' +
  '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()})})';
apply(t7, r7, "Render Masa Aktif row & dynamic expired badge");

// 8. Append expired edit modal at the end of saas-tenants section
const t8 = '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"';
const r8 = '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])},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"';
apply(t8, r8, "Append expired edit modal");

// 9. Force pending screen if account's expired_at has passed
const t9 = 'const Hi=tr.find(p=>p.email.trim().toLowerCase()===e.trim().toLowerCase());if(Hi&&Hi.status!=="active"&&!isPlatformOwner&&e.toLowerCase()!=="admin@mikrobil.net")';
const r9 = '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]))&&!isPlatformOwner&&e.toLowerCase()!=="admin@mikrobil.net")';
apply(t9, r9, "Force pending screen if account's expired_at has passed");

// 10. Update billing success handler to set/extend expiration to 30 days
const t10 = 'const p=()=>{const D=tr.map($=>$.email.trim().toLowerCase()===e.trim().toLowerCase()?{...$,status:"active"}:$);Hn(D);';
const r10 = '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);';
apply(t10, r10, "Update billing success handler");

// 11. Custom pending screen status if account is expired
const t11 = 'a.jsx("span",{className:"text-amber-400 font-bold",children:Hi.status==="pending_payment"?"Menunggu Pembayaran":"Menunggu Approval Admin"})';
const r11 = '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"})';
apply(t11, r11, "Custom pending screen status if account is expired");

// 12. Display expiration date inside the pending approval screen
const t12 = '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||"-"})]})';
const r12 = '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})]})';
apply(t12, r12, "Display expiration date inside the pending approval screen");

// 13. Display remaining active days on tenant dashboard sidebar
const t13_part1 = 'isPlatformOwner?a.jsx("span",{className:"text-[10px] text-purple-400 block font-mono font-bold",children:"ROLE: SUPER ADMIN"}):a.jsx("span",{className:';
const t13_part2 = '"text-[10px] text-emerald-400 block font-mono font-bold",children:"ROLE: TENANT ADMIN"}';
const t13_part3 = ')';
const t13 = t13_part1 + t13_part2 + t13_part3;
const r13 = 'isPlatformOwner?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; })()]})';
apply(t13, r13, "Display remaining active days on tenant dashboard sidebar");

// 14. Update operator approval (ACC Manual) to set expired_at if it is not set
const t14 = 'const z=tr.map(X=>X.id===E.id?{...X,status:"active"}:X);Hn(z);';
const r14 = '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);';
apply(t14, r14, "Update operator approval to set expired_at");


fs.writeFileSync(filePath, content, 'utf8');
console.log(`\nCompleted. Applied ${appliedCount} out of 16 replacements.`);
