<?php
if (!defined('ABSPATH')) {
	exit;
}
$s = IComm_SM_Settings::get();
$summary = IComm_SM_DB::summary(IComm_SM_Features::history_days());
$queries = IComm_SM_DB::top_queries(IComm_SM_Features::top_queries_limit());
$sync_url = wp_nonce_url(
	add_query_arg(['action' => 'icomm_sm_sync_now'], admin_url('admin-post.php')),
	'icomm_sm_sync_now'
);
$is_pro = IComm_SM_Features::is_pro();
$trial = IComm_SM_License::trial_days_left();
$lic = IComm_SM_License::get_settings();
$exp = (int) ($lic['license_expires_at'] ?? 0);
$now = current_time('timestamp');
$days_to_exp = ($exp > 0) ? (int) ceil(($exp - $now) / DAY_IN_SECONDS) : 0;
$buy_url = IComm_SM_Purchase::checkout_url();
$reco = IComm_SM_Features::can_use('recommendations') ? IComm_SM_Recommendations::dashboard_items() : [];
$trend = IComm_SM_Features::can_use('seo_trend') ? IComm_SM_Recommendations::seo_monthly_trend() : null;
$trend_months = is_array($trend) ? (array) ($trend['months'] ?? []) : [];
$trend_max_clicks = 1;
$trend_max_impr = 1;
foreach ($trend_months as $tm) {
	$trend_max_clicks = max($trend_max_clicks, (int) ($tm['clicks'] ?? 0));
	$trend_max_impr = max($trend_max_impr, (int) ($tm['impressions'] ?? 0));
}
?>
<div class="wrap icomm-sm-wrap" dir="rtl" lang="he">
	<h1><?php esc_html_e('icomm metrix - דשבורד', 'icomm-metrix'); ?> <span>v<?php echo esc_html(ICOMM_SM_VERSION); ?></span></h1>

	<?php if (!empty($_GET['synced'])) : ?>
		<div class="notice notice-success is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p><?php esc_html_e('הסנכרון הושלם.', 'icomm-metrix'); ?></p></div>
	<?php elseif (!empty($_GET['sync_error'])) : ?>
		<div class="notice notice-error is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p><?php esc_html_e('סנכרון נכשל, בדקו חיבורים והרשאות API.', 'icomm-metrix'); ?></p></div>
	<?php endif; ?>
	<?php if (!empty($_GET['trend_mail'])) : ?>
		<?php
		$tm = sanitize_key((string) wp_unslash($_GET['trend_mail']));
		$tm_err = isset($_GET['trend_mail_err']) ? sanitize_key((string) wp_unslash($_GET['trend_mail_err'])) : '';
		$tm_detail = (string) get_transient('icomm_sm_trend_mail_err_' . get_current_user_id());
		if ($tm_detail !== '') {
			delete_transient('icomm_sm_trend_mail_err_' . get_current_user_id());
		}
		?>
		<?php if ($tm === 'ok') : ?>
			<div class="notice notice-success is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;">
				<p>
					<?php esc_html_e('השרת דיווח שהמייל נשלח.', 'icomm-metrix'); ?>
					<?php esc_html_e('אם לא הגיע: בדקו ספאם, ואת יומן השליחות ב-icomm WP SMTP.', 'icomm-metrix'); ?>
				</p>
			</div>
		<?php else : ?>
			<div class="notice notice-error is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p>
				<?php
				if ($tm_err === 'invalid_email') {
					esc_html_e('כתובת המייל אינה תקינה.', 'icomm-metrix');
				} elseif ($tm_err === 'no_data') {
					esc_html_e('אין נתוני מגמה לשליחה. סנכרנו קודם.', 'icomm-metrix');
				} elseif ($tm === 'locked') {
					esc_html_e('שליחת מגמת SEO דורשת PRO.', 'icomm-metrix');
				} else {
					esc_html_e('שליחת המייל נכשלה.', 'icomm-metrix');
				}
				if ($tm_detail !== '') {
					echo ' ';
					echo esc_html($tm_detail);
				}
				?>
			</p></div>
		<?php endif; ?>
	<?php endif; ?>

	<p class="description" style="<?php echo ($is_pro && IComm_SM_License::is_active()) ? 'color:#15803d;font-weight:500;' : ''; ?>">
		<?php
		if ($is_pro && IComm_SM_License::is_active()) {
			if ($exp > 0) {
				echo esc_html(sprintf(__('רישיון PRO פעיל, תוקף עד %s.', 'icomm-metrix'), wp_date('d/m/Y', $exp)));
				if ($days_to_exp > 0 && $days_to_exp <= 30) {
					echo ' ' . esc_html(sprintf(__('(נותרו %d ימים)', 'icomm-metrix'), max(1, $days_to_exp)));
				}
			} else {
				esc_html_e('רישיון PRO פעיל.', 'icomm-metrix');
			}
		} elseif ($trial > 0) {
			echo esc_html(sprintf(__('ניסיון PRO: %d ימים נותרו.', 'icomm-metrix'), $trial));
		} else {
			esc_html_e('מצב חינמי, סיכום 7 ימים, 5 מילות חיפוש.', 'icomm-metrix');
		}
		?>
	</p>

	<?php if ($is_pro && IComm_SM_License::is_active() && $exp > 0 && $days_to_exp > 0 && $days_to_exp <= 30 && $buy_url !== '') : ?>
		<div class="notice notice-warning" dir="rtl" lang="he" style="direction:rtl;text-align:right;">
			<p style="margin:0;">
				<strong><?php esc_html_e('תזכורת חידוש:', 'icomm-metrix'); ?></strong>
				<?php echo esc_html(sprintf(__('נותרו %d ימים לתוקף הרישיון.', 'icomm-metrix'), max(1, $days_to_exp))); ?>
				<a class="button button-primary" href="<?php echo esc_url($buy_url); ?>" target="_blank" rel="noopener noreferrer" style="margin-right:10px;">
					<?php esc_html_e('חידוש', 'icomm-metrix'); ?>
				</a>
			</p>
		</div>
	<?php endif; ?>

	<?php if (!IComm_SM_Settings::is_gsc_ready()) : ?>
		<div class="notice notice-warning" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p>
			<?php esc_html_e('חברו נתוני חיפוש כדי לראות נתונים.', 'icomm-metrix'); ?>
			<a href="<?php echo esc_url(admin_url('admin.php?page=icomm-metrix-connections')); ?>"><?php esc_html_e('חיבורים', 'icomm-metrix'); ?></a>
		</p></div>
	<?php endif; ?>

	<div class="icomm-sm-cards">
		<div class="icomm-sm-card">
			<h3><?php esc_html_e('קליקים מגוגל', 'icomm-metrix'); ?></h3>
			<div class="icomm-sm-stat"><?php echo esc_html((string) (int) $summary['clicks']); ?></div>
		</div>
		<div class="icomm-sm-card">
			<h3><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></h3>
			<div class="icomm-sm-stat"><?php echo esc_html((string) (int) $summary['impressions']); ?></div>
		</div>
		<div class="icomm-sm-card <?php echo IComm_SM_Features::can_use('ga4_metrics') ? '' : 'icomm-sm-locked-preview'; ?>">
			<h3><?php esc_html_e('כניסות לאתר', 'icomm-metrix'); ?> <?php echo IComm_SM_Features::pro_badge_html(); ?></h3>
			<div class="icomm-sm-stat"><?php echo esc_html((string) (int) $summary['sessions']); ?></div>
		</div>
		<div class="icomm-sm-card">
			<h3><?php esc_html_e('תקופה', 'icomm-metrix'); ?></h3>
			<div class="icomm-sm-stat"><?php echo esc_html((string) (int) $summary['period_days']); ?> <?php esc_html_e('ימים', 'icomm-metrix'); ?></div>
		</div>
	</div>

	<p>
		<a class="button button-primary icomm-sm-busy-link" data-icomm-sm-busy="sync" href="<?php echo esc_url($sync_url); ?>"><?php esc_html_e('סנכרן עכשיו', 'icomm-metrix'); ?></a>
		<a class="button" href="<?php echo esc_url(admin_url('admin.php?page=icomm-metrix-client')); ?>"><?php esc_html_e('תצוגת דוח ללקוח', 'icomm-metrix'); ?></a>
	</p>
	<?php if (!empty($s['gsc_last_sync_at']) || !empty($s['ga4_last_sync_at']) || !empty($s['last_manual_sync_at'])) : ?>
		<p class="description">
			<?php if (!empty($s['gsc_last_sync_at'])) : ?>
				<?php echo esc_html(sprintf(__('GSC: סנכרון אחרון %s', 'icomm-metrix'), wp_date('d/m/Y H:i', (int) $s['gsc_last_sync_at']))); ?><br>
			<?php endif; ?>
			<?php if (!empty($s['ga4_last_sync_at']) && IComm_SM_Features::can_use('ga4_metrics')) : ?>
				<?php echo esc_html(sprintf(__('GA4: סנכרון אחרון %s', 'icomm-metrix'), wp_date('d/m/Y H:i', (int) $s['ga4_last_sync_at']))); ?><br>
			<?php endif; ?>
			<?php if (!empty($s['gsc_last_error'])) : ?>
				<span style="color:#d63638;"><?php echo esc_html(IComm_SM_Remote::friendly_google_error((string) $s['gsc_last_error'], 'gsc')); ?></span>
				- <a href="<?php echo esc_url(IComm_SM_Remote::connect_url('search')); ?>"><?php esc_html_e('חבר נתוני חיפוש מחדש', 'icomm-metrix'); ?></a><br>
			<?php endif; ?>
			<?php if (!empty($s['ga4_last_error']) && IComm_SM_Features::can_use('ga4_metrics')) : ?>
				<span style="color:#d63638;"><?php echo esc_html(IComm_SM_Remote::friendly_google_error((string) $s['ga4_last_error'], 'ga4')); ?></span>
			<?php endif; ?>
		</p>
	<?php elseif (!empty($s['gsc_last_error'])) : ?>
		<p class="description">
			<span style="color:#d63638;"><?php echo esc_html(IComm_SM_Remote::friendly_google_error((string) $s['gsc_last_error'], 'gsc')); ?></span>
			- <a href="<?php echo esc_url(IComm_SM_Remote::connect_url('search')); ?>"><?php esc_html_e('חבר נתוני חיפוש מחדש', 'icomm-metrix'); ?></a>
		</p>
	<?php endif; ?>

	<h2><?php esc_html_e('מגמת SEO חודשית', 'icomm-metrix'); ?> <?php echo IComm_SM_Features::pro_badge_html(); ?></h2>
	<?php echo IComm_SM_Features::locked_notice_html(__('מגמת SEO חודשית', 'icomm-metrix')); ?>
	<div class="icomm-sm-trend-panel <?php echo IComm_SM_Features::can_use('seo_trend') ? '' : 'icomm-sm-locked-preview'; ?>">
		<?php if (!IComm_SM_Features::can_use('seo_trend')) : ?>
			<p class="description"><?php esc_html_e('ב-PRO: גרף עד כ-16 חודשים (מקסימום GSC), השוואת חודש מול חודש, שנה מול שנה כשיש נתונים, ומגמה ארוכה עם המלצות.', 'icomm-metrix'); ?></p>
		<?php elseif ($trend_months === []) : ?>
			<p class="description"><?php esc_html_e('אין נתונים חודשיים עדיין. חברו GSC וסנכרנו.', 'icomm-metrix'); ?></p>
		<?php else : ?>
			<?php
			$dir = (string) ($trend['direction'] ?? 'unknown');
			$dir_class = 'icomm-sm-trend-badge--' . preg_replace('/[^a-z]/', '', $dir);
			?>
			<div class="icomm-sm-trend-head">
				<span class="icomm-sm-trend-badge <?php echo esc_attr($dir_class); ?>">
					<?php echo esc_html((string) ($trend['direction_label'] ?? '')); ?>
				</span>
				<p class="icomm-sm-trend-summary"><?php echo esc_html((string) ($trend['summary'] ?? '')); ?></p>
			</div>
			<?php if (!empty($trend['range_note'])) : ?>
				<p class="description icomm-sm-trend-range"><?php echo esc_html((string) $trend['range_note']); ?></p>
			<?php endif; ?>

			<?php
			$deltas = is_array($trend['deltas'] ?? null) ? $trend['deltas'] : [];
			$d_clicks = (float) ($deltas['clicks_pct'] ?? 0);
			$d_impr = (float) ($deltas['impressions_pct'] ?? 0);
			$d_ctr = (float) ($deltas['ctr_pct'] ?? 0);
			$d_pos = (float) ($deltas['position_delta'] ?? 0);
			$yoy = is_array($trend['yoy'] ?? null) ? $trend['yoy'] : [];
			$long = is_array($trend['long_term'] ?? null) ? $trend['long_term'] : [];
			?>
			<p class="icomm-sm-trend-section-label"><?php esc_html_e('חודש מול חודש קודם', 'icomm-metrix'); ?></p>
			<div class="icomm-sm-trend-deltas">
				<div class="icomm-sm-trend-delta">
					<span class="icomm-sm-trend-delta__label"><?php esc_html_e('קליקים', 'icomm-metrix'); ?></span>
					<span class="<?php echo $d_clicks >= 0 ? 'icomm-sm-delta-up' : 'icomm-sm-delta-down'; ?>">
						<?php echo esc_html(($d_clicks > 0 ? '+' : '') . (string) $d_clicks); ?>%
					</span>
				</div>
				<div class="icomm-sm-trend-delta">
					<span class="icomm-sm-trend-delta__label"><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></span>
					<span class="<?php echo $d_impr >= 0 ? 'icomm-sm-delta-up' : 'icomm-sm-delta-down'; ?>">
						<?php echo esc_html(($d_impr > 0 ? '+' : '') . (string) $d_impr); ?>%
					</span>
				</div>
				<div class="icomm-sm-trend-delta">
					<span class="icomm-sm-trend-delta__label"><?php esc_html_e('CTR', 'icomm-metrix'); ?></span>
					<span class="<?php echo $d_ctr >= 0 ? 'icomm-sm-delta-up' : 'icomm-sm-delta-down'; ?>">
						<?php echo esc_html(($d_ctr > 0 ? '+' : '') . (string) $d_ctr); ?>%
					</span>
				</div>
				<div class="icomm-sm-trend-delta">
					<span class="icomm-sm-trend-delta__label"><?php esc_html_e('שיפור מיקום', 'icomm-metrix'); ?></span>
					<span class="<?php echo $d_pos >= 0 ? 'icomm-sm-delta-up' : 'icomm-sm-delta-down'; ?>">
						<?php echo esc_html(($d_pos > 0 ? '+' : '') . (string) $d_pos); ?>
					</span>
				</div>
			</div>

			<?php if (!empty($yoy['available']) || !empty($long['available'])) : ?>
				<div class="icomm-sm-trend-compare-row">
					<?php if (!empty($yoy['available'])) : ?>
						<?php
						$yoy_c = (float) ($yoy['clicks_pct'] ?? 0);
						$yoy_i = (float) ($yoy['impressions_pct'] ?? 0);
						?>
						<div class="icomm-sm-trend-compare-card">
							<strong><?php esc_html_e('שנה מול שנה (YoY)', 'icomm-metrix'); ?></strong>
							<span class="description"><?php echo esc_html((string) ($yoy['label'] ?? '')); ?></span>
							<span>
								<?php esc_html_e('קליקים', 'icomm-metrix'); ?>:
								<span class="<?php echo $yoy_c >= 0 ? 'icomm-sm-delta-up' : 'icomm-sm-delta-down'; ?>">
									<?php echo esc_html(($yoy_c > 0 ? '+' : '') . (string) $yoy_c); ?>%
								</span>
								·
								<?php esc_html_e('חשיפות', 'icomm-metrix'); ?>:
								<span class="<?php echo $yoy_i >= 0 ? 'icomm-sm-delta-up' : 'icomm-sm-delta-down'; ?>">
									<?php echo esc_html(($yoy_i > 0 ? '+' : '') . (string) $yoy_i); ?>%
								</span>
							</span>
						</div>
					<?php endif; ?>
					<?php if (!empty($long['available'])) : ?>
						<?php
						$lt_c = (float) ($long['clicks_pct'] ?? 0);
						$lt_i = (float) ($long['impressions_pct'] ?? 0);
						?>
						<div class="icomm-sm-trend-compare-card">
							<strong><?php esc_html_e('מגמה ארוכה (3 מול 3 חודשים)', 'icomm-metrix'); ?></strong>
							<span class="description"><?php echo esc_html((string) ($long['label'] ?? '')); ?></span>
							<span>
								<?php esc_html_e('קליקים', 'icomm-metrix'); ?>:
								<span class="<?php echo $lt_c >= 0 ? 'icomm-sm-delta-up' : 'icomm-sm-delta-down'; ?>">
									<?php echo esc_html(($lt_c > 0 ? '+' : '') . (string) $lt_c); ?>%
								</span>
								·
								<?php esc_html_e('חשיפות', 'icomm-metrix'); ?>:
								<span class="<?php echo $lt_i >= 0 ? 'icomm-sm-delta-up' : 'icomm-sm-delta-down'; ?>">
									<?php echo esc_html(($lt_i > 0 ? '+' : '') . (string) $lt_i); ?>%
								</span>
							</span>
						</div>
					<?php endif; ?>
				</div>
			<?php endif; ?>

			<p class="icomm-sm-trend-actions">
				<button type="button" class="button button-primary" data-icomm-sm-open-trend-chart>
					<?php esc_html_e('פתח גרף מפורט', 'icomm-metrix'); ?>
				</button>
				<span class="description"><?php esc_html_e('עמודות, קו או נרות · בחירת מדד וטווח', 'icomm-metrix'); ?></span>
			</p>

			<?php
			$default_mail = '';
			if (!empty($s['client_report_email']) && is_email((string) $s['client_report_email'])) {
				$default_mail = (string) $s['client_report_email'];
			} else {
				$admin_mail = get_option('admin_email');
				$default_mail = is_string($admin_mail) ? $admin_mail : '';
			}
			?>
			<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="icomm-sm-trend-mail-form" target="_self">
				<?php wp_nonce_field('icomm_sm_send_trend_email'); ?>
				<input type="hidden" name="action" value="icomm_sm_send_trend_email" />
				<h3 class="icomm-sm-trend-mail-title"><?php esc_html_e('שליחת הגרף במייל', 'icomm-metrix'); ?></h3>
				<p class="description" style="margin-top:0;"><?php esc_html_e('מייל HTML מעוצב וקריא (RTL). אפשר לבחור אם לכלול ניתוח והמלצות.', 'icomm-metrix'); ?></p>
				<p>
					<label for="icomm-sm-trend-mail-to"><?php esc_html_e('אל', 'icomm-metrix'); ?></label><br>
					<input type="email" class="regular-text" name="trend_mail_to" id="icomm-sm-trend-mail-to" value="<?php echo esc_attr($default_mail); ?>" dir="ltr" required />
				</p>
				<p>
					<label>
						<input type="checkbox" name="trend_mail_analysis" value="1" checked />
						<?php esc_html_e('כלול ניתוח, הסברים והמלצות פעולה', 'icomm-metrix'); ?>
					</label>
					<br>
					<span class="description"><?php esc_html_e('בלי סימון: רק גרף, טבלת חודשים והשוואת חודש מול חודש.', 'icomm-metrix'); ?></span>
				</p>
				<p class="icomm-sm-trend-mail-buttons">
					<button type="submit" name="trend_mail_send" value="1" class="button button-primary"><?php esc_html_e('שלח מגמת SEO במייל', 'icomm-metrix'); ?></button>
					<button type="submit" name="trend_mail_preview" value="1" class="button" formtarget="_blank"><?php esc_html_e('תצוגה מקדימה', 'icomm-metrix'); ?></button>
				</p>
				<?php
				$last = get_option('icomm_sm_last_trend_mail', null);
				if (is_array($last) && !empty($last['at'])) :
					$when = wp_date('d/m/Y H:i', (int) $last['at']);
					?>
					<p class="description">
						<?php
						echo esc_html(sprintf(
							/* translators: 1: datetime, 2: email */
							__('שליחה אחרונה: %1$s אל %2$s', 'icomm-metrix'),
							$when,
							(string) ($last['to'] ?? '')
						));
						echo ' · ';
						echo !empty($last['ok'])
							? esc_html__('סטטוס: השרת דיווח הצלחה', 'icomm-metrix')
							: esc_html__('סטטוס: נכשל', 'icomm-metrix');
						if (empty($last['ok']) && !empty($last['error'])) {
							echo ' (' . esc_html((string) $last['error']) . ')';
						}
						?>
					</p>
				<?php endif; ?>
			</form>

			<div class="icomm-sm-trend-chart icomm-sm-trend-chart--clickable" role="button" tabindex="0" data-icomm-sm-open-trend-chart aria-label="<?php esc_attr_e('פתח גרף מפורט', 'icomm-metrix'); ?>">
				<div class="icomm-sm-trend-legend">
					<span><i class="icomm-sm-legend-swatch icomm-sm-legend-clicks"></i><?php esc_html_e('קליקים', 'icomm-metrix'); ?></span>
					<span><i class="icomm-sm-legend-swatch icomm-sm-legend-impr"></i><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></span>
				</div>
				<div class="icomm-sm-trend-bars-wrap">
				<div class="icomm-sm-trend-bars">
					<?php foreach ($trend_months as $tm) : ?>
						<?php
						$c = (int) ($tm['clicks'] ?? 0);
						$i = (int) ($tm['impressions'] ?? 0);
						$h_c = $trend_max_clicks > 0 ? max(4, (int) round(($c / $trend_max_clicks) * 100)) : 4;
						$h_i = $trend_max_impr > 0 ? max(4, (int) round(($i / $trend_max_impr) * 100)) : 4;
						if ($c === 0 && $i === 0) {
							$h_c = 2;
							$h_i = 2;
						}
						$pos = (float) ($tm['position'] ?? 0);
						$partial = !empty($tm['is_partial']);
						?>
						<div class="icomm-sm-trend-col<?php echo $partial ? ' is-partial' : ''; ?>">
							<div class="icomm-sm-trend-col__bars">
								<span class="icomm-sm-bar icomm-sm-bar--clicks" style="height:<?php echo esc_attr((string) $h_c); ?>%;" title="<?php echo esc_attr(sprintf(__('קליקים: %d', 'icomm-metrix'), $c)); ?>"></span>
								<span class="icomm-sm-bar icomm-sm-bar--impr" style="height:<?php echo esc_attr((string) $h_i); ?>%;" title="<?php echo esc_attr(sprintf(__('חשיפות: %d', 'icomm-metrix'), $i)); ?>"></span>
							</div>
							<div class="icomm-sm-trend-col__meta">
								<strong><?php echo esc_html((string) ($tm['label'] ?? '')); ?></strong>
								<span><?php echo esc_html(sprintf(__('%1$d קליקים · %2$d חשיפות', 'icomm-metrix'), $c, $i)); ?></span>
								<?php if ($pos > 0) : ?>
									<span><?php echo esc_html(sprintf(__('מיקום ממוצע %s', 'icomm-metrix'), (string) $pos)); ?></span>
								<?php endif; ?>
								<?php if ($partial) : ?>
									<span class="icomm-sm-trend-partial"><?php esc_html_e('חודש חלקי', 'icomm-metrix'); ?></span>
								<?php endif; ?>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
				</div>
			</div>

			<?php $trend_recs = is_array($trend['recommendations'] ?? null) ? $trend['recommendations'] : []; ?>
			<?php if ($trend_recs !== []) : ?>
				<h3 class="icomm-sm-trend-rec-title"><?php esc_html_e('איך לפעול הלאה', 'icomm-metrix'); ?></h3>
				<ul class="icomm-sm-trend-recs">
					<?php foreach ($trend_recs as $tr) : ?>
						<li class="icomm-sm-trend-rec icomm-sm-trend-rec--<?php echo esc_attr(preg_replace('/[^a-z]/', '', (string) ($tr['priority'] ?? 'low'))); ?>">
							<strong><?php echo esc_html((string) ($tr['title'] ?? '')); ?></strong>
							<span><?php echo esc_html((string) ($tr['details'] ?? '')); ?></span>
						</li>
					<?php endforeach; ?>
				</ul>
			<?php endif; ?>
			<p class="description" style="margin-top:8px;">
				<?php esc_html_e('המגמה מבוססת על נתוני GSC יומיים. אחרי עדכון שרת הרישוי + סנכרון מחדש נמשכים עד כ-16 חודשים. Google לא מספק היסטוריה לשנים ישנות יותר.', 'icomm-metrix'); ?>
				·
				<a href="<?php echo esc_url(admin_url('admin.php?page=icomm-metrix-opportunities')); ?>"><?php esc_html_e('הזדמנויות SEO', 'icomm-metrix'); ?></a>
			</p>
		<?php endif; ?>
	</div>

	<?php
	$kw_ranks_url = add_query_arg(['page' => 'icomm-metrix-keywords'], admin_url('admin.php'));
	$dash_rank_days = min(90, IComm_SM_Features::history_days());
	?>
	<h2 style="display:flex;flex-wrap:wrap;align-items:baseline;gap:10px;">
		<span><?php esc_html_e('מילות חיפוש בגוגל (ואיזה עמוד מדורג)', 'icomm-metrix'); ?></span>
		<a class="button button-secondary" href="<?php echo esc_url($kw_ranks_url); ?>" style="font-weight:600;">
			<?php esc_html_e('לכל הדירוגים: מילה + עמוד + מקום בגוגל', 'icomm-metrix'); ?>
		</a>
	</h2>
	<p class="description" style="margin-top:0;">
		<?php esc_html_e('זו רשימה קצרה מהדשבורד. במסך «דירוגים בגוגל» רואים גם שינוי חודשי וסינון לפי תחום.', 'icomm-metrix'); ?>
	</p>
	<?php if ($queries === []) : ?>
		<p><?php esc_html_e('אין נתונים. חברו GSC וסנכרנו.', 'icomm-metrix'); ?></p>
	<?php else : ?>
		<table class="icomm-sm-query-table widefat" dir="rtl" lang="he">
			<thead>
				<tr>
					<th><?php esc_html_e('מילת חיפוש', 'icomm-metrix'); ?></th>
					<th><?php esc_html_e('עמוד באתר', 'icomm-metrix'); ?></th>
					<th><?php esc_html_e('מקום בגוגל', 'icomm-metrix'); ?></th>
					<th><?php esc_html_e('קליקים', 'icomm-metrix'); ?></th>
					<th><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ($queries as $q) : ?>
					<?php
					$q_text = (string) ($q['query'] ?? '');
					$q_page = $q_text !== '' ? IComm_SM_DB::top_page_for_query($q_text, $dash_rank_days) : null;
					$q_page_url = is_array($q_page) ? (string) ($q_page['page_url'] ?? '') : '';
					$q_page_label = $q_page_url !== '' ? IComm_SM_DB::page_label_for_url($q_page_url) : '';
					$q_pos = (float) ($q['position'] ?? 0);
					?>
					<tr>
						<td><strong><?php echo esc_html($q_text); ?></strong></td>
						<td>
							<?php if ($q_page_url !== '') : ?>
								<a href="<?php echo esc_url($q_page_url); ?>" target="_blank" rel="noopener noreferrer">
									<?php echo esc_html($q_page_label !== '' ? $q_page_label : $q_page_url); ?>
								</a>
							<?php else : ?>
								<span class="description"><?php esc_html_e('לא ממופה עדיין', 'icomm-metrix'); ?></span>
							<?php endif; ?>
						</td>
						<td>
							<?php
							$serp = IComm_SM_DB::serp_place_label($q_pos);
							echo is_array($serp)
								? esc_html((string) $serp['label'])
								: '<span class="description">-</span>';
							?>
						</td>
						<td><?php echo esc_html((string) (int) $q['clicks']); ?></td>
						<td><?php echo esc_html((string) (int) $q['impressions']); ?></td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	<?php endif; ?>

	<?php if (!$is_pro) : ?>
		<?php echo IComm_SM_Features::locked_notice_html(__('היסטוריה 90 יום, GA4, דוח PDF ומעקב מילות', 'icomm-metrix')); ?>
	<?php endif; ?>

	<h2><?php esc_html_e('המלצות פעולה', 'icomm-metrix'); ?> <?php echo IComm_SM_Features::pro_badge_html(); ?></h2>
	<?php echo IComm_SM_Features::locked_notice_html(__('המלצות פעולה', 'icomm-metrix')); ?>
	<div class="<?php echo IComm_SM_Features::can_use('recommendations') ? '' : 'icomm-sm-locked-preview'; ?>" style="max-width:920px;">
		<?php if (!IComm_SM_Features::can_use('recommendations')) : ?>
			<p class="description"><?php esc_html_e('ב-PRO: שאילתות עם CTR נמוך, קרוב לטופ 5, ושאילתות בעלייה + הצעה לאיזה עמוד לשפר.', 'icomm-metrix'); ?></p>
		<?php elseif ($reco === []) : ?>
			<p class="description"><?php esc_html_e('אין המלצות חדות כרגע (או שחסרים נתונים).', 'icomm-metrix'); ?></p>
		<?php else : ?>
			<table class="widefat striped" dir="rtl" lang="he">
				<thead>
					<tr>
						<th><?php esc_html_e('סוג', 'icomm-metrix'); ?></th>
						<th><?php esc_html_e('פירוט', 'icomm-metrix'); ?></th>
						<th><?php esc_html_e('איפה לשפר באתר', 'icomm-metrix'); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ($reco as $r) : ?>
						<tr>
							<td><strong><?php echo esc_html((string) ($r['title'] ?? '')); ?></strong></td>
							<td><?php echo esc_html((string) ($r['details'] ?? '')); ?></td>
							<td>
								<?php if (!empty($r['edit_url']) && !empty($r['post_title'])) : ?>
									<a href="<?php echo esc_url((string) $r['edit_url']); ?>"><?php echo esc_html((string) $r['post_title']); ?></a>
								<?php else : ?>
									<span class="description"><?php esc_html_e('לא נמצאה התאמה אוטומטית. מומלץ ליצור עמוד/פוסט חדש בנושא.', 'icomm-metrix'); ?></span>
									<?php if (!empty($r['content_plan'])) : ?>
										<details style="margin-top:8px;">
											<summary><?php esc_html_e('תוכנית תוכן מומלצת (לחץ לפתיחה)', 'icomm-metrix'); ?></summary>
											<textarea readonly rows="12" class="large-text" style="margin-top:8px;direction:rtl;text-align:right;"><?php echo esc_textarea((string) $r['content_plan']); ?></textarea>
											<p class="description" style="margin-top:6px;"><?php esc_html_e('הדבק/י את המבנה בעמוד חדש (Elementor/עורך רגיל) והתאם/י לתוכן שלך.', 'icomm-metrix'); ?></p>
										</details>
									<?php endif; ?>
								<?php endif; ?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
			<p class="description" style="margin-top:8px;">
				<?php esc_html_e('טיפ מהיר: שפרו כותרת/תיאור, הוסיפו פסקת פתיחה ו-FAQ בעמוד המומלץ.', 'icomm-metrix'); ?>
				·
				<a href="<?php echo esc_url(admin_url('admin.php?page=icomm-metrix-opportunities')); ?>"><?php esc_html_e('למסך הזדמנויות SEO המלא', 'icomm-metrix'); ?></a>
			</p>
		<?php endif; ?>
	</div>

	<?php if (IComm_SM_Features::can_use('seo_trend') && $trend_months !== []) : ?>
		<div id="icomm-sm-trend-modal" class="icomm-sm-trend-modal" aria-hidden="true" role="dialog" aria-modal="true" aria-labelledby="icomm-sm-trend-modal-title">
			<div class="icomm-sm-trend-modal__dialog" dir="rtl" lang="he">
				<div class="icomm-sm-trend-modal__head">
					<h2 id="icomm-sm-trend-modal-title"><?php esc_html_e('גרף SEO מפורט', 'icomm-metrix'); ?></h2>
					<button type="button" class="icomm-sm-trend-modal__close" data-icomm-sm-close-trend-chart aria-label="<?php esc_attr_e('סגור', 'icomm-metrix'); ?>">×</button>
				</div>
				<div class="icomm-sm-trend-modal__toolbar">
					<div class="icomm-sm-trend-seg" role="group" aria-label="<?php esc_attr_e('סוג גרף', 'icomm-metrix'); ?>">
						<span class="icomm-sm-trend-seg__label"><?php esc_html_e('תצוגה', 'icomm-metrix'); ?></span>
						<button type="button" class="is-active" data-icomm-sm-chart-type="line" aria-pressed="true"><?php esc_html_e('קו', 'icomm-metrix'); ?></button>
						<button type="button" data-icomm-sm-chart-type="bars" aria-pressed="false"><?php esc_html_e('עמודות', 'icomm-metrix'); ?></button>
						<button type="button" data-icomm-sm-chart-type="candles" aria-pressed="false"><?php esc_html_e('נרות', 'icomm-metrix'); ?></button>
					</div>
					<div class="icomm-sm-trend-seg" role="group" aria-label="<?php esc_attr_e('מדד', 'icomm-metrix'); ?>">
						<span class="icomm-sm-trend-seg__label"><?php esc_html_e('מדד', 'icomm-metrix'); ?></span>
						<button type="button" class="is-active" data-icomm-sm-chart-metric="both" aria-pressed="true"><?php esc_html_e('שניהם', 'icomm-metrix'); ?></button>
						<button type="button" data-icomm-sm-chart-metric="clicks" aria-pressed="false"><?php esc_html_e('קליקים', 'icomm-metrix'); ?></button>
						<button type="button" data-icomm-sm-chart-metric="impressions" aria-pressed="false"><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></button>
					</div>
					<div class="icomm-sm-trend-seg" role="group" aria-label="<?php esc_attr_e('טווח', 'icomm-metrix'); ?>">
						<span class="icomm-sm-trend-seg__label"><?php esc_html_e('טווח', 'icomm-metrix'); ?></span>
						<button type="button" data-icomm-sm-chart-range="6" aria-pressed="false"><?php esc_html_e('6 חודשים', 'icomm-metrix'); ?></button>
						<button type="button" data-icomm-sm-chart-range="12" aria-pressed="false"><?php esc_html_e('12 חודשים', 'icomm-metrix'); ?></button>
						<button type="button" class="is-active" data-icomm-sm-chart-range="all" aria-pressed="true"><?php esc_html_e('הכל', 'icomm-metrix'); ?></button>
					</div>
				</div>
				<p id="icomm-sm-trend-chart-hint" class="description icomm-sm-trend-modal__hint" hidden></p>
				<p id="icomm-sm-trend-chart-error" class="notice notice-error inline" hidden></p>
				<div class="icomm-sm-trend-modal__canvas-wrap">
					<canvas id="icomm-sm-trend-canvas" aria-label="<?php esc_attr_e('גרף מגמת SEO', 'icomm-metrix'); ?>"></canvas>
				</div>
			</div>
		</div>
	<?php endif; ?>
</div>
