<?php
/**
 * Basic Forms - Template picker (Create Form)
 *
 * @package BasicForms
 */

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

use WP_PowerSuite\Admin\PageHero;

$list_url   = admin_url( 'admin.php?page=powersuite-basic-forms' );
$blank_url  = admin_url( 'admin.php?page=powersuite-basic-forms&action=add&blank=1' );
$categories = \BasicForms\FormTemplates::getCategories();
$grouped    = \BasicForms\FormTemplates::getGroupedByCategory();
$total      = count( \BasicForms\FormTemplates::getAll() );
$error      = isset( $_GET['template_error'] ) ? sanitize_key( wp_unslash( $_GET['template_error'] ) ) : '';

$active_categories = [];
foreach ( $categories as $cat_slug => $cat_meta ) {
	if ( ! empty( $grouped[ $cat_slug ] ) ) {
		$active_categories[ $cat_slug ] = $cat_meta;
	}
}
$first_cat = array_key_first( $active_categories );
?>
<div class="wrap wpps-bf-wrap wpps-bf-template-picker">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">

	<?php if ( $error === 'invalid' ) : ?>
		<div class="notice notice-error"><p><?php esc_html_e( 'That template could not be found. Choose another template or start with a blank form.', 'wp-powersuite' ); ?></p></div>
	<?php elseif ( $error === 'failed' ) : ?>
		<div class="notice notice-error"><p><?php esc_html_e( 'Could not create the form from that template. Please try again.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>

	<?php
	PageHero::render_for_module(
		[
			'icon'    => 'dashicons-feedback',
			'title'   => __( 'Create Form', 'wp-powersuite' ),
			'tagline' => sprintf(
				/* translators: %d: number of ready-made templates */
				__( 'Pick a template (%d ready-made) or start from scratch.', 'wp-powersuite' ),
				$total
			),
			'actions' => [
				[
					'label' => __( 'All Forms', 'wp-powersuite' ),
					'url'   => $list_url,
					'icon'  => 'dashicons-arrow-left-alt',
				],
			],
		]
	);
	?>

	<?php $ai_enabled = \BasicForms\FeatureGate::aiFormBuilderEnabled(); ?>
	<?php $ai_is_pro = \BasicForms\FeatureGate::isPro(); ?>
	<?php if ( $ai_enabled ) : ?>
	<div class="wpps-bf-ai-builder-promo">
		<div class="wpps-bf-ai-builder-promo__content">
			<span class="wpps-bf-ai-builder-promo__icon wpps-bf-ai-icon wpps-bf-ai-icon--lg" aria-hidden="true">
				<svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" focusable="false" role="img">
					<path d="M9.813 2.5 11 6.082l3.582 1.187L11 8.418 9.813 12 8.418 8.418 4.835 7.269l3.583-1.187L9.813 2.5Zm7.687 8.5.875 2.625L21 14.5l-2.625.875L17.5 18l-.875-2.625L14 14.5l2.625-.875L17.5 11ZM7 14l.55 1.65L9.2 16.2l-1.65.55L7 18.4l-.55-1.65L4.8 16.2l1.65-.55L7 14Z"/>
				</svg>
			</span>
			<div>
				<h2 class="wpps-bf-ai-builder-promo__title"><?php esc_html_e( 'AI Form Builder', 'wp-powersuite' ); ?></h2>
				<p class="wpps-bf-ai-builder-promo__desc"><?php esc_html_e( 'Describe your form in plain language and let AI draft the fields for you.', 'wp-powersuite' ); ?></p>
			</div>
		</div>
		<button type="button" class="button button-primary wpps-bf-open-ai-builder wpps-bf-ai-btn" id="wpps-bf-open-ai-builder-promo">
			<?php include __DIR__ . '/partials/ai-icon.php'; ?>
			<?php esc_html_e( 'Generate with AI', 'wp-powersuite' ); ?>
		</button>
	</div>
	<?php elseif ( ! $ai_is_pro ) : ?>
	<div class="wpps-bf-ai-builder-promo wpps-bf-ai-builder-promo--locked">
		<div class="wpps-bf-ai-builder-promo__content">
			<span class="wpps-bf-ai-builder-promo__icon wpps-bf-ai-icon wpps-bf-ai-icon--lg" aria-hidden="true">
				<svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" focusable="false" role="img">
					<path d="M9.813 2.5 11 6.082l3.582 1.187L11 8.418 9.813 12 8.418 8.418 4.835 7.269l3.583-1.187L9.813 2.5Zm7.687 8.5.875 2.625L21 14.5l-2.625.875L17.5 18l-.875-2.625L14 14.5l2.625-.875L17.5 11ZM7 14l.55 1.65L9.2 16.2l-1.65.55L7 18.4l-.55-1.65L4.8 16.2l1.65-.55L7 14Z"/>
				</svg>
			</span>
			<div>
				<h2 class="wpps-bf-ai-builder-promo__title">
					<?php esc_html_e( 'AI Form Builder', 'wp-powersuite' ); ?>
					<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
				</h2>
				<p class="wpps-bf-ai-builder-promo__desc"><?php esc_html_e( 'Generate and edit forms with AI. Manual templates and the form builder remain free.', 'wp-powersuite' ); ?></p>
			</div>
		</div>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-license' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
	</div>
	<?php endif; ?>

	<?php if ( [] === $active_categories ) : ?>
		<p class="wpps-bf-muted"><?php esc_html_e( 'No templates are available.', 'wp-powersuite' ); ?></p>
		<p><a href="<?php echo esc_url( $blank_url ); ?>" class="button button-primary"><?php esc_html_e( 'Start from scratch', 'wp-powersuite' ); ?></a></p>
	<?php else : ?>
		<div class="wpps-bf-template-tabs">
			<div class="wpps-bf-template-tabs__nav" role="tablist" aria-label="<?php esc_attr_e( 'Form template categories', 'wp-powersuite' ); ?>">
				<?php foreach ( $active_categories as $cat_slug => $cat_meta ) : ?>
					<button
						type="button"
						class="wpps-bf-template-tab<?php echo $cat_slug === $first_cat ? ' is-active' : ''; ?>"
						role="tab"
						id="wpps-bf-template-tab-<?php echo esc_attr( $cat_slug ); ?>"
						aria-selected="<?php echo $cat_slug === $first_cat ? 'true' : 'false'; ?>"
						aria-controls="wpps-bf-template-panel-<?php echo esc_attr( $cat_slug ); ?>"
						data-wpps-bf-template-tab="<?php echo esc_attr( $cat_slug ); ?>"
					>
						<span class="dashicons <?php echo esc_attr( (string) $cat_meta['icon'] ); ?>" aria-hidden="true"></span>
						<?php echo esc_html( (string) $cat_meta['label'] ); ?>
					</button>
				<?php endforeach; ?>
			</div>

			<?php foreach ( $active_categories as $cat_slug => $cat_meta ) : ?>
				<?php $templates = $grouped[ $cat_slug ] ?? []; ?>
				<section
					class="wpps-bf-template-panel<?php echo $cat_slug === $first_cat ? ' is-active' : ''; ?>"
					role="tabpanel"
					id="wpps-bf-template-panel-<?php echo esc_attr( $cat_slug ); ?>"
					aria-labelledby="wpps-bf-template-tab-<?php echo esc_attr( $cat_slug ); ?>"
					<?php echo $cat_slug !== $first_cat ? ' hidden' : ''; ?>
				>
					<p class="wpps-bf-template-panel__desc"><?php echo esc_html( (string) $cat_meta['description'] ); ?></p>
					<div class="wpps-bf-template-grid">
						<a class="wpps-bf-template-card wpps-bf-template-card--blank" href="<?php echo esc_url( $blank_url ); ?>">
							<span class="wpps-bf-template-card__icon dashicons dashicons-plus-alt2" aria-hidden="true"></span>
							<span class="wpps-bf-template-card__body">
								<span class="wpps-bf-template-card__title"><?php esc_html_e( 'Start from scratch', 'wp-powersuite' ); ?></span>
								<span class="wpps-bf-template-card__desc"><?php esc_html_e( 'Build a custom form with the field builder.', 'wp-powersuite' ); ?></span>
							</span>
							<span class="wpps-bf-template-card__action"><?php esc_html_e( 'Blank form', 'wp-powersuite' ); ?></span>
						</a>

						<?php foreach ( $templates as $template ) : ?>
							<?php
							$template_id = isset( $template['id'] ) ? sanitize_key( (string) $template['id'] ) : '';
							if ( $template_id === '' ) {
								continue;
							}
							$use_url = wp_nonce_url(
								add_query_arg(
									[
										'page'     => 'powersuite-basic-forms',
										'action'   => 'add',
										'template' => $template_id,
									],
									admin_url( 'admin.php' )
								),
								'wpps_bf_use_template_' . $template_id
							);
							$field_count = isset( $template['fields'] ) && is_array( $template['fields'] ) ? count( $template['fields'] ) : 0;
							$icon        = isset( $template['icon'] ) ? (string) $template['icon'] : 'dashicons-feedback';
							?>
							<a class="wpps-bf-template-card" href="<?php echo esc_url( $use_url ); ?>">
								<span class="wpps-bf-template-card__icon dashicons <?php echo esc_attr( $icon ); ?>" aria-hidden="true"></span>
								<span class="wpps-bf-template-card__body">
									<span class="wpps-bf-template-card__title"><?php echo esc_html( (string) ( $template['name'] ?? '' ) ); ?></span>
									<span class="wpps-bf-template-card__desc"><?php echo esc_html( (string) ( $template['description'] ?? '' ) ); ?></span>
									<span class="wpps-bf-template-card__meta">
										<?php
										echo esc_html(
											sprintf(
												/* translators: %d: number of fields */
												_n( '%d field', '%d fields', $field_count, 'wp-powersuite' ),
												$field_count
											)
										);
										?>
									</span>
								</span>
								<span class="wpps-bf-template-card__action"><?php esc_html_e( 'Use template', 'wp-powersuite' ); ?></span>
							</a>
						<?php endforeach; ?>
					</div>
				</section>
			<?php endforeach; ?>
		</div>
	<?php endif; ?>
</div>
	<?php
	if ( $ai_enabled ) {
		$ai_mode = 'create';
		include __DIR__ . '/partials/ai-form-builder-modal.php';
	}
	?>
<script>
(function () {
	var root = document.querySelector('.wpps-bf-template-tabs');
	if (!root) {
		return;
	}
	var tabs = root.querySelectorAll('[data-wpps-bf-template-tab]');
	var panels = root.querySelectorAll('.wpps-bf-template-panel');
	function activate(slug) {
		tabs.forEach(function (tab) {
			var on = tab.getAttribute('data-wpps-bf-template-tab') === slug;
			tab.classList.toggle('is-active', on);
			tab.setAttribute('aria-selected', on ? 'true' : 'false');
		});
		panels.forEach(function (panel) {
			var on = panel.id === 'wpps-bf-template-panel-' + slug;
			panel.classList.toggle('is-active', on);
			panel.hidden = !on;
		});
	}
	tabs.forEach(function (tab) {
		tab.addEventListener('click', function () {
			activate(tab.getAttribute('data-wpps-bf-template-tab'));
		});
	});
})();
</script>
