<?php

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'alphabet-avatars' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Alphabet Avatars requires an active license. Activate your license to configure letter avatars.', '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;
}

$module_id = $module_id ?? 'alphabet-avatars';
$settings = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $settings ) ) {
	$settings = [];
}
$defaults = [
	'letter_source' => 'first_last',
	'bg_mode'       => 'random',
	'custom_color'  => '#3498db',
	'shape'         => 'circle',
	'size'          => 'regular',
];
$settings = array_merge( $defaults, $settings );

$letter_source = in_array( $settings['letter_source'] ?? '', [ 'first_last', 'username', 'display_name', 'full_name' ], true ) ? $settings['letter_source'] : 'first_last';
$bg_mode       = $settings['bg_mode'] ?? 'random';
$default_custom_color = '#3498db';
$custom_color_raw     = (string) ( $settings['custom_color'] ?? '' );
$custom_color         = preg_match( '/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/', $custom_color_raw ) ? $custom_color_raw : $default_custom_color;
$custom_color_circle  = strlen( $custom_color ) > 7 ? substr( $custom_color, 0, 7 ) : $custom_color;
$shape         = in_array( $settings['shape'] ?? '', [ 'circle', 'rounded', 'square' ], true ) ? $settings['shape'] : 'circle';
$size          = in_array( $settings['size'] ?? '', [ 'small', 'regular' ], true ) ? $settings['size'] : 'regular';

$current_user = wp_get_current_user();
?>
<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Replace Gravatar with letter-based avatars in comments, author boxes, and the admin bar. Uses inline SVG (no external requests).', 'wp-powersuite' ); ?>
	</p>
	<div class="notice notice-info inline" style="margin: 12px 0 20px; padding: 10px 12px;">
		<p style="margin: 0;">
			<?php esc_html_e( 'Registered users without a local profile photo or Google avatar see colorful initials. Guest commenters still use the site default avatar from Settings → Discussion.', 'wp-powersuite' ); ?>
		</p>
	</div>

	<?php if ( $current_user->exists() ) : ?>
	<?php
		// Build preview with current settings (ensures correct avatar in settings context)
		$preview_module  = new \AlphabetAvatars\Module();
		$preview_settings = [
			'letter_source' => $letter_source,
			'bg_mode'       => $bg_mode,
			'custom_color'  => $custom_color,
			'shape'         => $shape,
			'size'          => $size,
		];
		$preview_avatar  = $preview_module->buildAvatar( $current_user, 64, $current_user->display_name, [], $preview_settings );
	?>
	<div class="wpps-alphabet-avatars-preview" style="margin-bottom: 20px; padding: 16px; background: #f6f7f7; border-radius: 8px; border: 1px solid #dcdcde;">
		<h4 style="margin: 0 0 12px 0; font-size: 13px;"><?php esc_html_e( 'Preview', 'wp-powersuite' ); ?></h4>
		<div style="display: flex; align-items: center; gap: 16px;">
			<?php echo $preview_avatar; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<div>
				<p style="margin: 0 0 4px 0; font-weight: 600; font-size: 14px;"><?php echo esc_html( $current_user->display_name ); ?></p>
				<p class="description" style="margin: 0; font-size: 12px;"><?php esc_html_e( 'Your avatar will update when you save settings.', 'wp-powersuite' ); ?></p>
			</div>
		</div>
	</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' ); ?>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_letter_source"><?php esc_html_e( 'Letter source', 'wp-powersuite' ); ?></label></th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_letter_source" name="letter_source" class="wp-powersuite-advanced-setting" data-setting-key="letter_source">
							<option value="first_last" <?php selected( $letter_source, 'first_last' ); ?>><?php esc_html_e( 'First + Last name (Recommended)', 'wp-powersuite' ); ?></option>
							<option value="full_name" <?php selected( $letter_source, 'full_name' ); ?>><?php esc_html_e( 'Full name (first letter of each word)', 'wp-powersuite' ); ?></option>
							<option value="username" <?php selected( $letter_source, 'username' ); ?>><?php esc_html_e( 'Username (first 2 letters)', 'wp-powersuite' ); ?></option>
							<option value="display_name" <?php selected( $letter_source, 'display_name' ); ?>><?php esc_html_e( 'Display name (first 2 letters)', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'How initials are generated. First+Last uses user meta (e.g. John Smith → JS); Full name uses first letter of each word; username/display use first 2 characters.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_bg_mode"><?php esc_html_e( 'Background', 'wp-powersuite' ); ?></label></th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_bg_mode" name="bg_mode" class="wp-powersuite-advanced-setting" data-setting-key="bg_mode">
							<option value="random" <?php selected( $bg_mode, 'random' ); ?>><?php esc_html_e( 'Random (per user)', 'wp-powersuite' ); ?></option>
							<option value="custom" <?php selected( $bg_mode, 'custom' ); ?>><?php esc_html_e( 'Custom color', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Random uses a fixed palette; each user keeps the same color. Custom uses one color for all.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr id="<?php echo esc_attr( $module_id ); ?>_custom_color_row" style="display: <?php echo $bg_mode === 'custom' ? 'table-row' : 'none'; ?>;">
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_custom_color"><?php esc_html_e( 'Custom color', 'wp-powersuite' ); ?></label></th>
					<td>
						<div class="wpps-color-field-row">
							<input
								type="color"
								id="<?php echo esc_attr( $module_id ); ?>_custom_color"
								name="custom_color"
								value="<?php echo esc_attr( $custom_color_circle ); ?>"
								class="wp-powersuite-advanced-setting wpps-color-picker-circle"
								data-setting-key="custom_color"
							/>
							<div class="wpps-color-code-wrap">
								<input
									type="text"
									id="<?php echo esc_attr( $module_id ); ?>_custom_color_hex"
									class="wpps-color-code-input regular-text wp-powersuite-advanced-setting"
									data-setting-key="custom_color"
									data-color-input="<?php echo esc_attr( $module_id ); ?>_custom_color"
									data-default-color="<?php echo esc_attr( $default_custom_color ); ?>"
									value="<?php echo esc_attr( $custom_color ); ?>"
									style="width: 100px; padding-right: 25px;"
									placeholder="<?php echo esc_attr( $default_custom_color ); ?>"
									maxlength="9"
								/>
								<button type="button" class="wpps-color-reset button-link" data-default-color="<?php echo esc_attr( $default_custom_color ); ?>" 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>
						<p class="description"><?php esc_html_e( 'Used when Background is Custom. Hex format (e.g. #3498db).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_shape"><?php esc_html_e( 'Shape', 'wp-powersuite' ); ?></label></th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_shape" name="shape" class="wp-powersuite-advanced-setting" data-setting-key="shape">
							<option value="circle" <?php selected( $shape, 'circle' ); ?>><?php esc_html_e( 'Circle', 'wp-powersuite' ); ?></option>
							<option value="rounded" <?php selected( $shape, 'rounded' ); ?>><?php esc_html_e( 'Rounded square', 'wp-powersuite' ); ?></option>
							<option value="square" <?php selected( $shape, 'square' ); ?>><?php esc_html_e( 'Square', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="<?php echo esc_attr( $module_id ); ?>_size"><?php esc_html_e( 'Letter size', 'wp-powersuite' ); ?></label></th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_size" name="size" class="wp-powersuite-advanced-setting" data-setting-key="size">
							<option value="small" <?php selected( $size, 'small' ); ?>><?php esc_html_e( 'Small', 'wp-powersuite' ); ?></option>
							<option value="regular" <?php selected( $size, 'regular' ); ?>><?php esc_html_e( 'Regular', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Relative size of the initials inside the avatar.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>
</div>

<style>
.wp-powersuite-module-settings .wpps-color-field-row { display: inline-flex; align-items: center; gap: 10px; flex-wrap: nowrap; }
.wp-powersuite-module-settings .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-module-settings .wpps-color-picker-circle::-webkit-color-swatch-wrapper { padding: 0 !important; margin: 0 !important; border: none !important; border-radius: 50% !important; }
.wp-powersuite-module-settings .wpps-color-picker-circle::-webkit-color-swatch { border: none !important; border-radius: 50% !important; width: 100% !important; height: 100% !important; }
.wp-powersuite-module-settings .wpps-color-picker-circle::-moz-color-swatch { border: none !important; border-radius: 50% !important; width: 100% !important; height: 100% !important; }
.wp-powersuite-module-settings .wpps-color-code-wrap { display: inline-block; position: relative; margin: 0; flex-shrink: 0; }
.wp-powersuite-module-settings .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-module-settings .wpps-color-code-wrap .wpps-color-reset:hover { color: #2271b1; }
</style>

<script type="text/javascript">
(function($) {
	$(function() {
		var mid = '<?php echo esc_js( $module_id ); ?>';
		var $mode = $('#' + mid + '_bg_mode');
		var $row = $('#' + mid + '_custom_color_row');

		function toggleCustomColorRow() {
			$row.toggle($mode.val() === 'custom');
		}

		$mode.on('change', toggleCustomColorRow);

		$(document).on('input change', '#' + mid + '_custom_color_hex', function() {
			var $textInput = $(this);
			var colorValue = ($textInput.val() || '').trim();
			if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}|[A-Fa-f0-9]{8})$/.test(colorValue)) {
				$textInput.css('border-color', '');
			} else if (colorValue === '') {
				$textInput.css('border-color', '');
			} else {
				$textInput.css('border-color', '#d63638');
			}
		});

		$(document).on('click', '#' + mid + '_custom_color_row .wpps-color-reset', function(e) {
			e.preventDefault();
			var $resetButton = $(this);
			var defaultColor = $resetButton.data('default-color');
			var $textInput = $resetButton.prev('.wpps-color-code-input');
			var colorInputId = $textInput.data('color-input');
			var $colorInput = $('#' + colorInputId);
			$textInput.val(defaultColor);
			$colorInput.val(defaultColor.length > 7 ? defaultColor.slice(0, 7) : defaultColor);
			$textInput.css('border-color', '');
			$textInput.trigger('change');
		});
	});
})(jQuery);
</script>
