(function ($) {
    "use strict";

    /* ===================================
         Profile Settings
     ====================================== */

    if ($('.gn-profile-setting-wrapper').length) {

        function ProfileHealthChartsInit() {
            let half_doughnut_chart = $('#gn-half-doughnut-chart');
            if (half_doughnut_chart.length) {
                let ctx2 = half_doughnut_chart[0].getContext('2d');

                let total = parseFloat(half_doughnut_chart.data('gn-total-percentage')) || 100;
                let completed = parseFloat(half_doughnut_chart.data('gn-completed-percentage')) || 0;

                let chartData = {
                    datasets: [{
                        data: [completed, total - completed],
                        backgroundColor: [GigneoCommon.primary_color || '#7B4BFD', '#f4f0fa'],
                        borderWidth: 0,
                        borderRadius: 20,
                        cutout: '80%',
                    }]
                };

                new Chart(ctx2, {
                    type: 'doughnut',
                    data: chartData,
                    options: {
                        rotation: -90,
                        circumference: 180,
                        responsive: false,
                        plugins: {
                            legend: {display: false},
                            tooltip: {enabled: false}
                        },
                        hover: {mode: null}
                    }
                });
            }
        }

        ProfileHealthChartsInit();

        //Media Uploader
        function ProfileMediaUploaderInit() {
            // Profile image
            $('#gn-change-profile-image').GigneoUploader({
                previewSelector: '#gn-profile-image > img',
                inputSelector: '#gn-profile-image input[name="profile_image"]',
                width: 300,
                height: 300,
                crop: true,
                previewMode: 'attribute',
                previewAttribute: 'src',
                allowedExtensions: GigneoDashboard.image_extensions || ['jpg', 'jpeg', 'png'],
                maxFileSize: GigneoDashboard.image_max_size * 1024 * 1024 || 1048576,
                ajaxCallback: function (attachment) {
                    var attachment_id = attachment.id ?? attachment.attachment_id;
                    $.ajax({
                        url: GigneoCommon.ajax_url,
                        method: 'POST',
                        data: {
                            action: 'gigneo_save_profile_setting',
                            security: GigneoCommon.security,
                            type: 'profile_media_image',
                            attachment_id: attachment_id
                        },
                        success: function (response) {
                            if (response.data.message) {

                                GigneoAlert.toast({
                                    icon: 'success',
                                    title: GigneoCommon.success,
                                    text: response.data.message
                                });

                                location.reload();
                            }
                        },
                        error: function (xhr) {
                            let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                            GigneoAlert.toast({
                                icon: 'error',
                                title: GigneoCommon.error,
                                text: error_message
                            });
                        }
                    });
                }
            });

            // Cover image
            $('#gn-change-profile-cover').GigneoUploader({
                previewSelector: '#gn-profile-cover-image > img',
                inputSelector: '#gn-profile-cover-image input[name="cover_image"]',
                width: 500,
                height: 125,
                crop: true,
                previewMode: 'attribute',
                previewAttribute: 'src',
                allowedExtensions: GigneoDashboard.image_extensions || ['jpg', 'jpeg', 'png'],
                maxFileSize: GigneoDashboard.image_max_size * 1024 * 1024 || 1048576,
                ajaxCallback: function (attachment) {
                    var attachment_id = attachment.id ?? attachment.attachment_id;
                    $.ajax({
                        url: GigneoCommon.ajax_url,
                        method: 'POST',
                        data: {
                            action: 'gigneo_save_profile_setting',
                            security: GigneoCommon.security,
                            type: 'profile_media_cover',
                            attachment_id: attachment_id
                        },
                        success: function (response) {
                            if (response.data.message) {

                                ProfileHealthChartsInit();

                                GigneoAlert.toast({
                                    icon: 'success',
                                    title: GigneoCommon.success,
                                    text: response.data.message
                                });
                            }
                        },
                        error: function (xhr) {
                            let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                            GigneoAlert.toast({
                                icon: 'error',
                                title: GigneoCommon.error,
                                text: error_message
                            });
                        }
                    });
                }
            });

            // Resume
            $('#gn-resume-upload .gn-media-upload-toggle').GigneoUploader({
                previewSelector: '#gn-resume-upload .gn-media-info',
                inputSelector: '#gn-resume-upload input[name="resume"]',
                removeSelector: '#gn-resume-upload .gn-media-uploader-remove',
                previewMode: 'attribute',
                previewAttribute: 'data-src',
                allowedExtensions: ['pdf'],
                maxFileSize: GigneoDashboard.document_max_size * 1024 * 1024 || 5242880,
                placeholderUrl: '',
            });

            // Intro Poster
            $('#gn-intro-poster-upload .gn-media-upload-toggle').GigneoUploader({
                previewSelector: '#gn-intro-poster-upload .gn-media-info > img',
                inputSelector: 'input[name="intro_poster"]',
                removeSelector: '#gn-intro-poster-upload .gn-media-uploader-remove',
                width: 300,
                height: 150,
                crop: true,
                previewMode: 'attribute',
                previewAttribute: 'src',
                allowedExtensions: GigneoDashboard.image_extensions || ['jpg', 'jpeg', 'png'],
                maxFileSize: GigneoDashboard.image_max_size * 1024 * 1024 || 1048576,
                placeholderUrl: '',
            });

            // Intro Video
            $('#gn-intro-video-upload .gn-media-upload-toggle').GigneoUploader({
                previewSelector: '#gn-intro-video-upload .gn-media-info',
                inputSelector: '#gn-intro-video-upload input[name="intro_video"]',
                removeSelector: '#gn-intro-video-upload .gn-media-uploader-remove',
                previewMode: 'attribute',
                previewAttribute: 'data-src',
                allowedExtensions: GigneoDashboard.video_extensions || ['mp4', 'avi', 'mov'],
                maxFileSize: GigneoDashboard.video_max_size * 1024 * 1024 || 10485760,
                placeholderUrl: '',
            });

            // Portfolio Featured Image
            $('#gn-portfolio-featured-image .gn-media-upload-toggle').GigneoUploader({
                previewSelector: '#gn-portfolio-featured-image .gn-media-info > img',
                inputSelector: 'input[name="portfolio_feature_image"]',
                removeSelector: '#gn-portfolio-featured-image .gn-media-uploader-remove',
                width: 300,
                height: 300,
                crop: true,
                previewMode: 'attribute',
                previewAttribute: 'src',
                allowedExtensions: GigneoDashboard.image_extensions || ['jpg', 'jpeg', 'png'],
                maxFileSize: GigneoDashboard.image_max_size * 1024 * 1024 || 1048576,
                placeholderUrl: '',
            });

            // Portfolio Preview Image
            $('#gn-portfolio-preview-image .gn-media-upload-toggle').GigneoUploader({
                previewSelector: '#gn-portfolio-preview-image .gn-media-info > img',
                inputSelector: 'input[name="portfolio_preview_image"]',
                removeSelector: '#gn-portfolio-preview-image .gn-media-uploader-remove',
                crop: false,
                previewMode: 'attribute',
                previewAttribute: 'src',
                allowedExtensions: GigneoDashboard.image_extensions || ['jpg', 'jpeg', 'png'],
                maxFileSize: GigneoDashboard.image_max_size * 1024 * 1024 || 1048576,
                placeholderUrl: '',
            });

            // Portfolio Preview Document
            $('#gn-portfolio-preview-document .gn-media-upload-toggle').GigneoUploader({
                previewSelector: '#gn-portfolio-preview-document .gn-media-info',
                inputSelector: 'input[name="portfolio_preview_document',
                removeSelector: '#gn-portfolio-preview-document .gn-media-uploader-remove',
                previewMode: 'attribute',
                previewAttribute: 'data-src',
                allowedExtensions: ['pdf'],
                maxFileSize: GigneoDashboard.document_max_size * 1024 * 1024 || 5242880,
                placeholderUrl: '',
            });

            // Certificate Logo
            $('#gn-certificate-image .gn-media-upload-toggle').GigneoUploader({
                previewSelector: '#gn-certificate-image .gn-media-info > img',
                inputSelector: 'input[name="certificate_image"]',
                removeSelector: '#gn-certificate-image .gn-media-uploader-remove',
                crop: false,
                previewMode: 'attribute',
                previewAttribute: 'src',
                allowedExtensions: GigneoDashboard.image_extensions || ['jpg', 'jpeg', 'png'],
                maxFileSize: GigneoDashboard.image_max_size * 1024 * 1024 || 1048576,
                placeholderUrl: '',
            });
        }

        ProfileMediaUploaderInit();

        // Initialize TinyMCE
        function ProfileTinymceInit() {
            if (typeof tinymce === 'undefined') {
                return;
            }
            if (tinymce.get('gn-description')) {
                tinymce.get('gn-description').remove();
                tinymce.init({
                    selector: '#gn-description',
                    toolbar: 'bold italic bullist numlist link unlink',
                    plugins: 'lists link',
                    resize: false,
                    menubar: false,
                    branding: false,
                    content_style: 'body { font-size: 14px; background-color: transparent; font-family: var(--gigneo-primary-font,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji) }',
                    content_css: GigneoDashboard.tinymce_skin,
                });
            }
        }

        var licenseUploader = null;
        var licenseFilesToUpload = [];

        function licensePluploadInit() {
            const { files, uploader } = window.GigneoPlupload.init({
                browseButtonId: 'gn-license-attachment-uploader',
                containerId: 'gn-license-attachment-container',
                dropElementId: 'gn-license-attachment-drop-area',
                attachmentListId: 'gn-license-attachment-list',
                allowedExtensions: GigneoDashboard.license_extensions || ['jpg', 'jpeg', 'png', 'doc'],
                maxFiles: GigneoDashboard.license_max_files || 3,
                maxSizeMb: GigneoDashboard.license_max_size || 5,
                errorMessages: {
                    maxFiles: GigneoDashboard.license_max_files_notice,
                    invalidExtension: GigneoDashboard.license_extension_notice,
                    maxSize: GigneoDashboard.license_max_size_notice,
                    error: GigneoCommon?.error
                }
            });
            licenseUploader = uploader;
            licenseFilesToUpload = files;
        }

        licensePluploadInit();

        //Add language
        $(document).on('click', '#gn-add-language-btn', function (e) {
            e.preventDefault();
            let _this = $(this);
            let wrapper = _this.parents('.gn-modal-wrapper');
            let language = wrapper.find('#gn-language-name').val();
            let language_name = wrapper.find(`#gn-language-name option[value="${language}"]`).text();
            let level = wrapper.find('#gn-language-level').val();
            let level_name = wrapper.find(`#gn-language-level option[value="${level}"]`).text();

            if (!language || !level) {
                GigneoAlert.toast();
                return;
            }

            let newLang = `<li id="gn-language-tag-${language}" class="gn-tag">
                                    <div class="gn-tag-info">
                                        <h6 class="gn-name">${language_name}</h6>
                                        <p class="gn-level">${level_name}</p>
                                        <input type="hidden" name="languages[${language}][name]" value="${language}">
                                        <input type="hidden" name="languages[${language}][level]" value="${level}">
                                    </div>
                                    <span class="gn-remove-tag"><i class="hi hi-x-mark" aria-hidden="true"></i></span></li>`;

            if (wrapper.find(`#gn-language-tag-${language}`).length) {
                wrapper.find(`#gn-language-tag-${language}`).replaceWith(newLang);
            } else {
                wrapper.find('.gn-repeater-tags').append(newLang);
            }

        });

        //Add social profiles
        $(document).on('click', '#gn-add-social-btn', function (e) {
            e.preventDefault();
            let _this = $(this);
            let random = Math.floor(1000 + Math.random() * 9000);
            let wrapper = _this.parents('.gn-modal-wrapper');
            let type = wrapper.find('#gn-social-type').val();
            let social = wrapper.find(`#gn-social-type option[value="${type}"]`).text();
            let url = wrapper.find('#gn-social-url').val();

            if (!type || !url) {
                GigneoAlert.toast();
                return;
            }

            let newLang = `<li id="gn-social-tag-${type}" class="gn-tag">
                                    <div class="gn-tag-info">
                                        <h6 class="gn-name">${social}</h6>
                                        <input type="hidden" name="socials[${random}][type]" value="${type}">
                                        <input type="hidden" name="socials[${random}][url]" value="${url}">
                                    </div>
                                    <span class="gn-remove-tag"><i class="hi hi-x-mark" aria-hidden="true"></i></span></li>`;

            wrapper.find('.gn-repeater-tags').append(newLang);
            wrapper.find('#gn-social-url').val('');
        });

        //Remove tags
        $(document).on('click', '.gn-repeater-tags .gn-remove-tag', function (e) {
            e.preventDefault();
            $(this).closest('li.gn-tag').fadeOut(100, function () {
                $(this).remove();
            });
        });

        //Country State & Cities
        $(document).on('change', '#gn-save-profile-setting-form #gn-country-state', function () {
            let _this = $(this);
            let country_state = _this.val();
            let cities_selector = _this.parents('.gn-form-fields').find('#gn-city');

            cities_selector.empty();

            if (country_state && GigneoDashboard.cities[country_state] !== undefined) {
                let cities = GigneoDashboard.cities[country_state];

                Object.entries(cities).forEach(function ([value, label]) {
                    cities_selector.append(
                        $('<option>', {
                            value: value,
                            text: label
                        })
                    );
                });

                cities_selector.trigger('change.select2');
            }

        });

        //Edit repeater data
        $(document).on('gigneo_modal_before_open', function (e, _this, modal_id) {
            let selector = $('#' + modal_id);
            let fields = _this.data('gn-fields');
            let previews = _this.data('gn-previews');

            if (selector.hasClass('gn-profile-setting-modal')) {
                if (fields !== undefined) {
                    selector.addClass('gn-profile-setting-edit');
                    if (typeof fields === 'object') {
                        $.each(fields, function (key, value) {
                            let field = selector.find(`[name="${key}"]`);
                            if (field.length) {
                                field.val(value);
                            }
                        });
                    } else {
                        selector.find('form')[0].reset();
                        selector.find('.gn-form-fields input,.gn-form-fields textarea,.gn-form-fields select').val('').prop('checked', false).prop('selected', false);
                        selector.removeClass('gn-profile-setting-edit');
                    }
                }

                if (previews !== undefined) {
                    if (typeof previews === 'object') {
                        $.each(previews, function (key, item) {
                            let preview_item = selector.find(item.selector);
                            if (preview_item.length) {
                                preview_item.attr(item.attribute, item.value);
                                let preview_remover = preview_item.parents('.gn-media-upload').find('.gn-media-uploader-remove');
                                if (preview_remover.length && item.value !== '') {
                                    preview_remover.show();
                                } else {
                                    preview_remover.hide();
                                }
                            }
                        });
                    } else {
                        selector.find('.gn-media-upload .gn-media-info > img').attr('src', '');
                    }
                }

                if (fields !== undefined || previews !== undefined) {
                    GigneoSelect2.init(); //Init Select2
                    GigneoFlatpickr.init(); //Init FlatPickr
                }

                GigneoTextareaCounter.init(); //Textarea counter init

                //Portfolio
                let portfolio_type = selector.find('#gn-portfolio-type');
                if (portfolio_type.length) {
                    let portfolio_previews = portfolio_type.parents('.gn-form-fields').find('[id*=gn-portfolio-preview-type]');
                    let portfolio_preview = $(`#gn-portfolio-preview-type-${portfolio_type.val()}`);
                    portfolio_previews.parents('.gn-portfolio-preview-type').hide();
                    portfolio_preview.parents('.gn-portfolio-preview-type').show();
                }

            }

        });

        //Portfolio type change
        $(document).on('change', '#gn-portfolio-type', function () {
            let _this = $(this);
            let type = _this.val();

            let previews = _this.parents('.gn-form-fields').find('[id*=gn-portfolio-preview-type]');
            let current = $(`#gn-portfolio-preview-type-${type}`);

            previews.parents('.gn-portfolio-preview-type').hide();
            current.parents('.gn-portfolio-preview-type').show();

        });

        //Save profile settings
        $(document).on('submit', '#gn-save-profile-setting-form', function (e) {
            e.preventDefault();

            let _this = $(this);
            let proceed = true;
            let form_data = new FormData(this);
            let setting_type = form_data.get('type');
            let submit_btn = _this.find('button[type="submit"]');

            proceed = window.GigneoRequiredFormFields.init(_this, proceed);

            if (proceed) {

                form_data.append('action', 'gigneo_save_profile_setting');
                form_data.append('security', GigneoCommon.security);

                if (setting_type === 'licenses' && licenseUploader && licenseFilesToUpload.length > 0) {
                    licenseFilesToUpload.forEach(function (file) {
                        let native_file = typeof file.getNative === 'function' ? file.getNative() : (typeof file.getSource === 'function' ? file.getSource() : (file.nativeFile || file));
                        if (native_file) {
                            form_data.append('license_files[]', native_file, file.name);
                        }
                    });
                }

                submit_btn.addClass('gn-loading');

                $.ajax({
                    url: GigneoCommon.ajax_url,
                    method: 'POST',
                    data: form_data,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        if (response.success) {

                            if (response.data.message) {
                                GigneoAlert.toast({
                                    icon: 'success',
                                    title: GigneoCommon.success,
                                    text: response.data.message
                                });
                            }

                            if (response.data.markup && Object.keys(response.data.markup).length > 0) {

                                let markup = response.data.markup;

                                $.each(markup, function (key, html) {
                                    let html_wrapper = $(document).find('#gn-profile-' + key);
                                    if (html_wrapper.length) {
                                        html_wrapper.replaceWith(html);
                                    }
                                });

                                if (markup?.description) {
                                    location.reload();
                                }

                                // Reinitialize
                                ProfileMediaUploaderInit();
                                ProfileHealthChartsInit();
                                licensePluploadInit();

                                GigneoSelect2.init();
                                GigneoFlatpickr.init();
                                window.GigneoGoogleMap?.init();
                            }

                            submit_btn.removeClass('gn-loading');
                            _this.parents('.gn-modal-wrapper').removeClass('gn-active');

                        } else {
                            submit_btn.removeClass('gn-loading');
                            GigneoAlert.toast({
                                icon: 'error',
                                title: GigneoCommon.error,
                                text: response?.data?.message || GigneoCommon.went_wrong
                            });
                        }
                    },
                    error: function (xhr, status, error) {
                        submit_btn.removeClass('gn-loading');
                        let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                        GigneoAlert.toast({
                            icon: 'error',
                            title: GigneoCommon.error,
                            text: error_message
                        });
                    }
                });
            }

        });

        //Delete profile setting
        $(document).on('click', '.gn-delete-profile-detail', function (e) {
            e.preventDefault();
            let _this = $(this);
            let type = _this.data('gn-type');
            let id = _this.data('gn-id');

            GigneoAlert.confirm({
                icon: "error",
                text: GigneoCommon.delete_confirmation_desc,
                confirmButtonText: GigneoCommon.delete,
                showLoaderOnConfirm: false,
                allowOutsideClick: () => !Swal.isLoading(),
                preConfirm: () => {
                    let confirmBtn = Swal.getConfirmButton();
                    confirmBtn.classList.add('gn-loading');
                    confirmBtn.disabled = true;

                    return new Promise((resolve, reject) => {
                        $.ajax({
                            url: GigneoCommon.ajax_url,
                            method: 'POST',
                            data: {
                                action: 'gigneo_delete_profile_setting',
                                type: type,
                                id: id,
                                security: GigneoCommon.security
                            },
                            success: function (response) {
                                confirmBtn.classList.remove('gn-loading');
                                confirmBtn.disabled = false;

                                if (response.success) {
                                    if (response.data.markup && Object.keys(response.data.markup).length > 0) {
                                        $.each(response.data.markup, function (key, html) {
                                            $('#gn-profile-' + key).replaceWith(html);
                                        });

                                        GigneoSelect2.init();
                                        GigneoFlatpickr.init();
                                        ProfileTinymceInit();
                                        ProfileMediaUploaderInit();
                                        ProfileHealthChartsInit();
                                    }

                                    if (response.data.message) {
                                        GigneoAlert.toast({
                                            icon: 'success',
                                            title: GigneoCommon.success,
                                            text: response.data.message
                                        });
                                    }
                                }
                                return Promise.resolve();
                            },
                            error: function (xhr) {
                                confirmBtn.classList.remove('gn-loading');
                                confirmBtn.disabled = false;
                                let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                                GigneoAlert.toast({
                                    icon: 'error',
                                    title: GigneoCommon.error,
                                    text: error_message
                                });
                                return Promise.resolve();
                            }
                        });
                    });
                }
            });

        });

    }

    /* ===================================
         Account Settings
     ====================================== */

    if ($('.gn-account-setting-wrapper').length) {

        //Save account settings
        $(document).on('submit', '#gn-save-account-setting-form', function (e) {
            e.preventDefault();

            let _this = $(this);
            let proceed = true;
            let form_data = new FormData(_this[0]);
            form_data.append('action', 'gigneo_save_account_setting');
            form_data.append('security', GigneoCommon.security);
            let submit_btn = _this.find('button[type="submit"]');

            proceed = window.GigneoRequiredFormFields.init(_this, proceed);

            if (proceed) {
                submit_btn.addClass('gn-loading');

                $.ajax({
                    url: GigneoCommon.ajax_url,
                    method: 'POST',
                    data: form_data,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        if (response.success) {

                            if (response.data.markup && Object.keys(response.data.markup).length > 0) {

                                let markup = response.data.markup;

                                $.each(markup, function (key, html) {
                                    let html_wrapper = $(document).find('#gn-account-' + key);
                                    if (html_wrapper.length) {
                                        html_wrapper.replaceWith(html);
                                    }
                                });
                                // Reinitialize
                                GigneoSelect2.init();
                            }

                            if (response.data.redirect) {
                                window.location.href = response.data.redirect;
                            }

                            submit_btn.removeClass('gn-loading');
                            _this.parents('.gn-modal-wrapper').removeClass('gn-active');

                            if (response.data.message) {
                                GigneoAlert.toast({
                                    icon: 'success',
                                    title: GigneoCommon.success,
                                    text: response.data.message
                                });
                            }

                        }
                    },
                    error: function (xhr, status, error) {
                        submit_btn.removeClass('gn-loading');
                        let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                        GigneoAlert.toast({
                            icon: 'error',
                            title: GigneoCommon.error,
                            text: error_message
                        });
                    }
                });
            }

        });

        //Make profile offline
        $(document).on('change', '#gn-offline-for', function () {
            let _this = $(this);
            let offline_for = _this.val();

            let form_data = new FormData();
            form_data.append('action', 'gigneo_save_account_setting');
            form_data.append('type', 'online_status');
            form_data.append('offline_for', offline_for);
            form_data.append('security', GigneoCommon.security);

            _this.parents('.gn-select2').addClass('gn-loading');

            $.ajax({
                url: GigneoCommon.ajax_url,
                method: 'POST',
                data: form_data,
                contentType: false,
                processData: false,
                success: function (response) {
                    _this.parents('.gn-select2').removeClass('gn-loading');
                    if (response.success) {

                        if (response.data.markup && Object.keys(response.data.markup).length > 0) {

                            let markup = response.data.markup;

                            $.each(markup, function (key, html) {
                                let html_wrapper = $(document).find('#gn-account-' + key);
                                if (html_wrapper.length) {
                                    html_wrapper.replaceWith(html);
                                }
                            });
                            // Reinitialize
                            GigneoSelect2.init();
                        }

                        if (response.data.message) {
                            GigneoAlert.toast({
                                icon: 'success',
                                title: GigneoCommon.success,
                                text: response.data.message
                            });
                        }

                    }
                },
                error: function (xhr, status, error) {
                    _this.parents('.gn-select2').removeClass('gn-loading');
                    let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                    GigneoAlert.toast({
                        icon: 'error',
                        title: GigneoCommon.error,
                        text: error_message
                    });
                }
            });

        });



        //Account notifications
        $(document).on('change', '#gn-account-notifications input[type="checkbox"]', function () {
            let _this = $(this);
            let type = _this.attr('name');
            let checked = _this.is(':checked');

            _this.parents('.gn-switch').addClass('gn-loading');

            $.ajax({
                url: GigneoCommon.ajax_url,
                method: 'POST',
                data: {
                    action: 'gigneo_account_notification',
                    type: type,
                    value: checked ? 'yes' : 'no',
                    security: GigneoCommon.security
                },
                success: function (response) {
                    _this.parents('.gn-switch').removeClass('gn-loading');
                    if (response.success) {
                        if (response.data.message) {
                            GigneoAlert.toast({
                                'icon': 'success',
                                title: GigneoCommon.success,
                                'text': response.data.message
                            });
                        }
                    }
                },
                error: function (xhr, status, error) {
                    _this.prop('checked', !checked);
                    _this.parents('.gn-switch').removeClass('gn-loading');
                    let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                    GigneoAlert.toast({
                        'icon': 'error',
                        title: GigneoCommon.error,
                        'text': error_message
                    });
                }
            });

        });

        //Remove an account form
        $(document).on('submit', '#gn-account-close-form', function (e) {
            e.preventDefault();

            let _this = $(this);
            let proceed = true;
            let form_data = new FormData(_this[0]);
            form_data.append('action', 'gigneo_save_account_setting');
            form_data.append('security', GigneoCommon.security);

            proceed = window.GigneoRequiredFormFields.init(_this, proceed);

            if (proceed) {

                _this.parents('.gn-modal-wrapper').removeClass('gn-active');

                GigneoAlert.confirm({
                    text: GigneoDashboard.close_account_confirmation_desc,
                    confirmButtonText: GigneoCommon.close,
                    icon: "warning",
                    showLoaderOnConfirm: false,
                    allowOutsideClick: () => !Swal.isLoading(),
                    preConfirm: () => {
                        const confirmBtn = Swal.getConfirmButton();
                        confirmBtn.classList.add('gn-loading');
                        confirmBtn.disabled = true;

                        return new Promise((resolve, reject) => {
                            $.ajax({
                                url: GigneoCommon.ajax_url,
                                method: 'POST',
                                data: form_data,
                                contentType: false,
                                processData: false,
                                success: function (response) {
                                    confirmBtn.classList.remove('gn-loading');
                                    confirmBtn.disabled = false;
                                    if (response.success) {

                                        if (response.data.redirect) {
                                            window.location.href = response.data.redirect;
                                        }

                                        if (response.data.message) {
                                            GigneoAlert.toast({
                                                icon: 'success',
                                                title: GigneoCommon.success,
                                                text: response.data.message
                                            });
                                        }
                                    }
                                    return Promise.resolve();
                                },
                                error: function (xhr) {
                                    confirmBtn.classList.remove('gn-loading');
                                    confirmBtn.disabled = false;
                                    let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                                    GigneoAlert.toast({
                                        icon: 'error',
                                        title: GigneoCommon.error,
                                        text: error_message
                                    });
                                    return Promise.resolve();
                                }
                            });
                        });
                    }
                });
            }

        });
    }

    /* ===================================
         Billing Settings
     ====================================== */

    if ($('.gn-billing-setting-wrapper').length) {

        //Save account settings
        $(document).on('submit', '#gn-save-user-billing-address-form', function (e) {
            e.preventDefault();

            let _this = $(this);
            let proceed = true;
            let form_data = new FormData(_this[0]);
            form_data.append('action', 'gigneo_save_billing_address');
            form_data.append('security', GigneoCommon.security);
            let submit_btn = _this.find('button[type="submit"]');

            proceed = window.GigneoRequiredFormFields.init(_this, proceed);

            if (proceed) {
                submit_btn.addClass('gn-loading');

                $.ajax({
                    url: GigneoCommon.ajax_url,
                    method: 'POST',
                    data: form_data,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        if (response.success) {

                            if (response.data.markup && Object.keys(response.data.markup).length > 0) {

                                let markup = response.data.markup;

                                $.each(markup, function (key, html) {
                                    let html_wrapper = $(document).find('#gn-billing-' + key);
                                    if (html_wrapper.length) {
                                        html_wrapper.replaceWith(html);
                                    }
                                });
                                // Reinitialize
                                GigneoSelect2.init();
                            }

                            submit_btn.removeClass('gn-loading');
                            _this.parents('.gn-modal-wrapper').removeClass('gn-active');

                            if (response.data.message) {
                                GigneoAlert.toast({
                                    icon: 'success',
                                    title: GigneoCommon.success,
                                    text: response.data.message
                                });
                            }

                        }
                    },
                    error: function (xhr, status, error) {
                        submit_btn.removeClass('gn-loading');
                        let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                        GigneoAlert.toast({
                            icon: 'error',
                            title: GigneoCommon.error,
                            text: error_message
                        });
                    }
                });
            }

        });

        //Select Payout Method
        $(document).on('submit', '#gn-select-payout-method-form', function (e) {
            e.preventDefault();

            let _this = $(this);
            let payout_type = _this.find('input[name="payout_type"]:checked').val();
            let payout_modal = $(document).find(`#gn-save-payout-${payout_type}`);

            if (payout_modal.length) {
                payout_modal.find('form')[0].reset();
                payout_modal.find('.gn-form-fields input,.gn-form-fields select').val('').prop('checked', false).prop('selected', false);
                payout_modal.addClass('gn-active');
                _this.parents('.gn-modal-wrapper').removeClass('gn-active');
            }

        });

        //Edit repeater data
        $(document).on('gigneo_modal_before_open', function (e, _this, modal_id) {
            let selector = $('#' + modal_id);
            let fields = _this.data('gn-fields');

            if (selector.hasClass('gn-edit-payout-modal')) {
                if (fields !== undefined) {
                    if (typeof fields === 'object') {
                        $.each(fields, function (key, value) {
                            let field = selector.find(`[name="${key}"]`);
                            if (field.length) {
                                field.val(value);
                            }
                        });
                    } else {
                        selector.find('form')[0].reset();
                        selector.find('.gn-form-fields input,.gn-form-fields textarea,.gn-form-fields select').val('').prop('checked', false).prop('selected', false);
                    }
                }

                if (fields !== undefined) {
                    GigneoSelect2.init();
                }

            }

        });

        //Save payout method
        $(document).on('submit', '#gn-save-payout-method-form', function (e) {
            e.preventDefault();

            let _this = $(this);
            let proceed = true;
            let form_data = new FormData(_this[0]);
            form_data.append('action', 'gigneo_save_payout_method');
            form_data.append('security', GigneoCommon.security);
            let submit_btn = _this.find('button[type="submit"]');

            proceed = window.GigneoRequiredFormFields.init(_this, proceed);

            if (proceed) {
                submit_btn.addClass('gn-loading');

                $.ajax({
                    url: GigneoCommon.ajax_url,
                    method: 'POST',
                    data: form_data,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        if (response.success) {

                            if (response.data.markup && Object.keys(response.data.markup).length > 0) {
                                let markup = response.data.markup;
                                $.each(markup, function (key, html) {
                                    let html_wrapper = $(document).find('#gn-billing-' + key);
                                    if (html_wrapper.length) {
                                        html_wrapper.replaceWith(html);
                                    }
                                });
                                // Reinitialize
                                GigneoSelect2.init();
                            }

                            submit_btn.removeClass('gn-loading');
                            _this.parents('.gn-modal-wrapper').removeClass('gn-active');

                            if (response.data.message) {
                                GigneoAlert.toast({
                                    icon: 'success',
                                    title: GigneoCommon.success,
                                    text: response.data.message
                                });
                            }

                        }
                    },
                    error: function (xhr, status, error) {
                        submit_btn.removeClass('gn-loading');
                        let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                        GigneoAlert.toast({
                            icon: 'error',
                            title: GigneoCommon.error,
                            text: error_message
                        });
                    }
                });
            }

        });

        //Remove payout method
        $(document).on('click', '.gn-delete-payout-btn', function (e) {
            e.preventDefault();
            let _this = $(this);
            let id = _this.data('gn-id');

            if (id === '') {
                return false;
            }

            GigneoAlert.confirm({
                icon: "warning",
                text: GigneoCommon.delete_confirmation_desc,
                confirmButtonText: GigneoCommon.delete,
                showLoaderOnConfirm: false,
                allowOutsideClick: () => !Swal.isLoading(),
                preConfirm: () => {
                    let confirmBtn = Swal.getConfirmButton();
                    confirmBtn.classList.add('gn-loading');
                    confirmBtn.disabled = true;

                    return new Promise((resolve, reject) => {
                        $.ajax({
                            url: GigneoCommon.ajax_url,
                            method: 'POST',
                            data: {
                                action: 'gigneo_delete_payout_method',
                                id: id,
                                security: GigneoCommon.security
                            },
                            success: function (response) {
                                confirmBtn.classList.remove('gn-loading');
                                confirmBtn.disabled = false;
                                if (response.success) {
                                    if (response.data.markup && Object.keys(response.data.markup).length > 0) {
                                        let markup = response.data.markup;
                                        $.each(markup, function (key, html) {
                                            let html_wrapper = $(document).find('#gn-billing-' + key);
                                            if (html_wrapper.length) {
                                                html_wrapper.replaceWith(html);
                                            }
                                        });
                                        // Reinitialize
                                        GigneoSelect2.init();
                                    }

                                    if (response.data.message) {
                                        GigneoAlert.toast({
                                            icon: 'success',
                                            title: GigneoCommon.success,
                                            text: response.data.message
                                        });
                                    }
                                }
                                return Promise.resolve();
                            },
                            error: function (xhr) {
                                confirmBtn.classList.remove('gn-loading');
                                confirmBtn.disabled = false;

                                let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                                GigneoAlert.toast({
                                    icon: 'error',
                                    title: GigneoCommon.error,
                                    text: error_message
                                });
                                return Promise.resolve();
                            }
                        });
                    });
                }
            });

        });

    }

    /* ===================================
        Security Settings
    ====================================== */

    if ($('.gn-security-setting-wrapper').length) {

        //Password strength
        $(document).on('input', '#gn-new-password', function () {
            let _this = $(this);
            let value = _this.val();

            let password_strength = GigneoCommon.password_strength;
            let password_notices = _this.parents('.gn-form-field').find('.gn-password-notice > li');

            let rulePatterns = {
                length: /.{8,}/,         // At least 8 characters
                uppercase: /[A-Z]/,       // At least one uppercase letter
                lowercase: /[a-z]/,       // At least one lowercase letter
                number: /[0-9]/,          // At least one number
                special: /[!@#$%^&*(),.?":{}|<>]/ // At least one special character
            };

            let firstErrorFound = false;

            password_strength.forEach(rule => {
                let noticeItem = password_notices.filter(`.${rule}`);
                if (!firstErrorFound && rulePatterns[rule] && !rulePatterns[rule].test(value)) {
                    noticeItem.show();
                    firstErrorFound = true;
                    _this.addClass('gn-input-invalid');
                    _this.parents('#gn-update-account-password-form').find('button[type="submit"]').attr('disabled', true);
                } else {
                    noticeItem.hide();
                    if (!firstErrorFound) {
                        _this.removeClass('gn-input-invalid');
                        _this.parents('#gn-update-account-password-form').find('button[type="submit"]').attr('disabled', false);
                    }
                }
            });
        });

        //Update Password
        $(document).on('submit', '#gn-update-account-password-form', function (e) {
            e.preventDefault();

            let _this = $(this);
            let proceed = true;
            let form_data = new FormData(_this[0]);
            form_data.append('action', 'gigneo_update_password');
            form_data.append('security', GigneoCommon.security);
            let submit_btn = _this.find('button[type="submit"]');

            proceed = window.GigneoRequiredFormFields.init(_this, proceed);

            if (proceed) {
                submit_btn.addClass('gn-loading');

                $.ajax({
                    url: GigneoCommon.ajax_url,
                    method: 'POST',
                    data: form_data,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        if (response.success) {

                            submit_btn.removeClass('gn-loading');
                            _this.parents('.gn-modal-wrapper').removeClass('gn-active');
                            _this[0].reset();

                            if (response.data.message) {
                                GigneoAlert.toast({
                                    icon: 'success',
                                    title: GigneoCommon.success,
                                    text: response.data.message
                                });
                            }

                        }
                    },
                    error: function (xhr, status, error) {
                        submit_btn.removeClass('gn-loading');
                        let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                        GigneoAlert.toast({
                            icon: 'error',
                            title: GigneoCommon.error,
                            text: error_message
                        });
                    }
                });
            }

        })

        //Delete user session
        $(document).on('click', '.gn-delete-user-session', function (e) {
            e.preventDefault();
            let _this = $(this);
            let id = _this.data('session-key');

            GigneoAlert.confirm({
                icon: "error",
                text: GigneoCommon.delete_confirmation_desc,
                confirmButtonText: GigneoCommon.delete,
                showLoaderOnConfirm: false,
                allowOutsideClick: () => !Swal.isLoading(),
                preConfirm: () => {
                    let confirmBtn = Swal.getConfirmButton();
                    confirmBtn.classList.add('gn-loading');
                    confirmBtn.disabled = true;

                    return new Promise((resolve, reject) => {
                        $.ajax({
                            url: GigneoCommon.ajax_url,
                            method: 'POST',
                            data: {
                                action: 'gigneo_delete_session',
                                id: id,
                                security: GigneoCommon.security
                            },
                            success: function (response) {
                                confirmBtn.classList.remove('gn-loading');
                                confirmBtn.disabled = false;

                                if (response.success) {
                                    if (response.data.markup && Object.keys(response.data.markup).length > 0) {
                                        $.each(response.data.markup, function (key, html) {
                                            $('#gn-security-' + key).replaceWith(html);
                                        });
                                    }

                                    if (response.data.message) {
                                        GigneoAlert.toast({
                                            icon: 'success',
                                            title: GigneoCommon.success,
                                            text: response.data.message
                                        });
                                    }
                                }
                                return Promise.resolve();
                            },
                            error: function (xhr) {
                                confirmBtn.classList.remove('gn-loading');
                                confirmBtn.disabled = false;
                                let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                                GigneoAlert.toast({
                                    icon: 'error',
                                    title: GigneoCommon.error,
                                    text: error_message
                                });
                                return Promise.resolve();
                            }
                        });
                    });
                }
            });

        });

        //Account Connect - Google
        $(document).on('click', '[data-gn-google-url]', function (e) {
            e.preventDefault();

            const url = $(this).attr('data-gn-google-url');
            if (!url) return;

            const popup = window.open(
                url,
                'google_auth',
                'width=600,height=700,left=' + (screen.width - 600) / 2 + ',top=' + (screen.height - 700) / 2
            );

            if (!popup) {
                return;
            }

            // This will now work because PHP sends real object
            window.addEventListener('message', function handler(e) {
                if (!e.data || !e.data.type) return;

                // Remove listener immediately
                window.removeEventListener('message', handler);

                if (e.data.type === 'GIGNEO_GOOGLE_SUCCESS') {
                    GigneoAlert.toast({
                        icon: 'success',
                        title: 'Success',
                        text: e.data.message || 'Logged in!'
                    });

                    if (e.data.redirect) {
                        setTimeout(() => location.href = e.data.redirect, 1200);
                    }
                }

                if (e.data.type === 'GIGNEO_GOOGLE_ERROR') {
                    GigneoAlert.toast({
                        icon: 'error',
                        title: 'Error',
                        text: e.data.message
                    });
                }
            });
        });

        //Account Disconnect
        $(document).on('click', '.gn-account-disconnect', function (e) {
            e.preventDefault();

            let _this = $(this);
            let account = _this.data('gn-account');

            if (!account) {
                return false;
            }

            GigneoAlert.confirm({
                icon: "error",
                text: GigneoCommon.disconnect_confirmation_desc,
                confirmButtonText: GigneoCommon.disconnect,
                showLoaderOnConfirm: false,
                allowOutsideClick: () => !Swal.isLoading(),
                preConfirm: () => {
                    let confirmBtn = Swal.getConfirmButton();
                    confirmBtn.classList.add('gn-loading');
                    confirmBtn.disabled = true;

                    return new Promise((resolve, reject) => {
                        $.ajax({
                            url: GigneoCommon.ajax_url,
                            method: 'POST',
                            data: {
                                action: 'gigneo_disconnect_auth_account',
                                account: account,
                                security: GigneoCommon.security
                            },
                            success: function (response) {
                                confirmBtn.classList.remove('gn-loading');
                                confirmBtn.disabled = false;

                                if (response.success && response.data.message) {
                                    GigneoAlert.toast({
                                        icon: 'success',
                                        title: GigneoCommon.success,
                                        text: response.data.message
                                    });
                                }

                                location.reload();

                                return Promise.resolve();
                            },
                            error: function (xhr) {
                                confirmBtn.classList.remove('gn-loading');
                                confirmBtn.disabled = false;
                                let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                                GigneoAlert.toast({
                                    icon: 'error',
                                    title: GigneoCommon.error,
                                    text: error_message
                                });
                                return Promise.resolve();
                            }
                        });
                    });
                }
            });

        });

        // Account Connect - LinkedIn
        $(document).on('click', '[data-gn-linkedin-url]', function (e) {
            e.preventDefault();

            const url = $(this).attr('data-gn-linkedin-url');
            if (!url) return;

            const popup = window.open(
                url,
                'linkedin_auth',
                'width=600,height=700,left=' + (screen.width - 600) / 2 + ',top=' + (screen.height - 700) / 2
            );

            if (!popup) return;

            window.addEventListener('message', function handler(e) {

                if (!e.data || !e.data.type) return;

                window.removeEventListener('message', handler);

                if (e.data.type === 'GIGNEO_LINKEDIN_SUCCESS') {
                    GigneoAlert.toast({
                        icon: 'success',
                        title: 'Success',
                        text: e.data.message || 'LinkedIn Connected!'
                    });

                    if (e.data.redirect) {
                        setTimeout(() => location.href = e.data.redirect, 1200);
                    }
                }

                if (e.data.type === 'GIGNEO_LINKEDIN_ERROR') {
                    GigneoAlert.toast({
                        icon: 'error',
                        title: 'Error',
                        text: e.data.message
                    });
                }
            });
        });

        // Account Connect - Facebook
        $(document).on('click', '[data-gn-facebook-url]', function (e) {
            e.preventDefault();

            const url = $(this).attr('data-gn-facebook-url');
            if (!url) return;

            const popup = window.open(
                url,
                'facebook_auth',
                'width=600,height=700,left=' + (screen.width - 600) / 2 + ',top=' + (screen.height - 700) / 2
            );

            if (!popup) return;

            window.addEventListener('message', function handler(e) {
                if (!e.data || !e.data.type) return;

                window.removeEventListener('message', handler);

                if (e.data.type === 'GIGNEO_FACEBOOK_SUCCESS') {
                    GigneoAlert.toast({
                        icon: 'success',
                        title: 'Success',
                        text: e.data.message || 'Facebook Connected!'
                    });

                    if (e.data.redirect) {
                        setTimeout(() => location.href = e.data.redirect, 1200);
                    }
                }

                if (e.data.type === 'GIGNEO_FACEBOOK_ERROR') {
                    GigneoAlert.toast({
                        icon: 'error',
                        title: 'Error',
                        text: e.data.message
                    });
                }
            });
        });
    }

}(jQuery));