<?php
/**
 * Tools view for admin interface.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Controllers\Admin\ToolsAdminController;
use Awesomemotive\Rewardswp\Factories\ViewsFactory;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Services\DataImportService;
use Awesomemotive\Rewardswp\Services\ColumnMappingService;
use Awesomemotive\Rewardswp\Views\Admin\Components\FileUploadComponentView;
use Awesomemotive\Rewardswp\Views\Admin\Components\SelectComponentView;
use Awesomemotive\Rewardswp\Views\Admin\Components\ColumnMappingComponentView;
use Awesomemotive\Rewardswp\Views\Admin\Modals\CsvPreviewModalView;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use function Awesomemotive\Rewardswp\Helpers\get_view_component;
use function Awesomemotive\Rewardswp\Helpers\kses;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;

class ToolsView extends AbstractView implements ViewInterface {

	/**
	 * Views factory instance.
	 *
	 * @since 1.0.0
	 *
	 * @var ViewsFactory
	 */
	private ViewsFactory $views_factory;

	/**
	 * Data import service instance.
	 *
	 * @since 1.0.0
	 *
	 * @var DataImportService
	 */
	private DataImportService $data_import_service;

	/**
	 * Column mapping service instance.
	 *
	 * @since 1.0.0
	 *
	 * @var ColumnMappingService
	 */
	private ColumnMappingService $column_mapping_service;

	/**
	 * Icon helper instance.
	 *
	 * @since 1.0.0
	 *
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param ViewsFactory         $views_factory
	 * @param DataImportService    $data_import_service
	 * @param ColumnMappingService $column_mapping_service
	 * @param IconHelper           $icon_helper
	 */
	public function __construct( ViewsFactory $views_factory, DataImportService $data_import_service, ColumnMappingService $column_mapping_service, IconHelper $icon_helper ) {
		$this->views_factory          = $views_factory;
		$this->data_import_service    = $data_import_service;
		$this->column_mapping_service = $column_mapping_service;
		$this->icon_helper            = $icon_helper;
	}

	/**
	 * Render the template.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args {
	 *
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {

		// Get active tab from URL query string or default to 'import'.
		$tab_raw      = filter_input( INPUT_GET, 'tab', FILTER_UNSAFE_RAW );
		$tab_param    = is_string( $tab_raw ) ? sanitize_text_field( wp_unslash( $tab_raw ) ) : '';
		$allowed_tabs = [ 'import' ];
		$active_tab   = in_array( $tab_param, $allowed_tabs, true ) ? $tab_param : 'import';

		$args = wp_parse_args(
			$args,
			[
				'page_title' => esc_html__( 'Tools', 'rewardswp' ),
			]
		);

		?>

		<div
			x-data="{
				activeTab: 'import',
				isDownloadingTemplate: false,
				selectedFile: null,
				csvData: null,
				isProcessingPreview: false,
				uploadError: '',

				// Column mapping state
				columnMappings: {},
				mappingErrors: [],
				isMappingValid: false,

				// Import processing state
				isImporting: false,
				importProgress: 0,
				importTotal: 0,
				importProcessed: 0,
				importBatchSize: 50,
				importResults: null,
				importError: '',


				downloadTemplate() {
					this.isDownloadingTemplate = true;

					const formData = new FormData();
					formData.append('action', 'rewardswp_download_csv_template');
					formData.append('_ajax_nonce', '<?php echo esc_js( wp_create_nonce( ToolsAdminController::AJAX_NONCE ) ); ?>');

					fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
						method: 'POST',
						body: formData,
					})
					.then(response => response.blob())
					.then(blob => {
						const url = window.URL.createObjectURL(blob);
						const a = document.createElement('a');
						a.style.display = 'none';
						a.href = url;
						a.download = 'rewardswp-points-template.csv';
						document.body.appendChild(a);
						a.click();
						window.URL.revokeObjectURL(url);
						document.body.removeChild(a);
					})
					.catch(error => {
						console.error('Template download error:', error);
					})
					.finally(() => {
						this.isDownloadingTemplate = false;
					});
				},

				loadCsvForMapping() {
					if (!this.selectedFile) {
						return;
					}

					this.isProcessingPreview = true;
					this.uploadError = '';

					const formData = new FormData();
					formData.append('action', 'rewardswp_load_csv_for_mapping');
					formData.append('_ajax_nonce', '<?php echo esc_js( wp_create_nonce( ToolsAdminController::AJAX_NONCE ) ); ?>');
					formData.append('csv_file', this.selectedFile);

					fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
						method: 'POST',
						body: formData,
					})
					.then(response => response.json())
					.then(result => {
						this.isProcessingPreview = false;
						if (result.success) {
							this.csvData = result.data;
							// Set up initial column mappings from auto-detection
							this.columnMappings = {};
							if (result.data.auto_mappings) {
								Object.keys(result.data.auto_mappings).forEach(column => {
									const mapping = result.data.auto_mappings[column];
									if (mapping.target_field && mapping.status === 'confident') {
										this.columnMappings[column] = mapping.target_field;
									} else {
										this.columnMappings[column] = '';
									}
								});
							}
							this.validateMappings();

							// Scroll to step 2 (mapping section)
							setTimeout(() => {
								const step2Element = document.getElementById('mapping-step-2');
								if (step2Element) {
									step2Element.scrollIntoView({ behavior: 'smooth', block: 'start' });
								}
							}, 100);
						} else {
							this.uploadError = result.data?.message || '<?php echo esc_js( __( 'An error occurred while processing the file', 'rewardswp' ) ); ?>';
						}
					})
					.catch(error => {
						this.isProcessingPreview = false;
						this.uploadError = '<?php echo esc_js( __( 'An error occurred while processing the file', 'rewardswp' ) ); ?>';
						console.error('CSV loading error:', error);
					});
				},

				validateMappings() {
					// Reset errors
					this.mappingErrors = [];
					this.isMappingValid = false;

					// Filter out empty mappings before sending
					const validMappings = {};
					Object.keys(this.columnMappings).forEach(column => {
						const value = this.columnMappings[column];
						if (value && value.trim() !== '' && value !== 'skip') {
							validMappings[column] = value;
						}
					});

					// Quick frontend validation check
					const hasPoints = Object.values(validMappings).includes('points');
					const hasUserId = Object.values(validMappings).includes('user_id');
					const hasEmail = Object.values(validMappings).includes('email');
					const hasMemberId = Object.values(validMappings).includes('member_id');

					// If validation passes on frontend, mark as valid
					if (hasPoints && (hasUserId || hasEmail || hasMemberId)) {
						this.isMappingValid = true;
						this.mappingErrors = [];
						return;
					}

					const formData = new FormData();
					formData.append('action', 'rewardswp_validate_column_mappings');
					formData.append('_ajax_nonce', '<?php echo esc_js( wp_create_nonce( ToolsAdminController::AJAX_NONCE ) ); ?>');
					formData.append('mappings', JSON.stringify(validMappings));

					fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
						method: 'POST',
						body: formData,
					})
					.then(response => response.json())
					.then(result => {
						if (result.success) {
							this.isMappingValid = true;
							this.mappingErrors = [];
						} else {
							this.isMappingValid = false;
							// Use detailed errors if available, otherwise fallback to main message
							this.mappingErrors = result.data?.errors || [result.data?.message || '<?php echo esc_js( __( 'Mapping validation failed', 'rewardswp' ) ); ?>'];
						}
					})
					.catch(error => {
						this.isMappingValid = false;
						this.mappingErrors = ['<?php echo esc_js( __( 'Error validating mappings', 'rewardswp' ) ); ?>'];
						console.error('Validation error:', error);
					});
				},

				previewMappedData() {
					if (!this.isMappingValid) {
						return;
					}

					this.$dispatch('show-csv-preview-modal', {
						csvData: this.csvData,
						columnMappings: this.columnMappings,
						selectedFile: this.selectedFile
					});
				},

				proceedToImport() {
					if (!this.isMappingValid) {
						return;
					}

					// Scroll to step 3 (import section)
					const step3Element = document.getElementById('import-step-3');
					if (step3Element) {
						step3Element.scrollIntoView({ behavior: 'smooth', block: 'start' });
					}
				},

				async startImport() {
					if (!this.selectedFile) {
						this.importError = '<?php echo esc_js( __( 'No file selected for import.', 'rewardswp' ) ); ?>';
						return;
					}

					if (!this.isMappingValid) {
						this.importError = '<?php echo esc_js( __( 'Please configure valid column mappings before importing.', 'rewardswp' ) ); ?>';
						return;
					}

					this.isImporting = true;
					this.importProgress = 0;
					this.importProcessed = 0;
					this.importError = '';
					this.importResults = {
						totalProcessed: 0,
						createdMembers: 0,
						createdPoints: 0,
						errors: []
					};

					// Get total rows from preview data, or estimate progressively during import
					this.importTotal = this.csvData?.total_rows || 0;

					// If we don't have total from preview, try to get it quickly
					if (this.importTotal === 0 && this.selectedFile) {
						try {
							const previewResult = await this.getQuickFileInfo();
							if (previewResult && previewResult.total_rows) {
								this.importTotal = previewResult.total_rows;
							}
						} catch (error) {
							console.log('Could not get file info, will use progressive estimation');
						}
					}

					await this.processBatches();
				},

				async processBatches() {
					let offset = 0;
					let hasMore = true;
					let batchCount = 0;

					while (hasMore && this.isImporting) {
						try {
							const result = await this.processBatch(offset);

							if (result.success) {
								const data = result.data;
								batchCount++;

								// Use batch_attempted to track actual progress through file
								this.importProcessed += (data.batch_attempted || data.batch_processed);
								this.importResults.totalProcessed += data.batch_processed;
								this.importResults.createdMembers += data.created_members;
								this.importResults.createdPoints += data.created_points;
								this.importResults.errors = this.importResults.errors.concat(data.errors);

								// Update progress
								if (this.importTotal > 0) {
									this.importProgress = Math.round((this.importProcessed / this.importTotal) * 100);
								} else {
									// Progressive estimation: if we don't know total, show progress based on batches processed
									// If we got a full batch, assume there might be more
									if (data.has_more) {
										// Show steady progress: 10% per batch, max 90%
										this.importProgress = Math.min(90, batchCount * 10);
									} else {
										this.importProgress = 100; // Last batch, complete
										this.importTotal = this.importProcessed; // Set final total
									}
								}

								hasMore = data.has_more;
								offset += (data.batch_attempted || this.importBatchSize);

								// Small delay to prevent overwhelming the server
								await new Promise(resolve => setTimeout(resolve, 100));
							} else {
								throw new Error(result.data.message || '<?php echo esc_js( __( 'Import failed', 'rewardswp' ) ); ?>');
							}
						} catch (error) {
							this.importError = error.message;
							this.isImporting = false;
							return;
						}
					}

					this.isImporting = false;
					this.importProgress = 100;
				},

				async getQuickFileInfo() {
					const formData = new FormData();
					formData.append('action', 'rewardswp_upload_csv_file');
					formData.append('_ajax_nonce', '<?php echo esc_js( wp_create_nonce( ToolsAdminController::AJAX_NONCE ) ); ?>');
					formData.append('csv_file', this.selectedFile);

					const response = await fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
						method: 'POST',
						body: formData,
					});

					const result = await response.json();
					return result.success ? result.data.data : null;
				},

				async processBatch(offset) {
					// Filter out empty mappings before sending (same as validation)
					const validMappings = {};
					Object.keys(this.columnMappings).forEach(column => {
						const value = this.columnMappings[column];
						if (value && value.trim() !== '' && value !== 'skip') {
							validMappings[column] = value;
						}
					});

					const formData = new FormData();
					formData.append('action', 'rewardswp_process_csv_batch');
					formData.append('_ajax_nonce', '<?php echo esc_js( wp_create_nonce( ToolsAdminController::AJAX_NONCE ) ); ?>');
					formData.append('csv_file', this.selectedFile);
					formData.append('batch_size', this.importBatchSize);
					formData.append('offset', offset);
					formData.append('column_mappings', JSON.stringify(validMappings));

					const response = await fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
						method: 'POST',
						body: formData,
					});

					return await response.json();
				},

				resetImport(fromUpload = false) {
					// Reset import state
					this.isImporting = false;
					this.importProgress = 0;
					this.importProcessed = 0;
					this.importTotal = 0;
					this.importResults = null;
					this.importError = '';

					// Reset column mapping state
					this.columnMappings = {};
					this.mappingErrors = [];
					this.isMappingValid = false;

					// Reset file selection (back to Step 1)
					this.selectedFile = null;
					this.csvData = null;
					this.uploadError = '';

					// Only trigger file removal if NOT coming from the upload component
					if (!fromUpload) {
						this.$dispatch('remove-file');
					}
				},

				async downloadErrorReport() {
					if (!this.importResults?.errors?.length) {
						return;
					}

					const formData = new FormData();
					formData.append('action', 'rewardswp_download_error_report');
					formData.append('_ajax_nonce', '<?php echo esc_js( wp_create_nonce( ToolsAdminController::AJAX_NONCE ) ); ?>');
					formData.append('errors', JSON.stringify(this.importResults.errors));

					// Create hidden form and submit for download
					const form = document.createElement('form');
					form.method = 'POST';
					form.action = '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>';
					form.style.display = 'none';

					for (const [key, value] of formData.entries()) {
						const input = document.createElement('input');
						input.type = 'hidden';
						input.name = key;
						input.value = value;
						form.appendChild(input);
					}

					document.body.appendChild(form);
					form.submit();
					document.body.removeChild(form);
				}
			}"
			x-init="activeTab = '<?php echo esc_js( $active_tab ); ?>'"
			x-on:file-uploaded="selectedFile = $event.detail.file; csvData = null; uploadError = ''; columnMappings = {}; mappingErrors = []; isMappingValid = false;"
			x-on:reset-import="resetImport(true)"
		>
			<div class="rewardswp-container max-[782px]:ml-[-10px] ml-[-20px]">
				<?php
					$common_classes   = 'px-4 py-5 text-sm whitespace-nowrap focus:outline-none focus:border-b-2 focus:border-blue-500';
					$active_classes   = 'text-blue-600 border-b-2 border-blue-500 ';
					$inactive_classes = 'text-gray-800 hover:text-gray-600';
				?>

				<div id="rewardswp-admin-settings-sentinel" class="absolute top-0 left-0 right-0"></div>

				<div class="px-8 pt-5 mx-auto max-w-7xl sr-only">
					<div class="mb-6 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
						<h1 class="text-2xl font-semibold text-slate-900"><?php echo esc_html( $args['page_title'] ); ?></h1>
					</div>
				</div>

				<div id="rewardswp-admin-settings-header" class="transition-shadow duration-250 shadow-gray-800/10 sticky max-[601px]:top-0 max-[783px]:top-[46px] top-[32px] bg-[#f0f0f1] z-10 border-b border-gray-300">
					<div class="px-8 mx-auto max-w-7xl flex justify-between items-center">
						<nav class="flex font-semibold overflow-x-auto scrollbar" aria-label="<?php esc_attr_e( 'Tabs', 'rewardswp' ); ?>">
							<?php
							$import_tab_url = add_query_arg( [ 'page' => 'rewardswp-tools', 'tab' => 'import' ], admin_url( 'admin.php' ) );
							?>
							<a
								x-on:click.prevent="activeTab = 'import'; history.pushState(null, '', '<?php echo esc_js( $import_tab_url ); ?>')"
								x-bind:class="{ '<?php echo esc_attr( $active_classes ); ?>': activeTab === 'import', '<?php echo esc_attr( $inactive_classes ); ?>': activeTab !== 'import' }"
								href="<?php echo esc_url( $import_tab_url ); ?>"
								class="<?php echo esc_attr( $common_classes ); ?>"
							>
								<?php esc_html_e( 'Import', 'rewardswp' ); ?>
							</a>
						</nav>
					</div>
				</div>

				<div class="px-8 pt-5 mx-auto max-w-7xl">

					<!-- Import Tab Content -->
					<div
						x-show="activeTab === 'import'"
						id="import"
						x-cloak
					>
						<?php ob_start(); ?>
						<div class="mb-6">
							<p class="mt-1 text-sm text-gray-600">
								<?php esc_html_e( 'Import points data from other platforms using any CSV file. Column headers will be mapped automatically.', 'rewardswp' ); ?>
								<a
									href="#"
									x-on:click.prevent="downloadTemplate()"
									x-bind:class="{ 'opacity-75 pointer-events-none': isDownloadingTemplate }"
									class="text-blue-600 hover:text-blue-800 underline"><span x-show="!isDownloadingTemplate"><?php esc_html_e( 'Download example CSV', 'rewardswp' ); ?></span><span x-show="isDownloadingTemplate"><?php esc_html_e( 'Downloading...', 'rewardswp' ); ?></span></a>
								<?php esc_html_e( ' if you need a reference.', 'rewardswp' ); ?>
							</p>
						</div>

						<!-- Import Steps -->
						<div class="space-y-6">
								<!-- Step 1: Upload File -->
								<div class="border border-gray-200 rounded-lg p-6">
									<div class="flex items-start">
										<div class="flex-shrink-0">
											<div class="flex items-center justify-center w-8 h-8 rounded-full border-2 border-gray-300">
												<span class="text-sm font-medium text-gray-500">1</span>
											</div>
										</div>
										<div class="ml-4 flex-1">
											<div class="flex items-center">
												<h3 class="text-sm font-medium text-gray-900"><?php esc_html_e( 'Upload CSV File', 'rewardswp' ); ?></h3>
													<div x-show="selectedFile" class="ml-2">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'check', 'w-4 h-4 text-green-500' ), svg_kses() ); ?>
												</div>
											</div>
											<p class="mt-1 text-sm text-gray-500"><?php esc_html_e( 'Select and upload your CSV file containing the points data to import.', 'rewardswp' ); ?></p>

											<!-- File Upload Component -->
											<div class="mt-4">
												<?php
												$max_upload_mb = $this->data_import_service->get_max_upload_size_mb();

												$this->views_factory->get_view( FileUploadComponentView::class )->render(
													[
														'label'      => '',
														'help_text'  => sprintf(
															/* translators: %d: Maximum file size in megabytes. */
															__( 'Upload a CSV file with your points data. Maximum size: %dMB.', 'rewardswp' ),
															$max_upload_mb
														),
														'max_size_mb' => $max_upload_mb,
													]
												);
												?>
											</div>

											<!-- Continue to Mapping Button -->
											<div class="mt-4" x-show="selectedFile">
												<button
													type="button"
													x-on:click="loadCsvForMapping()"
													x-bind:disabled="isProcessingPreview"
													x-bind:class="{ 'opacity-75 cursor-not-allowed': isProcessingPreview }"
													class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'arrow-right', 'w-4 h-4 mr-2' ), svg_kses() ); ?>
													<span x-show="!isProcessingPreview"><?php esc_html_e( 'Continue to Mapping', 'rewardswp' ); ?></span>
													<span x-show="isProcessingPreview"><?php esc_html_e( 'Loading...', 'rewardswp' ); ?></span>
												</button>
											</div>

											<!-- Upload Error -->
											<div x-show="uploadError" class="mt-4 p-3 bg-red-50 border border-red-200 rounded-md">
												<div class="flex">
													<div class="flex-shrink-0">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'alert-triangle', 'w-5 h-5 text-red-400' ), svg_kses() ); ?>
													</div>
													<div class="ml-3">
														<p class="text-sm text-red-800" x-text="uploadError"></p>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>

								<!-- Step 2: Map Columns -->
								<div id="mapping-step-2" class="border border-gray-200 rounded-lg p-6" x-bind:class="{ 'opacity-50': !csvData }">
									<div class="flex items-start">
										<div class="flex-shrink-0">
											<div class="flex items-center justify-center w-8 h-8 rounded-full border-2"
												x-bind:class="{
													'border-gray-300': !csvData,
													'border-blue-500 bg-blue-50': csvData && !isMappingValid,
													'border-green-500 bg-green-50': isMappingValid
												}">
												<span x-show="!isMappingValid" class="text-sm font-medium"
													x-bind:class="{
														'text-gray-500': !csvData,
														'text-blue-600': csvData
													}">2</span>
												<div x-show="isMappingValid">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'check', 'w-4 h-4 text-green-600' ), svg_kses() ); ?>
												</div>
											</div>
										</div>
										<div class="ml-4 flex-1">
											<div class="flex items-center">
												<h3 class="text-sm font-medium" x-bind:class="{ 'text-gray-900': csvData, 'text-gray-500': !csvData }">
													<?php esc_html_e( 'Map Columns', 'rewardswp' ); ?>
												</h3>
								<div x-show="isMappingValid" class="ml-2">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'check', 'w-4 h-4 text-green-500' ), svg_kses() ); ?>
												</div>
											</div>
											<p class="mt-1 text-sm text-gray-500">
												<span x-show="!csvData"><?php esc_html_e( 'Map your CSV columns to the appropriate fields.', 'rewardswp' ); ?></span>
												<span x-show="csvData && !isMappingValid"><?php esc_html_e( 'Configure how your CSV columns map to RewardsWP fields.', 'rewardswp' ); ?></span>
												<span x-show="isMappingValid"><?php esc_html_e( 'Column mapping configured successfully.', 'rewardswp' ); ?></span>
											</p>

											<!-- Column Mapping Interface -->
											<div x-show="csvData" class="mt-4">
												<div class="bg-white border border-gray-200 rounded-lg p-4">
													<h4 class="text-sm font-medium text-gray-900 mb-3">
														<?php esc_html_e( 'Map CSV Columns to Fields', 'rewardswp' ); ?>
													</h4>
													<p class="text-xs text-gray-600 mb-4">
														<?php esc_html_e( 'Select which field each CSV column should map to. You must map at least the Points field and one member identification field (Member ID, User ID, or Email).', 'rewardswp' ); ?>
													</p>

													<!-- Mapping Table -->
													<div class="overflow-hidden border border-gray-200 rounded-lg">
														<table class="min-w-full divide-y divide-gray-200">
															<thead class="bg-gray-50">
																<tr>
																	<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
																		<?php esc_html_e( 'CSV Column', 'rewardswp' ); ?>
																	</th>
																	<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
																		<?php esc_html_e( 'Sample Data', 'rewardswp' ); ?>
																	</th>
																	<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
																		<?php esc_html_e( 'Map to Field', 'rewardswp' ); ?>
																	</th>
																</tr>
															</thead>
															<tbody class="bg-white divide-y divide-gray-200">
																<template x-for="(header, index) in (csvData?.headers || [])" x-key="header">
																	<tr class="hover:bg-gray-50">
																		<!-- CSV Column -->
																		<td class="px-3 py-2 text-sm font-medium text-gray-900" x-text="header"></td>

																		<!-- Sample Data -->
																		<td class="px-3 py-2 text-sm text-gray-500">
																			<span class="font-mono text-xs px-2 py-1 rounded"
																				x-bind:class="(csvData?.preview?.[0]?.[header] || '').trim() === '' ? 'bg-gray-50 text-gray-400 italic' : 'bg-gray-100'"
																				x-text="(() => {
																					const value = csvData?.preview?.[0]?.[header] || '';
																					if (value.trim() === '') return 'empty';
																					return value.length > 20 ? value.substring(0, 20) + '...' : value;
																				})()">
																			</span>
																		</td>

																		<!-- Mapping Dropdown -->
																		<td class="px-3 py-2">
																			<?php
																			$mapping_options = $this->column_mapping_service->get_mapping_options();
																			$this->views_factory->get_view( SelectComponentView::class )->render(
																				[
																					'x-model' => 'columnMappings[header]',
																					'x-on:change' => 'validateMappings',
																					'options' => $mapping_options,
																				]
																			);
																			?>
																		</td>
																	</tr>
																</template>
															</tbody>
														</table>
													</div>
												</div>
											</div>

											<!-- Mapping Validation Messages -->
											<div x-show="mappingErrors.length > 0" class="mt-4 p-4 bg-red-50 border border-red-200 rounded-md">
												<div class="flex">
													<div class="flex-shrink-0">
														<?php echo wp_kses( $this->icon_helper->get_icon( 'alert-triangle', 'w-5 h-5 text-red-400' ), svg_kses() ); ?>
													</div>
													<div class="ml-3 flex-1">
														<h4 class="text-sm font-medium text-red-800 mb-2">
															<?php esc_html_e( 'Please fix the following mapping issues:', 'rewardswp' ); ?>
														</h4>
														<ul class="text-sm text-red-700 space-y-1">
															<template x-for="(error, index) in mappingErrors" x-key="error + index">
																<li class="flex items-start">
																	<span class="inline-block w-1 h-1 bg-red-500 rounded-full mt-2 mr-2 flex-shrink-0"></span>
																	<span x-text="error" class="leading-relaxed"></span>
																</li>
															</template>
														</ul>
														<div class="mt-3 text-xs text-red-600 bg-red-100 p-2 rounded">
															<strong><?php esc_html_e( 'Required:', 'rewardswp' ); ?></strong>
															<?php esc_html_e( 'Points field + at least one member identification field (Member ID, User ID, or Email)', 'rewardswp' ); ?>
														</div>
													</div>
												</div>
											</div>

											<!-- Mapping Success Message -->
											<div x-show="mappingErrors.length === 0 && isMappingValid && Object.keys(columnMappings).length > 0" class="mt-4 p-3 bg-green-50 border border-green-200 rounded-md">
												<div class="flex">
													<div class="flex-shrink-0">
														<?php echo wp_kses( $this->icon_helper->get_icon( 'check-circle', 'w-5 h-5 text-green-400' ), svg_kses() ); ?>
													</div>
													<div class="ml-3">
														<p class="text-sm text-green-800">
															<?php esc_html_e( 'Column mapping is complete and valid! You can now preview the data or proceed to import.', 'rewardswp' ); ?>
														</p>
													</div>
												</div>
											</div>

											<!-- Mapping Actions -->
											<div class="mt-4 flex gap-3" x-show="csvData">
												<!-- Preview Mapped Data Button (shows when mapping is valid) -->
												<button
													type="button"
													x-show="isMappingValid"
													x-on:click="previewMappedData()"
													class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'eye', 'w-4 h-4 mr-2' ), svg_kses() ); ?>
													<?php esc_html_e( 'Preview Mapped Data', 'rewardswp' ); ?>
												</button>

												<!-- Continue to Import Button (shows when mapping is valid) -->
												<button
													type="button"
													x-show="isMappingValid"
													x-on:click="proceedToImport()"
													class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'arrow-right', 'w-4 h-4 mr-2' ), svg_kses() ); ?>
													<?php esc_html_e( 'Continue to Import', 'rewardswp' ); ?>
												</button>
											</div>
										</div>
									</div>
								</div>

								<!-- Step 3: Process Import -->
								<div id="import-step-3" class="border border-gray-200 rounded-lg p-6" data-step="3" x-bind:class="{ 'opacity-50': !isMappingValid }">
									<div class="flex items-start">
										<div class="flex-shrink-0">
											<div class="flex items-center justify-center w-8 h-8 rounded-full border-2"
												x-bind:class="{
													'border-gray-300': !isMappingValid,
													'border-blue-500 bg-blue-50': isMappingValid && !importResults,
													'border-green-500 bg-green-50': importResults
												}">
												<span x-show="!importResults" class="text-sm font-medium"
													x-bind:class="{
														'text-gray-500': !isMappingValid,
														'text-blue-600': isMappingValid
													}">3</span>
												<div x-show="importResults">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'check', 'w-4 h-4 text-green-600' ), svg_kses() ); ?>
												</div>
											</div>
										</div>
										<div class="ml-4 flex-1">
											<div class="flex items-center">
												<h3 class="text-sm font-medium" x-bind:class="{ 'text-gray-900': isMappingValid, 'text-gray-500': !isMappingValid }">
													<?php esc_html_e( 'Process Import', 'rewardswp' ); ?>
												</h3>
												<div x-show="importResults" class="ml-2">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'check', 'w-4 h-4 text-green-500' ), svg_kses() ); ?>
												</div>
											</div>
											<p class="mt-1 text-sm text-gray-500">
												<span x-show="!isMappingValid"><?php esc_html_e( 'Complete column mapping to proceed with import.', 'rewardswp' ); ?></span>
												<span x-show="isMappingValid && !importResults"><?php esc_html_e( 'Ready to import! Configure your settings and start the import process.', 'rewardswp' ); ?></span>
												<span x-show="importResults"><?php esc_html_e( 'Import completed successfully.', 'rewardswp' ); ?></span>
											</p>

											<!-- Import configuration (shows when mapping is valid) -->
											<div x-show="isMappingValid && !isImporting && !importResults" class="mt-4 p-4 bg-gray-50 rounded-md">
												<h4 class="text-sm font-medium text-gray-900 mb-3"><?php esc_html_e( 'Import Configuration', 'rewardswp' ); ?></h4>

												<!-- Batch Size Configuration -->
												<div class="mb-4">
													<label class="block text-sm font-medium text-gray-700 mb-2">
														<?php esc_html_e( 'Batch Size', 'rewardswp' ); ?>
													</label>
													<?php
													$this->views_factory->get_view( SelectComponentView::class )->render(
														[
															'x-model' => 'importBatchSize',
															'options' => [
																'10'  => '10',
																'25'  => '25',
																'50'  => '50',
																'100' => '100',
																'200' => '200',
																'500' => '500',
															],
															'selected' => '50',
														]
													);
													?>
													<p class="mt-1 text-xs text-gray-500"><?php esc_html_e( 'Number of rows to process per batch. Lower values are safer for large imports.', 'rewardswp' ); ?></p>
												</div>

												<button
													type="button"
													x-on:click="startImport()"
													class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'trending-up', 'w-4 h-4 mr-2' ), svg_kses() ); ?>
													<?php esc_html_e( 'Start Import', 'rewardswp' ); ?>
												</button>
											</div>

											<!-- Import Progress (shows during import) -->
											<div x-show="isImporting" class="mt-4">
												<div class="p-4 bg-gray-50 border border-gray-200 rounded-md">
													<div class="flex items-center mb-3">
														<div class="animate-spin mr-2">
													<?php echo wp_kses( $this->icon_helper->get_icon( 'refresh', 'w-4 h-4 text-gray-600' ), svg_kses() ); ?>
														</div>
														<h4 class="text-sm font-medium text-gray-900"><?php esc_html_e( 'Import in Progress', 'rewardswp' ); ?></h4>
													</div>

													<!-- Progress Bar -->
													<div class="mb-3">
														<div class="flex justify-between text-xs text-gray-500 mb-2">
															<span><?php esc_html_e( 'Processing rows...', 'rewardswp' ); ?></span>
															<span x-show="importTotal > 0">
																<span x-text="importProcessed"></span> / <span x-text="importTotal"></span> (<span x-text="importProgress"></span>%)
															</span>
															<span x-show="importTotal === 0">
																<span x-text="importProcessed"></span> <?php esc_html_e( 'rows processed', 'rewardswp' ); ?> (<span x-text="importProgress"></span>%)
															</span>
														</div>
														<div class="w-full bg-gray-200 rounded-full h-2">
															<div
																class="bg-gray-600 h-2 rounded-full transition-all duration-300"
																x-bind:style="'width: ' + importProgress + '%'"
															></div>
														</div>
													</div>

													<p class="text-xs text-gray-500">
														<?php esc_html_e( 'Please do not close this page while the import is running.', 'rewardswp' ); ?>
													</p>
												</div>
											</div>

											<!-- Import Results (shows after completion) -->
											<div x-show="importResults && !isImporting" class="mt-4">
												<div class="p-4 bg-gray-50 border border-gray-200 rounded-md">
													<div class="flex items-center mb-4">
														<?php echo wp_kses( $this->icon_helper->get_icon( 'check', 'w-4 h-4 text-green-600 mr-2' ), svg_kses() ); ?>
														<h4 class="text-sm font-medium text-gray-900"><?php esc_html_e( 'Import Complete', 'rewardswp' ); ?></h4>
													</div>

													<div class="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4">
														<div class="flex items-center p-3 bg-white rounded-md border border-gray-200">
															<div class="flex-shrink-0 mr-3">
																<?php echo wp_kses( $this->icon_helper->get_icon( 'check', 'w-8 h-8 text-green-500' ), svg_kses() ); ?>
															</div>
															<div>
																<div class="text-lg font-semibold text-gray-900" x-text="importResults?.totalProcessed || 0"></div>
																<div class="text-xs text-gray-500"><?php esc_html_e( 'Rows Processed', 'rewardswp' ); ?></div>
															</div>
														</div>
														<div class="flex items-center p-3 bg-white rounded-md border border-gray-200">
															<div class="flex-shrink-0 mr-3">
																<?php // User signup icon for members created ?>
																<?php echo wp_kses( $this->icon_helper->get_icon( 'earn-signup', 'w-8 h-8 text-blue-500' ), svg_kses() ); ?>
															</div>
															<div>
																<div class="text-lg font-semibold text-gray-900" x-text="importResults?.createdMembers || 0"></div>
																<div class="text-xs text-gray-500"><?php esc_html_e( 'Members Created', 'rewardswp' ); ?></div>
															</div>
														</div>
														<div class="flex items-center p-3 bg-white rounded-md border border-gray-200">
															<div class="flex-shrink-0 mr-3">
																<?php echo wp_kses( $this->icon_helper->get_icon( 'reward-points', 'w-8 h-8 text-purple-500' ), svg_kses() ); ?>
															</div>
															<div>
																<div class="text-lg font-semibold text-gray-900" x-text="importResults?.createdPoints || 0"></div>
																<div class="text-xs text-gray-500"><?php esc_html_e( 'Points Created', 'rewardswp' ); ?></div>
															</div>
														</div>
													</div>

													<!-- Errors (if any) -->
													<div x-show="importResults?.errors?.length > 0" class="mb-4 p-3 bg-gray-50 border border-gray-300 rounded-md">
														<div class="flex justify-between items-start mb-2">
															<div class="flex items-center">
																<?php echo wp_kses( $this->icon_helper->get_icon( 'alert-triangle', 'w-4 h-4 text-amber-500 mr-1' ), svg_kses() ); ?>
																<h5 class="text-sm font-medium text-gray-900"><?php esc_html_e( 'Warnings/Errors', 'rewardswp' ); ?></h5>
															</div>
															<button
																type="button"
																x-on:click="downloadErrorReport()"
																class="text-xs text-blue-600 hover:text-blue-800 underline font-medium">
																<?php esc_html_e( 'Download Error Report', 'rewardswp' ); ?>
															</button>
														</div>
														<ul class="text-xs text-gray-600 space-y-1 max-h-32 overflow-y-auto">
															<template x-for="error in (importResults?.errors || []).slice(0, 10)" x-key="error">
																<li x-text="error" class="font-mono bg-gray-100 px-2 py-1 rounded text-xs"></li>
															</template>
															<li x-show="(importResults?.errors?.length || 0) > 10" class="font-medium text-gray-500 pt-1">
																<?php esc_html_e( 'And', 'rewardswp' ); ?> <span x-text="(importResults?.errors?.length || 0) - 10"></span> <?php esc_html_e( 'more errors...', 'rewardswp' ); ?>
															</li>
														</ul>
													</div>

													<button
														type="button"
														x-on:click="resetImport()"
														class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
														<?php echo wp_kses( $this->icon_helper->get_icon( 'refresh', 'w-4 h-4 mr-2' ), svg_kses() ); ?>
														<?php esc_html_e( 'Restart Import', 'rewardswp' ); ?>
													</button>
												</div>
											</div>

											<!-- Import Error (if any) -->
											<div x-show="importError" class="mt-4 p-3 bg-red-50 border border-red-200 rounded-md">
												<div class="flex">
													<div class="flex-shrink-0">
														<?php echo wp_kses( $this->icon_helper->get_icon( 'alert-triangle', 'w-5 h-5 text-red-400' ), svg_kses() ); ?>
													</div>
													<div class="ml-3">
														<p class="text-sm text-red-800" x-text="importError"></p>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
						<?php
							$section_content = ob_get_clean();

							// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Contents are escaped by the function.
							echo get_view_component(
								'section',
								[
									'title'   => esc_html__( 'Points Import', 'rewardswp' ),
									'content' => $section_content,
									'id'      => 'points_import',
								]
							);
						?>

					</div>
				</div>
			</div>

			<div class="rewardswp-container">
				<!-- CSV Preview Modal -->
				<?php
				$this->views_factory->get_view( CsvPreviewModalView::class )->render();
				?>
			</div>

		<?php
	}
}
