const form = document.getElementById("pilotIntakeForm");
const output = document.getElementById("pilotOutput");
const copyButton = document.getElementById("copyRequestButton");
const heroAnimation = document.getElementById("heroAnimation");
const submitEndpoint = "/api/pilot-request";

if (heroAnimation) {
  const posterSrc = heroAnimation.dataset.posterSrc;
  const playMs = Number(heroAnimation.dataset.playMs || "0");

  if (posterSrc && playMs > 0) {
    window.setTimeout(() => {
      heroAnimation.src = posterSrc;
    }, playMs);
  }
}

function buildMessage(data) {
  return [
    "Pilot request for SquareMCP",
    "",
    `Name: ${data.name}`,
    `Email: ${data.email}`,
    `Company: ${data.company}`,
    `Role: ${data.role}`,
    `Primary use case: ${data.use_case}`,
    `Timeline: ${data.timeline}`,
    "",
    "Internal systems to connect:",
    data.systems,
    "",
    "Security or compliance requirements:",
    data.requirements,
  ].join("\n");
}

function getFormData() {
  const formData = new FormData(form);
  return Object.fromEntries(formData.entries());
}

function setOutput(message, isReady = false) {
  output.textContent = message;
  output.classList.toggle("ready", isReady);
}

form.addEventListener("submit", async (event) => {
  event.preventDefault();

  if (!form.reportValidity()) {
    return;
  }

  const data = getFormData();
  const message = buildMessage(data);
  setOutput("Submitting your pilot request...", false);

  try {
    const response = await fetch(submitEndpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`submit failed (${response.status})`);
    }

    const result = await response.json();
    setOutput(
      `${message}\n\nSaved to SquareMCP intake successfully.${result.request_id ? `\nRequest ID: ${result.request_id}` : ""}`,
      true
    );
    form.reset();
  } catch {
    setOutput(
      `${message}\n\nSubmission failed. Copy the request below and send it to info@squaremcp.com manually.`,
      true
    );
  }
});

copyButton.addEventListener("click", async () => {
  if (!form.reportValidity()) {
    return;
  }

  const message = buildMessage(getFormData());
  try {
    await navigator.clipboard.writeText(message);
    setOutput(`${message}\n\nCopied to clipboard.`, true);
  } catch {
    setOutput(`${message}\n\nClipboard access failed. Copy the text manually.`, true);
  }
});
