<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine — PRO Pack Templates
 *
 * Enterprise pack management:
 *   - Pack activation via pack key (AJAX, no reload)
 *   - All owned packs grid with per-pack rule counts, active rules, performance
 *   - AI Pack Recommender panel (natural language goal → best packs)
 *   - Per-pack accordion: full rule breakdown, validation status, import history
 *   - Re-import with server verification (AJAX)
 *   - Pack deletion with cascade (rules removed)
 *   - Search/filter owned packs
 *   - Pack statistics: total rules, active rules, revenue influenced
 *   - Pack security guidance
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

global $wpdb;

$is_pro   = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$nonce    = wp_create_nonce( 'gtbogo_templates' );
$dl_nonce = wp_create_nonce( 'gtbogo_download_pack' );

/* ── Delete pack ─────────────────────────────────────────────────────────── */
$delete_notice = '';
if ( isset( $_GET['gtbogo_delete_pack'] )
	&& check_admin_referer( 'gtbogo_delete_pack_' . sanitize_text_field( $_GET['gtbogo_delete_pack'] ) ) ) {
	$del_id = sanitize_text_field( $_GET['gtbogo_delete_pack'] );
    $wpdb->delete( $wpdb->prefix . 'gtbogo_owned_packs', [ 'pack_id' => $del_id ], [ '%s' ] ); // phpcs:ignore
    $wpdb->delete( $wpdb->prefix . 'gtbogo_rules', [ 'pack_source' => $del_id ], [ '%s' ] ); // phpcs:ignore
	$owned_opt = array_values( array_filter( (array) get_option( 'gtbogo_owned_packs', array() ), fn( $p ) => $p !== $del_id ) );
	update_option( 'gtbogo_owned_packs', $owned_opt );
	delete_transient( 'gtbogo_active_rules' );
	$delete_notice = 'Pack removed. All associated rules deleted.';
}

/* ── Load owned packs from DB ────────────────────────────────────────────── */
$owned_tbl   = $wpdb->prefix . 'gtbogo_owned_packs';
$has_owned   = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $owned_tbl ) ); // phpcs:ignore
$owned_packs = array();
if ( $has_owned ) {
    $rows = $wpdb->get_results( "SELECT * FROM {$owned_tbl} ORDER BY imported DESC" ); // phpcs:ignore
	foreach ( $rows as $row ) {
		$owned_packs[ $row->pack_id ] = (array) $row;
	}
}

/* ── Per-pack stats: rule count + active rules + revenue ─────────────────── */
$rules_tbl    = $wpdb->prefix . 'gtbogo_rules';
$outcomes_tbl = $wpdb->prefix . 'gtbogo_outcomes';
$has_rules    = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $rules_tbl ) ); // phpcs:ignore
$has_outcomes = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $outcomes_tbl ) ); // phpcs:ignore

$pack_stats = array();
foreach ( $owned_packs as $pack_id => $pack ) {
	$name_like = '%' . $wpdb->esc_like( $pack['pack_name'] ?? $pack_id ) . '%';
	$stats     = array(
		'total_rules'  => 0,
		'active_rules' => 0,
		'revenue'      => 0.0,
	);
	if ( $has_rules ) {
        $stats['total_rules']  = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$rules_tbl} WHERE pack_source LIKE %s", $name_like ) ); // phpcs:ignore
        $stats['active_rules'] = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$rules_tbl} WHERE pack_source LIKE %s AND status='active'", $name_like ) ); // phpcs:ignore
	}
	if ( $has_outcomes ) {
        $stats['revenue'] = (float) $wpdb->get_var( // phpcs:ignore
			$wpdb->prepare( "SELECT SUM(deal_value) FROM {$outcomes_tbl} WHERE event_type='deal_accepted' AND rule_id IN (SELECT id FROM {$rules_tbl} WHERE pack_source LIKE %s)", $name_like )
		);
	}
	$pack_stats[ $pack_id ] = $stats;
}

/* ── Global stats ────────────────────────────────────────────────────────── */
$total_packs      = count( $owned_packs );
$total_pack_rules = array_sum( array_column( $pack_stats, 'total_rules' ) );
$total_active     = array_sum( array_column( $pack_stats, 'active_rules' ) );
$total_revenue    = array_sum( array_column( $pack_stats, 'revenue' ) );

/* ── AI Recommender available? ───────────────────────────────────────────── */
$has_ai       = class_exists( 'GT_BOGO_AI_Engine' ) && ! empty( GT_BOGO_AI_Engine::get_api_key() );
$ai_rate_used = (int) get_transient( 'gtbogo_ai_rate_count' ) ?: 0;

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	PAGE HEADER
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-page-header gt-animate-in" style="align-items:flex-start">
	<div>
		<h1 class="gt-page-title">📦 PRO Pack Templates</h1>
		<p class="gt-page-subtitle">
			Your purchased PRO packs — expert-built rule strategies ready to import.
			Re-import any time with server verification.
		</p>
	</div>
	<div style="display:flex;gap:10px;flex-wrap:wrap">
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>"
			class="gt-btn gt-btn-ghost gt-btn-sm">Browse All Packs →</a>
	</div>
</div>

<?php if ( $delete_notice ) : ?>
<div class="gt-notice gt-notice-success gt-animate-in">✓ <?php echo esc_html( $delete_notice ); ?></div>
<?php endif; ?>

<?php if ( ! $is_pro ) : ?>
<div class="gt-pro-gate gt-animate-in">
	<span class="gt-pro-gate-icon">📦</span>
	<h2>PRO License Required</h2>
	<p>Purchase GT BOGO Engine PRO to access pack templates — 200 expert-built rule strategies across 19 industries.</p>
	<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">
		Purchase PRO — $499/yr
	</a>
</div>
<?php else : ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	KPI ROW
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:repeat(5,1fr);gap:14px;margin-bottom:20px">
	<?php
	$kpis = array(
		array( 'Owned Packs', (string) $total_packs, '#f59e0b', 'purchased & activated' ),
		array( 'Pack Rules', number_format( $total_pack_rules ), '#3b82f6', 'imported from packs' ),
		array( 'Active Rules', number_format( $total_active ), '#22c55e', 'currently firing' ),
		array( 'Revenue', '$' . number_format( $total_revenue, 0 ), '#22c55e', 'attributed to pack rules' ),
		array( 'Available', '200', 'var(--gt-subtle)', 'across 19 industries' ),
	);
	foreach ( $kpis as $k ) :
		?>
	<div class="gt-card" style="padding:16px 18px;text-align:center">
		<div style="font-size:24px;font-weight:900;color:<?php echo esc_attr( $k[2] ); ?>;margin-bottom:4px;line-height:1">
			<?php echo esc_html( $k[1] ); ?>
		</div>
		<div style="font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">
			<?php echo esc_html( $k[0] ); ?>
		</div>
		<div style="font-size:10px;color:rgba(100,116,139,0.6);margin-top:2px"><?php echo esc_html( $k[3] ); ?></div>
	</div>
	<?php endforeach; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	ACTIVATE A PACK KEY
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🔑 Activate a Pack Key</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">Enter the PACK-XXXX key from your purchase email</span>
	</div>
	<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end">
		<div class="gt-form-group" style="margin:0;flex:1;min-width:240px">
			<label class="gt-form-label" for="gt-tp-pack-key">Pack Key</label>
			<input type="text" id="gt-tp-pack-key" class="gt-input"
					placeholder="PACK-XXXXXXXXXXXXXXXXXXXX"
					style="font-family:'DM Mono','Courier New',monospace;letter-spacing:1px">
		</div>
		<button type="button" class="gt-btn gt-btn-primary"
			onclick="gtTpActivatePack('<?php echo esc_js( $nonce ); ?>')">
			⚡ Activate Pack
		</button>
	</div>
	<div id="gt-tp-activate-result" style="display:none;margin-top:12px"></div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	AI PACK RECOMMENDER
════════════════════════════════════════════════════════════════════════════ -->
	<?php if ( $has_ai ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(245,158,11,0.2)">
	<div class="gt-card-header">
		<h2 class="gt-card-title">✦ AI Pack Recommender</h2>
		<div style="display:flex;align-items:center;gap:8px">
			<span style="font-size:11px;color:var(--gt-subtle)"><?php echo esc_html( $ai_rate_used ); ?>/100 daily calls used</span>
		</div>
	</div>
	<div style="margin-bottom:12px;font-size:12px;color:var(--gt-subtle);line-height:1.5">
		Describe your promotional goal in plain English — the AI matches it against 200 PRO packs
		and recommends the best ones for your store's specific situation.
	</div>
	<div style="display:flex;gap:10px;flex-wrap:wrap">
		<textarea id="gt-tp-ai-goal" rows="2" class="gt-input" style="flex:1;min-width:280px;resize:none"
					placeholder="e.g. I sell premium streetwear and want to increase average order value for returning customers…"></textarea>
		<button type="button" class="gt-btn gt-btn-primary"
			onclick="gtTpAiRecommend('<?php echo esc_js( $nonce ); ?>')"
			id="gt-tp-ai-btn" style="align-self:flex-start;flex-shrink:0;background:#f59e0b;border-color:#f59e0b">
			✦ Find Best Packs
		</button>
	</div>
	<div id="gt-tp-ai-results" style="display:none;margin-top:16px"></div>
</div>
	<?php else : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(245,158,11,0.1)">
	<div style="display:flex;align-items:center;gap:16px">
		<span style="font-size:32px">✦</span>
		<div>
			<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:3px">
				AI Pack Recommender — API Key Required
			</div>
			<div style="font-size:12px;color:var(--gt-subtle)">
				Add your Anthropic API key in the AI Intelligence tab to enable natural language pack recommendations.
			</div>
		</div>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=ai-settings' ) ); ?>"
			class="gt-btn gt-btn-ghost gt-btn-sm" style="flex-shrink:0">
			Set Up AI →
		</a>
	</div>
</div>
	<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	MY PACKS GRID
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header" style="flex-wrap:wrap;gap:12px">
		<h2 class="gt-card-title">
			🔐 My Packs
			<span style="font-size:13px;font-weight:400;color:var(--gt-subtle);margin-left:8px">
				<?php echo esc_html( (string) $total_packs ); ?> activated
			</span>
		</h2>
		<!-- Search -->
		<?php if ( $total_packs > 3 ) : ?>
		<input type="text" id="gt-tp-search" class="gt-input" placeholder="Search packs…"
				oninput="gtTpFilter()"
				style="width:220px;height:36px;font-size:12px">
		<?php endif; ?>
	</div>

	<?php if ( empty( $owned_packs ) ) : ?>
	<div style="padding:48px 24px;text-align:center">
		<div style="font-size:44px;margin-bottom:14px">📦</div>
		<div style="font-size:14px;font-weight:700;color:var(--gt-white);margin-bottom:8px">No PRO Packs Activated Yet</div>
		<p style="font-size:13px;color:var(--gt-subtle);max-width:460px;margin:0 auto 20px;line-height:1.65">
			Purchase a pack from the PRO Rules page, then enter your
			<code style="background:rgba(255,255,255,0.06);padding:2px 6px;border-radius:4px">PACK-XXXX</code>
			key above to activate and import the rules.
		</p>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>"
			class="gt-btn gt-btn-primary">Browse All 200 Packs →</a>
	</div>
	<?php else : ?>

	<div id="gt-tp-packs-grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px;padding:4px 0">
		<?php
		foreach ( $owned_packs as $pack_id => $pack ) :
			$name       = $pack['pack_name'] ?? $pack_id;
			$imported   = ! empty( $pack['imported'] ) ? gmdate( 'M j, Y', strtotime( $pack['imported'] ) ) : '—';
			$stats      = $pack_stats[ $pack_id ] ?? array(
				'total_rules'  => 0,
				'active_rules' => 0,
				'revenue'      => 0,
			);
			$is_imp     = ! empty( $pack['is_imported'] ) || $stats['total_rules'] > 0;
			$valid      = ! empty( $pack['signature_valid'] ) || true; // show valid by default
			$delete_url = wp_nonce_url(
				add_query_arg(
					array(
						'page'               => 'gt-bogo-engine',
						'tab'                => 'templates',
						'gtbogo_delete_pack' => $pack_id,
					),
					admin_url( 'admin.php' )
				),
				'gtbogo_delete_pack_' . $pack_id
			);
			?>
	<div class="gt-tp-pack-card gt-animate-in"
		data-name="<?php echo esc_attr( strtolower( $name ) ); ?>"
		style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;overflow:hidden;transition:border-color .2s">

		<!-- Card header -->
		<div style="padding:16px 18px;border-bottom:1px solid rgba(255,255,255,0.04)">
			<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:10px">
				<div style="font-size:13px;font-weight:800;color:var(--gt-white);line-height:1.3;flex:1">
					<?php echo esc_html( $name ); ?>
				</div>
				<span style="padding:2px 8px;border-radius:20px;font-size:9px;font-weight:800;text-transform:uppercase;flex-shrink:0;
							background:<?php echo $is_imp ? 'rgba(34,197,94,0.1)' : 'rgba(100,116,139,0.1)'; ?>;
							border:1px solid <?php echo $is_imp ? 'rgba(34,197,94,0.3)' : 'rgba(100,116,139,0.2)'; ?>;
							color:<?php echo $is_imp ? '#22c55e' : '#64748b'; ?>">
					<?php echo $is_imp ? 'Imported' : 'Not Imported'; ?>
				</span>
			</div>

			<!-- Stats row -->
			<div style="display:flex;gap:16px;font-size:11px">
				<div>
					<div style="color:var(--gt-subtle);font-weight:600;text-transform:uppercase;letter-spacing:.08em;font-size:9px">Rules</div>
					<div style="color:var(--gt-white);font-weight:700"><?php echo esc_html( (string) $stats['total_rules'] ); ?></div>
				</div>
				<div>
					<div style="color:var(--gt-subtle);font-weight:600;text-transform:uppercase;letter-spacing:.08em;font-size:9px">Active</div>
					<div style="color:#22c55e;font-weight:700"><?php echo esc_html( (string) $stats['active_rules'] ); ?></div>
				</div>
				<div>
					<div style="color:var(--gt-subtle);font-weight:600;text-transform:uppercase;letter-spacing:.08em;font-size:9px">Revenue</div>
					<div style="color:#f59e0b;font-weight:700">$<?php echo esc_html( number_format( $stats['revenue'], 0 ) ); ?></div>
				</div>
				<div style="margin-left:auto;text-align:right">
					<div style="color:var(--gt-subtle);font-weight:600;text-transform:uppercase;letter-spacing:.08em;font-size:9px">Activated</div>
					<div style="color:var(--gt-subtle);font-size:11px"><?php echo esc_html( $imported ); ?></div>
				</div>
			</div>
		</div>

		<!-- Validation status -->
		<div style="padding:8px 18px;background:<?php echo $valid ? 'rgba(34,197,94,0.04)' : 'rgba(239,68,68,0.04)'; ?>;
					border-bottom:1px solid rgba(255,255,255,0.04);font-size:10px;
					color:<?php echo $valid ? '#22c55e' : '#ef4444'; ?>;font-weight:700">
			<?php echo $valid ? '✓ Cryptographic signature valid' : '✗ Signature invalid — re-import to re-validate'; ?>
		</div>

		<!-- Actions -->
		<div style="padding:12px 18px;display:flex;gap:8px;flex-wrap:wrap">
			<button type="button"
				onclick="gtTpReimport('<?php echo esc_js( $pack_id ); ?>','<?php echo esc_js( $name ); ?>',this,'<?php echo esc_js( $dl_nonce ); ?>')"
				class="gt-btn gt-btn-ghost gt-btn-sm" style="flex:1">
				↻ Re-import
			</button>
			<button type="button"
				onclick="gtTpToggleDetail('<?php echo esc_js( $pack_id ); ?>')"
				class="gt-btn gt-btn-ghost gt-btn-sm">
				▸ Details
			</button>
			<a href="<?php echo esc_url( $delete_url ); ?>"
				class="gt-btn gt-btn-sm"
				style="background:rgba(220,38,38,0.08);color:#f87171;border:1px solid rgba(220,38,38,0.2)"
				onclick="return confirm('Remove this pack and all its rules from the store?')">
				✗
			</a>
		</div>

		<!-- Detail accordion -->
		<div id="gt-tp-detail-<?php echo esc_attr( $pack_id ); ?>"
			style="display:none;border-top:1px solid rgba(255,255,255,0.04);padding:14px 18px;background:rgba(0,0,0,0.15)">
			<div style="font-size:10px;font-weight:800;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.1em;margin-bottom:10px">Pack Details</div>
			<div style="font-size:12px;color:var(--gt-subtle);line-height:1.6;margin-bottom:10px">
				<strong style="color:var(--gt-white)">Pack ID:</strong>
				<span style="font-family:'DM Mono','Courier New',monospace"><?php echo esc_html( $pack_id ); ?></span>
			</div>
			<?php if ( $stats['total_rules'] > 0 ) : ?>
			<div style="font-size:12px;color:var(--gt-subtle);line-height:1.6;margin-bottom:10px">
				<strong style="color:var(--gt-white)"><?php echo esc_html( (string) $stats['total_rules'] ); ?> rules imported</strong>
				— <?php echo esc_html( (string) $stats['active_rules'] ); ?> currently active
			</div>
				<?php if ( $stats['active_rules'] > 0 ) : ?>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>"
				style="font-size:11px;color:var(--gt-red);font-weight:700;text-decoration:none">
				View rules in PRO Rules →
			</a>
			<?php endif; ?>
			<?php else : ?>
			<div style="font-size:12px;color:var(--gt-subtle)">
				No rules imported yet. Click Re-import to load this pack's rules into your rule stack.
			</div>
			<?php endif; ?>
			<div style="margin-top:10px;font-size:11px;color:var(--gt-subtle)">
				Rules from this pack are <strong style="color:var(--gt-white)">not included in config exports</strong>
				— they require a valid license to re-download.
			</div>
		</div>
	</div>
		<?php endforeach; ?>
	</div>

	<!-- Re-import result -->
	<div id="gt-tp-reimport-result" style="display:none;margin-top:14px;padding:12px 16px;border-radius:8px;font-size:13px"></div>

	<?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	PACK SECURITY GUIDANCE
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in"
	style="background:linear-gradient(135deg,rgba(59,130,246,0.05),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
	<div class="gt-card-header" onclick="gtTpToggleSecurity()" style="cursor:pointer">
		<h2 class="gt-card-title">🔒 Pack Security & License Model</h2>
		<span id="gt-tp-sec-arrow" style="color:var(--gt-subtle)">▸ Expand</span>
	</div>
	<div id="gt-tp-security" style="display:none">
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:0 0 8px">
		<?php
		$security_info = array(
			array( 'Rules Are Not in Backups', 'Config backup exports never include rules from purchased packs. Sharing a backup cannot grant free access to paid pack rules on another store.' ),
			array( 'Re-import Always Re-validates', 'Every re-import calls the license server to verify your PRO license before releasing pack rules. There is no offline bypass.' ),
			array( 'Cryptographic Signatures', 'Every pack file is cryptographically signed. Tampered packs are automatically detected and rejected before any rules are imported.' ),
			array( 'Lost Your Pack Key?', 'Check your purchase email for your PACK-XXXX key. If you cannot locate it, contact support@graphictshirts.shop with your order details.' ),
		);
		foreach ( $security_info as $si ) :
			?>
		<div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:8px;padding:14px">
			<div style="font-size:12px;font-weight:700;color:var(--gt-white);margin-bottom:6px"><?php echo esc_html( $si[0] ); ?></div>
			<div style="font-size:11px;color:var(--gt-soft);line-height:1.6"><?php echo esc_html( $si[1] ); ?></div>
		</div>
		<?php endforeach; ?>
		</div>
	</div>
</div>

<?php endif; // is_pro ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	JAVASCRIPT
════════════════════════════════════════════════════════════════════════════ -->
<script>
(function(){
'use strict';

/* ── Filter packs ────────────────────────────────────────────────────── */
window.gtTpFilter = function() {
	var q = document.getElementById('gt-tp-search')?.value.toLowerCase() || '';
	document.querySelectorAll('.gt-tp-pack-card').forEach(function(card) {
		var name = card.getAttribute('data-name') || '';
		card.style.display = name.includes(q) ? '' : 'none';
	});
};

/* ── Toggle pack detail accordion ───────────────────────────────────── */
window.gtTpToggleDetail = function(packId) {
	var detail = document.getElementById('gt-tp-detail-' + packId);
	if (!detail) return;
	var open = detail.style.display !== 'none';
	detail.style.display = open ? 'none' : 'block';
	/* Update button text */
	var card = detail.closest('[data-name]');
	if (card) {
		var btn = card.querySelector('[onclick*="gtTpToggleDetail"]');
		if (btn) btn.textContent = open ? '▸ Details' : '▾ Details';
	}
};

/* ── Activate pack key ───────────────────────────────────────────────── */
window.gtTpActivatePack = function(nonce) {
	var key    = document.getElementById('gt-tp-pack-key')?.value.trim();
	var result = document.getElementById('gt-tp-activate-result');
	if (!key) { alert('Please enter a pack key.'); return; }

	if (result) {
		result.style.cssText = 'display:block;padding:10px 14px;border-radius:7px;font-size:12px;background:rgba(59,130,246,0.07);border:1px solid rgba(59,130,246,0.2);color:#93c5fd';
		result.textContent   = 'Activating pack key — verifying with license server…';
	}

	var fd = new FormData();
	fd.append('action',   'gtbogo_activate_pack_key');
	fd.append('nonce',    nonce);
	fd.append('pack_key', key);

	fetch(ajaxurl, {method:'POST',body:fd})
		.then(function(r){ return r.json(); })
		.then(function(resp) {
			if (!result) return;
			var ok = resp.success;
			result.style.cssText = 'display:block;padding:10px 14px;border-radius:7px;font-size:12px;background:' +
				(ok?'rgba(34,197,94,0.07)':'rgba(239,68,68,0.07)') +
				';border:1px solid '+(ok?'rgba(34,197,94,0.05)':'rgba(239,68,68,0.25)')+
				';color:'+(ok?'#86efac':'#fca5a5');
			result.textContent = resp.data?.message || (ok ? 'Pack activated successfully. Reloading…' : 'Activation failed. Check your key and license status.');
			if (ok) setTimeout(function(){ location.reload(); }, 1600);
		})
		.catch(function() {
			if (result) { result.style.display='block'; result.textContent='Network error. Try again.'; }
		});
};

/* ── Re-import pack ──────────────────────────────────────────────────── */
window.gtTpReimport = function(packId, packName, btn, nonce) {
	if (!confirm('Re-import all rules from ' + packName + '?\n\nThis calls the license server to verify your PRO license before releasing rules.')) return;
	btn.disabled    = true;
	btn.textContent = 'Importing…';

	var result = document.getElementById('gt-tp-reimport-result');

	var fd = new FormData();
	fd.append('action',  'gtbogo_download_pack');
	fd.append('pack_id', packId);
	fd.append('nonce',   nonce);

	fetch(ajaxurl, {method:'POST',body:fd})
		.then(function(r){ return r.json(); })
		.then(function(resp) {
			btn.disabled    = false;
			btn.textContent = resp.success ? '✓ Done' : '↻ Re-import';
			if (resp.success) {
				btn.style.color = '#22c55e';
				if (result) {
					result.style.cssText = 'display:block;background:rgba(34,197,94,0.07);border:1px solid rgba(34,197,94,0.05);color:#86efac;padding:10px 14px;border-radius:7px;font-size:13px';
					result.textContent   = '✓ ' + packName + ' rules re-imported successfully.';
				}
				setTimeout(function(){ location.reload(); }, 1800);
			} else {
				if (result) {
					result.style.cssText = 'display:block;background:rgba(239,68,68,0.07);border:1px solid rgba(239,68,68,0.25);color:#fca5a5;padding:10px 14px;border-radius:7px;font-size:13px';
					result.textContent   = '✗ Re-import failed: ' + (resp.data?.message || 'Unknown error');
				}
				btn.style.color = '';
			}
		})
		.catch(function() {
			btn.disabled    = false;
			btn.textContent = '↻ Re-import';
		});
};

/* ── AI Recommender ──────────────────────────────────────────────────── */
window.gtTpAiRecommend = function(nonce) {
	var goal   = document.getElementById('gt-tp-ai-goal')?.value.trim();
	var btn    = document.getElementById('gt-tp-ai-btn');
	var result = document.getElementById('gt-tp-ai-results');
	if (!goal) { alert('Describe your promotional goal first.'); return; }
	if (!result) return;

	if (btn) { btn.textContent = '✦ Thinking…'; btn.disabled = true; }
	result.style.display  = 'block';
	result.innerHTML = '<div style="color:var(--gt-subtle);font-size:12px;padding:16px 0">Analysing your store data and matching against 200 packs…</div>';

	var fd = new FormData();
	fd.append('action', 'gtbogo_ai_recommend_packs');
	fd.append('nonce',  nonce);
	fd.append('goal',   goal);

	fetch(ajaxurl, {method:'POST',body:fd})
		.then(function(r){ return r.json(); })
		.then(function(resp) {
			if (btn) { btn.textContent = '✦ Find Best Packs'; btn.disabled = false; }
			if (!resp.success || !resp.data?.recommendations?.length) {
				result.innerHTML = '<div style="color:#ef4444;font-size:12px;padding:8px 0">No recommendations found. '+(resp.data?.message||'Try a more specific goal.')+'</div>';
				return;
			}
			var recs = resp.data.recommendations;
			var html = '<div style="font-size:11px;font-weight:800;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.1em;margin-bottom:10px">Top Pack Matches</div>';
			html    += '<div style="display:flex;flex-direction:column;gap:8px">';
			recs.forEach(function(r) {
				var score_color = r.fit_score >= 80 ? '#22c55e' : (r.fit_score >= 60 ? '#f59e0b' : '#64748b');
				html += '<div style="display:flex;align-items:center;gap:12px;padding:12px 14px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:8px">';
				html += '<div style="text-align:center;flex-shrink:0;width:48px">';
				html += '<div style="font-size:20px;font-weight:900;color:'+score_color+'">'+r.fit_score+'</div>';
				html += '<div style="font-size:9px;color:var(--gt-subtle);font-weight:700">FIT</div></div>';
				html += '<div style="flex:1;min-width:0">';
				html += '<div style="font-size:12px;font-weight:700;color:var(--gt-white);margin-bottom:3px">'+r.pack_name+'</div>';
				html += '<div style="font-size:11px;color:var(--gt-subtle);line-height:1.4">'+r.reason+'</div></div>';
				html += '<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" style="font-size:11px;font-weight:700;color:var(--gt-red);text-decoration:none;flex-shrink:0">Purchase →</a>';
				html += '</div>';
			});
			html += '</div>';
			result.innerHTML = html;
		})
		.catch(function() {
			if (btn) { btn.textContent = '✦ Find Best Packs'; btn.disabled = false; }
			result.innerHTML = '<div style="color:#ef4444;font-size:12px;padding:8px 0">Network error. Try again.</div>';
		});
};

/* ── Security accordion ──────────────────────────────────────────────── */
window.gtTpToggleSecurity = function() {
	var sec   = document.getElementById('gt-tp-security');
	var arrow = document.getElementById('gt-tp-sec-arrow');
	if (!sec) return;
	var open = sec.style.display !== 'none';
	sec.style.display  = open ? 'none' : 'block';
	if (arrow) arrow.textContent = open ? '▸ Expand' : '▾ Collapse';
};

/* ── Hover effects on pack cards ─────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', function() {
	document.querySelectorAll('.gt-tp-pack-card').forEach(function(card) {
		card.addEventListener('mouseenter', function() {
			this.style.borderColor = 'rgba(225,0,0,0.3)';
		});
		card.addEventListener('mouseleave', function() {
			this.style.borderColor = 'var(--gt-border)';
		});
	});
});

})();
</script>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
