<?php


if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class AIEO_Consent {

	const COOKIE         = 'aieo_consent';
	const POLICY_VERSION = 1; 
	const SCAN_NONCE     = 'aieo_consent_scan';

	
	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	
	
	

	public static function settings() {
		$o = get_option( 'aieo_consent_settings', array() );
		if ( ! is_array( $o ) ) {
			$o = array();
		}
		return array_merge( array(
			'enabled'        => 'no',       
			'eea_only'       => 'yes',      
			'default_state'  => 'denied',   
			'title'          => '',
			'message'        => '',         

			
			'layout'         => 'bar',      
			'policy_version' => 1,          

			
			'desc_necessary'  => '',
			'desc_functional' => '',
			'desc_analytics'  => '',
			'desc_marketing'  => '',

			
			
			
			
			
			'reopen_enabled'         => 'yes',
			'reopen_label'           => '',
			'reopen_pos_desktop'     => 'left',  
			'reopen_x_desktop'       => 86,      
			'reopen_bottom_desktop'  => 20,      
			'reopen_pos_mobile'      => 'left',
			'reopen_x_mobile'        => 86,
			'reopen_bottom_mobile'   => 20,

			
			
			
			
			
			'cookie_scan'    => 'yes',
			
			
			
			'cookie_scan_days' => 30,

			
			'logo'           => '',

			
			'bar_bg'         => '#1f2937',
			'bar_text_color' => '#ffffff',  
			'bar_text_size'  => '18px',
			'bar_desc_color' => '#d1d5db',  
			'bar_desc_size'  => '14px',
			'bar_link_color' => '#fbbf24',  

			
			
			
			'btn_accept_bg'            => '#111827',
			'btn_accept_fg'            => '#ffffff',
			'btn_accept_border'        => '#111827',
			'btn_accept_bg_hover'      => '#374151',
			'btn_accept_fg_hover'      => '#ffffff',
			'btn_accept_border_hover'  => '#374151',
			'btn_decline_bg'           => '#ffffff',
			'btn_decline_fg'           => '#111827',
			'btn_decline_border'       => '#111827',
			'btn_decline_bg_hover'     => '#f3f4f6',
			'btn_decline_fg_hover'     => '#111827',
			'btn_decline_border_hover' => '#111827',
			'btn_customize_bg'           => 'transparent',
			'btn_customize_fg'           => '#374151',
			'btn_customize_border'       => '#d1d5db',
			'btn_customize_bg_hover'     => '#f9fafb',
			'btn_customize_fg_hover'     => '#111827',
			'btn_customize_border_hover' => '#9ca3af',

			
			'cookie_overrides' => array(),
		), $o );
	}

	
	private static function policy_version() {
		$v = (int) self::settings()['policy_version'];
		return $v > 0 ? $v : self::POLICY_VERSION;
	}

	
	
	

	
	public static function allows( $category ) {
		if ( 'necessary' === $category ) {
			return true;
		}
		$state = self::cookie_state();
		if ( null !== $state ) {
			return ! empty( $state[ $category ] );
		}
		
		
		if ( 'personalize' === $category ) {
			return false;
		}
		
		$s = self::settings();
		if ( 'yes' === $s['eea_only'] && self::is_eea() ) {
			return false;
		}
		return 'granted' === $s['default_state'];
	}

	
	public static function has_choice() {
		return null !== self::cookie_state();
	}

	
	public static function is_enabled_here() {
		$s = self::settings();
		if ( 'yes' !== $s['enabled'] ) {
			return false;
		}
		if ( 'yes' === $s['eea_only'] && ! self::is_eea() ) {
			return false;
		}
		return true;
	}

	
	private static function cookie_state() {
		if ( empty( $_COOKIE[ self::COOKIE ] ) ) {
			return null;
		}
		$raw = json_decode( stripslashes( sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE ] ) ) ), true );
		if ( ! is_array( $raw ) ) {
			return null;
		}
		
		
		$stored_v = isset( $raw['v'] ) ? (int) $raw['v'] : 0;
		if ( $stored_v < self::policy_version() ) {
			return null;
		}
		return array(
			'functional'  => ! empty( $raw['functional'] ),
			'analytics'   => ! empty( $raw['analytics'] ),
			'marketing'   => ! empty( $raw['marketing'] ),
			'personalize' => ! empty( $raw['personalize'] ),
		);
	}

	
	private static function is_eea() {
		$cc = '';
		foreach ( array( 'HTTP_CF_IPCOUNTRY', 'GEOIP_COUNTRY_CODE', 'HTTP_X_COUNTRY_CODE' ) as $h ) {
			if ( ! empty( $_SERVER[ $h ] ) ) {
				$cc = strtoupper( substr( sanitize_text_field( wp_unslash( $_SERVER[ $h ] ) ), 0, 2 ) );
				break;
			}
		}
		if ( '' === $cc ) {
			return true; 
		}
		$eea = array( 'AT','BE','BG','HR','CY','CZ','DK','EE','FI','FR','DE','GR','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','RO','SK','SI','ES','SE','IS','LI','NO','GB','CH' );
		return in_array( $cc, $eea, true );
	}

	
	
	

	
	public static function ads_consent_state() {
		if ( self::has_choice() ) {
			return self::allows( 'marketing' ) ? 'granted' : 'denied';
		}
		return 'unspecified';
	}

	
	public static function ads_consent_for_order( $order ) {
		if ( is_a( $order, 'WC_Order' ) ) {
			$m = (string) $order->get_meta( '_aieo_ads_consent' );
			if ( 'granted' === $m || 'denied' === $m || 'unspecified' === $m ) {
				return $m;
			}
		}
		return self::ads_consent_state();
	}

	
	public function capture_ads_consent( $order ) {
		if ( is_numeric( $order ) && function_exists( 'wc_get_order' ) ) {
			$order = wc_get_order( (int) $order );
		}
		if ( ! is_a( $order, 'WC_Order' ) ) {
			return;
		}
		if ( '' !== (string) $order->get_meta( '_aieo_ads_consent' ) ) {
			return;
		}
		$order->update_meta_data( '_aieo_ads_consent', self::ads_consent_state() );
		
		
		if ( 'woocommerce_checkout_create_order' !== current_action() ) {
			$order->save();
		}
	}

	
	
	

	public function register() {
		
		
		add_action( 'admin_init', array( $this, 'maybe_install_log' ) );
		add_action( 'admin_init', array( $this, 'maybe_install_cookies_table' ) );
		add_action( 'wp_ajax_aieo_consent_log', array( $this, 'ajax_log' ) );
		add_action( 'wp_ajax_nopriv_aieo_consent_log', array( $this, 'ajax_log' ) );
		add_action( 'wp_ajax_aieo_consent_scan', array( $this, 'ajax_scan' ) );
		add_action( 'wp_ajax_nopriv_aieo_consent_scan', array( $this, 'ajax_scan' ) );

		
		
		
		add_action( 'woocommerce_checkout_create_order', array( $this, 'capture_ads_consent' ), 30, 1 );
		add_action( 'woocommerce_store_api_checkout_order_processed', array( $this, 'capture_ads_consent' ), 30, 1 );

		
		
		
		
		
		
		add_filter( 'rocket_delay_js_exclusions', array( $this, 'rocket_js_exclusions' ) );
		add_filter( 'rocket_exclude_defer_js', array( $this, 'rocket_js_exclusions' ) );

		if ( 'yes' !== self::settings()['enabled'] ) {
			return; 
		}
		add_action( 'wp_head', array( $this, 'consent_mode_default' ), 1 );
		add_action( 'wp_footer', array( $this, 'render_banner' ), 5 );
		if ( 'yes' === self::settings()['reopen_enabled'] ) {
			add_action( 'wp_footer', array( $this, 'render_reopen' ), 6 );
		}
	}

	
	public function rocket_js_exclusions( $excluded ) {
		$excluded = is_array( $excluded ) ? $excluded : array();
		foreach ( array(
			'aieoConsent',              
			'aieo-cmp',                 
			'aieo-consent-mode',        
			'aieo-attribution-client',  
			'aieo-session-tracker',     
		) as $needle ) {
			$excluded[] = $needle;
		}
		return $excluded;
	}

	
	
	

	public static function log_table() {
		global $wpdb;
		return $wpdb->prefix . 'aieo_consent_log';
	}

	
	public function maybe_install_log() {
		global $wpdb;
		$t = self::log_table();
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) === $t ) {
			return;
		}
		$cc  = function_exists( 'aieo_get_charset_collate' ) ? aieo_get_charset_collate() : $wpdb->get_charset_collate();
		$sql = "CREATE TABLE IF NOT EXISTS `{$t}` (
			`id` bigint unsigned NOT NULL AUTO_INCREMENT,
			`session_id` varchar(64) DEFAULT NULL,
			`user_id` bigint unsigned NOT NULL DEFAULT 0,
			`functional` tinyint(1) NOT NULL DEFAULT 0,
			`analytics` tinyint(1) NOT NULL DEFAULT 0,
			`marketing` tinyint(1) NOT NULL DEFAULT 0,
			`policy_version` smallint unsigned NOT NULL DEFAULT 0,
			`ip_hash` varchar(64) DEFAULT NULL,
			`ua_hash` varchar(64) DEFAULT NULL,
			`source` varchar(24) NOT NULL DEFAULT 'banner',
			`created_at` datetime DEFAULT NULL,
			PRIMARY KEY (`id`),
			KEY `session_id` (`session_id`),
			KEY `created_at` (`created_at`)
		) {$cc};";
		if ( function_exists( 'aieo_dbdelta' ) ) {
			aieo_dbdelta( $sql );
		} else {
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
			dbDelta( $sql );
		}
	}

	
	public function ajax_log() {
		global $wpdb;
		$t = self::log_table();
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
			wp_send_json_success();
		}
		$sid = '';
		foreach ( array( 'aieo_attr_sid', 'aieo_session_id' ) as $ck ) {
			if ( ! empty( $_COOKIE[ $ck ] ) ) {
				$sid = sanitize_text_field( wp_unslash( $_COOKIE[ $ck ] ) );
				break;
			}
		}
		$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
		$ua = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';

		$source = isset( $_POST['source'] ) ? sanitize_key( wp_unslash( $_POST['source'] ) ) : 'banner';
		if ( '' === $source ) {
			$source = 'banner';
		}

		$wpdb->insert( $t, array(
			'session_id'     => '' !== $sid ? $sid : null,
			'user_id'        => get_current_user_id(),
			'functional'     => ! empty( $_POST['functional'] ) ? 1 : 0,
			'analytics'      => ! empty( $_POST['analytics'] ) ? 1 : 0,
			'marketing'      => ! empty( $_POST['marketing'] ) ? 1 : 0,
			'policy_version' => self::policy_version(),
			'ip_hash'        => '' !== $ip ? hash( 'sha256', $ip ) : null,
			'ua_hash'        => '' !== $ua ? hash( 'sha256', $ua ) : null,
			'source'         => substr( $source, 0, 24 ),
			'created_at'     => current_time( 'mysql', true ),
		) );
		wp_send_json_success();
	}

	
	
	

	public static function cookies_table() {
		global $wpdb;
		return $wpdb->prefix . 'aieo_consent_cookies';
	}

	
	public function maybe_install_cookies_table() {
		global $wpdb;
		$t = self::cookies_table();
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) === $t ) {
			return;
		}
		$cc  = function_exists( 'aieo_get_charset_collate' ) ? aieo_get_charset_collate() : $wpdb->get_charset_collate();
		$sql = "CREATE TABLE IF NOT EXISTS `{$t}` (
			`id` bigint unsigned NOT NULL AUTO_INCREMENT,
			`name` varchar(191) NOT NULL,
			`service` varchar(120) DEFAULT NULL,
			`category` varchar(20) DEFAULT NULL,
			`description` varchar(255) DEFAULT NULL,
			`status` varchar(16) NOT NULL DEFAULT 'auto',
			`hits` bigint unsigned NOT NULL DEFAULT 0,
			`pre_consent` tinyint(1) NOT NULL DEFAULT 0,
			`first_seen` datetime DEFAULT NULL,
			`last_seen` datetime DEFAULT NULL,
			PRIMARY KEY (`id`),
			UNIQUE KEY `name` (`name`),
			KEY `category` (`category`),
			KEY `status` (`status`)
		) {$cc};";
		if ( function_exists( 'aieo_dbdelta' ) ) {
			aieo_dbdelta( $sql );
		} else {
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
			dbDelta( $sql );
		}
	}

	
	public static function classify_cookie( $name ) {
		$name = (string) $name;
		if ( '' === $name ) {
			return null;
		}

		
		$overrides = self::settings()['cookie_overrides'];
		if ( is_array( $overrides ) && ! empty( $overrides ) ) {
			$best = null;
			$len  = -1;
			foreach ( $overrides as $pattern => $meta ) {
				$pattern = (string) $pattern;
				if ( self::pattern_matches( $pattern, $name ) && strlen( $pattern ) > $len ) {
					$best = $meta;
					$len  = strlen( $pattern );
				}
			}
			if ( is_array( $best ) ) {
				return array(
					'service'     => isset( $best['service'] ) ? (string) $best['service'] : '',
					'category'    => isset( $best['category'] ) ? (string) $best['category'] : '',
					'description' => '',
				);
			}
		}

		
		if ( ! function_exists( 'aieo_consent_known_cookies' ) ) {
			require_once __DIR__ . '/data/known-cookies.php';
		}
		$best  = null;
		$score = -1;
		foreach ( aieo_consent_known_cookies() as $row ) {
			$pattern = (string) $row[0];
			$match   = (string) $row[1];
			$hit     = ( 'exact' === $match ) ? ( $name === $pattern ) : ( 0 === strpos( $name, $pattern ) );
			if ( ! $hit ) {
				continue;
			}
			$s = ( strlen( $pattern ) * 2 ) + ( 'exact' === $match ? 1 : 0 );
			if ( $s > $score ) {
				$score = $s;
				$best  = $row;
			}
		}
		if ( is_array( $best ) ) {
			return array( 'service' => $best[2], 'category' => $best[3], 'description' => $best[4] );
		}
		return null;
	}

	
	private static function pattern_matches( $pattern, $name ) {
		if ( '' === $pattern ) {
			return false;
		}
		if ( '*' === substr( $pattern, -1 ) ) {
			return 0 === strpos( $name, substr( $pattern, 0, -1 ) );
		}
		return $name === $pattern;
	}

	
	public function ajax_scan() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, self::SCAN_NONCE ) ) {
			wp_send_json_error();
		}
		global $wpdb;
		$t = self::cookies_table();
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
			wp_send_json_success();
		}
		$names    = isset( $_POST['names'] ) ? (array) wp_unslash( $_POST['names'] ) : array();
		$services = isset( $_POST['services'] ) ? (array) wp_unslash( $_POST['services'] ) : array();
		$pre      = ! empty( $_POST['pre_consent'] ) ? 1 : 0;
		$now      = current_time( 'mysql', true );

		if ( ! function_exists( 'aieo_consent_service_hosts' ) ) {
			require_once __DIR__ . '/data/known-cookies.php';
		}
		$host_map = aieo_consent_service_hosts();

		$count = 0;
		foreach ( $names as $name ) {
			if ( $count >= 60 ) {
				break;
			}
			$name = sanitize_text_field( $name );
			if ( '' === $name || ! preg_match( '/^[A-Za-z0-9_\-.]{1,191}$/', $name ) ) {
				continue;
			}
			self::upsert_cookie( $name, self::classify_cookie( $name ), $pre, $now );
			$count++;
		}
		foreach ( $services as $host ) {
			if ( $count >= 60 ) {
				break;
			}
			$host = sanitize_text_field( $host );
			if ( '' === $host || ! isset( $host_map[ $host ] ) ) {
				continue;
			}
			$m = $host_map[ $host ];
			self::upsert_cookie( 'svc:' . $host, array(
				'service'     => $m['service'],
				'category'    => $m['category'],
				'description' => isset( $m['description'] ) ? $m['description'] : '',
			), $pre, $now );
			$count++;
		}
		wp_send_json_success();
	}

	
	private static function upsert_cookie( $name, $cls, $pre, $now ) {
		global $wpdb;
		$t           = self::cookies_table();
		$service     = ( is_array( $cls ) && ! empty( $cls['service'] ) ) ? (string) $cls['service'] : '';
		$category    = ( is_array( $cls ) && ! empty( $cls['category'] ) ) ? (string) $cls['category'] : '';
		$description = ( is_array( $cls ) && ! empty( $cls['description'] ) ) ? (string) $cls['description'] : '';
		$status      = '' !== $category ? 'auto' : 'unclassified';

		
		$wpdb->query( $wpdb->prepare(
			"INSERT INTO `{$t}` (name, service, category, description, status, hits, pre_consent, first_seen, last_seen)
			 VALUES (%s, %s, %s, %s, %s, 1, %d, %s, %s)
			 ON DUPLICATE KEY UPDATE
			   hits = hits + 1,
			   last_seen = VALUES(last_seen),
			   pre_consent = GREATEST(pre_consent, VALUES(pre_consent)),
			   service = IF(status = 'reviewed', service, VALUES(service)),
			   category = IF(status = 'reviewed', category, VALUES(category)),
			   description = IF(status = 'reviewed', description, VALUES(description)),
			   status = IF(status = 'reviewed', 'reviewed', VALUES(status))",
			$name, $service, $category, $description, $status, $pre, $now, $now
		) );
	}

	
	public static function get_inventory() {
		global $wpdb;
		$t = self::cookies_table();
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
			return array();
		}
		
		$rows = $wpdb->get_results( "SELECT * FROM `{$t}` ORDER BY category ASC, hits DESC, name ASC" );
		$out  = array( 'necessary' => array(), 'functional' => array(), 'analytics' => array(), 'marketing' => array(), 'unclassified' => array() );
		foreach ( (array) $rows as $r ) {
			$cat = isset( $out[ $r->category ] ) ? $r->category : 'unclassified';
			$out[ $cat ][] = $r;
		}
		return $out;
	}

	
	public static function review_cookie( $name, $category, $service ) {
		global $wpdb;
		$t = self::cookies_table();
		$wpdb->update(
			$t,
			array(
				'category' => $category,
				'service'  => '' !== $service ? $service : null,
				'status'   => 'reviewed',
			),
			array( 'name' => $name )
		);
		$s  = self::settings();
		$ov = is_array( $s['cookie_overrides'] ) ? $s['cookie_overrides'] : array();
		$ov[ $name ] = array( 'category' => $category, 'service' => $service );
		$s['cookie_overrides'] = $ov;
		update_option( 'aieo_consent_settings', $s, false );
	}

	
	public static function clear_inventory() {
		global $wpdb;
		$t = self::cookies_table();
		
		$wpdb->query( "TRUNCATE TABLE `{$t}`" );
	}

	
	
	

	
	public function consent_mode_default() {
		
		
		
		
		
		
		
		
		$s            = self::settings();
		$region_aware = ( 'yes' === $s['eea_only'] && 'granted' === $s['default_state'] );
		?>
<script id="aieo-consent-mode" data-cfasync="false">
window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}
<?php if ( $region_aware ) :
		$eea = array( 'AT','BE','BG','HR','CY','CZ','DK','EE','FI','FR','DE','GR','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','RO','SK','SI','ES','SE','IS','LI','NO','GB','CH' ); ?>
gtag('consent','default',{'ad_storage':'denied','analytics_storage':'denied','ad_user_data':'denied','ad_personalization':'denied','region':<?php echo wp_json_encode( $eea ); ?>,'wait_for_update':500});
gtag('consent','default',{'ad_storage':'granted','analytics_storage':'granted','ad_user_data':'granted','ad_personalization':'granted'});
<?php else :
		$g = ( 'granted' === $s['default_state'] && 'yes' !== $s['eea_only'] ) ? 'granted' : 'denied'; ?>
gtag('consent','default',{'ad_storage':'<?php echo esc_js( $g ); ?>','analytics_storage':'<?php echo esc_js( $g ); ?>','ad_user_data':'<?php echo esc_js( $g ); ?>','ad_personalization':'<?php echo esc_js( $g ); ?>','wait_for_update':500});
<?php endif; ?>
</script>
		<?php
	}

	
	
	

	
	private static function color( $val ) {
		
		
		if ( class_exists( 'AIEO_Admin_Color' ) ) {
			return AIEO_Admin_Color::sanitize( $val );
		}
		$val = trim( (string) $val );
		if ( '' === $val ) {
			return '';
		}
		if ( 'transparent' === strtolower( $val ) ) {
			return 'transparent';
		}
		if ( preg_match( '/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $val ) ) {
			return $val;
		}
		return '';
	}

	
	private static function button_css_vars( $s ) {
		$buttons = array( 'accept', 'decline', 'customize' );
		$fields  = array(
			'bg'           => 'bg',
			'fg'           => 'fg',
			'border'       => 'border',
			'bg_hover'     => 'bg-h',
			'fg_hover'     => 'fg-h',
			'border_hover' => 'border-h',
		);
		$parts = array();
		foreach ( $buttons as $b ) {
			foreach ( $fields as $key => $css ) {
				$val = isset( $s[ 'btn_' . $b . '_' . $key ] ) ? self::color( $s[ 'btn_' . $b . '_' . $key ] ) : '';
				if ( '' === $val ) {
					continue;
				}
				$parts[] = '--aieo-cmp-' . $b . '-' . $css . ':' . $val;
			}
		}
		return implode( ';', $parts );
	}

	
	private static function len( $v ) {
		$v = trim( (string) $v );
		return preg_match( '/^[0-9]{1,3}(\.[0-9]{1,2})?(px|rem|em|%)?$/', $v ) ? $v : '';
	}

	
	private static function bar_css_vars( $s ) {
		$parts = array();
		foreach ( array( 'bar_bg' => '--aieo-bar-bg', 'bar_text_color' => '--aieo-bar-text', 'bar_desc_color' => '--aieo-bar-desc', 'bar_link_color' => '--aieo-bar-link' ) as $k => $css ) {
			$val = isset( $s[ $k ] ) ? self::color( $s[ $k ] ) : '';
			if ( '' !== $val ) { $parts[] = $css . ':' . $val; }
		}
		foreach ( array( 'bar_text_size' => '--aieo-bar-text-size', 'bar_desc_size' => '--aieo-bar-desc-size' ) as $k => $css ) {
			$val = isset( $s[ $k ] ) ? self::len( $s[ $k ] ) : '';
			if ( '' !== $val ) { $parts[] = $css . ':' . $val; }
		}
		return empty( $parts ) ? '' : ';' . implode( ';', $parts );
	}

	
	public static function partner_count() {
		global $wpdb;
		$t = self::cookies_table();
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
			return 0;
		}
		
		return (int) $wpdb->get_var( "SELECT COUNT(DISTINCT service) FROM `{$t}` WHERE service IS NOT NULL AND service <> '' AND category IN ('analytics','marketing','functional')" );
	}

	
	private static function bbc_modal_message( $partners ) {
		$intro = $partners > 0
			? sprintf(  __( 'We and our %d partners use cookies and similar technologies to collect and process personal data from your device, such as your IP address and the pages you visit.', 'ai-eshop-optimizer' ), $partners )
			: __( 'We and our partners use cookies and similar technologies to collect and process personal data from your device, such as your IP address and the pages you visit.', 'ai-eshop-optimizer' );
		$p2  = __( 'We use this data to help us better understand our audience and to improve and personalise your experience. We also use it to manage the advertising shown on our services, which in turn helps to fund our services and the creation of more content.', 'ai-eshop-optimizer' );
		$ask = __( 'Please let us know if you agree to:', 'ai-eshop-optimizer' );
		return '<p>' . esc_html( $intro ) . '</p><p>' . esc_html( $p2 ) . '</p><p><strong>' . esc_html( $ask ) . '</strong></p>';
	}

	
	private static function bbc_modal_purposes() {
		$d1t = __( 'Store and/or access information on a device', 'ai-eshop-optimizer' );
		$d1  = __( 'Cookies, device or similar online identifiers (e.g. login-based identifiers, randomly assigned identifiers, network based identifiers) together with other information (e.g. browser type, language, screen size, supported technologies) can be stored or read on your device to recognise it each time it connects to a website, for one or several of the purposes presented here.', 'ai-eshop-optimizer' );
		$d2t = __( 'Personalised advertising and content, advertising and content measurement, audience research and services development', 'ai-eshop-optimizer' );
		$d2  = __( 'Advertising and content can be personalised based on your profile. Your activity can be used to build or improve a profile for personalised advertising and content, and performance can be measured. Reports can be generated based on your activity and that of others, helping us develop and improve products and services.', 'ai-eshop-optimizer' );
		$foot = __( 'Click “Manage options” to set your choice for specific purposes. You can change your preferences at any time from the cookie settings.', 'ai-eshop-optimizer' );
		return '<details class="aieo-cmp-purpose"><summary>' . esc_html( $d1t ) . '</summary><p>' . esc_html( $d1 ) . '</p></details>'
			. '<details class="aieo-cmp-purpose"><summary>' . esc_html( $d2t ) . '</summary><p>' . esc_html( $d2 ) . '</p></details>'
			. '<p class="aieo-cmp-foot">' . esc_html( $foot ) . '</p>';
	}

	
	private static function bbc_bar_message() {
		return '<p>' . esc_html__( 'We use cookies to give you the best online experience. Please let us know if you agree to all of these cookies.', 'ai-eshop-optimizer' ) . '</p>';
	}

	
	
	

	public function render_banner() {
		$s = self::settings();
		
		
		
		
		
		$layout    = in_array( $s['layout'], array( 'bar', 'modal' ), true ) ? $s['layout'] : 'bar';
		$auto_show = false; 
		$is_modal  = ( 'modal' === $layout );

		
		
		$reopen_css = static function ( $pos, $x, $b ) {
			$x = (int) $x;
			$b = (int) $b;
			if ( 'right' === $pos ) {
				return "right:{$x}px;left:auto;transform:none;bottom:{$b}px;";
			}
			if ( 'center' === $pos ) {
				return "left:50%;right:auto;transform:translateX(-50%);bottom:{$b}px;";
			}
			return "left:{$x}px;right:auto;transform:none;bottom:{$b}px;";
		};
		$reopen_desktop_css = $reopen_css( isset( $s['reopen_pos_desktop'] ) ? $s['reopen_pos_desktop'] : 'left', isset( $s['reopen_x_desktop'] ) ? $s['reopen_x_desktop'] : 86, isset( $s['reopen_bottom_desktop'] ) ? $s['reopen_bottom_desktop'] : 20 );
		$reopen_mobile_css  = $reopen_css( isset( $s['reopen_pos_mobile'] ) ? $s['reopen_pos_mobile'] : 'left', isset( $s['reopen_x_mobile'] ) ? $s['reopen_x_mobile'] : 86, isset( $s['reopen_bottom_mobile'] ) ? $s['reopen_bottom_mobile'] : 20 );
		
		
		
		
		
		
		$mbar_owns_mobile = defined( 'AIEO_RUNTIME_OWNS_DISPLAY' ) 
			|| ( class_exists( 'AIEO_Side_Cart_Display' )
				&& class_exists( 'AIEO_DMM_Settings' )
				&& method_exists( 'AIEO_DMM_Settings', 'is_module_enabled' )
				&& AIEO_DMM_Settings::is_module_enabled( 'side_cart' ) );
		$partners  = self::partner_count();
		
		if ( '' !== $s['title'] ) {
			$title = $s['title'];
		} else {
			$title = $is_modal
				? __( 'Let us know you agree to advertising cookies', 'ai-eshop-optimizer' )
				: __( 'Let us know you agree to cookies', 'ai-eshop-optimizer' );
		}
		if ( '' !== $s['message'] ) {
			$msg = $s['message'];
		} else {
			$msg = $is_modal ? self::bbc_modal_message( $partners ) : self::bbc_bar_message();
		}
		$use_default_body = ( '' === $s['message'] ); 
		$logo      = isset( $s['logo'] ) ? trim( (string) $s['logo'] ) : '';
		$vars      = self::button_css_vars( $s ) . self::bar_css_vars( $s );
		$ajax      = admin_url( 'admin-ajax.php' );

		$descs = array(
			'necessary'  => '' !== $s['desc_necessary'] ? $s['desc_necessary'] : __( 'Required for the site to function; always on.', 'ai-eshop-optimizer' ),
			'functional' => '' !== $s['desc_functional'] ? $s['desc_functional'] : __( 'Remembers your preferences (language, region) for a better experience.', 'ai-eshop-optimizer' ),
			'analytics'  => '' !== $s['desc_analytics'] ? $s['desc_analytics'] : __( 'Helps us understand how visitors use the site so we can improve it.', 'ai-eshop-optimizer' ),
			'marketing'  => '' !== $s['desc_marketing'] ? $s['desc_marketing'] : __( 'Used to deliver and measure ads relevant to you.', 'ai-eshop-optimizer' ),
		);
		$cat_labels = array(
			'necessary'  => __( 'Strictly necessary', 'ai-eshop-optimizer' ),
			'functional' => __( 'Functional', 'ai-eshop-optimizer' ),
			'analytics'  => __( 'Analytics', 'ai-eshop-optimizer' ),
			'marketing'  => __( 'Marketing', 'ai-eshop-optimizer' ),
		);
		$hosts = function_exists( 'aieo_consent_service_hosts' ) ? array_keys( aieo_consent_service_hosts() ) : array();
		?>
<style id="aieo-cmp-style">
.aieo-cmp{box-sizing:border-box;font-size:14px;line-height:1.5;color:#1f2937;}
.aieo-cmp *,.aieo-cmp *::before,.aieo-cmp *::after{box-sizing:border-box;}
.aieo-cmp[hidden],.aieo-cmp-overlay[hidden]{display:none!important;}
.aieo-cmp--bar{position:fixed;left:0;right:0;bottom:0;z-index:99999;background:#fff;border-top:1px solid #e5e7eb;box-shadow:0 -2px 8px rgba(0,0,0,.08);padding:16px;max-height:92vh;overflow:auto;}
.aieo-cmp--bar .aieo-cmp-inner{max-width:1100px;margin:0 auto;}
.aieo-cmp--modal{position:fixed;z-index:99999;left:50%;top:calc(50% - (var(--aieo-mbar-height, 0px) / 2));transform:translate(-50%,-50%);max-width:560px;width:calc(100% - 32px);max-height:calc(100vh - var(--aieo-mbar-height, 0px) - 40px);overflow:auto;background:#fff;border-radius:12px;box-shadow:0 12px 40px rgba(0,0,0,.25);padding:24px;}
.aieo-cmp-overlay{position:fixed;inset:0;z-index:99998;background:color-mix(in srgb,#0b1020 38%,transparent);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);}
.aieo-cmp-inner{position:relative;}
.aieo-cmp-close{position:absolute;top:4px;right:4px;width:30px;height:30px;padding:0;border:0;background:transparent;font-size:24px;line-height:1;cursor:pointer;color:var(--aieo-cmp-customize-fg,#6b7280);border-radius:6px;z-index:1;}
.aieo-cmp-close:hover,.aieo-cmp-close:focus{background:rgba(0,0,0,.06);}
.aieo-cmp--bar .aieo-cmp-close{top:-6px;right:-2px;}
.aieo-cmp-main{display:flex;gap:16px;align-items:center;flex-wrap:wrap;}
.aieo-cmp--modal .aieo-cmp-main{display:block;}
.aieo-cmp-text{flex:1;min-width:220px;}
.aieo-cmp-text strong{display:block;margin-bottom:4px;font-size:15px;}
.aieo-cmp-text p{margin:0 0 6px;}
.aieo-cmp-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center;}
.aieo-cmp--modal .aieo-cmp-actions{margin-top:18px;}
.aieo-cmp-btn{padding:10px 18px;border-radius:6px;font-size:14px;line-height:1.2;cursor:pointer;border-width:1px;border-style:solid;font-family:inherit;font-weight:500;}
.aieo-cmp-btn--accept{background:var(--aieo-cmp-accept-bg,#111827);color:var(--aieo-cmp-accept-fg,#fff);border-color:var(--aieo-cmp-accept-border,#111827);}
.aieo-cmp-btn--accept:hover,.aieo-cmp-btn--accept:focus{background:var(--aieo-cmp-accept-bg-h,#374151);color:var(--aieo-cmp-accept-fg-h,#fff);border-color:var(--aieo-cmp-accept-border-h,#374151);}
.aieo-cmp-btn--decline{background:var(--aieo-cmp-decline-bg,#fff);color:var(--aieo-cmp-decline-fg,#111827);border-color:var(--aieo-cmp-decline-border,#111827);}
.aieo-cmp-btn--decline:hover,.aieo-cmp-btn--decline:focus{background:var(--aieo-cmp-decline-bg-h,#f3f4f6);color:var(--aieo-cmp-decline-fg-h,#111827);border-color:var(--aieo-cmp-decline-border-h,#111827);}
.aieo-cmp-btn--customize{background:var(--aieo-cmp-customize-bg,transparent);color:var(--aieo-cmp-customize-fg,#374151);border-color:var(--aieo-cmp-customize-border,#d1d5db);}
.aieo-cmp-btn--customize:hover,.aieo-cmp-btn--customize:focus{background:var(--aieo-cmp-customize-bg-h,#f9fafb);color:var(--aieo-cmp-customize-fg-h,#111827);border-color:var(--aieo-cmp-customize-border-h,#9ca3af);}
.aieo-cmp-prefs{margin-top:16px;border-top:1px solid #e5e7eb;padding-top:12px;}
.aieo-cmp-prefs[hidden]{display:none!important;}
.aieo-cmp-row{display:flex;gap:10px;align-items:flex-start;padding:8px 0;}
.aieo-cmp-row input[type=checkbox]{margin-top:3px;}
.aieo-cmp-row .cat{font-weight:600;}
.aieo-cmp-pill{display:inline-block;font-size:11px;color:#15803d;background:#dcfce7;border-radius:10px;padding:1px 8px;margin-left:6px;vertical-align:middle;}
.aieo-cmp-row .desc{color:#6b7280;font-size:13px;margin-top:2px;}
.aieo-cmp-prefs-actions{margin-top:12px;display:flex;gap:8px;flex-wrap:wrap;}
.aieo-cmp-reopen{position:fixed;<?php echo $reopen_desktop_css; ?>z-index:999996;width:56px;height:56px;padding:0;display:flex;align-items:center;justify-content:center;border-radius:50%;cursor:pointer;border-width:1px;border-style:solid;background:var(--aieo-cmp-customize-bg,#fff);color:var(--aieo-cmp-customize-fg,#374151);border-color:var(--aieo-cmp-customize-border,#d1d5db);box-shadow:0 8px 24px rgba(0,0,0,.18);font-family:inherit;}
.aieo-cmp-reopen svg{width:26px;height:26px;display:block;}
/* When re-opened (floating button or the side-cart mobile bar's cookie item),
   sit ABOVE the mobile bottom bar (z-index 999996) — bar layout lifts by the
   bar height, modal/overlay just raise their z-index. */
.aieo-cmp--bar.aieo-cmp--abovebar{bottom:var(--aieo-mbar-height,0px);z-index:1000000;}
.aieo-cmp--modal.aieo-cmp--abovebar{z-index:1000000;}
.aieo-cmp-overlay.aieo-cmp--abovebar{z-index:999999;}
@media(max-width:600px){.aieo-cmp-actions .aieo-cmp-btn{flex:1 1 auto;}}
/* Logo */
.aieo-cmp-logo{margin-bottom:14px;}
.aieo-cmp-logo img{max-height:46px;width:auto;display:block;}
.aieo-cmp--bar .aieo-cmp-logo{margin-bottom:0;}
.aieo-cmp--bar .aieo-cmp-logo img{max-height:30px;}
/* BBC-style modal button layout: two equal side-by-side + Manage below */
.aieo-cmp--modal .aieo-cmp-actions{display:flex;gap:12px;margin-top:20px;}
.aieo-cmp--modal .aieo-cmp-actions .aieo-cmp-btn{flex:1;justify-content:center;text-align:center;padding:12px 18px;}
.aieo-cmp-manage{margin-top:12px;text-align:center;}
.aieo-cmp-manage .aieo-cmp-btn{min-width:200px;}
.aieo-cmp-purpose{border-top:1px solid #e5e7eb;padding:10px 0;}
.aieo-cmp-purpose>summary{cursor:pointer;font-weight:700;list-style:none;display:flex;justify-content:space-between;align-items:center;gap:12px;}
.aieo-cmp-purpose>summary::-webkit-details-marker{display:none;}
.aieo-cmp-purpose>summary::after{content:"\203A";font-size:20px;line-height:1;transform:rotate(90deg);transition:transform .2s;color:#6b7280;}
.aieo-cmp-purpose[open]>summary::after{transform:rotate(-90deg);}
.aieo-cmp-purpose>p{color:#6b7280;font-size:13px;margin:8px 0 2px;}
.aieo-cmp-foot{font-size:13px;color:#6b7280;margin-top:14px;}
/* BBC-style bottom bar: 3 columns (title | description | links) + operator colours */
.aieo-cmp--bar{background:var(--aieo-bar-bg,#1f2937);color:var(--aieo-bar-text,#fff);border-top:0;}
.aieo-cmp--bar .aieo-cmp-bar3{display:flex;gap:24px;align-items:center;flex-wrap:wrap;}
.aieo-cmp-bar-title{flex:0 0 auto;font-weight:700;font-size:var(--aieo-bar-text-size,18px);color:var(--aieo-bar-text,#fff);max-width:280px;}
.aieo-cmp-bar-desc{flex:1;min-width:200px;font-size:var(--aieo-bar-desc-size,14px);color:var(--aieo-bar-desc,#d1d5db);}
.aieo-cmp-bar-desc p{margin:0;}
.aieo-cmp--bar .aieo-cmp-actions{flex:0 0 auto;flex-direction:column;gap:6px;align-items:flex-start;}
.aieo-cmp-link{color:var(--aieo-bar-link,#fbbf24);font-weight:700;cursor:pointer;text-decoration:none;white-space:nowrap;}
.aieo-cmp-link:hover,.aieo-cmp-link:focus{text-decoration:underline;}
.aieo-cmp--bar .aieo-cmp-close{color:var(--aieo-bar-text,#fff);}
@media(max-width:600px){.aieo-cmp--bar .aieo-cmp-bar3{gap:10px;}.aieo-cmp--bar .aieo-cmp-actions{flex-direction:row;}.aieo-cmp-bar-title{max-width:none;}}
<?php if ( ! $mbar_owns_mobile ) : ?>@media (max-width:768px){.aieo-cmp-reopen{<?php echo $reopen_mobile_css; ?>}}<?php endif; ?>
</style>
<?php if ( 'modal' === $layout ) : ?>
<div class="aieo-cmp-overlay"<?php echo $auto_show ? '' : ' hidden'; ?>></div>
<?php endif; ?>
<div id="aieo-consent-banner" class="aieo-cmp aieo-cmp--<?php echo esc_attr( $layout ); ?>"<?php echo $auto_show ? '' : ' hidden'; ?> style="<?php echo esc_attr( $vars ); ?>" role="dialog" aria-live="polite" aria-label="<?php echo esc_attr( $title ); ?>"<?php echo 'modal' === $layout ? ' aria-modal="true"' : ''; ?>>
	<div class="aieo-cmp-inner">
		<button type="button" class="aieo-cmp-close" data-aieo-consent="dismiss" aria-label="<?php esc_attr_e( 'Close', 'ai-eshop-optimizer' ); ?>">&times;</button>
		<?php if ( '' !== $logo ) : ?><div class="aieo-cmp-logo"><img src="<?php echo esc_url( $logo ); ?>" alt=""></div><?php endif; ?>
		<?php
		$aieo_ot_on  = ( 'yes' === ( isset( $s['one_tap_enabled'] ) ? $s['one_tap_enabled'] : 'no' ) );
		$aieo_ot_pre = ( 'checked' === ( isset( $s['one_tap_consent_default'] ) ? $s['one_tap_consent_default'] : 'unchecked' ) );
		?>
		<?php if ( $is_modal ) : ?>
		<div class="aieo-cmp-main">
			<div class="aieo-cmp-text"><strong><?php echo esc_html( $title ); ?></strong><div class="aieo-cmp-body" data-tpl="aieo-cmp-modal-tpl"></div></div>
		</div>
		<?php  ?>
		<template id="aieo-cmp-modal-tpl"><?php echo wp_kses_post( $msg ); ?><?php echo $use_default_body ? self::bbc_modal_purposes() : ''; ?></template>
		<?php if ( $aieo_ot_on ) : ?>
		<label class="aieo-cmp-personalize" style="display:flex;gap:9px;align-items:flex-start;margin:12px 0;padding:10px 12px;border:1px solid rgba(127,127,127,.35);border-radius:6px;font-size:13px;line-height:1.45;cursor:pointer;">
			<input type="checkbox" data-aieo-personalize="1"<?php echo $aieo_ot_pre ? ' checked' : ''; ?> style="margin-top:3px;flex:none;">
			<span><strong><?php esc_html_e( 'Personalise with my Google profile', 'ai-eshop-optimizer' ); ?></strong><br><?php esc_html_e( 'Show a one-tap Google prompt so we can tailor recommendations to you — we never sign you in.', 'ai-eshop-optimizer' ); ?></span>
		</label>
		<?php endif; ?>
		<div class="aieo-cmp-actions">
			<button type="button" data-aieo-consent="reject" class="aieo-cmp-btn aieo-cmp-btn--decline"><?php esc_html_e( 'I do not agree', 'ai-eshop-optimizer' ); ?></button>
			<button type="button" data-aieo-consent="accept" class="aieo-cmp-btn aieo-cmp-btn--accept"><?php esc_html_e( 'I agree', 'ai-eshop-optimizer' ); ?></button>
		</div>
		<div class="aieo-cmp-manage">
			<button type="button" data-aieo-consent="customize" class="aieo-cmp-btn aieo-cmp-btn--customize"><?php esc_html_e( 'Manage options', 'ai-eshop-optimizer' ); ?></button>
		</div>
		<?php else : ?>
		<div class="aieo-cmp-main aieo-cmp-bar3">
			<strong class="aieo-cmp-bar-title"><?php echo esc_html( $title ); ?></strong>
			<div class="aieo-cmp-bar-desc"><?php echo wp_kses_post( $msg ); ?></div>
			<?php if ( $aieo_ot_on ) : ?>
			<label class="aieo-cmp-personalize" style="display:flex;gap:8px;align-items:flex-start;margin:6px 0;font-size:12px;line-height:1.4;cursor:pointer;">
				<input type="checkbox" data-aieo-personalize="1"<?php echo $aieo_ot_pre ? ' checked' : ''; ?> style="margin-top:2px;flex:none;">
				<span><?php esc_html_e( 'Personalise with my Google profile (one-tap Google — no sign-in)', 'ai-eshop-optimizer' ); ?></span>
			</label>
			<?php endif; ?>
			<div class="aieo-cmp-actions">
				<a href="#" data-aieo-consent="accept" class="aieo-cmp-link aieo-cmp-link--yes"><?php esc_html_e( 'Yes, I agree', 'ai-eshop-optimizer' ); ?></a>
				<a href="#" data-aieo-consent="customize" class="aieo-cmp-link aieo-cmp-link--no"><?php esc_html_e( 'No, take me to settings', 'ai-eshop-optimizer' ); ?></a>
			</div>
		</div>
		<?php endif; ?>
		<div class="aieo-cmp-prefs" hidden>
			<?php foreach ( array( 'necessary', 'functional', 'analytics', 'marketing' ) as $cat ) : ?>
			<div class="aieo-cmp-row">
				<input type="checkbox" data-aieo-cat="<?php echo esc_attr( $cat ); ?>"<?php echo 'necessary' === $cat ? ' checked disabled' : ''; ?>>
				<div>
					<span class="cat"><?php echo esc_html( $cat_labels[ $cat ] ); ?></span><?php echo 'necessary' === $cat ? '<span class="aieo-cmp-pill">' . esc_html__( 'Always active', 'ai-eshop-optimizer' ) . '</span>' : ''; ?>
					<div class="desc"><?php echo wp_kses_post( $descs[ $cat ] ); ?></div>
				</div>
			</div>
			<?php endforeach; ?>
			<div class="aieo-cmp-prefs-actions">
				<button type="button" data-aieo-consent="savePrefs" class="aieo-cmp-btn aieo-cmp-btn--accept"><?php esc_html_e( 'Save preferences', 'ai-eshop-optimizer' ); ?></button>
				<button type="button" data-aieo-consent="reject" class="aieo-cmp-btn aieo-cmp-btn--decline"><?php esc_html_e( 'Decline all', 'ai-eshop-optimizer' ); ?></button>
			</div>
		</div>
	</div>
</div>
<script data-cfasync="false">
(function(){
	var b=document.getElementById('aieo-consent-banner'); if(!b){return;}
	var ov=document.querySelector('.aieo-cmp-overlay');
	var prefs=b.querySelector('.aieo-cmp-prefs');
	var VER=<?php echo (int) self::policy_version(); ?>, NAME='<?php echo esc_js( self::COOKIE ); ?>', AJAX='<?php echo esc_js( $ajax ); ?>';
	var SCAN_NONCE='<?php echo esc_js( wp_create_nonce( self::SCAN_NONCE ) ); ?>';
	var SCAN_ON=<?php echo ( 'no' !== ( isset( $s['cookie_scan'] ) ? $s['cookie_scan'] : 'yes' ) ) ? 'true' : 'false'; ?>;
	var SCAN_TTL=<?php echo (int) max( 1, (int) ( isset( $s['cookie_scan_days'] ) ? $s['cookie_scan_days'] : 30 ) ) * 86400000; ?>;
	var HOSTS=<?php echo wp_json_encode( $hosts ); ?>;
	var EEA_ONLY=<?php echo 'yes' === $s['eea_only'] ? 'true' : 'false'; ?>, DEF_GRANT=<?php echo 'granted' === $s['default_state'] ? 'true' : 'false'; ?>;
	// True only when the request reached the origin through Cloudflare (CF adds these
	// headers on every request). Gates the /cdn-cgi/trace geo probe so non-CF sites
	// (e.g. nginx-direct) don't 404 that path on every EEA-mode pageview.
	var CF_TRACE=<?php echo ( ! empty( $_SERVER['HTTP_CF_RAY'] ) || ! empty( $_SERVER['HTTP_CF_IPCOUNTRY'] ) ) ? 'true' : 'false'; ?>;
	var ONE_TAP=<?php echo ( 'yes' === ( isset( $s['one_tap_enabled'] ) ? $s['one_tap_enabled'] : 'no' ) ) ? 'true' : 'false'; ?>;
	var EEA_CC=['AT','BE','BG','HR','CY','CZ','DK','EE','FI','FR','DE','GR','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','RO','SK','SI','ES','SE','IS','LI','NO','GB','CH'];
	function readCookie(){ try{ var m=document.cookie.match(new RegExp('(?:^|; )'+NAME+'=([^;]*)')); if(!m){return null;} var o=JSON.parse(decodeURIComponent(m[1])); return (o&&typeof o==='object')?o:null; }catch(e){ return null; } }
	function setCookie(f,a,m,p){ var v=JSON.stringify({v:VER,t:Math.floor(Date.now()/1000),functional:f,analytics:a,marketing:m,personalize:p?1:0}); var d=new Date(); d.setTime(d.getTime()+180*864e5); document.cookie=NAME+'='+encodeURIComponent(v)+';expires='+d.toUTCString()+';path=/;SameSite=Lax'; }
	function gtagUpdate(a,m){ try{ if(typeof gtag==='function'){ gtag('consent','update',{'analytics_storage':a?'granted':'denied','ad_storage':m?'granted':'denied','ad_user_data':m?'granted':'denied','ad_personalization':m?'granted':'denied'}); } }catch(e){} }
	function logChoice(f,a,m,src){ try{ var fd=new FormData(); fd.set('action','aieo_consent_log'); fd.set('functional',f?1:0); fd.set('analytics',a?1:0); fd.set('marketing',m?1:0); fd.set('source',src||'banner'); if(navigator.sendBeacon){ navigator.sendBeacon(AJAX,fd); }else{ fetch(AJAX,{method:'POST',credentials:'same-origin',body:fd,keepalive:true}); } }catch(e){} }
	function hide(){ b.setAttribute('hidden','hidden'); if(ov){ ov.setAttribute('hidden','hidden'); } try{ document.dispatchEvent(new CustomEvent('aieo:consent-resolved')); }catch(e){} }
	function hydrate(){ var body=b.querySelector('.aieo-cmp-body[data-tpl]'); if(!body||body.getAttribute('data-hydrated')){return;} var tpl=document.getElementById(body.getAttribute('data-tpl')); if(tpl&&tpl.content){ body.appendChild(tpl.content.cloneNode(true)); body.setAttribute('data-hydrated','1'); } }
	function show(){ hydrate(); b.removeAttribute('hidden'); if(ov){ ov.removeAttribute('hidden'); } }
	function apply(f,a,m,p,src){ setCookie(f,a,m,p); gtagUpdate(a,m); logChoice(f,a,m,src); hide(); if(p){ try{ document.dispatchEvent(new CustomEvent('aieo:personalize-granted')); }catch(e){} } }
	function openPrefs(prefill){ if(prefs){ prefs.removeAttribute('hidden'); } show(); if(prefill){ var c=readCookie(); if(c){ ['functional','analytics','marketing'].forEach(function(k){ var cb=b.querySelector('[data-aieo-cat="'+k+'"]'); if(cb){ cb.checked=!!c[k]; } }); var pz=b.querySelector('[data-aieo-personalize]'); if(pz){ pz.checked=!!c.personalize; } } } }
	function setAboveBar(on){ [b,ov].forEach(function(el){ if(el){ if(on){el.classList.add('aieo-cmp--abovebar');}else{el.classList.remove('aieo-cmp--abovebar');} } }); }
	function reopen(){ openPrefs(true); setAboveBar(true); }
	// Public API so other surfaces (the side-cart mobile bar's cookie item) can
	// open/close the consent preferences "over the bar" like the other panels.
	window.aieoConsent={ open:reopen, close:function(){ hide(); setAboveBar(false); }, isOpen:function(){ return !!(b && !b.hasAttribute('hidden')); } };
	// Dismiss WITHOUT recording a choice: hides the banner/overlay so it never
	// traps the screen. A prior choice is kept; with no prior choice the safe
	// denied defaults stay and the banner re-prompts next visit.
	function dismiss(){ hide(); setAboveBar(false); }
	document.addEventListener('click',function(e){
		var ro=e.target.closest('#aieo-cmp-reopen'); if(ro){ e.preventDefault(); reopen(); return; }
		// Tap the dimmed backdrop (outside the dialog) to dismiss.
		if(e.target===ov){ dismiss(); return; }
		var t=e.target.closest('[data-aieo-consent]'); if(!t||!b.contains(t)){ return; }
		var act=t.getAttribute('data-aieo-consent');
		if(t.tagName==='A'){ e.preventDefault(); }
		if(act==='accept'){ var ap=b.querySelector('[data-aieo-personalize]'); apply(1,1,1, ap&&ap.checked?1:0, 'accept_all'); }
		else if(act==='reject'){ apply(1,0,0,0,'decline'); }
		else if(act==='customize'){ openPrefs(false); }
		else if(act==='dismiss'){ dismiss(); }
		else if(act==='savePrefs'){ var fn=b.querySelector('[data-aieo-cat="functional"]'), an=b.querySelector('[data-aieo-cat="analytics"]'), mk=b.querySelector('[data-aieo-cat="marketing"]'), pz=b.querySelector('[data-aieo-personalize]'); apply(fn&&fn.checked?1:0, an&&an.checked?1:0, mk&&mk.checked?1:0, pz&&pz.checked?1:0, 'customize'); }
	});
	document.addEventListener('keydown',function(e){ if(e.key==='Escape' && b && !b.hasAttribute('hidden')){ dismiss(); } });
	// ── Cache-safe init ──────────────────────────────────────────────
	// The banner is ALWAYS rendered hidden server-side; we decide visibility HERE
	// from the per-browser cookie, so a full-page cache (WP-Rocket / Cloudflare)
	// can never freeze the banner shown or hidden for the wrong visitor. show()
	// hydrates the <template> body on demand.
	function validChoice(){ var c=readCookie(); return (c && typeof c.v==='number' && c.v>=VER) ? c : null; }
	function init(){
		var c=validChoice();
		if(c){ gtagUpdate(!!c.analytics, !!c.marketing); return; } // restore the chooser's Consent Mode state; stay hidden
		if(!EEA_ONLY){ if(DEF_GRANT){ gtagUpdate(1,1); } show(); return; }
		// eea_only: confirm geo CLIENT-SIDE via Cloudflare's /cdn-cgi/trace (so it's
		// not a cached server value). ONLY when actually behind Cloudflare — otherwise
		// that path 404s (a wasted full-page download every pageview), so just show()
		// (deny-by-default: the safe choice with no client-side geo source).
		if(!CF_TRACE){ show(); return; }
		try{
			fetch('/cdn-cgi/trace',{credentials:'omit'}).then(function(r){return r.text();}).then(function(t){
				var m=t.match(/loc=([A-Z]{2})/), cc=m?m[1]:'';
				if(!cc || EEA_CC.indexOf(cc)!==-1){ show(); }      // EEA / unknown → show (deny-by-default); confirmed non-EEA → stay hidden
				else if(DEF_GRANT){ gtagUpdate(1,1); }
			}).catch(function(){ show(); });                       // trace error → show (safe)
		}catch(e){ show(); }
	}
	init();
	// Cookie scanner sweep — discovery only: gated by the operator toggle (SCAN_ON), fires
	// AFTER window 'load' via sendBeacon, throttled once per 30 days per visitor, NAMES +
	// service hosts only (never values). SCAN_ON=false => no per-visit request at all (static).
	try{
		var FORCE=/[?&]aieo_cmp_forcescan=1/.test(location.search||'');
			if((SCAN_ON || FORCE) && (FORCE || document.cookie.indexOf('aieo_cmp_scanned=1')===-1)){
			var sweep=function(){
				try{
					var names=document.cookie.split(';').map(function(s){ return s.split('=')[0].trim(); }).filter(function(n){ return n && /^[A-Za-z0-9_\-.]{1,191}$/.test(n); });
					var found={};
					var res=(window.performance&&performance.getEntriesByType)?performance.getEntriesByType('resource'):[];
					res.forEach(function(r){ HOSTS.forEach(function(h){ if(r.name&&r.name.indexOf(h)!==-1){ found[h]=1; } }); });
					document.querySelectorAll('script[src],iframe[src],link[href]').forEach(function(el){ var u=el.src||el.href||''; HOSTS.forEach(function(h){ if(u.indexOf(h)!==-1){ found[h]=1; } }); });
					var fd=new FormData(); fd.set('action','aieo_consent_scan'); fd.set('nonce',SCAN_NONCE); fd.set('pre_consent', readCookie()?'0':'1');
					names.slice(0,50).forEach(function(n){ fd.append('names[]',n); });
					Object.keys(found).forEach(function(h){ fd.append('services[]',h); });
					if(navigator.sendBeacon){ navigator.sendBeacon(AJAX,fd); }else{ fetch(AJAX,{method:'POST',credentials:'same-origin',body:fd,keepalive:true}); }
					if(!FORCE){ var d=new Date(); d.setTime(d.getTime()+SCAN_TTL); document.cookie='aieo_cmp_scanned=1;expires='+d.toUTCString()+';path=/;SameSite=Lax'; }
				}catch(e){}
			};
			var schedule=function(){ if(FORCE){ setTimeout(sweep,1500); }else if('requestIdleCallback' in window){ requestIdleCallback(sweep,{timeout:4000}); }else{ setTimeout(sweep,2500); } };
			if(document.readyState==='complete'){ schedule(); }else{ window.addEventListener('load',schedule); }
		}
	}catch(e){}
})();
</script>
		<?php
	}

	
	
	public static function reopen_button_vars() {
		return self::button_css_vars( self::settings() );
	}

	public function render_reopen() {
		
		
		
		
		
		if ( class_exists( 'AIEO_Side_Cart_Display' ) && AIEO_Side_Cart_Display::consent_button_active() ) {
			return;
		}
		$s = self::settings();
		
		
		
		$label = '' !== $s['reopen_label'] ? $s['reopen_label'] : __( 'Cookie settings', 'ai-eshop-optimizer' );
		$vars  = self::button_css_vars( $s );
		?>
<button id="aieo-cmp-reopen" class="aieo-cmp-reopen" type="button" style="<?php echo esc_attr( $vars ); ?>" aria-label="<?php echo esc_attr( $label ); ?>" title="<?php echo esc_attr( $label ); ?>"><svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2a10 10 0 1 0 10 10c0-.32-.02-.64-.05-.95a2.8 2.8 0 0 1-3.92-3.92A2.8 2.8 0 0 1 12.95 2.05 10.3 10.3 0 0 0 12 2z"/><circle cx="8.5" cy="9.5" r="1"/><circle cx="12.5" cy="13.5" r="1"/><circle cx="9" cy="15.5" r="0.9"/><circle cx="15.5" cy="10" r="0.9"/></svg></button>
		<?php
	}
}
