<?php

use GutenbergBlockControl\Module;
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 ?? 'gutenberg-block-control' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Gutenberg Block Control requires an active license. Activate your license to hide or restrict blocks in the editor.', '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 ( ! current_user_can( 'manage_options' ) ) {
	return;
}

if ( ! isset( $module_id ) ) {
	$module_id = 'gutenberg-block-control';
}

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

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

$cache_key          = Module::getBlocksCacheKey();
$cached_blocks      = get_transient( $cache_key );
$blocks_by_category = is_array( $cached_blocks ) ? $cached_blocks : [];

if ( $blocks_by_category === [] ) {
	$blocks_by_category = Module::buildAndCacheBlocks( $cache_key );
}

$show_setup_notice = empty( $blocks_by_category );

?>
<div class="wp-powersuite-module-settings">
	<div class="wpps-block-control-header">
		<div class="wpps-block-control-info">
			<p class="description">
				<?php esc_html_e( 'Check blocks to hide them from the block inserter. Disabled blocks will not appear when editing posts or pages.', 'wp-powersuite' ); ?>
			</p>
			<p class="description">
				<strong><?php esc_html_e( 'Tip:', 'wp-powersuite' ); ?></strong>
				<?php esc_html_e( 'Disable "Buttons" to remove the button container block, and "Button" to remove individual buttons. If plugin blocks are missing, open the block editor once, then click Refresh Block List.', 'wp-powersuite' ); ?>
			</p>
		</div>
	</div>

	<?php if ( $show_setup_notice ) : ?>
		<div class="wpps-block-control-setup-notice notice notice-info inline">
			<p><strong><?php esc_html_e( 'First-time setup:', 'wp-powersuite' ); ?></strong></p>
			<ol>
				<li><?php esc_html_e( 'Open any post or page in the block editor.', 'wp-powersuite' ); ?></li>
				<li><?php esc_html_e( 'Return here and click "Refresh Block List".', 'wp-powersuite' ); ?></li>
			</ol>
		</div>
	<?php endif; ?>

	<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' ); ?>

		<div class="wpps-block-control-search-row">
			<div class="wpps-block-control-search">
				<input
					type="search"
					id="wpps-block-search"
					placeholder="<?php esc_attr_e( 'Search blocks...', 'wp-powersuite' ); ?>"
					class="regular-text"
				/>
			</div>
			<div class="wpps-block-control-actions">
				<button type="button" id="wpps-refresh-blocks" class="button">
					<?php esc_html_e( 'Refresh Block List', 'wp-powersuite' ); ?>
				</button>
			</div>
		</div>

		<div class="wpps-block-control-list">
			<?php echo Module::renderBlockListHtml( $blocks_by_category, $disabled_blocks ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped in renderer ?>
		</div>
	</form>
</div>

<style>
.wpps-block-control-header {
	margin-bottom: 20px;
}

.wpps-block-control-setup-notice {
	margin: 0 0 20px;
	padding: 12px 15px;
}

.wpps-block-control-setup-notice ol {
	margin: 8px 0 0 20px;
}

.wpps-block-control-search-row {
	display: flex;
	align-items: center;
	gap: 15px;
	margin-bottom: 20px;
}

.wpps-block-control-search {
	flex: 1;
	max-width: 400px;
}

.wpps-block-control-search input {
	width: 100%;
}

.wpps-block-control-actions {
	flex-shrink: 0;
}

.wpps-block-control-list {
	border: 1px solid #ddd;
	padding: 15px;
	background: #fff;
}

.wpps-block-category {
	margin-bottom: 30px;
}

.wpps-block-category:last-child {
	margin-bottom: 0;
}

.wpps-block-category-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	flex-wrap: wrap;
	gap: 8px;
	margin-bottom: 15px;
	padding-bottom: 10px;
	border-bottom: 2px solid #ddd;
}

.wpps-block-category-title {
	margin: 0;
	font-size: 16px;
	font-weight: 600;
}

.wpps-block-category-actions {
	font-size: 13px;
}

.wpps-block-category-action-sep {
	color: #ccc;
	margin: 0 4px;
}

.wpps-block-category-blocks {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
	gap: 10px;
}

.wpps-block-item {
	display: flex;
	align-items: flex-start;
	padding: 10px;
	border: 1px solid #ddd;
	border-radius: 4px;
	cursor: pointer;
	transition: background-color 0.2s;
}

.wpps-block-item:hover {
	background-color: #f5f5f5;
}

.wpps-block-item:has(input:checked) {
	background-color: #fff5f5;
	border-color: #d63638;
}

.wpps-block-item .wpps-block-disabled-icon {
	display: none;
}

.wpps-block-item:has(input:checked) .wpps-block-disabled-icon {
	display: inline;
}

.wpps-block-item input[type="checkbox"] {
	margin-right: 10px;
	margin-top: 2px;
	flex-shrink: 0;
}

.wpps-block-title {
	font-weight: 500;
	flex: 1;
	display: flex;
	align-items: center;
	gap: 8px;
}

.wpps-block-disabled-icon {
	color: #d63638;
	font-weight: bold;
	font-size: 14px;
}

.wpps-block-control-empty {
	text-align: center;
	padding: 40px 20px;
	color: #666;
}

.wpps-block-category[style*="display: none"] {
	display: none !important;
}
</style>

<script>
(function() {
	var moduleId = <?php echo wp_json_encode( $module_id ); ?>;
	var i18n = {
		refreshing: <?php echo wp_json_encode( __( 'Refreshing...', 'wp-powersuite' ) ); ?>,
		refreshFailed: <?php echo wp_json_encode( __( 'Failed to refresh blocks. Please try again.', 'wp-powersuite' ) ); ?>,
		refreshError: <?php echo wp_json_encode( __( 'An error occurred while refreshing blocks.', 'wp-powersuite' ) ); ?>
	};

	function initCategoryActions(root) {
		root.querySelectorAll('.wpps-block-category-action').forEach(function(btn) {
			btn.addEventListener('click', function(e) {
				e.preventDefault();
				var category = btn.closest('.wpps-block-category');
				if (!category) {
					return;
				}
				var checkboxes = category.querySelectorAll('.wpps-block-category-blocks input[type="checkbox"]');
				var disableAll = btn.dataset.action === 'disable-all';
				checkboxes.forEach(function(cb) {
					cb.checked = disableAll;
				});
			});
		});
	}

	function initSearch(root) {
		var searchInput = root.querySelector('#wpps-block-search');
		if (!searchInput) {
			return;
		}

		searchInput.addEventListener('input', function(e) {
			var searchTerm = e.target.value.toLowerCase().trim();
			root.querySelectorAll('.wpps-block-category').forEach(function(category) {
				var hasVisibleBlocks = false;
				category.querySelectorAll('.wpps-block-item').forEach(function(block) {
					var blockName = (block.dataset.blockName || '').toLowerCase();
					var blockTitle = (block.dataset.blockTitle || '').toLowerCase();
					var blockDescription = (block.getAttribute('title') || '').toLowerCase();
					var matches = searchTerm === '' ||
						blockName.includes(searchTerm) ||
						blockTitle.includes(searchTerm) ||
						blockDescription.includes(searchTerm);
					block.style.display = matches ? '' : 'none';
					if (matches) {
						hasVisibleBlocks = true;
					}
				});
				category.style.display = hasVisibleBlocks ? '' : 'none';
			});
		});
	}

	function initRefreshButton(root) {
		var refreshBtn = root.querySelector('#wpps-refresh-blocks');
		var blockList = root.querySelector('.wpps-block-control-list');
		if (!refreshBtn || !blockList) {
			return;
		}

		refreshBtn.addEventListener('click', function(e) {
			e.preventDefault();
			var originalText = refreshBtn.textContent;
			var searchValue = root.querySelector('#wpps-block-search')?.value || '';
			refreshBtn.disabled = true;
			refreshBtn.textContent = i18n.refreshing;

			var formData = new FormData();
			formData.append('action', 'wp_powersuite_refresh_gutenberg_blocks');
			formData.append('module_id', moduleId);
			formData.append('nonce', window.wpPowerSuite?.nonce || '');

			fetch(window.wpPowerSuite?.ajaxUrl || ajaxurl, {
				method: 'POST',
				body: formData
			})
			.then(function(response) { return response.json(); })
			.then(function(data) {
				refreshBtn.disabled = false;
				refreshBtn.textContent = originalText;

				if (data.success && data.data && data.data.html) {
					blockList.innerHTML = data.data.html;
					initCategoryActions(root);
					var searchInput = root.querySelector('#wpps-block-search');
					if (searchInput) {
						searchInput.value = searchValue;
						searchInput.dispatchEvent(new Event('input', { bubbles: true }));
					}
					var setupNotice = root.querySelector('.wpps-block-control-setup-notice');
					if (setupNotice && data.data.has_blocks) {
						setupNotice.remove();
					}
				} else {
					alert(i18n.refreshFailed);
				}
			})
			.catch(function(error) {
				refreshBtn.disabled = false;
				refreshBtn.textContent = originalText;
				console.error('WP PowerSuite: Refresh blocks error', error);
				alert(i18n.refreshError);
			});
		});
	}

	function initBlockControl(root) {
		if (!root || root.dataset.wppsBlockControlInit === '1') {
			return;
		}
		root.dataset.wppsBlockControlInit = '1';
		initSearch(root);
		initCategoryActions(root);
		initRefreshButton(root);
	}

	function boot() {
		document.querySelectorAll('.wp-powersuite-module-settings').forEach(function(root) {
			if (root.querySelector('.wpps-block-control-list')) {
				initBlockControl(root);
			}
		});
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', boot);
	} else {
		boot();
	}
})();
</script>
