// Copyright Hassine RIANI (https://upvimeo.com)
// 2025. All Rights Reserved.
// This file is licensed under the GPLv2 License.
// License text available at https://opensource.org/licenses/gpl-2.0.php

window.UPVIMEO = window.hasOwnProperty('upvimeo') ? window.upvimeo : {};

window.UPVIMEO.Loader = '<div class="sweet_loader"><svg viewBox="0 0 140 140" width="140" height="140"><g class="outline"><path d="m 70 28 a 1 1 0 0 0 0 84 a 1 1 0 0 0 0 -84" stroke="rgba(0,0,0,0.1)" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"></path></g><g class="circle"><path d="m 70 28 a 1 1 0 0 0 0 84 a 1 1 0 0 0 0 -84" stroke="#71BBFF" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dashoffset="200" stroke-dasharray="300"></path></g></svg></div>';


var notice = function (message, type) {
    return '<div class="notice notice-' + type + ' is-dismissible upvimeo-clear-padding"><p>' + message + '</p></div>\n';
};

(function ($) {
    /**
     * Ajax select plugin
     * @param url
     * @param opts
     * @returns {*|jQuery|HTMLElement}
     */
    $.fn.ajaxSelect = function (url, opts) {

        if (!jQuery.fn.select2) {
            console.log('Upvimeo: Select2 library is not initialized.');
            return false;
        }

        var translated = {
            errorLoading: function () {
                return UPVIMEOAdmin.phrases.select2.errorLoading;
            },
            inputTooLong: function (args) {
                var overChars = args.input.length - args.maximum;
                var message = UPVIMEOAdmin.phrases.select2.inputTooShort;
                message = message.replace('{number}', overChars);
                if (overChars != 1) {
                    message += 's';
                }
                return message;
            },
            inputTooShort: function (args) {
                var remainingChars = args.minimum - args.input.length;
                var message = UPVIMEOAdmin.phrases.select2.inputTooShort;
                message = message.replace('{number}', remainingChars);
                return message;
            },
            loadingMore: function () {
                return UPVIMEOAdmin.phrases.select2.loadingMore;
            },
            maximumSelected: function (args) {
                var message = UPVIMEOAdmin.phrases.select2.maximumSelected;
                message = message.replace('{number}', args.maximum);
                if (args.maximum != 1) {
                    message += 's';
                }
                return message;
            },
            noResults: function () {
                return UPVIMEOAdmin.phrases.select2.noResults;
            },
            searching: function () {
                return UPVIMEOAdmin.phrases.select2.searching;
            },
            removeAllItems: function () {
                return UPVIMEOAdmin.phrases.select2.removeAllItems;
            },
            removeItem: function () {
                return UPVIMEOAdmin.phrases.select2.removeItem;
            },
            search: function () {
                return UPVIMEOAdmin.phrases.select2.search;
            }
        }

        var formatRepo = function (repo) {
            if (repo.loading) {
                return repo.text;
            }

            var markup = '<div class="upvimeo-library-item">';
            markup += '<span class="dashicons dashicons-category upvimeo-library-icon"></span>';
            markup += '<span class="upvimeo-library-text">' + repo.text + '</span>';
            markup += '</div>';

            return markup;
        };

        var formatRepoSelection = function (repo) {
            if (!repo.id || repo.id === 'default') {
                return repo.text;
            }
            return '<span class="dashicons dashicons-category upvimeo-library-icon"></span> ' + repo.text;
        };

        var args = {
            ajax: {
                url: url,
                dataType: 'json',
                delay: 350,
                type: 'POST',
                headers: { 'Accept': 'application/json' },
                data: function (params) {
                    return {
                        search_str: params.term,
                        page_number: params.page || 1
                    };
                },
                processResults: function (response) {
                    var options = [];
                    if (response.success) {
                        if (response.data.hasOwnProperty('results')) {
                            return response.data;
                        } else {
                            for (var i in response.data) {
                                var id = response.data[i].id;
                                var name = response.data[i].name;
                                options.push({ id: id, text: name });
                            }
                        }

                    }
                    return { results: options };
                },
                cache: true
            },
            language: translated,
            minimumInputLength: 3,
            width: '100%',
            allowClear: true,
            escapeMarkup: function (markup) { return markup; },
            templateResult: formatRepo,
            templateSelection: formatRepoSelection
        };

        $.extend(args, opts);
        $(this).select2(args);
        return $(this);
    }


    // Initialize
    $(document).find('.upvimeo-select2').each(function () {
        var params = {};
        var placehodler = $(this).data('placeholder');
        var action = $(this).data('action');
        var url = UPVIMEO.ajax_url + '?action=' + action + '&security=' + upvimeo_vars.nonce;
        var min_input_len = $(this).data('minInputLength');
        if (placehodler) {
            params.placeholder = placehodler;
        }
        if (min_input_len) {
            params.minimumInputLength = min_input_len;
        }
        $(this).ajaxSelect(url, params);
    });
    $(document).on('change', '.upvimeo-select2-clearable', function () {
        var value = $(this).val();
        if (value) {
            $('.upvimeo-clear-selection').show();
        } else {
            $('.upvimeo-clear-selection').hide();
        }
    });
    $(document).on('click', '.upvimeo-clear-selection', function (e) {
        e.preventDefault();
        var target = $(this).data('target');
        $(target).each(function (e) {
            $(this).val(null).trigger('change');
        })
    });

    // Intiializ

})(jQuery);

// Handle vimeo upload
(function ($) {

    jQuery('.wvv-video-upload').submit(function (e) {

        var $self = $(this);
        var $loader = $self.find('.upvimeo-loader');
        var $submit = $self.find('button[type=submit]');
        var $progressBar = $self.find('.upvimeo-progress-bar');

        var formData = new FormData(this);
        var videoFile = formData.get('upvimeo_video');

        if (!WPVimeoVideos.Uploader.validateVideo(videoFile)) {
            swal.fire(UPVIMEO.sorry, UPVIMEO.upload_invalid_file, 'error');
            return false;
        }

        var title = formData.get('upvimeo_title');
        var description = formData.get('upvimeo_description');
        var privacy = formData.get('upvimeo_view_privacy');
        if (!privacy) {
            privacy = UPVIMEO.default_privacy;
        }

        var errorHandler = function ($eself, error) {
            var type = 'error';
            var $_notice = $eself.find('.wvv-notice-wrapper');
            if ($_notice.length > 0) {
                $_notice.remove();
            }
            var message = '';
            try {
                var errorObject = JSON.parse(error);
                if (errorObject.hasOwnProperty('invalid_parameters')) {
                    for (var i in errorObject.invalid_parameters) {
                        var msg = errorObject.invalid_parameters[i].error + ' ' + errorObject.invalid_parameters[i].developer_message;
                        message += '<li>' + msg + '</li>';
                    }
                } else if (errorObject.hasOwnProperty('error')) {
                    message = errorObject.error;
                }

                if (message) {
                    message = '<p style="margin-bottom: 0;font-weight: bold;">' + UPVIMEO.correct_errors + ':</p>' + '<ul style="list-style: circle;padding-left: 20px;">' + message + '</ul>';
                }
            } catch (e) {
                message = error;
            }

            // Fallback for empty messages (often happens with false positive errors from Vimeo JS SDK)
            if (!message && typeof error === 'string' && error.trim() !== '') {
                message = error;
            }

            // Only show notice if there IS a message
            if (message) {
                $eself.prepend(notice(message, type));
            }

            $eself.find('.upvimeo-loader').css({ 'display': 'none' });
            $eself.find('button[type=submit]').prop('disabled', false);
        };

        var updateProgressBar = function ($pbar, value) {
            if ($pbar.is(':hidden')) {
                $pbar.show();
            }
            $pbar.find('.upvimeo-progress-bar-inner').css({ width: value + '%' })
            $pbar.find('.upvimeo-progress-bar-value').text(value + '%');
        };

        var uploader = new WPVimeoVideos.Uploader(UPVIMEO.nonce, videoFile, {
            'title': title,
            'description': description,
            'privacy': privacy,
            'wp': {
                'notify_endpoint': UPVIMEO.ajax_url + '?action=UPVIMEO_store_upload&security=' + upvimeo_vars.nonce,
            },
            'beforeStart': function () {
                $loader.css({ 'display': 'inline-flex' }); // Changed to inline-flex for SVG alignment
                $submit.prop('disabled', true);
            },
            'onProgress': function (bytesUploaded, bytesTotal) {
                var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2);
                updateProgressBar($progressBar, percentage);
            },
            'onSuccess': function (response, currentUpload) {
                var type = response.success ? 'success' : 'error';
                var message = response.data.message;
                var $_notice = $self.find('.wvv-notice-wrapper');
                if ($_notice.length > 0) {
                    $_notice.remove();
                }
                $self.prepend(notice(message, type));
                setTimeout(function () {
                    $self.get(0).reset();
                    $loader.css({ 'display': 'none' });
                    $submit.prop('disabled', false);
                    updateProgressBar($progressBar, 0);
                    $progressBar.hide();
                }, 1000);
            },
            'onError': function (error) {
                // Check if it's the "empty" error (false positive)
                if (!error || error === '{}' || error === '""') {
                    console.log('UpVimeo: Suppressed empty error from SDK.');
                    // We can optionally check status or just return.
                    // Often this triggers on successful uploads in some envs.
                    return;
                }
                errorHandler($self, error);
            },
            'onVideoCreateError': function (error) {
                errorHandler($self, error);
            },
            'onWPNotifyError': function (error) {
                errorHandler($self, error);
            }
        });
        uploader.start();
        return false;
    });

})(jQuery);

// Handle vimeo settings
(function ($) {
    $('#dg-vimeo-settings').submit(function (e) {
        var $self = $(this);
        var $btn = $self.find('button[type=submit]');
        var data = $self.serialize();
        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_handle_settings&security=' + upvimeo_vars.nonce,
            type: 'POST',
            data: data,
            beforeSend: function () {
                $btn.prepend('<span class="dashicons dashicons-update upvimeo-dashicon upvimeo-spin"></span>');
            },
            success: function (response) {
                var message;
                var type;
                if (response.success) {
                    message = response.data.message;
                    type = 'success';
                    if (response.data.hasOwnProperty('api_info')) {
                        $self.find('.vimeo-info-wrapper').html(response.data.api_info);
                    }
                } else {
                    message = response.data.message;
                    type = 'error';
                }
                var $_nwrapper = $self.closest('.wrap').find('.wvv-notice-wrapper');
                if ($_nwrapper.length > 0) {
                    $_nwrapper.html('');
                }
                $_nwrapper.prepend(notice(message, type));
            },
            complete: function () {
                var $icon = $btn.find('.upvimeo-dashicon');
                $icon.removeClass('dashicons-update upvimeo-spin').addClass('dashicons-yes')
                setTimeout(function () {
                    $icon.detach().remove();
                }, 1000);
            }
        });
        return false;
    });

    // Handle Purge Cache
    $(document).on('click', '.upvimeo-purge-cache', function (e) {
        e.preventDefault();
        var $self = $(this);
        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_handle_settings&security=' + upvimeo_vars.nonce,
            type: 'POST',
            data: { cv_purge_caches: 1 },
            beforeSend: function () {
                $self.prop('disabled', true);
                $self.prepend('<span class="dashicons dashicons-update upvimeo-dashicon upvimeo-spin"></span> ');
            },
            success: function (response) {
                var message = response.success ? response.data.message : 'Cache purged successfully.'; // Fallback msg
                var type = response.success ? 'success' : 'error';
                swal.fire(response.success ? UPVIMEO.success : UPVIMEO.sorry, message, type);
            },
            error: function () {
                swal.fire(UPVIMEO.sorry, UPVIMEO.http_error, 'error');
            },
            complete: function () {
                $self.prop('disabled', false);
                var $icon = $self.find('.upvimeo-dashicon');
                $icon.removeClass('dashicons-update upvimeo-spin').addClass('dashicons-yes')
                setTimeout(function () {
                    $icon.detach().remove();
                }, 1000);
            }
        });
    });
})(jQuery);

// Delete Videos
(function ($) {

    function deleteVideo(upvimeo_uri, post_id, context, $source) {
        swal.fire({
            title: UPVIMEO.delete_confirm_title,
            text: UPVIMEO.delete_confirm_desc,
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: UPVIMEO.confirm,
            cancelButtonText: UPVIMEO.cancel,
            showLoaderOnConfirm: true,
            preConfirm: function () {
                return new Promise(function (resolve, reject) {
                    $.ajax({
                        type: "POST",
                        url: UPVIMEO.ajax_url + '?action=UPVIMEO_handle_delete&security=' + upvimeo_vars.nonce,
                        data: { upvimeo_uri: upvimeo_uri, post_id: post_id },
                        success: function (response) {
                            resolve(response);
                        },
                        error: function () {
                            reject("HTTP Error");
                        }
                    });
                })
            },
            allowOutsideClick: false
        }).then(function (response) {

            if (response.value.data.hasOwnProperty('local_delete') && response.value.data.local_delete) {
                if (context === 'list') {
                    if ($source) {
                        $source.closest('tr').detach().remove();
                    }
                }
            }

            if (response.value.success) {
                swal.fire({
                    title: response.value.data.title,
                    type: 'success',
                    text: response.value.data.message,
                    showCancelButton: false,
                    confirmButtonText: UPVIMEO.close,
                    allowOutsideClick: false
                })
            } else {
                swal.fire({
                    title: response.value.data.title,
                    type: 'error',
                    text: response.value.data.message,
                    showCancelButton: false,
                    confirmButtonText: UPVIMEO.close,
                    allowOutsideClick: false
                })
            }
        });
    }

    $(document).on('click', '.upvimeo-delete', function (e) {
        var can_delete = $(this).data('can-delete');
        var uri = $(this).data('vimeo-uri');
        var id = $(this).data('id');
        if (!can_delete) {
            swal.fire(UPVIMEO.sorry, UPVIMEO.delete_not_allowed, 'error');
        } else {
            deleteVideo(uri, id, 'list', $(this));
        }
    })
})(jQuery);

// Conditional Love
(function ($) {
    $(document).on('change', '.upvimeo-conditional-field', function (e) {
        var targetClass = $(this).data('target');
        var currentValue = $(this).val();
        var targetConditionValue = $(this).data('show-target-if-value');
        if (currentValue === targetConditionValue) {
            $(targetClass).show();
        } else {
            $(targetClass).hide();
        }
    });
})(jQuery);


// Edit Video
(function ($) {

    // Save :: Basic Information
    $(document).on('submit', '#upvimeo-video-save-basic, #upvimeo-video-save-view-privacy', function (e) {
        var data = $(this).serialize();
        var $btn = $(this).find('button[type=submit]');
        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_handle_basic_edit&security=' + upvimeo_vars.nonce,
            type: 'POST',
            data: data,
            beforeSend: function () {
                $btn.prepend('<span class="dashicons dashicons-update upvimeo-dashicon upvimeo-spin"></span>');
            },
            success: function (response) {
                var title = response.success ? UPVIMEO.success : UPVIMEO.sorry;
                var type = response.success ? 'success' : 'error';
                swal.fire(title, response.data.message, type);
            },
            error: function () {
                swal.fire(UPVIMEO.sorry, UPVIMEO.http_error, 'error');
            },
            complete: function () {
                var $icon = $btn.find('.upvimeo-dashicon');
                $icon.removeClass('dashicons-update upvimeo-spin').addClass('dashicons-yes')
                setTimeout(function () {
                    $icon.detach().remove();
                }, 1000);
            }
        });
        return false
    });

    // Input :: Embed Privacy
    $(document).on('input', '#privacy_embed_domain', function (e) {
        var $form = $(this).closest('form');
        var $add = $form.find('button[name=admin_action][value=add_domain]');
        var value = $(this).val();
        if ($add.length) {
            var is_disabled = value === '';
            $add.prop('disabled', is_disabled);
        }
    });

    // Save :: Embed Privacy
    $(document).on('submit', '#upvimeo-video-save-embed-privacy', function (e) {
        var data = $(this).serialize();
        var $btn = $(this).find('button[type=submit].button-primary');
        var $domain_list = $(this).find('.privacy-embed-whitelisted-domains');
        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_handle_embed_privacy&security=' + upvimeo_vars.nonce,
            type: 'POST',
            data: data,
            beforeSend: function () {
                $btn.prepend('<span class="dashicons dashicons-update upvimeo-dashicon upvimeo-spin"></span>');
            },
            success: function (response) {
                var type = response.success ? 'success' : 'error';
                var domain = response.data.domain_added;
                if (response.success) {
                    if (response.data.hasOwnProperty('domain_added') && $domain_list.html().indexOf(domain) < 0) {
                        $domain_list.append('<li>' + domain + ' <a href="#" class="submitdelete upvimeo-delete-domain" data-domain="' + domain + '" data-uri="' + response.data.uri + '">(' + UPVIMEO.remove_lower + ')</a></li>')
                    }
                }
                if (response.data.hasOwnProperty('message')) {
                    var title = response.success ? UPVIMEO.success : UPVIMEO.sorry;
                    swal.fire(title, response.data.message, type);
                }
            },
            error: function () {
                swal.fire(UPVIMEO.sorry, UPVIMEO.http_error, 'error');
            },
            complete: function () {
                var $icon = $btn.find('.upvimeo-dashicon');
                $icon.removeClass('dashicons-update upvimeo-spin').addClass('dashicons-yes')
                setTimeout(function () {
                    $icon.detach().remove();
                }, 1000);
            }
        });

        return false;
    });

    // Save :: Delete domain
    $(document).on('click', '.upvimeo-delete-domain', function (e) {
        e.preventDefault();

        var $item = $(this).closest('li');

        var domain = $(this).data('domain');
        var uri = $(this).data('uri');

        var data = { 'domain': domain, 'uri': uri };

        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_delete_embed_privacy_domain&security=' + upvimeo_vars.nonce,
            type: 'POST',
            data: data,
            success: function (response) {

                if (response.success) {
                    $item.detach().remove();
                } else {
                    swal.fire(UPVIMEO.sorry, UPVIMEO.delete_whitelist_domain_error, 'error');
                }

            },
            error: function () {
                swal.fire(UPVIMEO.sorry, UPVIMEO.http_error, 'error');
            }
        });
    });

    // Remove
    setTimeout(function () {
        $(document).find('.upvimeo-embed-container .fluid-width-video-wrapper').removeClass('fluid-width-video-wrapper');
    }, 100);

    // Save Folders (Since 1.5.0)
    $(document).on('submit', '#upvimeo-video-save-folders', function (e) {
        var data = $(this).serialize();
        var $btn = $(this).find('button[type=submit]');
        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_handle_video_folder_set&security=' + upvimeo_vars.nonce,
            type: 'POST',
            data: data,
            beforeSend: function () {
                $btn.prepend('<span class="dashicons dashicons-update upvimeo-dashicon upvimeo-spin"></span>');
            },
            success: function (response) {
                var title = response.success ? UPVIMEO.success : UPVIMEO.sorry;
                var type = response.success ? 'success' : 'error';
                swal.fire(title, response.data.message, type);
            },
            complete: function () {
                var $icon = $btn.find('.upvimeo-dashicon');
                $icon.removeClass('dashicons-update upvimeo-spin').addClass('dashicons-yes')
                setTimeout(function () {
                    $icon.detach().remove();
                }, 1000);
            }
        });
        return false;
    });

    // Save embed preset (Since 1.5.0)
    $(document).on('submit', '#upvimeo-video-save-embed-preset', function (e) {
        var data = $(this).serialize();
        var $btn = $(this).find('button[type=submit]');
        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_handle_video_embed_preset_set&security=' + upvimeo_vars.nonce,
            type: 'POST',
            data: data,
            beforeSend: function () {
                $btn.prepend('<span class="dashicons dashicons-update upvimeo-dashicon upvimeo-spin"></span>');
            },
            success: function (response) {
                var title = response.success ? UPVIMEO.success : UPVIMEO.sorry;
                var type = response.success ? 'success' : 'error';
                swal.fire(title, response.data.message, type);
            },
            complete: function () {
                var $icon = $btn.find('.upvimeo-dashicon');
                $icon.removeClass('dashicons-update upvimeo-spin').addClass('dashicons-yes')
                setTimeout(function () {
                    $icon.detach().remove();
                }, 1000);
            }
        });
        return false;
    });


})(jQuery);


// UPLOAD Attachment: Button Popup
(function ($) {

    $(document).on('click', '.upvimeo-upload-attachment', function (e) {
        var id = $(this).data('id');

        var privacy_option = '';

        if (UPVIMEO.upload_form_options.enable_privacy_option) {
            var view_privacy_opts = '';
            for (var key in UPVIMEO.upload_form_options.privacy_view) {
                var name = UPVIMEO.upload_form_options.privacy_view[key].name;
                var is_available = UPVIMEO.upload_form_options.privacy_view[key].available;
                var is_default = UPVIMEO.upload_form_options.privacy_view[key].default;
                var disabled = is_available ? '' : 'disabled';
                var selected = is_default ? 'selected' : '';
                view_privacy_opts += '<option ' + disabled + ' ' + selected + ' value="' + key + '">' + name + '</option>';
            }
            privacy_option = '    <div class="upvimeo-vimeo-form-row">\n' +
                '        <label for="upvimeo_view_privacy">' + UPVIMEO.privacy_view + '</label>\n' +
                '        <select class="form-control wvv-w-100" name="upvimeo_view_privacy" id="upvimeo_view_privacy">' + view_privacy_opts + '</select>' +
                '    </div>\n'
        }

        swal.fire({
            showCloseButton: true,
            showCancelButton: false,
            showConfirmButton: false,
            allowOutsideClick: false,
            html: '<form class="upvimeo-media-library-upload upvimeo-text-left" method="POST">\n' +
                '    <div class="upvimeo-vimeo-form-row">\n' +
                '        <h4 for="upvimeo_title">' + UPVIMEO.upload_to_vimeo + '</h4>\n' +
                '    </div>\n' +
                '    <div class="upvimeo-vimeo-form-row">\n' +
                '        <label for="upvimeo_title">' + UPVIMEO.title + '</label>\n' +
                '        <input type="text" class="form-control" name="upvimeo_title" id="upvimeo_title">\n' +
                '    </div>\n' +
                '    <div class="upvimeo-vimeo-form-row">\n' +
                '        <label for="upvimeo_description">' + UPVIMEO.description + '</label>\n' +
                '        <textarea class="form-control" rows="5" name="upvimeo_description" id="upvimeo_description"></textarea>' +
                '    </div>\n' + privacy_option +
                '    <div class="upvimeo-vimeo-form-row upvimeo-vimeo-form-row-footer">\n' +
                '        <input type="hidden" name="attachment_id" value="' + id + '">\n' +
                '        <div class="upvimeo-loader upvimeo-loader-inline" style="display: none;"></div>' +
                '        <button type="submit" name="upvimeo_upload" class="button-primary button-small" value="1">' + UPVIMEO.upload + '</button>\n' +
                '    </div>\n' +
                '</form>'
        });
    });
})(jQuery);

// UPLOAD Attachment: Form Handler
(function ($) {
    $(document).on('submit', '.upvimeo-media-library-upload', function (e) {
        var data = $(this).serialize();
        var $inputID = $(this).find('input[name=attachment_id]');
        var $button = $(this).find('button[type=submit]');
        var ID = $inputID.val();
        var $self = $(this);
        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_attachment2vimeo&security=' + upvimeo_vars.nonce,
            type: 'POST',
            data: data,
            beforeSend: function () {
                $self.find('.upvimeo-loader').show();
                $button.prop('disabled', true);
            },
            success: function (response) {
                if (response.success) {
                    var metabox_html = response.data.info_metabox_html;
                    var $metabox = $('#upvimeo-mlmb-' + ID);
                    if ($metabox.length > 0) {
                        $metabox.html(metabox_html);
                    }
                    swal.fire(UPVIMEO.success, response.data.message, 'success');
                } else {
                    swal.fire(UPVIMEO.error, response.data.message, 'error');
                }
                $self.find('.upvimeo-loader').hide();
            },
            complete: function () {
                $self.find('.upvimeo-loader').hide();
                $button.prop('disabled', false);
            },
            error: function () {
                $self.find('.upvimeo-loader').hide();
                $button.prop('disabled', false);
                swal.fire(UPVIMEO.error, UPVIMEO.http_error, 'error');
            }
        });

        return false;
    });
})(jQuery);


// DELETE Vimeo Attachment: Button
(function ($) {

    $(document).on('click', '.upvimeo-delete-attachment', function (e) {
        var id = $(this).data('id');

        swal.fire({
            showCloseButton: true,
            showCancelButton: false,
            showConfirmButton: false,
            allowOutsideClick: false,
            html: '<form class="upvimeo-media-library-delete upvimeo-text-left" method="POST">\n' +
                '\t<div class="upvimeo-vimeo-form-row">\n' +
                '\t\t<label for="upvimeo_title">' + UPVIMEO.delete_confirmation + '</label>\n' +
                '\t</div>\n' +
                '\t<div class="upvimeo-vimeo-form-row">\n' +
                '\t<input type="hidden" name="attachment_id" value="' + id + '">\n' +
                '\t<div class="upvimeo-loader upvimeo-loader-inline" style="display: none;"></div>' +
                '\t<button type="submit" name="delete" class="button-primary" value="1">' + UPVIMEO.delete_confirmation_yes + '</button>\n' +
                '\t</div>\n' +
                '</form>'
        });
    });

})(jQuery);

// UPLOAD Attachment: Form Handler
(function ($) {
    $(document).on('submit', '.upvimeo-media-library-delete', function (e) {
        var $inputID = $(this).find('input[name=attachment_id]');
        var $button = $(this).find('button[type=submit]');
        var ID = $inputID.val();
        var $self = $(this);
        var data = $self.serialize();
        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_attachment2vimeo_delete&security=' + upvimeo_vars.nonce,
            type: 'POST',
            data: data,
            beforeSend: function () {
                $self.find('.upvimeo-loader').show();
                $button.prop('disabled', true);
            },
            success: function (response) {
                if (response.success) {
                    var metabox_html = response.data.info_metabox_html;
                    var $metabox = $('#upvimeo-mlmb-' + ID);
                    if ($metabox.length > 0) {
                        $metabox.html(metabox_html);
                    }
                    swal.fire(UPVIMEO.success, response.data.message, 'success');
                } else {
                    swal.fire(UPVIMEO.error, response.data.message, 'error');
                }
                $self.find('.upvimeo-loader').hide();
            },
            complete: function () {
                $self.find('.upvimeo-loader').hide();
                $button.prop('disabled', false);
            },
            error: function () {
                $self.find('.upvimeo-loader').hide();
                $button.prop('disabled', false);

                swal.fire(UPVIMEO.error, UPVIMEO.http_error, 'error');
            }
        });

        return false;
    });
})(jQuery);

// Fix problems
(function ($) {
    $(document).on('click', '.wvv-problem-fix-trigger', function (e) {
        e.preventDefault();
        var $wrap = $(this).closest('.wvv-problem-wrapper');
        var $fixWrap = $wrap.find('.wvv-problem--fix')
        var text = $fixWrap.text();
        swal.fire({
            showCloseButton: true,
            showCancelButton: false,
            showConfirmButton: false,
            html: '<div class="wvv-problem-solution">\n' +
                '\t<h2>' + UPVIMEO.problem_solution + '</h2>\n' +
                '\t<p>' + text + '</p>\n' +
                '</div>',
        });
    });
})(jQuery);


(function ($) {

    $(document).on('click', '.upvimeo-copy-embed-code', function (e) {
        var $self = $(this);
        var text = $self.closest('.column-embed').find('.upvimeo-embed-code').text().trim();
        navigator.clipboard.writeText(text).then(function () {
            $self.removeClass('dashicons-admin-links').addClass('dashicons-yes');
        });
        setTimeout(function () {
            $self.addClass('dashicons-admin-links');
            $self.removeClass('dashicons-yes')
        }, 2000);
    });

})(jQuery);


window.addEventListener('DOMContentLoaded', (event) => {
    window.UPVIMEO.AdminStats = function () {

        this.init = function () {
            // Trigger Action
            var stats_action = document.getElementById('upvimeo-vimeo-stats');
            if (stats_action) {
                stats_action.addEventListener('click', function (e) {
                    e.preventDefault();
                    var http = new window.UPVIMEO.Http()
                    http.get(UPVIMEO.ajax_url, {
                        data: {
                            action: 'UPVIMEO_generate_stats',
                            _wpnonce: UPVIMEO.nonce
                        },
                        beforeStart: function () {
                            swal.fire({
                                html: '<h4>' + UPVIMEO.loading + '</h4>',
                                onRender: function () {
                                    document.querySelector('.swal2-content').prepend(window.UPVIMEO.Loader);
                                }
                            })
                        },
                        success: function (response) {
                            swal.fire({
                                html: response.data.html,
                                showCloseButton: true,
                                showCancelButton: false,
                                showConfirmButton: false
                            })
                        },
                        complete: function () {

                        }
                    })
                });
            }
        }

        this.init();

    };

    window.UPVIMEO.AdminSettings = function () {
        this.init = function () {
            var infoFields = document.querySelectorAll('.upvimeo-settings-info');
            console.log(infoFields);
            for (var i = 0; i < infoFields.length; i++) {
                infoFields[i].addEventListener('click', function (e) {
                    swal.fire({
                        showCloseButton: true,
                        showCancelButton: false,
                        showConfirmButton: false,
                        html: '<div class="wvv-problem-solution">\n' +
                            '\t<h2>' + UPVIMEO.explanation + '</h2>\n' +
                            '\t<p>' + this.dataset.info + '</p>\n' +
                            '</div>',
                    });
                }.bind(infoFields[i]));
            }
        }
        this.init();
    }

    // Initialization

    new window.UPVIMEO.AdminStats();
    new window.UPVIMEO.AdminSettings();

});

// Import Video
(function ($) {
    $(document).on('click', '.upvimeo-import-video', function (e) {
        e.preventDefault();
        var $btn = $(this);
        if ($btn.hasClass('disabled')) return;

        $btn.addClass('disabled');
        var originalText = $btn.text();
        // Use localized string if available, otherwise fallback
        var loadingText = (typeof UPVIMEO !== 'undefined' && UPVIMEO.loading) ? UPVIMEO.loading : 'Importing...';
        $btn.text(loadingText);

        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_import_video&_wpnonce=' + UPVIMEO.nonce,
            type: 'POST',
            data: {
                upvimeo_id: $btn.data('vimeo-id'),
                upvimeo_uri: $btn.data('vimeo-uri'),
                title: $btn.data('title'),
                duration: $btn.data('duration'),
                width: $btn.data('width'),
                height: $btn.data('height')
            },
            success: function (response) {
                if (response.success) {
                    var importedText = (typeof UPVIMEO !== 'undefined' && UPVIMEO.imported) ? UPVIMEO.imported : 'Imported';
                    $btn.html('<span class="dashicons dashicons-yes"></span> ' + importedText);
                    swal.fire(UPVIMEO.success, response.data.message, 'success');
                } else {
                    $btn.removeClass('disabled').text(originalText);
                    swal.fire(UPVIMEO.error, response.data.message, 'error');
                }
            },
            error: function () {
                $btn.removeClass('disabled').text(originalText);
                swal.fire(UPVIMEO.error, UPVIMEO.http_error, 'error');
            }
        });
    });
})(jQuery);

// Domain Whitelist Logic
(function ($) {
    if ($('.upvimeo-tags-input-container').length === 0) return;

    var $container = $('.upvimeo-tags-input-container');
    var $input = $container.find('.upvimeo-new-domain-input');
    var $list = $container.find('.upvimeo-tags-list');
    var $hidden = $('#upvimeo_embed_domains');
    var $fetchBtn = $('#upvimeo-fetch-domains-btn');
    var $spinner = $('.upvimeo-fetch-spinner');

    function renderTags() {
        var val = $hidden.val();
        var domains = val ? val.split(',').filter(function (d) { return d.trim() !== ''; }) : [];
        $list.empty();
        domains.forEach(function (domain) {
            var $li = $('<li>' + domain + '<span class="upvimeo-remove-tag" data-domain="' + domain + '">&times;</span></li>');
            $list.append($li);
        });
    }

    function addTag(domain) {
        var val = $hidden.val();
        var domains = val ? val.split(',').filter(function (d) { return d.trim() !== ''; }) : [];
        domain = domain.trim();
        if (domain && domains.indexOf(domain) === -1) {
            domains.push(domain);
            $hidden.val(domains.join(','));
            renderTags();
        }
    }

    function removeTag(domain) {
        var val = $hidden.val();
        var domains = val ? val.split(',').filter(function (d) { return d.trim() !== ''; }) : [];
        var index = domains.indexOf(domain);
        if (index > -1) {
            domains.splice(index, 1);
            $hidden.val(domains.join(','));
            renderTags();
        }
    }

    // Init
    renderTags();

    // Input Handler
    $input.on('keypress', function (e) {
        if (e.which === 13) {
            e.preventDefault();
            addTag($(this).val());
            $(this).val('');
        }
    });

    // Remove Handler
    $list.on('click', '.upvimeo-remove-tag', function () {
        removeTag($(this).data('domain'));
    });

    // Fetch Handler
    $fetchBtn.on('click', function (e) {
        e.preventDefault();
        $spinner.addClass('is-active');
        $fetchBtn.prop('disabled', true);

        $.ajax({
            url: UPVIMEO.ajax_url + '?action=UPVIMEO_fetch_domains&_wpnonce=' + UPVIMEO.nonce,
            type: 'POST',
            success: function (response) {
                if (response.success) {
                    var newDomains = response.data.results;
                    var val = $hidden.val();
                    var currentDomains = val ? val.split(',').filter(function (d) { return d.trim() !== ''; }) : [];

                    var addedCount = 0;
                    if (newDomains && newDomains.length > 0) {
                        newDomains.forEach(function (d) {
                            if (currentDomains.indexOf(d) === -1) {
                                currentDomains.push(d);
                                addedCount++;
                            }
                        });
                        $hidden.val(currentDomains.join(','));
                        renderTags();
                        swal.fire(UPVIMEO.success, 'Successfully fetched ' + newDomains.length + ' domains (' + addedCount + ' new).', 'success');
                    } else {
                        // Show server message which might contain debug info
                        var msg = response.data.message ? response.data.message : 'No domains found in your Vimeo account whitelist.';
                        swal.fire(UPVIMEO.success, msg, 'info');
                    }


                } else {
                    swal.fire(UPVIMEO.error, response.data.message, 'error');
                }
            },
            error: function () {
                swal.fire(UPVIMEO.error, UPVIMEO.http_error, 'error');
            },
            complete: function () {
                $spinner.removeClass('is-active');
                $fetchBtn.prop('disabled', false);
            }
        });
    });

})(jQuery);

// Extracted from Settings / Notices page
(function ($) {
    // Password Toggle Script
    $(document).ready(function () {
        $('.upvimeo-password-toggle').on('click', function () {
            var $input = $(this).siblings('input');
            var type = $input.attr('type') === 'password' ? 'text' : 'password';
            $input.attr('type', type);
            $(this).toggleClass('dashicons-visibility dashicons-hidden');
        });

        // Privacy settings Radio Toggle 
        $('input[type="radio"]').change(function () {
            var $sel = $(this).closest('.upvimeo-privacy-selector');
            if ($sel.length) {
                $sel.find('.upvimeo-privacy-option').removeClass('selected');
                $(this).closest('.upvimeo-privacy-option').addClass('selected');
            }
        });
    });

    // Admin code for dismissing notifications.
    $(function () {
        $('.upvimeo_notice').on('click', '.notice-dismiss', function (event, el) {
            var $notice = $(this).parent('.notice.is-dismissible');
            var dismiss_url = $notice.attr('data-dismiss-url');
            if (dismiss_url) {
                $.get(dismiss_url);
            }
        });
    });
})(jQuery);
