jQuery(document).ready(function ($) {
    const createWrap = $('.ss-manually-create-wrap');
    const createButton = $('#ss-manually-create-empty-file');
    const cancelButton = $('#ss-manually-cancel-button');
    const closeIcon = $('.ss-manually-create-close-icon');
    const form = $('#ss-manually-create-form');
    const preloader = $('#ss-preloader');
	const fileExistsMessage = $('.ss-manually-input-css-name-exists');
	const fileNameWrongMessage = $('.ss-manually-input-css-name-wrong');
	const cssNameInput = $('#ss-css-name');

    let mediaUploader;

    $(document).on('click', '.ss-open-media-upload-image-button', function (e) {
        e.preventDefault();

        if (mediaUploader) {
            mediaUploader.open();
            return;
        }

        mediaUploader = wp.media({
            title: 'Загрузите или выберите квадратное изображение',
            button: {
                text: 'Выбрать',
            },
            multiple: false,
            library: {
                type: 'image',
            },
        });

        mediaUploader.on('select', function () {
            const attachment = mediaUploader.state().get('selection').first().toJSON();
            $('#ss-css-author-image').val(attachment.url);
        });

        mediaUploader.open();
    });

    const fadeIn = (element, duration = 300) => {
        $(element).css("opacity", 0).css("display", "flex").animate({ opacity: 1 }, duration);
    };

    const fadeOut = (element, duration = 300) => {
        $(element).animate({ opacity: 0 }, duration, function () {
            $(this).css("display", "none");
        });
    };

    createButton.on('click', function () {
        fadeIn(createWrap);
    });

    closeIcon.on('click', function () {
        fadeOut(createWrap);
		fileExistsMessage.hide();
		fileNameWrongMessage.hide();
    });

    createWrap.on('click', function (e) {
        if (!$(e.target).closest('.ss-manually-create-window').length) {
            fadeOut(createWrap);
			fileExistsMessage.hide();
			fileNameWrongMessage.hide();
        }
    });

    cancelButton.on('click', function () {
        form[0].reset();
		cssNameInput.removeClass('correct not-correct');
        fadeOut(createWrap);
		fileExistsMessage.hide();
		fileNameWrongMessage.hide();
    });

	cssNameInput.on('input', function () {
        const value = $(this).val();

        if (/^[a-zA-Z0-9\-]+\.(css|js)$/.test(value)) {
            $(this).removeClass('not-correct').addClass('correct');
        } else {
            $(this).removeClass('correct').addClass('not-correct');
        }
    });

    form.on('submit', function (e) {
        e.preventDefault();

        const cssName = cssNameInput.val();
		fileNameWrongMessage.hide();
		
        if (!/^[a-zA-Z0-9\-]+\.(css|js)$/.test(cssName)) {
            fileNameWrongMessage.css('display', 'flex');
            return;
        }

        fadeIn(preloader);
        fileExistsMessage.hide();

        $.ajax({
            url: ssManuallyCssUploadData.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ss_create_css_file',
                security: ssManuallyCssUploadData.nonce,
                css_name: cssName,
                css_title: $('#ss-css-title').val(),
                css_author: $('#ss-css-author-name').val(),
                css_image: $('#ss-css-author-image').val(),
                css_description: $('#ss-css-description').val(),
            },
            success: function (response) {
                fadeOut(preloader);

                if (response.success) {
                    if (response.data.exists) {
                        fileExistsMessage.css('display', 'flex');
                    } else {
                        location.reload();
                    }
                } else {
                    alert(response.data.message || 'Ошибка: сервер не смог обработать запрос.');
                }
            },
            error: function () {
                alert('Ошибка при создании файла. Проверьте соединение.');
                fadeOut(preloader);
            },
        });
    });
});