/* fitfilerunner — client-side logic */

const workoutEl = document.getElementById("workout");
const nameEl = document.getElementById("name");
const btn = document.getElementById("generate");
const errorEl = document.getElementById("error");
const successEl = document.getElementById("success");

// Click-to-load examples
document.querySelectorAll(".examples code").forEach((el) => {
  el.addEventListener("click", () => {
    workoutEl.value = el.textContent;
    workoutEl.focus();
    hideFeedback();
  });
});

btn.addEventListener("click", async () => {
  const workout = workoutEl.value.trim();
  if (!workout) {
    showError("Please enter a workout.");
    return;
  }

  hideFeedback();
  btn.disabled = true;
  btn.setAttribute("aria-busy", "true");
  btn.textContent = "Generating\u2026";

  try {
    const resp = await fetch("/api/generate", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        workout: workout,
        name: nameEl.value.trim() || null,
      }),
    });

    if (!resp.ok) {
      const data = await resp.json();
      throw new Error(data.detail || "Unknown error");
    }

    // Extract filename from Content-Disposition header
    const disposition = resp.headers.get("Content-Disposition") || "";
    const match = disposition.match(/filename="(.+?)"/);
    const filename = match ? match[1] : "workout.fit";

    const blob = await resp.blob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);

    showSuccess("Download started: " + filename);
  } catch (err) {
    showError(err.message);
  } finally {
    btn.disabled = false;
    btn.removeAttribute("aria-busy");
    btn.textContent = "Generate & Download";
  }
});

function hideFeedback() {
  errorEl.style.display = "none";
  successEl.style.display = "none";
}

function showError(msg) {
  errorEl.textContent = msg;
  errorEl.style.display = "block";
  successEl.style.display = "none";
}

function showSuccess(msg) {
  successEl.textContent = msg;
  successEl.style.display = "block";
  errorEl.style.display = "none";
}
