<?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 — White Label Manager
 *
 * Enterprise white label command center:
 *   - Master enable toggle with live status badge
 *   - Brand identity: plugin name, menu label, agency name, logo URL
 *   - Support & docs URL replacement
 *   - Email configuration: From name, From address, logo URL, accent color, email theme
 *   - Cart fee / line item label customization with live preview
 *   - Cart notice template customization
 *   - Per-superpower label overrides table (all 28 visual SPs)
 *   - CSS injection editor for custom admin styling
 *   - Hide branding + hide upgrade toggles
 *   - Export configuration as JSON
 *   - Import configuration from JSON
 *   - Reset to defaults with confirmation
 *   - Live admin sidebar preview (updates as you type)
 *   - Agency white label guide
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	wp_die( esc_html__( 'Insufficient permissions.', 'gt-bogo-engine' ) );
}

$is_pro       = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$nonce        = wp_create_nonce( 'gtbogo_white_label' );
$message      = '';
$message_type = 'success';

/* ── Handle save ─────────────────────────────────────────────────────────── */
if ( $is_pro && isset( $_POST['gtbogo_save_wl'] ) && check_admin_referer( 'gtbogo_white_label', 'gtbogo_wl_nonce' ) ) {
	$wl = array(
		'enabled'          => isset( $_POST['wl_enabled'] ),
		'plugin_name'      => sanitize_text_field( wp_unslash( $_POST['wl_plugin_name'] ?? 'GT BOGO Engine' ) ),
		'menu_label'       => sanitize_text_field( wp_unslash( $_POST['wl_menu_label'] ?? 'BOGO Engine' ) ),
		'agency_name'      => sanitize_text_field( wp_unslash( $_POST['wl_agency_name'] ?? '' ) ),
		'logo_url'         => esc_url_raw( wp_unslash( $_POST['wl_logo_url'] ?? '' ) ),
		'support_url'      => esc_url_raw( wp_unslash( $_POST['wl_support_url'] ?? '' ) ),
		'docs_url'         => esc_url_raw( wp_unslash( $_POST['wl_docs_url'] ?? '' ) ),
		'hide_branding'    => isset( $_POST['wl_hide_branding'] ),
		'hide_upgrade'     => isset( $_POST['wl_hide_upgrade'] ),
		'discount_name'    => sanitize_text_field( wp_unslash( $_POST['wl_discount_name'] ?? '' ) ),
		'cart_notice_text' => sanitize_textarea_field( wp_unslash( $_POST['wl_cart_notice'] ?? '' ) ),
		'custom_css'       => wp_strip_all_tags( wp_unslash( $_POST['wl_custom_css'] ?? '' ) ),
	);

	update_option( 'gtbogo_white_label', $wl );
	update_option( 'gtbogo_white_label_enabled', $wl['enabled'] );
	update_option( 'gtbogo_white_label_discount_name', $wl['discount_name'] );

	/* Save email settings */
	if ( ! empty( $_POST['wl_email_from_name'] ) ) {
		update_option( 'gtbogo_email_from_name', sanitize_text_field( wp_unslash( $_POST['wl_email_from_name'] ) ) );
		update_option( 'gtbogo_email_from_address', sanitize_email( wp_unslash( $_POST['wl_email_from_address'] ?? '' ) ) );
		update_option( 'gtbogo_email_logo_url', esc_url_raw( wp_unslash( $_POST['wl_email_logo_url'] ?? '' ) ) );
		update_option( 'gtbogo_email_accent_color', sanitize_hex_color( wp_unslash( $_POST['wl_email_accent'] ?? '#E10000' ) ) ?: '#E10000' );
	}

	/* Save SP label overrides */
	$sp_labels = array();
	foreach ( (array) ( $_POST['wl_sp_labels'] ?? array() ) as $slug => $lbl ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitize_key + sanitize_text_field inside loop
		$sp_labels[ sanitize_key( $slug ) ] = sanitize_text_field( $lbl );
	}
	update_option( 'gtbogo_wl_sp_labels', $sp_labels );

	$message = 'White label settings saved. Reload the page to see updated branding.';
}

/* ── Load settings ───────────────────────────────────────────────────────── */
$wl = get_option(
	'gtbogo_white_label',
	array(
		'enabled'          => false,
		'plugin_name'      => 'GT BOGO Engine',
		'menu_label'       => 'BOGO Engine',
		'agency_name'      => '',
		'logo_url'         => '',
		'support_url'      => '',
		'docs_url'         => '',
		'hide_branding'    => false,
		'hide_upgrade'     => false,
		'discount_name'    => '',
		'cart_notice_text' => '',
		'custom_css'       => '',
	)
);

$email_from_name = get_option( 'gtbogo_email_from_name', get_bloginfo( 'name' ) );
$email_from_addr = get_option( 'gtbogo_email_from_address', get_option( 'admin_email' ) );
$email_logo      = get_option( 'gtbogo_email_logo_url', '' );
$email_accent    = get_option( 'gtbogo_email_accent_color', '#E10000' );
$sp_labels       = get_option( 'gtbogo_wl_sp_labels', array() );

/* ── All 28 visual SPs for label overrides ───────────────────────────────── */
$all_sps = array(
	'abandon-nudge'        => 'Abandon Nudge',
	'announcement-bar'     => 'Announcement Bar',
	'badge-generator'      => 'Badge Generator',
	'bundle-configurator'  => 'Bundle Configurator',
	'bundle-spotlight'     => 'Bundle Spotlight',
	'cart-recommendations' => 'Cart Recommendations',
	'cart-recovery'        => 'Cart Recovery',
	'countdown-timer'      => 'Countdown Timer',
	'deal-comparison'      => 'Deal Comparison',
	'deal-share'           => 'Deal Share',
	'deal-unlock'          => 'Deal Unlock',
	'dynamic-pricing'      => 'Dynamic Pricing',
	'email-notifications'  => 'Email Notifications',
	'exit-intent'          => 'Exit Intent',
	'geo-banner'           => 'Geo Banner',
	'loyalty-widget'       => 'Loyalty Widget',
	'mobile-drawer'        => 'Mobile Drawer',
	'progress-bar'         => 'Cart Progress Bar',
	'quick-add'            => 'Quick Add',
	'referral-widget'      => 'Referral Widget',
	'savings-calculator'   => 'Savings Calculator',
	'savings-history'      => 'Savings History',
	'scarcity-bar'         => 'Scarcity Bar',
	'shipping-progress'    => 'Shipping Progress',
	'smart-popup'          => 'Smart Popup',
	'social-proof'         => 'Social Proof',
	'vip-badge'            => 'VIP Badge',
	'whatsapp-commerce'    => 'WhatsApp Commerce',
);

$wl_enabled = ! empty( $wl['enabled'] );

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">🏷️ White Label Manager</h1>
		<p class="gt-page-subtitle">
			Rebrand GT BOGO Engine for your clients — your name, your logo,
			your support links. Customers never see GT BOGO branding anywhere.
		</p>
	</div>
	<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
		<span class="gt-badge <?php echo $wl_enabled ? 'gt-badge-active' : 'gt-badge-free'; ?>">
			<?php echo $wl_enabled ? '● White Label Active' : '○ Default Branding'; ?>
		</span>
		<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
			onclick="gtWlExport('<?php echo esc_js( $nonce ); ?>')">
			↓ Export Config
		</button>
		<label class="gt-btn gt-btn-ghost gt-btn-sm" style="cursor:pointer">
			↑ Import Config
			<input type="file" accept=".json"
					onchange="gtWlImport(this,'<?php echo esc_js( $nonce ); ?>')"
					style="display:none">
		</label>
		<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
			onclick="gtWlReset('<?php echo esc_js( $nonce ); ?>')"
			style="border-color:rgba(239,68,68,0.3);color:#ef4444">
			↺ Reset
		</button>
	</div>
</div>

<?php if ( $message ) : ?>
<div class="gt-notice gt-notice-success gt-animate-in"><?php echo esc_html( $message ); ?></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>White Label Manager is an enterprise feature for agencies who resell this plugin under their own brand. Hide all GT BOGO Engine branding and replace it with your own.</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 : ?>

<form method="post" action="" id="gt-wl-form">
	<?php wp_nonce_field( 'gtbogo_white_label', 'gtbogo_wl_nonce' ); ?>

<!-- ── Two-column layout: settings left, preview right ──────────────── -->
<div style="display:grid;grid-template-columns:1fr 360px;gap:20px;align-items:start">
<div><!-- LEFT COLUMN -->

<!-- ═══════════════════════════════════════════════════════════════════════════
	MASTER TOGGLE
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-setting-row" style="border:none;padding:4px 0">
		<div>
			<div class="gt-setting-label" style="font-size:15px">Enable White Label Mode</div>
			<div class="gt-setting-desc">
				Activates all settings below. Clients see your branding, not GT BOGO Engine.
				The cart fee label, email sender name, and admin menu are all replaced.
			</div>
		</div>
		<label class="gt-toggle">
			<input type="checkbox" name="wl_enabled" value="1" id="gt-wl-master"
					onchange="gtWlUpdatePreview()"
					<?php checked( $wl_enabled ); ?>>
			<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
		</label>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	BRAND IDENTITY
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">🏷️ Brand Identity</h2></div>
	<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_plugin_name">Plugin Name</label>
			<input type="text" name="wl_plugin_name" id="wl_plugin_name" class="gt-input"
					value="<?php echo esc_attr( $wl['plugin_name'] ?? 'GT BOGO Engine' ); ?>"
					placeholder="Your Plugin Name"
					oninput="gtWlUpdatePreview()">
			<div class="gt-form-hint">Shown in the plugin list and admin menu header</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_menu_label">Admin Menu Label</label>
			<input type="text" name="wl_menu_label" id="wl_menu_label" class="gt-input"
					value="<?php echo esc_attr( $wl['menu_label'] ?? 'BOGO Engine' ); ?>"
					placeholder="Menu Label"
					oninput="gtWlUpdatePreview()">
			<div class="gt-form-hint">The left sidebar menu item label</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_agency_name">Agency / Company Name</label>
			<input type="text" name="wl_agency_name" id="wl_agency_name" class="gt-input"
					value="<?php echo esc_attr( $wl['agency_name'] ?? '' ); ?>"
					placeholder="Your Company Name"
					oninput="gtWlUpdatePreview()">
			<div class="gt-form-hint">Shown in plugin footer and about section</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_logo_url">Logo URL</label>
			<input type="url" name="wl_logo_url" id="wl_logo_url" class="gt-input"
					value="<?php echo esc_attr( $wl['logo_url'] ?? '' ); ?>"
					placeholder="https://yoursite.com/logo.png"
					oninput="gtWlUpdatePreview()">
			<div class="gt-form-hint">PNG/SVG recommended · 200×50px max for admin</div>
		</div>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	CART & CHECKOUT
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🛒 Cart & Checkout Labels</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">Replaces GT BOGO Engine text visible to customers</span>
	</div>
	<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_discount_name">Cart Fee / Discount Label</label>
			<input type="text" name="wl_discount_name" id="wl_discount_name" class="gt-input"
					value="<?php echo esc_attr( $wl['discount_name'] ?? '' ); ?>"
					placeholder="Buy 2 Get 1 Deal"
					oninput="gtWlUpdateCartPreview()">
			<div class="gt-form-hint">Line item label in WooCommerce cart. Empty = uses rule name.</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_cart_notice">Cart Notice Text (optional)</label>
			<textarea name="wl_cart_notice" id="wl_cart_notice" class="gt-input"
						style="height:70px;resize:vertical"
						placeholder="Add one more item to unlock your deal."
						oninput="gtWlUpdateCartPreview()"><?php echo esc_textarea( $wl['cart_notice_text'] ?? '' ); ?></textarea>
			<div class="gt-form-hint">Shown above the cart when a deal is active. Supports {discount_pct}, {deal_name}.</div>
		</div>
	</div>

	<!-- Cart line item preview -->
	<div style="margin-top:16px;padding:14px 16px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:8px">
		<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:10px">
			Cart Preview
		</div>
		<div style="background:#fff;border-radius:6px;padding:12px 16px;color:#1e293b">
			<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #e2e8f0;font-size:13px">
				<span>Graphic T-Shirt × 2</span><span>$59.98</span>
			</div>
			<div style="display:flex;justify-content:space-between;padding:6px 0;font-size:13px;color:#16a34a;font-weight:700" id="gt-wl-cart-label-preview">
				<span><?php echo $wl['discount_name'] ? esc_html( $wl['discount_name'] ) : 'Buy 2 Get 1 Deal'; ?></span>
				<span>-$29.99</span>
			</div>
			<div style="display:flex;justify-content:space-between;padding:6px 0;border-top:1px solid #e2e8f0;font-weight:700;font-size:14px;color:#0f172a">
				<span>Total</span><span>$29.99</span>
			</div>
		</div>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	EMAIL CONFIGURATION
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">✉️ Email Configuration</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">All BOGO emails sent from your brand</span>
	</div>
	<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_email_from_name">From Name</label>
			<input type="text" name="wl_email_from_name" id="wl_email_from_name" class="gt-input"
					value="<?php echo esc_attr( $email_from_name ); ?>"
					placeholder="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>">
			<div class="gt-form-hint">Shown as the sender name in email clients</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_email_from_address">From Address</label>
			<input type="email" name="wl_email_from_address" id="wl_email_from_address" class="gt-input"
					value="<?php echo esc_attr( $email_from_addr ); ?>"
					placeholder="noreply@yourstore.com">
			<div class="gt-form-hint">Replies will go here. Must match your sending domain.</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_email_logo_url">Email Header Logo URL</label>
			<input type="url" name="wl_email_logo_url" id="wl_email_logo_url" class="gt-input"
					value="<?php echo esc_attr( $email_logo ); ?>"
					placeholder="https://yourstore.com/email-logo.png">
			<div class="gt-form-hint">Shown at the top of all BOGO emails · 600px wide recommended</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_email_accent">Email Accent Color</label>
			<div style="display:flex;gap:8px;align-items:center">
				<input type="color" name="wl_email_accent" id="wl_email_accent"
						value="<?php echo esc_attr( $email_accent ); ?>"
						style="width:44px;height:36px;border:1px solid var(--gt-border);border-radius:6px;background:none;cursor:pointer;padding:2px">
				<input type="text" id="wl_email_accent_text" class="gt-input"
						value="<?php echo esc_attr( $email_accent ); ?>"
						placeholder="#E10000" maxlength="7"
						style="flex:1;font-family:'DM Mono','Courier New',monospace"
						oninput="document.getElementById('wl_email_accent').value=this.value">
			</div>
			<div class="gt-form-hint">Used for CTA buttons and highlights in all email themes</div>
		</div>
	</div>
	<!-- Colour picker sync -->
	<script>
	document.addEventListener('DOMContentLoaded',function(){
		var picker=document.getElementById('wl_email_accent');
		var text=document.getElementById('wl_email_accent_text');
		if(picker&&text){picker.addEventListener('input',function(){text.value=this.value;});}
	});
	</script>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	SUPPORT & DOCS LINKS
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🔗 Support & Documentation Links</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">All GT BOGO links replaced throughout the admin UI</span>
	</div>
	<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_support_url">Support URL</label>
			<input type="url" name="wl_support_url" id="wl_support_url" class="gt-input"
					value="<?php echo esc_attr( $wl['support_url'] ?? '' ); ?>"
					placeholder="https://youragency.com/support">
			<div class="gt-form-hint">Replaces all GT BOGO support links across the admin</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="wl_docs_url">Documentation URL</label>
			<input type="url" name="wl_docs_url" id="wl_docs_url" class="gt-input"
					value="<?php echo esc_attr( $wl['docs_url'] ?? '' ); ?>"
					placeholder="https://youragency.com/docs">
			<div class="gt-form-hint">Replaces the built-in documentation page link</div>
		</div>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	HIDE OPTIONS
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">🙈 Hide Options</h2></div>
	<?php
	$hide_opts = array(
		array(
			'wl_hide_branding',
			'hide_branding',
			'Hide GT BOGO Engine Branding',
			'Removes GT BOGO Engine logos, footer credits, and all brand references from the plugin admin. Clients see only your brand.',
		),
		array(
			'wl_hide_upgrade',
			'hide_upgrade',
			'Hide Upgrade / Purchase Prompts',
			'Removes all PRO upgrade CTAs, purchase links, and pricing mentions. Ideal when client is already on PRO.',
		),
	);
	foreach ( $hide_opts as $opt ) :
		?>
	<div class="gt-setting-row">
		<div>
			<div class="gt-setting-label"><?php echo esc_html( $opt[2] ); ?></div>
			<div class="gt-setting-desc"><?php echo esc_html( $opt[3] ); ?></div>
		</div>
		<label class="gt-toggle">
			<input type="checkbox" name="<?php echo esc_attr( $opt[0] ); ?>" value="1"
					<?php checked( ! empty( $wl[ $opt[1] ] ) ); ?>>
			<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
		</label>
	</div>
	<?php endforeach; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	SUPERPOWER LABEL OVERRIDES
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">⚡ Superpower Label Overrides</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">Rename any superpower in the admin UI — optional, leave blank to keep defaults</span>
	</div>
	<div style="max-height:340px;overflow-y:auto">
		<table style="width:100%;border-collapse:collapse;font-size:12px">
			<thead>
				<tr style="border-bottom:1px solid var(--gt-border);position:sticky;top:0;background:var(--gt-card);z-index:1">
					<th style="padding:9px 14px;text-align:left;font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">Superpower</th>
					<th style="padding:9px 14px;text-align:left;font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">Custom Label (optional)</th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $all_sps as $slug => $default_label ) :
				$current = $sp_labels[ $slug ] ?? '';
				?>
			<tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
				<td style="padding:7px 14px;color:var(--gt-white);font-weight:600">
					<?php echo esc_html( $default_label ); ?>
					<div style="font-size:10px;color:var(--gt-subtle);font-family:'DM Mono',monospace"><?php echo esc_html( $slug ); ?></div>
				</td>
				<td style="padding:7px 14px">
					<input type="text" name="wl_sp_labels[<?php echo esc_attr( $slug ); ?>]"
							class="gt-input" style="height:32px;font-size:12px"
							value="<?php echo esc_attr( $current ); ?>"
							placeholder="<?php echo esc_attr( $default_label ); ?>">
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	CUSTOM CSS INJECTION
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🎨 Custom Admin CSS</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">Injected into the admin head — override any admin styling</span>
	</div>
	<textarea name="wl_custom_css" class="gt-input"
				style="height:120px;resize:vertical;font-family:'DM Mono','Courier New',monospace;font-size:12px;line-height:1.6"
				placeholder="/* Your custom CSS here */&#10;.gt-brand-name { font-size: 14px; }&#10;:root { --gt-red: #0066cc; }"><?php echo esc_textarea( $wl['custom_css'] ?? '' ); ?></textarea>
	<div class="gt-form-hint" style="margin-top:6px">
		Use CSS variables to override colors: <code>--gt-red</code>, <code>--gt-card</code>, <code>--gt-bg</code>.
		Applied only to the GT BOGO admin pages.
	</div>
</div>

<!-- ── Save button ─────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in">
	<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
		<div>
			<div style="font-size:13px;font-weight:600;color:var(--gt-white)">Save White Label Configuration</div>
			<div style="font-size:12px;color:var(--gt-subtle);margin-top:2px">
				Changes take effect immediately. Reload to see updated admin branding.
			</div>
		</div>
		<button type="submit" name="gtbogo_save_wl" class="gt-btn gt-btn-primary" style="padding:12px 32px">
			💾 Save Settings
		</button>
	</div>
</div>

</div><!-- /LEFT COLUMN -->

<!-- ═══════════════════════════════════════════════════════════════════════════
	RIGHT COLUMN — LIVE PREVIEW
════════════════════════════════════════════════════════════════════════════ -->
<div>
	<div class="gt-card gt-animate-in" style="position:sticky;top:32px">
		<div class="gt-card-header">
			<h2 class="gt-card-title">👁 Live Preview</h2>
			<span style="font-size:11px;color:var(--gt-subtle)">Updates as you type</span>
		</div>

		<!-- Admin sidebar preview -->
		<div style="margin-bottom:16px">
			<div style="font-size:10px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;margin-bottom:8px">Admin Sidebar</div>
			<div style="background:#060d1f;border-radius:8px;padding:14px;border:1px solid rgba(255,255,255,0.06)">
				<!-- Brand section -->
				<div style="display:flex;align-items:center;gap:10px;padding-bottom:10px;border-bottom:1px solid rgba(255,255,255,0.06)">
					<div id="gt-wl-prev-logo"
						style="width:36px;height:36px;border-radius:7px;background:rgba(225,0,0,0.15);display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0">
						⚡
					</div>
					<div>
						<div id="gt-wl-prev-name" style="font-size:13px;font-weight:800;color:#fff;letter-spacing:1.5px;text-transform:uppercase">
							<?php echo esc_html( $wl['plugin_name'] ?? 'GT BOGO ENGINE' ); ?>
						</div>
						<div id="gt-wl-prev-agency" style="font-size:10px;color:#E10000;font-weight:700;letter-spacing:1px">
							<?php echo $wl['agency_name'] ? esc_html( strtoupper( $wl['agency_name'] ) ) : 'PRO'; ?>
						</div>
					</div>
				</div>
				<!-- Nav items -->
				<div style="padding-top:8px">
					<?php foreach ( array( 'Dashboard', 'Free Rule', 'PRO Rules', 'Superpowers', 'Settings' ) as $nav_item ) : ?>
					<div style="padding:6px 8px;border-radius:5px;font-size:11px;font-weight:600;color:#64748b;cursor:default">
						<?php echo esc_html( $nav_item ); ?>
					</div>
					<?php endforeach; ?>
					<div style="padding:6px 8px;border-radius:5px;font-size:11px;font-weight:600;color:var(--gt-subtle);border-left:2px solid #E10000">
						<span id="gt-wl-prev-menu"><?php echo esc_html( $wl['menu_label'] ?? 'BOGO Engine' ); ?></span> ◀
					</div>
				</div>
			</div>
		</div>

		<!-- Cart preview -->
		<div style="margin-bottom:16px">
			<div style="font-size:10px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;margin-bottom:8px">Cart Line Item</div>
			<div style="background:#fff;border-radius:6px;padding:10px 14px;border:1px solid rgba(0,0,0,0.1)">
				<div style="display:flex;justify-content:space-between;padding:4px 0;font-size:12px;color:#64748b">
					<span>T-Shirt Black × 2</span><span>$59.98</span>
				</div>
				<div style="display:flex;justify-content:space-between;padding:4px 0;font-size:12px;font-weight:700;color:#16a34a">
					<span id="gt-wl-prev-cart-label">
						<?php echo $wl['discount_name'] ? esc_html( $wl['discount_name'] ) : 'Buy 2 Get 1 Deal'; ?>
					</span>
					<span>−$29.99</span>
				</div>
				<div style="display:flex;justify-content:space-between;padding:4px 0;border-top:1px solid #e2e8f0;font-size:13px;font-weight:700;color:#0f172a">
					<span>Total</span><span>$29.99</span>
				</div>
			</div>
		</div>

		<!-- Status indicators -->
		<div>
			<div style="font-size:10px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;margin-bottom:8px">Configuration Status</div>
			<?php
			$status_checks = array(
				array( 'White Label', $wl_enabled ),
				array( 'Plugin Name', ! empty( $wl['plugin_name'] ) && $wl['plugin_name'] != 'GT BOGO Engine' ),
				array( 'Agency Name', ! empty( $wl['agency_name'] ) ),
				array( 'Logo Set', ! empty( $wl['logo_url'] ) ),
				array( 'Email From', ! empty( $email_from_name ) && $email_from_name != get_bloginfo( 'name' ) ),
				array( 'Cart Label', ! empty( $wl['discount_name'] ) ),
				array( 'Support URL', ! empty( $wl['support_url'] ) ),
			);
			foreach ( $status_checks as $sc ) :
				$sc_color = $sc[1] ? '#22c55e' : '#64748b';
				?>
			<div style="display:flex;align-items:center;justify-content:space-between;padding:5px 0;border-bottom:1px solid rgba(255,255,255,0.03)">
				<span style="font-size:11px;color:var(--gt-soft)"><?php echo esc_html( $sc[0] ); ?></span>
				<span style="font-size:11px;color:<?php echo esc_attr( $sc_color ); ?>;font-weight:700">
					<?php echo $sc[1] ? '✓ Set' : '○ Default'; ?>
				</span>
			</div>
			<?php endforeach; ?>
		</div>
	</div>
</div><!-- /RIGHT COLUMN -->

</div><!-- /grid -->

</form>

<!-- ═══════════════════════════════════════════════════════════════════════════
	AGENCY WHITE LABEL GUIDE (accordion)
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-top:20px">
	<div class="gt-card-header" onclick="gtWlToggleGuide()" style="cursor:pointer"
		onmouseover="this.style.background='rgba(255,255,255,0.02)'"
		onmouseout="this.style.background=''">
		<h2 class="gt-card-title">💡 Agency White Label Guide</h2>
		<span id="gt-wl-guide-arrow" style="color:var(--gt-subtle)">▸ Expand</span>
	</div>
	<div id="gt-wl-guide" style="display:none">
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:0 0 8px">
		<?php
		$guide = array(
			array( '🏷️', 'Naming Convention', 'Name the plugin something generic — "Promotions Manager" or "Deal Engine" works well. Your agency name in the footer gives you credit without exposing the underlying technology to clients.' ),
			array( '🔗', 'Support URL Strategy', 'Point the support URL to your own help desk, not GT BOGO support. You control the client relationship, filter issues before escalating, and can charge a retainer for ongoing support.' ),
			array( '💰', 'Pricing Your White Label', 'With a $499/yr PRO license you can charge clients $999–$1,499/yr for Promotions Manager PRO. Enable Hide Upgrade Prompts so clients never see competing purchase CTAs.' ),
			array( '📋', 'Client Onboarding', 'Use Import/Export to pre-configure rule templates per client vertical — fashion, food, electronics. Export your master config, import it on client sites, live in under 10 minutes.' ),
		);
		foreach ( $guide as $g ) :
			?>
		<div style="background:rgba(59,130,246,0.04);border:1px solid rgba(59,130,246,0.1);border-radius:10px;padding:16px">
			<div style="font-size:14px;font-weight:700;color:var(--gt-white);margin-bottom:8px">
				<?php echo esc_html( $g[0] ); ?> <?php echo esc_html( $g[1] ); ?>
			</div>
			<p style="font-size:12px;color:var(--gt-soft);line-height:1.6;margin:0"><?php echo esc_html( $g[2] ); ?></p>
		</div>
		<?php endforeach; ?>
		</div>
	</div>
</div>

<?php endif; // is_pro ?>

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

/* ── Live preview updates ────────────────────────────────────────────── */
window.gtWlUpdatePreview = function() {
	var name   = document.getElementById('wl_plugin_name')?.value || 'GT BOGO Engine';
	var menu   = document.getElementById('wl_menu_label')?.value  || 'BOGO Engine';
	var agency = document.getElementById('wl_agency_name')?.value || '';
	var logo   = document.getElementById('wl_logo_url')?.value    || '';

	var pName   = document.getElementById('gt-wl-prev-name');
	var pMenu   = document.getElementById('gt-wl-prev-menu');
	var pAgency = document.getElementById('gt-wl-prev-agency');
	var pLogo   = document.getElementById('gt-wl-prev-logo');

	if (pName)   pName.textContent   = name.toUpperCase();
	if (pMenu)   pMenu.textContent   = menu;
	if (pAgency) pAgency.textContent = agency ? agency.toUpperCase() : 'PRO';
	if (pLogo && logo) {
		pLogo.innerHTML = '<img src="'+logo+'" style="max-width:32px;max-height:32px;object-fit:contain" onerror="this.style.display=\'none\'">';
	}
};

window.gtWlUpdateCartPreview = function() {
	var label = document.getElementById('wl_discount_name')?.value || 'Buy 2 Get 1 Deal';
	var el1   = document.getElementById('gt-wl-prev-cart-label');
	var el2   = document.getElementById('gt-wl-cart-label-preview');
	if (el1) el1.textContent = label;
	if (el2) el2.querySelector('span:first-child').textContent = label;
};

/* ── Guide accordion ─────────────────────────────────────────────────── */
window.gtWlToggleGuide = function() {
	var guide = document.getElementById('gt-wl-guide');
	var arrow = document.getElementById('gt-wl-guide-arrow');
	if (!guide) return;
	var open = guide.style.display !== 'none';
	guide.style.display = open ? 'none' : 'block';
	if (arrow) arrow.textContent = open ? '▸ Expand' : '▾ Collapse';
};

/* ── Export config ───────────────────────────────────────────────────── */
window.gtWlExport = function(nonce) {
	window.open(ajaxurl+'?action=gtbogo_wl_export_config&nonce='+encodeURIComponent(nonce),'_blank');
};

/* ── Import config ───────────────────────────────────────────────────── */
window.gtWlImport = function(input, nonce) {
	var file = input.files[0];
	if (!file) return;
	var reader = new FileReader();
	reader.onload = function(e) {
		try {
			var cfg = JSON.parse(e.target.result);
			var fd  = new FormData();
			fd.append('action','gtbogo_wl_import_config');
			fd.append('nonce', nonce);
			fd.append('config', JSON.stringify(cfg));
			fetch(ajaxurl,{method:'POST',body:fd})
				.then(function(r){return r.json();})
				.then(function(resp){ if(resp.success) location.reload(); else alert(resp.data||'Import failed.'); });
		} catch(err) { alert('Invalid JSON: '+err.message); }
	};
	reader.readAsText(file);
};

/* ── Reset ───────────────────────────────────────────────────────────── */
window.gtWlReset = function(nonce) {
	if (!confirm('Reset all white label settings to defaults? This cannot be undone.')) return;
	var fd = new FormData();
	fd.append('action','gtbogo_wl_reset');
	fd.append('nonce', nonce);
	fetch(ajaxurl,{method:'POST',body:fd})
		.then(function(r){return r.json();})
		.then(function(resp){ if(resp.success) location.reload(); });
};

})();
</script>

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