/**
 * Admin Data Export/Import JavaScript
 *
 * Handles tab switching, file upload validation, select all/none,
 * and AJAX import with progress updates.
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/assets/js
 * @since      1.0.265
 */

/* global jQuery, macmDataAdmin */
(function($) {
	'use strict';

	/**
	 * Get a translated string from macmDataAdmin.i18n with a fallback.
	 *
	 * @param {string} key      The i18n key.
	 * @param {string} fallback The fallback string if key is not found.
	 * @return {string} The translated string or fallback.
	 */
	function i18n(key, fallback) {
		return (typeof macmDataAdmin !== 'undefined' && macmDataAdmin.i18n && macmDataAdmin.i18n[key]) ? macmDataAdmin.i18n[key] : fallback;
	}

	/**
	 * Data Admin Module
	 */
	var MACMDataAdmin = {
		/**
		 * Initialize the module.
		 */
		init: function() {
			this.bindEvents();
			this.initFileUpload();
		},

		/**
		 * Selected files array for multiple file upload.
		 */
		selectedFiles: [],

		/**
		 * Bind event handlers.
		 */
		bindEvents: function() {
			// Select all/none buttons.
			$('.macm-select-all').on('click', this.selectAll);
			$('.macm-select-none').on('click', this.selectNone);

			// Export form validation.
			$('.macm-export-form').on('submit', this.validateExport);

			// Export format change - toggle photos section.
			$('input[name="export_format"]').on('change', this.togglePhotosSection);
			this.togglePhotosSection();

			// Import form handling.
			$('#macm-import-form').on('submit', this.handleImport.bind(this));

			// File input change.
			$('#macm-import-file').on('change', this.handleFileSelect.bind(this));

			// Clear files button.
			$('#macm-clear-files').on('click', this.clearFiles.bind(this));

			// Reset button.
			$('#macm-reset-btn').on('click', this.handleReset.bind(this));
		},

		/**
		 * Toggle photos section visibility based on export format.
		 *
		 * Only visible when JSON format is selected and premium + ZipArchive available.
		 */
		togglePhotosSection: function() {
			var format = $('input[name="export_format"]:checked').val();
			var $section = $('#macm-photos-section');
			var canExportPhotos = macmDataAdmin.isPremium && macmDataAdmin.hasZip;

			if ('json' === format && canExportPhotos) {
				$section.show();
			} else {
				$section.hide();
				$('#macm-include-photos').prop('checked', false);
			}
		},

		/**
		 * Initialize file upload drag and drop.
		 */
		initFileUpload: function() {
			var $upload = $('.macm-file-upload');

			$upload.on('dragover dragenter', function(e) {
				e.preventDefault();
				e.stopPropagation();
				$(this).addClass('dragover');
			});

			$upload.on('dragleave dragend drop', function(e) {
				e.preventDefault();
				e.stopPropagation();
				$(this).removeClass('dragover');
			});

			$upload.on('drop', function(e) {
				var files = e.originalEvent.dataTransfer.files;
				if (files.length) {
					$('#macm-import-file')[0].files = files;
					$('#macm-import-file').trigger('change');
				}
			});
		},

		/**
		 * Select all checkboxes.
		 *
		 * @param {Event} e Click event.
		 */
		selectAll: function(e) {
			e.preventDefault();
			$('.macm-entity-card input[type="checkbox"]:not(:disabled)').prop('checked', true);
		},

		/**
		 * Deselect all checkboxes.
		 *
		 * @param {Event} e Click event.
		 */
		selectNone: function(e) {
			e.preventDefault();
			$('.macm-entity-card input[type="checkbox"]').prop('checked', false);
		},

		/**
		 * Validate export form.
		 *
		 * @param {Event} e Submit event.
		 * @return {boolean} Whether form is valid.
		 */
		validateExport: function(e) {
			var $checked = $('.macm-entity-card input[type="checkbox"]:checked');

			if ($checked.length === 0) {
				e.preventDefault();
				alert(macmDataAdmin.i18n.selectDataType || 'Please select at least one data type to export.');
				return false;
			}

			return true;
		},

		/**
		 * Handle file selection (supports multiple files).
		 *
		 * @param {Event} e Change event.
		 */
		handleFileSelect: function(e) {
			var files = e.target.files;
			var $preview = $('#macm-file-preview');
			var $fileList = $('#macm-selected-files');
			var self = this;

			// Reset import state when new files are selected.
			this.importId = null;
			$('#macm-import-btn').html('<span class="dashicons dashicons-upload"></span> ' + i18n('startImport', 'Start Import'));
			$('#macm-import-results').hide();
			$('#macm-import-progress').hide();

			if (!files || files.length === 0) {
				$preview.hide();
				$fileList.hide();
				this.selectedFiles = [];
				return;
			}

			// Validate files.
			var validTypes = ['application/json', 'text/csv', 'text/plain', 'application/zip', 'application/x-zip-compressed'];
			var validExtensions = ['.json', '.csv', '.zip'];
			var maxSize = 10 * 1024 * 1024;
			var maxSizeZip = 100 * 1024 * 1024;
			var validFiles = [];
			var hasJson = false;
			var hasZip = false;
			var errors = [];

			for (var i = 0; i < files.length; i++) {
				var file = files[i];
				var fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));

				// Validate file type.
				if (validTypes.indexOf(file.type) === -1 && validExtensions.indexOf(fileExtension) === -1) {
					errors.push(file.name + ': ' + i18n('invalidFileTypeShort', 'Invalid file type'));
					continue;
				}

				// Validate file size (ZIP has higher limit).
				var fileSizeLimit = (fileExtension === '.zip') ? maxSizeZip : maxSize;
				if (file.size > fileSizeLimit) {
					var limitLabel = (fileExtension === '.zip') ? '100MB' : '10MB';
					errors.push(file.name + ': ' + i18n('fileTooLargeMax', 'File too large (max %s)').replace('%s', limitLabel));
					continue;
				}

				// Check for JSON file.
				if (fileExtension === '.json') {
					if (hasJson) {
						errors.push(file.name + ': ' + i18n('onlyOneJson', 'Only one JSON file allowed'));
						continue;
					}
					hasJson = true;
				}

				// ZIP files must be imported alone.
				if (fileExtension === '.zip') {
					if (hasZip || hasJson || validFiles.length > 0) {
						errors.push(file.name + ': ' + i18n('zipImportAlone', 'ZIP files must be imported alone'));
						continue;
					}
					hasZip = true;
				}

				// If JSON or ZIP is selected, don't allow CSV files.
				if ((hasJson || hasZip) && fileExtension === '.csv') {
					errors.push(file.name + ': ' + i18n('cannotMixJsonZip', 'Cannot mix with JSON/ZIP files'));
					continue;
				}

				// Don't allow other files if ZIP is already selected.
				if (hasZip && fileExtension !== '.zip') {
					errors.push(file.name + ': ' + i18n('cannotMixZip', 'Cannot mix with ZIP file'));
					continue;
				}

				validFiles.push(file);
			}

			// Show errors if any.
			if (errors.length > 0) {
				alert(i18n('filesNotAdded', 'Some files were not added:') + '\n\n' + errors.join('\n'));
			}

			if (validFiles.length === 0) {
				e.target.value = '';
				$preview.hide();
				$fileList.hide();
				this.selectedFiles = [];
				return;
			}

			// Store valid files.
			this.selectedFiles = validFiles;

			// Update UI based on file count.
			if (validFiles.length === 1) {
				// Single file - show simple preview.
				var singleFile = validFiles[0];
				$('.macm-file-text').text(singleFile.name + ' (' + this.formatFileSize(singleFile.size) + ')');
				$fileList.hide();

				var ext = singleFile.name.toLowerCase().substring(singleFile.name.lastIndexOf('.'));
				if (ext === '.zip') {
					this.previewZipFile(singleFile, $preview);
				} else if (ext === '.json') {
					this.previewJsonFile(singleFile, $preview);
				} else {
					this.previewCsvFile(singleFile, $preview);
				}
			} else {
				// Multiple files - show file list.
				$('.macm-file-text').text(i18n('filesSelected', '%d files selected').replace('%d', validFiles.length));
				this.showFileList(validFiles);
				$preview.hide();
			}
		},

		/**
		 * Show list of selected files.
		 *
		 * @param {Array} files Array of File objects.
		 */
		showFileList: function(files) {
			var $fileList = $('#macm-selected-files');
			var $ul = $fileList.find('.macm-file-list');
			var self = this;

			$ul.empty();

			for (var i = 0; i < files.length; i++) {
				var file = files[i];
				var ext = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
				var icon = ext === '.json' ? 'media-code' : 'media-spreadsheet';

				var $li = $('<li class="macm-file-item" data-index="' + i + '">' +
					'<span class="dashicons dashicons-' + icon + '"></span>' +
					'<span class="macm-file-name">' + this.escapeHtml(file.name) + '</span>' +
					'<span class="macm-file-size">(' + this.formatFileSize(file.size) + ')</span>' +
					'<button type="button" class="macm-remove-file" title="Remove">' +
					'<span class="dashicons dashicons-no-alt"></span>' +
					'</button>' +
					'</li>');

				$li.find('.macm-remove-file').on('click', function() {
					var index = $(this).closest('.macm-file-item').data('index');
					self.removeFile(index);
				});

				$ul.append($li);
			}

			$fileList.show();
		},

		/**
		 * Remove a file from the selection.
		 *
		 * @param {number} index Index of file to remove.
		 */
		removeFile: function(index) {
			this.selectedFiles.splice(index, 1);

			if (this.selectedFiles.length === 0) {
				this.clearFiles();
			} else if (this.selectedFiles.length === 1) {
				// Switch to single file view.
				var file = this.selectedFiles[0];
				$('.macm-file-text').text(file.name + ' (' + this.formatFileSize(file.size) + ')');
				$('#macm-selected-files').hide();

				var ext = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
				var $preview = $('#macm-file-preview');
				if (ext === '.json') {
					this.previewJsonFile(file, $preview);
				} else {
					this.previewCsvFile(file, $preview);
				}
			} else {
				// Update file list.
				$('.macm-file-text').text(i18n('filesSelected', '%d files selected').replace('%d', this.selectedFiles.length));
				this.showFileList(this.selectedFiles);
			}
		},

		/**
		 * Clear all selected files.
		 */
		clearFiles: function() {
			this.selectedFiles = [];
			$('#macm-import-file').val('');
			$('.macm-file-text').text(i18n('chooseFilesOrDrag', 'Choose files or drag and drop'));
			$('#macm-selected-files').hide();
			$('#macm-file-preview').hide();
			this.importId = null;
		},

		/**
		 * Preview JSON file contents.
		 *
		 * @param {File}   file     The file to preview.
		 * @param {jQuery} $preview The preview container.
		 */
		previewJsonFile: function(file, $preview) {
			var reader = new FileReader();
			var self = this;

			reader.onload = function(e) {
				try {
					var data = JSON.parse(e.target.result);
					var html = '';

					if (data.macm_export) {
						html += '<div class="macm-preview-item">';
						html += '<span>' + i18n('exportVersion', 'Export Version:') + '</span>';
						html += '<span>' + self.escapeHtml(data.macm_export.version || i18n('unknown', 'Unknown')) + '</span>';
						html += '</div>';

						html += '<div class="macm-preview-item">';
						html += '<span>' + i18n('exportDate', 'Export Date:') + '</span>';
						html += '<span>' + self.escapeHtml(data.macm_export.exported_at || i18n('unknown', 'Unknown')) + '</span>';
						html += '</div>';

						if (data.macm_export.entities_included) {
							html += '<div class="macm-preview-item">';
							html += '<span>' + i18n('entities', 'Entities:') + '</span>';
							html += '<span>' + self.escapeHtml(data.macm_export.entities_included.join(', ')) + '</span>';
							html += '</div>';
						}
					}

					// Count records per entity.
					var counts = [];
					for (var key in data) {
						if (key !== 'macm_export' && Array.isArray(data[key])) {
							counts.push(key + ': ' + data[key].length);
						}
					}

					if (counts.length) {
						html += '<div class="macm-preview-item">';
						html += '<span>' + i18n('records', 'Records:') + '</span>';
						html += '<span>' + self.escapeHtml(counts.join(', ')) + '</span>';
						html += '</div>';
					}

					$preview.find('.macm-preview-content').html(html);
					$preview.show();
				} catch (err) {
					$preview.find('.macm-preview-content').html('<p>' + i18n('unableToParseJson', 'Unable to parse JSON file.') + '</p>');
					$preview.show();
				}
			};

			reader.readAsText(file);
		},

		/**
		 * Preview CSV file contents.
		 *
		 * @param {File}   file     The file to preview.
		 * @param {jQuery} $preview The preview container.
		 */
		previewCsvFile: function(file, $preview) {
			var reader = new FileReader();
			var self = this;

			reader.onload = function(e) {
				var lines = e.target.result.split('\n');
				var html = '';

				html += '<div class="macm-preview-item">';
				html += '<span>' + i18n('totalRows', 'Total Rows:') + '</span>';
				html += '<span>' + i18n('rowsExcludingHeader', '%d (excluding header)').replace('%d', lines.length - 1) + '</span>';
				html += '</div>';

				if (lines.length > 0) {
					var headers = lines[0].split(',');
					html += '<div class="macm-preview-item">';
					html += '<span>' + i18n('columns', 'Columns:') + '</span>';
					html += '<span>' + self.escapeHtml(headers.join(', ')) + '</span>';
					html += '</div>';
				}

				$preview.find('.macm-preview-content').html(html);
				$preview.show();
			};

			reader.readAsText(file);
		},

		/**
		 * Preview ZIP file contents.
		 *
		 * @param {File}   file     The file to preview.
		 * @param {jQuery} $preview The preview container.
		 */
		previewZipFile: function(file, $preview) {
			var html = '<div class="macm-preview-item">';
			html += '<span>File Type:</span>';
			html += '<span>' + i18n('zipArchiveWithPhotos', 'ZIP Archive (with photos)') + '</span>';
			html += '</div>';

			html += '<div class="macm-preview-item">';
			html += '<span>' + i18n('fileSize', 'File Size:') + '</span>';
			html += '<span>' + this.formatFileSize(file.size) + '</span>';
			html += '</div>';

			html += '<div class="macm-preview-item">';
			html += '<span>' + i18n('note', 'Note:') + '</span>';
			html += '<span>' + i18n('zipContentsNote', 'Full contents will be shown after validation.') + '</span>';
			html += '</div>';

			$preview.find('.macm-preview-content').html(html);
			$preview.show();
		},

		/**
		 * Current import ID (set after validation).
		 */
		importId: null,

		/**
		 * Handle import form submission.
		 *
		 * Two-step process: validate first, then import.
		 * Supports multiple CSV files.
		 *
		 * @param {Event} e Submit event.
		 */
		handleImport: function(e) {
			e.preventDefault();

			var $form = $(e.target);

			// Validate file selection using selectedFiles array.
			if (!this.selectedFiles || this.selectedFiles.length === 0) {
				alert(macmDataAdmin.i18n.selectFile || 'Please select a file to import.');
				return;
			}

			// If we already have an import_id, proceed with import.
			if (this.importId) {
				this.executeImport($form);
				return;
			}

			// Show progress section.
			$('#macm-import-progress').show();
			$('#macm-import-results').hide();
			$('#macm-import-btn').prop('disabled', true);

			var fileCount = this.selectedFiles.length;
			var statusText = fileCount === 1 ? i18n('validatingFile', 'Validating file...') : i18n('validatingFiles', 'Validating %d files...').replace('%d', fileCount);
			this.updateProgress(10, statusText);

			// Prepare form data for validation with all selected files.
			var formData = new FormData();
			formData.append('action', 'macm_validate_import');
			formData.append('nonce', macmDataAdmin.nonce);
			formData.append('user_mapping', $('input[name="user_mapping"]:checked').val());
			formData.append('conflict_resolution', $('input[name="conflict_resolution"]:checked').val());

			// Add all selected files.
			for (var i = 0; i < this.selectedFiles.length; i++) {
				formData.append('import_file[]', this.selectedFiles[i]);
			}

			// First step: validate the files.
			this.validateImport(formData, $form);
		},

		/**
		 * Step 1: Validate import file via AJAX.
		 *
		 * @param {FormData} formData The form data.
		 * @param {jQuery}   $form    The form element.
		 */
		validateImport: function(formData, $form) {
			var self = this;

			$.ajax({
				url: macmDataAdmin.ajaxUrl,
				type: 'POST',
				data: formData,
				processData: false,
				contentType: false,
				success: function(response) {
					if (response.success) {
						// Store import_id and show preview.
						self.importId = response.data.import_id;
						self.updateProgress(30, i18n('fileValidatedReview', 'File validated. Review preview and confirm import...'));
						self.showValidationPreview(response.data);

						// Now wait for user to confirm.
						$('#macm-import-btn').prop('disabled', false).html(
							'<span class="dashicons dashicons-yes"></span> ' + i18n('confirmImportBtn', 'Confirm Import')
						);
					} else {
						self.showError(response.data.message || macmDataAdmin.i18n.error);
						$('#macm-import-btn').prop('disabled', false).html(
							'<span class="dashicons dashicons-upload"></span> ' + i18n('startImport', 'Start Import')
						);
					}
				},
				error: function() {
					self.showError(macmDataAdmin.i18n.error);
					$('#macm-import-btn').prop('disabled', false).html(
						'<span class="dashicons dashicons-upload"></span> ' + i18n('startImport', 'Start Import')
					);
				}
			});
		},

		/**
		 * Show validation preview before import.
		 *
		 * @param {Object} data Validation response data.
		 */
		showValidationPreview: function(data) {
			var html = '<div class="macm-validation-summary">';

			// File info.
			if (data.file) {
				html += '<p><strong>' + i18n('fileLabel', 'File:') + '</strong> ' + this.escapeHtml(data.file.name) +
					' (' + this.escapeHtml(data.file.size) + ')</p>';
			}

			// Source info.
			if (data.metadata && data.metadata.source_site) {
				html += '<p><strong>' + i18n('sourceLabel', 'Source:') + '</strong> ' + this.escapeHtml(data.metadata.source_site) + '</p>';
			}

			// Entities to import.
			html += '<h4>' + i18n('dataToImport', 'Data to import:') + '</h4><ul>';
			for (var entity in data.entities) {
				var info = data.entities[entity];
				var label = info.label || entity;
				var count = info.count || 0;
				var premium = info.premium ? ' ' + i18n('premiumLabel', '(Premium)') : '';
				html += '<li>' + this.escapeHtml(label) + ': <strong>' + i18n('recordCount', '%d records').replace('%d', count) + '</strong>' + premium + '</li>';
			}
			html += '</ul>';

			// Photo count.
			if (data.photos && data.photos.count > 0) {
				html += '<p><strong>' + i18n('photosLabel', 'Photos:') + '</strong> ' + data.photos.count + ' photo(s) will be imported.</p>';
			}

			// User mapping info.
			if (data.user_mapping) {
				html += '<p><strong>' + i18n('userMatchingLabel', 'User Matching:') + '</strong> ' +
					data.user_mapping.matching_users + ' of ' +
					data.user_mapping.emails_found + ' emails match existing users.</p>';
			}

			// Warnings.
			if (data.warnings && data.warnings.length) {
				html += '<div class="macm-warnings"><strong>' + i18n('warningsLabel', 'Warnings:') + '</strong><ul>';
				for (var i = 0; i < data.warnings.length; i++) {
					html += '<li>' + this.escapeHtml(data.warnings[i]) + '</li>';
				}
				html += '</ul></div>';
			}

			html += '</div>';

			this.addLog(i18n('fileValidatedProceed', 'File validated successfully. Click "Confirm Import" to proceed.'), 'success');
			$('#macm-import-results .macm-results-content').html(html);
			$('#macm-import-results').show();
		},

		/**
		 * Step 2: Execute the actual import.
		 *
		 * @param {jQuery} $form The form element.
		 */
		executeImport: function($form) {
			var self = this;

			// Confirm import.
			if (!confirm(macmDataAdmin.i18n.confirmImport)) {
				return;
			}

			$('#macm-import-btn').prop('disabled', true).text(macmDataAdmin.i18n.importing);
			$('#macm-import-results').hide();
			this.updateProgress(50, i18n('importingData', 'Importing data...'));

			// Prepare data for import.
			var importData = {
				action: 'macm_process_import',
				nonce: macmDataAdmin.nonce,
				import_id: this.importId,
				user_mapping: $('input[name="user_mapping"]:checked').val(),
				conflict_resolution: $('input[name="conflict_resolution"]:checked').val()
			};

			$.ajax({
				url: macmDataAdmin.ajaxUrl,
				type: 'POST',
				data: importData,
				success: function(response) {
					if (response.success) {
						self.updateProgress(100, i18n('importCompleted', 'Import completed successfully!'));
						self.showResults(response.data);
						self.addLog(response.data.message, 'success');

						// Reset form after successful import.
						self.resetImportForm();
					} else {
						self.showError(response.data.message || macmDataAdmin.i18n.error);
						// Re-enable button on error.
						$('#macm-import-btn').prop('disabled', false).html(
							'<span class="dashicons dashicons-upload"></span> ' + i18n('startImport', 'Start Import')
						);
					}
				},
				error: function() {
					self.showError(macmDataAdmin.i18n.error);
					// Re-enable button on error.
					$('#macm-import-btn').prop('disabled', false).html(
						'<span class="dashicons dashicons-upload"></span> ' + i18n('startImport', 'Start Import')
					);
				}
			});
		},

		/**
		 * Update progress bar.
		 *
		 * @param {number} percent Progress percentage.
		 * @param {string} status  Status text.
		 */
		updateProgress: function(percent, status) {
			$('.macm-progress-fill').css('width', percent + '%');
			$('.macm-progress-percent').text(percent + '%');
			$('.macm-progress-text').text(status);
		},

		/**
		 * Add log entry.
		 *
		 * @param {string} message Log message.
		 * @param {string} type    Log type (success, error, warning).
		 */
		addLog: function(message, type) {
			var $log = $('.macm-progress-log');
			var className = type ? 'log-' + type : '';
			$log.append('<div class="log-item ' + className + '">' + this.escapeHtml(message) + '</div>');
			$log.scrollTop($log[0].scrollHeight);
		},

		/**
		 * Show import results.
		 *
		 * @param {Object} data Results data.
		 */
		showResults: function(data) {
			var html = '<table>';
			html += '<tr><th>' + i18n('thEntity', 'Entity') + '</th><th>' + i18n('thCreated', 'Created') + '</th><th>' + i18n('thUpdated', 'Updated') + '</th><th>' + i18n('thSkipped', 'Skipped') + '</th><th>' + i18n('thErrors', 'Errors') + '</th></tr>';

			if (data.results) {
				for (var entity in data.results) {
					var r = data.results[entity];
					html += '<tr>';
					html += '<td>' + this.escapeHtml(entity) + '</td>';
					html += '<td class="macm-results-success">' + (r.created || 0) + '</td>';
					html += '<td>' + (r.updated || 0) + '</td>';
					html += '<td>' + (r.skipped || 0) + '</td>';
					html += '<td class="macm-results-error">' + (r.errors || 0) + '</td>';
					html += '</tr>';
				}
			}

			html += '</table>';

			// Show photo results if available.
			if (data.photos) {
				html += '<p class="macm-photo-results">';
				html += '<strong>' + i18n('photos', 'Photos:') + '</strong> ';
				html += i18n('photosImportedCount', '%d imported').replace('%d', data.photos.imported || 0);
				if (data.photos.failed > 0) {
					html += ', ' + i18n('photosFailed', '%d failed').replace('%d', data.photos.failed);
				}
				if (data.photos.skipped > 0) {
					html += ', ' + i18n('photosSkipped', '%d skipped').replace('%d', data.photos.skipped);
				}
				html += '</p>';
			}

			$('#macm-import-results .macm-results-content').html(html);
			$('#macm-import-results').show();
		},

		/**
		 * Show error message.
		 *
		 * @param {string} message Error message.
		 */
		showError: function(message) {
			this.updateProgress(0, 'Error');
			this.addLog(message, 'error');
			$('#macm-import-btn').prop('disabled', false).html(
				'<span class="dashicons dashicons-upload"></span> ' + i18n('startImport', 'Start Import')
			);
		},

		/**
		 * Format file size.
		 *
		 * @param {number} bytes File size in bytes.
		 * @return {string} Formatted size.
		 */
		formatFileSize: function(bytes) {
			if (bytes === 0) {
				return '0 Bytes';
			}

			var k = 1024;
			var sizes = ['Bytes', 'KB', 'MB', 'GB'];
			var i = Math.floor(Math.log(bytes) / Math.log(k));

			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
		},

		/**
		 * Escape HTML entities.
		 *
		 * @param {string} text Text to escape.
		 * @return {string} Escaped text.
		 */
		escapeHtml: function(text) {
			if (typeof text !== 'string') {
				return text;
			}

			var map = {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				'"': '&quot;',
				"'": '&#039;'
			};

			return text.replace(/[&<>"']/g, function(m) {
				return map[m];
			});
		},

		/**
		 * Handle reset button click.
		 *
		 * Shows a multi-step confirmation dialog before resetting plugin data.
		 *
		 * @param {Event} e Click event.
		 */
		handleReset: function(e) {
			e.preventDefault();

			var self = this;

			// First confirmation - alert with warning.
			var confirmed = confirm(
				'⚠️ ' + macmDataAdmin.i18n.resetConfirm1 + '\n\n' +
				macmDataAdmin.i18n.resetConfirm2 + '\n\n' +
				i18n('clickOkOrCancel', 'Click OK to continue or Cancel to abort.')
			);

			if (!confirmed) {
				alert(macmDataAdmin.i18n.resetCancelled);
				return;
			}

			// Second confirmation - require typing "RESET".
			var typedConfirm = prompt(
				'⚠️ ' + i18n('finalWarning', 'FINAL WARNING') + ' ⚠️\n\n' +
				macmDataAdmin.i18n.resetConfirm1 + '\n\n' +
				macmDataAdmin.i18n.resetConfirm3
			);

			if (typedConfirm === null) {
				alert(macmDataAdmin.i18n.resetCancelled);
				return;
			}

			if (typedConfirm !== 'RESET') {
				alert(i18n('invalidResetConfirmation', 'Invalid confirmation. You must type "RESET" exactly.') + '\n\n' + macmDataAdmin.i18n.resetCancelled);
				return;
			}

			// User confirmed - proceed with reset.
			self.executeReset();
		},

		/**
		 * Execute the reset operation.
		 *
		 * Sends AJAX request to reset all plugin data.
		 */
		executeReset: function() {
			var self = this;
			var $btn = $('#macm-reset-btn');
			var $progress = $('#macm-reset-progress');
			var $results = $('#macm-reset-results');

			// Show progress, hide results.
			$progress.show();
			$results.hide().removeClass('success error');

			// Disable button and show loading state.
			$btn.prop('disabled', true).html(
				'<span class="dashicons dashicons-update-alt spin"></span> ' +
				macmDataAdmin.i18n.resetting
			);

			// Animate progress bar.
			$('.macm-progress-fill').css('width', '30%');

			// Send AJAX request.
			$.ajax({
				url: macmDataAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'macm_reset_plugin_data',
					nonce: macmDataAdmin.nonce,
					confirm_token: 'RESET'
				},
				success: function(response) {
					$('.macm-progress-fill').css('width', '100%');

					setTimeout(function() {
						$progress.hide();

						if (response.success) {
							self.showResetSuccess(response.data);
						} else {
							self.showResetError(response.data.message || macmDataAdmin.i18n.error);
						}
					}, 500);
				},
				error: function() {
					$progress.hide();
					self.showResetError(macmDataAdmin.i18n.error);
				},
				complete: function() {
					$btn.prop('disabled', false).html(
						'<span class="dashicons dashicons-trash"></span> ' + i18n('resetPluginContent', 'Reset Plugin Content')
					);
				}
			});
		},

		/**
		 * Show reset success message.
		 *
		 * @param {Object} data Response data.
		 */
		showResetSuccess: function(data) {
			var $results = $('#macm-reset-results');

			$results
				.addClass('success')
				.find('.macm-results-message')
				.html(
					'<strong>' + macmDataAdmin.i18n.resetSuccess + '</strong><br>' +
					'<small>' + data.reset_count + ' ' + i18n('tablesCleared', 'tables have been cleared.') + '</small>'
				);

			$results.show();
		},

		/**
		 * Show reset error message.
		 *
		 * @param {string} message Error message.
		 */
		showResetError: function(message) {
			var $results = $('#macm-reset-results');

			$results
				.addClass('error')
				.find('.macm-results-message')
				.html('<strong>' + i18n('errorLabel', 'Error:') + '</strong> ' + this.escapeHtml(message));

			$results.show();
		},

		/**
		 * Reset import form to initial state.
		 *
		 * Called after successful import to clear file selection,
		 * preview, and reset UI elements.
		 */
		resetImportForm: function() {
			// Clear file input.
			var $fileInput = $('#macm-import-file');
			$fileInput.val('');

			// Clear selected files array.
			this.selectedFiles = [];

			// Reset drag-and-drop text to original.
			$('.macm-file-text').text(i18n('chooseFilesOrDrag', 'Choose files or drag and drop'));

			// Hide file preview and file list.
			$('#macm-file-preview').hide();
			$('#macm-selected-files').hide();

			// Reset import ID.
			this.importId = null;

			// Reset button text.
			$('#macm-import-btn').prop('disabled', false).html(
				'<span class="dashicons dashicons-upload"></span> ' + i18n('startImport', 'Start Import')
			);

			// Clear progress log (keep results visible).
			$('.macm-progress-log').empty();
		}
	};

	// Initialize on document ready.
	$(document).ready(function() {
		MACMDataAdmin.init();
	});

})(jQuery);
