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

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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 ?? 'ip-whitelist-blacklist' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'IP Allow & Block List requires an active license. Activate your license to configure IP rules.', '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 ) || empty( $module_id ) ) {
	$module_id = 'ip-whitelist-blacklist';
}

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

$ip_addresses_raw  = $settings['ip_addresses'] ?? '';
$ip_addresses_text = '';
if ( is_array( $ip_addresses_raw ) ) {
	$ip_addresses_text = implode( "\n", array_filter( array_map( 'trim', $ip_addresses_raw ), static function( $ip ) {
		return ! empty( $ip );
	} ) );
} elseif ( is_string( $ip_addresses_raw ) ) {
	$ip_addresses_text = $ip_addresses_raw;
}

$mode = $settings['mode'] ?? 'blacklist';
if ( ! in_array( $mode, [ 'blacklist', 'whitelist' ], true ) ) {
	$mode = 'blacklist';
}

$current_ip = class_exists( \IPWhitelistBlacklist\Module::class, false )
	? \IPWhitelistBlacklist\Module::getResolvedClientIp()
	: '0.0.0.0';

$ip_source_label = class_exists( \IPWhitelistBlacklist\Module::class, false )
	? \IPWhitelistBlacklist\Module::getIpSourceLabel()
	: '';

$ip_header = class_exists( \IPWhitelistBlacklist\Module::class, false )
	? \IPWhitelistBlacklist\Module::normalizeIpHeader( $settings['ip_header'] ?? '' )
	: sanitize_text_field( (string) ( $settings['ip_header'] ?? '' ) );

$ip_list = array_filter( array_map( 'trim', explode( "\n", $ip_addresses_text ) ), static function( $ip ) {
	return ! empty( $ip );
} );

$valid_ip_count = class_exists( \IPWhitelistBlacklist\Module::class, false )
	? count( \IPWhitelistBlacklist\Module::filterValidListEntries( array_values( $ip_list ) ) )
	: count( $ip_list );

$add_ip = isset( $_GET['add_ip'] ) ? sanitize_text_field( wp_unslash( $_GET['add_ip'] ) ) : '';
if ( ! empty( $add_ip ) && filter_var( $add_ip, FILTER_VALIDATE_IP ) && ! in_array( $add_ip, $ip_list, true ) ) {
	if ( ! empty( $ip_addresses_text ) ) {
		$ip_addresses_text .= "\n";
	}
	$ip_addresses_text .= $add_ip;
}

$blocked = $settings['blocked_page'] ?? [];
if ( ! is_array( $blocked ) ) {
	$blocked = [];
}
$bp_template_raw = isset( $blocked['blocked_template'] ) ? sanitize_key( (string) $blocked['blocked_template'] ) : 'default';
if ( $bp_template_raw === 'page' ) {
	$bp_template_raw = 'default';
}
$bp_template = in_array( $bp_template_raw, [ 'default', 'html' ], true ) ? $bp_template_raw : 'default';
$bp_logo_aid = isset( $blocked['logo_attachment_id'] ) ? (int) $blocked['logo_attachment_id'] : 0;
$bp_html_aid = isset( $blocked['blocked_html_attachment_id'] ) ? (int) $blocked['blocked_html_attachment_id'] : 0;

$bp_title    = $blocked['title'] ?? __( 'Access Denied', 'wp-powersuite' );
$bp_headline = $blocked['headline'] ?? __( 'Access Denied', 'wp-powersuite' );
$bp_message  = $blocked['message'] ?? '';
$bp_bg_raw   = isset( $blocked['bg_color'] ) ? (string) $blocked['bg_color'] : '#f0f0f1';
$bp_text_raw = isset( $blocked['text_color'] ) ? (string) $blocked['text_color'] : '#1d2327';
$h_bg        = ltrim( $bp_bg_raw, '#' );
$h_tx        = ltrim( $bp_text_raw, '#' );
$bp_bg_color   = preg_match( '/^[a-fA-F0-9]{3}$|^[a-fA-F0-9]{6}$/', $h_bg ) ? '#' . substr( $h_bg, 0, 6 ) : '#f0f0f1';
$bp_text_color = preg_match( '/^[a-fA-F0-9]{3}$|^[a-fA-F0-9]{6}$/', $h_tx ) ? '#' . substr( $h_tx, 0, 6 ) : '#1d2327';

$bp_logo_preview = '';
if ( $bp_logo_aid > 0 ) {
	$bp_logo_preview = wp_get_attachment_image_url( $bp_logo_aid, 'full' );
	if ( ! $bp_logo_preview ) {
		$bp_logo_preview = wp_get_attachment_url( $bp_logo_aid );
	}
}

$bp_html_filename = '';
if ( $bp_html_aid > 0 ) {
	$_att = get_post( $bp_html_aid );
	if ( $_att && $_att->post_type === 'attachment' ) {
		$bp_html_filename = basename( get_attached_file( $bp_html_aid ) ?: '' );
		if ( $bp_html_filename === '.' || $bp_html_filename === '' ) {
			$bp_html_filename = $bp_html_aid ? '#' . (string) $bp_html_aid : '';
		}
	}
}

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

<?php if ( ! empty( $add_ip ) ) : ?>
	<div class="wpps-settings-alert wpps-settings-alert--info" role="status">
		<p>
			<?php
			printf(
				/* translators: %s: IP address */
				esc_html__( 'IP address %s has been added to the list. Save settings to apply.', 'wp-powersuite' ),
				'<code>' . esc_html( $add_ip ) . '</code>'
			);
			?>
		</p>
	</div>
<?php endif; ?>

<div class="wpps-settings-alert wpps-settings-alert--warning" role="note">
	<p>
		<strong><?php esc_html_e( 'Important', 'wp-powersuite' ); ?></strong>
		<?php esc_html_e( 'In whitelist mode, add your IP and save before enabling enforcement — rules apply everywhere, including wp-admin and login. Dynamic IPs can lock you out. Saving is blocked if your current IP is not in the list.', 'wp-powersuite' ); ?>
		<?php
		wpps_render_modal_settings_tip(
			__( 'Help: IP enforcement', 'wp-powersuite' ),
			__( 'Rules apply to the public site, wp-admin, login, REST, AJAX, and XML-RPC. No role bypasses IP rules. Cloudflare (CF-Connecting-IP) is detected automatically. For other reverse proxies, set Real IP header below. Full-page cache plugins should not cache 403 responses. Override detection with filter wp_powersuite_ip_whitelist_blacklist_client_ip.', 'wp-powersuite' )
		);
		?>
	</p>
</div>

<?php if ( $mode === 'whitelist' && $valid_ip_count === 0 ) : ?>
	<div class="wpps-settings-alert wpps-settings-alert--info" role="status">
		<p><?php esc_html_e( 'Whitelist mode is selected but no valid IP addresses are configured — enforcement is inactive until you add at least one IP or CIDR range.', 'wp-powersuite' ); ?></p>
	</div>
<?php endif; ?>

<div class="wpps-settings-alert wpps-settings-alert--info" role="note">
	<p>
		<strong><?php esc_html_e( 'Locked out?', 'wp-powersuite' ); ?></strong>
		<?php esc_html_e( 'Disable this module via WP-CLI (wp option patch), edit wp_powersuite_settings in the database, rename the plugin folder via SFTP, or define WPPS_IP_ACCESS_BYPASS as true in wp-config.php temporarily.', 'wp-powersuite' ); ?>
	</p>
</div>

<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' ); ?>

		<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_rules" aria-expanded="true" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_rules">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'IP rules', '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_rules" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_rules">
					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<span><?php esc_html_e( 'Mode', 'wp-powersuite' ); ?></span>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: list mode', 'wp-powersuite' ),
								__( 'Blacklist blocks listed IPs; everyone else is allowed. Whitelist allows only listed IPs; everyone else is blocked site-wide.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<fieldset class="wpps-ipbp-mode-fieldset">
								<label class="wpps-ipbp-mode-option">
									<input
										type="radio"
										name="<?php echo esc_attr( $module_id ); ?>[mode]"
										value="blacklist"
										<?php checked( $mode, 'blacklist' ); ?>
										class="wp-powersuite-advanced-setting"
										data-setting-key="mode"
									/>
									<strong><?php esc_html_e( 'Blacklist', 'wp-powersuite' ); ?></strong>
									<span class="description"><?php esc_html_e( 'Blocks IPs in the list. Everyone else gets in.', 'wp-powersuite' ); ?></span>
								</label>
								<label class="wpps-ipbp-mode-option">
									<input
										type="radio"
										name="<?php echo esc_attr( $module_id ); ?>[mode]"
										value="whitelist"
										<?php checked( $mode, 'whitelist' ); ?>
										class="wp-powersuite-advanced-setting"
										data-setting-key="mode"
									/>
									<strong><?php esc_html_e( 'Whitelist', 'wp-powersuite' ); ?></strong>
									<span class="description"><?php esc_html_e( 'Allows only IPs in the list. Everyone else is blocked.', 'wp-powersuite' ); ?></span>
								</label>
							</fieldset>
						</div>
					</div>

					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<label for="<?php echo esc_attr( $module_id ); ?>_ip_addresses"><?php esc_html_e( 'IP addresses & ranges', 'wp-powersuite' ); ?></label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: IP list', 'wp-powersuite' ),
								__( 'One IPv4/IPv6 address or CIDR range per line. Use “Add my IP” to append your detected address (same resolver as enforcement, including Cloudflare).', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<textarea
								id="<?php echo esc_attr( $module_id ); ?>_ip_addresses"
								name="<?php echo esc_attr( $module_id ); ?>[ip_addresses]"
								rows="8"
								class="large-text code wp-powersuite-advanced-setting"
								data-setting-key="ip_addresses"
								placeholder="<?php echo esc_attr( implode( "\n", [ '192.168.1.100', '10.0.0.50', '203.0.113.0/24', '2001:db8::1' ] ) ); ?>"
								spellcheck="false"
							><?php echo esc_textarea( $ip_addresses_text ); ?></textarea>
							<p class="description">
								<?php esc_html_e( 'One IP or CIDR per line. IPv4 and IPv6 supported.', 'wp-powersuite' ); ?>
								<code>192.168.1.0/24</code>,
								<code>10.0.0.0/8</code>,
								<code>2001:db8::1</code>
							</p>
							<p class="description">
								<?php
								printf(
									/* translators: 1: detected client IP, 2: IP source label */
									esc_html__( 'Detected client IP: %1$s (%2$s)', 'wp-powersuite' ),
									'<code>' . esc_html( $current_ip ) . '</code>',
									esc_html( $ip_source_label !== '' ? $ip_source_label : __( 'unknown source', 'wp-powersuite' ) )
								);
								?>
							</p>
							<p>
								<button type="button" class="button button-secondary" id="<?php echo esc_attr( $module_id ); ?>_add_my_ip">
									<?php esc_html_e( 'Add my IP to list', 'wp-powersuite' ); ?>
								</button>
								<span id="<?php echo esc_attr( $module_id ); ?>_add_ip_feedback" class="wpps-ipbp-add-ip-feedback" aria-live="polite"></span>
							</p>
						</div>
					</div>

					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<label for="<?php echo esc_attr( $module_id ); ?>_ip_header"><?php esc_html_e( 'Real IP header', 'wp-powersuite' ); ?></label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: proxy IP header', 'wp-powersuite' ),
								__( 'Leave blank for automatic detection (Cloudflare CF-Connecting-IP, then REMOTE_ADDR). For other trusted reverse proxies, set the PHP $_SERVER key (e.g. HTTP_X_REAL_IP). X-Forwarded-For and similar spoofable headers are not allowed.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<input
								type="text"
								id="<?php echo esc_attr( $module_id ); ?>_ip_header"
								name="<?php echo esc_attr( $module_id ); ?>[ip_header]"
								value="<?php echo esc_attr( $ip_header ); ?>"
								class="regular-text wp-powersuite-advanced-setting"
								data-setting-key="ip_header"
								placeholder="<?php echo esc_attr( 'HTTP_X_REAL_IP' ); ?>"
								spellcheck="false"
							/>
						</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_blocked" aria-expanded="false" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_blocked">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'Blocked page', '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_blocked" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_blocked">
					<div class="wpps-ts-field">
						<div class="wpps-ts-field__label-row">
							<span><?php esc_html_e( 'Response type', 'wp-powersuite' ); ?></span>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: blocked page', 'wp-powersuite' ),
								__( 'Choose the built-in layout or serve a custom HTML file from the media library when a visitor is blocked.', 'wp-powersuite' )
							);
							?>
						</div>
						<div class="wpps-ts-field__control">
							<div class="wpps-check-grid">
								<label>
									<input type="radio" name="<?php echo esc_attr( $module_id ); ?>[blocked_page][blocked_template]" value="default" class="wp-powersuite-advanced-setting wpps-ipbp-template-radio" data-setting-key="blocked_page.blocked_template" <?php checked( $bp_template, 'default' ); ?> />
									<?php esc_html_e( 'Built-in template', 'wp-powersuite' ); ?>
								</label>
								<label>
									<input type="radio" name="<?php echo esc_attr( $module_id ); ?>[blocked_page][blocked_template]" value="html" class="wp-powersuite-advanced-setting wpps-ipbp-template-radio" data-setting-key="blocked_page.blocked_template" <?php checked( $bp_template, 'html' ); ?> />
									<?php esc_html_e( 'HTML file (media library)', 'wp-powersuite' ); ?>
								</label>
							</div>
						</div>
					</div>

					<div id="<?php echo esc_attr( $module_id ); ?>_bp_panel_default" class="wpps-ipbp-panel-default"<?php echo $bp_template === 'default' ? '' : ' hidden'; ?>>
						<div class="wpps-ts-field">
							<div class="wpps-ts-field__label-row">
								<label for="<?php echo esc_attr( $module_id ); ?>_bp_title"><?php esc_html_e( 'Page title', 'wp-powersuite' ); ?></label>
							</div>
							<div class="wpps-ts-field__control">
								<input type="text" id="<?php echo esc_attr( $module_id ); ?>_bp_title" name="<?php echo esc_attr( $module_id ); ?>[blocked_page][title]" value="<?php echo esc_attr( $bp_title ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="blocked_page.title" />
							</div>
						</div>
						<div class="wpps-ts-field">
							<div class="wpps-ts-field__label-row">
								<label for="<?php echo esc_attr( $module_id ); ?>_bp_headline"><?php esc_html_e( 'Headline', 'wp-powersuite' ); ?></label>
							</div>
							<div class="wpps-ts-field__control">
								<input type="text" id="<?php echo esc_attr( $module_id ); ?>_bp_headline" name="<?php echo esc_attr( $module_id ); ?>[blocked_page][headline]" value="<?php echo esc_attr( $bp_headline ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="blocked_page.headline" />
							</div>
						</div>
						<div class="wpps-ts-field">
							<div class="wpps-ts-field__label-row">
								<label for="<?php echo esc_attr( $module_id ); ?>_bp_message"><?php esc_html_e( 'Message', 'wp-powersuite' ); ?></label>
							</div>
							<div class="wpps-ts-field__control">
								<textarea id="<?php echo esc_attr( $module_id ); ?>_bp_message" name="<?php echo esc_attr( $module_id ); ?>[blocked_page][message]" rows="3" class="large-text wp-powersuite-advanced-setting" data-setting-key="blocked_page.message"><?php echo esc_textarea( $bp_message ); ?></textarea>
								<p class="description"><?php esc_html_e( 'Leave blank to use the default message for blacklist or whitelist mode.', 'wp-powersuite' ); ?></p>
							</div>
						</div>
						<div class="wpps-ts-field">
							<div class="wpps-ts-field__label-row">
								<span><?php esc_html_e( 'Logo', 'wp-powersuite' ); ?></span>
							</div>
							<div class="wpps-ts-field__control">
								<input type="hidden" id="<?php echo esc_attr( $module_id ); ?>_bp_logo_attachment_id" name="<?php echo esc_attr( $module_id ); ?>[blocked_page][logo_attachment_id]" value="<?php echo esc_attr( (string) $bp_logo_aid ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="blocked_page.logo_attachment_id" />
								<button type="button" class="button" id="<?php echo esc_attr( $module_id ); ?>_bp_upload_logo"><?php esc_html_e( 'Select image', 'wp-powersuite' ); ?></button>
								<button type="button" class="button" id="<?php echo esc_attr( $module_id ); ?>_bp_remove_logo" <?php echo $bp_logo_aid ? '' : ' hidden'; ?>><?php esc_html_e( 'Remove', 'wp-powersuite' ); ?></button>
								<div class="wpps-ipbp-logo-preview-wrap" id="<?php echo esc_attr( $module_id ); ?>_bp_logo_preview_wrap">
									<?php if ( $bp_logo_preview ) : ?>
										<div class="wpps-ipbp-logo-preview-box">
											<button type="button" class="wpps-ipbp-logo-remove" aria-label="<?php esc_attr_e( 'Remove logo', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-no-alt"></span></button>
											<img src="<?php echo esc_url( $bp_logo_preview ); ?>" alt="" />
										</div>
									<?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 ); ?>_bp_bg"><?php esc_html_e( 'Background color', 'wp-powersuite' ); ?></label>
							</div>
							<div class="wpps-ts-field__control">
								<div class="wpps-color-field-row">
									<input type="color" id="<?php echo esc_attr( $module_id ); ?>_bp_bg" name="<?php echo esc_attr( $module_id ); ?>[blocked_page][bg_color]" value="<?php echo esc_attr( $bp_bg_color ); ?>" class="wp-powersuite-advanced-setting wpps-color-picker-circle" data-setting-key="blocked_page.bg_color" aria-label="<?php esc_attr_e( 'Background color', 'wp-powersuite' ); ?>" />
									<div class="wpps-color-code-wrap">
										<input type="text" class="wpps-color-code-input regular-text wp-powersuite-advanced-setting" data-setting-key="blocked_page.bg_color" data-color-input="<?php echo esc_attr( $module_id ); ?>_bp_bg" data-default-color="#f0f0f1" value="<?php echo esc_attr( $bp_bg_color ); ?>" style="width: 100px; padding-right: 25px;" placeholder="#f0f0f1" maxlength="9" aria-label="<?php esc_attr_e( 'Hex color code', 'wp-powersuite' ); ?>" />
										<button type="button" class="wpps-color-reset button-link" data-default-color="#f0f0f1" aria-label="<?php esc_attr_e( 'Reset to default', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-undo" style="font-size: 16px; width: 16px; height: 16px;"></span></button>
									</div>
								</div>
							</div>
						</div>
						<div class="wpps-ts-field">
							<div class="wpps-ts-field__label-row">
								<label for="<?php echo esc_attr( $module_id ); ?>_bp_text"><?php esc_html_e( 'Text color', 'wp-powersuite' ); ?></label>
							</div>
							<div class="wpps-ts-field__control">
								<div class="wpps-color-field-row">
									<input type="color" id="<?php echo esc_attr( $module_id ); ?>_bp_text" name="<?php echo esc_attr( $module_id ); ?>[blocked_page][text_color]" value="<?php echo esc_attr( $bp_text_color ); ?>" class="wp-powersuite-advanced-setting wpps-color-picker-circle" data-setting-key="blocked_page.text_color" aria-label="<?php esc_attr_e( 'Text color', 'wp-powersuite' ); ?>" />
									<div class="wpps-color-code-wrap">
										<input type="text" class="wpps-color-code-input regular-text wp-powersuite-advanced-setting" data-setting-key="blocked_page.text_color" data-color-input="<?php echo esc_attr( $module_id ); ?>_bp_text" data-default-color="#1d2327" value="<?php echo esc_attr( $bp_text_color ); ?>" style="width: 100px; padding-right: 25px;" placeholder="#1d2327" maxlength="9" aria-label="<?php esc_attr_e( 'Hex color code', 'wp-powersuite' ); ?>" />
										<button type="button" class="wpps-color-reset button-link" data-default-color="#1d2327" aria-label="<?php esc_attr_e( 'Reset to default', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-undo" style="font-size: 16px; width: 16px; height: 16px;"></span></button>
									</div>
								</div>
							</div>
						</div>
					</div>

					<div id="<?php echo esc_attr( $module_id ); ?>_bp_panel_html" class="wpps-ipbp-panel-html"<?php echo $bp_template === 'html' ? '' : ' hidden'; ?>>
						<div class="wpps-ts-field">
							<div class="wpps-ts-field__label-row">
								<span><?php esc_html_e( 'HTML file', 'wp-powersuite' ); ?></span>
							</div>
							<div class="wpps-ts-field__control">
								<input type="hidden" id="<?php echo esc_attr( $module_id ); ?>_bp_html_attachment_id" name="<?php echo esc_attr( $module_id ); ?>[blocked_page][blocked_html_attachment_id]" value="<?php echo esc_attr( (string) $bp_html_aid ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="blocked_page.blocked_html_attachment_id" />
								<button type="button" class="button" id="<?php echo esc_attr( $module_id ); ?>_bp_upload_html"><?php esc_html_e( 'Upload / select HTML file', 'wp-powersuite' ); ?></button>
								<button type="button" class="button" id="<?php echo esc_attr( $module_id ); ?>_bp_remove_html" <?php echo $bp_html_aid ? '' : ' hidden'; ?>><?php esc_html_e( 'Remove', 'wp-powersuite' ); ?></button>
								<p id="<?php echo esc_attr( $module_id ); ?>_bp_html_filename" class="wpps-ipbp-html-filename"<?php echo $bp_html_filename ? '' : ' hidden'; ?>><?php echo esc_html( $bp_html_filename ); ?></p>
								<p class="description"><?php esc_html_e( 'Upload a .html file or choose one from the media library. Full HTML documents are sent as-is; partial markup is wrapped in a minimal document.', 'wp-powersuite' ); ?></p>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</form>

	<style>
		.wp-powersuite-modal .wpps-ipbp-mode-fieldset { border: 0; margin: 0; padding: 0; }
		.wp-powersuite-modal .wpps-ipbp-mode-option { display: block; margin-bottom: 12px; }
		.wp-powersuite-modal .wpps-ipbp-mode-option strong { margin-right: 6px; }
		.wp-powersuite-modal .wpps-ipbp-mode-option .description { display: block; margin: 4px 0 0 24px; }
		.wp-powersuite-modal .wpps-ipbp-add-ip-feedback { margin-left: 10px; }
		.wp-powersuite-modal .wpps-ipbp-logo-preview-wrap { margin-top: 8px; }
		.wp-powersuite-modal .wpps-ipbp-logo-preview-box { position: relative; display: inline-block; }
		.wp-powersuite-modal .wpps-ipbp-logo-preview-box img { max-width: 200px; height: auto; border: 1px solid #ddd; padding: 5px; display: block; }
		.wp-powersuite-modal .wpps-ipbp-logo-remove { position: absolute; top: 4px; right: 4px; width: 24px; height: 24px; padding: 0; border: none; border-radius: 50%; background: #d63638; color: #fff; cursor: pointer; display: flex; align-items: center; justify-content: center; }
		.wp-powersuite-modal .wpps-ipbp-html-filename { margin-top: 8px; font-family: monospace; font-size: 13px; }
		.wp-powersuite-modal .wpps-settings-panel--accordion-stack .wpps-color-field-row { display: inline-flex; align-items: center; gap: 10px; flex-wrap: nowrap; }
		.wp-powersuite-modal .wpps-settings-panel--accordion-stack .wpps-color-picker-circle { width: 40px !important; height: 40px !important; min-width: 40px; min-height: 40px; flex-shrink: 0; border-radius: 50% !important; border: 2px solid #ddd !important; padding: 0 !important; cursor: pointer; -webkit-appearance: none !important; -moz-appearance: none !important; appearance: none !important; overflow: hidden; }
		.wp-powersuite-modal .wpps-settings-panel--accordion-stack .wpps-color-picker-circle::-webkit-color-swatch-wrapper { padding: 0 !important; margin: 0 !important; border: none !important; border-radius: 50% !important; }
		.wp-powersuite-modal .wpps-settings-panel--accordion-stack .wpps-color-picker-circle::-webkit-color-swatch { border: none !important; border-radius: 50% !important; width: 100% !important; height: 100% !important; }
		.wp-powersuite-modal .wpps-settings-panel--accordion-stack .wpps-color-picker-circle::-moz-color-swatch { border: none !important; border-radius: 50% !important; width: 100% !important; height: 100% !important; }
		.wp-powersuite-modal .wpps-settings-panel--accordion-stack .wpps-color-code-wrap { display: inline-block; position: relative; margin: 0; flex-shrink: 0; }
		.wp-powersuite-modal .wpps-settings-panel--accordion-stack .wpps-color-code-wrap .wpps-color-reset { position: absolute; right: 5px; top: 50%; transform: translateY(-50%); padding: 0; margin: 0; background: none; border: none; cursor: pointer; color: #646970; }
		.wp-powersuite-modal .wpps-settings-panel--accordion-stack .wpps-color-code-wrap .wpps-color-reset:hover { color: #2271b1; }
		.wp-powersuite-modal .wpps-settings-panel--accordion-stack .wpps-color-code-wrap .wpps-color-reset .dashicons { font-size: 16px; width: 16px; height: 16px; }
	</style>

	<script>
	(function($) {
		$(document).ready(function() {
			var mid = '<?php echo esc_js( $module_id ); ?>';
			var $panel = $('.wpps-settings-panel--accordion-stack[data-module-id="' + mid + '"]');

			$('#' + mid + '_add_my_ip').on('click', function() {
				var currentIP = '<?php echo esc_js( $current_ip ); ?>';
				var $textarea = $('#' + mid + '_ip_addresses');
				var currentValue = $textarea.val();
				var $feedback = $('#' + mid + '_add_ip_feedback');
				var lines = currentValue.split('\n');
				var ipExists = false;
				for (var i = 0; i < lines.length; i++) {
					if (lines[i].trim() === currentIP) { ipExists = true; break; }
				}
				if (ipExists) {
					$feedback.html('<span style="color:#d63638;"><?php echo esc_js( __( 'IP already in list', 'wp-powersuite' ) ); ?></span>');
					setTimeout(function() { $feedback.empty(); }, 3000);
					return;
				}
				if (currentValue.trim() !== '') { currentValue += '\n'; }
				$textarea.val(currentValue + currentIP).trigger('change');
				$feedback.html('<span style="color:#00a32a;"><?php echo esc_js( __( 'IP added successfully', 'wp-powersuite' ) ); ?></span>');
				setTimeout(function() { $feedback.empty(); }, 3000);
			});

			function refreshIpbpPanels() {
				var v = $panel.find('.wpps-ipbp-template-radio:checked').val() || 'default';
				$('#' + mid + '_bp_panel_default').prop('hidden', v !== 'default');
				$('#' + mid + '_bp_panel_html').prop('hidden', v !== 'html');
			}
			$panel.on('change', '.wpps-ipbp-template-radio', refreshIpbpPanels);
			refreshIpbpPanels();

			$panel.on('click', '.wpps-color-reset', function(e) {
				e.preventDefault();
				var def = $(this).data('default-color');
				var $hex = $(this).closest('.wpps-color-code-wrap').find('.wpps-color-code-input');
				var cid = $hex.data('color-input');
				if (cid && typeof jQuery.escapeSelector === 'function') {
					$('#' + jQuery.escapeSelector(cid)).val(def);
				} else if (cid) {
					var cEl = document.getElementById(cid);
					if (cEl) { cEl.value = def; }
				}
				$hex.val(def).trigger('change');
			});

			$panel.on('input change', '.wpps-color-picker-circle', function() {
				var cid = this.id;
				if (!cid) { return; }
				$panel.find('.wpps-color-code-input[data-color-input="' + cid + '"]').val(this.value).trigger('change');
			});

			var $logoWrap = $('#' + mid + '_bp_logo_preview_wrap');
			var $logoHid = $('#' + mid + '_bp_logo_attachment_id');
			var $logoRm = $('#' + mid + '_bp_remove_logo');
			function showLogoPreview(url) {
				var rt = '<?php echo esc_js( __( 'Remove logo', 'wp-powersuite' ) ); ?>';
				$logoWrap.html('<div class="wpps-ipbp-logo-preview-box"><button type="button" class="wpps-ipbp-logo-remove" aria-label="' + rt + '"><span class="dashicons dashicons-no-alt"></span></button><img src="' + url + '" alt="" /></div>');
				$logoRm.prop('hidden', false);
				$logoHid.trigger('change');
			}
			$('#' + mid + '_bp_upload_logo').on('click', function(e) {
				e.preventDefault();
				if (typeof wp === 'undefined' || !wp.media) { return; }
				var frame = wp.media({ title: '<?php echo esc_js( __( 'Select logo', 'wp-powersuite' ) ); ?>', button: { text: '<?php echo esc_js( __( 'Use this image', 'wp-powersuite' ) ); ?>' }, multiple: false, library: { type: 'image' } });
				frame.on('select', function() {
					var att = frame.state().get('selection').first().toJSON();
					$logoHid.val(att.id ? String(att.id) : '');
					if (att.url) { showLogoPreview(att.url); }
				});
				frame.open();
			});
			$logoWrap.on('click', '.wpps-ipbp-logo-remove', function() {
				$logoHid.val('').trigger('change');
				$logoWrap.empty();
				$logoRm.prop('hidden', true);
			});
			$logoRm.on('click', function() {
				$logoHid.val('').trigger('change');
				$logoWrap.empty();
				$(this).prop('hidden', true);
			});

			var $htmlHid = $('#' + mid + '_bp_html_attachment_id');
			var $htmlFn = $('#' + mid + '_bp_html_filename');
			var $htmlRm = $('#' + mid + '_bp_remove_html');
			$('#' + mid + '_bp_upload_html').on('click', function(e) {
				e.preventDefault();
				if (typeof wp === 'undefined' || !wp.media) { return; }
				var frame = wp.media({
					title: '<?php echo esc_js( __( 'Select HTML file', 'wp-powersuite' ) ); ?>',
					button: { text: '<?php echo esc_js( __( 'Use this file', 'wp-powersuite' ) ); ?>' },
					multiple: false,
					library: { type: '' }
				});
				frame.on('select', function() {
					var att = frame.state().get('selection').first().toJSON();
					var mime = String(att.mime || '').toLowerCase();
					var fname = String(att.filename || att.url || '').split('/').pop() || '';
					var extOk = /\.html?$/i.test(fname);
					var mimeOk = mime.indexOf('html') !== -1 || mime.indexOf('text') !== -1 || mime === 'application/octet-stream' || mime === '';
					if (!extOk && !mimeOk) {
						window.alert('<?php echo esc_js( __( 'Please choose an HTML file.', 'wp-powersuite' ) ); ?>');
						return;
					}
					$htmlHid.val(att.id ? String(att.id) : '').trigger('change');
					$htmlFn.text(fname || ('#' + att.id)).prop('hidden', false);
					$htmlRm.prop('hidden', false);
				});
				frame.open();
			});
			$htmlRm.on('click', function() {
				$htmlHid.val('').trigger('change');
				$htmlFn.prop('hidden', true).text('');
				$(this).prop('hidden', true);
			});
		});
	})(jQuery);
	</script>
</div>
