<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO Engine — Superpowers Hub
 * Central control panel for all 50 superpowers (count computed dynamically).
 * Enable/disable, intensity, animation, and per-superpower config.
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

$message      = '';
$message_type = '';

// ── Save handler ──────────────────────────────────────────────────────────────
if ( isset( $_POST['gtbogo_sp_nonce'] ) && wp_verify_nonce( $_POST['gtbogo_sp_nonce'], 'gtbogo_sp_save' ) ) {
	$sp_ids = array(
		'progress_bar',
		'shipping_progress',
		'savings_calculator',
		'deal_comparison',
		'cart_recommendations',
		'email_notif',
		'loyalty_widget',
		'referral_widget',
		'savings_history',
		'dynamic_pricing',
		'bundle_configurator',
		'ltv_scoring',
		'inventory_intel',
		'revenue_guard',
		'webhook_triggers',
		'subscription_intel',
		'anniversary_intel',
		'birthday_intel',
		'post_purchase_intel',
		'multicurrency_intel',
		'geo_rules',
		'ab_testing',
		'streak_rewards',
		'customer_segments',
		'smart_scheduling',
		'profile_tracker',
		'vip_detection',
		'white_label',
		'countdown_timer',
		'social_proof',
		'scarcity_bar',
		'badge_generator',
		'bundle_spotlight',
		'deal_share',
		'deal_unlock',
		'announcement_bar',
		'mobile_drawer',
		'exit_intent',
		'abandon_nudge',
		'cart_recovery',
		'vip_badge',
		'geo_banner',
		'quick_add',
		'mini_cart_badge',
		'smart_popup',
		'whatsapp_commerce',
		'fomo',
		'nudges',
		'auto_add',
	);
	foreach ( $sp_ids as $id ) {
		update_option( 'gtbogo_sp_' . esc_html( $id ) . '_enabled', isset( $_POST[ 'sp_enabled_' . $id ] ) ? 1 : 0 );
		update_option( 'gtbogo_sp_' . esc_html( $id ) . '_anim', isset( $_POST[ 'sp_anim_' . $id ] ) ? 1 : 0 );
		$intensity = sanitize_text_field( $_POST[ 'sp_intensity_' . $id ] ?? 'subtle' );
		if ( in_array( $intensity, array( 'subtle', 'moderate', 'bold', 'off' ), true ) ) {
			update_option( 'gtbogo_sp_' . esc_html( $id ) . '_intensity', $intensity );
		}
		// Per-superpower extras
		foreach ( array( 'message', 'threshold', 'label', 'text' ) as $extra ) {
			$key = 'sp_' . esc_html( $extra ) . '_' . $id;
			if ( isset( $_POST[ $key ] ) ) {
				update_option( 'gtbogo_sp_' . esc_html( $id ) . '_' . $extra, sanitize_text_field( $_POST[ $key ] ) );
			}
		}
	}
	// Referral-specific
	update_option( 'gtbogo_sp_referral_widget_enabled', isset( $_POST['sp_enabled_referral_widget'] ) ? 1 : 0 );
	update_option( 'gtbogo_flash_email_enabled', isset( $_POST['flash_email_enabled'] ) ? 1 : 0 );
	update_option( 'gtbogo_sp_scarcity_bar_threshold', intval( $_POST['scarcity_threshold'] ?? 10 ) );
	update_option( 'gtbogo_sp_countdown_timer_message', sanitize_text_field( $_POST['countdown_message'] ?? '' ) );

	$message      = 'Superpower settings saved.';
	$message_type = 'success';
}

// ── Superpower definitions ────────────────────────────────────────────────────
$superpowers = array(
	array(
		'section'      => 'Cart Intelligence',
		'section_desc' => 'Backend superpowers that operate silently in the cart and checkout. Zero frontend injection. Zero theme conflicts.',
		'items'        => array(
			array(
				'id'    => 'progress_bar',
				'name'  => 'Cart Progress Bar',
				'icon'  => '📊',
				'desc'  => 'Shows customers how close they are to unlocking a deal inside the cart totals area. AJAX-refreshed on every cart update. Cart page only — never injects into product pages.',
				'hooks' => 'woocommerce_before_cart_totals',
				'best'  => 'Threshold and quantity deals',
				'extra' => array(),
			),
			array(
				'id'    => 'shipping_progress',
				'name'  => 'Shipping Progress',
				'icon'  => '🚚',
				'desc'  => 'Shows customers how close they are to free shipping. Auto-detects WooCommerce Free Shipping zone threshold. AJAX-refreshed on cart update. The #1 reason for cart abandonment is unexpected shipping costs — this superpower eliminates it.',
				'hooks' => 'woocommerce_before_cart_totals',
				'best'  => 'All stores with free shipping threshold',
				'extra' => array(),
			),
			array(
				'id'    => 'savings_calculator',
				'name'  => 'Savings Calculator',
				'icon'  => '💰',
				'desc'  => 'Shows the exact amount saved in the cart totals area. "You saved $X" — real-time calculated from active rule discount. Cart and checkout pages only.',
				'hooks' => 'woocommerce_cart_totals_after_order_total',
				'best'  => 'All deal types',
				'extra' => array(),
			),
			array(
				'id'    => 'deal_comparison',
				'name'  => 'Deal Comparison',
				'icon'  => '🔄',
				'desc'  => 'Before/after price comparison in cart totals showing savings as a percentage and absolute amount. Helps customers understand what the deal is worth.',
				'hooks' => 'woocommerce_cart_totals_after_order_total',
				'best'  => 'Percentage and fixed deals',
				'extra' => array(),
			),
			array(
				'id'    => 'cart_recommendations',
				'name'  => 'Cart Recommendations',
				'icon'  => '🛒',
				'desc'  => 'Suggests qualifying products inside the cart when the customer is close to unlocking a deal. Pulls from active rule product and category scope. No UI injection outside cart.',
				'hooks' => 'woocommerce_after_cart_contents',
				'best'  => 'Buy X Get Y deals',
				'extra' => array(),
			),
		),
	),
	array(
		'section'      => 'Customer Lifecycle',
		'section_desc' => 'Backend superpowers that track and respond to customer behaviour over time. All run via WP-Cron or order hooks — zero page-load overhead.',
		'items'        => array(
			array(
				'id'    => 'email_notif',
				'name'  => 'Email Notifications',
				'icon'  => '📧',
				'desc'  => 'Triggers white-labelled lifecycle emails from the store owner\'s own email address when BOGO events occur at order completion. Zero GT BOGO branding visible to customers.',
				'hooks' => 'woocommerce_order_status_completed',
				'best'  => 'All deal types',
				'extra' => array(),
			),
			array(
				'id'    => 'loyalty_widget',
				'name'  => 'Loyalty Tier Tracking',
				'icon'  => '🏆',
				'desc'  => 'Tracks customer loyalty tier in user meta and applies tier-specific rules automatically. Tiers: Silver ($500 LTV), Gold ($1,000 LTV), VIP ($2,500 LTV). Works with Customer LTV Scoring.',
				'hooks' => 'woocommerce_order_status_completed',
				'best'  => 'VIP and loyalty deals',
				'extra' => array(),
			),
			array(
				'id'    => 'referral_widget',
				'name'  => 'Referral Attribution',
				'icon'  => '🔗',
				'desc'  => 'Backend referral tracking via URL parameter and cookie. Attributes conversions to referrers, increments referral count, and triggers referral reward emails automatically.',
				'hooks' => 'template_redirect, woocommerce_thankyou',
				'best'  => 'Referral reward deals',
				'extra' => array(),
			),
			array(
				'id'    => 'savings_history',
				'name'  => 'Savings History',
				'icon'  => '📚',
				'desc'  => 'Records cumulative BOGO savings per customer in user meta. Used by the customer intelligence system and available for export in the PDF report.',
				'hooks' => 'woocommerce_order_status_completed',
				'best'  => 'All deal types',
				'extra' => array(),
			),
			array(
				'id'    => 'dynamic_pricing',
				'name'  => 'Dynamic Pricing',
				'icon'  => '💸',
				'desc'  => 'Backend price adjustment engine for role-based and segment-based pricing rules. Adjusts rule discount values based on customer role before cart calculation fires.',
				'hooks' => 'gtbogo_rule_discount_value',
				'best'  => 'VIP and role-gated deals',
				'extra' => array(),
			),
			array(
				'id'    => 'bundle_configurator',
				'name'  => 'Bundle Configurator',
				'icon'  => '⚙️',
				'desc'  => 'Backend logic for bundle rule validation. Verifies that a cart meets bundle composition requirements before applying a bundle discount. Works with bundle-builder pack rules.',
				'hooks' => 'woocommerce_before_calculate_totals',
				'best'  => 'Bundle deals',
				'extra' => array(),
			),
		),
	),
	array(
		'section'      => 'Visual Frontend Superpowers',
		'section_desc' => '15 visual superpowers powered by the Orchestrator + Theme Intelligence + Signal Bus. Auto-adapt to every theme via CSS token system. WCAG 2.5.5 compliant. Full mobile breakpoints.',
		'items'        => array(
			array(
				'id'    => 'countdown_timer',
				'name'  => 'Countdown Timer',
				'icon'  => '⏱',
				'desc'  => 'Live countdown timer tied to deal expiry. Renders with full design token inheritance — radius, weight, tracking, shadow — matching the active theme automatically. Creates measurable urgency without cheap tactics.',
				'hooks' => 'woocommerce_before_cart_totals',
				'best'  => 'Flash sales, timed deals',
				'extra' => array(),
			),
			array(
				'id'    => 'social_proof',
				'name'  => 'Social Proof',
				'icon'  => '👥',
				'desc'  => 'Real-time messaging showing other shoppers are using the same deal. Signal Bus driven — copy escalates automatically at high urgency scores. Returns naturally for VIP customers.',
				'hooks' => 'woocommerce_before_cart',
				'best'  => 'High-traffic stores',
				'extra' => array(),
			),
			array(
				'id'    => 'scarcity_bar',
				'name'  => 'Scarcity Bar',
				'icon'  => '📉',
				'desc'  => 'Visual inventory scarcity indicator. Appends real-time Signal Bus urgency copy when stock signals are high. Purely additive — never injects aggressive UI.',
				'hooks' => 'woocommerce_before_cart',
				'best'  => 'Low-stock campaigns',
				'extra' => array(),
			),
			array(
				'id'    => 'badge_generator',
				'name'  => 'Badge Generator',
				'icon'  => '🏷',
				'desc'  => 'Deal badges on product images and cart rows using the full design token system. Signal Bus appends HOT suffix at high urgency. Margin Intelligence suppresses if cart already heavily discounted.',
				'hooks' => 'woocommerce_before_shop_loop_item_title',
				'best'  => 'All deal types',
				'extra' => array(),
			),
			array(
				'id'    => 'bundle_spotlight',
				'name'  => 'Bundle Spotlight',
				'icon'  => '🔦',
				'desc'  => 'Product bundle suggestion panel on single product pages. Signal Bus drives urgency headline. Profile Tracker prepends Your curated bundle for returning customers. Full token rendering.',
				'hooks' => 'woocommerce_after_single_product_summary',
				'best'  => 'Bundle deals',
				'extra' => array(),
			),
			array(
				'id'    => 'deal_share',
				'name'  => 'Deal Share',
				'icon'  => '🔗',
				'desc'  => 'Social share button for active deals. Copy personalises via Signal Bus urgency and Profile Tracker returning-customer detection. Appears on product pages and cart.',
				'hooks' => 'woocommerce_after_add_to_cart_button',
				'best'  => 'Viral campaigns',
				'extra' => array(),
			),
			array(
				'id'    => 'deal_unlock',
				'name'  => 'Deal Unlock Toast',
				'icon'  => '✅',
				'desc'  => 'Confirmation toast when a deal is applied. Signal Bus appends beat-the-rush copy at high signal. LTV Intelligence shows Platinum or Member acknowledgment for high-value customers.',
				'hooks' => 'wp_footer',
				'best'  => 'All deal types',
				'extra' => array(),
			),
			array(
				'id'    => 'announcement_bar',
				'name'  => 'Announcement Bar',
				'icon'  => '📣',
				'desc'  => 'Dismissible announcement bar on cart and checkout. Signal Bus appends urgency suffix at two threshold levels. Profile Tracker prepends Welcome back for returning customers.',
				'hooks' => 'woocommerce_before_cart',
				'best'  => 'Flash events, launches',
				'extra' => array(),
			),
			array(
				'id'    => 'mobile_drawer',
				'name'  => 'Mobile Deal Drawer',
				'icon'  => '📱',
				'desc'  => 'Slide-up deal summary drawer for mobile visitors. Signal Bus shows urgency line. Profile Tracker personalises sub-copy for returning customers. Fully token-rendered.',
				'hooks' => 'wp_footer',
				'best'  => 'Mobile-first stores',
				'extra' => array(),
			),
			array(
				'id'    => 'exit_intent',
				'name'  => 'Exit Intent',
				'icon'  => '🚪',
				'desc'  => 'Backend exit detection that triggers a retention offer when cursor leaves the viewport. RFM Intelligence skips high-retention customers who return naturally — never spam loyal buyers.',
				'hooks' => 'wp_footer',
				'best'  => 'Cart abandonment',
				'extra' => array(),
			),
			array(
				'id'    => 'abandon_nudge',
				'name'  => 'Abandon Nudge',
				'icon'  => '🔔',
				'desc'  => 'In-page nudge shown when a customer lingers without checking out. Signal Bus drives urgency title at high signal. RFM Intelligence switches to retention copy for loyal customers.',
				'hooks' => 'wp_footer',
				'best'  => 'High cart-abandon stores',
				'extra' => array(),
			),
			array(
				'id'    => 'cart_recovery',
				'name'  => 'Cart Recovery Email',
				'icon'  => '📧',
				'desc'  => 'Schedules a personalised cart recovery email 60 minutes after a logged-in customer abandons their cart with an active BOGO deal. RFM Intelligence skips high-retention customers who return naturally.',
				'hooks' => 'wp_footer, gtbogo_check_cart_abandonment',
				'best'  => 'Cart abandonment',
				'extra' => array(),
			),
			array(
				'id'    => 'vip_badge',
				'name'  => 'VIP Badge',
				'icon'  => '👑',
				'desc'  => 'Displays a VIP status badge and tier-aware hint copy in the cart. LTV-aware — Platinum customers see exclusive deal acknowledgment, VIP customers see member copy, Gold customers see recognition.',
				'hooks' => 'woocommerce_before_cart_totals',
				'best'  => 'Loyalty and VIP stores',
				'extra' => array(),
			),
			array(
				'id'    => 'geo_banner',
				'name'  => 'Geo Banner',
				'icon'  => '🌍',
				'desc'  => 'Location-specific deal messaging using WooCommerce native geolocation. Detects customer country and shows a matching deal banner. Assigns geo zone WordPress roles to logged-in customers — used as rule conditions for country-specific discounts. No IP lookup frontend injection.',
				'hooks' => 'wp_footer',
				'best'  => 'Multi-market stores',
				'extra' => array(),
			),
			array(
				'id'    => 'quick_add',
				'name'  => 'Quick Add',
				'icon'  => '⚡',
				'desc'  => 'Enhances add-to-cart flow with deal-aware CTAs. Signal Bus urgency escalates the label at high signal scores. LTV/RFM awards tier-aware CTA copy. Profile Tracker personalises for returning customers. WCAG 2.5.5 compliant touch targets on mobile.',
				'hooks' => 'woocommerce_loop_add_to_cart_link',
				'best'  => 'All deal types',
				'extra' => array(),
			),
			array(
				'id'    => 'mini_cart_badge',
				'name'  => 'Mini-Cart Badge',
				'icon'  => '🛒',
				'desc'  => 'Shows live deal status in the WooCommerce mini-cart and off-canvas drawer. Active state: green dot with savings amount. Inactive state: gray dot with add N more message. Signal Bus timing_confidence drives urgency copy. LTV/RFM awards VIP copy variant. Cart fragment wired for instant AJAX updates. aria-live polite. Respects prefers-reduced-motion.',
				'hooks' => 'woocommerce_before_mini_cart, woocommerce_add_to_cart_fragments',
				'best'  => 'All deal types',
				'extra' => array(),
			),
			array(
				'id'    => 'deal_banner',
				'name'  => 'Deal Banner',
				'icon'  => '📢',
				'desc'  => 'Dismissible site-wide announcement bar showing the active BOGO deal. Orchestrator intensity controls page scope: subtle = cart + checkout, moderate = + shop + category, bold = all pages including product singles. AI Copywriter generates brand-voice messages. sessionStorage dismiss. Signal Bus wired. prefers-reduced-motion compliant.',
				'hooks' => 'wp_footer, wp_enqueue_scripts',
				'best'  => 'All deal types — highest visibility superpower',
				'extra' => array(),
			),
			array(
				'id'    => 'smart_popup',
				'name'  => 'Smart Popup',
				'icon'  => '💬',
				'desc'  => 'Contextual deal popup with four configurable triggers: cart deal applied, idle timer, scroll depth, and page visit count. Session-capped — fires once per visit maximum. Orchestrator-gated and Signal Bus wired — suppresses automatically for platinum and returning VIP archetypes. Theme Intelligence controls animation profile and intensity.',
				'hooks' => 'wp_footer',
				'best'  => 'Cart abandonment recovery',
				'extra' => array(),
			),
			array(
				'id'    => 'whatsapp_commerce',
				'name'  => 'WhatsApp Commerce',
				'icon'  => '📱',
				'desc'  => 'WhatsApp deal sharing with configurable Business Hours mode — restricts display to your store operating hours so customers contact you when you are available. Signal Bus drives urgency copy at high signal scores. Cart and checkout only — never fires on product or shop pages.',
				'hooks' => 'wp_footer',
				'best'  => 'Mobile-first and direct commerce stores',
				'extra' => array(),
			),
		),
	),
	array(
		'section'      => 'Backend Intelligence',
		'section_desc' => '17 invisible backend engines on WP-Cron and order hooks. All write to the Signal Bus. Zero frontend output. Zero theme conflicts.',
		'items'        => array(
			array(
				'id'      => 'ltv_scoring',
				'name'    => 'LTV Scoring',
				'icon'    => '&#x1F4C8;',
				'desc'    => 'Scores customers by LTV and assigns tiers automatically.',
				'hooks'   => 'woocommerce_order_status_completed',
				'best'    => 'VIP deals',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'inventory_intel',
				'name'    => 'Inventory Intelligence',
				'icon'    => '&#x1F4E6;',
				'desc'    => 'Adjusts BOGO multipliers based on stock levels to protect margin.',
				'hooks'   => 'woocommerce_product_set_stock',
				'best'    => 'Clearance deals',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'revenue_guard',
				'name'    => 'Revenue Guard',
				'icon'    => '&#x1F6E1;',
				'desc'    => 'Pauses BOGO rules when discount depth exceeds margin thresholds.',
				'hooks'   => 'gtbogo_revenue_guard_check',
				'best'    => 'High-volume stores',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'webhook_triggers',
				'name'    => 'Webhook Triggers',
				'icon'    => '&#x1F50C;',
				'desc'    => 'Fires webhooks on BOGO events to Zapier, Make, and more.',
				'hooks'   => 'gtbogo_order_bogo_applied',
				'best'    => 'Automation platforms',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'subscription_intel',
				'name'    => 'Subscription Detection',
				'icon'    => '&#x1F504;',
				'desc'    => 'Applies subscriber rules on subscription status changes.',
				'hooks'   => 'woocommerce_subscription_status_active',
				'best'    => 'Subscription stores',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'anniversary_intel',
				'name'    => 'Anniversary Intelligence',
				'icon'    => '&#x1F382;',
				'desc'    => 'Fires anniversary deals automatically via WP-Cron.',
				'hooks'   => 'gtbogo_anniversary_check',
				'best'    => 'Retention campaigns',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'birthday_intel',
				'name'    => 'Birthday Intelligence',
				'icon'    => '&#x1F381;',
				'desc'    => 'Fires birthday deals based on customer stored birth date.',
				'hooks'   => 'woocommerce_order_status_completed',
				'best'    => 'Loyalty campaigns',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'post_purchase_intel',
				'name'    => 'Post-Purchase Intelligence',
				'icon'    => '&#x1F9E0;',
				'desc'    => 'Builds product affinity maps from purchase history.',
				'hooks'   => 'woocommerce_order_status_completed',
				'best'    => 'Cross-sell rules',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'multicurrency_intel',
				'name'    => 'Multi-Currency Optimizer',
				'icon'    => '&#x1F4B1;',
				'desc'    => 'Adjusts BOGO values for currency conversion across all currencies.',
				'hooks'   => 'gtbogo_rule_discount_value',
				'best'    => 'International stores',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'geo_rules',
				'name'    => 'Geo Rules Engine',
				'icon'    => '&#x1F30D;',
				'desc'    => 'Applies geo-targeted BOGO rules based on customer country.',
				'hooks'   => 'gtbogo_customer_eligible',
				'best'    => 'Multi-market stores',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'ab_testing',
				'name'    => 'A/B Testing Engine',
				'icon'    => '&#x1F9EA;',
				'desc'    => 'Splits customers into groups to measure BOGO deal performance.',
				'hooks'   => 'gtbogo_customer_eligible',
				'best'    => 'Optimising deals',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'streak_rewards',
				'name'    => 'Streak Rewards Engine',
				'icon'    => '&#x1F525;',
				'desc'    => 'Fires escalating rewards at consecutive purchase milestones.',
				'hooks'   => 'woocommerce_thankyou',
				'best'    => 'Repeat purchases',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'customer_segments',
				'name'    => 'Customer Segmentation',
				'icon'    => '&#x1F465;',
				'desc'    => 'Segments customers into cohorts for targeted BOGO rules.',
				'hooks'   => 'woocommerce_order_status_completed',
				'best'    => 'Personalised promos',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'smart_scheduling',
				'name'    => 'Smart Scheduling Engine',
				'icon'    => '&#x1F4C5;',
				'desc'    => 'Runs all WP-Cron BOGO jobs on intelligent conflict-free schedules.',
				'hooks'   => 'WP-Cron multiple schedules',
				'best'    => 'All stores',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'profile_tracker',
				'name'    => 'Customer Profile Tracker',
				'icon'    => '&#x1F464;',
				'desc'    => 'Full behavioural profile per customer including tier streak and LTV.',
				'hooks'   => 'Multiple WC hooks',
				'best'    => 'All stores',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'vip_detection',
				'name'    => 'VIP Detection',
				'icon'    => '&#x2B50;',
				'desc'    => 'Assigns VIP role automatically based on LTV thresholds.',
				'hooks'   => 'woocommerce_order_status_completed',
				'best'    => 'Luxury stores',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'white_label',
				'name'    => 'White Label Engine',
				'icon'    => '&#x1F3F7;',
				'desc'    => 'Removes all GT BOGO branding from customer-facing output.',
				'hooks'   => 'Multiple output filters',
				'best'    => 'All stores',
				'extra'   => array(),
				'backend' => true,
			),
		),
	),
	array(
		'section'      => 'Behavioral Superpowers',
		'section_desc' => 'Autonomous behavioral engines that run on wp and plugins_loaded hooks. Wired to the Orchestrator and Signal Bus — fire only when intelligence confirms eligibility.',
		'items'        => array(
			array(
				'id'      => 'fomo',
				'name'    => 'FOMO Engine',
				'icon'    => '&#x1F525;',
				'desc'    => 'Timing Intelligence peak-window aware FOMO messaging. Lifecycle-aware delay — 3000ms in hot windows, 8000ms in cold. Gamification pulse ring on AI/bold themes. Signal Bus gated — suppresses below score threshold.',
				'hooks'   => 'wp_footer',
				'best'    => 'High-intent sessions',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'nudges',
				'name'    => 'Smart Nudges',
				'icon'    => '&#x1F514;',
				'desc'    => 'Streak Bonus integration with progress bar inside nudge. Shop banner with Signal Bus urgency suffix. Three copy tiers driven by Orchestrator copy_tone. Suppressed for platinum_returning and at_risk archetypes.',
				'hooks'   => 'wp_footer, woocommerce_before_shop_loop',
				'best'    => 'All stores',
				'extra'   => array(),
				'backend' => true,
			),
			array(
				'id'      => 'auto_add',
				'name'    => 'Auto Add',
				'icon'    => '&#x1F6D2;',
				'desc'    => 'Automatically adds qualifying free items to cart when deal threshold is met. Signal Bus gated — skips if composite score below 1.0. Margin gated — skips if margin ratio below 0.35. LTV/RFM eligibility check. Inventory Intelligence stockout guard.',
				'hooks'   => 'woocommerce_before_calculate_totals',
				'best'    => 'Buy X Get Y free deals',
				'extra'   => array(),
				'backend' => true,
			),
		),
	),
);

require_once __DIR__ . '/../ui-system/wrapper-start.php';
$is_pro = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">⚡ Superpowers</h1>
		<?php $total_sp = array_sum( array_map( fn( $s ) => count( $s['items'] ), $superpowers ) ); ?>
		<p class="gt-page-subtitle"><?php echo esc_html( $total_sp ); ?> superpowers — Orchestrator-driven, theme-intelligent, Signal Bus wired</p>
	</div>
	<div style="display:flex;gap:10px;align-items:center">
		<?php
		$total_enabled = 0;
		foreach ( $superpowers as $sec ) {
			foreach ( $sec['items'] as $sp ) {
				if ( get_option( 'gtbogo_sp_' . $sp['id'] . '_enabled', 0 ) ) {
					++$total_enabled;
				}
			}
		}
		?>
		<span class="gt-badge gt-badge-active"><?php echo esc_html( $total_enabled ); ?>/<?php echo esc_html( $total_sp ); ?> <?php esc_html_e( 'active', 'gt-bogo-engine' ); ?></span>
	</div>
</div>

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

<form method="post">
<?php wp_nonce_field( 'gtbogo_sp_save', 'gtbogo_sp_nonce' ); ?>

<?php foreach ( $superpowers as $section ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:28px">
	<div class="gt-card-header" style="border-bottom:1px solid var(--gt-border);padding-bottom:20px;margin-bottom:0">
		<div>
			<h2 class="gt-card-title"><?php echo esc_html( $section['section'] ); ?></h2>
			<p class="gt-text-soft" style="font-size:13px"><?php echo esc_html( $section['section_desc'] ); ?></p>
		</div>
		<?php
		$sec_active = 0;
		foreach ( $section['items'] as $sp ) {
			if ( get_option( 'gtbogo_sp_' . $sp['id'] . '_enabled', 0 ) ) {
				++$sec_active;
			}
		}
		?>
		<span class="gt-badge <?php echo $sec_active > 0 ? 'gt-badge-active' : 'gt-badge-free'; ?>">
			<?php echo esc_html( $sec_active ); ?>/<?php echo esc_html( count( $section['items'] ) ); ?> <?php esc_html_e( 'active', 'gt-bogo-engine' ); ?>
		</span>
	</div>

	<?php
	foreach ( $section['items'] as $idx => $sp ) :
		$enabled   = (bool) get_option( 'gtbogo_sp_' . esc_html( $sp['id'] ) . '_enabled', 0 );
		$anim      = (bool) get_option( 'gtbogo_sp_' . esc_html( $sp['id'] ) . '_anim', 0 );
		$intensity = get_option( 'gtbogo_sp_' . esc_html( $sp['id'] ) . '_intensity', 'subtle' );
		$is_last   = $idx === count( $section['items'] ) - 1;
		?>
	<div style="padding:24px;<?php echo ! $is_last ? 'border-bottom:1px solid var(--gt-border);' : ''; ?>">
		<div style="display:grid;grid-template-columns:1fr auto;gap:20px;align-items:center">

			<!-- Left: Info + config -->
			<div>
				<div style="display:flex;align-items:center;gap:10px;margin-bottom:8px;flex-wrap:wrap">
					<span style="font-size:22px"><?php echo esc_html( $sp['icon'] ); ?></span>
					<h3 style="margin:0;color:var(--gt-white);font-size:16px;font-weight:700"><?php echo esc_html( $sp['name'] ); ?></h3>
					<span class="gt-sp-status-badge"
							data-sp-id="<?php echo esc_attr( $sp['id'] ); ?>"
							style="font-size:11px;font-weight:700;padding:2px 10px;border-radius:999px;letter-spacing:.04em;transition:all .2s;<?php echo $enabled ? 'background:rgba(34,197,94,0.15);border:1px solid rgba(34,197,94,0.4);color:#4ade80' : 'display:none'; ?>">
						<?php echo $enabled ? 'Active' : ''; ?>
					</span>
				</div>

				<p style="color:var(--gt-subtle);font-size:13px;line-height:1.65;margin:0 0 12px;max-width:680px"><?php echo esc_html( $sp['desc'] ); ?></p>

				<div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:<?php echo ! empty( $sp['extra'] ) ? '14px' : '0'; ?>">
					<span style="font-size:13px;color:var(--gt-subtle)">
						<strong style="color:var(--gt-soft)">Hooks:</strong> <?php echo esc_html( $sp['hooks'] ); ?>
					</span>
					<span style="font-size:13px;color:var(--gt-subtle)">
						<strong style="color:var(--gt-soft)">Best for:</strong> <?php echo esc_html( $sp['best'] ); ?>
					</span>
				</div>

				<!-- Extra config fields -->
				<?php if ( ! empty( $sp['extra'] ) ) : ?>
				<div style="display:flex;gap:12px;flex-wrap:wrap;margin-top:12px">
					<?php
					foreach ( $sp['extra'] as [$fname, $flabel, $fdesc, $fdefault] ) :
						$fval = get_option( 'gtbogo_sp_' . $sp['id'] . '_' . str_replace( 'sp_' . '' . $sp['id'] . '_', '', $fname ), $fdefault );
						// Actually just use a direct option read
						$opt_key = 'gtbogo_sp_' . esc_html( $sp['id'] ) . '_' . explode( '_', $fname, 2 )[0];
						// Use fname directly as the post key
						?>
					<div>
						<div style="font-size:13px;font-weight:600;color:var(--gt-soft);margin-bottom:4px"><?php echo esc_html( $flabel ); ?></div>
						<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:6px"><?php echo esc_html( $fdesc ); ?></div>
						<input type="<?php echo is_numeric( $fdefault ) ? 'number' : 'text'; ?>"
								name="<?php echo esc_attr( $fname ); ?>"
								class="gt-input"
								style="max-width:180px;font-size:13px"
								value="<?php echo esc_attr( get_option( 'gtbogo_sp_' . $sp['id'] . '_' . explode( '_', $fname )[0], $fdefault ) ); ?>"
								placeholder="<?php echo esc_attr( $fdefault ); ?>" id="gtbogo___php_echo_esc_attr__fdefault_" aria-label="<?php echo esc_attr( $fdefault ); ?>">
					</div>
					<?php endforeach; ?>
				</div>
				<?php endif; ?>
			</div>

			<?php if ( empty( $sp['backend'] ) ) : ?>
			<!-- Right: Controls — 3-col grid, borders on middle col, no divider cells -->
			<div class="gt-sp-controls" data-sp="<?php echo esc_attr( $sp['id'] ); ?>"
				style="display:grid;grid-template-columns:100px 220px 100px;grid-template-rows:14px 24px;row-gap:8px;align-items:center;flex-shrink:0;margin-left:32px;border-left:1px solid var(--gt-border);transition:opacity .2s;<?php echo ! $enabled ? 'opacity:.45' : ''; ?>">

				<!-- Row 1: Labels — sequential placement, no gaps, guaranteed alignment -->
				<div style="display:flex;justify-content:center;align-items:center">
					<span style="font-size:10px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.08em">Enable</span>
				</div>
				<div style="display:flex;justify-content:center;align-items:center;border-left:1px solid var(--gt-border);border-right:1px solid var(--gt-border)">
					<span style="font-size:10px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.08em">Intensity</span>
				</div>
				<div style="display:flex;justify-content:center;align-items:center">
					<span style="font-size:10px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.08em">Animate</span>
				</div>

				<!-- Row 2: Controls — same grid columns = pixel-perfect alignment -->
				<div style="display:flex;justify-content:center;align-items:center;height:24px">
					<label class="gt-toggle gt-toggle-green" style="margin:0">
						<input type="checkbox" name="sp_enabled_<?php echo esc_attr( $sp['id'] ); ?>" value="1" <?php checked( $enabled ); ?>>
						<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
					</label>
				</div>
				<div style="display:flex;justify-content:center;align-items:center;border-left:1px solid var(--gt-border);border-right:1px solid var(--gt-border);height:24px;display:flex;align-items:center;justify-content:center">
					<?php
					$intensities = array(
						'subtle'   => 'Subtle',
						'moderate' => 'Moderate',
						'bold'     => 'Bold',
						'off'      => 'Off',
					);
					?>
					<div class="gt-intensity-group" style="display:flex;gap:4px;align-items:center;height:24px;margin:0;padding:0">
						<?php foreach ( $intensities as $val => $lbl ) : ?>
						<button type="button"
							onclick="gtSetIntensity(this,'<?php echo esc_js( $sp['id'] ); ?>','<?php echo esc_js( $val ); ?>')"
							data-val="<?php echo esc_attr( $val ); ?>"
							style="display:inline-flex;align-items:center;justify-content:center;height:24px;padding:0 9px;font-size:10px;font-weight:600;border-radius:4px;cursor:pointer;white-space:nowrap;letter-spacing:.03em;transition:all .15s;border:1px solid;margin:0;box-sizing:border-box;vertical-align:middle;<?php echo $intensity === $val ? 'background:#16a34a;border-color:#22c55e;color:#fff' : 'background:rgba(255,255,255,0.05);border-color:rgba(255,255,255,0.12);color:#64748b'; ?>">
							<?php echo esc_html( $lbl ); ?>
						</button>
						<?php endforeach; ?>
						<input type="hidden" name="sp_intensity_<?php echo esc_attr( $sp['id'] ); ?>" class="gt-intensity-val" value="<?php echo esc_attr( $intensity ); ?>">
					</div>
				</div>
				<div style="display:flex;justify-content:center;align-items:center;height:24px">
					<label class="gt-toggle" style="margin:0">
						<input type="checkbox" name="sp_anim_<?php echo esc_attr( $sp['id'] ); ?>" value="1" <?php checked( $anim ); ?>>
						<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
					</label>
				</div>

			</div>
			<?php else : ?>
			<div style="display:flex;align-items:center;flex-shrink:0;margin-left:32px;border-left:1px solid var(--gt-border);padding-left:24px">
				<div style="display:flex;flex-direction:column;align-items:center;gap:8px">
					<span style="font-size:10px;color:#64748b;font-weight:700;text-transform:uppercase">Enable</span>
					<label class="gt-toggle gt-toggle-green" style="margin:0">
						<input type="checkbox" name="sp_enabled_<?php echo esc_attr( $sp['id'] ); ?>" value="1" <?php checked( $enabled ); ?>>
						<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
					</label>
				</div>
			</div>
			<?php endif; ?>
		</div>
	</div>
	<?php endforeach; ?>
</div>
<?php endforeach; ?>

<!-- Global settings -->
<div class="gt-card gt-animate-in" style="margin-bottom:28px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📉 Global Superpower Settings</h2>
	</div>
	<div class="gt-card-body">
		<div class="gt-setting-row">
			<div>
				<div class="gt-setting-label"><?php esc_html_e( 'Flash Sale Broadcast Emails', 'gt-bogo-engine' ); ?></div>
				<div class="gt-setting-desc"><?php esc_html_e( 'When a flash sale rule is activated in Pro Rules, automatically broadcast an email to recent customers. Requires Customer Emails enabled in Settings.', 'gt-bogo-engine' ); ?></div>
			</div>
			<label class="gt-toggle">
				<input type="checkbox" name="flash_email_enabled" value="1" <?php checked( get_option( 'gtbogo_flash_email_enabled', 0 ) ); ?>>
				<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
			</label>
		</div>
		<div class="gt-setting-row" style="border:none">
			<div>
				<div class="gt-setting-label"><?php esc_html_e( 'Countdown Timer Default Message', 'gt-bogo-engine' ); ?></div>
				<div class="gt-setting-desc"><?php esc_html_e( 'Default text shown before the countdown clock when no rule-specific message is set.', 'gt-bogo-engine' ); ?></div>
			</div>
			<input type="text" name="countdown_message" class="gt-input" style="max-width:240px"
					value="<?php echo esc_attr( get_option( 'gtbogo_sp_countdown_timer_message', __( 'Deal ends in', 'gt-bogo-engine' ) ) ); ?>"
					placeholder="<?php esc_attr_e( 'Deal ends in', 'gt-bogo-engine' ); ?>" id="gtbogo_countdown_message" aria-label="Countdown Message">
		</div>
	</div>
</div>

<div style="display:flex;gap:12px;align-items:center;padding-bottom:40px">
	<button type="submit" class="gt-btn gt-btn-primary">Save All Superpower Settings</button>
	<span style="font-size:13px;color:var(--gt-subtle)"><?php esc_html_e( 'Settings apply immediately on save. No cache flush required.', 'gt-bogo-engine' ); ?></span>
</div>

</form>




<script>
(function() {
	var nonce = '<?php echo esc_js( wp_create_nonce( 'gt_bogo_sp_toggle' ) ); ?>';
	var ajaxUrl = '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>';

	// Expose saveSP for global gtSetIntensity access
	window._gtSaveSP = function(sp_id, field, value) {
		saveSP(sp_id, field, value, function(){});
	};

	function saveSP(sp_id, field, value, callback) {
		var data = new FormData();
		data.append('action',  'gt_bogo_save_superpower_field');
		data.append('nonce',   nonce);
		data.append('sp_id',   sp_id);
		data.append('field',   field);
		data.append('value',   value);
		fetch(ajaxUrl, { method:'POST', body:data, credentials:'same-origin' })
		.then(function(r){ return r.json(); })
		.then(function(res){
			if (res.success) {
				if (field === 'enabled' && window.gtBogoSPBroadcast) {
					gtBogoSPBroadcast(sp_id, value === '1');
				}
				if (callback) callback(true);
			} else {
				if (callback) callback(false);
			}
		})
		.catch(function(){ if (callback) callback(false); });
	}

	function getSpId(el) {
		var name = el.name || '';
		// sp_enabled_cart_progress_bar -> cart_progress_bar
		var m = name.match(/^sp_(?:enabled|intensity|anim)_(.+)$/);
		return m ? m[1] : null;
	}

	function showFeedback(el, ok) {
		// Feedback handled by wrapper-start.php global tick handler
		// No local tick here to prevent double-tick + card height jump
	}

	document.addEventListener('DOMContentLoaded', function() {
		// Hide Save button — all saves are now instant
		var saveBtn = document.querySelector('button[type="submit"].gt-btn-primary');
		if (saveBtn) {
			saveBtn.style.display = 'none';
			// Add live-save indicator next to where button was
			var ind = document.createElement('div');
			ind.style.cssText = 'font-size:13px;color:var(--gt-subtle);padding:10px 0';
			ind.textContent = 'All changes save instantly';
			saveBtn.parentNode.insertBefore(ind, saveBtn);
		}

		// Enable toggles
		document.querySelectorAll('input[name^="sp_enabled_"]').forEach(function(el) {
			el.addEventListener('change', function() {
				var sp_id = getSpId(el);
				if (!sp_id) return;
				saveSP(sp_id, 'enabled', el.checked ? '1' : '0', function(ok) {
					showFeedback(el, ok);
					if (!ok) return;
					var isOn = el.checked;

					// Dim Intensity+Animate cols when disabled — clear UX signal
					var ctrlWrap = document.querySelector('.gt-sp-controls[data-sp="' + sp_id + '"]');
					if (ctrlWrap) ctrlWrap.style.opacity = isOn ? '1' : '.45';

					// Update inline Active badge for this row
					var row = el.closest('div[style*="padding:24px"]');
					if (row) {
						var statusBadge = row.querySelector('.gt-sp-status-badge[data-sp-id="' + sp_id + '"]');
						if (statusBadge) {
							if (isOn) {
								statusBadge.textContent = 'Active';
								statusBadge.style.cssText = 'font-size:11px;font-weight:700;padding:2px 10px;border-radius:999px;letter-spacing:.04em;transition:all .2s;background:rgba(34,197,94,0.15);border:1px solid rgba(34,197,94,0.4);color:#4ade80';
							} else {
								statusBadge.textContent = '';
								statusBadge.style.display = 'none';
							}
						}
					}

					// Update top-right active count (9/25 active)
					var totalActive = document.querySelectorAll('input[name^="sp_enabled_"]:checked').length;
					var headerBadge = document.querySelector('.gt-page-header .gt-badge-active');
					if (headerBadge) headerBadge.textContent = totalActive + '/50 active';

					// Update section badge (4/4 active)
					var section = el.closest('.gt-card');
					if (section) {
						var secActive = section.querySelectorAll('input[name^="sp_enabled_"]:checked').length;
						var secTotal  = section.querySelectorAll('input[name^="sp_enabled_"]').length;
						var secBadge  = section.querySelector('.gt-card-header .gt-badge');
						if (secBadge) secBadge.textContent = secActive + '/' + secTotal + ' active';
					}
				});
			});
		});

		// Intensity selects
		document.querySelectorAll('select[name^="sp_intensity_"]').forEach(function(el) {
			el.addEventListener('change', function() {
				var sp_id = getSpId(el);
				if (!sp_id) return;
				saveSP(sp_id, 'intensity', el.value, function(ok) {
					showFeedback(el, ok);
					// Update intensity preview bars and label
					// Intensity updated via dropdown — no preview bar
				});
			});
		});

		// Animate toggles
		document.querySelectorAll('input[name^="sp_anim_"]').forEach(function(el) {
			el.addEventListener('change', function() {
				var sp_id = getSpId(el);
				if (!sp_id) return;
				saveSP(sp_id, 'animate', el.checked ? '1' : '0', function(ok) {
					showFeedback(el, ok);
				});
			});
		});
	});
})();

// Global scope — accessible from onclick attributes
window.gtSetIntensity = function(btn, sp_id, val) {
	var group = btn.closest('.gt-intensity-group');
	if (!group) return;
	// Update button visual states
	group.querySelectorAll('button[data-val]').forEach(function(b) {
		var on = b.dataset.val === val;
		b.style.background  = on ? '#16a34a' : 'rgba(255,255,255,0.05)';
		b.style.borderColor = on ? '#22c55e' : 'rgba(255,255,255,0.12)';
		b.style.color       = on ? '#fff'    : '#64748b';
	});
	// Update hidden input value
	var hidden = group.querySelector('.gt-intensity-val');
	if (hidden) hidden.value = val;
	// AJAX save — saveSP is defined in the IIFE above and exposed on window
	if (typeof window._gtSaveSP === 'function') {
		window._gtSaveSP(sp_id, 'intensity', val);
	}
};
</script>

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