/**
 * popup.js — Kling Token Bot Popup Logic
 */

// ─── Helpers ────────────────────────────────────────────────────────────────

const $ = (id) => document.getElementById(id);
const isExpiredToken = (t) => Date.now() / 1000 > t.exp;

function formatExpiry(exp) {
  const diff = Math.floor(exp - Date.now() / 1000);
  if (diff <= 0) return { label: "Expired", cls: "bad" };
  if (diff < 300)  return { label: `${Math.floor(diff / 60)}m ${diff % 60}s`, cls: "warn" };
  if (diff < 3600) return { label: `${Math.floor(diff / 60)} menit`, cls: "good" };
  return { label: `${Math.floor(diff / 3600)}j ${Math.floor((diff % 3600) / 60)}m`, cls: "good" };
}

function showResult(elId, msg, type = "ok") {
  const el = $(elId);
  el.textContent = msg;
  el.className = `result-msg ${type}`;
}

function hideResult(elId) {
  $(elId).className = "result-msg hidden";
}

// ─── Tab navigation ──────────────────────────────────────────────────────────

document.querySelectorAll(".tab").forEach((tab) => {
  tab.addEventListener("click", () => {
    document.querySelectorAll(".tab").forEach((t) => t.classList.remove("active"));
    document.querySelectorAll(".tab-content").forEach((c) => c.classList.remove("active"));
    tab.classList.add("active");
    $(`tab-${tab.dataset.tab}`).classList.add("active");
    
    if (tab.dataset.tab === "bot") {
      startBotStatusPolling();
      stopWizardPolling();
    } else if (tab.dataset.tab === "wizard") {
      stopBotStatusPolling();
      startWizardPolling();
    } else {
      stopBotStatusPolling();
      stopWizardPolling();
    }
  });
});

// ─── Load settings ───────────────────────────────────────────────────────────

let settings = {
  serverUrl: "http://localhost:3001",
  adminPassword: "Tekno@Project03",
  autoSend: false,
  notify: true,
  icloudSetanVoucher: "",
};

async function loadSettings() {
  const result = await chrome.storage.local.get(["serverUrl", "adminPassword", "autoSend", "notify", "icloudSetanVoucher"]);
  settings.serverUrl          = result.serverUrl          || "http://localhost:3001";
  settings.adminPassword       = result.adminPassword       || "Tekno@Project03";
  settings.autoSend           = result.autoSend           ?? false;
  settings.notify             = result.notify             ?? true;
  settings.icloudSetanVoucher = result.icloudSetanVoucher || "";

  $("set-server-url").value = settings.serverUrl;
  $("set-icloud-voucher").value = settings.icloudSetanVoucher;
  $("set-auto-send").checked = settings.autoSend;
  $("set-notify").checked = settings.notify;
}

$("btn-save-settings").addEventListener("click", async () => {
  settings.serverUrl          = $("set-server-url").value.trim() || "http://localhost:3001";
  settings.icloudSetanVoucher = $("set-icloud-voucher").value.trim();
  settings.autoSend           = $("set-auto-send").checked;
  settings.notify             = $("set-notify").checked;

  await chrome.storage.local.set(settings);
  showResult("settings-msg", "✅ Setelan disimpan!", "ok");
  setTimeout(() => hideResult("settings-msg"), 2000);
});

// ─── Connection test ─────────────────────────────────────────────────────────

$("btn-test-conn").addEventListener("click", async () => {
  const url = $("set-server-url").value.trim() || settings.serverUrl;
  showResult("conn-result", "🔌 Mengecek koneksi...", "info");
  try {
    const res = await fetch(`${url}/api/health`, { signal: AbortSignal.timeout(5000) });
    if (res.ok) {
      showResult("conn-result", `✅ Server terhubung di ${url}`, "ok");
    } else {
      showResult("conn-result", `⚠️ Server merespons tapi status ${res.status}`, "err");
    }
  } catch (err) {
    showResult("conn-result", `❌ Tidak bisa terhubung: ${err.message}`, "err");
  }
});

// ─── Token list rendering ────────────────────────────────────────────────────

function renderTokens(tokens) {
  const list = $("token-list");

  const active  = tokens.filter((t) => !isExpiredToken(t));
  const expired = tokens.filter((t) => isExpiredToken(t));

  $("stat-total").textContent  = tokens.length;
  $("stat-active").textContent = active.length;
  $("stat-unsent").textContent = active.filter((t) => !t.sent).length;

  // Status dot
  const dot = $("status-dot");
  if (active.length === 0) { dot.className = "status-dot idle"; }
  else if (active.some((t) => !t.sent)) { dot.className = "status-dot active"; }
  else { dot.className = "status-dot success"; }

  if (tokens.length === 0) {
    list.innerHTML = `
      <div class="empty-state">
        <div class="empty-icon">🔍</div>
        <div class="empty-title">Belum Ada Token</div>
        <div class="empty-sub">Buka weave.figma.com dan login —<br>token akan otomatis tertangkap</div>
      </div>`;
    return;
  }

  list.innerHTML = "";

  // Active tokens first, then expired
  [...active, ...expired].forEach((t) => {
    const expired = isExpiredToken(t);
    const exp = formatExpiry(t.exp);
    const preview = t.token.slice(0, 16) + "…" + t.token.slice(-8);

    const item = document.createElement("div");
    item.className = `token-item ${t.sent ? "sent" : ""} ${expired ? "expired" : ""}`;
    item.innerHTML = `
      <span class="token-dot ${expired ? "expired" : t.sent ? "sent" : "active"}"></span>
      <div class="token-info">
        <div class="token-email">${escapeHtml(t.email)}</div>
        <div class="token-meta">
          <span class="token-exp ${exp.cls}">⏱ ${exp.label}</span>
          <span>${preview}</span>
          ${t.sent ? '<span class="token-sent-badge">✓ Terkirim</span>' : ""}
        </div>
      </div>
      <button class="token-send-btn" data-token='${JSON.stringify(t)}' ${expired ? "disabled" : ""}>
        ${t.sent ? "↩" : "📤"}
      </button>
    `;

    // Send individual token
    item.querySelector(".token-send-btn").addEventListener("click", async (e) => {
      const btn = e.currentTarget;
      btn.disabled = true;
      btn.textContent = "…";
      const tokenData = JSON.parse(btn.dataset.token);
      const result = await chrome.runtime.sendMessage({
        type: "SEND_TOKEN",
        tokenData,
        serverUrl: settings.serverUrl,
        password: settings.adminPassword,
      });
      if (result.ok) {
        btn.textContent = "✓";
        showResult("result-msg", `✅ Token ${tokenData.email} berhasil dikirim ke pool!`, "ok");
        setTimeout(() => { hideResult("result-msg"); loadTokens(); }, 2000);
      } else {
        btn.textContent = "✗";
        showResult("result-msg", `❌ Gagal: ${result.error}`, "err");
        setTimeout(() => btn.disabled = false, 2000);
      }
    });

    list.appendChild(item);
  });
}

function escapeHtml(s) {
  return String(s ?? "").replace(/[&<>"']/g, (c) => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
}

async function loadTokens() {
  const tokens = await chrome.runtime.sendMessage({ type: "GET_TOKENS" });
  renderTokens(tokens || []);
}

// ─── Send all ────────────────────────────────────────────────────────────────

$("btn-send-all").addEventListener("click", async () => {
  $("btn-send-all").disabled = true;
  showResult("result-msg", "📤 Mengirim semua token aktif...", "info");

  const result = await chrome.runtime.sendMessage({
    type: "SEND_ALL_UNSENT",
    serverUrl: settings.serverUrl,
    password: settings.adminPassword,
  });

  const ok  = result.results.filter((r) => r.ok).length;
  const err = result.results.filter((r) => !r.ok).length;

  if (ok > 0) {
    showResult("result-msg", `✅ ${ok} token berhasil dikirim ke pool${err > 0 ? `, ${err} gagal` : ""}`, "ok");
  } else if (err > 0) {
    showResult("result-msg", `❌ Semua gagal: ${result.results[0]?.error || "cek koneksi server"}`, "err");
  } else {
    showResult("result-msg", "ℹ️ Tidak ada token baru yang perlu dikirim", "info");
  }

  $("btn-send-all").disabled = false;
  setTimeout(() => { hideResult("result-msg"); loadTokens(); }, 3000);
});

// ─── Open weave ─────────────────────────────────────────────────────────────

$("btn-open-weave").addEventListener("click", () => {
  chrome.tabs.create({ url: "https://weave.figma.com/" });
  // Show banner briefly
  $("capture-banner").classList.remove("hidden");
  $("banner-text").textContent = "Membuka weave.figma.com… token akan otomatis tertangkap!";
});

// ─── Clear ──────────────────────────────────────────────────────────────────

$("btn-clear").addEventListener("click", async () => {
  if (!confirm("Hapus semua token tersimpan?")) return;
  await chrome.runtime.sendMessage({ type: "CLEAR_TOKENS" });
  showResult("result-msg", "🗑️ Semua token dihapus.", "info");
  setTimeout(() => { hideResult("result-msg"); loadTokens(); }, 1500);
});

// ═══════════════════════════════════════════════════════════════════════════════
// WIZARD TAB LOGIC
// ═══════════════════════════════════════════════════════════════════════════════

let wizardPollInterval = null;

function startWizardPolling() {
  if (wizardPollInterval) clearInterval(wizardPollInterval);
  updateWizardUI();
  wizardPollInterval = setInterval(updateWizardUI, 2000);
}

function stopWizardPolling() {
  if (wizardPollInterval) {
    clearInterval(wizardPollInterval);
    wizardPollInterval = null;
  }
}

const STEP_LABELS = {
  IDLE: "Menunggu...",
  STARTING: "⏳ Memulai...",
  ICLOUD_LOGIN: "1️⃣ Login iCloud Setan",
  GENERATING_EMAIL: "2️⃣ Generate email",
  RESERVING_EMAIL: "3️⃣ Reserve email",
  FIGMA_SIGNUP: "4️⃣ Signup Figma",
  WAITING_CAPTCHA: "5️⃣ Menunggu CAPTCHA...",
  WAITING_VERIFY: "6️⃣ Menunggu verifikasi",
  VERIFYING: "7️⃣ Verifikasi email",
  CAPTURING_TOKEN: "8️⃣ Capture token",
  ROUND_DONE: "✅ Ronde selesai",
  DONE: "🏁 Selesai!",
  STOPPED: "🛑 Dihentikan",
  ERROR: "❌ Error",
};

async function updateWizardUI() {
  try {
    const state = await chrome.runtime.sendMessage({ type: "WIZARD_STATUS" });
    if (!state) return;

    // Badge
    const badge = $("wiz-badge");
    if (state.running) {
      badge.className = "badge-ext badge-running";
      badge.textContent = "RUNNING";
    } else if (state.step === "DONE") {
      badge.className = "badge-ext badge-success";
      badge.textContent = "DONE";
    } else if (state.step === "ERROR" || state.step === "STOPPED") {
      badge.className = "badge-ext badge-error";
      badge.textContent = state.step;
    } else {
      badge.className = "badge-ext badge-idle";
      badge.textContent = "IDLE";
    }

    // Buttons
    if (state.running) {
      $("wiz-start-btn").style.display = "none";
      $("wiz-stop-btn").style.display = "block";
      $("wiz-rounds").disabled = true;
    } else {
      $("wiz-start-btn").style.display = "block";
      $("wiz-start-btn").disabled = false;
      $("wiz-start-btn").textContent = "🚀 Mulai Wizard";
      $("wiz-stop-btn").style.display = "none";
      $("wiz-rounds").disabled = false;
    }

    // Progress
    if (state.totalRequested > 0) {
      $("wiz-progress").classList.remove("hidden");
      const pct = Math.round(((state.completed + state.failed) / state.totalRequested) * 100);
      $("wiz-progress-bar").style.width = `${pct}%`;
      $("wiz-step-label").textContent = STEP_LABELS[state.step] || state.step;
      $("wiz-round-label").textContent = `${state.currentRound}/${state.totalRequested}`;
      $("wiz-ok").textContent = state.completed;
      $("wiz-fail").textContent = state.failed;
      $("wiz-email").textContent = state.email || "-";
    }

    // Log
    if (state.log && state.log.length > 0) {
      const logEl = $("wiz-log");
      logEl.innerHTML = state.log.map(line => {
        let cls = "";
        if (line.includes("❌") || line.includes("Error")) cls = "error";
        else if (line.includes("✅") || line.includes("🎯") || line.includes("🏁")) cls = "success";
        else if (line.includes("⏳") || line.includes("🔄") || line.includes("📬")) cls = "info";
        return `<div class="wiz-log-line ${cls}">${escapeHtml(line)}</div>`;
      }).join("");
    }
  } catch (e) {
    // Extension context invalidated, stop polling
    stopWizardPolling();
  }
}

// Wizard Start
$("wiz-start-btn").addEventListener("click", async () => {
  const rounds = parseInt($("wiz-rounds").value, 10) || 1;
  const revive = $("wiz-revive-toggle") ? $("wiz-revive-toggle").checked : true;
  
  // Check voucher is set
  const { icloudSetanVoucher } = await chrome.storage.local.get("icloudSetanVoucher");
  if (!icloudSetanVoucher) {
    showResult("wiz-msg", "❌ Voucher iCloud Setan belum diatur! Buka tab Setelan dulu.", "err");
    return;
  }

  $("wiz-start-btn").disabled = true;
  $("wiz-start-btn").textContent = "⏳ Memulai...";
  showResult("wiz-msg", `🧙 Memulai wizard untuk ${rounds} akun...`, "info");

  await chrome.runtime.sendMessage({ type: "WIZARD_START", rounds, revive });
  
  setTimeout(() => {
    hideResult("wiz-msg");
    startWizardPolling();
  }, 1500);
});

// Wizard Stop
$("wiz-stop-btn").addEventListener("click", async () => {
  $("wiz-stop-btn").disabled = true;
  $("wiz-stop-btn").textContent = "⏳ Menghentikan...";
  
  await chrome.runtime.sendMessage({ type: "WIZARD_STOP" });
  
  showResult("wiz-msg", "🛑 Wizard dihentikan.", "info");
  setTimeout(() => {
    hideResult("wiz-msg");
    $("wiz-stop-btn").disabled = false;
    $("wiz-stop-btn").textContent = "🛑 Hentikan";
    updateWizardUI();
  }, 1500);
});

// ─── Auto Token Bot Controls (Extension Side) ───────────────────────────────

let botStatusInterval = null;
let nextBotRunTime = null;
let countdownTimerInterval = null;

function startBotStatusPolling() {
  if (botStatusInterval) clearInterval(botStatusInterval);
  updateBotStatus();
  botStatusInterval = setInterval(updateBotStatus, 4000);
}

function stopBotStatusPolling() {
  if (botStatusInterval) {
    clearInterval(botStatusInterval);
    botStatusInterval = null;
  }
  if (countdownTimerInterval) {
    clearInterval(countdownTimerInterval);
    countdownTimerInterval = null;
  }
}

async function updateBotStatus() {
  try {
    const res = await fetch(`${settings.serverUrl}/api/admin/auto-token/status`, {
      headers: { "x-admin-password": settings.adminPassword }
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const st = await res.json();

    // Update Badge
    const badge = $("ext-bot-badge");
    badge.className = "badge-ext " + (st.running ? "badge-running" : "badge-idle");
    badge.textContent = st.running ? "RUNNING" : "IDLE";
    
    if (st.running) {
      $("ext-bot-run-btn").style.display = "none";
      if ($("ext-bot-stop-btn")) $("ext-bot-stop-btn").style.display = "inline-block";
    } else {
      $("ext-bot-run-btn").style.display = "inline-block";
      $("ext-bot-run-btn").disabled = false;
      $("ext-bot-run-btn").textContent = "▶ Jalankan Sekarang";
      if ($("ext-bot-stop-btn")) $("ext-bot-stop-btn").style.display = "none";
    }

    // Update Scheduler Toggle & Select (if not active tab changes to prevent cursor reset)
    if (document.activeElement !== $("ext-scheduler-toggle")) {
      $("ext-scheduler-toggle").checked = st.schedulerActive;
    }
    if (document.activeElement !== $("ext-scheduler-interval")) {
      $("ext-scheduler-interval").value = String(st.intervalMinutes || 45);
    }
    if (document.activeElement !== $("ext-headless-toggle")) {
      $("ext-headless-toggle").checked = st.headless;
    }

    // Last Run Time
    if (st.lastRunAt) {
      const d = new Date(st.lastRunAt).toLocaleString("id-ID", { hour: '2-digit', minute: '2-digit', second: '2-digit' });
      const statusText = st.lastRunResult?.ok ? "✅ Berhasil" : "❌ Gagal";
      $("ext-bot-last-run").textContent = `${d} (${statusText})`;
    } else {
      $("ext-bot-last-run").textContent = "-";
    }

    // Next Auto Run
    if (st.schedulerActive && st.nextRunAt) {
      nextBotRunTime = new Date(st.nextRunAt).getTime();
      $("ext-countdown-row").classList.remove("hidden");
      startLocalCountdown();
    } else {
      nextBotRunTime = null;
      $("ext-countdown-row").classList.add("hidden");
      if (countdownTimerInterval) clearInterval(countdownTimerInterval);
    }
  } catch (err) {
    const badge = $("ext-bot-badge");
    badge.className = "badge-ext badge-error";
    badge.textContent = "OFFLINE";
    $("ext-bot-run-btn").disabled = true;
    $("ext-bot-last-run").textContent = "Gagal konek server";
    $("ext-countdown-row").classList.add("hidden");
  }
}

function startLocalCountdown() {
  if (countdownTimerInterval) clearInterval(countdownTimerInterval);
  countdownTimerInterval = setInterval(() => {
    if (!nextBotRunTime) return;
    const diff = Math.max(0, nextBotRunTime - Date.now());
    const m = Math.floor(diff / 60000);
    const s = Math.floor((diff % 60000) / 1000);
    $("ext-countdown-timer").textContent = `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
    if (diff === 0) nextBotRunTime = null;
  }, 1000);
}

// Event Listeners for Bot Tab
$("ext-bot-run-btn").addEventListener("click", async () => {
  $("ext-bot-run-btn").disabled = true;
  showResult("ext-bot-msg", "▶ Menjalankan bot otomatis...", "info");
  try {
    const res = await fetch(`${settings.serverUrl}/api/admin/auto-token/run`, {
      method: "POST",
      headers: { 
        "Content-Type": "application/json",
        "x-admin-password": settings.adminPassword 
      },
      body: JSON.stringify({ force: true })
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || "Gagal menjalankan");
    showResult("ext-bot-msg", "✅ Bot berhasil dijalankan!", "ok");
    setTimeout(() => { hideResult("ext-bot-msg"); updateBotStatus(); }, 2000);
  } catch (err) {
    showResult("ext-bot-msg", `❌ Error: ${err.message}`, "err");
    setTimeout(() => { hideResult("ext-bot-msg"); updateBotStatus(); }, 2000);
  }
});

$("ext-bot-stop-btn").addEventListener("click", async () => {
  $("ext-bot-stop-btn").disabled = true;
  $("ext-bot-stop-btn").textContent = "⏳ Menghentikan...";
  showResult("ext-bot-msg", "🛑 Menghentikan bot otomatis...", "info");
  try {
    const res = await fetch(`${settings.serverUrl}/api/admin/auto-token/stop`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-admin-password": settings.adminPassword
      }
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || "Gagal menghentikan");
    showResult("ext-bot-msg", "⏹️ Bot berhasil dihentikan!", "ok");
    setTimeout(() => { hideResult("ext-bot-msg"); updateBotStatus(); }, 2000);
  } catch (err) {
    showResult("ext-bot-msg", `❌ Error: ${err.message}`, "err");
    setTimeout(() => { hideResult("ext-bot-msg"); updateBotStatus(); }, 2000);
  } finally {
    $("ext-bot-stop-btn").disabled = false;
    $("ext-bot-stop-btn").textContent = "⏹️ Hentikan Bot";
  }
});

async function saveBotConfig() {
  const enabled = $("ext-scheduler-toggle").checked;
  const intervalMinutes = parseInt($("ext-scheduler-interval").value, 10);
  const headless = $("ext-headless-toggle").checked;
  try {
    const res = await fetch(`${settings.serverUrl}/api/admin/auto-token/config`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-admin-password": settings.adminPassword
      },
      body: JSON.stringify({ enabled, intervalMinutes, headless })
    });
    if (!res.ok) {
      const data = await res.json();
      throw new Error(data.error || "Gagal update config");
    }
    showResult("ext-bot-msg", `⏰ Config updated!`, "ok");
    setTimeout(() => { hideResult("ext-bot-msg"); updateBotStatus(); }, 1500);
  } catch (err) {
    showResult("ext-bot-msg", `❌ Error: ${err.message}`, "err");
    setTimeout(() => { hideResult("ext-bot-msg"); updateBotStatus(); }, 2000);
  }
}

$("ext-scheduler-toggle").addEventListener("change", saveBotConfig);
$("ext-scheduler-interval").addEventListener("change", saveBotConfig);
$("ext-headless-toggle").addEventListener("change", saveBotConfig);

$("btn-open-icloud-setan").addEventListener("click", () => {
  chrome.tabs.create({ url: "https://icloud.texaproject.com/" });
});

// ─── Init ────────────────────────────────────────────────────────────────────

(async function init() {
  await loadSettings();
  await loadTokens();
  // Refresh tokens every 15 seconds
  setInterval(loadTokens, 15000);

  // Keep-alive port connection to prevent Service Worker suspension
  try {
    let port = chrome.runtime.connect({ name: "wizard-keepalive" });
    port.onDisconnect.addListener(() => {
      setTimeout(() => {
        try { port = chrome.runtime.connect({ name: "wizard-keepalive" }); } catch (e) {}
      }, 1000);
    });
    setInterval(() => {
      try { port.postMessage({ type: "ping" }); } catch (e) {}
    }, 8000);
  } catch (e) {}
})();
