<?php

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'alpine-js-enqueue';
}

if ( ! class_exists( \AlpineJsEnqueue\Module::class, false ) ) {
	$module_file = __DIR__ . DIRECTORY_SEPARATOR . 'module.php';
	if ( is_readable( $module_file ) ) {
		require_once $module_file;
	}
}

$stored_settings = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $stored_settings ) ) {
	$stored_settings = [];
}

$settings = class_exists( \AlpineJsEnqueue\Module::class )
	? \AlpineJsEnqueue\Module::normalizeSettings( $stored_settings )
	: $stored_settings;

$load_frontend         = ! empty( $settings['load_frontend'] );
$load_admin            = ! empty( $settings['load_admin'] );
$source                = $settings['source'] ?? 'bundled';
$version               = $settings['version'] ?? '3.13.5';
$custom_path           = $settings['custom_path'] ?? '';
$allow_cdn_fallback    = ! empty( $settings['allow_cdn_fallback'] );
$defer                 = ! empty( $settings['defer'] );
$async                 = ! empty( $settings['async'] );
$init_code             = $settings['init_code'] ?? '';
$frontend_scope        = $settings['frontend_scope'] ?? 'all';
$frontend_post_types   = is_array( $settings['frontend_post_types'] ?? null ) ? $settings['frontend_post_types'] : [];
$exclude_feeds         = ! empty( $settings['exclude_feeds'] );
$exclude_customizer    = ! empty( $settings['exclude_customizer'] );
$require_alpine_markup = ! empty( $settings['require_alpine_markup'] );
$admin_scope           = $settings['admin_scope'] ?? 'powersuite';
$admin_screens         = is_array( $settings['admin_screens'] ?? null ) ? $settings['admin_screens'] : [];
$skip_if_detected      = ! empty( $settings['skip_if_detected'] );
$available_versions    = class_exists( \AlpineJsEnqueue\Module::class )
	? \AlpineJsEnqueue\Module::getAvailableVersions()
	: [ '3.13.5' => '3.13.5' ];
$public_post_types     = get_post_types( [ 'public' => true ], 'objects' );
$no_load_contexts      = ! $load_frontend && ! $load_admin;
$bundled_available     = class_exists( \AlpineJsEnqueue\Module::class )
	&& is_readable( \AlpineJsEnqueue\Module::getBundledAssetPath() );
?>

<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Load Alpine.js only where you need reactive UI. Prefer the bundled copy for privacy and supply-chain safety; use CDN only when required.', 'wp-powersuite' ); ?>
	</p>

	<?php if ( $no_load_contexts ) : ?>
		<div class="wp-powersuite-info-box wp-powersuite-info-box--warning">
			<p>
				<strong><?php esc_html_e( 'No load context selected.', 'wp-powersuite' ); ?></strong>
				<?php esc_html_e( 'The module is enabled but Alpine.js will not load until you choose Frontend and/or Admin below.', 'wp-powersuite' ); ?>
			</p>
		</div>
	<?php endif; ?>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Load On', 'wp-powersuite' ); ?></th>
					<td>
						<fieldset>
							<label for="<?php echo esc_attr( $module_id ); ?>_load_frontend" class="wpps-alpine-setting-label">
								<input
									type="checkbox"
									id="<?php echo esc_attr( $module_id ); ?>_load_frontend"
									name="load_frontend"
									class="wp-powersuite-advanced-setting"
									data-setting-key="load_frontend"
									value="1"
									<?php checked( $load_frontend ); ?>
								/>
								<?php esc_html_e( 'Frontend (Public Website)', 'wp-powersuite' ); ?>
							</label>
							<label for="<?php echo esc_attr( $module_id ); ?>_load_admin" class="wpps-alpine-setting-label">
								<input
									type="checkbox"
									id="<?php echo esc_attr( $module_id ); ?>_load_admin"
									name="load_admin"
									class="wp-powersuite-advanced-setting"
									data-setting-key="load_admin"
									value="1"
									<?php checked( $load_admin ); ?>
								/>
								<?php esc_html_e( 'Admin Dashboard', 'wp-powersuite' ); ?>
							</label>
						</fieldset>
						<p class="description">
							<?php esc_html_e( 'Enable only the contexts where your theme or custom markup uses Alpine directives.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>

				<tr class="wpps-alpine-frontend-row">
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_frontend_scope"><?php esc_html_e( 'Frontend Scope', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id ); ?>_frontend_scope"
							name="frontend_scope"
							class="wp-powersuite-advanced-setting"
							data-setting-key="frontend_scope"
						>
							<option value="all" <?php selected( $frontend_scope, 'all' ); ?>><?php esc_html_e( 'All frontend pages', 'wp-powersuite' ); ?></option>
							<option value="singular" <?php selected( $frontend_scope, 'singular' ); ?>><?php esc_html_e( 'Singular posts/pages only', 'wp-powersuite' ); ?></option>
							<option value="post_types" <?php selected( $frontend_scope, 'post_types' ); ?>><?php esc_html_e( 'Selected post types only', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description">
							<?php esc_html_e( 'Limit frontend loading to reduce conflicts with checkout, LMS, and page-builder routes.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>

				<tr id="<?php echo esc_attr( $module_id ); ?>_frontend_post_types_row" class="wpps-alpine-frontend-row">
					<th scope="row"><?php esc_html_e( 'Frontend Post Types', 'wp-powersuite' ); ?></th>
					<td>
						<fieldset>
							<?php foreach ( $public_post_types as $post_type_name => $post_type_object ) : ?>
								<label class="wpps-alpine-setting-label">
									<input
										type="checkbox"
										name="frontend_post_types[]"
										class="wp-powersuite-advanced-setting"
										data-setting-key="frontend_post_types"
										value="<?php echo esc_attr( $post_type_name ); ?>"
										<?php checked( in_array( $post_type_name, $frontend_post_types, true ) ); ?>
									/>
									<?php echo esc_html( $post_type_object->labels->singular_name ?? $post_type_name ); ?>
								</label>
							<?php endforeach; ?>
						</fieldset>
					</td>
				</tr>

				<tr class="wpps-alpine-frontend-row">
					<th scope="row"><?php esc_html_e( 'Frontend Exclusions', 'wp-powersuite' ); ?></th>
					<td>
						<fieldset>
							<label class="wpps-alpine-setting-label">
								<input type="checkbox" name="exclude_feeds" class="wp-powersuite-advanced-setting" data-setting-key="exclude_feeds" value="1" <?php checked( $exclude_feeds ); ?> />
								<?php esc_html_e( 'Skip RSS/Atom feeds', 'wp-powersuite' ); ?>
							</label>
							<label class="wpps-alpine-setting-label">
								<input type="checkbox" name="exclude_customizer" class="wp-powersuite-advanced-setting" data-setting-key="exclude_customizer" value="1" <?php checked( $exclude_customizer ); ?> />
								<?php esc_html_e( 'Skip Customizer preview', 'wp-powersuite' ); ?>
							</label>
							<label class="wpps-alpine-setting-label">
								<input type="checkbox" name="require_alpine_markup" class="wp-powersuite-advanced-setting" data-setting-key="require_alpine_markup" value="1" <?php checked( $require_alpine_markup ); ?> />
								<?php esc_html_e( 'Only load on singular content that contains Alpine directives', 'wp-powersuite' ); ?>
							</label>
						</fieldset>
					</td>
				</tr>

				<tr class="wpps-alpine-admin-row">
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_admin_scope"><?php esc_html_e( 'Admin Scope', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id ); ?>_admin_scope"
							name="admin_scope"
							class="wp-powersuite-advanced-setting"
							data-setting-key="admin_scope"
						>
							<option value="powersuite" <?php selected( $admin_scope, 'powersuite' ); ?>><?php esc_html_e( 'WP PowerSuite screens only (recommended)', 'wp-powersuite' ); ?></option>
							<option value="all" <?php selected( $admin_scope, 'all' ); ?>><?php esc_html_e( 'All wp-admin screens', 'wp-powersuite' ); ?></option>
							<option value="screens" <?php selected( $admin_scope, 'screens' ); ?>><?php esc_html_e( 'Selected admin screens', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>

				<tr id="<?php echo esc_attr( $module_id ); ?>_admin_screens_row" class="wpps-alpine-admin-row">
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_admin_screens"><?php esc_html_e( 'Admin Screen IDs', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<textarea
							id="<?php echo esc_attr( $module_id ); ?>_admin_screens"
							name="admin_screens"
							class="large-text code wp-powersuite-advanced-setting"
							data-setting-key="admin_screens"
							rows="4"
							placeholder="<?php esc_attr_e( "toplevel_page_powersuite\npost", 'wp-powersuite' ); ?>"
						><?php echo esc_textarea( implode( "\n", $admin_screens ) ); ?></textarea>
						<p class="description">
							<?php esc_html_e( 'One screen ID per line (for example: toplevel_page_powersuite, post, woocommerce_page_wc-settings).', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>

				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_source"><?php esc_html_e( 'Source', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id ); ?>_source"
							name="source"
							class="wp-powersuite-advanced-setting"
							data-setting-key="source"
						>
							<option value="bundled" <?php selected( $source, 'bundled' ); ?>><?php esc_html_e( 'Bundled (recommended)', 'wp-powersuite' ); ?></option>
							<option value="cdn" <?php selected( $source, 'cdn' ); ?>><?php esc_html_e( 'CDN (jsDelivr)', 'wp-powersuite' ); ?></option>
							<option value="custom" <?php selected( $source, 'custom' ); ?>><?php esc_html_e( 'Custom local file', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description">
							<?php
							if ( $bundled_available ) {
								esc_html_e( 'Bundled Alpine.js is served from your site with Subresource Integrity. CDN mode sends browser requests to cdn.jsdelivr.net.', 'wp-powersuite' );
							} else {
								esc_html_e( 'Bundled file is missing from the plugin. Choose CDN or provide a custom local file.', 'wp-powersuite' );
							}
							?>
						</p>
					</td>
				</tr>

				<tr id="<?php echo esc_attr( $module_id ); ?>_version_row">
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_version"><?php esc_html_e( 'CDN Version', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id ); ?>_version"
							name="version"
							class="wp-powersuite-advanced-setting"
							data-setting-key="version"
						>
							<?php foreach ( $available_versions as $ver => $label ) : ?>
								<option value="<?php echo esc_attr( $ver ); ?>" <?php selected( $version, $ver ); ?>>
									<?php
									echo esc_html(
										$ver === '3.13.5'
											/* translators: %s: Alpine.js version number. */
											? sprintf( __( '%s (bundled default)', 'wp-powersuite' ), $ver )
											: $label
									);
									?>
								</option>
							<?php endforeach; ?>
						</select>
					</td>
				</tr>

				<tr id="<?php echo esc_attr( $module_id ); ?>_custom_path_row">
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_custom_path"><?php esc_html_e( 'Custom File Path', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input
							type="text"
							id="<?php echo esc_attr( $module_id ); ?>_custom_path"
							name="custom_path"
							value="<?php echo esc_attr( $custom_path ); ?>"
							class="large-text code wp-powersuite-advanced-setting"
							data-setting-key="custom_path"
							placeholder="<?php echo esc_attr( WP_CONTENT_DIR . '/alpine.min.js' ); ?>"
						/>
						<p class="description">
							<?php esc_html_e( 'Must be a readable .js file inside wp-content. Alpine will not load if the file is missing unless CDN fallback is enabled.', 'wp-powersuite' ); ?>
						</p>
						<label class="wpps-alpine-setting-label">
							<input type="checkbox" name="allow_cdn_fallback" class="wp-powersuite-advanced-setting" data-setting-key="allow_cdn_fallback" value="1" <?php checked( $allow_cdn_fallback ); ?> />
							<?php esc_html_e( 'Allow CDN fallback when bundled/custom file is unavailable', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Loading Strategy', 'wp-powersuite' ); ?></th>
					<td>
						<fieldset>
							<label class="wpps-alpine-setting-label">
								<input type="radio" name="alpine_load_strategy" class="wpps-alpine-load-strategy" value="defer" <?php checked( $defer && ! $async ); ?> />
								<?php esc_html_e( 'Defer (recommended)', 'wp-powersuite' ); ?>
							</label>
							<label class="wpps-alpine-setting-label">
								<input type="radio" name="alpine_load_strategy" class="wpps-alpine-load-strategy" value="async" <?php checked( $async ); ?> />
								<?php esc_html_e( 'Async', 'wp-powersuite' ); ?>
							</label>
							<input type="hidden" id="<?php echo esc_attr( $module_id ); ?>_defer" name="defer" class="wp-powersuite-advanced-setting" data-setting-key="defer" value="<?php echo $defer && ! $async ? '1' : '0'; ?>" />
							<input type="hidden" id="<?php echo esc_attr( $module_id ); ?>_async" name="async" class="wp-powersuite-advanced-setting" data-setting-key="async" value="<?php echo $async ? '1' : '0'; ?>" />
						</fieldset>
						<p class="description">
							<?php esc_html_e( 'Defer and async are mutually exclusive. Defer preserves execution order with other footer scripts.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Compatibility', 'wp-powersuite' ); ?></th>
					<td>
						<label class="wpps-alpine-setting-label">
							<input type="checkbox" name="skip_if_detected" class="wp-powersuite-advanced-setting" data-setting-key="skip_if_detected" value="1" <?php checked( $skip_if_detected ); ?> />
							<?php esc_html_e( 'Skip loading when another plugin or theme already registered Alpine.js', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>

				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_init_code"><?php esc_html_e( 'Initialization Code', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<textarea
							id="<?php echo esc_attr( $module_id ); ?>_init_code"
							name="init_code"
							class="large-text code wp-powersuite-advanced-setting"
							data-setting-key="init_code"
							rows="10"
							placeholder="<?php esc_attr_e( "Alpine.data('counter', () => ({\n  count: 0,\n  increment() { this.count++; }\n}));", 'wp-powersuite' ); ?>"
						><?php echo esc_textarea( $init_code ); ?></textarea>
						<p class="description">
							<?php esc_html_e( 'Runs on the alpine:init event after Alpine loads. Requires the unfiltered_html capability to save. Useful for Alpine.data(), Alpine.store(), Alpine.plugin(), and Alpine.config().', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
			</tbody>
		</table>

		<div class="wp-powersuite-info-box wp-powersuite-info-box--warning">
			<p>
				<strong><?php esc_html_e( 'Compatibility notes:', 'wp-powersuite' ); ?></strong><br>
				<?php esc_html_e( 'If another plugin or your theme already loads Alpine.js, keep duplicate detection enabled to avoid double-loading.', 'wp-powersuite' ); ?><br>
				<?php esc_html_e( 'CDN mode makes third-party requests from visitor browsers. Bundled mode avoids that and works better with privacy and CSP policies.', 'wp-powersuite' ); ?><br>
				<?php esc_html_e( 'If you use the Security Headers module with Content-Security-Policy, allow script-src from your site origin and cdn.jsdelivr.net when CDN mode is enabled.', 'wp-powersuite' ); ?><br>
				<?php esc_html_e( 'Defer/delay JavaScript optimizers and Cloudflare Rocket Loader can affect Alpine startup—test checkout, page builders, and LMS pages after enabling.', 'wp-powersuite' ); ?>
			</p>
		</div>

		<div class="wp-powersuite-info-box wp-powersuite-info-box--accent">
			<p>
				<strong><?php esc_html_e( 'Example markup:', 'wp-powersuite' ); ?></strong><br>
				<code>&lt;div x-data="{ open: false }"&gt;</code><br>
				<code>&nbsp;&nbsp;&lt;button @click="open = !open"&gt;Toggle&lt;/button&gt;</code><br>
				<code>&nbsp;&nbsp;&lt;div x-show="open"&gt;Content here&lt;/div&gt;</code><br>
				<code>&lt;/div&gt;</code>
			</p>
		</div>
	</form>
</div>

<style>
.wpps-alpine-setting-label { display: block; margin-bottom: 10px; }
</style>

<script type="text/javascript">
(function($) {
	function syncLoadStrategy() {
		var strategy = $('.wpps-alpine-load-strategy:checked').val() || 'defer';
		$('#<?php echo esc_js( $module_id ); ?>_defer').val(strategy === 'defer' ? '1' : '0');
		$('#<?php echo esc_js( $module_id ); ?>_async').val(strategy === 'async' ? '1' : '0');
	}

	function toggleSourceRows() {
		var source = $('#<?php echo esc_js( $module_id ); ?>_source').val();
		$('#<?php echo esc_js( $module_id ); ?>_version_row').toggle(source === 'cdn');
		$('#<?php echo esc_js( $module_id ); ?>_custom_path_row').toggle(source === 'custom');
	}

	function toggleScopeRows() {
		var frontendScope = $('#<?php echo esc_js( $module_id ); ?>_frontend_scope').val();
		$('#<?php echo esc_js( $module_id ); ?>_frontend_post_types_row').toggle(frontendScope === 'post_types');
		var adminScope = $('#<?php echo esc_attr( $module_id ); ?>_admin_scope').val();
		$('#<?php echo esc_js( $module_id ); ?>_admin_screens_row').toggle(adminScope === 'screens');
	}

	$(document).ready(function() {
		$('#<?php echo esc_js( $module_id ); ?>_source').on('change', toggleSourceRows);
		$('#<?php echo esc_js( $module_id ); ?>_frontend_scope').on('change', toggleScopeRows);
		$('#<?php echo esc_js( $module_id ); ?>_admin_scope').on('change', toggleScopeRows);
		$('.wpps-alpine-load-strategy').on('change', syncLoadStrategy);
		toggleSourceRows();
		toggleScopeRows();
		syncLoadStrategy();
	});
})(jQuery);
</script>
