<?php
/**
 * Blog Agent admin view.
 *
 * Three tabs: New Post (manual generate form), Drafts, Settings.
 * Included by admin-my-agent.php inside the Blog Agent panel.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/views
 * @since      1.21.0
 */

if ( ! defined( 'WPINC' ) ) {
    die;
}

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// Refresh post + topic budget from the middleware on page load (best-effort) so
// grants, resets, renewals, and exempt "Unlimited" status show immediately rather
// than only after a generation.
if ( class_exists( 'SiteStaffr_AI_Client' ) ) {
	( new SiteStaffr_AI_Client() )->refresh_blog_budget();
}
$blog_settings         = SiteStaffr_Blog_Manager::get_settings();
$blog_jobs             = SiteStaffr_Blog_Manager::get_all_jobs();
// Topic credits retired (reservoir, 1.32.0): topics are unlimited for every
// plan — the middleware rate-limits reservoir replans instead.
$post_budget           = max( 0, (int) $blog_settings['post_budget'] );
$post_remaining        = max( 0, $post_budget - (int) $blog_settings['post_budget_used'] );
$has_post_credits      = $post_remaining > 0;
$usage_state_class     = $has_post_credits ? '' : 'is-zero';
// Real billing-cycle reset date supplied by middleware (empty until the first
// blog response syncs it — then UI copy falls back to generic "this month").
$budget_reset_label    = '';
$budget_reset_raw      = isset( $blog_settings['budget_reset_date'] ) ? (string) $blog_settings['budget_reset_date'] : '';
$blog_display_tz       = new DateTimeZone( 'America/New_York' );
if ( '' !== $budget_reset_raw ) {
    $budget_reset_ts = strtotime( $budget_reset_raw );
    if ( false !== $budget_reset_ts ) {
        $budget_reset_label = wp_date( (string) get_option( 'date_format', 'F j, Y' ), $budget_reset_ts, $blog_display_tz );
    }
}
$next_due_label        = '';
$blog_tone_options     = array(
    'professional'  => __( 'Professional', 'sitestaffr' ),
    'friendly'      => __( 'Friendly', 'sitestaffr' ),
    'authoritative' => __( 'Authoritative', 'sitestaffr' ),
);
$blog_wc_options = array(
    800  => __( 'Short (~800 words)', 'sitestaffr' ),
    1200 => __( 'Medium (~1,200 words)', 'sitestaffr' ),
    1500 => __( 'Standard (~1,500 words)', 'sitestaffr' ),
    2000 => __( 'Long (~2,000 words)', 'sitestaffr' ),
    2500 => __( 'Comprehensive (~2,500 words)', 'sitestaffr' ),
);
$blog_language_options = array(
    'en' => __( 'English', 'sitestaffr' ),
    'es' => __( 'Spanish', 'sitestaffr' ),
    'fr' => __( 'French', 'sitestaffr' ),
    'pt' => __( 'Portuguese', 'sitestaffr' ),
);
$blog_language_default = substr( (string) $blog_settings['language'], 0, 2 );
if ( ! isset( $blog_language_options[ $blog_language_default ] ) ) {
    $blog_language_default = 'en';
}
if ( ! empty( $blog_settings['autopilot_enabled'] ) ) {
    // Prefer the live cron event over the stored value, and show it in Eastern
    // Time — the timezone the schedule is configured in.
    $next_due_timestamp = wp_next_scheduled( 'sitestaffr_blog_autopilot_tick' );
    if ( ! $next_due_timestamp && ! empty( $blog_settings['next_due_at'] ) ) {
        $next_due_timestamp = strtotime( (string) $blog_settings['next_due_at'] );
    }
    if ( $next_due_timestamp ) {
        // Literal "ET" instead of the PHP T token: rendering is always
        // America/New_York, and EDT/EST flip-flopping confuses owners.
        $next_due_label = wp_date( 'M j, Y g:i a', $next_due_timestamp, $blog_display_tz ) . ' ET';
    }
}

// AI Visibility Tracker — Task 16 (B6) dashboard card. get_state()/seed_prompts()
// always return arrays (see SiteStaffr_Visibility::get_state() defaults), so no
// class_exists() guard is needed — the class is required unconditionally by
// includes/class-sitestaffr.php.
$visibility_state   = SiteStaffr_Visibility::get_state();
// Empty state shows the seeded (not-yet-saved) prompt set as a preview so the
// owner can see/edit what the first run would ask before it exists.
$visibility_prompts = ! empty( $visibility_state['prompts'] ) ? $visibility_state['prompts'] : SiteStaffr_Visibility::seed_prompts();
$visibility_latest  = ( ! empty( $visibility_state['latest'] ) && is_array( $visibility_state['latest'] ) ) ? $visibility_state['latest'] : null;
$visibility_history = is_array( $visibility_state['history'] ) ? $visibility_state['history'] : array();

// Trend vs. the previous history point. record_run() appends the current run
// to history before storing it as `latest`, so "previous" is the
// second-to-last entry — same rule as SiteStaffr_Email_Notifications::calculate_visibility_trend_delta().
$visibility_prev_cited = null;
if ( count( $visibility_history ) >= 2 ) {
    $visibility_prev_point = $visibility_history[ count( $visibility_history ) - 2 ];
    if ( is_array( $visibility_prev_point ) && isset( $visibility_prev_point['score']['cited'] ) ) {
        $visibility_prev_cited = (int) $visibility_prev_point['score']['cited'];
    }
}

$visibility_platform_labels = array(
    'perplexity' => __( 'Perplexity', 'sitestaffr' ),
    'chatgpt'    => __( 'ChatGPT', 'sitestaffr' ),
    'gemini'     => __( 'Gemini', 'sitestaffr' ),
);

// rate_limit is attached to `run` by SiteStaffr_Visibility::request_run() and
// persisted onto `latest` by record_run(), so it survives a plain page load
// (no AJAX round-trip needed to know remaining on-demand checks).
$visibility_remaining_on_demand = null;
if ( $visibility_latest && isset( $visibility_latest['rate_limit']['remaining_on_demand'] ) ) {
    $visibility_remaining_on_demand = (int) $visibility_latest['rate_limit']['remaining_on_demand'];
}
?>

<div class="sitestaffr-blog-agent">

    <section class="sitestaffr-blog-usage sitestaffr-blog-usage-global <?php echo esc_attr( $usage_state_class ); ?>" aria-label="<?php esc_attr_e( 'Blog Agent monthly usage', 'sitestaffr' ); ?>">
        <div class="sitestaffr-blog-usage-primary">
            <span class="sitestaffr-blog-usage-label">
                <?php esc_html_e( 'Posts remaining', 'sitestaffr' ); ?>
                <?php
                $post_credit_tooltip = '' !== $budget_reset_label
                    ? sprintf(
                        /* translators: %s: localized reset date */
                        __( 'Post-generation credits for your plan. Every generated post (manual, from a topic, or Autopilot) uses 1 credit. Credits reset on your billing renewal, %s.', 'sitestaffr' ),
                        $budget_reset_label
                    )
                    : __( 'Post-generation credits for your plan. Every generated post (manual, from a topic, or Autopilot) uses 1 credit. Credits reset each billing cycle.', 'sitestaffr' );
                ?>
                <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php echo esc_attr( $post_credit_tooltip ); ?>">
                    <span class="dashicons dashicons-info" aria-hidden="true"></span>
                </span>
            </span>
            <strong class="sitestaffr-blog-usage-number"><?php echo esc_html( $post_remaining ); ?></strong>
            <span class="sitestaffr-blog-usage-total">
                <?php
                if ( '' !== $budget_reset_label ) {
                    printf(
                        /* translators: %1$d: total post credits, %2$s: localized reset date */
                        esc_html__( 'of %1$d &middot; resets %2$s', 'sitestaffr' ),
                        (int) $blog_settings['post_budget'],
                        esc_html( $budget_reset_label )
                    );
                } else {
                    printf(
                        /* translators: %d: total monthly post credits */
                        esc_html__( 'of %d this month', 'sitestaffr' ),
                        (int) $blog_settings['post_budget']
                    );
                }
                ?>
            </span>
        </div>
        <?php if ( $next_due_label ) : ?>
            <?php
            // Autopilot's next topic = the head of the approved queue (read-only
            // peek; pop happens at generation time).
            $next_topic_label = '';
            foreach ( SiteStaffr_Blog_Manager::get_topic_queue() as $queued_topic ) {
                $queued_status = isset( $queued_topic['status'] ) ? (string) $queued_topic['status'] : '';
                if ( in_array( $queued_status, array( 'approved', 'queued' ), true ) && ! empty( $queued_topic['topic'] ) ) {
                    $next_topic_label = (string) $queued_topic['topic'];
                    break;
                }
            }
            ?>
            <div class="sitestaffr-blog-usage-secondary">
                <span>
                    <strong><?php esc_html_e( 'Next Autopilot run:', 'sitestaffr' ); ?></strong>
                    <?php echo esc_html( $next_due_label ); ?>
                    <?php if ( '' !== $next_topic_label ) : ?>
                        <span class="sitestaffr-blog-next-topic">&rarr; &ldquo;<?php echo esc_html( $next_topic_label ); ?>&rdquo;</span>
                    <?php endif; ?>
                </span>
            </div>
        <?php endif; ?>
        <?php if ( ! $has_post_credits ) : ?>
            <p class="sitestaffr-blog-usage-warning"><?php esc_html_e( 'You have used all monthly Blog Agent post credits. New manual posts are paused until credits reset.', 'sitestaffr' ); ?></p>
        <?php endif; ?>
    </section>

    <?php
    // Autopilot era: land on what the agent is doing — Pipeline is the default tab.
    $draft_count = count( array_filter( $blog_jobs, function( $j ) {
        return in_array( $j->status, array( 'complete', 'generating' ), true );
    } ) );
    ?>
    <div class="sitestaffr-agent-tabs" role="tablist" data-tab-storage="sitestaffr_blog_tab" aria-label="<?php esc_attr_e( 'Blog Agent tabs', 'sitestaffr' ); ?>">
        <button type="button" role="tab" class="sitestaffr-agent-tab is-active" aria-selected="true" aria-controls="blog-tab-drafts" id="blog-tab-btn-drafts">
            <?php esc_html_e( 'Pipeline', 'sitestaffr' ); ?>
            <?php if ( $draft_count > 0 ) : ?>
                <span class="sitestaffr-blog-tab-count"><?php echo (int) $draft_count; ?></span>
            <?php endif; ?>
        </button>
        <button type="button" role="tab" class="sitestaffr-agent-tab" aria-selected="false" aria-controls="blog-tab-new-post" id="blog-tab-btn-new-post" tabindex="-1"><?php esc_html_e( 'New Post', 'sitestaffr' ); ?></button>
        <button type="button" role="tab" class="sitestaffr-agent-tab" aria-selected="false" aria-controls="blog-tab-visibility" id="blog-tab-btn-visibility" tabindex="-1"><?php esc_html_e( 'AI Visibility', 'sitestaffr' ); ?></button>
        <button type="button" role="tab" class="sitestaffr-agent-tab" aria-selected="false" aria-controls="blog-tab-settings" id="blog-tab-btn-settings" tabindex="-1"><?php esc_html_e( 'Settings', 'sitestaffr' ); ?></button>
    </div>

    <!-- New Post Tab -->
    <div id="blog-tab-new-post" role="tabpanel" class="sitestaffr-agent-tabpanel sitestaffr-settings" aria-labelledby="blog-tab-btn-new-post" hidden>
        <section class="sitestaffr-settings-card">
            <header class="sitestaffr-settings-card-header">
                <h2>
                    <span class="dashicons dashicons-welcome-write-blog" aria-hidden="true"></span>
                    <?php esc_html_e( 'Generate Blog Post', 'sitestaffr' ); ?>
                    <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Enter a topic and optional keyword. The AI will research competitors, create an SEO-optimized post, and save manual posts as WordPress drafts for your review.', 'sitestaffr' ); ?>">
                        <span class="dashicons dashicons-info" aria-hidden="true"></span>
                    </span>
                </h2>
            </header>
            <div class="sitestaffr-settings-card-body">
                <div id="sitestaffr-blog-form-content">
                    <div class="sitestaffr-blog-form">
                        <div class="sitestaffr-blog-form-field">
                            <label for="sitestaffr-blog-topic">
                                <?php esc_html_e( 'Topic', 'sitestaffr' ); ?>
                                <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'No ideas? Click Suggest topic and the AI proposes a topic and keyword for you. Click again for a different suggestion.', 'sitestaffr' ); ?>">
                                    <span class="dashicons dashicons-info" aria-hidden="true"></span>
                                </span>
                            </label>
                            <div class="sitestaffr-blog-topic-row">
                                <input type="text" id="sitestaffr-blog-topic" class="regular-text" placeholder="<?php esc_attr_e( 'e.g., How Much Do Dental Implants Cost in 2026?', 'sitestaffr' ); ?>" />
                                <button type="button" class="button" id="sitestaffr-blog-suggest-topic">
                                    <span class="dashicons dashicons-lightbulb" aria-hidden="true"></span>
                                    <?php esc_html_e( 'Suggest topic', 'sitestaffr' ); ?>
                                </button>
                            </div>
                            <p class="description" id="sitestaffr-blog-suggest-status" aria-live="polite"></p>
                        </div>

                        <div class="sitestaffr-blog-form-field">
                            <label for="sitestaffr-blog-keyword">
                                <?php esc_html_e( 'Target Keyword', 'sitestaffr' ); ?>
                                <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Optional, but recommended for stronger SEO focus.', 'sitestaffr' ); ?>">
                                    <span class="dashicons dashicons-info" aria-hidden="true"></span>
                                </span>
                            </label>
                            <input type="text" id="sitestaffr-blog-keyword" class="regular-text" placeholder="<?php esc_attr_e( 'e.g., dental implant cost', 'sitestaffr' ); ?>" />
                        </div>

                        <div class="sitestaffr-blog-options-panel">
                            <h3>
                                <?php esc_html_e( 'Post Options', 'sitestaffr' ); ?>
                                <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'These settings apply to this post only and start with your saved defaults.', 'sitestaffr' ); ?>">
                                    <span class="dashicons dashicons-info" aria-hidden="true"></span>
                                </span>
                            </h3>

                            <div class="sitestaffr-blog-form-grid">
                                <div class="sitestaffr-blog-form-field">
                                    <label for="sitestaffr-blog-run-tone"><?php esc_html_e( 'Tone', 'sitestaffr' ); ?></label>
                                    <select id="sitestaffr-blog-run-tone">
                                        <?php foreach ( $blog_tone_options as $tone_value => $tone_label ) : ?>
                                            <option value="<?php echo esc_attr( $tone_value ); ?>" <?php selected( $blog_settings['tone'], $tone_value ); ?>><?php echo esc_html( $tone_label ); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="sitestaffr-blog-form-field">
                                    <label for="sitestaffr-blog-run-wc-target"><?php esc_html_e( 'Target Word Count', 'sitestaffr' ); ?></label>
                                    <select id="sitestaffr-blog-run-wc-target">
                                        <?php foreach ( $blog_wc_options as $wc_value => $wc_label ) : ?>
                                            <option value="<?php echo esc_attr( $wc_value ); ?>" <?php selected( (int) $blog_settings['word_count_target'], (int) $wc_value ); ?>><?php echo esc_html( $wc_label ); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="sitestaffr-blog-form-field">
                                    <label for="sitestaffr-blog-run-language"><?php esc_html_e( 'Language', 'sitestaffr' ); ?></label>
                                    <select id="sitestaffr-blog-run-language">
                                        <?php foreach ( $blog_language_options as $language_value => $language_label ) : ?>
                                            <option value="<?php echo esc_attr( $language_value ); ?>" <?php selected( $blog_language_default, $language_value ); ?>><?php echo esc_html( $language_label ); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="sitestaffr-blog-form-field sitestaffr-toggle-row sitestaffr-blog-run-image-row">
                                    <label class="sitestaffr-toggle-switch">
                                        <input type="checkbox" id="sitestaffr-blog-run-image-gen" value="1" <?php checked( $blog_settings['image_generation'] ); ?> />
                                        <span class="sitestaffr-toggle-slider"></span>
                                    </label>
                                    <div class="sitestaffr-toggle-label">
                                        <span><?php esc_html_e( 'Generate featured image', 'sitestaffr' ); ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <?php if ( ! $has_post_credits ) : ?>
                            <p class="sitestaffr-blog-zero-copy">
                                <?php
                                if ( '' !== $budget_reset_label ) {
                                    printf(
                                        /* translators: %s: localized reset date */
                                        esc_html__( 'No post credits remain, so manual generation is disabled. More credits arrive on %s.', 'sitestaffr' ),
                                        esc_html( $budget_reset_label )
                                    );
                                } else {
                                    esc_html_e( 'No post credits remain this month, so manual generation is disabled.', 'sitestaffr' );
                                }
                                ?>
                            </p>
                        <?php endif; ?>

                        <div class="sitestaffr-blog-form-actions">
                            <button type="button" id="sitestaffr-blog-generate" class="button button-primary button-hero" <?php disabled( ! $has_post_credits ); ?>>
                                <span class="dashicons dashicons-edit-large" aria-hidden="true"></span>
                                <?php esc_html_e( 'Generate Post', 'sitestaffr' ); ?>
                            </button>
                            <span id="sitestaffr-blog-generate-status" class="sitestaffr-inline-status"></span>
                        </div>
                    </div>
                </div>

                <div id="sitestaffr-blog-progress" class="sitestaffr-blog-progress" style="display: none;">
                    <div class="sitestaffr-blog-progress-circle-wrap">
                        <svg class="sitestaffr-blog-progress-circle" viewBox="0 0 136 136">
                            <circle class="sitestaffr-blog-progress-track" cx="68" cy="68" r="60" fill="none" stroke-width="8" />
                            <circle class="sitestaffr-blog-progress-arc" cx="68" cy="68" r="60" fill="none" stroke-width="8" stroke-linecap="round" />
                        </svg>
                        <span class="sitestaffr-blog-progress-icon dashicons dashicons-welcome-learn-more" aria-hidden="true"></span>
                    </div>
                    <p class="sitestaffr-blog-progress-step"></p>
                    <p class="sitestaffr-blog-progress-notice" style="display: none;" role="status"></p>
                </div>
            </div>
        </section>
    </div>

    <!-- Pipeline Tab (default) -->
    <div id="blog-tab-drafts" role="tabpanel" class="sitestaffr-agent-tabpanel sitestaffr-settings" aria-labelledby="blog-tab-btn-drafts">
        <section class="sitestaffr-settings-card">
            <header class="sitestaffr-settings-card-header">
                <h2>
                    <span class="dashicons dashicons-media-text" aria-hidden="true"></span>
                    <?php esc_html_e( 'Content Pipeline', 'sitestaffr' ); ?>
                    <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Upcoming Topics are AI-suggested ideas waiting to be written — generate one now or skip it for a replacement. Generated Posts shows every post the Blog Agent has created and its status.', 'sitestaffr' ); ?>">
                        <span class="dashicons dashicons-info" aria-hidden="true"></span>
                    </span>
                </h2>
            </header>
            <div class="sitestaffr-settings-card-body">
                <div id="sitestaffr-blog-drafts-list">
                    <?php if ( empty( $blog_jobs ) ) : ?>
                        <div class="sitestaffr-blog-empty sitestaffr-blog-pipeline-empty">
                            <p><?php esc_html_e( 'No posts generated yet. Your first post is one topic away.', 'sitestaffr' ); ?></p>
                            <button type="button" class="button button-primary sitestaffr-blog-goto-new-post">
                                <?php esc_html_e( 'Write your first post', 'sitestaffr' ); ?>
                            </button>
                        </div>
                    <?php else : ?>
                        <table class="widefat sitestaffr-blog-drafts-table">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e( 'Status', 'sitestaffr' ); ?></th>
                                    <th><?php esc_html_e( 'Topic', 'sitestaffr' ); ?></th>
                                    <th><?php esc_html_e( 'Keyword', 'sitestaffr' ); ?></th>
                                    <th><?php esc_html_e( 'Created', 'sitestaffr' ); ?></th>
                                    <th><?php esc_html_e( 'Actions', 'sitestaffr' ); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                // Warm the post cache once — otherwise every row pays
                                // separate get_post lookups for title/status/permalink.
                                $pipeline_post_ids = array_filter( array_map( function ( $j ) {
                                    return (int) $j->wp_post_id;
                                }, $blog_jobs ) );
                                if ( ! empty( $pipeline_post_ids ) ) {
                                    _prime_post_caches( $pipeline_post_ids, false, false );
                                }
                                ?>
                                <?php foreach ( $blog_jobs as $job ) : ?>
                                    <?php
                                    // Prefer the CURRENT WP post title (reflects any edit); fall back to
                                    // the original generation topic when there is no post yet.
                                    $row_post_title = ! empty( $job->wp_post_id ) ? get_the_title( $job->wp_post_id ) : '';
                                    $row_title      = '' !== $row_post_title ? $row_post_title : $job->topic;

                                    // Real lifecycle: merge job status with the WP post status so a
                                    // published post reads Published, not "Ready".
                                    $row_post_status = ! empty( $job->wp_post_id ) ? get_post_status( $job->wp_post_id ) : false;
                                    $row_is_published = ( 'publish' === $row_post_status );

                                    // Failure reason: stored middleware payload when present, else the
                                    // stuck-job sweep explanation (shared with the AJAX renderer).
                                    $row_fail_reason = ( 'failed' === $job->status ) ? $this->extract_blog_fail_reason( $job ) : '';
                                    ?>
                                    <tr data-job-id="<?php echo (int) $job->id; ?>">
                                        <td data-colname="<?php esc_attr_e( 'Status', 'sitestaffr' ); ?>">
                                            <?php if ( 'generating' === $job->status ) : ?>
                                                <span class="sitestaffr-blog-status is-generating"><span class="spinner is-active" style="float:none;margin:0 4px 0 0;"></span><?php esc_html_e( 'Generating', 'sitestaffr' ); ?></span>
                                            <?php elseif ( 'complete' === $job->status && $row_is_published ) : ?>
                                                <span class="sitestaffr-blog-status is-published"><?php esc_html_e( 'Published', 'sitestaffr' ); ?></span>
                                            <?php elseif ( 'complete' === $job->status && 'draft' === $row_post_status ) : ?>
                                                <span class="sitestaffr-blog-status is-complete"><?php esc_html_e( 'Ready for review', 'sitestaffr' ); ?></span>
                                            <?php elseif ( 'complete' === $job->status ) : ?>
                                                <span class="sitestaffr-blog-status is-complete"><?php esc_html_e( 'Ready', 'sitestaffr' ); ?></span>
                                            <?php elseif ( 'failed' === $job->status ) : ?>
                                                <span class="sitestaffr-blog-status is-failed" title="<?php echo esc_attr( $row_fail_reason ); ?>"><?php esc_html_e( 'Failed', 'sitestaffr' ); ?><span class="dashicons dashicons-info-outline" aria-hidden="true"></span></span>
                                            <?php else : ?>
                                                <span class="sitestaffr-blog-status"><?php echo esc_html( ucfirst( $job->status ) ); ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td data-colname="<?php esc_attr_e( 'Topic', 'sitestaffr' ); ?>"><?php echo esc_html( $row_title ); ?></td>
                                        <td data-colname="<?php esc_attr_e( 'Keyword', 'sitestaffr' ); ?>"><?php echo esc_html( $job->keyword ); ?></td>
                                        <td data-colname="<?php esc_attr_e( 'Created', 'sitestaffr' ); ?>"><?php echo esc_html( SiteStaffr_Blog_Manager::format_job_created_at( $job->created_at ) ); ?></td>
                                        <td class="sitestaffr-blog-draft-actions">
                                            <?php if ( $row_is_published ) : ?>
                                                <a href="<?php echo esc_url( get_permalink( $job->wp_post_id ) ); ?>" target="_blank" rel="noopener" class="button button-small"><?php esc_html_e( 'View live', 'sitestaffr' ); ?></a>
                                            <?php endif; ?>
                                            <?php if ( ! empty( $job->wp_post_id ) ) : ?>
                                                <a href="<?php echo esc_url( get_edit_post_link( $job->wp_post_id ) ); ?>" class="button button-small"><?php echo $row_is_published ? esc_html__( 'Edit', 'sitestaffr' ) : esc_html__( 'Edit Draft', 'sitestaffr' ); ?></a>
                                                <?php if ( 'draft' === $row_post_status ) : ?>
                                                    <button type="button" class="button button-small sitestaffr-blog-email-review" data-sitestaffr-email="review_link" data-id="<?php echo (int) $job->wp_post_id; ?>" title="<?php esc_attr_e( 'Email Review Link', 'sitestaffr' ); ?>" aria-label="<?php esc_attr_e( 'Email Review Link', 'sitestaffr' ); ?>"><span class="dashicons dashicons-email-alt" aria-hidden="true"></span></button>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                            <?php if ( 'failed' === $job->status && $has_post_credits ) : ?>
                                                <button type="button" class="button button-small sitestaffr-blog-retry" data-topic="<?php echo esc_attr( $job->topic ); ?>" data-keyword="<?php echo esc_attr( $job->keyword ); ?>"><?php esc_html_e( 'Retry', 'sitestaffr' ); ?></button>
                                            <?php endif; ?>
                                            <button type="button" class="button button-small button-link-delete sitestaffr-blog-delete" data-id="<?php echo (int) $job->id; ?>"><?php esc_html_e( 'Delete', 'sitestaffr' ); ?></button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </section>
    </div>

    <!-- Settings Tab -->
    <div id="blog-tab-settings" role="tabpanel" class="sitestaffr-agent-tabpanel sitestaffr-settings" aria-labelledby="blog-tab-btn-settings" hidden>
        <section class="sitestaffr-settings-card">
            <header class="sitestaffr-settings-card-header">
                <h2>
                    <span class="dashicons dashicons-admin-generic" aria-hidden="true"></span>
                    <?php esc_html_e( 'Blog Agent Settings', 'sitestaffr' ); ?>
                </h2>
            </header>
            <div class="sitestaffr-settings-card-body">
                <div class="sitestaffr-blog-settings-form">
                    <div class="sitestaffr-blog-settings-section">
                        <h3>
                            <?php esc_html_e( 'Post Defaults', 'sitestaffr' ); ?>
                            <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Used as defaults for manual posts and Autopilot unless you override them for a single manual run.', 'sitestaffr' ); ?>">
                                <span class="dashicons dashicons-info" aria-hidden="true"></span>
                            </span>
                        </h3>

                        <div class="sitestaffr-blog-form-field">
                            <label for="sitestaffr-blog-tone"><?php esc_html_e( 'Content Tone', 'sitestaffr' ); ?></label>
                            <select id="sitestaffr-blog-tone">
                                <?php foreach ( $blog_tone_options as $tone_value => $tone_label ) : ?>
                                    <option value="<?php echo esc_attr( $tone_value ); ?>" <?php selected( $blog_settings['tone'], $tone_value ); ?>><?php echo esc_html( $tone_label ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="sitestaffr-blog-form-field">
                            <label for="sitestaffr-blog-wc-target"><?php esc_html_e( 'Target Word Count', 'sitestaffr' ); ?></label>
                            <select id="sitestaffr-blog-wc-target">
                                <?php foreach ( $blog_wc_options as $wc_value => $wc_label ) : ?>
                                    <option value="<?php echo esc_attr( $wc_value ); ?>" <?php selected( (int) $blog_settings['word_count_target'], (int) $wc_value ); ?>><?php echo esc_html( $wc_label ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="sitestaffr-blog-form-field">
                            <label for="sitestaffr-blog-language"><?php esc_html_e( 'Language', 'sitestaffr' ); ?></label>
                            <select id="sitestaffr-blog-language">
                                <?php foreach ( $blog_language_options as $language_value => $language_label ) : ?>
                                    <option value="<?php echo esc_attr( $language_value ); ?>" <?php selected( $blog_language_default, $language_value ); ?>><?php echo esc_html( $language_label ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="sitestaffr-blog-settings-section">
                        <h3><?php esc_html_e( 'Content Preferences', 'sitestaffr' ); ?></h3>
                        <div class="sitestaffr-blog-form-field sitestaffr-toggle-row">
                            <label class="sitestaffr-toggle-switch">
                                <input type="checkbox" id="sitestaffr-blog-image-gen" value="1" <?php checked( $blog_settings['image_generation'] ); ?> />
                                <span class="sitestaffr-toggle-slider"></span>
                            </label>
                            <div class="sitestaffr-toggle-label">
                                <span>
                                    <?php esc_html_e( 'Generate featured images by default', 'sitestaffr' ); ?>
                                    <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Manual posts can override this per run. Autopilot uses this saved default.', 'sitestaffr' ); ?>">
                                        <span class="dashicons dashicons-info" aria-hidden="true"></span>
                                    </span>
                                </span>
                            </div>
                        </div>
                    </div>

                    <?php if ( SiteStaffr_Blog_Manager::is_autopilot_allowed() ) : ?>
                    <div class="sitestaffr-blog-settings-section">
                        <h3>
                            <?php esc_html_e( 'Autopilot', 'sitestaffr' ); ?>
                            <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Let SiteStaffr generate posts on your selected days.', 'sitestaffr' ); ?>">
                                <span class="dashicons dashicons-info" aria-hidden="true"></span>
                            </span>
                        </h3>

                        <div class="sitestaffr-blog-form-field sitestaffr-toggle-row">
                            <label class="sitestaffr-toggle-switch">
                                <input type="checkbox" id="sitestaffr-blog-autopilot" value="1" <?php checked( $blog_settings['autopilot_enabled'] ); ?> />
                                <span class="sitestaffr-toggle-slider"></span>
                            </label>
                            <div class="sitestaffr-toggle-label">
                                <span>
                                    <?php esc_html_e( 'Enable Autopilot', 'sitestaffr' ); ?>
                                    <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Automatically generate blog posts on a schedule, within your plan\'s monthly post allowance.', 'sitestaffr' ); ?>">
                                        <span class="dashicons dashicons-info" aria-hidden="true"></span>
                                    </span>
                                </span>
                            </div>
                        </div>

                        <div id="sitestaffr-blog-autopilot-options" <?php echo $blog_settings['autopilot_enabled'] ? '' : 'style="display:none;"'; ?>>
                            <div class="sitestaffr-blog-form-field">
                                <label><?php esc_html_e( 'Publish Days', 'sitestaffr' ); ?></label>
                                <div class="sitestaffr-blog-day-checkboxes">
                                    <?php
                                    $days          = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );
                                    $selected_days = isset( $blog_settings['schedule_days'] ) ? $blog_settings['schedule_days'] : array( 'tuesday', 'thursday' );
                                    foreach ( $days as $day ) :
                                    ?>
                                        <label>
                                            <input type="checkbox" name="schedule_days[]" value="<?php echo esc_attr( $day ); ?>" <?php checked( in_array( $day, $selected_days, true ) ); ?> />
                                            <?php echo esc_html( ucfirst( $day ) ); ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="sitestaffr-blog-form-field">
                                <label for="sitestaffr-blog-schedule-time"><?php esc_html_e( 'Publish Time (Eastern Time)', 'sitestaffr' ); ?></label>
                                <input type="time" id="sitestaffr-blog-schedule-time" value="<?php echo esc_attr( $blog_settings['schedule_time'] ); ?>" />
                            </div>

                            <?php /* Topic approval toggle removed 1.23.14 — Skip on the Upcoming Topics list is the rejection mechanism. */ ?>

                            <?php $autopilot_delivery = ! empty( $blog_settings['review_by_email'] ) ? 'review' : 'publish'; ?>
                            <div class="sitestaffr-blog-form-field sitestaffr-blog-radio-group">
                                <label class="sitestaffr-blog-radio-group-label">
                                    <?php esc_html_e( 'When Autopilot generates a post', 'sitestaffr' ); ?>
                                    <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Choose one: publish automatically (you get an email with a preview), or have us email you a no-login link to review, edit, and publish it yourself.', 'sitestaffr' ); ?>">
                                        <span class="dashicons dashicons-info" aria-hidden="true"></span>
                                    </span>
                                </label>
                                <label class="sitestaffr-blog-radio-row">
                                    <input type="radio" name="autopilot_delivery" value="publish" <?php checked( $autopilot_delivery, 'publish' ); ?> />
                                    <span><?php esc_html_e( 'Publish it automatically and email me a preview', 'sitestaffr' ); ?></span>
                                </label>
                                <label class="sitestaffr-blog-radio-row">
                                    <input type="radio" name="autopilot_delivery" value="review" <?php checked( $autopilot_delivery, 'review' ); ?> />
                                    <span><?php esc_html_e( 'Email me to review and publish it myself (saved as a draft, no login needed)', 'sitestaffr' ); ?></span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="sitestaffr-blog-form-actions">
                        <button type="button" id="sitestaffr-blog-save-settings" class="button button-primary">
                            <span class="dashicons dashicons-saved" aria-hidden="true"></span>
                            <?php esc_html_e( 'Save Settings', 'sitestaffr' ); ?>
                        </button>
                        <span id="sitestaffr-blog-settings-status" class="sitestaffr-inline-status"></span>
                    </div>

                </div>
            </div>
        </section>

        <!-- Blog email recipients — its own list + enable, separate from conversation
             notifications. Mirrors the Voice & Text agent's notification card. -->
        <section class="sitestaffr-settings-card sitestaffr-settings-card-email sitestaffr-email-notifications">
            <header class="sitestaffr-settings-card-header">
                <h2>
                    <span class="dashicons dashicons-email-alt" aria-hidden="true"></span>
                    <?php esc_html_e( 'Blog Post Notifications', 'sitestaffr' ); ?>
                </h2>
            </header>
            <div class="sitestaffr-settings-card-body">
                <?php
                $sitestaffr_blog_notif = get_option( 'sitestaffr_blog_notifications', array() );
                $blog_notif_enabled    = ! isset( $sitestaffr_blog_notif['enabled'] ) || $sitestaffr_blog_notif['enabled'];
                $blog_notif_email      = ! empty( $sitestaffr_blog_notif['email'] ) ? $sitestaffr_blog_notif['email'] : '';
                $blog_notif_cc         = ! empty( $sitestaffr_blog_notif['cc'] ) ? $sitestaffr_blog_notif['cc'] : '';
                ?>
                <div class="sitestaffr-email-layout">
                    <div class="sitestaffr-email-primary">
                        <div class="sitestaffr-email-row">
                            <div class="sitestaffr-email-row-label">
                                <label for="sitestaffr-blog-notif-enabled"><?php esc_html_e( 'Enable Notifications', 'sitestaffr' ); ?></label>
                            </div>
                            <div class="sitestaffr-email-row-control">
                                <label class="sitestaffr-email-checkbox-label">
                                    <input type="checkbox" id="sitestaffr-blog-notif-enabled" value="1" <?php checked( $blog_notif_enabled ); ?> />
                                    <?php esc_html_e( 'Send email notifications for blog posts', 'sitestaffr' ); ?>
                                </label>
                            </div>
                        </div>

                        <div class="sitestaffr-email-row">
                            <div class="sitestaffr-email-row-label">
                                <label for="sitestaffr-blog-notif-email"><?php esc_html_e( 'Notification Email', 'sitestaffr' ); ?></label>
                            </div>
                            <div class="sitestaffr-email-row-control">
                                <input type="email" id="sitestaffr-blog-notif-email" value="<?php echo esc_attr( $blog_notif_email ); ?>" class="regular-text" placeholder="blog@email.com" />
                            </div>
                        </div>

                        <div class="sitestaffr-email-row">
                            <div class="sitestaffr-email-row-label">
                                <label for="sitestaffr-blog-notif-cc"><?php esc_html_e( 'Additional Emails (CC)', 'sitestaffr' ); ?></label>
                                <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Separate multiple emails with commas. Up to 5 additional addresses can be CC\'d.', 'sitestaffr' ); ?>">
                                    <span class="dashicons dashicons-info" aria-hidden="true"></span>
                                </span>
                            </div>
                            <div class="sitestaffr-email-row-control">
                                <input type="text" id="sitestaffr-blog-notif-cc" value="<?php echo esc_attr( $blog_notif_cc ); ?>" class="regular-text sitestaffr-notification-cc-input" placeholder="manager@example.com, team@example.com" />
                            </div>
                        </div>

                        <div class="sitestaffr-email-row sitestaffr-email-row-actions">
                            <button type="button" id="sitestaffr-blog-notif-save" class="button button-primary">
                                <span class="dashicons dashicons-saved"></span>
                                <span class="sitestaffr-save-notif-text"><?php esc_html_e( 'Save Notification Settings', 'sitestaffr' ); ?></span>
                            </button>
                            <span id="sitestaffr-blog-notif-save-status" class="sitestaffr-inline-status" style="margin-left: 10px;"></span>
                        </div>
                    </div>

                    <aside class="sitestaffr-email-test-panel">
                        <h3><?php esc_html_e( 'Test Email Notifications', 'sitestaffr' ); ?></h3>
                        <p><?php esc_html_e( 'Send a test email to verify your notification settings are working correctly.', 'sitestaffr' ); ?></p>
                        <button type="button" id="sitestaffr-blog-notif-test" class="button button-secondary">
                            <span class="dashicons dashicons-email"></span>
                            <?php esc_html_e( 'Send Test Email', 'sitestaffr' ); ?>
                        </button>
                        <span id="sitestaffr-blog-notif-test-status" class="sitestaffr-inline-status"></span>
                    </aside>
                </div>
            </div>
        </section>
    </div>

    <!-- AI Visibility Tab -->
    <div id="blog-tab-visibility" role="tabpanel" class="sitestaffr-agent-tabpanel sitestaffr-settings" aria-labelledby="blog-tab-btn-visibility" hidden>
        <section class="sitestaffr-settings-card sitestaffr-visibility-card" id="sitestaffr-visibility-card">
            <header class="sitestaffr-settings-card-header">
                <h2>
                    <span class="dashicons dashicons-visibility" aria-hidden="true"></span>
                    <?php esc_html_e( 'AI Visibility', 'sitestaffr' ); ?>
                    <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'Tracks whether AI assistants like Perplexity, ChatGPT, and Gemini cite or mention your business when people ask about it. Runs automatically once a month, plus on-demand checks.', 'sitestaffr' ); ?>">
                        <span class="dashicons dashicons-info" aria-hidden="true"></span>
                    </span>
                </h2>
            </header>
            <div class="sitestaffr-settings-card-body">

                <?php
                // Score baseline for the JS trend calc lives on the results wrapper
                // (data-score-cited), available whether or not a run exists yet.
                $v_score_cited = $visibility_latest && isset( $visibility_latest['score']['cited'] ) ? (int) $visibility_latest['score']['cited'] : 0;
                $v_score_total = $visibility_latest && isset( $visibility_latest['score']['total'] ) ? (int) $visibility_latest['score']['total'] : 0;

                // On-demand "Refresh" is disabled only when the monthly allowance is
                // known to be exhausted; the remaining count rides a button tooltip
                // rather than a persistent line of copy.
                $v_run_disabled = ( 0 === $visibility_remaining_on_demand );
                $v_run_title    = ( null !== $visibility_remaining_on_demand )
                    ? sprintf(
                        /* translators: %d: number of on-demand visibility checks left this month. */
                        _n( '%d on-demand check left this month', '%d on-demand checks left this month', max( 0, (int) $visibility_remaining_on_demand ), 'sitestaffr' ),
                        max( 0, (int) $visibility_remaining_on_demand )
                    )
                    : '';
                ?>
                <div id="sitestaffr-visibility-results" class="sitestaffr-visibility-results" <?php echo $visibility_latest ? 'data-score-cited="' . esc_attr( $v_score_cited ) . '"' : ''; ?> <?php echo $visibility_latest ? '' : 'hidden'; ?>>
                    <?php if ( $visibility_latest ) :
                        // Trend vs. the previous run (rendered only when a prior run exists).
                        $v_trend_class = '';
                        $v_trend_text  = '';
                        if ( null !== $visibility_prev_cited ) {
                            $v_delta = $v_score_cited - (int) $visibility_prev_cited;
                            if ( $v_delta > 0 ) {
                                $v_trend_class = 'is-up';
                                $v_trend_text  = sprintf( "\u{25B2} %s %d", __( 'Up', 'sitestaffr' ), $v_delta );
                            } elseif ( $v_delta < 0 ) {
                                $v_trend_class = 'is-down';
                                $v_trend_text  = sprintf( "\u{25BC} %s %d", __( 'Down', 'sitestaffr' ), abs( $v_delta ) );
                            } else {
                                $v_trend_class = 'is-flat';
                                $v_trend_text  = "\u{2014} " . __( 'No change', 'sitestaffr' );
                            }
                        }
                        $v_run_date_label = '';
                        if ( ! empty( $visibility_latest['date'] ) ) {
                            $v_run_ts = strtotime( (string) $visibility_latest['date'] );
                            if ( false !== $v_run_ts ) {
                                $v_run_date_label = wp_date( (string) get_option( 'date_format', 'F j, Y' ), $v_run_ts );
                            }
                        }
                        $v_result_prompts = ( isset( $visibility_latest['prompts'] ) && is_array( $visibility_latest['prompts'] ) ) ? $visibility_latest['prompts'] : array();
                        $v_cited_count    = 0;
                        foreach ( $v_result_prompts as $v_p ) {
                            if ( is_array( $v_p ) && ! empty( $v_p['cited'] ) ) {
                                $v_cited_count++;
                            }
                        }
                        $v_missed_count = max( 0, count( $v_result_prompts ) - $v_cited_count );
                        $v_agg          = ( isset( $visibility_latest['competitorsAggregate'] ) && is_array( $visibility_latest['competitorsAggregate'] ) ) ? $visibility_latest['competitorsAggregate'] : array();
                        $v_has_rail     = ! empty( $v_agg );
                        $v_byplatform   = ( isset( $visibility_latest['byPlatform'] ) && is_array( $visibility_latest['byPlatform'] ) ) ? $visibility_latest['byPlatform'] : array();
                        ?>
                        <!-- Summary band: score + per-engine breakdown + actions -->
                        <div class="sitestaffr-visibility-summary">
                            <div class="sitestaffr-visibility-score">
                                <div class="sitestaffr-visibility-score-top">
                                    <span class="sitestaffr-visibility-num"><b><?php echo esc_html( $v_score_cited ); ?></b><span class="den">/ <?php echo esc_html( $v_score_total ); ?></span></span>
                                    <?php if ( '' !== $v_trend_class ) : ?>
                                        <span class="sitestaffr-visibility-trend <?php echo esc_attr( $v_trend_class ); ?>"><?php echo esc_html( $v_trend_text ); ?></span>
                                    <?php endif; ?>
                                </div>
                                <span class="sitestaffr-visibility-score-lab"><?php esc_html_e( 'AI answers cite you', 'sitestaffr' ); ?></span>
                            </div>
                            <div class="sitestaffr-visibility-vr" aria-hidden="true"></div>
                            <div class="sitestaffr-visibility-engines">
                                <?php foreach ( $visibility_platform_labels as $v_platform_key => $v_platform_label ) :
                                    $v_platform_data      = ( isset( $v_byplatform[ $v_platform_key ] ) && is_array( $v_byplatform[ $v_platform_key ] ) ) ? $v_byplatform[ $v_platform_key ] : array();
                                    $v_platform_cited     = isset( $v_platform_data['cited'] ) ? (int) $v_platform_data['cited'] : 0;
                                    $v_platform_total     = isset( $v_platform_data['total'] ) ? (int) $v_platform_data['total'] : 0;
                                    $v_platform_available = ! empty( $v_platform_data['available'] );
                                    ?>
                                    <div class="sitestaffr-visibility-eng">
                                        <span class="k"><?php echo esc_html( $v_platform_label ); ?></span>
                                        <?php if ( $v_platform_available ) : ?>
                                            <span class="v"><?php echo esc_html( sprintf( '%d/%d', $v_platform_cited, $v_platform_total ) ); ?></span>
                                        <?php else : ?>
                                            <span class="v na" title="<?php esc_attr_e( 'Unavailable for this check', 'sitestaffr' ); ?>">&mdash;</span>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="sitestaffr-visibility-summary-right">
                                <?php if ( '' !== $v_run_date_label ) : ?>
                                    <span class="sitestaffr-visibility-meta"><?php
                                        /* translators: %s: date of the last visibility check. */
                                        printf( esc_html__( 'Checked %s', 'sitestaffr' ), esc_html( $v_run_date_label ) );
                                    ?></span>
                                <?php endif; ?>
                                <div class="sitestaffr-visibility-actions">
                                    <button type="button" class="button sitestaffr-visibility-run" <?php disabled( $v_run_disabled ); ?> <?php echo $v_run_title ? 'title="' . esc_attr( $v_run_title ) . '"' : ''; ?>>
                                        <span class="dashicons dashicons-update" aria-hidden="true"></span>
                                        <?php esc_html_e( 'Refresh', 'sitestaffr' ); ?>
                                    </button>
                                    <button type="button" class="button sitestaffr-visibility-email">
                                        <span class="dashicons dashicons-email-alt" aria-hidden="true"></span>
                                        <?php esc_html_e( 'Email report', 'sitestaffr' ); ?>
                                    </button>
                                </div>
                                <span class="sitestaffr-visibility-status" aria-live="polite"></span>
                            </div>
                        </div>

                        <!-- Two-column data area -->
                        <div class="sitestaffr-visibility-grid <?php echo $v_has_rail ? '' : 'is-single'; ?>">
                            <div class="sitestaffr-visibility-byprompt">
                                <div class="sitestaffr-visibility-block-h">
                                    <h3><?php esc_html_e( 'By prompt', 'sitestaffr' ); ?></h3>
                                    <span class="meta"><?php
                                        printf(
                                            /* translators: %1$d: prompts cited, %2$d: prompts missed. */
                                            esc_html__( '%1$d cited · %2$d missed', 'sitestaffr' ),
                                            (int) $v_cited_count,
                                            (int) $v_missed_count
                                        );
                                    ?></span>
                                </div>
                                <table class="sitestaffr-visibility-tbl">
                                    <thead>
                                        <tr>
                                            <th class="c-q"><?php esc_html_e( 'Prompt', 'sitestaffr' ); ?></th>
                                            <th class="c-res"><?php esc_html_e( 'Result', 'sitestaffr' ); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ( $v_result_prompts as $v_prompt ) :
                                            if ( ! is_array( $v_prompt ) ) {
                                                continue;
                                            }
                                            $v_prompt_text  = isset( $v_prompt['text'] ) ? (string) $v_prompt['text'] : '';
                                            $v_prompt_cited = ! empty( $v_prompt['cited'] );
                                            $v_cited_on     = ( isset( $v_prompt['citedOn'] ) && is_array( $v_prompt['citedOn'] ) ) ? $v_prompt['citedOn'] : array();
                                            $v_competitors  = ( isset( $v_prompt['competitors'] ) && is_array( $v_prompt['competitors'] ) ) ? $v_prompt['competitors'] : array();
                                            ?>
                                            <tr class="<?php echo $v_prompt_cited ? 'tr-cited' : 'tr-miss'; ?>">
                                                <td class="c-q">
                                                    <span class="q-cell">
                                                        <span class="mk" aria-hidden="true"><?php echo $v_prompt_cited ? '&#10003;' : '&#10007;'; ?></span>
                                                        <span class="q-text"><?php echo esc_html( $v_prompt_text ); ?></span>
                                                    </span>
                                                </td>
                                                <td class="c-res">
                                                    <?php if ( $v_prompt_cited ) :
                                                        $v_cited_on_labels = array_map(
                                                            function ( $p ) use ( $visibility_platform_labels ) {
                                                                return isset( $visibility_platform_labels[ $p ] ) ? $visibility_platform_labels[ $p ] : $p;
                                                            },
                                                            $v_cited_on
                                                        );
                                                        ?>
                                                        <span class="res-ok"><?php echo esc_html( ! empty( $v_cited_on_labels ) ? implode( ', ', $v_cited_on_labels ) : __( 'cited', 'sitestaffr' ) ); ?></span>
                                                    <?php else : ?>
                                                        <span class="res-no"><b><?php esc_html_e( 'not cited', 'sitestaffr' ); ?></b><?php if ( ! empty( $v_competitors ) ) : ?> · <?php echo esc_html( implode( ', ', $v_competitors ) ); ?><?php endif; ?></span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <?php if ( $v_has_rail ) : ?>
                                <div class="sitestaffr-visibility-competitors">
                                    <div class="sitestaffr-visibility-rail">
                                        <div class="sitestaffr-visibility-block-h">
                                            <h3><?php esc_html_e( "Who's beating you", 'sitestaffr' ); ?></h3>
                                        </div>
                                        <ul class="sitestaffr-visibility-rank">
                                            <?php foreach ( $v_agg as $v_agg_row ) :
                                                if ( ! is_array( $v_agg_row ) ) {
                                                    continue;
                                                }
                                                $v_agg_domain = isset( $v_agg_row['domain'] ) ? (string) $v_agg_row['domain'] : '';
                                                $v_agg_count  = isset( $v_agg_row['count'] ) ? (int) $v_agg_row['count'] : 0;
                                                if ( '' === $v_agg_domain ) {
                                                    continue;
                                                }
                                                ?>
                                                <li>
                                                    <span class="d"><?php echo esc_html( $v_agg_domain ); ?></span>
                                                    <span class="c" title="<?php
                                                        /* translators: %d: number of missed questions this competitor was cited on. */
                                                        echo esc_attr( sprintf( _n( 'cited on %d missed question', 'cited on %d missed questions', $v_agg_count, 'sitestaffr' ), $v_agg_count ) );
                                                    ?>"><?php echo esc_html( $v_agg_count ); ?></span>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <div id="sitestaffr-visibility-empty" class="sitestaffr-visibility-empty" <?php echo $visibility_latest ? 'hidden' : ''; ?>>
                    <p><?php esc_html_e( "No visibility check yet. We run one automatically each month — or run one now to see whether Perplexity, ChatGPT, and Gemini cite your site today.", 'sitestaffr' ); ?></p>
                    <p class="sitestaffr-visibility-empty-actions">
                        <button type="button" class="button button-primary sitestaffr-visibility-run" <?php disabled( $v_run_disabled ); ?>>
                            <span class="dashicons dashicons-update" aria-hidden="true"></span>
                            <?php esc_html_e( 'Run first check', 'sitestaffr' ); ?>
                        </button>
                        <span class="sitestaffr-visibility-status" aria-live="polite"></span>
                    </p>
                </div>

                <div class="sitestaffr-visibility-prompts">
                    <div class="sitestaffr-visibility-block-h">
                        <h3><?php esc_html_e( 'Tracked prompts', 'sitestaffr' ); ?></h3>
                        <span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'The questions we ask AI assistants on your behalf. Auto-seeded from your business profile — add, edit, or remove prompts anytime. Up to 10.', 'sitestaffr' ); ?>">
                            <span class="dashicons dashicons-info" aria-hidden="true"></span>
                        </span>
                    </div>
                    <p class="sitestaffr-visibility-prompts-lead"><?php esc_html_e( 'The questions asked on your behalf each check. Auto-seeded from your business profile — edit, add, or remove anytime.', 'sitestaffr' ); ?></p>
                    <ul id="sitestaffr-visibility-prompts-list" class="sitestaffr-visibility-prompts-list" data-max="<?php echo esc_attr( SiteStaffr_Visibility::MAX_PROMPTS ); ?>">
                        <?php
                        foreach ( $visibility_prompts as $v_seed_prompt ) :
                            if ( ! is_array( $v_seed_prompt ) ) {
                                continue;
                            }
                            $v_seed_id   = isset( $v_seed_prompt['id'] ) ? (string) $v_seed_prompt['id'] : '';
                            $v_seed_text = isset( $v_seed_prompt['text'] ) ? (string) $v_seed_prompt['text'] : '';
                            $v_seed_type = ( isset( $v_seed_prompt['type'] ) && 'unbranded' === $v_seed_prompt['type'] ) ? 'unbranded' : 'branded';
                            ?>
                            <li class="sitestaffr-visibility-prompt-row" data-id="<?php echo esc_attr( $v_seed_id ); ?>">
                                <input type="text" class="regular-text sitestaffr-visibility-prompt-input" value="<?php echo esc_attr( $v_seed_text ); ?>" maxlength="200" aria-label="<?php esc_attr_e( 'Prompt text', 'sitestaffr' ); ?>" />
                                <select class="sitestaffr-visibility-prompt-type" aria-label="<?php esc_attr_e( 'Prompt type', 'sitestaffr' ); ?>">
                                    <option value="branded" <?php selected( $v_seed_type, 'branded' ); ?>><?php esc_html_e( 'Branded', 'sitestaffr' ); ?></option>
                                    <option value="unbranded" <?php selected( $v_seed_type, 'unbranded' ); ?>><?php esc_html_e( 'Local/Unbranded', 'sitestaffr' ); ?></option>
                                </select>
                                <button type="button" class="button button-small button-link-delete sitestaffr-visibility-prompt-delete" aria-label="<?php esc_attr_e( 'Delete prompt', 'sitestaffr' ); ?>">
                                    <span class="dashicons dashicons-trash" aria-hidden="true"></span>
                                </button>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                    <div class="sitestaffr-visibility-prompts-actions">
                        <button type="button" id="sitestaffr-visibility-prompts-suggest" class="button">
                            <span class="dashicons dashicons-lightbulb" aria-hidden="true"></span>
                            <?php esc_html_e( 'Suggest prompts', 'sitestaffr' ); ?>
                        </button>
                        <button type="button" id="sitestaffr-visibility-prompts-add" class="button">
                            <span class="dashicons dashicons-plus-alt2" aria-hidden="true"></span>
                            <?php esc_html_e( 'Add prompt', 'sitestaffr' ); ?>
                        </button>
                        <button type="button" id="sitestaffr-visibility-prompts-save" class="button button-primary">
                            <span class="dashicons dashicons-saved" aria-hidden="true"></span>
                            <?php esc_html_e( 'Save prompts', 'sitestaffr' ); ?>
                        </button>
                        <span id="sitestaffr-visibility-prompts-status" class="sitestaffr-inline-status" aria-live="polite"></span>
                    </div>
                    <div id="sitestaffr-visibility-suggestions" class="sitestaffr-visibility-suggestions" hidden>
                        <div class="sitestaffr-visibility-block-h">
                            <h3><?php esc_html_e( 'Suggested prompts', 'sitestaffr' ); ?></h3>
                            <span class="meta"><?php esc_html_e( 'Based on where competitors are beating you', 'sitestaffr' ); ?></span>
                        </div>
                        <ul id="sitestaffr-visibility-suggestions-list" class="sitestaffr-visibility-suggestions-list"></ul>
                    </div>
                </div>

            </div>
        </section>
    </div>

    <!-- Blog Preview Lightbox -->
    <div id="sitestaffr-blog-preview-lightbox" class="sitestaffr-blog-lightbox" style="display: none;">
        <div class="sitestaffr-blog-lightbox-backdrop"></div>
        <div class="sitestaffr-blog-lightbox-dialog">
            <header class="sitestaffr-blog-lightbox-header">
                <h3 id="sitestaffr-blog-preview-title"></h3>
                <span id="sitestaffr-blog-preview-wc" class="sitestaffr-blog-lightbox-wc"></span>
            </header>
            <div class="sitestaffr-blog-lightbox-body" id="sitestaffr-blog-preview-body"></div>
            <footer class="sitestaffr-blog-lightbox-footer">
                <p id="sitestaffr-blog-preview-img-notice" style="display:none;margin:0 0 8px;color:#92400e;font-size:13px;"></p>
                <button id="sitestaffr-blog-preview-publish" type="button" class="button button-primary"><?php esc_html_e( 'Publish', 'sitestaffr' ); ?></button>
                <a id="sitestaffr-blog-preview-edit" href="#" class="button"><?php esc_html_e( 'Open in Editor', 'sitestaffr' ); ?></a>
                <button type="button" class="button sitestaffr-blog-lightbox-close"><?php esc_html_e( 'Close', 'sitestaffr' ); ?></button>
            </footer>
        </div>
    </div>

</div>
<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
