<?php

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'compact-tables';
}

$settings = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$defaults = [
	'post_types'   => [ 'post', 'page' ],
	'row_height'   => 28,
	'cell_padding' => 3,
	'font_size'    => 12,
	'compact_date' => true,
];
$settings = array_merge( $defaults, $settings );

$post_types_selected = $settings['post_types'] ?? [];
if ( ! is_array( $post_types_selected ) ) {
	$post_types_selected = [];
}

$row_height   = isset( $settings['row_height'] ) ? max( 24, min( 40, (int) $settings['row_height'] ) ) : 28;
$cell_padding = isset( $settings['cell_padding'] ) ? max( 1, min( 10, (int) $settings['cell_padding'] ) ) : 3;
$font_size    = isset( $settings['font_size'] ) ? max( 10, min( 14, (int) $settings['font_size'] ) ) : 12;
$compact_date = ! empty( $settings['compact_date'] );

$excluded = [
	'revision', 'nav_menu_item', 'customize_changeset', 'oembed_cache', 'user_request',
	'wp_global_styles', 'wp_font_family', 'wp_font_face', 'elementskit_template', 'elementskit_content',
	'wp_css', 'wp_template_part', 'wp_navigation', 'jkit-header', 'jkit-footer', 'jkit-template',
	'attachment', /* Media uses upload.php; compact applies to edit.php list tables only */
];
$always_include = [ 'wp_block', 'elementor_library' ];
$labels_skip    = [ 'Custom CSS', 'Template Parts', 'Navigation Menus', 'Changesets', 'oEmbed Responses', 'User Requests', 'Global Styles', 'Font Families', 'Font Faces', 'ElementsKit items' ];
$cpt_objects    = get_post_types( [ 'public' => true ], 'objects' );
$post_type_list = [];

foreach ( $cpt_objects as $pt ) {
	if ( in_array( $pt->name, $excluded, true ) ) {
		continue;
	}
	if ( ! in_array( $pt->name, $always_include, true ) && in_array( $pt->labels->name ?? '', $labels_skip, true ) ) {
		continue;
	}
	$post_type_list[] = [
		'name'  => $pt->name,
		'label' => $pt->labels->name,
	];
}

?>
<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Make admin post list tables compact so you can see 2–3× more rows per screen. Choose post types, then tweak row height, padding, and font size. Works alongside Admin Columns Customizer.', 'wp-powersuite' ); ?>
	</p>

	<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"><?php esc_html_e( 'Post types', 'wp-powersuite' ); ?></th>
					<td>
						<p class="description" style="margin-bottom: 8px;"><?php esc_html_e( 'Apply compact layout to these list tables:', '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' ) ); ?>"
							<?php /* translators: %d: number value. */ ?>
							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 post types...', '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 ( $post_type_list as $pt ) : ?>
										<?php $checked = in_array( $pt['name'], $post_types_selected, true ); ?>
										<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $pt['name'] ); ?>" data-label="<?php echo esc_attr( $pt['label'] ); ?>">
											<input type="checkbox"
												name="post_types[]"
												class="wp-powersuite-advanced-setting"
												data-setting-key="post_types"
												value="<?php echo esc_attr( $pt['name'] ); ?>"
												<?php checked( $checked ); ?>
											/>
											<span class="wpps-ct-multiselect__option-label"><?php echo esc_html( $pt['label'] ); ?></span>
											<span class="wpps-ct-multiselect__option-slug">(<?php echo esc_html( $pt['name'] ); ?>)</span>
										</label>
									<?php endforeach; ?>
								</div>
							</div>
						</div>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_row_height"><?php esc_html_e( 'Row height', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="number"
							id="<?php echo esc_attr( $module_id ); ?>_row_height"
							name="row_height"
							value="<?php echo esc_attr( $row_height ); ?>"
							min="24"
							max="40"
							step="1"
							class="small-text wp-powersuite-advanced-setting"
							data-setting-key="row_height"
						/>
						<span class="description"><?php esc_html_e( 'px (24–40)', 'wp-powersuite' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_cell_padding"><?php esc_html_e( 'Cell padding', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="number"
							id="<?php echo esc_attr( $module_id ); ?>_cell_padding"
							name="cell_padding"
							value="<?php echo esc_attr( $cell_padding ); ?>"
							min="1"
							max="10"
							step="1"
							class="small-text wp-powersuite-advanced-setting"
							data-setting-key="cell_padding"
						/>
						<span class="description"><?php esc_html_e( 'px (1–10)', 'wp-powersuite' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_font_size"><?php esc_html_e( 'Font size', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="number"
							id="<?php echo esc_attr( $module_id ); ?>_font_size"
							name="font_size"
							value="<?php echo esc_attr( $font_size ); ?>"
							min="10"
							max="14"
							step="1"
							class="small-text wp-powersuite-advanced-setting"
							data-setting-key="font_size"
						/>
						<span class="description"><?php esc_html_e( 'px (10–14)', 'wp-powersuite' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Compact date', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox"
								name="compact_date"
								class="wp-powersuite-advanced-setting"
								data-setting-key="compact_date"
								value="1"
								<?php checked( $compact_date ); ?>
							/>
							<?php esc_html_e( 'Use single-line date format (e.g. 2024/12/01 3:45 pm) in the Date column', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<style>
		.wpps-ct-multiselect { position: relative; max-width: 360px; }
		.wpps-ct-multiselect__trigger {
			display: flex; align-items: center; justify-content: space-between;
			width: 100%; padding: 8px 12px; border: 1px solid #8c8f94; border-radius: 4px;
			background: #fff; font-size: 14px; text-align: left; cursor: pointer;
			line-height: 1.4; color: #1d2327;
		}
		.wpps-ct-multiselect__trigger:hover { border-color: #2271b1; }
		.wpps-ct-multiselect__chevron { font-size: 18px; width: 18px; height: 18px; color: #787c82; flex-shrink: 0; margin-left: 8px; }
		.wpps-ct-multiselect__trigger[aria-expanded="true"] .wpps-ct-multiselect__chevron { transform: rotate(180deg); }
		.wpps-ct-multiselect__dropdown {
			position: absolute; top: 100%; left: 0; right: 0; margin-top: 4px;
			border: 1px solid #8c8f94; border-radius: 4px; background: #fff;
			box-shadow: 0 2px 8px rgba(0,0,0,.12); z-index: 100;
			max-height: 280px; display: flex; flex-direction: column;
		}
		.wpps-ct-multiselect__dropdown[hidden] { display: none !important; }
		.wpps-ct-multiselect__search {
			width: 100%; padding: 8px 12px; border: none; border-bottom: 1px solid #dcdcde;
			font-size: 13px; box-sizing: border-box; outline: none;
		}
		.wpps-ct-multiselect__search::placeholder { color: #a7aaad; }
		.wpps-ct-multiselect__actions { padding: 6px 10px; border-bottom: 1px solid #dcdcde; display: flex; gap: 12px; flex-shrink: 0; }
		.wpps-ct-multiselect__action {
			background: none; border: none; color: #2271b1; cursor: pointer; font-size: 12px; padding: 0;
		}
		.wpps-ct-multiselect__action:hover { color: #135e96; text-decoration: underline; }
		.wpps-ct-multiselect__options {
			overflow-y: auto; padding: 4px 0; max-height: 200px;
		}
		.wpps-ct-multiselect__option {
			display: flex; align-items: center; gap: 6px; padding: 6px 12px; cursor: pointer;
			font-size: 13px; white-space: nowrap;
		}
		.wpps-ct-multiselect__option:hover { background: #f0f0f1; }
		.wpps-ct-multiselect__option input { flex-shrink: 0; margin: 0; }
		.wpps-ct-multiselect__option-slug { color: #646970; font-size: 12px; }
		.wpps-ct-multiselect__option.wpps-ct-multiselect__option--hidden { display: none; }
	</style>
	<script>
		(function() {
			var root = document.querySelector('.wpps-ct-multiselect');
			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 || 'Select post types...';
				var single = root.dataset.labelSingle || '1 selected';
				var multi = (root.dataset.labelMulti || '%d selected').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');
					search.value = '';
					filterOptions('');
					search.focus();
				} else {
					dropdown.setAttribute('hidden', '');
					trigger.setAttribute('aria-expanded', 'false');
				}
			}

			trigger.addEventListener('click', function() { toggleDropdown(); });
			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>
</div>

