<?php
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! \WP_PowerSuite\Core\NetworkScope::canManagePlugin() ) {
	return;
}

$module_id    = $module_id ?? 'reading-time-calculator';
$raw      = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$settings = class_exists( '\ReadingTimeCalculator\Module' )
	? \ReadingTimeCalculator\Module::normalizeSettings( is_array( $raw ) ? $raw : [] )
	: array_merge( [
		'auto_insert'        => true,
		'enabled_post_types' => [ 'post' ],
		'position'           => 'before_content',
		'words_per_minute'   => 200,
		'minimum_words'      => 0,
		'label_template'     => '%minutes% min read',
		'show_word_count'    => false,
		'count_excerpt'      => false,
		'skip_if_shortcode'  => true,
	], is_array( $raw ) ? $raw : [] );

$enabled_post_types = $settings['enabled_post_types'];

$excluded     = [ 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block' ];
$available_pt = [];
foreach ( get_post_types( [ 'public' => true ], 'objects' ) as $slug => $obj ) {
	if ( ! in_array( $slug, $excluded, true ) ) {
		$available_pt[ $slug ] = $obj;
	}
}

$auto_insert       = ! empty( $settings['auto_insert'] );
$show_word_count   = ! empty( $settings['show_word_count'] );
$count_excerpt     = ! empty( $settings['count_excerpt'] );
$skip_if_shortcode = ! empty( $settings['skip_if_shortcode'] );
$position          = isset( $settings['position'] ) ? (string) $settings['position'] : 'before_content';
$words_per_minute  = isset( $settings['words_per_minute'] ) ? max( 60, min( 600, (int) $settings['words_per_minute'] ) ) : 200;
$minimum_words     = isset( $settings['minimum_words'] ) ? max( 0, min( 50000, (int) $settings['minimum_words'] ) ) : 0;
$label_template    = (string) $settings['label_template'];
?>

<div class="wp-powersuite-module-settings">
	<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 ); ?>_auto_insert"><?php esc_html_e( 'Auto insert', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" id="<?php echo esc_attr( $module_id ); ?>_auto_insert" name="auto_insert" value="1"
								class="wp-powersuite-advanced-setting" data-setting-key="auto_insert" <?php checked( $auto_insert ); ?> />
							<span class="description"><?php esc_html_e( 'Insert on singular views (main query only).', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Post types', 'wp-powersuite' ); ?></th>
					<td>
						<?php if ( empty( $available_pt ) ) : ?>
							<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( 'Applies to auto-insert and the shortcode.', '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"></span>
								</button>
								<div class="wpps-ct-multiselect__dropdown" id="<?php echo esc_attr( $module_id ); ?>_post_types_list" role="listbox" hidden>
									<input type="text" class="wpps-ct-multiselect__search" placeholder="<?php esc_attr_e( 'Search…', 'wp-powersuite' ); ?>" autocomplete="off" />
									<div class="wpps-ct-multiselect__actions">
										<button type="button" class="wpps-ct-multiselect__action" data-action="select-all"><?php esc_html_e( 'Select all', 'wp-powersuite' ); ?></button>
										<button type="button" class="wpps-ct-multiselect__action" data-action="clear"><?php esc_html_e( 'Clear', 'wp-powersuite' ); ?></button>
									</div>
									<div class="wpps-ct-multiselect__options">
										<?php foreach ( $available_pt as $slug => $obj ) : ?>
											<?php
											$plabel  = $obj->labels->name ?? $slug;
											$pticked = in_array( $slug, $enabled_post_types, true );
											?>
											<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $slug ); ?>" data-label="<?php echo esc_attr( $plabel ); ?>">
												<input type="checkbox" name="enabled_post_types[]" class="wp-powersuite-advanced-setting" data-setting-key="enabled_post_types"
													value="<?php echo esc_attr( $slug ); ?>" <?php checked( $pticked ); ?> />
												<span class="wpps-ct-multiselect__option-label"><?php echo esc_html( $plabel ); ?></span>
												<span class="wpps-ct-multiselect__option-slug">(<?php echo esc_html( $slug ); ?>)</span>
											</label>
										<?php endforeach; ?>
									</div>
								</div>
							</div>
						<?php endif; ?>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_position"><?php esc_html_e( '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="before_content" <?php selected( $position, 'before_content' ); ?>><?php esc_html_e( 'Before content', 'wp-powersuite' ); ?></option>
							<option value="before_first_paragraph" <?php selected( $position, 'before_first_paragraph' ); ?>><?php esc_html_e( 'Before first paragraph', 'wp-powersuite' ); ?></option>
							<option value="after_first_paragraph" <?php selected( $position, 'after_first_paragraph' ); ?>><?php esc_html_e( 'After first paragraph', 'wp-powersuite' ); ?></option>
							<option value="after_content" <?php selected( $position, 'after_content' ); ?>><?php esc_html_e( 'After content', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_wpm"><?php esc_html_e( 'Words per minute', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="number" id="<?php echo esc_attr( $module_id ); ?>_wpm" name="words_per_minute" class="small-text wp-powersuite-advanced-setting" data-setting-key="words_per_minute"
							value="<?php echo esc_attr( (string) $words_per_minute ); ?>" min="60" max="600" step="1" />
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_minw"><?php esc_html_e( 'Minimum words', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="number" id="<?php echo esc_attr( $module_id ); ?>_minw" name="minimum_words" class="small-text wp-powersuite-advanced-setting" data-setting-key="minimum_words"
							value="<?php echo esc_attr( (string) $minimum_words ); ?>" min="0" max="50000" step="1" />
						<p class="description"><?php esc_html_e( 'Hide output below this word count (0 = no minimum).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_template"><?php esc_html_e( 'Label template', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="text" id="<?php echo esc_attr( $module_id ); ?>_template" name="label_template" class="large-text wp-powersuite-advanced-setting" data-setting-key="label_template"
							value="<?php echo esc_attr( $label_template ); ?>" maxlength="300" />
						<p class="description"><?php esc_html_e( 'Placeholders:', 'wp-powersuite' ); ?> <code>%minutes%</code> <?php esc_html_e( 'and', 'wp-powersuite' ); ?> <code>%words%</code> (<?php esc_html_e( 'if word count enabled', 'wp-powersuite' ); ?>).</p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Options', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap" style="display:block;margin-bottom:8px;">
							<input type="checkbox" name="show_word_count" value="1" class="wp-powersuite-advanced-setting" data-setting-key="show_word_count" <?php checked( $show_word_count ); ?> />
							<span class="description"><?php esc_html_e( 'Include %words% in the template', 'wp-powersuite' ); ?></span>
						</label>
						<label class="wp-powersuite-toggle-wrap" style="display:block;margin-bottom:8px;">
							<input type="checkbox" name="count_excerpt" value="1" class="wp-powersuite-advanced-setting" data-setting-key="count_excerpt" <?php checked( $count_excerpt ); ?> />
							<span class="description"><?php esc_html_e( 'Add excerpt to the word count', 'wp-powersuite' ); ?></span>
						</label>
						<label class="wp-powersuite-toggle-wrap" style="display:block;">
							<input type="checkbox" name="skip_if_shortcode" value="1" class="wp-powersuite-advanced-setting" data-setting-key="skip_if_shortcode" <?php checked( $skip_if_shortcode ); ?> />
							<span class="description"><?php esc_html_e( 'Skip auto-insert if content already has the shortcode', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
			</tbody>
		</table>

		<div class="wp-powersuite-info-box wpps-module-callout">
			<p style="margin:0 0 6px;"><strong><?php esc_html_e( 'Shortcode', 'wp-powersuite' ); ?></strong></p>
			<p style="margin:0 0 4px;"><code>[wpps_reading_time]</code> — <?php esc_html_e( 'full line using your label template', 'wp-powersuite' ); ?></p>
			<p style="margin:0 0 4px;"><code>[wpps_reading_time format="short"]</code> — <?php esc_html_e( 'e.g. 5 mins', 'wp-powersuite' ); ?></p>
			<p style="margin:0 0 4px;"><code>[wpps_reading_time format="number"]</code> — <?php esc_html_e( 'minutes only', 'wp-powersuite' ); ?></p>
			<p style="margin:0 0 4px;"><code>[wpps_reading_time wpm="250"]</code> — <?php esc_html_e( 'override WPM for this shortcode', 'wp-powersuite' ); ?></p>
			<p style="margin:0 0 4px;"><code>[wpps_reading_time id="123"]</code> / <code>[wpps_reading_time post_id="123"]</code></p>
		</div>
	</form>

	<?php if ( ! empty( $available_pt ) ) : ?>
	<script>
	(function() {
		var root = document.querySelector('#<?php echo esc_js( $module_id ); ?>_post_types_ms');
		if (!root) return;
		var trigger = root.querySelector('.wpps-ct-multiselect__trigger');
		var triggerText = root.querySelector('.wpps-ct-multiselect__trigger-text');
		var dropdown = root.querySelector('.wpps-ct-multiselect__dropdown');
		var search = root.querySelector('.wpps-ct-multiselect__search');
		var options = root.querySelectorAll('.wpps-ct-multiselect__option');
		function countChecked() {
			var n = 0;
			options.forEach(function(o) {
				var cb = o.querySelector('input[type="checkbox"]');
				if (cb && cb.checked) n++;
			});
			return n;
		}
		function updateTriggerText() {
			var n = countChecked();
			var none = root.dataset.labelNone || '…';
			var single = root.dataset.labelSingle || '1';
			var multi = (root.dataset.labelMulti || '%d').replace('%d', n);
			triggerText.textContent = n === 0 ? none : (n === 1 ? single : multi);
		}
		function filterOptions(q) {
			q = (q || '').toLowerCase().trim();
			options.forEach(function(o) {
				var label = (o.dataset.label || '').toLowerCase();
				var slug = (o.dataset.slug || '').toLowerCase();
				var show = !q || label.indexOf(q) !== -1 || slug.indexOf(q) !== -1;
				o.classList.toggle('wpps-ct-multiselect__option--hidden', !show);
			});
		}
		function toggleDropdown(open) {
			var isOpen = open === undefined ? dropdown.hasAttribute('hidden') : !!open;
			if (isOpen) {
				dropdown.removeAttribute('hidden');
				trigger.setAttribute('aria-expanded', 'true');
				if (search) { search.value = ''; filterOptions(''); search.focus(); }
			} else {
				dropdown.setAttribute('hidden', '');
				trigger.setAttribute('aria-expanded', 'false');
			}
		}
		if (trigger) trigger.addEventListener('click', function() { toggleDropdown(); });
		if (search) {
			search.addEventListener('input', function() { filterOptions(this.value); });
			search.addEventListener('keydown', function(e) { if (e.key === 'Escape') toggleDropdown(false); });
		}
		root.querySelectorAll('.wpps-ct-multiselect__action').forEach(function(btn) {
			btn.addEventListener('click', function() {
				var action = btn.dataset.action;
				var visible = Array.prototype.filter.call(options, function(o) { return !o.classList.contains('wpps-ct-multiselect__option--hidden'); });
				if (action === 'select-all') {
					visible.forEach(function(o) { var cb = o.querySelector('input[type="checkbox"]'); if (cb) cb.checked = true; });
				} else if (action === 'clear') {
					options.forEach(function(o) { var cb = o.querySelector('input[type="checkbox"]'); if (cb) cb.checked = false; });
				}
				updateTriggerText();
			});
		});
		options.forEach(function(o) {
			var cb = o.querySelector('input[type="checkbox"]');
			if (cb) cb.addEventListener('change', updateTriggerText);
		});
		document.addEventListener('click', function(e) { if (!root.contains(e.target)) toggleDropdown(false); });
		updateTriggerText();
	})();
	</script>
	<?php endif; ?>
</div>
