let routePayload = null;

function showStep(n) {
  document.querySelectorAll(".step-tab").forEach((el) => {
    el.classList.toggle("active", Number(el.dataset.step) === n);
  });
  document.querySelectorAll(".panel").forEach((el) => {
    el.classList.toggle("active", Number(el.dataset.panel) === n);
  });
}

document.querySelectorAll(".step-tab").forEach((btn) => {
  btn.addEventListener("click", () => {
    const step = Number(btn.dataset.step);
    if (step === 3 && !routePayload) return;
    if (step === 4 && !routePayload) return;
    showStep(step);
  });
});

document.querySelectorAll("[data-back]").forEach((btn) => {
  btn.addEventListener("click", () => showStep(Number(btn.dataset.back)));
});

async function fetchHealth() {
  const res = await fetch("/api/health");
  if (!res.ok) throw new Error("Health check failed");
  return res.json();
}

function formatHealth(data) {
  const d = data.doctor;
  const s = data.status;
  const lines = [
    data.ok ? "✓ Doctor: OK" : "✗ Doctor: issues found",
    `Skills on disk: ${s.skills_on_disk}`,
    `Matrix: ${s.matrix_version || "—"}`,
    `CapInt pkg: ${s.capint_package || "—"}`
  ];
  if (d.warnings?.length) {
    lines.push("", "Warnings:");
    for (const w of d.warnings.slice(0, 5)) lines.push(`  • ${w}`);
  }
  if (d.issues?.length) {
    lines.push("", "Issues:");
    for (const i of d.issues) lines.push(`  • ${i}`);
    lines.push("", `Hint: ${d.hint}`);
  }
  return lines.join("\n");
}

function renderPlan(payload) {
  const ei = payload.result.execution_intent;
  const ex = ei.explanation || {};
  const card = document.getElementById("plan-card");
  const files = (ex.files_to_read || []).map((f) => `<li><code>${f}</code></li>`).join("");
  const boundary = ei.workspace_boundary?.violated
    ? `<p class="error">Workspace sınırı: ${ei.workspace_boundary.override_hint}</p>`
    : "";
  card.innerHTML = `
    <dl>
      <dt>Capability</dt><dd>${ei.capability}</dd>
      <dt>Resolution</dt><dd>${ei.resolution} (${ei.resolution_status || "installed"})</dd>
      <dt>Neden</dt><dd>${ex.reason_summary || "—"}</dd>
      <dt>Keywords</dt><dd>${(ex.matched_keywords || []).join(", ") || "—"}</dd>
      <dt>Okunacak dosyalar</dt><dd><ul>${files || "<li>—</li>"}</ul></dd>
    </dl>
    ${boundary}
  `;

  const confirmField = document.querySelector(".confirm-field");
  const defaultChoice = ei.confirm_default_option || "apply_now";
  if (ei.plan === "override" || ei.confirm?.mode === "blocked" || !ei.confirm?.enabled) {
    confirmField.hidden = true;
  } else {
    confirmField.hidden = false;
    document.querySelectorAll('input[name="confirm"]').forEach((input) => {
      input.checked = input.value === defaultChoice;
    });
  }
}

document.getElementById("btn-health").addEventListener("click", async () => {
  const out = document.getElementById("health-out");
  const next = document.getElementById("to-step-2");
  out.textContent = "Kontrol ediliyor…";
  try {
    const data = await fetchHealth();
    out.textContent = formatHealth(data);
    next.disabled = false;
  } catch (e) {
    out.textContent = `Hata: ${e.message}`;
    next.disabled = true;
  }
});

document.getElementById("to-step-2").addEventListener("click", () => showStep(2));

document.getElementById("btn-route").addEventListener("click", async () => {
  const task = document.getElementById("task-input").value.trim();
  const errEl = document.getElementById("route-error");
  errEl.hidden = true;
  if (!task) {
    errEl.textContent = "Görev metni boş olamaz.";
    errEl.hidden = false;
    return;
  }
  const btn = document.getElementById("btn-route");
  btn.disabled = true;
  btn.textContent = "Route ediliyor…";
  try {
    const res = await fetch("/api/route", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ task })
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || "Route failed");
    routePayload = data;
    renderPlan(data);
    showStep(3);
  } catch (e) {
    errEl.textContent = e.message;
    errEl.hidden = false;
  } finally {
    btn.disabled = false;
    btn.textContent = "Route et";
  }
});

document.getElementById("to-step-4").addEventListener("click", () => {
  if (!routePayload) return;
  const ei = routePayload.result.execution_intent;
  const choice =
    ei.confirm?.enabled === false
      ? "blocked"
      : document.querySelector('input[name="confirm"]:checked')?.value ||
        ei.confirm_default_option ||
        "apply_now";
  let text = routePayload.chat_copy;
  text += `\n\nSeçimim: ${choice}`;
  document.getElementById("chat-copy").value = text;
  showStep(4);
});

document.getElementById("btn-copy").addEventListener("click", async () => {
  const ta = document.getElementById("chat-copy");
  const status = document.getElementById("copy-status");
  try {
    await navigator.clipboard.writeText(ta.value);
    status.textContent = "Panoya kopyalandı.";
  } catch {
    ta.select();
    document.execCommand("copy");
    status.textContent = "Panoya kopyalandı (fallback).";
  }
});

document.getElementById("btn-restart").addEventListener("click", () => {
  routePayload = null;
  document.getElementById("task-input").value = "";
  document.getElementById("chat-copy").value = "";
  document.getElementById("copy-status").textContent = "";
  showStep(2);
});

showStep(1);
