<?php

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

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

$module_id = $module_id ?? 'table-of-contents';

$raw      = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$settings = class_exists( '\TableOfContents\Module' )
	? \TableOfContents\Module::normalizeSettings( is_array( $raw ) ? $raw : [] )
	: array_merge(
		[
			'auto_insert'        => true,
			'enabled_post_types' => [ 'post' ],
			'position'           => 'after_first_paragraph',
			'minimum_headings'   => 3,
			'heading_levels'     => '2,3',
			'toc_title'          => 'Table of Contents',
			'numbered_list'      => false,
		],
		is_array( $raw ) ? $raw : []
	);

$enabled_post_types = $settings['enabled_post_types'];

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

$auto_insert      = ! empty( $settings['auto_insert'] );
$position         = (string) $settings['position'];
$minimum_headings = (int) $settings['minimum_headings'];
$heading_levels   = (string) $settings['heading_levels'];
$toc_title        = (string) $settings['toc_title'];
$numbered_list    = ! empty( $settings['numbered_list'] );
?>

<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Generate a table of contents from headings with anchor links. Use [wpps_toc] or [toc] (when available) for manual placement, or enable auto-insert.', '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">
						<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"
								<?php checked( $auto_insert ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="auto_insert"
							/>
							<span class="description"><?php esc_html_e( 'Automatically add TOC to single posts/pages', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label><?php esc_html_e( 'Post Types', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<?php if ( empty( $available_post_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( 'Select which post types use the table of contents (auto-insert and shortcodes).', '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 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 ( $available_post_types as $post_type_name => $post_type_object ) : ?>
											<?php
											$label   = $post_type_object->labels->name ?? $post_type_name;
											$checked = in_array( $post_type_name, $enabled_post_types, true );
											?>
											<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="enabled_post_types[]"
													class="wp-powersuite-advanced-setting"
													data-setting-key="enabled_post_types"
													value="<?php echo esc_attr( $post_type_name ); ?>"
													<?php checked( $checked ); ?>
												/>
												<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 ); ?>_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="after_first_paragraph" <?php selected( $position, 'after_first_paragraph' ); ?>><?php esc_html_e( 'After First Paragraph', 'wp-powersuite' ); ?></option>
							<option value="before_first_heading" <?php selected( $position, 'before_first_heading' ); ?>><?php esc_html_e( 'Before First Heading', 'wp-powersuite' ); ?></option>
							<option value="after_first_heading" <?php selected( $position, 'after_first_heading' ); ?>><?php esc_html_e( 'After First Heading', 'wp-powersuite' ); ?></option>
							<option value="top" <?php selected( $position, 'top' ); ?>><?php esc_html_e( 'Top of Content', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Where to display the TOC when auto-insert is enabled.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_minimum_headings"><?php esc_html_e( 'Minimum Headings', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input
							type="number"
							id="<?php echo esc_attr( $module_id ); ?>_minimum_headings"
							name="minimum_headings"
							value="<?php echo esc_attr( (string) $minimum_headings ); ?>"
							min="1"
							max="50"
							step="1"
							class="small-text wp-powersuite-advanced-setting"
							data-setting-key="minimum_headings"
						/>
						<p class="description"><?php esc_html_e( 'Only show TOC if the post has at least this many matching headings.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_heading_levels"><?php esc_html_e( 'Heading Levels', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input
							type="text"
							id="<?php echo esc_attr( $module_id ); ?>_heading_levels"
							name="heading_levels"
							value="<?php echo esc_attr( $heading_levels ); ?>"
							class="regular-text wp-powersuite-advanced-setting"
							data-setting-key="heading_levels"
							placeholder="2,3,4"
						/>
						<p class="description"><?php esc_html_e( 'Comma-separated levels to include (e.g. 2,3,4 for H2–H4).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_toc_title"><?php esc_html_e( 'TOC Title', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input
							type="text"
							id="<?php echo esc_attr( $module_id ); ?>_toc_title"
							name="toc_title"
							value="<?php echo esc_attr( $toc_title ); ?>"
							class="regular-text wp-powersuite-advanced-setting"
							data-setting-key="toc_title"
							placeholder="<?php esc_attr_e( 'Table of Contents', 'wp-powersuite' ); ?>"
						/>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_numbered_list"><?php esc_html_e( 'Numbered List', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input
								type="checkbox"
								id="<?php echo esc_attr( $module_id ); ?>_numbered_list"
								name="numbered_list"
								value="1"
								<?php checked( $numbered_list ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="numbered_list"
							/>
							<span class="description"><?php esc_html_e( 'Use numbers instead of bullets', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
			</tbody>
		</table>

		<div class="wp-powersuite-info-box" style="background: #f0f6fc; border-left: 4px solid #2271b1; padding: 12px; margin: 20px 0;">
			<p style="margin: 0 0 8px 0;"><strong><?php esc_html_e( 'Shortcode', 'wp-powersuite' ); ?></strong></p>
			<p style="margin: 0 0 8px 0;"><code>[wpps_toc]</code> <?php esc_html_e( 'or', 'wp-powersuite' ); ?> <code>[toc]</code> — <?php esc_html_e( 'Manual placement. The [toc] tag is registered only if no other plugin already defines it. If either shortcode appears in the post, auto-insert is skipped for that post.', 'wp-powersuite' ); ?></p>
			<p style="margin: 0;"><strong><?php esc_html_e( 'Styling', 'wp-powersuite' ); ?></strong> — <?php esc_html_e( 'The TOC uses', 'wp-powersuite' ); ?> <code>nav.wpps-toc</code>, <code>.wpps-toc__title</code>, <code>.wpps-toc__link</code>, <?php esc_html_e( 'etc. Override in your theme.', 'wp-powersuite' ); ?></p>
		</div>
	</form>
</div>

<?php if ( ! empty( $available_post_types ) ) : ?>
<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 || '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('');
			if (search) 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; ?>
