jQuery(document).ready(function ($) {
    $('.mpvw-notice .notice-dismiss').on('click', function () {
        const notice = $(this).closest('.mpvw-notice');
        const noticeType = notice.data('type');

        if (noticeType) {
            $.ajax({
                url: ajaxDataMPVW.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'mpvw_dismiss_notice',
                    type: noticeType,
                    nonce: ajaxDataMPVW.nonce,
                },
                success: function (response) {
                    console.log('Notice dismissed:', response);
                },
                error: function (xhr, status, error) {
                    console.error('Error dismissing notice:', error);
                },
            });
        }
    });

    const mpvwNotification = new WpvNotification('.product-video-woocommerce-block__notification');
    const mpvw_preloader = $('#product-video-woocommerce-preloader');
    const mpvw_button = $('#upload_video_button');
    const mpvw_button_clear = $('#upload_video_button_clear');
    const mpvw_player = $('#product_video_player');
    const mpvw_input = $('#product_video_url');

    mpvw_button_clear.on('click', function (e) {
        mpvw_button.text(ajaxDataMPVW.translations.button.upload);
        mpvw_input.val('');
        mpvw_player.children('source[type="video/mp4"]').attr('src', '');
        mpvw_player.children('source[type="video/webm"]').attr('src', '');
        mpvw_player.removeClass('product-video-woocommerce-show');
        mpvw_player.addClass('product-video-woocommerce-hide');
        mpvw_button_clear.removeClass('product-video-woocommerce-show');
        mpvw_button_clear.addClass('product-video-woocommerce-hide');
    });

    // allTimeMute();

    mpvw_button.on('click', function (e) {
        e.preventDefault();
        mpvwNotification.reset();
        let mpvw_file_frame = wp.media({
            title: ajaxDataMPVW.translations.fileFrame.title,
            button: {
                text: ajaxDataMPVW.translations.fileFrame.button.text,
            },
            library: {
                type: 'video'
            },
            multiple: false
        });

        mpvw_file_frame.on('select', function () {
            let attachment = mpvw_file_frame.state().get('selection').first().toJSON();
            mpvw_preloader.show();

            $.ajax({
                type: 'POST',
                url: ajaxDataMPVW.ajaxUrl,
                data: {
                    action: 'mpvw_convert_video_format',
                    attachment_id: attachment.id,
                    _ajax_nonce: ajaxDataMPVW.nonce
                },
                success: function (response) {
                    if (!response.success) {
                        mpvw_preloader.hide();
                        mpvwNotification.error(response.data);
                        return false;
                    }

                    const files = response.data['files'];
                    const progressFiles = response.data['progress_files'] ?? null;
                    const duration = response.data['duration'];

                    if (progressFiles === null) {
                        changeStatusBlock(files);
                        if (response.data['missing_format']) {
                            mpvwNotification.warning(ajaxDataMPVW.translations.notifications.missingFormats + ' ' + response.data['missing_format'].join(','));
                        }
                    } else {
                        const allCompleted = [];
                        Object.keys(progressFiles).forEach(format => allCompleted[format] = false);

                        const interval = setInterval(() => {
                            Object.keys(progressFiles).forEach(format => {
                                $.ajax({
                                    type: 'POST',
                                    url: ajaxDataMPVW.ajaxUrl,
                                    data: {
                                        action: 'mpvw_get_conversion_progress',
                                        progress_file: progressFiles[format],
                                        _ajax_nonce: ajaxDataMPVW.nonce
                                    },
                                    success: function (progressResponse) {
                                        if (progressResponse.success) {
                                            const progress = parseProgress(progressResponse.data.progressContent, duration);
                                            updateProgressBar(format, progress);
                                            allCompleted[format] = progress.progress === 'end';
                                        }
                                    },
                                    error: function (error) {
                                        clearInterval(interval);
                                        mpvw_preloader.hide();
                                        console.error('error', error);
                                    }
                                });
                            });

                            if (areAllTrue(allCompleted)) {
                                clearInterval(interval);
                                changeStatusBlock(files);
                            }

                        }, 1000);
                    }
                },
                error: function (error) {
                    mpvw_preloader.hide();
                    console.error('error', error);
                }
            });
        });

        mpvw_file_frame.open();
    });

    function changeStatusBlock(files = '') {
        let class1 = 'product-video-woocommerce-hide';
        let class2 = 'product-video-woocommerce-show';
        let valueFiles = '';

        if (files === '') {
            class1 = 'product-video-woocommerce-show';
            class2 = 'product-video-woocommerce-hide';
            mpvw_button.text(ajaxDataMPVW.translations.button.upload);
        } else {
            valueFiles = JSON.stringify(files);
            mpvw_button.text(ajaxDataMPVW.translations.button.change);
        }

        mpvw_input.val(valueFiles);
        mpvw_player.children('source[type="video/mp4"]').attr('src', files === '' ? '' : files['mp4']);
        mpvw_player.children('source[type="video/webm"]').attr('src', files === '' ? '' : files['webm']);
        mpvw_player.removeClass(class1);
        mpvw_player.addClass(class2);
        mpvw_button_clear.removeClass(class1);
        mpvw_button_clear.addClass(class2);

        if (files !== '') {
            mpvw_preloader.hide();
            mpvw_player[0].load();
            mpvw_player[0].play();
        }
    }

    function allTimeMute() {
        mpvw_player[0].volume = 0;
        mpvw_player[0].muted = true;
        mpvw_player[0].addEventListener('volumechange', () => {
            mpvw_player.muted = true;
            mpvw_player.volume = 0;
        });
    }
});

function parseProgress(progressContent, duration) {
    const progress = {};
    const lines = progressContent.split('\n');
    lines.forEach(line => {
        const [key, value] = line.split('=');
        if (key !== '') {
            progress[key] = value;
        }
    });
    progress['duration'] = duration;
    progress['percent'] = progress && progress.out_time_us ? Math.ceil((parseInt(progress.out_time_us) / duration) * 100) : 0;
    return progress;
}

function updateProgressBar(format, progress) {
    const progressBar = document.getElementById(`progress-bar-${format}`);
    if (progressBar) {
        progressBar.style.width = `${progress.percent}%`;
        progressBar.textContent = `${format}: ${progress.percent}%`;
    }
}

function areAllTrue(obj) {
    return Object.values(obj).every(value => value === true);
}

// Simple Notifications
class WpvNotification {
    constructor(selector) {
        this.notification = jQuery(selector);
    }

    #show() {
        this.notification.addClass('product-video-woocommerce-block__notification--show');
    }

    #add(text) {
        if (typeof text === 'string') {
            this.notification.text(text);
        }
    }

    #setTextType(classType, text) {
        this.notification.addClass('product-video-woocommerce-block__notification--' + classType);
        this.#add(text);
        this.#show();
    }

    error(text) {
        this.#setTextType('error', text);
    }

    success(text) {
        this.#setTextType('success', text);
    }

    warning(text) {
        this.#setTextType('warning', text);
    }

    log(text) {
        this.#setTextType('log', text);
    }

    hide() {
        this.notification.removeClass(function (index, className) {
            return (className.match(/product-video-woocommerce-block__notification--\S+/g) || []).join(' ');
        });
    }

    reset() {
        this.hide();
        this.#add('');
    }
}
