/**
 * Clicks User Manager - Admin JavaScript
 * Developer: Clicks - Digital Marketing & Software Agency | clicks.com.pk
 */
/* global wpum_ajax, jQuery */
( function ( $ ) {
	'use strict';

	// =========================================================================
	// Cached references
	// =========================================================================
	var $body            = $( 'body' );
	var $table           = $( '#wpum-users-table' );
	var $selectAll       = $( '#wpum-select-all' );
	var $bulkAction      = $( '#wpum-bulk-action' );
	var $bulkRole        = $( '#wpum-bulk-role' );
	var $applyBulk       = $( '#wpum-apply-bulk' );
	var $bulkSpinner     = $( '#wpum-bulk-spinner' );
	var $selectedCount   = $( '#wpum-selected-count' );
	var $noticeWrap      = $( '#wpum-notice-wrap' );
	var $perPage         = $( '#wpum-per-page' );

	// Delete modal
	var $deleteModal     = $( '#wpum-delete-modal' );
	var $modalMessage    = $( '#wpum-modal-message' );
	var $modalConfirm    = $( '#wpum-modal-confirm' );
	var $modalCancel     = $( '#wpum-modal-cancel' );

	// Mail modal
	var $mailModal       = $( '#wpum-mail-modal' );
	var $mailSubject     = $( '#wpum-mail-subject' );
	var $mailMessage     = $( '#wpum-mail-message' );
	var $mailSend        = $( '#wpum-mail-send' );
	var $mailCancel      = $( '#wpum-mail-cancel' );
	var $mailClose       = $( '#wpum-mail-modal-close' );
	var $mailSpinner     = $( '#wpum-mail-spinner' );
	var $mailResult      = $( '#wpum-mail-result' );

	// Export
	var $exportForm      = $( '#wpum-export-form' );
	var $doExport        = $( '#wpum-do-export' );
	var $exportSpinner   = $( '#wpum-export-spinner' );
	var $exportStatus    = $( '#wpum-export-status' );

	// Pending delete state
	var pendingDeleteIds = [];

	// =========================================================================
	// Utility: Show admin notice
	// =========================================================================
	function showNotice( message, type ) {
		type = type || 'success';
		var icon = 'success' === type ? '✓' : '✗';
		var $notice = $(
			'<div class="wpum-notice ' + type + '">' +
				'<span>' + icon + ' ' + message + '</span>' +
				'<button type="button" class="wpum-notice-dismiss">&times;</button>' +
			'</div>'
		);
		$noticeWrap.empty().append( $notice );
		$( 'html, body' ).animate( { scrollTop: $noticeWrap.offset() ? $noticeWrap.offset().top - 80 : 0 }, 300 );

		$notice.find( '.wpum-notice-dismiss' ).on( 'click', function () {
			$notice.fadeOut( 200, function () { $notice.remove(); } );
		} );

		// Auto-dismiss success after 5 seconds.
		if ( 'success' === type ) {
			setTimeout( function () {
				$notice.fadeOut( 400, function () { $notice.remove(); } );
			}, 5000 );
		}
	}

	$noticeWrap.on( 'click', '.wpum-notice-dismiss', function () {
		$( this ).closest( '.wpum-notice' ).fadeOut( 200, function () { $( this ).remove(); } );
	} );

	// =========================================================================
	// Utility: Get selected user IDs
	// =========================================================================
	function getSelectedIds() {
		var ids = [];
		$table.find( '.wpum-user-cb:checked' ).each( function () {
			ids.push( $( this ).val() );
		} );
		return ids;
	}

	// =========================================================================
	// Checkbox: Select All
	// =========================================================================
	$selectAll.on( 'change', function () {
		var checked = $( this ).prop( 'checked' );
		$table.find( '.wpum-user-cb' ).prop( 'checked', checked );
		updateSelectedCount();
	} );

	$table.on( 'change', '.wpum-user-cb', function () {
		var total   = $table.find( '.wpum-user-cb' ).length;
		var checked = $table.find( '.wpum-user-cb:checked' ).length;
		$selectAll.prop( 'indeterminate', checked > 0 && checked < total );
		$selectAll.prop( 'checked', checked === total );
		updateSelectedCount();
	} );

	function updateSelectedCount() {
		var count = getSelectedIds().length;
		if ( count > 0 ) {
			$selectedCount.text( count + ' selected' );
		} else {
			$selectedCount.text( '' );
		}
	}

	// =========================================================================
	// Bulk action: show role selector when "change_role" is selected
	// =========================================================================
	$bulkAction.on( 'change', function () {
		if ( 'change_role' === $( this ).val() ) {
			$bulkRole.show();
		} else {
			$bulkRole.hide();
		}
	} );

	// =========================================================================
	// Apply Bulk Action
	// =========================================================================
	$applyBulk.on( 'click', function () {
		var action  = $bulkAction.val();
		var ids     = getSelectedIds();

		if ( ! action ) {
			alert( wpum_ajax.select_action );
			return;
		}

		if ( ! ids.length ) {
			alert( wpum_ajax.select_users );
			return;
		}

		if ( 'delete' === action ) {
			pendingDeleteIds = ids;
			$modalMessage.text(
				ids.length === 1
					? 'Are you sure you want to delete 1 user? This cannot be undone.'
					: 'Are you sure you want to delete ' + ids.length + ' users? This cannot be undone.'
			);
			openModal( $deleteModal );
			return;
		}

		if ( 'bulk_mail' === action ) {
			openModal( $mailModal );
			return;
		}

		if ( 'export_csv' === action ) {
			exportSelectedCSV( ids );
			return;
		}

		if ( 'change_role' === action ) {
			var newRole = $bulkRole.val();
			if ( ! newRole ) {
				alert( wpum_ajax.select_role );
				return;
			}
			doBulkAction( 'change_role', ids, { new_role: newRole } );
			return;
		}
	} );

	// =========================================================================
	// Single delete button
	// =========================================================================
	$table.on( 'click', '.wpum-delete-single', function () {
		var uid      = $( this ).data( 'user-id' );
		var username = $( this ).data( 'username' );
		pendingDeleteIds = [ uid ];
		$modalMessage.text( 'Are you sure you want to delete user "' + username + '"? This cannot be undone.' );
		openModal( $deleteModal );
	} );

	// =========================================================================
	// Delete Modal: Confirm / Cancel
	// =========================================================================
	$modalConfirm.on( 'click', function () {
		if ( ! pendingDeleteIds.length ) {
			return;
		}
		closeModal( $deleteModal );
		doBulkAction( 'delete', pendingDeleteIds, {} );
		pendingDeleteIds = [];
	} );

	$modalCancel.on( 'click', function () {
		closeModal( $deleteModal );
		pendingDeleteIds = [];
	} );

	$deleteModal.find( '.wpum-modal-backdrop' ).on( 'click', function () {
		closeModal( $deleteModal );
		pendingDeleteIds = [];
	} );

	// =========================================================================
	// Mail Modal: Send / Cancel
	// =========================================================================
	$mailSend.on( 'click', function () {
		var subject = $.trim( $mailSubject.val() );
		var message = $.trim( $mailMessage.val() );
		var ids     = getSelectedIds();

		if ( ! subject ) {
			alert( wpum_ajax.mail_subject_required );
			return;
		}
		if ( ! message ) {
			alert( wpum_ajax.mail_message_required );
			return;
		}
		if ( ! ids.length ) {
			alert( wpum_ajax.select_users );
			return;
		}

		$mailSend.prop( 'disabled', true ).text( wpum_ajax.sending );
		$mailSpinner.addClass( 'is-active' );
		$mailResult.hide().removeClass( 'success error' );

		$.ajax( {
			url:    wpum_ajax.ajax_url,
			type:   'POST',
			data:   {
				action:   'wpum_bulk_mail',
				nonce:    wpum_ajax.nonce,
				user_ids: ids,
				subject:  subject,
				message:  message,
			},
			success: function ( response ) {
				$mailSpinner.removeClass( 'is-active' );
				$mailSend.prop( 'disabled', false ).html( '<span class="dashicons dashicons-email"></span> Send Emails' );

				if ( response.success ) {
					$mailResult.addClass( 'success' ).text( response.data.message ).show();
				} else {
					$mailResult.addClass( 'error' ).text( response.data.message ).show();
				}
			},
			error: function () {
				$mailSpinner.removeClass( 'is-active' );
				$mailSend.prop( 'disabled', false ).html( '<span class="dashicons dashicons-email"></span> Send Emails' );
				$mailResult.addClass( 'error' ).text( 'An error occurred. Please try again.' ).show();
			},
		} );
	} );

	$mailCancel.add( $mailClose ).on( 'click', function () {
		closeModal( $mailModal );
	} );

	$mailModal.find( '.wpum-modal-backdrop' ).on( 'click', function () {
		closeModal( $mailModal );
	} );

	// =========================================================================
	// Bulk AJAX action
	// =========================================================================
	function doBulkAction( action, ids, extraData ) {
		$bulkSpinner.addClass( 'is-active' );
		$applyBulk.prop( 'disabled', true ).text( wpum_ajax.processing );

		var data = $.extend(
			{
				action:      'wpum_bulk_action',
				nonce:       wpum_ajax.nonce,
				bulk_action: action,
				user_ids:    ids,
			},
			extraData
		);

		$.ajax( {
			url:     wpum_ajax.ajax_url,
			type:    'POST',
			data:    data,
			success: function ( response ) {
				$bulkSpinner.removeClass( 'is-active' );
				$applyBulk.prop( 'disabled', false ).text( 'Apply' );

				if ( response.success ) {
					showNotice( response.data.message, 'success' );

					if ( 'delete' === action ) {
						// Remove deleted rows.
						$.each( ids, function ( i, uid ) {
							$table.find( 'tr[data-user-id="' + uid + '"]' ).fadeOut( 300, function () {
								$( this ).remove();
								updateSelectedCount();
							} );
						} );
					} else if ( 'change_role' === action ) {
						// Reload the page to reflect role changes.
						setTimeout( function () { window.location.reload(); }, 1200 );
					}
				} else {
					showNotice( response.data.message, 'error' );
				}
			},
			error: function () {
				$bulkSpinner.removeClass( 'is-active' );
				$applyBulk.prop( 'disabled', false ).text( 'Apply' );
				showNotice( 'An unexpected error occurred. Please try again.', 'error' );
			},
		} );
	}

	// =========================================================================
	// Export selected to CSV (creates a form POST)
	// =========================================================================
	function exportSelectedCSV( ids ) {
		var $form = $( '<form>', {
			method: 'post',
			action: wpum_ajax.ajax_url,
		} );

		$form.append( $( '<input>', { type: 'hidden', name: 'action', value: 'wpum_export_csv' } ) );
		$form.append( $( '<input>', { type: 'hidden', name: 'nonce', value: wpum_ajax.nonce } ) );

		$.each( ids, function ( i, uid ) {
			$form.append( $( '<input>', { type: 'hidden', name: 'user_ids[]', value: uid } ) );
		} );

		$body.append( $form );
		$form.submit();
		$form.remove();
	}

	// =========================================================================
	// Per-page selector
	// =========================================================================
	if ( $perPage.length ) {
		$perPage.on( 'change', function () {
			var url = new URL( window.location.href );
			url.searchParams.set( 'per_page', $( this ).val() );
			url.searchParams.set( 'paged', '1' );
			window.location.href = url.toString();
		} );
	}

	// =========================================================================
	// Export page
	// =========================================================================
	$( '#wpum-check-all-cols' ).on( 'click', function ( e ) {
		e.preventDefault();
		$( 'input[name="export_cols[]"]' ).prop( 'checked', true );
	} );

	$( '#wpum-uncheck-all-cols' ).on( 'click', function ( e ) {
		e.preventDefault();
		$( 'input[name="export_cols[]"]' ).prop( 'checked', false );
	} );

	$doExport.on( 'click', function () {
		var cols = [];
		$( 'input[name="export_cols[]"]:checked' ).each( function () {
			cols.push( $( this ).val() );
		} );

		if ( ! cols.length ) {
			alert( 'Please select at least one column to export.' );
			return;
		}

		$exportSpinner.show();
		$exportStatus.text( 'Generating CSV…' );

		var $form = $( '<form>', { method: 'post', action: wpum_ajax.ajax_url } );
		$form.append( $( '<input>', { type: 'hidden', name: 'action', value: 'wpum_export_csv' } ) );
		$form.append( $( '<input>', { type: 'hidden', name: 'nonce', value: wpum_ajax.nonce } ) );

		// Append filter fields.
		$exportForm.find( 'input, select' ).not( '[name="wpum_export_nonce"]' ).each( function () {
			var $el  = $( this );
			var name = $el.attr( 'name' );
			var val  = $el.val();
			if ( ! name ) { return; }
			if ( 'export_cols[]' === name ) { return; } // we add cols separately below
			$form.append( $( '<input>', { type: 'hidden', name: name, value: val } ) );
		} );

		$.each( cols, function ( i, col ) {
			$form.append( $( '<input>', { type: 'hidden', name: 'export_cols[]', value: col } ) );
		} );

		$body.append( $form );
		$form.submit();
		$form.remove();

		setTimeout( function () {
			$exportSpinner.hide();
			$exportStatus.text( 'Download started!' );
			setTimeout( function () { $exportStatus.text( '' ); }, 3000 );
		}, 1500 );
	} );

	// =========================================================================
	// Modal helpers
	// =========================================================================
	function openModal( $modal ) {
		$modal.addClass( 'is-open' ).attr( 'aria-hidden', 'false' );
		$body.css( 'overflow', 'hidden' );
	}

	function closeModal( $modal ) {
		$modal.removeClass( 'is-open' ).attr( 'aria-hidden', 'true' );
		$body.css( 'overflow', '' );
	}

	// Close modals on Escape key.
	$( document ).on( 'keydown', function ( e ) {
		if ( 27 === e.which ) {
			closeModal( $deleteModal );
			closeModal( $mailModal );
			closeModal( $notesModal );
			closeModal( $bulkNoteModal );
			pendingDeleteIds = [];
		}
	} );

	// =========================================================================
	// User Notes Modal Handlers
	// =========================================================================
	var $notesModal      = $( '#wpum-notes-modal' );
	var $notesModalClose = $( '#wpum-notes-modal-close' );
	var $notesUsername   = $( '#wpum-notes-modal-username' );
	var $newNoteText     = $( '#wpum-new-note-text' );
	var $saveNoteBtn     = $( '#wpum-save-note-btn' );
	var $notesList       = $( '#wpum-notes-list' );
	var $noteLimitMsg    = $( '#wpum-note-limit-msg' );
	var activeNotesUserId = null;

	// Bulk note modal
	var $bulkNoteModal   = $( '#wpum-bulk-note-modal' );
	var $bulkNoteClose   = $( '#wpum-bulk-note-close' );
	var $bulkNoteCancel  = $( '#wpum-bulk-note-cancel' );
	var $bulkNoteSave    = $( '#wpum-bulk-note-save' );
	var $bulkNoteText    = $( '#wpum-bulk-note-text' );

	// Listen for notes button clicks
	$table.on( 'click', '.wpum-notes-trigger', function () {
		var $btn  = $( this );
		var uid   = $btn.data( 'user-id' );
		var uname = $btn.data( 'username' );

		activeNotesUserId = uid;
		$notesUsername.text( uname );
		$newNoteText.val( '' );
		$notesList.html( '<span class="wpum-spinner is-active" style="float:none; margin:10px auto; display:block;"></span>' );
		$noteLimitMsg.text( '' );
		$saveNoteBtn.prop( 'disabled', true );

		openModal( $notesModal );

		// Fetch notes list
		$.ajax( {
			url:    wpum_ajax.ajax_url,
			type:   'POST',
			data:   {
				action:  'wpum_get_notes',
				nonce:   wpum_ajax.nonce,
				user_id: uid
			},
			success: function ( response ) {
				$notesList.empty();
				if ( response.success ) {
					var notes = response.data.notes;
					if ( notes.length > 0 ) {
						$.each( notes, function ( i, note ) {
							$notesList.append( renderNoteRow( note ) );
						} );
					} else {
						$notesList.append( '<p class="description wpum-no-notes">No notes yet.</p>' );
					}

					// Update UI limits
					updateNoteLimitUI( response.data.can_add, response.data.note_qty, response.data.is_pro );
				} else {
					$notesList.html( '<p class="error">' + response.data.message + '</p>' );
				}
			},
			error: function () {
				$notesList.html( '<p class="error">Failed to fetch notes. Please try again.</p>' );
			}
		} );
	} );

	function renderNoteRow( note ) {
		return $(
			'<div class="wpum-note-row" data-note-id="' + note.id + '" style="background:#f6f7f7; border-left:4px solid #007cba; padding:10px; margin-bottom:8px; position:relative; border-radius: 0 4px 4px 0;">' +
				'<div style="font-weight:600; font-size:11px; color:#50575e; margin-bottom:4px;">' +
					note.author + ' &bull; ' + note.display_date +
				'</div>' +
				'<div style="font-size:13px; line-height:1.4; white-space:pre-wrap; padding-right:24px;">' + note.text + '</div>' +
				'<button type="button" class="wpum-delete-note-btn" style="position:absolute; right:10px; top:10px; background:none; border:none; cursor:pointer; color:#b32d2e; padding:0; font-size:18px; font-weight:bold;" title="Delete note">&times;</button>' +
			'</div>'
		);
	}

	function updateNoteLimitUI( canAdd, count, isPro ) {
		if ( canAdd ) {
			$newNoteText.prop( 'disabled', false );
			$saveNoteBtn.prop( 'disabled', false );
			if ( ! isPro ) {
				$noteLimitMsg.html( '<span style="color:#d54e21;">Free Tier: ' + count + '/3 notes used. Upgrade for unlimited.</span>' );
			} else {
				$noteLimitMsg.text( count + ' notes' );
			}
		} else {
			$newNoteText.prop( 'disabled', true );
			$saveNoteBtn.prop( 'disabled', true );
			$noteLimitMsg.html( '<span style="color:#d54e21; font-weight:600;">Limit Reached (3/3). <a href="admin.php?page=clicks-user-manager-about">Upgrade to Pro</a> for unlimited notes.</span>' );
		}
	}

	// Delete note click
	$notesList.on( 'click', '.wpum-delete-note-btn', function () {
		var $row   = $( this ).closest( '.wpum-note-row' );
		var noteId = $row.data( 'note-id' );

		if ( ! confirm( 'Are you sure you want to delete this note?' ) ) {
			return;
		}

		$row.css( 'opacity', 0.5 );

		$.ajax( {
			url:    wpum_ajax.ajax_url,
			type:   'POST',
			data:   {
				action:  'wpum_delete_note',
				nonce:   wpum_ajax.nonce,
				user_id: activeNotesUserId,
				note_id: noteId
			},
			success: function ( response ) {
				if ( response.success ) {
					$row.fadeOut( 300, function () {
						$( this ).remove();
						var count = $notesList.find( '.wpum-note-row' ).length;
						if ( count === 0 ) {
							$notesList.append( '<p class="description wpum-no-notes">No notes yet.</p>' );
						}
						// Update trigger count on the main table row
						var $trigger = $( '.wpum-notes-trigger[data-user-id="' + activeNotesUserId + '"]' );
						$trigger.find( '.wpum-notes-count' ).text( count );

						updateNoteLimitUI( response.data.can_add, response.data.note_qty, wpum_ajax.is_pro || false );
					} );
				} else {
					alert( response.data.message );
					$row.css( 'opacity', 1 );
				}
			},
			error: function () {
				alert( 'Failed to delete note.' );
				$row.css( 'opacity', 1 );
			}
		} );
	} );

	// Add note click
	$saveNoteBtn.on( 'click', function () {
		var text = $.trim( $newNoteText.val() );
		if ( ! text ) {
			return;
		}

		$saveNoteBtn.prop( 'disabled', true ).text( 'Adding…' );

		$.ajax( {
			url:    wpum_ajax.ajax_url,
			type:   'POST',
			data:   {
				action:  'wpum_add_note',
				nonce:   wpum_ajax.nonce,
				user_id: activeNotesUserId,
				note:    text
			},
			success: function ( response ) {
				$saveNoteBtn.text( 'Add Note' );
				if ( response.success ) {
					$newNoteText.val( '' );
					$notesList.find( '.wpum-no-notes' ).remove();
					$notesList.append( renderNoteRow( response.data.note ) );

					// Update trigger count on table row
					var $trigger = $( '.wpum-notes-trigger[data-user-id="' + activeNotesUserId + '"]' );
					$trigger.find( '.wpum-notes-count' ).text( response.data.note_qty );

					updateNoteLimitUI( response.data.can_add, response.data.note_qty, wpum_ajax.is_pro || false );
				} else {
					alert( response.data.message );
					$saveNoteBtn.prop( 'disabled', false );
				}
			},
			error: function () {
				$saveNoteBtn.prop( 'disabled', false ).text( 'Add Note' );
				alert( 'Failed to add note.' );
			}
		} );
	} );

	$notesModalClose.on( 'click', function () {
		closeModal( $notesModal );
	} );

	$notesModal.find( '.wpum-modal-backdrop' ).on( 'click', function () {
		closeModal( $notesModal );
	} );

	// Bulk note action trigger
	$bulkNoteClose.add( $bulkNoteCancel ).on( 'click', function () {
		closeModal( $bulkNoteModal );
	} );

	$bulkNoteModal.find( '.wpum-modal-backdrop' ).on( 'click', function () {
		closeModal( $bulkNoteModal );
	} );

	$bulkNoteSave.on( 'click', function () {
		var text = $.trim( $bulkNoteText.val() );
		var ids  = getSelectedIds();

		if ( ! text ) {
			alert( 'Please enter some note text.' );
			return;
		}

		if ( ! ids.length ) {
			alert( wpum_ajax.select_users );
			return;
		}

		$bulkNoteSave.prop( 'disabled', true ).text( 'Processing…' );

		$.ajax( {
			url:    wpum_ajax.ajax_url,
			type:   'POST',
			data:   {
				action:   'wpum_bulk_add_note',
				nonce:    wpum_ajax.nonce,
				user_ids: ids,
				note:     text
			},
			success: function ( response ) {
				$bulkNoteSave.prop( 'disabled', false ).text( 'Add Note to Selected' );
				if ( response.success ) {
					closeModal( $bulkNoteModal );
					showNotice( response.data.message, 'success' );
					// Reload to refresh note counts
					setTimeout( function () { window.location.reload(); }, 1200 );
				} else {
					alert( response.data.message );
				}
			},
			error: function () {
				$bulkNoteSave.prop( 'disabled', false ).text( 'Add Note to Selected' );
				alert( 'An error occurred while bulk adding notes.' );
			}
		} );
	} );

	// Hook bulk_note action into Apply Bulk action listener
	$applyBulk.on( 'click', function () {
		var action  = $bulkAction.val();
		var ids     = getSelectedIds();
		if ( 'bulk_note' === action && ids.length ) {
			openModal( $bulkNoteModal );
		}
	} );

	// =========================================================================
	// Smart Segments / Saved Templates Handlers
	// =========================================================================
	var $saveSegmentModal   = $( '#wpum-save-segment-modal' );
	var $saveSegmentClose   = $( '#wpum-save-segment-close' );
	var $saveSegmentCancel  = $( '#wpum-save-segment-cancel' );
	var $saveSegmentConfirm = $( '#wpum-save-segment-confirm' );
	var $segmentSelect      = $( '#wpum-segment-select' );
	var $deleteSegmentBtn   = $( '#wpum-delete-segment-btn' );
	var $saveSegmentTrigger = $( '#wpum-save-segment-trigger' );
	var $segmentNameInput   = $( '#wpum-segment-name' );
	var $segmentLimitMsg    = $( '#wpum-segment-limit-msg' );

	// If a saved segment was pre-selected (via URL matching params), show the delete button
	function checkSegmentSelection() {
		var selectedVal = $segmentSelect.val();
		if ( selectedVal ) {
			$deleteSegmentBtn.show();
		} else {
			$deleteSegmentBtn.hide();
		}
	}

	// Try to match URL query parameters to one of the saved segments on load
	function matchUrlToSegment() {
		var urlParams = new URLSearchParams( window.location.search );
		var matched = false;

		$segmentSelect.find( 'option' ).each( function () {
			var $opt = $( this );
			var paramsData = $opt.data( 'params' );
			if ( ! paramsData ) { return; }

			// Compare keys
			var match = true;
			$.each( paramsData, function ( key, val ) {
				var urlVal = urlParams.get( key ) || '';
				// Normalize 's' search field
				if ( 's' === key ) {
					urlVal = urlParams.get( 's' ) || '';
				}
				if ( String( val ) !== String( urlVal ) ) {
					match = false;
					return false; // break loop
				}
			} );

			if ( match ) {
				$segmentSelect.val( $opt.val() );
				matched = true;
				return false; // break loop
			}
		} );

		checkSegmentSelection();
	}

	matchUrlToSegment();

	// Segment selected change
	$segmentSelect.on( 'change', function () {
		var $opt = $( this ).find( 'option:selected' );
		var params = $opt.data( 'params' );

		if ( ! params ) {
			// Clear segment parameters and reload page
			var url = new URL( window.location.href );
			var keys = [ 'role', 's', 'date_from', 'date_to', 'last_login', 'inactive', 'post_count', 'orders', 'paged' ];
			$.each( keys, function ( i, key ) {
				url.searchParams.delete( key );
			} );
			window.location.href = url.toString();
			return;
		}

		// Navigate to URL with segment parameters
		var redirectUrl = new URL( window.location.href );
		redirectUrl.searchParams.set( 'paged', '1' ); // reset paging

		// Clear old values first
		var keys = [ 'role', 's', 'date_from', 'date_to', 'last_login', 'inactive', 'post_count', 'orders' ];
		$.each( keys, function ( i, key ) {
			redirectUrl.searchParams.delete( key );
		} );

		// Set segment values
		$.each( params, function ( key, val ) {
			if ( val ) {
				redirectUrl.searchParams.set( key, val );
			}
		} );

		window.location.href = redirectUrl.toString();
	} );

	// Open Save Segment modal
	$saveSegmentTrigger.on( 'click', function () {
		$segmentNameInput.val( '' );
		$segmentLimitMsg.empty();
		$saveSegmentConfirm.prop( 'disabled', false );

		// Check count of currently saved segments to show warning early if free tier
		var segmentCount = $segmentSelect.find( 'option' ).length - 1; // subtract default empty option
		if ( ! wpum_ajax.is_pro && segmentCount >= 1 ) {
			$segmentLimitMsg.html(
				'<div style="background:#fcf0ec; border-left:4px solid #d54e21; padding:10px; font-weight:600; color:#50575e;">' +
					'Free version is limited to 1 saved template. ' +
					'<a href="admin.php?page=clicks-user-manager-about">Upgrade to Pro</a> for unlimited templates.' +
				'</div>'
			);
			$saveSegmentConfirm.prop( 'disabled', true );
		}

		openModal( $saveSegmentModal );
	} );

	$saveSegmentClose.add( $saveSegmentCancel ).on( 'click', function () {
		closeModal( $saveSegmentModal );
	} );

	$saveSegmentModal.find( '.wpum-modal-backdrop' ).on( 'click', function () {
		closeModal( $saveSegmentModal );
	} );

	// Confirm save segment
	$saveSegmentConfirm.on( 'click', function () {
		var name = $.trim( $segmentNameInput.val() );
		if ( ! name ) {
			alert( 'Please enter a name for the segment.' );
			return;
		}

		// Gather current filter values from the form
		var params = {};
		var role       = $( '#wpum-filter-role' ).val();
		var search     = $( '#wpum-search' ).val();
		var dateFrom   = $( 'input[name="date_from"]' ).val();
		var dateTo     = $( 'input[name="date_to"]' ).val();
		var lastLogin  = $( '#wpum-filter-last-login' ).val();
		var inactive   = $( '#wpum-filter-inactive' ).val();
		var postCount  = $( '#wpum-filter-post-count' ).val();
		var orders     = $( '#wpum-filter-orders' ).val();

		if ( role ) params.role = role;
		if ( search ) params.s = search;
		if ( dateFrom ) params.date_from = dateFrom;
		if ( dateTo ) params.date_to = dateTo;
		if ( lastLogin ) params.last_login = lastLogin;
		if ( inactive ) params.inactive = inactive;
		if ( postCount ) params.post_count = postCount;
		if ( orders ) params.orders = orders;

		$saveSegmentConfirm.prop( 'disabled', true ).text( 'Saving…' );

		$.ajax( {
			url:    wpum_ajax.ajax_url,
			type:   'POST',
			data:   {
				action: 'wpum_save_segment',
				nonce:  wpum_ajax.nonce,
				name:   name,
				params: params
			},
			success: function ( response ) {
				$saveSegmentConfirm.text( 'Save Template' );
				if ( response.success ) {
					closeModal( $saveSegmentModal );
					showNotice( response.data.message, 'success' );
					
					// Rebuild dropdown values
					$segmentSelect.empty().append( '<option value="">— Load Saved Segment —</option>' );
					$.each( response.data.segments, function ( i, seg ) {
						var $opt = $( '<option>', { value: seg.id, text: seg.name } );
						$opt.attr( 'data-params', JSON.stringify( seg.params ) );
						$segmentSelect.append( $opt );
					} );

					// Pre-select the new one
					$segmentSelect.val( response.data.segment.id );
					checkSegmentSelection();
				} else {
					alert( response.data.message );
					$saveSegmentConfirm.prop( 'disabled', false );
				}
			},
			error: function () {
				$saveSegmentConfirm.prop( 'disabled', false ).text( 'Save Template' );
				alert( 'An error occurred while saving the template.' );
			}
		} );
	} );

	// Delete segment action
	$deleteSegmentBtn.on( 'click', function () {
		var segmentId = $segmentSelect.val();
		if ( ! segmentId ) { return; }

		if ( ! confirm( 'Are you sure you want to delete this saved filter template?' ) ) {
			return;
		}

		$deleteSegmentBtn.prop( 'disabled', true );

		$.ajax( {
			url:    wpum_ajax.ajax_url,
			type:   'POST',
			data:   {
				action:     'wpum_delete_segment',
				nonce:      wpum_ajax.nonce,
				segment_id: segmentId
			},
			success: function ( response ) {
				$deleteSegmentBtn.prop( 'disabled', false );
				if ( response.success ) {
					showNotice( response.data.message, 'success' );
					
					// Rebuild dropdown
					$segmentSelect.empty().append( '<option value="">— Load Saved Segment —</option>' );
					$.each( response.data.segments, function ( i, seg ) {
						var $opt = $( '<option>', { value: seg.id, text: seg.name } );
						$opt.attr( 'data-params', JSON.stringify( seg.params ) );
						$segmentSelect.append( $opt );
					} );

					$segmentSelect.val( '' );
					checkSegmentSelection();
				} else {
					alert( response.data.message );
				}
			},
			error: function () {
				$deleteSegmentBtn.prop( 'disabled', false );
				alert( 'Failed to delete template.' );
			}
		} );
	} );

	// =========================================================================
	// Quick Edit Drawer Handlers
	// =========================================================================
	var $drawer          = $( '#wpum-quick-edit-drawer' );
	var $backdrop        = $( '#wpum-quick-edit-backdrop' );
	var $qeClose         = $( '#wpum-quick-edit-close' );
	var $qeCancel        = $( '#wpum-qe-cancel-btn' );
	var $qeSave          = $( '#wpum-qe-save-btn' );
	var $qeSpinner       = $( '#wpum-qe-spinner' );
	var $qeForm          = $( '#wpum-quick-edit-form' );

	var $qeUserId        = $( '#wpum-qe-user-id' );
	var $qeUsername      = $( '#wpum-qe-username' );
	var $qeEmail         = $( '#wpum-qe-email' );
	var $qeFirstName     = $( '#wpum-qe-first-name' );
	var $qeLastName      = $( '#wpum-qe-last-name' );
	var $qeDisplayName   = $( '#wpum-qe-display-name' );
	var $qeRole          = $( '#wpum-qe-role' );
	var $qeMetaSection   = $( '#wpum-qe-meta-section' );
	var $qeFullEditLink  = $( '#wpum-qe-full-edit-link' );

	var deletedMetaKeys = [];

	function openDrawer() {
		$drawer.addClass( 'is-open' );
		$backdrop.addClass( 'is-open' );
		$body.css( 'overflow', 'hidden' );
	}

	function closeDrawer() {
		$drawer.removeClass( 'is-open' );
		$backdrop.removeClass( 'is-open' );
		$body.css( 'overflow', '' );
	}

	// Close drawer on escape key
	$( document ).on( 'keydown', function ( e ) {
		if ( 27 === e.which ) {
			closeDrawer();
		}
	} );

	$qeClose.add( $qeCancel ).add( $backdrop ).on( 'click', function () {
		closeDrawer();
	} );

	// Quick edit trigger click
	$table.on( 'click', '.wpum-quick-edit-trigger', function () {
		var uid   = $( this ).data( 'user-id' );
		var uname = $( this ).data( 'username' );

		$qeUserId.val( uid );
		$qeUsername.text( uname );
		$qeEmail.val( '' );
		$qeFirstName.val( '' );
		$qeLastName.val( '' );
		$qeDisplayName.val( '' );
		$qeRole.val( '' );
		$qeMetaSection.html( '<span class="wpum-spinner is-active" style="float:none; margin:10px auto; display:block;"></span>' );
		$qeFullEditLink.attr( 'href', 'user-edit.php?user_id=' + uid );
		deletedMetaKeys = [];

		openDrawer();

		$.ajax( {
			url:    wpum_ajax.ajax_url,
			type:   'POST',
			data:   {
				action:  'wpum_get_quick_edit',
				nonce:   wpum_ajax.nonce,
				user_id: uid
			},
			success: function ( response ) {
				if ( response.success ) {
					var u = response.data.user;
					$qeEmail.val( u.user_email );
					$qeFirstName.val( u.first_name );
					$qeLastName.val( u.last_name );
					$qeDisplayName.val( u.display_name );
					$qeRole.val( u.role );

					// Render meta section
					renderQEFields( response.data.meta, response.data.is_pro );
				} else {
					$qeMetaSection.html( '<p class="error">' + response.data.message + '</p>' );
				}
			},
			error: function () {
				$qeMetaSection.html( '<p class="error">Failed to load user details.</p>' );
			}
		} );
	} );

	function renderQEFields( meta, isPro ) {
		$qeMetaSection.empty();

		if ( ! isPro ) {
			// Lock message
			$qeMetaSection.append(
				'<div style="background:#fcf0ec; border-left:4px solid #d54e21; padding:8px 12px; margin-bottom:12px; font-size:12px; font-weight:600; color:#50575e;">' +
					'🔒 Meta editing is a Pro Feature. ' +
					'<a href="admin.php?page=clicks-user-manager-about">Upgrade to Pro</a> to add/edit custom fields.' +
				'</div>'
			);
		}

		var count = 0;
		$.each( meta, function ( key, val ) {
			count++;
			var $row = $( '<div class="wpum-meta-edit-row">' );
			
			// Label/Key
			$row.append( $( '<strong>', { text: key, style: 'width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px;' } ) );
			
			// Value field
			var $valInput = $( '<input>', {
				type: 'text',
				class: 'wpum-qe-meta-input',
				'data-key': key,
				value: val,
				disabled: ! isPro
			} );
			$row.append( $valInput );

			// Delete button (Pro only)
			if ( isPro ) {
				var $delBtn = $( '<button>', {
					type: 'button',
					class: 'wpum-meta-delete-btn',
					html: '&times;',
					title: 'Delete metadata'
				} ).on( 'click', function () {
					deletedMetaKeys.push( key );
					$row.fadeOut( 200, function () { $( this ).remove(); } );
				} );
				$row.append( $delBtn );
			}

			$qeMetaSection.append( $row );
		} );

		if ( count === 0 && isPro ) {
			$qeMetaSection.append( '<p class="description wpum-no-meta-msg">No custom metadata for this user.</p>' );
		}

		// Add meta key form (Pro only)
		if ( isPro ) {
			var $addWrap = $( '<div class="wpum-add-meta-wrap">' );
			var $newKey  = $( '<input>', { type: 'text', placeholder: 'New key…', id: 'wpum-new-meta-key' } );
			var $newVal  = $( '<input>', { type: 'text', placeholder: 'New value…', id: 'wpum-new-meta-value' } );
			var $addBtn  = $( '<button>', {
				type: 'button',
				class: 'button button-secondary button-small',
				text: 'Add Field',
				style: 'font-size: 11px;'
			} ).on( 'click', function () {
				var k = $.trim( $newKey.val() ).toLowerCase().replace( /[^a-z0-9_]/g, '' );
				var v = $.trim( $newVal.val() );
				if ( ! k ) {
					alert( 'Please enter a valid meta key (alphanumeric and underscore only).' );
					return;
				}
				
				// Check if exists
				if ( $( '.wpum-qe-meta-input[data-key="' + k + '"]' ).length ) {
					alert( 'Key already exists.' );
					return;
				}

				// Append new row
				var $row = $( '<div class="wpum-meta-edit-row">' );
				$row.append( $( '<strong>', { text: k, style: 'width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px;' } ) );
				var $valInput = $( '<input>', {
					type: 'text',
					class: 'wpum-qe-meta-input',
					'data-key': k,
					value: v
				} );
				$row.append( $valInput );
				var $delBtn = $( '<button>', {
					type: 'button',
					class: 'wpum-meta-delete-btn',
					html: '&times;',
					title: 'Delete metadata'
				} ).on( 'click', function () {
					$row.remove();
				} );
				$row.append( $delBtn );

				$( '.wpum-no-meta-msg' ).remove();
				$addWrap.before( $row );
				$newKey.val( '' );
				$newVal.val( '' );
			} );

			$addWrap.append( $newKey ).append( $newVal ).append( $addBtn );
			$qeMetaSection.append( $addWrap );
		}
	}

	// Save Quick Edit changes
	$qeSave.on( 'click', function () {
		if ( ! $qeForm[0].reportValidity() ) {
			return;
		}

		$qeSave.prop( 'disabled', true );
		$qeSpinner.addClass( 'is-active' );

		// Compile core details
		var userData = {
			ID:           $qeUserId.val(),
			user_email:   $qeEmail.val(),
			first_name:   $qeFirstName.val(),
			last_name:    $qeLastName.val(),
			display_name: $qeDisplayName.val(),
			role:         $qeRole.val()
		};

		// Compile meta updates
		var metaData = {};
		$( '.wpum-qe-meta-input' ).each( function () {
			var $input = $( this );
			metaData[ $input.data( 'key' ) ] = $input.val();
		} );

		$.ajax( {
			url:    wpum_ajax.ajax_url,
			type:   'POST',
			data:   {
				action:       'wpum_save_quick_edit',
				nonce:        wpum_ajax.nonce,
				user_data:    userData,
				meta_data:    metaData,
				deleted_meta: deletedMetaKeys
			},
			success: function ( response ) {
				$qeSave.prop( 'disabled', false );
				$qeSpinner.removeClass( 'is-active' );

				if ( response.success ) {
					closeDrawer();
					showNotice( response.data.message, 'success' );
					
					// Reload row updates
					setTimeout( function () { window.location.reload(); }, 1200 );
				} else {
					alert( response.data.message );
				}
			},
			error: function () {
				$qeSave.prop( 'disabled', false );
				$qeSpinner.removeClass( 'is-active' );
				alert( 'An error occurred while saving.' );
			}
		} );
	} );

	// =========================================================================
	// Advanced Filters Toggle Handlers
	// =========================================================================
	var $advFiltersBtn   = $( '#wpum-toggle-adv-filters' );
	var $advFiltersPanel = $( '#wpum-adv-filters-panel' );

	$advFiltersBtn.on( 'click', function ( e ) {
		e.preventDefault();
		$advFiltersPanel.slideToggle( 200 );
	} );

	// Auto-expand advanced filters panel if any advanced parameters are active in URL
	function autoExpandAdvFilters() {
		var urlParams = new URLSearchParams( window.location.search );
		var advKeys   = [ 'login_from', 'login_to', 'ltv_min', 'ltv_max', 'aov_min', 'aov_max', 'meta_key', 'meta_value' ];
		var hasActive = false;

		$.each( advKeys, function ( i, key ) {
			if ( urlParams.get( key ) ) {
				hasActive = true;
				return false; // break loop
			}
		} );

		if ( hasActive ) {
			$advFiltersPanel.show();
		}
	}

	autoExpandAdvFilters();

	// =========================================================================
	// Scheduled Exports Handlers
	// =========================================================================
	var $schedForm        = $( '#wpum-schedule-form' );
	var $schedEnabled     = $( '#wpum-sched-enabled' );
	var $schedDest        = $( '#wpum-sched-dest' );
	var $schedSave        = $( '#wpum-save-schedule' );
	var $schedSpinner     = $( '#wpum-sched-spinner' );
	var $schedStatus      = $( '#wpum-sched-status' );

	function toggleSchedFields() {
		if ( ! $schedForm.length ) return;
		var isEnabled = $schedEnabled.prop( 'checked' );
		var dest = $schedDest.val();

		if ( isEnabled ) {
			$( '.wpum-sched-field' ).show();
			if ( 'email' === dest ) {
				$( '.wpum-sched-dest-email' ).show();
				$( '.wpum-sched-dest-webhook' ).hide();
			} else {
				$( '.wpum-sched-dest-email' ).hide();
				$( '.wpum-sched-dest-webhook' ).show();
			}
		} else {
			$( '.wpum-sched-field' ).hide();
		}
		// Always show enabled checkbox field itself
		$schedEnabled.closest( 'tr' ).show();
	}

	if ( $schedForm.length ) {
		toggleSchedFields();

		$schedEnabled.on( 'change', function () {
			toggleSchedFields();
		} );

		$schedDest.on( 'change', function () {
			toggleSchedFields();
		} );

		$schedSave.on( 'click', function () {
			var enabled = $schedEnabled.prop( 'checked' ) ? '1' : '0';
			var frequency = $( '#wpum-sched-freq' ).val();
			var segment = $( '#wpum-sched-segment' ).val();
			var dest = $schedDest.val();
			var email = $.trim( $( '#wpum-sched-email' ).val() );
			var webhook = $.trim( $( '#wpum-sched-webhook' ).val() );
			
			var cols = [];
			$( 'input[name="sched_cols[]"]:checked' ).each( function () {
				cols.push( $( this ).val() );
			} );

			if ( '1' === enabled ) {
				if ( 'email' === dest && ! email ) {
					alert( 'Please enter a recipient email address.' );
					return;
				}
				if ( 'webhook' === dest && ! webhook ) {
					alert( 'Please enter a webhook URL.' );
					return;
				}
				if ( ! cols.length ) {
					alert( 'Please select at least one column to include in the scheduled export.' );
					return;
				}
			}

			$schedSpinner.show();
			$schedStatus.text( 'Saving settings…' );
			$schedSave.prop( 'disabled', true );

			$.ajax( {
				url:    wpum_ajax.ajax_url,
				type:   'POST',
				data:   {
					action:    'wpum_save_export_schedule',
					nonce:     wpum_ajax.nonce,
					enabled:   enabled,
					frequency: frequency,
					segment:   segment,
					dest:      dest,
					email:     email,
					webhook:   webhook,
					cols:      cols
				},
				success: function ( response ) {
					$schedSpinner.hide();
					$schedSave.prop( 'disabled', false );

					if ( response.success ) {
						$schedStatus.text( response.data.message );
						showNotice( response.data.message, 'success' );
					} else {
						$schedStatus.text( 'Failed to save.' );
						alert( response.data.message );
					}
					setTimeout( function () { $schedStatus.text( '' ); }, 3000 );
				},
				error: function () {
					$schedSpinner.hide();
					$schedSave.prop( 'disabled', false );
					$schedStatus.text( 'An error occurred.' );
					alert( 'Failed to update schedule settings. Please try again.' );
					setTimeout( function () { $schedStatus.text( '' ); }, 3000 );
				}
			} );
		} );
	}

} )( jQuery );
