/* assets/js/comments.js
   Handles comment submit + auto-refresh timeline – NO duplicate posts */
document.addEventListener("DOMContentLoaded", () => {
  const form = document.getElementById("comment-form");
  if (!form) return;           // form only exists inside the modal

  // cache bits we toggle
  const spinner   = document.getElementById("comment-spinner");
  const feedback  = document.getElementById("feedback");
  const submitBtn = document.getElementById("submit-comment-btn");
  const defaultBtnText = submitBtn ? submitBtn.textContent : "Post Comment";
  let inFlight = false;

  function setSubmittingState(isSubmitting) {
    if (submitBtn) {
      submitBtn.disabled = !!isSubmitting;
      submitBtn.setAttribute("aria-busy", isSubmitting ? "true" : "false");
      submitBtn.style.opacity = isSubmitting ? "0.75" : "";
      submitBtn.style.cursor = isSubmitting ? "not-allowed" : "";
      submitBtn.textContent = isSubmitting ? "Posting..." : defaultBtnText;
    }

    if (spinner) {
      spinner.style.display = isSubmitting ? "flex" : "none";
      spinner.classList.toggle("hidden", !isSubmitting);
    }
  }

  /** Pull fresh timeline fragment via AJAX and swap it in-place */
  function refreshTimeline(taskGid, gatewayToken) {
    const body = new URLSearchParams({
      action: "afb_get_comments_timeline_html",
      task_gid: taskGid || "",
      gateway_token: gatewayToken || ""
    });

    fetch(afb_ajax.ajax_url, { method: "POST", body })
      .then(r => r.json())
      .then(result => {
        if (!result?.success || !result?.data?.html) return;
        const doc = new DOMParser().parseFromString(result.data.html, "text/html");
        const newTL = doc.getElementById("comments-timeline");
        const currentTL = document.getElementById("comments-timeline");
        if (newTL && currentTL) currentTL.innerHTML = newTL.innerHTML;

        /* Also close the modal (Alpine listens for this) */
        window.dispatchEvent(new CustomEvent("comment-posted"));
      });
  }

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

    if (inFlight) {
      return;
    }
    inFlight = true;

    setSubmittingState(true);
    feedback.textContent = "";

    const fd = new FormData(form);
    const body = new URLSearchParams({
      action      : "afb_post_comment",
      task_gid    : fd.get("task_gid"),
      guest_name  : fd.get("guest_name"),
      guest_email : fd.get("guest_email"),
      gateway_token : fd.get("gateway_token"),
      comment     : fd.get("comment")
    });

    try {
      const res    = await fetch(afb_ajax.ajax_url, { method: "POST", body });
      const result = await res.json();

      if (result.success) {
        feedback.textContent = "Comment posted. It will appear shortly.";
        const currentTaskGid = String(fd.get("task_gid") || "");
        const currentGatewayToken = String(fd.get("gateway_token") || "");
        form.reset();
        refreshTimeline(currentTaskGid, currentGatewayToken);
      } else {
        feedback.textContent =
          "❌ " + (result?.data?.message || "Unable to post comment.");
      }
    } catch {
      feedback.textContent = "❌ Network error.";
    } finally {
      inFlight = false;
      setSubmittingState(false);
    }
  });
});
