(function () {
  if (window.cmbirdAiQaBound) {
    return;
  }
  window.cmbirdAiQaBound = true;

  var config = window.cmbirdAiQaConfig || {};
  var ajaxUrl = config.ajaxUrl || "";
  var action = config.action || "cmbird_ai_product_qa";
  var messages = config.messages || {};

  function msg(key, fallback) {
    return messages[key] || fallback;
  }

  document.addEventListener("click", async function (e) {
    var btn = e.target.closest(".cmbird-ai-qa-submit");
    if (!btn) {
      return;
    }

    var box = btn.closest(".cmbird-ai-qa-box");
    if (!box) {
      return;
    }

    var input = box.querySelector(".cmbird-ai-qa-input");
    var feedback = box.querySelector(".cmbird-ai-qa-feedback");
    var history = box.querySelector(".cmbird-ai-qa-history");
    var hpA = box.querySelector(".cmbird-ai-qa-hp-a");
    var hpB = box.querySelector(".cmbird-ai-qa-hp-b");

    if (!input || !feedback || !history || !hpA || !hpB) {
      return;
    }

    var question = (input.value || "").trim();
    if (!question) {
      feedback.style.display = "block";
      feedback.textContent = msg(
        "enterQuestion",
        "Please enter a question first.",
      );
      return;
    }

    feedback.style.display = "none";
    btn.disabled = true;

    try {
      var params = new URLSearchParams();
      params.set("action", action);
      params.set("product_id", btn.dataset.productId || "");
      params.set("question", question);
      params.set("nonce", btn.dataset.nonce || "");
      params.set("hp_session", btn.dataset.hpSession || "");
      params.set("hp_token", btn.dataset.hpToken || "");
      params.set("hp_created", btn.dataset.hpCreated || "");
      params.set("hp_field_a_name", btn.dataset.hpFieldAName || "");
      params.set("hp_field_b_name", btn.dataset.hpFieldBName || "");

      if (btn.dataset.hpFieldAName) {
        params.set(btn.dataset.hpFieldAName, hpA.value || "");
      }
      if (btn.dataset.hpFieldBName) {
        params.set(btn.dataset.hpFieldBName, hpB.value || "");
      }

      var res = await fetch(ajaxUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        },
        body: params.toString(),
      });

      var data = await res.json();
      if (!data || !data.success) {
        throw new Error(
          data && data.data && data.data.message
            ? data.data.message
            : msg("answerError", "Unable to answer this question right now."),
        );
      }

      var empty = history.querySelector(".cmbird-ai-qa-empty");
      if (empty) {
        empty.remove();
      }

      var row = document.createElement("details");
      row.className = "cmbird-ai-qa-item";
      row.style.background = "#fff";
      row.style.border = "1px solid #e2e8f0";
      row.style.borderRadius = "8px";
      row.style.padding = "0 10px";

      var summary = document.createElement("summary");
      summary.style.padding = "9px 0";
      summary.style.cursor = "pointer";
      summary.style.color = "#0f172a";

      var qStrong = document.createElement("strong");
      qStrong.textContent = msg("qLabel", "Q:");
      summary.appendChild(qStrong);
      summary.appendChild(document.createTextNode(" " + question));

      var body = document.createElement("div");
      body.style.padding = "0 0 10px";
      body.style.color = "#334155";

      var p = document.createElement("p");
      p.style.margin = "0";

      var aStrong = document.createElement("strong");
      aStrong.textContent = msg("aLabel", "A:");
      p.appendChild(aStrong);
      p.appendChild(
        document.createTextNode(" " + String(data.data.answer || "")),
      );

      body.appendChild(p);
      row.appendChild(summary);
      row.appendChild(body);
      history.prepend(row);
      input.value = "";
    } catch (err) {
      feedback.style.display = "block";
      feedback.textContent =
        err && err.message
          ? err.message
          : msg("answerError", "Unable to answer this question right now.");
    } finally {
      btn.disabled = false;
    }
  });
})();
