/* global jQuery */
(function ($) {
  "use strict";

  function setLoadingState(isLoading) {
    $("#loginSubmitBtn").prop("disabled", isLoading);
    $("#loginSpinner").toggleClass("d-none", !isLoading);
    $("#loginSubmitBtn .btn-label").text(isLoading ? "Signing in..." : "Login to Dashboard");
  }

  function showAlert(type, message) {
    const $alert = $("#loginAlert");
    $alert
      .removeClass("d-none alert-success alert-danger")
      .addClass("alert-" + type)
      .text(message);
  }

  function clearAlert() {
    $("#loginAlert").addClass("d-none").removeClass("alert-success alert-danger").text("");
  }

  $(function () {
    const $form = $("#adminLoginForm");

    $("#togglePassword").on("click", function () {
      const $password = $("#password");
      const isPassword = $password.attr("type") === "password";
      $password.attr("type", isPassword ? "text" : "password");
      $(this).find("i").toggleClass("bi-eye bi-eye-slash");
    });

    $form.on("submit", function (e) {
      e.preventDefault();
      clearAlert();

      if (!this.checkValidity()) {
        $form.addClass("was-validated");
        return;
      }

      setLoadingState(true);

      $.ajax({
        url: "../login.php",
        type: "POST",
        dataType: "json",
        data: $form.serialize()
        //timeout: 12000
      })
        .done(function (response) {   
          if (response && response.success) {
            showAlert("success", response.message || "Login successful. Redirecting...");
            window.setTimeout(function () {
              window.location.href = "index.html";
            }, 800);
            return;
          }
          showAlert("danger", (response && response.message) || "Invalid credentials.");
        })
        .fail(function () { 
          showAlert("danger", "Unable to reach login service. Please try again.");
        })
        .always(function () {
          setLoadingState(false);
        });
    });
  });
})(jQuery);

