jQuery(document).ready(function ($) {
  const $purchaseBtn = $("#storevoiceai-search-numbers");
  const $areaCodeInput = $("#storevoiceai-area-code");
  const $listContainer = $("#storevoiceai-phone-numbers-list");
  const $phoneSetup = $purchaseBtn.closest(".phone-setup");
  const $phoneSetupGrid = $phoneSetup.find(".phone-setup-grid");

  if (!$purchaseBtn.length || !$listContainer.length) {
    return;
  }

  const defaultBtnLabel = $purchaseBtn.text().trim() || "Get Phone Number";
  $purchaseBtn.data("default-label", defaultBtnLabel);
  $purchaseBtn.html(
    '<span class="search-button-label">' + defaultBtnLabel + "</span>",
  );

  if (!storevoiceaiCallLogger.is_subscribed) {
    renderSubscriptionWall();
  }

  function showNotice(type, message, options) {
    const opts = options || {};
    window.StoreVoiceAINotice.show({
      target: $listContainer,
      position: "before",
      type: type,
      message: message,
      autoDismiss: opts.autoDismiss,
      duration: opts.duration,
      action: opts.action,
    });
  }

  function getSafePricingUrl() {
    const rawUrl = storevoiceaiCallLogger.pricing_url || "";
    if (!rawUrl) return "";

    try {
      const parsed = new URL(rawUrl, window.location.origin);
      if (parsed.protocol === "http:" || parsed.protocol === "https:") {
        return parsed.toString();
      }
    } catch (e) {
      return "";
    }

    return "";
  }

  function setCreationFieldsVisible(visible) {
    $phoneSetupGrid
      .prop("hidden", !visible)
      .toggleClass("phone-setup-grid--hidden", !visible);
    $phoneSetupGrid.find("input, select, button").prop("disabled", !visible);
    if (visible) {
      setButtonEnabled($areaCodeInput.val().trim().length > 0);
    }
  }

  function renderSubscriptionWall() {
    const safeUrl = getSafePricingUrl();
    const $wall = $('<div class="phone-subscription-wall" role="status">');
    const $content = $('<div class="phone-subscription-wall__content">');

    $content.append(
      '<span class="dashicons dashicons-lock phone-subscription-wall__icon" aria-hidden="true"></span>',
    );
    $content.append($("<strong>").text("Can't use this feature"));
    $content.append(
      $("<p>").text(
        "Subscribe to add a dedicated phone number customers can call directly to reach your AI agent.",
      ),
    );

    if (safeUrl) {
      $content.append(
        $('<a class="button button-primary phone-subscription-wall__action">')
          .attr("href", safeUrl)
          .text("View pricing"),
      );
    }

    $wall.append($content);
    $phoneSetup.addClass("phone-setup--locked").append($wall);
  }

  function hasPhoneNumber(numbers) {
    return (numbers || []).some(function (item) {
      return extractNumber(item) !== "";
    });
  }

  // Block actions until an agent has been created
  if (!storevoiceaiCallLogger.has_agent) {
    $purchaseBtn
      .prop("disabled", true)
      .addClass("is-disabled")
      .find(".search-button-label")
      .text("Create agent first");
    $listContainer.html(
      '<p class="info">Please create a support agent before getting a phone number.</p>',
    );
    // No agent means no numbers — let the transfer gate resolve out of its
    // loading state instead of leaving the shimmer up forever.
    $(document).trigger("storevoiceai:phoneNumbersChanged", {
      hasPhoneNumber: false,
      numbers: [],
    });
    return;
  }

  function setButtonEnabled(enabled) {
    $purchaseBtn
      .prop("disabled", !enabled)
      .toggleClass("is-disabled", !enabled);
  }

  function setButtonLoading(loading, label) {
    if (loading) {
      $purchaseBtn
        .prop("disabled", true)
        .addClass("is-loading")
        .attr("aria-busy", "true")
        .find(".search-button-label")
        .text(label || "Working…");
    } else {
      $purchaseBtn
        .removeClass("is-loading")
        .removeAttr("aria-busy")
        .find(".search-button-label")
        .text($purchaseBtn.data("default-label"));
      setButtonEnabled($areaCodeInput.val().trim().length > 0);
    }
  }

  function extractNumber(item) {
    if (!item) return "";
    if (typeof item === "string") return item;
    return item.phoneNumber || item.number || item.id || "";
  }

  function renderList(numbers) {
    $listContainer.empty();
    const hasNumber = hasPhoneNumber(numbers);
    $(document).trigger("storevoiceai:phoneNumbersChanged", {
      hasPhoneNumber: hasNumber,
      numbers: numbers || [],
    });
    setCreationFieldsVisible(!hasNumber);

    if (!hasNumber) {
      $listContainer.html(
        '<div class="phone-empty-state" role="status">' +
          '<span class="dashicons dashicons-phone" aria-hidden="true"></span>' +
          "<div>" +
            "<strong>No phone numbers yet</strong>" +
            "<p>Enter an area code and click Get Phone Number to provision your first number.</p>" +
          "</div>" +
        "</div>",
      );
      return;
    }

    const agentName =
      ($("#storevoiceai-asst-name").val() || "").trim() || "your AI agent";
    const $heading = $("<p>")
      .addClass("phone-numbers-list__description")
      .text(
        "Customers can call this phone number to speak with " + agentName + ".",
      );
    const $list = $("<ul>").addClass("phone-numbers-list");

    numbers.forEach(function (item) {
      const phoneNumber = extractNumber(item);
      if (!phoneNumber) return;

      const $row = $("<li>").addClass("phone-numbers-list__item");
      $row.append(
        $("<span>")
          .addClass("phone-numbers-list__icon")
          .attr("aria-hidden", "true")
          .html('<span class="dashicons dashicons-phone"></span>'),
      );
      $row.append(
        $("<span>").addClass("phone-numbers-list__number").text(phoneNumber),
      );
      $row.append(
        $("<button>")
          .attr("type", "button")
          .addClass("phone-numbers-list__delete")
          .attr("aria-label", "Delete phone number " + phoneNumber)
          .attr("data-number", phoneNumber)
          .html('<span class="dashicons dashicons-trash" aria-hidden="true"></span>'),
      );
      $list.append($row);
    });

    $listContainer.append($heading).append($list);
  }

  // Confirmation modal
  const $modal = $(
    '<div class="phone-modal" hidden role="dialog" aria-modal="true" aria-labelledby="phone-modal-title">' +
      '<div class="phone-modal__backdrop" data-dismiss></div>' +
      '<div class="phone-modal__dialog" role="document">' +
        '<h3 id="phone-modal-title" class="phone-modal__title">Delete phone number?</h3>' +
        '<p class="phone-modal__body"></p>' +
        '<div class="phone-modal__actions">' +
          '<button type="button" class="button phone-modal__cancel" data-dismiss>Cancel</button>' +
          '<button type="button" class="button button-primary phone-modal__confirm">Delete</button>' +
        '</div>' +
      '</div>' +
    '</div>',
  );
  $("body").append($modal);

  let pendingDeleteNumber = null;
  let pendingDeleteRow = null;
  let currentNumbers = [];

  function openModal(phoneNumber, $row) {
    pendingDeleteNumber = phoneNumber;
    pendingDeleteRow = $row;
    $modal
      .find(".phone-modal__body")
      .text(
        "Are you sure you want to delete " +
          phoneNumber +
          "? This action cannot be undone.",
      );
    $modal.find(".phone-modal__confirm").prop("disabled", false).text("Delete");
    $modal.removeAttr("hidden");
    requestAnimationFrame(function () {
      $modal.addClass("phone-modal--is-visible");
    });
    $modal.find(".phone-modal__confirm").trigger("focus");
  }

  function closeModal() {
    $modal.removeClass("phone-modal--is-visible");
    setTimeout(function () {
      $modal.attr("hidden", true);
    }, 150);
    pendingDeleteNumber = null;
    pendingDeleteRow = null;
  }

  $modal.on("click", "[data-dismiss]", function () {
    if ($modal.find(".phone-modal__confirm").prop("disabled")) return;
    closeModal();
  });

  $(document).on("keydown.phoneModal", function (e) {
    if (e.key === "Escape" && !$modal.attr("hidden")) {
      if ($modal.find(".phone-modal__confirm").prop("disabled")) return;
      closeModal();
    }
  });

  $modal.on("click", ".phone-modal__confirm", function () {
    if (!pendingDeleteNumber) return;
    const phoneNumber = pendingDeleteNumber;
    const $row = pendingDeleteRow;
    const $confirmBtn = $(this);

    $confirmBtn.prop("disabled", true).text("Deleting…");

    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "storevoiceai_delete_phone_number",
        phone_number: phoneNumber,
        nonce: storevoiceaiCallLogger.nonce,
      },
      success: function (response) {
        if (response.success) {
          currentNumbers = currentNumbers.filter(function (item) {
            return extractNumber(item) !== phoneNumber;
          });

          if ($row && $row.length) {
            $row.fadeOut(150, function () {
              if (!currentNumbers.length) {
                renderList(currentNumbers);
              } else {
                $row.remove();
              }
            });
          } else {
            renderList(currentNumbers);
          }

          closeModal();
          showNotice(
            "success",
            "Phone number " + phoneNumber + " deleted successfully.",
          );
        } else {
          const msg =
            (response.data && response.data.message) ||
            "Failed to delete phone number.";
          $confirmBtn.prop("disabled", false).text("Delete");
          showNotice("error", msg);
        }
      },
      error: function () {
        $confirmBtn.prop("disabled", false).text("Delete");
        showNotice(
          "error",
          "Failed to delete phone number. Please try again.",
        );
      },
    });
  });

  $listContainer.on("click", ".phone-numbers-list__delete", function () {
    const $btn = $(this);
    const phoneNumber = $btn.attr("data-number");
    if (!phoneNumber) return;
    openModal(phoneNumber, $btn.closest(".phone-numbers-list__item"));
  });

  function showLoadingList() {
    setCreationFieldsVisible(false);
    $listContainer.html(
      '<div class="phone-number-skeleton" role="status" aria-label="Loading phone numbers">' +
        '<div class="phone-number-skeleton__line phone-number-skeleton__line--text"></div>' +
        '<div class="phone-number-skeleton__card">' +
          '<div class="phone-number-skeleton__icon"></div>' +
          '<div class="phone-number-skeleton__line phone-number-skeleton__line--number"></div>' +
          '<div class="phone-number-skeleton__action"></div>' +
        "</div>" +
      "</div>",
    );
  }

  function showError(message) {
    setCreationFieldsVisible(true);
    $listContainer.empty().append(
      $("<p>").addClass("error").text(message || "Something went wrong."),
    );
    // Couldn't confirm a number — clear the transfer shimmer and fall back to
    // the locked gate rather than leaving the loader spinning indefinitely.
    $(document).trigger("storevoiceai:phoneNumbersChanged", {
      hasPhoneNumber: false,
      numbers: [],
    });
  }

  function loadPhoneNumbers() {
    showLoadingList();
    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "storevoiceai_get_phone_numbers",
        nonce: storevoiceaiCallLogger.nonce,
      },
      success: function (response) {
        if (response.success) {
          currentNumbers = response.data.numbers || [];
          renderList(currentNumbers);
        } else {
          const msg = (response.data && response.data.message) || "Unknown error";
          showError("Error: " + msg);
        }
      },
      error: function () {
        showError("Failed to load phone numbers. Please refresh the page.");
      },
    });
  }

  // Initial state: disabled until something is typed
  setButtonEnabled($areaCodeInput.val().trim().length > 0);

  $areaCodeInput.on("input", function () {
    if ($purchaseBtn.hasClass("is-loading")) return;
    setButtonEnabled($(this).val().trim().length > 0);
  });

  $areaCodeInput.on("keydown", function (e) {
    if (e.key === "Enter" && !$purchaseBtn.prop("disabled")) {
      e.preventDefault();
      $purchaseBtn.trigger("click");
    }
  });

  $("#storevoiceai-asst-name").on("input", function () {
    if (hasPhoneNumber(currentNumbers)) {
      renderList(currentNumbers);
    }
  });

  function purchaseNumber(areaCode) {
    if (!storevoiceaiCallLogger.is_subscribed) {
      renderList(currentNumbers);
      return;
    }

    if (hasPhoneNumber(currentNumbers)) {
      renderList(currentNumbers);
      showNotice(
        "error",
        "Your store already has a phone number. Delete it before getting another one.",
        { autoDismiss: false },
      );
      return;
    }

    const data = {
      action: "storevoiceai_purchase_phone_number",
      nonce: storevoiceaiCallLogger.nonce,
    };
    if (areaCode) {
      data.area_code = areaCode;
    }

    setButtonLoading(true, "Getting number…");

    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: data,
      success: function (response) {
        if (response.success) {
          const newNumber = response.data && response.data.number;
          const phone = extractNumber(newNumber);

          if (phone) {
            currentNumbers = [newNumber].concat(currentNumbers);
            renderList(currentNumbers);
            $areaCodeInput.val("");
            showNotice(
              "success",
              "Phone number " + phone + " purchased successfully.",
            );
          } else {
            showNoUnavailableNotice(areaCode);
          }
        } else {
          const msg =
            (response.data && response.data.message) ||
            (areaCode
              ? "No phone number is available in that area code."
              : "No phone number is available right now.");
          if (msg.indexOf("already has a phone number") !== -1) {
            renderList(currentNumbers);
            showNotice("error", msg, { autoDismiss: false });
            return;
          }
          showNoUnavailableNotice(areaCode, msg);
        }
      },
      error: function () {
        showNotice("error", "Failed to get phone number. Please try again.");
      },
      complete: function () {
        setButtonLoading(false);
      },
    });
  }

  function showNoUnavailableNotice(areaCode, customMessage) {
    const message =
      customMessage ||
      (areaCode
        ? "No phone number is available in area code " + areaCode + "."
        : "No phone number is available right now.");

    const options = { autoDismiss: false };
    if (areaCode) {
      options.action = {
        label: "Get me any available number",
        onClick: function ($notice) {
          window.StoreVoiceAINotice.hide($notice);
          purchaseNumber(null);
        },
      };
    }
    showNotice("error", message, options);
  }

  $purchaseBtn.on("click", function () {
    const areaCode = $areaCodeInput.val().trim();
    if (!areaCode) {
      setButtonEnabled(false);
      return;
    }
    purchaseNumber(areaCode);
  });

  loadPhoneNumbers();
});
