// ================== Path ==================
const IDLE_FILE      = "/data/adb/modules/RaiRin-AI/cortex/battery/idle.txt";
const POWERSAVE_FILE = "/data/adb/modules/RaiRin-AI/cortex/battery/powersave.txt";
const KILL_LIST_FILE = "/data/adb/modules/RaiRin-AI/cortex/battery/kill-list.txt";

// ================== Wrapper exec (KernelSU) ==================
function exec(command) {
  return new Promise((resolve, reject) => {
    const cb = `exec_cb_${Date.now()}`;
    window[cb] = (errno, stdout, stderr) => {
      delete window[cb];
      if (errno !== 0) reject(new Error(stderr || stdout || "Unknown error"));
      else resolve(stdout);
    };
    try { ksu.exec(command, `window.${cb}`); }
    catch (e) { reject(e); }
  });
}

// ================== Idle Mode ==================
const idleEnableBtn  = document.getElementById("idleEnableBtn");
const idleDisableBtn = document.getElementById("idleDisableBtn");
const idleOutput     = document.getElementById("idleOutput");

function updateIdleUI(state) {
  const enabled = state === "on";
  

  // Toggle warna aktif tombol
  idleEnableBtn.classList.toggle("btn-active", enabled);
  idleDisableBtn.classList.toggle("btn-active", !enabled);
}

async function writeIdle(option) {
  idleOutput.innerHTML = `Setting Idle Mode to ${option}... <span class="blinker">_</span>`;
  try {
    await exec(`echo ${option} > ${IDLE_FILE}`);
    updateIdleUI(option);
    idleOutput.innerHTML = `<span class="green">Idle Mode: ${option}</span>`;
  } catch (err) {
    idleOutput.innerHTML = `<span class="red">Failed: ${err.message}</span>`;
  }
}

async function initIdle() {
  try {
    const out = await exec(`cat ${IDLE_FILE}`);
    const state = out.trim() === "on" ? "on" : "off";
    updateIdleUI(state);
  } catch {
    updateIdleUI("off");
  }

  idleEnableBtn.addEventListener("click", () => writeIdle("on"));
  idleDisableBtn.addEventListener("click", () => writeIdle("off"));
}
// ================== Powersave Mode ==================
const psEnableBtn  = document.getElementById("psEnableBtn");
const psDisableBtn = document.getElementById("psDisableBtn");
const psOutput     = document.getElementById("psOutput");

function updatePSUI(state) {
  const enabled = state === "on";
  

  // Toggle warna aktif tombol
  psEnableBtn.classList.toggle("btn-active", enabled);
  psDisableBtn.classList.toggle("btn-active", !enabled);
}

async function writePowersave(option) {
  psOutput.innerHTML = `Setting Powersave to ${option}... <span class="blinker">_</span>`;
  try {
    await exec(`echo ${option} > ${POWERSAVE_FILE}`);
    updatePSUI(option);
    psOutput.innerHTML = `<span class="green">Powersave: ${option}</span>`;
  } catch (err) {
    psOutput.innerHTML = `<span class="red">Failed: ${err.message}</span>`;
  }
}

async function initPowersave() {
  try {
    const out = await exec(`cat ${POWERSAVE_FILE}`);
    const state = out.trim() === "on" ? "on" : "off";
    updatePSUI(state);
  } catch {
    updatePSUI("off");
  }

  psEnableBtn.addEventListener("click", () => writePowersave("on"));
  psDisableBtn.addEventListener("click", () => writePowersave("off"));
}

// ================== Kill List ==================
const editKillListBtn = document.getElementById("editKillListBtn");
const killListSection = document.getElementById("killListSection");
const killListList = document.getElementById("killListList");
const killListSearch = document.getElementById("killListSearch");

let killInstalledApps = [];
let killListLines = [];

editKillListBtn.addEventListener("click", async () => {
  killListSection.style.display = killListSection.style.display === "block" ? "none" : "block";
  if (killListSection.style.display !== "block") return;

  try {
    const content = await exec(`cat ${KILL_LIST_FILE}`);
    killListLines = content.split("\n").map(l => l.trim()).filter(l => l);

    const apps = await exec("pm list packages -3");
    killInstalledApps = apps.split("\n").map(l => l.replace("package:", "").trim()).filter(l => l);

    renderKillList(killInstalledApps, killListLines);
  } catch {
    killListList.innerHTML = `<span class="red">Failed to load Kill List</span>`;
  }
});

function renderKillList(apps, selected) {
  killListList.innerHTML = "";
  apps.forEach(pkg => {
    const div = document.createElement("div");
    div.className = "list-item";

    const checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.value = pkg;
    checkbox.checked = selected.includes(pkg);
    checkbox.addEventListener("change", () => updateKillListFile(pkg, checkbox.checked));

    const label = document.createElement("label");
    label.textContent = pkg;
    label.style.marginLeft = "6px";

    div.appendChild(checkbox);
    div.appendChild(label);
    killListList.appendChild(div);
  });
}

async function updateKillListFile(pkg, checked) {
  if (checked && !killListLines.includes(pkg)) killListLines.push(pkg);
  else if (!checked) killListLines = killListLines.filter(p => p !== pkg);

  const content = killListLines.join("\n");
  const escaped = content.replace(/(["\\`$])/g, '\\$1');
  const command = `su -c 'cat > ${KILL_LIST_FILE} <<EOF\n${escaped}\nEOF'`;
  try {
    await exec(command);
    killListList.insertAdjacentHTML("afterbegin", `<span class="green">Kill list updated</span>`);
  } catch {
    killListList.insertAdjacentHTML("afterbegin", `<span class="red">Failed to update Kill List</span>`);
  }
}

killListSearch.addEventListener("input", () => {
  const query = killListSearch.value.toLowerCase();
  const filtered = killInstalledApps.filter(pkg => pkg.toLowerCase().includes(query));
  renderKillList(filtered, killListLines);
});

// ================== Info Modal Handling (Fixed) ==================
document.querySelectorAll(".info-icon").forEach(icon => {
  icon.addEventListener("click", () => {
    const modalId = icon.id.replace("Info", "Modal");
    const modal = document.getElementById(modalId);
    if (modal) modal.style.display = "flex";
  });
});

document.querySelectorAll(".closeModal").forEach(btn => {
  btn.addEventListener("click", () => {
    btn.parentElement.style.display = "none";
  });
});

window.addEventListener("click", e => {
  if (e.target.classList.contains("infoModal")) {
    e.target.style.display = "none";
  }
});

// ================== Daemon Status ==================
async function updateDaemonStatus() {
  const statusElem = document.getElementById("daemonStatus");
  try {
    const output = await exec("pidof RaiRin-bat");
    if (output.trim()) {
      statusElem.innerHTML = `<span class="green">Online</span> <img src="assets/rairin.webp" alt="RaiRin" style="width:20px;height:20px;vertical-align:middle;margin-left:5px;">`;
      statusElem.classList.replace("status-offline", "status-online");
    } else {
      statusElem.innerHTML = "Offline";
      statusElem.classList.replace("status-online", "status-offline");
    }
  } catch {
    statusElem.innerHTML = "Offline";
    statusElem.classList.replace("status-online", "status-offline");
  }
}

// ================== Footer Action ==================
async function openELMalware() {
  try {
    await exec('cmd activity start -a android.intent.action.VIEW -d "https://t.me/kaminarich_here"');
  } catch {}
}

// ================== Init ==================
document.addEventListener("DOMContentLoaded", async () => {
  updateDaemonStatus();
  setInterval(updateDaemonStatus, 5000);

  await initIdle();
  await initPowersave();
});