(function($) {
	'use strict';

	const cfg = window.wppsMediaRename || {};
	const ajaxUrl = cfg.ajaxUrl || '';
	const nonce = cfg.nonce || '';
	const strings = cfg.strings || {};

	function clearChildren(el) {
		while (el.firstChild) {
			el.removeChild(el.firstChild);
		}
	}

	function appendDismissButton(el) {
		var btn = document.createElement('button');
		btn.type = 'button';
		btn.className = 'wpps-result-dismiss';
		btn.setAttribute('aria-label', strings.dismiss || 'Dismiss');
		btn.textContent = '\u00d7';
		el.appendChild(btn);
	}

	function resultBaseClass(el) {
		return el && el.classList && el.classList.contains('wpps-scan-result') ? 'wpps-scan-result' : 'wpps-rename-result';
	}

	function showResult(el, msg, type) {
		if (!el) return;
		el.className = resultBaseClass(el) + ' ' + (type || 'info');
		clearChildren(el);
		var content = document.createElement('span');
		content.className = 'wpps-result-content';
		content.textContent = msg;
		el.appendChild(content);
		appendDismissButton(el);
		el.style.display = 'block';

		if (el._hideTimer) {
			clearTimeout(el._hideTimer);
		}
		el._hideTimer = setTimeout(function() {
			el._hideTimer = null;
			el.style.display = 'none';
		}, 20000);
	}

	function showResultLines(el, lines, type) {
		if (!el) return;
		el.className = resultBaseClass(el) + ' ' + (type || 'info');
		clearChildren(el);
		var content = document.createElement('span');
		content.className = 'wpps-result-content';
		lines.forEach(function(line, index) {
			if (index > 0) {
				content.appendChild(document.createElement('br'));
			}
			if (line.label) {
				var strong = document.createElement('strong');
				strong.textContent = line.label;
				content.appendChild(strong);
				content.appendChild(document.createTextNode(line.text || ''));
			} else {
				content.appendChild(document.createTextNode(line.text || ''));
			}
		});
		el.appendChild(content);
		appendDismissButton(el);
		el.style.display = 'block';

		if (el._hideTimer) {
			clearTimeout(el._hideTimer);
		}
		el._hideTimer = setTimeout(function() {
			el._hideTimer = null;
			el.style.display = 'none';
		}, 20000);
	}

	function hideResult(el) {
		if (!el) return;
		if (el._hideTimer) {
			clearTimeout(el._hideTimer);
			el._hideTimer = null;
		}
		el.style.display = 'none';
	}

	$(document).on('click', '.wpps-result-dismiss', function() {
		var box = this.closest('.wpps-rename-result, .wpps-scan-result');
		if (box) hideResult(box);
	});

	function renderScanResult(res, scanEl) {
		if (!res.success || !res.data) return;
		var lines = [];
		if (res.data.posts && res.data.posts.length) {
			lines.push({ label: (strings.postsInContent || 'Posts (in content)') + ':', text: ' ' + res.data.posts.length });
		}
		if (res.data.featured_in && res.data.featured_in.length) {
			var n = res.data.featured_in.length;
			var countStr = n === 1 ? (strings.postCount || '%d post').replace('%d', n) : (strings.postsCount || '%d posts').replace('%d', n);
			lines.push({ label: (strings.featuredIn || 'Featured image in') + ':', text: ' ' + countStr });
		}
		if (res.data.meta && res.data.meta.length) {
			lines.push({ label: (strings.meta || 'Meta') + ':', text: ' ' + res.data.meta.length });
		}
		if (res.data.options && res.data.options.length) {
			lines.push({ label: (strings.options || 'Options') + ':', text: ' ' + res.data.options.length });
		}
		if (lines.length) {
			showResultLines(scanEl, lines, 'info');
		} else {
			showResult(scanEl, strings.noReferences || 'No references found.', 'info');
		}
	}

	function renderBulkSummary(summaryDiv, results) {
		var success = 0;
		var failed = 0;
		var skipped = 0;
		results.forEach(function(r) {
			if (r.success) success++;
			else if (r.message && r.message.indexOf('excluded') !== -1) skipped++;
			else failed++;
		});

		clearChildren(summaryDiv);
		var strong = document.createElement('strong');
		strong.textContent = strings.bulkComplete || 'Complete';
		summaryDiv.appendChild(strong);
		summaryDiv.appendChild(document.createElement('br'));
		var text = (strings.bulkSuccess || 'Success') + ': ' + success;
		if (skipped) text += ', ' + (strings.bulkSkipped || 'Skipped') + ': ' + skipped;
		if (failed) text += ', ' + (strings.bulkFailed || 'Failed') + ': ' + failed;
		summaryDiv.appendChild(document.createTextNode(text));
		summaryDiv.style.display = 'block';
	}

	function showBulkError(summaryDiv, message) {
		clearChildren(summaryDiv);
		var strong = document.createElement('strong');
		strong.textContent = 'Error:';
		summaryDiv.appendChild(strong);
		summaryDiv.appendChild(document.createTextNode(' ' + message));
		summaryDiv.style.display = 'block';
	}

	function updateBulkProgress(done, total) {
		var pct = total > 0 ? Math.round((done / total) * 100) : 0;
		$('#wpps-bulk-progress-bar').attr({ value: pct, max: 100 });
		$('#wpps-bulk-counter').text(done);
		$('#wpps-bulk-total').text(total);
	}

	function renameOneBulkItem(id, pattern, prefix, suffix, updateTitle, counter) {
		return $.post(ajaxUrl, {
			action: 'wpps_media_rename_bulk',
			nonce: nonce,
			ids: [id],
			pattern: pattern,
			prefix: prefix,
			suffix: suffix,
			update_title: updateTitle ? 1 : 0,
			counter: counter
		});
	}

	function runBulkRename(ids, pattern, prefix, suffix, updateTitle, summaryDiv) {
		var results = [];
		var counter = 1;
		var index = 0;

		function next() {
			if (index >= ids.length) {
				renderBulkSummary(summaryDiv, results);
				$('#wpps-bulk-rename-start').prop('disabled', false);
				return;
			}

			var id = ids[index];
			renameOneBulkItem(id, pattern, prefix, suffix, updateTitle, counter)
				.done(function(res) {
					if (res.success && res.data && res.data.results && res.data.results.length) {
						results.push(res.data.results[0]);
						if (res.data.counter) {
							counter = res.data.counter;
						} else {
							counter++;
						}
					} else {
						results.push({
							id: id,
							success: false,
							message: res.data && res.data.message ? res.data.message : (strings.error || 'An error occurred.')
						});
						counter++;
					}
				})
				.fail(function() {
					results.push({
						id: id,
						success: false,
						message: strings.error || 'An error occurred.'
					});
					counter++;
				})
				.always(function() {
					index++;
					updateBulkProgress(index, ids.length);
					next();
				});
		}

		next();
	}

	$(document).on('click', '.wpps-scan-references-btn', function() {
		var btn = $(this);
		var panel = btn.closest('.wpps-media-rename-panel');
		var attachmentId = btn.data('attachment-id') || panel.data('attachment-id');
		var scanEl = panel.find('.wpps-scan-result')[0];
		hideResult(panel.find('.wpps-rename-result')[0]);
		hideResult(scanEl);
		btn.prop('disabled', true);
		$.post(ajaxUrl, {
			action: 'wpps_media_rename_scan',
			nonce: nonce,
			attachment_id: attachmentId
		})
			.done(function(res) {
				renderScanResult(res, scanEl);
			})
			.fail(function() {
				showResult(scanEl, strings.error || 'An error occurred.', 'error');
			})
			.always(function() {
				btn.prop('disabled', false);
			});
	});

	$(document).on('click', '.wpps-rename-file-btn', function() {
		var btn = $(this);
		var panel = btn.closest('.wpps-media-rename-panel');
		var attachmentId = btn.data('attachment-id') || panel.data('attachment-id');
		var input = panel.find('.wpps-new-filename');
		var newName = input.val().trim();
		var updateTitle = panel.find('.wpps-update-title').is(':checked');
		var resultEl = panel.find('.wpps-rename-result')[0];
		var scanEl = panel.find('.wpps-scan-result')[0];

		hideResult(resultEl);
		hideResult(scanEl);

		if (!newName) {
			newName = input.data('default') || '';
		}
		if (!newName) {
			showResult(resultEl, strings.emptyFilename || 'Please enter a new filename.', 'error');
			return;
		}

		btn.prop('disabled', true);
		$.post(ajaxUrl, {
			action: 'wpps_media_rename_rename',
			nonce: nonce,
			attachment_id: attachmentId,
			new_name: newName,
			update_title: updateTitle ? 1 : 0
		})
			.done(function(res) {
				if (res.success) {
					if (res.data && res.data.new_name) {
						panel.find('.wpps-current-filename code').text(res.data.new_name);
					}
					location.reload();
					return;
				}
				showResult(resultEl, res.data && res.data.message ? res.data.message : strings.error, 'error');
			})
			.fail(function() {
				showResult(resultEl, strings.error || 'An error occurred.', 'error');
			})
			.always(function() {
				btn.prop('disabled', false);
			});
	});

	$(document).on('click', '.wpps-bulk-rename-notice .button-primary', function() {
		$('#wpps-bulk-rename-modal').addClass('is-open').show();
	});

	$(document).on('click', '#wpps-bulk-rename-close', function() {
		$('#wpps-bulk-rename-modal').removeClass('is-open').hide();
		var url = new URL(window.location.href);
		url.searchParams.delete('wpps_bulk_rename');
		url.searchParams.delete('media');
		window.location.href = url.toString();
	});

	$(document).on('click', '#wpps-bulk-rename-start', function() {
		var idsStr = $('#wpps-bulk-rename-ids').val();
		var ids = idsStr ? idsStr.split(',').map(function(v) { return parseInt(v, 10); }).filter(Boolean) : [];
		var pattern = ($('#wpps-bulk-pattern').val() || '').trim() || '{title}';
		var prefix = ($('#wpps-bulk-prefix').val() || '').trim();
		var suffix = ($('#wpps-bulk-suffix').val() || '').trim();
		var updateTitle = $('#wpps-bulk-update-title').is(':checked');
		var summaryDiv = $('.wpps-bulk-summary')[0];

		if (!ids.length) {
			alert(strings.noFilesSelected || 'No files selected.');
			return;
		}

		$('.wpps-bulk-progress').show();
		if (summaryDiv) {
			summaryDiv.style.display = 'none';
		}
		$('#wpps-bulk-rename-start').prop('disabled', true);
		updateBulkProgress(0, ids.length);

		runBulkRename(ids, pattern, prefix, suffix, updateTitle, summaryDiv);
	});

	$(document).on('keydown', function(e) {
		if (e.key === 'Escape' && $('#wpps-bulk-rename-modal').hasClass('is-open')) {
			$('#wpps-bulk-rename-modal').removeClass('is-open').hide();
		}
	});

})(jQuery);
