<?php


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

$s = isset( $settings ) && is_array( $settings )
	? $settings
	: ( class_exists( 'AIEO_Consent' ) ? AIEO_Consent::settings() : array() );

$inventory = isset( $inventory ) && is_array( $inventory ) ? $inventory : array();

$nonce = wp_create_nonce( AIEO_DMM::NONCE_ACTION );
$ajax  = admin_url( 'admin-ajax.php' );

$enabled = ! empty( $s['enabled'] ) && 'yes' === $s['enabled'];
$eea     = ! isset( $s['eea_only'] ) || 'yes' === $s['eea_only'];
$default = isset( $s['default_state'] ) ? $s['default_state'] : 'denied';
$layout  = isset( $s['layout'] ) && 'modal' === $s['layout'] ? 'modal' : 'bar';
$reopen  = ! isset( $s['reopen_enabled'] ) || 'yes' === $s['reopen_enabled'];

if ( function_exists( 'wp_enqueue_media' ) ) { wp_enqueue_media(); }


$color_row = function ( $label, $name ) use ( $s ) {
	$val = isset( $s[ $name ] ) ? (string) $s[ $name ] : '';
	echo '<p style="margin:6px 0;display:flex;align-items:center;gap:10px;">';
	echo '<label style="width:130px;display:inline-block;color:#374151;font-size:13px;">' . esc_html( $label ) . '</label>';
	echo '<input type="text" name="' . esc_attr( $name ) . '" value="' . esc_attr( $val ) . '" class="aieo-cmp-color" data-default-color="' . esc_attr( $val ) . '">';
	echo '</p>';
};


$btn_groups = array(
	'accept'    => __( 'Accept all', 'ai-eshop-optimizer' ),
	'decline'   => __( 'Decline', 'ai-eshop-optimizer' ),
	'customize' => __( 'Customize', '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' ),
	'unclassified' => __( 'Unclassified', 'ai-eshop-optimizer' ),
);
?>
<div class="aieo-dmm-section">
	<h2><?php esc_html_e( 'Consent / GDPR', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description" style="max-width:880px;"><?php esc_html_e( "AIEO's own lightweight cookie-consent banner — a first-party alternative to a heavy CMP. It powers Google Consent Mode v2 and gates AIEO analytics plus the Facebook / GA4 senders. Measurement-scope (advertiser) by design — no IAB TCF. Leave the banner OFF to defer to an external CMP you already run.", 'ai-eshop-optimizer' ); ?></p>

	<form id="aieo-dmm-consent-form" onsubmit="return false;">

		<!-- ── Banner ─────────────────────────────────────────────── -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Banner', 'ai-eshop-optimizer' ); ?></h3>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Show banner', 'ai-eshop-optimizer' ); ?></th>
					<td><label><input type="checkbox" name="enabled" value="1" <?php checked( $enabled ); ?>> <?php esc_html_e( 'Show the first-party consent banner', 'ai-eshop-optimizer' ); ?></label></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Scope', 'ai-eshop-optimizer' ); ?></th>
					<td><label><input type="checkbox" name="eea_only" value="1" <?php checked( $eea ); ?>> <?php esc_html_e( 'EEA / UK only (deny-by-default there; elsewhere use the default below)', 'ai-eshop-optimizer' ); ?></label></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Default (before choice / outside EEA)', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<select name="default_state">
							<option value="denied"  <?php selected( $default, 'denied' ); ?>><?php esc_html_e( 'Denied (opt-in)', 'ai-eshop-optimizer' ); ?></option>
							<option value="granted" <?php selected( $default, 'granted' ); ?>><?php esc_html_e( 'Granted (opt-out)', 'ai-eshop-optimizer' ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Layout', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<select name="layout">
							<option value="bar"   <?php selected( $layout, 'bar' ); ?>><?php esc_html_e( 'Bar (bottom of screen)', 'ai-eshop-optimizer' ); ?></option>
							<option value="modal" <?php selected( $layout, 'modal' ); ?>><?php esc_html_e( 'Pop-up (centre, glass)', 'ai-eshop-optimizer' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Bar (default) converts best and is least intrusive. The centre pop-up with a glass blur is more prominent but tends to raise bounce — pick it consciously.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Title', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="title" value="<?php echo esc_attr( isset( $s['title'] ) ? $s['title'] : '' ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'We value your privacy', 'ai-eshop-optimizer' ); ?>"></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Logo / image', 'ai-eshop-optimizer' ); ?></th>
						<td>
							<input type="text" id="aieo-cmp-logo" name="logo" value="<?php echo esc_attr( isset( $s['logo'] ) ? $s['logo'] : '' ); ?>" class="regular-text" placeholder="https://…">
							<button type="button" class="button" id="aieo-cmp-logo-btn"><?php esc_html_e( 'Choose image', 'ai-eshop-optimizer' ); ?></button>
							<button type="button" class="button-link" id="aieo-cmp-logo-clear" style="color:#b91c1c;"><?php esc_html_e( 'Remove', 'ai-eshop-optimizer' ); ?></button>
							<br><img id="aieo-cmp-logo-preview" src="<?php echo esc_url( isset( $s['logo'] ) ? $s['logo'] : '' ); ?>" alt="" style="max-height:46px;margin-top:8px;<?php echo empty( $s['logo'] ) ? 'display:none;' : ''; ?>">
							<p class="description"><?php esc_html_e( 'Shown at the top of the pop-up (and the bar). Your store logo works well.', 'ai-eshop-optimizer' ); ?></p>
							<script>
							(function(){ document.addEventListener('click',function(e){
								var btn=e.target.closest('#aieo-cmp-logo-btn'), clr=e.target.closest('#aieo-cmp-logo-clear');
								if(btn){ e.preventDefault(); if(!window.wp||!wp.media){return;} var fr=wp.media({title:'Select logo',button:{text:'Use image'},multiple:false,library:{type:'image'}}); fr.on('select',function(){ var a=fr.state().get('selection').first().toJSON(); var i=document.getElementById('aieo-cmp-logo'); if(i){i.value=a.url;} var p=document.getElementById('aieo-cmp-logo-preview'); if(p){p.src=a.url;p.style.display='';} }); fr.open(); }
								if(clr){ e.preventDefault(); var i=document.getElementById('aieo-cmp-logo'); if(i){i.value='';} var p=document.getElementById('aieo-cmp-logo-preview'); if(p){p.style.display='none';} }
							}); })();
							</script>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Message', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<?php
						wp_editor(
							isset( $s['message'] ) ? (string) $s['message'] : '',
							'aieo_consent_message',
							array(
								'textarea_name' => 'message',
								'media_buttons' => false,
								'teeny'         => true,
								'textarea_rows' => 5,
								'quicktags'     => true,
							)
						);
						?>
						<p class="description"><?php esc_html_e( 'Rich text. Links and basic formatting are allowed; scripts are stripped on save.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
			</table>
		</div>

		<!-- ── Google One Tap (recognise-only) ───────────────────── -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Google One Tap — personalisation', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:760px;"><?php esc_html_e( 'Show visitors who are signed into Google a one-tap "Continue as…" prompt to recognise them (name + email) for personalised recommendations. Recognise-only — it never logs them in or creates an account; sign-in stays at checkout. Requires your Google client ID under Social Login.', 'ai-eshop-optimizer' ); ?></p>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Enable One Tap', 'ai-eshop-optimizer' ); ?></th>
					<td><label><input type="checkbox" name="one_tap_enabled" value="1" <?php checked( ! empty( $s['one_tap_enabled'] ) && 'yes' === $s['one_tap_enabled'] ); ?>> <?php esc_html_e( 'Show the One Tap prompt to consenting, logged-out visitors', 'ai-eshop-optimizer' ); ?></label></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Consent line default', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<?php $aieo_otd = ( isset( $s['one_tap_consent_default'] ) && 'checked' === $s['one_tap_consent_default'] ) ? 'checked' : 'unchecked'; ?>
						<select name="one_tap_consent_default" id="aieo-onetap-default">
							<option value="unchecked" <?php selected( $aieo_otd, 'unchecked' ); ?>><?php esc_html_e( 'Unticked (recommended)', 'ai-eshop-optimizer' ); ?></option>
							<option value="checked"   <?php selected( $aieo_otd, 'checked' ); ?>><?php esc_html_e( 'Pre-ticked', 'ai-eshop-optimizer' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Default state of the "Personalise with my Google profile" line shown in the consent banner.', 'ai-eshop-optimizer' ); ?></p>
						<p id="aieo-onetap-gdpr-warn" class="description" style="color:#b91c1c;<?php echo 'checked' === $aieo_otd ? '' : 'display:none;'; ?>"><?php esc_html_e( '⚠ A pre-ticked consent box is rejected by the GDPR (Recital 32 / Planet49). Only use it if your legal review confirms it for your jurisdiction — your responsibility.', 'ai-eshop-optimizer' ); ?></p>
						<script>(function(){var s=document.getElementById('aieo-onetap-default'),w=document.getElementById('aieo-onetap-gdpr-warn');if(s&&w){s.addEventListener('change',function(){w.style.display=this.value==='checked'?'':'none';});}})();</script>
					</td>
				</tr>
			</table>
		</div>

		<!-- ── Re-open + policy version (moved: right after One Tap) ── -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Re-open & policy', 'ai-eshop-optimizer' ); ?></h3>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Re-open button', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<label><input type="checkbox" name="reopen_enabled" value="1" <?php checked( $reopen ); ?>> <?php esc_html_e( 'Show a floating "Cookie settings" button so visitors can change or withdraw consent', 'ai-eshop-optimizer' ); ?></label>
						<p style="margin-top:8px;"><input type="text" name="reopen_label" value="<?php echo esc_attr( isset( $s['reopen_label'] ) ? $s['reopen_label'] : '' ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'Cookie settings', 'ai-eshop-optimizer' ); ?>"></p>
					<?php
					$aieo_pos_fields = array(
						'desktop' => __( 'Desktop position', 'ai-eshop-optimizer' ),
						'mobile'  => __( 'Mobile position', 'ai-eshop-optimizer' ),
					);
					foreach ( $aieo_pos_fields as $aieo_dev => $aieo_devlabel ) :
						$aieo_pos = isset( $s[ 'reopen_pos_' . $aieo_dev ] ) ? $s[ 'reopen_pos_' . $aieo_dev ] : 'left';
						$aieo_x   = isset( $s[ 'reopen_x_' . $aieo_dev ] ) ? (int) $s[ 'reopen_x_' . $aieo_dev ] : 86;
						$aieo_b   = isset( $s[ 'reopen_bottom_' . $aieo_dev ] ) ? (int) $s[ 'reopen_bottom_' . $aieo_dev ] : 20;
						?>
						<p style="margin-top:8px;display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
							<strong style="min-width:140px;"><?php echo esc_html( $aieo_devlabel ); ?></strong>
							<select name="reopen_pos_<?php echo esc_attr( $aieo_dev ); ?>">
								<option value="left" <?php selected( 'left', $aieo_pos ); ?>><?php esc_html_e( 'Left', 'ai-eshop-optimizer' ); ?></option>
								<option value="center" <?php selected( 'center', $aieo_pos ); ?>><?php esc_html_e( 'Centre', 'ai-eshop-optimizer' ); ?></option>
								<option value="right" <?php selected( 'right', $aieo_pos ); ?>><?php esc_html_e( 'Right', 'ai-eshop-optimizer' ); ?></option>
							</select>
							<label><?php esc_html_e( 'Edge offset (px)', 'ai-eshop-optimizer' ); ?> <input type="number" name="reopen_x_<?php echo esc_attr( $aieo_dev ); ?>" value="<?php echo esc_attr( $aieo_x ); ?>" min="0" max="2000" style="width:80px;"></label>
							<label><?php esc_html_e( 'Bottom (px)', 'ai-eshop-optimizer' ); ?> <input type="number" name="reopen_bottom_<?php echo esc_attr( $aieo_dev ); ?>" value="<?php echo esc_attr( $aieo_b ); ?>" min="0" max="2000" style="width:80px;"></label>
						</p>
					<?php endforeach; ?>
					<p class="description"><?php esc_html_e( 'Position of the floating cookie button per device, so it can be aligned with other floating widgets (WhatsApp, scroll-to-top). Edge offset applies from the chosen side; ignored for Centre. When the Side Cart bottom navigator is active, its coordinated styling SUPERSEDES the mobile settings here (the navigator owns the mobile bottom edge and includes its own cookie item).', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Cookie scanning', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<label><input type="checkbox" name="cookie_scan" value="1" <?php checked( ! isset( $s['cookie_scan'] ) || 'no' !== $s['cookie_scan'] ); ?>> <?php esc_html_e( 'Discover cookies live from storefront visitors (sweep)', 'ai-eshop-optimizer' ); ?></label>
						<p style="margin-top:8px;"><?php esc_html_e( 'Re-scan each visitor at most once every', 'ai-eshop-optimizer' ); ?>
							<input type="number" name="cookie_scan_days" min="1" max="365" step="1" value="<?php echo esc_attr( (int) ( isset( $s['cookie_scan_days'] ) ? $s['cookie_scan_days'] : 30 ) ); ?>" style="width:80px;">
							<?php esc_html_e( 'days', 'ai-eshop-optimizer' ); ?></p>
						<p class="description" style="max-width:780px;"><?php esc_html_e( 'Lightweight and privacy-safe: sends cookie NAMES + detected service hosts only (never values), via sendBeacon, AFTER the page has loaded, and only once per 30 days per visitor. Leave it on while building your cookie inventory (or briefly after adding a new third-party script). Turn it OFF once the inventory is complete — the storefront then makes NO scan request at all (fully static), removing a per-visitor server hit on every visit.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Policy version', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<input type="number" name="policy_version" value="<?php echo esc_attr( isset( $s['policy_version'] ) ? (int) $s['policy_version'] : 1 ); ?>" min="1" step="1" style="width:90px;">
						<p class="description"><?php esc_html_e( 'Bump this number after a material change to your cookie/privacy policy to re-ask every visitor (existing choices below this version are treated as no choice).', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
			</table>
		</div>

		<!-- ── Categories ────────────────────────────────────────── -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Category descriptions', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Shown next to each toggle in the preferences panel (Customize). Leave blank to use the defaults.', 'ai-eshop-optimizer' ); ?></p>
			<table class="form-table">
				<?php foreach ( array( 'necessary', 'functional', 'analytics', 'marketing' ) as $cat ) : ?>
				<tr>
					<th scope="row"><?php echo esc_html( $cat_labels[ $cat ] ); ?></th>
					<td><textarea name="desc_<?php echo esc_attr( $cat ); ?>" rows="2" class="large-text"><?php echo esc_textarea( isset( $s[ 'desc_' . $cat ] ) ? (string) $s[ 'desc_' . $cat ] : '' ); ?></textarea></td>
				</tr>
				<?php endforeach; ?>
			</table>
		</div>

		<!-- ── Bottom-bar appearance ──────────────────────────────── -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Bottom-bar appearance', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Colours + text sizes for the horizontal bottom-bar layout (BBC-style title | description | links).', 'ai-eshop-optimizer' ); ?></p>
			<?php
			$color_row( __( 'Background', 'ai-eshop-optimizer' ), 'bar_bg' );
			$color_row( __( 'Links (Yes / No)', 'ai-eshop-optimizer' ), 'bar_link_color' );
			$color_row( __( 'Main text', 'ai-eshop-optimizer' ), 'bar_text_color' );
			$color_row( __( 'Description', 'ai-eshop-optimizer' ), 'bar_desc_color' );
			?>
			<p style="margin:6px 0;display:flex;align-items:center;gap:10px;">
				<label style="width:130px;display:inline-block;color:#374151;font-size:13px;"><?php esc_html_e( 'Main text size', 'ai-eshop-optimizer' ); ?></label>
				<input type="text" name="bar_text_size" value="<?php echo esc_attr( isset( $s['bar_text_size'] ) ? $s['bar_text_size'] : '' ); ?>" placeholder="18px" style="width:90px;">
			</p>
			<p style="margin:6px 0;display:flex;align-items:center;gap:10px;">
				<label style="width:130px;display:inline-block;color:#374151;font-size:13px;"><?php esc_html_e( 'Description size', 'ai-eshop-optimizer' ); ?></label>
				<input type="text" name="bar_desc_size" value="<?php echo esc_attr( isset( $s['bar_desc_size'] ) ? $s['bar_desc_size'] : '' ); ?>" placeholder="14px" style="width:90px;">
			</p>
		</div>

		<!-- ── Theming ───────────────────────────────────────────── -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Button colours', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:820px;"><?php esc_html_e( 'Accept and Decline keep the same size and shape by design (equal prominence). Don\'t hide Decline — regulators treat a faint "reject" as a dark pattern. Customize may be lighter. Use "transparent" for a see-through background.', 'ai-eshop-optimizer' ); ?></p>
			<div style="display:flex;gap:32px;flex-wrap:wrap;">
				<?php foreach ( $btn_groups as $btn => $glabel ) : ?>
				<div style="min-width:300px;">
					<h4 style="margin:0 0 6px;"><?php echo esc_html( $glabel ); ?></h4>
					<?php
					$color_row( __( 'Background', 'ai-eshop-optimizer' ),    'btn_' . $btn . '_bg' );
					$color_row( __( 'Text', 'ai-eshop-optimizer' ),          'btn_' . $btn . '_fg' );
					$color_row( __( 'Border', 'ai-eshop-optimizer' ),        'btn_' . $btn . '_border' );
					$color_row( __( 'Hover background', 'ai-eshop-optimizer' ), 'btn_' . $btn . '_bg_hover' );
					$color_row( __( 'Hover text', 'ai-eshop-optimizer' ),    'btn_' . $btn . '_fg_hover' );
					$color_row( __( 'Hover border', 'ai-eshop-optimizer' ),  'btn_' . $btn . '_border_hover' );
					?>
				</div>
				<?php endforeach; ?>
			</div>
		</div>

		<p>
			<button type="button" class="button button-primary" id="aieo-dmm-consent-save"><?php esc_html_e( 'Save settings', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-dmm-consent-status" style="margin-left:10px;font-weight:600;"></span>
		</p>
	</form>

	<!-- ── Cookie inventory ──────────────────────────────────────── -->
	<div class="aieo-dmm-card" id="aieo-cmp-inventory">
		<h3><?php esc_html_e( 'Cookie inventory (scanner)', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:880px;"><?php esc_html_e( 'Cookies and third-party services seen on your storefront, classified against a built-in database. Re-assign anything in the "Unclassified" bucket so the categories your visitors see are accurate; your choices override the built-in database. Use "Re-scan storefront now" to refresh this list on demand — handy when live scanning is off.', 'ai-eshop-optimizer' ); ?></p>
		<p style="margin:10px 0 4px;">
			<button type="button" class="button button-secondary" id="aieo-cmp-rescan"><?php esc_html_e( 'Re-scan storefront now', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-cmp-rescan-status" style="margin-left:10px;font-weight:600;"></span>
		</p>
		<p class="description" style="max-width:880px;"><?php esc_html_e( 'Loads your storefront in the background (homepage, cart, checkout, shop) and refreshes this list with the cookies + services currently set — even when live scanning is off. Run it after adding a new third-party script. Tip: grant consent once on the storefront first so consent-gated cookies are included.', 'ai-eshop-optimizer' ); ?></p>
		<?php
		$aieo_rescan_urls = array( home_url( '/' ) );
		if ( function_exists( 'wc_get_cart_url' ) )      { $aieo_rescan_urls[] = wc_get_cart_url(); }
		if ( function_exists( 'wc_get_checkout_url' ) )   { $aieo_rescan_urls[] = wc_get_checkout_url(); }
		if ( function_exists( 'wc_get_page_permalink' ) ) { $aieo_shop = wc_get_page_permalink( 'shop' ); if ( $aieo_shop ) { $aieo_rescan_urls[] = $aieo_shop; } }
		$aieo_rescan_urls = array_values( array_unique( array_filter( $aieo_rescan_urls ) ) );
		?>
		<script>
		(function(){
			var btn=document.getElementById('aieo-cmp-rescan'), st=document.getElementById('aieo-cmp-rescan-status');
			if(!btn){ return; }
			var urls=<?php echo wp_json_encode( $aieo_rescan_urls ); ?>;
			var L_scan=<?php echo wp_json_encode( __( 'Scanning', 'ai-eshop-optimizer' ) ); ?>;
			var L_done=<?php echo wp_json_encode( __( 'Done — refreshing the list…', 'ai-eshop-optimizer' ) ); ?>;
			// Loads each storefront page in a background iframe with ?aieo_cmp_forcescan=1.
			// The admin is logged-in, so the request bypasses the page cache (fresh sweep
			// code) and the storefront sweep runs once, reporting cookies + service hosts.
			btn.addEventListener('click',function(){
				btn.disabled=true; st.style.color='#2271b1'; st.textContent=L_scan+' (0/'+urls.length+')';
				var i=0;
				function next(){
					if(i>=urls.length){ st.style.color='#15803d'; st.textContent=L_done; setTimeout(function(){ location.reload(); },1500); return; }
					var u=urls[i], sep=(u.indexOf('?')>-1?'&':'?');
					var f=document.createElement('iframe');
					f.style.cssText='position:fixed;left:-10000px;top:0;width:1024px;height:800px;border:0;';
					var done=false, fin=function(){ if(done){return;} done=true; try{ document.body.removeChild(f); }catch(e){} i++; st.textContent=L_scan+' ('+i+'/'+urls.length+')'; next(); };
					f.onload=function(){ setTimeout(fin,4000); };  // sweep fires at load+1.5s; allow the beacon to send
					setTimeout(fin,10000);                          // hard cap per page (blocked iframe / slow load)
					f.src=u+sep+'aieo_cmp_forcescan=1&_='+Date.now();
					document.body.appendChild(f);
				}
				next();
			});
		})();
		</script>
		<?php
		$total = 0;
		foreach ( $inventory as $rows ) { $total += is_array( $rows ) ? count( $rows ) : 0; }
		?>
		<?php if ( 0 === $total ) : ?>
			<p class="description" style="color:#9ca3af;"><?php esc_html_e( 'Nothing scanned yet. Enable the banner and visit the storefront — the inventory fills as pages load.', 'ai-eshop-optimizer' ); ?></p>
		<?php else : ?>
			<?php foreach ( array( 'unclassified', 'necessary', 'functional', 'analytics', 'marketing' ) as $cat ) :
				$rows = isset( $inventory[ $cat ] ) ? $inventory[ $cat ] : array();
				if ( empty( $rows ) ) { continue; }
				?>
				<h4 style="margin:18px 0 6px;<?php echo 'unclassified' === $cat ? 'color:#b45309;' : ''; ?>"><?php echo esc_html( $cat_labels[ $cat ] ); ?> <span style="color:#9ca3af;font-weight:400;">(<?php echo (int) count( $rows ); ?>)</span></h4>
				<table class="widefat striped">
					<thead><tr>
						<th><?php esc_html_e( 'Name', 'ai-eshop-optimizer' ); ?></th>
						<th><?php esc_html_e( 'Service', 'ai-eshop-optimizer' ); ?></th>
						<th><?php esc_html_e( 'Hits', 'ai-eshop-optimizer' ); ?></th>
						<th><?php esc_html_e( 'Pre-consent', 'ai-eshop-optimizer' ); ?></th>
						<th><?php esc_html_e( 'Category', 'ai-eshop-optimizer' ); ?></th>
						<th></th>
					</tr></thead>
					<tbody>
					<?php foreach ( $rows as $r ) :
						$rname = isset( $r->name ) ? (string) $r->name : '';
						$rcat  = isset( $r->category ) ? (string) $r->category : '';
						$rsvc  = isset( $r->service ) ? (string) $r->service : '';
						?>
						<tr data-name="<?php echo esc_attr( $rname ); ?>">
							<td><code style="font-size:12px;"><?php echo esc_html( $rname ); ?></code><?php echo ( isset( $r->status ) && 'reviewed' === $r->status ) ? ' <span style="font-size:11px;color:#15803d;">' . esc_html__( '✓ reviewed', 'ai-eshop-optimizer' ) . '</span>' : ''; ?><?php echo ( isset( $r->description ) && '' !== (string) $r->description ) ? '<br><span style="font-size:12px;color:#6b7280;">' . esc_html( (string) $r->description ) . '</span>' : ''; ?></td>
							<td><input type="text" class="aieo-cmp-inv-service" value="<?php echo esc_attr( $rsvc ); ?>" style="width:140px;font-size:12px;"></td>
							<td><?php echo (int) ( isset( $r->hits ) ? $r->hits : 0 ); ?></td>
							<td><?php echo ! empty( $r->pre_consent ) ? '<span style="color:#b91c1c;">' . esc_html__( 'yes', 'ai-eshop-optimizer' ) . '</span>' : '&mdash;'; ?></td>
							<td>
								<select class="aieo-cmp-inv-cat" style="font-size:12px;">
									<option value=""           <?php selected( $rcat, '' ); ?>><?php esc_html_e( '— unclassified —', 'ai-eshop-optimizer' ); ?></option>
									<option value="necessary"  <?php selected( $rcat, 'necessary' ); ?>><?php esc_html_e( 'Strictly necessary', 'ai-eshop-optimizer' ); ?></option>
									<option value="functional" <?php selected( $rcat, 'functional' ); ?>><?php esc_html_e( 'Functional', 'ai-eshop-optimizer' ); ?></option>
									<option value="analytics"  <?php selected( $rcat, 'analytics' ); ?>><?php esc_html_e( 'Analytics', 'ai-eshop-optimizer' ); ?></option>
									<option value="marketing"  <?php selected( $rcat, 'marketing' ); ?>><?php esc_html_e( 'Marketing', 'ai-eshop-optimizer' ); ?></option>
								</select>
							</td>
							<td><button type="button" class="button button-small aieo-cmp-inv-save"><?php esc_html_e( 'Save', 'ai-eshop-optimizer' ); ?></button></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
			<?php endforeach; ?>
			<p style="margin-top:14px;"><button type="button" class="button" id="aieo-cmp-inv-clear"><?php esc_html_e( 'Clear inventory', 'ai-eshop-optimizer' ); ?></button> <span id="aieo-cmp-inv-status" style="margin-left:8px;color:#6b7280;"></span></p>
		<?php endif; ?>
	</div>
</div>

<script>
(function(){
	var NONCE = '<?php echo esc_js( $nonce ); ?>', AJAX = '<?php echo esc_js( $ajax ); ?>';

	// ── Save settings ──
	var form = document.getElementById('aieo-dmm-consent-form');
	var btn  = document.getElementById('aieo-dmm-consent-save');
	var stat = document.getElementById('aieo-dmm-consent-status');
	if (form && btn) {
		btn.addEventListener('click', function(){
			// Sync the TinyMCE message editor into its textarea before reading the form.
			try { if (window.tinyMCE) { tinyMCE.triggerSave(); } } catch(e){}
			var fd = new FormData(form);
			fd.set('action', 'aieo_dmm_consent_save');
			fd.set('nonce', NONCE);
			stat.style.color = '#6b7280';
			stat.textContent = '<?php echo esc_js( __( 'Saving…', 'ai-eshop-optimizer' ) ); ?>';
			fetch(AJAX, { method:'POST', credentials:'same-origin', body: fd })
				.then(function(r){ return r.json(); })
				.then(function(j){
					if (j && j.success) { stat.style.color = '#15803d'; stat.textContent = j.data.message; }
					else { stat.style.color = '#b91c1c'; stat.textContent = (j && j.data && j.data.message) ? j.data.message : 'Save failed.'; }
				})
				.catch(function(){ stat.style.color = '#b91c1c'; stat.textContent = 'Network error.'; });
		});
	}

	// ── Inventory: per-row Save (classify) ──
	Array.prototype.forEach.call(document.querySelectorAll('.aieo-cmp-inv-save'), function(b){
		b.addEventListener('click', function(){
			var tr = b.closest('tr'); if (!tr) { return; }
			var name = tr.getAttribute('data-name');
			var cat  = tr.querySelector('.aieo-cmp-inv-cat');
			var svc  = tr.querySelector('.aieo-cmp-inv-service');
			var fd = new FormData();
			fd.set('action', 'aieo_dmm_consent_classify');
			fd.set('nonce', NONCE);
			fd.set('name', name);
			fd.set('category', cat ? cat.value : '');
			fd.set('service', svc ? svc.value : '');
			b.disabled = true; var old = b.textContent; b.textContent = '…';
			fetch(AJAX, { method:'POST', credentials:'same-origin', body: fd })
				.then(function(r){ return r.json(); })
				.then(function(j){ b.disabled = false; b.textContent = (j && j.success) ? '✓' : '!'; setTimeout(function(){ b.textContent = old; }, 1500); })
				.catch(function(){ b.disabled = false; b.textContent = old; });
		});
	});

	// ── Inventory: clear ──
	var clr = document.getElementById('aieo-cmp-inv-clear');
	var cst = document.getElementById('aieo-cmp-inv-status');
	if (clr) {
		clr.addEventListener('click', function(){
			if (!window.confirm('<?php echo esc_js( __( 'Clear the whole cookie inventory? It will repopulate as visitors browse.', 'ai-eshop-optimizer' ) ); ?>')) { return; }
			var fd = new FormData(); fd.set('action', 'aieo_dmm_consent_clear'); fd.set('nonce', NONCE);
			fetch(AJAX, { method:'POST', credentials:'same-origin', body: fd })
				.then(function(r){ return r.json(); })
				.then(function(j){ if (cst) { cst.textContent = (j && j.success) ? '<?php echo esc_js( __( 'Cleared. Reload to refresh the list.', 'ai-eshop-optimizer' ) ); ?>' : 'Failed.'; } });
		});
	}
})();
</script>
