<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine — AI Intelligence Admin Page v3.20.5
 *
 * Connect Anthropic + OpenRouter API keys. Monitor usage, rate limits,
 * and recent AI activity across all intelligence superpowers.
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_woocommerce' ) ) {
	return;
}

$ai    = class_exists( 'GT_BOGO_AI_Engine' ) ? GT_BOGO_AI_Engine::instance() : null;
$msg   = '';
$msg_t = '';

// ── Anthropic key save ─────────────────────────────────────────────────
if ( isset( $_POST['gtbogo_save_anthropic'] ) && check_admin_referer( 'gtbogo_ai_settings' ) ) {
	$raw = sanitize_text_field( wp_unslash( $_POST['gtbogo_anthropic_key'] ?? '' ) );
	if ( $ai ) {
		$ai->set_api_key( $raw );
		$msg   = 'Anthropic key saved.';
		$msg_t = 'success';
	}
}

// ── Anthropic test ─────────────────────────────────────────────────────
if ( isset( $_POST['gtbogo_test_anthropic'] ) && check_admin_referer( 'gtbogo_ai_settings' ) ) {
	if ( $ai ) {
		$result = $ai->validate_api_key();
		if ( $result === true ) {
			$msg   = 'Anthropic connection successful.';
			$msg_t = 'success';
		} else {
			$msg   = $result;
			$msg_t = 'error';
		}
	}
}

// ── OpenRouter key save ─────────────────────────────────────────────────
if ( isset( $_POST['gtbogo_save_openrouter'] ) && check_admin_referer( 'gtbogo_ai_settings' ) ) {
	$raw = sanitize_text_field( wp_unslash( $_POST['gtbogo_openrouter_key'] ?? '' ) );
	if ( $ai ) {
		$ai->set_openrouter_key( $raw );
		$msg   = 'OpenRouter key saved.';
		$msg_t = 'success';
	}
}

// ── OpenRouter test ─────────────────────────────────────────────────────
if ( isset( $_POST['gtbogo_test_openrouter'] ) && check_admin_referer( 'gtbogo_ai_settings' ) ) {
	if ( $ai ) {
		$result = $ai->validate_openrouter_key();
		if ( $result === true ) {
			$msg   = 'OpenRouter connection successful.';
			$msg_t = 'success';
		} else {
			$msg   = $result ?? 'OpenRouter test failed.';
			$msg_t = 'error';
		}
	}
}

// ── Gather state ───────────────────────────────────────────────────────
$ant_key  = $ai ? $ai->get_api_key() : '';
$or_key   = $ai ? $ai->get_openrouter_key() : '';
$provider = $ai ? $ai->get_provider() : 'none';
$rate     = $ai ? $ai->get_rate_status() : array(
	'used'  => 0,
	'limit' => 100,
);
$stats    = $ai ? $ai->get_usage_stats( 30 ) : array();
$log      = $ai ? $ai->get_audit_log( 20 ) : array();

$ant_masked = $ant_key ? '••••••••' . substr( $ant_key, -4 ) : '';
$or_masked  = $or_key ? '••••••••' . substr( $or_key, -4 ) : '';
$pct_used   = $rate['limit'] > 0 ? min( 100, round( ( $rate['used'] / $rate['limit'] ) * 100 ) ) : 0;

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

<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">✦ AI Intelligence</h1>
		<p class="gt-page-subtitle">Connect your AI provider keys to unlock intelligent pack recommendations, deal gap analysis, AI copywriting, and performance coaching.</p>
	</div>
	<div class="gt-page-actions">
		<span class="gt-badge <?php echo $provider !== 'none' ? 'gt-badge-active' : 'gt-badge-free'; ?>">
			<?php echo $provider !== 'none' ? '● ' . esc_html( ucfirst( $provider ) ) . ' Active' : '○ No Provider'; ?>
		</span>
	</div>
</div>

<?php if ( $msg ) : ?>
<div class="gt-notice gt-notice-<?php echo esc_attr( $msg_t ); ?> gt-animate-in"><?php echo esc_html( $msg ); ?></div>
<?php endif; ?>

<!-- ── API Configuration ──────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🔑 API Configuration</h2>
	</div>

	<div class="gt-grid-2">
		<!-- Anthropic -->
		<div class="gt-card" style="background:rgba(255,255,255,0.015);margin-bottom:0">
			<div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
				<span style="font-size:20px">🧠</span>
				<div>
					<div style="font-size:14px;font-weight:700;color:var(--gt-white)">Anthropic</div>
					<div style="font-size:12px;color:var(--gt-soft)">Claude models — intelligence engine</div>
				</div>
				<?php if ( $ant_key ) : ?>
				<span class="gt-badge gt-badge-active" style="margin-left:auto">● Active</span>
				<?php else : ?>
				<span class="gt-badge gt-badge-free" style="margin-left:auto">○ Not set</span>
				<?php endif; ?>
			</div>
			<form method="post" action="">
				<?php wp_nonce_field( 'gtbogo_ai_settings' ); ?>
				<div class="gt-form-group">
					<label class="gt-form-label">API Key</label>
					<input type="password" name="gtbogo_anthropic_key" class="gt-input"
							value="<?php echo esc_attr( $ant_masked ); ?>"
							placeholder="sk-ant-api03-..."
							style="font-family:monospace"
							onfocus="if(this.value.indexOf('••••')===0)this.value=''">
					<div class="gt-form-hint">Keys are encrypted with Sodium before storage. Never stored in plaintext.</div>
				</div>
				<div class="gt-flex gt-gap-sm">
					<button type="submit" name="gtbogo_save_anthropic" class="gt-btn gt-btn-primary">Save Key</button>
					<button type="submit" name="gtbogo_test_anthropic" class="gt-btn gt-btn-secondary">Test Connection</button>
				</div>
			</form>
		</div>

		<!-- OpenRouter -->
		<div class="gt-card" style="background:rgba(255,255,255,0.015);margin-bottom:0">
			<div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
				<span style="font-size:20px">🌐</span>
				<div>
					<div style="font-size:14px;font-weight:700;color:var(--gt-white)">OpenRouter</div>
					<div style="font-size:12px;color:var(--gt-soft)">Multi-model gateway — 200+ models</div>
				</div>
				<?php if ( $or_key ) : ?>
				<span class="gt-badge gt-badge-active" style="margin-left:auto">● Active</span>
				<?php else : ?>
				<span class="gt-badge gt-badge-free" style="margin-left:auto">○ Not set</span>
				<?php endif; ?>
			</div>
			<form method="post" action="">
				<?php wp_nonce_field( 'gtbogo_ai_settings' ); ?>
				<div class="gt-form-group">
					<label class="gt-form-label">API Key</label>
					<input type="password" name="gtbogo_openrouter_key" class="gt-input"
							value="<?php echo esc_attr( $or_masked ); ?>"
							placeholder="sk-or-v1-..."
							style="font-family:monospace"
							onfocus="if(this.value.indexOf('••••')===0)this.value=''">
					<div class="gt-form-hint">Add credits at <a href="https://openrouter.ai/settings/credits" target="_blank" rel="noopener" style="color:#60a5fa">openrouter.ai/settings/credits</a></div>
				</div>
				<div class="gt-flex gt-gap-sm">
					<button type="submit" name="gtbogo_save_openrouter" class="gt-btn gt-btn-primary">Save Key</button>
					<button type="submit" name="gtbogo_test_openrouter" class="gt-btn gt-btn-secondary">Test Connection</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- ── Pack Recommendations ──────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📦 AI Pack Recommendations</h2>
		<span style="font-size:12px;color:var(--gt-soft)">Describe your promotional goal — AI recommends the best packs</span>
	</div>
	<div class="gt-form-group">
		<label class="gt-form-label">What is your promotional goal?</label>
		<textarea id="ai-goal-input" class="gt-input" rows="3" style="width:100%;resize:vertical;font-family:inherit;font-size:14px;"
			placeholder="e.g. I want to move overstock winter inventory before spring, or I need a loyalty programme for returning customers..."></textarea>
		<div class="gt-form-hint">Be specific — mention your goal, timeline, and customer type for the best results.</div>
	</div>
	<div class="gt-flex gt-gap-sm" style="margin-top:10px">
		<button type="button" id="ai-recommend-btn" class="gt-btn gt-btn-primary" onclick="gtbogoAiRecommend()">
			⚡ Get Recommendations
		</button>
		<span id="ai-recommend-status" style="display:none;align-items:center;gap:6px;font-size:13px;color:var(--gt-soft)">
			<span style="display:inline-block;width:14px;height:14px;border:2px solid var(--gt-red);border-top-color:transparent;border-radius:50%;animation:gt-spin 0.6s linear infinite"></span>
			Analysing your store and 200 packs...
		</span>
	</div>
	<div id="ai-recommend-results" style="margin-top:20px;display:none;">
		<div class="gt-grid-3" id="ai-recommend-grid"></div>
	</div>
</div>

<!-- ── AI Copywriter ───────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">

<!-- ── BRAND INTELLIGENCE ──────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">&#129504; Brand Intelligence</h2>
        <span class="gt-text-soft" style="font-size:13px">Auto-extracted from your store. Powers all 6 AI features with your brand voice.</span>
    </div>
    <?php
    $bv = class_exists( 'GT_BOGO_AI_Copywriter' ) ? GT_BOGO_AI_Copywriter::get_brand_voice() : [];
    $bv_set = ! empty( $bv['brand_name'] );
    $bv_error = get_option( 'gtbogo_brand_voice_extract_error', '' );
    ?>
    <?php if ( $bv_set ) : ?>
    <div style="padding:16px 20px;background:rgba(34,197,94,0.05);border-bottom:1px solid var(--gt-border)">
        <div style="display:flex;gap:16px;flex-wrap:wrap;align-items:flex-start">
            <div style="flex:1;min-width:200px">
                <div style="font-size:11px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;margin-bottom:6px">Extracted Brand Voice</div>
                <div style="font-size:14px;font-weight:700;color:var(--gt-text);margin-bottom:4px"><?php echo esc_html( $bv['brand_name'] ?? '' ); ?> &mdash; <span style="color:var(--gt-red);text-transform:capitalize"><?php echo esc_html( $bv['personality'] ?? '' ); ?></span></div>
                <div style="font-size:12px;color:var(--gt-subtle)"><?php echo esc_html( $bv['customer_desc'] ?? '' ); ?></div>
                <?php if ( ! empty( $bv['differentiator'] ) ) : ?>
                <div style="font-size:12px;color:var(--gt-subtle);margin-top:4px"><em><?php echo esc_html( $bv['differentiator'] ); ?></em></div>
                <?php endif; ?>
                <?php if ( ! empty( $bv['avoid_words'] ) ) : ?>
                <div style="font-size:11px;color:var(--gt-subtle);margin-top:6px">Avoids: <code style="font-size:11px"><?php echo esc_html( $bv['avoid_words'] ); ?></code></div>
                <?php endif; ?>
                <?php if ( ! empty( $bv['extracted_at'] ) ) : ?>
                <div style="font-size:11px;color:var(--gt-subtle);margin-top:6px">&#128337; Last analyzed: <?php echo esc_html( $bv['extracted_at'] ); ?> from <?php echo esc_html( $bv['extracted_from'] ?? '' ); ?></div>
                <?php endif; ?>
            </div>
            <?php if ( ! empty( $bv['example_copy'] ) ) : ?>
            <div style="flex:1;min-width:200px;padding:12px 16px;background:var(--gt-bg-card);border:1px solid var(--gt-border);border-radius:8px;border-left:3px solid var(--gt-red)">
                <div style="font-size:11px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;margin-bottom:6px">Voice Example</div>
                <div style="font-size:13px;color:var(--gt-text);font-style:italic">"<?php echo esc_html( $bv['example_copy'] ); ?>"</div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
    <?php if ( $bv_error && ! $bv_set ) : ?>
    <div style="padding:12px 20px;background:rgba(239,68,68,0.05);border-bottom:1px solid var(--gt-border)">
        <p style="margin:0;font-size:13px;color:#ef4444">&#9888; Auto-extraction failed: <?php echo esc_html( $bv_error ); ?> — try re-analyzing below.</p>
    </div>
    <?php endif; ?>
    <div class="gt-setting-row">
        <div>
            <div class="gt-setting-label"><?php echo $bv_set ? 'Re-analyze Website' : 'Analyze My Website'; ?></div>
            <div class="gt-setting-desc">Crawls your homepage, about page, and product pages. Extracts your brand personality, voice, customer language, and words to avoid. Used by every AI feature automatically.</div>
        </div>
        <button type="button" class="gt-btn" onclick="gtbogoExtractBrandVoice()" id="gtbogo-extract-btn">
            &#129504; <?php echo $bv_set ? 'Re-analyze' : 'Analyze My Website'; ?>
        </button>
    </div>
    <div class="gt-setting-row" style="border:none">
        <div>
            <div class="gt-setting-label">Additional Pages (optional)</div>
            <div class="gt-setting-desc">Add URLs to specific pages that best represent your brand — one per line. e.g. your About page, brand story, or key product category.</div>
        </div>
        <textarea id="gtbogo-extra-urls" class="gt-input" style="max-width:320px;height:80px;resize:vertical" placeholder="https://yourdomain.com/about/&#10;https://yourdomain.com/our-story/"></textarea>
    </div>
    <div id="gtbogo-extract-status" style="padding:12px 20px;display:none;border-top:1px solid var(--gt-border)">
        <p style="margin:0;font-size:13px" id="gtbogo-extract-msg"></p>
    </div>
</div>

	<div class="gt-card-header">
		<h2 class="gt-card-title">✍️ AI Copywriter</h2>
		<span style="font-size:12px;color:var(--gt-soft)">Define your brand voice once — AI writes all superpower copy</span>
	</div>

	<!-- Brand Voice Profile -->
	<div id="ai-copywriter-profile" style="margin-bottom:20px">
		<div class="gt-grid-2" style="gap:14px">
			<div class="gt-form-group">
				<label class="gt-form-label">Brand Name</label>
				<input type="text" id="ai-cw-brand" class="gt-input" placeholder="e.g. Acme Outdoors" onchange="gtbogoAiCWSaveProfile()">
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Personality</label>
				<select id="ai-cw-personality" class="gt-select" onchange="gtbogoAiCWSaveProfile()">
					<option value="professional">Professional</option>
					<option value="friendly">Friendly</option>
					<option value="bold">Bold / Edgy</option>
					<option value="luxury">Luxury / Refined</option>
					<option value="playful">Playful / Witty</option>
					<option value="minimalist">Minimalist</option>
				</select>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Who are your customers?</label>
				<input type="text" id="ai-cw-customers" class="gt-input" placeholder="e.g. Busy professionals, luxury shoppers, fitness enthusiasts" onchange="gtbogoAiCWSaveProfile()">
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">What makes your store different?</label>
				<input type="text" id="ai-cw-diff" class="gt-input" placeholder="e.g. Handcrafted in small batches, free returns forever" onchange="gtbogoAiCWSaveProfile()">
			</div>
		</div>
		<div class="gt-grid-2" style="gap:14px;margin-top:4px">
			<div class="gt-form-group">
				<label class="gt-form-label">Words or tone to AVOID</label>
				<input type="text" id="ai-cw-avoid" class="gt-input" placeholder="e.g. no slang, no emoji, no pressure language" onchange="gtbogoAiCWSaveProfile()">

									<!-- GAP 5: Luxury Copy Constitution -->
									<div class="gt-setting-row" style="border-top:1px solid var(--gt-border);margin-top:12px;padding-top:12px">
										<div>
											<div class="gt-setting-label">Luxury Copy Constitution</div>
											<div class="gt-setting-desc">Enforces Gucci/Prada-tier copy standards. Permanently bans discount language, urgency, and scarcity pressure. Replaces them with aspiration, invitation, and heritage vocabulary.</div>
										</div>
										<label class="gt-toggle"><input type="checkbox" id="ai-cw-luxury-constitution" onchange="gtbogoSaveLuxuryConstitution()" <?php checked( (bool) get_option( 'gtbogo_luxury_copy_constitution', 0 ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
									</div>
									<div class="gt-setting-row">
										<div>
											<div class="gt-setting-label">Brand-Specific Prohibited Words</div>
											<div class="gt-setting-desc">Additional words banned for your brand, comma-separated. Added to the baseline luxury prohibited list.</div>
										</div>
										<input type="text" id="ai-cw-prohibited-words" class="gt-input" style="max-width:320px"
											placeholder="e.g. promo, deal, offer, special"
											value="<?php echo esc_attr( get_option( 'gtbogo_luxury_prohibited_words', '' ) ); ?>"
											onchange="gtbogoSaveLuxuryConstitution()">
									</div>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Example of copy you love</label>
				<input type="text" id="ai-cw-example" class="gt-input" placeholder="e.g. 'Built to last. Priced to own.'" onchange="gtbogoAiCWSaveProfile()">
			</div>
		</div>
		<div class="gt-form-hint" style="margin-top:6px">Changes save automatically as you type. Fill all fields for the best results.</div>
	</div>

	<!-- Generate Button -->
	<div class="gt-flex gt-gap-sm" style="margin-bottom:20px">
		<button type="button" id="ai-cw-generate-btn" class="gt-btn gt-btn-primary" onclick="gtbogoAiCWGenerateAll()">
			⚡ Generate All Copy
		</button>
		<span id="ai-cw-gen-status" style="display:none;align-items:center;gap:6px;font-size:13px;color:var(--gt-soft)">
			<span style="display:inline-block;width:14px;height:14px;border:2px solid var(--gt-red);border-top-color:transparent;border-radius:50%;animation:gt-spin 0.6s linear infinite"></span>
			<span id="ai-cw-gen-text">Generating copy across 31 superpowers...</span>
		</span>
		<span id="ai-cw-gen-done" style="display:none;align-items:center;gap:6px;font-size:13px;color:#22c55e">✅ Copy generated</span>
	</div>

	<!-- Copy Management Table -->
	<div id="ai-cw-table-wrap" style="overflow-x:auto;display:none">
		<table class="gt-table" style="width:100%;font-size:12px">
			<thead>
				<tr>
					<th>Superpower</th>
					<th>Fields</th>
					<th>AI Copy Preview</th>
					<th style="width:100px">Actions</th>
				</tr>
			</thead>
			<tbody id="ai-cw-table-body"></tbody>
		</table>
	</div>
	<div id="ai-cw-empty" style="text-align:center;padding:32px;color:var(--gt-soft);font-size:13px">
		Set up your brand voice profile above and click "Generate All Copy" to begin.
	</div>
</div>

<!-- ── Gap Analyzer ─────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🔍 Gap Analyzer</h2>
		<span style="font-size:12px;color:var(--gt-soft)">AI scans your deals against 200 packs — finds missing revenue opportunities</span>
	</div>
	<div class="gt-flex gt-gap-sm" style="margin-bottom:16px">
		<button type="button" id="ai-gap-btn" class="gt-btn gt-btn-primary" onclick="gtbogoAiGapRun()">
			🔍 Run Gap Analysis
		</button>
		<span id="ai-gap-status" style="display:none;align-items:center;gap:6px;font-size:13px;color:var(--gt-soft)">
			<span style="display:inline-block;width:14px;height:14px;border:2px solid var(--gt-red);border-top-color:transparent;border-radius:50%;animation:gt-spin 0.6s linear infinite"></span>
			Analysing your store...
		</span>
		<span id="ai-gap-cached" style="display:none;font-size:12px;color:var(--gt-subtle)"></span>
	</div>
	<div id="ai-gap-results" style="display:none">
		<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:10px" id="ai-gap-grid"></div>
	</div>
	<div id="ai-gap-empty" style="text-align:center;padding:24px;color:var(--gt-soft);font-size:13px">
		Click "Run Gap Analysis" to scan your store for missing promotional opportunities.
	</div>
</div>

<!-- ── AI Superpowers ──────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header">
		<h2 class="gt-card-title">⚡ AI Superpowers</h2>
		<span style="font-size:12px;color:var(--gt-soft)">Powered by <?php echo esc_html( ucfirst( $provider ) ); ?></span>
	</div>
	<div class="gt-grid-3">
		<?php
		$features = array(
			array( '📦', 'Pack Recommender', 'AI-powered pack suggestions based on store profile, industry, and deal history.' ),
			array( '✍️', 'AI Copywriter', 'Generates urgency copy, email subject lines, and deal descriptions tuned to customer archetypes.' ),
			array( '🔍', 'Gap Analyzer', 'Scans current deals against 200 PRO Packs to surface missing revenue opportunities.' ),
			array( '🛒', 'Cart Intelligence', 'Real-time cart analysis — predicts conversion probability and optimal discount depth.' ),
			array( '📈', 'Performance Coach', 'Weekly AI report with actionable revenue recommendations and strategy adjustments.' ),
			array( '🧪', 'A/B Test Optimizer', 'AI-driven statistical analysis of A/B test results with significance scoring.' ),
		);
		$active   = $provider !== 'none';
		foreach ( $features as $f ) :
			?>
		<div class="gt-metric" style="--gt-metric-c:<?php echo $active ? '#22c55e' : '#475569'; ?>;border-top:2px solid <?php echo $active ? '#22c55e' : '#475569'; ?>">
			<span class="gt-metric-icon"><?php echo esc_html( $f[0] ); ?></span>
			<div class="gt-metric-label"><?php echo esc_html( $f[1] ); ?></div>
			<div style="font-size:12px;color:var(--gt-soft);line-height:1.5;margin-top:6px"><?php echo esc_html( $f[2] ); ?></div>
			<div style="margin-top:12px">
				<span class="gt-badge <?php echo $active ? 'gt-badge-active' : 'gt-badge-free'; ?>">
					<?php echo $active ? '● Active' : '○ Needs Key'; ?>
				</span>
			</div>
		</div>
		<?php endforeach; ?>
	</div>
</div>

<!-- ── Performance Coach ────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📈 Performance Coach</h2>
		<span style="font-size:12px;color:var(--gt-soft)">Weekly AI report — revenue recommendations, underperforming deals, customer outreach</span>
	</div>
	<div class="gt-flex gt-gap-sm" style="margin-bottom:16px">
		<button type="button" id="ai-coach-btn" class="gt-btn gt-btn-primary" onclick="gtbogoAiCoachGenerate()">
			📊 Generate Report Now
		</button>
		<span id="ai-coach-status" style="display:none;align-items:center;gap:6px;font-size:13px;color:var(--gt-soft)">
			<span style="display:inline-block;width:14px;height:14px;border:2px solid var(--gt-red);border-top-color:transparent;border-radius:50%;animation:gt-spin 0.6s linear infinite"></span>
			Generating report...
		</span>
	</div>
	<div id="ai-coach-report" style="display:none">
		<div id="ai-coach-content" style="font-size:13px;color:var(--gt-soft);line-height:1.7"></div>
	</div>
	<div id="ai-coach-empty" style="text-align:center;padding:24px;color:var(--gt-soft);font-size:13px">
		Click "Generate Report Now" to get your first AI performance review. Reports run automatically every Monday.
	</div>
</div>

<!-- ── Usage & Rate Limits ─────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📊 Usage & Rate Limits</h2>
	</div>

	<div class="gt-metrics">
		<div class="gt-metric" style="--gt-metric-c:#22c55e">
			<span class="gt-metric-icon">⚡</span>
			<div class="gt-metric-label">Requests Today</div>
			<div class="gt-metric-value"><?php echo absint( $rate['used'] ); ?></div>
			<div class="gt-metric-trend">of <?php echo absint( $rate['limit'] ); ?> limit</div>
		</div>
		<div class="gt-metric" style="--gt-metric-c:#3b82f6">
			<span class="gt-metric-icon">🪙</span>
			<div class="gt-metric-label">Tokens (30d)</div>
			<div class="gt-metric-value"><?php echo number_format( absint( $stats['total_tokens'] ?? 0 ) ); ?></div>
			<div class="gt-metric-trend">across all features</div>
		</div>
		<div class="gt-metric" style="--gt-metric-c:#f59e0b">
			<span class="gt-metric-icon">🔄</span>
			<div class="gt-metric-label">Live Calls (30d)</div>
			<div class="gt-metric-value"><?php echo number_format( absint( $stats['live_calls'] ?? 0 ) ); ?></div>
			<div class="gt-metric-trend">non-cached requests</div>
		</div>
		<div class="gt-metric" style="--gt-metric-c:#8b5cf6">
			<span class="gt-metric-icon">💾</span>
			<div class="gt-metric-label">Cached Calls (30d)</div>
			<div class="gt-metric-value"><?php echo number_format( absint( $stats['cached_calls'] ?? 0 ) ); ?></div>
			<div class="gt-metric-trend">served from cache</div>
		</div>
	</div>

	<!-- Rate bar -->
	<div style="margin-top:8px">
		<div class="gt-flex-between" style="margin-bottom:6px">
			<span style="font-size:13px;color:var(--gt-soft)">Rate Usage</span>
			<span style="font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo absint( $pct_used ); ?>%</span>
		</div>
		<div style="height:6px;background:rgba(255,255,255,0.05);border-radius:3px;overflow:hidden">
			<div style="height:100%;width:<?php echo absint( $pct_used ); ?>%;background:<?php echo $pct_used > 80 ? 'var(--gt-red)' : '#22c55e'; ?>;border-radius:3px;transition:width 0.5s"></div>
		</div>
	</div>
</div>

<!-- ── Intelligence Engine ──────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🧪 Intelligence Engine</h2>
		<span style="font-size:12px;color:var(--gt-soft)">Control how the AI makes decisions vs. classic logic</span>
	</div>
	<div class="gt-grid-2" style="gap:16px;margin-bottom:16px">
		<div class="gt-form-group">
			<label class="gt-form-label">Decision Mode</label>
			<select id="ai-ie-mode" class="gt-select" onchange="gtbogoAiIESetMode()">
				<option value="shadow">Shadow — AI runs silently, classic logic decides</option>
				<option value="rollout">Rollout — AI decides for a % of visitors</option>
				<option value="full">Full — AI makes all decisions</option>
			</select>
			<div class="gt-form-hint">Shadow mode lets you verify AI decisions before going live.</div>
		</div>
		<div class="gt-form-group" id="ai-ie-rollout-wrap" style="display:none">
			<label class="gt-form-label">Rollout Percentage</label>
			<div style="display:flex;align-items:center;gap:10px">
				<input type="range" id="ai-ie-rollout" min="1" max="100" value="10" style="flex:1" onchange="gtbogoAiIESetRollout()">
				<span id="ai-ie-rollout-val" style="font-size:14px;font-weight:700;color:var(--gt-white);min-width:40px;text-align:right">10%</span>
			</div>
		</div>
	</div>
	<div id="ai-ie-log-wrap" style="display:none;overflow-x:auto">
		<table class="gt-table" style="width:100%;font-size:11px">
			<thead>
				<tr><th>Time</th><th>Decision</th><th>Classic</th><th>AI</th><th>Winner</th></tr>
			</thead>
			<tbody id="ai-ie-log-body"></tbody>
		</table>
	</div>
</div>

<!-- ── Recent Activity ─────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📋 Recent API Calls</h2>
	</div>
	<div style="overflow-x:auto">
		<table class="gt-table">
			<thead>
				<tr>
					<th>Time (UTC)</th>
					<th>Feature</th>
					<th>Model</th>
					<th>Tokens</th>
					<th>Cached</th>
					<th>Error</th>
				</tr>
			</thead>
			<tbody>
				<?php if ( empty( $log ) ) : ?>
				<tr><td colspan="6" style="text-align:center;padding:32px;color:var(--gt-soft)">No API calls yet. Connect a key to get started.</td></tr>
					<?php
				else :
					foreach ( $log as $entry ) :
						?>
				<tr>
					<td style="white-space:nowrap"><?php echo esc_html( $entry['created_at'] ?? '' ); ?></td>
					<td><?php echo esc_html( $entry['feature'] ?? '' ); ?></td>
					<td><?php echo esc_html( $entry['model'] ?? '—' ); ?></td>
					<td><?php echo absint( $entry['tokens_used'] ?? 0 ); ?></td>
					<td><?php echo ( $entry['was_cached'] ?? false ) ? '✅' : '🔄'; ?></td>
					<td style="color:var(--gt-red)"><?php echo esc_html( $entry['error_msg'] ?? '' ); ?></td>
				</tr>
									<?php
				endforeach;
endif;
				?>
			</tbody>
		</table>
	</div>
</div>

<style>
@keyframes gt-spin{to{transform:rotate(360deg)}}
.gt-pack-rec-card:hover{border-color:rgba(225,0,0,0.25)!important;transform:translateY(-2px);box-shadow:0 8px 30px rgba(0,0,0,0.3)}
</style>
<script>
function gtbogoAiRecommend(){
	var goal=document.getElementById("ai-goal-input").value.trim();
	if(!goal){alert("Please describe your promotional goal.");return;}
	var btn=document.getElementById("ai-recommend-btn");
	var status=document.getElementById("ai-recommend-status");
	var results=document.getElementById("ai-recommend-results");
	var grid=document.getElementById("ai-recommend-grid");
	btn.disabled=true;status.style.display="flex";results.style.display="none";
	var fd=new FormData();
	fd.append("action","gtbogo_ai_recommend_packs");
	fd.append("nonce","<?php echo esc_js( wp_create_nonce( 'gtbogo_ai_recommend_packs' ) ); ?>");
	fd.append("goal",goal);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){
		btn.disabled=false;status.style.display="none";results.style.display="block";
		if(!d.success){grid.innerHTML='<div style="padding:20px;text-align:center;color:var(--gt-red)">'+d.data.message+'</div>';return;}
		var recs=d.data.recommendations;
		if(!recs.length){grid.innerHTML='<div style="padding:20px;text-align:center;color:var(--gt-soft)">No matching packs found. Try a different goal description.</div>';return;}
		var html="";
		recs.forEach(function(r,i){
			var scorePct=Math.round(r.fit_score*100);
			var scoreColor=scorePct>=85?"#22c55e":scorePct>=70?"#f59e0b":"#64748b";
			html+='<div class="gt-metric gt-pack-rec-card" style="--gt-metric-c:#E10000;border-top:2px solid #E10000;cursor:pointer;transition:all 0.2s" onclick="window.open(\''+r.purchase_url+'\',\'_blank\')">';
			html+='<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">';
			html+='<span class="gt-metric-icon">&#128230;</span>';
			html+='<span style="font-size:13px;font-weight:800;color:'+scoreColor+';font-family:monospace">'+scorePct+'% fit</span>';
			html+='</div>';
			html+='<div class="gt-metric-label" style="font-size:14px;">'+r.pack_name+'</div>';
			html+='<div style="font-size:12px;color:var(--gt-soft);line-height:1.5;margin-top:6px;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden">'+r.match_reason+'</div>';
			html+='<div style="margin-top:12px;display:flex;align-items:center;gap:8px">';
			html+='<span class="gt-badge gt-badge-pro" style="font-size:10px;">PRO Pack</span>';
			html+='<span style="font-size:11px;color:var(--gt-soft);margin-left:auto">Click to view &#8594;</span>';
			html+='</div></div>';
		});
		grid.innerHTML=html;
		results.scrollIntoView({behavior:"smooth",block:"center"});
	})
	.catch(function(){
		btn.disabled=false;status.style.display="none";results.style.display="block";
		grid.innerHTML='<div style="padding:20px;text-align:center;color:var(--gt-red)">Network error. Please try again.</div>';
	});
}
</script>
<script>
// ── AI Copywriter ──────────────────────────────────────────────────
var gtbogoAiCWN = '<?php echo esc_js( wp_create_nonce( 'gtbogo_ai_copywriter' ) ); ?>';
var gtbogoAiCWProfileLoaded = false;

function gtbogoAiCWSaveProfile(){
	var fd = new FormData();
	fd.append("action","gtbogo_ai_save_brand_voice");
	fd.append("nonce",gtbogoAiCWN);
	fd.append("brand_name",document.getElementById("ai-cw-brand").value);
	fd.append("personality",document.getElementById("ai-cw-personality").value);
	fd.append("customer_desc",document.getElementById("ai-cw-customers").value);
	fd.append("differentiator",document.getElementById("ai-cw-diff").value);
	fd.append("avoid_words",document.getElementById("ai-cw-avoid").value);
	fd.append("example_copy",document.getElementById("ai-cw-example").value);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"});
}

function gtbogoAiCWGenerateAll(){
	var btn=document.getElementById("ai-cw-generate-btn");
	var status=document.getElementById("ai-cw-gen-status");
	var done=document.getElementById("ai-cw-gen-done");
	btn.disabled=true;status.style.display="flex";done.style.display="none";
	var fd=new FormData();
	fd.append("action","gtbogo_ai_generate_all_copy");
	fd.append("nonce",gtbogoAiCWN);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){
		btn.disabled=false;status.style.display="none";
		if(d.success){done.style.display="flex";gtbogoAiCWLoadStatus();}
		else{alert(d.data.message);}
	});
}

function gtbogoAiCWLoadStatus(){
	var fd=new FormData();
	fd.append("action","gtbogo_ai_get_copy_status");
	fd.append("nonce",gtbogoAiCWN);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){
		if(!d.success)return;
		// Load profile
		if(d.data.profile&&!gtbogoAiCWProfileLoaded){
			document.getElementById("ai-cw-brand").value=d.data.profile.brand_name||"";
			document.getElementById("ai-cw-personality").value=d.data.profile.personality||"professional";
			document.getElementById("ai-cw-customers").value=d.data.profile.customer_desc||"";
			document.getElementById("ai-cw-diff").value=d.data.profile.differentiator||"";
			document.getElementById("ai-cw-avoid").value=d.data.profile.avoid_words||"";
			document.getElementById("ai-cw-example").value=d.data.profile.example_copy||"";
			gtbogoAiCWProfileLoaded=true;
		}
		var status=d.data.status;
		var hasAny=false;
		for(var k in status){if(status[k].has_ai){hasAny=true;break;}}
		if(!hasAny){return;}
		document.getElementById("ai-cw-table-wrap").style.display="block";
		document.getElementById("ai-cw-empty").style.display="none";
		var html="";
		var spList=[
			["progress_bar","Progress Bar"],["savings_calculator","Savings Calculator"],["countdown_timer","Countdown Timer"],
			["scarcity_bar","Scarcity Bar"],["social_proof","Social Proof"],["badge_generator","Badge Generator"],
			["deal_share","Deal Share"],["deal_unlock","Deal Unlock"],["announcement_bar","Announcement Bar"],
			["mobile_drawer","Mobile Drawer"],["exit_intent","Exit Intent"],["abandon_nudge","Abandon Nudge"],
			["cart_recovery","Cart Recovery"],["vip_badge","VIP Badge"],["shipping_progress","Shipping Progress"],
			["smart_popup","Smart Popup"],["nudges","Nudges"],["fomo","FOMO Engine"],["auto_add","Auto-Add"],
			["quick_add","Quick Add"],["deal_comparison","Deal Comparison"],["cart_recommendations","Cart Recommendations"],
			["bundle_spotlight","Bundle Spotlight"],["bundle_configurator","Bundle Configurator"],["loyalty_widget","Loyalty Widget"],
			["referral_widget","Referral Widget"],["savings_history","Savings History"],["dynamic_pricing","Dynamic Pricing"],
			["geo_banner","Geo Banner"],["whatsapp_commerce","WhatsApp Commerce"],["email_notifications","Email Notifications"]
		];
		spList.forEach(function(sp){
			var sid=sp[0],sname=sp[1];
			var spData=status[sid]||{has_ai:false,fields:[]};
			html+='<tr>';
			html+='<td style="font-weight:600;white-space:nowrap">'+sname+'</td>';
			html+='<td style="font-size:11px;color:var(--gt-subtle)">'+(spData.fields||[]).join(", ")||"—"+"</td>";
			if(spData.has_ai){
				html+='<td style="font-size:11px;color:#22c55e">✅ AI copy active</td>';
			}else{
				html+='<td style="font-size:11px;color:var(--gt-soft)">○ Default copy</td>';
			}
			html+='<td><div style="display:flex;gap:4px">';
			html+='<button class="gt-btn gt-btn-xs" style="padding:3px 8px;font-size:10px" onclick="gtbogoAiCWGenerateSingle(\''+sid+'\')">Gen</button>';
			if(spData.has_ai){
				html+='<button class="gt-btn gt-btn-xs" style="padding:3px 8px;font-size:10px;background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.2);color:#fca5a5" onclick="gtbogoAiCWReset(\''+sid+'\')">Reset</button>';
			}
			html+='</div></td>';
			html+='</tr>';
		});
		document.getElementById("ai-cw-table-body").innerHTML=html;
	});
}

function gtbogoAiCWGenerateSingle(spid){
	var fd=new FormData();
	fd.append("action","gtbogo_ai_generate_single_copy");
	fd.append("nonce",gtbogoAiCWN);
	fd.append("sp_id",spid);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){if(d.success)gtbogoAiCWLoadStatus();else alert(d.data.message);});
}

function gtbogoAiCWReset(spid){
	if(!confirm("Reset this superpower back to default copy?"))return;
	var fd=new FormData();
	fd.append("action","gtbogo_ai_reset_copy");
	fd.append("nonce",gtbogoAiCWN);
	fd.append("sp_id",spid);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){if(d.success)gtbogoAiCWLoadStatus();});
}

// Load status on page load
document.addEventListener("DOMContentLoaded",function(){
	gtbogoAiCWLoadStatus();
});
</script>
<script>
// ── Gap Analyzer ───────────────────────────────────────────────────
var gtbogoAiN2 = '<?php echo esc_js( wp_create_nonce( 'gtbogo_ai_intelligence' ) ); ?>';

function gtbogoAiGapRun(){
	var btn=document.getElementById("ai-gap-btn");
	var status=document.getElementById("ai-gap-status");
	var results=document.getElementById("ai-gap-results");
	btn.disabled=true;status.style.display="flex";results.style.display="none";
	var fd=new FormData();
	fd.append("action","gtbogo_ai_gap_analysis");
	fd.append("nonce",gtbogoAiN2);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){
		btn.disabled=false;status.style.display="none";results.style.display="block";
		if(!d.success){document.getElementById("ai-gap-grid").innerHTML='<div style="padding:20px;color:var(--gt-red)">'+d.data.message+'</div>';return;}
		var gaps=d.data.gaps;
		if(!gaps||!gaps.length){document.getElementById("ai-gap-grid").innerHTML='<div style="padding:20px;text-align:center;color:#22c55e;grid-column:span 2">✅ No gaps detected — your promotional coverage looks complete.</div>';return;}
		var sevColors={high:"#ef4444",medium:"#f59e0b",low:"#22c55e"};
		var sevLabels={high:"Critical",medium:"Important",low:"Suggested"};
		var html="";
		gaps.forEach(function(g){
			var c=sevColors[g.severity]||"#64748b";
			html+='<div style="padding:14px;background:rgba(255,255,255,0.02);border:1px solid '+c+'33;border-left:3px solid '+c+';border-radius:6px">';
			html+='<div style="display:flex;align-items:center;gap:8px;margin-bottom:6px"><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:'+c+'"></span><span style="font-size:12px;font-weight:700;color:'+c+'">'+(sevLabels[g.severity]||g.severity)+'</span><span style="font-size:10px;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.06em;margin-left:auto">'+g.gap_type+'</span></div>';
			html+='<div style="font-size:12px;color:var(--gt-white);line-height:1.5;margin-bottom:4px">'+g.description+'</div>';
			html+='<div style="font-size:11px;color:var(--gt-soft)">'+g.urgency+'</div>';
			if(g.recommended_pack_keywords){
				html+='<div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:4px">';
				(Array.isArray(g.recommended_pack_keywords)?g.recommended_pack_keywords:g.recommended_pack_keywords.split(",")).forEach(function(k){
					html+='<span style="font-size:10px;padding:2px 8px;border-radius:50px;background:rgba(225,0,0,0.08);border:1px solid rgba(225,0,0,0.2);color:var(--gt-red)">'+k.trim()+'</span>';
				});
				html+='</div>';
			}
			html+='</div>';
		});
		document.getElementById("ai-gap-grid").innerHTML=html;
		document.getElementById("ai-gap-cached").style.display="none";
	});
}

function gtbogoAiGapLoad(){
	var fd=new FormData();
	fd.append("action","gtbogo_ai_get_gap_results");
	fd.append("nonce",gtbogoAiN2);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){
		if(!d.success||!d.data.gaps||!d.data.gaps.length)return;
		var results=document.getElementById("ai-gap-results");
		results.style.display="block";
		var html="";
		var sevColors={high:"#ef4444",medium:"#f59e0b",low:"#22c55e"};
		var sevLabels={high:"Critical",medium:"Important",low:"Suggested"};
		d.data.gaps.forEach(function(g){
			var c=sevColors[g.severity]||"#64748b";
			html+='<div style="padding:10px;background:rgba(255,255,255,0.02);border:1px solid '+c+'33;border-left:3px solid '+c+';border-radius:6px;margin-bottom:8px">';
			html+='<div style="display:flex;align-items:center;gap:6px;margin-bottom:4px"><span style="display:inline-block;width:6px;height:6px;border-radius:50%;background:'+c+'"></span><span style="font-size:11px;font-weight:700;color:'+c+'">'+(sevLabels[g.severity]||g.severity)+'</span><span style="font-size:10px;color:var(--gt-subtle);margin-left:auto">'+g.gap_type+'</span></div>';
			html+='<div style="font-size:11px;color:var(--gt-white);line-height:1.4">'+g.description+'</div>';
			html+='</div>';
		});
		document.getElementById("ai-gap-grid").innerHTML=html;
	});
}

// ── Performance Coach ───────────────────────────────────────────────
function gtbogoAiCoachGenerate(){
	var btn=document.getElementById("ai-coach-btn");
	var status=document.getElementById("ai-coach-status");
	btn.disabled=true;status.style.display="flex";
	var fd=new FormData();
	fd.append("action","gtbogo_ai_generate_report");
	fd.append("nonce",gtbogoAiN2);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){
		btn.disabled=false;status.style.display="none";
		if(d.success&&d.data.report){
			document.getElementById("ai-coach-report").style.display="block";
			document.getElementById("ai-coach-empty").style.display="none";
			var r=d.data.report;
			var html='<div style="font-size:14px;font-weight:700;color:var(--gt-white);margin-bottom:12px">Weekly Performance Report</div>';
			if(r.summary)html+='<div style="margin-bottom:12px">'+r.summary+'</div>';
			if(r.recommendations&&r.recommendations.length){
				html+='<div style="font-size:13px;font-weight:700;color:#E10000;margin-bottom:8px">Recommendations</div>';
				r.recommendations.forEach(function(rec){html+='<div style="padding:8px 12px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:6px;margin-bottom:6px;font-size:12px">'+rec+'</div>';});
			}
			document.getElementById("ai-coach-content").innerHTML=html;
		}
	});
}

function gtbogoAiCoachLoad(){
	var fd=new FormData();
	fd.append("action","gtbogo_ai_get_report");
	fd.append("nonce",gtbogoAiN2);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){
		if(!d.success||!d.data.report||d.data.report==="")return;
		document.getElementById("ai-coach-report").style.display="block";
		document.getElementById("ai-coach-empty").style.display="none";
		var r=d.data.report;
		var html='<div style="font-size:14px;font-weight:700;color:var(--gt-white);margin-bottom:12px">Weekly Performance Report</div>';
		if(r.summary)html+='<div style="margin-bottom:12px;font-size:13px;color:var(--gt-soft);line-height:1.7">'+r.summary+'</div>';
		if(r.recommendations&&r.recommendations.length){
			html+='<div style="font-size:13px;font-weight:700;color:#E10000;margin-bottom:8px">Recommendations</div>';
			r.recommendations.forEach(function(rec){html+='<div style="padding:8px 12px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:6px;margin-bottom:6px;font-size:12px">'+rec+'</div>';});
		}
		document.getElementById("ai-coach-content").innerHTML=html;
	});
}

// ── Intelligence Engine ─────────────────────────────────────────────
function gtbogoAiIESetMode(){
	var mode=document.getElementById("ai-ie-mode").value;
	document.getElementById("ai-ie-rollout-wrap").style.display=mode==="rollout"?"block":"none";
	var fd=new FormData();
	fd.append("action","gtbogo_ai_set_mode");
	fd.append("nonce",gtbogoAiN2);
	fd.append("mode",mode);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"});
}

function gtbogoAiIESetRollout(){
	var pct=document.getElementById("ai-ie-rollout").value;
	document.getElementById("ai-ie-rollout-val").textContent=pct+"%";
	var fd=new FormData();
	fd.append("action","gtbogo_ai_set_rollout");
	fd.append("nonce",gtbogoAiN2);
	fd.append("pct",pct);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"});
}

function gtbogoAiIELoad(){
	var fd=new FormData();
	fd.append("action","gtbogo_ai_get_comparison_log");
	fd.append("nonce",gtbogoAiN2);
	fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"})
	.then(function(r){return r.json();})
	.then(function(d){
		if(!d.success)return;
		document.getElementById("ai-ie-mode").value=d.data.mode||"shadow";
		document.getElementById("ai-ie-rollout-wrap").style.display=d.data.mode==="rollout"?"block":"none";
		if(d.data.rollout_pct){
			document.getElementById("ai-ie-rollout").value=d.data.rollout_pct;
			document.getElementById("ai-ie-rollout-val").textContent=d.data.rollout_pct+"%";
		}
		if(d.data.log&&d.data.log.length){
			document.getElementById("ai-ie-log-wrap").style.display="block";
			var html="";
			d.data.log.forEach(function(e){
				html+='<tr><td style="font-size:10px;white-space:nowrap">'+(e.time||e.created_at||"")+'</td><td>'+(e.decision_type||"")+'</td><td style="font-size:10px">'+(e.classic||"")+'</td><td style="font-size:10px">'+(e.ai||"")+'</td><td style="font-weight:700;color:'+(e.winner==="ai"?"#22c55e":"#64748b")+'">'+(e.winner||"")+'</td></tr>';
			});
			document.getElementById("ai-ie-log-body").innerHTML=html;
		}
	});
}

// ── Load all on page load ───────────────────────────────────────────
document.addEventListener("DOMContentLoaded",function(){
	gtbogoAiCWLoadStatus();
	gtbogoAiGapLoad();
	gtbogoAiCoachLoad();
	gtbogoAiIELoad();
});
</script>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
