"use strict";
initPageLoader(),
    $(function () {
        if (
            ("development" === env && changeDemoImages(),
            feather.replace(),
            initDarkMode(),
            initAnimatedModals(),
            $("#login-submit").on("click", function() {
                var i = $(this);
                i.addClass("is-loading");
                // Get username and password from login form fields
                const username = $("#username").val(); // Assuming username field ID is "username"
                const password = $("#password").val(); // Assuming password field ID is "password"
              
                // Create credentials object
                const credentials = {
                  username: username,
                  password: password
                };
                const xhr = new XMLHttpRequest();
                xhr.open("POST", "https://app.thegreengrowth.com/api/auth");
                xhr.setRequestHeader("Content-Type", "application/json"); // Set content type for JSON data
              
                xhr.onload = function() {
                  if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.data.api_status === 200) {
                      const token = response.data.access_token;
                      const userId = response.data.user_id;
              
                      const data_fetch = "user_data";
                      const data = new FormData();
                      data.append("server_key",  '3b28702903f325a2680b08327783bae8');
                      data.append("fetch", "user_data");
                      data.append("user_id", userId);
              
                      // Fetch user data using the access token and user_id
                      const xhr2 = new XMLHttpRequest();
                      xhr2.open("POST", "https://app.thegreengrowth.com/api/get-user-data?access_token=" + token);
                      xhr2.setRequestHeader("Content-Type", "multipart/form-data"); // Set content type for FormData
              
                      xhr2.onload = function() {
                        if (xhr2.status === 200) {
                          const userDataResponse = JSON.parse(xhr2.responseText);
                          if (userDataResponse.data.api_status === 200) {
                            console.log(userDataResponse.data);
                            localStorage.setItem('EcoJusticeuserdata', JSON.stringify(userDataResponse.data));
                            var notyf = new Notyf();
                            notyf.success('Login successfully!');
                            
                          } else {
                            throw new Error('Failed to fetch user data'); // Throw error for non-200 status
                          }
                        } else {
                          // Handle error fetching user data
                          var notyf = new Notyf();
                          notyf.error('Error fetching user data: ' + xhr2.statusText);
                        
                        }
                      };
              
                      xhr2.onerror = function() {
                        // Handle network errors
                        var notyf = new Notyf();
                          notyf.error('Network error occurred during user data fetch.');
                        
                      };
              
                      xhr2.send(data);
                    } else {
                      let errorData = JSON.parse(xhr.responseText);
                      if (errorData.api_status === "400" && errorData.errors) {
                        var notyf = new Notyf();
                        notyf.error(errorData.errors.error_text);
                        
                         
                      }
                    }
                  } else {
                    // Handle other errors
                    var notyf = new Notyf();
                    notyf.error('An error occurred during login: ' + xhr.statusText);
                  }
                     i.removeClass("is-loading");
                };
              
                xhr.onerror = function() {
                  // Handle network errors
                  var notyf = new Notyf();
                  notyf.error('Network error occurred during login.'); 
                 
                     i.removeClass("is-loading");
                };
              
                xhr.send(JSON.stringify(credentials)); // Send credentials as JSON data
              
               
              }),
           
            $("#forgot-link, #cancel-recover").on("click", function () {
                $(this).closest(".is-form").find("form, .form-text").toggleClass("is-hidden");
            }),
            $("#huro-signup").length)
        ) {
            if (
                ($(".step-icon").on("click", function () {
                    var i = $(this).attr("data-step"),
                        e = $(this).attr("data-progress");
                    $(this).prevAll().addClass("is-done"),
                        $(this).removeClass("is-done").addClass("is-active"),
                        $(this).nextAll().removeClass("is-active is-done"),
                        $("#signup-steps-progress").val(e),
                        void 0 !== i && ($(".signup-columns").addClass("is-hidden"), $("#" + i).removeClass("is-hidden"), $(".avatar-carousel").slick("setPosition"), $(".card-bg").addClass("faded")),
                        "signup-step-1" == i && $(".card-bg").removeClass("faded");
                }),
                $("#confirm-step-1").on("click", function () {
                    var i = $(this);
                    i.addClass("is-loading"),
                        setTimeout(function () {
                            i.removeClass("is-loading"), $(".card-bg").addClass("faded"), $(".signup-steps").removeClass("is-hidden"), $("#signup-step-1, #signup-step-2").toggleClass("is-hidden"), $(".avatar-carousel").slick("setPosition");
                        }, 1e3);
                }),
                $(".avatar-carousel").length)
            ) {
                var i = $(".avatar-carousel");
                i.on("init", function () {
                    feather.replace();
                }),
                    i.on("afterChange", function () {
                        var i = $(".avatar-carousel").find(".slick-current img").attr("src");
                        $(".picture-selector .image-container img").attr("src", i), $("#confirm-step-2").removeClass("is-disabled");
                    }),
                    $(".avatar-carousel").slick({
                        centerMode: !0,
                        dots: !1,
                        infinite: !0,
                        centerPadding: "100px",
                        prevArrow: "<div class='slick-custom is-prev'><i data-feather='chevron-left'></i></div>",
                        nextArrow: "<div class='slick-custom is-next'><i data-feather='chevron-right'></i></div>",
                        slidesToShow: 3,
                    }),
                    $(".slick-slider").on("click", ".slick-slide", function (i) {
                        i.stopPropagation();
                        var e = $(this).data("slick-index");
                        $(".slick-slider").slick("slickCurrentSlide") !== e && $(".slick-slider").slick("slickGoTo", e);
                    });
            }
            FilePond.registerPlugin(FilePondPluginImagePreview, FilePondPluginImageExifOrientation, FilePondPluginFileValidateSize, FilePondPluginImageEdit),
                FilePond.create(document.querySelector(".signup-filepond"), {
                    labelIdle: '<i class="lnil lnil-cloud-upload"></>',
                    imagePreviewHeight: 140,
                    imageCropAspectRatio: "1:1",
                    imageResizeTargetWidth: 140,
                    imageResizeTargetHeight: 140,
                    stylePanelLayout: "compact circle",
                    styleLoadIndicatorPosition: "center bottom",
                    styleProgressIndicatorPosition: "right bottom",
                    styleButtonRemoveItemPosition: "left bottom",
                    styleButtonProcessItemPosition: "right bottom",
                }),
                document.querySelector(".signup-filepond").addEventListener("FilePond:addfile", function (i) {
                    console.log("File added", i.detail), document.getElementById("signup-profile-upload").classList.remove("is-disabled");
                }),
                $("#confirm-step-2").on("click", function () {
                    var i = $(this);
                    i.addClass("is-loading"),
                        setTimeout(function () {
                            i.removeClass("is-loading"), $(".step-icon:nth-child(2)").removeClass("is-inactive").trigger("click");
                        }, 1e3);
                }),
                $("#finish-signup").on("click", function () {
                    var i = $(this);
                    i.addClass("is-loading"),
                        $(".step-icon.is-inactive").removeClass("is-inactive").trigger("click"),
                        setTimeout(function () {
                            i.removeClass("is-loading"), (window.location.href = "/admin-dashboards-personal-1.html");
                        }, 1400);
                });
        }
    });
