<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'simple-captcha';
}

$settings     = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $settings ) ) {
	$settings = [];
}

$captcha_type         = in_array( $settings['captcha_type'] ?? 'math', [ 'math', 'text', 'image' ], true ) ? ( $settings['captcha_type'] ?? 'math' ) : 'math';
$math_difficulty      = in_array( $settings['math_difficulty'] ?? 'easy', [ 'easy', 'medium', 'hard' ], true ) ? ( $settings['math_difficulty'] ?? 'easy' ) : 'easy';
$text_questions       = is_array( $settings['text_questions'] ?? null ) ? $settings['text_questions'] : [];
$image_style          = in_array( $settings['image_style'] ?? 'distorted', [ 'distorted', 'simple' ], true ) ? ( $settings['image_style'] ?? 'distorted' ) : 'distorted';
$image_length         = max( 4, min( 8, (int) ( $settings['image_length'] ?? 5 ) ) );
$image_case_sensitive = ! empty( $settings['image_case_sensitive'] );
$skip_logged_in       = ! isset( $settings['skip_logged_in'] ) || ! empty( $settings['skip_logged_in'] );
$error_message        = trim( (string) ( $settings['error_message'] ?? '' ) );

$protect_login          = ! empty( $settings['protect_login'] );
$protect_registration   = ! empty( $settings['protect_registration'] );
$protect_password_reset = ! empty( $settings['protect_password_reset'] );
$protect_comments       = ! empty( $settings['protect_comments'] );

$woo_login          = ! empty( $settings['woo_login'] );
$woo_registration   = ! empty( $settings['woo_registration'] );
$woo_lost_password  = ! empty( $settings['woo_lost_password'] );
$woo_checkout       = ! empty( $settings['woo_checkout'] );
$woo_reviews        = ! empty( $settings['woo_reviews'] );

$login_canonical_only    = ! empty( $settings['login_canonical_only'] );
$register_canonical_only = ! empty( $settings['register_canonical_only'] );
$woo_checkout_guest_only = ! empty( $settings['woo_checkout_guest_only'] );

$anti_bot_honeypot  = ! isset( $settings['anti_bot_honeypot'] ) || ! empty( $settings['anti_bot_honeypot'] );
$anti_bot_timing    = ! isset( $settings['anti_bot_timing'] ) || ! empty( $settings['anti_bot_timing'] );
$min_submit_seconds = max( 1, min( 30, (int) ( $settings['min_submit_seconds'] ?? 2 ) ) );
$ajax_comment_reset = ! isset( $settings['ajax_comment_reset'] ) || ! empty( $settings['ajax_comment_reset'] );

$skip_rules        = isset( $settings['skip_rules'] ) && is_array( $settings['skip_rules'] ) ? $settings['skip_rules'] : [];
$skip_enabled      = ! empty( $skip_rules['enabled'] );
$skip_roles_saved  = isset( $skip_rules['roles'] ) && is_array( $skip_rules['roles'] ) ? $skip_rules['roles'] : [];
$skip_ips_saved    = isset( $skip_rules['ips'] ) && is_array( $skip_rules['ips'] ) ? $skip_rules['ips'] : [];
$skip_ips_textarea = implode( "\n", array_map( 'strval', $skip_ips_saved ) );
$all_roles         = function_exists( 'wp_roles' ) ? wp_roles()->roles : [];

$woo_active           = class_exists( 'WooCommerce', false );
$elementor_pro_active = defined( 'ELEMENTOR_PRO_VERSION' );

$wpps_sc_integrations = [
	[ 'key' => 'basic_forms', 'label' => __( 'Basic Forms (WP PowerSuite)', 'wp-powersuite' ), 'available' => true ],
	[ 'key' => 'cf7', 'label' => __( 'Contact Form 7', 'wp-powersuite' ), 'available' => class_exists( 'WPCF7' ) ],
	[ 'key' => 'wpforms', 'label' => __( 'WPForms', 'wp-powersuite' ), 'available' => function_exists( 'wpforms' ) ],
	[ 'key' => 'formidable', 'label' => __( 'Formidable Forms', 'wp-powersuite' ), 'available' => class_exists( 'FrmFormsController' ) ],
	[ 'key' => 'fluent_forms', 'label' => __( 'Fluent Forms', 'wp-powersuite' ), 'available' => defined( 'FLUENTFORM' ) ],
	[ 'key' => 'elementor_forms', 'label' => __( 'Elementor Pro Forms', 'wp-powersuite' ), 'available' => $elementor_pro_active ],
	[ 'key' => 'integration_gravity', 'label' => __( 'Gravity Forms', 'wp-powersuite' ), 'available' => class_exists( 'GFForms' ) ],
	[ 'key' => 'integration_jetpack', 'label' => __( 'Jetpack forms', 'wp-powersuite' ), 'available' => defined( 'JETPACK__VERSION' ) ],
	[ 'key' => 'integration_bbpress', 'label' => __( 'bbPress', 'wp-powersuite' ), 'available' => function_exists( 'bbpress' ) ],
	[ 'key' => 'integration_buddypress', 'label' => __( 'BuddyPress', 'wp-powersuite' ), 'available' => class_exists( 'BuddyPress' ) ],
	[ 'key' => 'integration_ultimate_member', 'label' => __( 'Ultimate Member', 'wp-powersuite' ), 'available' => class_exists( 'UM' ) ],
	[ 'key' => 'integration_memberpress', 'label' => __( 'MemberPress', 'wp-powersuite' ), 'available' => class_exists( 'MeprAppCtrl' ) ],
	[ 'key' => 'integration_edd', 'label' => __( 'Easy Digital Downloads', 'wp-powersuite' ), 'available' => function_exists( 'EDD' ) ],
	[ 'key' => 'integration_pmp', 'label' => __( 'Paid Memberships Pro', 'wp-powersuite' ), 'available' => defined( 'PMPRO_VERSION' ) ],
	[ 'key' => 'integration_mc4wp', 'label' => __( 'MC4WP (Mailchimp)', 'wp-powersuite' ), 'available' => defined( 'MC4WP_VERSION' ) ],
];

$builtin_text_questions = [];
if ( class_exists( \WP_PowerSuite\Core\ModuleManager::class ) ) {
	$sc_mod = \WP_PowerSuite\Core\ModuleManager::getInstance()->getModule( 'simple-captcha' );
	if ( $sc_mod instanceof \SimpleCaptcha\Module ) {
		$builtin_text_questions = $sc_mod->getBuiltinTextQuestionDefinitions();
	}
}

// Rows shown in the accordion: saved custom rows, or (when none) built-in defaults for editing.
$text_rows_for_ui = [];
foreach ( is_array( $text_questions ) ? $text_questions : [] as $q ) {
	if ( ! is_array( $q ) ) {
		continue;
	}
	$q_question = trim( (string) ( $q['question'] ?? '' ) );
	$q_answer   = trim( (string) ( $q['answer'] ?? '' ) );
	if ( $q_question !== '' && $q_answer !== '' ) {
		$text_rows_for_ui[] = [ 'question' => $q_question, 'answer' => $q_answer ];
	}
}
if ( $text_rows_for_ui === [] && $builtin_text_questions !== [] ) {
	foreach ( $builtin_text_questions as $b ) {
		$qtxt = trim( (string) ( $b['question'] ?? '' ) );
		$ans  = is_array( $b['answers'] ?? null ) ? $b['answers'] : [];
		$ans  = array_map( 'strval', $ans );
		if ( $qtxt === '' || $ans === [] ) {
			continue;
		}
		$text_rows_for_ui[] = [
			'question' => $qtxt,
			'answer'   => implode( ' | ', $ans ),
		];
	}
}

$uid = preg_replace( '/[^a-z0-9_-]/i', '', $module_id );

$premium_unlocked = function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
$license_page_url = admin_url( 'admin.php?page=powersuite-license' );

$wpps_sc_render_premium_notice = static function () use ( $premium_unlocked, $license_page_url ): void {
	if ( $premium_unlocked ) {
		return;
	}
	?>
	<div class="notice notice-info inline" style="margin:0 0 12px; padding:8px 12px;">
		<p style="margin:0;">
			<?php
			echo wp_kses_post(
				sprintf(
					/* translators: %s: URL to license page */
					__( 'This section is a Premium feature. <a href="%s">Activate your license</a> to configure form integrations, advanced options, and skip rules.', 'wp-powersuite' ),
					esc_url( $license_page_url )
				)
			);
			?>
		</p>
	</div>
	<?php
};
?>

<?php wpps_render_captcha_overlap_notices( $module_id ); ?>

<div class="wp-powersuite-module-settings wpps-settings-panel wpps-settings-panel--accordion-stack" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<input type="hidden" id="<?php echo esc_attr( $module_id ); ?>_text_questions" class="wp-powersuite-advanced-setting" data-setting-key="text_questions" value="<?php echo esc_attr( wp_json_encode( $text_questions ) ); ?>" />

		<div class="wpps-ts-accordions">
			<div class="wpps-ts-accordion is-open">
				<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_type" aria-expanded="true" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_type">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'CAPTCHA type & messages', 'wp-powersuite' ); ?></span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-ts-accordion-chevron" aria-hidden="true"></span>
				</button>
				<div class="wpps-ts-accordion-body" id="<?php echo esc_attr( $uid ); ?>_acc_body_type" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_type">
					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<label for="<?php echo esc_attr( $module_id ); ?>_captcha_type"><?php esc_html_e( 'CAPTCHA type', 'wp-powersuite' ); ?></label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: CAPTCHA type', 'wp-powersuite' ),
								__( 'Math, text Q&A, or image CAPTCHA — all run on your server without third-party services.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<select
								id="<?php echo esc_attr( $module_id ); ?>_captcha_type"
								name="<?php echo esc_attr( $module_id ); ?>[captcha_type]"
								class="wp-powersuite-advanced-setting"
								data-setting-key="captcha_type"
							>
								<option value="math" <?php selected( $captcha_type, 'math' ); ?>><?php esc_html_e( 'Math', 'wp-powersuite' ); ?></option>
								<option value="text" <?php selected( $captcha_type, 'text' ); ?>><?php esc_html_e( 'Text', 'wp-powersuite' ); ?></option>
								<option value="image" <?php selected( $captcha_type, 'image' ); ?>><?php esc_html_e( 'Image', 'wp-powersuite' ); ?></option>
							</select>
							<p class="description"><?php esc_html_e( 'Math: simple arithmetic. Text: custom Q&A. Image: type characters from image.', 'wp-powersuite' ); ?></p>
						</div>
					</div>

					<div class="wpps-ts-field wpps-sc-math-options"<?php echo $captcha_type !== 'math' ? ' hidden' : ''; ?>>
						<div class="wpps-ts-field__label-row">
							<label for="<?php echo esc_attr( $module_id ); ?>_math_difficulty"><?php esc_html_e( 'Math difficulty', 'wp-powersuite' ); ?></label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: math difficulty', 'wp-powersuite' ),
								__( 'Easy: 1–10 addition. Medium: 5–20 with +/-. Hard: 10–99 with +/–/*.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<select
								id="<?php echo esc_attr( $module_id ); ?>_math_difficulty"
								name="<?php echo esc_attr( $module_id ); ?>[math_difficulty]"
								class="wp-powersuite-advanced-setting"
								data-setting-key="math_difficulty"
							>
								<option value="easy" <?php selected( $math_difficulty, 'easy' ); ?>><?php esc_html_e( 'Easy', 'wp-powersuite' ); ?></option>
								<option value="medium" <?php selected( $math_difficulty, 'medium' ); ?>><?php esc_html_e( 'Medium', 'wp-powersuite' ); ?></option>
								<option value="hard" <?php selected( $math_difficulty, 'hard' ); ?>><?php esc_html_e( 'Hard', 'wp-powersuite' ); ?></option>
							</select>
						</div>
					</div>

					<div class="wpps-ts-field wpps-sc-text-options"<?php echo $captcha_type !== 'text' ? ' hidden' : ''; ?>>
						<div class="wpps-ts-field__label-row">
							<span><?php esc_html_e( 'Text questions', 'wp-powersuite' ); ?></span>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: text questions', 'wp-powersuite' ),
								__( 'One random question is shown per challenge. If you save no questions, the built-in set is used on the site. For several acceptable answers, separate with | (e.g. 7|seven).', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<div id="<?php echo esc_attr( $module_id ); ?>_text_questions_container" class="wpps-sc-text-accordion" role="region" aria-label="<?php esc_attr_e( 'Text CAPTCHA questions', 'wp-powersuite' ); ?>">
								<?php foreach ( $text_rows_for_ui as $idx => $q ) : ?>
									<?php
									$q_question  = (string) ( $q['question'] ?? '' );
									$q_answer    = (string) ( $q['answer'] ?? '' );
									$sum_preview = $q_question !== '' ? ( function_exists( 'mb_substr' ) ? mb_substr( $q_question, 0, 72 ) : substr( $q_question, 0, 72 ) ) : (string) __( '(empty question)', 'wp-powersuite' );
									if ( function_exists( 'mb_strlen' ) ? ( mb_strlen( $q_question ) > 72 ) : ( strlen( $q_question ) > 72 ) ) {
										$sum_preview .= '…';
									}
									?>
									<details class="wpps-sc-text-accordion__item" data-index="<?php echo (int) $idx; ?>" <?php echo 0 === (int) $idx ? 'open' : ''; ?>>
										<summary class="wpps-sc-text-accordion__summary"><?php echo esc_html( $sum_preview ); ?></summary>
										<div class="wpps-sc-text-accordion__body">
											<div class="wpps-sc-text-accordion__field">
												<label class="screen-reader-text" for="<?php echo esc_attr( $module_id ); ?>-tq-q-<?php echo (int) $idx; ?>"><?php esc_html_e( 'Question', 'wp-powersuite' ); ?></label>
												<input
													type="text"
													id="<?php echo esc_attr( $module_id ); ?>-tq-q-<?php echo (int) $idx; ?>"
													class="wpps-sc-question large-text"
													placeholder="<?php esc_attr_e( 'Question', 'wp-powersuite' ); ?>"
													value="<?php echo esc_attr( $q_question ); ?>"
												/>
											</div>
											<div class="wpps-sc-text-accordion__field" style="margin-top:8px;">
												<label class="screen-reader-text" for="<?php echo esc_attr( $module_id ); ?>-tq-a-<?php echo (int) $idx; ?>"><?php esc_html_e( 'Acceptable answer(s)', 'wp-powersuite' ); ?></label>
												<input
													type="text"
													id="<?php echo esc_attr( $module_id ); ?>-tq-a-<?php echo (int) $idx; ?>"
													class="wpps-sc-answer large-text"
													placeholder="<?php esc_attr_e( 'Answer(s), e.g. blue or 7|seven', 'wp-powersuite' ); ?>"
													value="<?php echo esc_attr( $q_answer ); ?>"
												/>
											</div>
											<p class="wpps-sc-text-accordion__actions" style="margin:10px 0 0;">
												<button type="button" class="button-link wpps-sc-remove-row" style="color:#b32d2e; border:0; background:transparent; padding:0; cursor:pointer; text-decoration:underline;"><?php esc_html_e( 'Delete question', 'wp-powersuite' ); ?></button>
											</p>
										</div>
									</details>
								<?php endforeach; ?>
							</div>
							<?php if ( $text_rows_for_ui === [] && $captcha_type === 'text' ) : ?>
								<p class="description wpps-sc-text-empty-hint" style="margin:8px 0;"><?php esc_html_e( 'No questions in the list yet — the plugin will use built-in questions until you add and save your own. Click “Add question” to start.', 'wp-powersuite' ); ?></p>
							<?php endif; ?>
							<p style="margin-top: 10px;">
								<button type="button" class="button button-secondary wpps-sc-add-row"><?php esc_html_e( 'Add question', 'wp-powersuite' ); ?></button>
							</p>
						</div>
					</div>

					<div class="wpps-ts-field wpps-sc-image-options"<?php echo $captcha_type !== 'image' ? ' hidden' : ''; ?>>
						<div class="wpps-ts-controls-row wpps-ts-controls-row--adv-2col">
							<div class="wpps-ts-controls-row__cell">
								<div class="wpps-ts-field__label-row">
									<label for="<?php echo esc_attr( $module_id ); ?>_image_style"><?php esc_html_e( 'Image style', 'wp-powersuite' ); ?></label>
								</div>
								<select
									id="<?php echo esc_attr( $module_id ); ?>_image_style"
									name="<?php echo esc_attr( $module_id ); ?>[image_style]"
									class="wp-powersuite-advanced-setting"
									data-setting-key="image_style"
								>
									<option value="distorted" <?php selected( $image_style, 'distorted' ); ?>><?php esc_html_e( 'Distorted', 'wp-powersuite' ); ?></option>
									<option value="simple" <?php selected( $image_style, 'simple' ); ?>><?php esc_html_e( 'Simple', 'wp-powersuite' ); ?></option>
								</select>
								<p class="description"><?php esc_html_e( 'Distorted adds lines and noise. Simple is cleaner.', 'wp-powersuite' ); ?></p>
							</div>
							<div class="wpps-ts-controls-row__cell">
								<div class="wpps-ts-field__label-row">
									<label for="<?php echo esc_attr( $module_id ); ?>_image_length"><?php esc_html_e( 'Image length', 'wp-powersuite' ); ?></label>
								</div>
								<input
									type="number"
									id="<?php echo esc_attr( $module_id ); ?>_image_length"
									name="<?php echo esc_attr( $module_id ); ?>[image_length]"
									value="<?php echo esc_attr( $image_length ); ?>"
									min="4"
									max="8"
									class="small-text wp-powersuite-advanced-setting"
									data-setting-key="image_length"
								/>
								<p class="description"><?php esc_html_e( 'Number of characters in the image (4–8).', 'wp-powersuite' ); ?></p>
							</div>
						</div>
					</div>

					<div class="wpps-ts-field wpps-sc-image-options"<?php echo $captcha_type !== 'image' ? ' hidden' : ''; ?>>
						<div class="wpps-ts-field__control">
							<label class="wpps-ts-inline-check">
								<input
									type="checkbox"
									name="<?php echo esc_attr( $module_id ); ?>[image_case_sensitive]"
									value="1"
									<?php checked( $image_case_sensitive ); ?>
									class="wp-powersuite-advanced-setting"
									data-setting-key="image_case_sensitive"
								/>
								<?php esc_html_e( 'Require exact case for image CAPTCHA', 'wp-powersuite' ); ?>
							</label>
						</div>
					</div>

					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<span><?php esc_html_e( 'Visitors', 'wp-powersuite' ); ?></span>
						</div>
						<div class="wpps-ts-field__control">
							<label class="wpps-ts-inline-check">
								<input
									type="checkbox"
									name="<?php echo esc_attr( $module_id ); ?>[skip_logged_in]"
									value="1"
									<?php checked( $skip_logged_in ); ?>
									class="wp-powersuite-advanced-setting"
									data-setting-key="skip_logged_in"
								/>
								<?php esc_html_e( "Don't show CAPTCHA to logged-in users", 'wp-powersuite' ); ?>
							</label>
						</div>
					</div>

					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<label for="<?php echo esc_attr( $module_id ); ?>_error_message"><?php esc_html_e( 'Error message', 'wp-powersuite' ); ?></label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: error message', 'wp-powersuite' ),
								__( 'Custom message when verification fails. Leave blank for the default.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<input
								type="text"
								id="<?php echo esc_attr( $module_id ); ?>_error_message"
								name="<?php echo esc_attr( $module_id ); ?>[error_message]"
								value="<?php echo esc_attr( $error_message ); ?>"
								class="wp-powersuite-advanced-setting"
								data-setting-key="error_message"
								placeholder="<?php esc_attr_e( 'Please complete the verification.', 'wp-powersuite' ); ?>"
							/>
						</div>
					</div>
				</div>
			</div>

			<div class="wpps-ts-accordion">
				<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_wp" aria-expanded="false" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_wp">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'WordPress core', 'wp-powersuite' ); ?></span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-ts-accordion-chevron" aria-hidden="true"></span>
				</button>
				<div class="wpps-ts-accordion-body" id="<?php echo esc_attr( $uid ); ?>_acc_body_wp" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_wp">
					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<span><?php esc_html_e( 'Protected forms', 'wp-powersuite' ); ?></span>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: WordPress forms', 'wp-powersuite' ),
								__( 'Adds Simple CAPTCHA to core WordPress flows. Enable only what you use — each adds a verification step for visitors.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<div class="wpps-check-grid">
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[protect_login]" value="1" <?php checked( $protect_login ); ?> class="wp-powersuite-advanced-setting" data-setting-key="protect_login" />
									<?php esc_html_e( 'Login', 'wp-powersuite' ); ?>
								</label>
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[protect_registration]" value="1" <?php checked( $protect_registration ); ?> class="wp-powersuite-advanced-setting" data-setting-key="protect_registration" />
									<?php esc_html_e( 'Registration', 'wp-powersuite' ); ?>
								</label>
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[protect_password_reset]" value="1" <?php checked( $protect_password_reset ); ?> class="wp-powersuite-advanced-setting" data-setting-key="protect_password_reset" />
									<?php esc_html_e( 'Password reset', 'wp-powersuite' ); ?>
								</label>
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[protect_comments]" value="1" <?php checked( $protect_comments ); ?> class="wp-powersuite-advanced-setting" data-setting-key="protect_comments" />
									<?php esc_html_e( 'Comments', 'wp-powersuite' ); ?>
								</label>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="wpps-ts-accordion">
				<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_woo" aria-expanded="false" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_woo">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'WooCommerce', 'wp-powersuite' ); ?></span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-ts-accordion-chevron" aria-hidden="true"></span>
				</button>
				<div class="wpps-ts-accordion-body" id="<?php echo esc_attr( $uid ); ?>_acc_body_woo" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_woo">
					<?php if ( ! $woo_active ) : ?>
						<p class="description"><?php esc_html_e( 'WooCommerce is not active. These options stay disabled until you install and activate WooCommerce.', 'wp-powersuite' ); ?></p>
					<?php endif; ?>
					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<span><?php esc_html_e( 'Protected forms', 'wp-powersuite' ); ?></span>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: WooCommerce', 'wp-powersuite' ),
								__( 'Adds Simple CAPTCHA to storefront forms. Product reviews only applies when Comments protection above is off.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<div class="wpps-check-grid">
								<label<?php echo $woo_active ? '' : ' class="wpps-ts-integration--unavailable"'; ?>>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[woo_login]" value="1" <?php checked( $woo_login ); ?> class="wp-powersuite-advanced-setting" data-setting-key="woo_login" <?php disabled( ! $woo_active ); ?> />
									<?php esc_html_e( 'Login', 'wp-powersuite' ); ?>
								</label>
								<label<?php echo $woo_active ? '' : ' class="wpps-ts-integration--unavailable"'; ?>>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[woo_registration]" value="1" <?php checked( $woo_registration ); ?> class="wp-powersuite-advanced-setting" data-setting-key="woo_registration" <?php disabled( ! $woo_active ); ?> />
									<?php esc_html_e( 'Registration', 'wp-powersuite' ); ?>
								</label>
								<label<?php echo $woo_active ? '' : ' class="wpps-ts-integration--unavailable"'; ?>>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[woo_lost_password]" value="1" <?php checked( $woo_lost_password ); ?> class="wp-powersuite-advanced-setting" data-setting-key="woo_lost_password" <?php disabled( ! $woo_active ); ?> />
									<?php esc_html_e( 'Lost password', 'wp-powersuite' ); ?>
								</label>
								<label<?php echo $woo_active ? '' : ' class="wpps-ts-integration--unavailable"'; ?>>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[woo_checkout]" value="1" <?php checked( $woo_checkout ); ?> class="wp-powersuite-advanced-setting" data-setting-key="woo_checkout" <?php disabled( ! $woo_active ); ?> />
									<?php esc_html_e( 'Checkout', 'wp-powersuite' ); ?>
								</label>
								<label class="wpps-check-grid__label-with-tip<?php echo $woo_active ? '' : ' wpps-ts-integration--unavailable'; ?>">
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[woo_reviews]" value="1" <?php checked( $woo_reviews ); ?> class="wp-powersuite-advanced-setting" data-setting-key="woo_reviews" <?php disabled( ! $woo_active ); ?> />
									<span><?php esc_html_e( 'Product reviews', 'wp-powersuite' ); ?></span>
									<?php
									wpps_render_modal_settings_tip(
										__( 'Help: product reviews', 'wp-powersuite' ),
										__( 'Use when Comments protection is disabled but you still want Simple CAPTCHA on WooCommerce product reviews only.', 'wp-powersuite' )
									);
									?>
								</label>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="wpps-ts-accordion">
				<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_forms" aria-expanded="false" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_forms">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'Forms & integrations', 'wp-powersuite' ); ?><?php if ( ! $premium_unlocked ) : ?> <span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span><?php endif; ?></span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-ts-accordion-chevron" aria-hidden="true"></span>
				</button>
				<div class="wpps-ts-accordion-body" id="<?php echo esc_attr( $uid ); ?>_acc_body_forms" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_forms">
					<?php $wpps_sc_render_premium_notice(); ?>
					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<span><?php esc_html_e( 'Integrations', 'wp-powersuite' ); ?></span>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: form plugins', 'wp-powersuite' ),
								__( 'Supported integrations for Simple CAPTCHA in this plugin. Install and activate a plugin to enable its checkbox. Basic Forms is built into WP PowerSuite.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<div class="wpps-check-grid">
								<?php foreach ( $wpps_sc_integrations as $wpps_sc_int ) : ?>
									<?php
									$ik = $wpps_sc_int['key'];
									$ia = $wpps_sc_int['available'];
									$iv = ! empty( $settings[ $ik ] );
									?>
								<label<?php echo $ia ? '' : ' class="wpps-ts-integration--unavailable"'; ?>>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[<?php echo esc_attr( $ik ); ?>]" value="1" <?php checked( $iv ); ?> class="wp-powersuite-advanced-setting" data-setting-key="<?php echo esc_attr( $ik ); ?>" <?php disabled( ! $ia || ! $premium_unlocked ); ?> />
									<?php echo esc_html( $wpps_sc_int['label'] ); ?>
								</label>
								<?php endforeach; ?>
							</div>
							<?php if ( $elementor_pro_active ) : ?>
								<p class="description" style="margin-top:12px;">
									<?php esc_html_e( 'Elementor Pro: adds a “Simple CAPTCHA” field to the Form widget. Edit your template, open the Form → add a field → Field type: Simple CAPTCHA (place it where you want, usually before Submit).', 'wp-powersuite' ); ?>
								</p>
							<?php endif; ?>
						</div>
					</div>
				</div>
			</div>

			<div class="wpps-ts-accordion">
				<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_adv" aria-expanded="false" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_adv">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'Advanced options', 'wp-powersuite' ); ?><?php if ( ! $premium_unlocked ) : ?> <span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span><?php endif; ?></span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-ts-accordion-chevron" aria-hidden="true"></span>
				</button>
				<div class="wpps-ts-accordion-body" id="<?php echo esc_attr( $uid ); ?>_acc_body_adv" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_adv">
					<?php $wpps_sc_render_premium_notice(); ?>
					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row"><?php esc_html_e( 'Anti-bot', 'wp-powersuite' ); ?></div>
						<div class="wpps-ts-field__control">
							<div class="wpps-check-grid">
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[anti_bot_honeypot]" value="1" <?php checked( $anti_bot_honeypot ); ?> class="wp-powersuite-advanced-setting" data-setting-key="anti_bot_honeypot" <?php disabled( ! $premium_unlocked ); ?> />
									<?php esc_html_e( 'Honeypot field (hidden trap for bots)', 'wp-powersuite' ); ?>
								</label>
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[anti_bot_timing]" value="1" <?php checked( $anti_bot_timing ); ?> class="wp-powersuite-advanced-setting" data-setting-key="anti_bot_timing" <?php disabled( ! $premium_unlocked ); ?> />
									<?php esc_html_e( 'Reject submissions that are too fast', 'wp-powersuite' ); ?>
								</label>
							</div>
							<p class="description" style="margin:12px 0 0;">
								<label for="<?php echo esc_attr( $module_id ); ?>_min_submit_seconds"><?php esc_html_e( 'Minimum seconds before submit', 'wp-powersuite' ); ?></label>
								<input type="number" id="<?php echo esc_attr( $module_id ); ?>_min_submit_seconds" name="<?php echo esc_attr( $module_id ); ?>[min_submit_seconds]" value="<?php echo esc_attr( $min_submit_seconds ); ?>" min="1" max="30" class="small-text wp-powersuite-advanced-setting" data-setting-key="min_submit_seconds" <?php disabled( ! $premium_unlocked ); ?> />
							</p>
						</div>
					</div>

					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row"><?php esc_html_e( 'Behavior', 'wp-powersuite' ); ?></div>
						<div class="wpps-ts-field__control">
							<div class="wpps-check-grid">
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[ajax_comment_reset]" value="1" <?php checked( $ajax_comment_reset ); ?> class="wp-powersuite-advanced-setting" data-setting-key="ajax_comment_reset" <?php disabled( ! $premium_unlocked ); ?> />
									<?php esc_html_e( 'Clear CAPTCHA when replying to comments (AJAX)', 'wp-powersuite' ); ?>
								</label>
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[login_canonical_only]" value="1" <?php checked( $login_canonical_only ); ?> class="wp-powersuite-advanced-setting" data-setting-key="login_canonical_only" <?php disabled( ! $premium_unlocked ); ?> />
									<?php esc_html_e( 'Protect wp-login.php login only', 'wp-powersuite' ); ?>
								</label>
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[register_canonical_only]" value="1" <?php checked( $register_canonical_only ); ?> class="wp-powersuite-advanced-setting" data-setting-key="register_canonical_only" <?php disabled( ! $premium_unlocked ); ?> />
									<?php esc_html_e( 'Protect wp-login.php registration only', 'wp-powersuite' ); ?>
								</label>
								<?php if ( $woo_active ) : ?>
								<label>
									<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[woo_checkout_guest_only]" value="1" <?php checked( $woo_checkout_guest_only ); ?> class="wp-powersuite-advanced-setting" data-setting-key="woo_checkout_guest_only" <?php disabled( ! $premium_unlocked ); ?> />
									<?php esc_html_e( 'WooCommerce checkout: guests only', 'wp-powersuite' ); ?>
								</label>
								<?php endif; ?>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="wpps-ts-accordion">
				<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_skip" aria-expanded="false" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_skip">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'Skip rules', 'wp-powersuite' ); ?><?php if ( ! $premium_unlocked ) : ?> <span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span><?php endif; ?></span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-ts-accordion-chevron" aria-hidden="true"></span>
				</button>
				<div class="wpps-ts-accordion-body" id="<?php echo esc_attr( $uid ); ?>_acc_body_skip" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_skip">
					<?php $wpps_sc_render_premium_notice(); ?>
					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<span><?php esc_html_e( 'Trusted visitors', 'wp-powersuite' ); ?></span>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: skip rules', 'wp-powersuite' ),
								__( 'Matching roles or IPs bypass the challenge (no CAPTCHA and no server verification for matching visitors). IP rules require correct proxy/Cloudflare configuration. Leave lists empty when skip is enabled to effectively disable skipping.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<label class="wpps-ts-inline-check">
								<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[skip_rules][enabled]" value="1" <?php checked( $skip_enabled ); ?> class="wp-powersuite-advanced-setting" data-setting-key="skip_rules.enabled" <?php disabled( ! $premium_unlocked ); ?> />
								<?php esc_html_e( 'Enable skip rules', 'wp-powersuite' ); ?>
							</label>
						</div>
					</div>

					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row"><?php esc_html_e( 'Allowed roles', 'wp-powersuite' ); ?></div>
						<div class="wpps-ts-field__control">
							<div class="wpps-check-grid wpps-check-grid--roles">
								<?php if ( ! empty( $all_roles ) ) : ?>
									<?php foreach ( $all_roles as $slug => $role_data ) : ?>
										<label>
											<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[skip_rules][roles][]" value="<?php echo esc_attr( $slug ); ?>" <?php checked( in_array( $slug, $skip_roles_saved, true ) ); ?> class="wp-powersuite-advanced-setting" data-setting-key="skip_rules.roles" <?php disabled( ! $premium_unlocked ); ?> />
											<?php echo esc_html( is_array( $role_data ) && isset( $role_data['name'] ) ? $role_data['name'] : $slug ); ?>
										</label>
									<?php endforeach; ?>
								<?php endif; ?>
							</div>
						</div>
					</div>

					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<label for="<?php echo esc_attr( $module_id ); ?>_skip_ips"><?php esc_html_e( 'Allowed IPs / CIDR', 'wp-powersuite' ); ?></label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: IP allowlist', 'wp-powersuite' ),
								__( 'One IP or CIDR per line. Supports IPv4 and IPv6. Useful for office networks; misconfiguration can weaken protection.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<textarea
								id="<?php echo esc_attr( $module_id ); ?>_skip_ips"
								name="<?php echo esc_attr( $module_id ); ?>[skip_rules][ips]"
								class="large-text code wp-powersuite-advanced-setting"
								data-setting-key="skip_rules.ips"
								rows="4"
								placeholder="203.0.113.5&#10;10.0.0.0/24"
								spellcheck="false"
								<?php disabled( ! $premium_unlocked ); ?>
							><?php echo esc_textarea( $skip_ips_textarea ); ?></textarea>
						</div>
					</div>
				</div>
			</div>
		</div>
	</form>
</div>

<style>
.wp-powersuite-modal .wpps-sc-text-accordion { border: 1px solid #c3c4c7; border-radius: 4px; background: #fff; }
.wp-powersuite-modal .wpps-sc-text-accordion__item { border-bottom: 1px solid #dcdcde; }
.wp-powersuite-modal .wpps-sc-text-accordion__item:last-child { border-bottom: 0; }
.wp-powersuite-modal .wpps-sc-text-accordion__summary {
	cursor: pointer; padding: 10px 12px; font-weight: 600; list-style: none; display: flex; align-items: center; gap: 8px; user-select: none;
}
.wp-powersuite-modal .wpps-sc-text-accordion__summary::-webkit-details-marker { display: none; }
.wp-powersuite-modal .wpps-sc-text-accordion__summary::before { content: '▸'; font-size: 10px; opacity: 0.6; }
.wp-powersuite-modal .wpps-sc-text-accordion__item[open] .wpps-sc-text-accordion__summary::before { content: '▾'; }
.wp-powersuite-modal .wpps-sc-text-accordion__body { padding: 0 12px 14px; border-top: 1px solid #f0f0f1; }
.wp-powersuite-modal .wpps-sc-text-accordion__field .large-text { width: 100%; max-width: 100%; }
</style>

<script>
(function() {
	var mid = '<?php echo esc_js( $module_id ); ?>';
	var panel = document.querySelector('.wpps-settings-panel--accordion-stack[data-module-id="' + mid + '"]');
	if (!panel) {
		return;
	}
	var $container = document.getElementById(mid + '_text_questions_container');
	var $hidden = document.getElementById(mid + '_text_questions');
	var $typeSelect = panel.querySelector('#' + mid + '_captcha_type');

	if (!$container || !$hidden) {
		return;
	}

	var qPh = <?php echo wp_json_encode( __( 'Question', 'wp-powersuite' ) ); ?>;
	var aPh = <?php echo wp_json_encode( __( 'Answer(s), e.g. blue or 7|seven', 'wp-powersuite' ) ); ?>;
	var aLbl = <?php echo wp_json_encode( __( 'Acceptable answer(s)', 'wp-powersuite' ) ); ?>;
	var delLabel = <?php echo wp_json_encode( __( 'Delete question', 'wp-powersuite' ) ); ?>;
	var emptyQ = <?php echo wp_json_encode( __( '(empty question)', 'wp-powersuite' ) ); ?>;
	var itemCounter = 0;

	function getQuestions() {
		var arr = [];
		$container.querySelectorAll('.wpps-sc-text-accordion__item').forEach(function( item ) {
			var qel = item.querySelector('.wpps-sc-question');
			var ael = item.querySelector('.wpps-sc-answer');
			var q = qel && qel.value ? qel.value.trim() : '';
			var a = ael && ael.value ? ael.value.trim() : '';
			if (q !== '' && a !== '') {
				arr.push({ question: q, answer: a });
			}
		});
		return arr;
	}

	function syncHidden() {
		$hidden.value = JSON.stringify(getQuestions());
	}

	function truncateSummary( text, max ) {
		max = max || 72;
		if (!text) return emptyQ;
		if (text.length <= max) return text;
		return text.slice(0, max) + '…';
	}

	function setSummary( details ) {
		var qel = details.querySelector('.wpps-sc-question');
		var sum = details.querySelector('.wpps-sc-text-accordion__summary');
		if (!qel || !sum) return;
		sum.textContent = truncateSummary(qel.value ? qel.value.trim() : '');
	}

	function bindItem( details ) {
		var qel = details.querySelector('.wpps-sc-question');
		var ael = details.querySelector('.wpps-sc-answer');
		if (qel) {
			qel.addEventListener('input', function() { setSummary(details); syncHidden(); });
			qel.addEventListener('change', function() { setSummary(details); syncHidden(); });
		}
		if (ael) {
			ael.addEventListener('input', syncHidden);
			ael.addEventListener('change', syncHidden);
		}
	}

	function addRow( question, answer, open ) {
		question = question || '';
		answer = answer || '';
		itemCounter += 1;
		var uid = 'n' + itemCounter + '-' + Date.now();
		var details = document.createElement('details');
		details.className = 'wpps-sc-text-accordion__item';
		details.open = !!open;
		var sm = document.createElement('summary');
		sm.className = 'wpps-sc-text-accordion__summary';
		sm.textContent = truncateSummary(question);
		var body = document.createElement('div');
		body.className = 'wpps-sc-text-accordion__body';
		var fq = document.createElement('div');
		fq.className = 'wpps-sc-text-accordion__field';
		var lq = document.createElement( 'label' );
		lq.className = 'screen-reader-text';
		lq.setAttribute( 'for', mid + '-tq-q-' + uid );
		lq.textContent = qPh;
		var iq = document.createElement('input');
		iq.type = 'text';
		iq.id = mid + '-tq-q-' + uid;
		iq.className = 'wpps-sc-question large-text';
		iq.placeholder = qPh;
		iq.value = question;
		fq.appendChild(lq);
		fq.appendChild(iq);
		var fa = document.createElement('div');
		fa.className = 'wpps-sc-text-accordion__field';
		fa.style.marginTop = '8px';
		var la = document.createElement( 'label' );
		la.className = 'screen-reader-text';
		la.setAttribute( 'for', mid + '-tq-a-' + uid );
		la.textContent = aLbl;
		var ia = document.createElement('input');
		ia.type = 'text';
		ia.id = mid + '-tq-a-' + uid;
		ia.className = 'wpps-sc-answer large-text';
		ia.placeholder = aPh;
		ia.value = answer;
		fa.appendChild(la);
		fa.appendChild(ia);
		var act = document.createElement('p');
		act.className = 'wpps-sc-text-accordion__actions';
		act.style.margin = '10px 0 0';
		var del = document.createElement('button');
		del.type = 'button';
		del.className = 'button-link wpps-sc-remove-row';
		del.style.cssText = 'color:#b32d2e;border:0;background:transparent;padding:0;cursor:pointer;text-decoration:underline;';
		del.textContent = delLabel;
		act.appendChild(del);
		body.appendChild(fq);
		body.appendChild(fa);
		body.appendChild(act);
		details.appendChild(sm);
		details.appendChild(body);
		$container.appendChild(details);
		bindItem(details);
		var emptyHint = $container.parentElement && $container.parentElement.querySelector('.wpps-sc-text-empty-hint');
		if (emptyHint) { emptyHint.style.display = 'none'; }
		syncHidden();
	}

	$container.addEventListener('click', function( e ) {
		var t = e.target;
		if (t && t.classList && t.classList.contains('wpps-sc-remove-row')) {
			var item = t.closest('.wpps-sc-text-accordion__item');
			if (item) {
				item.remove();
				syncHidden();
			}
		}
	});

	$container.querySelectorAll('.wpps-sc-text-accordion__item').forEach(function( details ) {
		bindItem( details );
	});

	var addBtn = $container.parentElement && $container.parentElement.querySelector('.wpps-sc-add-row');
	if (addBtn) {
		addBtn.addEventListener('click', function() {
			addRow('', '', true);
		});
	}

	syncHidden();

	function syncCaptchaTypeUi() {
		if (!$typeSelect) {
			return;
		}
		var v = $typeSelect.value;
		panel.querySelectorAll('.wpps-sc-math-options').forEach(function(el) { el.hidden = v !== 'math'; });
		panel.querySelectorAll('.wpps-sc-text-options').forEach(function(el) { el.hidden = v !== 'text'; });
		panel.querySelectorAll('.wpps-sc-image-options').forEach(function(el) { el.hidden = v !== 'image'; });
	}

	if ($typeSelect) {
		$typeSelect.addEventListener('change', syncCaptchaTypeUi);
		syncCaptchaTypeUi();
	}

	if (window.wpPowerSuite) {
		window.wpPowerSuite.syncModuleSettingsBeforeSave = window.wpPowerSuite.syncModuleSettingsBeforeSave || {};
		window.wpPowerSuite.syncModuleSettingsBeforeSave[mid] = function() {
			syncHidden();
		};
	}
})();
</script>
