function showNotification(message, type = 'info') {
	const notification = document.createElement('div');
	notification.className = `ss-notification ss-notification-${type}`;
	notification.textContent = message;
	document.body.appendChild(notification);

	setTimeout(() => {
		notification.classList.add('show');
	}, 10);

	setTimeout(() => {
		notification.classList.remove('show');
		setTimeout(() => notification.remove(), 300);
	}, 3000);
}

document.addEventListener('DOMContentLoaded', function () {
    const filesWrap = document.querySelector('.ss-table-connected-files-wrap');
	const noFilesMassegeWrap = document.querySelector('.ss-no-files-massege-wrap');
	const expandCollapseButton = document.querySelector(".ss-table-title-wrap");
    const headerAndListFilesWrap = document.querySelector(".ss-table-header-and-list-files-wrap");
	const expandCollapseIcon = document.querySelector("#ss-expand-collapse-button span");
	const saveButton = document.querySelector('.ss-save-options-button');
    const checkboxes = document.querySelectorAll('.ss-css-checkbox');
	const paginationWrap = document.createElement('div');
    paginationWrap.className = 'ss-pagination-wrap';
    headerAndListFilesWrap.appendChild(paginationWrap);

    let filesPerPage = 10;
    let currentPage = 1;
    let allFiles = [];
	let activeFilesGlobal = [];
	let cachedPages = {};

    function applyTheme(theme) {
        const lightThemeLink = document.querySelector('link#wp-custom-css-ss-light-theme, link[href*="ss-light-theme.css"]');
        const darkThemeLink = document.querySelector('link#wp-custom-css-ss-dark-theme, link[href*="ss-dark-theme.css"]');
        if (!lightThemeLink) {
            const links = document.querySelectorAll('link');
            links.forEach(link => {
                if (link.href && link.href.indexOf('ss-light-theme.css') !== -1) {
                    link.id = 'wp-custom-css-ss-light-theme';
                }
                if (link.href && link.href.indexOf('ss-dark-theme.css') !== -1) {
                    link.id = 'wp-custom-css-ss-dark-theme';
                }
            });
            lightThemeLink = document.querySelector('link#wp-custom-css-ss-light-theme');
            darkThemeLink = document.querySelector('link#wp-custom-css-ss-dark-theme');
        }

        if (theme === 'dark') {
            if (lightThemeLink) lightThemeLink.disabled = true;
            if (darkThemeLink) darkThemeLink.disabled = false;
        } else {
            if (lightThemeLink) lightThemeLink.disabled = false;
            if (darkThemeLink) darkThemeLink.disabled = true;
        }
    }

    function toggleTheme() {
        let currentTheme = localStorage.getItem('ss_theme') || 'light';
        const newTheme = currentTheme === 'light' ? 'dark' : 'light';

		const overlay = document.createElement('div');
		overlay.style.position = 'fixed';
		overlay.style.top = 0;
		overlay.style.left = 0;
		overlay.style.width = '100%';
		overlay.style.height = '100%';
		overlay.style.backgroundColor = newTheme === 'dark' ? '#F0F0F0' : '#1E1E1E';
		overlay.style.opacity = 0;
		overlay.style.transition = 'opacity 0.5s ease';
		overlay.style.zIndex = 9999;
		document.body.appendChild(overlay);
		void overlay.offsetWidth;
		overlay.style.opacity = 1;

		setTimeout(() => {
			localStorage.setItem('ss_theme', newTheme);
			applyTheme(newTheme);
			const themeSwitch = document.querySelector('.ss-switch-theme');
			themeSwitch.classList.remove('ss-light-theme', 'ss-dark-theme');
			themeSwitch.classList.add('ss-' + newTheme + '-theme');
			overlay.style.opacity = 0;
			setTimeout(() => {
				document.body.removeChild(overlay);
			}, 500);
		}, 100);
    }

    const savedTheme = localStorage.getItem('ss_theme') || 'light';
    applyTheme(savedTheme);

    const themeSwitch = document.querySelector('.ss-switch-theme');
    if (themeSwitch) {
        themeSwitch.addEventListener('click', toggleTheme);
    }

    function updateFileCounts() {
        const totalFiles = allFiles.filter(file => file !== 'ss-active-css.json').length;
        const activeFilesCount = activeFilesGlobal.length;

        document.querySelector('.ss-active-files').textContent = activeFilesCount;
        document.querySelector('.ss-all-installed-files').textContent = totalFiles;
		
		console.log(`Обновлено: ${activeFilesCount} активных из ${totalFiles} файлов.`);
    }

    if (filesWrap) {
        if (!ssUploadData.hasFiles) {
            filesWrap.style.display = 'none';
            noFilesMassegeWrap.style.display = '';
        } else {
            filesWrap.style.display = '';
            noFilesMassegeWrap.style.display = 'none';
        }
    }

    let isExpanded = true;

    function toggleExpandCollapse() {
        isExpanded = !isExpanded;
        if (isExpanded) {
            headerAndListFilesWrap.classList.remove('ss-collapsed');
            expandCollapseIcon.classList.remove('fi-rr-caret-square-down');
            expandCollapseIcon.classList.add('fi-rr-caret-quare-up');
        } else {
            headerAndListFilesWrap.classList.add('ss-collapsed');
            expandCollapseIcon.classList.remove('fi-rr-caret-quare-up');
            expandCollapseIcon.classList.add('fi-rr-caret-square-down');
        }
    }

    expandCollapseButton.addEventListener("click", toggleExpandCollapse);

    function toggleExpandCollapseContent(wrapper) {
        const description = wrapper.querySelector('#ss-human-description-css');
        const authorName = wrapper.querySelector('#ss-author-human-name');
        const humanName = wrapper.querySelector('#ss-human-name-css');

        if (description && authorName && humanName) {
            const elements = [description, authorName, humanName];
            elements.forEach(element => {
                element.classList.toggle('ss-expand-collapse-content');
            });
        } else {
            console.warn('Не удалось найти элементы внутри .ss-single-file-wrap для переключения класса.');
        }

		const allFilesWrap = wrapper.closest('.ss-all-files-wrap');
		if (allFilesWrap) {
			if (allFilesWrap.id === "ss-expand-collapse-wrap") {
				allFilesWrap.removeAttribute("id");
			} else {
				allFilesWrap.id = "ss-expand-collapse-wrap";
			}
		}
    }

    document.addEventListener('click', function (event) {
        const singleFileWrap = event.target.closest('.ss-single-file-wrap');
        if (singleFileWrap) {
            toggleExpandCollapseContent(singleFileWrap);
        }
    });

	function syncCheckboxStates() {
		const cacheBuster = `?t=${new Date().getTime()}`;

		fetch(`/wp-content/ss-css/ss-active-css.json${cacheBuster}`)
			.then(response => response.json())
			.then(activeFiles => {

				const checkboxes = document.querySelectorAll('.ss-css-checkbox');
				if (!checkboxes.length) {
					console.warn('Чекбоксы ещё не добавлены в DOM');
					return;
				}
				
                checkboxes.forEach(checkbox => {
                    const isChecked = activeFiles.includes(checkbox.value);
                    checkbox.checked = isChecked;

                    if (isChecked && !activeFilesGlobal.includes(checkbox.value)) {
                        activeFilesGlobal.push(checkbox.value);
                    } else if (!isChecked) {
                        activeFilesGlobal = activeFilesGlobal.filter(file => file !== checkbox.value);
                    }
                });
                console.log('Синхронизированные активные файлы:', activeFilesGlobal);
				updateFileCounts();
            })
            .catch(console.error);
	}

	jQuery(document).ready(function ($) {
		const preloader = $("#ss-preloader");
		const dropArea = $(".ss-upload-area-wrap");
		const statusuploadOut = $(".ss-status-upload-out");
		const statusuploadIn = $(".ss-status-upload-in");
		const uploadButton = $("#ss-upload-button");
		const resetButton = $("#ss-reset-upload-button");
		const alertWrap = $(".ss-hidden-upload-alert-wrap");
		const yesButton = $(".ss-yes-upload-button");
		const noButton = $(".ss-no-upload-button");
		const filesListWrap = $(".ss-list-all-files-section");
		const fileInput = $("<input type='file' multiple accept='.css,.js'>");

		let selectedFiles = [];
		let existingFiles = [];

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

		statusuploadOut.css("display", "flex");
		statusuploadIn.css("display", "none");

		function getFilesMeta(fileNames) {
			return new Promise((resolve, reject) => {
				$.ajax({
					url: ssUploadData.ajaxUrl,
					method: "POST",
					data: {
						action: "ss_get_files_meta",
						files: JSON.stringify(fileNames),
						nonce: ssUploadData.nonce
					},
					success: function(response) {
						if (response.success) {
							resolve(response.data);
						} else {
							reject(response.data?.message);
						}
					},
					error: function() {
						reject("Ошибка запроса");
					}
				});
			});
		}

		async function isImageAvailable(url) {
			try {
				const response = await fetch(url, { method: 'HEAD' });
				return response.ok;
			} catch (error) {
				console.error(`Ошибка при проверке изображения: ${url}`, error);
				return false;
			}
		}

		function renderFileListForPage(page) {
			const uniqueFiles = [...new Set(allFiles)].filter(file => file !== 'ss-active-css.json');
			const preloader = $('#ss-preloader-content-mini');
			fadeIn(preloader);

			if (cachedPages[page]) {
				filesListWrap.html(cachedPages[page]);
				renderPagination();
				syncCheckboxStates();
				fadeOut(preloader);
				return;
			}

			filesListWrap.empty();
			paginationWrap.innerHTML = '';

			const startIndex = (page - 1) * filesPerPage;
			const endIndex = Math.min(startIndex + filesPerPage, uniqueFiles.length);
			const filesToRender = uniqueFiles.slice(startIndex, endIndex);

			getFilesMeta(filesToRender).then(metaDataObj => {
				let html = '';
				filesToRender.forEach(file => {
					const meta = metaDataObj[file] || {};
					const fileExt = file.split('.').pop();
					const displayName = meta.humanName || "Без названия";
					const displayDescription = meta.humanDescription || "(пока пусто)";
					const displayAuthor = meta.humanAuthor || "Пришелец";
					const defaultAuthorImage = `${window.location.origin}/wp-content/plugins/super-style/assets/image/autor-default.png`;
					const displayAuthorImage = meta.humanAuthorImage || defaultAuthorImage;

					const fileHtml = `
						<div class="ss-all-files-wrap">
							<input type="checkbox" id="${file}" value="${file}" class="ss-css-checkbox">
							<div class="ss-single-file-wrap" data-file-name="${file}">
								<div class="ss-file-row">
									<div class="ss-file-name-and-icon-wrap">
										<div class="ss-file-name-and-icon">
											<span class="fi fi-rr-file"></span>
											<p id="ss-human-name-css">${displayName}</p>
										</div>
									</div>
									<div class="ss-file-type-wrap">
										<p>${fileExt}</p>
									</div>
									<div class="ss-author-name-and-image-wrap">
										<div class="ss-author-name-and-image">
											<img id="ss-human-author-image" src="${displayAuthorImage}">
											<p id="ss-author-human-name">${displayAuthor}</p>
										</div>
									</div>									
									<div class="ss-file-description-wrap">
										<p id="ss-human-description-css">${displayDescription}</p>
									</div>
									<div class="ss-file-settings">
										<div class="ss-file-edit">
											<span class="fi fi-rr-pencil"></span>
										</div>
										<div class="ss-file-download">
											<span class="fi fi-rr-download"></span>
										</div>
										<div class="ss-file-delete">
											<span class="fi fi-rr-trash"></span>
										</div>
									</div>
								</div>
							</div>
						</div>`;
					html += fileHtml;
				});
				filesListWrap.html(html);

				cachedPages[page] = html;
				
				syncCheckboxStates();
				renderPagination();
				fadeOut(preloader);
			}).catch(err => {
				console.error("Ошибка получения метаданных:", err);
				fadeOut(preloader);
			});
		}

		function renderPagination() {
			const uniqueFiles = [...new Set(allFiles)].filter(file => file !== 'ss-active-css.json');
			const totalPages = Math.ceil(uniqueFiles.length / filesPerPage);

			if (totalPages <= 1) return;

			paginationWrap.innerHTML = '';

			for (let i = 1; i <= totalPages; i++) {
				const pageButton = document.createElement('button');
				pageButton.className = 'ss-pagination-button';
				pageButton.textContent = i;
				if (i === currentPage) {
					pageButton.classList.add('active');
				}
				pageButton.addEventListener('click', () => {
					currentPage = i;
					renderFileListForPage(currentPage);
				});
				paginationWrap.appendChild(pageButton);
			}
		}

        $(document).on('change', '.ss-css-checkbox', function () {
            const fileName = $(this).val();
            if ($(this).is(':checked')) {
                if (!activeFilesGlobal.includes(fileName)) {
                    activeFilesGlobal.push(fileName);
                }
            } else {
                activeFilesGlobal = activeFilesGlobal.filter(file => file !== fileName);
            }
            console.log('Текущие активные файлы:', activeFilesGlobal);
        });

		saveButton.addEventListener('click', function () {
			console.log('Сохраняем активные файлы:', activeFilesGlobal);

			const formData = new URLSearchParams();
			formData.append('action', 'ss_save_active_css');
			formData.append('nonce', ssUploadData.nonce);
			formData.append('activeFiles', JSON.stringify(activeFilesGlobal));

			fadeIn(preloader);

			fetch(ssUploadData.ajaxUrl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: formData.toString(),
			})
				.then(response => response.json())
				.then(data => {
					if (data.success) {
						fadeOut(preloader, 300);
						updateFileCounts();
						showNotification(data.message || 'Настройки успешно сохранены', 'success');
					} else {
						console.error('Ошибка ответа:', data);
						fadeOut(preloader, 300);
						showNotification(data.data?.message || 'Ошибка сохранения', 'error');
					}
				})
				.catch(error => {
					console.error('Ошибка при сохранении:', error);
					fadeOut(preloader, 300);
					showNotification('Ошибка при сохранении', 'error');
				});
		});

		function updateFileList() {
			$.post(ssUploadData.ajaxUrl, { action: "ss_get_existing_files", nonce: ssUploadData.nonce }, function (response) {
				if (response.success) {
					existingFiles = response.data;
					allFiles = response.data;
					cachedPages = {};

					fetch(`/wp-content/ss-css/ss-active-css.json`)
						.then((res) => res.json())
						.then((activeFiles) => {
							activeFilesGlobal = activeFiles.filter((file) => allFiles.includes(file));
							console.log("Инициализированные активные файлы:", activeFilesGlobal);
							renderFileListForPage(1);
						})
						.catch((err) => {
							console.error("Ошибка загрузки active-css.json:", err);
							renderFileListForPage(1);
						});
				} else {
					console.error("Ошибка получения списка файлов: ", response.data);
				}
			});
		}

		$(document).on('change', '#ss-check-all-files', function () {
			const isChecked = $(this).is(':checked');

			$('.ss-css-checkbox').each(function () {
				const fileName = $(this).val();
				
				if (fileName === 'ss-active-css.json') {
					return;
				}

				$(this).prop('checked', isChecked);

				if (isChecked) {
					if (!activeFilesGlobal.includes(fileName)) {
						activeFilesGlobal.push(fileName);
					}
				} else {
					activeFilesGlobal = activeFilesGlobal.filter(file => file !== fileName);
				}
			});

			if (isChecked) {
				allFiles.forEach(file => {
					if (file !== 'ss-active-css.json' && !activeFilesGlobal.includes(file)) {
						activeFilesGlobal.push(file);
					}
				});
			} else {
				activeFilesGlobal = [];
			}

			console.log('Текущие активные файлы после изменения "Выбрать все":', activeFilesGlobal);
		});

		function updateFileSelection(files) {
			selectedFiles = Array.from(files);
			const validFiles = selectedFiles.filter(file => file.name.endsWith(".css") || file.name.endsWith(".js"));
			$(".count-selected-files").text(validFiles.length);
			uploadButton.prop("disabled", validFiles.length === 0);
			$("#ss-select-upload-status").toggle(validFiles.length > 0);

			fileInput.val("");
		}

		dropArea.on("click", function () {
			fileInput.off("change").on("change", function (e) {
				updateFileSelection(e.target.files);
			}).click();
		});

		dropArea.on("dragenter dragover", function (e) {
			e.preventDefault();
			e.stopPropagation();
			dropArea.addClass("dragover");
			statusuploadOut.hide();
			statusuploadIn.show();
		});

		dropArea.on("dragleave drop", function (e) {
			e.preventDefault();
			e.stopPropagation();
			dropArea.removeClass("dragover");
			statusuploadOut.show();
			statusuploadIn.hide();

			if (e.type === "drop") {
				updateFileSelection(e.originalEvent.dataTransfer.files);
			}
		});

		resetButton.on("click", function () {
			selectedFiles = [];
			updateFileSelection([]);
		});

		uploadButton.on("click", function () {
			const validFiles = selectedFiles.filter(file => file.name.endsWith(".css") || file.name.endsWith(".js"));
			const duplicateFiles = validFiles.filter(file => existingFiles.includes(file.name));

			if (duplicateFiles.length > 0) {
				alertWrap.fadeIn();
				console.log("Совпадающие файлы:", duplicateFiles);
			} else {
				uploadFiles(validFiles);
			}
		});

		yesButton.on("click", function () {
			const validFiles = selectedFiles.filter(file => file.name.endsWith(".css") || file.name.endsWith(".js"));
			alertWrap.fadeOut();
			uploadFiles(validFiles);
		});

		noButton.on("click", function () {
			selectedFiles = selectedFiles.filter(file => !existingFiles.includes(file.name));
			updateFileSelection(selectedFiles);
			alertWrap.fadeOut();
		});

		function uploadFiles(files) {
			const formData = new FormData();
			files.forEach(file => formData.append("files[]", file));
			formData.append("action", "ss_upload_files");
			formData.append("nonce", ssUploadData.nonce);

			preloader.fadeIn();
			$.ajax({
				url: ssUploadData.ajaxUrl,
				method: "POST",
				data: formData,
				processData: false,
				contentType: false,
				success: function (response) {
					if (response.success) {
						location.reload();
					} else {
						alert("Ошибка загрузки: " + response.data.message);
					}
				},
				error: function () {
					alert("Произошла ошибка при загрузке файлов.");
				},
				complete: function () {
					preloader.fadeOut();
					selectedFiles = [];
					updateFileSelection([]);
				}
			});
		}
		updateFileList();
	});
});