<?php
/**
 * Admin — Templates library (kits, pages, sections, user).
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Admin;

use AuraBuilder\REST\RestRegistrar;
use AuraBuilder\Templates\TemplateRepository;
use AuraBuilder\Templates\TemplateTypes;

final class TemplatesPage {

	public function hooks(): void {
		add_action( 'admin_menu', array( $this, 'menu' ), 22 );
		add_action( 'admin_enqueue_scripts', array( $this, 'assets' ) );
	}

	public function menu(): void {
		add_submenu_page(
			'aura-builder-pages',
			'Templates',
			'Templates',
			'edit_pages',
			'aura-builder-templates',
			array( $this, 'render' )
		);
	}

	public function assets( string $hook ): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( empty( $_GET['page'] ) || $_GET['page'] !== 'aura-builder-templates' ) {
			return;
		}
		$css = AURA_BUILDER_PATH . 'frontend/css/templates-admin.css';
		$js  = AURA_BUILDER_PATH . 'frontend/js/templates-admin.js';
		wp_enqueue_style(
			'aura-builder-templates',
			AURA_BUILDER_URL . 'frontend/css/templates-admin.css',
			array(),
			is_file( $css ) ? (string) filemtime( $css ) : AURA_BUILDER_VERSION
		);
		wp_enqueue_script(
			'aura-builder-templates',
			AURA_BUILDER_URL . 'frontend/js/templates-admin.js',
			array(),
			is_file( $js ) ? (string) filemtime( $js ) : AURA_BUILDER_VERSION,
			true
		);
		wp_localize_script(
			'aura-builder-templates',
			'AuraBuilderTemplates',
			array(
				'restUrl'    => esc_url_raw( rest_url( RestRegistrar::NS ) ),
				'nonce'      => wp_create_nonce( 'wp_rest' ),
				'admin'      => admin_url( 'admin.php' ),
				'pluginLogo' => defined( 'AURA_BUILDER_LOGO_64_URL' ) ? AURA_BUILDER_LOGO_64_URL : '',
			)
		);
	}

	public function render(): void {
		if ( ! current_user_can( 'edit_pages' ) ) {
			wp_die( esc_html__( 'Sem permissão.', 'auranet-page-theme-builder' ) );
		}
		$repo  = new TemplateRepository();
		$all   = $repo->list( array() );
		$counts = array(
			'kit'       => 0,
			'page'      => 0,
			'component' => 0,
			'header'    => 0,
			'footer'    => 0,
			'user'      => 0,
		);
		foreach ( $all as $t ) {
			$type = (string) ( $t['type'] ?? '' );
			if ( isset( $counts[ $type ] ) ) {
				++$counts[ $type ];
			}
			if ( ( $t['source'] ?? '' ) === TemplateTypes::SOURCE_USER ) {
				++$counts['user'];
			}
		}
		$logo = defined( 'AURA_BUILDER_LOGO_64_URL' ) ? AURA_BUILDER_LOGO_64_URL : '';
		?>
		<div class="wrap ab-tpl-wrap">
			<h1 class="wp-heading-inline" style="display:inline-flex;align-items:center;gap:8px">
				<?php if ( $logo ) : ?>
					<img src="<?php echo esc_url( $logo ); ?>" alt="" width="28" height="28" style="width:28px;height:28px;object-fit:contain;border-radius:6px"/>
				<?php else : ?>
					<span class="dashicons dashicons-layout" style="font-size:28px;width:28px;height:28px;margin-right:6px"></span>
				<?php endif; ?>
				Templates &amp; Kits
			</h1>
			<hr class="wp-header-end"/>

			<p class="ab-tpl-intro">
				Biblioteca de <strong>seções</strong>, <strong>páginas</strong>, <strong>headers/footers</strong> e
				<strong>Site Kits</strong>. Use o assistente para criar um site, troque o design system sem apagar conteúdo,
				ou importe kits parciais. Tudo permanece 100% editável.
			</p>

			<div class="ab-tpl-hero-actions">
				<button type="button" class="button button-primary button-hero" id="ab-tpl-open-wizard">
					✦ Criar meu site (assistente)
				</button>
				<a class="button button-hero" href="<?php echo esc_url( admin_url( 'admin.php?page=aura-builder&mode=single' ) ); ?>">
					Editar Single Post
				</a>
			</div>

			<div class="ab-tpl-toolbar">
				<nav class="ab-tpl-tabs" role="tablist">
					<button type="button" class="ab-tpl-tab is-active" data-tab="kit">Kits <span><?php echo (int) $counts['kit']; ?></span></button>
					<button type="button" class="ab-tpl-tab" data-tab="page">Páginas <span><?php echo (int) $counts['page']; ?></span></button>
					<button type="button" class="ab-tpl-tab" data-tab="component">Seções <span><?php echo (int) $counts['component']; ?></span></button>
					<button type="button" class="ab-tpl-tab" data-tab="header">Headers <span><?php echo (int) $counts['header']; ?></span></button>
					<button type="button" class="ab-tpl-tab" data-tab="footer">Footers <span><?php echo (int) $counts['footer']; ?></span></button>
					<button type="button" class="ab-tpl-tab" data-tab="design">Design Systems</button>
					<button type="button" class="ab-tpl-tab" data-tab="favorites">★ Favoritos</button>
					<button type="button" class="ab-tpl-tab" data-tab="user">Meus templates <span><?php echo (int) $counts['user']; ?></span></button>
				</nav>
				<div class="ab-tpl-filters">
					<input type="search" id="ab-tpl-search" class="ab-tpl-search" placeholder="Buscar modelo…"/>
					<select id="ab-tpl-category" class="ab-tpl-select">
						<option value="">Todas categorias</option>
						<option value="education">Educação</option>
						<option value="business">Empresa</option>
						<option value="blog">Blog</option>
						<option value="news">Notícias</option>
						<option value="landing">Landing</option>
						<option value="restaurant">Restaurante</option>
						<option value="portfolio">Portfólio</option>
						<option value="realestate">Imobiliária</option>
						<option value="general">Geral</option>
						<option value="custom">Personalizado</option>
					</select>
				</div>
			</div>

			<div id="ab-tpl-grid" class="ab-tpl-grid" aria-live="polite">
				<p class="ab-tpl-loading">Carregando biblioteca…</p>
			</div>
		</div>

		<div id="ab-tpl-modal" class="ab-tpl-modal" hidden>
			<div class="ab-tpl-modal__panel" role="dialog" aria-modal="true" aria-labelledby="ab-tpl-modal-title">
				<button type="button" class="ab-tpl-modal__close" id="ab-tpl-modal-close" aria-label="Fechar">&times;</button>
				<h2 id="ab-tpl-modal-title">Importar Site Kit</h2>
				<p class="ab-tpl-modal__desc" id="ab-tpl-modal-desc"></p>
				<div id="ab-tpl-modal-body" class="ab-tpl-modal__body"></div>
				<div class="ab-tpl-modal__actions">
					<button type="button" class="button" id="ab-tpl-modal-cancel">Cancelar</button>
					<button type="button" class="button button-primary" id="ab-tpl-modal-confirm">Importar</button>
				</div>
				<p class="ab-tpl-modal__status" id="ab-tpl-modal-status" hidden></p>
			</div>
		</div>

		<div id="ab-tpl-wizard" class="ab-tpl-modal" hidden>
			<div class="ab-tpl-modal__panel ab-tpl-modal__panel--wide" role="dialog" aria-modal="true" aria-labelledby="ab-tpl-wizard-title">
				<button type="button" class="ab-tpl-modal__close" id="ab-tpl-wizard-close" aria-label="Fechar">&times;</button>
				<h2 id="ab-tpl-wizard-title">Criar meu site</h2>
				<p class="ab-tpl-modal__desc">Escolha o tipo, o estilo e o kit. O assistente importa páginas, header, footer e (se houver) single dinâmico.</p>
				<div class="ab-tpl-wizard-steps">
					<label class="ab-tpl-wizard-field">1. Tipo de site
						<select id="ab-wiz-category">
							<option value="business">Empresa</option>
							<option value="education">Escola / Educação</option>
							<option value="blog">Blog</option>
							<option value="news">Notícias / Portal</option>
							<option value="landing">Landing Page</option>
							<option value="restaurant">Restaurante</option>
							<option value="portfolio">Portfólio</option>
							<option value="realestate">Imobiliária</option>
						</select>
					</label>
					<label class="ab-tpl-wizard-field">2. Estilo (Design System)
						<select id="ab-wiz-design">
							<option value="">Padrão do kit</option>
							<option value="modern-purple">Modern Purple</option>
							<option value="corporate-blue">Corporate Blue</option>
							<option value="modern-dark">Modern Dark</option>
							<option value="elegant-green">Elegant Green</option>
							<option value="news-red">News Red</option>
							<option value="warm-terracotta">Warm Terracotta (restaurante)</option>
							<option value="indigo-portfolio">Indigo Portfolio</option>
							<option value="emerald-estate">Emerald Estate (imóveis)</option>
						</select>
					</label>
					<label class="ab-tpl-wizard-field">3. Nome do site (opcional)
						<input type="text" id="ab-wiz-name" placeholder="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>"/>
					</label>
					<label class="ab-tpl-wizard-check"><input type="checkbox" id="ab-wiz-home" checked/> Definir Home do kit como página inicial</label>
					<label class="ab-tpl-wizard-check"><input type="checkbox" id="ab-wiz-globals" checked/> Aplicar cores e tipografia</label>
				</div>
				<div class="ab-tpl-modal__actions">
					<button type="button" class="button" id="ab-tpl-wizard-cancel">Cancelar</button>
					<button type="button" class="button button-primary" id="ab-tpl-wizard-run">Criar meu site</button>
				</div>
				<p class="ab-tpl-modal__status" id="ab-tpl-wizard-status" hidden></p>
			</div>
		</div>
		<?php
	}
}
