const $ = (s) => document.querySelector(s);

let running = false;
let configured = false;

async function refresh() {
  const s = await (await fetch("/api/status")).json();
  running = s.running;
  configured = s.has_key && s.has_endpoint;

  if (!configured) {
    $("#settings").classList.remove("hidden");
    $("#state").classList.add("hidden");
  } else {
    $("#settings").classList.add("hidden");
    $("#state").classList.remove("hidden");
  }

  // Endpoint line
  $("#endpointLine").textContent = s.endpoint || "";

  // Status
  const dot = $("#statusDot");
  const text = $("#statusText");
  dot.className = "status-dot";
  text.className = "status-text";
  if (running) {
    dot.classList.add("running");
    text.classList.add("running");
    text.textContent = "Running";
  } else {
    text.textContent = "Idle";
  }

  // Buttons visibility
  $("#btnStart").classList.toggle("hidden", running);
  $("#btnStop").classList.toggle("hidden", !running);
  $("#btnOpen").classList.toggle("hidden", !running);
}

async function pollLogs() {
  try {
    const { lines } = await (await fetch("/api/logs")).json();
    const logs = $("#logs");
    logs.textContent = lines.join("\n");
    logs.scrollTop = logs.scrollHeight;
  } catch (_) {}
}

// ═══ Save settings ═══
$("#btnSave").addEventListener("click", async () => {
  const fal_key = $("#inpKey").value.trim();
  const endpoint = $("#inpEndpoint").value.trim();
  if (!fal_key || !endpoint) return;
  $("#btnSave").disabled = true;
  await fetch("/api/settings", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ fal_key, endpoint }),
  });
  $("#btnSave").disabled = false;
  await refresh();
});

// ═══ Start / Stop / Open / Edit ═══
$("#btnStart").addEventListener("click", async () => {
  $("#btnStart").disabled = true;
  $("#statusDot").className = "status-dot starting";
  $("#statusText").textContent = "Starting…";
  $("#logsWrap").setAttribute("open", "");
  try {
    const resp = await fetch("/api/start", { method: "POST" });
    if (!resp.ok) throw new Error(await resp.text());
    // Wait a moment for proxy to bind 8188
    for (let i = 0; i < 30; i++) {
      await new Promise((r) => setTimeout(r, 500));
      try {
        await fetch("http://localhost:8188/", { mode: "no-cors" });
        break;
      } catch (_) {}
    }
  } catch (e) {
    $("#statusDot").className = "status-dot error";
    $("#statusText").textContent = "Failed to start";
  } finally {
    $("#btnStart").disabled = false;
    await refresh();
  }
});

$("#btnStop").addEventListener("click", async () => {
  $("#btnStop").disabled = true;
  await fetch("/api/stop", { method: "POST" });
  $("#btnStop").disabled = false;
  await refresh();
});

$("#btnOpen").addEventListener("click", () => {
  window.open("http://localhost:8188", "_blank");
});

$("#btnEditSettings").addEventListener("click", async () => {
  const s = await (await fetch("/api/status")).json();
  $("#inpEndpoint").value = s.endpoint || "";
  $("#inpKey").value = "";
  $("#settings").classList.remove("hidden");
  $("#state").classList.add("hidden");
});

// ═══ Init ═══
refresh();
setInterval(refresh, 3000);
setInterval(pollLogs, 1500);
