<?php
/**
 * AI Summarize module settings (modal).
 *
 * @package AISummarize
 */

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 ?? 'ai-summarize' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'AI Summarize requires an active license. Activate your license to configure the shortcode and providers.', '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;
}

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

$module_id = $module_id ?? 'ai-summarize';
$uid       = 'wpps_ais_' . preg_replace( '/[^a-z0-9_]/i', '_', $module_id );

if ( ! class_exists( '\AISummarize\Module', false ) ) {
	$mod = __DIR__ . '/module.php';
	if ( is_readable( $mod ) ) {
		require_once $mod;
	}
}

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

$providers_resolved = class_exists( '\AISummarize\ProviderRegistry' )
	? \AISummarize\ProviderRegistry::resolve( $settings )
	: [];

$show_heading = ! empty( $settings['show_heading'] );
?>

<div class="wp-powersuite-module-settings wpps-ai-summarize-admin" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<p class="description">
		<?php
		echo wp_kses(
			sprintf(
				/* translators: %s: shortcode */
				__( 'Place %s in content or a template. Opens a third-party AI chat with the page URL — no API key required.', 'wp-powersuite' ),
				'<code>[wpps_ai_summarize]</code>'
			),
			[ 'code' => [] ]
		);
		?>
	</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( 'Show heading', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" id="<?php echo esc_attr( $uid ); ?>_show_heading" class="wp-powersuite-advanced-setting" data-setting-key="show_heading" value="1" <?php checked( $show_heading ); ?> />
							<span class="description"><?php esc_html_e( 'Show a heading above the provider buttons.', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr class="wpps-ais-heading-text-row"<?php echo $show_heading ? '' : ' hidden'; ?>>
					<th scope="row"><label for="<?php echo esc_attr( $uid ); ?>_heading_text"><?php esc_html_e( 'Heading text', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text" id="<?php echo esc_attr( $uid ); ?>_heading_text" class="regular-text wp-powersuite-advanced-setting" data-setting-key="heading_text" value="<?php echo esc_attr( (string) ( $settings['heading_text'] ?? '' ) ); ?>" />
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Open in new tab', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="open_new_tab" value="1" <?php checked( ! empty( $settings['open_new_tab'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Open AI providers in a new browser tab.', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Also copy prompt', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="copy_prompt_before_opening" value="1" <?php checked( ! empty( $settings['copy_prompt_before_opening'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Also copy the prompt to the clipboard (prefill URL is still used).', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Remove query parameters', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="remove_query_params" value="1" <?php checked( ! empty( $settings['remove_query_params'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Strip tracking args from the shared URL (keeps ?p= for plain permalinks).', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Visibility', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wp-powersuite-toggle-wrap" style="margin-right:16px;">
							<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="disable_logged_out" value="1" <?php checked( ! empty( $settings['disable_logged_out'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Hide for logged-out users', 'wp-powersuite' ); ?></span>
						</label>
						<label class="wp-powersuite-toggle-wrap">
							<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="disable_logged_in" value="1" <?php checked( ! empty( $settings['disable_logged_in'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Hide for logged-in users', 'wp-powersuite' ); ?></span>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Providers', 'wp-powersuite' ); ?></th>
					<td>
						<input type="hidden" class="wp-powersuite-advanced-setting" data-setting-key="provider_order" id="<?php echo esc_attr( $uid ); ?>_provider_order" value="<?php echo esc_attr( wp_json_encode( array_values( $settings['provider_order'] ?? [] ) ) ); ?>" />
						<ul class="wpps-ais-provider-list" id="<?php echo esc_attr( $uid ); ?>_provider_list">
							<?php foreach ( $providers_resolved as $slug => $provider ) : ?>
								<?php $saved = $settings['providers'][ $slug ] ?? []; ?>
								<li class="wpps-ais-provider-item" draggable="true" data-slug="<?php echo esc_attr( $slug ); ?>">
									<span class="wpps-ais-provider-item__handle" aria-hidden="true" title="<?php esc_attr_e( 'Drag to reorder', 'wp-powersuite' ); ?>">&#8942;&#8942;</span>
									<label>
										<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="providers.<?php echo esc_attr( $slug ); ?>.enabled" value="1" <?php checked( ! empty( $saved['enabled'] ) || ( ! isset( $saved['enabled'] ) && ! empty( $provider['enabled'] ) ) ); ?> />
										<?php echo esc_html( (string) ( $provider['name'] ?? $slug ) ); ?>
									</label>
								</li>
							<?php endforeach; ?>
						</ul>
						<p class="description"><?php esc_html_e( 'Enable providers and drag to reorder.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Display', 'wp-powersuite' ); ?></th>
					<td>
						<div class="wpps-ais-display-row">
							<label>
								<span class="screen-reader-text"><?php esc_html_e( 'Alignment', 'wp-powersuite' ); ?></span>
								<select id="<?php echo esc_attr( $uid ); ?>_alignment" class="wp-powersuite-advanced-setting" data-setting-key="alignment">
									<option value="left" <?php selected( ( $settings['alignment'] ?? '' ) === 'left' ); ?>><?php esc_html_e( 'Left', 'wp-powersuite' ); ?></option>
									<option value="center" <?php selected( ( $settings['alignment'] ?? '' ) === 'center' ); ?>><?php esc_html_e( 'Center', 'wp-powersuite' ); ?></option>
									<option value="right" <?php selected( ( $settings['alignment'] ?? '' ) === 'right' ); ?>><?php esc_html_e( 'Right', 'wp-powersuite' ); ?></option>
								</select>
							</label>
							<label>
								<span class="screen-reader-text"><?php esc_html_e( 'Button style', 'wp-powersuite' ); ?></span>
								<select id="<?php echo esc_attr( $uid ); ?>_button_style" class="wp-powersuite-advanced-setting" data-setting-key="button_style">
									<option value="icon" <?php selected( ( $settings['button_style'] ?? '' ) === 'icon' ); ?>><?php esc_html_e( 'Icon only', 'wp-powersuite' ); ?></option>
									<option value="icon_label" <?php selected( ( $settings['button_style'] ?? '' ) === 'icon_label' ); ?>><?php esc_html_e( 'Icon + label', 'wp-powersuite' ); ?></option>
									<option value="label" <?php selected( ( $settings['button_style'] ?? '' ) === 'label' ); ?>><?php esc_html_e( 'Label only', 'wp-powersuite' ); ?></option>
								</select>
							</label>
							<label>
								<span class="screen-reader-text"><?php esc_html_e( 'Button shape', 'wp-powersuite' ); ?></span>
								<select id="<?php echo esc_attr( $uid ); ?>_shape" class="wp-powersuite-advanced-setting" data-setting-key="button_shape">
									<option value="rounded" <?php selected( ( $settings['button_shape'] ?? '' ) === 'rounded' ); ?>><?php esc_html_e( 'Rounded', 'wp-powersuite' ); ?></option>
									<option value="square" <?php selected( ( $settings['button_shape'] ?? '' ) === 'square' ); ?>><?php esc_html_e( 'Square', 'wp-powersuite' ); ?></option>
									<option value="circle" <?php selected( ( $settings['button_shape'] ?? '' ) === 'circle' ); ?>><?php esc_html_e( 'Circle', 'wp-powersuite' ); ?></option>
								</select>
							</label>
							<label>
								<span class="screen-reader-text"><?php esc_html_e( 'Button size', 'wp-powersuite' ); ?></span>
								<select id="<?php echo esc_attr( $uid ); ?>_size" class="wp-powersuite-advanced-setting" data-setting-key="button_size">
									<option value="small" <?php selected( ( $settings['button_size'] ?? '' ) === 'small' ); ?>><?php esc_html_e( 'Small', 'wp-powersuite' ); ?></option>
									<option value="medium" <?php selected( ( $settings['button_size'] ?? '' ) === 'medium' ); ?>><?php esc_html_e( 'Medium', 'wp-powersuite' ); ?></option>
									<option value="large" <?php selected( ( $settings['button_size'] ?? '' ) === 'large' ); ?>><?php esc_html_e( 'Large', 'wp-powersuite' ); ?></option>
								</select>
							</label>
						</div>
						<p class="description"><?php esc_html_e( 'Alignment, style, shape, and size.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>
</div>

<style>
.wpps-ai-summarize-admin .wpps-ais-provider-list { list-style: none; margin: 0 0 4px; padding: 0; }
.wpps-ai-summarize-admin .wpps-ais-provider-item { display: flex; align-items: center; gap: 6px; margin: 0; padding: 2px 0; }
.wpps-ai-summarize-admin .wpps-ais-provider-item__handle { cursor: grab; color: #8c8f94; user-select: none; letter-spacing: -2px; line-height: 1; }
.wpps-ai-summarize-admin .wpps-ais-provider-item label { margin: 0; font-weight: 400; }
.wpps-ai-summarize-admin .wpps-ais-provider-item.is-dragging { opacity: 0.5; }
.wpps-ai-summarize-admin .wpps-ais-display-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.wpps-ai-summarize-admin .wpps-ais-display-row select { max-width: 140px; }
</style>

<script>
(function ($) {
	'use strict';
	var mid = <?php echo wp_json_encode( $module_id ); ?>;
	var uid = <?php echo wp_json_encode( $uid ); ?>;
	var $panel = $('.wpps-ai-summarize-admin[data-module-id="' + mid + '"]');
	if (!$panel.length) { return; }

	function syncHeadingRow() {
		var on = $panel.find('#' + uid + '_show_heading').is(':checked');
		$panel.find('.wpps-ais-heading-text-row').prop('hidden', !on);
	}
	$panel.on('change', '#' + uid + '_show_heading', syncHeadingRow);
	syncHeadingRow();

	function syncOrder() {
		var order = [];
		$panel.find('#' + uid + '_provider_list .wpps-ais-provider-item').each(function () {
			var slug = $(this).attr('data-slug');
			if (slug) { order.push(slug); }
		});
		$panel.find('#' + uid + '_provider_order').val(JSON.stringify(order));
	}

	var dragEl = null;
	$panel.on('dragstart', '.wpps-ais-provider-item', function (e) {
		dragEl = this;
		$(this).addClass('is-dragging');
		if (e.originalEvent && e.originalEvent.dataTransfer) {
			e.originalEvent.dataTransfer.effectAllowed = 'move';
		}
	});
	$panel.on('dragend', '.wpps-ais-provider-item', function () {
		$(this).removeClass('is-dragging');
		dragEl = null;
		syncOrder();
	});
	$panel.on('dragover', '.wpps-ais-provider-item', function (e) {
		e.preventDefault();
		if (!dragEl || dragEl === this) { return; }
		var $list = $(this).parent();
		var rect = this.getBoundingClientRect();
		var next = (e.originalEvent.clientY - rect.top) > (rect.height / 2);
		if (next) {
			$list[0].insertBefore(dragEl, this.nextSibling);
		} else {
			$list[0].insertBefore(dragEl, this);
		}
	});

	syncOrder();
})(jQuery);
</script>
