jQuery(document).ready(function ($) {
    let editor = null;

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

    $(document).on("click", ".ss-file-edit", function () {
        const fileRow = $(this).closest(".ss-single-file-wrap");
        const fileName = fileRow.data("file-name");
		const fileExtension = fileName.split('.').pop();

        if (!["css", "js"].includes(fileExtension)) {
            alert("Неподдерживаемый формат файла.");
            return;
        }

        if (fileRow.find(".ss-file-content-wrap").length === 0) {
            const editWindowHtml = `
                <div class="ss-file-content-wrap" style="display: none;">
                    <div class="ss-file-content-window">
                        <div class="ss-window-close-wrap">
                            <span class="ss-window-close-icon"></span>
                        </div>
                        <div class="ss-window-content-wrap">
                            <div class="ss-window-title-and-button-wrap">
                                <div class="ss-window-title-wrap">
                                    <h2>Содержание файла</h2>
									<span id="ss-name-current-file">${fileName}</span>
                                </div>
                                <div class="ss-window-button-wrap">
                                    <button type="button" id="ss-file-content-save">Сохранить изменения</button>
                                </div>
                            </div>
                            <div class="ss-file-content-save-status" style="display: none;">
                                <p>Сохранено. Обновите страницу через Ctrl+F5, чтобы увидеть изменения.</p>
                            </div>
                            <div id="ss-file-content"></div>
                        </div>
                    </div>
                </div>`;
            fileRow.append(editWindowHtml);
        }

		fileRow.find("#ss-name-current-css-file").text(fileName);

        fadeIn($("#ss-preloader"));

        $.ajax({
            url: ssEditSinglePluginData.ajaxUrl,
            type: "POST",
            data: {
                action: "ss_get_css_file_content",
                fileName: fileName,
                nonce: ssEditSinglePluginData.nonce,
            },
            success: function (response) {
                if (response.success) {
                    const contentWrap = fileRow.find(".ss-file-content-wrap");
                    const contentElement = contentWrap.find("#ss-file-content")[0];

                    if (editor) {
                        editor.toTextArea();
                        editor = null;
                    }

                    contentElement.value = response.data.content;

                    editor = CodeMirror.fromTextArea(contentElement, {
                        value: response.data.content,
                        mode: "css",
                        lineNumbers: true,
						lineWrapping: true,
						scrollbarStyle: "overlay",
						autoCloseBrackets: true,
						styleActiveLine: true,
						colorpicker : true,
						colorpicker : {
							mode : 'edit',
							type: 'box',
							hideDelay: 100000,
						  },
                        theme: "default",
                        indentUnit: 4,
                        tabSize: 4,
						extraKeys: {
							"F11": function(cm) {
							  cm.setOption("fullScreen", !cm.getOption("fullScreen"));
							},
							"Esc": function(cm) {
							  if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
							}
						  }
                    });

                    fadeIn(contentWrap, 300);

					setTimeout(() => {
						editor.refresh();
					}, 10);
				} else {
					alert(response.data.message || "Ошибка при загрузке содержимого файла.");
				}
				fadeOut($("#ss-preloader"));
            },
            error: function () {
                alert("Ошибка AJAX-запроса.");
                fadeOut($("#ss-preloader"));
            },
        });
    });

    $(document).on("click", ".ss-window-close-icon", function () {
        const contentWrap = $(this).closest(".ss-file-content-wrap");
        fadeOut(contentWrap);
    });

	$(document).on("click", ".ss-file-content-wrap", function (e) {
		if (!$(e.target).closest(".ss-file-content-window").length) {
			fadeOut($(this));
		}
	});

    $(document).on("click", "#ss-file-content-save", function () {
        const contentWrap = $(this).closest(".ss-file-content-wrap");
        const fileRow = contentWrap.closest(".ss-single-file-wrap");
        const fileName = fileRow.data("file-name");

        const newContent = editor.getValue();

        fadeIn($("#ss-preloader"));

        $.ajax({
            url: ssEditSinglePluginData.ajaxUrl,
            type: "POST",
            data: {
                action: "ss_save_css_file_content",
                fileName: fileName,
                content: newContent,
                nonce: ssEditSinglePluginData.nonce,
            },
            success: function (response) {
                if (response.success) {
                    const saveStatus = contentWrap.find(".ss-file-content-save-status");
                    fadeIn(saveStatus);
                    setTimeout(() => {
                        fadeOut(saveStatus);
                    }, 3000);
                } else {
                    alert(response.data.message || "Ошибка при сохранении файла.");
                }
                fadeOut($("#ss-preloader"));
            },
            error: function () {
                alert("Ошибка AJAX-запроса.");
                fadeOut($("#ss-preloader"));
            },
        });
    });
});