<?php

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

$score_color = static function ( $s ) {
	$s = (int) $s;
	return $s >= 80 ? '#15803d' : ( $s >= 50 ? '#b45309' : '#b91c1c' );
};
$avg_color = $score_color( $summary['avg'] );
?>
<div class="aieo-dmm-section">
	<h2><?php esc_html_e( 'SEO Health', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description" style="max-width:880px;">
		<?php esc_html_e( 'Your content ranked by REAL demand (sales-led on shops, visits + engagement on catalog/content profiles) — work the high-demand, low-score pages first for the biggest organic upside. “Pillars” are the AI-determined cornerstone pages (best performers + most internally linked), surfaced automatically from performance, not flagged by hand.', 'ai-eshop-optimizer' ); ?>
	</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 to start scoring; scores + pillars build on the data-prep schedule.', 'ai-eshop-optimizer' ); ?>
		</p></div>
	<?php endif; ?>

	<!-- ── AI suggestions review (SERP-context write queue) ─────────────── -->
	<div class="aieo-dmm-card">
		<h3 style="margin-top:0;"><?php esc_html_e( 'AI suggestions — review & apply', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:880px;margin-top:0;">
			<?php esc_html_e( 'The nightly write queue picks the highest-ROI pages (striking-distance keywords first), pulls the live Google results for each target query, and has the AI write a title + description to beat that exact SERP. Nothing goes live without your approval — unless Autopilot is enabled in SEO → General.', 'ai-eshop-optimizer' ); ?>
		</p>
		<p>
			<button type="button" class="button" id="aieo-sugg-generate" <?php disabled( empty( $wq_available ) ); ?>><?php esc_html_e( 'Generate suggestions now (3)', 'ai-eshop-optimizer' ); ?></button>
			<?php if ( ! empty( $suggestions ) ) : ?>
				<button type="button" class="button button-primary" id="aieo-sugg-approve-all"><?php esc_html_e( 'Approve all', 'ai-eshop-optimizer' ); ?></button>
			<?php endif; ?>
			<span id="aieo-sugg-status" style="margin-left:8px;font-size:12px;"></span>
			<?php if ( empty( $wq_available ) ) : ?>
				<span class="description" style="margin-left:8px;"><?php esc_html_e( 'Needs the Rooster Content Connector token (AI) + a DataForSEO connection.', 'ai-eshop-optimizer' ); ?></span>
			<?php endif; ?>
		</p>
		<?php if ( ! empty( $suggestions ) ) : ?>
			<table class="widefat striped" style="max-width:1100px;">
				<thead><tr>
					<th style="width:220px;"><?php esc_html_e( 'Page', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'Current → Suggested', 'ai-eshop-optimizer' ); ?></th>
					<th style="width:150px;"></th>
				</tr></thead>
				<tbody>
				<?php foreach ( $suggestions as $sg ) :
					$edit = post_type_exists( (string) $sg['object_type'] ) ? get_edit_post_link( (int) $sg['object_id'] ) : '';
					$name = get_the_title( (int) $sg['object_id'] );
					?>
					<tr data-type="<?php echo esc_attr( (string) $sg['object_type'] ); ?>" data-id="<?php echo (int) $sg['object_id']; ?>">
						<td>
							<?php if ( $edit ) : ?><a href="<?php echo esc_url( $edit ); ?>"><?php echo esc_html( $name ?: '#' . (int) $sg['object_id'] ); ?></a>
							<?php else : ?><?php echo esc_html( $name ?: '#' . (int) $sg['object_id'] ); ?><?php endif; ?>
							<br><span style="color:#94a3b8;font-size:11px;"><?php echo esc_html( (string) $sg['object_type'] ); ?></span>
						</td>
						<td style="font-size:12px;">
							<div><strong>T:</strong> <span style="color:#94a3b8;"><?php echo esc_html( (string) ( $sg['title'] ?: '—' ) ); ?></span> → <strong><?php echo esc_html( (string) $sg['suggested_title'] ); ?></strong></div>
							<div style="margin-top:4px;"><strong>D:</strong> <span style="color:#94a3b8;"><?php echo esc_html( mb_substr( (string) ( $sg['description'] ?: '—' ), 0, 120 ) ); ?></span> → <?php echo esc_html( (string) $sg['suggested_description'] ); ?></div>
							<?php if ( ! empty( $sg['suggested_keyphrase'] ) ) : ?>
								<div style="margin-top:4px;color:#7c3aed;"><strong>KP:</strong> <?php echo esc_html( (string) $sg['suggested_keyphrase'] ); ?></div>
							<?php endif; ?>
						</td>
						<td>
							<button type="button" class="button button-small aieo-sugg-approve"><?php esc_html_e( 'Approve', 'ai-eshop-optimizer' ); ?></button>
							<button type="button" class="button-link aieo-sugg-dismiss" style="color:#b91c1c;"><?php esc_html_e( 'dismiss', 'ai-eshop-optimizer' ); ?></button>
						</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		<?php else : ?>
			<p class="description"><?php esc_html_e( 'No pending suggestions.', '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.' } }); });
		}
		var st = document.getElementById('aieo-sugg-status');
		var gen = document.getElementById('aieo-sugg-generate');
		if (gen) { gen.addEventListener('click', function(){
			gen.disabled = true;
			st.textContent = <?php echo wp_json_encode( __( 'Working… (SERP pulls + AI, ~30s)', 'ai-eshop-optimizer' ) ); ?>;
			post('aieo_seo_sugg_generate', {}, function(j){
				gen.disabled = false;
				st.textContent = (j && j.data && j.data.message) || (j && j.success ? 'Done.' : 'Failed.');
				if (j && j.success) { setTimeout(function(){ location.reload(); }, 1200); }
			});
		}); }
		var all = document.getElementById('aieo-sugg-approve-all');
		if (all) { all.addEventListener('click', function(){
			if (!confirm(<?php echo wp_json_encode( __( 'Apply ALL pending suggestions (titles + descriptions go live, heads rebuild)?', 'ai-eshop-optimizer' ) ); ?>)) { return; }
			all.disabled = true;
			post('aieo_seo_sugg_action', { op: 'approve_all' }, function(j){
				st.textContent = (j && j.data && j.data.message) || '';
				setTimeout(function(){ location.reload(); }, 900);
			});
		}); }
		document.querySelectorAll('.aieo-sugg-approve, .aieo-sugg-dismiss').forEach(function(b){
			b.addEventListener('click', function(){
				var tr = b.closest('tr');
				b.disabled = true;
				post('aieo_seo_sugg_action', {
					op: b.classList.contains('aieo-sugg-approve') ? 'approve' : 'dismiss',
					object_type: tr.getAttribute('data-type'),
					object_id: tr.getAttribute('data-id')
				}, function(j){
					if (j && j.success) { tr.remove(); }
					else { b.disabled = false; alert((j && j.data && j.data.message) || 'Failed.'); }
				});
			});
		});
	})();
	</script>

	<p>
		<button type="button" class="button button-primary" id="aieo-seo-recompute"><?php esc_html_e( 'Recompute scores now', 'ai-eshop-optimizer' ); ?></button>
		<span id="aieo-seo-recompute-status" style="margin-left:8px;font-size:12px;color:#64748b;"></span>
	</p>

	<?php 
	      
	      
	      
	      $card = 'flex:1 1 0;min-width:160px;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:16px;text-align:center;margin:0;'; ?>
	<div style="display:flex;gap:12px;flex-wrap:wrap;margin:14px 0;align-items:stretch;">
		<div class="aieo-dmm-card" style="<?php echo esc_attr( $card ); ?>">
			<div style="font-size:26px;font-weight:700;line-height:1.1;"><?php echo (int) $summary['total']; ?></div>
			<div style="font-size:12px;color:#64748b;margin-top:4px;"><?php esc_html_e( 'Objects scored', 'ai-eshop-optimizer' ); ?></div>
		</div>
		<div class="aieo-dmm-card" style="<?php echo esc_attr( $card ); ?>">
			<div style="font-size:26px;font-weight:700;line-height:1.1;color:<?php echo esc_attr( $avg_color ); ?>;"><?php echo (int) $summary['avg']; ?></div>
			<div style="font-size:12px;color:#64748b;margin-top:4px;"><?php esc_html_e( 'Average score / 100', 'ai-eshop-optimizer' ); ?></div>
		</div>
		<a class="aieo-dmm-card" href="<?php echo esc_url( add_query_arg( 'seo_view', 'pillars' ) ); ?>" title="<?php esc_attr_e( 'View pillar products', 'ai-eshop-optimizer' ); ?>" style="<?php echo esc_attr( $card ); ?>text-decoration:none;color:inherit;">
			<div style="font-size:26px;font-weight:700;line-height:1.1;color:#7c3aed;">&#9733; <?php echo (int) $summary['pillars']; ?></div>
			<div style="font-size:12px;color:#64748b;margin-top:4px;"><?php esc_html_e( 'Pillar products', 'ai-eshop-optimizer' ); ?> &rsaquo;</div>
		</a>
		<div class="aieo-dmm-card" style="<?php echo esc_attr( $card ); ?>">
			<div style="font-size:26px;font-weight:700;line-height:1.1;color:#b45309;"><?php echo (int) $summary['needswork']; ?></div>
			<div style="font-size:12px;color:#64748b;margin-top:4px;"><?php esc_html_e( 'Pages with open fixes', 'ai-eshop-optimizer' ); ?></div>
		</div>
	</div>

	<?php if ( ! empty( $pillars_only ) ) : ?>
		<p style="margin:8px 0;"><strong><?php esc_html_e( 'Showing pillar products only.', 'ai-eshop-optimizer' ); ?></strong>
			&nbsp;<a href="<?php echo esc_url( remove_query_arg( 'seo_view' ) ); ?>">&larr; <?php esc_html_e( 'Show all', 'ai-eshop-optimizer' ); ?></a></p>
	<?php endif; ?>

	<?php if ( empty( $rows ) ) : ?>
		<p><?php esc_html_e( 'No scores yet — they build on the data-prep schedule (or run the pipeline now from Operational Efficiency).', 'ai-eshop-optimizer' ); ?></p>
	<?php else : ?>
		<table class="widefat striped">
			<thead><tr>
				<th><?php esc_html_e( 'Product / Post', 'ai-eshop-optimizer' ); ?></th>
				<th style="width:120px;"><?php esc_html_e( 'Demand', 'ai-eshop-optimizer' ); ?></th>
				<th style="width:90px;"><?php esc_html_e( 'SEO score', 'ai-eshop-optimizer' ); ?></th>
				<th style="width:70px;"><?php esc_html_e( 'Fixes', 'ai-eshop-optimizer' ); ?></th>
				<th style="width:80px;"><?php esc_html_e( 'Pillar', 'ai-eshop-optimizer' ); ?></th>
			</tr></thead>
			<tbody>
			<?php foreach ( $rows as $r ) : ?>
				<?php
				$oid    = (int) $r['object_id'];
				$score  = (int) $r['score'];
				$demand = (int) $r['demand'];
				$edit   = get_edit_post_link( $oid );
				$title  = '' !== (string) $r['post_title'] ? (string) $r['post_title'] : ( '#' . $oid );
				?>
				<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; ?>
						<span style="color:#94a3b8;font-size:11px;">· <?php echo esc_html( (string) $r['object_type'] ); ?></span>
					</td>
					<td>
						<div style="background:#e2e8f0;border-radius:4px;height:8px;overflow:hidden;">
							<div style="background:#7c3aed;height:8px;width:<?php echo (int) max( 0, min( 100, $demand ) ); ?>%;"></div>
						</div>
						<span style="font-size:11px;color:#64748b;"><?php echo (int) $demand; ?></span>
					</td>
					<td><strong style="color:<?php echo esc_attr( $score_color( $score ) ); ?>;"><?php echo (int) $score; ?></strong></td>
					<td><?php echo (int) $r['fix_count']; ?></td>
					<td><?php echo ! empty( $r['is_pillar'] ) ? '<span style="color:#7c3aed;font-weight:700;">★</span>' : '<span style="color:#cbd5e1;">—</span>'; ?></td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<p class="description"><?php esc_html_e( 'Top 100 by demand. Open a row to edit its SEO (title / description / keyphrase) with the live score + AI Assist.', 'ai-eshop-optimizer' ); ?></p>
	<?php endif; ?>
</div>
<script>
(function(){
	var btn = document.getElementById('aieo-seo-recompute');
	if (!btn) { return; }
	var st = document.getElementById('aieo-seo-recompute-status');
	var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
	btn.addEventListener('click', function(){
		btn.disabled = true; st.style.color = '#64748b';
		var cursor = { phase: 0, last_id: 0 }, total = 0, guard = 0;
		function step(){
			if (++guard > 100000) { st.style.color = '#b91c1c'; st.textContent = 'Stopped.'; btn.disabled = false; return; }
			var fd = new FormData();
			fd.set('action', 'aieo_seo_health_recompute');
			fd.set('nonce', nonce);
			fd.set('cursor', JSON.stringify(cursor));
			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; }
					var d = j.data;
					total += (d.built | 0);
					cursor = d.cursor || cursor;
					st.textContent = <?php echo wp_json_encode( __( 'Computing…', 'ai-eshop-optimizer' ) ); ?> + ' ' + total + ' scored';
					if (d.done) {
						st.style.color = '#15803d';
						st.textContent = <?php echo wp_json_encode( __( 'Done — reloading…', 'ai-eshop-optimizer' ) ); ?>;
						setTimeout(function(){ location.reload(); }, 700);
						return;
					}
					step();
				})
				.catch(function(){ st.style.color = '#b91c1c'; st.textContent = 'Network error.'; btn.disabled = false; });
		}
		step();
	});
})();
</script>
