<?php

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

$quad_labels = array(
	'hidden_gem'      => __( 'Hidden gems', 'ai-eshop-optimizer' ),
	'intent_mismatch' => __( 'Intent mismatch', 'ai-eshop-optimizer' ),
	'defend'          => __( 'Defend', 'ai-eshop-optimizer' ),
	'prune'           => __( 'Prune', 'ai-eshop-optimizer' ),
);
$is_shop = ! isset( $profile ) || 'shop' === $profile;
?>
<div class="aieo-dmm-section aieo-opp">
	<h2><?php esc_html_e( 'Content Opportunities', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description aieo-opp-intro">
		<?php if ( $is_shop ) : ?>
			<?php esc_html_e( 'Products placed on the traffic × on-site-conversion grid from real visitor behaviour — so you act on intent, not just keyword volume. Hidden gems convert but are under-exposed; intent mismatches pull traffic that doesn’t convert. The same behavioural signal feeds cornerstone (pillar) selection. Everything below is advisory — you decide what to apply.', 'ai-eshop-optimizer' ); ?>
		<?php else : ?>
			<?php esc_html_e( 'Content placed on the traffic × engagement grid from real visitor behaviour (this site’s profile treats products as content — no cart/sales signal). Hidden gems engage strongly but are under-exposed; intent mismatches pull traffic that doesn’t stay. The same behavioural signal feeds cornerstone (pillar) selection. Everything below is advisory — you decide what to apply.', 'ai-eshop-optimizer' ); ?>
		<?php endif; ?>
	</p>

	<?php if ( ! $enabled ) : ?>
		<div class="notice notice-info inline"><p>
			<?php esc_html_e( 'The SEO engine is off. Enable it in SEO → General; opportunities build from the analytics metrics on the data-prep schedule.', 'ai-eshop-optimizer' ); ?>
		</p></div>
	<?php endif; ?>

	<p>
		<button type="button" class="button button-primary" id="aieo-opp-recompute"><?php esc_html_e( 'Recompute now', 'ai-eshop-optimizer' ); ?></button>
		<span id="aieo-opp-status" class="aieo-opp-status"></span>
	</p>

	<!-- ── Priority controls ─────────────────────────────────────────── -->
	<details class="aieo-opp-controls" <?php echo empty( $rows ) ? 'open' : ''; ?>>
		<summary><?php esc_html_e( 'Priority controls — tune how cornerstones and opportunities are scored', 'ai-eshop-optimizer' ); ?></summary>

		<div class="aieo-opp-controls-grid">
			<fieldset class="aieo-opp-fieldset">
				<legend><?php esc_html_e( 'Cornerstone (pillar) weights', 'ai-eshop-optimizer' ); ?></legend>
				<?php if ( $is_shop ) : ?>
					<p class="aieo-opp-hint"><?php esc_html_e( 'How much each signal drives cornerstone selection. “Behaviour share” is how much the behavioural discovery signal counts vs commerce — set to 0 for commerce-only.', 'ai-eshop-optimizer' ); ?></p>
					<label><?php esc_html_e( 'Sales', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="cw_sales" value="<?php echo esc_attr( $corner['sales'] ); ?>"></label>
					<label><?php esc_html_e( 'Turnover', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="cw_turnover" value="<?php echo esc_attr( $corner['turnover'] ); ?>"></label>
					<label><?php esc_html_e( 'Forecast', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="cw_forecast" value="<?php echo esc_attr( $corner['forecast'] ); ?>"></label>
				<?php else : ?>
					<p class="aieo-opp-hint"><?php esc_html_e( 'This site’s profile has no sales signal — cornerstones blend the behavioural discovery signal with internal-link centrality. “Behaviour share” is how much behaviour counts vs link centrality.', 'ai-eshop-optimizer' ); ?></p>
				<?php endif; ?>
				<label><?php esc_html_e( 'Link centrality', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="cw_links" value="<?php echo esc_attr( $corner['links'] ); ?>"></label>
				<label class="aieo-opp-strong"><?php esc_html_e( 'Behaviour share', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="cw_behavior" value="<?php echo esc_attr( $corner['behavior'] ); ?>"></label>
				<label><?php esc_html_e( 'Pillars = top %', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.01" min="0.01" max="1" id="pillar_top_pct" value="<?php echo esc_attr( $top_pct ); ?>"></label>
			</fieldset>

			<fieldset class="aieo-opp-fieldset">
				<legend><?php echo esc_html( $is_shop ? __( 'Conversion axis', 'ai-eshop-optimizer' ) : __( 'Engagement axis', 'ai-eshop-optimizer' ) ); ?></legend>
				<?php if ( $is_shop ) : ?>
					<p class="aieo-opp-hint"><?php esc_html_e( 'How the on-site “does it convert” axis is composed.', 'ai-eshop-optimizer' ); ?></p>
					<label><?php esc_html_e( 'View→cart rate', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="op_conv_cart" value="<?php echo esc_attr( $opp_cfg['conv_w_cart'] ); ?>"></label>
				<?php else : ?>
					<p class="aieo-opp-hint"><?php esc_html_e( 'How the on-site “does it engage” axis is composed. There is no add-to-cart on this profile — its weight is folded into the two signals below at compute time.', 'ai-eshop-optimizer' ); ?></p>
				<?php endif; ?>
				<label><?php esc_html_e( 'Engagement', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="op_conv_engagement" value="<?php echo esc_attr( $opp_cfg['conv_w_engagement'] ); ?>"></label>
				<label><?php esc_html_e( 'Retention (1−bounce)', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="op_conv_retention" value="<?php echo esc_attr( $opp_cfg['conv_w_retention'] ); ?>"></label>
			</fieldset>

			<fieldset class="aieo-opp-fieldset">
				<legend><?php esc_html_e( 'Behavioural cornerstone axis', 'ai-eshop-optimizer' ); ?></legend>
				<p class="aieo-opp-hint"><?php esc_html_e( 'How the “earns the journey” discovery signal is composed.', 'ai-eshop-optimizer' ); ?></p>
				<label><?php esc_html_e( 'Entry strength', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="op_corner_entry" value="<?php echo esc_attr( $opp_cfg['corner_w_entry'] ); ?>"></label>
				<label><?php esc_html_e( 'Onward routing', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="op_corner_onward" value="<?php echo esc_attr( $opp_cfg['corner_w_onward'] ); ?>"></label>
				<label><?php esc_html_e( 'Engagement', 'ai-eshop-optimizer' ); ?> <input type="number" step="0.05" min="0" max="1" id="op_corner_engagement" value="<?php echo esc_attr( $opp_cfg['corner_w_engagement'] ); ?>"></label>
			</fieldset>

			<fieldset class="aieo-opp-fieldset">
				<legend><?php esc_html_e( 'Grid thresholds', 'ai-eshop-optimizer' ); ?></legend>
				<p class="aieo-opp-hint"><?php esc_html_e( 'Percentile cut (1–99) that splits low/high, and the minimum views before a product is scored.', 'ai-eshop-optimizer' ); ?></p>
				<label><?php esc_html_e( 'Traffic split %', 'ai-eshop-optimizer' ); ?> <input type="number" step="1" min="1" max="99" id="op_traffic_threshold" value="<?php echo esc_attr( $opp_cfg['traffic_threshold'] ); ?>"></label>
				<label><?php esc_html_e( 'Conversion split %', 'ai-eshop-optimizer' ); ?> <input type="number" step="1" min="1" max="99" id="op_conversion_threshold" value="<?php echo esc_attr( $opp_cfg['conversion_threshold'] ); ?>"></label>
				<label><?php esc_html_e( 'Min views', 'ai-eshop-optimizer' ); ?> <input type="number" step="1" min="1" id="op_min_views" value="<?php echo esc_attr( $opp_cfg['min_views'] ); ?>"></label>
			</fieldset>
		</div>

		<p>
			<button type="button" class="button" id="aieo-opp-save"><?php esc_html_e( 'Save priorities', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-opp-save-status" class="aieo-opp-status"></span>
		</p>
	</details>

	<?php if ( ! empty( $striking ) && is_array( $striking ) ) : ?>
		<!-- ── Striking distance (DataForSEO weekly snapshot) ─────────────── -->
		<div class="aieo-dmm-card" style="margin:12px 0;">
			<h3 style="margin-top:0;"><?php esc_html_e( 'Striking distance — one push from page 1', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:880px;margin-top:0;">
				<?php esc_html_e( 'Keywords this site already ranks 8–20 for (weekly DataForSEO snapshot), highest search volume first. Strengthening these pages — title, internal links, content depth — is the highest-ROI SEO work available: Google has already shortlisted you.', 'ai-eshop-optimizer' ); ?>
			</p>
			<table class="widefat striped" style="max-width:880px;">
				<thead><tr>
					<th><?php esc_html_e( 'Keyword', 'ai-eshop-optimizer' ); ?></th>
					<th style="width:70px;"><?php esc_html_e( 'Position', 'ai-eshop-optimizer' ); ?></th>
					<th style="width:80px;"><?php esc_html_e( 'Volume', 'ai-eshop-optimizer' ); ?></th>
					<th style="width:90px;"><?php esc_html_e( 'Intent', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'Page', 'ai-eshop-optimizer' ); ?></th>
				</tr></thead>
				<tbody>
				<?php foreach ( $striking as $s ) :
					$edit = ( ! empty( $s['object_id'] ) && post_type_exists( (string) $s['object_type'] ) ) ? get_edit_post_link( (int) $s['object_id'] ) : '';
					?>
					<tr>
						<td><strong><?php echo esc_html( (string) $s['keyword'] ); ?></strong></td>
						<td><?php echo (int) $s['position']; ?></td>
						<td><?php echo esc_html( number_format_i18n( (int) $s['volume'] ) ); ?></td>
						<td><?php echo esc_html( (string) ( $s['intent'] ?? '' ) ); ?></td>
						<td>
							<?php if ( $edit ) : ?>
								<a href="<?php echo esc_url( $edit ); ?>"><?php echo esc_html( (string) $s['url_path'] ); ?></a>
							<?php else : ?>
								<?php echo esc_html( (string) $s['url_path'] ); ?>
							<?php endif; ?>
						</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
	<?php endif; ?>

	<!-- ── Quadrant filter chips ─────────────────────────────────────── -->
	<ul class="subsubsub aieo-opp-chips">
		<li><a href="<?php echo esc_url( remove_query_arg( 'quad' ) ); ?>" class="<?php echo '' === $quad ? 'current' : ''; ?>"><?php esc_html_e( 'All', 'ai-eshop-optimizer' ); ?></a></li>
		<?php foreach ( $quad_labels as $key => $label ) : ?>
			<li> |
				<a href="<?php echo esc_url( add_query_arg( 'quad', $key ) ); ?>" class="<?php echo $quad === $key ? 'current' : ''; ?>">
					<?php echo esc_html( $label ); ?> <span class="count">(<?php echo (int) ( $counts[ $key ] ?? 0 ); ?>)</span>
				</a>
			</li>
		<?php endforeach; ?>
	</ul>

	<?php if ( empty( $rows ) ) : ?>
		<p><?php esc_html_e( 'No opportunities computed yet. Click “Recompute now” (needs analytics metrics from the data-prep schedule).', 'ai-eshop-optimizer' ); ?></p>
	<?php else : ?>
		<table class="widefat striped aieo-opp-table">
			<thead><tr>
				<th><?php esc_html_e( 'Product', 'ai-eshop-optimizer' ); ?></th>
				<th class="aieo-opp-col-quad"><?php esc_html_e( 'Quadrant', 'ai-eshop-optimizer' ); ?></th>
				<th class="aieo-opp-col-num"><?php esc_html_e( 'Traffic', 'ai-eshop-optimizer' ); ?></th>
				<th class="aieo-opp-col-num"><?php echo esc_html( $is_shop ? __( 'Conversion', 'ai-eshop-optimizer' ) : __( 'Engagement', 'ai-eshop-optimizer' ) ); ?></th>
				<th class="aieo-opp-col-num"><?php esc_html_e( 'Cornerstone', 'ai-eshop-optimizer' ); ?></th>
				<th class="aieo-opp-col-num"><?php esc_html_e( 'Priority', 'ai-eshop-optimizer' ); ?></th>
				<th><?php esc_html_e( 'Recommendation', 'ai-eshop-optimizer' ); ?></th>
				<th class="aieo-opp-col-pin"><?php esc_html_e( 'Pillar', 'ai-eshop-optimizer' ); ?></th>
				<th class="aieo-opp-col-act"><?php esc_html_e( 'Apply', 'ai-eshop-optimizer' ); ?></th>
			</tr></thead>
			<tbody>
			<?php foreach ( $rows as $r ) :
				$pid   = (int) $r['object_id'];
				$otype = (string) $r['object_type'];
				$is_product_row = ( 'product' === $otype );
				$qkey  = (string) $r['quadrant'];
				$edit  = get_edit_post_link( $pid );
				$title = '' !== (string) $r['post_title'] ? (string) $r['post_title'] : ( '#' . $pid );
				$pinned = $is_product_row && isset( $overrides[ $pid ] ) && 1 === (int) $overrides[ $pid ];
				$excluded = $is_product_row && isset( $overrides[ $pid ] ) && 0 === (int) $overrides[ $pid ];
				?>
				<tr>
					<td>
						<?php if ( $edit ) : ?>
							<a href="<?php echo esc_url( $edit ); ?>"><?php echo esc_html( $title ); ?></a>
						<?php else : ?>
							<?php echo esc_html( $title ); ?>
						<?php endif; ?>
						<?php if ( ! $is_product_row ) : ?>
							<br><span style="color:#94a3b8;font-size:11px;"><?php echo esc_html( $otype ); ?></span>
						<?php endif; ?>
					</td>
					<td><span class="aieo-opp-badge aieo-opp-q-<?php echo esc_attr( $qkey ); ?>"><?php echo esc_html( $quad_labels[ $qkey ] ?? $qkey ); ?></span></td>
					<td class="aieo-opp-col-num">
						<span class="aieo-opp-bar"><span class="aieo-opp-bar-fill" data-w="<?php echo (int) $r['traffic_score']; ?>"></span></span>
						<span class="aieo-opp-num"><?php echo (int) $r['traffic_score']; ?></span>
					</td>
					<td class="aieo-opp-col-num">
						<span class="aieo-opp-bar"><span class="aieo-opp-bar-fill" data-w="<?php echo (int) $r['conversion_score']; ?>"></span></span>
						<span class="aieo-opp-num"><?php echo (int) $r['conversion_score']; ?></span>
					</td>
					<td class="aieo-opp-col-num"><?php echo (int) $r['cornerstone_score']; ?></td>
					<td class="aieo-opp-col-num"><strong><?php echo (int) $r['priority']; ?></strong></td>
					<td class="aieo-opp-rec"><?php echo esc_html( (string) $r['recommendation'] ); ?></td>
					<td class="aieo-opp-col-pin">
						<?php if ( $is_product_row ) : ?>
							<button type="button"
								class="button button-small aieo-opp-pin <?php echo $pinned ? 'is-pinned' : ''; ?>"
								data-product="<?php echo $pid; ?>"
								data-state="<?php echo $pinned ? 'clear' : 'pin'; ?>">
								<?php echo $pinned ? esc_html__( '★ Pinned', 'ai-eshop-optimizer' ) : ( ! empty( $r['is_pillar'] ) ? esc_html__( '★ auto', 'ai-eshop-optimizer' ) : esc_html__( 'Pin', 'ai-eshop-optimizer' ) ); ?>
							</button>
							<?php if ( $excluded ) : ?><span class="aieo-opp-excluded"><?php esc_html_e( 'excluded', 'ai-eshop-optimizer' ); ?></span><?php endif; ?>
						<?php elseif ( ! empty( $r['is_pillar'] ) ) : ?>
							<span title="<?php esc_attr_e( 'Pillar', 'ai-eshop-optimizer' ); ?>" style="color:#7c3aed;">&#9733;</span>
						<?php endif; ?>
					</td>
					<td class="aieo-opp-col-act" data-product="<?php echo $pid; ?>" data-type="<?php echo esc_attr( $otype ); ?>">
						<div class="aieo-opp-apply-kp-row">
							<input type="text" class="aieo-opp-kp" placeholder="<?php esc_attr_e( 'focus keyphrase', 'ai-eshop-optimizer' ); ?>">
							<button type="button" class="button button-small aieo-opp-set-kp"><?php esc_html_e( 'Set', 'ai-eshop-optimizer' ); ?></button>
							<button type="button" class="button-link aieo-opp-suggest" title="<?php esc_attr_e( 'Suggest from converting searches', 'ai-eshop-optimizer' ); ?>"><?php esc_html_e( 'suggest', 'ai-eshop-optimizer' ); ?></button>
						</div>
						<div class="aieo-opp-suggest-out"></div>
						<div class="aieo-opp-apply-pri-row">
							<label><?php esc_html_e( 'Sitemap', 'ai-eshop-optimizer' ); ?>
								<input type="number" step="0.1" min="0" max="1" class="aieo-opp-pri" placeholder="0.0–1.0">
							</label>
							<button type="button" class="button button-small aieo-opp-set-pri"><?php esc_html_e( 'Set', 'ai-eshop-optimizer' ); ?></button>
						</div>
						<span class="aieo-opp-apply-status"></span>
					</td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<p class="description"><?php esc_html_e( 'Top 100 by priority. “Cornerstone” is the behavioural discovery score; “Pin” forces a product to cornerstone status regardless of the computed signal.', 'ai-eshop-optimizer' ); ?></p>
	<?php endif; ?>
</div>
<script>
(function(){
	var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
	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.' } }); });
	}
	// Render the static bar widths (no inline style in markup; set here).
	document.querySelectorAll('.aieo-opp-bar-fill').forEach(function(el){
		el.style.width = (parseInt(el.getAttribute('data-w'), 10) || 0) + '%';
	});
	// Save priorities.
	var save = document.getElementById('aieo-opp-save');
	if (save) { save.addEventListener('click', function(){
		var st = document.getElementById('aieo-opp-save-status');
		st.textContent = '…';
		var ids = ['cw_sales','cw_turnover','cw_forecast','cw_links','cw_behavior','pillar_top_pct',
			'op_conv_cart','op_conv_engagement','op_conv_retention','op_corner_entry','op_corner_onward',
			'op_corner_engagement','op_traffic_threshold','op_conversion_threshold','op_min_views'];
		var data = {};
		ids.forEach(function(id){ var e = document.getElementById(id); if (e) { data[id] = e.value; } });
		post('aieo_seo_opp_save', data, function(j){
			st.textContent = (j && j.data && j.data.message) || (j && j.success ? 'Saved.' : 'Failed.');
		});
	}); }
	// Recompute.
	var rc = document.getElementById('aieo-opp-recompute');
	if (rc) { rc.addEventListener('click', function(){
		var st = document.getElementById('aieo-opp-status');
		rc.disabled = true; st.textContent = <?php echo wp_json_encode( __( 'Computing…', 'ai-eshop-optimizer' ) ); ?>;
		post('aieo_seo_opp_recompute', {}, function(j){
			if (j && j.success) {
				st.textContent = <?php echo wp_json_encode( __( 'Done — reloading…', 'ai-eshop-optimizer' ) ); ?>;
				setTimeout(function(){ location.reload(); }, 700);
			} else { rc.disabled = false; st.textContent = (j && j.data && j.data.message) || 'Failed.'; }
		});
	}); }
	// Pin / unpin.
	document.querySelectorAll('.aieo-opp-pin').forEach(function(btn){
		btn.addEventListener('click', function(){
			var pid = btn.getAttribute('data-product'), state = btn.getAttribute('data-state');
			btn.disabled = true;
			post('aieo_seo_opp_pin', { product_id: pid, state: state }, function(j){
				btn.disabled = false;
				if (j && j.success) {
					if (state === 'pin') { btn.classList.add('is-pinned'); btn.textContent = '★ Pinned'; btn.setAttribute('data-state','clear'); }
					else { btn.classList.remove('is-pinned'); btn.textContent = 'Pin'; btn.setAttribute('data-state','pin'); }
				}
			});
		});
	});
	// Write-back: set focus keyphrase / sitemap priority + suggest converting terms.
	document.querySelectorAll('.aieo-opp-col-act').forEach(function(cell){
		var pid = cell.getAttribute('data-product');
		var oty = cell.getAttribute('data-type') || 'product';
		var st  = cell.querySelector('.aieo-opp-apply-status');
		var kp  = cell.querySelector('.aieo-opp-kp');
		var pri = cell.querySelector('.aieo-opp-pri');
		function flash(j){ st.textContent = (j && j.data && j.data.message) || (j && j.success ? 'OK' : 'Failed.'); }
		var setKp = cell.querySelector('.aieo-opp-set-kp');
		if (setKp) { setKp.addEventListener('click', function(){
			st.textContent = '…';
			post('aieo_seo_opp_apply', { product_id: pid, object_type: oty, field: 'keyphrase', value: kp ? kp.value : '' }, flash);
		}); }
		var setPri = cell.querySelector('.aieo-opp-set-pri');
		if (setPri) { setPri.addEventListener('click', function(){
			st.textContent = '…';
			post('aieo_seo_opp_apply', { product_id: pid, object_type: oty, field: 'sitemap_priority', value: pri ? pri.value : '' }, flash);
		}); }
		var sug = cell.querySelector('.aieo-opp-suggest');
		var out = cell.querySelector('.aieo-opp-suggest-out');
		if (sug) { sug.addEventListener('click', function(){
			out.textContent = '…';
			post('aieo_seo_opp_suggest', { product_id: pid, object_type: oty }, function(j){
				out.textContent = '';
				var terms = (j && j.data && j.data.terms) || [];
				if (!terms.length) { out.textContent = <?php echo wp_json_encode( __( 'No converting searches yet.', 'ai-eshop-optimizer' ) ); ?>; return; }
				terms.forEach(function(t){
					var a = document.createElement('a');
					a.href = '#'; a.className = 'aieo-opp-term';
					a.textContent = t.term + ' (' + t.hits + ')';
					a.addEventListener('click', function(e){ e.preventDefault(); if (kp) { kp.value = t.term; } });
					out.appendChild(a);
				});
			});
		}); }
	});
})();
</script>
