document.addEventListener("DOMContentLoaded", function () {
    const { __, _x, _n, sprintf } = wp.i18n;

    let selectedImageURL = "";
    let default_user_avatar_url = author_kit_user_script_vars.default_user_avatar_url;

    const uploadAvatarButton = document.getElementById("avatar-preview");
    const avatarField = document.getElementById("avatar");


    initMediaUploader();
    toggleFieldsForGuestRole();
    handleFieldValidationOnChange();
    author_kit_add_or_edit_user();
    display_name_on_fields_change();
    togglePassword();


    // Initializes the WordPress Media Uploader.
    function initMediaUploader() {
        const mediaUploader = wp.media({
            title: __("Select or Upload an Avatar", "author-kit"),
            button: {
                text: __("Use This Avatar", "author-kit"),
            },
            multiple: false,
        });

        // Open the media uploader when the button is clicked
        uploadAvatarButton.addEventListener("click", function (e) {
            e.preventDefault();
            mediaUploader.open();
        });

        // Handle the image selection
        mediaUploader.on("select", function () {
            const attachment = mediaUploader.state().get("selection").first().toJSON();
            selectedImageURL = attachment.url;
            updateAvatarPreview(selectedImageURL);
        });
    }

    /**
     * Updates the avatar preview with the selected image URL.
     * @param {string} url - The URL of the selected image.
     */
    function updateAvatarPreview(url) {
        uploadAvatarButton.src = url || default_user_avatar_url;
        avatarField.value = url || "";
    }

    // Removes the current avatar preview and resets to the default image.
    window.removePhoto = function () {
        selectedImageURL = "";
        updateAvatarPreview();
    };


    // Toggle fields based on selected role
    function toggleFieldsForGuestRole() {
        const roleField = document.getElementById("role");
        const emailField = document.getElementById("email-field");
        const passwordField = document.getElementById("password-field");
        const sendEmailField = document.getElementById("send-email-group");

        roleField.addEventListener("change", function () {
            if (this.value === "guest") {
                emailField.style.display = "none";
                passwordField.style.display = "none";
                sendEmailField.style.display = "none";
            } else {
                emailField.style.display = "block";
                passwordField.style.display = "block";
                sendEmailField.style.display = "block";
            }
        });
    }

    // Function to toggle password visibility
    function togglePassword() {
        // Get the password input field
        const passwordField = document.getElementById("password");
        // Get the eye icon element
        const toggleIcon = document.querySelector(".toggle-password");

        toggleIcon.addEventListener("click", function () {

            // If input is currently of type "password", change it to "text"
            if (passwordField.type === "password") {
                passwordField.type = "text";    // Show the password
                toggleIcon.innerHTML = '<i class="fa-solid fa-eye-slash"></i>';  // Change icon to "hide" state
            } else {
                passwordField.type = "password"; // Hide the password
                toggleIcon.innerHTML = '<i class="fa-solid fa-eye"></i>';  // Change icon back to "show" state
            }
        });

    }

    // Validate an individual field
    function validateField(field, errorMessage) {
        const errorElement = document.getElementById(`${field.id}-error`);
        if (!field.checkValidity()) {
            errorElement.textContent = errorMessage;
            errorElement.style.display = "block";
            return false;
        } else {
            errorElement.textContent = ""; // Clear error message
            errorElement.style.display = "none";
            return true;
        }
    }

    // Attach validation checks to field change events
    function handleFieldValidationOnChange() {
        const fieldsToValidate = [
            {
                field: document.getElementById("role"),
                errorMessage: __("Please select a valid role.", "author-kit"),
            },
            {
                field: document.getElementById("username"),
                errorMessage: __("Username is required and must be 3-60 characters long.", "author-kit"),
            },
            {
                field: document.getElementById("email"),
                errorMessage: __("Please enter a valid email address.", "author-kit"),
            },
            {
                field: document.getElementById("first-name"),
                errorMessage: __("First name must be less than 50 characters.", "author-kit"),
            },
            {
                field: document.getElementById("last-name"),
                errorMessage: __("Last name must be less than 50 characters.", "author-kit"),
            },
            {
                field: document.getElementById("password"),
                errorMessage: __("Password must be at least 8 characters and include uppercase, lowercase, a number, and a special character.", "author-kit"),
            },
        ];

        fieldsToValidate.forEach(({ field, errorMessage }) => {
            field.addEventListener("change", function () {
                validateField(field, errorMessage);
            });
        });
    }

    // Handle form validation and submission
    function author_kit_add_or_edit_user() {
        document.getElementById("add-new-user-button").addEventListener("click", function (event) {
            event.preventDefault();

            user_action = document.getElementById("user-action")?.value || 'add-new';
            toast_text = user_action == 'edit' ? __('Updating User... Please Wait!', 'author-kit') : __('Adding New User... Please Wait!', 'author-kit');

            show_author_kit_toast(toast_text, 'performing');

            // Validate all fields
            const isRoleValid = validateField(
                document.getElementById("role"),
                __("Please select a valid role.", "author-kit")
            );

            const isUsernameValid = validateField(
                document.getElementById("username"),
                __("Username is required and must be 3-60 characters long.", "author-kit")
            );

            const emailDiv = document.getElementById("email-field");
            const emailField = document.getElementById("email");
            let isEmailValid = true;

            // Only validate email and password if they are visible
            if (emailDiv.style.display != 'none') {
                isEmailValid = validateField(
                    emailField,
                    __("Please enter a valid email address.", "author-kit")
                );
            }

            const isFirstNameValid = validateField(
                document.getElementById("first-name"),
                __("First name must be less than 50 characters.", "author-kit")
            );

            const isLastNameValid = validateField(
                document.getElementById("last-name"),
                __("Last name must be less than 50 characters.", "author-kit")
            );

            const passwordDiv = document.getElementById("password-field");
            const passwordField = document.getElementById("password");
            let isPasswordValid = true;

            // Only validate email and password if they are visible
            if (passwordDiv.style.display != 'none') {
                isPasswordValid = validateField(
                    passwordField,
                    __("Password must be at least 8 characters and include uppercase, lowercase, a number, and a special character.", "author-kit")
                );
            }

            const email_notification_field = document.getElementById("send-email") || '';
            // If all validations pass, submit the form
            if (
                isRoleValid &&
                isUsernameValid &&
                isEmailValid &&
                isFirstNameValid &&
                isLastNameValid &&
                isPasswordValid
            ) {

                const formData = {
                    action: "author_kit_add_or_edit_user",
                    nonce: author_kit_user_script_vars.nonce,
                    user_id: document.getElementById("user-id")?.value || 0,
                    username: document.getElementById("username")?.value || '',
                    email: emailField?.value || '',
                    first_name: document.getElementById("first-name")?.value || '',
                    last_name: document.getElementById("last-name")?.value || '',
                    display_name: document.getElementById("display-name") ? document.getElementById("display-name").value : username,
                    role: document.getElementById("role")?.value || '',
                    user_action: user_action,
                    avatar: avatarField?.value || '',
                    password: passwordField?.value || '',
                    emailNotifications: email_notification_field.checked ? true : false,
                }

                fetch(author_kit_user_script_vars.ajax_url, {
                    method: "POST",
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body: new URLSearchParams(formData),
                })
                    .then((response) => response.json())
                    .then((data) => {
                        if (data.success) {
                            show_author_kit_toast(data.data.message, 'success');

                            if (user_action == 'add-new') {
                                setTimeout(function () {
                                    window.location.href = "admin.php?page=author-kit-dashboard";
                                }, 3000);
                            } else {
                                setTimeout(function () {
                                    location.reload();
                                }, 3000);
                            }

                        } else {
                            show_author_kit_toast(data.data.message, 'error');
                        }
                    })
                    .catch((error) => show_author_kit_toast(__("Error Occurred in Request", "author-kit"), 'error'));
            } else {
                show_author_kit_toast(__('Fields validation Failed', "author-kit"), 'error');
            }
        });
    }

    // Adds first and last name to display name options like WordPress
    function display_name_on_fields_change() {
        let select = document.getElementById("display-name");

        if (select) {
            let updateDisplayNameOptions = function () {
                let dub = Array.from(select.options).map(option => option.value);
                let inputs = {
                    display_nickname: document.getElementById("nickname")?.value || "",
                    // display_username: document.getElementById("user_login")?.value || "",
                    display_firstname: document.getElementById("first-name")?.value || "",
                    display_lastname: document.getElementById("last-name")?.value || ""
                };

                if (inputs.display_firstname && inputs.display_lastname) {
                    inputs.display_firstlast = `${inputs.display_firstname} ${inputs.display_lastname}`;
                    inputs.display_lastfirst = `${inputs.display_lastname} ${inputs.display_firstname}`;
                }

                Object.values(inputs).forEach(value => {
                    if (value && !dub.includes(value.replace(/<\/?[a-z][^>]*>/gi, ""))) {
                        let option = document.createElement("option");
                        option.textContent = value;
                        select.appendChild(option);
                    }
                });
            };

            ["first-name", "last-name"].forEach(id => {
                let input = document.getElementById(id);
                if (input) {
                    input.addEventListener("change", updateDisplayNameOptions);
                }
            });
        }
    }
});

