<?php

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

$enabled   = ! empty( $seo['enabled'] );
$separator = isset( $seo['separator'] ) && '' !== $seo['separator'] ? (string) $seo['separator'] : '-';

$site_profile     = isset( $seo['site_profile'] ) ? (string) $seo['site_profile'] : 'auto';
$detected_profile = isset( $detected_profile ) ? (string) $detected_profile : 'shop';
$profile_labels   = array(
	'shop'    => __( 'Shop (transactional)', 'ai-eshop-optimizer' ),
	'catalog' => __( 'Catalog (products as content)', 'ai-eshop-optimizer' ),
	'content' => __( 'Content site (no WooCommerce)', 'ai-eshop-optimizer' ),
);

$rg             = ( isset( $seo['robots_global'] ) && is_array( $seo['robots_global'] ) ) ? $seo['robots_global'] : null;
$noindex_pag    = ( null === $rg ) ? true : ! empty( $rg['noindex_paginated'] );
$nofollow_pag   = ( null === $rg ) ? false : ! empty( $rg['nofollow_paginated'] );
$noindex_date   = ! empty( $rg['noindex_date'] );
$noindex_author = ! empty( $rg['noindex_author'] );
?>
<div class="aieo-dmm-section">
	<h2><?php esc_html_e( 'SEO Engine', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description" style="max-width:860px;">
		<?php esc_html_e( 'The in-house, performance-driven SEO engine — the lean, Greek-aware replacement for AIOSEO. It optimises titles, meta, canonical URLs, schema and the sitemap from your real sales and demand data, and serves the entire head from a materialised cache (~0 ms). Turning it on here is safe: AIEO only takes over the page head once a competitor SEO plugin (AIOSEO / Yoast / Rank Math) is no longer active.', 'ai-eshop-optimizer' ); ?>
	</p>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Provider status', 'ai-eshop-optimizer' ); ?></h3>
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Competitor SEO plugin', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<?php if ( '' !== $competitor ) : ?>
						<span style="color:#b45309;font-weight:600;">●</span>
						<?php
						echo esc_html( sprintf(
							
							__( '%s is active', 'ai-eshop-optimizer' ),
							$competitor
						) );
						?>
					<?php else : ?>
						<span style="color:#15803d;font-weight:600;">●</span>
						<?php esc_html_e( 'None detected', 'ai-eshop-optimizer' ); ?>
					<?php endif; ?>
				</td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'AIEO is the active provider', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<?php if ( $is_active ) : ?>
						<span style="color:#15803d;font-weight:700;">✓ <?php esc_html_e( 'Yes — AIEO serves the page head', 'ai-eshop-optimizer' ); ?></span>
					<?php else : ?>
						<span style="color:#6b7280;font-weight:600;">— <?php esc_html_e( 'No (augment-only)', 'ai-eshop-optimizer' ); ?></span>
					<?php endif; ?>
				</td>
			</tr>
		</table>
		<?php if ( '' !== $competitor && $enabled ) : ?>
			<p class="description" style="color:#b45309;">
				<?php
				echo esc_html( sprintf(
					
					__( 'The engine is enabled but %s is still active, so AIEO stays in augment-only mode (it contributes ratings to the competitor\'s schema but does not emit its own head). Deactivate the competitor to complete the cut-over.', 'ai-eshop-optimizer' ),
					$competitor
				) );
				?>
			</p>
		<?php endif; ?>
	</div>

	<form id="aieo-seo-general-form" class="aieo-dmm-card">
		<h3><?php esc_html_e( 'General', 'ai-eshop-optimizer' ); ?></h3>
		<table class="form-table">
			<tr>
				<th scope="row"><?php esc_html_e( 'Enable AIEO SEO engine', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<label>
						<input type="checkbox" name="enabled" value="1" <?php checked( $enabled ); ?>>
						<?php esc_html_e( 'Let AIEO own the page head once no competitor SEO plugin is active', 'ai-eshop-optimizer' ); ?>
					</label>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Title separator', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<input type="text" name="separator" value="<?php echo esc_attr( $separator ); ?>" class="small-text" maxlength="8">
					<p class="description"><?php esc_html_e( 'The character placed between title parts (the #separator_sa smart tag). Default: -', 'ai-eshop-optimizer' ); ?></p>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Site profile', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<select name="site_profile">
						<option value="auto" <?php selected( 'auto', $site_profile ); ?>>
							<?php
							echo esc_html( sprintf(
								
								__( 'Auto — detected: %s', 'ai-eshop-optimizer' ),
								isset( $profile_labels[ $detected_profile ] ) ? $profile_labels[ $detected_profile ] : $detected_profile
							) );
							?>
						</option>
						<?php foreach ( $profile_labels as $pk => $pl ) : ?>
							<option value="<?php echo esc_attr( $pk ); ?>" <?php selected( $pk, $site_profile ); ?>><?php echo esc_html( $pl ); ?></option>
						<?php endforeach; ?>
					</select>
					<p class="description" style="max-width:640px;">
						<?php esc_html_e( 'Drives what "success" means in Opportunities, cornerstone (pillar) selection and the demand score. Shops weigh add-to-cart and sales; catalog sites (products published but deliberately not sold — no add to cart / checkout) and content sites weigh visits and engagement instead. Auto detects from WooCommerce + sales history; pin it explicitly for catalog-by-design sites so a stray test order can never flip the profile.', 'ai-eshop-optimizer' ); ?>
					</p>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'AI Autopilot', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<input type="hidden" name="autopilot_present" value="1">
					<label>
						<input type="checkbox" name="autopilot" value="1" <?php checked( ! empty( $seo['autopilot'] ) ); ?>>
						<?php esc_html_e( 'Apply AI-written titles/descriptions immediately (no draft review)', 'ai-eshop-optimizer' ); ?>
					</label>
					<p class="description" style="max-width:640px;">
						<?php esc_html_e( 'Off = the nightly write queue saves SERP-informed suggestions as drafts you approve on SEO → Health. On = they go live automatically and heads rebuild. Per-object opt-out: tick "AI locked" on the object.', 'ai-eshop-optimizer' ); ?>
					</p>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Archive robots', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<input type="hidden" name="robots_global_present" value="1">
					<label>
						<input type="checkbox" name="noindex_paginated" value="1" <?php checked( $noindex_pag ); ?>>
						<?php esc_html_e( 'noindex paginated pages (/page/2/…) — out of the index, still crawled (follow)', 'ai-eshop-optimizer' ); ?>
					</label><br>
					<label>
						<input type="checkbox" name="nofollow_paginated" value="1" <?php checked( $nofollow_pag ); ?>>
						<?php esc_html_e( 'nofollow paginated pages (not recommended — hides deep content from crawlers)', 'ai-eshop-optimizer' ); ?>
					</label><br>
					<label>
						<input type="checkbox" name="noindex_date" value="1" <?php checked( $noindex_date ); ?>>
						<?php esc_html_e( 'noindex date archives (/2026/07/…)', 'ai-eshop-optimizer' ); ?>
					</label><br>
					<label>
						<input type="checkbox" name="noindex_author" value="1" <?php checked( $noindex_author ); ?>>
						<?php esc_html_e( 'noindex author archives', 'ai-eshop-optimizer' ); ?>
					</label>
					<p class="description" style="max-width:640px;">
						<?php esc_html_e( 'Paginated pages also get a self-referential canonical (their own /page/N/ URL) instead of pointing at page 1 — together these clear the “Duplicate without user-selected canonical” / “Alternative page with proper canonical tag” reports in Search Console. Search result pages are already noindexed by WordPress core.', 'ai-eshop-optimizer' ); ?>
					</p>
				</td>
			</tr>
		</table>
		<p>
			<button type="button" class="button button-primary" id="aieo-seo-save"><?php esc_html_e( 'Save settings', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-seo-status" style="margin-left:10px;font-weight:600;"></span>
		</p>
	</form>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Head cache', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:860px;">
			<?php esc_html_e( 'AIEO serves the whole page head from a materialised cache, so there is ~0 ms render cost. Heads are (re)built automatically when you edit a product/post/term and on the scheduled data-prep run. Before going live (cut-over), rebuild the full cache once so every page is warm. This only builds while AIEO is the active provider.', 'ai-eshop-optimizer' ); ?>
		</p>
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Cached heads', 'ai-eshop-optimizer' ); ?></th>
				<td><strong id="aieo-seo-hc-count"><?php echo (int) $head_cache_count; ?></strong></td>
			</tr>
		</table>
		<p>
			<button type="button" class="button button-primary" id="aieo-seo-rebuild"<?php disabled( ! $is_active ); ?>><?php esc_html_e( 'Rebuild head cache', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-seo-rebuild-status" style="margin-left:10px;font-weight:600;"></span>
		</p>
		<?php if ( ! $is_active ) : ?>
			<p class="description" style="color:#6b7280;"><?php esc_html_e( 'Rebuild is available once the engine is enabled and no competitor SEO plugin is active.', 'ai-eshop-optimizer' ); ?></p>
		<?php endif; ?>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'DataForSEO connection', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:860px;margin-top:0;">
			<?php esc_html_e( 'Connect this site to DataForSEO to enrich the SEO engine with real search data — keyword volumes, live rankings, competitor SERPs — feeding content optimisation, cornerstone selection and automated title/description writing (see docs/DATAFORSEO-INTEGRATION-PLAN.md). Per-site credential: paste login:password or the Base64 string from your DataForSEO dashboard → API Access. Verification uses a free endpoint; data pulls are billed by DataForSEO per request.', 'ai-eshop-optimizer' ); ?>
		</p>
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Status', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<?php if ( ! empty( $dfs_connected ) ) : ?>
						<span style="color:#15803d;font-weight:600;">●</span>
						<?php
						echo esc_html( sprintf(
							
							__( 'Configured (%s)', 'ai-eshop-optimizer' ),
							! empty( $dfs_login ) ? $dfs_login : __( 'credential stored', 'ai-eshop-optimizer' )
						) );
						?>
					<?php else : ?>
						<span style="color:#6b7280;font-weight:600;">●</span> <?php esc_html_e( 'Not connected', 'ai-eshop-optimizer' ); ?>
					<?php endif; ?>
				</td>
			</tr>
			<tr>
				<th><label for="aieo-dfs-credentials"><?php esc_html_e( 'API credentials', 'ai-eshop-optimizer' ); ?></label></th>
				<td>
					<input type="password" id="aieo-dfs-credentials" class="regular-text" autocomplete="off"
						placeholder="<?php echo esc_attr( ! empty( $dfs_connected ) ? __( 'Stored — paste to replace, or just Test', 'ai-eshop-optimizer' ) : 'login:password or Base64' ); ?>">
					<p class="description"><?php esc_html_e( 'Stored server-side in a non-autoloaded option; never rendered back. A fresh DataForSEO account must verify its e-mail before the API accepts calls.', 'ai-eshop-optimizer' ); ?></p>
				</td>
			</tr>
		</table>
		<p>
			<button type="button" class="button button-primary" id="aieo-dfs-connect"><?php echo esc_html( ! empty( $dfs_connected ) ? __( 'Test / update connection', 'ai-eshop-optimizer' ) : __( 'Connect & test', 'ai-eshop-optimizer' ) ); ?></button>
			<?php if ( ! empty( $dfs_connected ) ) : ?>
				<button type="button" class="button" id="aieo-dfs-disconnect"><?php esc_html_e( 'Disconnect', 'ai-eshop-optimizer' ); ?></button>
			<?php endif; ?>
			<span id="aieo-dfs-status" style="margin-left:10px;font-weight:600;"></span>
		</p>
		<?php if ( ! empty( $dfs_connected ) ) : ?>
			<?php
			$dfs_locale    = ( isset( $dfs_locale ) && is_array( $dfs_locale ) ) ? $dfs_locale : array( 'location_code' => 2840, 'language_code' => 'en' );
			$dfs_last_pull = ( isset( $dfs_last_pull ) && is_array( $dfs_last_pull ) ) ? $dfs_last_pull : array();
			?>
			<hr style="margin:14px 0;">
			<h4 style="margin:0 0 6px;"><?php esc_html_e( 'Ranked-keywords snapshot (weekly)', 'ai-eshop-optimizer' ); ?></h4>
			<p class="description" style="max-width:860px;margin-top:0;">
				<?php esc_html_e( 'Every keyword this domain ranks for — position, volume, ETV, intent — pulled weekly by the nightly cron, resolved to your pages via the canonical index, and materialised as per-page search aggregates (volume, best position, striking-distance count). Positions are noisy day-to-day: weekly is signal, daily is spend. Location 2840 = United States, 2826 = United Kingdom, 2300 = Greece.', 'ai-eshop-optimizer' ); ?>
			</p>
			<p style="display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;">
				<label><?php esc_html_e( 'Location', 'ai-eshop-optimizer' ); ?> <input type="number" id="aieo-dfs-location" class="small-text" style="width:80px" value="<?php echo (int) $dfs_locale['location_code']; ?>"></label>
				<label><?php esc_html_e( 'Language', 'ai-eshop-optimizer' ); ?> <input type="text" id="aieo-dfs-language" class="small-text" style="width:50px" maxlength="8" value="<?php echo esc_attr( $dfs_locale['language_code'] ); ?>"></label>
				<label><?php esc_html_e( 'Monthly budget $', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.5" min="0" id="aieo-dfs-budget" class="small-text" style="width:70px" value="<?php echo esc_attr( isset( $dfs_budget ) ? $dfs_budget : 5 ); ?>"></label>
				<button type="button" class="button" id="aieo-dfs-pull"><?php esc_html_e( 'Pull rankings now', 'ai-eshop-optimizer' ); ?></button>
				<span id="aieo-dfs-pull-status" style="font-size:12px;"></span>
			</p>
			<p class="description">
				<?php
				if ( ! empty( $dfs_last_pull['finished_at'] ) ) {
					echo esc_html( sprintf(
						
						__( 'Last snapshot: %1$d keywords ($%2$s) %3$s ago. Spend this month: $%4$s.', 'ai-eshop-optimizer' ),
						(int) ( $dfs_last_pull['rows'] ?? 0 ),
						number_format_i18n( (float) ( $dfs_last_pull['cost'] ?? 0 ), 4 ),
						human_time_diff( (int) $dfs_last_pull['finished_at'] ),
						number_format_i18n( isset( $dfs_spend ) ? (float) $dfs_spend : 0, 4 )
					) );
				} else {
					esc_html_e( 'No snapshot yet — the weekly cron will run one, or pull now.', 'ai-eshop-optimizer' );
				}
				?>
			</p>
		<?php endif; ?>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Conversion goals', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:860px;margin-top:0;">
			<?php esc_html_e( 'What counts as a CONVERSION on this site — a site can have several. Pick the exact Gravity Forms whose submission is a goal; Newsletter signups are covered by our Newsletter-plugin integration below. Each conversion is recorded (consent-gated) into the session stream, attributed to its page, and folded into content engagement/demand exactly like add-to-cart is for shops. "Analyse" reads the form’s fields with AI and stores its goal context — the SEO write queue then writes titles/descriptions toward that actual conversion.', 'ai-eshop-optimizer' ); ?>
		</p>
		<?php
		$goal_forms  = ( isset( $goal_forms ) && is_array( $goal_forms ) ) ? $goal_forms : array();
		$goal_config = ( isset( $goal_config ) && is_array( $goal_config ) ) ? $goal_config : array( 'forms' => array(), 'builtin' => array() );
		?>
		<?php if ( empty( $goal_forms ) ) : ?>
			<p class="description"><?php esc_html_e( 'Gravity Forms not detected — form goals need it (the supported form provider).', 'ai-eshop-optimizer' ); ?></p>
		<?php else : ?>
			<table class="widefat striped" style="max-width:960px;" id="aieo-goal-forms">
				<thead><tr>
					<th style="width:60px;"><?php esc_html_e( 'Goal?', 'ai-eshop-optimizer' ); ?></th>
					<th style="width:260px;"><?php esc_html_e( 'Form', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'AI goal context (feeds the SEO writer)', 'ai-eshop-optimizer' ); ?></th>
					<th style="width:90px;"></th>
				</tr></thead>
				<tbody>
				<?php foreach ( $goal_forms as $gk => $gf ) :
					$saved = isset( $goal_config['forms'][ $gk ] ) ? $goal_config['forms'][ $gk ] : array();
					?>
					<tr data-key="<?php echo esc_attr( $gk ); ?>" data-provider="<?php echo esc_attr( $gf['provider'] ); ?>" data-form="<?php echo (int) $gf['form_id']; ?>">
						<td><input type="checkbox" class="aieo-goal-on" <?php checked( ! empty( $saved['on'] ) ); ?>></td>
						<td>
							<strong><?php echo esc_html( $gf['title'] ?: ( '#' . $gf['form_id'] ) ); ?></strong>
							<br><span style="color:#94a3b8;font-size:11px;"><?php echo esc_html( $gf['provider'] . ' #' . $gf['form_id'] ); ?></span>
							<?php if ( ! empty( $saved['label'] ) ) : ?>
								<br><span style="color:#7c3aed;font-size:11px;">★ <?php echo esc_html( $saved['label'] ); ?></span>
							<?php endif; ?>
						</td>
						<td class="aieo-goal-context" style="font-size:12px;color:#475569;"><?php echo esc_html( (string) ( $saved['context'] ?? '' ) ); ?></td>
						<td><button type="button" class="button button-small aieo-goal-analyze"><?php esc_html_e( 'Analyse', 'ai-eshop-optimizer' ); ?></button></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		<?php endif; ?>
		<p style="display:flex;flex-wrap:wrap;gap:6px 18px;align-items:center;margin-top:10px;">
			<?php
			$builtin_labels = array(
				'newsletter_signup' => __( 'Newsletter signups', 'ai-eshop-optimizer' ),
				'course_enroll'     => __( 'Course enrolments', 'ai-eshop-optimizer' ),
				'lesson_complete'   => __( 'Lesson completions', 'ai-eshop-optimizer' ),
				'user_register'     => __( 'Registrations', 'ai-eshop-optimizer' ),
			);
			foreach ( $builtin_labels as $bk => $bl ) :
				?>
				<label style="white-space:nowrap;"><input type="checkbox" class="aieo-goal-builtin" data-key="<?php echo esc_attr( $bk ); ?>" <?php checked( ! empty( $goal_config['builtin'][ $bk ] ) ); ?>> <?php echo esc_html( $bl ); ?></label>
			<?php endforeach; ?>
		</p>
		<p style="margin-top:4px;">
			<label>
				<input type="checkbox" class="aieo-goal-builtin" data-key="gravity_attribution" <?php checked( class_exists( 'AIEO_Goal_Tracker' ) && AIEO_Goal_Tracker::gravity_attribution_on() ); ?>>
				<?php esc_html_e( 'Append campaign attribution to Gravity notification emails', 'ai-eshop-optimizer' ); ?>
			</label>
			<span class="description" style="margin-left:6px;">
				<?php esc_html_e( 'Adds the same styled block as the order emails: channel + all five utm_* properties + gclid + landing page + original referrer + IP. A gclid alone is classified as Paid · Google Ads (Google Ads auto-tagging sends no utm parameters). Values come from the entry’s own utm_*/gclid fields when the form has them, else AIEO’s session capture / HandL-style cookies — no per-site snippets needed. Staff notifications only; visitor autoresponders are never touched. Also auto-prefills utm_* form fields and strips tracking parameters from the page URL sent to HubSpot.', 'ai-eshop-optimizer' ); ?>
			</span>
		</p>
		<p>
			<button type="button" class="button button-primary" id="aieo-goals-save"><?php esc_html_e( 'Save goals', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-goals-status" style="margin-left:10px;font-weight:600;"></span>
		</p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Canonical categories', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:860px;">
			<?php esc_html_e( 'A product in several categories has ONE canonical category that drives its URL + canonical link. Pick it per product in the product editor (the "AIEO SEO" box). To seed every product that has none pinned yet with its first-assigned category, run the bulk backfill (skips products you already set, safe to re-run):', 'ai-eshop-optimizer' ); ?>
		</p>
		<p>
			<button type="button" class="button" id="aieo-seo-backfill-canon"><?php esc_html_e( 'Set missing canonical categories = first assigned', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-seo-backfill-status" style="margin-left:10px;font-weight:600;"></span>
		</p>
	</div>
</div>
<script>
(function(){
	var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
	var btn = document.getElementById('aieo-seo-save'), st = document.getElementById('aieo-seo-status');
	if (!btn) { return; }
	btn.addEventListener('click', function(){
		st.style.color = '#6b7280';
		st.textContent = <?php echo wp_json_encode( __( 'Saving…', 'ai-eshop-optimizer' ) ); ?>;
		var fd = new FormData(document.getElementById('aieo-seo-general-form'));
		fd.set('action', 'aieo_dmm_save_seo');
		fd.set('nonce', nonce);
		fetch(ajax, { method:'POST', credentials:'same-origin', body: fd })
			.then(function(r){ return r.json(); })
			.then(function(j){
				if (j && j.success) {
					st.style.color = '#15803d';
					st.textContent = (j.data && j.data.message) || 'Saved.';
					setTimeout(function(){ location.reload(); }, 700);
				} else {
					st.style.color = '#b91c1c';
					st.textContent = (j && j.data && j.data.message) || 'Save failed.';
				}
			})
			.catch(function(){ st.style.color = '#b91c1c'; st.textContent = 'Network error.'; });
	});
})();
</script>
<script>
(function(){
	var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
	var btn = document.getElementById('aieo-seo-rebuild');
	if (!btn) { return; }
	var st = document.getElementById('aieo-seo-rebuild-status');
	var cnt = document.getElementById('aieo-seo-hc-count');
	btn.addEventListener('click', function(){
		btn.disabled = true;
		var total = 0, first = true, guard = 0, cursor = null;
		st.style.color = '#6b7280';
		function step(){
			if (++guard > 20000) { st.style.color = '#b91c1c'; st.textContent = 'Stopped (too many iterations).'; btn.disabled = false; return; }
			var fd = new FormData();
			fd.set('action', 'aieo_seo_rebuild_head_cache');
			fd.set('nonce', nonce);
			if (first) { fd.set('reset', '1'); first = false; }
			else if (cursor) { fd.set('phase', cursor.phase); fd.set('last_id', cursor.last_id); fd.set('last_tax', cursor.last_tax || ''); }
			fetch(ajax, { method:'POST', credentials:'same-origin', body: fd })
				.then(function(r){ return r.json(); })
				.then(function(j){
					if (!j || !j.success) { st.style.color = '#b91c1c'; st.textContent = (j && j.data && j.data.message) || 'Rebuild failed.'; btn.disabled = false; return; }
					total += (j.data.built | 0);
					cursor = j.data.cursor || null;
					if (cnt && typeof j.data.total !== 'undefined') { cnt.textContent = j.data.total; }
					if (j.data.done) {
						st.style.color = '#15803d';
						st.textContent = <?php echo wp_json_encode( __( 'Done — cached heads:', 'ai-eshop-optimizer' ) ); ?> + ' ' + ((j.data.total | 0) || total);
						btn.disabled = false;
					} else {
						st.textContent = <?php echo wp_json_encode( __( 'Building… processed', 'ai-eshop-optimizer' ) ); ?> + ' ' + total;
						step();
					}
				})
				.catch(function(){ st.style.color = '#b91c1c'; st.textContent = 'Network error.'; btn.disabled = false; });
		}
		step();
	});
})();
</script>
<script>
(function(){
	var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
	var btn = document.getElementById('aieo-dfs-connect'), st = document.getElementById('aieo-dfs-status');
	if (!btn) { return; }
	function post(action, extra, cb){
		var fd = new FormData();
		fd.set('action', action); fd.set('nonce', nonce);
		Object.keys(extra || {}).forEach(function(k){ fd.set(k, extra[k]); });
		fetch(ajax, { method:'POST', credentials:'same-origin', body: fd })
			.then(function(r){ return r.json(); }).then(cb)
			.catch(function(){ cb({ success:false, data:{ message:'Network error.' } }); });
	}
	btn.addEventListener('click', function(){
		btn.disabled = true;
		st.style.color = '#6b7280';
		st.textContent = <?php echo wp_json_encode( __( 'Testing…', 'ai-eshop-optimizer' ) ); ?>;
		var input = document.getElementById('aieo-dfs-credentials');
		post('aieo_dfs_connect', { credentials: input ? input.value : '' }, function(j){
			btn.disabled = false;
			if (j && j.success) {
				st.style.color = '#15803d';
				st.textContent = (j.data && j.data.message) || 'Connected.';
				if (input) { input.value = ''; }
				setTimeout(function(){ location.reload(); }, 900);
			} else {
				st.style.color = '#b91c1c';
				st.textContent = (j && j.data && j.data.message) || 'Failed.';
			}
		});
	});
	var dbtn = document.getElementById('aieo-dfs-disconnect');
	if (dbtn) { dbtn.addEventListener('click', function(){
		dbtn.disabled = true;
		post('aieo_dfs_disconnect', {}, function(j){
			dbtn.disabled = false;
			st.textContent = (j && j.data && j.data.message) || '';
			if (j && j.success) { setTimeout(function(){ location.reload(); }, 600); }
		});
	}); }
	// ── Conversion goals ────────────────────────────────────────────────
	var gsave = document.getElementById('aieo-goals-save'), gst = document.getElementById('aieo-goals-status');
	if (gsave) { gsave.addEventListener('click', function(){
		gsave.disabled = true;
		gst.style.color = '#6b7280'; gst.textContent = '…';
		var forms = {};
		document.querySelectorAll('#aieo-goal-forms tbody tr').forEach(function(tr){
			forms[tr.getAttribute('data-key')] = {
				on: tr.querySelector('.aieo-goal-on').checked ? 1 : 0,
				context: (tr.querySelector('.aieo-goal-context') || {}).textContent || ''
			};
		});
		var builtin = {};
		document.querySelectorAll('.aieo-goal-builtin').forEach(function(c){
			builtin[c.getAttribute('data-key')] = c.checked ? 1 : 0;
		});
		post('aieo_goals_save', { forms: JSON.stringify(forms), builtin: JSON.stringify(builtin) }, function(j){
			gsave.disabled = false;
			gst.style.color = (j && j.success) ? '#15803d' : '#b91c1c';
			gst.textContent = (j && j.data && j.data.message) || ((j && j.success) ? 'Saved.' : 'Failed.');
		});
	}); }
	document.querySelectorAll('.aieo-goal-analyze').forEach(function(b){
		b.addEventListener('click', function(){
			var tr = b.closest('tr'), ctx = tr.querySelector('.aieo-goal-context');
			b.disabled = true; ctx.textContent = '… (AI)';
			post('aieo_goal_analyze', { provider: tr.getAttribute('data-provider'), form_id: tr.getAttribute('data-form') }, function(j){
				b.disabled = false;
				if (j && j.success) {
					ctx.textContent = j.data.context || '';
					if (j.data.label) {
						var td = tr.children[1];
						var star = td.querySelector('span[style*="7c3aed"]');
						if (!star) { star = document.createElement('span'); star.style.cssText = 'color:#7c3aed;font-size:11px;'; td.appendChild(document.createElement('br')); td.appendChild(star); }
						star.textContent = '★ ' + j.data.label;
					}
				} else {
					ctx.textContent = (j && j.data && j.data.message) || 'Failed.';
				}
			});
		});
	});
	var pbtn = document.getElementById('aieo-dfs-pull'), pst = document.getElementById('aieo-dfs-pull-status');
	if (pbtn) { pbtn.addEventListener('click', function(){
		pbtn.disabled = true;
		pst.style.color = '#6b7280';
		pst.textContent = <?php echo wp_json_encode( __( 'Pulling… (paged API calls, can take a minute)', 'ai-eshop-optimizer' ) ); ?>;
		post('aieo_dfs_pull', {
			location_code: (document.getElementById('aieo-dfs-location') || {}).value || 2840,
			language_code: (document.getElementById('aieo-dfs-language') || {}).value || 'en',
			budget_usd:    (document.getElementById('aieo-dfs-budget') || {}).value || 5
		}, function(j){
			pbtn.disabled = false;
			pst.style.color = (j && j.success) ? '#15803d' : '#b91c1c';
			pst.textContent = (j && j.data && j.data.message) || ((j && j.success) ? 'Done.' : 'Failed.');
		});
	}); }
})();
</script>
<script>
(function(){
	var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
	var btn = document.getElementById('aieo-seo-backfill-canon');
	if (!btn) { return; }
	var st = document.getElementById('aieo-seo-backfill-status');
	btn.addEventListener('click', function(){
		btn.disabled = true;
		var set = 0, lastId = 0, guard = 0;
		st.style.color = '#6b7280';
		function step(){
			if (++guard > 20000) { st.style.color = '#b91c1c'; st.textContent = 'Stopped.'; btn.disabled = false; return; }
			var fd = new FormData();
			fd.set('action', 'aieo_seo_backfill_canonical');
			fd.set('nonce', nonce);
			fd.set('last_id', lastId);
			fetch(ajax, { method:'POST', credentials:'same-origin', body: fd })
				.then(function(r){ return r.json(); })
				.then(function(j){
					if (!j || !j.success) { st.style.color = '#b91c1c'; st.textContent = (j && j.data && j.data.message) || 'Failed.'; btn.disabled = false; return; }
					set += (j.data.set | 0);
					lastId = Number( j.data.last_id ) || 0; // Number() not |0 — product ids are bigint
					if (j.data.done) {
						st.style.color = '#15803d';
						st.textContent = <?php echo wp_json_encode( __( 'Done — canonical set on:', 'ai-eshop-optimizer' ) ); ?> + ' ' + set;
						btn.disabled = false;
					} else {
						st.textContent = <?php echo wp_json_encode( __( 'Setting…', 'ai-eshop-optimizer' ) ); ?> + ' ' + set;
						step();
					}
				})
				.catch(function(){ st.style.color = '#b91c1c'; st.textContent = 'Network error.'; btn.disabled = false; });
		}
		step();
	});
})();
</script>
