<?php
/**
 * Magic Login settings UI (dedicated admin page under WP PowerSuite).
 *
 * @package MagicLogin
 */

namespace MagicLogin;

use WP_PowerSuite\Core\ModuleManager;
use WP_PowerSuite\Core\NetworkScope;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

require_once __DIR__ . '/includes/class-link-repository.php';

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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'magic-login' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Magic Login requires an active license. Activate your license to configure passwordless login links, codes, and QR sign-in.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! isset( $module_id ) ) {
	$module_id = 'magic-login';
}

$defaults = Module::getDefaultSettings();
$settings = $defaults;
if ( class_exists( ModuleManager::class ) ) {
	$mod = ModuleManager::getInstance()->getModule( 'magic-login' );
	if ( $mod instanceof Module ) {
		$settings = $mod->getSettings();
	}
} else {
	$raw      = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
	$settings = is_array( $raw ) ? wp_parse_args( $raw, $defaults ) : $defaults;
}

$allowed_roles_saved = isset( $settings['allowed_roles'] ) && is_array( $settings['allowed_roles'] ) ? $settings['allowed_roles'] : [];

if ( ! function_exists( 'wp_roles' ) ) {
	require_once ABSPATH . 'wp-admin/includes/user.php';
}

$all_roles = wp_roles()->roles;
uksort(
	$all_roles,
	static function ( $a, $b ) {
		$core = [ 'administrator' => 0, 'editor' => 1, 'author' => 2, 'contributor' => 3, 'subscriber' => 4 ];
		$ia   = $core[ $a ] ?? 100;
		$ib   = $core[ $b ] ?? 100;
		return $ia === $ib ? strcasecmp( $a, $b ) : $ia <=> $ib;
	}
);

$wc_active              = class_exists( 'WooCommerce' );
$woo_login_form         = ! empty( $settings['woo_login_form'] );
$simple_available       = OptionStoreModuleSettingsRepository::isModuleEnabled( 'simple-captcha' );
$recaptcha_available    = OptionStoreModuleSettingsRepository::isModuleEnabled( 'google-recaptcha' );
$turnstile_available    = OptionStoreModuleSettingsRepository::isModuleEnabled( 'cloudflare-turnstile' );
$two_fa_available       = OptionStoreModuleSettingsRepository::isModuleEnabled( 'two-factor-authentication' );
$wp_registration_on    = (bool) get_option( 'users_can_register' );

$captcha_provider = sanitize_key( (string) ( $settings['captcha_provider'] ?? 'none' ) );

$ml_repo  = new LinkRepository();
$ml_stats = $ml_repo->getStats();

require_once __DIR__ . '/includes/class-magic-login-activity-list-table.php';

$activity_status = isset( $_GET['activity_status'] ) ? sanitize_key( wp_unslash( (string) $_GET['activity_status'] ) ) : 'all';
if ( ! in_array( $activity_status, [ 'all', 'used', 'pending', 'expired' ], true ) ) {
	$activity_status = 'all';
}
$activity_search = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( (string) $_REQUEST['s'] ) ) : '';

if (
	isset( $_SERVER['REQUEST_METHOD'] )
	&& strtoupper( sanitize_text_field( wp_unslash( (string) $_SERVER['REQUEST_METHOD'] ) ) ) === 'POST'
	&& isset( $_POST['page'] )
	&& sanitize_key( wp_unslash( (string) $_POST['page'] ) ) === 'powersuite-magic-login'
	&& empty( $_POST['ml_activity'] )
	&& ( ! isset( $_POST['action'] ) || sanitize_key( wp_unslash( (string) $_POST['action'] ) ) === '-1' )
	&& ( ! isset( $_POST['action2'] ) || sanitize_key( wp_unslash( (string) $_POST['action2'] ) ) === '-1' )
) {
	$search_redirect = [
		'page'            => 'powersuite-magic-login',
		'activity_status' => $activity_status,
	];
	if ( isset( $_POST['s'] ) ) {
		$search_redirect['s'] = sanitize_text_field( wp_unslash( (string) $_POST['s'] ) );
	}
	wp_safe_redirect( add_query_arg( $search_redirect, admin_url( 'admin.php' ) ) );
	exit;
}

if ( NetworkScope::canManagePlugin() ) {
	$single_action = isset( $_GET['ml_activity_action'] ) ? sanitize_key( wp_unslash( (string) $_GET['ml_activity_action'] ) ) : '';
	$single_id     = isset( $_GET['ml_activity_id'] ) ? absint( $_GET['ml_activity_id'] ) : 0;
	if ( $single_action === 'delete' && $single_id > 0 && wp_verify_nonce( sanitize_text_field( wp_unslash( (string) ( $_GET['_wpnonce'] ?? '' ) ) ), 'wpps_ml_delete_activity_' . $single_id ) ) {
		$ml_repo->deleteRowsByIds( [ $single_id ] );
		wp_safe_redirect(
			add_query_arg(
				[
					'page'            => 'powersuite-magic-login',
					'ml_bulk'         => 'deleted_1',
					'activity_status' => $activity_status,
					's'               => $activity_search,
				],
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	$bulk_action = isset( $_POST['action'] ) && $_POST['action'] !== '-1'
		? sanitize_key( wp_unslash( (string) $_POST['action'] ) )
		: ( isset( $_POST['action2'] ) && $_POST['action2'] !== '-1' ? sanitize_key( wp_unslash( (string) $_POST['action2'] ) ) : '' );
	$bulk_ids = isset( $_POST['ml_activity'] ) && is_array( $_POST['ml_activity'] )
		? array_values( array_filter( array_map( 'absint', wp_unslash( $_POST['ml_activity'] ) ) ) )
		: [];
	if ( $bulk_action && $bulk_ids !== [] && check_admin_referer( 'bulk-ml-activities' ) ) {
		$count = 0;
		if ( $bulk_action === 'delete' ) {
			$count = $ml_repo->deleteRowsByIds( $bulk_ids );
		} elseif ( $bulk_action === 'revoke' ) {
			$count = $ml_repo->revokeRowsByIds( $bulk_ids );
		}
		wp_safe_redirect(
			add_query_arg(
				[
					'page'            => 'powersuite-magic-login',
					'ml_bulk'         => sanitize_key( $bulk_action . '_' . $count ),
					'activity_status' => $activity_status,
					's'               => $activity_search,
				],
				admin_url( 'admin.php' )
			)
		);
		exit;
	}
}

$activity_list_table = new Activity_List_Table( $ml_repo, $activity_status, $activity_search );
$activity_list_table->prepare_items();

/**
 * @param mixed $v
 */
$cb = static function ( $v ): bool {
	return ! empty( $v );
};

if ( ! function_exists( __NAMESPACE__ . '\\wpps_ml_accordion_open' ) ) {
	/**
	 * @param string $id    Accordion slug.
	 * @param string $title Section title.
	 * @param string $tip   Tooltip copy (Code Snippets accordion style).
	 * @param bool   $open  Initially expanded.
	 */
	function wpps_ml_accordion_open( string $id, string $title, string $tip, bool $open = false ): void {
		$open_class = $open ? ' is-open' : '';
		$expanded   = $open ? 'true' : 'false';
		?>
		<div class="wpps-cs-accordion<?php echo esc_attr( $open_class ); ?>" data-accordion-id="<?php echo esc_attr( $id ); ?>">
			<button type="button" class="wpps-cs-accordion-header" aria-expanded="<?php echo esc_attr( $expanded ); ?>" aria-controls="wpps-ml-accordion-<?php echo esc_attr( $id ); ?>">
				<span class="wpps-cs-accordion-title">
					<?php echo esc_html( $title ); ?>
					<span class="wpps-cs-accordion-tooltip" aria-label="<?php esc_attr_e( 'Help', 'wp-powersuite' ); ?>">
						<span class="wpps-cs-accordion-tooltip-trigger">?</span>
						<span class="wpps-cs-accordion-tooltip-panel"><?php echo esc_html( $tip ); ?></span>
					</span>
				</span>
				<span class="dashicons dashicons-arrow-down-alt2 wpps-cs-accordion-chevron"></span>
			</button>
			<div id="wpps-ml-accordion-<?php echo esc_attr( $id ); ?>" class="wpps-cs-accordion-body">
		<?php
	}

	function wpps_ml_accordion_close(): void {
		echo '</div></div>';
	}
}

$module_enabled = $module_enabled ?? OptionStoreModuleSettingsRepository::isModuleEnabled( $module_id  );
$powersuite_url = $powersuite_url ?? admin_url( 'admin.php?page=powersuite' );

?>
<div class="wrap wpps-cs-wrap">
	<hr class="wp-header-end">

	<?php
	\WP_PowerSuite\Admin\PageHero::render_for_module(
		[
			'icon'      => 'dashicons-email-alt',
			'title'     => __( 'Magic Login', 'wp-powersuite' ),
			'tagline'   => __( 'Passwordless sign-in with magic links, QR codes, one-time codes, and optional registration.', 'wp-powersuite' ),
			'meta_html' => '<button type="button" id="wpps-ml-save-settings" class="button button-primary">' . esc_html__( 'Save settings', 'wp-powersuite' ) . '</button>',
		]
	);
	?>

	<?php if ( ! $module_enabled ) : ?>
		<div class="notice notice-warning">
			<p>
				<strong><?php esc_html_e( 'Magic Login is disabled.', 'wp-powersuite' ); ?></strong>
				<?php esc_html_e( 'Enable the module on the PowerSuite modules screen for magic links to work on your site.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $powersuite_url ); ?>"><?php esc_html_e( 'Open modules', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	<?php endif; ?>

	<?php if ( ! is_ssl() ) : ?>
		<div class="notice notice-warning">
			<p>
				<strong><?php esc_html_e( 'HTTPS recommended', 'wp-powersuite' ); ?></strong>
				<?php esc_html_e( 'Magic login links and codes are safer over HTTPS. Enable SSL on your site so login links are not sent or opened over plain HTTP.', 'wp-powersuite' ); ?>
			</p>
		</div>
	<?php endif; ?>

	<div id="wpps-ml-toast" class="wpps-cs-toast" role="status" aria-live="polite" aria-atomic="true" aria-hidden="true">
		<span id="wpps-ml-toast-message"></span>
	</div>

	<div class="wpps-cs-accordions">
	<form id="wpps-magic-login-settings-form" class="wp-powersuite-module-settings-form wpps-magic-login-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>" onsubmit="return false;">
		<?php
		wpps_ml_accordion_open(
			'general',
			__( 'General', 'wp-powersuite' ),
			__( 'wp-login integration, link expiry, and allowed roles.', 'wp-powersuite' ),
			true
		);
		?>
			<div class="wpps-ml-form-panel">
				<div class="wpps-ml-form-card">
					<h3 class="wpps-ml-form-panel-title"><?php esc_html_e( 'Login form', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-form-panel-desc"><?php esc_html_e( 'wp-login integration, link expiry, and which roles may use Magic Login.', 'wp-powersuite' ); ?></p>

					<div class="wpps-ml-form-grid wpps-ml-form-grid-2col">
						<div class="wpps-ml-form-group">
							<label class="wpps-ml-form-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="show_on_login" value="1" <?php checked( $cb( $settings['show_on_login'] ?? true ) ); ?> />
								<?php esc_html_e( 'Show “Email me a login link” on wp-login.php.', 'wp-powersuite' ); ?>
							</label>
						</div>
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_expiry' ); ?>"><?php esc_html_e( 'Link expiry', 'wp-powersuite' ); ?></label>
							<div class="wpps-ml-form-inline-suffix">
								<input type="number" min="5" max="60" step="1" class="wpps-ml-form-input wp-powersuite-advanced-setting" data-setting-key="expiry_minutes" id="<?php echo esc_attr( $module_id . '_expiry' ); ?>" value="<?php echo esc_attr( (string) ( $settings['expiry_minutes'] ?? 15 ) ); ?>" />
								<span class="wpps-ml-form-help"><?php esc_html_e( 'minutes (5–60)', 'wp-powersuite' ); ?></span>
							</div>
						</div>
					</div>

					<div class="wpps-ml-form-grid">
						<div class="wpps-ml-form-group wpps-ml-form-full">
							<span class="wpps-ml-form-group-label"><?php esc_html_e( 'Allowed roles', 'wp-powersuite' ); ?></span>
							<?php if ( empty( $all_roles ) ) : ?>
								<p class="wpps-ml-form-help"><?php esc_html_e( 'No roles found.', 'wp-powersuite' ); ?></p>
							<?php else : ?>
								<p class="wpps-ml-form-help"><?php esc_html_e( 'Roles that may use Magic Login. When every role is selected, all roles are allowed (same as the default).', 'wp-powersuite' ); ?></p>
								<div class="wpps-ct-multiselect" id="<?php echo esc_attr( $module_id ); ?>_allowed_roles_ms"
									data-label-none="<?php echo esc_attr( __( 'Select roles…', 'wp-powersuite' ) ); ?>"
									data-label-single="<?php echo esc_attr( __( '1 selected', 'wp-powersuite' ) ); ?>"
									data-label-multi="<?php echo esc_attr( __( '%d selected', 'wp-powersuite' ) ); ?>">
									<button type="button" class="wpps-ct-multiselect__trigger" aria-expanded="false" aria-haspopup="listbox" aria-controls="<?php echo esc_attr( $module_id ); ?>_allowed_roles_list">
										<span class="wpps-ct-multiselect__trigger-text"><?php esc_html_e( 'Select roles…', 'wp-powersuite' ); ?></span>
										<span class="dashicons dashicons-arrow-down-alt2 wpps-ct-multiselect__chevron"></span>
									</button>
									<div class="wpps-ct-multiselect__dropdown" id="<?php echo esc_attr( $module_id ); ?>_allowed_roles_list" role="listbox" hidden>
										<input type="text" class="wpps-ct-multiselect__search" placeholder="<?php esc_attr_e( 'Search roles…', 'wp-powersuite' ); ?>" autocomplete="off" />
										<div class="wpps-ct-multiselect__actions">
											<button type="button" class="wpps-ct-multiselect__action" data-action="select-all"><?php esc_html_e( 'Select all', 'wp-powersuite' ); ?></button>
											<button type="button" class="wpps-ct-multiselect__action" data-action="clear"><?php esc_html_e( 'Clear', 'wp-powersuite' ); ?></button>
										</div>
										<div class="wpps-ct-multiselect__options">
											<?php foreach ( $all_roles as $role_key => $role_info ) : ?>
												<?php
												$role_key = sanitize_key( $role_key );
												$label    = isset( $role_info['name'] ) ? translate_user_role( $role_info['name'] ) : $role_key;
												$checked  = $allowed_roles_saved === [] || in_array( $role_key, $allowed_roles_saved, true );
												?>
												<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $role_key ); ?>" data-label="<?php echo esc_attr( $label ); ?>">
													<input type="checkbox" name="allowed_roles[]" class="wp-powersuite-advanced-setting" data-setting-key="allowed_roles" value="<?php echo esc_attr( $role_key ); ?>" <?php checked( $checked ); ?> />
													<span class="wpps-ct-multiselect__option-label"><?php echo esc_html( $label ); ?></span>
													<span class="wpps-ct-multiselect__option-slug">(<?php echo esc_html( $role_key ); ?>)</span>
												</label>
											<?php endforeach; ?>
										</div>
									</div>
								</div>
							<?php endif; ?>
						</div>
					</div>
				</div>
			</div>
		<?php
		wpps_ml_accordion_close();
		wpps_ml_accordion_open(
			'features',
			__( 'Features', 'wp-powersuite' ),
			__( 'QR codes, one-time code login, email placeholders, and admin stats.', 'wp-powersuite' )
		);
		?>
			<div class="wpps-ml-form-panel">
				<div class="wpps-ml-form-card">
					<h3 class="wpps-ml-form-panel-title"><?php esc_html_e( 'Email & login', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-form-panel-desc"><?php esc_html_e( 'QR codes, one-time code login, email placeholders, and admin stats.', 'wp-powersuite' ); ?></p>

					<div class="wpps-ml-form-grid wpps-ml-form-grid-2col">
						<div class="wpps-ml-form-group">
							<label class="wpps-ml-form-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="include_qr_code" value="1" <?php checked( $cb( $settings['include_qr_code'] ?? true ) ); ?> />
								<?php esc_html_e( 'Include QR code in magic login emails.', 'wp-powersuite' ); ?>
							</label>
						</div>
						<div class="wpps-ml-form-group">
							<label class="wpps-ml-form-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="enable_code_login" value="1" <?php checked( $cb( $settings['enable_code_login'] ?? true ) ); ?> />
								<?php esc_html_e( 'Enable one-time numeric code login (alternative to the link).', 'wp-powersuite' ); ?>
							</label>
						</div>
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_code_digits' ); ?>"><?php esc_html_e( 'Code length (digits)', 'wp-powersuite' ); ?></label>
							<input type="number" min="6" max="10" step="1" class="wpps-ml-form-input wp-powersuite-advanced-setting" data-setting-key="login_code_digits" id="<?php echo esc_attr( $module_id . '_code_digits' ); ?>" value="<?php echo esc_attr( (string) ( $settings['login_code_digits'] ?? 8 ) ); ?>" />
							<p class="wpps-ml-form-help"><?php esc_html_e( 'Use at least 8 digits for stronger one-time codes.', 'wp-powersuite' ); ?></p>
						</div>
						<div class="wpps-ml-form-group">
							<label class="wpps-ml-form-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="show_users_column_stats" value="1" <?php checked( $cb( $settings['show_users_column_stats'] ?? true ) ); ?> />
								<?php esc_html_e( 'Show Magic Login stats column on Users screen.', 'wp-powersuite' ); ?>
							</label>
						</div>
					</div>

					<div class="wpps-ml-form-grid">
						<div class="wpps-ml-form-group wpps-ml-form-full">
							<label class="wpps-ml-form-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="enable_auto_login" value="1" <?php checked( $cb( $settings['enable_auto_login'] ?? false ) ); ?> />
								<?php esc_html_e( 'Enable {{MAGIC_LINK}}, {{MAGIC_LINK_BUTTON}}, {{MAGIC_LOGIN_QR}} in outgoing emails.', 'wp-powersuite' ); ?>
							</label>
							<p class="wpps-ml-form-help"><?php esc_html_e( 'Only rewrites other WordPress emails that already contain those placeholders. Magic login messages use the standard PowerSuite notification layout.', 'wp-powersuite' ); ?></p>
							<?php if ( ! empty( $settings['enable_auto_login'] ) ) : ?>
								<p class="wpps-ml-form-help" style="color:#b45309;">
									<?php esc_html_e( 'Security note: any email containing these placeholders may embed a live login link for the recipient when they have an account. Use only in trusted templates.', 'wp-powersuite' ); ?>
								</p>
							<?php endif; ?>
						</div>
					</div>
				</div>
			</div>
		<?php
		wpps_ml_accordion_close();
		$ml_style_defaults = [
			'style_bg_color'            => '#ffffff',
			'style_border_color'        => '#e2e8f0',
			'style_title_color'         => '#1e293b',
			'style_desc_color'          => '#64748b',
			'style_input_border_color'  => '#d1d5db',
			'style_button_bg'           => '#3b82f6',
			'style_button_text_color'   => '#ffffff',
			'style_border_radius'       => 12,
			'style_input_border_radius' => 8,
			'style_button_radius'       => 8,
		];
		$normalize_ml_color = static function ( string $val, string $fallback ): string {
			if ( $val === '' ) {
				return $fallback;
			}
			if ( preg_match( '/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/', $val ) ) {
				return strlen( $val ) > 7 ? substr( $val, 0, 7 ) : $val;
			}
			if ( preg_match( '/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/', $val, $m ) ) {
				return sprintf( '#%02x%02x%02x', (int) $m[1], (int) $m[2], (int) $m[3] );
			}
			return $fallback;
		};
		$style_color_fields = [
			'style_bg_color'           => __( 'Card background', 'wp-powersuite' ),
			'style_border_color'       => __( 'Card border', 'wp-powersuite' ),
			'style_title_color'        => __( 'Title text', 'wp-powersuite' ),
			'style_desc_color'         => __( 'Description text', 'wp-powersuite' ),
			'style_input_border_color' => __( 'Input border', 'wp-powersuite' ),
			'style_button_bg'          => __( 'Button background', 'wp-powersuite' ),
			'style_button_text_color'  => __( 'Button text', 'wp-powersuite' ),
		];
		$style_radius_fields = [
			'style_border_radius'       => __( 'Card border radius', 'wp-powersuite' ),
			'style_input_border_radius' => __( 'Input border radius', 'wp-powersuite' ),
			'style_button_radius'       => __( 'Button border radius', 'wp-powersuite' ),
		];
		$sc_mode = sanitize_key( (string) ( $settings['sc_mode'] ?? 'auto' ) );
		wpps_ml_accordion_open(
			'shortcode',
			__( 'Shortcode', 'wp-powersuite' ),
			__( 'Embed and customize the magic login shortcode form.', 'wp-powersuite' )
		);
		?>
			<div class="wpps-ml-sc-panel">
				<p class="wpps-ml-shortcode-callout">
					<?php esc_html_e( 'Add this shortcode to any page, post, or widget:', 'wp-powersuite' ); ?>
					<code>[<?php echo esc_html( Module::SHORTCODE ); ?>]</code>
				</p>

				<div class="wpps-ml-sc-card">
					<h3 class="wpps-ml-sc-panel-title"><?php esc_html_e( 'Form content', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-sc-panel-desc"><?php esc_html_e( 'Labels and behavior for the shortcode login form.', 'wp-powersuite' ); ?></p>

					<div class="wpps-ml-sc-form-grid">
						<div class="wpps-ml-sc-form-group wpps-ml-sc-form-full">
							<label for="<?php echo esc_attr( $module_id . '_sc_mode' ); ?>"><?php esc_html_e( 'Form mode', 'wp-powersuite' ); ?></label>
							<select class="wpps-ml-sc-select wp-powersuite-advanced-setting" data-setting-key="sc_mode" id="<?php echo esc_attr( $module_id . '_sc_mode' ); ?>">
								<option value="auto" <?php selected( $sc_mode, 'auto' ); ?>><?php esc_html_e( 'Auto (login + registration when enabled)', 'wp-powersuite' ); ?></option>
								<option value="login" <?php selected( $sc_mode, 'login' ); ?>><?php esc_html_e( 'Login only', 'wp-powersuite' ); ?></option>
								<option value="register" <?php selected( $sc_mode, 'register' ); ?>><?php esc_html_e( 'Registration only', 'wp-powersuite' ); ?></option>
							</select>
						</div>
					</div>

					<div class="wpps-ml-sc-form-grid wpps-ml-sc-form-grid-2col">
						<div class="wpps-ml-sc-form-group">
							<label for="<?php echo esc_attr( $module_id . '_sc_title' ); ?>"><?php esc_html_e( 'Title', 'wp-powersuite' ); ?></label>
							<input type="text" class="wpps-ml-sc-input wp-powersuite-advanced-setting" data-setting-key="sc_title" id="<?php echo esc_attr( $module_id . '_sc_title' ); ?>" value="<?php echo esc_attr( (string) ( $settings['sc_title'] ?? '' ) ); ?>" />
						</div>
						<div class="wpps-ml-sc-form-group">
							<label for="<?php echo esc_attr( $module_id . '_sc_desc' ); ?>"><?php esc_html_e( 'Description', 'wp-powersuite' ); ?></label>
							<input type="text" class="wpps-ml-sc-input wp-powersuite-advanced-setting" data-setting-key="sc_description" id="<?php echo esc_attr( $module_id . '_sc_desc' ); ?>" value="<?php echo esc_attr( (string) ( $settings['sc_description'] ?? '' ) ); ?>" />
						</div>
					</div>

					<div class="wpps-ml-sc-form-grid wpps-ml-sc-form-grid-3col">
						<div class="wpps-ml-sc-form-group">
							<label for="<?php echo esc_attr( $module_id . '_sc_email_label' ); ?>"><?php esc_html_e( 'Email label', 'wp-powersuite' ); ?></label>
							<input type="text" class="wpps-ml-sc-input wp-powersuite-advanced-setting" data-setting-key="sc_email_label" id="<?php echo esc_attr( $module_id . '_sc_email_label' ); ?>" value="<?php echo esc_attr( (string) ( $settings['sc_email_label'] ?? '' ) ); ?>" />
						</div>
						<div class="wpps-ml-sc-form-group">
							<label for="<?php echo esc_attr( $module_id . '_sc_btn' ); ?>"><?php esc_html_e( 'Button text', 'wp-powersuite' ); ?></label>
							<input type="text" class="wpps-ml-sc-input wp-powersuite-advanced-setting" data-setting-key="sc_button_text" id="<?php echo esc_attr( $module_id . '_sc_btn' ); ?>" value="<?php echo esc_attr( (string) ( $settings['sc_button_text'] ?? '' ) ); ?>" />
						</div>
						<div class="wpps-ml-sc-form-group">
							<label for="<?php echo esc_attr( $module_id . '_sc_ph' ); ?>"><?php esc_html_e( 'Placeholder', 'wp-powersuite' ); ?></label>
							<input type="text" class="wpps-ml-sc-input wp-powersuite-advanced-setting" data-setting-key="sc_placeholder" id="<?php echo esc_attr( $module_id . '_sc_ph' ); ?>" value="<?php echo esc_attr( (string) ( $settings['sc_placeholder'] ?? '' ) ); ?>" />
						</div>
					</div>

					<div class="wpps-ml-sc-form-grid wpps-ml-sc-form-grid-2col">
						<div class="wpps-ml-sc-form-group">
							<label class="wpps-ml-sc-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="sc_show_password_link" value="1" <?php checked( $cb( $settings['sc_show_password_link'] ?? true ) ); ?> />
								<?php esc_html_e( 'Show “Use password instead” link', 'wp-powersuite' ); ?>
							</label>
						</div>
						<div class="wpps-ml-sc-form-group">
							<label class="wpps-ml-sc-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="woo_login_form" value="1" <?php checked( $cb( $settings['woo_login_form'] ?? false ) ); ?> <?php disabled( ! $wc_active ); ?> />
								<?php esc_html_e( 'Show below WooCommerce My Account login', 'wp-powersuite' ); ?>
							</label>
							<?php if ( ! $wc_active ) : ?>
								<p class="wpps-ml-sc-help"><?php esc_html_e( 'Enable WooCommerce to use this option.', 'wp-powersuite' ); ?></p>
							<?php endif; ?>
						</div>
					</div>
				</div>

				<div class="wpps-ml-sc-card">
					<h3 class="wpps-ml-sc-panel-title"><?php esc_html_e( 'Appearance', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-sc-panel-desc"><?php esc_html_e( 'Colors and border radius for the shortcode form card.', 'wp-powersuite' ); ?></p>

					<h4 class="wpps-ml-sc-subsection-title"><?php esc_html_e( 'Colors', 'wp-powersuite' ); ?></h4>
					<div class="wpps-cwe-color-grid wpps-ml-sc-color-grid">
						<?php foreach ( $style_color_fields as $key => $label ) : ?>
							<?php
							$def      = $normalize_ml_color( (string) $ml_style_defaults[ $key ], '#ffffff' );
							$val      = $normalize_ml_color( (string) ( $settings[ $key ] ?? $def ), $def );
							$field_id = $module_id . '_' . $key;
							?>
							<div class="wpps-cwe-color-cell">
								<label for="<?php echo esc_attr( $field_id ); ?>" class="wpps-cwe-color-label"><?php echo esc_html( $label ); ?></label>
								<div class="wpps-color-field-row">
									<input type="color" id="<?php echo esc_attr( $field_id ); ?>" value="<?php echo esc_attr( $val ); ?>" class="wpps-color-picker-circle wp-powersuite-advanced-setting" data-setting-key="<?php echo esc_attr( $key ); ?>" data-default-color="<?php echo esc_attr( $def ); ?>" aria-label="<?php echo esc_attr( $label ); ?>" />
									<div class="wpps-color-code-wrap">
										<input type="text" class="wpps-color-code-input wpps-cwe-input wp-powersuite-advanced-setting" data-setting-key="<?php echo esc_attr( $key ); ?>" data-color-input="<?php echo esc_attr( $field_id ); ?>" data-default-color="<?php echo esc_attr( $def ); ?>" value="<?php echo esc_attr( $val ); ?>" placeholder="<?php echo esc_attr( $def ); ?>" maxlength="9" aria-label="<?php echo esc_attr( $label ); ?>" />
										<button type="button" class="wpps-color-reset button-link" data-default-color="<?php echo esc_attr( $def ); ?>" aria-label="<?php esc_attr_e( 'Reset to default', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-undo"></span></button>
									</div>
								</div>
							</div>
						<?php endforeach; ?>
					</div>

					<h4 class="wpps-ml-sc-subsection-title"><?php esc_html_e( 'Border radius', 'wp-powersuite' ); ?></h4>
					<div class="wpps-ml-radius-grid">
						<?php foreach ( $style_radius_fields as $key => $label ) : ?>
							<?php
							$radius_val = (int) ( $settings[ $key ] ?? $ml_style_defaults[ $key ] );
							$field_id   = $module_id . '_' . $key;
							?>
							<div class="wpps-cwe-field-cell">
								<label for="<?php echo esc_attr( $field_id ); ?>" class="wpps-cwe-color-label"><?php echo esc_html( $label ); ?></label>
								<div class="wpps-ml-radius-field">
									<input type="number" min="0" max="64" step="1" class="wpps-ml-sc-input wpps-cwe-input wp-powersuite-advanced-setting" data-setting-key="<?php echo esc_attr( $key ); ?>" id="<?php echo esc_attr( $field_id ); ?>" value="<?php echo esc_attr( (string) $radius_val ); ?>" />
									<span class="wpps-ml-radius-suffix">px</span>
								</div>
							</div>
						<?php endforeach; ?>
					</div>
				</div>

				<div class="wpps-ml-sc-card">
					<h3 class="wpps-ml-sc-panel-title"><?php esc_html_e( 'Custom CSS', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-sc-panel-desc"><?php esc_html_e( 'Optional scoped CSS for Magic Login forms. Script tags and unsafe URL protocols are stripped before output.', 'wp-powersuite' ); ?></p>
					<div class="wpps-ml-sc-form-group">
						<label for="<?php echo esc_attr( $module_id . '_shortcode_css' ); ?>" class="screen-reader-text"><?php esc_html_e( 'Custom CSS', 'wp-powersuite' ); ?></label>
						<textarea class="wpps-ml-sc-textarea code wp-powersuite-advanced-setting" rows="6" data-setting-key="shortcode_css" id="<?php echo esc_attr( $module_id . '_shortcode_css' ); ?>"><?php echo esc_textarea( (string) ( $settings['shortcode_css'] ?? '' ) ); ?></textarea>
					</div>
				</div>
			</div>
		<?php
		wpps_ml_accordion_close();
		wpps_ml_accordion_open(
			'register',
			__( 'Registration', 'wp-powersuite' ),
			__( 'Magic registration links for new email addresses when WordPress registration is enabled.', 'wp-powersuite' )
		);
		?>
			<div class="wpps-ml-form-panel">
				<div class="wpps-ml-form-card">
					<h3 class="wpps-ml-form-panel-title"><?php esc_html_e( 'Magic registration', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-form-panel-desc"><?php esc_html_e( 'Send registration links to new email addresses when WordPress registration is enabled.', 'wp-powersuite' ); ?></p>

					<?php if ( ! $wp_registration_on ) : ?>
						<div class="notice notice-warning inline"><p>
							<?php
							echo wp_kses(
								sprintf(
									/* translators: %s: link to Settings → General. */
									__( 'WordPress “Anyone can register” is off. Turn it on under %s to use magic registration.', 'wp-powersuite' ),
									'<a href="' . esc_url( admin_url( 'options-general.php#users_can_register' ) ) . '">' . esc_html__( 'Settings → General', 'wp-powersuite' ) . '</a>'
								),
								[
									'a' => [
										'href' => [],
									],
								]
							);
							?>
						</p></div>
					<?php endif; ?>

					<div class="wpps-ml-form-grid wpps-ml-form-grid-2col">
						<div class="wpps-ml-form-group">
							<label class="wpps-ml-form-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="enable_registration" value="1" <?php checked( $cb( $settings['enable_registration'] ?? false ) ); ?> <?php disabled( ! $wp_registration_on ); ?> />
								<?php esc_html_e( 'Send registration links to new email addresses (when global registration is allowed).', 'wp-powersuite' ); ?>
							</label>
						</div>
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_reg_role' ); ?>"><?php esc_html_e( 'Default new user role', 'wp-powersuite' ); ?></label>
							<select class="wpps-ml-form-select wp-powersuite-advanced-setting" data-setting-key="registration_default_role" id="<?php echo esc_attr( $module_id . '_reg_role' ); ?>">
								<?php
								$def_role = sanitize_key( (string) ( $settings['registration_default_role'] ?? 'subscriber' ) );
								foreach ( $all_roles as $role_key => $role_info ) :
									$role_key = sanitize_key( $role_key );
									$label    = isset( $role_info['name'] ) ? translate_user_role( $role_info['name'] ) : $role_key;
									?>
									<option value="<?php echo esc_attr( $role_key ); ?>" <?php selected( $def_role, $role_key ); ?>><?php echo esc_html( $label ); ?></option>
								<?php endforeach; ?>
							</select>
						</div>
					</div>
				</div>
			</div>
		<?php
		wpps_ml_accordion_close();
		wpps_ml_accordion_open(
			'limits',
			__( 'Rate limits', 'wp-powersuite' ),
			__( 'Throttle link requests and one-time code verification attempts.', 'wp-powersuite' )
		);
		?>
			<div class="wpps-ml-form-panel">
				<div class="wpps-ml-form-card">
					<h3 class="wpps-ml-form-panel-title"><?php esc_html_e( 'Link requests', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-form-panel-desc"><?php esc_html_e( 'Limits how often someone can click “Send link” or request a magic login email.', 'wp-powersuite' ); ?></p>

					<h4 class="wpps-ml-form-subsection-title"><?php esc_html_e( 'Per IP', 'wp-powersuite' ); ?></h4>
					<div class="wpps-ml-form-grid wpps-ml-form-grid-2col">
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_rate_ip_max' ); ?>"><?php esc_html_e( 'Max requests', 'wp-powersuite' ); ?></label>
							<input type="number" min="0" max="10000" class="wpps-ml-form-input wp-powersuite-advanced-setting" data-setting-key="rate_ip_max" id="<?php echo esc_attr( $module_id . '_rate_ip_max' ); ?>" value="<?php echo esc_attr( (string) ( $settings['rate_ip_max'] ?? 5 ) ); ?>" />
							<p class="wpps-ml-form-help"><?php esc_html_e( '0 = disable IP limit.', 'wp-powersuite' ); ?></p>
						</div>
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_rate_ip_window' ); ?>"><?php esc_html_e( 'Window (minutes)', 'wp-powersuite' ); ?></label>
							<input type="number" min="1" max="1440" class="wpps-ml-form-input wp-powersuite-advanced-setting" data-setting-key="rate_ip_window_minutes" id="<?php echo esc_attr( $module_id . '_rate_ip_window' ); ?>" value="<?php echo esc_attr( (string) ( $settings['rate_ip_window_minutes'] ?? 5 ) ); ?>" />
						</div>
					</div>

					<h4 class="wpps-ml-form-subsection-title"><?php esc_html_e( 'Per email', 'wp-powersuite' ); ?></h4>
					<div class="wpps-ml-form-grid wpps-ml-form-grid-2col">
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_rate_email_max' ); ?>"><?php esc_html_e( 'Max requests', 'wp-powersuite' ); ?></label>
							<input type="number" min="0" max="1000" class="wpps-ml-form-input wp-powersuite-advanced-setting" data-setting-key="rate_email_max" id="<?php echo esc_attr( $module_id . '_rate_email_max' ); ?>" value="<?php echo esc_attr( (string) ( $settings['rate_email_max'] ?? 3 ) ); ?>" />
							<p class="wpps-ml-form-help"><?php esc_html_e( '0 = disable email limit.', 'wp-powersuite' ); ?></p>
						</div>
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_rate_email_window' ); ?>"><?php esc_html_e( 'Window (minutes)', 'wp-powersuite' ); ?></label>
							<input type="number" min="1" max="1440" class="wpps-ml-form-input wp-powersuite-advanced-setting" data-setting-key="rate_email_window_minutes" id="<?php echo esc_attr( $module_id . '_rate_email_window' ); ?>" value="<?php echo esc_attr( (string) ( $settings['rate_email_window_minutes'] ?? 2 ) ); ?>" />
						</div>
					</div>
				</div>

				<div class="wpps-ml-form-card">
					<h3 class="wpps-ml-form-panel-title"><?php esc_html_e( 'Code verification', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-form-panel-desc"><?php esc_html_e( 'Limits wrong guesses when someone enters the one-time numeric code. Applies when one-time code login is enabled in Features.', 'wp-powersuite' ); ?></p>

					<div class="wpps-ml-form-grid wpps-ml-form-grid-2col">
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_code_rate' ); ?>"><?php esc_html_e( 'Per IP — max attempts', 'wp-powersuite' ); ?></label>
							<input type="number" min="1" max="100" step="1" class="wpps-ml-form-input wp-powersuite-advanced-setting" data-setting-key="code_rate_max" id="<?php echo esc_attr( $module_id . '_code_rate' ); ?>" value="<?php echo esc_attr( (string) ( $settings['code_rate_max'] ?? 10 ) ); ?>" />
							<p class="wpps-ml-form-help"><?php esc_html_e( 'Rolling 15-minute window per IP address.', 'wp-powersuite' ); ?></p>
						</div>
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_code_rate_user' ); ?>"><?php esc_html_e( 'Per account — max attempts', 'wp-powersuite' ); ?></label>
							<input type="number" min="1" max="50" step="1" class="wpps-ml-form-input wp-powersuite-advanced-setting" data-setting-key="code_rate_max_user" id="<?php echo esc_attr( $module_id . '_code_rate_user' ); ?>" value="<?php echo esc_attr( (string) ( $settings['code_rate_max_user'] ?? 5 ) ); ?>" />
							<p class="wpps-ml-form-help"><?php esc_html_e( 'Rolling 15-minute window per user account.', 'wp-powersuite' ); ?></p>
						</div>
					</div>
				</div>
			</div>
		<?php
		wpps_ml_accordion_close();
		wpps_ml_accordion_open(
			'security',
			__( 'Security', 'wp-powersuite' ),
			__( 'Honeypot, CAPTCHA integration, and AJAX submission for shortcode forms.', 'wp-powersuite' )
		);
		?>
			<div class="wpps-ml-form-panel">
				<div class="wpps-ml-form-card">
					<h3 class="wpps-ml-form-panel-title"><?php esc_html_e( 'Form protection', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-form-panel-desc"><?php esc_html_e( 'Honeypot, CAPTCHA integration, and AJAX submission for shortcode forms.', 'wp-powersuite' ); ?></p>

					<div class="wpps-ml-form-grid wpps-ml-form-grid-3col">
						<div class="wpps-ml-form-group">
							<label class="wpps-ml-form-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="enable_honeypot" value="1" <?php checked( $cb( $settings['enable_honeypot'] ?? true ) ); ?> />
								<?php esc_html_e( 'Honeypot — hidden field on shortcode / AJAX forms.', 'wp-powersuite' ); ?>
							</label>
						</div>
						<div class="wpps-ml-form-group">
							<label for="<?php echo esc_attr( $module_id . '_captcha' ); ?>"><?php esc_html_e( 'CAPTCHA', 'wp-powersuite' ); ?></label>
							<select class="wpps-ml-form-select wp-powersuite-advanced-setting" data-setting-key="captcha_provider" id="<?php echo esc_attr( $module_id . '_captcha' ); ?>">
								<option value="none" <?php selected( $captcha_provider, 'none' ); ?>><?php esc_html_e( 'None', 'wp-powersuite' ); ?></option>
								<option value="simple" <?php selected( $captcha_provider, 'simple' ); ?> <?php disabled( ! $simple_available ); ?>><?php esc_html_e( 'Simple Captcha module', 'wp-powersuite' ); ?></option>
								<option value="recaptcha" <?php selected( $captcha_provider, 'recaptcha' ); ?> <?php disabled( ! $recaptcha_available ); ?>><?php esc_html_e( 'Google reCAPTCHA module', 'wp-powersuite' ); ?></option>
								<option value="turnstile" <?php selected( $captcha_provider, 'turnstile' ); ?> <?php disabled( ! $turnstile_available ); ?>><?php esc_html_e( 'Cloudflare Turnstile module', 'wp-powersuite' ); ?></option>
							</select>
							<p class="wpps-ml-form-help"><?php esc_html_e( 'Enable the matching security module in PowerSuite first.', 'wp-powersuite' ); ?></p>
						</div>
						<div class="wpps-ml-form-group">
							<label class="wpps-ml-form-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="enable_ajax" value="1" <?php checked( $cb( $settings['enable_ajax'] ?? true ) ); ?> />
								<?php esc_html_e( 'AJAX — submit shortcode form without page reload when possible.', 'wp-powersuite' ); ?>
							</label>
						</div>
					</div>

					<div class="wpps-ml-form-grid">
						<div class="wpps-ml-form-group wpps-ml-form-full">
							<label class="wpps-ml-form-checkbox-label">
								<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="bypass_2fa" value="1" <?php checked( $cb( $settings['bypass_2fa'] ?? false ) ); ?> <?php disabled( ! $two_fa_available ); ?> />
								<?php esc_html_e( 'Bypass two-factor authentication after magic link or code login.', 'wp-powersuite' ); ?>
							</label>
							<?php if ( ! $two_fa_available ) : ?>
								<p class="wpps-ml-form-help"><?php esc_html_e( 'Enable the Two-Factor Authentication module in PowerSuite to use this option.', 'wp-powersuite' ); ?></p>
							<?php elseif ( ! empty( $settings['bypass_2fa'] ) ) : ?>
								<p class="wpps-ml-form-help" style="color:#b45309;">
									<?php esc_html_e( 'Security note: users who sign in via magic link or one-time code will skip the second factor. Password login still requires 2FA when enforced.', 'wp-powersuite' ); ?>
								</p>
							<?php else : ?>
								<p class="wpps-ml-form-help"><?php esc_html_e( 'When off, users with 2FA enabled must complete the second step after verifying their magic link or code.', 'wp-powersuite' ); ?></p>
							<?php endif; ?>
						</div>
					</div>
				</div>
			</div>
		<?php
		wpps_ml_accordion_close();

		$error_defaults = Module::getDefaultErrorMessages();
		$error_saved    = isset( $settings['error_messages'] ) && is_array( $settings['error_messages'] ) ? $settings['error_messages'] : [];
		$error_sections = [
			'magic_link' => [
				'title'  => __( 'Magic link requests', 'wp-powersuite' ),
				'fields' => [
					'nonce'         => [
						'label'   => __( 'Security check failed', 'wp-powersuite' ),
						'desc'    => __( 'Shown when a form or AJAX security token is invalid.', 'wp-powersuite' ),
						'legacy'  => [ 'nonce_ajax', 'code_nonce' ],
					],
					'invalid_email' => [
						'label' => __( 'Invalid email', 'wp-powersuite' ),
						'desc'  => __( 'Shown when the submitted email address is not valid.', 'wp-powersuite' ),
					],
					'captcha'       => [
						'label' => __( 'CAPTCHA failed', 'wp-powersuite' ),
						'desc'  => __( 'Shown when CAPTCHA verification fails.', 'wp-powersuite' ),
					],
					'rate_ip'       => [
						'label' => __( 'IP rate limit', 'wp-powersuite' ),
						'desc'  => __( 'Shown when too many magic-link requests come from the same IP.', 'wp-powersuite' ),
					],
					'rate_email'    => [
						'label' => __( 'Email rate limit', 'wp-powersuite' ),
						'desc'  => __( 'Shown when a link was recently sent to the same email.', 'wp-powersuite' ),
					],
					'send_failed'   => [
						'label' => __( 'Email send failed', 'wp-powersuite' ),
						'desc'  => __( 'Shown when WordPress cannot send the magic-link email.', 'wp-powersuite' ),
					],
					'unknown'       => [
						'label' => __( 'Unknown error fallback', 'wp-powersuite' ),
						'desc'  => __( 'Fallback message for unrecognized error codes.', 'wp-powersuite' ),
					],
				],
			],
			'code_login' => [
				'title'  => __( 'One-time code login', 'wp-powersuite' ),
				'fields' => [
					'code_invalid'      => [
						'label' => __( 'Invalid code format', 'wp-powersuite' ),
						'desc'  => __( 'Shown when the submitted code length or format is wrong.', 'wp-powersuite' ),
					],
					'code_rate'         => [
						'label'  => __( 'Too many code attempts', 'wp-powersuite' ),
						'desc'   => __( 'Shown when IP or account code attempt limits are exceeded.', 'wp-powersuite' ),
						'legacy' => [ 'code_rate_ip', 'code_rate_user' ],
					],
					'code_expired'      => [
						'label' => __( 'Invalid or expired code', 'wp-powersuite' ),
						'desc'  => __( 'Shown when the code does not match or has expired.', 'wp-powersuite' ),
					],
					'code_invalid_user' => [
						'label' => __( 'Invalid user', 'wp-powersuite' ),
						'desc'  => __( 'Shown when the user account for the code no longer exists.', 'wp-powersuite' ),
					],
					'code_role_denied'  => [
						'label' => __( 'Role not allowed', 'wp-powersuite' ),
						'desc'  => __( 'Shown when the user role is not allowed to use Magic Login.', 'wp-powersuite' ),
					],
				],
			],
		];

		wpps_ml_accordion_open(
			'error_messages',
			__( 'Error messages', 'wp-powersuite' ),
			__( 'Customize each user-facing error shown during magic link and code login flows.', 'wp-powersuite' )
		);
		?>
			<div class="wpps-ml-form-panel">
				<p class="wpps-ml-error-intro"><?php esc_html_e( 'Leave a field empty to use the default message shown as placeholder text.', 'wp-powersuite' ); ?></p>
				<?php foreach ( $error_sections as $section_key => $section ) : ?>
					<div class="wpps-ml-form-card">
						<h3 class="wpps-ml-form-panel-title"><?php echo esc_html( $section['title'] ); ?></h3>
						<div class="wpps-ml-error-grid">
							<?php foreach ( $section['fields'] as $err_key => $field ) : ?>
								<?php
								$default_val = $error_defaults[ $err_key ] ?? '';
								$legacy_keys = isset( $field['legacy'] ) && is_array( $field['legacy'] ) ? $field['legacy'] : [];
								$saved_val   = Module::getSavedErrorMessage( $error_saved, $err_key, $legacy_keys );
								$input_id    = $module_id . '_err_' . $err_key;
								?>
								<div class="wpps-ml-error-field">
									<label for="<?php echo esc_attr( $input_id ); ?>"><?php echo esc_html( $field['label'] ); ?></label>
									<input
										type="text"
										class="wpps-ml-form-input wp-powersuite-advanced-setting"
										data-setting-key="<?php echo esc_attr( 'error_messages.' . $err_key ); ?>"
										id="<?php echo esc_attr( $input_id ); ?>"
										value="<?php echo esc_attr( $saved_val ); ?>"
										placeholder="<?php echo esc_attr( $default_val ); ?>"
									/>
									<p class="wpps-ml-form-help"><?php echo esc_html( $field['desc'] ); ?></p>
								</div>
							<?php endforeach; ?>
						</div>
					</div>
				<?php endforeach; ?>
			</div>
		<?php
		wpps_ml_accordion_close();
		?>

	</form>

		<?php
		wpps_ml_accordion_open(
			'stats',
			__( 'Stats', 'wp-powersuite' ),
			__( 'Magic link usage totals and recent login activity.', 'wp-powersuite' )
		);
		?>
			<div class="wpps-ml-form-panel">
				<?php if ( isset( $_GET['ml_bulk'] ) ) : ?>
					<?php
					$bulk_notice = sanitize_key( wp_unslash( (string) $_GET['ml_bulk'] ) );
					$bulk_parts  = explode( '_', $bulk_notice );
					$bulk_count  = isset( $bulk_parts[1] ) ? absint( $bulk_parts[1] ) : 0;
					$bulk_type   = $bulk_parts[0] ?? '';
					$bulk_msg    = match ( $bulk_type ) {
						'delete', 'deleted' => sprintf(
							/* translators: %d: number of rows. */
							_n( '%d activity row deleted.', '%d activity rows deleted.', $bulk_count, 'wp-powersuite' ),
							$bulk_count
						),
						'revoke' => sprintf(
							/* translators: %d: number of rows. */
							_n( '%d pending link revoked.', '%d pending links revoked.', $bulk_count, 'wp-powersuite' ),
							$bulk_count
						),
						default => __( 'Bulk action completed.', 'wp-powersuite' ),
					};
					?>
					<div class="notice notice-success is-dismissible inline"><p><?php echo esc_html( $bulk_msg ); ?></p></div>
				<?php endif; ?>

				<div class="wpps-ml-form-card">
					<h3 class="wpps-ml-form-panel-title"><?php esc_html_e( 'Overview', 'wp-powersuite' ); ?></h3>
					<p class="wpps-ml-form-panel-desc"><?php esc_html_e( 'Magic link usage totals across your site.', 'wp-powersuite' ); ?></p>
					<div class="wpps-ml-stats-grid">
						<div class="wpps-ml-stat-card">
							<p class="wpps-ml-stat-card__label"><?php esc_html_e( 'Total links', 'wp-powersuite' ); ?></p>
							<p class="wpps-ml-stat-card__value"><?php echo esc_html( (string) ( $ml_stats['total'] ?? 0 ) ); ?></p>
						</div>
						<div class="wpps-ml-stat-card">
							<p class="wpps-ml-stat-card__label"><?php esc_html_e( 'Used', 'wp-powersuite' ); ?></p>
							<p class="wpps-ml-stat-card__value is-used"><?php echo esc_html( (string) ( $ml_stats['used'] ?? 0 ) ); ?></p>
						</div>
						<div class="wpps-ml-stat-card">
							<p class="wpps-ml-stat-card__label"><?php esc_html_e( 'Active', 'wp-powersuite' ); ?></p>
							<p class="wpps-ml-stat-card__value is-active"><?php echo esc_html( (string) ( $ml_stats['active'] ?? 0 ) ); ?></p>
						</div>
						<div class="wpps-ml-stat-card">
							<p class="wpps-ml-stat-card__label"><?php esc_html_e( 'Users (used)', 'wp-powersuite' ); ?></p>
							<p class="wpps-ml-stat-card__value"><?php echo esc_html( (string) ( $ml_stats['unique_users'] ?? 0 ) ); ?></p>
						</div>
					</div>
				</div>

				<div class="wpps-ml-form-card wpps-ml-activity-table-wrap">
					<h3 class="wpps-ml-form-panel-title"><?php esc_html_e( 'Recent magic login activity', 'wp-powersuite' ); ?></h3>
					<form method="post" id="wpps-ml-activity-list-form">
						<?php wp_nonce_field( 'bulk-ml-activities' ); ?>
						<input type="hidden" name="page" value="powersuite-magic-login" />
						<input type="hidden" name="activity_status" value="<?php echo esc_attr( $activity_status ); ?>" />
						<?php if ( $activity_search !== '' ) : ?>
							<input type="hidden" name="s" value="<?php echo esc_attr( $activity_search ); ?>" />
						<?php endif; ?>
						<div class="wpps-ml-activity-list-header">
							<?php $activity_list_table->views(); ?>
							<?php $activity_list_table->search_box( __( 'Search activity', 'wp-powersuite' ), 'ml-activity' ); ?>
						</div>
						<?php $activity_list_table->display(); ?>
					</form>
				</div>
			</div>
		<?php wpps_ml_accordion_close(); ?>

	</div>
</div>
