<?php
if ( ! defined( 'ABSPATH' ) ) exit;

if ( ! function_exists( 'nros_clear_task_transients' ) ) {
	/**
	 * Drop sidebar task-list transients when alerts change (avoid stale metabox data).
	 */
	function nros_clear_task_transients() {
		if ( function_exists( 'newsai_delete_transients_by_prefix' ) ) {
			newsai_delete_transients_by_prefix( 'nros_tasks_user_' );
		}
		if ( function_exists( 'newsai_invalidate_task_due_metrics_cache' ) ) {
			newsai_invalidate_task_due_metrics_cache();
		}
	}
}

if ( ! function_exists( 'newsai_allowed_admin_badge_html' ) ) {
	/**
	 * Allowlist for small admin badge HTML fragments.
	 *
	 * @return array<string, array<string, bool>>
	 */
	function newsai_allowed_admin_badge_html() {
		return [
			'span' => [
				'class'       => true,
				'title'       => true,
				'aria-hidden' => true,
			],
		];
	}
}

if ( ! function_exists( 'newsai_inbox_task_status_badge_html' ) ) {
	/**
	 * Editorial inbox task status pill (escaped text, CSS classes only).
	 *
	 * @param string $status   Task status slug.
	 * @param int    $diff_d   Days until/since due.
	 * @param int    $lead_days Lead window from alert row.
	 * @return string HTML for wp_kses().
	 */
	function newsai_inbox_task_status_badge_html( $status, $diff_d, $lead_days ) {
		$status    = (string) $status;
		$diff_d    = (int) $diff_d;
		$lead_days = (int) $lead_days;

		if ( $status === 'done' ) {
			$class = 'nros-inbox-badge nros-inbox-badge--done';
			$text  = '✓ ' . __( 'Done', 'newsroom-ai-assistant' );
		} elseif ( $diff_d < 0 ) {
			$class = 'nros-inbox-badge nros-inbox-badge--overdue';
			$text  = __( 'Overdue', 'newsroom-ai-assistant' );
		} elseif ( $diff_d <= $lead_days ) {
			$class = 'nros-inbox-badge nros-inbox-badge--due-soon';
			$text  = __( 'Due soon', 'newsroom-ai-assistant' );
		} else {
			$class = 'nros-inbox-badge nros-inbox-badge--scheduled';
			$text  = __( 'Scheduled', 'newsroom-ai-assistant' );
		}

		return '<span class="' . esc_attr( $class ) . '">' . esc_html( $text ) . '</span>';
	}
}

if ( ! function_exists( 'nros_register_admin_menu' ) ) {
function nros_register_admin_menu() {
    $svg_icon = 'data:image/svg+xml;base64,' . base64_encode('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5" fill="currentColor"></circle><circle cx="15.5" cy="8.5" r="1.5" fill="currentColor"></circle><path d="M9 15c1 1 2 1.5 3 1.5s2-.5 3-1.5"></path></svg>');

    // Editor-in-chief surface — full dashboard, tasks, settings, AI Assist, Indexing, etc.
    // Reserved for users that can edit other people's posts (Editor / Administrator).
    // Authors and contributors get the slimmer "My Inbox" submenu instead.
    $chief_cap   = 'edit_others_posts';
    $author_cap  = 'edit_posts';
    $is_chief    = current_user_can( $chief_cap );

    $chief_label = 'Editorial Control';
    $author_label = 'My Inbox';
    if ( function_exists( 'newsai_task_get_user_unread_total' ) ) {
        $unread = (int) newsai_task_get_user_unread_total();
        if ( $unread > 0 ) {
            $bubble = ' <span class="awaiting-mod menu-counter"><span class="pending-count">' . esc_html( $unread > 99 ? '99+' : (string) $unread ) . '</span></span>';
            if ( $is_chief ) {
                $chief_label .= $bubble;
            } else {
                $author_label .= $bubble;
            }
        }
    }

    if ( $is_chief ) {
        // Chiefs get the full "Editorial Control" dashboard as their top-level entry.
        add_menu_page( 'Newsroom OS', $chief_label, $chief_cap, 'newsai-settings', 'newsai_render_admin', $svg_icon, 25 );
        // …plus an explicit "My Inbox" submenu so they can also operate in writer-mode
        // (their own assignments, threads, focus-score card). Breaks the strict mental
        // model on purpose: chiefs that also write articles need a personal lane.
        add_submenu_page(
            'newsai-settings',
            $author_label,
            '📥 ' . $author_label,
            $author_cap,
            'newsai-inbox',
            'newsai_render_author_inbox'
        );
    } else {
        // Author flow: top-level menu points to the dedicated inbox page so authors never
        // see settings, prompts, indexing, AI keys, etc.
        add_menu_page( 'Newsroom OS', $author_label, $author_cap, 'newsai-inbox', 'newsai_render_author_inbox', $svg_icon, 25 );
    }
}
}
add_action( 'admin_menu', 'nros_register_admin_menu', 9 );

if ( ! function_exists( 'newsai_admin_screen_hooks' ) ) {
	/**
	 * @return list<string>
	 */
	function newsai_admin_screen_hooks() {
		return [
			'toplevel_page_newsai-settings',
			'toplevel_page_newsai-inbox',
			'newsai-settings_page_newsai-inbox',
		];
	}
}

if ( ! function_exists( 'newsai_admin_set_page_title' ) ) {
	/**
	 * Avoid null $title → strip_tags() deprecation in admin-header.php on plugin tabs.
	 */
	function newsai_admin_set_page_title() {
		global $title;
		$tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'alerts';
		$labels = [
			'alerts'   => __( 'Dashboard', 'newsroom-ai-assistant' ),
			'insights' => __( 'Chief Insights', 'newsroom-ai-assistant' ),
			'perf'     => __( 'Author Performance', 'newsroom-ai-assistant' ),
			'settings' => __( 'Settings', 'newsroom-ai-assistant' ),
			'pro'      => __( 'PRO', 'newsroom-ai-assistant' ),
		];
		$page_title = $labels[ $tab ] ?? __( 'Newsroom OS', 'newsroom-ai-assistant' );
		$title      = $page_title;
	}
}

foreach ( newsai_admin_screen_hooks() as $newsai_admin_hook ) {
	add_action( 'load-' . $newsai_admin_hook, 'newsai_admin_set_page_title' );
}

if ( ! function_exists( 'newsai_render_classic_admin_sidebar' ) ) {
	/**
	 * Vertical sidebar navigation for classic Newsroom OS admin (2.7 premium shell).
	 *
	 * @param string $current_tab Active tab key.
	 * @return void
	 */
	function newsai_render_classic_admin_sidebar( $current_tab ) {
		$base  = admin_url( 'admin.php?page=newsai-settings' );
		$items = [
			[
				'tab'   => 'alerts',
				'icon'  => '📊',
				'label' => __( 'Dashboard', 'newsroom-ai-assistant' ),
			],
			[
				'tab'   => 'insights',
				'icon'  => '🧭',
				'label' => __( 'Chief Insights', 'newsroom-ai-assistant' ),
			],
		];
		if ( function_exists( 'newsai_is_pro' ) && newsai_is_pro() && current_user_can( 'edit_others_posts' ) ) {
			$items[] = [
				'tab'   => 'perf',
				'icon'  => '📈',
				'label' => __( 'Author Performance', 'newsroom-ai-assistant' ),
			];
		}
		$items[] = [
			'tab'   => 'settings',
			'icon'  => '⚙️',
			'label' => __( 'Settings', 'newsroom-ai-assistant' ),
		];

		$is_pro = function_exists( 'newsai_is_pro' ) && newsai_is_pro();
		?>
		<aside class="nros-classic-sidebar" aria-label="<?php echo esc_attr__( 'Newsroom OS navigation', 'newsroom-ai-assistant' ); ?>">
			<div class="nros-classic-sidebar__brand">
				<span class="nros-classic-sidebar__logo" aria-hidden="true">N</span>
				<span class="nros-classic-sidebar__name"><?php echo esc_html__( 'Newsroom OS', 'newsroom-ai-assistant' ); ?></span>
			</div>
			<nav class="nros-classic-sidebar__nav">
				<?php foreach ( $items as $item ) : ?>
					<?php
					$active = ( $current_tab === $item['tab'] );
					$url    = add_query_arg( 'tab', $item['tab'], $base );
					?>
					<a href="<?php echo esc_url( $url ); ?>" class="nros-classic-sidebar__link<?php echo $active ? ' is-active' : ''; ?>">
						<span class="nros-classic-sidebar__icon" aria-hidden="true"><?php echo esc_html( $item['icon'] ); ?></span>
						<span class="nros-classic-sidebar__label"><?php echo esc_html( $item['label'] ); ?></span>
					</a>
				<?php endforeach; ?>
			</nav>
			<div class="nros-classic-sidebar__foot">
				<a href="<?php echo esc_url( add_query_arg( 'tab', 'pro', $base ) ); ?>" class="nros-classic-sidebar__pro<?php echo $current_tab === 'pro' ? ' is-active' : ''; ?>">
					<span aria-hidden="true">⚡</span>
					<?php echo esc_html__( 'PRO Features', 'newsroom-ai-assistant' ); ?>
					<?php if ( $is_pro ) : ?>
						<span class="nros-classic-sidebar__pro-badge"><?php echo esc_html__( 'Active', 'newsroom-ai-assistant' ); ?></span>
					<?php endif; ?>
				</a>
				<span class="nros-classic-sidebar__ver">v<?php echo esc_html( NEWSAI_VERSION ); ?></span>
			</div>
		</aside>
		<?php
	}
}

if ( ! function_exists( 'newsai_render_classic_page_head' ) ) {
	/**
	 * Page title row inside classic main content.
	 *
	 * @param string $title    Heading.
	 * @param string $subtitle Optional description.
	 * @param string $actions  Optional raw HTML for header actions.
	 * @return void
	 */
	function newsai_render_classic_page_head( $title, $subtitle = '', $actions = '' ) {
		echo '<header class="nros-classic-page-head">';
		echo '<div class="nros-classic-page-head__main">';
		echo '<h2 class="nros-classic-page-head__title">' . esc_html( $title ) . '</h2>';
		if ( $subtitle !== '' ) {
			echo '<p class="nros-classic-page-head__sub">' . esc_html( $subtitle ) . '</p>';
		}
		echo '</div>';
		if ( $actions !== '' ) {
			echo '<div class="nros-classic-page-head__actions">' . $actions . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}
		echo '</header>';
	}
}

/**
 * Author-only "My Inbox" page. Renders the user's assigned tasks plus their discussion
 * threads — no settings, no AI configuration, no indexing. Capability is enforced via the
 * `edit_posts` requirement on the menu registration; chiefs (`edit_others_posts`) are routed
 * to the full dashboard instead.
 */
function newsai_render_author_inbox() {
    if ( ! current_user_can( 'edit_posts' ) ) {
        wp_die( esc_html__( 'You do not have permission to access this page.', 'newsroom-ai-assistant' ) );
    }
    // Chiefs are now also allowed to land on the inbox via the explicit submenu so they
    // can operate as writers on their own assignments. The chief dashboard remains the
    // primary surface — this is the personal-lane companion.
    global $wpdb;
    $table   = $wpdb->prefix . 'newsai_alerts';
    $lang    = function_exists( 'newsai_get_ui_lang' ) ? newsai_get_ui_lang() : 'en';
    $user_id = (int) get_current_user_id();
    $is_pro  = function_exists( 'newsai_is_pro' ) && newsai_is_pro();

    // Authors see personal assignments plus unassigned "pool" tasks open to the whole desk.
    $tasks = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT id, title, day, month, year, lead_days, status, notes, target_keyword, ref_link
             FROM {$table}
             WHERE author_id = %d OR author_id = 0
             ORDER BY (status = 'done') ASC, year ASC, month ASC, day ASC
             LIMIT 100",
            $user_id
        )
    );

    $threads_by_alert = [];
    $total_unread     = 0;
    if ( function_exists( 'newsai_task_get_user_threads_with_unread' ) ) {
        $rows = newsai_task_get_user_threads_with_unread( $user_id, 100 );
        foreach ( $rows as $r ) {
            $threads_by_alert[ (int) $r['alert_id'] ] = $r;
            $total_unread += (int) $r['unread'];
        }
    }
    $messaging_on = function_exists( 'newsai_task_messaging_active' ) && newsai_task_messaging_active();
    ?>
    <div class="wrap nros-inbox-wrap">
        <h1 class="nros-inbox-header">
            📥 <?php echo esc_html( __( 'My Inbox', 'newsroom-ai-assistant' ) ); ?>
            <?php if ( $total_unread > 0 ) : ?>
                <span class="nros-inbox-header__badge"><?php echo esc_html( $total_unread > 99 ? '99+' : (string) $total_unread ); ?></span>
            <?php endif; ?>
        </h1>
        <p class="nros-inbox-intro">
            <?php echo esc_html( __( 'Stories assigned to you by the editorial team, plus the messages around them.', 'newsroom-ai-assistant' ) ); ?>
        </p>

        <?php
        // Personal performance card (all plans). Team-wide Author Performance tab stays Pro/chief-only.
        if ( function_exists( 'newsai_pro_author_performance' ) ) {
            $me = newsai_pro_author_performance( $user_id, 30 );
            if ( ! empty( $me ) ) :
                $score_avg = (int) $me['score']['avg'];
                $score_col = $score_avg >= 85 ? 'nros-inbox-val--good' : ( $score_avg >= 60 ? 'nros-inbox-val--warn' : ( $score_avg > 0 ? 'nros-inbox-val--bad' : 'nros-inbox-val--muted' ) );
                $gsc_disc   = isset( $me['discover'] ) && is_array( $me['discover'] ) ? $me['discover'] : null;
                $gsc_gnews  = isset( $me['gnews'] ) && is_array( $me['gnews'] ) ? $me['gnews'] : null;
                $gsc_disc_clicks = $gsc_disc ? (int) ( $gsc_disc['clicks'] ?? 0 ) : 0;
                $gsc_gn_clicks   = $gsc_gnews ? (int) ( $gsc_gnews['clicks'] ?? 0 ) : 0;
                $gsc_on          = $is_pro && function_exists( 'newsai_gsc_data_available' ) && newsai_gsc_data_available();
                ?>
                <div class="nros-card nros-inbox-perf">
                    <h2 class="nros-inbox-perf__title">📈 <?php echo esc_html( __( 'My performance (30 days)', 'newsroom-ai-assistant' ) ); ?></h2>
                    <div class="nros-inbox-perf__grid">
                        <div class="nros-inbox-stat">
                            <div class="nros-inbox-stat__label"><?php echo esc_html( __( 'Posts', 'newsroom-ai-assistant' ) ); ?></div>
                            <div class="nros-inbox-stat__val"><?php echo (int) $me['posts']['recent']; ?></div>
                            <div class="nros-inbox-stat__sub"><?php echo esc_html( sprintf( __( 'Prior: %d', 'newsroom-ai-assistant' ), (int) $me['posts']['prior'] ) ); ?></div>
                        </div>
                        <div class="nros-inbox-stat">
                            <div class="nros-inbox-stat__label"><?php echo esc_html( __( 'Tasks done', 'newsroom-ai-assistant' ) ); ?></div>
                            <div class="nros-inbox-stat__val"><?php echo (int) $me['tasks']['done']; ?></div>
                            <div class="nros-inbox-stat__sub"><?php echo esc_html( sprintf( __( 'Open: %d', 'newsroom-ai-assistant' ), (int) $me['tasks']['open'] ) . ( (int) $me['tasks']['overdue'] > 0 ? ' ' . sprintf( __( '(overdue %d)', 'newsroom-ai-assistant' ), (int) $me['tasks']['overdue'] ) : '' ) ); ?></div>
                        </div>
                        <div class="nros-inbox-stat">
                            <div class="nros-inbox-stat__label"><?php echo esc_html( __( 'Avg Focus Score', 'newsroom-ai-assistant' ) ); ?></div>
                            <div class="nros-inbox-stat__val <?php echo esc_attr( $score_col ); ?>"><?php echo $score_avg > 0 ? esc_html( $score_avg . '%' ) : esc_html( '—' ); ?></div>
                            <div class="nros-inbox-stat__sub"><?php echo esc_html( sprintf( __( 'Sample: %d posts', 'newsroom-ai-assistant' ), (int) $me['score']['sample'] ) ); ?></div>
                        </div>
                        <div class="nros-inbox-stat">
                            <?php
                            $disc_avg = isset( $me['discover_readiness']['avg'] ) ? (int) $me['discover_readiness']['avg'] : 0;
                            $disc_col = $disc_avg >= 80 ? 'nros-inbox-val--good' : ( $disc_avg >= 60 ? 'nros-inbox-val--warn' : ( $disc_avg > 0 ? 'nros-inbox-val--bad' : 'nros-inbox-val--muted' ) );
                            ?>
                            <div class="nros-inbox-stat__label"><?php echo esc_html( __( 'Avg Discover', 'newsroom-ai-assistant' ) ); ?></div>
                            <div class="nros-inbox-stat__val <?php echo esc_attr( $disc_col ); ?>"><?php echo $disc_avg > 0 ? esc_html( $disc_avg . '%' ) : esc_html( '—' ); ?></div>
                            <div class="nros-inbox-stat__sub"><?php echo esc_html( sprintf( __( 'Sample: %d posts', 'newsroom-ai-assistant' ), (int) ( $me['discover_readiness']['sample'] ?? 0 ) ) ); ?></div>
                        </div>
                        <?php if ( $gsc_on && $gsc_disc && ( $gsc_disc_clicks > 0 || ! empty( $gsc_disc['impressions'] ) ) ) : ?>
                        <div class="nros-inbox-stat nros-inbox-stat--gsc">
                            <div class="nros-inbox-stat__label"><?php echo esc_html( __( 'Discover clicks (GSC)', 'newsroom-ai-assistant' ) ); ?></div>
                            <div class="nros-inbox-stat__val nros-inbox-val--good"><?php echo esc_html( number_format_i18n( $gsc_disc_clicks ) ); ?></div>
                            <?php if ( ! empty( $gsc_disc['impressions'] ) ) : ?>
                                <div class="nros-inbox-stat__sub"><?php echo esc_html( sprintf( __( 'Impressions: %s', 'newsroom-ai-assistant' ), number_format_i18n( (int) $gsc_disc['impressions'] ) ) ); ?></div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                        <?php if ( $gsc_on && $gsc_gnews && ( $gsc_gn_clicks > 0 || ! empty( $gsc_gnews['impressions'] ) ) ) : ?>
                        <div class="nros-inbox-stat nros-inbox-stat--gsc">
                            <div class="nros-inbox-stat__label"><?php echo esc_html( __( 'Google News clicks', 'newsroom-ai-assistant' ) ); ?></div>
                            <div class="nros-inbox-stat__val nros-inbox-val--good"><?php echo esc_html( number_format_i18n( $gsc_gn_clicks ) ); ?></div>
                            <?php if ( ! empty( $gsc_gnews['impressions'] ) ) : ?>
                                <div class="nros-inbox-stat__sub"><?php echo esc_html( sprintf( __( 'Impressions: %s', 'newsroom-ai-assistant' ), number_format_i18n( (int) $gsc_gnews['impressions'] ) ) ); ?></div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <p class="nros-inbox-perf__hint">
                        <?php echo esc_html( __( 'Discover % = editorial readiness. GSC clicks = real Google traffic (Pro, when sync is enabled).', 'newsroom-ai-assistant' ) ); ?>
                    </p>
                    <?php if ( ! empty( $me['categories'] ) ) : ?>
                        <div class="nros-inbox-cats">
                            <span class="nros-inbox-cats__label"><?php echo esc_html( __( 'You cover:', 'newsroom-ai-assistant' ) ); ?></span>
                            <?php foreach ( $me['categories'] as $cat ) : ?>
                                <span class="nros-inbox-cats__pill"><?php echo esc_html( $cat['name'] . ' · ' . (int) $cat['count'] ); ?></span>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <p class="nros-inbox-perf__hint">
                        <?php echo esc_html( __( '💡 Your Focus Score is saved while you edit and locked when the article goes live.', 'newsroom-ai-assistant' ) ); ?>
                    </p>
                    <?php if ( ! $is_pro && function_exists( 'newsai_pro_promo_link' ) ) : ?>
                        <p class="nros-inbox-perf__hint">
                            <?php
                            echo wp_kses(
                                sprintf(
                                    /* translators: %s: Pro upgrade URL */
                                    __( 'Pro unlocks team Author Performance and desk-wide analytics. <a href="%s" target="_blank" rel="noopener">Upgrade →</a>', 'newsroom-ai-assistant' ),
                                    esc_url( newsai_pro_promo_link( 'inbox-performance' ) )
                                ),
                                [
                                    'a' => [
                                        'href'   => [],
                                        'target' => [],
                                        'rel'    => [],
                                    ],
                                ]
                            );
                            ?>
                        </p>
                    <?php endif; ?>
                </div>
                <?php
            endif;
        }
        ?>

        <?php if ( $messaging_on && ! empty( $threads_by_alert ) ) :
            $threads_ordered = array_values( $threads_by_alert );
            usort( $threads_ordered, static function ( $a, $b ) {
                if ( (int) $a['unread'] !== (int) $b['unread'] ) {
                    return (int) $b['unread'] <=> (int) $a['unread'];
                }
                return strcmp( (string) $b['last_ts'], (string) $a['last_ts'] );
            } );
            $threads_with_activity = array_values( array_filter( $threads_ordered, static function ( $t ) { return ! empty( $t['last_ts'] ); } ) );
            if ( ! empty( $threads_with_activity ) ) : ?>
            <div class="nros-card nros-inbox-discussions">
                <h2 class="nros-inbox-section-title">💬 <?php echo esc_html( __( 'Recent discussions', 'newsroom-ai-assistant' ) ); ?></h2>
                <ul class="nros-inbox-thread-list">
                    <?php
                    $shown = 0;
                    foreach ( $threads_with_activity as $t ) {
                        if ( $shown >= 8 ) { break; }
                        $shown++;
                        $unread = (int) $t['unread'];
                        $last_human = '';
                        if ( ! empty( $t['last_ts'] ) ) {
                            $ts = strtotime( $t['last_ts'] . ' UTC' );
                            if ( $ts > 0 ) {
                                $last_human = human_time_diff( $ts, current_time( 'timestamp' ) ) . ' ' . ( __( 'ago', 'newsroom-ai-assistant' ) );
                            }
                        }
                        $link_class = 'nros-inbox-thread__link' . ( $unread > 0 ? ' nros-inbox-thread__link--unread' : '' );
                        ?>
                        <li class="nros-inbox-thread">
                            <a href="#" class="newsai-task-thread-open <?php echo esc_attr( $link_class ); ?>" data-alert-id="<?php echo (int) $t['alert_id']; ?>" data-alert-title="<?php echo esc_attr( $t['title'] ); ?>">
                                <span class="nros-inbox-thread__body">
                                    <strong class="nros-inbox-thread__title"><?php echo esc_html( $t['title'] ); ?></strong>
                                    <?php if ( $last_human !== '' ) : ?>
                                        <small class="nros-inbox-thread__time">🕒 <?php echo esc_html( $last_human ); ?></small>
                                    <?php endif; ?>
                                </span>
                                <?php if ( $unread > 0 ) : ?>
                                    <span class="nros-inbox-thread__badge"><?php echo esc_html( $unread > 99 ? '99+' : (string) $unread ); ?></span>
                                <?php else : ?>
                                    <span class="nros-inbox-thread__read" aria-hidden="true">✓</span>
                                <?php endif; ?>
                            </a>
                        </li>
                        <?php
                    }
                    ?>
                </ul>
            </div>
        <?php endif; endif; ?>

        <div class="nros-card nros-inbox-assignments">
            <h2 class="nros-inbox-section-title">📋 <?php echo esc_html( __( 'My assignments', 'newsroom-ai-assistant' ) ); ?></h2>
            <?php if ( empty( $tasks ) ) : ?>
                <p class="nros-inbox-empty"><?php echo esc_html( __( 'You have no active assignments right now.', 'newsroom-ai-assistant' ) ); ?></p>
            <?php else : ?>
                <table class="wp-list-table widefat striped nros-inbox-table">
                    <thead>
                        <tr>
                            <th><?php echo esc_html( __( 'Story', 'newsroom-ai-assistant' ) ); ?></th>
                            <th class="nros-inbox-table__col-date"><?php echo esc_html( __( 'Date', 'newsroom-ai-assistant' ) ); ?></th>
                            <th class="nros-inbox-table__col-status"><?php echo esc_html( __( 'Status', 'newsroom-ai-assistant' ) ); ?></th>
                            <th class="nros-inbox-table__col-actions"><?php echo esc_html( __( 'Actions', 'newsroom-ai-assistant' ) ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $now_ts = strtotime( gmdate( 'Y-m-d' ) );
                        foreach ( $tasks as $r ) :
                            $t_year  = ( (int) $r->year > 0 ) ? (int) $r->year : (int) gmdate( 'Y' );
                            $t_month = ( (int) $r->month > 0 ) ? (int) $r->month : (int) gmdate( 'm' );
                            $task_ts = strtotime( sprintf( '%04d-%02d-%02d', $t_year, $t_month, (int) $r->day ) );
                            $diff_d  = $task_ts ? (int) round( ( $task_ts - $now_ts ) / 86400 ) : 0;
                            $status  = isset( $r->status ) ? (string) $r->status : 'pending';
                            $unread  = isset( $threads_by_alert[ (int) $r->id ] ) ? (int) $threads_by_alert[ (int) $r->id ]['unread'] : 0;
                            $badge   = newsai_inbox_task_status_badge_html( $status, $diff_d, (int) $r->lead_days );
                            $done_url = wp_nonce_url(
                                add_query_arg(
                                    [ 'page' => 'newsai-inbox', 'newsai_inbox_done' => (int) $r->id ],
                                    admin_url( 'admin.php' )
                                ),
                                'newsai_inbox_done_' . (int) $r->id
                            );
                            ?>
                            <tr data-alert-id="<?php echo (int) $r->id; ?>" data-alert-title="<?php echo esc_attr( $r->title ); ?>">
                                <td>
                                    <strong><?php echo esc_html( $r->title ); ?></strong>
                                    <?php if ( ! empty( $r->target_keyword ) ) : ?>
                                        <br><span class="nros-inbox-kw">🔑 <?php echo esc_html( $r->target_keyword ); ?></span>
                                    <?php endif; ?>
                                    <?php if ( ! empty( $r->ref_link ) ) : ?>
                                        <br><a class="nros-inbox-ref" href="<?php echo esc_url( $r->ref_link ); ?>" target="_blank" rel="noopener">🔗 <?php echo esc_html( __( 'Reference', 'newsroom-ai-assistant' ) ); ?></a>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo esc_html( sprintf( '%02d/%02d', (int) $r->day, (int) $r->month ) ); ?></td>
                                <td><?php echo wp_kses( $badge, newsai_allowed_admin_badge_html() ); ?></td>
                                <td>
                                    <?php if ( $messaging_on ) : ?>
                                        <a href="#" class="newsai-task-thread-open button button-small nros-inbox-msg-btn" data-alert-id="<?php echo (int) $r->id; ?>" data-alert-title="<?php echo esc_attr( $r->title ); ?>">
                                            💬
                                            <?php if ( $unread > 0 ) : ?>
                                                <span class="nros-inbox-msg-btn__badge"><?php echo esc_html( $unread > 99 ? '99+' : (string) $unread ); ?></span>
                                            <?php endif; ?>
                                        </a>
                                    <?php endif; ?>
                                    <?php if ( $status !== 'done' ) : ?>
                                        <a href="<?php echo esc_url( $done_url ); ?>" class="button button-small" onclick="return confirm('<?php echo esc_js( __( 'Mark as done?', 'newsroom-ai-assistant' ) ); ?>');">✓</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <?php if ( ! $is_pro ) : ?>
            <p class="nros-inbox-footnote">
                <?php echo esc_html( __( 'Note: two-way messaging and email notifications activate when the site has a Pro license.', 'newsroom-ai-assistant' ) ); ?>
            </p>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * Handle "mark as done" from the author inbox (GET with nonce).
 */
add_action( 'admin_init', function () {
    if ( ! isset( $_GET['page'] ) || $_GET['page'] !== 'newsai-inbox' ) { return; }
    if ( ! isset( $_GET['newsai_inbox_done'] ) ) { return; }
    $alert_id = (int) $_GET['newsai_inbox_done'];
    if ( $alert_id < 1 ) { return; }
    if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'newsai_inbox_done_' . $alert_id ) ) { return; }
    if ( ! function_exists( 'newsai_task_can_access' ) || ! newsai_task_can_access( $alert_id ) ) {
        return;
    }
    global $wpdb;
    $table = $wpdb->prefix . 'newsai_alerts';
    $wpdb->update( $table, [ 'status' => 'done' ], [ 'id' => $alert_id ] );
    if ( function_exists( 'nros_clear_task_transients' ) ) { nros_clear_task_transients(); }
    do_action( 'newsai_task_completed', $alert_id, (int) get_current_user_id() );
    wp_safe_redirect( admin_url( 'admin.php?page=newsai-inbox&inbox_done=1' ) );
    exit;
});

if ( ! function_exists( 'newsai_insights_trend_badge_html' ) ) {
	/**
	 * Trend arrow + label for Chief Insights article tables.
	 *
	 * @param array{delta_clicks?:int,prev_clicks?:int,clicks?:int,trend?:string} $row Row data.
	 * @return string Safe HTML.
	 */
	function newsai_insights_trend_badge_html( $row ) {
		$trend = isset( $row['trend'] ) ? (string) $row['trend'] : 'flat';
		$delta = isset( $row['delta_clicks'] ) ? (int) $row['delta_clicks'] : 0;
		$prev  = isset( $row['prev_clicks'] ) ? (int) $row['prev_clicks'] : 0;
		$cur   = isset( $row['clicks'] ) ? (int) $row['clicks'] : 0;

		if ( ! in_array( $trend, [ 'up', 'down', 'flat', 'new' ], true ) && function_exists( 'newsai_gsc_insights_trend_key' ) ) {
			$trend = newsai_gsc_insights_trend_key( $delta, $prev, $cur );
		}

		$class = 'nros-trend nros-trend--' . $trend;
		$icon  = '→';
		$label = __( 'Stable', 'newsroom-ai-assistant' );

		if ( 'new' === $trend ) {
			$icon  = '▲';
			$label = __( 'New traffic', 'newsroom-ai-assistant' );
		} elseif ( 'up' === $trend ) {
			$icon  = '▲';
			/* translators: %s: click delta (signed number) */
			$label = sprintf( __( 'Up %s clicks', 'newsroom-ai-assistant' ), number_format_i18n( $delta ) );
			if ( $prev > 0 ) {
				$pct = (int) round( ( $delta / $prev ) * 100 );
				$label .= ' (' . sprintf(
					/* translators: %s: percent change */
					__( '+%s%%', 'newsroom-ai-assistant' ),
					number_format_i18n( $pct )
				) . ')';
			}
		} elseif ( 'down' === $trend ) {
			$icon  = '▼';
			/* translators: %s: click delta (absolute) */
			$label = sprintf( __( 'Down %s clicks', 'newsroom-ai-assistant' ), number_format_i18n( abs( $delta ) ) );
			if ( $prev > 0 ) {
				$pct = (int) round( ( abs( $delta ) / $prev ) * 100 );
				$label .= ' (' . sprintf(
					/* translators: %s: percent change */
					__( '-%s%%', 'newsroom-ai-assistant' ),
					number_format_i18n( $pct )
				) . ')';
			}
		}

		return '<span class="' . esc_attr( $class ) . '" title="' . esc_attr( $label ) . '"><span class="nros-trend__icon" aria-hidden="true">' . esc_html( $icon ) . '</span><span class="nros-trend__label">' . esc_html( $label ) . '</span></span>';
	}
}

if ( ! function_exists( 'newsai_render_insights_articles_table' ) ) {
	/**
	 * Reusable article traffic table for Chief Insights.
	 *
	 * @param list<array<string,mixed>> $rows Article rows.
	 * @param bool                      $with_trend Show trend column.
	 * @return void
	 */
	function newsai_render_insights_articles_table( $rows, $with_trend = true ) {
		?>
		<table class="wp-list-table widefat striped nros-insights-articles-table">
			<thead>
				<tr>
					<th><?php echo esc_html__( 'Article', 'newsroom-ai-assistant' ); ?></th>
					<?php if ( $with_trend ) : ?>
						<th class="nros-insights-col-trend"><?php echo esc_html__( 'Trend', 'newsroom-ai-assistant' ); ?></th>
					<?php endif; ?>
					<th><?php echo esc_html__( 'Clicks', 'newsroom-ai-assistant' ); ?></th>
					<th><?php echo esc_html__( 'Impressions', 'newsroom-ai-assistant' ); ?></th>
				</tr>
			</thead>
			<tbody>
			<?php if ( empty( $rows ) ) : ?>
				<tr><td colspan="<?php echo $with_trend ? 4 : 3; ?>"><?php echo esc_html__( 'No traffic data yet in this window.', 'newsroom-ai-assistant' ); ?></td></tr>
			<?php else : ?>
				<?php foreach ( $rows as $row ) : ?>
					<tr>
						<td>
							<?php
							$edit = ! empty( $row['post_id'] ) ? get_edit_post_link( (int) $row['post_id'], 'raw' ) : '';
							if ( $edit ) :
								?>
								<a href="<?php echo esc_url( $edit ); ?>"><?php echo esc_html( (string) ( $row['title'] ?? '' ) ); ?></a>
							<?php else : ?>
								<?php echo esc_html( (string) ( $row['title'] ?? '' ) ); ?>
							<?php endif; ?>
						</td>
						<?php if ( $with_trend ) : ?>
							<td class="nros-insights-col-trend"><?php echo wp_kses( newsai_insights_trend_badge_html( $row ), newsai_allowed_admin_badge_html() ); ?></td>
						<?php endif; ?>
						<td><strong><?php echo esc_html( number_format_i18n( (int) ( $row['clicks'] ?? 0 ) ) ); ?></strong></td>
						<td><?php echo esc_html( number_format_i18n( (int) ( $row['impressions'] ?? 0 ) ) ); ?></td>
					</tr>
				<?php endforeach; ?>
			<?php endif; ?>
			</tbody>
		</table>
		<?php
	}
}

if ( ! function_exists( 'newsai_render_chief_insights_panel' ) ) {
	/**
	 * Chief-level KPI dashboard (PRO full data, Free demo mode).
	 *
	 * @param int  $days  Window size in days.
	 * @param bool $is_pro Whether PRO is active.
	 * @return void
	 */
	function newsai_render_chief_insights_panel( $days = 30, $is_pro = false ) {
		$days = max( 7, min( 90, (int) $days ) );
		if ( isset( $_GET['newsai_refresh_insights'] ) && current_user_can( 'edit_others_posts' ) ) {
			if ( function_exists( 'newsai_chief_insights_flush_cache' ) ) {
				newsai_chief_insights_flush_cache();
			}
		}
		$gsc_channel = isset( $_GET['gsc_channel'] ) && function_exists( 'newsai_chief_gsc_resolve_channel' )
			? newsai_chief_gsc_resolve_channel( (string) wp_unslash( $_GET['gsc_channel'] ) )
			: 'all';

		$insights_data = function_exists( 'newsai_chief_insights_get_cached_data' )
			? newsai_chief_insights_get_cached_data( $days, $is_pro )
			: ( function_exists( 'newsai_chief_insights_collect_data' ) ? newsai_chief_insights_collect_data( $days, $is_pro ) : [] );

		$post_count         = (int) ( $insights_data['post_count'] ?? 0 );
		$avg_words          = (int) ( $insights_data['avg_words'] ?? 0 );
		$avg_focus          = (int) ( $insights_data['avg_focus'] ?? 0 );
		$avg_discover       = (int) ( $insights_data['avg_discover'] ?? 0 );
		$focus_n            = (int) ( $insights_data['focus_n'] ?? 0 );
		$disc_n             = (int) ( $insights_data['disc_n'] ?? 0 );
		$avg_seo_score      = (int) ( $insights_data['avg_seo_score'] ?? 0 );
		$seo_n              = (int) ( $insights_data['seo_n'] ?? 0 );
		$seo_plugin         = (string) ( $insights_data['seo_plugin'] ?? '' );
		$prev_post_count    = (int) ( $insights_data['prev_post_count'] ?? 0 );
		$prev_avg_words     = (int) ( $insights_data['prev_avg_words'] ?? 0 );
		$prev_avg_focus     = (int) ( $insights_data['prev_avg_focus'] ?? 0 );
		$prev_avg_discover  = (int) ( $insights_data['prev_avg_discover'] ?? 0 );
		$prev_avg_seo_score = (int) ( $insights_data['prev_avg_seo_score'] ?? 0 );
		$prev_gsc_clicks    = (int) ( $insights_data['prev_gsc_clicks'] ?? 0 );
		$top_categories     = (array) ( $insights_data['top_categories'] ?? [] );
		$top_tags           = (array) ( $insights_data['top_tags'] ?? [] );
		$gsc                = (array) ( $insights_data['gsc'] ?? [] );
		$top_articles       = (array) ( $insights_data['top_articles'] ?? [] );
		$top_discover       = (array) ( $insights_data['top_discover'] ?? [] );
		$top_google_news    = (array) ( $insights_data['top_google_news'] ?? [] );
		$gsc_ready          = ! empty( $insights_data['gsc_ready'] );
		$total_clicks       = (int) ( $insights_data['total_clicks'] ?? 0 );
		$chief_gsc_series   = (array) ( $insights_data['chief_gsc_series'] ?? [] );
		$chief_gsc_devices  = (array) ( $insights_data['chief_gsc_devices'] ?? [] );
		$gsc_kpis_all       = (array) ( $insights_data['gsc_kpis'] ?? [] );
		$post_movers_all    = (array) ( $insights_data['post_movers'] ?? [] );
		$keyword_movers     = (array) ( $insights_data['keyword_movers'] ?? [] );
		$gsc_kpis           = isset( $gsc_kpis_all[ $gsc_channel ] ) ? (array) $gsc_kpis_all[ $gsc_channel ] : [];
		$post_movers        = isset( $post_movers_all[ $gsc_channel ] ) ? (array) $post_movers_all[ $gsc_channel ] : [ 'win' => [], 'lose' => [] ];
		$insights_cached_at = (int) ( $insights_data['cached_at'] ?? 0 );
		$channel_labels     = function_exists( 'newsai_chief_device_channel_labels' )
			? newsai_chief_device_channel_labels()
			: [ 'web' => 'Web', 'discover' => 'Discover', 'googleNews' => 'Google News' ];

		$insights_prev_label = sprintf(
			/* translators: %d: number of days in comparison window */
			__( 'vs previous %d days', 'newsroom-ai-assistant' ),
			(int) $days
		);
		$show_kpi_deltas = $is_pro && function_exists( 'newsai_chief_kpi_delta_text' ) && function_exists( 'newsai_chief_kpi_delta_class' );
		$brief_payload = function_exists( 'newsai_chief_daily_brief_payload' )
			? newsai_chief_daily_brief_payload( (int) $days )
			: [
				'days'      => (int) $days,
				'kpis'      => [
					'published_articles' => (int) $post_count,
					'avg_words'          => (int) $avg_words,
					'avg_focus'          => (int) $avg_focus,
					'avg_discover'       => (int) $avg_discover,
					'total_gsc_clicks'   => (int) $total_clicks,
				],
				'channels'  => $gsc,
				'top_categories' => array_slice( (array) $top_categories, 0, 5 ),
				'top_tags'       => array_slice( (array) $top_tags, 0, 8 ),
				'top_articles'   => array_slice( (array) $top_articles, 0, 5 ),
				'seasonal'       => ( $is_pro && function_exists( 'newsai_seasonal_radar_get_cached' ) )
					? array_slice( (array) ( newsai_seasonal_radar_get_cached()['items'] ?? [] ), 0, 5 )
					: [],
			];
		$chief_delta = static function ( $current, $previous, $mode = 'number' ) use ( $show_kpi_deltas, $days ) {
			if ( ! $show_kpi_deltas ) {
				return '';
			}
			$class = newsai_chief_kpi_delta_class( $current, $previous );
			$text  = newsai_chief_kpi_delta_text( $current, $previous, $days, $mode );
			return '<div class="nros-kpi-sub ' . esc_attr( $class ) . '">' . esc_html( $text ) . '</div>';
		};
		?>
		<div id="nros-insights-print-area">
		<div class="nros-chief-command">
			<div class="nros-chief-command__top">
				<div class="nros-chief-command__title-wrap">
					<h2>
						<?php echo esc_html__( 'Chief Insights', 'newsroom-ai-assistant' ); ?>
						<?php if ( $is_pro ) : ?>
							<span class="nros-chief-live-badge" title="<?php echo esc_attr__( 'Desk metrics from your published posts', 'newsroom-ai-assistant' ); ?>"><?php echo esc_html__( 'LIVE', 'newsroom-ai-assistant' ); ?></span>
						<?php else : ?>
							<span class="nros-chief-live-badge" style="background:#fef3c7;color:#92400e;"><?php echo esc_html__( 'DEMO', 'newsroom-ai-assistant' ); ?></span>
						<?php endif; ?>
					</h2>
					<p class="nros-chief-command__sub"><?php echo esc_html__( 'High-level overview of editorial and search performance.', 'newsroom-ai-assistant' ); ?>
					<?php if ( $insights_cached_at > 0 ) : ?>
						<span class="nros-insights-cache-hint">
							<?php echo esc_html( sprintf( __( 'Metrics cached · refreshes daily or after GSC sync (last built %s).', 'newsroom-ai-assistant' ), wp_date( 'M j, H:i', $insights_cached_at ) ) ); ?>
							<a href="<?php echo esc_url( add_query_arg( [ 'page' => 'newsai-settings', 'tab' => 'insights', 'days' => $days, 'gsc_channel' => $gsc_channel, 'newsai_refresh_insights' => '1' ], admin_url( 'admin.php' ) ) ); ?>" class="nros-insights-refresh-link"><?php echo esc_html__( 'Refresh now', 'newsroom-ai-assistant' ); ?></a>
						</span>
					<?php endif; ?>
					<span class="nros-insights-cache-hint"><?php echo esc_html( sprintf( __( 'KPI deltas and movers compare the selected window vs the previous %d days.', 'newsroom-ai-assistant' ), (int) $days ) ); ?></span>
					</p>
				</div>
				<div class="nros-chief-command__actions">
					<form method="get" class="nros-chief-command__window">
						<input type="hidden" name="page" value="newsai-settings">
						<input type="hidden" name="tab" value="insights">
						<label for="nros-insights-days"><?php echo esc_html__( 'Window', 'newsroom-ai-assistant' ); ?></label>
						<select id="nros-insights-days" name="days">
							<option value="7" <?php selected( $days, 7 ); ?>>7d</option>
							<option value="30" <?php selected( $days, 30 ); ?>>30d</option>
							<option value="90" <?php selected( $days, 90 ); ?>>90d</option>
						</select>
						<label for="nros-insights-channel" class="screen-reader-text"><?php echo esc_html__( 'GSC channel', 'newsroom-ai-assistant' ); ?></label>
						<select id="nros-insights-channel" name="gsc_channel">
							<option value="all" <?php selected( $gsc_channel, 'all' ); ?>><?php echo esc_html__( 'All traffic', 'newsroom-ai-assistant' ); ?></option>
							<option value="web" <?php selected( $gsc_channel, 'web' ); ?>><?php echo esc_html__( 'Web', 'newsroom-ai-assistant' ); ?></option>
							<option value="discover" <?php selected( $gsc_channel, 'discover' ); ?>><?php echo esc_html__( 'Discover', 'newsroom-ai-assistant' ); ?></option>
							<option value="googleNews" <?php selected( $gsc_channel, 'googleNews' ); ?>><?php echo esc_html__( 'Google News', 'newsroom-ai-assistant' ); ?></option>
						</select>
						<button type="submit" class="button button-secondary"><?php echo esc_html__( 'Apply', 'newsroom-ai-assistant' ); ?></button>
					</form>
					<button type="button" class="button" id="nros-insights-print"><?php echo esc_html__( 'Export PDF', 'newsroom-ai-assistant' ); ?></button>
					<select id="nros-insights-brief-mode" <?php disabled( ! $is_pro ); ?>>
						<option value="morning"><?php echo esc_html__( 'Morning', 'newsroom-ai-assistant' ); ?></option>
						<option value="evening"><?php echo esc_html__( 'Evening', 'newsroom-ai-assistant' ); ?></option>
					</select>
					<button type="button" class="button button-primary" id="nros-insights-ai-brief" <?php disabled( ! $is_pro ); ?>><?php echo esc_html__( 'AI Daily Brief', 'newsroom-ai-assistant' ); ?></button>
					<button type="button" class="button button-secondary" id="nros-insights-palette-open" aria-label="<?php echo esc_attr__( 'Open command palette', 'newsroom-ai-assistant' ); ?>">
						<?php echo esc_html__( 'Commands', 'newsroom-ai-assistant' ); ?>
						<span class="nros-chief-kbd-hint"><kbd>Ctrl</kbd>+<kbd>K</kbd></span>
					</button>
				</div>
			</div>
			<div id="nros-insights-ai-result" class="nros-chief-ai-result" data-brief="<?php echo esc_attr( wp_json_encode( $brief_payload ) ); ?>"></div>
		</div>

		<div class="nros-insights-wrap nros-insights-wrap--v2<?php echo $is_pro ? '' : ' is-demo'; ?>">
			<?php
			$kpi_spark_clicks = function_exists( 'newsai_chief_render_mini_sparkline' ) && ! empty( $gsc_kpis['spark_clicks'] )
				? newsai_chief_render_mini_sparkline( (array) $gsc_kpis['spark_clicks'], '#2271b1', 120, 28 )
				: '';
			$kpi_spark_impr = function_exists( 'newsai_chief_render_mini_sparkline' ) && ! empty( $gsc_kpis['spark_impr'] )
				? newsai_chief_render_mini_sparkline( (array) $gsc_kpis['spark_impr'], '#7c3aed', 120, 28 )
				: $kpi_spark_clicks;
			$kpi_clicks_val = $is_pro && $gsc_ready && $gsc_kpis !== []
				? number_format_i18n( (int) ( $gsc_kpis['clicks'] ?? 0 ) )
				: number_format_i18n( $total_clicks );
			$kpi_impr_val = $is_pro && $gsc_ready && $gsc_kpis !== []
				? number_format_i18n( (int) ( $gsc_kpis['impressions'] ?? 0 ) )
				: '—';
			$kpi_ctr_val = $is_pro && $gsc_ready && $gsc_kpis !== []
				? number_format_i18n( (float) ( $gsc_kpis['ctr'] ?? 0 ) * 100, 2 ) . '%'
				: '—';
			$kpi_pos_val = $is_pro && $gsc_ready && $gsc_kpis !== [] && (float) ( $gsc_kpis['position'] ?? 0 ) > 0
				? number_format_i18n( (float) $gsc_kpis['position'], 1 )
				: '—';
			$channel_title = $gsc_channel === 'all'
				? __( 'All traffic', 'newsroom-ai-assistant' )
				: ( $channel_labels[ $gsc_channel ] ?? $gsc_channel );
			?>
			<div class="nros-chief-kpi-strip nros-chief-kpi-strip--primary">
				<?php
				if ( function_exists( 'newsai_chief_render_kpi_card' ) && function_exists( 'newsai_chief_kpi_delta_chip' ) ) {
					echo newsai_chief_render_kpi_card( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						__( 'Total clicks', 'newsroom-ai-assistant' ),
						$kpi_clicks_val,
						$show_kpi_deltas && $gsc_kpis !== []
							? newsai_chief_kpi_delta_chip( (int) ( $gsc_kpis['clicks'] ?? 0 ), (int) ( $gsc_kpis['prev_clicks'] ?? 0 ), 'percent' )
							: [ 'class' => '', 'text' => '' ],
						$kpi_spark_clicks,
						(string) $channel_title,
						'hero'
					);
					echo newsai_chief_render_kpi_card(
						__( 'Impressions', 'newsroom-ai-assistant' ),
						$kpi_impr_val,
						$show_kpi_deltas && $gsc_kpis !== []
							? newsai_chief_kpi_delta_chip( (int) ( $gsc_kpis['impressions'] ?? 0 ), (int) ( $gsc_kpis['prev_impressions'] ?? 0 ), 'percent' )
							: [ 'class' => '', 'text' => '' ],
						$kpi_spark_impr
					);
					echo newsai_chief_render_kpi_card(
						__( 'Avg. CTR', 'newsroom-ai-assistant' ),
						$kpi_ctr_val,
						$show_kpi_deltas && $gsc_kpis !== []
							? newsai_chief_kpi_delta_chip( (float) ( $gsc_kpis['ctr'] ?? 0 ), (float) ( $gsc_kpis['prev_ctr'] ?? 0 ), 'ctr' )
							: [ 'class' => '', 'text' => '' ]
					);
					echo newsai_chief_render_kpi_card(
						__( 'Avg. position', 'newsroom-ai-assistant' ),
						$kpi_pos_val,
						$show_kpi_deltas && $gsc_kpis !== []
							? newsai_chief_kpi_delta_chip( (float) ( $gsc_kpis['position'] ?? 0 ), (float) ( $gsc_kpis['prev_position'] ?? 0 ), 'position' )
							: [ 'class' => '', 'text' => '' ]
					);
				}
				?>
			</div>
			<div class="nros-chief-kpi-strip nros-chief-kpi-strip--secondary">
				<?php
				if ( function_exists( 'newsai_chief_render_kpi_card' ) && function_exists( 'newsai_chief_kpi_delta_chip' ) ) {
					echo newsai_chief_render_kpi_card( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						__( 'Desk output', 'newsroom-ai-assistant' ),
						number_format_i18n( $post_count ),
						$show_kpi_deltas ? newsai_chief_kpi_delta_chip( $post_count, $prev_post_count, 'percent' ) : [ 'class' => '', 'text' => '' ],
						'',
						sprintf( __( 'Published · %d days', 'newsroom-ai-assistant' ), (int) $days )
					);
					echo newsai_chief_render_kpi_card(
						__( 'Avg Discover', 'newsroom-ai-assistant' ),
						$avg_discover > 0 ? $avg_discover . '%' : '—',
						$show_kpi_deltas ? newsai_chief_kpi_delta_chip( $avg_discover, $prev_avg_discover, 'percent' ) : [ 'class' => '', 'text' => '' ],
						'',
						sprintf( __( 'Sample %d', 'newsroom-ai-assistant' ), (int) $disc_n )
					);
					if ( $seo_plugin !== '' && $avg_seo_score > 0 ) {
						$seo_label = $seo_plugin === 'rankmath'
							? __( 'Avg RM SEO', 'newsroom-ai-assistant' )
							: __( 'Avg Yoast SEO', 'newsroom-ai-assistant' );
						echo newsai_chief_render_kpi_card(
							$seo_label,
							$avg_seo_score . '/100',
							$show_kpi_deltas ? newsai_chief_kpi_delta_chip( $avg_seo_score, $prev_avg_seo_score, 'percent' ) : [ 'class' => '', 'text' => '' ],
							'',
							sprintf( __( 'Sample %d', 'newsroom-ai-assistant' ), (int) $seo_n )
						);
					}
				}
				?>
			</div>
			<p class="nros-chief-legend-hint">
				<?php echo esc_html__( 'Green Δ = more clicks or better rank · Red Δ = fewer clicks or worse rank · GSC data is usually 2–3 days behind.', 'newsroom-ai-assistant' ); ?>
			</p>

			<div class="nros-chief-bento">
				<?php if ( $is_pro && $gsc_ready ) : ?>
				<div class="nros-card nros-chief-bento__chart">
					<div class="nros-chief-card-head">
						<h3><?php echo esc_html__( 'Search performance', 'newsroom-ai-assistant' ); ?></h3>
						<p class="nros-insights-table-hint"><?php echo esc_html__( 'Clicks distribution across Google surfaces.', 'newsroom-ai-assistant' ); ?></p>
					</div>
					<?php
					if ( function_exists( 'newsai_chief_render_gsc_line_chart' ) ) {
						echo newsai_chief_render_gsc_line_chart( $chief_gsc_series, $days, $gsc_channel ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					} elseif ( function_exists( 'newsai_chief_render_gsc_trend_chart' ) ) {
						echo newsai_chief_render_gsc_trend_chart( $chief_gsc_series, $days ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					}
					?>
				</div>
				<?php endif; ?>

				<div class="nros-chief-bento__movers">
					<div class="nros-card nros-chief-bento__win">
						<h3><?php echo esc_html__( 'Top winning posts', 'newsroom-ai-assistant' ); ?></h3>
						<?php
						if ( function_exists( 'newsai_chief_render_post_movers_list' ) ) {
							echo newsai_chief_render_post_movers_list( (array) ( $post_movers['win'] ?? [] ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						} elseif ( function_exists( 'newsai_chief_render_post_movers_table' ) ) {
							echo newsai_chief_render_post_movers_table( (array) ( $post_movers['win'] ?? [] ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						}
						?>
					</div>
					<div class="nros-card nros-chief-bento__lose">
						<h3><?php echo esc_html__( 'Top losing posts', 'newsroom-ai-assistant' ); ?></h3>
						<?php
						if ( function_exists( 'newsai_chief_render_post_movers_list' ) ) {
							echo newsai_chief_render_post_movers_list(
								(array) ( $post_movers['lose'] ?? [] ),
								__( 'No posts with meaningful click loss in this window.', 'newsroom-ai-assistant' )
							); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						} elseif ( function_exists( 'newsai_chief_render_post_movers_table' ) ) {
							echo newsai_chief_render_post_movers_table(
								(array) ( $post_movers['lose'] ?? [] ),
								__( 'No posts with meaningful click loss in this window.', 'newsroom-ai-assistant' )
							); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						}
						?>
					</div>
				</div>

				<?php if ( $is_pro && $gsc_ready ) : ?>
				<div class="nros-card nros-chief-bento__device">
					<h3><?php echo esc_html__( 'Device breakdown', 'newsroom-ai-assistant' ); ?></h3>
					<?php
					$device_ch  = $gsc_channel === 'all' ? 'web' : $gsc_channel;
					$device_lbl = $channel_labels[ $device_ch ] ?? __( 'Web', 'newsroom-ai-assistant' );
					?>
					<div class="nros-chief-seg" id="nros-chief-device-channel" data-days="<?php echo (int) $days; ?>" role="group" aria-label="<?php echo esc_attr__( 'GSC channel', 'newsroom-ai-assistant' ); ?>">
						<?php foreach ( $channel_labels as $ch_key => $ch_label ) : ?>
							<button type="button" class="nros-chief-seg__btn<?php echo $ch_key === $device_ch ? ' is-on' : ''; ?>" data-channel="<?php echo esc_attr( $ch_key ); ?>"><?php echo esc_html( $ch_label ); ?></button>
						<?php endforeach; ?>
					</div>
					<div id="nros-chief-device-donut">
					<?php
					if ( function_exists( 'newsai_chief_render_device_donut' ) ) {
						echo newsai_chief_render_device_donut( $chief_gsc_devices, (string) $device_lbl ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					}
					?>
					</div>
				</div>
				<div class="nros-card nros-chief-bento__channels">
					<h3><?php echo esc_html__( 'Channel clicks', 'newsroom-ai-assistant' ); ?></h3>
					<p class="nros-insights-table-hint"><?php echo esc_html( sprintf( __( 'Site-wide GSC totals · last %d days.', 'newsroom-ai-assistant' ), (int) $days ) ); ?></p>
					<?php
					if ( function_exists( 'newsai_chief_render_channel_click_bars' ) ) {
						echo newsai_chief_render_channel_click_bars( $gsc, $channel_labels ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					}
					?>
				</div>
				<div class="nros-card nros-chief-bento__seasonal">
					<?php
					if ( function_exists( 'newsai_chief_render_seasonal_highlight' ) ) {
						echo newsai_chief_render_seasonal_highlight(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					}
					?>
				</div>
				<?php endif; ?>
			</div>

			<div class="nros-chief-accordions">
				<?php if ( $is_pro && function_exists( 'newsai_seasonal_radar_render_panel' ) ) : ?>
				<details class="nros-chief-accordion" id="nros-chief-seasonal-full">
					<summary><?php echo esc_html__( 'Seasonal radar — full list', 'newsroom-ai-assistant' ); ?></summary>
					<div class="nros-chief-accordion__body">
						<?php newsai_seasonal_radar_render_panel(); ?>
					</div>
				</details>
				<?php endif; ?>
				<details class="nros-chief-accordion">
					<summary><?php echo esc_html__( 'Keywords & desk pulse', 'newsroom-ai-assistant' ); ?></summary>
					<div class="nros-chief-accordion__body">
						<div class="nros-dashboard-grid">
							<div class="nros-card nros-col-6">
								<h3><?php echo esc_html__( 'Winning keywords', 'newsroom-ai-assistant' ); ?></h3>
								<?php
								if ( function_exists( 'newsai_chief_render_keyword_movers_table' ) ) {
									echo newsai_chief_render_keyword_movers_table( (array) ( $keyword_movers['win'] ?? [] ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
								}
								?>
							</div>
							<div class="nros-card nros-col-6">
								<h3><?php echo esc_html__( 'Losing keywords', 'newsroom-ai-assistant' ); ?></h3>
								<?php
								if ( function_exists( 'newsai_chief_render_keyword_movers_table' ) ) {
									echo newsai_chief_render_keyword_movers_table( (array) ( $keyword_movers['lose'] ?? [] ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
								}
								?>
							</div>
							<div class="nros-card nros-col-6 nros-card--war-room">
								<?php
								if ( $is_pro && function_exists( 'newsai_warroom_render_compact' ) ) {
									newsai_warroom_render_compact( $days, $is_pro );
								} else {
									echo '<h3>' . esc_html__( 'War room', 'newsroom-ai-assistant' ) . '</h3>';
									echo '<p class="nros-insights-table-hint">' . esc_html__( 'Live desk pulse is available in Pro.', 'newsroom-ai-assistant' ) . '</p>';
								}
								?>
							</div>
							<div class="nros-card nros-col-6">
								<h3><?php echo esc_html__( 'Top categories', 'newsroom-ai-assistant' ); ?></h3>
								<?php if ( empty( $top_categories ) ) : ?>
									<p class="nros-insights-table-hint"><?php echo esc_html__( 'No category data yet.', 'newsroom-ai-assistant' ); ?></p>
								<?php else : ?>
									<?php foreach ( array_slice( $top_categories, 0, 6 ) as $cat ) : ?>
										<div class="nros-perf-row"><span><?php echo esc_html( (string) $cat['name'] ); ?></span><strong><?php echo esc_html( number_format_i18n( (int) $cat['cnt'] ) ); ?></strong></div>
									<?php endforeach; ?>
								<?php endif; ?>
							</div>
						</div>
					</div>
				</details>
				<?php if ( $is_pro && function_exists( 'newsai_gsc_traffic_drop_render_panel' ) ) : ?>
				<details class="nros-chief-accordion">
					<summary><?php echo esc_html__( 'Traffic drop alerts', 'newsroom-ai-assistant' ); ?></summary>
					<div class="nros-chief-accordion__body">
						<?php newsai_gsc_traffic_drop_render_panel( $days ); ?>
					</div>
				</details>
				<?php endif; ?>
				<?php if ( $is_pro && function_exists( 'newsai_crux_render_panel' ) ) : ?>
				<details class="nros-chief-accordion">
					<summary><?php echo esc_html__( 'Core Web Vitals', 'newsroom-ai-assistant' ); ?></summary>
					<div class="nros-chief-accordion__body">
						<?php newsai_crux_render_panel(); ?>
					</div>
				</details>
				<?php endif; ?>
			</div>

			<?php if ( ! $is_pro && function_exists( 'newsai_pro_promo_link' ) ) : ?>
				<div class="nros-pro-overlay">
					<div class="nros-pro-badge">PRO DEMO</div>
					<h3 style="margin:0 0 8px;"><?php echo esc_html__( 'Unlock live Chief Insights', 'newsroom-ai-assistant' ); ?></h3>
					<p style="max-width:480px; color:#50575e;"><?php echo esc_html__( 'This is a demo layout. Activate Pro to see live desk-wide metrics from your own posts, tags, and Search Console channels.', 'newsroom-ai-assistant' ); ?></p>
					<a class="button button-primary" href="<?php echo esc_url( newsai_pro_promo_link( 'chief-insights-demo' ) ); ?>" target="_blank" rel="noopener"><?php echo esc_html__( 'Upgrade to Pro', 'newsroom-ai-assistant' ); ?></a>
				</div>
			<?php endif; ?>
		</div>
		</div>
		<script>
		document.addEventListener('DOMContentLoaded', function () {
			var btn = document.getElementById('nros-insights-print');
			var aiBtn = document.getElementById('nros-insights-ai-brief');
			var aiBox = document.getElementById('nros-insights-ai-result');
			var modeSel = document.getElementById('nros-insights-brief-mode');
			var paletteBtn = document.getElementById('nros-insights-palette-open');
			if (paletteBtn && window.nrosCommandPalette && typeof window.nrosCommandPalette.open === 'function') {
				paletteBtn.addEventListener('click', function () {
					window.nrosCommandPalette.open();
				});
			}
			if (!btn) return;
			btn.addEventListener('click', function () {
				window.print();
			});
			if (aiBtn && aiBox && window.jQuery) {
				function nrosBriefEsc(text) {
					var d = document.createElement('div');
					d.textContent = String(text || '');
					return d.innerHTML;
				}
				function nrosBriefShowError(msg) {
					aiBox.innerHTML = '<span class="nros-chief-delta--down">❌ ' + nrosBriefEsc(msg) + '</span>';
				}
				aiBtn.addEventListener('click', function () {
					var newsaiVars = window.newsai_vars || {};
					if (!newsaiVars.ajax_url || !newsaiVars.nonce) {
						nrosBriefShowError(<?php echo wp_json_encode( __( 'Newsroom scripts not loaded. Hard-refresh this page.', 'newsroom-ai-assistant' ) ); ?>);
						return;
					}
					var daysSel = document.getElementById('nros-insights-days');
					var briefDays = daysSel ? parseInt(daysSel.value, 10) : 30;
					if (!briefDays || briefDays < 7) { briefDays = 30; }
					aiBtn.disabled = true;
					aiBox.classList.add('is-visible');
					aiBox.innerHTML = '<em><?php echo esc_js( __( 'Generating daily brief…', 'newsroom-ai-assistant' ) ); ?></em>';
					window.jQuery.post(newsaiVars.ajax_url, {
						action: 'newsai_ai_chief_daily_brief',
						nonce: newsaiVars.nonce,
						brief_days: briefDays,
						brief_mode: modeSel ? String(modeSel.value || 'morning') : 'morning'
					}).done(function(resp){
						if (!resp || !resp.success) {
							var errMsg = (resp && resp.data && resp.data.message) ? resp.data.message : <?php echo wp_json_encode( __( 'Could not generate AI brief.', 'newsroom-ai-assistant' ) ); ?>;
							nrosBriefShowError(errMsg);
							return;
						}
						if (!resp.data || !resp.data.html) {
							nrosBriefShowError(<?php echo wp_json_encode( __( 'Could not generate AI brief.', 'newsroom-ai-assistant' ) ); ?>);
							return;
						}
						aiBox.innerHTML = resp.data.html;
					}).fail(function(xhr){
						var errMsg = <?php echo wp_json_encode( __( 'AI request failed.', 'newsroom-ai-assistant' ) ); ?>;
						if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
							errMsg = xhr.responseJSON.data.message;
						}
						nrosBriefShowError(errMsg);
					}).always(function(){
						aiBtn.disabled = false;
					});
				});
			}
		});
		</script>
		<?php
	}
}

if ( ! function_exists( 'newsai_ajax_ai_chief_daily_brief' ) ) {
	/**
	 * AI summary block for Chief Insights.
	 *
	 * @return void
	 */
	function newsai_ajax_ai_chief_daily_brief() {
		check_ajax_referer( 'newsai_ajax_nonce', 'nonce' );
		if ( ! current_user_can( 'edit_others_posts' ) ) {
			wp_send_json_error( [ 'message' => 'forbidden' ], 403 );
		}
		if ( ! function_exists( 'newsai_is_pro' ) || ! newsai_is_pro() ) {
			wp_send_json_error( [ 'message' => 'pro_required' ], 403 );
		}
		if ( ! function_exists( 'newsai_ai_call' ) || ! function_exists( 'newsai_ai_is_active' ) || ! newsai_ai_is_active() ) {
			wp_send_json_error(
				[
					'message' => __( 'Configure your AI provider and API key under Settings → AI Assist, then save.', 'newsroom-ai-assistant' ),
				],
				400
			);
		}

		$brief_days = isset( $_POST['brief_days'] ) ? (int) $_POST['brief_days'] : 30;
		$brief_days = max( 7, min( 90, $brief_days ) );
		$brief_mode  = isset( $_POST['brief_mode'] ) ? sanitize_key( (string) wp_unslash( $_POST['brief_mode'] ) ) : 'morning';
		if ( ! in_array( $brief_mode, [ 'morning', 'evening' ], true ) ) {
			$brief_mode = 'morning';
		}
		$payload = function_exists( 'newsai_chief_daily_brief_payload' )
			? newsai_chief_daily_brief_payload( $brief_days )
			: [];
		if ( empty( $payload ) ) {
			$raw_payload = isset( $_POST['brief_payload'] ) ? (string) wp_unslash( $_POST['brief_payload'] ) : '';
			$payload     = json_decode( $raw_payload, true );
		}
		if ( ! is_array( $payload ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid brief metrics payload.', 'newsroom-ai-assistant' ) ], 400 );
		}
		$payload_json = wp_json_encode( $payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );

		$system = newsai_ai_seo_editor_preamble() . ' '
			. 'You are also a newsroom chief analytics assistant. '
			. newsai_ai_json_output_rules( '{"headline":"brief title","summary":"paragraph","wins":["win"],"risks":["risk"],"actions":["action"]}' )
			. ' Keep concise, practical, executive tone. wins/risks/actions: max 3 items each. '
			. 'When payload.seasonal has items, mention YoY seasonal tag opportunities in wins or actions.';
		$mode_instruction = ( 'evening' === $brief_mode )
			? 'Mode: Evening. Focus on what happened today, what underperformed, and 3 concrete actions for tomorrow.'
			: 'Mode: Morning. Focus on priorities for the day, biggest opportunities, and 3 concrete execution actions now.';
		$user   = $mode_instruction . "\n\nBuild a newsroom brief from this JSON metrics payload:\n" . $payload_json;
		$seed   = 'chief_daily_brief-v2|' . $brief_mode . '|' . md5( $payload_json . '|' . gmdate( 'Y-m-d-H' ) );
		$ai = newsai_ai_call( $system, $user, $seed );
		if ( empty( $ai['ok'] ) || empty( $ai['data'] ) || ! is_array( $ai['data'] ) ) {
			$err = (string) ( $ai['error'] ?? __( 'AI request failed.', 'newsroom-ai-assistant' ) );
			if ( function_exists( 'newsai_ai_format_error_for_ui' ) ) {
				$err = newsai_ai_format_error_for_ui( $err );
			}
			wp_send_json_error( [ 'message' => $err ], 400 );
		}

		$data = $ai['data'];
		$headline = sanitize_text_field( (string) ( $data['headline'] ?? __( 'Daily newsroom brief', 'newsroom-ai-assistant' ) ) );
		$summary  = sanitize_textarea_field( (string) ( $data['summary'] ?? '' ) );
		$wins     = isset( $data['wins'] ) && is_array( $data['wins'] ) ? array_slice( $data['wins'], 0, 3 ) : [];
		$risks    = isset( $data['risks'] ) && is_array( $data['risks'] ) ? array_slice( $data['risks'], 0, 3 ) : [];
		$actions  = isset( $data['actions'] ) && is_array( $data['actions'] ) ? array_slice( $data['actions'], 0, 3 ) : [];

		$mode_label = ( 'evening' === $brief_mode ) ? __( 'Evening mode', 'newsroom-ai-assistant' ) : __( 'Morning mode', 'newsroom-ai-assistant' );
		$html = '<h4 style="margin:0 0 8px 0;">🧠 ' . esc_html( $headline ) . ' <span style="font-size:11px;color:#64748b;">(' . esc_html( $mode_label ) . ')</span></h4>';
		if ( $summary !== '' ) {
			$html .= '<p style="margin:0 0 10px 0;color:#334155;">' . esc_html( $summary ) . '</p>';
		}
		$render_list = static function( $title, $items ) {
			if ( empty( $items ) ) {
				return '';
			}
			$out = '<div style="margin-bottom:8px;"><strong>' . esc_html( $title ) . '</strong><ul style="margin:6px 0 0 18px;">';
			foreach ( $items as $item ) {
				$out .= '<li>' . esc_html( sanitize_text_field( (string) $item ) ) . '</li>';
			}
			$out .= '</ul></div>';
			return $out;
		};
		$html .= $render_list( __( 'Wins', 'newsroom-ai-assistant' ), $wins );
		$html .= $render_list( __( 'Risks', 'newsroom-ai-assistant' ), $risks );
		$html .= $render_list( __( 'Next Actions', 'newsroom-ai-assistant' ), $actions );
		if ( ! empty( $ai['cached'] ) ) {
			$html .= '<p style="margin:8px 0 0 0;color:#64748b;font-size:11px;">' . esc_html__( 'Served from AI cache.', 'newsroom-ai-assistant' ) . '</p>';
		}

		wp_send_json_success( [ 'html' => $html ] );
	}
}
add_action( 'wp_ajax_newsai_ai_chief_daily_brief', 'newsai_ajax_ai_chief_daily_brief' );

add_action( 'wp_ajax_newsai_save_indexing_sa', 'newsai_ajax_save_indexing_sa' );
if ( ! function_exists( 'newsai_ajax_save_indexing_sa' ) ) {
	/**
	 * Save Google service account JSON via AJAX (avoids megasite settings-form POST limits / WAF).
	 */
	function newsai_ajax_save_indexing_sa() {
		check_ajax_referer( 'newsai_ajax_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Unauthorized.', 'newsroom-ai-assistant' ) ], 403 );
		}
		if ( ! function_exists( 'newsai_save_indexing_service_json_from_request' ) ) {
			wp_send_json_error( [ 'message' => __( 'Secrets module not loaded.', 'newsroom-ai-assistant' ) ], 500 );
		}
		$result = newsai_save_indexing_service_json_from_request( wp_unslash( $_POST ) );
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}
		$cleared = ! empty( $_POST['indexing_service_json_clear'] ) && (string) wp_unslash( $_POST['indexing_service_json_clear'] ) === '1';
		wp_send_json_success(
			[
				'message' => $cleared
					? __( 'Service account JSON removed.', 'newsroom-ai-assistant' )
					: __( 'Service account JSON saved.', 'newsroom-ai-assistant' ),
				'email'   => function_exists( 'newsai_secret_indexing_client_email' ) ? newsai_secret_indexing_client_email() : '',
				'cleared' => $cleared,
			]
		);
	}
}

function newsai_render_admin() {
    global $wpdb;
    $table = $wpdb->prefix . 'newsai_alerts';
    $can_manage_all = current_user_can('manage_options');
    $can_edit_tasks = current_user_can('edit_posts');
    $security_notice = '';
    $settings_notice = '';
    
    // 🚀 FIX: Caching των στηλών της βάσης για αποφυγή heavy DESC queries
    $table_cols = get_transient('newsai_table_cols_cache');
    if (false === $table_cols) {
        $table_cols = $wpdb->get_col("DESC {$table}", 0);
        set_transient('newsai_table_cols_cache', $table_cols, DAY_IN_SECONDS);
    }

    $tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'alerts'; 
    $lang = function_exists( 'newsai_get_ui_lang' ) ? newsai_get_ui_lang() : 'en';
    $geo_opt = function_exists( 'newsai_get_target_geo' ) ? newsai_get_target_geo() : 'US';
    $newsai_is_pro_active = function_exists( 'newsai_is_pro' ) && newsai_is_pro();

    // Central i18n dictionary for the chief dashboard + settings tabs. All strings flow
    // through gettext now (load_plugin_textdomain('newsroom-ai-assistant', …)) so adding
    // a new language is just dropping a .mo file in /languages.
    $i18n = [
        'settings_title' => __( 'Site Details', 'newsroom-ai-assistant' ),
        'schema_title'   => __( 'Schema & SEO Settings', 'newsroom-ai-assistant' ),
        'prompts_title'  => __( '🧠 Prompt Engineering (Customization)', 'newsroom-ai-assistant' ),
        'prompts_desc'   => __( 'Customize the commands copied to your AI.', 'newsroom-ai-assistant' ),
        'timeline_title' => __( '⏳ Auto-Timeline Settings', 'newsroom-ai-assistant' ),
        'btn_save'       => __( 'Save Settings', 'newsroom-ai-assistant' ),
        'add_alert'      => __( '➕ Assign New Task', 'newsroom-ai-assistant' ),
        'edit_alert'     => __( '✏️ Edit Task', 'newsroom-ai-assistant' ),
        'topic'          => __( 'Story Topic', 'newsroom-ai-assistant' ),
        'topic_ph'       => __( 'e.g. Local Elections', 'newsroom-ai-assistant' ),
        'notes'          => __( '📝 Briefing / Notes', 'newsroom-ai-assistant' ),
        'notes_ph'       => __( 'e.g. Ask the Mayor for a statement...', 'newsroom-ai-assistant' ),
        'date'           => __( '📅 Date', 'newsroom-ai-assistant' ),
        'recurrence'     => __( 'Recurrence:', 'newsroom-ai-assistant' ),
        'yearly'         => __( 'Yearly', 'newsroom-ai-assistant' ),
        'monthly'        => __( 'Monthly', 'newsroom-ai-assistant' ),
        'once'           => __( 'One-time', 'newsroom-ai-assistant' ),
        'lead_days'      => __( '⏳ Lead Days', 'newsroom-ai-assistant' ),
        'days_before'    => __( 'days before', 'newsroom-ai-assistant' ),
        'assign_to'      => __( '👤 Assign to Writer', 'newsroom-ai-assistant' ),
        'all_users'      => __( 'All Authors', 'newsroom-ai-assistant' ),
        'btn_add_task'   => __( '+ Assign Task', 'newsroom-ai-assistant' ),
        'btn_update_task'=> __( '💾 Save Changes', 'newsroom-ai-assistant' ),
        'btn_cancel'     => __( 'Cancel', 'newsroom-ai-assistant' ),
        'msg_task_ok'    => __( '✅ Task assigned successfully!', 'newsroom-ai-assistant' ),
        'msg_task_upd'   => __( '✅ Task updated successfully!', 'newsroom-ai-assistant' ),
        'feed_pages'     => __( 'Custom Feed Page IDs', 'newsroom-ai-assistant' ),
        'feed_pages_d'   => __( 'Comma-separated IDs for Page Builders (Enables ItemList Carousel).', 'newsroom-ai-assistant' ),
        'about_page_id'  => __( 'About page ID', 'newsroom-ai-assistant' ),
        'about_page_d'   => __( 'WordPress Page ID for “About us” / Ποιοι είμαστε. Emits AboutPage JSON-LD (links to #organization) instead of NewsArticle. Find the ID in Pages → Edit → URL (post=123). Leave 0 to disable.', 'newsroom-ai-assistant' ),
        'speakable_snippet'       => __( 'Speakable: concise lede snippet', 'newsroom-ai-assistant' ),
        'speakable_snippet_d'     => __( 'Prepends a visible paragraph with class .nros-speakable-snippet (capped at the max characters you set) so voice/TTS can target a short section. That class is added to Speakable cssSelector automatically. Other selectors (e.g. .entry-title) are unchanged; only the snippet text is capped. Text source: manual excerpt if set, otherwise a trimmed lede from the body.', 'newsroom-ai-assistant' ),
        'speakable_snippet_chars' => __( 'Max characters', 'newsroom-ai-assistant' ),
        'speakable_snippet_cb'   => __( 'Enable short snippet for Speakable (recommended)', 'newsroom-ai-assistant' ),
        'speakable_snippet_strip_cb' => __( 'When snippet is on, omit wide body selectors from Speakable (recommended)', 'newsroom-ai-assistant' ),
        'speakable_snippet_strip_d' => __( 'The character limit applies only to the prepended .nros-speakable-snippet paragraph. Selectors like .entry-content still match the full article in the DOM, so Rich Results Test can show huge text. With this on, common body wrappers (entry-content, post-content, etc.) are removed from cssSelector while the snippet feature is active. Uncheck if you intentionally want the full body in speakable.', 'newsroom-ai-assistant' ),
        'speakable_d'    => __( 'Comma-separated CSS selectors, e.g. .entry-title, .post-excerpt. Bare class names (entry-title) become .entry-title. Two classes on the same element can be written as entry-content clear and become .entry-content.clear. Speakable is emitted on posts for Balanced and Full presets only (not Minimal). The same block is attached to both NewsArticle and WebPage. Google documents Assistant “speakable news” as beta and US + English only — Greek pages may not get voice playback even with valid markup.', 'newsroom-ai-assistant' ),
        'city'           => __( 'Primary City (Local SEO)', 'newsroom-ai-assistant' ),
        'city_desc'      => __( 'Publisher home city: used on the Organization node (areaServed / location). It is not copied onto every article unless you enable the fallback below.', 'newsroom-ai-assistant' ),
        'city_fallback_label' => __( 'Use primary city on articles when no story place is detected', 'newsroom-ai-assistant' ),
        'city_fallback_desc'  => __( 'For purely local newsrooms only. When off (recommended), contentLocation and dateline are omitted unless a Place tag, city tag, or lede dateline is found — avoids marking international stories with your HQ city.', 'newsroom-ai-assistant' ),
        'geo_desc'       => __( 'Publisher market (organization areaServed). Per-article override available in the editor sidebar.', 'newsroom-ai-assistant' ),
        'schema_output_mode' => __( 'Schema Output Mode', 'newsroom-ai-assistant' ),
        'schema_output_strict' => __( 'Strict Override (disables Yoast/Rank Math JSON-LD entirely — use only if you have no custom SEO plugin schema)', 'newsroom-ai-assistant' ),
        'schema_output_hybrid' => __( 'Hybrid Merge (keep plugin schema + selected SEO schema)', 'newsroom-ai-assistant' ),
        'schema_output_strict_label' => __( 'Strict', 'newsroom-ai-assistant' ),
        'schema_output_hybrid_label' => __( 'Hybrid', 'newsroom-ai-assistant' ),
        'schema_richness' => __( 'Schema richness preset', 'newsroom-ai-assistant' ),
        'schema_richness_hint' => __( 'Controls how much structured data is emitted on single posts. Full VAT / legal / postal organization markup is printed on the homepage only; posts reference the same organization @id with a slim publisher node. Full author E-E-A-T (bio, jobTitle, sameAs, alumniOf, knowsAbout) is printed on author archive pages only; posts reference the author @id with a minimal Person node in the article graph.', 'newsroom-ai-assistant' ),
        'schema_richness_min_label' => __( 'Minimal', 'newsroom-ai-assistant' ),
        'schema_richness_bal_label' => __( 'Balanced', 'newsroom-ai-assistant' ),
        'schema_richness_full_label' => __( 'Full', 'newsroom-ai-assistant' ),
        'schema_richness_min' => __( 'Core NewsArticle fields, slim publisher @id, inline author (name + URL only), no tag entities / video / speakable.', 'newsroom-ai-assistant' ),
        'schema_richness_bal' => __( 'Author @id + minimal Person on posts; capped tag entities; video allowed; speakable when CSS selectors are set (not emitted in Minimal).', 'newsroom-ai-assistant' ),
        'schema_richness_full' => __( 'Rich tag entities, video, and speakable when CSS selectors are set. Full Person graph only on the author profile URL; single posts use the same #author @id with a pointer-style Person node.', 'newsroom-ai-assistant' ),
        'schema_article_body' => __( 'Article body in JSON-LD', 'newsroom-ai-assistant' ),
        'schema_article_body_hint' => __( 'Including the full post text duplicates content in the HTML payload. Use Omit or Limited on long articles.', 'newsroom-ai-assistant' ),
        'schema_article_body_omit' => __( 'Omit articleBody', 'newsroom-ai-assistant' ),
        'schema_article_body_full' => __( 'Full article text', 'newsroom-ai-assistant' ),
        'schema_article_body_limited' => __( 'First N words only', 'newsroom-ai-assistant' ),
        'schema_article_body_words' => __( 'Max words (when limited)', 'newsroom-ai-assistant' ),
        'liveblog_global' => __( 'Enable LiveBlog schema feature (Article + NewsArticle)', 'newsroom-ai-assistant' ),
        'breaking_expire_hours' => __( 'Breaking news auto-expire (hours)', 'newsroom-ai-assistant' ),
        'breaking_badge' => __( 'Show “developing story” badge on live articles', 'newsroom-ai-assistant' ),
        'schema_qa_title' => __( 'Schema QA Panel', 'newsroom-ai-assistant' ),
        'schema_qa_desc' => __( 'Quick validation hints and preview template with soft profile behavior (Article/NewsArticle).', 'newsroom-ai-assistant' ),
        'schema_qa_ok' => __( 'OK', 'newsroom-ai-assistant' ),
        'schema_qa_warn' => __( 'Needs attention', 'newsroom-ai-assistant' ),
        'org_details_title' => __( 'Organization Identity (Google Organization markup)', 'newsroom-ai-assistant' ),
        'org_logo_url' => __( 'Organization Logo URL (Schema override)', 'newsroom-ai-assistant' ),
        'org_logo_url_desc' => __( 'Optional. Used as Organization logo/image in JSON-LD before theme/Yoast/Rank Math fallbacks. Google News / Publisher Center: prefer 600px wide, max 60px height (e.g. 600×60). Upload via Media Library and paste the URL here.', 'newsroom-ai-assistant' ),
        'org_legal_name' => __( 'Legal Name', 'newsroom-ai-assistant' ),
        'org_alt_name' => __( 'Alternate Name', 'newsroom-ai-assistant' ),
        'org_email' => __( 'Organization Email', 'newsroom-ai-assistant' ),
        'org_phone' => __( 'Organization Phone', 'newsroom-ai-assistant' ),
        'org_tax_id' => __( 'Tax ID (taxID)', 'newsroom-ai-assistant' ),
        'org_vat_id' => __( 'VAT ID (vatID)', 'newsroom-ai-assistant' ),
        'org_iso6523' => __( 'ISO6523 Code', 'newsroom-ai-assistant' ),
        'org_naics' => __( 'NAICS Code', 'newsroom-ai-assistant' ),
        'org_addr_country' => __( 'Address Country (ISO-2)', 'newsroom-ai-assistant' ),
        'org_addr_locality' => __( 'Address Locality (City)', 'newsroom-ai-assistant' ),
        'org_addr_region' => __( 'Address Region', 'newsroom-ai-assistant' ),
        'org_addr_postal' => __( 'Address Postal Code', 'newsroom-ai-assistant' ),
        'org_addr_street' => __( 'Address Street', 'newsroom-ai-assistant' ),
        'chip_all'       => __( 'All Tasks', 'newsroom-ai-assistant' ),
        'chip_overdue'   => __( 'Overdue', 'newsroom-ai-assistant' ),
        'chip_today'     => __( 'Due Today', 'newsroom-ai-assistant' ),
        'chip_unassigned'=> __( 'Unassigned', 'newsroom-ai-assistant' ),
        'chip_done'      => __( 'Done', 'newsroom-ai-assistant' ),
        'col_task'       => __( 'Task', 'newsroom-ai-assistant' ),
        'col_date'       => __( 'Date', 'newsroom-ai-assistant' ),
        'col_writer'     => __( 'Writer', 'newsroom-ai-assistant' ),
        'col_status'     => __( 'Status', 'newsroom-ai-assistant' ),
        'col_actions'    => __( 'Actions', 'newsroom-ai-assistant' ),
        'actions_label'  => __( 'Actions', 'newsroom-ai-assistant' ),
        'actions_edit'   => __( 'Edit task', 'newsroom-ai-assistant' ),
        'actions_done'   => __( 'Mark as done', 'newsroom-ai-assistant' ),
        'actions_delete' => __( 'Delete task', 'newsroom-ai-assistant' ),
        'confirm_delete' => __( 'Delete this task?', 'newsroom-ai-assistant' ),
        'confirm_done'   => __( 'Mark this task as done?', 'newsroom-ai-assistant' ),
        'no_tasks'       => __( 'No tasks found. Create one above!', 'newsroom-ai-assistant' ),
        'loading'        => __( 'Loading...', 'newsroom-ai-assistant' ),
        'sec_settings'   => __( 'Security check failed while saving settings. Please refresh and try again.', 'newsroom-ai-assistant' ),
        'sec_task_save'  => __( 'Security check failed while saving task. Please refresh and try again.', 'newsroom-ai-assistant' ),
        'sec_done'       => __( 'Security check failed for "Mark as done". Please reload and retry.', 'newsroom-ai-assistant' ),
        'sec_delete'     => __( 'Security check failed for task deletion. Please reload and retry.', 'newsroom-ai-assistant' ),
        'status_api_clear'=> __( 'Status API Clear', 'newsroom-ai-assistant' ),
        'no_articles'    => __( 'No articles found.', 'newsroom-ai-assistant' ),
        'invalid_rss'    => __( 'Invalid RSS feed.', 'newsroom-ai-assistant' ),
        'ux_ai_title'    => __( 'UX & AI Engine Toggles', 'newsroom-ai-assistant' ),
        'toggle_gauge'   => __( 'Circular score gauges (editor)', 'newsroom-ai-assistant' ),
        'toggle_gauge_desc' => __( 'Show Focus and Discover scores as donut rings in the post editor sidebar. Frontend is unaffected.', 'newsroom-ai-assistant' ),
        'toggle_onboarding' => __( 'First-use onboarding modal (editor)', 'newsroom-ai-assistant' ),
        'toggle_onboarding_desc' => __( 'One-time welcome popup the first time a writer opens the Newsroom sidebar (stored in browser localStorage).', 'newsroom-ai-assistant' ),
        'toggle_nlp'     => __( 'Bigram matching for related articles', 'newsroom-ai-assistant' ),
        'toggle_nlp_desc' => __( 'Uses two-word phrases (bigrams) to rank Auto-Timeline and tag suggestions. Turn off if you use Manual timeline only or Lite mode.', 'newsroom-ai-assistant' ),
        'toggle_mobile_sheet' => __( 'Mobile bottom sheet sidebar (editor)', 'newsroom-ai-assistant' ),
        'toggle_mobile_sheet_desc' => __( 'On narrow screens, the editor sidebar opens as a swipe-up panel instead of a cramped column.', 'newsroom-ai-assistant' ),
        'toggle_faq_block' => __( 'FAQ quick block (editor)', 'newsroom-ai-assistant' ),
        'toggle_faq_block_desc' => __( 'Off by default. Inserts FAQ microdata in post HTML only when enabled — Google does not use empty FAQ placeholders.', 'newsroom-ai-assistant' ),
        'toggle_floating_ai' => __( 'Floating AI toolbar (editor)', 'newsroom-ai-assistant' ),
        'toggle_floating_ai_desc' => __( 'Shows Rewrite / Shorten / Expand / Simplify when you highlight text in Gutenberg or Classic (Pro BYOK required).', 'newsroom-ai-assistant' ),
        'decay_deprecated' => __( 'Legacy feature — prefer Seasonal radar (Chief Insights) or manual refresh tasks. Off by default on new setups.', 'newsroom-ai-assistant' ),
        'indexing_title' => __( 'Instant Indexing Ping (Google API)', 'newsroom-ai-assistant' ),
        'indexing_enabled' => __( 'Enable Instant Indexing Ping on save', 'newsroom-ai-assistant' ),
        'indexing_publish_only' => __( 'Only ping when post is published', 'newsroom-ai-assistant' ),
        'indexing_token' => __( 'Google Bearer Token (OAuth Access Token)', 'newsroom-ai-assistant' ),
        'indexing_sa_json' => __( 'Google Service Account JSON (recommended)', 'newsroom-ai-assistant' ),
        'indexing_sa_email' => __( 'Service account email', 'newsroom-ai-assistant' ),
        'indexing_sc_property' => __( 'Search Console property', 'newsroom-ai-assistant' ),
        'indexing_sc_property_d' => __( 'Domain property: example.com or sc-domain:example.com · URL prefix: https://www.example.com/ — must match the property in Search Console exactly (any site).', 'newsroom-ai-assistant' ),
        'indexing_sc_property_ph' => __( 'sc-domain:example.com or https://www.example.com/', 'newsroom-ai-assistant' ),
        'indexing_help' => __( 'Uses URL_UPDATED to indexing.googleapis.com asynchronously after save_post.', 'newsroom-ai-assistant' ),
        'indexing_status' => __( 'Last Indexing Ping Status', 'newsroom-ai-assistant' ),
        'indexing_status_ok' => __( 'Success (2xx)', 'newsroom-ai-assistant' ),
        'indexing_status_err' => __( 'Error', 'newsroom-ai-assistant' ),
        'indexing_status_unknown' => __( 'No pings yet', 'newsroom-ai-assistant' ),
        'indexing_status_pending' => __( 'Credentials OK — ping runs when you publish or update a live post', 'newsroom-ai-assistant' ),
        'indexing_test_note' => __( 'Test sends a real ping to your latest published post and updates the status badge (refresh if needed).', 'newsroom-ai-assistant' ),
        'indexing_last_url' => __( 'Last URL', 'newsroom-ai-assistant' ),
        'indexing_last_time' => __( 'Last ping time', 'newsroom-ai-assistant' ),
        'indexing_last_error' => __( 'Last error', 'newsroom-ai-assistant' ),
        'indexing_setup_title' => __( 'Required Setup (without API it will not work)', 'newsroom-ai-assistant' ),
        'indexing_setup_1' => __( 'Create a Google Cloud project and enable the Indexing API.', 'newsroom-ai-assistant' ),
        'indexing_setup_2' => __( 'Create a Service Account key and paste the full JSON below.', 'newsroom-ai-assistant' ),
        'indexing_setup_3' => __( 'Add the service account email as Owner in Search Console for your property.', 'newsroom-ai-assistant' ),
        'indexing_setup_4' => __( 'Enable ping, save a published post, and check status for 2xx.', 'newsroom-ai-assistant' ),
        'gsc_title'        => __( 'GSC Performance sync (Pro)', 'newsroom-ai-assistant' ),
        'gsc_enabled'      => __( 'Enable daily Search Console performance sync', 'newsroom-ai-assistant' ),
        'gsc_enabled_d'    => __( 'Stores clicks/impressions per post (web, Discover, Google News) for Author Performance. Uses the same service account and property URL as above. Enable the Search Console API in Google Cloud.', 'newsroom-ai-assistant' ),
        'gsc_last_sync'    => __( 'Last GSC sync', 'newsroom-ai-assistant' ),
        'gsc_rows'         => __( 'Rows in database', 'newsroom-ai-assistant' ),
        'gsc_last_error'   => __( 'Last GSC error', 'newsroom-ai-assistant' ),
        'gsc_test'         => __( 'Test GSC API', 'newsroom-ai-assistant' ),
        'gsc_sync_now'     => __( 'Sync now', 'newsroom-ai-assistant' ),
        'gsc_next_cron'    => __( 'Next automatic sync', 'newsroom-ai-assistant' ),
        'gsc_cron_off'     => __( 'Automatic sync is off (enable above and save, or add service account).', 'newsroom-ai-assistant' ),
        'timeline_items' => __( 'Articles in Timeline', 'newsroom-ai-assistant' ),
        'timeline_use_tag' => __( 'Use <code>{tag}</code> to render the topic name dynamically.', 'newsroom-ai-assistant' ),
        'timeline_strategy' => __( 'Storytelling Strategy', 'newsroom-ai-assistant' ),
        'timeline_breaking' => __( 'Breaking (3-7 days)', 'newsroom-ai-assistant' ),
        'timeline_ongoing' => __( 'Ongoing (14-30 days)', 'newsroom-ai-assistant' ),
        'timeline_evergreen' => __( 'Evergreen (60-180 days)', 'newsroom-ai-assistant' ),
        'timeline_labels' => __( 'Timeline Labels', 'newsroom-ai-assistant' ),
        'lbl_today' => __( 'Today label', 'newsroom-ai-assistant' ),
        'lbl_yesterday' => __( 'Yesterday label', 'newsroom-ai-assistant' ),
        'lbl_days_ago' => __( 'Days ago pattern (%d placeholder)', 'newsroom-ai-assistant' ),
        'lbl_start' => __( 'Start marker label', 'newsroom-ai-assistant' ),
        'lbl_full_timeline' => __( 'Full timeline button text', 'newsroom-ai-assistant' ),
        'timeline_labels_help' => __( 'Leave any field empty to use the automatic default text.', 'newsroom-ai-assistant' ),
        'ph_today' => __( 'e.g. Today', 'newsroom-ai-assistant' ),
        'ph_yesterday' => __( 'e.g. Yesterday', 'newsroom-ai-assistant' ),
        'ph_days_ago' => __( 'e.g. %d days ago', 'newsroom-ai-assistant' ),
        'ph_start' => __( 'e.g. The Start', 'newsroom-ai-assistant' ),
        'ph_full_timeline' => __( 'e.g. Full timeline →', 'newsroom-ai-assistant' ),
        'timeline_threshold' => __( 'Minimum relevance threshold', 'newsroom-ai-assistant' ),
        'timeline_threshold_desc' => __( 'Higher value = stricter matching (fewer but more relevant results).', 'newsroom-ai-assistant' ),
        'timeline_threshold_presets' => __( 'Suggested presets: Breaking 4 • Ongoing 6 • Evergreen 8', 'newsroom-ai-assistant' ),
        'switch_profile_title' => __( 'Switch profile now', 'newsroom-ai-assistant' ),
        'switch_profile_desc' => __( 'Apply preset defaults instantly based on your site type.', 'newsroom-ai-assistant' ),
        'switch_profile_apply' => __( 'Apply profile preset', 'newsroom-ai-assistant' ),
        'switch_profile_preview' => __( 'Preview changes:', 'newsroom-ai-assistant' ),
        'profile_newsroom' => __( 'Newsroom Profile', 'newsroom-ai-assistant' ),
        'profile_blog' => __( 'Blog Profile', 'newsroom-ai-assistant' ),
        'switch_profile_success' => __( 'Profile preset applied successfully.', 'newsroom-ai-assistant' ),
        'decay_title' => __( 'Content Decay Radar (Auto Alerts)', 'newsroom-ai-assistant' ),
        'publisher_profile_title' => __( 'Publisher performance profile', 'newsroom-ai-assistant' ),
        'publisher_profile_desc' => __( 'One-click presets for every site size. Does not change Newsroom vs Blog site type (below). Existing custom settings are replaced when you apply.', 'newsroom-ai-assistant' ),
        'publisher_profile_apply' => __( 'Apply performance profile', 'newsroom-ai-assistant' ),
        'publisher_profile_success' => __( 'Performance profile applied.', 'newsroom-ai-assistant' ),
        'publisher_profile_active' => __( 'Active profile', 'newsroom-ai-assistant' ),
        'decay_enabled' => __( 'Enable Content Decay Radar', 'newsroom-ai-assistant' ),
        'decay_batch' => __( 'Scan batch size (posts/run)', 'newsroom-ai-assistant' ),
        'decay_batch_desc' => __( 'Weekly scan in small batches (cursor by post ID). Recommended: 15-30 posts per run.', 'newsroom-ai-assistant' ),
        'decay_views_filter' => __( 'Use visits/clicks filter before creating task', 'newsroom-ai-assistant' ),
        'decay_views_key' => __( 'Post views meta key', 'newsroom-ai-assistant' ),
        'decay_views_min' => __( 'Minimum visits to qualify', 'newsroom-ai-assistant' ),
        'decay_views_desc' => __( 'If enabled, low-traffic posts are skipped. Works with common counters like post_views_count.', 'newsroom-ai-assistant' ),
        'decay_detect_btn' => __( 'Auto-detect views key', 'newsroom-ai-assistant' ),
        'decay_detect_ok' => __( 'Detected and saved views key:', 'newsroom-ai-assistant' ),
        'decay_detect_fail' => __( 'No reliable views meta key detected. Set it manually.', 'newsroom-ai-assistant' ),
        'weekly_report_title' => __( 'Weekly newsroom report email', 'newsroom-ai-assistant' ),
        'weekly_report_enabled' => __( 'Send weekly digest to editors', 'newsroom-ai-assistant' ),
        'weekly_report_enabled_desc' => __( 'Runs on the same weekly cron as task cleanup (typically once per week). One email per calendar week.', 'newsroom-ai-assistant' ),
        'weekly_report_recipients' => __( 'Recipients (one email per line)', 'newsroom-ai-assistant' ),
        'weekly_report_recipients_desc' => __( 'Leave empty to email all users with Administrator capability.', 'newsroom-ai-assistant' ),
        'weekly_report_window' => __( 'Metrics window (days)', 'newsroom-ai-assistant' ),
        'weekly_report_test' => __( 'Send test report now', 'newsroom-ai-assistant' ),
        'weekly_report_last' => __( 'Last sent', 'newsroom-ai-assistant' ),
        'pro_lic_title' => __( 'NewsOS Pro license', 'newsroom-ai-assistant' ),
        'pro_lic_key' => __( 'License key', 'newsroom-ai-assistant' ),
        'pro_lic_email' => __( 'Email (optional, for support)', 'newsroom-ai-assistant' ),
        'pro_lic_activate' => __( 'Activate license', 'newsroom-ai-assistant' ),
        'pro_lic_refresh' => __( 'Verify again', 'newsroom-ai-assistant' ),
        'pro_lic_verify_hint' => __( 'Checks with NewsOS that this site is registered for your key and the subscription is still valid. If the server lost the link, it will re-register this URL automatically.', 'newsroom-ai-assistant' ),
        'pro_lic_deactivate' => __( 'Deactivate on this site', 'newsroom-ai-assistant' ),
        'pro_lic_buy' => __( 'Get a license at NewsOS.io', 'newsroom-ai-assistant' ),
        'pro_lic_build' => __( 'Development mode: NEWSAI_PRO_BUILD is enabled (e.g. in wp-config). Customer sites should use a NewsOS license instead.', 'newsroom-ai-assistant' ),
        'pro_lic_status' => __( 'Status', 'newsroom-ai-assistant' ),
        'pro_lic_last_check' => __( 'Last verified', 'newsroom-ai-assistant' ),
        'pro_lic_api_note' => __( 'Validation URL (filter: newsai_pro_license_api_base):', 'newsroom-ai-assistant' ),
        'pro_lic_format_hint' => __( 'Format: NROS-XXXX-XXXX-XXXX (letters A–Z and digits; I, O, 0, 1 are not used).', 'newsroom-ai-assistant' ),
        'pro_lic_paid_through' => __( 'Paid through (subscription)', 'newsroom-ai-assistant' ),
        'pro_lic_expired_local' => __( 'This subscription date has passed. After renewing at NewsOS.io, click Verify again.', 'newsroom-ai-assistant' ),
        'pro_lic_email_required' => __( 'Use the same email you used when purchasing.', 'newsroom-ai-assistant' ),
        'pro_lic_intro' => __( 'Same plugin everywhere — keep it updated from the Plugins screen. Pro stays off until you activate a valid NewsOS license below. One license key per site: if you run multiple sites, buy one license per site at newsos.io.', 'newsroom-ai-assistant' ),
        'pro_lic_registered_site' => __( 'Registered with NewsOS', 'newsroom-ai-assistant' ),
        'pro_lic_registered_hint' => __( 'This URL is sent to newsos.io when you activate or verify. All Pro sites appear in your NewsOS admin under Settings → NewsOS Licenses → Activations (sites).', 'newsroom-ai-assistant' ),
        'usage_registry_title' => __( 'Usage insights (optional)', 'newsroom-ai-assistant' ),
        'usage_registry_label' => __( 'I agree to share anonymous site info with NewsOS', 'newsroom-ai-assistant' ),
        'usage_registry_desc' => __( 'Off by default. If you opt in, we send your public site URL, site name, plugin version, WordPress/PHP versions, and locale to newsos.io once per week to improve the product. No post content, no API keys, no license data. You can withdraw consent anytime by unchecking and saving.', 'newsroom-ai-assistant' ),
        'usage_registry_pro_skip' => __( 'Pro sites are registered automatically via your license — this option applies to the free tier only.', 'newsroom-ai-assistant' ),
        'usage_registry_consent_note' => __( 'Consent recorded:', 'newsroom-ai-assistant' ),
    ];

    if ( function_exists( 'newsai_pro_consume_license_flash_to_settings' ) ) {
        newsai_pro_consume_license_flash_to_settings();
    }

    if ( $can_manage_all && isset( $_POST['newsai_pro_license_action'] ) ) {
        if ( ! isset( $_POST['newsai_pro_license_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newsai_pro_license_nonce'] ) ), 'newsai_pro_license_save' ) ) {
            $security_notice = $i18n['sec_settings'];
        } elseif ( function_exists( 'newsai_pro_flash_license_message' ) ) {
            $lic_do = sanitize_key( wp_unslash( $_POST['newsai_pro_license_action'] ) );
            if ( $lic_do === 'activate' && function_exists( 'newsai_pro_activate_license' ) ) {
                $raw_key = isset( $_POST['newsai_pro_license_key'] ) ? wp_unslash( $_POST['newsai_pro_license_key'] ) : '';
                $raw_em  = isset( $_POST['newsai_pro_license_email'] ) ? wp_unslash( $_POST['newsai_pro_license_email'] ) : '';
                $res     = newsai_pro_activate_license( $raw_key, sanitize_email( $raw_em ) );
                if ( $res['success'] ) {
                    newsai_pro_flash_license_message( 'success', __( 'License activated successfully.', 'newsroom-ai-assistant' ) );
                } else {
                    newsai_pro_flash_license_message( 'error', $res['message'] );
                }
            } elseif ( $lic_do === 'refresh' && function_exists( 'newsai_pro_refresh_license' ) ) {
                $res = newsai_pro_refresh_license();
                if ( $res['success'] ) {
                    newsai_pro_flash_license_message( 'success', __( 'License verified.', 'newsroom-ai-assistant' ) );
                } else {
                    newsai_pro_flash_license_message( 'error', $res['message'] );
                }
            } elseif ( $lic_do === 'deactivate' && function_exists( 'newsai_pro_deactivate_license' ) ) {
                newsai_pro_deactivate_license();
                newsai_pro_flash_license_message( 'success', __( 'License removed from this site.', 'newsroom-ai-assistant' ) );
            }
            wp_safe_redirect( admin_url( 'admin.php?page=newsai-settings&tab=pro' ) );
            exit;
        }
    }

    if (!function_exists('newsai_detect_views_meta_key')) {
        function newsai_detect_views_meta_key() {
            global $wpdb;
            $candidates = ['post_views_count', 'views', 'page_views', 'view_count', 'post_views'];
            $placeholders = implode(',', array_fill(0, count($candidates), '%s'));
            $best_key = $wpdb->get_var(
                $wpdb->prepare(
                    "
                SELECT pm.meta_key, COUNT(*) AS c, MAX(CAST(pm.meta_value AS UNSIGNED)) AS mx
                FROM {$wpdb->postmeta} pm
                INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                WHERE p.post_type = 'post'
                  AND p.post_status = 'publish'
                  AND pm.meta_key IN ({$placeholders})
                  AND pm.meta_value REGEXP '^[0-9]+$'
                GROUP BY pm.meta_key
                HAVING c >= 5
                ORDER BY mx DESC, c DESC
                LIMIT 1
            ",
                    ...$candidates
                )
            );
            return is_string($best_key) && $best_key !== '' ? sanitize_key($best_key) : '';
        }
    }

    if (!function_exists('newsai_apply_site_profile_defaults')) {
        function newsai_apply_site_profile_defaults($profile) {
            if ($profile === 'blog') {
                update_option('newsai_timeline_mode', 'manual');
                update_option('newsai_timeline_strategy', 'evergreen');
                update_option('newsai_timeline_limit', 3);
                update_option('newsai_timeline_relevance_threshold', 8);
                update_option('newsai_ui_circular_gauge', 'yes');
                update_option('newsai_ui_onboarding_modal', 'yes');
                update_option('newsai_advanced_nlp', 'yes');
                update_option('nros_schema_type', 'article');
                update_option('nros_schema_output_mode', 'hybrid');
                update_option('newsai_liveblog_schema_enabled', 'no');
            } else {
                update_option('newsai_timeline_mode', 'auto');
                update_option('newsai_timeline_strategy', 'ongoing');
                update_option('newsai_timeline_limit', 5);
                update_option('newsai_timeline_relevance_threshold', 5);
                update_option('newsai_ui_circular_gauge', 'yes');
                update_option('newsai_ui_onboarding_modal', 'yes');
                update_option('newsai_advanced_nlp', 'yes');
                update_option('nros_schema_type', 'newsarticle');
                update_option('nros_schema_output_mode', 'hybrid');
                update_option('newsai_liveblog_schema_enabled', 'yes');
            }
            update_option('newsai_site_profile', $profile);
        }
    }

    // ==========================================
    // REACT SETTINGS UI TOGGLE (classic settings tab)
    // ==========================================
    if ( isset( $_POST['newsai_toggle_react_settings'] ) ) {
        if (
            ! isset( $_POST['newsai_react_ui_nonce'] )
            || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newsai_react_ui_nonce'] ) ), 'newsai_toggle_react_settings' )
        ) {
            $security_notice = $i18n['sec_settings'];
        } elseif ( function_exists( 'newsai_settings_set_ui_mode' ) ) {
            $enable = isset( $_POST['newsai_settings_ui_enable'] ) && (string) wp_unslash( $_POST['newsai_settings_ui_enable'] ) === '1';
            if ( newsai_settings_set_ui_mode( $enable ? 'react' : 'classic' ) ) {
                $redirect = admin_url( 'admin.php?page=newsai-settings&tab=settings' );
                if ( ! $enable ) {
                    $redirect = add_query_arg( 'ui', 'classic', $redirect );
                }
                wp_safe_redirect( $redirect );
                exit;
            }
            $settings_notice = __( 'Could not change settings UI mode.', 'newsroom-ai-assistant' );
        }
    }

    // ==========================================
    // SAVE SETTINGS
    // ==========================================
    if (isset($_POST['newsai_save_settings'])) {
        if (!isset($_POST['newsai_settings_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['newsai_settings_nonce'])), 'newsai_save_settings_action')) {
            $security_notice = $i18n['sec_settings'];
        } else {

            $nros_schema_opts_before = function_exists( 'nros_schema_snapshot_versioned_options' )
                ? nros_schema_snapshot_versioned_options()
                : [];
        
            $old_lang = (string) get_option( 'newsai_lang', '' );
            if ( $old_lang === '' && function_exists( 'newsai_get_ui_lang' ) ) {
                $old_lang = newsai_get_ui_lang();
            }
            if ( $old_lang === '' ) {
                $old_lang = 'en';
            }
            $new_lang = isset($_POST['lang']) ? sanitize_text_field(wp_unslash($_POST['lang'])) : ( function_exists( 'newsai_get_ui_lang' ) ? newsai_get_ui_lang() : 'en' );
            $supported_ui = function_exists('newsai_supported_languages') ? array_keys( newsai_supported_languages() ) : [ 'el', 'en', 'de', 'es' ];
            if ( ! in_array( $new_lang, $supported_ui, true ) ) {
                $new_lang = function_exists( 'newsai_get_ui_lang' ) ? newsai_get_ui_lang() : 'en';
            }

            update_option('nros_site_name', isset($_POST['sn']) ? sanitize_text_field(wp_unslash($_POST['sn'])) : ''); 
            update_option('newsai_site_desc', isset($_POST['sd']) ? sanitize_text_field(wp_unslash($_POST['sd'])) : ''); 
            update_option('newsai_lang', $new_lang);
            update_option('newsai_geo', isset($_POST['geo']) ? sanitize_text_field(wp_unslash($_POST['geo'])) : ( function_exists( 'newsai_get_target_geo' ) ? newsai_get_target_geo() : 'US' ) );

            if ( function_exists( 'newsai_usage_registry_on_optin_changed' ) ) {
                $was_optin = function_exists( 'newsai_usage_registry_opted_in' ) && newsai_usage_registry_opted_in();
                $now_optin = isset( $_POST['newsai_usage_registry_optin'] );
                if ( $was_optin !== $now_optin ) {
                    newsai_usage_registry_on_optin_changed( $now_optin );
                } elseif ( $now_optin ) {
                    newsai_usage_registry_schedule();
                }
            }

        update_option('nros_primary_city', isset($_POST['primary_city']) ? sanitize_text_field(wp_unslash($_POST['primary_city'])) : '');
        update_option( 'nros_primary_city_article_fallback', isset( $_POST['primary_city_article_fallback'] ) ? 'yes' : 'no' );

        $nros_schema_type_before = (string) get_option( 'nros_schema_type', 'newsarticle' );
        update_option('nros_schema_type', isset($_POST['schema_type']) ? sanitize_text_field(wp_unslash($_POST['schema_type'])) : 'newsarticle');
        $nros_schema_type_after = (string) get_option( 'nros_schema_type', 'newsarticle' );
        if ( $nros_schema_type_before === 'none' && $nros_schema_type_after !== 'none' && function_exists( 'nros_schema_on_schema_enabled' ) ) {
            nros_schema_on_schema_enabled();
        }
        if ( $nros_schema_type_after === 'none' && function_exists( 'nros_schema_schedule_legacy_warm_cron' ) ) {
            nros_schema_schedule_legacy_warm_cron();
        }
        update_option('nros_org_type', isset($_POST['org_type']) ? sanitize_text_field(wp_unslash($_POST['org_type'])) : 'NewsMediaOrganization');
        update_option('nros_schema_output_mode', isset($_POST['schema_output_mode']) ? sanitize_text_field(wp_unslash($_POST['schema_output_mode'])) : 'hybrid');
        $rich = isset($_POST['nros_schema_richness']) ? sanitize_key(wp_unslash($_POST['nros_schema_richness'])) : 'balanced';
        if (!in_array($rich, ['minimal', 'balanced', 'full'], true)) {
            $rich = 'balanced';
        }
        update_option('nros_schema_richness', $rich);
        $ab = isset($_POST['nros_schema_article_body']) ? sanitize_key(wp_unslash($_POST['nros_schema_article_body'])) : 'full';
        if (!in_array($ab, ['omit', 'full', 'limited'], true)) {
            $ab = 'full';
        }
        update_option('nros_schema_article_body', $ab);
        $abw = isset($_POST['nros_schema_article_body_words']) ? (int) $_POST['nros_schema_article_body_words'] : 200;
        $abw = max(30, min(2000, $abw));
        update_option('nros_schema_article_body_words', $abw);
        // Megasite mode is intentionally NOT a versioned option (toggling it must not invalidate caches).
        $megasite_before = ( get_option( 'nros_schema_megasite_mode', 'yes' ) === 'yes' );
        update_option( 'nros_schema_megasite_mode', isset( $_POST['nros_schema_megasite_mode'] ) ? 'yes' : 'no' );
        $megasite_after = ( get_option( 'nros_schema_megasite_mode', 'yes' ) === 'yes' );
        $warm_before = ( get_option( 'nros_schema_background_warm', 'yes' ) === 'yes' );
        update_option( 'nros_schema_background_warm', isset( $_POST['nros_schema_background_warm'] ) ? 'yes' : 'no' );
        $warm_after = ( get_option( 'nros_schema_background_warm', 'yes' ) === 'yes' );
        $nightly_before = ( get_option( 'nros_schema_nightly_warm', 'no' ) === 'yes' );
        update_option( 'nros_schema_nightly_warm', isset( $_POST['nros_schema_nightly_warm'] ) ? 'yes' : 'no' );
        $nightly_start_before = (string) get_option( 'nros_schema_nightly_warm_start', '02:00' );
        $nightly_end_before   = (string) get_option( 'nros_schema_nightly_warm_end', '06:00' );
        $nightly_start = function_exists( 'nros_schema_sanitize_hm' )
            ? nros_schema_sanitize_hm( isset( $_POST['nros_schema_nightly_warm_start'] ) ? wp_unslash( $_POST['nros_schema_nightly_warm_start'] ) : '02:00', 2, 0 )
            : '02:00';
        $nightly_end = function_exists( 'nros_schema_sanitize_hm' )
            ? nros_schema_sanitize_hm( isset( $_POST['nros_schema_nightly_warm_end'] ) ? wp_unslash( $_POST['nros_schema_nightly_warm_end'] ) : '06:00', 6, 0 )
            : '06:00';
        update_option( 'nros_schema_nightly_warm_start', $nightly_start );
        update_option( 'nros_schema_nightly_warm_end', $nightly_end );
        $nightly_after = ( get_option( 'nros_schema_nightly_warm', 'no' ) === 'yes' );
        if ( ( $megasite_before !== $megasite_after || $warm_before !== $warm_after || $nightly_before !== $nightly_after || $nightly_start_before !== $nightly_start || $nightly_end_before !== $nightly_end ) && function_exists( 'nros_schema_schedule_legacy_warm_cron' ) ) {
            nros_schema_schedule_legacy_warm_cron();
        }
        if ( function_exists( 'nros_schema_schedule_nightly_warm_events' ) ) {
            nros_schema_schedule_nightly_warm_events( true );
        }
        update_option('newsai_liveblog_schema_enabled', isset($_POST['liveblog_schema_enabled']) ? 'yes' : 'no');
        $bh = isset($_POST['newsai_breaking_expire_hours']) ? (int) $_POST['newsai_breaking_expire_hours'] : 48;
        if (!in_array($bh, [24, 48, 72], true)) {
            $bh = 48;
        }
        update_option('newsai_breaking_expire_hours', $bh);
        update_option('newsai_breaking_badge_enabled', isset($_POST['newsai_breaking_badge_enabled']) ? 'yes' : 'no');
        update_option('nros_org_logo_url', isset($_POST['org_logo_url']) ? esc_url_raw(wp_unslash($_POST['org_logo_url'])) : '');
        update_option('nros_org_legal_name', isset($_POST['org_legal_name']) ? sanitize_text_field(wp_unslash($_POST['org_legal_name'])) : '');
        update_option('nros_org_alternate_name', isset($_POST['org_alternate_name']) ? sanitize_text_field(wp_unslash($_POST['org_alternate_name'])) : '');
        update_option('nros_org_email', isset($_POST['org_email']) ? sanitize_email(wp_unslash($_POST['org_email'])) : '');
        update_option('nros_org_phone', isset($_POST['org_phone']) ? sanitize_text_field(wp_unslash($_POST['org_phone'])) : '');
        update_option('nros_org_tax_id', isset($_POST['org_tax_id']) ? sanitize_text_field(wp_unslash($_POST['org_tax_id'])) : '');
        update_option('nros_org_vat_id', isset($_POST['org_vat_id']) ? sanitize_text_field(wp_unslash($_POST['org_vat_id'])) : '');
        update_option('nros_org_iso6523', isset($_POST['org_iso6523']) ? sanitize_text_field(wp_unslash($_POST['org_iso6523'])) : '');
        update_option('nros_org_naics', isset($_POST['org_naics']) ? sanitize_text_field(wp_unslash($_POST['org_naics'])) : '');
        update_option('nros_org_address_country', isset($_POST['org_address_country']) ? sanitize_text_field(wp_unslash($_POST['org_address_country'])) : '');
        update_option('nros_org_address_locality', isset($_POST['org_address_locality']) ? sanitize_text_field(wp_unslash($_POST['org_address_locality'])) : '');
        update_option('nros_org_address_region', isset($_POST['org_address_region']) ? sanitize_text_field(wp_unslash($_POST['org_address_region'])) : '');
        update_option('nros_org_address_postal_code', isset($_POST['org_address_postal_code']) ? sanitize_text_field(wp_unslash($_POST['org_address_postal_code'])) : '');
        update_option('nros_org_address_street', isset($_POST['org_address_street']) ? sanitize_text_field(wp_unslash($_POST['org_address_street'])) : '');
        update_option('nros_social_links', isset($_POST['social_links']) ? sanitize_textarea_field(wp_unslash($_POST['social_links'])) : '');
        update_option( 'nros_org_publishing_principles_url', isset( $_POST['org_publishing_principles_url'] ) ? esc_url_raw( wp_unslash( $_POST['org_publishing_principles_url'] ) ) : '' );
        update_option( 'nros_org_corrections_policy_url', isset( $_POST['org_corrections_policy_url'] ) ? esc_url_raw( wp_unslash( $_POST['org_corrections_policy_url'] ) ) : '' );
        update_option( 'nros_org_ownership_funding_url', isset( $_POST['org_ownership_funding_url'] ) ? esc_url_raw( wp_unslash( $_POST['org_ownership_funding_url'] ) ) : '' );
        update_option( 'nros_org_actionable_feedback_url', isset( $_POST['org_actionable_feedback_url'] ) ? esc_url_raw( wp_unslash( $_POST['org_actionable_feedback_url'] ) ) : '' );
        update_option('newsai_custom_feed_pages', isset($_POST['feed_pages']) ? sanitize_text_field(wp_unslash($_POST['feed_pages'])) : '');
        $about_pid = isset( $_POST['about_page_id'] ) ? (int) $_POST['about_page_id'] : 0;
        if ( $about_pid > 0 && get_post_type( $about_pid ) !== 'page' ) {
            $about_pid = 0;
        }
        update_option( 'newsai_about_page_id', max( 0, $about_pid ) );
        if (array_key_exists('speakable', $_POST)) {
            update_option('newsai_speakable_selectors', sanitize_text_field(wp_unslash($_POST['speakable'])));
        }
        update_option( 'nros_speakable_snippet_enabled', isset( $_POST['nros_speakable_snippet_enabled'] ) ? 'yes' : 'no' );
        $snip_max = isset( $_POST['nros_speakable_snippet_max_chars'] ) ? (int) $_POST['nros_speakable_snippet_max_chars'] : 400;
        $snip_max = max( 80, min( 2000, $snip_max ) );
        update_option( 'nros_speakable_snippet_max_chars', $snip_max );
        update_option( 'nros_speakable_snippet_strip_body', isset( $_POST['nros_speakable_snippet_strip_body'] ) ? 'yes' : 'no' );
        if ( function_exists( 'nros_schema_maybe_bump_global_version' ) && ! empty( $nros_schema_opts_before ) ) {
            nros_schema_maybe_bump_global_version( $nros_schema_opts_before );
        }
        update_option('newsai_timeline_days', isset($_POST['t_days']) ? intval($_POST['t_days']) : 30);
        update_option('newsai_timeline_para', isset($_POST['t_para']) ? intval($_POST['t_para']) : -1);
        $submitted_t_mode = isset($_POST['t_mode']) ? sanitize_text_field(wp_unslash($_POST['t_mode'])) : 'auto';
        if (!in_array($submitted_t_mode, ['auto', 'manual'], true)) {
            $submitted_t_mode = 'auto';
        }
        // Auto-Timeline auto mode is gated to Pro; persist the user choice as 'manual' otherwise.
        if ($submitted_t_mode === 'auto' && function_exists('newsai_is_pro') && !newsai_is_pro()) {
            $submitted_t_mode = 'manual';
        }
        update_option('newsai_timeline_mode', $submitted_t_mode);
        update_option('newsai_timeline_limit', isset($_POST['t_limit']) ? intval($_POST['t_limit']) : 4);
        update_option('newsai_timeline_strategy', isset($_POST['t_strategy']) ? sanitize_text_field(wp_unslash($_POST['t_strategy'])) : 'ongoing');
        update_option('newsai_timeline_relevance_threshold', isset($_POST['t_relevance']) ? intval($_POST['t_relevance']) : 5);
        $timeline_label_fields = [
            'newsai_timeline_label_today'     => 't_lbl_today',
            'newsai_timeline_label_yesterday' => 't_lbl_yesterday',
            'newsai_timeline_label_days_ago'  => 't_lbl_days_ago',
            'newsai_timeline_label_start'     => 't_lbl_start',
            'newsai_timeline_label_full'      => 't_lbl_full',
        ];
        foreach ( $timeline_label_fields as $opt_key => $post_key ) {
            $raw = isset( $_POST[ $post_key ] ) ? sanitize_text_field( wp_unslash( $_POST[ $post_key ] ) ) : '';
            if ( trim( $raw ) === '' ) {
                delete_option( $opt_key );
            } else {
                update_option( $opt_key, $raw );
            }
        }
        $t_heading_raw = isset( $_POST['t_heading'] ) ? sanitize_text_field( wp_unslash( $_POST['t_heading'] ) ) : '';
        if ( trim( $t_heading_raw ) === '' ) {
            delete_option( 'newsai_timeline_heading' );
        } else {
            update_option( 'newsai_timeline_heading', $t_heading_raw );
        }
        update_option('newsai_ui_circular_gauge', isset($_POST['ui_circular_gauge']) ? 'yes' : 'no');
        update_option('newsai_ui_onboarding_modal', isset($_POST['ui_onboarding_modal']) ? 'yes' : 'no');
        update_option('newsai_advanced_nlp', isset($_POST['advanced_nlp']) ? 'yes' : 'no');
        update_option( 'newsai_editor_faq_enabled', isset( $_POST['editor_faq_enabled'] ) ? 'yes' : 'no' );
        update_option( 'newsai_editor_floating_ai', isset( $_POST['editor_floating_ai'] ) ? 'yes' : 'no' );
        // Tag duplicate guard toggle — only Pro users can flip the runtime behavior, but the option
        // is stored regardless so a freshly-activated license picks the user's preference up.
        if (function_exists('newsai_is_pro') && newsai_is_pro()) {
            update_option('newsai_tag_guard_enabled', isset($_POST['tag_guard_enabled']) ? 'yes' : 'no');
        }
        if ( isset( $_POST['tag_pool_size'] ) && function_exists( 'newsai_tag_pool_size_choices' ) ) {
            $allowed_pool = array_keys( newsai_tag_pool_size_choices() );
            $new_pool     = (int) $_POST['tag_pool_size'];
            if ( in_array( $new_pool, $allowed_pool, true ) ) {
                $prev_pool = function_exists( 'newsai_tag_pool_size_get' ) ? newsai_tag_pool_size_get() : 800;
                update_option( 'newsai_tag_pool_size', $new_pool );
                if ( $new_pool !== $prev_pool && function_exists( 'newsai_tag_pool_size_clear_caches' ) ) {
                    newsai_tag_pool_size_clear_caches();
                }
            }
        }
        if ( isset( $_POST['tag_pool_editor_size'] ) && function_exists( 'newsai_tag_pool_editor_size_choices' ) ) {
            $allowed_editor = array_keys( newsai_tag_pool_editor_size_choices() );
            $new_editor     = (int) $_POST['tag_pool_editor_size'];
            if ( in_array( $new_editor, $allowed_editor, true ) ) {
                $prev_editor = function_exists( 'newsai_tag_pool_editor_size_get' ) ? newsai_tag_pool_editor_size_get() : 300;
                update_option( 'newsai_tag_pool_editor_size', $new_editor );
                if ( $new_editor !== $prev_editor && function_exists( 'newsai_tag_pool_size_clear_caches' ) ) {
                    newsai_tag_pool_size_clear_caches();
                }
            }
        }
        update_option( 'newsai_wikidata_enrich_enabled', isset( $_POST['wikidata_enrich_enabled'] ) ? 'yes' : 'no' );
        if ( isset( $_POST['sem_links_profile'] ) && function_exists( 'newsai_sem_links_profiles' ) ) {
            $sem_profiles = newsai_sem_links_profiles();
            $sem_key      = sanitize_key( wp_unslash( (string) $_POST['sem_links_profile'] ) );
            if ( isset( $sem_profiles[ $sem_key ] ) ) {
                update_option( 'newsai_sem_links_profile', $sem_key );
            }
        }

        // Team workflow (messaging + notifications) — Pro-only writes. The toggles render but
        // are disabled in the form for non-Pro users, so we only persist when Pro is active.
        if (function_exists('newsai_is_pro') && newsai_is_pro()) {
            update_option('newsai_task_messaging_enabled', isset($_POST['task_messaging_enabled']) ? 'yes' : 'no');
            update_option('newsai_task_email_enabled',     isset($_POST['task_email_enabled'])     ? 'yes' : 'no');
            update_option('newsai_task_email_assigned',    isset($_POST['task_email_assigned'])    ? 'yes' : 'no');
            update_option('newsai_task_email_message',     isset($_POST['task_email_message'])     ? 'yes' : 'no');
            update_option('newsai_task_email_done',        isset($_POST['task_email_done'])        ? 'yes' : 'no');

            $retention_days = isset($_POST['task_retention_days']) ? (int) $_POST['task_retention_days'] : 30;
            if ($retention_days < 0)   { $retention_days = 0; }
            if ($retention_days > 365) { $retention_days = 365; }
            update_option('newsai_task_messages_retention_days', $retention_days);
        }

        if ( current_user_can( 'manage_options' ) ) {
            update_option( 'newsai_weekly_report_enabled', isset( $_POST['weekly_report_enabled'] ) ? 'yes' : 'no' );
            $wr_days = isset( $_POST['weekly_report_window_days'] ) ? (int) $_POST['weekly_report_window_days'] : 7;
            if ( ! in_array( $wr_days, [ 7, 14, 30 ], true ) ) {
                $wr_days = 7;
            }
            update_option( 'newsai_weekly_report_window_days', $wr_days );
            $wr_recipients = isset( $_POST['weekly_report_recipients'] ) ? sanitize_textarea_field( wp_unslash( (string) $_POST['weekly_report_recipients'] ) ) : '';
            update_option( 'newsai_weekly_report_recipients', $wr_recipients );
        }

        // AI Assist (BYOK) — Pro-only writes. Keys are stored as non-autoloaded options and
        // submitting an empty field keeps the previously saved key (common UX for secrets).
        if (function_exists('newsai_is_pro') && newsai_is_pro()) {
            $ai_provider_in = isset($_POST['ai_provider']) ? sanitize_key(wp_unslash($_POST['ai_provider'])) : '';
            if (!in_array($ai_provider_in, ['', 'openai', 'gemini', 'groq'], true)) {
                $ai_provider_in = '';
            }
            update_option('newsai_ai_provider', $ai_provider_in, false);

            if ( isset( $_POST['ai_openai_api_key'] ) && ( ! function_exists( 'newsai_secret_is_locked' ) || ! newsai_secret_is_locked( 'openai_api_key' ) ) ) {
                $k = trim( (string) wp_unslash( $_POST['ai_openai_api_key'] ) );
                if ( $k !== '' ) {
                    if ( function_exists( 'newsai_secret_update_option' ) ) {
                        newsai_secret_update_option( 'openai_api_key', sanitize_text_field( $k ) );
                    } else {
                        update_option( 'newsai_ai_openai_api_key', sanitize_text_field( $k ), false );
                    }
                }
            }
            if (isset($_POST['ai_openai_model'])) {
                $m = sanitize_text_field(wp_unslash($_POST['ai_openai_model']));
                if ($m === '') { $m = defined('NEWSAI_AI_DEFAULT_OPENAI_MODEL') ? NEWSAI_AI_DEFAULT_OPENAI_MODEL : 'gpt-4o-mini'; }
                update_option('newsai_ai_openai_model', $m, false);
            }
            if ( isset( $_POST['ai_gemini_api_key'] ) && ( ! function_exists( 'newsai_secret_is_locked' ) || ! newsai_secret_is_locked( 'gemini_api_key' ) ) ) {
                $k = trim( (string) wp_unslash( $_POST['ai_gemini_api_key'] ) );
                if ( $k !== '' ) {
                    if ( function_exists( 'newsai_secret_update_option' ) ) {
                        newsai_secret_update_option( 'gemini_api_key', sanitize_text_field( $k ) );
                    } else {
                        update_option( 'newsai_ai_gemini_api_key', sanitize_text_field( $k ), false );
                    }
                }
            }
            if (isset($_POST['ai_gemini_model'])) {
                $m = sanitize_text_field(wp_unslash($_POST['ai_gemini_model']));
                if ($m === '') { $m = defined('NEWSAI_AI_DEFAULT_GEMINI_MODEL') ? NEWSAI_AI_DEFAULT_GEMINI_MODEL : 'gemini-2.5-flash'; }
                update_option('newsai_ai_gemini_model', $m, false);
            }
            if ( isset( $_POST['ai_groq_api_key'] ) && ( ! function_exists( 'newsai_secret_is_locked' ) || ! newsai_secret_is_locked( 'groq_api_key' ) ) ) {
                $k = trim( (string) wp_unslash( $_POST['ai_groq_api_key'] ) );
                if ( $k !== '' ) {
                    if ( function_exists( 'newsai_secret_update_option' ) ) {
                        newsai_secret_update_option( 'groq_api_key', sanitize_text_field( $k ) );
                    } else {
                        update_option( 'newsai_ai_groq_api_key', sanitize_text_field( $k ), false );
                    }
                }
            }
            if (isset($_POST['ai_groq_model'])) {
                $m = sanitize_text_field(wp_unslash($_POST['ai_groq_model']));
                if ($m === '') { $m = defined('NEWSAI_AI_DEFAULT_GROQ_MODEL') ? NEWSAI_AI_DEFAULT_GROQ_MODEL : 'llama-3.3-70b-versatile'; }
                update_option('newsai_ai_groq_model', $m, false);
            }
            if (isset($_POST['ai_daily_limit'])) {
                $lim = (int) $_POST['ai_daily_limit'];
                if ($lim < 0) { $lim = 0; }
                if ($lim > 1000) { $lim = 1000; }
                update_option('newsai_ai_daily_limit_per_user', $lim, false);
            }
            update_option( 'newsai_ai_alt_enabled', isset( $_POST['ai_alt_enabled'] ) ? 'yes' : 'no' );
            update_option( 'newsai_ai_alt_on_upload', isset( $_POST['ai_alt_on_upload'] ) ? 'yes' : 'no' );
        }
        update_option('newsai_mobile_bottom_sheet', isset($_POST['ui_mobile_bottom_sheet']) ? 'yes' : 'no');
        // Instant indexing toggles — only persisted when Pro is active so a lapsed license
        // immediately halts outgoing pings (the queue itself also re-checks newsai_is_pro()).
        if (function_exists('newsai_is_pro') && newsai_is_pro()) {
            update_option('newsai_indexing_enabled', isset($_POST['indexing_enabled']) ? 'yes' : 'no');
            update_option('newsai_indexing_publish_only', isset($_POST['indexing_publish_only']) ? 'yes' : 'no');
            update_option( 'newsai_gsc_enabled', isset( $_POST['gsc_enabled'] ) ? 'yes' : 'no' );
            update_option( 'newsai_gsc_query_sync_enabled', isset( $_POST['gsc_query_sync_enabled'] ) ? 'yes' : 'no' );
            $indexnow_on = isset( $_POST['indexnow_enabled'] ) ? 'yes' : 'no';
            update_option( 'newsai_indexnow_enabled', $indexnow_on );
            if ( $indexnow_on === 'yes' && function_exists( 'newsai_indexnow_flush_rewrite_rules' ) ) {
                newsai_indexnow_flush_rewrite_rules();
            }
        }
        update_option('newsai_indexing_bearer_token', isset($_POST['indexing_bearer_token']) ? sanitize_text_field(wp_unslash($_POST['indexing_bearer_token'])) : '');
        if ( isset( $_POST['indexing_service_json'] ) && trim( (string) wp_unslash( $_POST['indexing_service_json'] ) ) !== '' && function_exists( 'newsai_save_indexing_service_json_from_request' ) ) {
            $sa_inline = newsai_save_indexing_service_json_from_request( $_POST );
            if ( is_wp_error( $sa_inline ) ) {
                add_settings_error( 'newsai_settings', 'newsai_indexing_sa_inline', $sa_inline->get_error_message(), 'error' );
            }
        }
        $sc_prop_raw = isset( $_POST['indexing_sc_property'] ) ? wp_unslash( $_POST['indexing_sc_property'] ) : '';
        $sc_prop     = function_exists( 'newsai_sanitize_sc_property' )
            ? newsai_sanitize_sc_property( $sc_prop_raw )
            : esc_url_raw( (string) $sc_prop_raw );
        update_option( 'newsai_indexing_sc_property', $sc_prop, false );
        if ( function_exists( 'newsai_crux_save_settings' ) ) {
            newsai_crux_save_settings();
        }
        if ( function_exists( 'newsai_gsc_schedule_cron' ) ) {
            newsai_gsc_schedule_cron();
        }
        update_option( 'newsai_lite_mode', isset( $_POST['newsai_lite_mode'] ) ? 'yes' : 'no' );
        update_option( 'newsai_large_site_mode', isset( $_POST['newsai_large_site_mode'] ) ? 'yes' : 'no' );
        update_option( 'newsai_gsc_traffic_drop_enabled', isset( $_POST['gsc_traffic_drop_enabled'] ) ? 'yes' : 'no' );
        $drop_days = isset( $_POST['gsc_traffic_drop_days'] ) ? (int) $_POST['gsc_traffic_drop_days'] : 28;
        if ( $drop_days < 7 ) {
            $drop_days = 7;
        }
        if ( $drop_days > 90 ) {
            $drop_days = 90;
        }
        update_option( 'newsai_gsc_traffic_drop_days', $drop_days, false );
        $drop_min_prev = isset( $_POST['gsc_traffic_drop_min_prev'] ) ? (int) $_POST['gsc_traffic_drop_min_prev'] : 25;
        if ( $drop_min_prev < 5 ) {
            $drop_min_prev = 5;
        }
        update_option( 'newsai_gsc_traffic_drop_min_prev_clicks', $drop_min_prev, false );
        $drop_min_loss = isset( $_POST['gsc_traffic_drop_min_loss'] ) ? (int) $_POST['gsc_traffic_drop_min_loss'] : 15;
        if ( $drop_min_loss < 5 ) {
            $drop_min_loss = 5;
        }
        update_option( 'newsai_gsc_traffic_drop_min_loss', $drop_min_loss, false );
        $drop_channel = isset( $_POST['gsc_traffic_drop_channel'] ) ? sanitize_key( wp_unslash( $_POST['gsc_traffic_drop_channel'] ) ) : 'web';
        if ( ! in_array( $drop_channel, [ 'web', 'discover', 'googleNews' ], true ) ) {
            $drop_channel = 'web';
        }
        update_option( 'newsai_gsc_traffic_drop_channel', $drop_channel, false );

        update_option( 'newsai_seasonal_radar_enabled', isset( $_POST['seasonal_radar_enabled'] ) ? 'yes' : 'no' );
        $seasonal_lead = isset( $_POST['seasonal_lead_days'] ) ? (int) $_POST['seasonal_lead_days'] : 30;
        if ( ! in_array( $seasonal_lead, [ 14, 30, 45 ], true ) ) {
            $seasonal_lead = 30;
        }
        update_option( 'newsai_seasonal_lead_days', $seasonal_lead );
        $seasonal_min = isset( $_POST['seasonal_min_clicks'] ) ? (int) $_POST['seasonal_min_clicks'] : 25;
        if ( $seasonal_min < 5 ) {
            $seasonal_min = 5;
        }
        if ( $seasonal_min > 5000 ) {
            $seasonal_min = 5000;
        }
        update_option( 'newsai_seasonal_min_clicks', $seasonal_min );
        update_option( 'newsai_seasonal_email_enabled', isset( $_POST['seasonal_email_enabled'] ) ? 'yes' : 'no' );
        if ( function_exists( 'newsai_schedule_seasonal_radar' ) ) {
            newsai_schedule_seasonal_radar();
        }
        if ( function_exists( 'newsai_seasonal_radar_compute' ) && get_option( 'newsai_seasonal_radar_enabled', 'yes' ) === 'yes' ) {
            newsai_seasonal_radar_compute();
        }

        if ($old_lang !== $new_lang && function_exists('newsai_get_default_prompt')) {
            update_option('newsai_prompt_title', newsai_get_default_prompt('title', $new_lang));
            update_option('newsai_prompt_rewrite', newsai_get_default_prompt('rewrite', $new_lang));
            update_option('newsai_prompt_seo', newsai_get_default_prompt('seo', $new_lang));
        } else {
            update_option('newsai_prompt_title', isset($_POST['p_title']) ? sanitize_textarea_field(wp_unslash($_POST['p_title'])) : '');
            update_option('newsai_prompt_rewrite', isset($_POST['p_rewrite']) ? sanitize_textarea_field(wp_unslash($_POST['p_rewrite'])) : '');
            update_option('newsai_prompt_seo', isset($_POST['p_seo']) ? sanitize_textarea_field(wp_unslash($_POST['p_seo'])) : '');
        }
        
        if ( function_exists( 'newsai_clear_settings_save_transients' ) ) {
            newsai_clear_settings_save_transients();
        }

            echo "<script>window.location.href = window.location.href;</script>"; 
        }
    }

    if (isset($_POST['newsai_save_indexing_sa'])) {
        if (!isset($_POST['newsai_indexing_sa_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['newsai_indexing_sa_nonce'])), 'newsai_save_indexing_sa_action')) {
            $security_notice = $i18n['sec_settings'];
        } elseif (!current_user_can('manage_options')) {
            $security_notice = $i18n['sec_settings'];
        } elseif (function_exists('newsai_save_indexing_service_json_from_request')) {
            $sa_result = newsai_save_indexing_service_json_from_request($_POST);
            if (is_wp_error($sa_result)) {
                add_settings_error('newsai_settings', 'newsai_indexing_sa_err', $sa_result->get_error_message(), 'error');
            } else {
                add_settings_error(
                    'newsai_settings',
                    'newsai_indexing_sa_ok',
                    isset($_POST['indexing_service_json_clear']) && $_POST['indexing_service_json_clear'] === '1'
                        ? __( 'Service account JSON removed.', 'newsroom-ai-assistant' )
                        : __( 'Service account JSON saved.', 'newsroom-ai-assistant' ),
                    'updated'
                );
            }
            wp_safe_redirect(
                add_query_arg(
                    [
                        'page'                  => 'newsai-settings',
                        'tab'                   => 'settings',
                        'newsai_settings_pane'  => 'indexing',
                    ],
                    admin_url( 'admin.php' )
                )
            );
            exit;
        }
    }

    if (isset($_POST['newsai_save_competitor']) && isset($_POST['newsai_comp_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['newsai_comp_nonce'])), 'save_comp')) {
        update_option('newsai_competitor_rss', sanitize_textarea_field(wp_unslash($_POST['comp_rss'])));
        echo "<script>window.location.href = window.location.href;</script>"; 
    }
    if (isset($_POST['newsai_schema_warm_batch'])) {
        if (!isset($_POST['newsai_settings_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['newsai_settings_nonce'])), 'newsai_save_settings_action')) {
            $security_notice = $i18n['sec_settings'];
        } elseif (!current_user_can('manage_options')) {
            $security_notice = $i18n['sec_settings'];
        } else {
            $warmed = function_exists('nros_schema_warm_posts_batch') ? nros_schema_warm_posts_batch(25) : 0;
            add_settings_error(
                'newsai_settings',
                'newsai_schema_warm_ok',
                sprintf(
                    /* translators: %d: number of posts warmed */
                    __( 'Schema cache warmed for %d published post(s). Run again for the next batch, or let the daily cron continue.', 'newsroom-ai-assistant' ),
                    (int) $warmed
                ),
                'updated'
            );
            echo "<script>window.location.href = window.location.href;</script>";
        }
    }
    if ( isset( $_POST['newsai_schema_warm_archives'] ) ) {
        if ( ! isset( $_POST['newsai_settings_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newsai_settings_nonce'] ) ), 'newsai_save_settings_action' ) ) {
            $security_notice = $i18n['sec_settings'];
        } elseif ( ! current_user_can( 'manage_options' ) ) {
            $security_notice = $i18n['sec_settings'];
        } else {
            if ( function_exists( 'nros_schema_enqueue_default_home_archives' ) ) {
                nros_schema_enqueue_default_home_archives();
            }
            $arch_warmed = function_exists( 'nros_schema_warm_archives_batch' ) ? nros_schema_warm_archives_batch( 3 ) : 0;
            add_settings_error(
                'newsai_settings',
                'newsai_schema_warm_archives_ok',
                sprintf(
                    /* translators: %d: number of archive pages warmed */
                    __( 'Home/archive schema warmed for %d page(s) (ItemList + CollectionPage). View source on your news feed to verify.', 'newsroom-ai-assistant' ),
                    (int) $arch_warmed
                ),
                'updated'
            );
            echo '<script>window.location.href = window.location.href;</script>';
        }
    }
    if (isset($_POST['newsai_switch_publisher_profile'])) {
        if (!isset($_POST['newsai_publisher_profile_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['newsai_publisher_profile_nonce'])), 'newsai_switch_publisher_profile_action')) {
            $security_notice = $i18n['sec_settings'];
        } else {
            $target = isset($_POST['publisher_profile']) ? sanitize_key(wp_unslash($_POST['publisher_profile'])) : 'standard';
            if (function_exists('newsai_apply_publisher_profile')) {
                newsai_apply_publisher_profile($target);
            }
            add_settings_error('newsai_settings', 'newsai_publisher_profile_ok', $i18n['publisher_profile_success'], 'updated');
        }
    }

    if (isset($_POST['newsai_switch_profile'])) {
        if (!isset($_POST['newsai_profile_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['newsai_profile_nonce'])), 'newsai_switch_profile_action')) {
            $security_notice = $i18n['sec_settings'];
        } else {
            $target_profile = isset($_POST['site_profile']) ? sanitize_text_field(wp_unslash($_POST['site_profile'])) : 'newsroom';
            if (!in_array($target_profile, ['newsroom', 'blog'], true)) {
                $target_profile = 'newsroom';
            }
            newsai_apply_site_profile_defaults($target_profile);
            add_settings_error('newsai_settings', 'newsai_profile_ok', $i18n['switch_profile_success'], 'updated');
            echo "<script>window.location.href = window.location.href;</script>";
        }
    }
    $comp_rss = get_option('newsai_competitor_rss', '');
    $index_last_code = (int) get_option('newsai_indexing_last_code', 0);
    $index_last_ping = (int) get_option('newsai_indexing_last_ping', 0);
    $index_last_url = (string) get_option('newsai_indexing_last_url', '');
    $index_last_error = (string) get_option('newsai_indexing_last_error', '');
    $index_last_success_code = (int) get_option('newsai_indexing_last_success_code', 0);
    $index_last_success_ping = (int) get_option('newsai_indexing_last_success_ping', 0);
    $index_last_success_url  = (string) get_option('newsai_indexing_last_success_url', '');
    $index_health_label = __( 'Unknown', 'newsroom-ai-assistant' );
    $index_health_color = '#64748b';
    if ( $index_last_success_ping > 0 && $index_last_success_ping >= ( time() - ( 7 * DAY_IN_SECONDS ) ) ) {
        $index_health_label = __( 'Healthy', 'newsroom-ai-assistant' );
        $index_health_color = '#15803d';
    } elseif ( $index_last_ping > 0 && $index_last_error !== '' ) {
        $index_health_label = __( 'Degraded', 'newsroom-ai-assistant' );
        $index_health_color = '#b91c1c';
    }
    $index_service_email = (string) get_option('newsai_indexing_service_email', '');
    $index_sc_property = (string) get_option('newsai_indexing_sc_property', home_url('/'));
    $gsc_last_sync     = (string) get_option( 'newsai_gsc_last_sync', '' );
    $gsc_last_count    = (int) get_option( 'newsai_gsc_last_count', 0 );
    $gsc_last_error    = (string) get_option( 'newsai_gsc_last_error', '' );
    $gsc_db_rows       = function_exists( 'newsai_gsc_row_count' ) ? newsai_gsc_row_count() : 0;
    $gsc_next_cron_ts  = function_exists( 'newsai_gsc_should_schedule_cron' ) && newsai_gsc_should_schedule_cron()
        ? (int) wp_next_scheduled( 'newsai_gsc_daily_sync' )
        : 0;
    $gsc_breakdown          = function_exists( 'newsai_gsc_table_breakdown' ) ? newsai_gsc_table_breakdown() : [];
    $gsc_query_db_rows      = function_exists( 'newsai_gsc_query_row_count' ) ? newsai_gsc_query_row_count() : 0;
    $gsc_last_query_rows    = (int) get_option( 'newsai_gsc_last_query_rows', 0 );
    $gsc_last_query_mode    = (string) get_option( 'newsai_gsc_last_query_sync_mode', '' );
    $gsc_backfill_state     = function_exists( 'newsai_gsc_backfill_get_state' ) ? newsai_gsc_backfill_get_state() : [];
    $gsc_backfill_done_at   = (int) get_option( 'newsai_gsc_backfill_completed_at', 0 );
    $gsc_backfill_running   = function_exists( 'newsai_gsc_backfill_is_running' ) && newsai_gsc_backfill_is_running();

    if (isset($_POST['newsai_add_alert'])) {
        if (!isset($_POST['newsai_alert_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['newsai_alert_nonce'])), 'newsai_add_alert_action')) {
            $security_notice = $i18n['sec_task_save'];
        } else {
        $date = isset($_POST['task_date']) ? sanitize_text_field(wp_unslash($_POST['task_date'])) : '';
        if (!empty($date)) {
            $parts = explode('-', $date);
            $recurrence = isset($_POST['recurrence']) ? sanitize_text_field(wp_unslash($_POST['recurrence'])) : 'yearly';
            if ($recurrence === 'monthly') { $year = 0; $month = 0; } elseif ($recurrence === 'yearly') { $year = 0; $month = intval($parts[1]); } else { $year = intval($parts[0]); $month = intval($parts[1]); }
            
            $day = intval($parts[2]);
            $alert_id = isset($_POST['newsai_alert_id']) ? intval($_POST['newsai_alert_id']) : 0;
            
            $data = [
                'title'          => sanitize_text_field(wp_unslash($_POST['t'])),
                'day'            => $day,
                'month'          => $month,
                'year'           => $year,
                'lead_days'      => isset($_POST['ld']) ? intval($_POST['ld']) : 7,
                'author_id'      => intval($_POST['author_id']),
                'notes'          => isset($_POST['n']) ? sanitize_textarea_field(wp_unslash($_POST['n'])) : '',
                'target_keyword' => isset($_POST['tk']) ? sanitize_text_field(wp_unslash($_POST['tk'])) : '',
                'ref_link'       => isset($_POST['rl']) ? sanitize_url(wp_unslash($_POST['rl'])) : '',
                'status'         => 'pending'
            ];

            if (!in_array('target_keyword', $table_cols)) unset($data['target_keyword']);
            if (!in_array('ref_link', $table_cols)) unset($data['ref_link']);
            if (!in_array('status', $table_cols)) unset($data['status']);

            $prev_author = 0;
            if ($alert_id > 0) {
                $prev_author = (int) $wpdb->get_var($wpdb->prepare("SELECT author_id FROM {$table} WHERE id = %d", $alert_id));
                $wpdb->update($table, $data, ['id' => $alert_id]); echo '<div class="updated"><p>' . esc_html($i18n['msg_task_upd']) . '</p></div>';
                do_action('newsai_task_assigned', (int) $alert_id, false, $prev_author);
            } else {
                $wpdb->insert($table, $data);
                $new_id = (int) $wpdb->insert_id;
                echo '<div class="updated"><p>' . esc_html($i18n['msg_task_ok']) . '</p></div>';
                if ($new_id > 0) {
                    do_action('newsai_task_assigned', $new_id, true, 0);
                }
            }
            
            nros_clear_task_transients(); // 🚀 FIX: Καθαρίζει τη μνήμη της Sidebar!
        }
        }
    }
    
    if (isset($_GET['mark_done']) && isset($_GET['id'])) {
        $alert_id_done = (int) $_GET['id'];
        $mark_nonce_ok = isset($_GET['_wpnonce']) && wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
            'newsai_mark_done_' . $alert_id_done
        );
        $mark_access_ok = $alert_id_done > 0
            && function_exists( 'newsai_task_can_access' )
            && newsai_task_can_access( $alert_id_done );
        if ( $can_edit_tasks && $mark_nonce_ok && $mark_access_ok ) {
            if ( in_array( 'status', $table_cols, true ) ) {
                $wpdb->update( $table, [ 'status' => 'done' ], [ 'id' => $alert_id_done ] );
            }
            nros_clear_task_transients();
            do_action( 'newsai_task_completed', $alert_id_done, (int) get_current_user_id() );
        } else {
            $security_notice = $i18n['sec_done'];
        }
    }
    
    if (isset($_GET['del'])) { 
        if ($can_manage_all && isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'newsai_delete_task_' . intval($_GET['del']))) {
            $wpdb->delete($table, ['id' => intval($_GET['del'])]); 
            nros_clear_task_transients(); // 🚀 FIX: Καθαρίζει τη μνήμη
        } else {
            $security_notice = $i18n['sec_delete'];
        }
    }

    if (isset($_POST['newsai_bulk_delete']) && isset($_POST['newsai_alert_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['newsai_alert_nonce'])), 'newsai_add_alert_action')) {
        if ($can_manage_all) {
            if ($_POST['newsai_bulk_delete'] === 'done') { $wpdb->query("DELETE FROM {$table} WHERE status = 'done'"); } 
            elseif ($_POST['newsai_bulk_delete'] === 'all') { $wpdb->query("TRUNCATE TABLE {$table}"); }
            nros_clear_task_transients(); // 🚀 FIX: Καθαρίζει τη μνήμη
        }
    }

    $edit_id = isset($_GET['edit']) ? intval($_GET['edit']) : 0;
    $edit_data = ($edit_id > 0) ? $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $edit_id)) : null; 
    
    $def_t = $edit_data ? $edit_data->title : ''; 
    $def_n = $edit_data ? $edit_data->notes : '';
    $def_tk = ($edit_data && isset($edit_data->target_keyword)) ? $edit_data->target_keyword : ''; 
    $def_rl = ($edit_data && isset($edit_data->ref_link)) ? $edit_data->ref_link : ''; 
    $def_ld = $edit_data ? $edit_data->lead_days : 7; 
    $def_author = $edit_data ? $edit_data->author_id : 0;
    
    $def_date = ''; $def_rec = 'yearly';
    if ($edit_data) {
        $y = $edit_data->year > 0 ? $edit_data->year : gmdate('Y'); 
        $m = $edit_data->month > 0 ? sprintf('%02d', $edit_data->month) : gmdate('m'); 
        $d = sprintf('%02d', $edit_data->day);
        $def_date = "$y-$m-$d";
        if ($edit_data->year == 0 && $edit_data->month == 0) $def_rec = 'monthly'; elseif ($edit_data->year == 0 && $edit_data->month > 0) $def_rec = 'yearly'; else $def_rec = 'none';
    }

    // ==========================================
    // UI RENDER
    // ==========================================
    if ( function_exists( 'newsai_enqueue_nros_admin_dashboard_styles' ) ) {
        newsai_enqueue_nros_admin_dashboard_styles();
    }
    ?>
    <div class="wrap nros-admin-wrap nros-wrap-header nros-admin-wrap--classic-shell">
       <h1>Newsroom OS <span class="nros-version-badge">v<?php echo esc_html(NEWSAI_VERSION); ?></span></h1>
        <?php
        $active_profile = get_option('newsai_site_profile', 'newsroom');
        $profile_label = ($active_profile === 'blog') ? (__( 'Blog Profile', 'newsroom-ai-assistant' )) : (__( 'Newsroom Profile', 'newsroom-ai-assistant' ));
        ?>
        <p class="nros-site-meta">
            <strong><?php echo esc_html( __( 'Active on:', 'newsroom-ai-assistant' ) ); ?></strong>
            <code><?php echo esc_html(home_url()); ?></code>
            <span class="nros-profile-pill"><?php echo esc_html($profile_label); ?></span>
        </p>
        <?php if (!empty($security_notice)): ?>
            <div class="notice notice-error is-dismissible"><p><?php echo esc_html($security_notice); ?></p></div>
        <?php endif; ?>
        <?php if (!empty($settings_notice)): ?>
            <div class="notice notice-success is-dismissible"><p><?php echo esc_html($settings_notice); ?></p></div>
        <?php endif; ?>
        <?php settings_errors('newsai_settings'); ?>
        <?php if (isset($_GET['msg']) && $_GET['msg'] === 'imported'): ?>
            <div class="notice notice-success is-dismissible"><p>✅ Εισαγωγή γεγονότων επιτυχής!</p></div>
        <?php endif; ?>

        <h2 class="nav-tab-wrapper nros-nav-tabs nros-nav-tabs--legacy" hidden aria-hidden="true">
            <a href="?page=newsai-settings&tab=alerts" class="nav-tab <?php echo esc_attr( $tab === 'alerts' ? 'nav-tab-active' : '' ); ?>">📊 Dashboard</a>
            <a href="?page=newsai-settings&tab=insights" class="nav-tab <?php echo esc_attr( $tab === 'insights' ? 'nav-tab-active' : '' ); ?>">🧭 <?php echo esc_html( __( 'Chief Insights', 'newsroom-ai-assistant' ) ); ?></a>
            <?php if ( function_exists( 'newsai_is_pro' ) && newsai_is_pro() && current_user_can( 'edit_others_posts' ) ): ?>
            <a href="?page=newsai-settings&tab=perf" class="nav-tab <?php echo esc_attr( $tab === 'perf' ? 'nav-tab-active' : '' ); ?>">📈 <?php echo esc_html( __( 'Author Performance', 'newsroom-ai-assistant' ) ); ?></a>
            <?php endif; ?>
            <a href="?page=newsai-settings&tab=settings" class="nav-tab <?php echo esc_attr( $tab === 'settings' ? 'nav-tab-active' : '' ); ?>">⚙️ <?php echo esc_html__( 'Settings & Prompts', 'newsroom-ai-assistant' ); ?></a>
            <a href="?page=newsai-settings&tab=pro" class="nav-tab nav-tab--pro <?php echo esc_attr( $tab === 'pro' ? 'nav-tab-active' : '' ); ?>">🚀 PRO</a>
        </h2>

        <?php
        $newsai_react_shell = function_exists( 'newsai_admin_react_render_shell' ) && newsai_admin_react_render_shell();
        ?>

        <div class="nros-classic-shell">
        <?php
        if ( function_exists( 'newsai_render_classic_admin_sidebar' ) ) {
            newsai_render_classic_admin_sidebar( $tab );
        }
        ?>
        <main class="nros-classic-main" id="nros-classic-main">
        <?php if ($tab == 'settings'): ?>
        <?php
        $nros_react_settings = $newsai_react_shell;
        $nros_react_build_ready = function_exists( 'newsai_settings_react_build_exists' ) && newsai_settings_react_build_exists();
        $nros_react_ui_locked = function_exists( 'newsai_settings_ui_locked_by_constant' ) && newsai_settings_ui_locked_by_constant();
        $nros_react_ui_mode = function_exists( 'newsai_settings_ui_mode' ) ? newsai_settings_ui_mode() : 'classic';
        ?>
        <?php if ( $nros_react_ui_mode !== 'react' && ! $nros_react_ui_locked ) : ?>
        <?php $nros_show_react_promo = true; ?>
        <?php else : ?>
        <?php $nros_show_react_promo = false; ?>
        <?php endif; ?>
        <div class="newsai-classic-settings-wrap<?php echo $nros_react_settings ? ' newsai-classic-settings-wrap--defer-hide' : ''; ?>">
        <div class="nros-settings-bento">
        <?php
        if ( function_exists( 'newsai_render_classic_page_head' ) ) {
            newsai_render_classic_page_head(
                __( 'Settings', 'newsroom-ai-assistant' ),
                __( 'Publisher profile, schema, AI, indexing, and team defaults.', 'newsroom-ai-assistant' )
            );
        }
        ?>
        <div class="nros-settings-bento__cards">
        <?php if ( $nros_show_react_promo ) : ?>
        <div class="nros-card nros-settings-bento__card nros-settings-bento__card--react">
            <h3><?php echo esc_html__( 'Modern settings UI', 'newsroom-ai-assistant' ); ?></h3>
            <p class="nros-card-desc"><?php echo esc_html__( 'A redesigned guided React settings experience is on the way.', 'newsroom-ai-assistant' ); ?></p>
            <button type="button" class="button button-secondary nros-coming-soon-btn" disabled aria-disabled="true"><?php echo esc_html__( 'Coming Soon', 'newsroom-ai-assistant' ); ?></button>
        </div>
        <?php endif; ?>
        <div class="nros-card nros-settings-bento__card nros-settings-bento__card--profile">
            <h3><?php echo esc_html($i18n['switch_profile_title']); ?></h3>
            <p class="nros-card-desc"><?php echo esc_html($i18n['switch_profile_desc']); ?></p>
            <form method="post" onsubmit="return confirm('<?php echo esc_js(__( 'Apply this profile preset now?', 'newsroom-ai-assistant' )); ?>');">
                <?php wp_nonce_field('newsai_switch_profile_action', 'newsai_profile_nonce'); ?>
                <div class="nros-settings-profile-row">
                    <select name="site_profile">
                        <option value="newsroom" <?php selected($active_profile, 'newsroom'); ?>><?php echo esc_html($i18n['profile_newsroom']); ?></option>
                        <option value="blog" <?php selected($active_profile, 'blog'); ?>><?php echo esc_html($i18n['profile_blog']); ?></option>
                    </select>
                    <button type="submit" name="newsai_switch_profile" class="button button-secondary"><?php echo esc_html($i18n['switch_profile_apply']); ?></button>
                </div>
                <p class="description nros-card-desc--tight">
                    <strong><?php echo esc_html($i18n['switch_profile_preview']); ?></strong>
                    <?php echo esc_html(__( 'Newsroom: Auto timeline, Ongoing strategy, limit 5, threshold 5. Blog: Manual timeline, Evergreen strategy, limit 3, threshold 8.', 'newsroom-ai-assistant' )); ?>
                </p>
            </form>
        </div>
        </div>

        <form id="newsai-publisher-profile-form" method="post" style="display:none;" tabindex="-1" aria-hidden="true">
            <?php wp_nonce_field( 'newsai_switch_publisher_profile_action', 'newsai_publisher_profile_nonce' ); ?>
        </form>
        
        <?php
        $p_title = get_option('newsai_prompt_title', '');
        if (empty(trim($p_title)) && function_exists('newsai_get_default_prompt')) { $p_title = newsai_get_default_prompt('title', $lang); }

        $p_rewrite = get_option('newsai_prompt_rewrite', '');
        if (empty(trim($p_rewrite)) && function_exists('newsai_get_default_prompt')) { $p_rewrite = newsai_get_default_prompt('rewrite', $lang); }

        $p_seo = get_option('newsai_prompt_seo', '');
        if (empty(trim($p_seo)) && function_exists('newsai_get_default_prompt')) { $p_seo = newsai_get_default_prompt('seo', $lang); }

        $schema_type_preview = get_option('nros_schema_type', 'newsarticle');
        $schema_output_preview = get_option('nros_schema_output_mode', 'hybrid');
        $liveblog_preview = get_option('newsai_liveblog_schema_enabled', 'yes');
        $speakable_preview = trim((string)get_option('newsai_speakable_selectors', ''));
        $richness_preview  = sanitize_key( (string) get_option( 'nros_schema_richness', 'balanced' ) );
        if ( ! in_array( $richness_preview, [ 'minimal', 'balanced', 'full' ], true ) ) {
            $richness_preview = 'full';
        }
        $primary_city_preview = trim((string)get_option('nros_primary_city', ''));
        $newsai_ui_code = function_exists( 'newsai_get_ui_lang' ) ? newsai_get_ui_lang() : 'en';
        $newsai_inlang_map = array( 'el' => 'el-GR', 'de' => 'de-DE', 'es' => 'es-ES', 'en' => 'en-US' );
        $schema_preview_payload = [
            '@context' => 'https://schema.org',
            '@type' => ($schema_type_preview === 'article') ? 'Article' : (($schema_type_preview === 'none') ? 'Thing' : 'NewsArticle'),
            'publisher' => [
                '@type' => get_option('nros_org_type', 'NewsMediaOrganization'),
                'name' => get_option('nros_site_name', get_bloginfo('name')),
            ],
            'inLanguage' => isset( $newsai_inlang_map[ $newsai_ui_code ] ) ? $newsai_inlang_map[ $newsai_ui_code ] : 'en-US',
            'isAccessibleForFree' => (get_option('nros_paywall_active', 'no') === 'yes') ? false : true,
        ];
        if ($primary_city_preview !== '' && function_exists( 'nros_schema_primary_city_article_fallback' ) && nros_schema_primary_city_article_fallback()) {
            $schema_preview_payload['contentLocation'] = ['@type' => 'Place', 'name' => $primary_city_preview];
        }
        $speakable_sel_preview = function_exists( 'nros_schema_parse_speakable_selectors' )
            ? nros_schema_parse_speakable_selectors( $speakable_preview )
            : array_values( array_filter( array_map( 'trim', explode( ',', $speakable_preview ) ) ) );
        if ( function_exists( 'nros_speakable_finalize_schema_selectors' ) ) {
            $speakable_sel_preview = nros_speakable_finalize_schema_selectors( $speakable_sel_preview, $richness_preview, 0, null );
        }
        if ( ! empty( $speakable_sel_preview ) && 'minimal' !== $richness_preview ) {
            $schema_preview_payload['speakable'] = [
                '@type'         => 'SpeakableSpecification',
                'cssSelector'   => $speakable_sel_preview,
            ];
        }
        $schema_preview_json = wp_json_encode($schema_preview_payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $snippet_preview_on = ( get_option( 'nros_speakable_snippet_enabled', 'no' ) === 'yes' );
        $speakable_hint_ok  = ( ! empty( $speakable_sel_preview ) && 'minimal' !== $richness_preview );
        $schema_hints = [
            ['state' => ($schema_type_preview !== 'none') ? 'ok' : 'warn', 'message' => __( 'Schema engine is enabled.', 'newsroom-ai-assistant' )],
            ['state' => ($schema_output_preview === 'strict' || $schema_output_preview === 'hybrid') ? 'ok' : 'warn', 'message' => __( 'Output policy is configured.', 'newsroom-ai-assistant' )],
            ['state' => ($liveblog_preview === 'yes') ? 'ok' : 'warn', 'message' => __( 'LiveBlog feature is available in editor.', 'newsroom-ai-assistant' )],
            [
                'state'   => $speakable_hint_ok ? 'ok' : ( $speakable_preview === '' && ! $snippet_preview_on ? 'warn' : 'warn' ),
                'message' => ( $speakable_preview === '' && ! $snippet_preview_on )
                    ? __( 'Speakable selectors are empty (optional).', 'newsroom-ai-assistant' )
                    : ( 'minimal' === $richness_preview
                        ? __( 'Speakable is disabled while the schema preset is Minimal. Switch to Balanced or Full to emit speakable on posts.', 'newsroom-ai-assistant' )
                        : ( ( $speakable_preview === '' && $snippet_preview_on )
                            ? __( 'Speakable will use the auto .nros-speakable-snippet selector on single posts (Balanced / Full). Add headline selectors above if you want the title included.', 'newsroom-ai-assistant' )
                            : __( 'Speakable selectors will be emitted on single posts (Balanced / Full).', 'newsroom-ai-assistant' ) ) ),
            ],
            ['state' => ($primary_city_preview !== '') ? 'ok' : 'warn', 'message' => __( 'Primary city is set for publisher Organization markup.', 'newsroom-ai-assistant' )],
        ];
        if ( $speakable_preview !== '' || $snippet_preview_on ) {
            $schema_hints[] = [
                'state'   => 'ok',
                'message' => __( 'Google documents Speakable for Assistant topical news as beta and limited to U.S. users with English content. Valid JSON-LD on Greek (or other) sites may not trigger Assistant audio; use View Source / Rich Results Test and confirm selectors match your live HTML.', 'newsroom-ai-assistant' ),
            ];
        }
        ?>

        <div class="nros-card nros-settings-bento__form">
            <form method="post" class="nros-settings-form">
                <?php wp_nonce_field('newsai_save_settings_action', 'newsai_settings_nonce'); ?>
                <div class="nros-settings-layout">
                <nav class="nros-settings-nav" id="nros-settings-tabs" aria-label="<?php echo esc_attr__( 'Settings sections', 'newsroom-ai-assistant' ); ?>">
                    <button type="button" class="nros-settings-tab-btn active" data-pane="site"><?php echo esc_html(__( 'Site Details', 'newsroom-ai-assistant' )); ?></button>
                    <button type="button" class="nros-settings-tab-btn" data-pane="schema"><?php echo esc_html(__( 'Schema & SEO', 'newsroom-ai-assistant' )); ?></button>
                    <button type="button" class="nros-settings-tab-btn" data-pane="timeline"><?php echo esc_html(__( 'Auto-Timeline', 'newsroom-ai-assistant' )); ?></button>
                    <button type="button" class="nros-settings-tab-btn" data-pane="ux"><?php echo esc_html(__( 'UX & AI', 'newsroom-ai-assistant' )); ?></button>
                    <button type="button" class="nros-settings-tab-btn" data-pane="ai_assist"><?php echo esc_html(__( 'AI Assist', 'newsroom-ai-assistant' )); ?></button>
                    <button type="button" class="nros-settings-tab-btn" data-pane="team"><?php echo esc_html(__( 'Team', 'newsroom-ai-assistant' )); ?></button>
                    <button type="button" class="nros-settings-tab-btn" data-pane="indexing"><?php echo esc_html(__( 'Instant Indexing', 'newsroom-ai-assistant' )); ?></button>
                    <button type="button" class="nros-settings-tab-btn" data-pane="decay"><?php echo esc_html(__( 'Performance', 'newsroom-ai-assistant' )); ?></button>
                    <button type="button" class="nros-settings-tab-btn" data-pane="prompts"><?php echo esc_html(__( 'Prompts', 'newsroom-ai-assistant' )); ?></button>
                </nav>
                <div class="nros-settings-panes">

                <div class="nros-settings-pane active" data-pane="site">
                <h3><?php echo esc_html($i18n['settings_title']); ?></h3>
                <table class="form-table">
                    <tr><th>Site Name</th><td><input type="text" name="sn" value="<?php echo esc_attr(get_option('nros_site_name', get_bloginfo('name'))); ?>" class="regular-text"></td></tr>
                    <tr><th><?php echo esc_html(__( 'Site Niche', 'newsroom-ai-assistant' )); ?></th><td><input type="text" name="sd" value="<?php echo esc_attr(newsai_get_best_site_description()); ?>" class="regular-text" style="width:100%;"></td></tr>
                    <tr><th><?php echo esc_html( __( 'Language', 'newsroom-ai-assistant' ) ); ?></th><td><select name="lang"><?php
                    $newsai_lang_saved = function_exists( 'newsai_get_ui_lang' ) ? newsai_get_ui_lang() : 'en';
                    $newsai_lang_choices = function_exists( 'newsai_supported_languages' ) ? newsai_supported_languages() : [ 'el' => [ 'native' => 'Ελληνικά' ], 'en' => [ 'native' => 'English' ] ];
                    foreach ( $newsai_lang_choices as $code => $meta ) :
                        $label = isset( $meta['native'] ) ? $meta['native'] : $code;
                        ?><option value="<?php echo esc_attr( $code ); ?>" <?php selected( $newsai_lang_saved, $code ); ?>><?php echo esc_html( $label ); ?></option><?php
                    endforeach;
                    ?></select></td></tr>
                    <tr><th>Target Geo</th><td>
                        <select name="geo">
                            <option value="GR" <?php selected($geo_opt, 'GR'); ?>>Greece (GR)</option>
                            <option value="CY" <?php selected($geo_opt, 'CY'); ?>>Cyprus (CY)</option>
                            <option value="US" <?php selected($geo_opt, 'US'); ?>>USA (US)</option>
                            <option value="GB" <?php selected($geo_opt, 'GB'); ?>>UK (GB)</option>
                            <option value="CA" <?php selected($geo_opt, 'CA'); ?>>Canada (CA)</option>
                            <option value="AU" <?php selected($geo_opt, 'AU'); ?>>Australia (AU)</option>
                            <option value="DE" <?php selected($geo_opt, 'DE'); ?>>Germany (DE)</option>
                            <option value="FR" <?php selected($geo_opt, 'FR'); ?>>France (FR)</option>
                            <option value="IT" <?php selected($geo_opt, 'IT'); ?>>Italy (IT)</option>
                            <option value="ES" <?php selected($geo_opt, 'ES'); ?>>Spain (ES)</option>
                            <option value="NL" <?php selected($geo_opt, 'NL'); ?>>Netherlands (NL)</option>
                            <option value="BE" <?php selected($geo_opt, 'BE'); ?>>Belgium (BE)</option>
                            <option value="CH" <?php selected($geo_opt, 'CH'); ?>>Switzerland (CH)</option>
                            <option value="SE" <?php selected($geo_opt, 'SE'); ?>>Sweden (SE)</option>
                            <option value="PT" <?php selected($geo_opt, 'PT'); ?>>Portugal (PT)</option>
                            <option value="BR" <?php selected($geo_opt, 'BR'); ?>>Brazil (BR)</option>
                            <option value="MX" <?php selected($geo_opt, 'MX'); ?>>Mexico (MX)</option>
                            <option value="RU" <?php selected($geo_opt, 'RU'); ?>>Russia (RU)</option>
                            <option value="JP" <?php selected($geo_opt, 'JP'); ?>>Japan (JP)</option>
                            <option value="IN" <?php selected($geo_opt, 'IN'); ?>>India (IN)</option>
                            <option value="ID" <?php selected($geo_opt, 'ID'); ?>>Indonesia (ID)</option>
                            <option value="ZA" <?php selected($geo_opt, 'ZA'); ?>>South Africa (ZA)</option>
                        </select>
                        <p class="description"><?php echo esc_html( $i18n['geo_desc'] ); ?></p>
                    </td></tr>
                    <?php if ( ! $newsai_is_pro_active ) : ?>
                    <?php
                    $usage_registry_on = function_exists( 'newsai_usage_registry_opted_in' ) && newsai_usage_registry_opted_in();
                    $usage_consent_ts  = function_exists( 'newsai_usage_registry_consent_timestamp' ) ? newsai_usage_registry_consent_timestamp() : 0;
                    ?>
                    <tr>
                        <th><?php echo esc_html( $i18n['usage_registry_title'] ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="newsai_usage_registry_optin" value="yes" <?php checked( $usage_registry_on ); ?>>
                                <?php echo esc_html( $i18n['usage_registry_label'] ); ?>
                            </label>
                            <p class="description" style="margin-top:8px; max-width:520px;"><?php echo esc_html( $i18n['usage_registry_desc'] ); ?></p>
                            <?php if ( $usage_consent_ts > 0 ) : ?>
                                <p class="description" style="margin-top:6px;">
                                    <?php
                                    echo esc_html( $i18n['usage_registry_consent_note'] ) . ' ';
                                    echo esc_html(
                                        date_i18n(
                                            get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
                                            $usage_consent_ts
                                        )
                                    );
                                    ?>
                                </p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php else : ?>
                    <tr>
                        <th><?php echo esc_html( $i18n['usage_registry_title'] ); ?></th>
                        <td>
                            <p class="description" style="margin:0;"><?php echo esc_html( $i18n['usage_registry_pro_skip'] ); ?></p>
                        </td>
                    </tr>
                    <?php endif; ?>
                </table>
                </div>

                <div class="nros-settings-pane" data-pane="schema">
                <hr style="margin: 20px 0; border-top: 1px solid #f0f0f1;">

                <h3><?php echo esc_html($i18n['schema_title']); ?></h3>
                <table class="form-table">
                    <tr><th>Schema Engine</th><td>
                        <select name="schema_type">
                            <option value="newsarticle" <?php selected(get_option('nros_schema_type', 'newsarticle'), 'newsarticle'); ?>>📰 NewsArticle (Publisher profile)</option>
                            <option value="article" <?php selected(get_option('nros_schema_type', 'newsarticle'), 'article'); ?>>🏢 Article (Content profile)</option>
                            <option value="none" <?php selected(get_option('nros_schema_type', 'newsarticle'), 'none'); ?>>🚫 Disabled</option>
                        </select>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['schema_output_mode']); ?></th><td>
                        <?php $schema_output_mode = get_option( 'nros_schema_output_mode', 'hybrid' ); ?>
                        <select name="schema_output_mode" id="nros-schema-output-mode" class="nros-settings-select">
                            <option value="hybrid" <?php selected( $schema_output_mode, 'hybrid' ); ?>><?php echo esc_html( $i18n['schema_output_hybrid_label'] ); ?></option>
                            <option value="strict" <?php selected( $schema_output_mode, 'strict' ); ?>><?php echo esc_html( $i18n['schema_output_strict_label'] ); ?></option>
                        </select>
                        <p id="nros-schema-output-mode-detail" class="description nros-select-detail"><?php echo esc_html( 'strict' === $schema_output_mode ? $i18n['schema_output_strict'] : $i18n['schema_output_hybrid'] ); ?></p>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['liveblog_global']); ?></th><td>
                        <label><input type="checkbox" name="liveblog_schema_enabled" value="yes" <?php checked(get_option('newsai_liveblog_schema_enabled', 'yes'), 'yes'); ?>> LiveBlogPosting</label>
                        <p class="description"><?php echo esc_html__( 'Required for Breaking news mode in the editor.', 'newsroom-ai-assistant' ); ?></p>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['breaking_expire_hours']); ?></th><td>
                        <select name="newsai_breaking_expire_hours">
                            <option value="24" <?php selected((int) get_option('newsai_breaking_expire_hours', 48), 24); ?>>24</option>
                            <option value="48" <?php selected((int) get_option('newsai_breaking_expire_hours', 48), 48); ?>>48</option>
                            <option value="72" <?php selected((int) get_option('newsai_breaking_expire_hours', 48), 72); ?>>72</option>
                        </select>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['breaking_badge']); ?></th><td>
                        <label><input type="checkbox" name="newsai_breaking_badge_enabled" value="yes" <?php checked(get_option('newsai_breaking_badge_enabled', 'yes'), 'yes'); ?>></label>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['schema_richness']); ?></th><td>
                        <?php
                        $schema_richness_cur = get_option( 'nros_schema_richness', 'balanced' );
                        $schema_richness_descs = [
                            'minimal'  => $i18n['schema_richness_min'],
                            'balanced' => $i18n['schema_richness_bal'],
                            'full'     => $i18n['schema_richness_full'],
                        ];
                        $schema_richness_detail = $schema_richness_descs[ $schema_richness_cur ] ?? $i18n['schema_richness_bal'];
                        ?>
                        <select name="nros_schema_richness" id="nros-schema-richness" class="nros-settings-select">
                            <option value="minimal" <?php selected( $schema_richness_cur, 'minimal' ); ?>><?php echo esc_html( $i18n['schema_richness_min_label'] ); ?></option>
                            <option value="balanced" <?php selected( $schema_richness_cur, 'balanced' ); ?>><?php echo esc_html( $i18n['schema_richness_bal_label'] ); ?></option>
                            <option value="full" <?php selected( $schema_richness_cur, 'full' ); ?>><?php echo esc_html( $i18n['schema_richness_full_label'] ); ?></option>
                        </select>
                        <p id="nros-schema-richness-detail" class="description nros-select-detail"><?php echo esc_html( $schema_richness_detail ); ?></p>
                        <p class="description"><?php echo esc_html($i18n['schema_richness_hint']); ?></p>
                    </td></tr>
                    <?php
                    $schema_article_body_cur = get_option( 'nros_schema_article_body', 'full' );
                    $schema_article_body_words_cur = (int) get_option( 'nros_schema_article_body_words', 200 );
                    ?>
                    <tr><th><?php echo esc_html($i18n['schema_article_body']); ?></th><td>
                        <div class="nros-schema-article-body">
                            <select name="nros_schema_article_body" id="nros-schema-article-body" class="nros-settings-select">
                                <option value="omit" <?php selected( $schema_article_body_cur, 'omit' ); ?>><?php echo esc_html($i18n['schema_article_body_omit']); ?></option>
                                <option value="limited" <?php selected( $schema_article_body_cur, 'limited' ); ?>><?php echo esc_html($i18n['schema_article_body_limited']); ?></option>
                                <option value="full" <?php selected( $schema_article_body_cur, 'full' ); ?>><?php echo esc_html($i18n['schema_article_body_full']); ?></option>
                            </select>
                            <div id="nros-schema-article-body-words" class="nros-schema-article-body-words<?php echo 'limited' === $schema_article_body_cur ? '' : ' is-hidden'; ?>">
                                <label for="nros-schema-article-body-words-input"><?php echo esc_html($i18n['schema_article_body_words']); ?></label>
                                <input type="number" id="nros-schema-article-body-words-input" name="nros_schema_article_body_words" value="<?php echo esc_attr( (string) $schema_article_body_words_cur ); ?>" min="30" max="2000" step="10" class="small-text">
                            </div>
                            <p class="description"><?php echo esc_html($i18n['schema_article_body_hint']); ?></p>
                        </div>
                    </td></tr>
                    <tr><th><?php echo esc_html( __( 'Megasite mode', 'newsroom-ai-assistant' ) ); ?></th><td>
                        <label>
                            <input type="checkbox" name="nros_schema_megasite_mode" value="yes" <?php checked( get_option( 'nros_schema_megasite_mode', 'yes' ), 'yes' ); ?>>
                            <?php echo esc_html( __( 'Serve cached schema instantly and rebuild in the background (recommended for high-traffic sites).', 'newsroom-ai-assistant' ) ); ?>
                        </label>
                        <p class="description" style="max-width:560px;margin-top:6px;">
                            <?php echo esc_html( __( 'When a global schema setting (or author/plugin update) changes, posts keep serving their existing schema and are refreshed gradually by a background task instead of all rebuilding at once on the next visit. Edited posts are always rebuilt immediately on save.', 'newsroom-ai-assistant' ) ); ?>
                        </p>
                    </td></tr>
                    <tr><th><?php echo esc_html( __( 'Background schema warm', 'newsroom-ai-assistant' ) ); ?></th><td>
                        <label>
                            <input type="checkbox" name="nros_schema_background_warm" value="yes" <?php checked( get_option( 'nros_schema_background_warm', 'yes' ), 'yes' ); ?>>
                            <?php echo esc_html( __( 'Allow background cron to backfill JSON-LD for old posts', 'newsroom-ai-assistant' ) ); ?>
                        </label>
                        <p class="description" style="max-width:560px;margin-top:6px;">
                            <?php echo esc_html( __( 'Turn OFF on high-load servers. Lite Mode also disables this automatically. Schema still prints (cached/slim); only the migration cron stops. Use “Warm next 25 posts” manually off-peak if needed.', 'newsroom-ai-assistant' ) ); ?>
                        </p>
                    </td></tr>
                    <tr><th><?php echo esc_html( __( 'Nightly schema warm', 'newsroom-ai-assistant' ) ); ?></th><td>
                        <label>
                            <input type="checkbox" name="nros_schema_nightly_warm" value="yes" <?php checked( get_option( 'nros_schema_nightly_warm', 'no' ), 'yes' ); ?>>
                            <?php echo esc_html( __( 'Run background schema backfill only during off-peak hours (works with Lite Mode ON)', 'newsroom-ai-assistant' ) ); ?>
                        </label>
                        <p style="margin:10px 0 6px;display:flex;flex-wrap:wrap;gap:12px;align-items:center;">
                            <label>
                                <?php echo esc_html( __( 'From', 'newsroom-ai-assistant' ) ); ?>
                                <input type="time" name="nros_schema_nightly_warm_start" value="<?php echo esc_attr( get_option( 'nros_schema_nightly_warm_start', '02:00' ) ); ?>" style="margin-left:4px;">
                            </label>
                            <label>
                                <?php echo esc_html( __( 'To', 'newsroom-ai-assistant' ) ); ?>
                                <input type="time" name="nros_schema_nightly_warm_end" value="<?php echo esc_attr( get_option( 'nros_schema_nightly_warm_end', '06:00' ) ); ?>" style="margin-left:4px;">
                            </label>
                            <span class="description"><?php echo esc_html( sprintf( /* translators: %s: WordPress timezone string */ __( 'Site timezone: %s', 'newsroom-ai-assistant' ), wp_timezone_string() ) ); ?></span>
                        </p>
                        <p class="description" style="max-width:560px;margin-top:6px;">
                            <?php echo esc_html( __( 'Keeps Lite Mode on all day but enables the schema migration cron only inside this window (default 02:00–06:00). Ideal for backfilling thousands of posts without daytime CPU spikes.', 'newsroom-ai-assistant' ) ); ?>
                        </p>
                        <?php
                        if ( function_exists( 'nros_schema_nightly_warm_enabled' ) && nros_schema_nightly_warm_enabled() ) {
                            $nightly_active = function_exists( 'nros_schema_nightly_warm_window_active' ) && nros_schema_nightly_warm_window_active();
                            echo '<p class="description" style="margin-top:6px;"><strong>' . esc_html(
                                $nightly_active
                                    ? __( 'Status: nightly warm is ACTIVE right now.', 'newsroom-ai-assistant' )
                                    : __( 'Status: nightly warm is scheduled (outside the window now).', 'newsroom-ai-assistant' )
                            ) . '</strong></p>';
                        }
                        ?>
                    </td></tr>
                    <tr><th><?php echo esc_html( __( 'Legacy schema cache', 'newsroom-ai-assistant' ) ); ?></th><td>
                        <button type="submit" name="newsai_schema_warm_batch" class="button"><?php echo esc_html( __( 'Warm next 25 posts', 'newsroom-ai-assistant' ) ); ?></button>
                        <button type="submit" name="newsai_schema_warm_archives" class="button button-secondary" style="margin-left:8px;"><?php echo esc_html( __( 'Warm home & feed archives', 'newsroom-ai-assistant' ) ); ?></button>
                        <p class="description" style="max-width:520px;margin-top:6px;">
                            <?php echo esc_html( __( 'Old articles do not need a re-save: schema is built on first pageview or via this batch (15/day automatic). Stored in post meta like Rank Math.', 'newsroom-ai-assistant' ) ); ?>
                        </p>
                        <p class="description" style="max-width:520px;margin-top:4px;">
                            <?php echo esc_html( __( 'Use “Warm home & feed archives” to build ItemList JSON-LD for your news feed (roi-eidiseon) without waiting for cron — megasite-safe.', 'newsroom-ai-assistant' ) ); ?>
                        </p>
                        <?php
                        $sw_last = (int) get_option( 'nros_schema_warm_last_batch', 0 );
                        $sw_cnt  = (int) get_option( 'nros_schema_warm_last_count', 0 );
                        $arch_q  = function_exists( 'nros_schema_get_archive_warm_queue' ) ? count( nros_schema_get_archive_warm_queue() ) : 0;
                        if ( $sw_last > 0 ) {
                            echo '<p class="description">' . esc_html(
                                sprintf(
                                    /* translators: 1: UTC datetime, 2: count */
                                    __( 'Last batch: %1$s UTC — %2$d post(s).', 'newsroom-ai-assistant' ),
                                    gmdate( 'Y-m-d H:i', $sw_last ),
                                    $sw_cnt
                                )
                            ) . '</p>';
                        }
                        if ( $arch_q > 0 ) {
                            echo '<p class="description">' . esc_html(
                                sprintf(
                                    /* translators: %d: queued archive count */
                                    __( 'Archive warm queue: %d page(s) pending (cron processes ~1 every 15 min).', 'newsroom-ai-assistant' ),
                                    (int) $arch_q
                                )
                            ) . '</p>';
                        }
                        ?>
                    </td></tr>
                    <tr>
                        <th><?php echo esc_html($i18n['city']); ?></th>
                        <td>
                            <input type="text" name="primary_city" value="<?php echo esc_attr(get_option('nros_primary_city', '')); ?>" class="regular-text">
                            <p class="description"><?php echo esc_html($i18n['city_desc']); ?></p>
                            <label style="display:block;margin-top:10px;">
                                <input type="checkbox" name="primary_city_article_fallback" value="yes" <?php checked( get_option( 'nros_primary_city_article_fallback', 'no' ), 'yes' ); ?>>
                                <?php echo esc_html( $i18n['city_fallback_label'] ); ?>
                            </label>
                            <p class="description"><?php echo esc_html( $i18n['city_fallback_desc'] ); ?></p>
                        </td>
                    </tr>

                    <tr><th>Organization Type</th><td>
                        <select name="org_type">
                            <option value="NewsMediaOrganization" <?php selected(get_option('nros_org_type', 'NewsMediaOrganization'), 'NewsMediaOrganization'); ?>>📡 NewsMediaOrganization</option>
                            <option value="Organization" <?php selected(get_option('nros_org_type', 'NewsMediaOrganization'), 'Organization'); ?>>🏢 Organization</option>
                        </select>
                    </td></tr>
                    <tr><th colspan="2" style="padding-top:14px;"><?php echo esc_html($i18n['org_details_title']); ?></th></tr>
                    <tr><th><?php echo esc_html($i18n['org_logo_url']); ?></th><td>
                        <input type="url" name="org_logo_url" value="<?php echo esc_attr(get_option('nros_org_logo_url', '')); ?>" class="regular-text" style="width:100%;" placeholder="https://example.com/uploads/logo.png">
                        <p class="description"><?php echo esc_html($i18n['org_logo_url_desc']); ?></p>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['org_legal_name']); ?></th><td><input type="text" name="org_legal_name" value="<?php echo esc_attr(get_option('nros_org_legal_name', '')); ?>" class="regular-text" style="width:100%;"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_alt_name']); ?></th><td><input type="text" name="org_alternate_name" value="<?php echo esc_attr(get_option('nros_org_alternate_name', '')); ?>" class="regular-text" style="width:100%;"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_email']); ?></th><td><input type="email" name="org_email" value="<?php echo esc_attr(get_option('nros_org_email', '')); ?>" class="regular-text" style="width:100%;"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_phone']); ?></th><td><input type="text" name="org_phone" value="<?php echo esc_attr(get_option('nros_org_phone', '')); ?>" class="regular-text" style="width:100%;"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_tax_id']); ?></th><td>
                        <input type="text" name="org_tax_id" value="<?php echo esc_attr(get_option('nros_org_tax_id', '')); ?>" class="regular-text">
                        <p class="description"><?php echo esc_html( __( 'Tax ID (taxID schema.org). For GR: your AFM e.g. 123456789', 'newsroom-ai-assistant' ) ); ?></p>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['org_vat_id']); ?></th><td>
                        <input type="text" name="org_vat_id" value="<?php echo esc_attr(get_option('nros_org_vat_id', '')); ?>" class="regular-text">
                        <p class="description"><?php echo esc_html( __( 'VAT ID (vatID). For GR: EL + AFM e.g. EL123456789. Leave blank if same as Tax ID.', 'newsroom-ai-assistant' ) ); ?></p>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['org_iso6523']); ?></th><td><input type="text" name="org_iso6523" value="<?php echo esc_attr(get_option('nros_org_iso6523', '')); ?>" class="regular-text"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_naics']); ?></th><td><input type="text" name="org_naics" value="<?php echo esc_attr(get_option('nros_org_naics', '')); ?>" class="regular-text"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_addr_country']); ?></th><td><input type="text" name="org_address_country" value="<?php echo esc_attr(get_option('nros_org_address_country', '')); ?>" class="regular-text" placeholder="GR"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_addr_locality']); ?></th><td><input type="text" name="org_address_locality" value="<?php echo esc_attr(get_option('nros_org_address_locality', '')); ?>" class="regular-text"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_addr_region']); ?></th><td><input type="text" name="org_address_region" value="<?php echo esc_attr(get_option('nros_org_address_region', '')); ?>" class="regular-text"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_addr_postal']); ?></th><td><input type="text" name="org_address_postal_code" value="<?php echo esc_attr(get_option('nros_org_address_postal_code', '')); ?>" class="regular-text"></td></tr>
                    <tr><th><?php echo esc_html($i18n['org_addr_street']); ?></th><td><input type="text" name="org_address_street" value="<?php echo esc_attr(get_option('nros_org_address_street', '')); ?>" class="regular-text" style="width:100%;"></td></tr>
                    <tr><th>Social Media Links</th><td>
                        <textarea name="social_links" rows="3" style="width:100%;"><?php echo esc_textarea(get_option('nros_social_links', '')); ?></textarea>
                    </td></tr>
                    <tr><th colspan="2" style="padding-top:14px;"><?php echo esc_html__( 'Publisher transparency (Google News)', 'newsroom-ai-assistant' ); ?></th></tr>
                    <?php
                    $trust_fields = [
                        'org_publishing_principles_url' => [ 'option' => 'nros_org_publishing_principles_url', 'label' => __( 'Publishing principles URL', 'newsroom-ai-assistant' ), 'policy' => 'publishing_principles' ],
                        'org_corrections_policy_url'    => [ 'option' => 'nros_org_corrections_policy_url', 'label' => __( 'Corrections policy URL', 'newsroom-ai-assistant' ), 'policy' => 'corrections_policy' ],
                        'org_ownership_funding_url'     => [ 'option' => 'nros_org_ownership_funding_url', 'label' => __( 'Ownership & funding URL', 'newsroom-ai-assistant' ), 'policy' => 'ownership_funding' ],
                        'org_actionable_feedback_url'   => [ 'option' => 'nros_org_actionable_feedback_url', 'label' => __( 'Actionable feedback URL', 'newsroom-ai-assistant' ), 'policy' => 'actionable_feedback' ],
                    ];
                    $ai_policy_ready = function_exists( 'newsai_ai_is_active' ) && newsai_ai_is_active();
                    foreach ( $trust_fields as $field_name => $meta ) :
                        $val = esc_attr( get_option( $meta['option'], '' ) );
                        ?>
                    <tr>
                        <th><label for="<?php echo esc_attr( $field_name ); ?>"><?php echo esc_html( $meta['label'] ); ?></label></th>
                        <td>
                            <input type="url" name="<?php echo esc_attr( $field_name ); ?>" id="<?php echo esc_attr( $field_name ); ?>" value="<?php echo $val; ?>" class="regular-text" style="width:100%;" placeholder="https://example.com/<?php echo esc_attr( str_replace( '_', '-', $meta['policy'] ) ); ?>/">
                            <?php if ( $ai_policy_ready ) : ?>
                            <p style="margin-top:8px;">
                                <button type="button" class="button button-secondary nros-ai-policy-page" data-policy="<?php echo esc_attr( $meta['policy'] ); ?>" data-target="<?php echo esc_attr( $field_name ); ?>">
                                    ✨ <?php echo esc_html__( 'Generate page with AI', 'newsroom-ai-assistant' ); ?>
                                </button>
                                <span class="nros-ai-policy-status" data-policy="<?php echo esc_attr( $meta['policy'] ); ?>" style="margin-left:8px;font-size:12px;color:#646970;"></span>
                            </p>
                            <?php else : ?>
                            <p class="description"><?php echo esc_html__( 'Add your API key in Settings → AI Assist to auto-generate policy pages.', 'newsroom-ai-assistant' ); ?></p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <tr><td colspan="2"><p class="description"><?php echo esc_html__( 'These URLs are emitted on your homepage Organization schema (publishingPrinciples, correctionsPolicy, ownershipFundingInfo, actionableFeedbackPolicy).', 'newsroom-ai-assistant' ); ?></p></td></tr>
                    <tr><th><label>Custom Feed Page IDs</label></th><td>
                        <input type="text" name="feed_pages" value="<?php echo esc_attr(get_option('newsai_custom_feed_pages', '')); ?>" class="regular-text" style="width:100%;">
                        <p class="description"><?php echo esc_html( $i18n['feed_pages_d'] ); ?></p>
                    </td></tr>
                    <tr><th><label for="newsai_about_page_id"><?php echo esc_html( $i18n['about_page_id'] ); ?></label></th><td>
                        <?php
                        $about_page_id_val = (int) get_option( 'newsai_about_page_id', 0 );
                        $about_page_title  = $about_page_id_val > 0 ? get_the_title( $about_page_id_val ) : '';
                        ?>
                        <input type="number" name="about_page_id" id="newsai_about_page_id" value="<?php echo $about_page_id_val > 0 ? (int) $about_page_id_val : ''; ?>" min="0" step="1" class="small-text" style="width:6em;">
                        <?php if ( $about_page_id_val > 0 && $about_page_title ) : ?>
                            <span style="margin-left:8px; color:#50575e;"><?php echo esc_html( $about_page_title ); ?></span>
                            <?php if ( get_edit_post_link( $about_page_id_val ) ) : ?>
                                <a href="<?php echo esc_url( get_edit_post_link( $about_page_id_val, 'raw' ) ); ?>" style="margin-left:6px;"><?php esc_html_e( 'Edit', 'newsroom-ai-assistant' ); ?></a>
                            <?php endif; ?>
                        <?php endif; ?>
                        <p class="description"><?php echo esc_html( $i18n['about_page_d'] ); ?></p>
                    </td></tr>
                    <tr><th><label>Speakable CSS Classes</label></th><td>
                        <input type="text" name="speakable" value="<?php echo esc_attr(get_option('newsai_speakable_selectors', '')); ?>" class="regular-text" style="width:100%;">
                        <p class="description"><?php echo esc_html( $i18n['speakable_d'] ); ?></p>
                    </td></tr>
                    <tr><th><?php echo esc_html( $i18n['speakable_snippet'] ); ?></th><td>
                        <label><input type="checkbox" name="nros_speakable_snippet_enabled" value="1" <?php checked( get_option( 'nros_speakable_snippet_enabled', 'no' ), 'yes' ); ?> /> <?php echo esc_html( $i18n['speakable_snippet_cb'] ); ?></label>
                        <p><label><?php echo esc_html( $i18n['speakable_snippet_chars'] ); ?>
                            <input type="number" name="nros_speakable_snippet_max_chars" value="<?php echo esc_attr( (string) (int) get_option( 'nros_speakable_snippet_max_chars', 400 ) ); ?>" min="80" max="2000" step="10" class="small-text" style="width:5.5em;">
                        </label></p>
                        <p><label><input type="checkbox" name="nros_speakable_snippet_strip_body" value="1" <?php checked( get_option( 'nros_speakable_snippet_strip_body', 'yes' ), 'yes' ); ?> /> <?php echo esc_html( $i18n['speakable_snippet_strip_cb'] ); ?></label></p>
                        <p class="description"><?php echo esc_html( $i18n['speakable_snippet_d'] ); ?></p>
                        <p class="description"><?php echo esc_html( $i18n['speakable_snippet_strip_d'] ); ?></p>
                    </td></tr>
                </table>
                <div style="background:#f8f9fa; border:1px solid #e2e4e7; border-radius:8px; padding:14px; margin-top:8px;">
                    <h4 style="margin:0 0 8px 0;"><?php echo esc_html($i18n['schema_qa_title']); ?></h4>
                    <p style="margin:0 0 10px 0; color:#50575e;"><?php echo esc_html($i18n['schema_qa_desc']); ?></p>
                    <ul style="margin:0 0 10px 18px;">
                        <?php foreach ($schema_hints as $hint): ?>
                            <li style="margin-bottom:4px;">
                                <strong style="color:<?php echo ($hint['state'] === 'ok') ? '#15803d' : '#b91c1c'; ?>;">
                                    <?php echo esc_html(($hint['state'] === 'ok') ? $i18n['schema_qa_ok'] : $i18n['schema_qa_warn']); ?>:
                                </strong>
                                <?php echo esc_html($hint['message']); ?>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                    <textarea readonly rows="10" style="width:100%; font-family:Consolas,Monaco,monospace; font-size:12px;"><?php echo esc_textarea((string)$schema_preview_json); ?></textarea>
                </div>
                </div>

                <div class="nros-settings-pane" data-pane="timeline">
                <hr style="margin: 20px 0; border-top: 1px solid #f0f0f1;">

                <h3><?php echo esc_html($i18n['timeline_title']); ?></h3>
                <?php if (!$newsai_is_pro_active && function_exists('newsai_pro_render_lock_card')): ?>
                    <?php
                    newsai_pro_render_lock_card(
                        __( 'Auto-Timeline (Pro)', 'newsroom-ai-assistant' ),
                        __( 'Automatically build story timelines and inject them inside articles. Activate Pro to unlock auto mode and per-strategy tuning. The manual [newsroom_timeline] shortcode keeps working in the free edition.', 'newsroom-ai-assistant' ),
                        'auto-timeline'
                    );
                    ?>
                    <div aria-hidden="true" style="opacity:.55;pointer-events:none;margin-top:12px;">
                <?php endif; ?>
                <table class="form-table">
                    <tr><th>Injection Mode</th><td>
                        <select name="t_mode">
                            <option value="auto" <?php selected(get_option('newsai_timeline_mode', 'auto'), 'auto'); ?>>⚡ Auto-Pilot</option>
                            <option value="manual" <?php selected(get_option('newsai_timeline_mode', 'auto'), 'manual'); ?>>✋ Manual Only</option>
                        </select>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['timeline_items']); ?></th><td><input type="number" name="t_limit" value="<?php echo esc_attr(get_option('newsai_timeline_limit', 4)); ?>" class="small-text" min="1" max="10"></td></tr>
                    <tr><th>Search Past Days</th><td><input type="number" name="t_days" value="<?php echo esc_attr(get_option('newsai_timeline_days', 30)); ?>" class="small-text"></td></tr>
                    <tr><th><?php echo esc_html($i18n['timeline_strategy']); ?></th><td>
                        <select name="t_strategy">
                            <option value="breaking" <?php selected(get_option('newsai_timeline_strategy', 'ongoing'), 'breaking'); ?>><?php echo esc_html($i18n['timeline_breaking']); ?></option>
                            <option value="ongoing" <?php selected(get_option('newsai_timeline_strategy', 'ongoing'), 'ongoing'); ?>><?php echo esc_html($i18n['timeline_ongoing']); ?></option>
                            <option value="evergreen" <?php selected(get_option('newsai_timeline_strategy', 'ongoing'), 'evergreen'); ?>><?php echo esc_html($i18n['timeline_evergreen']); ?></option>
                        </select>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['timeline_threshold']); ?></th><td>
                        <input type="range" name="t_relevance" min="1" max="15" step="1" value="<?php echo esc_attr(get_option('newsai_timeline_relevance_threshold', 5)); ?>" oninput="this.nextElementSibling.value=this.value">
                        <output style="display:inline-block; min-width:24px; font-weight:700;"><?php echo esc_html((string)get_option('newsai_timeline_relevance_threshold', 5)); ?></output>
                        <p class="description"><?php echo esc_html($i18n['timeline_threshold_desc']); ?></p>
                        <p class="description"><em><?php echo esc_html($i18n['timeline_threshold_presets']); ?></em></p>
                    </td></tr>
                    <tr><th>Auto-Insert After Paragraph</th><td><input type="number" name="t_para" value="<?php echo esc_attr(get_option('newsai_timeline_para', -1)); ?>" class="small-text"></td></tr>
                    <tr><th>Timeline Heading</th><td>
                        <input type="text" name="t_heading" value="<?php echo esc_attr(get_option('newsai_timeline_heading', '⏳ Το Χρονικό της Είδησης: {tag}')); ?>" class="regular-text" style="width: 100%;">
                        <p class="description"><?php echo wp_kses_post($i18n['timeline_use_tag']); ?></p>
                    </td></tr>
                    <tr><th colspan="2" style="padding-top:16px;"><?php echo esc_html($i18n['timeline_labels']); ?></th></tr>
                    <tr><td colspan="2"><p class="description" style="margin: 0 0 10px;"><?php echo esc_html($i18n['timeline_labels_help']); ?></p></td></tr>
                    <tr><th><?php echo esc_html($i18n['lbl_today']); ?></th><td><input type="text" name="t_lbl_today" value="<?php echo esc_attr(get_option('newsai_timeline_label_today', '')); ?>" class="regular-text" placeholder="<?php echo esc_attr($i18n['ph_today']); ?>"></td></tr>
                    <tr><th><?php echo esc_html($i18n['lbl_yesterday']); ?></th><td><input type="text" name="t_lbl_yesterday" value="<?php echo esc_attr(get_option('newsai_timeline_label_yesterday', '')); ?>" class="regular-text" placeholder="<?php echo esc_attr($i18n['ph_yesterday']); ?>"></td></tr>
                    <tr><th><?php echo esc_html($i18n['lbl_days_ago']); ?></th><td><input type="text" name="t_lbl_days_ago" value="<?php echo esc_attr(get_option('newsai_timeline_label_days_ago', '')); ?>" class="regular-text" placeholder="<?php echo esc_attr($i18n['ph_days_ago']); ?>"></td></tr>
                    <tr><th><?php echo esc_html($i18n['lbl_start']); ?></th><td><input type="text" name="t_lbl_start" value="<?php echo esc_attr(get_option('newsai_timeline_label_start', '')); ?>" class="regular-text" placeholder="<?php echo esc_attr($i18n['ph_start']); ?>"></td></tr>
                    <tr><th><?php echo esc_html($i18n['lbl_full_timeline']); ?></th><td><input type="text" name="t_lbl_full" value="<?php echo esc_attr(get_option('newsai_timeline_label_full', '')); ?>" class="regular-text" placeholder="<?php echo esc_attr($i18n['ph_full_timeline']); ?>"></td></tr>
                </table>
                <?php if (!$newsai_is_pro_active): ?>
                    </div>
                <?php endif; ?>
                </div>

                <div class="nros-settings-pane" data-pane="ux">
                <hr style="margin: 20px 0; border-top: 1px solid #f0f0f1;">
                <h3><?php echo esc_html($i18n['ux_ai_title']); ?></h3>
                <table class="form-table">
                    <tr><th><?php echo esc_html($i18n['toggle_gauge']); ?></th><td><label><input type="checkbox" name="ui_circular_gauge" value="yes" <?php checked(get_option('newsai_ui_circular_gauge', 'yes'), 'yes'); ?>> <?php echo esc_html(__( 'On', 'newsroom-ai-assistant' )); ?></label><p class="description"><?php echo esc_html( $i18n['toggle_gauge_desc'] ); ?></p></td></tr>
                    <tr><th><?php echo esc_html($i18n['toggle_onboarding']); ?></th><td><label><input type="checkbox" name="ui_onboarding_modal" value="yes" <?php checked(get_option('newsai_ui_onboarding_modal', 'yes'), 'yes'); ?>> <?php echo esc_html(__( 'On', 'newsroom-ai-assistant' )); ?></label><p class="description"><?php echo esc_html( $i18n['toggle_onboarding_desc'] ); ?></p></td></tr>
                    <tr><th><?php echo esc_html($i18n['toggle_nlp']); ?></th><td><label><input type="checkbox" name="advanced_nlp" value="yes" <?php checked(get_option('newsai_advanced_nlp', 'yes'), 'yes'); ?>> <?php echo esc_html(__( 'On', 'newsroom-ai-assistant' )); ?></label><p class="description"><?php echo esc_html( $i18n['toggle_nlp_desc'] ); ?></p></td></tr>
                    <tr><th><?php echo esc_html($i18n['toggle_mobile_sheet']); ?></th><td><label><input type="checkbox" name="ui_mobile_bottom_sheet" value="yes" <?php checked(get_option('newsai_mobile_bottom_sheet', 'yes'), 'yes'); ?>> <?php echo esc_html(__( 'On', 'newsroom-ai-assistant' )); ?></label><p class="description"><?php echo esc_html( $i18n['toggle_mobile_sheet_desc'] ); ?></p></td></tr>
                    <tr><th><?php echo esc_html($i18n['toggle_faq_block']); ?></th><td><label><input type="checkbox" name="editor_faq_enabled" value="yes" <?php checked(get_option('newsai_editor_faq_enabled', 'no'), 'yes'); ?>> <?php echo esc_html(__( 'On', 'newsroom-ai-assistant' )); ?></label><p class="description"><?php echo esc_html( $i18n['toggle_faq_block_desc'] ); ?></p></td></tr>
                    <tr><th><?php echo esc_html($i18n['toggle_floating_ai']); ?></th><td><label><input type="checkbox" name="editor_floating_ai" value="yes" <?php checked(get_option('newsai_editor_floating_ai', 'yes'), 'yes'); ?>> <?php echo esc_html(__( 'On', 'newsroom-ai-assistant' )); ?></label><p class="description"><?php echo esc_html( $i18n['toggle_floating_ai_desc'] ); ?></p></td></tr>
                    <tr>
                        <th>
                            <?php echo esc_html(__( 'Duplicate tag guard', 'newsroom-ai-assistant' )); ?>
                            <?php if (!$newsai_is_pro_active): ?>
                                <span style="display:inline-block;margin-left:6px;padding:1px 8px;border-radius:999px;background:#e0e7ff;color:#3730a3;font-weight:600;font-size:10px;letter-spacing:.04em;text-transform:uppercase;">Pro</span>
                            <?php endif; ?>
                        </th>
                        <td>
                            <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                                <input type="checkbox" name="tag_guard_enabled" value="yes"
                                       <?php checked(get_option('newsai_tag_guard_enabled', 'yes'), 'yes'); ?>
                                       <?php disabled(!$newsai_is_pro_active); ?>>
                                <?php echo esc_html(__( 'On', 'newsroom-ai-assistant' )); ?>
                            </label>
                            <p class="description">
                                <?php echo esc_html(__( 'Warns editors before saving a tag that closely matches an existing one. Adds “Use suggested” / “Keep anyway” actions in Gutenberg and the Classic editor.', 'newsroom-ai-assistant' )); ?>
                            </p>
                            <?php if (!$newsai_is_pro_active && function_exists('newsai_pro_promo_link')): ?>
                                <p>
                                    <a href="<?php echo esc_url(newsai_pro_promo_link('tag-guard-toggle')); ?>" target="_blank" rel="noopener" class="button button-secondary">
                                        🔒 <?php echo esc_html(__( 'Unlock with Pro', 'newsroom-ai-assistant' )); ?>
                                    </a>
                                </p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php
                    $tag_pool_current = function_exists( 'newsai_tag_pool_size_get' ) ? newsai_tag_pool_size_get() : 800;
                    $tag_pool_choices = function_exists( 'newsai_tag_pool_size_choices' ) ? newsai_tag_pool_size_choices() : [ 800 => '800' ];
                    ?>
                    <tr>
                        <th><?php echo esc_html( __( 'Tag pool size', 'newsroom-ai-assistant' ) ); ?></th>
                        <td>
                            <fieldset>
                                <?php foreach ( $tag_pool_choices as $size => $label ) : ?>
                                    <label style="display:block; margin-bottom:6px;">
                                        <input type="radio" name="tag_pool_size" value="<?php echo esc_attr( (string) $size ); ?>"
                                            <?php checked( $tag_pool_current, $size ); ?>>
                                        <?php echo esc_html( $label ); ?>
                                    </label>
                                <?php endforeach; ?>
                            </fieldset>
                            <p class="description">
                                <?php echo esc_html( __( 'How many existing tags (by usage) to load for duplicate-tag guard checks (server-side).', 'newsroom-ai-assistant' ) ); ?>
                            </p>
                        </td>
                    </tr>
                    <?php
                    $tag_editor_current = function_exists( 'newsai_tag_pool_editor_size_get' ) ? newsai_tag_pool_editor_size_get() : 300;
                    $tag_editor_choices = function_exists( 'newsai_tag_pool_editor_size_choices' ) ? newsai_tag_pool_editor_size_choices() : [ 300 => '300' ];
                    ?>
                    <tr>
                        <th><?php echo esc_html( __( 'Editor tag pool (sidebar JSON)', 'newsroom-ai-assistant' ) ); ?></th>
                        <td>
                            <fieldset>
                                <?php foreach ( $tag_editor_choices as $size => $label ) : ?>
                                    <label style="display:block; margin-bottom:6px;">
                                        <input type="radio" name="tag_pool_editor_size" value="<?php echo esc_attr( (string) $size ); ?>"
                                            <?php checked( $tag_editor_current, $size ); ?>>
                                        <?php echo esc_html( $label ); ?>
                                    </label>
                                <?php endforeach; ?>
                            </fieldset>
                            <p class="description">
                                <?php echo esc_html( __( 'Tags embedded in the post editor for local suggestions. Kept smaller than the guard pool for faster page loads.', 'newsroom-ai-assistant' ) ); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html( __( 'Wikidata auto-enrich', 'newsroom-ai-assistant' ) ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="wikidata_enrich_enabled" value="yes" <?php checked( get_option( 'newsai_wikidata_enrich_enabled', 'yes' ), 'yes' ); ?>>
                                <?php echo esc_html( __( 'Fill empty tag Wikidata / entity fields when a tag is used on a post (lazy, once per tag).', 'newsroom-ai-assistant' ) ); ?>
                            </label>
                        </td>
                    </tr>
                    <?php
                    $sem_profiles = function_exists( 'newsai_sem_links_profiles' ) ? newsai_sem_links_profiles() : [];
                    $sem_current  = (string) get_option( 'newsai_sem_links_profile', 'balanced' );
                    if ( ! isset( $sem_profiles[ $sem_current ] ) ) {
                        $sem_current = 'balanced';
                    }
                    ?>
                    <tr>
                        <th><?php echo esc_html( __( 'Archive link suggestions', 'newsroom-ai-assistant' ) ); ?></th>
                        <td>
                            <fieldset>
                                <?php foreach ( $sem_profiles as $sem_key => $sem_cfg ) : ?>
                                    <label style="display:block; margin-bottom:6px;">
                                        <input type="radio" name="sem_links_profile" value="<?php echo esc_attr( $sem_key ); ?>"
                                            <?php checked( $sem_current, $sem_key ); ?>>
                                        <?php echo esc_html( (string) $sem_cfg['label'] ); ?>
                                    </label>
                                <?php endforeach; ?>
                            </fieldset>
                            <p class="description">
                                <?php echo esc_html( __( 'Controls the “Find archive links” button in the editor sidebar: how old posts must be, minimum relevance score, and how many links to show.', 'newsroom-ai-assistant' ) ); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                </div>

                <div class="nros-settings-pane" data-pane="ai_assist">
                <hr style="margin: 20px 0; border-top: 1px solid #f0f0f1;">
                <h3>🧠 <?php echo esc_html(__( 'AI Assist (Pro)', 'newsroom-ai-assistant' )); ?></h3>
                <p class="description" style="max-width:760px;">
                    <?php echo esc_html(__( 'Bring your own OpenAI, Google Gemini or Groq API key to unlock title suggestions after the AI reads your article, targeted (non-rewrite) optimization tips, and trend-aware keyword recommendations powered by Google Trends. Gemini and Groq offer free tiers.', 'newsroom-ai-assistant' )); ?>
                </p>
                <?php if (!$newsai_is_pro_active && function_exists('newsai_pro_render_lock_card')): ?>
                    <?php
                    newsai_pro_render_lock_card(
                        __( 'AI Assist (Pro)', 'newsroom-ai-assistant' ),
                        __( 'Pro license required. The AI never rewrites — it only suggests. You pay only your own AI provider; no data is sent to NewsOS.', 'newsroom-ai-assistant' ),
                        'ai-assist'
                    );
                    ?>
                    <div aria-hidden="true" style="opacity:.55;pointer-events:none;margin-top:12px;">
                <?php endif; ?>
                <?php
                $ai_provider_saved   = (string) get_option('newsai_ai_provider', '');
                $ai_openai_has       = function_exists( 'newsai_secret_has_stored' ) ? newsai_secret_has_stored( 'openai_api_key' ) : ( trim( (string) get_option( 'newsai_ai_openai_api_key', '' ) ) !== '' );
                $ai_gemini_has       = function_exists( 'newsai_secret_has_stored' ) ? newsai_secret_has_stored( 'gemini_api_key' ) : ( trim( (string) get_option( 'newsai_ai_gemini_api_key', '' ) ) !== '' );
                $ai_groq_has         = function_exists( 'newsai_secret_has_stored' ) ? newsai_secret_has_stored( 'groq_api_key' ) : ( trim( (string) get_option( 'newsai_ai_groq_api_key', '' ) ) !== '' );
                $ai_openai_locked    = function_exists( 'newsai_secret_is_locked' ) && newsai_secret_is_locked( 'openai_api_key' );
                $ai_gemini_locked    = function_exists( 'newsai_secret_is_locked' ) && newsai_secret_is_locked( 'gemini_api_key' );
                $ai_groq_locked      = function_exists( 'newsai_secret_is_locked' ) && newsai_secret_is_locked( 'groq_api_key' );
                $ai_openai_mask      = $ai_openai_has && function_exists( 'newsai_secret_get' ) ? newsai_secret_mask( newsai_secret_get( 'openai_api_key' ) ) : '';
                $ai_gemini_mask      = $ai_gemini_has && function_exists( 'newsai_secret_get' ) ? newsai_secret_mask( newsai_secret_get( 'gemini_api_key' ) ) : '';
                $ai_groq_mask        = $ai_groq_has && function_exists( 'newsai_secret_get' ) ? newsai_secret_mask( newsai_secret_get( 'groq_api_key' ) ) : '';
                $ai_openai_model     = (string) get_option('newsai_ai_openai_model', defined('NEWSAI_AI_DEFAULT_OPENAI_MODEL') ? NEWSAI_AI_DEFAULT_OPENAI_MODEL : 'gpt-4o-mini');
                $ai_gemini_model     = (string) get_option('newsai_ai_gemini_model', defined('NEWSAI_AI_DEFAULT_GEMINI_MODEL') ? NEWSAI_AI_DEFAULT_GEMINI_MODEL : 'gemini-2.5-flash');
                $ai_groq_model       = (string) get_option('newsai_ai_groq_model', defined('NEWSAI_AI_DEFAULT_GROQ_MODEL') ? NEWSAI_AI_DEFAULT_GROQ_MODEL : 'llama-3.3-70b-versatile');
                $ai_daily_limit      = (int) get_option('newsai_ai_daily_limit_per_user', defined('NEWSAI_AI_DAILY_DEFAULT_LIMIT') ? NEWSAI_AI_DAILY_DEFAULT_LIMIT : 50);
                ?>
                <div style="background:#fff8e5;border:1px solid #f0d78c;border-left:4px solid #dba617;border-radius:6px;padding:12px 14px;margin:0 0 16px 0;max-width:760px;">
                    <p style="margin:0;font-size:13px;color:#50575e;">
                        <strong><?php echo esc_html( __( 'Privacy notice', 'newsroom-ai-assistant' ) ); ?>:</strong>
                        <?php echo esc_html( __( 'When AI Assist runs, article title and body text are sent directly from your server to the API provider you select (OpenAI, Google Gemini, or Groq). NewsOS does not proxy that traffic. Keys are stored in the database as plaintext unless you define constants in wp-config.php.', 'newsroom-ai-assistant' ) ); ?>
                    </p>
                </div>
                <p class="description" style="max-width:760px;margin:0 0 12px 0;">
                    <?php echo esc_html( __( 'Optional wp-config.php overrides (not editable here): NEWSAI_OPENAI_API_KEY, NEWSAI_GEMINI_API_KEY, NEWSAI_GROQ_API_KEY, NEWSAI_INDEXING_SERVICE_JSON, NEWSAI_PRO_LICENSE_KEY.', 'newsroom-ai-assistant' ) ); ?>
                </p>
                <table class="form-table">
                    <tr>
                        <th><?php echo esc_html(__( 'AI provider', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <label style="margin-right:14px;">
                                <input type="radio" name="ai_provider" value=""
                                       <?php checked($ai_provider_saved, ''); ?>>
                                <?php echo esc_html(__( 'None (disabled)', 'newsroom-ai-assistant' )); ?>
                            </label>
                            <label style="margin-right:14px;">
                                <input type="radio" name="ai_provider" value="openai"
                                       <?php checked($ai_provider_saved, 'openai'); ?>>
                                OpenAI
                            </label>
                            <label style="margin-right:14px;">
                                <input type="radio" name="ai_provider" value="gemini"
                                       <?php checked($ai_provider_saved, 'gemini'); ?>>
                                Google Gemini
                            </label>
                            <label>
                                <input type="radio" name="ai_provider" value="groq"
                                       <?php checked($ai_provider_saved, 'groq'); ?>>
                                Groq <span style="color:#646970;font-size:11px;">(<?php echo esc_html(__( 'free, very fast', 'newsroom-ai-assistant' )); ?>)</span>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th>OpenAI API key</th>
                        <td>
                            <?php if ( $ai_openai_locked ) : ?>
                                <p style="margin:0 0 8px 0;"><code><?php echo esc_html( newsai_secret_mask( newsai_secret_get( 'openai_api_key' ) ) ); ?></code>
                                <span style="color:#646970;font-size:12px;"> — <?php echo esc_html( __( 'Set via NEWSAI_OPENAI_API_KEY in wp-config.php', 'newsroom-ai-assistant' ) ); ?></span></p>
                            <?php else : ?>
                            <input type="password" name="ai_openai_api_key" value="" autocomplete="new-password"
                                   placeholder="<?php echo esc_attr( $ai_openai_has ? $ai_openai_mask : 'sk-...' ); ?>"
                                   class="regular-text" style="width:100%;max-width:520px;">
                            <?php endif; ?>
                            <p class="description">
                                <?php
                                $openai_link = '<a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener">platform.openai.com/api-keys</a>';
                                echo wp_kses_post( sprintf(
                                    /* translators: %s: HTML link to OpenAI key dashboard */
                                    __( 'Get a key at %s. Leave blank to keep the saved key. Stored as a non-autoloaded option (plaintext in the database).', 'newsroom-ai-assistant' ),
                                    $openai_link
                                ) );
                                ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( 'OpenAI model', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <input type="text" name="ai_openai_model" value="<?php echo esc_attr($ai_openai_model); ?>" class="regular-text" placeholder="gpt-4o-mini">
                            <p class="description">gpt-4o-mini, gpt-4o, …</p>
                        </td>
                    </tr>
                    <tr>
                        <th>Gemini API key</th>
                        <td>
                            <?php if ( $ai_gemini_locked ) : ?>
                                <p style="margin:0 0 8px 0;"><code><?php echo esc_html( newsai_secret_mask( newsai_secret_get( 'gemini_api_key' ) ) ); ?></code>
                                <span style="color:#646970;font-size:12px;"> — <?php echo esc_html( __( 'Set via NEWSAI_GEMINI_API_KEY in wp-config.php', 'newsroom-ai-assistant' ) ); ?></span></p>
                            <?php else : ?>
                            <input type="password" name="ai_gemini_api_key" value="" autocomplete="new-password"
                                   placeholder="<?php echo esc_attr( $ai_gemini_has ? $ai_gemini_mask : 'AIza...' ); ?>"
                                   class="regular-text" style="width:100%;max-width:520px;">
                            <?php endif; ?>
                            <p class="description">
                                <?php
                                $gemini_link = '<a href="https://aistudio.google.com/apikey" target="_blank" rel="noopener">aistudio.google.com/apikey</a>';
                                echo wp_kses_post( sprintf(
                                    /* translators: %s: HTML link to Google AI Studio key page */
                                    __( 'Get a free key at %s (Google AI Studio → Create API key). Leave blank to keep the saved key.', 'newsroom-ai-assistant' ),
                                    $gemini_link
                                ) );
                                ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( 'Gemini model', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <input type="text" name="ai_gemini_model" value="<?php echo esc_attr($ai_gemini_model); ?>" class="regular-text" placeholder="gemini-2.5-flash">
                            <p class="description">
                                <?php echo esc_html(__( 'Recommended: gemini-2.5-flash (default). Alternatives: gemini-2.5-flash-lite (cheapest), gemini-2.5-pro (highest quality). Older 1.5-* names are deprecated and auto-mapped to the default.', 'newsroom-ai-assistant' )); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th>Groq API key</th>
                        <td>
                            <?php if ( $ai_groq_locked ) : ?>
                                <p style="margin:0 0 8px 0;"><code><?php echo esc_html( newsai_secret_mask( newsai_secret_get( 'groq_api_key' ) ) ); ?></code>
                                <span style="color:#646970;font-size:12px;"> — <?php echo esc_html( __( 'Set via NEWSAI_GROQ_API_KEY in wp-config.php', 'newsroom-ai-assistant' ) ); ?></span></p>
                            <?php else : ?>
                            <input type="password" name="ai_groq_api_key" value="" autocomplete="new-password"
                                   placeholder="<?php echo esc_attr( $ai_groq_has ? $ai_groq_mask : 'gsk_...' ); ?>"
                                   class="regular-text" style="width:100%;max-width:520px;">
                            <?php endif; ?>
                            <p class="description">
                                <?php
                                $groq_link = '<a href="https://console.groq.com/keys" target="_blank" rel="noopener">console.groq.com/keys</a>';
                                echo wp_kses_post( sprintf(
                                    /* translators: %s: HTML link to Groq console keys page */
                                    __( 'Get a free key at %s (Sign in → API Keys → Create API Key). Free tier is rate-limited but generous; inference is the fastest among supported providers.', 'newsroom-ai-assistant' ),
                                    $groq_link
                                ) );
                                ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( 'Groq model', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <input type="text" name="ai_groq_model" value="<?php echo esc_attr($ai_groq_model); ?>" class="regular-text" placeholder="llama-3.3-70b-versatile">
                            <p class="description">
                                <?php echo esc_html(__( 'Recommended: llama-3.3-70b-versatile (default, ~280 tok/s). Alternatives: llama-3.1-8b-instant (faster), openai/gpt-oss-120b (higher quality), openai/gpt-oss-20b (balanced).', 'newsroom-ai-assistant' )); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( 'Daily AI calls per user', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <input type="number" name="ai_daily_limit" value="<?php echo esc_attr((string) $ai_daily_limit); ?>" min="0" max="1000" class="small-text">
                            <p class="description">
                                <?php echo esc_html(__( '0 = unlimited. Counter resets at UTC midnight.', 'newsroom-ai-assistant' )); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( 'Auto alt text (images)', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <label style="display:block;margin-bottom:6px;">
                                <input type="checkbox" name="ai_alt_enabled" value="yes" <?php checked( get_option( 'newsai_ai_alt_enabled', 'no' ), 'yes' ); ?>>
                                <?php echo esc_html(__( 'Generate descriptive alt text with AI (OpenAI/Gemini vision)', 'newsroom-ai-assistant' )); ?>
                            </label>
                            <label style="display:block;">
                                <input type="checkbox" name="ai_alt_on_upload" value="yes" <?php checked( get_option( 'newsai_ai_alt_on_upload', 'yes' ), 'yes' ); ?>>
                                <?php echo esc_html(__( 'Run automatically on image upload when alt is empty (5s delay, counts toward daily limit)', 'newsroom-ai-assistant' )); ?>
                            </label>
                            <p class="description"><?php echo esc_html(__( 'Media Library shows a “Generate alt (AI)” button. Never overwrites existing alt text. Improves accessibility and Discover score.', 'newsroom-ai-assistant' )); ?></p>
                        </td>
                    </tr>
                </table>
                <?php if (!$newsai_is_pro_active): ?>
                    </div>
                <?php endif; ?>
                </div>

                <div class="nros-settings-pane" data-pane="team">
                <hr style="margin: 20px 0; border-top: 1px solid #f0f0f1;">
                <h3>👥 <?php echo esc_html(__( 'Team workflow (Pro)', 'newsroom-ai-assistant' )); ?></h3>
                <p class="description" style="max-width:760px;">
                    <?php echo esc_html(__( 'Built-in messaging between the editor-in-chief and writers on each assigned story, plus email notifications for assignments, new messages, and completions.', 'newsroom-ai-assistant' )); ?>
                </p>
                <?php if (!$newsai_is_pro_active && function_exists('newsai_pro_render_lock_card')): ?>
                    <?php
                    newsai_pro_render_lock_card(
                        __( 'Team messaging & email (Pro)', 'newsroom-ai-assistant' ),
                        __( 'Pro license required. Free sites keep the dashboard task board; messaging threads and automated emails activate after Pro.', 'newsroom-ai-assistant' ),
                        'team-workflow'
                    );
                    ?>
                    <div aria-hidden="true" style="opacity:.55;pointer-events:none;margin-top:12px;">
                <?php endif; ?>
                <table class="form-table">
                    <tr>
                        <th><?php echo esc_html(__( 'In-task messaging', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                                <input type="checkbox" name="task_messaging_enabled" value="yes"
                                       <?php checked(get_option('newsai_task_messaging_enabled', 'yes'), 'yes'); ?>
                                       <?php disabled(!$newsai_is_pro_active); ?>>
                                <?php echo esc_html(__( 'Show the “Discussion” thread on every task in the dashboard.', 'newsroom-ai-assistant' )); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( 'Email notifications', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                                <input type="checkbox" name="task_email_enabled" value="yes"
                                       <?php checked(get_option('newsai_task_email_enabled', 'yes'), 'yes'); ?>
                                       <?php disabled(!$newsai_is_pro_active); ?>>
                                <?php echo esc_html(__( 'Master switch — required for the individual notifications below.', 'newsroom-ai-assistant' )); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( '— Assignment', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                                <input type="checkbox" name="task_email_assigned" value="yes"
                                       <?php checked(get_option('newsai_task_email_assigned', 'yes'), 'yes'); ?>
                                       <?php disabled(!$newsai_is_pro_active); ?>>
                                <?php echo esc_html(__( 'Email the author when a task is assigned or reassigned.', 'newsroom-ai-assistant' )); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( '— New message', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                                <input type="checkbox" name="task_email_message" value="yes"
                                       <?php checked(get_option('newsai_task_email_message', 'yes'), 'yes'); ?>
                                       <?php disabled(!$newsai_is_pro_active); ?>>
                                <?php echo esc_html(__( 'Email thread participants when a new message is posted.', 'newsroom-ai-assistant' )); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( '— Completion', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                                <input type="checkbox" name="task_email_done" value="yes"
                                       <?php checked(get_option('newsai_task_email_done', 'yes'), 'yes'); ?>
                                       <?php disabled(!$newsai_is_pro_active); ?>>
                                <?php echo esc_html(__( 'Email the team when a task is marked done.', 'newsroom-ai-assistant' )); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html(__( 'Auto-purge threads', 'newsroom-ai-assistant' )); ?></th>
                        <td>
                            <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                                <input type="number" name="task_retention_days" min="0" max="365" step="1"
                                       value="<?php echo esc_attr((string) get_option('newsai_task_messages_retention_days', 30)); ?>"
                                       class="small-text"
                                       <?php disabled(!$newsai_is_pro_active); ?>>
                                <?php echo esc_html(__( 'days after the task is marked done (0 = never auto-delete).', 'newsroom-ai-assistant' )); ?>
                            </label>
                            <p class="description">
                                <?php
                                $last_purge       = (int) get_option('newsai_task_last_purge', 0);
                                $last_purge_count = (int) get_option('newsai_task_last_purge_count', 0);
                                if ($last_purge > 0) {
                                    echo esc_html( sprintf(
                                        /* translators: 1: date/time in UTC, 2: number of messages removed */
                                        __( 'Last run: %1$s UTC, %2$d messages removed.', 'newsroom-ai-assistant' ),
                                        gmdate( 'Y-m-d H:i:s', $last_purge ),
                                        $last_purge_count
                                    ) );
                                } else {
                                    echo esc_html(__( 'Cron has not run yet.', 'newsroom-ai-assistant' ));
                                }
                                ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th colspan="2"><h3 style="margin:24px 0 8px;"><?php echo esc_html( $i18n['weekly_report_title'] ); ?></h3></th>
                    </tr>
                    <tr>
                        <th><?php echo esc_html( $i18n['weekly_report_enabled'] ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="weekly_report_enabled" value="yes" <?php checked( get_option( 'newsai_weekly_report_enabled', 'no' ), 'yes' ); ?>>
                                <?php echo esc_html( $i18n['weekly_report_enabled_desc'] ); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html( $i18n['weekly_report_recipients'] ); ?></th>
                        <td>
                            <textarea name="weekly_report_recipients" rows="3" class="large-text" placeholder="editor@newsroom.example"><?php echo esc_textarea( (string) get_option( 'newsai_weekly_report_recipients', '' ) ); ?></textarea>
                            <p class="description"><?php echo esc_html( $i18n['weekly_report_recipients_desc'] ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html( $i18n['weekly_report_window'] ); ?></th>
                        <td>
                            <?php $wr_win = (int) get_option( 'newsai_weekly_report_window_days', 7 ); ?>
                            <select name="weekly_report_window_days">
                                <option value="7" <?php selected( $wr_win, 7 ); ?>><?php echo esc_html__( '7 days', 'newsroom-ai-assistant' ); ?></option>
                                <option value="14" <?php selected( $wr_win, 14 ); ?>><?php echo esc_html__( '14 days', 'newsroom-ai-assistant' ); ?></option>
                                <option value="30" <?php selected( $wr_win, 30 ); ?>><?php echo esc_html__( '30 days', 'newsroom-ai-assistant' ); ?></option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html( $i18n['weekly_report_test'] ); ?></th>
                        <td>
                            <button type="button" class="button" id="newsai-weekly-report-test"><?php echo esc_html( $i18n['weekly_report_test'] ); ?></button>
                            <span id="newsai-weekly-report-test-status" style="margin-left:8px;font-size:12px;color:#646970;"></span>
                            <p class="description">
                                <?php
                                $wr_last = (int) get_option( 'newsai_weekly_report_last_sent', 0 );
                                $wr_cnt  = (int) get_option( 'newsai_weekly_report_last_count', 0 );
                                if ( $wr_last > 0 ) {
                                    echo esc_html(
                                        sprintf(
                                            /* translators: 1: label, 2: UTC datetime, 3: recipient count */
                                            __( '%1$s: %2$s UTC — %3$d recipient(s).', 'newsroom-ai-assistant' ),
                                            $i18n['weekly_report_last'],
                                            gmdate( 'Y-m-d H:i', $wr_last ),
                                            $wr_cnt
                                        )
                                    );
                                } else {
                                    echo esc_html__( 'No report has been sent yet.', 'newsroom-ai-assistant' );
                                }
                                ?>
                            </p>
                            <p class="description"><?php echo esc_html__( 'Uses your WordPress admin email as sender. If the test fails, install an SMTP plugin — many hosts block PHP mail().', 'newsroom-ai-assistant' ); ?></p>
                        </td>
                    </tr>
                </table>
                <?php if (!$newsai_is_pro_active): ?>
                    </div>
                <?php endif; ?>
                </div>

                <div class="nros-settings-pane" data-pane="indexing">
                <hr style="margin: 20px 0; border-top: 1px solid #f0f0f1;">
                <h3>⚡ <?php echo esc_html(__( 'Instant Indexing (Pro)', 'newsroom-ai-assistant' )); ?></h3>
                <p class="description" style="max-width:760px;">
                    <?php echo esc_html(__( 'Push every newly-published article to Google Indexing API and Microsoft Bing / Yandex (IndexNow) within seconds, so it surfaces in search and Discover faster.', 'newsroom-ai-assistant' )); ?>
                </p>
                <?php if (!$newsai_is_pro_active && function_exists('newsai_pro_render_lock_card')): ?>
                    <?php
                    newsai_pro_render_lock_card(
                        __( 'Instant Indexing (Pro)', 'newsroom-ai-assistant' ),
                        __( 'Pro license required. Without Pro, the ping queue is paused so saved drafts never call external APIs.', 'newsroom-ai-assistant' ),
                        'instant-indexing'
                    );
                    ?>
                    <div aria-hidden="true" style="opacity:.55;pointer-events:none;margin-top:12px;">
                <?php endif; ?>

                <h4 style="margin-top:18px;">🔵 Google Indexing API</h4>
                <table class="form-table">
                    <tr><th><?php echo esc_html($i18n['indexing_enabled']); ?></th><td>
                        <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                            <input type="checkbox" name="indexing_enabled" value="yes" <?php checked(get_option('newsai_indexing_enabled', 'no'), 'yes'); ?> <?php disabled(!$newsai_is_pro_active); ?>>
                            <?php echo esc_html(__( 'Ping Google on save', 'newsroom-ai-assistant' )); ?>
                        </label>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['indexing_publish_only']); ?></th><td>
                        <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                            <input type="checkbox" name="indexing_publish_only" value="yes" <?php checked(get_option('newsai_indexing_publish_only', 'yes'), 'yes'); ?> <?php disabled(!$newsai_is_pro_active); ?>>
                            <?php echo esc_html(__( 'Only ping for "publish" status (recommended)', 'newsroom-ai-assistant' )); ?>
                        </label>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['indexing_sa_json']); ?></th><td>
                        <?php
                        $indexing_json_has    = function_exists( 'newsai_secret_has_stored' ) && newsai_secret_has_stored( 'indexing_service_json' );
                        $indexing_json_locked = function_exists( 'newsai_secret_is_locked' ) && newsai_secret_is_locked( 'indexing_service_json' );
                        $indexing_sa_email_ui = function_exists( 'newsai_secret_indexing_client_email' ) ? newsai_secret_indexing_client_email() : (string) get_option( 'newsai_indexing_service_email', '' );
                        ?>
                        <?php if ( $indexing_json_has ) : ?>
                            <p style="margin:0 0 10px 0;">
                                <span style="display:inline-block;font-weight:600;color:#15803d;background:#ecfdf5;border:1px solid #a7f3d0;border-radius:4px;padding:2px 8px;font-size:12px;">
                                    <?php echo esc_html( __( 'Service account configured', 'newsroom-ai-assistant' ) ); ?>
                                </span>
                                <?php if ( $indexing_sa_email_ui !== '' ) : ?>
                                    <span style="margin-left:8px;font-size:12px;color:#50575e;"><?php echo esc_html( __( 'Client email:', 'newsroom-ai-assistant' ) ); ?> <code><?php echo esc_html( $indexing_sa_email_ui ); ?></code></span>
                                <?php endif; ?>
                            </p>
                            <p class="description" style="margin-top:0;"><?php echo esc_html( __( 'Private key JSON is not shown here. Use “Replace JSON” to paste a new file, or remove the stored credentials.', 'newsroom-ai-assistant' ) ); ?></p>
                        <?php else : ?>
                            <p class="description" style="margin:0 0 10px 0;"><?php echo esc_html( __( 'No service account stored yet.', 'newsroom-ai-assistant' ) ); ?></p>
                        <?php endif; ?>
                        <?php if ( $indexing_json_locked ) : ?>
                            <p class="description" style="color:#646970;"><?php echo esc_html( __( 'Credentials are supplied via NEWSAI_INDEXING_SERVICE_JSON in wp-config.php and cannot be edited in this screen.', 'newsroom-ai-assistant' ) ); ?></p>
                        <?php else : ?>
                            <?php if ( $indexing_json_has ) : ?>
                            <p style="margin:0 0 8px 0;">
                                <label><input type="checkbox" name="indexing_service_json_replace" value="1" id="newsai-indexing-json-replace" <?php disabled( ! $newsai_is_pro_active ); ?> />
                                <?php echo esc_html( __( 'Replace service account JSON', 'newsroom-ai-assistant' ) ); ?></label>
                            </p>
                            <?php endif; ?>
                            <textarea name="indexing_service_json" id="newsai-indexing-json-field" rows="6" style="width:100%; font-family:Consolas,Monaco,monospace;<?php echo esc_attr( $indexing_json_has ? ' display:none;' : '' ); ?>" placeholder='{"type":"service_account","project_id":"...","client_email":"...","private_key":"..."}' <?php disabled(!$newsai_is_pro_active); ?>></textarea>
                            <?php if ( $indexing_json_has ) : ?>
                                <p style="margin:8px 0 0 0;">
                                    <label><input type="checkbox" name="indexing_service_json_clear" value="1" id="newsai-indexing-json-clear" <?php disabled( ! $newsai_is_pro_active ); ?> />
                                    <?php echo esc_html( __( 'Remove stored service account JSON from the database', 'newsroom-ai-assistant' ) ); ?></label>
                                </p>
                            <?php endif; ?>
                            <p style="margin:10px 0 0 0;">
                                <button type="button" id="newsai-save-indexing-sa" class="button button-secondary" <?php disabled( ! $newsai_is_pro_active ); ?>>
                                    <?php echo esc_html( __( 'Save service account JSON', 'newsroom-ai-assistant' ) ); ?>
                                </button>
                                <span id="newsai-save-indexing-sa-result" style="margin-left:10px;font-size:12px;"></span>
                            </p>
                            <p class="description"><?php echo esc_html( $indexing_json_has ? __( 'Paste the full JSON file from Google Cloud → IAM → Service accounts. Use the button above — it saves via AJAX so megasite settings forms cannot drop this field.', 'newsroom-ai-assistant' ) : __( 'Paste the full JSON file from Google Cloud → IAM → Service accounts, then click “Save service account JSON”.', 'newsroom-ai-assistant' ) ); ?></p>
                            <?php if ( $indexing_json_has ) : ?>
                            <script>
                            (function () {
                                var cb = document.getElementById('newsai-indexing-json-replace');
                                var ta = document.getElementById('newsai-indexing-json-field');
                                if (!cb || !ta) { return; }
                                function sync() { ta.style.display = cb.checked ? 'block' : 'none'; }
                                cb.addEventListener('change', sync);
                                sync();
                            })();
                            </script>
                            <?php endif; ?>
                        <?php endif; ?>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['indexing_sc_property']); ?></th><td>
                        <input type="text" name="indexing_sc_property" value="<?php echo esc_attr($index_sc_property); ?>" class="regular-text" style="width:100%;" placeholder="<?php echo esc_attr( $i18n['indexing_sc_property_ph'] ); ?>" <?php disabled(!$newsai_is_pro_active); ?> autocomplete="off" spellcheck="false">
                        <p class="description"><?php echo esc_html( $i18n['indexing_sc_property_d'] ); ?></p>
                    </td></tr>
                    <tr><th><?php echo esc_html($i18n['indexing_status']); ?></th><td>
                        <?php
                            $status_text = $i18n['indexing_status_unknown'];
                            $status_color = '#646970';
                            if ($index_last_code >= 200 && $index_last_code < 300) {
                                $status_text = $i18n['indexing_status_ok'] . ' • HTTP ' . $index_last_code;
                                $status_color = '#15803d';
                            } elseif ($index_last_code > 0) {
                                $status_text = $i18n['indexing_status_err'] . ' • HTTP ' . $index_last_code;
                                $status_color = '#b91c1c';
                            } elseif ($index_last_ping > 0 && !empty($index_last_error)) {
                                $status_text = $i18n['indexing_status_err'] . ' • ' . $index_last_error;
                                $status_color = '#b91c1c';
                            } elseif ($index_last_ping > 0) {
                                $status_text = $i18n['indexing_status_err'];
                                $status_color = '#b91c1c';
                            } elseif ($newsai_is_pro_active && get_option('newsai_indexing_enabled', 'no') === 'yes') {
                                $status_text = $i18n['indexing_status_pending'];
                                $status_color = '#646970';
                            }
                        ?>
                        <div style="display:inline-block; font-weight:700; padding:4px 8px; border-radius:999px; background:#f6f7f7; color:<?php echo esc_attr($status_color); ?>; border:1px solid #e2e4e7;">
                            <?php echo esc_html($status_text); ?>
                        </div>
                        <div style="display:inline-block; margin-left:6px; font-weight:700; padding:4px 8px; border-radius:999px; background:#f8fafc; color:<?php echo esc_attr( $index_health_color ); ?>; border:1px solid #e2e8f0;">
                            <?php echo esc_html__( 'Health', 'newsroom-ai-assistant' ); ?>: <?php echo esc_html( $index_health_label ); ?>
                        </div>
                        <button type="button" id="newsai-indexing-test" class="button button-secondary" style="margin-left:8px;" <?php disabled(!$newsai_is_pro_active); ?>>🧪 <?php echo esc_html(__( 'Test connection', 'newsroom-ai-assistant' )); ?></button>
                        <span id="newsai-indexing-test-result" style="margin-left:10px; font-size:12px;"></span>
                        <p class="description" style="margin-top:8px;"><?php echo esc_html( $i18n['indexing_test_note'] ); ?></p>
                        <?php if ($index_last_ping > 0): ?>
                            <p class="description" style="margin-top:8px;"><strong><?php echo esc_html__( 'Last attempted ping', 'newsroom-ai-assistant' ); ?>:</strong> <?php echo esc_html(gmdate('Y-m-d H:i:s', $index_last_ping)); ?> UTC<?php if ($index_last_code > 0) : ?> · HTTP <?php echo esc_html((string) $index_last_code); ?><?php endif; ?></p>
                        <?php endif; ?>
                        <?php if (!empty($index_last_url)): ?>
                            <p class="description"><strong><?php echo esc_html__( 'Last attempted URL', 'newsroom-ai-assistant' ); ?>:</strong> <code><?php echo esc_html($index_last_url); ?></code></p>
                        <?php endif; ?>
                        <?php if ($index_last_success_ping > 0): ?>
                            <p class="description" style="margin-top:8px;"><strong><?php echo esc_html__( 'Last successful ping', 'newsroom-ai-assistant' ); ?>:</strong> <?php echo esc_html(gmdate('Y-m-d H:i:s', $index_last_success_ping)); ?> UTC<?php if ($index_last_success_code > 0) : ?> · HTTP <?php echo esc_html((string) $index_last_success_code); ?><?php endif; ?></p>
                        <?php endif; ?>
                        <?php if (!empty($index_last_success_url)): ?>
                            <p class="description"><strong><?php echo esc_html__( 'Last successful URL', 'newsroom-ai-assistant' ); ?>:</strong> <code><?php echo esc_html($index_last_success_url); ?></code></p>
                        <?php endif; ?>
                        <?php if (!empty($index_last_error)): ?>
                            <p class="description" style="color:#b91c1c;"><?php echo esc_html($i18n['indexing_last_error']); ?>: <?php echo esc_html($index_last_error); ?></p>
                        <?php endif; ?>
                        <?php if (!empty($index_service_email)): ?>
                            <p class="description"><?php echo esc_html($i18n['indexing_sa_email']); ?>: <code><?php echo esc_html($index_service_email); ?></code></p>
                        <?php endif; ?>
                    </td></tr>
                </table>
                <details style="background:#eff6ff; border:1px solid #bfdbfe; border-left:4px solid #2563eb; border-radius:8px; padding:12px; margin-top:8px;">
                    <summary style="cursor:pointer; font-weight:700;">📖 <?php echo esc_html(__( 'How to get the Google Service Account JSON (5 steps)', 'newsroom-ai-assistant' )); ?></summary>
                    <ol style="margin:10px 0 0 18px; line-height:1.7;">
                        <li><?php echo wp_kses_post(__( 'Open <a href="https://console.cloud.google.com/" target="_blank" rel="noopener">Google Cloud Console</a> and create a new project (or pick an existing one).', 'newsroom-ai-assistant' )); ?></li>
                        <li><?php echo wp_kses_post(__( 'Go to <strong>APIs &amp; Services → Library</strong> and enable: <em>Indexing API</em>, <em>Google Search Console API</em>, and <em>PageSpeed Insights API</em> (same project).', 'newsroom-ai-assistant' )); ?></li>
                        <li><?php echo wp_kses_post(__( 'Open <strong>IAM &amp; Admin → Service accounts → Create service account</strong>. Give it a name (e.g. "newsroom-os"). After it is created, open it, go to <strong>Keys → Add key → Create new key → JSON</strong>. A JSON file will download — paste its full contents above.', 'newsroom-ai-assistant' )); ?></li>
                        <li><?php echo wp_kses_post(__( 'Open <a href="https://search.google.com/search-console" target="_blank" rel="noopener">Search Console</a> → Settings → Users and permissions → Add user. Paste the service account email (something@project-id.iam.gserviceaccount.com) and grant <strong>Owner</strong> access.', 'newsroom-ai-assistant' )); ?></li>
                        <li><?php echo wp_kses_post(__( 'For Core Web Vitals (optional, recommended): <strong>APIs &amp; Services → Credentials → Create credentials → API key</strong>. Restrict it to <em>PageSpeed Insights API</em> and paste it in the CWV section below.', 'newsroom-ai-assistant' )); ?></li>
                        <li><?php echo esc_html(__( 'Save settings here, then click "Test connection" above. A green check means you are live.', 'newsroom-ai-assistant' )); ?></li>
                    </ol>
                </details>

                <h4 id="newsai-gsc-panel" style="margin-top:26px;">📊 <?php echo esc_html( $i18n['gsc_title'] ); ?></h4>
                <table class="form-table">
                    <tr>
                        <th><?php echo esc_html( $i18n['gsc_enabled'] ); ?></th>
                        <td>
                            <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                                <input type="checkbox" name="gsc_enabled" value="yes" <?php checked( get_option( 'newsai_gsc_enabled', 'no' ), 'yes' ); ?> <?php disabled( ! $newsai_is_pro_active ); ?>>
                                <?php echo esc_html( __( 'Sync web + Discover + Google News metrics into the database', 'newsroom-ai-assistant' ) ); ?>
                            </label>
                            <p class="description"><?php echo esc_html( $i18n['gsc_enabled_d'] ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__( 'Search query sync', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                                <input type="checkbox" name="gsc_query_sync_enabled" value="yes" <?php checked( get_option( 'newsai_gsc_query_sync_enabled', 'yes' ), 'yes' ); ?> <?php disabled( ! $newsai_is_pro_active ); ?>>
                                <?php echo esc_html__( 'Store web search queries (query + date) for Seasonal radar YoY forecasting', 'newsroom-ai-assistant' ); ?>
                            </label>
                            <p class="description"><?php echo esc_html__( 'Incremental sync on each GSC run; full 56-day refresh weekly. Prunes rows older than 13 months.', 'newsroom-ai-assistant' ); ?></p>
                            <?php if ( $gsc_query_db_rows > 0 ) : ?>
                                <p class="description" style="margin:6px 0 0;">
                                    <?php
                                    echo esc_html(
                                        sprintf(
                                            /* translators: 1: total query rows in DB, 2: rows from last sync, 3: sync mode */
                                            __( 'Query table: %1$s rows in database%2$s.', 'newsroom-ai-assistant' ),
                                            number_format_i18n( $gsc_query_db_rows ),
                                            $gsc_last_query_rows > 0
                                                ? sprintf(
                                                    /* translators: 1: rows stored last run, 2: sync mode */
                                                    __( '; last run stored %1$d (%2$s)', 'newsroom-ai-assistant' ),
                                                    $gsc_last_query_rows,
                                                    $gsc_last_query_mode !== '' ? $gsc_last_query_mode : __( 'sync', 'newsroom-ai-assistant' )
                                                )
                                                : ''
                                        )
                                    );
                                    ?>
                                </p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html( $i18n['indexing_status'] ); ?></th>
                        <td>
                            <?php if ( $gsc_last_sync !== '' ) : ?>
                                <p class="description" style="margin:0 0 6px 0;">
                                    <strong><?php echo esc_html( $i18n['gsc_last_sync'] ); ?>:</strong>
                                    <?php echo esc_html( $gsc_last_sync ); ?> UTC
                                    · <?php echo esc_html( $i18n['gsc_rows'] ); ?>: <strong><?php echo esc_html( (string) $gsc_db_rows ); ?></strong>
                                    <?php if ( $gsc_last_count > 0 ) : ?>
                                        · <?php echo esc_html( sprintf( __( 'Last run stored: %d', 'newsroom-ai-assistant' ), $gsc_last_count ) ); ?>
                                    <?php endif; ?>
                                </p>
                            <?php else : ?>
                                <p class="description" style="margin:0 0 6px 0;"><?php echo esc_html( __( 'No sync yet. Save settings, then click “Sync now”.', 'newsroom-ai-assistant' ) ); ?></p>
                            <?php endif; ?>
                            <?php if ( $gsc_last_error !== '' ) : ?>
                                <p class="description" style="color:#b91c1c;margin:0 0 8px 0;">
                                    <?php echo esc_html( $i18n['gsc_last_error'] ); ?>: <?php echo esc_html( $gsc_last_error ); ?>
                                </p>
                            <?php endif; ?>
                            <?php if ( $gsc_next_cron_ts > 0 ) : ?>
                                <p class="description" style="margin:0 0 8px 0;">
                                    <strong><?php echo esc_html( $i18n['gsc_next_cron'] ); ?>:</strong>
                                    <?php echo esc_html( wp_date( 'Y-m-d H:i', $gsc_next_cron_ts ) ); ?>
                                    (<?php echo esc_html( wp_timezone_string() ); ?>)
                                </p>
                            <?php elseif ( $newsai_is_pro_active && get_option( 'newsai_gsc_enabled', 'no' ) === 'yes' ) : ?>
                                <p class="description" style="margin:0 0 8px 0;"><?php echo esc_html( $i18n['gsc_cron_off'] ); ?></p>
                            <?php endif; ?>
                            <?php if ( ! empty( $gsc_breakdown ) ) : ?>
                                <p class="description" style="margin:0 0 8px 0;">
                                    <strong><?php echo esc_html( __( 'In database by channel', 'newsroom-ai-assistant' ) ); ?>:</strong>
                                    <?php
                                    $gsc_parts = [];
                                    foreach ( $gsc_breakdown as $gb ) {
                                        $gsc_parts[] = sprintf(
                                            '%s %s clicks (%s rows)',
                                            (string) $gb['label'],
                                            number_format_i18n( (int) $gb['clicks'] ),
                                            number_format_i18n( (int) $gb['rows'] )
                                        );
                                    }
                                    echo esc_html( implode( ' · ', $gsc_parts ) );
                                    ?>
                                </p>
                            <?php endif; ?>
                            <p class="description" style="margin:0 0 8px 0;"><?php echo esc_html( __( 'Test is quick (~20s). Sync can take 1–2 minutes (3 API calls: Web, Discover, Google News).', 'newsroom-ai-assistant' ) ); ?></p>
                            <button type="button" id="newsai-gsc-test" class="button button-secondary" <?php disabled( ! $newsai_is_pro_active ); ?>>
                                🧪 <?php echo esc_html( $i18n['gsc_test'] ); ?>
                            </button>
                            <button type="button" id="newsai-gsc-sync" class="button button-primary" style="margin-left:8px;" <?php disabled( ! $newsai_is_pro_active ); ?>>
                                <?php echo esc_html( $i18n['gsc_sync_now'] ); ?>
                            </button>
                            <span id="newsai-gsc-test-result" style="margin-left:10px;font-size:12px;"></span>
                            <span id="newsai-gsc-sync-result" style="display:block;margin-top:8px;font-size:12px;"></span>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__( 'Historical backfill', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <p class="description" style="margin:0 0 8px 0;">
                                <?php echo esc_html__( 'One-time import of the last 12 months of GSC data (queries, site totals, and top ~150 articles plus tagged posts). Data older than 13 months is pruned automatically. Run once to power Seasonal radar YoY.', 'newsroom-ai-assistant' ); ?>
                            </p>
                            <?php if ( $gsc_backfill_done_at > 0 ) : ?>
                                <p class="description" style="margin:0 0 8px 0;">
                                    <?php
                                    echo esc_html(
                                        sprintf(
                                            /* translators: %s: localized date/time */
                                            __( 'Last completed: %s', 'newsroom-ai-assistant' ),
                                            wp_date( 'Y-m-d H:i', $gsc_backfill_done_at )
                                        )
                                    );
                                    ?>
                                </p>
                            <?php endif; ?>
                            <?php
                            $gsc_bf_chunks = isset( $gsc_backfill_state['chunks'] ) && is_array( $gsc_backfill_state['chunks'] ) ? $gsc_backfill_state['chunks'] : [];
                            $gsc_bf_index  = (int) ( $gsc_backfill_state['chunk_index'] ?? 0 );
                            $gsc_bf_total  = count( $gsc_bf_chunks );
                            ?>
                            <p id="newsai-gsc-backfill-progress" class="description" style="margin:0 0 8px 0;<?php echo $gsc_backfill_running ? '' : 'display:none;'; ?>">
                                <span id="newsai-gsc-backfill-chunk">
                                    <?php if ( $gsc_backfill_running && $gsc_bf_total > 0 ) : ?>
                                        <?php
                                        echo esc_html(
                                            sprintf(
                                                /* translators: 1: current chunk, 2: total chunks */
                                                __( 'Progress: month %1$d of %2$d', 'newsroom-ai-assistant' ),
                                                min( $gsc_bf_index + 1, $gsc_bf_total ),
                                                $gsc_bf_total
                                            )
                                        );
                                        ?>
                                    <?php endif; ?>
                                </span>
                                <span id="newsai-gsc-backfill-step-msg"><?php echo ! empty( $gsc_backfill_state['last_message'] ) ? ' · ' . esc_html( (string) $gsc_backfill_state['last_message'] ) : ''; ?></span>
                            </p>
                            <button type="button" id="newsai-gsc-backfill" class="button button-secondary" <?php disabled( ! $newsai_is_pro_active || $gsc_backfill_running ); ?>>
                                <?php echo $gsc_backfill_running ? esc_html__( 'Backfill running…', 'newsroom-ai-assistant' ) : esc_html__( 'Start 12-month backfill', 'newsroom-ai-assistant' ); ?>
                            </button>
                            <span id="newsai-gsc-backfill-result" style="display:block;margin-top:8px;font-size:12px;"></span>
                        </td>
                    </tr>
                </table>

                <?php
                $crux_has_sa   = function_exists( 'newsai_crux_has_service_account' ) && newsai_crux_has_service_account();
                $crux_page_url = function_exists( 'newsai_crux_origin_url' ) ? newsai_crux_origin_url() : trailingslashit( home_url( '/' ) );
                $crux_has_key  = function_exists( 'newsai_crux_get_api_key' ) && newsai_crux_get_api_key() !== '';
                ?>
                <h4 id="newsai-crux-panel" style="margin-top:26px;">⚡ <?php echo esc_html__( 'Core Web Vitals (PageSpeed / CrUX)', 'newsroom-ai-assistant' ); ?></h4>
                <p class="description" style="max-width:720px;margin:0 0 12px 0;">
                    <?php echo esc_html__( 'Chief Insights panel reads real-user CWV via PageSpeed Insights. Uses a full https:// page URL (not sc-domain:). The service account JSON above is for GSC/Indexing only — CrUX needs the PageSpeed Insights API enabled plus an optional API key below.', 'newsroom-ai-assistant' ); ?>
                </p>
                <?php if ( $crux_has_sa && ! $crux_has_key ) : ?>
                    <p class="description" style="color:#92400e;margin:0 0 12px 0;">
                        <?php echo esc_html__( 'Service account detected for GSC. Enable PageSpeed Insights API in Cloud Console and add an API key below (recommended) — the service account token cannot call PageSpeed.', 'newsroom-ai-assistant' ); ?>
                    </p>
                <?php elseif ( $crux_has_key ) : ?>
                    <p class="description" style="color:#046c4e;margin:0 0 12px 0;">✓ <?php echo esc_html__( 'PageSpeed API key saved.', 'newsroom-ai-assistant' ); ?></p>
                <?php endif; ?>
                <table class="form-table">
                    <tr>
                        <th><label for="newsai_crux_origin_url"><?php echo esc_html__( 'Page URL to test', 'newsroom-ai-assistant' ); ?></label></th>
                        <td>
                            <input type="url" name="newsai_crux_origin_url" id="newsai_crux_origin_url" class="regular-text" style="width:100%;" value="<?php echo esc_attr( $crux_page_url ); ?>" placeholder="https://newsos.io/" <?php disabled( ! $newsai_is_pro_active ); ?>>
                            <p class="description"><?php echo esc_html__( 'Full URL with https:// — e.g. https://newsos.io/ for sc-domain:newsos.io. Leave blank on save to auto-use your Search Console property or site homepage.', 'newsroom-ai-assistant' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="newsai_psi_api_key"><?php echo esc_html__( 'PageSpeed Insights API key', 'newsroom-ai-assistant' ); ?></label></th>
                        <td>
                            <input type="password" name="newsai_psi_api_key" id="newsai_psi_api_key" class="regular-text" style="width:100%;" autocomplete="off" value="<?php echo esc_attr( function_exists( 'newsai_crux_get_api_key' ) ? newsai_crux_get_api_key() : '' ); ?>" placeholder="AIza…" <?php disabled( ! $newsai_is_pro_active ); ?>>
                            <p class="description"><?php echo wp_kses_post( __( 'Google Cloud → <strong>Credentials → Create credentials → API key</strong> → restrict to <em>PageSpeed Insights API</em>. Saved with the main Save button below.', 'newsroom-ai-assistant' ) ); ?></p>
                        </td>
                    </tr>
                </table>

                <h4 style="margin-top:26px;">🟢 IndexNow — Bing &amp; Yandex</h4>
                <?php
                $indexnow_key = function_exists('newsai_indexnow_get_key') ? newsai_indexnow_get_key() : '';
                $indexnow_key_url = function_exists('newsai_indexnow_key_url') ? newsai_indexnow_key_url() : '';
                $indexnow_last_code = (int) get_option('newsai_indexnow_last_code', 0);
                $indexnow_last_ping = (int) get_option('newsai_indexnow_last_ping', 0);
                $indexnow_last_url  = (string) get_option('newsai_indexnow_last_url', '');
                $indexnow_last_err  = (string) get_option('newsai_indexnow_last_error', '');
                $indexnow_last_success_code = (int) get_option('newsai_indexnow_last_success_code', 0);
                $indexnow_last_success_ping = (int) get_option('newsai_indexnow_last_success_ping', 0);
                $indexnow_last_success_url  = (string) get_option('newsai_indexnow_last_success_url', '');
                $indexnow_health_label = __( 'Unknown', 'newsroom-ai-assistant' );
                $indexnow_health_color = '#64748b';
                if ( $indexnow_last_success_ping > 0 && $indexnow_last_success_ping >= ( time() - ( 7 * DAY_IN_SECONDS ) ) ) {
                    $indexnow_health_label = __( 'Healthy', 'newsroom-ai-assistant' );
                    $indexnow_health_color = '#15803d';
                } elseif ( $indexnow_last_ping > 0 && $indexnow_last_err !== '' ) {
                    $indexnow_health_label = __( 'Degraded', 'newsroom-ai-assistant' );
                    $indexnow_health_color = '#b91c1c';
                }
                $in_status_text = __( 'No pings yet', 'newsroom-ai-assistant' );
                $in_status_color = '#646970';
                if ($indexnow_last_code >= 200 && $indexnow_last_code < 300) {
                    $in_status_text = (__( 'Success (2xx)', 'newsroom-ai-assistant' )) . ' • HTTP ' . $indexnow_last_code;
                    $in_status_color = '#15803d';
                } elseif ($indexnow_last_code > 0) {
                    $in_status_text = (__( 'Error', 'newsroom-ai-assistant' )) . ' • HTTP ' . $indexnow_last_code;
                    $in_status_color = '#b91c1c';
                }
                ?>
                <table class="form-table">
                    <tr><th><?php echo esc_html(__( 'IndexNow (Bing / Yandex)', 'newsroom-ai-assistant' )); ?></th><td>
                        <label style="<?php echo esc_attr( $newsai_is_pro_active ? '' : 'opacity:.55;' ); ?>">
                            <input type="checkbox" name="indexnow_enabled" value="yes" <?php checked(get_option('newsai_indexnow_enabled', 'no'), 'yes'); ?> <?php disabled(!$newsai_is_pro_active); ?>>
                            <?php echo esc_html(__( 'Submit each published article to Bing &amp; Yandex automatically.', 'newsroom-ai-assistant' )); ?>
                        </label>
                        <p class="description" style="margin-top:6px;">
                            <?php echo esc_html(__( 'No API key required from Microsoft — IndexNow uses a key file we serve automatically for you.', 'newsroom-ai-assistant' )); ?>
                        </p>
                    </td></tr>
                    <tr><th><?php echo esc_html(__( 'Your IndexNow key', 'newsroom-ai-assistant' )); ?></th><td>
                        <code style="user-select:all; background:#f6f7f7; padding:6px 8px; border-radius:6px; display:inline-block;"><?php echo esc_html($indexnow_key); ?></code>
                        <p class="description" style="margin-top:6px;">
                            <?php echo esc_html(__( 'Verification file:', 'newsroom-ai-assistant' )); ?>
                            <a href="<?php echo esc_url($indexnow_key_url); ?>" target="_blank" rel="noopener"><code><?php echo esc_html($indexnow_key_url); ?></code></a>
                        </p>
                        <p class="description" style="margin-top:4px;">
                            <?php echo esc_html(__( 'We serve this file virtually via WordPress rewrites — no FTP upload needed. If your host blocks unknown URLs, allow this exact path.', 'newsroom-ai-assistant' )); ?>
                        </p>
                    </td></tr>
                    <tr><th><?php echo esc_html(__( 'Last submission', 'newsroom-ai-assistant' )); ?></th><td>
                        <div style="display:inline-block; font-weight:700; padding:4px 8px; border-radius:999px; background:#f6f7f7; color:<?php echo esc_attr($in_status_color); ?>; border:1px solid #e2e4e7;">
                            <?php echo esc_html($in_status_text); ?>
                        </div>
                        <div style="display:inline-block; margin-left:6px; font-weight:700; padding:4px 8px; border-radius:999px; background:#f8fafc; color:<?php echo esc_attr( $indexnow_health_color ); ?>; border:1px solid #e2e8f0;">
                            <?php echo esc_html__( 'Health', 'newsroom-ai-assistant' ); ?>: <?php echo esc_html( $indexnow_health_label ); ?>
                        </div>
                        <button type="button" id="newsai-indexnow-test" class="button button-secondary" style="margin-left:8px;" <?php disabled(!$newsai_is_pro_active); ?>>🧪 <?php echo esc_html(__( 'Test now', 'newsroom-ai-assistant' )); ?></button>
                        <span id="newsai-indexnow-test-result" style="margin-left:10px; font-size:12px;"></span>
                        <?php if ($indexnow_last_ping > 0): ?>
                            <p class="description" style="margin-top:8px;"><strong><?php echo esc_html__( 'Last attempted ping', 'newsroom-ai-assistant' ); ?>:</strong> <?php echo esc_html(gmdate('Y-m-d H:i:s', $indexnow_last_ping)); ?> UTC<?php if ($indexnow_last_code > 0) : ?> · HTTP <?php echo esc_html((string) $indexnow_last_code); ?><?php endif; ?></p>
                        <?php endif; ?>
                        <?php if (!empty($indexnow_last_url)): ?>
                            <p class="description"><strong><?php echo esc_html__( 'Last attempted URL', 'newsroom-ai-assistant' ); ?>:</strong> <code><?php echo esc_html($indexnow_last_url); ?></code></p>
                        <?php endif; ?>
                        <?php if ($indexnow_last_success_ping > 0): ?>
                            <p class="description" style="margin-top:8px;"><strong><?php echo esc_html__( 'Last successful ping', 'newsroom-ai-assistant' ); ?>:</strong> <?php echo esc_html(gmdate('Y-m-d H:i:s', $indexnow_last_success_ping)); ?> UTC<?php if ($indexnow_last_success_code > 0) : ?> · HTTP <?php echo esc_html((string) $indexnow_last_success_code); ?><?php endif; ?></p>
                        <?php endif; ?>
                        <?php if (!empty($indexnow_last_success_url)): ?>
                            <p class="description"><strong><?php echo esc_html__( 'Last successful URL', 'newsroom-ai-assistant' ); ?>:</strong> <code><?php echo esc_html($indexnow_last_success_url); ?></code></p>
                        <?php endif; ?>
                        <?php if (!empty($indexnow_last_err)): ?>
                            <p class="description" style="color:#b91c1c;"><?php echo esc_html(__( 'Last error', 'newsroom-ai-assistant' )); ?>: <?php echo esc_html($indexnow_last_err); ?></p>
                        <?php endif; ?>
                    </td></tr>
                </table>
                <details style="background:#ecfdf5; border:1px solid #a7f3d0; border-left:4px solid #059669; border-radius:8px; padding:12px; margin-top:8px;">
                    <summary style="cursor:pointer; font-weight:700;">📖 <?php echo esc_html(__( 'How IndexNow works (3 steps, zero config)', 'newsroom-ai-assistant' )); ?></summary>
                    <ol style="margin:10px 0 0 18px; line-height:1.7;">
                        <li><?php echo esc_html(__( 'Toggle "Submit each published article" above and click Save.', 'newsroom-ai-assistant' )); ?></li>
                        <li><?php echo wp_kses_post(__( 'Click <strong>Test now</strong> — we will verify your key file is reachable and submit your homepage. A green tick means Bing/Yandex accepted the ping.', 'newsroom-ai-assistant' )); ?></li>
                        <li><?php echo esc_html(__( 'From now on, every published or updated post is pushed automatically within seconds. No keys to copy, no files to FTP.', 'newsroom-ai-assistant' )); ?></li>
                    </ol>
                    <p style="margin-top:10px; font-size:12px; color:#374151;">
                        <?php echo wp_kses_post(__( 'IndexNow is supported by Microsoft Bing, Yandex, Seznam, and others. <a href="https://www.indexnow.org/" target="_blank" rel="noopener">Read the protocol →</a>', 'newsroom-ai-assistant' )); ?>
                    </p>
                </details>

                <?php if (!$newsai_is_pro_active): ?>
                    </div>
                <?php endif; ?>
                </div>

                <div class="nros-settings-pane" data-pane="decay">
                <hr style="margin: 20px 0; border-top: 1px solid #f0f0f1;">
                <?php
                $active_publisher_profile = function_exists( 'newsai_get_publisher_profile' ) ? newsai_get_publisher_profile() : 'standard';
                $publisher_choices        = function_exists( 'newsai_publisher_profile_choices' ) ? newsai_publisher_profile_choices() : [];
                ?>
                <h3><?php echo esc_html( $i18n['publisher_profile_title'] ); ?></h3>
                <p class="description" style="max-width:640px;margin-bottom:12px;"><?php echo esc_html( $i18n['publisher_profile_desc'] ); ?></p>
                <div style="margin-bottom:20px;">
                    <fieldset style="border:1px solid #e2e4e7;border-radius:8px;padding:12px 14px;margin:0 0 12px 0;">
                        <legend style="font-weight:600;padding:0 6px;"><?php echo esc_html( $i18n['publisher_profile_active'] ); ?>: <?php echo esc_html( $publisher_choices[ $active_publisher_profile ]['label'] ?? $active_publisher_profile ); ?></legend>
                        <?php foreach ( $publisher_choices as $key => $meta ) : ?>
                            <label style="display:block;margin-bottom:10px;max-width:640px;">
                                <input type="radio" name="publisher_profile" form="newsai-publisher-profile-form" value="<?php echo esc_attr( $key ); ?>" <?php checked( $active_publisher_profile, $key ); ?>>
                                <strong><?php echo esc_html( (string) ( $meta['label'] ?? $key ) ); ?></strong>
                                <span class="description" style="display:block;margin-left:22px;"><?php echo esc_html( (string) ( $meta['desc'] ?? '' ) ); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </fieldset>
                    <button type="submit" form="newsai-publisher-profile-form" name="newsai_switch_publisher_profile" class="button button-secondary" onclick="return confirm('<?php echo esc_js( __( 'Apply this performance profile? Current performance-related settings will be overwritten.', 'newsroom-ai-assistant' ) ); ?>');"><?php echo esc_html( $i18n['publisher_profile_apply'] ); ?></button>
                </div>

                <h3><?php echo esc_html__( 'Performance & insights', 'newsroom-ai-assistant' ); ?></h3>
                <table class="form-table">
                    <tr>
                        <th><?php echo esc_html( __( '⚡ Lite / Performance Mode', 'newsroom-ai-assistant' ) ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="newsai_lite_mode" value="yes" <?php checked( get_option( 'newsai_lite_mode', 'no' ), 'yes' ); ?>>
                                <?php echo esc_html( __( 'Enable Lite Mode (for large/high-traffic sites)', 'newsroom-ai-assistant' ) ); ?>
                            </label>
                            <p class="description" style="max-width:520px; margin-top:6px;">
                                <?php echo esc_html( __( 'For high-traffic sites: disables the post editor sidebar, Auto-Timeline, Breaking badge, and Speakable snippet on articles; pauses War-room live polling in admin. JSON-LD schema, GSC sync, and indexing crons stay active.', 'newsroom-ai-assistant' ) ); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html( __( '🏗 Large site mode', 'newsroom-ai-assistant' ) ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="newsai_large_site_mode" value="yes" <?php checked( get_option( 'newsai_large_site_mode', 'no' ), 'yes' ); ?>>
                                <?php echo esc_html( __( 'Enable large-site optimizations (staggered crons, smaller schema batches)', 'newsroom-ai-assistant' ) ); ?>
                            </label>
                            <p class="description" style="max-width:520px; margin-top:6px;">
                                <?php
                                $threshold = function_exists( 'newsai_large_site_post_threshold' ) ? (int) newsai_large_site_post_threshold() : 5000;
                                printf(
                                    esc_html__( 'Defers heavy background jobs after activation and caps schema warm batches. When this box is checked, Auto-Timeline injection is also skipped (Manual insert / shortcode still work), Trend Radar AJAX is paused, and tag duplicate guard is off. Sites with %1$s+ posts still get safer cron batching automatically — without turning Auto-Timeline off. Use Lite Mode above to disable the entire editor sidebar.', 'newsroom-ai-assistant' ),
                                    number_format_i18n( $threshold )
                                );
                                ?>
                            </p>
                        </td>
                    </tr>
                    <tr><th colspan="2"><h4 style="margin:16px 0 4px;"><?php echo esc_html__( 'GSC traffic drops (Chief Insights)', 'newsroom-ai-assistant' ); ?></h4></th></tr>
                    <tr>
                        <th><?php echo esc_html__( 'Enable traffic-drop alerts', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <label><input type="checkbox" name="gsc_traffic_drop_enabled" value="yes" <?php checked( get_option( 'newsai_gsc_traffic_drop_enabled', 'yes' ), 'yes' ); ?>> <?php echo esc_html__( 'On', 'newsroom-ai-assistant' ); ?></label>
                            <p class="description"><?php echo esc_html__( 'Surfaces articles with meaningful GSC click loss vs the previous period — replaces the retired Content Decay auto-tasks.', 'newsroom-ai-assistant' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__( 'Comparison window (days)', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <?php $drop_days_saved = (int) get_option( 'newsai_gsc_traffic_drop_days', 28 ); ?>
                            <select name="gsc_traffic_drop_days">
                                <option value="14" <?php selected( $drop_days_saved, 14 ); ?>>14</option>
                                <option value="28" <?php selected( $drop_days_saved, 28 ); ?>>28</option>
                                <option value="30" <?php selected( $drop_days_saved, 30 ); ?>>30</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__( 'GSC channel', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <?php $drop_ch = (string) get_option( 'newsai_gsc_traffic_drop_channel', 'web' ); ?>
                            <select name="gsc_traffic_drop_channel">
                                <option value="web" <?php selected( $drop_ch, 'web' ); ?>><?php echo esc_html__( 'Web', 'newsroom-ai-assistant' ); ?></option>
                                <option value="discover" <?php selected( $drop_ch, 'discover' ); ?>><?php echo esc_html__( 'Discover', 'newsroom-ai-assistant' ); ?></option>
                                <option value="googleNews" <?php selected( $drop_ch, 'googleNews' ); ?>><?php echo esc_html__( 'Google News', 'newsroom-ai-assistant' ); ?></option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__( 'Minimum prior-period clicks', 'newsroom-ai-assistant' ); ?></th>
                        <td><input type="number" name="gsc_traffic_drop_min_prev" value="<?php echo esc_attr( (string) get_option( 'newsai_gsc_traffic_drop_min_prev_clicks', 25 ) ); ?>" class="small-text" min="5" max="500"></td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__( 'Minimum click loss', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <input type="number" name="gsc_traffic_drop_min_loss" value="<?php echo esc_attr( (string) get_option( 'newsai_gsc_traffic_drop_min_loss', 15 ) ); ?>" class="small-text" min="5" max="500">
                            <p class="description"><?php echo esc_html__( 'Article must lose at least this many clicks vs the previous window (and meet the prior-period minimum).', 'newsroom-ai-assistant' ); ?></p>
                        </td>
                    </tr>
                    <tr><th colspan="2"><h4 style="margin:16px 0 4px;"><?php echo esc_html__( 'Seasonal radar (Chief Insights)', 'newsroom-ai-assistant' ); ?></h4></th></tr>
                    <tr>
                        <th><?php echo esc_html__( 'Enable seasonal radar', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <label><input type="checkbox" name="seasonal_radar_enabled" value="yes" <?php checked( get_option( 'newsai_seasonal_radar_enabled', 'yes' ), 'yes' ); ?>> <?php echo esc_html__( 'On', 'newsroom-ai-assistant' ); ?></label>
                            <p class="description"><?php echo esc_html__( 'YoY GSC search queries and tag signals with lead-time alerts in Chief Insights (requires GSC sync with query sync on; tags optional).', 'newsroom-ai-assistant' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__( 'Lead time (days ahead)', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <?php $seasonal_lead_saved = (int) get_option( 'newsai_seasonal_lead_days', 30 ); ?>
                            <select name="seasonal_lead_days">
                                <option value="14" <?php selected( $seasonal_lead_saved, 14 ); ?>>14</option>
                                <option value="30" <?php selected( $seasonal_lead_saved, 30 ); ?>>30</option>
                                <option value="45" <?php selected( $seasonal_lead_saved, 45 ); ?>>45</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__( 'Minimum YoY GSC clicks', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <input type="number" name="seasonal_min_clicks" value="<?php echo esc_attr( (string) get_option( 'newsai_seasonal_min_clicks', 25 ) ); ?>" class="small-text" min="5" max="5000">
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__( 'Weekly email section', 'newsroom-ai-assistant' ); ?></th>
                        <td>
                            <label><input type="checkbox" name="seasonal_email_enabled" value="yes" <?php checked( get_option( 'newsai_seasonal_email_enabled', 'yes' ), 'yes' ); ?>> <?php echo esc_html__( 'Include top seasonal opportunities in the weekly desk report', 'newsroom-ai-assistant' ); ?></label>
                        </td>
                    </tr>
                </table>
                </div>

                <div class="nros-settings-pane" data-pane="prompts">
                <hr style="margin: 20px 0; border-top: 1px solid #f0f0f1;">

                <h3><?php echo esc_html($i18n['prompts_title']); ?></h3>
                <p class="description" style="max-width:760px;margin-bottom:12px;"><?php echo esc_html__( 'Copy-to-clipboard templates for ChatGPT and other external AI tools. Customize here — editors can also use AI Assist (BYOK) in the sidebar; both options stay available.', 'newsroom-ai-assistant' ); ?></p>
                <table class="form-table">
                    <tr><th>Title Prompt</th><td><textarea name="p_title" rows="4" style="width:100%; font-family:monospace;"><?php echo esc_textarea($p_title); ?></textarea></td></tr>
                    <tr><th>Rewrite Prompt</th><td><textarea name="p_rewrite" rows="5" style="width:100%; font-family:monospace;"><?php echo esc_textarea($p_rewrite); ?></textarea></td></tr>
                    <tr><th>SEO Tags & Meta</th><td><textarea name="p_seo" rows="4" style="width:100%; font-family:monospace;"><?php echo esc_textarea($p_seo); ?></textarea></td></tr>
                </table>
                </div>
                </div><!-- .nros-settings-panes -->
                </div><!-- .nros-settings-layout -->
                <p class="submit"><input type="submit" name="newsai_save_settings" class="button button-primary button-large" value="<?php echo esc_attr($i18n['btn_save']); ?>"></p>
            </form>
        </div><!-- .nros-settings-bento__form -->
        </div><!-- .nros-settings-bento -->

            <script>
            // Indexing tab — self-contained "Test now" handlers. Inlines ajax_url + nonce so
            // they keep working even when the global newsai_vars script isn't enqueued on this
            // hook for some reason (cache plugins, deferred scripts, etc.).
            (function () {
                var AJAX_URL = <?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>;
                var NONCE    = <?php echo wp_json_encode( wp_create_nonce( 'newsai_ajax_nonce' ) ); ?>;
                function esc(s) { var d = document.createElement('div'); d.textContent = String(s == null ? '' : s); return d.innerHTML; }
                function runTest(buttonId, resultId, action) {
                    var btn = document.getElementById(buttonId);
                    var res = document.getElementById(resultId);
                    if (!btn || !res) { return; }
                    btn.addEventListener('click', function (e) {
                        e.preventDefault();
                        if (btn.disabled) return;
                        btn.disabled = true;
                        res.style.color = '#646970';
                        res.textContent = action === 'newsai_gsc_test' ? '⏳ Testing GSC (up to 30s)…' : '⏳ Testing…';
                        var body = new URLSearchParams();
                        body.append('action', action);
                        body.append('nonce',  NONCE);
                        var ctrl = (typeof AbortController !== 'undefined') ? new AbortController() : null;
                        var timer = ctrl ? setTimeout(function () { try { ctrl.abort(); } catch (err) {} }, action === 'newsai_gsc_test' ? 35000 : 60000) : null;
                        fetch(AJAX_URL, {
                            method: 'POST',
                            credentials: 'same-origin',
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                            body: body.toString(),
                            signal: ctrl ? ctrl.signal : undefined
                        })
                        .then(function (r) {
                            return r.text().then(function (t) {
                                var data = null;
                                try { data = t ? JSON.parse(t) : null; } catch (parseErr) {}
                                return { status: r.status, data: data, raw: t };
                            });
                        })
                        .then(function (r) {
                            if (r.data && r.data.success) {
                                var ok = (r.data.data && r.data.data.message) ? r.data.data.message : 'OK';
                                res.innerHTML = '✅ ' + esc(ok);
                                res.style.color = '#15803d';
                                if (action === 'newsai_indexing_test') {
                                    setTimeout(function () { window.location.reload(); }, 900);
                                }
                                return;
                            }
                            var msg = (r.data && r.data.data && r.data.data.message)
                                ? r.data.data.message
                                : ('HTTP ' + r.status + (r.raw ? ' — ' + r.raw.substring(0, 160) : ''));
                            res.innerHTML = '❌ ' + esc(msg);
                            res.style.color = '#b91c1c';
                        })
                        .catch(function (err) {
                            var msg = (err && err.name === 'AbortError')
                                ? 'Request timed out — try again or check PHP max_execution_time / outbound HTTPS.'
                                : ((err && err.message) || 'Network error');
                            res.innerHTML = '❌ ' + esc(msg);
                            res.style.color = '#b91c1c';
                        })
                        .then(function () {
                            if (timer) { clearTimeout(timer); }
                            btn.disabled = false;
                        });
                    });
                }
                runTest('newsai-indexing-test',  'newsai-indexing-test-result',  'newsai_indexing_test');
                (function () {
                    var btn = document.getElementById('newsai-save-indexing-sa');
                    var ta  = document.getElementById('newsai-indexing-json-field');
                    var res = document.getElementById('newsai-save-indexing-sa-result');
                    if (!btn || !ta || !res) { return; }
                    btn.addEventListener('click', function () {
                        if (btn.disabled) { return; }
                        btn.disabled = true;
                        res.style.color = '#646970';
                        res.textContent = '⏳ <?php echo esc_js( __( 'Saving…', 'newsroom-ai-assistant' ) ); ?>';
                        var body = new URLSearchParams();
                        body.append('action', 'newsai_save_indexing_sa');
                        body.append('nonce', NONCE);
                        body.append('indexing_service_json', ta.value || '');
                        var replaceCb = document.getElementById('newsai-indexing-json-replace');
                        var clearCb   = document.getElementById('newsai-indexing-json-clear');
                        if (replaceCb && replaceCb.checked) { body.append('indexing_service_json_replace', '1'); }
                        if (clearCb && clearCb.checked) { body.append('indexing_service_json_clear', '1'); }
                        fetch(AJAX_URL, {
                            method: 'POST',
                            credentials: 'same-origin',
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                            body: body.toString()
                        })
                        .then(function (r) {
                            return r.text().then(function (t) {
                                var data = null;
                                try { data = t ? JSON.parse(t) : null; } catch (e) {}
                                return { status: r.status, data: data, raw: t };
                            });
                        })
                        .then(function (r) {
                            if (r.data && r.data.success) {
                                var ok = (r.data.data && r.data.data.message) ? r.data.data.message : 'OK';
                                res.innerHTML = '✅ ' + esc(ok);
                                res.style.color = '#15803d';
                                setTimeout(function () { window.location.reload(); }, 700);
                                return;
                            }
                            var msg = (r.data && r.data.data && r.data.data.message)
                                ? r.data.data.message
                                : ('HTTP ' + r.status + (r.raw ? ' — ' + r.raw.substring(0, 160) : ''));
                            res.innerHTML = '❌ ' + esc(msg);
                            res.style.color = '#b91c1c';
                        })
                        .catch(function (err) {
                            res.innerHTML = '❌ ' + esc((err && err.message) || 'Network error');
                            res.style.color = '#b91c1c';
                        })
                        .then(function () { btn.disabled = false; });
                    });
                })();
                runTest('newsai-indexnow-test',  'newsai-indexnow-test-result',  'newsai_indexnow_test');
                runTest('newsai-gsc-test', 'newsai-gsc-test-result', 'newsai_gsc_test');
                (function () {
                    var btn = document.getElementById('newsai-gsc-sync');
                    var res = document.getElementById('newsai-gsc-sync-result');
                    if (!btn || !res) { return; }
                    btn.addEventListener('click', function () {
                        btn.disabled = true;
                        res.textContent = '⏳ Syncing (Web + Discover + Google News, up to 2 min)…';
                        res.style.color = '#646970';
                        var fd = new FormData();
                        fd.append('action', 'newsai_gsc_sync_now');
                        fd.append('nonce', NONCE);
                        var syncCtrl = (typeof AbortController !== 'undefined') ? new AbortController() : null;
                        var syncTimer = syncCtrl ? setTimeout(function () { try { syncCtrl.abort(); } catch (e) {} }, 180000) : null;
                        fetch(AJAX_URL, { method: 'POST', body: fd, credentials: 'same-origin', signal: syncCtrl ? syncCtrl.signal : undefined })
                            .then(function (r) {
                                return r.text().then(function (t) {
                                    var data = null;
                                    try { data = t ? JSON.parse(t) : null; } catch (parseErr) {}
                                    return { ok: r.ok, status: r.status, data: data, raw: t };
                                });
                            })
                            .then(function (r) {
                                if (r.data && r.data.success) {
                                    var d = r.data.data || {};
                                    res.innerHTML = '✅ ' + esc(d.message || 'OK') + (d.rows !== undefined ? ' · rows: ' + esc(String(d.rows)) : '');
                                    res.style.color = '#15803d';
                                    setTimeout(function () { window.location.reload(); }, 1200);
                                    return;
                                }
                                if (!r.data && r.ok) {
                                    res.innerHTML = '✅ <?php echo esc_js( __( 'Sync finished (response was not JSON — refreshing…)', 'newsroom-ai-assistant' ) ); ?>';
                                    res.style.color = '#15803d';
                                    setTimeout(function () { window.location.reload(); }, 900);
                                    return;
                                }
                                var d = (r.data && r.data.data) ? r.data.data : {};
                                var msg = d.message
                                    || ('HTTP ' + r.status + (r.raw ? ' — ' + r.raw.substring(0, 160) : ''));
                                res.innerHTML = '❌ ' + esc(msg || 'Sync failed');
                                res.style.color = '#b91c1c';
                            })
                            .catch(function (err) {
                                var msg = (err && err.name === 'AbortError')
                                    ? '<?php echo esc_js( __( 'Sync timed out in the browser — data may still be saved. Refresh the page to check Last GSC sync.', 'newsroom-ai-assistant' ) ); ?>'
                                    : ((err && err.message) || 'Network error');
                                res.innerHTML = '⚠️ ' + esc(msg);
                                res.style.color = '#b45309';
                            })
                            .then(function () {
                                if (syncTimer) { clearTimeout(syncTimer); }
                                btn.disabled = false;
                            });
                    });
                })();
                (function () {
                    var bfBtn = document.getElementById('newsai-gsc-backfill');
                    var bfRes = document.getElementById('newsai-gsc-backfill-result');
                    var bfProg = document.getElementById('newsai-gsc-backfill-progress');
                    var bfChunk = document.getElementById('newsai-gsc-backfill-chunk');
                    var bfStepMsg = document.getElementById('newsai-gsc-backfill-step-msg');
                    var syncBtn = document.getElementById('newsai-gsc-sync');
                    if (!bfBtn || !bfRes) { return; }

                    function bfSetBusy(on) {
                        bfBtn.disabled = !!on;
                        bfBtn.textContent = on ? '<?php echo esc_js( __( 'Backfill running…', 'newsroom-ai-assistant' ) ); ?>' : '<?php echo esc_js( __( 'Start 12-month backfill', 'newsroom-ai-assistant' ) ); ?>';
                        if (syncBtn) { syncBtn.disabled = !!on; }
                    }

                    function bfUpdateProgress(progress) {
                        if (!progress || !bfProg) { return; }
                        var chunks = progress.chunks || [];
                        var idx = parseInt(progress.chunk_index, 10) || 0;
                        var total = chunks.length;
                        if (total > 0 && (progress.status === 'running' || idx < total)) {
                            bfProg.style.display = '';
                            if (bfChunk) {
                                var cur = Math.min(idx + 1, total);
                                bfChunk.textContent = '<?php echo esc_js( __( 'Progress: month', 'newsroom-ai-assistant' ) ); ?> ' + cur + ' <?php echo esc_js( __( 'of', 'newsroom-ai-assistant' ) ); ?> ' + total;
                            }
                        }
                        if (bfStepMsg && progress.last_message) {
                            bfStepMsg.textContent = ' · ' + progress.last_message;
                        }
                    }

                    function bfPost(action) {
                        var fd = new FormData();
                        fd.append('action', action);
                        fd.append('nonce', NONCE);
                        return fetch(AJAX_URL, { method: 'POST', body: fd, credentials: 'same-origin' })
                            .then(function (r) { return r.json().then(function (d) { return { ok: r.ok, data: d }; }); });
                    }

                    function bfRunSteps() {
                        return bfPost('newsai_gsc_backfill_step').then(function (r) {
                            var payload = (r.data && r.data.data) ? r.data.data : {};
                            var progress = payload.progress || {};
                            if (r.data && r.data.success) {
                                bfRes.innerHTML = '⏳ ' + esc(payload.message || '');
                                bfRes.style.color = '#646970';
                                bfUpdateProgress(progress);
                                if (payload.done) {
                                    bfRes.innerHTML = '✅ ' + esc(payload.message || '<?php echo esc_js( __( 'Backfill complete.', 'newsroom-ai-assistant' ) ); ?>');
                                    bfRes.style.color = '#15803d';
                                    bfSetBusy(false);
                                    setTimeout(function () { window.location.reload(); }, 1200);
                                    return;
                                }
                                return new Promise(function (resolve) {
                                    setTimeout(function () { resolve(bfRunSteps()); }, 800);
                                });
                            }
                            var msg = (r.data && r.data.data && r.data.data.message) ? r.data.data.message : '<?php echo esc_js( __( 'Backfill failed.', 'newsroom-ai-assistant' ) ); ?>';
                            bfRes.innerHTML = '❌ ' + esc(msg);
                            bfRes.style.color = '#b91c1c';
                            bfSetBusy(false);
                        }).catch(function (err) {
                            bfRes.innerHTML = '❌ ' + esc((err && err.message) || 'Network error');
                            bfRes.style.color = '#b91c1c';
                            bfSetBusy(false);
                        });
                    }

                    function bfStart() {
                        bfSetBusy(true);
                        if (bfProg) { bfProg.style.display = ''; }
                        bfRes.textContent = '⏳ <?php echo esc_js( __( 'Preparing URL list (may take 1–2 min)…', 'newsroom-ai-assistant' ) ); ?>';
                        bfRes.style.color = '#646970';
                        return bfPost('newsai_gsc_backfill_start').then(function (r) {
                            if (!r.data || !r.data.success) {
                                var msg = (r.data && r.data.data && r.data.data.message) ? r.data.data.message : '<?php echo esc_js( __( 'Could not start backfill.', 'newsroom-ai-assistant' ) ); ?>';
                                bfRes.innerHTML = '❌ ' + esc(msg);
                                bfRes.style.color = '#b91c1c';
                                bfSetBusy(false);
                                return;
                            }
                            var payload = r.data.data || {};
                            bfRes.innerHTML = '✅ ' + esc(payload.message || '');
                            bfRes.style.color = '#15803d';
                            bfUpdateProgress(payload.progress || {});
                            return bfRunSteps();
                        }).catch(function (err) {
                            bfRes.innerHTML = '❌ ' + esc((err && err.message) || 'Network error');
                            bfRes.style.color = '#b91c1c';
                            bfSetBusy(false);
                        });
                    }

                    bfBtn.addEventListener('click', function (e) {
                        e.preventDefault();
                        if (bfBtn.disabled) { return; }
                        bfStart();
                    });

                    <?php if ( $gsc_backfill_running ) : ?>
                    bfSetBusy(true);
                    bfRes.textContent = '⏳ <?php echo esc_js( __( 'Resuming backfill…', 'newsroom-ai-assistant' ) ); ?>';
                    bfRes.style.color = '#646970';
                    bfRunSteps();
                    <?php endif; ?>
                })();
                (function () {
                    document.querySelectorAll('.nros-ai-policy-page').forEach(function (btn) {
                        btn.addEventListener('click', function (e) {
                            e.preventDefault();
                            if (btn.disabled) { return; }
                            var policy = btn.getAttribute('data-policy') || '';
                            var targetId = btn.getAttribute('data-target') || '';
                            var targetInput = targetId ? document.getElementById(targetId) : null;
                            var status = document.querySelector('.nros-ai-policy-status[data-policy="' + policy + '"]');
                            btn.disabled = true;
                            if (status) { status.textContent = '⏳ …'; }
                            var fd = new FormData();
                            fd.append('action', 'newsai_ai_generate_policy_page');
                            fd.append('nonce', NONCE);
                            fd.append('policy', policy);
                            fetch(AJAX_URL, { method: 'POST', body: fd, credentials: 'same-origin' })
                                .then(function (r) { return r.json(); })
                                .then(function (data) {
                                    if (data && data.success && data.data) {
                                        if (targetInput && data.data.url) {
                                            targetInput.value = data.data.url;
                                        }
                                        if (status) {
                                            status.innerHTML = '✅ ' + esc(data.data.message || '');
                                            if (data.data.edit_url) {
                                                status.innerHTML += ' <a href="' + esc(data.data.edit_url) + '" target="_blank" rel="noopener"><?php echo esc_js( __( 'Edit draft', 'newsroom-ai-assistant' ) ); ?></a>';
                                            }
                                        }
                                    } else {
                                        var msg = (data && data.data && data.data.message) ? data.data.message : '<?php echo esc_js( __( 'Generation failed.', 'newsroom-ai-assistant' ) ); ?>';
                                        if (status) { status.textContent = '❌ ' + msg; }
                                    }
                                })
                                .catch(function () {
                                    if (status) { status.textContent = '❌ <?php echo esc_js( __( 'Network error.', 'newsroom-ai-assistant' ) ); ?>'; }
                                })
                                .then(function () { btn.disabled = false; });
                        });
                    });
                })();
                (function () {
                    if (window.location.search.indexOf('newsai_gsc_focus=1') === -1) { return; }
                    var panel = document.getElementById('newsai-gsc-panel');
                    var syncBtn = document.getElementById('newsai-gsc-sync');
                    if (panel) {
                        panel.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                    if (syncBtn) {
                        syncBtn.focus({ preventScroll: true });
                    }
                })();
                (function () {
                    var btn = document.getElementById('newsai-weekly-report-test');
                    var status = document.getElementById('newsai-weekly-report-test-status');
                    if (!btn || !status) { return; }
                    btn.addEventListener('click', function (e) {
                        e.preventDefault();
                        btn.disabled = true;
                        status.textContent = '⏳ …';
                        status.style.color = '#646970';
                        var fd = new FormData();
                        fd.append('action', 'newsai_weekly_report_test');
                        fd.append('nonce', NONCE);
                        var rec = document.querySelector('textarea[name="weekly_report_recipients"]');
                        if (rec) { fd.append('recipients', rec.value); }
                        var en = document.querySelector('input[name="weekly_report_enabled"]');
                        if (en && en.checked) { fd.append('weekly_report_enabled', 'yes'); }
                        fetch(AJAX_URL, { method: 'POST', body: fd, credentials: 'same-origin' })
                            .then(function (r) { return r.json(); })
                            .then(function (data) {
                                if (data && data.success) {
                                    var human = (data.data && data.data.message_human) ? data.data.message_human : '';
                                    var sent = (data.data && data.data.sent) ? data.data.sent : 0;
                                    status.textContent = '✅ ' + (human || (sent + ' sent'));
                                    status.style.color = '#15803d';
                                    return;
                                }
                                var msg = (data && data.data && data.data.message_human)
                                    ? data.data.message_human
                                    : ((data && data.data && data.data.message) ? data.data.message : 'Failed');
                                status.textContent = '❌ ' + msg;
                                status.style.color = '#b91c1c';
                            })
                            .catch(function () {
                                status.textContent = '❌ Network error';
                                status.style.color = '#b91c1c';
                            })
                            .then(function () { btn.disabled = false; });
                    });
                })();
            })();
            </script>
        </div>
        <script>
        (function() {
            const root = document.getElementById('nros-settings-tabs');
            if (!root) return;
            const key = 'nros_settings_active_pane';
            const buttons = Array.from(root.querySelectorAll('.nros-settings-tab-btn'));
            const panes = Array.from(document.querySelectorAll('.nros-settings-pane'));
            function activate(name) {
                buttons.forEach(btn => btn.classList.toggle('active', btn.dataset.pane === name));
                panes.forEach(p => p.classList.toggle('active', p.dataset.pane === name));
                try { localStorage.setItem(key, name); } catch (e) {}
            }
            buttons.forEach(btn => btn.addEventListener('click', () => activate(btn.dataset.pane)));
            let saved = null;
            try { saved = localStorage.getItem(key); } catch (e) {}
            var paneFromUrl = null;
            try {
                paneFromUrl = new URLSearchParams(window.location.search).get('newsai_settings_pane');
            } catch (e) {}
            if (paneFromUrl && buttons.some(b => b.dataset.pane === paneFromUrl)) {
                activate(paneFromUrl);
            } else if (saved && buttons.some(b => b.dataset.pane === saved)) {
                activate(saved);
            }
        })();
        (function () {
            function bindSelectDetail(selectId, detailId, map) {
                var sel = document.getElementById(selectId);
                var det = document.getElementById(detailId);
                if (!sel || !det || !map) { return; }
                function sync() {
                    var key = String(sel.value || '');
                    if (map[key]) { det.textContent = map[key]; }
                }
                sel.addEventListener('change', sync);
                sync();
            }
            bindSelectDetail('nros-schema-richness', 'nros-schema-richness-detail', <?php echo wp_json_encode( $schema_richness_descs ?? [] ); ?>);
            bindSelectDetail('nros-schema-output-mode', 'nros-schema-output-mode-detail', <?php echo wp_json_encode( [
                'strict' => $i18n['schema_output_strict'],
                'hybrid' => $i18n['schema_output_hybrid'],
            ] ); ?>);
            var articleBodySel = document.getElementById('nros-schema-article-body');
            var articleBodyWords = document.getElementById('nros-schema-article-body-words');
            if (articleBodySel && articleBodyWords) {
                function syncArticleBodyWords() {
                    articleBodyWords.classList.toggle('is-hidden', articleBodySel.value !== 'limited');
                }
                articleBodySel.addEventListener('change', syncArticleBodyWords);
                syncArticleBodyWords();
            }
        })();
        </script>
        </div><!-- .newsai-classic-settings-wrap -->

       <?php elseif ($tab == 'alerts'): ?>
        <?php
        $nros_react_dashboard = $newsai_react_shell;
        ?>
        <div class="newsai-classic-dashboard-wrap<?php echo $nros_react_dashboard ? ' newsai-classic-dashboard-wrap--defer-hide' : ''; ?>">
        <?php
        if ( function_exists( 'newsai_render_classic_page_head' ) ) {
            newsai_render_classic_page_head(
                __( 'Dashboard', 'newsroom-ai-assistant' ),
                __( 'Welcome back. Here\'s what\'s happening today.', 'newsroom-ai-assistant' ),
                '<button type="button" class="button button-primary nros-dash-new-task" id="nros-dash-new-task">+ ' . esc_html__( 'New Task', 'newsroom-ai-assistant' ) . '</button>'
            );
        }
        ?>
        <?php
            $has_status = in_array( 'status', $table_cols, true );

            $total_tasks = $has_status
                ? (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE status != %s", 'done' ) )
                : (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
            
            $due_metrics = function_exists( 'newsai_get_dashboard_due_metrics_cached' ) ? newsai_get_dashboard_due_metrics_cached( $table ) : [ 'overdue' => 0, 'due_today' => 0 ];
            $overdue_count = (int) $due_metrics['overdue'];
            $due_today_count = (int) $due_metrics['due_today'];

            $post_kpis = function_exists( 'newsai_get_dashboard_post_publish_kpis' ) ? newsai_get_dashboard_post_publish_kpis() : [ 'posts_this_week' => 0, 'posts_last_week' => 0, 'total_posts_30d' => 0 ];
            $posts_this_week = (int) $post_kpis['posts_this_week'];
            $posts_last_week = (int) $post_kpis['posts_last_week'];
            $week_diff = $posts_this_week - $posts_last_week;
            $week_trend = ($posts_last_week > 0) ? round(($week_diff / $posts_last_week) * 100) : ($posts_this_week > 0 ? 100 : 0);
            $week_trend_class = $week_trend >= 0 ? 'nros-kpi-sub--good' : 'nros-kpi-sub--bad';
            $week_trend_arrow = $week_trend >= 0 ? '↑' : '↓';

            $missing_seo = function_exists('newsroom_os_get_missing_seo_count') ? newsroom_os_get_missing_seo_count() : 0;
            $total_posts_30d = (int) $post_kpis['total_posts_30d'];

            $post_spark  = function_exists( 'newsai_dashboard_registry_sparkline_posts' ) ? newsai_dashboard_registry_sparkline_posts( 7 ) : [];
            $task_spark  = function_exists( 'newsai_dashboard_registry_sparkline_tasks' ) ? newsai_dashboard_registry_sparkline_tasks( $table, 7 ) : [];
            $spark_fn    = function_exists( 'newsai_chief_render_mini_sparkline' ) ? 'newsai_chief_render_mini_sparkline' : null;
            $spark_tasks = $spark_fn ? $spark_fn( $task_spark, '#6366f1', 96, 34 ) : '';
            $spark_posts = $spark_fn ? $spark_fn( $post_spark, '#10b981', 96, 34 ) : '';
            $spark_alerts = $spark_fn ? $spark_fn( $task_spark, '#ef4444', 96, 34 ) : '';

            $pill_tasks_class = $overdue_count > 0 ? 'is-down' : 'is-up';
            $pill_tasks_text  = $overdue_count > 0
                ? sprintf( __( '%d overdue', 'newsroom-ai-assistant' ), (int) $overdue_count )
                : __( 'On track', 'newsroom-ai-assistant' );
            $pill_posts_class = $week_trend >= 0 ? 'is-up' : 'is-down';
            $pill_posts_text  = ( $week_trend >= 0 ? '+' : '' ) . (int) $week_trend . '%';
            $readiness_kpis = function_exists( 'newsai_get_dashboard_desk_readiness_kpis' )
                ? newsai_get_dashboard_desk_readiness_kpis( 30 )
                : [ 'avg' => 0, 'sample' => 0, 'posts_recent' => 0, 'low_count' => 0, 'focus_avg' => 0, 'discover_avg' => 0 ];
            $readiness_avg    = (int) $readiness_kpis['avg'];
            $readiness_sample = (int) $readiness_kpis['sample'];
            $readiness_low    = (int) $readiness_kpis['low_count'];

            $readiness_spark_vals = function_exists( 'newsai_get_dashboard_readiness_sparkline_7d' )
                ? newsai_get_dashboard_readiness_sparkline_7d()
                : [];
            $spark_readiness = $spark_fn ? $spark_fn( $readiness_spark_vals, '#8b5cf6', 96, 34 ) : '';

            $pill_readiness_class = $readiness_avg >= 80 ? 'is-up' : ( $readiness_avg >= 55 ? 'is-warn' : ( $readiness_avg > 0 ? 'is-down' : 'is-warn' ) );
            $pill_readiness_text  = $readiness_low > 0
                ? sprintf( __( '%d low', 'newsroom-ai-assistant' ), (int) $readiness_low )
                : ( $readiness_avg > 0 ? __( 'On track', 'newsroom-ai-assistant' ) : __( 'No scores yet', 'newsroom-ai-assistant' ) );
            $readiness_sub = $readiness_sample > 0
                ? sprintf( __( 'From %1$d scored posts (30d)', 'newsroom-ai-assistant' ), (int) $readiness_sample )
                : sprintf( __( '%d posts published (30d)', 'newsroom-ai-assistant' ), (int) $total_posts_30d );

            $desk_alerts_variant = $overdue_count > 0 ? 'alert' : 'default';
            $pill_alerts_text    = $overdue_count > 0
                ? sprintf( __( '%d overdue', 'newsroom-ai-assistant' ), (int) $overdue_count )
                : __( 'All clear', 'newsroom-ai-assistant' );
            $pill_alerts_class   = $overdue_count > 0 ? 'is-down' : 'is-up';
            $desk_alerts_sub     = $due_today_count > 0
                ? sprintf( __( '%d due today', 'newsroom-ai-assistant' ), (int) $due_today_count )
                : __( 'No overdue desk tasks', 'newsroom-ai-assistant' );

            $google_update_info = function_exists('newsroom_os_check_google_updates') ? newsroom_os_check_google_updates() : ['state' => 'clear', 'message' => $i18n['status_api_clear']];
        ?>

       <div class="nros-dash-bento">
        <div class="nros-dash-kpi-row">
            <?php
            if ( function_exists( 'newsai_dashboard_render_kpi_card' ) ) {
                echo newsai_dashboard_render_kpi_card(
                    __( 'Active Tasks', 'newsroom-ai-assistant' ),
                    (string) (int) $total_tasks,
                    $pill_tasks_text,
                    $pill_tasks_class,
                    $spark_tasks,
                    '',
                    'hero',
                    $due_today_count > 0 ? sprintf( __( '%d due today', 'newsroom-ai-assistant' ), (int) $due_today_count ) : ''
                ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo newsai_dashboard_render_kpi_card(
                    __( 'Articles This Week', 'newsroom-ai-assistant' ),
                    (string) (int) $posts_this_week,
                    $pill_posts_text,
                    $pill_posts_class,
                    $spark_posts
                ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo newsai_dashboard_render_kpi_card(
                    __( 'Desk Alerts', 'newsroom-ai-assistant' ),
                    (string) (int) $overdue_count,
                    $pill_alerts_text,
                    $pill_alerts_class,
                    $spark_alerts,
                    '',
                    $desk_alerts_variant,
                    $desk_alerts_sub
                ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo newsai_dashboard_render_kpi_card(
                    __( 'Avg AI Readiness', 'newsroom-ai-assistant' ),
                    $readiness_avg > 0 ? ( (string) (int) $readiness_avg . '%' ) : '—',
                    $pill_readiness_text,
                    $pill_readiness_class,
                    $spark_readiness,
                    '',
                    $readiness_avg >= 80 ? 'success' : 'default',
                    $readiness_sub
                ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            }
            ?>
        </div>

       <div class="nros-mb-24 nros-dash-google">
            <?php
            if ($google_update_info['state'] === 'active'): 
            ?>
                <div class="nros-google-status nros-google-status--alert">
                    <div class="nros-flex-gap-15">
                        <span class="nros-google-status__icon">🚨</span>
                        <div>
                            <strong class="nros-google-status__title"><?php echo esc_html( 'Ενεργό: ' . $google_update_info['message'] ); ?></strong><br>
                            <span class="nros-google-status__sub"><?php echo esc_html( __( 'Expect high volatility in SERPs. Avoid major SEO changes.', 'newsroom-ai-assistant' ) ); ?></span>
                        </div>
                    </div>
                    <?php if(!empty($google_update_info['link'])): ?>
                        <a href="<?php echo esc_url($google_update_info['link']); ?>" target="_blank" rel="noopener noreferrer" class="nros-google-status__link nros-google-status__link--alert"><?php echo esc_html( __( 'View Details', 'newsroom-ai-assistant' ) ); ?></a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="nros-google-status nros-google-status--ok">
                    <div class="nros-flex-gap-15">
                        <span class="nros-google-status__icon">✅</span>
                        <div>
                            <strong class="nros-google-status__title"><?php echo esc_html( __( 'No Active Core Updates', 'newsroom-ai-assistant' ) ); ?></strong><br>
                            <span class="nros-google-status__sub"><?php echo esc_html( __( 'Google search systems are operating normally.', 'newsroom-ai-assistant' ) ); ?></span>
                        </div>
                    </div>
                    <a href="<?php echo esc_url( 'https://status.search.google.com/' ); ?>" target="_blank" rel="noopener noreferrer" class="nros-google-status__link nros-google-status__link--ok">Google Status</a>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="nros-dashboard-grid nros-dash-bento__grid">
            
            <div class="nros-col-8 nros-dash-bento__main">
                
                <details class="nros-card nros-card--spaced nros-dash-task-form" id="nros-task-form-card"<?php echo ( $edit_id > 0 ) ? ' open' : ''; ?>>
                    <summary class="nros-dash-task-form__summary">
                        <span><?php echo ($edit_id > 0) ? esc_html($i18n['edit_alert']) : esc_html__( 'New editorial task', 'newsroom-ai-assistant' ); ?></span>
                    </summary>
                    <div class="nros-dash-task-form__body">
                    <?php if ($edit_id == 0): ?>
                    <form method="post" class="nros-form-inline nros-mb-12">
                        <?php wp_nonce_field('newsai_bulk_import', 'newsai_import_nonce'); ?>
                        <button type="submit" name="newsai_bulk_import_btn" class="button button-small" onclick="return confirm('<?php echo esc_js( __( 'Import default holidays for your country?', 'newsroom-ai-assistant' ) ); ?>');">
                            📅 <?php echo esc_html( __( 'Import Holidays', 'newsroom-ai-assistant' ) ); ?>
                        </button>
                    </form>
                    <?php endif; ?>
                    <form method="post" action="?page=newsai-settings&tab=alerts">
                        <?php wp_nonce_field('newsai_add_alert_action', 'newsai_alert_nonce'); ?>
                        <input type="hidden" name="newsai_alert_id" value="<?php echo esc_attr($edit_id); ?>">
                        
                        <div class="nros-form-grid">
                            
                            <div class="nros-form-grid--full">
                                <label class="nros-field-label"><?php echo esc_html($i18n['topic']); ?> (Required)</label>
                                <input name="t" id="nros-task-input" value="<?php echo esc_attr($def_t); ?>" required class="regular-text nros-field-input">
                            </div>
                            
                            <div>
                                <label class="nros-field-label">Target Keyword (SEO)</label>
                                <input name="tk" value="<?php echo esc_attr($def_tk); ?>" placeholder="e.g. OpenAI Sora" class="regular-text nros-field-input">
                            </div>
                            <div>
                                <label class="nros-field-label">Competitor / Reference Link</label>
                                <input type="url" name="rl" value="<?php echo esc_attr($def_rl); ?>" placeholder="https://..." class="regular-text nros-field-input">
                            </div>

                            <div class="nros-form-grid--full">
                                <label class="nros-field-label"><?php echo esc_html($i18n['notes']); ?></label>
                                <textarea name="n" rows="2" class="nros-field-input"><?php echo esc_textarea($def_n); ?></textarea>
                            </div>
                            
                            <div>
                                <label class="nros-field-label"><?php echo esc_html($i18n['date']); ?></label>
                                <input type="date" name="task_date" value="<?php echo esc_attr($def_date); ?>" required class="nros-field-input">
                            </div>
                            <div>
                                <label class="nros-field-label"><?php echo esc_html($i18n['assign_to']); ?></label>
                                <?php wp_dropdown_users([
                                    'show_option_all' => $i18n['all_users'],
                                    'name'            => 'author_id',
                                    'selected'        => $def_author,
                                    'capability'      => 'edit_posts',
                                    'number'          => 100,
                                ]); ?>
                            </div>
                            
                            <div>
                                <label class="nros-field-label"><?php echo esc_html($i18n['lead_days']); ?></label>
                                <input type="number" name="ld" value="<?php echo esc_attr($def_ld); ?>" min="1" max="90" class="nros-field-input">
                            </div>
                            <div>
                                <label class="nros-field-label"><?php echo esc_html($i18n['recurrence']); ?></label>
                                <select name="recurrence" class="nros-field-input">
                                    <option value="none" <?php selected($def_rec, 'none'); ?>><?php echo esc_html($i18n['once']); ?></option>
                                    <option value="yearly" <?php selected($def_rec, 'yearly'); ?>><?php echo esc_html($i18n['yearly']); ?></option>
                                    <option value="monthly" <?php selected($def_rec, 'monthly'); ?>><?php echo esc_html($i18n['monthly']); ?></option>
                                </select>
                            </div>

                            <div class="nros-form-actions">
                                <input type="submit" name="newsai_add_alert" class="button button-primary" value="<?php echo ($edit_id > 0) ? esc_attr($i18n['btn_update_task']) : esc_attr($i18n['btn_add_task']); ?>">
                                <?php if ($edit_id > 0): ?>
                                    <a href="?page=newsai-settings&tab=alerts" class="button"><?php echo esc_html($i18n['btn_cancel']); ?></a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                    </div>
                </details>

                <div class="nros-card nros-card--spaced nros-dash-workflow" id="nros-tasks-card">
                    <div class="nros-dash-workflow__head">
                        <div>
                            <h3 class="nros-card-title nros-dash-workflow__title"><?php echo esc_html__( 'Editorial Workflow', 'newsroom-ai-assistant' ); ?></h3>
                            <p class="nros-card-desc"><?php echo esc_html__( 'Track and manage content pipeline.', 'newsroom-ai-assistant' ); ?></p>
                        </div>
                        <div class="nros-command-bar nros-dash-workflow__filters">
                            <button type="button" class="nros-filter-chip active" data-filter="all"><?php echo esc_html($i18n['chip_all']); ?></button>
                            <button type="button" class="nros-filter-chip" data-filter="overdue"><?php echo esc_html($i18n['chip_overdue']); ?></button>
                            <button type="button" class="nros-filter-chip" data-filter="today"><?php echo esc_html($i18n['chip_today']); ?></button>
                            <?php if ($can_manage_all): ?>
                            <button type="button" class="nros-filter-chip" data-filter="unassigned"><?php echo esc_html($i18n['chip_unassigned']); ?></button>
                            <button type="button" class="nros-filter-chip" data-filter="done"><?php echo esc_html($i18n['chip_done']); ?></button>
                            <?php endif; ?>
                            <div class="nros-view-toggle">
                                <button type="button" class="nros-view-btn" data-view="table"><?php echo esc_html__( 'Table', 'newsroom-ai-assistant' ); ?></button>
                                <button type="button" class="nros-view-btn active" data-view="kanban">Kanban</button>
                            </div>
                        </div>
                    </div>
                    <div class="nros-dash-workflow__actions">
                        <form method="post" class="nros-form-inline">
                            <?php wp_nonce_field('newsai_add_alert_action', 'newsai_alert_nonce'); ?>
                            <button type="submit" name="newsai_bulk_delete" value="done" class="button button-small" onclick="return confirm('<?php echo esc_js( __( 'Delete all completed tasks?', 'newsroom-ai-assistant' ) ); ?>');">🗑️ <?php echo esc_html( __( 'Clear Completed', 'newsroom-ai-assistant' ) ); ?></button>
                            <?php if ( $can_manage_all ) : ?>
                            <button type="submit" name="newsai_bulk_delete" value="all" class="button button-small nros-btn-danger-outline" onclick="return confirm('<?php echo esc_js( __( 'WARNING: Delete ALL tasks?', 'newsroom-ai-assistant' ) ); ?>');">🚨 <?php echo esc_html( __( 'Delete All', 'newsroom-ai-assistant' ) ); ?></button>
                            <?php endif; ?>
                        </form>
                    </div>

                    <?php
                    // Whitelist ORDER BY so dynamic SQL stays review-safe.
                    $order_sql = $has_status ? 'ORDER BY status DESC, month, day' : 'ORDER BY month, day';
                    // Role gating for the task list:
                    //   - "chiefs" (Editor + Administrator, i.e. edit_others_posts) see every task
                    //   - everyone else (Author / Contributor) sees tasks assigned to them
                    //     plus unassigned pool tasks (author_id = 0).
                    $newsai_can_see_all_tasks = current_user_can( 'edit_others_posts' );
                    if ( $newsai_can_see_all_tasks ) {
                        $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} {$order_sql} LIMIT %d", 100 ) );
                    } else {
                        $rows = $wpdb->get_results(
                            $wpdb->prepare(
                                "SELECT * FROM {$table} WHERE ( author_id = %d OR author_id = 0 ) {$order_sql} LIMIT %d",
                                (int) get_current_user_id(),
                                100
                            )
                        );
                    }

                    $now_time = (int) strtotime( gmdate( 'Y-m-d' ) );
                    ?>

                    <?php newsai_render_kanban_board( $rows, $has_status, $now_time, $i18n ); ?>

                    <?php
                    // Prefetch unread message counts for every visible task in a single query
                    // (the helper handles the per-user last-seen watermark).
                    $newsai_unread_map = [];
                    if (function_exists('newsai_task_messaging_active') && newsai_task_messaging_active() && !empty($rows)) {
                        $newsai_alert_ids = [];
                        foreach ($rows as $newsai_r) {
                            $newsai_alert_ids[] = (int) $newsai_r->id;
                        }
                        if (function_exists('newsai_task_get_unread_counts')) {
                            $newsai_unread_map = newsai_task_get_unread_counts($newsai_alert_ids);
                        }
                    }
                    ?>
                    <table id="nros-table-view" class="wp-list-table widefat striped nros-border-none" style="display:none;">
                        <thead><tr><th><?php echo esc_html($i18n['col_task']); ?></th><th><?php echo esc_html($i18n['col_date']); ?></th><th><?php echo esc_html($i18n['col_writer']); ?></th><th><?php echo esc_html($i18n['col_status']); ?></th><th><?php echo esc_html($i18n['col_actions']); ?></th></tr></thead>
                        <tbody>
                            <?php 
                            if($rows): foreach($rows as $r):
                                $user = get_userdata($r->author_id);
                                $assignee = $user ? $user->display_name : $i18n['all_users'];
                                
                                $t_year = ($r->year > 0) ? $r->year : (int)gmdate('Y');
                                $t_month = ($r->month > 0) ? $r->month : (int)gmdate('m');
                                $task_time = strtotime(sprintf('%04d-%02d-%02d', $t_year, $t_month, $r->day));
                                
                                if ($r->year == 0 && $r->month > 0) { 
                                    if (($now_time - $task_time) > (15 * 86400)) { 
                                        $t_year++; 
                                        $task_time = strtotime(sprintf('%04d-%02d-%02d', $t_year, $t_month, $r->day));
                                    }
                                } elseif ($r->year == 0 && $r->month == 0) { 
                                    if (($now_time - $task_time) > (5 * 86400)) { 
                                        $t_month++; 
                                        if ($t_month > 12) { $t_month = 1; $t_year++; }
                                        $task_time = strtotime(sprintf('%04d-%02d-%02d', $t_year, $t_month, $r->day));
                                    }
                                }
                                
                                $diff_days = ($task_time - $now_time) / 86400; 

                                $status_val = $has_status ? $r->status : 'pending';
                                $status_ui = '';
                                if ($status_val === 'done') {
                                    $status_ui = '<span class="nros-status-badge nros-status-done">' . esc_html($i18n['chip_done']) . '</span>';
                                } else {
                                    if ( $diff_days < 0 ) {
                                        $status_ui = '<span class="nros-status-badge nros-status-overdue">' . esc_html__( 'OVERDUE', 'newsroom-ai-assistant' ) . '</span>';
                                    } elseif ( $diff_days <= $r->lead_days ) {
                                        $status_ui = '<span class="nros-status-badge nros-status-pending">' . esc_html(
                                            sprintf(
                                                /* translators: %d: days until task is due */
                                                __( 'Due in %d d', 'newsroom-ai-assistant' ),
                                                (int) $diff_days
                                            )
                                        ) . '</span>';
                                    } else {
                                        $status_ui = '<span class="nros-status-scheduled">' . esc_html__( 'Scheduled', 'newsroom-ai-assistant' ) . '</span>';
                                    }
                                }
                                ?>
                                <?php
                                $task_messaging_on = function_exists('newsai_task_messaging_active') && newsai_task_messaging_active();
                                $task_messaging_locked = !$task_messaging_on && function_exists('newsai_is_pro') && !newsai_is_pro();
                                $msg_label_open = __( '💬 Discussion', 'newsroom-ai-assistant' );
                                $msg_label_lock = __( '💬 Discussion (Pro)', 'newsroom-ai-assistant' );
                                ?>
                                <tr data-status="<?php echo esc_attr($status_val); ?>" data-overdue="<?php echo esc_attr( ( $diff_days < 0 ) ? '1' : '0' ); ?>" data-today="<?php echo esc_attr( ( $diff_days == 0 ) ? '1' : '0' ); ?>" data-unassigned="<?php echo esc_attr( ( (int) $r->author_id === 0 ) ? '1' : '0' ); ?>" data-alert-id="<?php echo (int) $r->id; ?>" data-alert-title="<?php echo esc_attr($r->title); ?>">
                                    <td>
                                        <strong><?php echo esc_html($r->title); ?></strong>
                                        <?php if(isset($r->target_keyword) && !empty($r->target_keyword)) echo '<br><span class="nros-task-keyword">🔑 ' . esc_html($r->target_keyword) . '</span>'; ?>
                                        <?php if ($task_messaging_on): ?>
                                            <?php
                                            $unread_count = isset($newsai_unread_map[(int)$r->id]) ? (int) $newsai_unread_map[(int)$r->id] : 0;
                                            $badge_label  = $unread_count > 99 ? '99+' : (string) $unread_count;
                                            $badge_aria = sprintf(
                                                /* translators: %d: number of unread messages */
                                                _n( '%d unread message', '%d unread messages', $unread_count, 'newsroom-ai-assistant' ),
                                                $unread_count
                                            );
                                            ?>
                                            <br><a href="#" class="newsai-task-thread-open nros-task-thread-link" data-alert-id="<?php echo (int)$r->id; ?>" data-alert-title="<?php echo esc_attr($r->title); ?>">
                                                <span><?php echo esc_html($msg_label_open); ?></span>
                                                <span class="newsai-task-thread-badge nros-unread-badge" data-alert-id="<?php echo (int)$r->id; ?>" aria-label="<?php echo esc_attr($badge_aria); ?>"<?php echo $unread_count > 0 ? '' : ' hidden'; ?>><?php echo esc_html($badge_label); ?></span>
                                            </a>
                                        <?php elseif ($task_messaging_locked && function_exists('newsai_pro_promo_link')): ?>
                                            <br><a href="<?php echo esc_url(newsai_pro_promo_link('task-thread-lock')); ?>" target="_blank" rel="noopener" class="nros-task-thread-link nros-task-thread-link--locked" title="<?php echo esc_attr(__( 'Unlock with Pro', 'newsroom-ai-assistant' )); ?>">🔒 <?php echo esc_html($msg_label_lock); ?></a>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo esc_html( sprintf( '%02d/%02d', (int) $r->day, (int) $r->month ) ); ?></td>
                                    <td><?php echo esc_html($assignee); ?></td>
                                    <td><?php echo wp_kses_post( $status_ui ); ?></td>
                                    <td>
                                        <?php
                                        $edit_url = add_query_arg(['page' => 'newsai-settings', 'tab' => 'alerts', 'edit' => (int)$r->id], admin_url('admin.php'));
                                        $done_url = wp_nonce_url(add_query_arg(['page' => 'newsai-settings', 'tab' => 'alerts', 'mark_done' => 1, 'id' => (int)$r->id], admin_url('admin.php')), 'newsai_mark_done_' . (int)$r->id);
                                        $delete_url = wp_nonce_url(add_query_arg(['page' => 'newsai-settings', 'tab' => 'alerts', 'del' => (int)$r->id], admin_url('admin.php')), 'newsai_delete_task_' . (int)$r->id);
                                        ?>
                                        <select class="nros-actions-select" data-id="<?php echo (int)$r->id; ?>">
                                            <option value=""><?php echo esc_html($i18n['actions_label']); ?></option>
                                            <option value="<?php echo esc_url($edit_url); ?>"><?php echo esc_html($i18n['actions_edit']); ?></option>
                                            <?php if ($status_val !== 'done' && $has_status && $can_edit_tasks): ?>
                                            <option value="<?php echo esc_url($done_url); ?>"><?php echo esc_html($i18n['actions_done']); ?></option>
                                            <?php endif; ?>
                                            <?php if ($can_manage_all): ?>
                                            <option value="<?php echo esc_url($delete_url); ?>"><?php echo esc_html($i18n['actions_delete']); ?></option>
                                            <?php endif; ?>
                                        </select>
                                    </td>
                                </tr>
                            <?php endforeach; else: ?>
                                <tr><td colspan="5" class="nros-empty-cell"><?php echo esc_html($i18n['no_tasks']); ?></td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="nros-card nros-card--spaced nros-dash-latest">
                    <div class="nros-card-header">
                        <h3 class="nros-card-title"><?php echo esc_html( __( 'Latest Published', 'newsroom-ai-assistant' ) ); ?></h3>
                        <a href="<?php echo esc_url( admin_url( 'edit.php' ) ); ?>" class="button button-small"><?php echo esc_html( __( 'View All', 'newsroom-ai-assistant' ) ); ?></a>
                    </div>
                    <ul class="nros-post-list">
                        <?php
                        $latest_posts = get_posts(['post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 5]);
                        if ($latest_posts) {
                            foreach ($latest_posts as $lp) {
                                $author_name = get_the_author_meta('display_name', $lp->post_author);
                                $edit_l = get_edit_post_link( $lp->ID );
                                $permalink = get_permalink( $lp->ID );
                                $thumb = get_the_post_thumbnail_url( $lp->ID, 'thumbnail' );
                                $initials = function_exists( 'newsai_dashboard_registry_initials' ) ? newsai_dashboard_registry_initials( $author_name ) : '?';
                                echo '<li class="nros-post-list__item nros-dash-post">';
                                if ( $thumb ) {
                                    echo '<img class="nros-dash-post__thumb" src="' . esc_url( $thumb ) . '" alt="" loading="lazy" width="48" height="48">';
                                } else {
                                    echo '<span class="nros-dash-post__thumb nros-dash-post__thumb--placeholder" aria-hidden="true"></span>';
                                }
                                echo '<div class="nros-min-w-0 nros-post-list__body">';
                                echo '<a href="' . esc_url( $edit_l ? $edit_l : '#' ) . '" class="nros-post-list__title">' . esc_html( $lp->post_title ) . '</a>';
                                echo '<span class="nros-post-list__meta"><span class="nros-dash-post__avatar" aria-hidden="true">' . esc_html( $initials ) . '</span> ' . esc_html( $author_name ) . ' · ' . esc_html( human_time_diff( get_post_time( 'U', false, $lp->ID ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'newsroom-ai-assistant' ) ) . '</span>';
                                echo '</div>';
                                echo '<span class="nros-dash-post__badge">' . esc_html__( 'Published', 'newsroom-ai-assistant' ) . '</span>';
                                echo '</li>';
                            }
                        } else {
                            echo '<li class="nros-post-list__empty">' . esc_html($i18n['no_articles']) . '</li>';
                        }
                        ?>
                    </ul>
                </div>

            </div>

            <div class="nros-col-4">

                <?php
                // My discussions — appears for any Pro user (authors + chiefs) when at least
                // one task thread has activity they can see. Click rows to open the same
                // drawer used everywhere else.
                $newsai_threads = [];
                if (function_exists('newsai_task_messaging_active') && newsai_task_messaging_active()
                    && function_exists('newsai_task_get_user_threads_with_unread')) {
                    $newsai_threads_all = newsai_task_get_user_threads_with_unread((int) get_current_user_id(), 50);
                    // Keep only tasks that actually have a message thread (last_ts not empty),
                    // so the card disappears entirely on a brand-new install.
                    foreach ($newsai_threads_all as $t) {
                        if (!empty($t['last_ts'])) { $newsai_threads[] = $t; }
                    }
                }
                $newsai_total_unread = 0;
                foreach ($newsai_threads as $t) { $newsai_total_unread += (int) $t['unread']; }
                if (!empty($newsai_threads)):
                ?>
                <div class="nros-card nros-card--spaced">
                    <div class="nros-flex-between nros-mb-8">
                        <h3 class="nros-card-title">💬 <?php echo esc_html(__( 'My discussions', 'newsroom-ai-assistant' )); ?></h3>
                        <?php if ($newsai_total_unread > 0): ?>
                            <span class="nros-unread-badge nros-unread-badge--md"><?php echo esc_html($newsai_total_unread > 99 ? '99+' : (string) $newsai_total_unread); ?></span>
                        <?php endif; ?>
                    </div>
                    <p class="nros-card-desc nros-mb-14">
                        <?php echo esc_html(__( 'Latest activity on tasks you participate in. Click a row to open the thread.', 'newsroom-ai-assistant' )); ?>
                    </p>
                    <ul class="nros-thread-list">
                        <?php
                        $display_count = 0;
                        foreach ($newsai_threads as $t) {
                            if ($display_count >= 6) { break; }
                            // Skip tasks with no activity AND no unread (already filtered above
                            // by last_ts, but be defensive).
                            if (empty($t['last_ts']) && (int) $t['unread'] === 0) { continue; }
                            $display_count++;
                            $unread = (int) $t['unread'];
                            $row_class = $unread > 0 ? 'nros-thread-row nros-thread-row--unread' : 'nros-thread-row';
                            $last_human = '';
                            if (!empty($t['last_ts'])) {
                                $ts = strtotime($t['last_ts'] . ' UTC');
                                if ($ts > 0) {
                                    $last_human = human_time_diff($ts, current_time('timestamp')) . ' ' . (__( 'ago', 'newsroom-ai-assistant' ));
                                }
                            }
                            ?>
                            <li>
                                <a href="#" class="newsai-task-thread-open <?php echo esc_attr( $row_class ); ?>" data-alert-id="<?php echo (int) $t['alert_id']; ?>" data-alert-title="<?php echo esc_attr($t['title']); ?>">
                                    <span class="nros-min-w-0">
                                        <strong class="nros-thread-row__title"><?php echo esc_html($t['title']); ?></strong>
                                        <?php if ($last_human !== ''): ?>
                                            <small class="nros-thread-row__time">🕒 <?php echo esc_html($last_human); ?></small>
                                        <?php endif; ?>
                                    </span>
                                    <?php if ($unread > 0): ?>
                                        <span class="nros-unread-badge nros-unread-badge--sm nros-flex-shrink-0"><?php echo esc_html($unread > 99 ? '99+' : (string) $unread); ?></span>
                                    <?php else: ?>
                                        <span class="nros-thread-done">✓</span>
                                    <?php endif; ?>
                                </a>
                            </li>
                            <?php
                        }
                        ?>
                    </ul>
                </div>
                <?php endif; ?>

                <?php
                // Instant URL Ping widget — visible only to editors-in-chief (manage_options).
                // Pro-gated: writers and free sites don't see this card at all to keep the
                // dashboard uncluttered. Submit pushes the URL to whichever pipes are enabled
                // in Settings → Instant Indexing (Google API and/or Bing IndexNow).
                $newsai_can_ping = $can_manage_all && function_exists('newsai_is_pro') && newsai_is_pro();
                $newsai_google_on   = (get_option('newsai_indexing_enabled', 'no') === 'yes');
                $newsai_indexnow_on = (get_option('newsai_indexnow_enabled', 'no') === 'yes');
                if ($newsai_can_ping):
                ?>
                <div class="nros-card nros-card--spaced">
                    <h3 class="nros-card-title nros-card-title--sm">⚡ <?php echo esc_html(__( 'Instant URL ping', 'newsroom-ai-assistant' )); ?></h3>
                    <p class="nros-card-desc">
                        <?php echo esc_html(__( 'Force a re-crawl for any URL on this site. Goes to whichever providers are enabled in Settings.', 'newsroom-ai-assistant' )); ?>
                    </p>
                    <?php if (!$newsai_google_on && !$newsai_indexnow_on): ?>
                        <div class="nros-notice-warn">
                            <?php
                            $settings_link = '<a href="' . esc_url(admin_url('admin.php?page=newsai-settings&tab=settings#indexing')) . '">' . esc_html(__( 'Settings → Instant Indexing', 'newsroom-ai-assistant' )) . '</a>';
                            echo wp_kses_post( sprintf(
                                /* translators: %s: HTML link to the Instant Indexing settings tab */
                                __( 'No indexing provider is enabled yet. Open %s to enable Google or Bing IndexNow.', 'newsroom-ai-assistant' ),
                                $settings_link
                            ) );
                            ?>
                        </div>
                    <?php else: ?>
                        <p class="nros-card-desc nros-card-desc--tight">
                            <?php
                            $active = [];
                            if ($newsai_google_on)   { $active[] = '🔵 Google'; }
                            if ($newsai_indexnow_on) { $active[] = '🟢 IndexNow'; }
                            echo esc_html(__( 'Active providers: ', 'newsroom-ai-assistant' )) . esc_html(implode(' · ', $active));
                            ?>
                        </p>
                    <?php endif; ?>

                    <input type="url" id="newsai-ping-url" class="nros-ping-input" placeholder="<?php echo esc_attr(home_url('/your-article/')); ?>"
                           <?php echo (!$newsai_google_on && !$newsai_indexnow_on) ? 'disabled' : ''; ?>>
                    <button type="button" id="newsai-ping-submit" class="button button-primary nros-w-full"
                           <?php echo (!$newsai_google_on && !$newsai_indexnow_on) ? 'disabled' : ''; ?>>
                        🚀 <?php echo esc_html(__( 'Submit now', 'newsroom-ai-assistant' )); ?>
                    </button>
                    <div id="newsai-ping-result" class="nros-ping-result"></div>
                </div>
                <script>
                (function () {
                    if (typeof jQuery === 'undefined' || typeof newsai_vars === 'undefined') { return; }
                    var $ = jQuery;
                    var $btn = $('#newsai-ping-submit');
                    var $url = $('#newsai-ping-url');
                    var $out = $('#newsai-ping-result');
                    if (!$btn.length) { return; }
                    $btn.on('click', function () {
                        var url = $.trim($url.val() || '');
                        if (!url) {
                            $out.html('<span class="nros-ping-msg nros-ping-msg--err">⚠️ ' + <?php echo wp_json_encode(__( 'Enter a URL first.', 'newsroom-ai-assistant' )); ?> + '</span>');
                            return;
                        }
                        $btn.prop('disabled', true);
                        $out.html('<span class="nros-ping-msg nros-ping-msg--muted">⏳ ' + <?php echo wp_json_encode(__( 'Submitting…', 'newsroom-ai-assistant' )); ?> + '</span>');
                        $.post(newsai_vars.ajax_url, {
                            action: 'newsai_ping_url',
                            nonce: newsai_vars.nonce,
                            url: url
                        }).done(function (resp) {
                            if (resp && resp.success) {
                                var lines = [];
                                if (resp.data.google) {
                                    var g = resp.data.google;
                                    lines.push((g.ok ? '✅ ' : '❌ ') + 'Google: ' + (g.message || ('HTTP ' + g.code)));
                                }
                                if (resp.data.indexnow) {
                                    var i = resp.data.indexnow;
                                    lines.push((i.ok ? '✅ ' : '❌ ') + 'IndexNow: ' + (i.message || ('HTTP ' + i.code)));
                                }
                                if (!lines.length) {
                                    lines.push('ℹ️ ' + (resp.data.message || 'Done.'));
                                }
                                $out.html(lines.map(function (l) {
                                    var cls = (l.indexOf('✅') === 0) ? 'nros-ping-msg--ok' : (l.indexOf('❌') === 0 ? 'nros-ping-msg--err' : 'nros-ping-msg--neutral');
                                    return '<div class="nros-ping-msg ' + cls + '">' + $('<div/>').text(l).html() + '</div>';
                                }).join(''));
                            } else {
                                var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Error';
                                $out.html('<span class="nros-ping-msg nros-ping-msg--err">❌ ' + $('<div/>').text(msg).html() + '</span>');
                            }
                        }).fail(function () {
                            $out.html('<span class="nros-ping-msg nros-ping-msg--err">❌ Network error</span>');
                        }).always(function () {
                            $btn.prop('disabled', false);
                        });
                    });
                })();
                </script>
                <?php endif; ?>

                <div class="nros-card nros-card--flush nros-card--spaced">
                    <div class="nros-p-20">
                        <h3 class="nros-card-title nros-card-title--sm"><?php echo esc_html( __( 'Writer performance', 'newsroom-ai-assistant' ) ); ?></h3>
                        <p class="nros-card-desc nros-mb-20"><?php echo esc_html( __( 'Published posts (last 30 days) vs the previous 30 days.', 'newsroom-ai-assistant' ) ); ?></p>
                        <?php
                        $pro_unlocked = function_exists( 'newsai_is_pro' ) && newsai_is_pro();
                        if ( $pro_unlocked ) {
                            $board = function_exists( 'newsai_pro_get_writer_leaderboard' ) ? newsai_pro_get_writer_leaderboard( 5 ) : [];
                            if ( empty( $board ) ) {
                                echo '<p class="nros-card-desc nros-mb-0">' . esc_html( __( 'No posts published in the last 30 days.', 'newsroom-ai-assistant' ) ) . '</p>';
                            } else {
                                $n = count( $board );
                                foreach ( $board as $i => $row ) {
                                    $is_last = ( $i === $n - 1 );
                                    $hue       = abs( crc32( (string) $row['user_id'] ) % 360 );
                                    $bg        = "hsl({$hue}, 70%, 95%)";
                                    $fg        = "hsl({$hue}, 70%, 32%)";
                                    $trend = isset( $row['trend'] ) ? $row['trend'] : 'flat';
                                    $row_class = $is_last ? 'nros-perf-row nros-perf-row--last' : 'nros-perf-row';
                                    echo '<div class="' . esc_attr( $row_class ) . '">';
                                    echo '<div class="nros-flex-center nros-min-w-0">';
                                    echo '<div class="nros-avatar nros-flex-shrink-0" style="background:' . esc_attr( $bg ) . ';color:' . esc_attr( $fg ) . ';">' . esc_html( $row['initials'] ) . '</div>';
                                    echo '<span class="nros-perf-row__name" title="' . esc_attr( $row['name'] ) . '">' . esc_html( $row['name'] ) . '</span>';
                                    echo '</div>';
                                    echo '<div class="nros-flex-gap-8 nros-flex-shrink-0">';
                                    echo '<strong class="nros-perf-row__score">' . esc_html( (string) (int) $row['posts_30d'] ) . '</strong>';
                                    if ( $trend === 'up' ) {
                                        echo '<span class="nros-trend-up">↗</span>';
                                    } elseif ( $trend === 'down' ) {
                                        echo '<span class="nros-trend-down">↘</span>';
                                    } else {
                                        echo '<span class="nros-trend-flat">—</span>';
                                    }
                                    echo '</div></div>';
                                }
                            }
                        } else {
                            ?>
                        <div class="nros-perf-row">
                            <div class="nros-flex-center">
                                <div class="nros-avatar">JD</div>
                                <span class="nros-perf-row__name">John Doe</span>
                            </div>
                            <div class="nros-flex-gap-8">
                                <strong class="nros-perf-row__score">88</strong>
                                <span class="nros-trend-up">↗</span>
                            </div>
                        </div>
                        <div class="nros-perf-row">
                            <div class="nros-flex-center">
                                <div class="nros-avatar" style="background:#fef2f2;color:#dc2626;">MS</div>
                                <span class="nros-perf-row__name">Maria Smith</span>
                            </div>
                            <div class="nros-flex-gap-8">
                                <strong class="nros-perf-row__score">82</strong>
                                <span class="nros-trend-up">↗</span>
                            </div>
                        </div>
                        <div class="nros-perf-row nros-perf-row--last">
                            <div class="nros-flex-center">
                                <div class="nros-avatar" style="background:#fcfcfc;color:#646970;">AC</div>
                                <span class="nros-perf-row__name">Alex Chen</span>
                            </div>
                            <div class="nros-flex-gap-8">
                                <strong class="nros-perf-row__score">75</strong>
                                <span class="nros-trend-down">↘</span>
                            </div>
                        </div>
                            <?php
                        }
                        ?>
                    </div>
                    <?php if ( ! $pro_unlocked ) : ?>
                    <div class="nros-pro-overlay">
                        <div class="nros-pro-badge">🔒 PRO FEATURE</div>
                        <h4><?php echo esc_html( __( 'Editorial analytics', 'newsroom-ai-assistant' ) ); ?></h4>
                        <p><?php echo esc_html( __( 'Real writer leaderboards, output trends, and SEO signals — unlock with Newsroom Pro.', 'newsroom-ai-assistant' ) ); ?></p>
                    </div>
                    <?php endif; ?>
                </div>

                <div class="nros-card nros-radar-card postbox nros-card--flush nros-card--spaced">
                    <div class="nros-p-15-20">
                        <h3 class="nros-card-title nros-card-title--sm nros-flex-gap-8">
                            <?php echo esc_html__( 'Trend Radar', 'newsroom-ai-assistant' ); ?>
                            <span class="nros-live-badge">LIVE</span>
                        </h3>
                        <div class="nros-radar-tabs">
                            <div class="nros-flex-gap-20">
                                <span class="newsai-tab active" data-target="newsai-trends">TRENDS</span>
                                <span class="newsai-tab" data-target="newsai-news">NEWS</span>
                            </div>
                            <select id="newsai-trends-geo" class="nros-radar-geo">
    <option value="GR" <?php selected($geo_opt, 'GR'); ?>>Greece (GR)</option>
    <option value="CY" <?php selected($geo_opt, 'CY'); ?>>Cyprus (CY)</option>
    <option value="US" <?php selected($geo_opt, 'US'); ?>>USA (US)</option>
    <option value="GB" <?php selected($geo_opt, 'GB'); ?>>UK (GB)</option>
    <option value="CA" <?php selected($geo_opt, 'CA'); ?>>Canada (CA)</option>
    <option value="AU" <?php selected($geo_opt, 'AU'); ?>>Australia (AU)</option>
    <option value="DE" <?php selected($geo_opt, 'DE'); ?>>Germany (DE)</option>
    <option value="FR" <?php selected($geo_opt, 'FR'); ?>>France (FR)</option>
    <option value="IT" <?php selected($geo_opt, 'IT'); ?>>Italy (IT)</option>
    <option value="ES" <?php selected($geo_opt, 'ES'); ?>>Spain (ES)</option>
    <option value="NL" <?php selected($geo_opt, 'NL'); ?>>Netherlands (NL)</option>
    <option value="BE" <?php selected($geo_opt, 'BE'); ?>>Belgium (BE)</option>
    <option value="CH" <?php selected($geo_opt, 'CH'); ?>>Switzerland (CH)</option>
    <option value="SE" <?php selected($geo_opt, 'SE'); ?>>Sweden (SE)</option>
    <option value="PT" <?php selected($geo_opt, 'PT'); ?>>Portugal (PT)</option>
    <option value="BR" <?php selected($geo_opt, 'BR'); ?>>Brazil (BR)</option>
    <option value="MX" <?php selected($geo_opt, 'MX'); ?>>Mexico (MX)</option>
    <option value="RU" <?php selected($geo_opt, 'RU'); ?>>Russia (RU)</option>
    <option value="JP" <?php selected($geo_opt, 'JP'); ?>>Japan (JP)</option>
    <option value="IN" <?php selected($geo_opt, 'IN'); ?>>India (IN)</option>
    <option value="ID" <?php selected($geo_opt, 'ID'); ?>>Indonesia (ID)</option>
    <option value="ZA" <?php selected($geo_opt, 'ZA'); ?>>South Africa (ZA)</option>
</select>
                        </div>
                    </div>
                    <div id="newsai-trends-list" class="newsai-tab-content nros-radar-pane" data-nros-radar-lazy="1"><span class="nros-radar-idle"><?php echo esc_html__( 'Loading trends…', 'newsroom-ai-assistant' ); ?></span></div>
                    <div id="newsai-news-list" class="newsai-tab-content nros-radar-pane" style="display:none;" data-nros-radar-lazy="1"><span class="nros-radar-idle"><?php echo esc_html__( 'Tap NEWS to load headlines.', 'newsroom-ai-assistant' ); ?></span></div>
                    <?php
                    if ( function_exists( 'newsai_render_content_brief_bar' ) ) {
                        newsai_render_content_brief_bar( [ 'context' => 'dashboard' ] );
                    }
                    ?>
                </div>

                <div class="nros-card nros-p-20 nros-card--spaced nros-dash-competitor">
                    <h3 class="nros-card-title nros-card-title--sm"><?php echo esc_html__( 'Competitor Watch', 'newsroom-ai-assistant' ); ?></h3>
                    <p class="nros-card-desc"><?php echo esc_html__( 'Latest articles from tracked competitors', 'newsroom-ai-assistant' ); ?></p>
                    <form method="post" class="nros-mb-14">
                        <?php wp_nonce_field('save_comp', 'newsai_comp_nonce'); ?>
                        <textarea name="comp_rss" class="nros-field-input nros-comp-feed-input" placeholder="RSS URLs (1 per line)"><?php echo esc_textarea($comp_rss); ?></textarea>
                        <input type="submit" name="newsai_save_competitor" class="button button-small nros-comp-save-btn" value="Save Feeds">
                    </form>
                    
                    <div class="nros-comp-scroll">
                        <ul class="nros-comp-list">
                        <?php
                        $comp_rss_array = array_filter(array_map('trim', explode("\n", $comp_rss)));
                        if (!empty($comp_rss_array)) {
                            $nros_feed_lifetime_filter = function(){ return 120; };
                            add_filter('wp_feed_cache_transient_lifetime', $nros_feed_lifetime_filter);
                            
                            $nros_timeout = function() { return 3; };
                            add_filter( 'http_request_timeout', $nros_timeout, 999 );
                            
                            $comp_feed = fetch_feed($comp_rss_array);
                            
                            remove_filter( 'http_request_timeout', $nros_timeout, 999 );
                            remove_filter('wp_feed_cache_transient_lifetime', $nros_feed_lifetime_filter);

                            if (!is_wp_error($comp_feed)) {
                                $maxitems = $comp_feed->get_item_quantity(10);
                                $rss_items = $comp_feed->get_items(0, $maxitems);
                                if (empty($rss_items)) {
                                    echo '<li class="nros-comp-empty">' . esc_html($i18n['no_articles']) . '</li>';
                                } else {
                                    foreach ($rss_items as $item) {
                                        $safe_title = esc_attr($item->get_title()); 
                                        $feed = $item->get_feed();
                                        $raw_site_name = $feed ? $feed->get_title() : '';
                                        if (empty($raw_site_name)) {
                                            $parsed_url = parse_url($item->get_permalink());
                                            $raw_site_name = isset($parsed_url['host']) ? str_replace('www.', '', $parsed_url['host']) : 'News';
                                        }
                                        $site_name = mb_strlen($raw_site_name) > 18 ? mb_substr($raw_site_name, 0, 15) . '...' : $raw_site_name;
                                        
                                        $hue = abs(crc32($raw_site_name) % 360);
                                        $color = "hsl({$hue}, 70%, 35%)";
                                        $bg = "hsl({$hue}, 70%, 95%)";

                                        echo '<li class="nros-comp-item">';
                                        echo '<div class="nros-comp-item__meta">';
                                        echo '<span class="nros-comp-source" style="background:' . esc_attr( $bg ) . ';color:' . esc_attr( $color ) . ';border-color:' . esc_attr( $color ) . ';">' . esc_html($site_name) . '</span>';
                                        echo '<span class="nros-comp-time">' . esc_html($item->get_date('H:i')) . '</span>';
                                        echo '</div>';
                                        echo '<div class="nros-comp-item__body">';
                                        echo '<a href="' . esc_url($item->get_permalink()) . '" target="_blank" rel="noopener noreferrer" class="nros-comp-link">' . esc_html($item->get_title()) . '</a>';
                                        echo '<button type="button" class="button button-small nros-copy-task-btn nros-comp-add-btn" data-title="' . $safe_title . '" aria-label="' . esc_attr__( 'Add to brief', 'newsroom-ai-assistant' ) . '"><span class="nros-comp-add-btn__icon" aria-hidden="true">+</span><span class="nros-comp-add-btn__label">' . esc_html__( 'Brief', 'newsroom-ai-assistant' ) . '</span></button>';
                                        echo '</div></li>';
                                    }
                                }
                            } else { echo '<li class="nros-comp-error">' . esc_html($i18n['invalid_rss']) . '</li>'; }
                        } else { 
                            echo '<li class="nros-comp-placeholder">Add competitor RSS URLs to track content gaps here.</li>'; 
                        }
                        ?>
                        </ul>
                    </div>
                </div>

            </div>
        </div>
        </div><!-- .nros-dash-bento -->
        
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            const nrosUi = {
                confirmDelete: <?php echo wp_json_encode($i18n['confirm_delete']); ?>,
                confirmDone: <?php echo wp_json_encode($i18n['confirm_done']); ?>
            };
            const tableView = document.getElementById('nros-table-view');
            const kanbanView = document.getElementById('nros-kanban-view');
            const taskFormCard = document.getElementById('nros-task-form-card');
            const newTaskBtn = document.getElementById('nros-dash-new-task');

            function setDashboardView(isKanban) {
                if (tableView) tableView.style.display = isKanban ? 'none' : '';
                if (kanbanView) {
                    kanbanView.style.display = isKanban ? 'block' : 'none';
                    kanbanView.classList.toggle('is-visible', isKanban);
                }
            }

            function applyTaskFilter(filter) {
                const taskRows = document.querySelectorAll('.wp-list-table tbody tr[data-status]');
                taskRows.forEach(row => {
                    let show = true;
                    if (filter === 'overdue') show = row.getAttribute('data-overdue') === '1' && row.getAttribute('data-status') !== 'done';
                    if (filter === 'today') show = row.getAttribute('data-today') === '1' && row.getAttribute('data-status') !== 'done';
                    if (filter === 'unassigned') show = row.getAttribute('data-unassigned') === '1' && row.getAttribute('data-status') !== 'done';
                    if (filter === 'done') show = row.getAttribute('data-status') === 'done';
                    if (filter === 'all') show = true;
                    row.style.display = show ? '' : 'none';
                });

                const kanbanCards = document.querySelectorAll('.nros-kanban-card[data-status]');
                kanbanCards.forEach(card => {
                    let show = true;
                    if (filter === 'overdue') show = card.getAttribute('data-overdue') === '1' && card.getAttribute('data-status') !== 'done';
                    if (filter === 'today') show = card.getAttribute('data-today') === '1' && card.getAttribute('data-status') !== 'done';
                    if (filter === 'unassigned') show = card.getAttribute('data-unassigned') === '1' && card.getAttribute('data-status') !== 'done';
                    if (filter === 'done') show = card.getAttribute('data-status') === 'done';
                    if (filter === 'all') show = true;
                    card.style.display = show ? '' : 'none';
                });

                document.querySelectorAll('.nros-kanban-empty').forEach(empty => {
                    const body = empty.closest('.nros-kanban-body');
                    if (!body) return;
                    const visible = body.querySelectorAll('.nros-kanban-card:not([style*="display: none"])').length;
                    empty.style.display = visible === 0 ? '' : 'none';
                });
            }

            setDashboardView(true);

            if (newTaskBtn && taskFormCard) {
                newTaskBtn.addEventListener('click', function() {
                    taskFormCard.open = true;
                    taskFormCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    const taskInput = document.getElementById('nros-task-input');
                    if (taskInput) {
                        setTimeout(function() { taskInput.focus(); }, 300);
                    }
                });
            }
            
            document.addEventListener('click', function(e) {
                const viewBtn = e.target.closest('.nros-view-btn');
                if (viewBtn) {
                    document.querySelectorAll('.nros-view-btn').forEach(v => v.classList.remove('active'));
                    viewBtn.classList.add('active');
                    const isKanban = viewBtn.getAttribute('data-view') === 'kanban';
                    setDashboardView(isKanban);
                    return;
                }

                const chip = e.target.closest('.nros-filter-chip');
                if (chip) {
                    document.querySelectorAll('.nros-filter-chip').forEach(c => c.classList.remove('active'));
                    chip.classList.add('active');
                    const filter = chip.getAttribute('data-filter') || 'all';
                    applyTaskFilter(filter);
                    return;
                }
            });

            document.addEventListener('change', function(e) {
                const sel = e.target.closest('.nros-actions-select');
                if (!sel || !sel.value) return;
                const isDelete = sel.value.includes('&del=');
                const isMarkDone = sel.value.includes('&mark_done=1');
                if (isDelete && !confirm(nrosUi.confirmDelete)) {
                    sel.value = '';
                    return;
                }
                if (isMarkDone && !confirm(nrosUi.confirmDone)) {
                    sel.value = '';
                    return;
                }
                window.location.href = sel.value;
            });
        });
        </script>
        </div><!-- .newsai-classic-dashboard-wrap -->

        <?php elseif ($tab == 'insights'): ?>
            <div class="newsai-classic-insights-wrap<?php echo $newsai_react_shell ? ' newsai-classic-insights-wrap--defer-hide' : ''; ?>">
            <?php
            $days = isset( $_GET['days'] ) ? (int) wp_unslash( $_GET['days'] ) : 30;
            $days = max( 7, min( 90, $days ) );
            $is_pro_active = function_exists( 'newsai_is_pro' ) && newsai_is_pro();
            if ( current_user_can( 'edit_others_posts' ) && function_exists( 'newsai_render_chief_insights_panel' ) ) {
                newsai_render_chief_insights_panel( $days, $is_pro_active );
            } else {
                echo '<div class="nros-card"><p>' . esc_html( __( 'Chief Insights is available to users who can edit others\' posts.', 'newsroom-ai-assistant' ) ) . '</p></div>';
            }
            ?>
            </div>

        <?php elseif ($tab == 'perf'): ?>
            <div class="newsai-classic-perf-wrap<?php echo $newsai_react_shell ? ' newsai-classic-perf-wrap--defer-hide' : ''; ?>">
            <?php
            if ( function_exists( 'newsai_is_pro' ) && newsai_is_pro() && current_user_can( 'edit_others_posts' ) ) {
                if ( function_exists( 'newsai_pro_render_author_performance_panel' ) ) {
                    newsai_pro_render_author_performance_panel( $lang );
                } else {
                    echo '<p style="color:#646970;">' . esc_html( __( 'Author Performance module not loaded.', 'newsroom-ai-assistant' ) ) . '</p>';
                }
            } else {
                echo '<div class="nros-card"><p>' . esc_html( __( 'This section is available only with a PRO license and to users who can edit others\' posts.', 'newsroom-ai-assistant' ) ) . '</p></div>';
            }
            ?>
            </div>

        <?php elseif ($tab == 'pro'): ?>
            <div class="newsai-classic-pro-wrap<?php echo $newsai_react_shell ? ' newsai-classic-pro-wrap--defer-hide' : ''; ?>">
            <?php
            $pro_build    = defined( 'NEWSAI_PRO_BUILD' ) && NEWSAI_PRO_BUILD;
            $lic_valid    = ( function_exists( 'newsai_is_pro' ) && newsai_is_pro() );
            $saved_key    = function_exists( 'newsai_secret_get' ) ? newsai_secret_get( 'pro_license_key' ) : (string) get_option( 'newsai_pro_license_key', '' );
            $lic_status   = (string) get_option( 'newsai_pro_license_status', '' );
            $lic_checked  = (int) get_option( 'newsai_pro_license_checked_at', 0 );
            $lic_expires  = (string) get_option( 'newsai_pro_license_expires_at', '' );
            $exp_still_ok = ( $lic_expires === '' || ! function_exists( 'newsai_pro_license_date_still_valid' ) )
                ? true
                : newsai_pro_license_date_still_valid( $lic_expires );
            $mask_key = '';
            if ( strlen( $saved_key ) > 10 ) {
                $mask_key = substr( $saved_key, 0, 4 ) . '****' . substr( $saved_key, -4 );
            }
            if ( function_exists( 'newsai_render_classic_page_head' ) ) {
                newsai_render_classic_page_head(
                    __( 'PRO Features', 'newsroom-ai-assistant' ),
                    __( 'Activate your NewsOS license and unlock desk-wide analytics.', 'newsroom-ai-assistant' )
                );
            }
            ?>
        <div class="nros-card nros-pro-panel">
            <div class="nros-pro-panel__hero">
                <span class="nros-pro-panel__icon" aria-hidden="true">⚡</span>
                <div>
                    <h3 class="nros-pro-panel__title"><?php echo esc_html( $i18n['pro_lic_title'] ); ?></h3>
                    <p class="nros-pro-panel__intro"><?php echo esc_html( $i18n['pro_lic_intro'] ); ?></p>
                </div>
                <?php if ( $lic_valid && ! $pro_build ) : ?>
                    <span class="nros-pro-panel__status is-active"><?php echo esc_html__( 'Active', 'newsroom-ai-assistant' ); ?></span>
                <?php elseif ( ! $pro_build ) : ?>
                    <span class="nros-pro-panel__status"><?php echo esc_html__( 'Inactive', 'newsroom-ai-assistant' ); ?></span>
                <?php endif; ?>
            </div>
            <div class="nros-pro-panel__body">
            <?php if ( $pro_build ) : ?>
                <div class="notice notice-info" style="margin: 0 0 20px 0;"><p><?php echo esc_html( $i18n['pro_lic_build'] ); ?></p></div>
            <?php endif; ?>

            <?php if ( $lic_valid && ! $pro_build && $saved_key !== '' && $exp_still_ok ) : ?>
                <p style="color:#50575e; font-size: 14px;"><strong><?php echo esc_html( $i18n['pro_lic_status'] ); ?>:</strong> <?php echo esc_html( ( $lic_status === 'valid' ) ? ( __( 'Active', 'newsroom-ai-assistant' ) ) : $lic_status ); ?></p>
                <p style="color:#50575e; font-size: 14px;"><strong><?php echo esc_html( $i18n['pro_lic_key'] ); ?>:</strong> <code><?php echo esc_html( $mask_key ); ?></code></p>
                <?php if ( $lic_expires !== '' ) : ?>
                    <p style="color:#50575e; font-size: 14px;"><strong><?php echo esc_html( $i18n['pro_lic_paid_through'] ); ?>:</strong> <?php echo esc_html( $lic_expires ); ?> <span style="color:#646970;">(UTC)</span></p>
                <?php endif; ?>
                <?php if ( $lic_checked > 0 ) : ?>
                    <p style="color:#646970; font-size: 13px;"><strong><?php echo esc_html( $i18n['pro_lic_last_check'] ); ?>:</strong> <?php echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $lic_checked ) ); ?></p>
                <?php endif; ?>
                <?php
                $reg_url = function_exists( 'newsai_pro_registered_site_url' ) ? newsai_pro_registered_site_url() : home_url( '/' );
                ?>
                <div style="margin:16px 0; padding:12px 14px; background:#f6f7f7; border:1px solid #dcdcde; border-radius:4px;">
                    <p style="margin:0 0 6px 0; font-size:14px;"><strong><?php echo esc_html( $i18n['pro_lic_registered_site'] ); ?>:</strong> <a href="<?php echo esc_url( $reg_url ); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html( $reg_url ); ?></a></p>
                    <p style="margin:0; font-size:12px; color:#646970;"><?php echo esc_html( $i18n['pro_lic_registered_hint'] ); ?></p>
                </div>
                <?php if ( $can_manage_all ) : ?>
                <p style="font-size:12px; color:#646970; max-width:520px; margin:12px 0 8px 0;"><?php echo esc_html( $i18n['pro_lic_verify_hint'] ); ?></p>
                <form method="post" style="margin-top:16px; display:inline-block; margin-right:8px;">
                    <?php wp_nonce_field( 'newsai_pro_license_save', 'newsai_pro_license_nonce' ); ?>
                    <input type="hidden" name="newsai_pro_license_action" value="refresh">
                    <button type="submit" class="button"><?php echo esc_html( $i18n['pro_lic_refresh'] ); ?></button>
                </form>
                <form method="post" style="margin-top:16px; display:inline-block;" onsubmit="return confirm('<?php echo esc_js( __( 'Deactivate Pro on this site?', 'newsroom-ai-assistant' ) ); ?>');">
                    <?php wp_nonce_field( 'newsai_pro_license_save', 'newsai_pro_license_nonce' ); ?>
                    <input type="hidden" name="newsai_pro_license_action" value="deactivate">
                    <button type="submit" class="button button-secondary"><?php echo esc_html( $i18n['pro_lic_deactivate'] ); ?></button>
                </form>
                <?php endif; ?>
            <?php elseif ( ! $pro_build && $saved_key !== '' && ! $exp_still_ok && $can_manage_all ) : ?>
                <div class="notice notice-warning" style="margin:0 0 16px 0;"><p><?php echo esc_html( $i18n['pro_lic_expired_local'] ); ?></p></div>
                <p style="color:#50575e; font-size: 14px;"><strong><?php echo esc_html( $i18n['pro_lic_key'] ); ?>:</strong> <code><?php echo esc_html( $mask_key ); ?></code></p>
                <?php if ( $lic_expires !== '' ) : ?>
                    <p style="color:#50575e;"><strong><?php echo esc_html( $i18n['pro_lic_paid_through'] ); ?>:</strong> <?php echo esc_html( $lic_expires ); ?></p>
                <?php endif; ?>
                <?php if ( $can_manage_all ) : ?>
                <form method="post" style="margin-top:16px; display:inline-block; margin-right:8px;">
                    <?php wp_nonce_field( 'newsai_pro_license_save', 'newsai_pro_license_nonce' ); ?>
                    <input type="hidden" name="newsai_pro_license_action" value="refresh">
                    <button type="submit" class="button button-primary"><?php echo esc_html( $i18n['pro_lic_refresh'] ); ?></button>
                </form>
                <form method="post" style="margin-top:16px; display:inline-block;" onsubmit="return confirm('<?php echo esc_js( __( 'Deactivate this license on this site?', 'newsroom-ai-assistant' ) ); ?>');">
                    <?php wp_nonce_field( 'newsai_pro_license_save', 'newsai_pro_license_nonce' ); ?>
                    <input type="hidden" name="newsai_pro_license_action" value="deactivate">
                    <button type="submit" class="button"><?php echo esc_html( $i18n['pro_lic_deactivate'] ); ?></button>
                </form>
                <?php endif; ?>
            <?php elseif ( ! $pro_build && $can_manage_all ) : ?>
                <p style="color:#50575e; font-size: 14px;"><?php echo esc_html( __( 'Paste the license key from your NewsOS.io email and the billing email you used at checkout.', 'newsroom-ai-assistant' ) ); ?></p>
                <p style="font-size: 13px; color:#646970;"><?php echo esc_html( $i18n['pro_lic_format_hint'] ); ?></p>
                <form method="post" style="max-width:480px; margin-top:16px;">
                    <?php wp_nonce_field( 'newsai_pro_license_save', 'newsai_pro_license_nonce' ); ?>
                    <input type="hidden" name="newsai_pro_license_action" value="activate">
                    <p><label for="newsai_pro_license_key"><strong><?php echo esc_html( $i18n['pro_lic_key'] ); ?></strong></label><br>
                    <input type="text" name="newsai_pro_license_key" id="newsai_pro_license_key" class="large-text" autocomplete="off" placeholder="NROS-XXXX-XXXX-XXXX" required></p>
                    <p><label for="newsai_pro_license_email"><strong><?php echo esc_html( $i18n['pro_lic_email'] ); ?></strong></label><br>
                    <span style="font-size:12px;color:#646970;"><?php echo esc_html( $i18n['pro_lic_email_required'] ); ?></span><br>
                    <input type="email" name="newsai_pro_license_email" id="newsai_pro_license_email" class="large-text" value="<?php echo esc_attr( (string) get_option( 'newsai_pro_license_email', '' ) ); ?>" required></p>
                    <p><button type="submit" class="button button-primary"><?php echo esc_html( $i18n['pro_lic_activate'] ); ?></button></p>
                </form>
            <?php elseif ( ! $pro_build && ! $can_manage_all ) : ?>
                <p style="color:#646970;"><?php echo esc_html( __( 'Only administrators can activate a license.', 'newsroom-ai-assistant' ) ); ?></p>
            <?php endif; ?>

            <?php if ( $lic_valid ) : ?>
            <div class="nros-pro-panel__features">
                <h4><?php echo esc_html( __( 'Included with Pro', 'newsroom-ai-assistant' ) ); ?></h4>
                <ul>
                    <li><?php echo esc_html( __( 'Chief Insights — live GSC desk metrics', 'newsroom-ai-assistant' ) ); ?></li>
                    <li><?php echo esc_html( __( 'Author Performance — coaching & exports', 'newsroom-ai-assistant' ) ); ?></li>
                    <li><?php echo esc_html( __( 'Writer leaderboard & publish trends', 'newsroom-ai-assistant' ) ); ?></li>
                    <li><?php echo esc_html( __( 'GSC sync, seasonal radar, war room', 'newsroom-ai-assistant' ) ); ?></li>
                </ul>
            </div>
            <?php endif; ?>
            </div>
            <div class="nros-pro-panel__foot">
            <p class="nros-pro-panel__api"><strong><?php echo esc_html( $i18n['pro_lic_api_note'] ); ?></strong><br><code><?php echo esc_html( function_exists( 'newsai_pro_license_api_url' ) ? newsai_pro_license_api_url() : 'https://newsos.io/wp-json/newsos/v1/license/validate' ); ?></code></p>
            <a href="https://newsos.io" class="button button-primary nros-pro-panel__buy" target="_blank" rel="noopener noreferrer"><?php echo esc_html( $i18n['pro_lic_buy'] ); ?></a>
            </div>
        </div>
            </div>
        <?php endif; ?>
        </main>
        </div><!-- .nros-classic-shell -->
    </div>
    <?php
}

function newsai_get_best_site_description() {
    $desc = get_bloginfo('description');
    if (class_exists('WPSEO_Options')) { $yoast = WPSEO_Options::get('og_frontpage_desc', ''); if ($yoast) $desc = $yoast; }
    return $desc;
}

function newsai_get_default_prompt($type, $lang) {
    $lang = is_string($lang) ? strtolower($lang) : 'en';
    if ($lang === 'el') {
        if ($type === 'title') return "Είσαι SEO expert. Γράψε 5 εναλλακτικούς click-worthy τίτλους (κάτω από 60 χαρακτήρες) για το εξής άρθρο:
Τίτλος: {title}
Περιεχόμενο: {content}

Στόχος: Google Discover.";
        if ($type === 'rewrite') return "Ως έμπειρος δημοσιογράφος για το site {site} ({site_desc}), διόρθωσε το παρακάτω κείμενο και πρόσθεσε H2 υπότιτλους. Στο τέλος πρόσθεσε 3 Ερωτήσεις/Απαντήσεις (FAQ):
{content}";
        if ($type === 'seo') return "Δώσε μου 5 SEO keywords, 1 Meta Description (max 150 chars) και 3 ιδανικά Tags για το άρθρο:
Τίτλος: {title}
Κείμενο: {content}";
    }
    if ($type === 'title') return "Act as an SEO expert. Write 5 click-worthy alternative titles (under 60 chars) for this article:
Title: {title}
Content: {content}

Goal: Google Discover.";
    if ($type === 'rewrite') return "As a senior journalist for {site} ({site_desc}), proofread this text, add H2 subheadings, and append 3 FAQs at the end:
{content}";
    if ($type === 'seo') return "Provide 5 SEO keywords, 1 Meta Description (max 150 chars), and 3 perfect Tags for this article:
Title: {title}
Content: {content}";
    return '';
}