<?php
/**
 * Accessibility Widget — advanced settings UI.
 *
 * @package AccessibilityWidget
 */

namespace AccessibilityWidget;

use WP_PowerSuite\Core\Http\AjaxRouter;
use WP_PowerSuite\Core\NetworkScope;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

require_once __DIR__ . '/FeatureGate.php';

/**
 * Capability gate for the settings screen. Filterable so site owners can grant
 * access to other roles without touching core capability mapping.
 */
$wpps_a11y_capability = (string) apply_filters( 'wp_powersuite_a11y_settings_capability', NetworkScope::adminCapability() );
if ( ! current_user_can( $wpps_a11y_capability ) ) {
	return;
}

$module_id = isset( $module_id ) ? (string) $module_id : 'accessibility-widget';

if ( ! class_exists( '\AccessibilityWidget\Module', false ) ) {
	$wpps_a11y_module_file = WP_POWERSUITE_MODULES_DIR . 'accessibility-widget' . DIRECTORY_SEPARATOR . 'module.php';
	if ( is_readable( $wpps_a11y_module_file ) ) {
		require_once $wpps_a11y_module_file;
	}
}

if ( ! class_exists( '\AccessibilityWidget\Module', false ) ) {
	echo '<div class="notice notice-error inline"><p>' . esc_html__( 'Accessibility Widget module could not be loaded.', 'wp-powersuite' ) . '</p></div>';
	return;
}

$premium_unlocked = FeatureGate::isPremiumLicensed();
$license_page_url = admin_url( 'admin.php?page=powersuite-license' );

$raw      = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$settings = Module::normalizeSettings( is_array( $raw ) ? $raw : [] );

$position       = (string) $settings['position'];
$button_size    = (string) $settings['button_size'];
$button_icon    = (string) $settings['button_icon'];
$button_color   = (string) $settings['button_color'];
$panel_layout   = (string) $settings['panel_layout'];
$features        = is_array( $settings['features'] ) ? $settings['features'] : [];
$tool_order      = is_array( $settings['tool_order'] ) ? $settings['tool_order'] : Module::getToolKeys();
$excluded_types  = is_array( $settings['excluded_post_types'] ) ? $settings['excluded_post_types'] : [];

$tool_labels   = Module::getToolLabels();
$tool_registry = Module::getToolRegistry();

$section_labels = [
	'profiles'   => __( 'Profiles', 'wp-powersuite' ),
	'vision'     => __( 'Vision', 'wp-powersuite' ),
	'reading'    => __( 'Reading', 'wp-powersuite' ),
	'navigation' => __( 'Navigation', 'wp-powersuite' ),
	'tools'      => __( 'Tools', 'wp-powersuite' ),
	'motion'     => __( 'Motion', 'wp-powersuite' ),
];

$icon_labels = [
	'accessibility'   => __( 'Universal access', 'wp-powersuite' ),
	'wheelchair'      => __( 'Wheelchair', 'wp-powersuite' ),
	'wheelchair-move' => __( 'Active wheelchair', 'wp-powersuite' ),
	'person'          => __( 'Person', 'wp-powersuite' ),
	'eye'             => __( 'Eye (vision)', 'wp-powersuite' ),
	'low-vision'      => __( 'Low vision', 'wp-powersuite' ),
	'ear'             => __( 'Ear (hearing)', 'wp-powersuite' ),
	'hands'           => __( 'Sign language', 'wp-powersuite' ),
	'braille'         => __( 'Braille', 'wp-powersuite' ),
];

$button_icon_size  = (string) ( $settings['button_icon_size'] ?? 'medium' );
$button_icon_color = (string) ( $settings['button_icon_color'] ?? '' );
$button_icon_color_auto = ! isset( $settings['button_icon_color_auto'] ) || ! empty( $settings['button_icon_color_auto'] );
$widget_offset     = (int) ( $settings['widget_offset'] ?? 20 );
$widget_offset_y   = (int) ( $settings['widget_offset_y'] ?? 20 );
$statement_type    = (string) ( $settings['statement_type'] ?? 'link' );

$enabled_feature_keys = [];
foreach ( Module::getFeatureKeys() as $feature_key ) {
	if ( ! empty( $features[ $feature_key ] ) ) {
		$enabled_feature_keys[] = $feature_key;
	}
}

$internal_post_types = [ 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block' ];
$available_types     = [];
foreach ( get_post_types( [ 'public' => true ], 'objects' ) as $post_type_name => $post_type_object ) {
	if ( ! in_array( $post_type_name, $internal_post_types, true ) ) {
		$available_types[ $post_type_name ] = $post_type_object;
	}
}

$scan_url_default = home_url( '/' );
$ajax_nonce       = wp_create_nonce( AjaxRouter::NONCE_ACTION );

?>

<div class="wp-powersuite-module-settings wpps-a11y-widget-settings">
	<p class="description">
		<?php esc_html_e( 'Add a floating widget that lets visitors adjust text, contrast, motion, and navigation helpers. This improves usability but does not replace accessible themes, semantic markup, alt text, keyboard support, or manual testing.', 'wp-powersuite' ); ?>
	</p>

	<?php if ( ! $premium_unlocked ) : ?>
		<div class="notice notice-info inline" style="margin:12px 0;">
			<p style="margin:0;">
				<?php
				echo wp_kses_post(
					sprintf(
						/* translators: %s: license page URL */
						__( 'Core controls (text size, contrast, grayscale/invert, highlights, spacing, reading guide, skip link, focus, and more) are free. Advanced tools (profiles, color-blind filters, saturation, dyslexia font, text-to-speech, link navigator, page structure, mute sounds, simplified layout) are Premium. <a href="%s">Activate your license</a> to enable them.', 'wp-powersuite' ),
						esc_url( $license_page_url )
					)
				);
				?>
			</p>
		</div>
	<?php endif; ?>

	<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" class="wp-powersuite-advanced-setting" data-setting-key="tool_order" id="wpps_a11y_tool_order" value="<?php echo esc_attr( implode( ',', $tool_order ) ); ?>" />
		<input type="hidden" class="wp-powersuite-advanced-setting" data-setting-key="enabled_features" id="wpps_a11y_enabled_features" value="<?php echo esc_attr( implode( ',', $enabled_feature_keys ) ); ?>" />
		<input type="hidden" class="wp-powersuite-advanced-setting" data-setting-key="button_icon" id="wpps_a11y_button_icon" value="<?php echo esc_attr( $button_icon ); ?>" />

		<div class="wpps-a11y-acc-group">
		<details class="wpps-a11y-acc" open>
			<summary class="wpps-a11y-acc__summary"><span class="wpps-a11y-acc__title"><?php esc_html_e( 'Options', 'wp-powersuite' ); ?></span><span class="dashicons dashicons-arrow-down-alt2 wpps-a11y-acc__chev" aria-hidden="true"></span></summary>
			<div class="wpps-a11y-acc__body">
		<p class="description"><?php esc_html_e( 'The widget shows on the public site whenever this module is enabled. These options control how it behaves.', 'wp-powersuite' ); ?></p>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Show on mobile', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" name="show_on_mobile" value="1" class="wp-powersuite-advanced-setting" data-setting-key="show_on_mobile" <?php checked( ! empty( $settings['show_on_mobile'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Show the floating button on small screens.', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Auto display', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" name="auto_display" value="1" class="wp-powersuite-advanced-setting" data-setting-key="auto_display" <?php checked( ! empty( $settings['auto_display'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Show the floating button automatically. Disable to place it only via the shortcode.', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Save visitor preferences', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" name="save_preferences" value="1" class="wp-powersuite-advanced-setting" data-setting-key="save_preferences" <?php checked( ! empty( $settings['save_preferences'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Remember each visitor’s choices in their browser (localStorage). No database writes.', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
			</tbody>
		</table>
			</div>
		</details>

		<details class="wpps-a11y-acc">
			<summary class="wpps-a11y-acc__summary"><span class="wpps-a11y-acc__title"><?php esc_html_e( 'Display', 'wp-powersuite' ); ?></span><span class="dashicons dashicons-arrow-down-alt2 wpps-a11y-acc__chev" aria-hidden="true"></span></summary>
			<div class="wpps-a11y-acc__body">
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_position"><?php esc_html_e( 'Button position', 'wp-powersuite' ); ?></label></th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_position" name="position" class="wp-powersuite-advanced-setting" data-setting-key="position">
							<option value="bottom-right" <?php selected( $position, 'bottom-right' ); ?>><?php esc_html_e( 'Bottom right', 'wp-powersuite' ); ?></option>
							<option value="bottom-left" <?php selected( $position, 'bottom-left' ); ?>><?php esc_html_e( 'Bottom left', 'wp-powersuite' ); ?></option>
							<option value="middle-right" <?php selected( $position, 'middle-right' ); ?>><?php esc_html_e( 'Middle right', 'wp-powersuite' ); ?></option>
							<option value="middle-left" <?php selected( $position, 'middle-left' ); ?>><?php esc_html_e( 'Middle left', 'wp-powersuite' ); ?></option>
							<option value="top-right" <?php selected( $position, 'top-right' ); ?>><?php esc_html_e( 'Top right', 'wp-powersuite' ); ?></option>
							<option value="top-left" <?php selected( $position, 'top-left' ); ?>><?php esc_html_e( 'Top left', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Where the floating button is anchored on every screen size.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Button icon', 'wp-powersuite' ); ?></th>
					<td>
						<div class="wpps-a11y-iconpicker" id="<?php echo esc_attr( $module_id ); ?>_iconpicker" role="group" aria-label="<?php esc_attr_e( 'Button icon', 'wp-powersuite' ); ?>">
							<?php foreach ( $icon_labels as $icon_key => $icon_label ) : ?>
								<button type="button" class="wpps-a11y-iconpicker__opt<?php echo $button_icon === $icon_key ? ' is-selected' : ''; ?>" data-icon="<?php echo esc_attr( $icon_key ); ?>" aria-pressed="<?php echo $button_icon === $icon_key ? 'true' : 'false'; ?>" title="<?php echo esc_attr( $icon_label ); ?>" aria-label="<?php echo esc_attr( $icon_label ); ?>">
									<span class="wpps-a11y-iconpicker__glyph" aria-hidden="true"><?php echo Module::getIconSvg( (string) $icon_key ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static SVG. ?></span>
								</button>
							<?php endforeach; ?>
						</div>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_button_size"><?php esc_html_e( 'Button size', 'wp-powersuite' ); ?></label></th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_button_size" name="button_size" class="wp-powersuite-advanced-setting" data-setting-key="button_size">
							<option value="small" <?php selected( $button_size, 'small' ); ?>><?php esc_html_e( 'Small', 'wp-powersuite' ); ?></option>
							<option value="medium" <?php selected( $button_size, 'medium' ); ?>><?php esc_html_e( 'Medium', 'wp-powersuite' ); ?></option>
							<option value="large" <?php selected( $button_size, 'large' ); ?>><?php esc_html_e( 'Large', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_button_icon_size"><?php esc_html_e( 'Icon size &amp; padding', 'wp-powersuite' ); ?></label></th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_button_icon_size" name="button_icon_size" class="wp-powersuite-advanced-setting" data-setting-key="button_icon_size">
							<option value="small" <?php selected( $button_icon_size, 'small' ); ?>><?php esc_html_e( 'Small icon (more padding)', 'wp-powersuite' ); ?></option>
							<option value="medium" <?php selected( $button_icon_size, 'medium' ); ?>><?php esc_html_e( 'Medium', 'wp-powersuite' ); ?></option>
							<option value="large" <?php selected( $button_icon_size, 'large' ); ?>><?php esc_html_e( 'Large icon (less padding)', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Controls how large the glyph is inside the button.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_button_icon_color"><?php esc_html_e( 'Icon color', 'wp-powersuite' ); ?></label></th>
					<td>
						<?php $icon_color_hex = preg_match( '/^#[a-f0-9]{6}$/i', $button_icon_color ) ? $button_icon_color : '#ffffff'; ?>
						<div class="wpps-color-field-row wpps-a11y-iconcolor">
							<input type="color" id="<?php echo esc_attr( $module_id ); ?>_button_icon_color" name="button_icon_color" value="<?php echo esc_attr( $icon_color_hex ); ?>" class="wp-powersuite-advanced-setting wpps-color-picker-circle" data-setting-key="button_icon_color" />
							<div class="wpps-color-code-wrap">
								<input type="text" class="wpps-color-code-input regular-text wp-powersuite-advanced-setting" data-setting-key="button_icon_color" data-color-input="<?php echo esc_attr( $module_id ); ?>_button_icon_color" data-default-color="#ffffff" value="<?php echo esc_attr( $icon_color_hex ); ?>" maxlength="9" placeholder="#ffffff" />
								<button type="button" class="wpps-color-reset button-link" data-default-color="#ffffff" title="<?php esc_attr_e( 'Reset', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-undo"></span></button>
							</div>
						</div>
						<p>
							<label>
								<input type="checkbox" name="button_icon_color_auto" value="1" class="wp-powersuite-advanced-setting wpps-a11y-icon-auto" data-setting-key="button_icon_color_auto" <?php checked( $button_icon_color_auto ); ?> />
								<?php esc_html_e( 'Automatic (best contrast with the accent color)', 'wp-powersuite' ); ?>
							</label>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_widget_offset"><?php esc_html_e( 'Edge spacing', 'wp-powersuite' ); ?></label></th>
					<td>
						<label style="display:inline-flex;align-items:center;gap:6px;margin-inline-end:16px;">
							<span><?php esc_html_e( 'Horizontal', 'wp-powersuite' ); ?></span>
							<input type="number" min="0" max="120" step="1" id="<?php echo esc_attr( $module_id ); ?>_widget_offset" name="widget_offset" value="<?php echo esc_attr( (string) $widget_offset ); ?>" class="small-text wp-powersuite-advanced-setting" data-setting-key="widget_offset" /> <?php esc_html_e( 'px', 'wp-powersuite' ); ?>
						</label>
						<label style="display:inline-flex;align-items:center;gap:6px;">
							<span><?php esc_html_e( 'Vertical', 'wp-powersuite' ); ?></span>
							<input type="number" min="0" max="120" step="1" id="<?php echo esc_attr( $module_id ); ?>_widget_offset_y" name="widget_offset_y" value="<?php echo esc_attr( (string) $widget_offset_y ); ?>" class="small-text wp-powersuite-advanced-setting" data-setting-key="widget_offset_y" /> <?php esc_html_e( 'px', 'wp-powersuite' ); ?>
						</label>
						<p class="description"><?php esc_html_e( 'Distance between the floating button and the screen edges. Vertical spacing is ignored for the middle positions (always centered).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_panel_layout"><?php esc_html_e( 'Panel layout', 'wp-powersuite' ); ?></label></th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_panel_layout" name="panel_layout" class="wp-powersuite-advanced-setting" data-setting-key="panel_layout">
							<option value="list" <?php selected( $panel_layout, 'list' ); ?>><?php esc_html_e( 'List (single column)', 'wp-powersuite' ); ?></option>
							<option value="grid" <?php selected( $panel_layout, 'grid' ); ?>><?php esc_html_e( 'Grid (two columns)', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_button_color"><?php esc_html_e( 'Accent color', 'wp-powersuite' ); ?></label></th>
					<td>
						<?php $accent_hex = preg_match( '/^#[a-f0-9]{6}$/i', $button_color ) ? $button_color : '#2271b1'; ?>
						<div class="wpps-color-field-row">
							<input type="color" id="<?php echo esc_attr( $module_id ); ?>_button_color" name="button_color" value="<?php echo esc_attr( $accent_hex ); ?>" class="wp-powersuite-advanced-setting wpps-color-picker-circle" data-setting-key="button_color" />
							<div class="wpps-color-code-wrap">
								<input type="text" class="wpps-color-code-input regular-text wp-powersuite-advanced-setting" data-setting-key="button_color" data-color-input="<?php echo esc_attr( $module_id ); ?>_button_color" data-default-color="#2271b1" value="<?php echo esc_attr( $accent_hex ); ?>" maxlength="9" placeholder="#2271b1" />
								<button type="button" class="wpps-color-reset button-link" data-default-color="#2271b1" title="<?php esc_attr_e( 'Reset', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-undo"></span></button>
							</div>
						</div>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_panel_title"><?php esc_html_e( 'Panel title', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text" id="<?php echo esc_attr( $module_id ); ?>_panel_title" name="panel_title" value="<?php echo esc_attr( (string) $settings['panel_title'] ); ?>" class="regular-text wp-powersuite-advanced-setting" data-setting-key="panel_title" placeholder="<?php esc_attr_e( 'Accessibility options', 'wp-powersuite' ); ?>" />
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_footer_note"><?php esc_html_e( 'Footer note', 'wp-powersuite' ); ?></label></th>
					<td>
						<label class="wp-powersuite-toggle-wrap" style="display:block;margin-bottom:8px;">
							<input type="checkbox" name="show_footer_note" value="1" class="wp-powersuite-advanced-setting" data-setting-key="show_footer_note" <?php checked( ! empty( $settings['show_footer_note'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Show a short note at the bottom of the widget panel.', 'wp-powersuite' ); ?></span>
						</label>
						<textarea id="<?php echo esc_attr( $module_id ); ?>_footer_note" name="footer_note" class="large-text wp-powersuite-advanced-setting" data-setting-key="footer_note" rows="2" maxlength="300" placeholder="<?php esc_attr_e( 'Adjust these options to suit your needs. Your choices apply only on this device and can be reset anytime.', 'wp-powersuite' ); ?>"><?php echo esc_textarea( (string) ( $settings['footer_note'] ?? '' ) ); ?></textarea>
						<p class="description"><?php esc_html_e( 'Leave empty to use the default text shown above. Plain text only, up to 300 characters.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_button_label"><?php esc_html_e( 'Button label', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text" id="<?php echo esc_attr( $module_id ); ?>_button_label" name="button_label" value="<?php echo esc_attr( (string) $settings['button_label'] ); ?>" class="regular-text wp-powersuite-advanced-setting" data-setting-key="button_label" placeholder="<?php esc_attr_e( 'Open accessibility options', 'wp-powersuite' ); ?>" />
						<p class="description"><?php esc_html_e( 'Accessible label announced for the floating button.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_custom_css_class"><?php esc_html_e( 'Custom CSS class', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text" id="<?php echo esc_attr( $module_id ); ?>_custom_css_class" name="custom_css_class" value="<?php echo esc_attr( (string) $settings['custom_css_class'] ); ?>" class="regular-text wp-powersuite-advanced-setting" data-setting-key="custom_css_class" />
						<p class="description"><?php esc_html_e( 'Optional extra class on the widget root element.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
			</div>
		</details>

		<details class="wpps-a11y-acc">
			<summary class="wpps-a11y-acc__summary"><span class="wpps-a11y-acc__title"><?php esc_html_e( 'Tools &amp; order', 'wp-powersuite' ); ?></span><span class="dashicons dashicons-arrow-down-alt2 wpps-a11y-acc__chev" aria-hidden="true"></span></summary>
			<div class="wpps-a11y-acc__body">
		<p class="description"><?php esc_html_e( 'Show or hide each control and drag to reorder. Use the arrow buttons or Space/Arrow keys for keyboard reordering. Section headings follow this order automatically.', 'wp-powersuite' ); ?></p>

		<ul class="wpps-a11y-tools" id="wpps_a11y_tools_list">
			<?php foreach ( $tool_order as $tool_key ) : ?>
				<?php
				if ( ! isset( $tool_registry[ $tool_key ] ) ) {
					continue;
				}
				$is_premium  = FeatureGate::isPremiumFeature( $tool_key );
				$is_locked   = $is_premium && ! $premium_unlocked;
				$is_enabled  = ! empty( $features[ $tool_key ] );
				$section     = $tool_registry[ $tool_key ]['section'];
				$section_lbl = $section_labels[ $section ] ?? ucfirst( $section );
				$label       = $tool_labels[ $tool_key ] ?? ucwords( str_replace( '_', ' ', $tool_key ) );
				?>
				<li class="wpps-a11y-tools__item<?php echo $is_locked ? ' is-locked' : ''; ?>" data-tool="<?php echo esc_attr( $tool_key ); ?>" draggable="true">
					<span class="wpps-a11y-tools__handle dashicons dashicons-menu" aria-hidden="true"></span>
					<span class="wpps-a11y-tools__icon" aria-hidden="true"><?php echo Module::getToolIcon( (string) $tool_key ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static SVG. ?></span>
					<label class="wpps-a11y-tools__toggle">
						<input type="checkbox" data-a11y-feature="<?php echo esc_attr( $tool_key ); ?>" value="1" <?php checked( $is_enabled ); ?> <?php disabled( $is_locked ); ?> />
						<span class="wpps-a11y-tools__label"><?php echo esc_html( $label ); ?></span>
					</label>
					<span class="wpps-a11y-tools__section"><?php echo esc_html( (string) $section_lbl ); ?></span>
					<?php if ( $is_premium && ! $premium_unlocked ) : ?>
						<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
					<?php endif; ?>
					<span class="wpps-a11y-tools__move">
						<button type="button" class="button-link wpps-a11y-tools__up" aria-label="<?php echo esc_attr( sprintf( /* translators: %s: tool name */ __( 'Move %s up', 'wp-powersuite' ), $label ) ); ?>"><span class="dashicons dashicons-arrow-up-alt2" aria-hidden="true"></span></button>
						<button type="button" class="button-link wpps-a11y-tools__down" aria-label="<?php echo esc_attr( sprintf( /* translators: %s: tool name */ __( 'Move %s down', 'wp-powersuite' ), $label ) ); ?>"><span class="dashicons dashicons-arrow-down-alt2" aria-hidden="true"></span></button>
					</span>
				</li>
			<?php endforeach; ?>
		</ul>
			</div>
		</details>

		<details class="wpps-a11y-acc">
			<summary class="wpps-a11y-acc__summary"><span class="wpps-a11y-acc__title"><?php esc_html_e( 'Accessibility statement', 'wp-powersuite' ); ?></span><span class="dashicons dashicons-arrow-down-alt2 wpps-a11y-acc__chev" aria-hidden="true"></span></summary>
			<div class="wpps-a11y-acc__body">
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Show statement', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" data-a11y-feature="accessibility_statement" value="1" <?php checked( ! empty( $features['accessibility_statement'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Show an accessibility statement in the widget footer.', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_statement_type"><?php esc_html_e( 'Statement type', 'wp-powersuite' ); ?></label></th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_statement_type" name="statement_type" class="wp-powersuite-advanced-setting" data-setting-key="statement_type">
							<option value="link" <?php selected( $statement_type, 'link' ); ?>><?php esc_html_e( 'Link to a page (opens in a new tab)', 'wp-powersuite' ); ?></option>
							<option value="text" <?php selected( $statement_type, 'text' ); ?>><?php esc_html_e( 'Inline text (opens in a popup)', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>
				<tr class="wpps-a11y-statement-link-row">
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_statement_url"><?php esc_html_e( 'Statement URL', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="url" id="<?php echo esc_attr( $module_id ); ?>_statement_url" name="statement_url" value="<?php echo esc_url( (string) ( $settings['statement_url'] ?? '' ) ); ?>" class="large-text wp-powersuite-advanced-setting" data-setting-key="statement_url" placeholder="https://example.com/accessibility" />
					</td>
				</tr>
				<tr class="wpps-a11y-statement-text-row">
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_statement_content"><?php esc_html_e( 'Statement text', 'wp-powersuite' ); ?></label></th>
					<td>
						<textarea id="<?php echo esc_attr( $module_id ); ?>_statement_content" name="statement_content" class="large-text wp-powersuite-advanced-setting" data-setting-key="statement_content" rows="6" placeholder="<?php esc_attr_e( 'Describe your accessibility commitment, supported features, and how visitors can reach you for assistance.', 'wp-powersuite' ); ?>"><?php echo esc_textarea( (string) ( $settings['statement_content'] ?? '' ) ); ?></textarea>
						<p class="description"><?php esc_html_e( 'Basic HTML (paragraphs and links) is allowed. Shown in a popup inside the widget.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_statement_text"><?php esc_html_e( 'Label', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text" id="<?php echo esc_attr( $module_id ); ?>_statement_text" name="statement_text" value="<?php echo esc_attr( (string) $settings['statement_text'] ); ?>" class="regular-text wp-powersuite-advanced-setting" data-setting-key="statement_text" placeholder="<?php esc_attr_e( 'Accessibility statement', 'wp-powersuite' ); ?>" />
						<p class="description"><?php esc_html_e( 'Text shown for the link or popup trigger in the footer.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
			</div>
		</details>

		<details class="wpps-a11y-acc">
			<summary class="wpps-a11y-acc__summary"><span class="wpps-a11y-acc__title"><?php esc_html_e( 'Visibility &amp; exclusions', 'wp-powersuite' ); ?></span><span class="dashicons dashicons-arrow-down-alt2 wpps-a11y-acc__chev" aria-hidden="true"></span></summary>
			<div class="wpps-a11y-acc__body">
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Exclude post types', 'wp-powersuite' ); ?></th>
					<td>
						<?php if ( empty( $available_types ) ) : ?>
							<p class="description"><?php esc_html_e( 'No public post types found.', 'wp-powersuite' ); ?></p>
						<?php else : ?>
							<p class="description" style="margin-bottom:8px;"><?php esc_html_e( 'Do not show the widget on these post types.', 'wp-powersuite' ); ?></p>
							<div class="wpps-ct-multiselect" id="<?php echo esc_attr( $module_id ); ?>_post_types_ms"
								data-label-none="<?php echo esc_attr__( 'Select post types...', '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 ); ?>_post_types_list">
									<span class="wpps-ct-multiselect__trigger-text"><?php esc_html_e( 'Select post types...', 'wp-powersuite' ); ?></span>
									<span class="dashicons dashicons-arrow-down-alt2 wpps-ct-multiselect__chevron" aria-hidden="true"></span>
								</button>
								<div class="wpps-ct-multiselect__dropdown" id="<?php echo esc_attr( $module_id ); ?>_post_types_list" role="listbox" hidden>
									<div class="wpps-ct-multiselect__options">
										<?php foreach ( $available_types as $post_type_name => $post_type_object ) : ?>
											<?php $label = $post_type_object->labels->name ?? $post_type_name; ?>
											<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $post_type_name ); ?>" data-label="<?php echo esc_attr( $label ); ?>">
												<input type="checkbox" name="excluded_post_types[]" class="wp-powersuite-advanced-setting" data-setting-key="excluded_post_types" value="<?php echo esc_attr( $post_type_name ); ?>" <?php checked( in_array( $post_type_name, $excluded_types, true ) ); ?> />
												<span class="wpps-ct-multiselect__option-label"><?php echo esc_html( $label ); ?></span>
												<span class="wpps-ct-multiselect__option-slug">(<?php echo esc_html( $post_type_name ); ?>)</span>
											</label>
										<?php endforeach; ?>
									</div>
								</div>
							</div>
						<?php endif; ?>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_excluded_post_ids"><?php esc_html_e( 'Exclude posts/pages by ID', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text" id="<?php echo esc_attr( $module_id ); ?>_excluded_post_ids" name="excluded_post_ids" value="<?php echo esc_attr( (string) $settings['excluded_post_ids'] ); ?>" class="large-text wp-powersuite-advanced-setting" data-setting-key="excluded_post_ids" placeholder="12, 45, 102" />
						<p class="description"><?php esc_html_e( 'Comma-separated post IDs where the widget should not appear.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_exclude_urls"><?php esc_html_e( 'Exclude URLs', 'wp-powersuite' ); ?></label></th>
					<td>
						<textarea id="<?php echo esc_attr( $module_id ); ?>_exclude_urls" name="exclude_urls" class="wp-powersuite-advanced-setting large-text code" data-setting-key="exclude_urls" rows="4" placeholder="/checkout&#10;/cart&#10;/my-account*"><?php echo esc_textarea( (string) $settings['exclude_urls'] ); ?></textarea>
						<p class="description"><?php esc_html_e( 'One path per line. Use * as a wildcard. Example: /checkout', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
			</div>
		</details>

		</div><!-- /.wpps-a11y-acc-group -->
	</form>

	<details class="wpps-a11y-acc wpps-a11y-acc--standalone wpps-a11y-admin-checks">
		<summary class="wpps-a11y-acc__summary"><span class="wpps-a11y-acc__title"><?php esc_html_e( 'Accessibility checks (admin only)', 'wp-powersuite' ); ?></span><span class="dashicons dashicons-arrow-down-alt2 wpps-a11y-acc__chev" aria-hidden="true"></span></summary>
		<div class="wpps-a11y-acc__body">
		<p class="description"><?php esc_html_e( 'Run a lightweight, on-demand scan of a single URL on this site. Results include an advisory WCAG-oriented score mapped to common success criteria—not a full audit or legal certification.', 'wp-powersuite' ); ?></p>

		<div class="wpps-a11y-admin-checks__form">
			<label class="screen-reader-text" for="<?php echo esc_attr( $module_id ); ?>_scan_url"><?php esc_html_e( 'URL to scan', 'wp-powersuite' ); ?></label>
			<input type="url" id="<?php echo esc_attr( $module_id ); ?>_scan_url" class="regular-text" value="<?php echo esc_url( $scan_url_default ); ?>" />
			<button type="button" class="button button-secondary wpps-a11y-run-checks" data-module-id="<?php echo esc_attr( $module_id ); ?>">
				<?php esc_html_e( 'Run checks', 'wp-powersuite' ); ?>
			</button>
		</div>

		<div class="wpps-a11y-admin-checks__results" aria-live="polite" hidden></div>
		</div>
	</details>

	<div class="wpps-a11y-notes">
		<h3 class="wpps-a11y-notes__heading"><?php esc_html_e( 'Shortcode &amp; notes', 'wp-powersuite' ); ?></h3>
		<div class="wp-powersuite-info-box" style="background:#f0f6fc;border-left:4px solid #2271b1;padding:12px;margin:0 0 12px;">
			<p style="margin:0 0 8px;"><strong><?php esc_html_e( 'Shortcode', 'wp-powersuite' ); ?></strong></p>
			<p style="margin:0;"><code>[wpps_accessibility_widget]</code> — <?php esc_html_e( 'Place the widget manually. When the shortcode is used, the auto floating button is not duplicated.', 'wp-powersuite' ); ?></p>
		</div>

		<div class="wp-powersuite-info-box" style="background:#fff8e5;border-left:4px solid #dba617;padding:12px;margin:0 0 12px;">
			<p style="margin:0;"><strong><?php esc_html_e( 'Important', 'wp-powersuite' ); ?></strong> — <?php esc_html_e( 'This widget provides visitor-facing accessibility preferences and usability enhancements. It does not replace a full accessibility audit or proper WCAG implementation.', 'wp-powersuite' ); ?></p>
		</div>

		<p class="description" style="margin:0;"><?php esc_html_e( 'Settings access is controlled by the wp_powersuite_a11y_settings_capability filter (defaults to your network/site admin capability).', 'wp-powersuite' ); ?></p>
	</div>
</div>

<style>
	.wpps-a11y-acc-group { max-width: 760px; }
	.wpps-a11y-acc {
		border: 1px solid #dcdcde; border-radius: 8px; background: #fff;
		margin: 0 0 12px; box-shadow: 0 1px 2px rgba(0,0,0,.04);
	}
	.wpps-a11y-acc--standalone { max-width: 760px; margin-top: 20px; }
	.wpps-a11y-acc__summary {
		display: flex; align-items: center; justify-content: space-between; gap: 12px;
		padding: 13px 16px; cursor: pointer; font-size: 14px; font-weight: 600; color: #1d2327;
		list-style: none; user-select: none; border-radius: 8px;
	}
	.wpps-a11y-acc__summary::-webkit-details-marker { display: none; }
	.wpps-a11y-acc__summary::marker { content: ''; }
	.wpps-a11y-acc__summary:hover { background: #f6f7f7; }
	.wpps-a11y-acc__summary:focus-visible { outline: 2px solid var(--wp-admin-theme-color, #2271b1); outline-offset: -2px; }
	.wpps-a11y-acc__title { display: inline-flex; align-items: center; gap: 8px; }
	.wpps-a11y-acc__chev { color: #646970; transition: transform .2s ease; }
	.wpps-a11y-acc[open] > .wpps-a11y-acc__summary {
		border-bottom: 1px solid #dcdcde; border-radius: 8px 8px 0 0;
	}
	.wpps-a11y-acc[open] > .wpps-a11y-acc__summary .wpps-a11y-acc__chev { transform: rotate(180deg); }
	.wpps-a11y-acc__body { padding: 6px 16px 14px; }
	.wpps-a11y-acc__body .form-table { margin-top: 0; }
	.wpps-a11y-acc__body .form-table th { padding-top: 14px; padding-bottom: 14px; }
	.wpps-a11y-tools { margin: 0 0 8px; padding: 0; list-style: none; max-width: 640px; }
	.wpps-a11y-tools__item {
		display: flex; align-items: center; gap: 10px; padding: 8px 10px; margin: 0 0 6px;
		border: 1px solid #dcdcde; border-radius: 6px; background: #fff;
	}
	.wpps-a11y-tools__item.is-dragover { border-color: var(--wp-admin-theme-color, #2271b1); box-shadow: 0 0 0 1px var(--wp-admin-theme-color, #2271b1) inset; }
	.wpps-a11y-tools__item.is-dragging { opacity: .5; }
	.wpps-a11y-tools__item.is-locked { background: #f6f7f7; }
	.wpps-a11y-tools__handle { color: #8c8f94; cursor: grab; flex: 0 0 auto; }
	.wpps-a11y-tools__toggle { display: flex; align-items: center; gap: 8px; flex: 1 1 auto; cursor: pointer; }
	.wpps-a11y-tools__label { font-weight: 500; }
	.wpps-a11y-tools__section {
		flex: 0 0 auto; font-size: 11px; text-transform: uppercase; letter-spacing: .04em;
		color: #646970; background: #f0f0f1; border-radius: 999px; padding: 2px 8px;
	}
	.wpps-a11y-tools__move { display: inline-flex; gap: 2px; flex: 0 0 auto; }
	.wpps-a11y-tools__move .button-link { color: #50575e; padding: 2px; }
	.wpps-a11y-tools__move .button-link:hover { color: var(--wp-admin-theme-color, #2271b1); }
	.wpps-pro-badge {
		flex: 0 0 auto; font-size: 11px; font-weight: 600; color: #8a5a00;
		background: #fff3cd; border: 1px solid #ffe69c; border-radius: 999px; padding: 1px 8px;
	}
	.wpps-color-field-row { display: flex; align-items: center; gap: 8px; }
	.wpps-a11y-compliance-score { font-size: 1.4rem; font-weight: 700; }
	.wpps-a11y-tools__icon { flex: 0 0 auto; display: inline-flex; justify-content: center; width: 20px; color: #50575e; font-size: 15px; }
	.wpps-a11y-tools__item.is-locked .wpps-a11y-tools__icon { opacity: .5; }
	/* Button-icon picker */
	.wpps-a11y-iconpicker { display: flex; flex-wrap: wrap; gap: 8px; }
	.wpps-a11y-iconpicker__opt {
		display: inline-flex; align-items: center; justify-content: center;
		width: 46px; height: 46px; padding: 0; cursor: pointer;
		border: 1.5px solid #dcdcde; border-radius: 10px; background: #fff; color: #1d2327;
		transition: border-color .12s ease, background .12s ease, box-shadow .12s ease;
	}
	.wpps-a11y-iconpicker__opt:hover { border-color: var(--wp-admin-theme-color, #2271b1); background: #f0f6fc; }
	.wpps-a11y-iconpicker__opt:focus-visible { outline: 2px solid var(--wp-admin-theme-color, #2271b1); outline-offset: 2px; }
	.wpps-a11y-iconpicker__opt.is-selected { border-color: var(--wp-admin-theme-color, #2271b1); background: var(--wp-admin-theme-color, #2271b1); color: #fff; box-shadow: 0 2px 6px rgba(0,0,0,.18); }
	.wpps-a11y-iconpicker__glyph { display: inline-flex; font-size: 22px; line-height: 1; }
	.wpps-a11y-notes { max-width: 760px; margin-top: 20px; }
	.wpps-a11y-notes__heading { margin: 0 0 10px; font-size: 14px; }
</style>

<script>
(function() {
	var form = document.querySelector('.wpps-a11y-widget-settings .wp-powersuite-module-settings-form');
	if (!form) { return; }

	var orderInput = form.querySelector('#wpps_a11y_tool_order');
	var featuresInput = form.querySelector('#wpps_a11y_enabled_features');
	var list = form.querySelector('#wpps_a11y_tools_list');

	function syncHiddenFields() {
		if (orderInput && list) {
			var order = [];
			list.querySelectorAll('.wpps-a11y-tools__item').forEach(function(li) {
				if (li.dataset.tool) { order.push(li.dataset.tool); }
			});
			orderInput.value = order.join(',');
		}
		if (featuresInput) {
			var enabled = [];
			form.querySelectorAll('input[data-a11y-feature]').forEach(function(cb) {
				if (cb.checked) { enabled.push(cb.getAttribute('data-a11y-feature')); }
			});
			featuresInput.value = enabled.join(',');
		}
	}

	form.querySelectorAll('input[data-a11y-feature]').forEach(function(cb) {
		cb.addEventListener('change', syncHiddenFields);
	});

	if (list) {
		// Up / down buttons.
		list.addEventListener('click', function(e) {
			var item = e.target.closest('.wpps-a11y-tools__item');
			if (!item) { return; }
			if (e.target.closest('.wpps-a11y-tools__up') && item.previousElementSibling) {
				list.insertBefore(item, item.previousElementSibling);
				syncHiddenFields();
			} else if (e.target.closest('.wpps-a11y-tools__down') && item.nextElementSibling) {
				list.insertBefore(item.nextElementSibling, item);
				syncHiddenFields();
			}
		});

		// Drag and drop.
		var dragged = null;
		list.addEventListener('dragstart', function(e) {
			dragged = e.target.closest('.wpps-a11y-tools__item');
			if (dragged) { dragged.classList.add('is-dragging'); }
		});
		list.addEventListener('dragend', function() {
			if (dragged) { dragged.classList.remove('is-dragging'); }
			list.querySelectorAll('.is-dragover').forEach(function(el) { el.classList.remove('is-dragover'); });
			dragged = null;
			syncHiddenFields();
		});
		list.addEventListener('dragover', function(e) {
			e.preventDefault();
			var target = e.target.closest('.wpps-a11y-tools__item');
			if (!target || target === dragged) { return; }
			list.querySelectorAll('.is-dragover').forEach(function(el) { el.classList.remove('is-dragover'); });
			target.classList.add('is-dragover');
		});
		list.addEventListener('drop', function(e) {
			e.preventDefault();
			var target = e.target.closest('.wpps-a11y-tools__item');
			if (!target || !dragged || target === dragged) { return; }
			var rect = target.getBoundingClientRect();
			var after = (e.clientY - rect.top) > (rect.height / 2);
			list.insertBefore(dragged, after ? target.nextElementSibling : target);
			target.classList.remove('is-dragover');
			syncHiddenFields();
		});
	}

	// and syncs the paired circle picker + hex input (shared color-panel.js).
	form.querySelectorAll('.wpps-color-reset').forEach(function(btn) {
		btn.addEventListener('click', function() {
			var def = btn.getAttribute('data-default-color') || '';
			var wrap = btn.closest('.wpps-color-field-row');
			if (!wrap) { return; }
			var circle = wrap.querySelector('.wpps-color-picker-circle');
			var code = wrap.querySelector('.wpps-color-code-input');
			if (circle && def) { circle.value = def; }
			if (code) {
				code.value = def;
				code.dispatchEvent(new Event('change', { bubbles: true }));
			}
		});
	});

	// The icon color field is de-emphasized while "Automatic" contrast is on.
	var iconAuto = form.querySelector('.wpps-a11y-icon-auto');
	var iconColorWrap = form.querySelector('.wpps-a11y-iconcolor');
	function syncIconAuto() {
		if (!iconAuto || !iconColorWrap) { return; }
		// Keep the inputs enabled so their value is preserved when toggling back,
		// but visually de-emphasize them while automatic contrast is active.
		iconColorWrap.style.opacity = iconAuto.checked ? '0.4' : '';
		iconColorWrap.style.pointerEvents = iconAuto.checked ? 'none' : '';
	}
	if (iconAuto) {
		iconAuto.addEventListener('change', syncIconAuto);
		syncIconAuto();
	}

	// Button-icon visual picker -> hidden input.
	var iconHidden = document.getElementById('wpps_a11y_button_icon');
	var iconPicker = document.getElementById('<?php echo esc_js( $module_id ); ?>_iconpicker');
	if (iconHidden && iconPicker) {
		iconPicker.addEventListener('click', function(e) {
			var opt = e.target.closest('.wpps-a11y-iconpicker__opt');
			if (!opt) { return; }
			iconPicker.querySelectorAll('.wpps-a11y-iconpicker__opt').forEach(function(o) {
				var on = o === opt;
				o.classList.toggle('is-selected', on);
				o.setAttribute('aria-pressed', on ? 'true' : 'false');
			});
			iconHidden.value = opt.getAttribute('data-icon') || 'accessibility';
			iconHidden.dispatchEvent(new Event('change', { bubbles: true }));
		});
	}

	// Statement type: show URL vs inline text fields.
	var statementType = document.getElementById('<?php echo esc_js( $module_id ); ?>_statement_type');
	function syncStatementType() {
		if (!statementType) { return; }
		var isText = statementType.value === 'text';
		form.querySelectorAll('.wpps-a11y-statement-link-row').forEach(function(r) { r.style.display = isText ? 'none' : ''; });
		form.querySelectorAll('.wpps-a11y-statement-text-row').forEach(function(r) { r.style.display = isText ? '' : 'none'; });
	}
	if (statementType) {
		statementType.addEventListener('change', syncStatementType);
		syncStatementType();
	}

	// Post-type multiselect trigger text.
	var ms = document.getElementById('<?php echo esc_js( $module_id ); ?>_post_types_ms');
	if (ms) {
		var trigger = ms.querySelector('.wpps-ct-multiselect__trigger');
		var triggerText = ms.querySelector('.wpps-ct-multiselect__trigger-text');
		var dropdown = ms.querySelector('.wpps-ct-multiselect__dropdown');
		var options = ms.querySelectorAll('.wpps-ct-multiselect__option input[type="checkbox"]');
		function updateText() {
			var n = 0;
			options.forEach(function(cb) { if (cb.checked) { n++; } });
			var none = ms.dataset.labelNone, single = ms.dataset.labelSingle, multi = (ms.dataset.labelMulti || '%d').replace('%d', n);
			triggerText.textContent = n === 0 ? none : (n === 1 ? single : multi);
		}
		if (trigger) {
			trigger.addEventListener('click', function() {
				var open = dropdown.hasAttribute('hidden');
				if (open) { dropdown.removeAttribute('hidden'); trigger.setAttribute('aria-expanded', 'true'); }
				else { dropdown.setAttribute('hidden', ''); trigger.setAttribute('aria-expanded', 'false'); }
			});
		}
		document.addEventListener('click', function(e) {
			if (!ms.contains(e.target)) { dropdown.setAttribute('hidden', ''); if (trigger) { trigger.setAttribute('aria-expanded', 'false'); } }
		});
		options.forEach(function(cb) { cb.addEventListener('change', updateText); });
		updateText();
	}

	// Admin scanner.
	var runBtn = document.querySelector('.wpps-a11y-run-checks[data-module-id="<?php echo esc_js( $module_id ); ?>"]');
	var urlInput = document.getElementById('<?php echo esc_js( $module_id ); ?>_scan_url');
	var results = document.querySelector('.wpps-a11y-admin-checks__results');
	if (runBtn && urlInput && results) {
		runBtn.addEventListener('click', function() {
			results.hidden = false;
			results.textContent = '<?php echo esc_js( __( 'Running checks…', 'wp-powersuite' ) ); ?>';
			var body = new URLSearchParams();
			body.append('action', 'wpps_a11y_run_checks');
			body.append('nonce', '<?php echo esc_js( $ajax_nonce ); ?>');
			body.append('url', urlInput.value || '');
			fetch((window.ajaxurl || ''), {
				method: 'POST',
				credentials: 'same-origin',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
				body: body.toString()
			}).then(function(r) { return r.json(); }).then(function(data) {
				if (!data || !data.success) {
					var msg = (data && data.data && data.data.message) ? data.data.message : '<?php echo esc_js( __( 'Scan failed.', 'wp-powersuite' ) ); ?>';
					results.innerHTML = '';
					var p = document.createElement('p');
					p.className = 'notice notice-error';
					p.textContent = msg;
					results.appendChild(p);
					return;
				}
				renderScanResults(results, data.data || {});
			}).catch(function() {
				results.innerHTML = '';
				var p = document.createElement('p');
				p.className = 'notice notice-error';
				p.textContent = '<?php echo esc_js( __( 'Scan failed.', 'wp-powersuite' ) ); ?>';
				results.appendChild(p);
			});
		});
	}

	// Build scan results with DOM APIs (no innerHTML of server text) to avoid XSS.
	function renderScanResults(container, payload) {
		container.innerHTML = '';
		if (typeof payload.score === 'number') {
			var score = document.createElement('p');
			score.className = 'wpps-a11y-compliance-score';
			score.textContent = '<?php echo esc_js( __( 'Advisory score:', 'wp-powersuite' ) ); ?> ' + payload.score + '/100';
			container.appendChild(score);
		}
		if (payload.summary) {
			var summary = document.createElement('p');
			summary.className = 'description';
			summary.textContent = payload.summary;
			container.appendChild(summary);
		}
		var issues = payload.issues || [];
		if (!issues.length) {
			var none = document.createElement('p');
			none.textContent = '<?php echo esc_js( __( 'No issues returned.', 'wp-powersuite' ) ); ?>';
			container.appendChild(none);
			return;
		}
		var ul = document.createElement('ul');
		ul.className = 'wpps-a11y-check-list';
		issues.forEach(function(issue) {
			var li = document.createElement('li');
			li.className = 'wpps-a11y-check-list__item wpps-a11y-check-list__item--' + (issue.severity || 'info');
			var strong = document.createElement('strong');
			strong.textContent = issue.message || '';
			li.appendChild(strong);
			if (issue.wcag) {
				li.appendChild(document.createElement('br'));
				var wcag = document.createElement('span');
				wcag.className = 'wpps-a11y-check-list__wcag';
				wcag.textContent = issue.wcag;
				li.appendChild(wcag);
			}
			if (issue.suggestion) {
				li.appendChild(document.createElement('br'));
				var sug = document.createElement('span');
				sug.className = 'description';
				sug.textContent = issue.suggestion;
				li.appendChild(sug);
			}
			ul.appendChild(li);
		});
		container.appendChild(ul);
		if (payload.message) {
			var note = document.createElement('p');
			note.className = 'description';
			note.textContent = payload.message;
			container.appendChild(note);
		}
	}
})();
</script>
