<?php
/**
 * Livada SEO — Metabox View Template
 *
 * Rendered inside the "Livada SEO" metabox on post/page edit screens.
 * All outputs are escaped; all inputs read current post meta.
 *
 * @package    Livada_SEO
 * @var WP_Post $post  Current post (passed by render_metabox()).
 */

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

// ── Read existing meta values ──────────────────────────────────────────────────

$seo_title        = (string) get_post_meta( $post->ID, '_livada_seo_title',         true );
$seo_description  = (string) get_post_meta( $post->ID, '_livada_seo_description',   true );
$focus_keyword    = (string) get_post_meta( $post->ID, '_livada_seo_focus_keyword',  true );
$noindex          = (bool)   get_post_meta( $post->ID, '_livada_seo_noindex',        true );
$nofollow         = (bool)   get_post_meta( $post->ID, '_livada_seo_nofollow',       true );
$canonical        = (string) get_post_meta( $post->ID, '_livada_seo_canonical',      true );
$og_image         = (string) get_post_meta( $post->ID, '_livada_seo_og_image',       true );
$service_schema   = (bool)   get_post_meta( $post->ID, '_livada_seo_service_schema', true );
$faq_schema       = (bool)   get_post_meta( $post->ID, '_livada_seo_faq_schema', true );
$schema_type      = (string) get_post_meta( $post->ID, '_livada_seo_schema_type', true );
$sitemap_exclude  = (bool)   get_post_meta( $post->ID, '_livada_seo_sitemap_exclude', true );
$location_id      = (string) get_post_meta( $post->ID, '_livada_seo_location_id', true );
$cornerstone      = (bool)   get_post_meta( $post->ID, '_livada_seo_cornerstone', true );

// Hreflang manual overrides (per-post). Stored either as a serialized array
// or as a JSON string — normalise both into [ lang => url ] for the UI.
$hreflang_meta = get_post_meta( $post->ID, '_livada_seo_hreflang', true );
if ( is_string( $hreflang_meta ) && '' !== $hreflang_meta ) {
	$decoded = json_decode( $hreflang_meta, true );
	if ( is_array( $decoded ) ) {
		$hreflang_meta = $decoded;
	}
}
if ( ! is_array( $hreflang_meta ) ) {
	$hreflang_meta = [];
}

// Locations list — only render the dropdown when more than one location exists.
$locations_for_metabox = class_exists( 'Livada_SEO_Schema' )
	? Livada_SEO_Schema::get_locations()
	: [];

// Show the "AI ✨" buttons in the metabox only if the operator configured an
// Anthropic API key. Avoids exposing dead buttons.
$has_ai_key = class_exists( 'Livada_SEO_Image_Bulk' )
	? '' !== Livada_SEO_Image_Bulk::get_anthropic_key()
	: false;

// Cornerstone reverse counter: how many cornerstone posts link to THIS post?
// Cheap COUNT against postmeta + posts via permalink LIKE — bounded enough for
// metabox load (one query, indexed on meta_key).
$cornerstone_links_in = 0;
$current_permalink    = (string) get_permalink( $post->ID );
if ( '' !== $current_permalink ) {
	global $wpdb;
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery
	$cornerstone_links_in = (int) $wpdb->get_var(
		$wpdb->prepare(
			"SELECT COUNT(DISTINCT p.ID)
			 FROM {$wpdb->posts} p
			 INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID
			 WHERE p.post_status = 'publish'
			   AND p.ID != %d
			   AND pm.meta_key = '_livada_seo_cornerstone'
			   AND pm.meta_value = '1'
			   AND p.post_content LIKE %s",
			(int) $post->ID,
			'%' . $wpdb->esc_like( $current_permalink ) . '%'
		)
	);
}

$schema_choices = [
	''        => __( '— None —',                            'livada-seo' ),
	'HowTo'   => __( 'How-to guide',                        'livada-seo' ),
	'Product' => __( 'Product',                             'livada-seo' ),
	'Event'   => __( 'Event',                               'livada-seo' ),
	'Recipe'  => __( 'Recipe',                              'livada-seo' ),
	'Review'  => __( 'Review',                              'livada-seo' ),
	'Offer'   => __( 'Offer (seasonal package, room rate)', 'livada-seo' ),
];

// Offer fields (only used when schema_type = Offer).
$offer_price         = (string) get_post_meta( $post->ID, '_livada_seo_offer_price',         true );
$offer_currency      = (string) get_post_meta( $post->ID, '_livada_seo_offer_currency',      true );
$offer_valid_from    = (string) get_post_meta( $post->ID, '_livada_seo_offer_valid_from',    true );
$offer_valid_through = (string) get_post_meta( $post->ID, '_livada_seo_offer_valid_through', true );
$offer_availability  = (string) get_post_meta( $post->ID, '_livada_seo_offer_availability',  true );

if ( '' === $offer_currency ) {
	$offer_currency = 'EUR';
}
if ( '' === $offer_availability ) {
	$offer_availability = 'in_stock';
}

$offer_availability_choices = [
	'in_stock'     => __( 'Available',          'livada-seo' ),
	'limited'      => __( 'Limited',            'livada-seo' ),
	'sold_out'     => __( 'Sold out',           'livada-seo' ),
	'preorder'     => __( 'Pre-order',          'livada-seo' ),
	'out_of_stock' => __( 'Out of stock',       'livada-seo' ),
];

// SEO score details (populated by class-analysis.php on post save).
$score_details = get_post_meta( $post->ID, '_livada_seo_score_details', true );
if ( ! is_array( $score_details ) ) {
	$score_details = [];
}

// Fallbacks for SERP preview.
$serp_title = $seo_title ?: get_the_title( $post->ID );
$serp_url   = get_permalink( $post->ID );
?>

<style>
/* ── Metabox shell ─────────────────────────────────────────────── */
.livada-seo-metabox { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-size: 13px; color: #1e2327; }

/* ── Tab nav ──────────────────────────────────────────────────── */
.livada-seo-tabs { display: flex; border-bottom: 1px solid #c3c4c7; margin-bottom: 16px; gap: 0; }
.livada-seo-tab-btn { background: none; border: none; border-bottom: 3px solid transparent; padding: 8px 16px; font-size: 13px; font-weight: 600; color: #646970; cursor: pointer; margin-bottom: -1px; transition: color .15s, border-color .15s; }
.livada-seo-tab-btn:hover { color: #2271b1; }
.livada-seo-tab-btn.is-active { color: #2271b1; border-bottom-color: #2271b1; }

/* ── Panels ───────────────────────────────────────────────────── */
.livada-seo-panel { display: none; }
.livada-seo-panel.is-active { display: block; }

/* ── Field rows ───────────────────────────────────────────────── */
.livada-seo-field { margin-bottom: 14px; }
.livada-seo-field label { display: block; font-weight: 600; margin-bottom: 4px; color: #1e2327; }
.livada-seo-field input[type="text"],
.livada-seo-field input[type="url"],
.livada-seo-field textarea { width: 100%; box-sizing: border-box; }
.livada-seo-field textarea { min-height: 80px; resize: vertical; }
.livada-seo-field .description { font-size: 12px; color: #646970; margin-top: 4px; }

/* ── Character counter ────────────────────────────────────────── */
.livada-seo-counter { font-size: 12px; margin-top: 4px; font-weight: 500; }
.livada-seo-counter.is-green  { color: #00a32a; }
.livada-seo-counter.is-orange { color: #dba617; }
.livada-seo-counter.is-red    { color: #d63638; }

/* ── SERP preview ─────────────────────────────────────────────── */
.livada-seo-serp-toolbar { display: flex; gap: 4px; margin-bottom: 8px; }
.livada-seo-serp-toolbar button { background: #f0f0f1; border: 1px solid #c3c4c7; padding: 4px 10px; font-size: 11px; font-weight: 600; color: #50575e; cursor: pointer; border-radius: 3px; }
.livada-seo-serp-toolbar button.is-active { background: #2271b1; color: #fff; border-color: #2271b1; }
.livada-seo-serp { border: 1px solid #c3c4c7; border-radius: 4px; padding: 14px 16px; background: #fff; margin-bottom: 16px; }
.livada-seo-serp.is-hidden { display: none; }
.livada-seo-serp__title { font-size: 18px; color: #1a0dab; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; line-height: 1.3; }
.livada-seo-serp__url { font-size: 13px; color: #006621; margin: 2px 0 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.livada-seo-serp__desc { font-size: 13px; color: #545454; line-height: 1.5; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }

/* Mobile SERP variant — narrower, tighter typography that mirrors Google's mobile SERP. */
.livada-seo-serp--mobile { max-width: 360px; padding: 10px 12px; font-family: arial, sans-serif; border-radius: 8px; }
.livada-seo-serp--mobile .livada-seo-serp__title { font-size: 16px; line-height: 1.25; white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.livada-seo-serp--mobile .livada-seo-serp__url { font-size: 12px; }
.livada-seo-serp--mobile .livada-seo-serp__desc { font-size: 12px; -webkit-line-clamp: 3; }

/* ── SEO score ────────────────────────────────────────────────── */
.livada-seo-score { margin-top: 16px; }
.livada-seo-score__label { font-weight: 600; margin-bottom: 8px; }
.livada-seo-score__list { list-style: none; margin: 0; padding: 0; }
.livada-seo-score__list li { display: flex; align-items: flex-start; gap: 8px; padding: 4px 0; font-size: 12px; line-height: 1.4; }
.livada-seo-score__dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; margin-top: 2px; }
.livada-seo-score__dot.is-green  { background: #00a32a; }
.livada-seo-score__dot.is-orange { background: #dba617; }
.livada-seo-score__dot.is-red    { background: #d63638; }

/* ── Live score (JS-driven) ───────────────────────────────────── */
.livada-seo-live-score { margin-top: 16px; border-top: 1px solid #f0f0f1; padding-top: 12px; }
.livada-seo-live-score__title { font-weight: 600; font-size: 12px; margin-bottom: 8px; color: #646970; text-transform: uppercase; letter-spacing: .03em; }
.livada-seo-live-score__list { list-style: none; margin: 0; padding: 0; }
.livada-seo-live-score__list li { display: flex; align-items: flex-start; gap: 8px; padding: 3px 0; font-size: 12px; line-height: 1.4; }

/* ── Internal link suggestions ─────────────────────────────────── */
.livada-seo-suggestions { margin-top: 16px; border-top: 1px solid #f0f0f1; padding-top: 12px; }
.livada-seo-suggestions__list { list-style: none; margin: 0; padding: 0; }
.livada-seo-suggestions__list li { padding: 6px 0; font-size: 12px; line-height: 1.4; border-bottom: 1px dashed #f0f0f1; }
.livada-seo-suggestions__list li:last-child { border-bottom: 0; }
.livada-seo-suggestions__list a { font-weight: 600; color: #2271b1; text-decoration: none; }
.livada-seo-suggestions__list a:hover { text-decoration: underline; }
.livada-seo-suggestions__list .why { color: #646970; font-size: 11px; }
.livada-seo-suggestions__empty { color: #646970; font-style: italic; }

/* ── OG image ─────────────────────────────────────────────────── */
.livada-seo-og-preview { max-width: 200px; max-height: 105px; display: block; margin: 8px 0; border: 1px solid #c3c4c7; border-radius: 3px; }
.livada-seo-og-preview.is-hidden { display: none; }
.livada-seo-og-actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }

/* ── Checkbox rows ────────────────────────────────────────────── */
.livada-seo-check-row { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
.livada-seo-check-row label { margin: 0; font-weight: normal; }
</style>

<div class="livada-seo-metabox">

	<?php wp_nonce_field( 'livada_seo_save_metabox', 'livada_seo_metabox_nonce' ); ?>

	<!-- ── Tab navigation ──────────────────────────────────────────────── -->
	<div class="livada-seo-tabs" role="tablist">
		<button type="button" class="livada-seo-tab-btn is-active"
			role="tab" aria-selected="true" aria-controls="livada-seo-panel-seo"
			data-panel="seo">
			<?php esc_html_e( 'SEO', 'livada-seo' ); ?>
		</button>
		<button type="button" class="livada-seo-tab-btn"
			role="tab" aria-selected="false" aria-controls="livada-seo-panel-social"
			data-panel="social">
			<?php esc_html_e( 'Social', 'livada-seo' ); ?>
		</button>
		<button type="button" class="livada-seo-tab-btn"
			role="tab" aria-selected="false" aria-controls="livada-seo-panel-advanced"
			data-panel="advanced">
			<?php esc_html_e( 'Advanced', 'livada-seo' ); ?>
		</button>
	</div>

	<!-- ══════════════════════════════════════════════════════════════════ -->
	<!-- SEO PANEL                                                         -->
	<!-- ══════════════════════════════════════════════════════════════════ -->
	<div id="livada-seo-panel-seo" class="livada-seo-panel is-active" role="tabpanel" aria-labelledby="livada-seo-tab-seo">

		<!-- Focus keyword -->
		<div class="livada-seo-field">
			<label for="livada_seo_focus_keyword">
				<?php esc_html_e( 'Focus Keyword', 'livada-seo' ); ?>
				<?php if ( $has_ai_key ) : ?>
					<button type="button" class="button button-small livada-seo-ai-btn" data-target="keyword" style="float:right; padding:0 6px; line-height:1.6;">
						<?php esc_html_e( 'AI ✨', 'livada-seo' ); ?>
					</button>
				<?php endif; ?>
			</label>
			<input
				type="text"
				id="livada_seo_focus_keyword"
				name="_livada_seo_focus_keyword"
				value="<?php echo esc_attr( $focus_keyword ); ?>"
				placeholder="<?php esc_attr_e( 'Enter your target keyword…', 'livada-seo' ); ?>"
			/>
			<p class="description"><?php esc_html_e( 'The primary keyword you want this page to rank for.', 'livada-seo' ); ?></p>
		</div>

		<!-- Meta title -->
		<div class="livada-seo-field">
			<label for="livada_seo_title">
				<?php esc_html_e( 'Meta Title', 'livada-seo' ); ?>
				<?php if ( $has_ai_key ) : ?>
					<button type="button" class="button button-small livada-seo-ai-btn" data-target="title" style="float:right; padding:0 6px; line-height:1.6;">
						<?php esc_html_e( 'AI ✨', 'livada-seo' ); ?>
					</button>
				<?php endif; ?>
			</label>
			<input
				type="text"
				id="livada_seo_title"
				name="_livada_seo_title"
				value="<?php echo esc_attr( $seo_title ); ?>"
				placeholder="<?php echo esc_attr( get_the_title( $post->ID ) ); ?>"
			/>
			<div class="livada-seo-counter" id="livada-seo-title-counter" aria-live="polite"></div>
			<p class="description"><?php esc_html_e( 'Ideal length: 50–60 characters. Leave blank to use the post title.', 'livada-seo' ); ?></p>
		</div>

		<!-- Meta description -->
		<div class="livada-seo-field">
			<label for="livada_seo_description">
				<?php esc_html_e( 'Meta Description', 'livada-seo' ); ?>
				<?php if ( $has_ai_key ) : ?>
					<button type="button" class="button button-small livada-seo-ai-btn" data-target="description" style="float:right; padding:0 6px; line-height:1.6;">
						<?php esc_html_e( 'AI ✨', 'livada-seo' ); ?>
					</button>
				<?php endif; ?>
			</label>
			<textarea
				id="livada_seo_description"
				name="_livada_seo_description"
				rows="3"
			><?php echo esc_textarea( $seo_description ); ?></textarea>
			<div class="livada-seo-counter" id="livada-seo-desc-counter" aria-live="polite"></div>
			<p class="description"><?php esc_html_e( 'Ideal length: 120–160 characters.', 'livada-seo' ); ?></p>
		</div>

		<?php if ( $has_ai_key ) : ?>
		<script>
		(function () {
			'use strict';
			var data    = window.livadaSEO || {};
			var ajaxUrl = data.ajaxUrl   || '/wp-admin/admin-ajax.php';
			var nonce   = data.adminNonce || data.nonce || '';
			var postId  = parseInt( ( document.getElementById( 'post_ID' ) || {} ).value || '0', 10 );

			var fieldMap = {
				title:       'livada_seo_title',
				description: 'livada_seo_description',
				keyword:     'livada_seo_focus_keyword',
			};

			document.querySelectorAll( '.livada-seo-ai-btn' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function ( e ) {
					e.preventDefault();

					var type   = btn.getAttribute( 'data-target' );
					var target = document.getElementById( fieldMap[ type ] );
					if ( ! target ) { return; }

					if ( ! postId ) {
						alert( '<?php echo esc_js( __( 'Save the post once before requesting AI suggestions.', 'livada-seo' ) ); ?>' );
						return;
					}

					if ( target.value && ! confirm( '<?php echo esc_js( __( 'Replace the current value with an AI suggestion?', 'livada-seo' ) ); ?>' ) ) {
						return;
					}

					var oldLabel = btn.textContent;
					btn.disabled = true;
					btn.textContent = '…';

					var body = new URLSearchParams( {
						action:  'livada_seo_ai_suggest',
						nonce:   nonce,
						post_id: String( postId ),
						type:    type,
					} );

					fetch( ajaxUrl, {
						method:      'POST',
						credentials: 'same-origin',
						headers:     { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
						body:        body.toString(),
					} )
						.then( function ( r ) { return r.json(); } )
						.then( function ( res ) {
							btn.disabled    = false;
							btn.textContent = oldLabel;

							if ( res && res.success && res.data && typeof res.data.value === 'string' ) {
								target.value = res.data.value;
								target.style.borderColor = '#2271b1';
								target.dispatchEvent( new Event( 'input', { bubbles: true } ) );
								setTimeout( function () { target.style.borderColor = ''; }, 1500 );
							} else {
								alert( ( res && res.data && res.data.message ) || '<?php echo esc_js( __( 'AI request failed.', 'livada-seo' ) ); ?>' );
							}
						} )
						.catch( function () {
							btn.disabled    = false;
							btn.textContent = oldLabel;
							alert( '<?php echo esc_js( __( 'Network error.', 'livada-seo' ) ); ?>' );
						} );
				} );
			} );
		})();
		</script>
		<?php endif; ?>

		<!-- Schema test buttons — only visible once the post has a permalink -->
		<?php if ( '' !== $serp_url ) :
			$rr_url = 'https://search.google.com/test/rich-results?url=' . rawurlencode( $serp_url );
			$sm_url = 'https://validator.schema.org/#url=' . rawurlencode( $serp_url );
		?>
		<div class="livada-seo-validators" style="margin: 4px 0 16px; display:flex; flex-wrap:wrap; gap:8px;">
			<a class="button button-small" href="<?php echo esc_url( $rr_url ); ?>" target="_blank" rel="noopener noreferrer">
				<?php esc_html_e( 'Test in Google Rich Results', 'livada-seo' ); ?> ↗
			</a>
			<a class="button button-small" href="<?php echo esc_url( $sm_url ); ?>" target="_blank" rel="noopener noreferrer">
				<?php esc_html_e( 'Validate on Schema.org', 'livada-seo' ); ?> ↗
			</a>
			<span class="description" style="align-self:center;">
				<?php esc_html_e( 'Save the post first so changes are reflected in the test.', 'livada-seo' ); ?>
			</span>
		</div>
		<?php endif; ?>

		<!-- SERP preview (desktop + mobile) -->
		<div class="livada-seo-serp-toolbar" role="tablist" aria-label="<?php esc_attr_e( 'Preview device', 'livada-seo' ); ?>">
			<button type="button" class="livada-seo-serp-device-btn is-active" data-device="desktop" role="tab" aria-selected="true">
				<?php esc_html_e( 'Desktop', 'livada-seo' ); ?>
			</button>
			<button type="button" class="livada-seo-serp-device-btn" data-device="mobile" role="tab" aria-selected="false">
				<?php esc_html_e( 'Mobile', 'livada-seo' ); ?>
			</button>
		</div>
		<div class="livada-seo-serp" id="livada-seo-serp" data-device="desktop">
			<div class="livada-seo-serp__title" id="livada-seo-serp-title"><?php echo esc_html( $serp_title ); ?></div>
			<div class="livada-seo-serp__url"   id="livada-seo-serp-url"><?php echo esc_url( $serp_url ); ?></div>
			<div class="livada-seo-serp__desc"  id="livada-seo-serp-desc"><?php echo esc_html( $seo_description ); ?></div>
		</div>
		<div class="livada-seo-serp livada-seo-serp--mobile is-hidden" id="livada-seo-serp-mobile" data-device="mobile">
			<div class="livada-seo-serp__title" id="livada-seo-serp-title-mobile"><?php echo esc_html( $serp_title ); ?></div>
			<div class="livada-seo-serp__url"   id="livada-seo-serp-url-mobile"><?php echo esc_url( $serp_url ); ?></div>
			<div class="livada-seo-serp__desc"  id="livada-seo-serp-desc-mobile"><?php echo esc_html( $seo_description ); ?></div>
		</div>

		<!-- Stored SEO score (from analysis module) -->
		<?php if ( ! empty( $score_details ) ) : ?>
		<div class="livada-seo-score">
			<div class="livada-seo-score__label"><?php esc_html_e( 'SEO Score', 'livada-seo' ); ?></div>
			<ul class="livada-seo-score__list">
				<?php foreach ( $score_details as $item ) :
					$status  = isset( $item['status'] ) ? $item['status'] : 'orange';
					$message = isset( $item['message'] ) ? $item['message'] : '';
					$allowed = [ 'green', 'orange', 'red' ];
					$status  = in_array( $status, $allowed, true ) ? $status : 'orange';
				?>
				<li>
					<span class="livada-seo-score__dot is-<?php echo esc_attr( $status ); ?>"></span>
					<span><?php echo esc_html( $message ); ?></span>
				</li>
				<?php endforeach; ?>
			</ul>
		</div>
		<?php endif; ?>

		<!-- Live SEO score (JS-driven) -->
		<div class="livada-seo-live-score">
			<div class="livada-seo-live-score__title"><?php esc_html_e( 'Live Checks', 'livada-seo' ); ?></div>
			<ul class="livada-seo-live-score__list" id="livada-seo-live-checks" aria-live="polite"></ul>
		</div>

		<?php
		$gsc_keywords = class_exists( 'Livada_SEO_GSC_Import' )
			? Livada_SEO_GSC_Import::get_post_keywords( $post->ID )
			: [];
		if ( ! empty( $gsc_keywords ) ) :
		?>
		<!-- GSC keywords (imported from Search Console) -->
		<div class="livada-seo-gsc" style="margin-top:16px; border-top:1px solid #f0f0f1; padding-top:12px;">
			<details>
				<summary style="cursor:pointer; font-weight:600; font-size:12px; color:#646970; text-transform:uppercase; letter-spacing:.03em;">
					<?php esc_html_e( 'Search Console — top queries', 'livada-seo' ); ?>
					<span style="font-weight:400; text-transform:none; letter-spacing:0; color:#646970; margin-left:6px;">
						(<?php echo (int) count( $gsc_keywords ); ?>)
					</span>
				</summary>
				<table class="widefat striped" style="margin-top:6px; font-size:11px;">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Query', 'livada-seo' ); ?></th>
							<th style="width:70px; text-align:right;"><?php esc_html_e( 'Clicks', 'livada-seo' ); ?></th>
							<th style="width:90px; text-align:right;"><?php esc_html_e( 'Impr.', 'livada-seo' ); ?></th>
							<th style="width:80px; text-align:right;"><?php esc_html_e( 'Pos.', 'livada-seo' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $gsc_keywords as $kw ) : ?>
							<tr>
								<td><?php echo esc_html( (string) ( $kw['query'] ?? '' ) ); ?></td>
								<td style="text-align:right;"><?php echo esc_html( (string) (int) ( $kw['clicks'] ?? 0 ) ); ?></td>
								<td style="text-align:right;"><?php echo esc_html( (string) (int) ( $kw['impressions'] ?? 0 ) ); ?></td>
								<td style="text-align:right;">
									<?php echo isset( $kw['position'] ) && null !== $kw['position']
										? esc_html( number_format( (float) $kw['position'], 1 ) )
										: '—'; ?>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</details>
		</div>
		<?php endif; ?>

		<!-- Schema preview (live JSON-LD) -->
		<div class="livada-seo-schema-preview" style="margin-top:16px; border-top:1px solid #f0f0f1; padding-top:12px;">
			<details>
				<summary style="cursor:pointer; font-weight:600; font-size:12px; color:#646970; text-transform:uppercase; letter-spacing:.03em;">
					<?php esc_html_e( 'Schema preview (JSON-LD)', 'livada-seo' ); ?>
				</summary>
				<p class="description" style="margin: 6px 0;">
					<?php esc_html_e( 'Preview the @graph Livada SEO would emit on this post. Save the post first if you want fresh data.', 'livada-seo' ); ?>
				</p>
				<button type="button" id="livada-seo-schema-load" class="button button-small">
					<?php esc_html_e( 'Load preview', 'livada-seo' ); ?>
				</button>
				<pre id="livada-seo-schema-output" style="display:none; background:#1d2327; color:#d4d4d4; padding:12px; border-radius:3px; max-height:320px; overflow:auto; font-size:11px; line-height:1.4; margin-top:8px;"></pre>
			</details>
		</div>

		<!-- Internal linking suggestions -->
		<div class="livada-seo-suggestions">
			<div class="livada-seo-live-score__title"><?php esc_html_e( 'Internal Link Suggestions', 'livada-seo' ); ?></div>
			<p class="description" style="margin: 4px 0 8px;"><?php esc_html_e( 'Posts and pages on this site that match your focus keyword.', 'livada-seo' ); ?></p>
			<ul class="livada-seo-suggestions__list" id="livada-seo-suggestions" aria-live="polite">
				<li class="livada-seo-suggestions__empty"><?php esc_html_e( 'Enter a focus keyword to see suggestions.', 'livada-seo' ); ?></li>
			</ul>
		</div>

	</div><!-- /panel-seo -->

	<!-- ══════════════════════════════════════════════════════════════════ -->
	<!-- SOCIAL PANEL                                                      -->
	<!-- ══════════════════════════════════════════════════════════════════ -->
	<div id="livada-seo-panel-social" class="livada-seo-panel" role="tabpanel" aria-labelledby="livada-seo-tab-social">

		<div class="livada-seo-field">
			<label for="livada_seo_og_image"><?php esc_html_e( 'OG Image', 'livada-seo' ); ?></label>

			<?php
			$has_og = ! empty( $og_image );
			?>
			<img
				id="livada-seo-og-preview"
				class="livada-seo-og-preview<?php echo $has_og ? '' : ' is-hidden'; ?>"
				src="<?php echo $has_og ? esc_url( $og_image ) : ''; ?>"
				alt="<?php esc_attr_e( 'OG image preview', 'livada-seo' ); ?>"
				width="200"
				height="105"
			/>

			<input
				type="hidden"
				id="livada_seo_og_image"
				name="_livada_seo_og_image"
				value="<?php echo esc_url( $og_image ); ?>"
			/>

			<div class="livada-seo-og-actions">
				<button type="button" id="livada-seo-og-pick" class="button button-secondary">
					<?php esc_html_e( 'Select / Change Image', 'livada-seo' ); ?>
				</button>
				<button type="button" id="livada-seo-og-remove" class="button button-link-delete<?php echo $has_og ? '' : ' is-hidden'; ?>">
					<?php esc_html_e( 'Remove image', 'livada-seo' ); ?>
				</button>
			</div>

			<p class="description"><?php esc_html_e( 'Recommended size: 1200 × 630 px. Overrides the site-wide default OG image.', 'livada-seo' ); ?></p>
		</div>

	</div><!-- /panel-social -->

	<!-- ══════════════════════════════════════════════════════════════════ -->
	<!-- ADVANCED PANEL                                                    -->
	<!-- ══════════════════════════════════════════════════════════════════ -->
	<div id="livada-seo-panel-advanced" class="livada-seo-panel" role="tabpanel" aria-labelledby="livada-seo-tab-advanced">

		<!-- Noindex -->
		<div class="livada-seo-check-row">
			<input
				type="checkbox"
				id="livada_seo_noindex"
				name="_livada_seo_noindex"
				value="1"
				<?php checked( $noindex, true ); ?>
			/>
			<label for="livada_seo_noindex"><?php esc_html_e( 'Noindex — ask search engines not to index this post/page', 'livada-seo' ); ?></label>
		</div>

		<!-- Nofollow -->
		<div class="livada-seo-check-row">
			<input
				type="checkbox"
				id="livada_seo_nofollow"
				name="_livada_seo_nofollow"
				value="1"
				<?php checked( $nofollow, true ); ?>
			/>
			<label for="livada_seo_nofollow"><?php esc_html_e( 'Nofollow — ask search engines not to follow links on this post/page', 'livada-seo' ); ?></label>
		</div>

		<!-- Cornerstone -->
		<div class="livada-seo-check-row">
			<input
				type="checkbox"
				id="livada_seo_cornerstone"
				name="_livada_seo_cornerstone"
				value="1"
				<?php checked( $cornerstone, true ); ?>
			/>
			<label for="livada_seo_cornerstone">
				<?php esc_html_e( 'Cornerstone content — flagship article that other posts should link to', 'livada-seo' ); ?>
			</label>
		</div>

		<?php if ( $cornerstone_links_in > 0 ) : ?>
		<p class="description" style="margin: 4px 0 12px; padding-left: 24px;">
			<?php
			printf(
				/* translators: %d: number of cornerstone posts that link here */
				esc_html( _n(
					'%d cornerstone post already links to this page.',
					'%d cornerstone posts already link to this page.',
					$cornerstone_links_in,
					'livada-seo'
				) ),
				(int) $cornerstone_links_in
			);
			?>
		</p>
		<?php endif; ?>

		<!-- Canonical URL -->
		<div class="livada-seo-field">
			<label for="livada_seo_canonical"><?php esc_html_e( 'Canonical URL', 'livada-seo' ); ?></label>
			<input
				type="url"
				id="livada_seo_canonical"
				name="_livada_seo_canonical"
				value="<?php echo esc_url( $canonical ); ?>"
				placeholder="<?php echo esc_url( get_permalink( $post->ID ) ); ?>"
			/>
			<p class="description"><?php esc_html_e( 'Leave blank to use the default permalink as canonical.', 'livada-seo' ); ?></p>
		</div>

		<!-- Service schema -->
		<div class="livada-seo-check-row">
			<input
				type="checkbox"
				id="livada_seo_service_schema"
				name="_livada_seo_service_schema"
				value="1"
				<?php checked( $service_schema, true ); ?>
			/>
			<label for="livada_seo_service_schema"><?php esc_html_e( 'Enable Service schema on this page', 'livada-seo' ); ?></label>
		</div>

		<!-- FAQ schema -->
		<div class="livada-seo-check-row">
			<input
				type="checkbox"
				id="livada_seo_faq_schema"
				name="_livada_seo_faq_schema"
				value="1"
				<?php checked( $faq_schema, true ); ?>
			/>
			<label for="livada_seo_faq_schema"><?php esc_html_e( 'Enable FAQPage schema (auto-detects accordion/heading + paragraph patterns)', 'livada-seo' ); ?></label>
		</div>

		<!-- Content schema type -->
		<div class="livada-seo-field">
			<label for="livada_seo_schema_type"><?php esc_html_e( 'Content Schema Type', 'livada-seo' ); ?></label>
			<select id="livada_seo_schema_type" name="_livada_seo_schema_type">
				<?php foreach ( $schema_choices as $value => $label ) : ?>
					<option value="<?php echo esc_attr( $value ); ?>"<?php selected( $schema_type, $value ); ?>>
						<?php echo esc_html( $label ); ?>
					</option>
				<?php endforeach; ?>
			</select>
			<p class="description">
				<?php esc_html_e( 'Optional rich-result type for this post. Each type reads its data from dedicated post meta keys (see plugin docs).', 'livada-seo' ); ?>
			</p>
		</div>

		<!-- Offer fields — shown only when schema_type === Offer -->
		<fieldset id="livada-seo-offer-fields" style="<?php echo 'Offer' === $schema_type ? '' : 'display:none;'; ?> border:1px solid #f0f0f1; padding:10px 12px; border-radius:3px; margin-top:8px;">
			<legend style="font-weight:600; padding:0 4px;"><?php esc_html_e( 'Offer details', 'livada-seo' ); ?></legend>

			<div class="livada-seo-field" style="display:flex; gap:8px; align-items:end;">
				<div style="flex:1;">
					<label for="livada_seo_offer_price"><?php esc_html_e( 'Price', 'livada-seo' ); ?></label>
					<input type="number" id="livada_seo_offer_price" name="_livada_seo_offer_price" step="0.01" min="0" value="<?php echo esc_attr( $offer_price ); ?>" style="width:100%;">
				</div>
				<div style="width:90px;">
					<label for="livada_seo_offer_currency"><?php esc_html_e( 'Currency', 'livada-seo' ); ?></label>
					<input type="text" id="livada_seo_offer_currency" name="_livada_seo_offer_currency" maxlength="3" value="<?php echo esc_attr( $offer_currency ); ?>" style="width:100%; text-transform:uppercase;">
				</div>
			</div>

			<div class="livada-seo-field" style="display:flex; gap:8px;">
				<div style="flex:1;">
					<label for="livada_seo_offer_valid_from"><?php esc_html_e( 'Valid from', 'livada-seo' ); ?></label>
					<input type="date" id="livada_seo_offer_valid_from" name="_livada_seo_offer_valid_from" value="<?php echo esc_attr( $offer_valid_from ); ?>" style="width:100%;">
				</div>
				<div style="flex:1;">
					<label for="livada_seo_offer_valid_through"><?php esc_html_e( 'Valid through', 'livada-seo' ); ?></label>
					<input type="date" id="livada_seo_offer_valid_through" name="_livada_seo_offer_valid_through" value="<?php echo esc_attr( $offer_valid_through ); ?>" style="width:100%;">
				</div>
			</div>

			<div class="livada-seo-field">
				<label for="livada_seo_offer_availability"><?php esc_html_e( 'Availability', 'livada-seo' ); ?></label>
				<select id="livada_seo_offer_availability" name="_livada_seo_offer_availability" style="width:100%;">
					<?php foreach ( $offer_availability_choices as $value => $label ) : ?>
						<option value="<?php echo esc_attr( $value ); ?>"<?php selected( $offer_availability, $value ); ?>>
							<?php echo esc_html( $label ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</div>
		</fieldset>

		<script>
		(function () {
			var sel = document.getElementById('livada_seo_schema_type');
			var box = document.getElementById('livada-seo-offer-fields');
			if (sel && box) {
				sel.addEventListener('change', function () {
					box.style.display = sel.value === 'Offer' ? '' : 'none';
				});
			}
		})();
		</script>

		<!-- Exclude from sitemap -->
		<div class="livada-seo-check-row">
			<input
				type="checkbox"
				id="livada_seo_sitemap_exclude"
				name="_livada_seo_sitemap_exclude"
				value="1"
				<?php checked( $sitemap_exclude, true ); ?>
			/>
			<label for="livada_seo_sitemap_exclude"><?php esc_html_e( 'Exclude this post/page from the XML sitemap', 'livada-seo' ); ?></label>
		</div>

		<!-- Hreflang manual override -->
		<div class="livada-seo-field">
			<label><?php esc_html_e( 'Hreflang Overrides', 'livada-seo' ); ?></label>
			<p class="description" style="margin-top:0;">
				<?php esc_html_e( 'Override the hreflang URLs emitted on this post. Leave empty to let the multilingual plugin (Polylang / WPML / TranslatePress) provide them automatically.', 'livada-seo' ); ?>
			</p>

			<table class="livada-hreflang-table" style="width:100%; margin-top:6px;">
				<thead>
					<tr>
						<th style="width: 28%; text-align:left; font-size:11px; color:#646970;">
							<?php esc_html_e( 'Language', 'livada-seo' ); ?>
						</th>
						<th style="text-align:left; font-size:11px; color:#646970;">
							<?php esc_html_e( 'URL', 'livada-seo' ); ?>
						</th>
						<th style="width: 24px;"></th>
					</tr>
				</thead>
				<tbody id="livada-hreflang-rows">
					<?php
					$idx = 0;
					if ( ! empty( $hreflang_meta ) ) :
						foreach ( $hreflang_meta as $lang => $url ) :
							$lang = (string) $lang;
							$url  = (string) $url;
							?>
							<tr class="livada-hreflang-row">
								<td>
									<input type="text" name="_livada_seo_hreflang[<?php echo (int) $idx; ?>][lang]" value="<?php echo esc_attr( $lang ); ?>" placeholder="fr-FR" style="width:100%;" maxlength="12">
								</td>
								<td>
									<input type="url" name="_livada_seo_hreflang[<?php echo (int) $idx; ?>][url]" value="<?php echo esc_url( $url ); ?>" placeholder="https://" style="width:100%;">
								</td>
								<td>
									<button type="button" class="button-link livada-hreflang-remove" aria-label="<?php esc_attr_e( 'Remove row', 'livada-seo' ); ?>" style="color:#b32d2e;">&#10005;</button>
								</td>
							</tr>
							<?php
							$idx++;
						endforeach;
					endif;
					?>
				</tbody>
			</table>

			<!-- Hidden template row cloned by JS when "+ Add" is clicked -->
			<template id="livada-hreflang-template">
				<tr class="livada-hreflang-row">
					<td>
						<input type="text" name="_livada_seo_hreflang[__IDX__][lang]" placeholder="fr-FR" style="width:100%;" maxlength="12">
					</td>
					<td>
						<input type="url" name="_livada_seo_hreflang[__IDX__][url]" placeholder="https://" style="width:100%;">
					</td>
					<td>
						<button type="button" class="button-link livada-hreflang-remove" aria-label="<?php esc_attr_e( 'Remove row', 'livada-seo' ); ?>" style="color:#b32d2e;">&#10005;</button>
					</td>
				</tr>
			</template>

			<p style="margin-top:6px;">
				<button type="button" class="button button-small" id="livada-hreflang-add">
					<?php esc_html_e( '+ Add hreflang entry', 'livada-seo' ); ?>
				</button>
				<span class="description" style="margin-left:8px;">
					<?php esc_html_e( 'Use BCP-47 codes: fr, en, fr-FR, en-GB, x-default.', 'livada-seo' ); ?>
				</span>
			</p>
		</div>

		<script>
		(function () {
			'use strict';
			var addBtn = document.getElementById( 'livada-hreflang-add' );
			var tbody  = document.getElementById( 'livada-hreflang-rows' );
			var tpl    = document.getElementById( 'livada-hreflang-template' );

			if ( ! addBtn || ! tbody || ! tpl ) { return; }

			function nextIndex() {
				return tbody.querySelectorAll( '.livada-hreflang-row' ).length;
			}

			addBtn.addEventListener( 'click', function () {
				var idx   = nextIndex();
				var html  = tpl.innerHTML.replace( /__IDX__/g, String( idx ) );
				var wrap  = document.createElement( 'tbody' );
				wrap.innerHTML = html;
				tbody.appendChild( wrap.firstElementChild );
			} );

			tbody.addEventListener( 'click', function ( e ) {
				var btn = e.target.closest( '.livada-hreflang-remove' );
				if ( ! btn ) { return; }
				var row = btn.closest( '.livada-hreflang-row' );
				if ( row ) { row.remove(); }
			} );
		})();
		</script>

		<?php if ( count( $locations_for_metabox ) > 1 ) : ?>
		<!-- Linked location -->
		<div class="livada-seo-field">
			<label for="livada_seo_location_id"><?php esc_html_e( 'Linked Location', 'livada-seo' ); ?></label>
			<select id="livada_seo_location_id" name="_livada_seo_location_id">
				<option value=""<?php selected( '' === $location_id, true ); ?>>
					<?php esc_html_e( '— Default (location #1) —', 'livada-seo' ); ?>
				</option>
				<?php foreach ( $locations_for_metabox as $idx => $loc_meta ) :
					$loc_label = isset( $loc_meta['name'] ) ? (string) $loc_meta['name'] : '';
					if ( '' === $loc_label ) {
						$loc_label = sprintf( __( 'Location #%d', 'livada-seo' ), (int) $idx + 1 );
					}
				?>
					<option value="<?php echo esc_attr( (string) $idx ); ?>"<?php selected( (string) $idx, $location_id ); ?>>
						<?php echo esc_html( sprintf( '#%d — %s', (int) $idx + 1, $loc_label ) ); ?>
					</option>
				<?php endforeach; ?>
			</select>
			<p class="description">
				<?php esc_html_e( 'Schema references on this post (Article publisher, Service provider, Offer seller) point to the selected business location.', 'livada-seo' ); ?>
			</p>
		</div>
		<?php endif; ?>

	</div><!-- /panel-advanced -->

</div><!-- /.livada-seo-metabox -->
