const RENDER_FILE = "/data/adb/modules/RaiRin-AI/webroot/integrated/rendering";
const SOC_FILE = "/data/local/tmp/thunder_default/soc";
const VERSION_FILE = "/data/adb/modules/RaiRin-AI/version.txt";
const NET_FILE = "/data/adb/modules/RaiRin-AI/cortex/net/booster.txt";
// ======== Wrapper exec KSU ========
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);
    }
  });
}
// ================== License ==================
const LICENSE_FILE = "/data/adb/modules/RaiRin-AI/engine/license.txt";
const licenseInput = document.getElementById("licenseInput");
const licenseBtn = document.getElementById("licenseActivateBtn");
const licenseOutput = document.getElementById("licenseOutput");

licenseBtn.addEventListener("click", async () => {
  const code = licenseInput.value.trim();
  if (!code) {
    licenseOutput.innerHTML = "<span class='red'>Please enter a license code</span>";
    return;
  }
  licenseOutput.innerHTML = "Activating... <span class='blinker'>_</span>";
  try {
    await exec(`echo "${code}" > ${LICENSE_FILE}`);
    licenseOutput.innerHTML =
      "<span class='green'>License successfully added, please reboot.</span>";
    licenseInput.value = "";
  } catch (err) {
    licenseOutput.innerHTML = `<span class='red'>Failed to add license: ${err.message}</span>`;
  }
});
// ================== Daemon Status ==================
async function updateDaemonStatus() {
  const statusElem = document.getElementById("daemonStatus");
  try {
    const output = await exec("pidof RaiRin-game");
    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");
  }
}

// ================== Chipset ==================
const chipsetSelect = document.getElementById("chipsetSelect");
const chipsetOutput = document.getElementById("chipsetOutput");

chipsetSelect.addEventListener("change", async (e) => {
  const val = e.target.value;
  if (!val) return;
  try {
    await exec(`echo ${val} > ${SOC_FILE}`);
    chipsetOutput.innerHTML = `<span class='green'>Chipset set to ID ${val}</span>`;
  } catch (err) {
    chipsetOutput.innerHTML = `<span class='red'>Failed: ${err.message}</span>`;
  }
});

async function initChipsetSelect() {
  try {
    const out = await exec(`cat ${SOC_FILE}`);
    const id = out.trim();
    if (["1", "2", "3", "4", "5"].includes(id)) {
      chipsetSelect.value = id;
      chipsetOutput.innerHTML = `<span class='green'>Current: ${
        chipsetSelect.options[chipsetSelect.selectedIndex].text
      }</span>`;
    }
  } catch {
    chipsetOutput.innerHTML = "No chipset selected.";
  }
}

// ================== System Info ==================
async function loadSystemInfo() {
  const verEl = document.getElementById("infoVersion");
  const kerEl = document.getElementById("infoKernel");
  const sdkEl = document.getElementById("infoSDK");
  const chipEl = document.getElementById("infoChipset");

  try {
    const version = await exec(`cat /data/adb/modules/RaiRin-AI/module.prop | grep version= | cut -d= -f2`);
    const kernel = await exec("uname -r");
    const sdk = await exec("getprop ro.build.version.sdk");
    const soc = await exec("cat /data/local/tmp/thunder_default/soc || echo Unknown");

    verEl.textContent = version.trim() || "Unknown";
    kerEl.textContent = kernel.trim() || "Unknown";
    sdkEl.textContent = sdk.trim() || "Unknown";

    let chipName = "Unknown";
    switch (soc.trim()) {
      case "1": chipName = "Mediatek"; break;
      case "2": chipName = "Snapdragon"; break;
      case "3": chipName = "Exynos"; break;
      case "4": chipName = "Unisoc"; break;
      case "5": chipName = "Tensor"; break;
    }
    chipEl.textContent = chipName;
  } catch (err) {
    verEl.textContent = "Error";
    kerEl.textContent = "Error";
    sdkEl.textContent = "Error";
    chipEl.textContent = "Error";
    console.error("System Info failed:", err);
  }
}
// ================== Cache ==================
document.getElementById("clearCacheBtn").addEventListener("click", async () => {
  const out = document.getElementById("cacheOutput");
  out.innerHTML = "Clearing cache... <span class='blinker'>_</span>";
  try {
    await exec("/data/adb/modules/RaiRin-AI/cortex/cache/clear.sh");
    out.innerHTML = "<span class='green'>Cache cleared successfully!</span>";
  } catch (e) {
    out.innerHTML = `<span class='red'>Failed: ${e.message}</span>`;
  }
});

// ================== Rendering ==================
const renderOutput = document.getElementById("renderOutput");
const renderSkiaBtn = document.getElementById("renderSkiaBtn");
const renderVulkanBtn = document.getElementById("renderVulkanBtn");

function updateRenderUI(current) {
  renderOutput.innerHTML = `<span class="green">Current: ${current}</span>`;
  renderSkiaBtn.classList.toggle("btn-active", current === "SkiaGL");
  renderVulkanBtn.classList.toggle("btn-active", current === "Vulkan");
}

async function writeRenderingOption(option) {
  renderOutput.innerHTML = `Setting Rendering to ${option}... <span class="blinker">_</span>`;
  try {
    const cmd = option === "SkiaGL"
      ? "/data/adb/modules/RaiRin-AI/cortex/render/skiagl"
      : "/data/adb/modules/RaiRin-AI/cortex/render/vulkan";
    await exec(cmd);
    await exec(`echo ${option} > ${RENDER_FILE}`);
    updateRenderUI(option);
  } catch (err) {
    renderOutput.innerHTML = `<span class='red'>Failed: ${err.message}</span>`;
  }
}

renderSkiaBtn.addEventListener("click", () => writeRenderingOption("SkiaGL"));
renderVulkanBtn.addEventListener("click", () => writeRenderingOption("Vulkan"));

async function initRenderingButtons() {
  try {
    const out = await exec(`cat ${RENDER_FILE}`);
    updateRenderUI(out.trim());
  } catch {
    renderOutput.innerHTML = "Choose rendering option";
  }
}

// ================== Net Booster ==================
const netOutput = document.getElementById("netOutput");
const netBoostBtn = document.getElementById("netBoostBtn");
const netDefaultBtn = document.getElementById("netDefaultBtn");

function updateNetUI(current) {
  netOutput.innerHTML = `<span class="green">Current: ${current}</span>`;
  netBoostBtn.classList.toggle("btn-active", current === "Boost");
  netDefaultBtn.classList.toggle("btn-active", current === "Default");
}

async function writeNetOption(option) {
  netOutput.innerHTML = `Setting Network ${option}... <span class="blinker">_</span>`;
  try {
    const cmd = option === "Boost"
      ? "/data/adb/modules/RaiRin-AI/cortex/net/net-boost.sh"
      : "/data/adb/modules/RaiRin-AI/cortex/net/net-default.sh";

    await exec(cmd);
    await exec(`echo ${option} > ${NET_FILE}`);
    updateNetUI(option);
  } catch (err) {
    netOutput.innerHTML = `<span class='red'>Failed: ${err.message}</span>`;
  }
}

// Event listener tombol
netBoostBtn.addEventListener("click", () => writeNetOption("Boost"));
netDefaultBtn.addEventListener("click", () => writeNetOption("Default"));

// Inisialisasi status saat load
async function initNetButtons() {
  try {
    const out = await exec(`cat ${NET_FILE} 2>/dev/null || echo Default`);
    updateNetUI(out.trim()); // pastikan UI sinkron
  } catch {
    netOutput.innerHTML = "Choose option";
  }
}

// ================== Logs ==================
const LOG_FILE = "/data/local/tmp/RaiRin-AI/log_option.txt";
const logEnableBtn = document.getElementById("logEnableBtn");
const logDisableBtn = document.getElementById("logDisableBtn");
const logCurrent = document.getElementById("logCurrent");
const logOutput = document.getElementById("logOutput");

function updateLogUI(state) {
  logCurrent.innerText = `Current: ${state}`;
  logCurrent.className = state === "enabled" ? "current green" : "current red";
  logEnableBtn.classList.toggle("btn-active", state === "enabled");
  logDisableBtn.classList.toggle("btn-active", state === "disabled");
}

async function writeLogOption(option) {
  logOutput.innerHTML = `Setting logs to ${option}... <span class='blinker'>_</span>`;
  try {
    const script = option === "enabled"
      ? "/data/adb/modules/RaiRin-AI/cortex/log/enable.sh"
      : "/data/adb/modules/RaiRin-AI/cortex/log/disable.sh";
    await exec(script);
    await exec(`echo ${option} > ${LOG_FILE}`);
    updateLogUI(option);
    logOutput.innerHTML = `<span class='green'>Logs ${option}</span>`;
  } catch (e) {
    logOutput.innerHTML = `<span class='red'>Failed: ${e.message}</span>`;
  }
}

async function initLogButtons() {
  try {
    const out = await exec(`cat ${LOG_FILE} 2>/dev/null || echo enabled`);
    const current = out.trim() === "disabled" ? "disabled" : "enabled";
    updateLogUI(current);
  } catch {
    updateLogUI("enabled");
  }

  
  logEnableBtn.addEventListener("click", async () => {
    await writeLogOption("enabled");
    updateLogUI("enabled");
  });

  logDisableBtn.addEventListener("click", async () => {
    await writeLogOption("disabled");
    updateLogUI("disabled");
  });
}
// ================== Dex2OAT ==================
const DEX_STATUS_FILE = "/data/adb/modules/RaiRin-AI/cortex/dex2oat/status.txt";
const DEX_BINARY = "/data/adb/modules/RaiRin-AI/cortex/dex2oat/dex";
const dexEnableBtn = document.getElementById("dexEnableBtn");
const dexDisableBtn = document.getElementById("dexDisableBtn");
const dexOutput = document.getElementById("dexOutput");
const dexCurrent = document.getElementById("dexCurrent");

function updateDexUI(enabled) {
  dexCurrent.innerText = `Current: ${enabled ? "Enabled" : "Disabled"}`;
  dexCurrent.className = enabled ? "current green" : "current red";
  dexEnableBtn.classList.toggle("btn-active", enabled);
  dexDisableBtn.classList.toggle("btn-active", !enabled);
}

async function writeDexOption(enable) {
  dexOutput.innerHTML = "Processing... <span class='blinker'>_</span>";
  try {
    if (enable) {
      await exec(`${DEX_BINARY}`);
      await exec(`echo enabled > ${DEX_STATUS_FILE}`);
      updateDexUI(true);
      dexOutput.innerHTML = "<span class='green'>Dex2OAT optimization applied!</span>";
    } else {
      await exec(`echo disabled > ${DEX_STATUS_FILE}`);
      updateDexUI(false);
      dexOutput.innerHTML = "<span class='green'>Dex2OAT disabled</span>";
    }
  } catch (e) {
    dexOutput.innerHTML = `<span class='red'>Failed: ${e.message}</span>`;
  }
}

async function initDexButtons() {
  try {
    const out = await exec(`cat ${DEX_STATUS_FILE} 2>/dev/null || echo disabled`);
    const current = out.trim() === "enabled";
    updateDexUI(current);
  } catch {
    updateDexUI(false);
  }

  dexEnableBtn.addEventListener("click", async () => {
    await writeDexOption(true);
    updateDexUI(true);
  });

  dexDisableBtn.addEventListener("click", async () => {
    await writeDexOption(false);
    updateDexUI(false);
  });
}

// ================== Additional: Color Boost ==================
function initColorBoost() {
  const colorBtn = document.getElementById("colorBoostBtn");
  const section = document.getElementById("colorBoostSection");
  const slider = document.getElementById("colorBoostSlider");
  const valueText = document.getElementById("colorBoostValue");
  const image = document.getElementById("colorBoostImage"); 
  // Awalnya hid
  section.style.display = "none";
  let visible = false;


  colorBtn.addEventListener("click", () => {
    visible = !visible;
    section.style.display = visible ? "block" : "none";
  });

  
  colorBtn.addEventListener("dblclick", () => {
    visible = false;
    section.style.display = "none";
  });

  // Slider dinamis
  slider.addEventListener("input", async () => {
    const scale = parseFloat(slider.value);
    let actualBoost = 1.0;

    // Mapping custom: 0 = gray (0.8), 1 = normal (1.0), 2–10 = 1.1 → 1.9
    if (scale === 0) actualBoost = 0.0;
    else if (scale >= 1) actualBoost = 1.0 + (scale - 1) * 0.2;

    const displayText =
      scale === 0 ? "Monochrome mode (0.0)" : `Boost ×${actualBoost.toFixed(2)}`;
    valueText.textContent = `Scale: ${scale} → ${displayText}`;

    try {
      await exec(`service call SurfaceFlinger 1022 f ${actualBoost.toFixed(2)}`);

      // Optional: update gambar efek visual
      if (image) {
        image.style.filter =
          scale === 0
            ? "grayscale(100%)"
            : `saturate(${actualBoost.toFixed(2)}) brightness(${actualBoost.toFixed(2)})`;
      }
    } catch (err) {
      console.error("Color Boost failed:", err);
    }
  });
}
// ================== Info Modals ==================
function initModals() {
  const modals = [
  { icon: "logInfo", modal: "logModal" },
  { icon: "dexInfo", modal: "dexModal" },
  { icon: "netInfo", modal: "netModal" }, 
];
  modals.forEach(({ icon, modal }) => {
    const btn = document.getElementById(icon);
    const box = document.getElementById(modal);
    const close = box.querySelector(".closeModal");
    btn.onclick = () => (box.style.display = "block");
    close.onclick = () => (box.style.display = "none");
    window.addEventListener("click", (e) => {
      if (e.target === box) box.style.display = "none";
    });
  });
}

// ================== Init ==================
document.addEventListener("DOMContentLoaded", async () => {
  updateDaemonStatus();
  loadSystemInfo();
  setInterval(updateDaemonStatus, 4000);
  await initRenderingButtons();
  await initLogButtons();
  await initDexButtons();
  await initNetButtons();
  initColorBoost();
  initModals();
});