document.addEventListener("DOMContentLoaded", function () {

    const { __, _x, _n, sprintf } = wp.i18n;

    let default_user_avatar_url = author_kit_update_author_profile_vars.default_user_avatar_url;

    sidebar_functionality();
    display_name_on_fields_change();
    handleFieldValidationOnChange();
    author_kit_update_author_profile();


    const avatarField = document.getElementById("avatar");

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


    // 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();
            console.log(attachment);

            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();
    };



    // Sidebar Functionality
    function sidebar_functionality() {
        const sidebarLinks = document.querySelectorAll(".sidebar-link");
        const contentSections = document.querySelectorAll(".content-section");

        // Ensure the first section is displayed and the first link is active on load
        if (contentSections.length > 0) {
            contentSections.forEach((section, index) => {
                section.style.display = index === 0 ? "block" : "none"; // Show the first section
            });
        }

        if (sidebarLinks.length > 0) {
            sidebarLinks.forEach((link, index) => {
                if (index === 0) {
                    link.classList.add("active"); // Add active class to the first link
                } else {
                    link.classList.remove("active");
                }
            });
        }

        // Event listener for sidebar links
        sidebarLinks.forEach((link) => {
            link.addEventListener("click", () => {
                const target = link.getAttribute("data-target");

                // Hide all sections
                contentSections.forEach((section) => {
                    section.style.display = "none";
                });

                // Show the selected section
                const targetSection = document.getElementById(target);
                if (targetSection) {
                    targetSection.style.display = "block";
                }

                // Add active class to the clicked sidebar link
                sidebarLinks.forEach((l) => l.classList.remove("active"));
                link.classList.add("active");
            });
        });

        // Show Custom URL Field when Custom URL Radio is selected
        document.querySelectorAll('input[name="link_type"]').forEach((radio) => {
            radio.addEventListener("change", function () {
                const customUrlField = document.getElementById("custom-url");
                const errorElement = document.getElementById("error-custom-url");
                const errorMessage = __('Please enter a valid URL...', 'author-kit');
                if (this.value === "custom_url") {
                    customUrlField.style.display = "block";
                    if (!customUrlField.checkValidity()) {
                        errorElement.textContent = errorMessage;
                        errorElement.style.display = "block";
                        return false;
                    } else {
                        errorElement.textContent = ""; // Clear error message
                        errorElement.style.display = "none";
                        return true;
                    }
                } else {
                    customUrlField.style.display = "none";
                    errorElement.style.display = "none";
                }
            });
        });


    }

    // 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);
                }
            });
        }
    }

    // Validate an individual field
    function validateField(field, errorMessage) {
        const errorElement = document.getElementById(`error-${field.id}`);
        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("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("custom-url"),
                errorMessage: __("Custom URL is either empty or have invalid URL", "author-kit"),
            },
            {
                field: document.getElementById("website"),
                errorMessage: __("Please enter a valid URL", "author-kit"),
            },
            {
                field: document.getElementById("contact-email"),
                errorMessage: __("Please enter a valid Email", "author-kit"),
            },
        ];

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

    // Function to validate all fields before submitting
    function validateAllFields() {

        const fieldsToValidate = [
            {
                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("custom-url"),
                errorMessage: __("Custom URL is either empty or have invalid URL", "author-kit"),
            },
            {
                field: document.getElementById("website"),
                errorMessage: __("Please enter a valid URL", "author-kit"),
            },
            {
                field: document.getElementById("contact-email"),
                errorMessage: __("Please enter a valid Email", "author-kit"),
            },
        ];


        let isValid = true;
        fieldsToValidate.forEach(({ field, errorMessage }) => {
            if (!validateField(field, errorMessage)) {
                isValid = false;
            }
        });

        return isValid;
    }

    function author_kit_update_author_profile() {
        document.querySelectorAll("[id^='author-kit-update-button']").forEach((button) => {
            button.addEventListener("click", function (event) {
                event.preventDefault();

                show_author_kit_toast(__('Updating Author Profile... Please Wait!', 'author-kit'), 'performing');


                if (!validateAllFields()) {
                    show_author_kit_toast(__("Validation Failed: Fix Errors Before Submitting", 'author-kit'), 'error');
                    return;
                }

                // Collect social media links, only include non-empty values
                const socialPlatforms = author_kit_update_author_profile_vars.selected_platforms_keys;

                const social_links = {};

                socialPlatforms.forEach((platform) => {
                    const field = document.getElementById(platform);
                    if (field && field.value.trim()) {
                        social_links[platform] = field.value.trim();
                    }
                });

                // Get selected radio button value
                const link_preference = document.querySelector('input[name="link_type"]:checked')?.value || "";

                // Get the content of the TinyMCE editor with HTML
                const bioContent = tinymce.get('description') ? tinymce.get('description').getContent() : "";

                // Collect form data
                const author_data = {
                    action: 'author_kit_update_author_profile',
                    nonce: author_kit_update_author_profile_vars.nonce,
                    ID: document.getElementById("ID")?.value.trim(),
                    display_name: document.getElementById("display-name")?.value.trim(),
                    first_name: document.getElementById("first-name")?.value.trim(),
                    last_name: document.getElementById("last-name")?.value.trim(),
                    link_preference: link_preference, // Add selected radio button value
                    custom_url: link_preference === "custom_url" ? document.getElementById("custom-url")?.value.trim() : "", // Only send custom URL if selected                    
                    website: document.getElementById("website")?.value.trim(),
                    description: bioContent,
                    avatar: document.getElementById("avatar").value || "",
                    contact_email: document.getElementById("contact-email")?.value.trim(),
                    company: document.getElementById("company")?.value.trim(),
                    job_title: document.getElementById("job-title")?.value.trim(),
                    social_links: JSON.stringify(social_links),
                };

                // Send AJAX request to PHP backend
                fetch(author_kit_update_author_profile_vars.ajax_url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body: new URLSearchParams(author_data),
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            show_author_kit_toast(__("Profile updated successfully!", 'author-kit'), 'success');
                            setTimeout(function () {
                                location.reload();
                            }, 3000);
                        } else {
                            show_author_kit_toast(__("Error in Updating Author Profile", 'author-kit'), 'error');
                        }
                    })
                    .catch(error => show_author_kit_toast(__("Failed to Update Author Profile", 'author-kit'), 'error'));

            });
        });

    }

});
