jQuery(document).ready(function ($) {
  var $select = $("#storevoiceai-kb-page-select");
  var $response = $("#storevoiceai-kb-response");

  if (!$select.length) return;

  // Fetch the allowed pages (About, Services, Contact)
  $.ajax({
    url: ajaxurl,
    type: "POST",
    data: {
      action: "storevoiceai_get_knowledge_base_pages",
      nonce: storevoiceaiCallLogger.nonce,
    },
    success: function (response) {
      if (!response.success) {
        $response.html(
          '<p class="kb-error">Could not load available pages.</p>',
        );
        return;
      }

      var allowedPages = response.data.pages; // [{id, title}, ...]

      // Collect IDs already rendered by PHP as pre-selected options
      var savedIds = [];
      $select.find("option").each(function () {
        savedIds.push(parseInt($(this).val()));
      });

      // Append allowed pages that are NOT already in the markup
      // (avoids duplicate options for saved pages)
      allowedPages.forEach(function (page) {
        var alreadyInDom = savedIds.indexOf(parseInt(page.id)) !== -1;
        if (!alreadyInDom) {
          $select.append(new Option(page.title, page.id, false, false));
        }
      });

      // Init Select2 — static options only, no AJAX
      $select.select2({
        placeholder: "Select pages to include...",
        minimumInputLength: 0, // show all options on click
        width: "100%",
        // No ajax: property — keeps dropdown to our three options only
      });
    },
    error: function () {
      $response.html('<p class="kb-error">Failed to load available pages.</p>');
    },
  });

  // User selects a page
  $select.on("select2:select", function () {
    syncKnowledgeBasePages();
  });

  // User removes a page tag
  $select.on("select2:unselect", function () {
    syncKnowledgeBasePages();
  });

  // Send full current selection to PHP on every change
  function syncKnowledgeBasePages() {
    var selectedIds = $select.val(); // full array of currently selected IDs

    $response.html(
      '<div class="phone-search-loading" role="status">' +
        '<span class="phone-spinner" aria-hidden="true"></span>' +
        "<span>Saving knowledge base…</span>" +
        "</div>",
    );

    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "storevoiceai_create_knowledge_base_pages",
        page_ids: selectedIds || [],
        nonce: storevoiceaiCallLogger.nonce,
      },
      success: function (response) {
        $response.empty();
        if (response.success) {
          window.StoreVoiceAINotice.show({
            target: $select.next(".select2").length
              ? $select.next(".select2")
              : $select,
            type: "success",
            message:
              response.data.message || "Knowledge base updated successfully.",
            position: "after",
          });
        } else {
          var errMsg =
            (response.data && (response.data.message || response.data)) ||
            "Failed to save knowledge base.";
          window.StoreVoiceAINotice.show({
            target: $select.next(".select2").length
              ? $select.next(".select2")
              : $select,
            type: "error",
            message:
              typeof errMsg === "string"
                ? errMsg
                : "Failed to save knowledge base.",
            position: "after",
          });
        }
      },
      error: function () {
        $response.empty();
        window.StoreVoiceAINotice.show({
          target: $select.next(".select2").length
            ? $select.next(".select2")
            : $select,
          type: "error",
          message: "Failed to save knowledge base. Please try again.",
          position: "after",
        });
      },
    });
  }
});
