/**
 * Settings Page Scripts
 * Handles debug log viewer and cleanup button functionality
 *
 * @package OptiBehavior
 */

(function() {
	/**
	 * Display a styled dismissible admin notice instead of native alert().
	 *
	 * @param {string} message  Text to show.
	 * @param {string} type     'success' | 'error' | 'warning' | 'info'
	 */
	function showOptiNotice(message, type) {
		var borderColors = { success: '#00a32a', error: '#d63638', warning: '#dba617', info: '#72aee6' };
		var border = borderColors[type] || borderColors.info;
		var notice = document.createElement('div');
		notice.style.cssText = 'position:fixed;top:40px;right:20px;z-index:999999;padding:12px 20px;'
			+ 'border-left:4px solid ' + border + ';background:#fff;'
			+ 'box-shadow:0 2px 8px rgba(0,0,0,.18);max-width:400px;font-size:13px;line-height:1.5;'
			+ 'border-radius:2px;word-wrap:break-word;';
		notice.textContent = message;
		document.body.appendChild(notice);
		setTimeout(function() {
			notice.style.transition = 'opacity .3s';
			notice.style.opacity = '0';
			setTimeout(function() { if (notice.parentNode) { notice.parentNode.removeChild(notice); } }, 350);
		}, 5000);
	}

	// Debug Log Viewer Function
	function viewDebugLog() {
		var modal = document.getElementById("opti-behavior-log-viewer");
		var content = document.getElementById("opti-behavior-log-content");

		if (!modal || !content) {
			// console.error("Debug log viewer elements not found");
			return;
		}

		// Show modal
		modal.style.display = "block";
		content.textContent = "Loading debug log...";

		// Setup close button handler (if not already set)
		var closeBtn = modal.querySelector('.opti-behavior-log-close-btn');
		if (closeBtn && !closeBtn.hasAttribute('data-handler-attached')) {
			closeBtn.addEventListener('click', function() {
				modal.style.display = 'none';
			});
			closeBtn.setAttribute('data-handler-attached', 'true');
		}

		// Fetch log content via AJAX
		jQuery.ajax({
			url: ajaxurl,
			type: "POST",
			data: {
				action: "opti_behavior_get_debug_log",
				nonce: opti_behaviorSettings.viewLogNonce
			},
			success: function(response) {
				if (response.success) {
					content.textContent = response.data.log_content || "Log file is empty";
				} else {
					content.textContent = "Error loading log: " + (response.data || "Unknown error");
				}
			},
			error: function(xhr, status, error) {
				content.textContent = "Error loading log: " + error;
			}
		});
	}

	// Attach event listener to view log button
	document.addEventListener('DOMContentLoaded', function() {
		var viewLogBtn = document.getElementById('opti-behavior-view-log-btn');
		if (viewLogBtn) {
			viewLogBtn.addEventListener('click', viewDebugLog);
		}
	});

	// Handle delete form confirmations
	document.addEventListener('submit', function(e){
		// e.target is the form element when submit event fires
		var form = e.target;
		if(form && form.classList && form.classList.contains('optibehavior-delete-form')){
			var msg = form.getAttribute('data-confirm');
			if(msg && !confirm(msg)){
				e.preventDefault();
			} else {
				// Show success message after form submission
				var successMsg = form.getAttribute('data-success');
				if(successMsg) {
					// Store success message in sessionStorage to show after page reload
					sessionStorage.setItem('opti_behavior_success_msg', successMsg);
				}
			}
		}
	});

	// Display success message if stored in sessionStorage
	document.addEventListener('DOMContentLoaded', function() {
		var successMsg = sessionStorage.getItem('opti_behavior_success_msg');
		if(successMsg) {
			// Remove from sessionStorage
			sessionStorage.removeItem('opti_behavior_success_msg');
			// Show styled notice instead of native alert
			showOptiNotice(successMsg, 'success');
		}
	});

	// Cleanup Buttons Event Handlers
	jQuery(document).ready(function($) {
		// Delete Old Recordings by Date
		$("#cleanup_by_date_btn").on("click", function() {
			var date = $("#cleanup_before_date").val();
			if (!date) {
				showOptiNotice('Please select a date', 'warning');
				return;
			}
			if (!confirm("Are you sure you want to delete all recordings before " + date + "?")) {
				return;
			}
			$(this).prop("disabled", true).text("Deleting...");
			$.ajax({
				url: ajaxurl,
				type: "POST",
				data: {
					action: "opti_behavior_cleanup_by_date",
					date: date,
					nonce: opti_behaviorSettings.cleanupNonce
				},
				success: function(response) {
					if (response.success) {
						showOptiNotice(response.data.message || 'Recordings deleted successfully', 'success');
						location.reload();
					} else {
						showOptiNotice('Error: ' + (response.data || 'Unknown error'), 'error');
						$("#cleanup_by_date_btn").prop("disabled", false).html("<span class=\"btn-icon\"><i data-lucide=\"trash-2\"></i></span> Delete Old Recordings");
						if (typeof lucide !== 'undefined') lucide.createIcons();
					}
				},
				error: function() {
					showOptiNotice('Error deleting recordings', 'error');
					$("#cleanup_by_date_btn").prop("disabled", false).html("<span class=\"btn-icon\"><i data-lucide=\"trash-2\"></i></span> Delete Old Recordings");
					if (typeof lucide !== 'undefined') lucide.createIcons();
				}
			});
		});

		// Delete Short Recordings by Duration
		$("#cleanup_by_duration_btn").on("click", function() {
			var duration = $("#min_duration_seconds").val();
			if (!duration || duration < 1) {
				showOptiNotice('Please enter a valid duration', 'warning');
				return;
			}
			if (!confirm("Are you sure you want to delete all recordings shorter than " + duration + " seconds?")) {
				return;
			}
			$(this).prop("disabled", true).text("Deleting...");
			$.ajax({
				url: ajaxurl,
				type: "POST",
				data: {
					action: "opti_behavior_cleanup_by_duration",
					duration: duration,
					nonce: opti_behaviorSettings.cleanupNonce
				},
				success: function(response) {
					if (response.success) {
						showOptiNotice(response.data.message || 'Short recordings deleted successfully', 'success');
						location.reload();
					} else {
						showOptiNotice('Error: ' + (response.data || 'Unknown error'), 'error');
						$("#cleanup_by_duration_btn").prop("disabled", false).html("<span class=\"btn-icon\"><i data-lucide=\"trash-2\"></i></span> Delete Short Recordings");
						if (typeof lucide !== 'undefined') lucide.createIcons();
					}
				},
				error: function() {
					showOptiNotice('Error deleting recordings', 'error');
					$("#cleanup_by_duration_btn").prop("disabled", false).html("<span class=\"btn-icon\"><i data-lucide=\"trash-2\"></i></span> Delete Short Recordings");
					if (typeof lucide !== 'undefined') lucide.createIcons();
				}
			});
		});

		// Delete Orphaned Files
		$("#cleanup_orphaned_files_btn").on("click", function() {
			if (!confirm("Are you sure you want to delete all orphaned recording files? This cannot be undone.")) {
				return;
			}
			$(this).prop("disabled", true).text("Deleting...");
			$.ajax({
				url: ajaxurl,
				type: "POST",
				data: {
					action: "opti_behavior_cleanup_orphaned",
					nonce: opti_behaviorSettings.cleanupNonce
				},
				success: function(response) {
					if (response.success) {
						showOptiNotice(response.data.message || 'Orphaned files deleted successfully', 'success');
						location.reload();
					} else {
						showOptiNotice('Error: ' + (response.data || 'Unknown error'), 'error');
						$("#cleanup_orphaned_files_btn").prop("disabled", false).html("<span class=\"btn-icon\"><i data-lucide=\"trash-2\"></i></span> Delete Orphaned Files");
						if (typeof lucide !== 'undefined') lucide.createIcons();
					}
				},
				error: function() {
					showOptiNotice('Error deleting orphaned files', 'error');
					$("#cleanup_orphaned_files_btn").prop("disabled", false).html("<span class=\"btn-icon\"><i data-lucide=\"trash-2\"></i></span> Delete Orphaned Files");
					if (typeof lucide !== 'undefined') lucide.createIcons();
				}
			});
		});

		// =========================================================
		// Spam Recalculation with Progress Bar
		// =========================================================

		// Store original spam settings values to detect changes
		var originalSpamSettings = {
			duration: $('input[name="opti_behavior_traffic[spam_duration_threshold]"]').val(),
			minScrolls: $('input[name="opti_behavior_traffic[spam_min_scrolls_threshold]"]').val(),
			minClicks: $('input[name="opti_behavior_traffic[spam_min_clicks_threshold]"]').val(),
			enabled: $('input[name="opti_behavior_traffic[spam_detection_enabled]"]').is(':checked')
		};

		// Handle traffic settings form submission
		$('button[name="opti_behavior_traffic_settings_submit"]').closest('form').on('submit', function(e) {
			// Get current values
			var currentSettings = {
				duration: $('input[name="opti_behavior_traffic[spam_duration_threshold]"]').val(),
				minScrolls: $('input[name="opti_behavior_traffic[spam_min_scrolls_threshold]"]').val(),
				minClicks: $('input[name="opti_behavior_traffic[spam_min_clicks_threshold]"]').val(),
				enabled: $('input[name="opti_behavior_traffic[spam_detection_enabled]"]').is(':checked')
			};

			// Check if spam settings changed
			var spamSettingsChanged = (
				currentSettings.duration !== originalSpamSettings.duration ||
				currentSettings.minScrolls !== originalSpamSettings.minScrolls ||
				currentSettings.minClicks !== originalSpamSettings.minClicks ||
				currentSettings.enabled !== originalSpamSettings.enabled
			);

			// If spam detection is enabled and settings changed, show progress bar
			if (currentSettings.enabled && spamSettingsChanged) {
				e.preventDefault();

				// Save settings first via regular form submission, then recalculate
				var formData = $(this).serialize();

				// Show progress bar
				$('#spam-recalc-container').show();
				$('#spam-recalc-success').hide();

				// Disable submit button
				$('button[name="opti_behavior_traffic_settings_submit"]').prop('disabled', true).text('Saving...');

				// First save the settings
				$.ajax({
					url: window.location.href,
					type: 'POST',
					data: formData,
					success: function() {
						// Settings saved, now start recalculation
						startSpamRecalculation();
					},
					error: function() {
						showOptiNotice(opti_behaviorSettings.strings.error || 'Error saving settings. Please try again.', 'error');
						$('button[name="opti_behavior_traffic_settings_submit"]').prop('disabled', false).text('Save Traffic Settings');
						$('#spam-recalc-container').hide();
					}
				});
			}
		});

		/**
		 * Start spam recalculation process
		 */
		function startSpamRecalculation() {
			$('#spam-recalc-status').text('Initializing...');
			$('#spam-recalc-progress-bar').css('width', '0%');
			$('#spam-recalc-percent').text('0%');

			// Start the recalculation
			$.ajax({
				url: opti_behaviorSettings.ajaxUrl || ajaxurl,
				type: 'POST',
				data: {
					action: 'optibehavior_recalculate_spam',
					nonce: opti_behaviorSettings.settingsNonce,
					action_type: 'start',
					offset: 0,
					batch_size: 500
				},
				success: function(response) {
					if (response.success) {
						if (response.data.status === 'started') {
							// Begin batch processing
							processSpamBatch(0, response.data.total);
						} else if (response.data.status === 'completed') {
							// No sessions to process
							spamRecalcComplete(response.data.message);
						}
					} else {
						spamRecalcError(response.data ? response.data.message : 'Unknown error');
					}
				},
				error: function(xhr, status, error) {
					spamRecalcError('AJAX error: ' + error);
				}
			});
		}

		/**
		 * Process a batch of sessions
		 */
		function processSpamBatch(offset, total) {
			$.ajax({
				url: opti_behaviorSettings.ajaxUrl || ajaxurl,
				type: 'POST',
				data: {
					action: 'optibehavior_recalculate_spam',
					nonce: opti_behaviorSettings.settingsNonce,
					action_type: 'recalculate',
					offset: offset,
					batch_size: 500
				},
				success: function(response) {
					if (response.success) {
						if (response.data.status === 'processing') {
							// Update progress bar
							var progress = response.data.progress;
							var processed = response.data.processed;
							var totalSessions = response.data.total;

							$('#spam-recalc-progress-bar').css('width', progress + '%');
							$('#spam-recalc-percent').text(progress + '%');
							$('#spam-recalc-status').text('Processing ' + processed.toLocaleString() + ' of ' + totalSessions.toLocaleString() + ' sessions...');

							// Process next batch
							processSpamBatch(response.data.next_offset, totalSessions);
						} else if (response.data.status === 'completed') {
							spamRecalcComplete(response.data.message);
						}
					} else {
						spamRecalcError(response.data ? response.data.message : 'Unknown error');
					}
				},
				error: function(xhr, status, error) {
					spamRecalcError('AJAX error: ' + error);
				}
			});
		}

		/**
		 * Handle successful completion
		 */
		function spamRecalcComplete(message) {
			$('#spam-recalc-progress-bar').css('width', '100%');
			$('#spam-recalc-percent').text('100%');
			$('#spam-recalc-status').text('Complete!');

			// Hide progress bar after a moment
			setTimeout(function() {
				$('#spam-recalc-container').hide();
				$('#spam-recalc-success').show();
				$('#spam-recalc-success-msg').text(message || opti_behaviorSettings.strings.completed);

				// Update original settings to current values
				originalSpamSettings = {
					duration: $('input[name="opti_behavior_traffic[spam_duration_threshold]"]').val(),
					minScrolls: $('input[name="opti_behavior_traffic[spam_min_scrolls_threshold]"]').val(),
					minClicks: $('input[name="opti_behavior_traffic[spam_min_clicks_threshold]"]').val(),
					enabled: $('input[name="opti_behavior_traffic[spam_detection_enabled]"]').is(':checked')
				};

				// Re-enable submit button
				$('button[name="opti_behavior_traffic_settings_submit"]').prop('disabled', false).text('Save Traffic Settings');
			}, 500);
		}

		/**
		 * Handle error
		 */
		function spamRecalcError(message) {
			$('#spam-recalc-container').hide();
			showOptiNotice((opti_behaviorSettings.strings.error || 'Error') + ' ' + message, 'error');
			$('button[name="opti_behavior_traffic_settings_submit"]').prop('disabled', false).text('Save Traffic Settings');
		}

		// =========================================================
		// Delete All Data with Progress Modal
		// =========================================================

		var $deleteModal = $('#opti-behavior-delete-modal');
		var $deleteBtn = $('#opti-behavior-delete-all-btn');
		var $confirmBtn = $('#opti-behavior-confirm-delete-btn');
		var $confirmStep = $('#opti-behavior-delete-confirm');
		var $progressStep = $('#opti-behavior-delete-progress');
		var $completeStep = $('#opti-behavior-delete-complete');
		var $toggleAllLink = $('#opti-behavior-toggle-all-categories');
		var $categoryChecks = $('.danger-category-check');
		var selectedCategories = [];

		// Open modal when delete button is clicked
		$deleteBtn.on('click', function() {
			showDeleteModal();
		});

		// Close modal handlers
		$deleteModal.on('click', '.opti-behavior-modal-close, .opti-behavior-modal-cancel, .opti-behavior-modal-overlay', function(e) {
			if ($(e.target).is('.opti-behavior-modal-overlay') || $(e.target).is('.opti-behavior-modal-close') || $(e.target).is('.opti-behavior-modal-cancel')) {
				hideDeleteModal();
			}
		});

		// Done button after completion
		$deleteModal.on('click', '.opti-behavior-modal-done', function() {
			location.reload();
		});

		// Start deletion when confirm button is clicked
		$confirmBtn.on('click', function() {
			startDeletion();
		});

		// Select All / Deselect All toggle
		$toggleAllLink.on('click', function(e) {
			e.preventDefault();
			var allChecked = $categoryChecks.filter(':checked').length === $categoryChecks.length;
			$categoryChecks.prop('checked', !allChecked);
			updateDeleteButtonState();
		});

		// Update state whenever a category checkbox changes
		$categoryChecks.on('change', function() {
			updateDeleteButtonState();
		});

		/**
		 * Update delete button state based on checked categories
		 */
		function updateDeleteButtonState() {
			var checkedCount = $categoryChecks.filter(':checked').length;
			var allChecked = checkedCount === $categoryChecks.length;

			// Update toggle link text
			$toggleAllLink.text(allChecked ? 'Deselect All' : 'Select All');

			// Disable button when nothing is checked
			$deleteBtn.prop('disabled', checkedCount === 0);

			// Update button label while preserving the icon element
			if (checkedCount > 0) {
				var btnText = allChecked ? 'Delete All Analytics Data' : 'Delete Selected Data';
				$deleteBtn.contents().filter(function() {
					return this.nodeType === 3; // text nodes only
				}).last().replaceWith(document.createTextNode(' ' + btnText));
			}
		}

		/**
		 * Show the delete modal
		 */
		function showDeleteModal() {
			var checkedCount = $categoryChecks.filter(':checked').length;
			var allChecked = checkedCount === $categoryChecks.length;

			// Populate modal category list with checked categories
			var $categoryList = $('#opti-behavior-delete-category-list');
			$categoryList.empty();
			$categoryChecks.filter(':checked').each(function() {
				var label = $(this).closest('label').find('.condition-label strong').text();
				$categoryList.append('<li>' + label + '</li>');
			});

			// Update modal warning body text
			var warningText = allChecked
				? 'This will permanently delete ALL analytics data from your database. This action cannot be undone.'
				: 'This will permanently delete the selected analytics data from your database. This action cannot be undone.';
			$('#opti-behavior-modal-warning-body').text(warningText);

			// Update confirm button text (preserve icon)
			var confirmText = allChecked ? 'Yes, Delete All Data' : 'Yes, Delete Selected Data';
			$confirmBtn.contents().filter(function() {
				return this.nodeType === 3; // text nodes only
			}).last().replaceWith(document.createTextNode(' ' + confirmText));

			// Reset to confirm step
			$confirmStep.show();
			$progressStep.hide();
			$completeStep.hide();
			$deleteModal.fadeIn(200);
			// Reinitialize Lucide icons in modal
			if (typeof lucide !== 'undefined') {
				lucide.createIcons();
			}
		}

		/**
		 * Hide the delete modal
		 */
		function hideDeleteModal() {
			$deleteModal.fadeOut(200);
		}

		/**
		 * Start the deletion process
		 */
		function startDeletion() {
			// Collect checked category keys before starting AJAX loop
			selectedCategories = [];
			$categoryChecks.filter(':checked').each(function() {
				selectedCategories.push($(this).data('category'));
			});

			// Show progress step
			$confirmStep.hide();
			$progressStep.show();
			$completeStep.hide();

			// Reset progress
			$('#opti-behavior-delete-progress-bar').css('width', '0%');
			$('#opti-behavior-delete-percent').text('0%');
			$('#opti-behavior-delete-status').text('Initializing...');

			// Start processing
			processDeleteStep(0);
		}

		/**
		 * Process deletion step by step
		 */
		function processDeleteStep(step) {
			$.ajax({
				url: opti_behaviorSettings.ajaxUrl || ajaxurl,
				type: 'POST',
				data: {
					action: 'optibehavior_delete_all_data',
					nonce: opti_behaviorSettings.deleteAllNonce,
					step: step,
					categories: selectedCategories
				},
				success: function(response) {
					if (response.success) {
						if (response.data.status === 'processing') {
							// Update progress
							$('#opti-behavior-delete-progress-bar').css('width', response.data.progress + '%');
							$('#opti-behavior-delete-percent').text(response.data.progress + '%');
							$('#opti-behavior-delete-status').text(response.data.message);

							// Process next step
							processDeleteStep(response.data.step);
						} else if (response.data.status === 'completed') {
							// Show completion
							deletionComplete(response.data.message);
						}
					} else {
						deletionError(response.data ? response.data.message : 'Unknown error');
					}
				},
				error: function(xhr, status, error) {
					deletionError('AJAX error: ' + error);
				}
			});
		}

		/**
		 * Handle successful completion
		 */
		function deletionComplete(message) {
			$('#opti-behavior-delete-progress-bar').css('width', '100%');
			$('#opti-behavior-delete-percent').text('100%');
			$('#opti-behavior-delete-status').text('Complete!');

			setTimeout(function() {
				$progressStep.hide();
				$completeStep.show();
				$('#opti-behavior-delete-result').text(message || opti_behaviorSettings.strings.deleteComplete);
				// Reinitialize Lucide icons
				if (typeof lucide !== 'undefined') {
					lucide.createIcons();
				}
			}, 500);
		}

		/**
		 * Handle deletion error
		 */
		function deletionError(message) {
			hideDeleteModal();
			showOptiNotice((opti_behaviorSettings.strings.deleteError || 'Delete error') + ' ' + message, 'error');
		}

		// =========================================================
		// Delete Data by Date Range with Progress Modal
		// =========================================================

		var $rangeModal = $('#opti-behavior-delete-range-modal');
		var $rangeBtn = $('#opti-behavior-delete-range-btn');
		var $rangeConfirmBtn = $('#opti-behavior-confirm-range-delete-btn');
		var $rangeConfirmStep = $('#opti-behavior-range-confirm');
		var $rangeProgressStep = $('#opti-behavior-range-progress');
		var $rangeCompleteStep = $('#opti-behavior-range-complete');
		var $rangeStartInput = $('#opti-behavior-range-start');
		var $rangeEndInput = $('#opti-behavior-range-end');

		// Open modal when date range delete button is clicked
		$rangeBtn.on('click', function() {
			showRangeModal();
		});

		// Close modal handlers
		$rangeModal.on('click', '.opti-behavior-modal-close, .opti-behavior-modal-cancel, .opti-behavior-modal-overlay', function(e) {
			if ($(e.target).is('.opti-behavior-modal-overlay') || $(e.target).is('.opti-behavior-modal-close') || $(e.target).is('.opti-behavior-modal-cancel')) {
				hideRangeModal();
			}
		});

		// Done button after completion
		$rangeModal.on('click', '.opti-behavior-modal-done', function() {
			location.reload();
		});

		// Start deletion when confirm button is clicked
		$rangeConfirmBtn.on('click', function() {
			startRangeDeletion();
		});

		/**
		 * Show the date range delete modal
		 */
		function showRangeModal() {
			var startDate = $rangeStartInput.val();
			var endDate = $rangeEndInput.val();

			// Validate date range
			if (!startDate || !endDate) {
				showOptiNotice(opti_behaviorSettings.strings.invalidDateRange || 'Invalid date range', 'warning');
				return;
			}

			if (new Date(startDate) > new Date(endDate)) {
				showOptiNotice(opti_behaviorSettings.strings.invalidDateRange || 'Invalid date range', 'warning');
				return;
			}

			// Format dates for display
			var startFormatted = formatDate(startDate);
			var endFormatted = formatDate(endDate);

			$('#opti-behavior-range-display-start').text(startFormatted);
			$('#opti-behavior-range-display-end').text(endFormatted);

			// Reset to confirm step
			$rangeConfirmStep.show();
			$rangeProgressStep.hide();
			$rangeCompleteStep.hide();
			$rangeModal.fadeIn(200);

			// Reinitialize Lucide icons in modal
			if (typeof lucide !== 'undefined') {
				lucide.createIcons();
			}
		}

		/**
		 * Hide the date range modal
		 */
		function hideRangeModal() {
			$rangeModal.fadeOut(200);
		}

		/**
		 * Format date for display
		 */
		function formatDate(dateStr) {
			var date = new Date(dateStr);
			var options = { year: 'numeric', month: 'short', day: 'numeric' };
			return date.toLocaleDateString(undefined, options);
		}

		/**
		 * Start the date range deletion process
		 */
		function startRangeDeletion() {
			// Show progress step
			$rangeConfirmStep.hide();
			$rangeProgressStep.show();
			$rangeCompleteStep.hide();

			// Reset progress
			$('#opti-behavior-range-progress-bar').css('width', '0%');
			$('#opti-behavior-range-percent').text('0%');
			$('#opti-behavior-range-status').text('Initializing...');

			// Start processing
			processRangeDeleteStep(0);
		}

		/**
		 * Process date range deletion step by step
		 */
		function processRangeDeleteStep(step) {
			var startDate = $rangeStartInput.val();
			var endDate = $rangeEndInput.val();

			$.ajax({
				url: opti_behaviorSettings.ajaxUrl || ajaxurl,
				type: 'POST',
				data: {
					action: 'optibehavior_delete_data_by_range',
					nonce: opti_behaviorSettings.deleteRangeNonce,
					step: step,
					start_date: startDate,
					end_date: endDate
				},
				success: function(response) {
					if (response.success) {
						if (response.data.status === 'processing') {
							// Update progress
							$('#opti-behavior-range-progress-bar').css('width', response.data.progress + '%');
							$('#opti-behavior-range-percent').text(response.data.progress + '%');
							$('#opti-behavior-range-status').text(response.data.message);

							// Process next step
							processRangeDeleteStep(response.data.step);
						} else if (response.data.status === 'completed') {
							// Show completion
							rangeDeletionComplete(response.data.message);
						}
					} else {
						rangeDeletionError(response.data ? response.data.message : 'Unknown error');
					}
				},
				error: function(xhr, status, error) {
					rangeDeletionError('AJAX error: ' + error);
				}
			});
		}

		/**
		 * Handle successful date range deletion completion
		 */
		function rangeDeletionComplete(message) {
			$('#opti-behavior-range-progress-bar').css('width', '100%');
			$('#opti-behavior-range-percent').text('100%');
			$('#opti-behavior-range-status').text('Complete!');

			setTimeout(function() {
				$rangeProgressStep.hide();
				$rangeCompleteStep.show();
				$('#opti-behavior-range-result').text(message);
				// Reinitialize Lucide icons
				if (typeof lucide !== 'undefined') {
					lucide.createIcons();
				}
			}, 500);
		}

		/**
		 * Handle date range deletion error
		 */
		function rangeDeletionError(message) {
			hideRangeModal();
			showOptiNotice((opti_behaviorSettings.strings.deleteError || 'Delete error') + ' ' + message, 'error');
		}

		// =========================================================
		// Smart Data Cleanup
		// =========================================================

		var $botCleanupBtn = $('#opti-behavior-bot-cleanup-btn');
		var $botModal = $('#opti-behavior-bot-cleanup-modal');
		var $smartPreviewBtn = $('#opti-behavior-smart-preview-btn');
		var $smartDeleteBtn = $('#opti-behavior-smart-delete-btn');
		var $smartModal = $('#opti-behavior-smart-cleanup-modal');
		var $saveConditionsBtn = $('#opti-behavior-save-conditions-btn');
		var $saveScheduleBtn = $('#opti-behavior-save-schedule-btn');

		// Enable/disable condition inputs based on checkbox state
		$('.condition-check').on('change', function() {
			var $row = $(this).closest('.condition-row');
			var isChecked = $(this).is(':checked');
			$row.find('.condition-input').prop('disabled', !isChecked);
		});

		// Auto-cleanup toggle
		$('#sc-auto-enabled').on('change', function() {
			var enabled = $(this).is(':checked');
			$('#sc-frequency-group').css({
				'opacity': enabled ? 1 : 0.5,
				'pointer-events': enabled ? 'auto' : 'none'
			});
		});

		/**
		 * Collect active conditions from the form
		 */
		function collectConditions() {
			var conditions = {};

			$('.condition-check:checked').each(function() {
				var conditionKey = $(this).data('condition');
				if (!conditionKey) return;

				switch (conditionKey) {
					case 'older_than_days':
						conditions.older_than_days = parseInt($('#sc-older-than-days').val()) || 0;
						break;
					case 'inactive_visitor_days':
						conditions.inactive_visitor_days = parseInt($('#sc-inactive-days').val()) || 0;
						break;
					case 'min_duration':
						conditions.min_duration = parseInt($('#sc-min-duration').val()) || 0;
						conditions.min_duration_age_days = parseInt($('#sc-min-duration-age').val()) || 0;
						break;
					case 'max_duration':
						conditions.max_duration = parseInt($('#sc-max-duration').val()) || 0;
						conditions.max_duration_age_days = parseInt($('#sc-max-duration-age').val()) || 0;
						break;
					case 'min_events':
						conditions.min_events = parseInt($('#sc-min-events').val()) || 0;
						conditions.min_events_age_days = parseInt($('#sc-min-events-age').val()) || 0;
						break;
					case 'max_events':
						conditions.max_events = parseInt($('#sc-max-events').val()) || 0;
						break;
					case 'min_page_views':
						conditions.min_page_views = parseInt($('#sc-min-pageviews').val()) || 0;
						break;
					case 'bounce_only':
						conditions.bounce_only = true;
						conditions.bounce_age_days = parseInt($('#sc-bounce-age').val()) || 0;
						break;
					case 'single_visit_only':
						conditions.single_visit_only = true;
						conditions.single_visit_age_days = parseInt($('#sc-single-visit-age').val()) || 0;
						break;
				}
			});

			// Add orphaned visitors option
			conditions.delete_orphaned_visitors = $('#sc-delete-orphans').is(':checked');

			return conditions;
		}

		/**
		 * Check if any condition is selected
		 */
		function hasActiveConditions() {
			return $('.condition-check:checked').length > 0;
		}

		// ---- Save Conditions ----
		$saveConditionsBtn.on('click', function() {
			var $btn = $(this);
			$btn.prop('disabled', true).find('.btn-text').text(opti_behaviorSettings.strings.saving || 'Saving...');

			var settings = {
				enabled: $('#sc-auto-enabled').is(':checked'),
				frequency: $('#sc-auto-frequency').val(),
				conditions: collectConditions(),
				delete_orphaned_visitors: $('#sc-delete-orphans').is(':checked')
			};

			$.ajax({
				url: opti_behaviorSettings.ajaxUrl || ajaxurl,
				type: 'POST',
				data: {
					action: 'optibehavior_save_auto_cleanup',
					nonce: opti_behaviorSettings.smartCleanupNonce,
					settings: settings
				},
				success: function(response) {
					$btn.prop('disabled', false).find('.btn-text').text(opti_behaviorSettings.strings.saveConditions || 'Save Conditions');
					if (typeof lucide !== 'undefined') { lucide.createIcons(); }
					if (response.success) {
						var $notice = $('<div class="notice notice-success is-dismissible" style="position:fixed;top:40px;right:20px;z-index:99999;padding:10px 15px;border-left:4px solid #46b450;background:#fff;box-shadow:0 2px 8px rgba(0,0,0,0.15);"><p>' + (response.data.message || 'Conditions saved successfully.') + '</p></div>');
						$('body').append($notice);
						setTimeout(function() { $notice.fadeOut(300, function() { $(this).remove(); }); }, 3000);
					} else {
						showOptiNotice(response.data ? response.data.message : 'Error saving conditions', 'error');
					}
				},
				error: function() {
					$btn.prop('disabled', false).find('.btn-text').text(opti_behaviorSettings.strings.saveConditions || 'Save Conditions');
					if (typeof lucide !== 'undefined') { lucide.createIcons(); }
					showOptiNotice('AJAX error', 'error');
				}
			});
		});

		// ---- Preview ----
		$smartPreviewBtn.on('click', function() {
			if (!hasActiveConditions()) {
				showOptiNotice(opti_behaviorSettings.strings.noConditions || 'Please select at least one condition.', 'warning');
				return;
			}

			var $btn = $(this);
			var $countSpan = $('#opti-behavior-preview-count');
			$btn.prop('disabled', true).find('.btn-text').text(opti_behaviorSettings.strings.previewing || 'Checking...');

			$.ajax({
				url: opti_behaviorSettings.ajaxUrl || ajaxurl,
				type: 'POST',
				data: {
					action: 'optibehavior_smart_cleanup_preview',
					nonce: opti_behaviorSettings.smartCleanupNonce,
					conditions: collectConditions()
				},
				success: function(response) {
					$btn.prop('disabled', false).find('.btn-text').text(opti_behaviorSettings.strings.preview || 'Preview');
					if (response.success) {
						$countSpan.text('(' + response.data.count + ' sessions)').show();
						$smartDeleteBtn.prop('disabled', response.data.count === 0);
					} else {
						showOptiNotice(response.data ? response.data.message : 'Error', 'error');
					}
				},
				error: function() {
					$btn.prop('disabled', false).find('.btn-text').text(opti_behaviorSettings.strings.preview || 'Preview');
					showOptiNotice('AJAX error', 'error');
				}
			});
		});

		// ---- Smart Cleanup Delete ----
		$smartDeleteBtn.on('click', function() {
			$('#opti-behavior-smart-preview-summary').text(
				$('#opti-behavior-preview-count').text()
			);
			$('#opti-behavior-smart-confirm').show();
			$('#opti-behavior-smart-progress').hide();
			$('#opti-behavior-smart-complete').hide();
			$smartModal.fadeIn(200);
			if (typeof lucide !== 'undefined') { lucide.createIcons(); }
		});

		// Smart modal close
		$smartModal.on('click', '.opti-behavior-modal-close, .opti-behavior-modal-cancel, .opti-behavior-modal-overlay', function(e) {
			if ($(e.target).is('.opti-behavior-modal-overlay, .opti-behavior-modal-close, .opti-behavior-modal-cancel')) {
				$smartModal.fadeOut(200);
			}
		});
		$smartModal.on('click', '.opti-behavior-modal-done', function() { location.reload(); });

		// Confirm smart cleanup
		$('#opti-behavior-confirm-smart-cleanup-btn').on('click', function() {
			$('#opti-behavior-smart-confirm').hide();
			$('#opti-behavior-smart-progress').show();
			$('#opti-behavior-smart-progress-bar').css('width', '0%');
			$('#opti-behavior-smart-percent').text('0%');
			$('#opti-behavior-smart-status').text('Initializing...');
			processSmartCleanupStep(0);
		});

		function processSmartCleanupStep(step) {
			$.ajax({
				url: opti_behaviorSettings.ajaxUrl || ajaxurl,
				type: 'POST',
				data: {
					action: 'optibehavior_smart_cleanup_execute',
					nonce: opti_behaviorSettings.smartCleanupNonce,
					conditions: collectConditions(),
					step: step
				},
				success: function(response) {
					if (response.success) {
						if (response.data.status === 'processing') {
							$('#opti-behavior-smart-progress-bar').css('width', response.data.progress + '%');
							$('#opti-behavior-smart-percent').text(response.data.progress + '%');
							$('#opti-behavior-smart-status').text(response.data.message);
							processSmartCleanupStep(response.data.step);
						} else if (response.data.status === 'completed') {
							$('#opti-behavior-smart-progress-bar').css('width', '100%');
							$('#opti-behavior-smart-percent').text('100%');
							setTimeout(function() {
								$('#opti-behavior-smart-progress').hide();
								$('#opti-behavior-smart-complete').show();
								$('#opti-behavior-smart-result').text(
									(response.data.deleted || 0) + ' sessions deleted successfully.'
								);
								if (typeof lucide !== 'undefined') { lucide.createIcons(); }
							}, 500);
						}
					} else {
						$smartModal.fadeOut(200);
						showOptiNotice(response.data ? response.data.message : 'Error', 'error');
					}
				},
				error: function(xhr, status, error) {
					$smartModal.fadeOut(200);
					showOptiNotice('AJAX error: ' + error, 'error');
				}
			});
		}

		// ---- Bot Cleanup ----
		$botCleanupBtn.on('click', function() {
			$('#opti-behavior-bot-confirm').show();
			$('#opti-behavior-bot-progress').hide();
			$('#opti-behavior-bot-complete').hide();
			$botModal.fadeIn(200);
			if (typeof lucide !== 'undefined') { lucide.createIcons(); }
		});

		// Bot modal close
		$botModal.on('click', '.opti-behavior-modal-close, .opti-behavior-modal-cancel, .opti-behavior-modal-overlay', function(e) {
			if ($(e.target).is('.opti-behavior-modal-overlay, .opti-behavior-modal-close, .opti-behavior-modal-cancel')) {
				$botModal.fadeOut(200);
			}
		});
		$botModal.on('click', '.opti-behavior-modal-done', function() { location.reload(); });

		// Confirm bot cleanup
		$('#opti-behavior-confirm-bot-cleanup-btn').on('click', function() {
			$('#opti-behavior-bot-confirm').hide();
			$('#opti-behavior-bot-progress').show();
			$('#opti-behavior-bot-progress-bar').css('width', '0%');
			$('#opti-behavior-bot-percent').text('0%');
			$('#opti-behavior-bot-status').text('Initializing...');
			processBotCleanupStep(0);
		});

		function processBotCleanupStep(step) {
			$.ajax({
				url: opti_behaviorSettings.ajaxUrl || ajaxurl,
				type: 'POST',
				data: {
					action: 'optibehavior_bot_cleanup',
					nonce: opti_behaviorSettings.smartCleanupNonce,
					step: step
				},
				success: function(response) {
					if (response.success) {
						if (response.data.status === 'processing') {
							$('#opti-behavior-bot-progress-bar').css('width', response.data.progress + '%');
							$('#opti-behavior-bot-percent').text(response.data.progress + '%');
							$('#opti-behavior-bot-status').text(response.data.message);
							processBotCleanupStep(response.data.step);
						} else if (response.data.status === 'completed') {
							$('#opti-behavior-bot-progress-bar').css('width', '100%');
							$('#opti-behavior-bot-percent').text('100%');
							setTimeout(function() {
								$('#opti-behavior-bot-progress').hide();
								$('#opti-behavior-bot-complete').show();
								$('#opti-behavior-bot-result').text(
									(response.data.deleted || 0) + ' bot sessions cleaned successfully.'
								);
								if (typeof lucide !== 'undefined') { lucide.createIcons(); }
							}, 500);
						}
					} else {
						$botModal.fadeOut(200);
						showOptiNotice(response.data ? response.data.message : 'Error', 'error');
					}
				},
				error: function(xhr, status, error) {
					$botModal.fadeOut(200);
					showOptiNotice('AJAX error: ' + error, 'error');
				}
			});
		}

		// ---- Save Schedule ----
		$saveScheduleBtn.on('click', function() {
			var $btn = $(this);
			$btn.prop('disabled', true).text(opti_behaviorSettings.strings.saving || 'Saving...');

			var settings = {
				enabled: $('#sc-auto-enabled').is(':checked'),
				frequency: $('#sc-auto-frequency').val(),
				conditions: collectConditions(),
				delete_orphaned_visitors: $('#sc-delete-orphans').is(':checked')
			};

			$.ajax({
				url: opti_behaviorSettings.ajaxUrl || ajaxurl,
				type: 'POST',
				data: {
					action: 'optibehavior_save_auto_cleanup',
					nonce: opti_behaviorSettings.smartCleanupNonce,
					settings: settings
				},
				success: function(response) {
					$btn.prop('disabled', false).html('<span class="btn-icon"><i data-lucide="save"></i></span> ' + (opti_behaviorSettings.strings.saveSchedule || 'Save Schedule'));
					if (typeof lucide !== 'undefined') { lucide.createIcons(); }
					if (response.success) {
						// Show a brief success notification
						var $notice = $('<div class="notice notice-success is-dismissible" style="position:fixed;top:40px;right:20px;z-index:99999;padding:10px 15px;"><p>' + response.data.message + '</p></div>');
						$('body').append($notice);
						setTimeout(function() { $notice.fadeOut(300, function() { $(this).remove(); }); }, 3000);
					} else {
						showOptiNotice(response.data ? response.data.message : 'Error saving settings', 'error');
					}
				},
				error: function() {
					$btn.prop('disabled', false).html('<span class="btn-icon"><i data-lucide="save"></i></span> ' + (opti_behaviorSettings.strings.saveSchedule || 'Save Schedule'));
					if (typeof lucide !== 'undefined') { lucide.createIcons(); }
					showOptiNotice('AJAX error', 'error');
				}
			});
		});

		// Danger Zone sub-tabs
		$('.danger-zone-tab').on('click', function() {
			var tab = $(this).data('danger-tab');
			$('.danger-zone-tab').removeClass('active');
			$(this).addClass('active');
			$('.danger-tab-panel').removeClass('active');
			$('.danger-tab-panel[data-danger-tab="' + tab + '"]').addClass('active');
			if (typeof lucide !== 'undefined') { lucide.createIcons(); }
		});

	});

	// Privacy mode toggle — show/hide Consent Banner Configuration card
	(function() {
		function obToggleConsentCard() {
			var selected = document.querySelector('input[name="privacy_mode"]:checked');
			var card = document.querySelector('.ob-consent-card');
			if (!card) { return; }
			if (selected && selected.value === 'full') {
				card.classList.remove('ob-consent-card--hidden');
			} else {
				card.classList.add('ob-consent-card--hidden');
			}
		}
		var privacyRadios = document.querySelectorAll('input[name="privacy_mode"]');
		privacyRadios.forEach(function(r) {
			r.addEventListener('change', obToggleConsentCard);
		});

		// Update hex label when color picker changes
		var colorPickers = document.querySelectorAll('.ob-color-picker-item input[type="color"]');
		colorPickers.forEach(function(picker) {
			picker.addEventListener('input', function() {
				var hexSpan = picker.parentElement.querySelector('.ob-color-hex');
				if (hexSpan) { hexSpan.textContent = picker.value; }
			});
		});
	}());

})();