<?php
/**
 * SiteStaffr Admin Dashboard
 *
 * Qualified Leads is the headline metric; conversations, minutes health,
 * and the unread "Needs your attention" list follow. A getting-started
 * checklist replaces the metrics until the first real conversation.
 *
 * @link       https://github.com/sitestaffr/sitestaffr-plugin
 * @since      1.0.0
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/views
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
    die;
}

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

if ( ! isset( $sitestaffr_admin_view_query_service ) || ! ( $sitestaffr_admin_view_query_service instanceof SiteStaffr_Admin_View_Query_Service ) ) {
    $sitestaffr_admin_view_query_service = new SiteStaffr_Admin_View_Query_Service();
}

// Read-only routing params — sanitized and validated against strict allowlists.
// These are standard WordPress admin page navigation params set by menu links,
// not form submissions, so nonces do not apply. The call detail view (action=view)
// performs its own nonce verification before displaying any data.
$sitestaffr_action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only routing; value checked against 'view' only.
if ( 'view' === $sitestaffr_action ) {
    include_once SITESTAFFR_PLUGIN_DIR . 'admin/views/admin-call-detail.php';
    return;
}

$sitestaffr_view = isset( $_GET['view'] ) ? sanitize_key( wp_unslash( $_GET['view'] ) ) : ( isset( $sitestaffr_default_view ) ? $sitestaffr_default_view : '' ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only routing; strict allowlist below.
if ( in_array( $sitestaffr_view, array( 'all', 'leads', 'trash', 'banned' ), true ) ) {
    include_once SITESTAFFR_PLUGIN_DIR . 'admin/views/admin-calls-list.php';
    return;
}

// Get settings and data
$is_setup_complete = SiteStaffr_Admin::is_setup_complete();
$last_test_call = SiteStaffr_Database::get_last_test_call();

// Billing cache (middleware source of truth for admin display).
// The forced refresh makes a live call to the middleware; its return value is
// the honest "reachable right now" signal for the Agent Health section.
$dashboard_billing_cache  = array();
$health_service_connected = false;
if ( class_exists( 'SiteStaffr_Billing_State' ) ) {
	// Force refresh on dashboard load to keep minute balance accurate after recent calls.
	$health_service_connected = (bool) SiteStaffr_Billing_State::maybe_refresh_cache( true );
	$dashboard_billing_cache  = SiteStaffr_Billing_State::get_cache();
}

$dashboard_status_key = isset( $dashboard_billing_cache['subscription_status'] ) ? sanitize_key( $dashboard_billing_cache['subscription_status'] ) : '';

// -----------------------------------------------------------------------------
// Row-1 strip: current cycle vs the same point last cycle.
// Cycle windows come from SiteStaffr_Leads so the leads count here always
// matches what the Leads tab shows for the current cycle.
// -----------------------------------------------------------------------------
$cycle_now  = SiteStaffr_Leads::get_cycle_window( 0 );
$cycle_prev = SiteStaffr_Leads::get_cycle_window( 1 );
$now_dt     = gmdate( 'Y-m-d H:i:s' );
$cycle_elapsed = max( 0, time() - $cycle_now['start_ts'] );
$prev_cut   = gmdate( 'Y-m-d H:i:s', $cycle_prev['start_ts'] + $cycle_elapsed );

$leads_now  = SiteStaffr_Leads::get_lead_count_between( $cycle_now['start_dt'], $now_dt );
$leads_prev = SiteStaffr_Leads::get_lead_count_between( $cycle_prev['start_dt'], $prev_cut );

$convo_counts_now  = $sitestaffr_admin_view_query_service->get_dashboard_period_counts( $cycle_now['start_dt'], $now_dt );
$convo_counts_prev = $sitestaffr_admin_view_query_service->get_dashboard_period_counts( $cycle_prev['start_dt'], $prev_cut );
$convos_now  = (int) $convo_counts_now['total_calls'];
$convos_prev = (int) $convo_counts_prev['total_calls'];

// A delta only makes sense when the previous cycle had any activity to compare against.
$has_prev_cycle_data = ( $leads_prev > 0 || $convos_prev > 0 );

// Sparkline: last 14 days of conversations/day, zero-filled.
$spark_start = gmdate( 'Y-m-d 00:00:00', strtotime( '-13 days' ) );
$spark_rows  = $sitestaffr_admin_view_query_service->get_daily_conversation_rows( $spark_start, $now_dt );
$spark_map   = array();
foreach ( $spark_rows as $spark_row ) {
	$spark_map[ $spark_row->day_key ] = (int) $spark_row->total;
}
$spark_values = array();
for ( $spark_i = 13; $spark_i >= 0; $spark_i-- ) {
	$spark_day      = gmdate( 'Y-m-d', strtotime( "-{$spark_i} days" ) );
	$spark_values[] = isset( $spark_map[ $spark_day ] ) ? $spark_map[ $spark_day ] : 0;
}

// -----------------------------------------------------------------------------
// Minutes balance + health tier (middleware-backed cache, local fallback).
// -----------------------------------------------------------------------------
$subscription_option = get_option( 'sitestaffr_subscription', array() );
$subscription_option = is_array( $subscription_option ) ? $subscription_option : array();

$dashboard_plan_key = isset( $dashboard_billing_cache['plan_name'] ) ? sanitize_key( $dashboard_billing_cache['plan_name'] ) : '';
if ( empty( $dashboard_plan_key ) ) {
    if ( ! empty( $subscription_option['plan_name'] ) ) {
        $dashboard_plan_key = sanitize_key( $subscription_option['plan_name'] );
    } elseif ( ! empty( $subscription_option['plan'] ) ) {
        $dashboard_plan_key = sanitize_key( $subscription_option['plan'] );
    }
}
if ( empty( $dashboard_plan_key ) ) {
    $dashboard_plan_key = 'starter';
}

$dashboard_plan_quotas = array(
    'trial'    => 30,
    'starter'  => 60,
    'business' => 300,
    'pro'      => 700,
);
if ( ! isset( $dashboard_plan_quotas[ $dashboard_plan_key ] ) ) {
    $dashboard_plan_key = 'starter';
}
$included_quota = (int) $dashboard_plan_quotas[ $dashboard_plan_key ];

// Prefer middleware-backed cache for accurate billing stats; fallback to local usage only when missing.
$included = isset( $dashboard_billing_cache['included_minutes_remaining'] ) ? (int) $dashboard_billing_cache['included_minutes_remaining'] : null;
$purchased = isset( $dashboard_billing_cache['addon_minutes_remaining'] ) ? (int) $dashboard_billing_cache['addon_minutes_remaining'] : null;
$has_seconds_precision = isset( $dashboard_billing_cache['included_seconds_remaining'] ) || isset( $dashboard_billing_cache['addon_seconds_remaining'] );
$included_seconds_remaining = $has_seconds_precision ? (int) ( isset( $dashboard_billing_cache['included_seconds_remaining'] ) ? $dashboard_billing_cache['included_seconds_remaining'] : 0 ) : null;
$addon_seconds_remaining = $has_seconds_precision ? (int) ( isset( $dashboard_billing_cache['addon_seconds_remaining'] ) ? $dashboard_billing_cache['addon_seconds_remaining'] : 0 ) : null;

if ( $has_seconds_precision ) {
    // Use second-level values as source of truth for minute display near 0.
    $included = (int) floor( max( 0, $included_seconds_remaining ) / 60 );
    $purchased = (int) floor( max( 0, $addon_seconds_remaining ) / 60 );
}

if ( null === $included || null === $purchased ) {
    $usage_manager = SiteStaffr_Usage_Manager::get_instance();
    $balance = $usage_manager->get_minutes_balance();
    $included = ( null === $included ) ? (int) $balance['included'] : $included;
    $purchased = ( null === $purchased ) ? (int) $balance['purchased'] : $purchased;
}
if ( null === $included ) {
    $included = $included_quota;
}
if ( null === $purchased ) {
    $purchased = 0;
}
$total = $included + $purchased;

// Use second-level precision so small usage is reflected accurately.
if ( null === $included_seconds_remaining ) {
    $included_seconds_remaining = $included * 60;
}
if ( null === $addon_seconds_remaining ) {
    $addon_seconds_remaining = $purchased * 60;
}
$total_seconds_remaining = max( 0, $included_seconds_remaining + $addon_seconds_remaining );
$total_quota_seconds = ( $included_quota * 60 ) + max( 0, $addon_seconds_remaining );

$percentage = ( $total_quota_seconds > 0 ) ? ( $total_seconds_remaining / $total_quota_seconds ) * 100 : 0;
$percentage = max( 0, min( 100, $percentage ) );

// Health tier: ambient when fine, loud (banner + tile color) when not.
if ( $percentage >= 25 && $total >= 15 ) {
    $status = 'healthy';
} elseif ( $percentage >= 5 && $total >= 2 ) {
    $status = 'medium';
} else {
    $status = 'critical';
}

// Next reset date from billing cache (consistent with Usage page).
$next_reset_raw = isset( $dashboard_billing_cache['subscription_current_period_end'] ) ? $dashboard_billing_cache['subscription_current_period_end'] : null;
if ( 'trial' === $dashboard_plan_key && ! empty( $dashboard_billing_cache['trial_expires_at'] ) ) {
    $next_reset_raw = $dashboard_billing_cache['trial_expires_at'];
}
$next_reset_timestamp = ! empty( $next_reset_raw ) ? strtotime( $next_reset_raw ) : false;
// All dates display in Eastern Time (site-wide convention).
$dashboard_display_tz = new DateTimeZone( 'America/New_York' );
if ( false !== $next_reset_timestamp ) {
    $next_month = wp_date( 'F j, Y', $next_reset_timestamp, $dashboard_display_tz );
} else {
    // Fallback to legacy subscription option when billing cache unavailable
    $subscription = wp_parse_args(
        $subscription_option,
        array(
            'next_billing_date' => current_datetime()->modify( '+1 month' )->format( 'Y-m-d' ),
        )
    );
    $next_billing_timestamp = strtotime( $subscription['next_billing_date'] );
    $next_month             = false !== $next_billing_timestamp
        ? wp_date( 'F j, Y', $next_billing_timestamp, $dashboard_display_tz )
        : current_datetime()->modify( '+1 month' )->format( 'F j, Y' );
}

// Usage projection ("~N days at current pace") over the current cycle.
$projection_stat_value = '';
$projection_calls = $sitestaffr_admin_view_query_service->get_projection_usage_calls_since( $cycle_now['start_dt'] );
if ( ! empty( $projection_calls ) ) {
    $first_call_date = strtotime( $projection_calls[0]->created_at );
    $days_of_history = max( 1, ( current_time( 'timestamp' ) - $first_call_date ) / DAY_IN_SECONDS );

    $total_minutes_used = 0;
    foreach ( $projection_calls as $projection_call ) {
        $total_minutes_used += max( 1, (int) $projection_call->effective_billable_minutes );
    }
    $avg_daily_usage = $total_minutes_used / $days_of_history;

    if ( $avg_daily_usage > 0 ) {
        if ( $total <= 0 ) {
            $projection_stat_value = '0';
        } else {
            $days_remaining = $total / $avg_daily_usage;
            if ( $days_remaining >= 365 ) {
                $projection_stat_value = __( '~365+', 'sitestaffr' );
            } elseif ( $days_remaining >= 1 ) {
                $projection_stat_value = sprintf( '~%d', (int) round( $days_remaining ) );
            } else {
                $projection_stat_value = __( '~<1', 'sitestaffr' );
            }
        }
    }
}

// -----------------------------------------------------------------------------
// Conversation lists (test conversations excluded from both).
// -----------------------------------------------------------------------------
$recent_calls = SiteStaffr_Call_Manager::get_calls( array(
    'is_test_call' => 0,
    'per_page'     => 8,
    'page'         => 1,
) );

$new_calls = SiteStaffr_Call_Manager::get_calls( array(
    'handled'      => 0,
    'is_test_call' => 0,
    'per_page'     => 10,
    'page'         => 1,
) );

// Triage: not-yet-handled rows with captured contact become Follow-up slips;
// everything else flows into the day-grouped Activity feed, with no-info rows
// collapsed into one aggregate line per day. Gated on handled_at (deliberate
// "followed up"), so viewing a transcript never clears a pending follow-up.
$dashboard_triage = SiteStaffr_Dashboard_Triage::partition( $new_calls );
$follow_ups       = $dashboard_triage['follow_ups'];
$has_new_calls    = ! empty( $follow_ups );

$follow_up_ids  = array_map( 'intval', wp_list_pluck( $follow_ups, 'id' ) );
$activity_feed  = array_values( array_filter( $recent_calls, static function ( $activity_call ) use ( $follow_up_ids ) {
    return ! in_array( (int) $activity_call->id, $follow_up_ids, true );
} ) );
$activity_groups = SiteStaffr_Dashboard_Triage::group_activity_by_day( $activity_feed, current_time( 'timestamp' ) );

// Shared recap formatter — Follow-up slips render summaries the same way the
// Conversation Details page does (intro paragraph + key-detail bullets).
require_once SITESTAFFR_PLUGIN_DIR . 'includes/sitestaffr-format-recap.php';

// Agent health signals (agent status + knowledge; minutes live in the tile).
$health_widget_settings = get_option( 'sitestaffr_widget_settings', array() );
$health_widget_mode     = isset( $health_widget_settings['mode'] ) ? sanitize_key( $health_widget_settings['mode'] ) : 'both';
$health_mode_labels     = array(
    'voice' => __( 'voice', 'sitestaffr' ),
    'text'  => __( 'text', 'sitestaffr' ),
    'both'  => __( 'text + voice', 'sitestaffr' ),
);
$health_mode_label   = isset( $health_mode_labels[ $health_widget_mode ] ) ? $health_mode_labels[ $health_widget_mode ] : $health_mode_labels['both'];
$health_agent_paused = class_exists( 'SiteStaffr_Billing_State' ) && SiteStaffr_Billing_State::is_subscription_inactive();
// "View live widget" only makes sense while the fixed widget renders on the site.
$widget_auto_display = ! isset( $health_widget_settings['fixed_auto_display'] ) || $health_widget_settings['fixed_auto_display'];

// Knowledge stats (first-run checklist + Agent health reuse these).
$health_knowledge_stats = SiteStaffr_Knowledge_Manager::get_stats();
$health_knowledge_total = isset( $health_knowledge_stats['total_posts'] ) ? (int) $health_knowledge_stats['total_posts'] : 0;

// $health_service_connected was captured above from the live billing refresh.

// Last real conversation (any read state) for the health glance.
$health_last_convo_ago = '';
if ( ! empty( $recent_calls ) ) {
    $health_last_convo_ago = human_time_diff( strtotime( $recent_calls[0]->created_at ), current_time( 'timestamp' ) );
}

// First-run: until the site has a single real conversation, the metrics make
// no sense — show the getting-started checklist instead.
$has_real_conversations = ( SiteStaffr_Call_Manager::get_calls_count( array( 'is_test_call' => 0 ) ) > 0 );

// Stale knowledge count powers the conditional "Re-sync knowledge" quick action.
$stale_knowledge_count = $sitestaffr_admin_view_query_service->get_stale_knowledge_count();

/**
 * Build a one-line summary snippet for a dashboard conversation row.
 *
 * @param object $call Call row.
 * @return string Plain-text snippet ('' when no summary exists).
 */
function sitestaffr_dashboard_call_snippet( $call ) {
	$snippet_raw = isset( $call->ai_summary ) ? stripslashes( (string) $call->ai_summary ) : '';
	if ( '' === trim( $snippet_raw ) ) {
		return '';
	}
	// Onboarding table recaps: build a clean "Name · Business" snippet.
	if ( false !== stripos( $snippet_raw, '<table' ) ) {
		$snippet_parts = array();
		if ( preg_match_all( '/<td[^>]*style="padding:6px 0;"[^>]*>(.*?)<\/td>/si', $snippet_raw, $td_matches ) ) {
			foreach ( $td_matches[1] as $td_val ) {
				$clean = trim( wp_strip_all_tags( $td_val ) );
				if ( '' !== $clean ) {
					$snippet_parts[] = $clean;
				}
			}
		}
		return implode( ' · ', $snippet_parts );
	}
	return wp_trim_words( wp_strip_all_tags( $snippet_raw ), 24, '...' );
}

/**
 * Render one Activity feed conversation row.
 *
 * @param object $call Call row.
 * @return void
 */
function sitestaffr_dashboard_render_call_row( $call ) {
	$view_url = wp_nonce_url(
		add_query_arg(
			array(
				'page'    => 'sitestaffr',
				'action'  => 'view',
				'call_id' => $call->id,
			),
			admin_url( 'admin.php' )
		),
		'sitestaffr_view_call'
	);
	$snippet = sitestaffr_dashboard_call_snippet( $call );
	// No-info rows read as receptionist shorthand, not as a raw AI summary.
	if ( SiteStaffr_Dashboard_Triage::is_brief_no_info( $call ) ) {
		$snippet = ( 'phone' === $call->service_type )
			? __( 'Brief call — no message left', 'sitestaffr' )
			: __( 'Brief chat — no message left', 'sitestaffr' );
	}
	$channel_icon = ( 'phone' === $call->service_type ) ? 'dashicons-phone' : 'dashicons-format-chat';
	?>
	<div class="sitestaffr-call-item <?php echo esc_attr( $call->is_read ? '' : 'sitestaffr-call-unread' ); ?>" data-call-id="<?php echo esc_attr( $call->id ); ?>" data-call-url="<?php echo esc_url( $view_url ); ?>">
		<div class="sitestaffr-call-avatar-circle">
			<span class="dashicons <?php echo esc_attr( $channel_icon ); ?>"></span>
		</div>
		<div class="sitestaffr-call-info">
			<?php if ( ! $call->is_read ) : ?>
				<span class="sitestaffr-badge-new"><?php esc_html_e( 'New', 'sitestaffr' ); ?></span>
			<?php endif; ?>
			<?php if ( isset( $call->persona ) && 'onboarding' === sanitize_key( $call->persona ) ) : ?>
				<span class="sitestaffr-persona-badge sitestaffr-persona-badge--onboarding"><?php esc_html_e( 'Onboarding Lead', 'sitestaffr' ); ?></span>
			<?php endif; ?>
			<?php if ( '' !== $snippet ) : ?>
				<p class="sitestaffr-call-summary-snippet"><?php echo esc_html( $snippet ); ?></p>
			<?php else : ?>
				<p class="sitestaffr-call-summary-snippet sitestaffr-call-summary-empty"><?php esc_html_e( 'No summary available', 'sitestaffr' ); ?></p>
			<?php endif; ?>
			<span class="sitestaffr-call-time"><?php echo esc_html( human_time_diff( strtotime( $call->created_at ), current_time( 'timestamp' ) ) ); ?> <?php esc_html_e( 'ago', 'sitestaffr' ); ?></span>
		</div>
		<div class="sitestaffr-call-meta">
			<?php if ( $call->call_duration > 0 ) : ?>
				<span class="sitestaffr-call-duration"><?php echo esc_html( sprintf( '%d:%02d', floor( $call->call_duration / 60 ), $call->call_duration % 60 ) ); ?></span>
			<?php endif; ?>
		</div>
	</div>
	<?php
}

/**
 * Render one Follow-up "while you were out" message slip.
 *
 * The receptionist's slip: visitor name up top, tap-to-call / tap-to-email
 * actions, what they want, and one state button — Followed up.
 *
 * @param object $call Call row (unread, with captured contact).
 * @return void
 */
function sitestaffr_dashboard_render_follow_up_slip( $call ) {
	$view_url = wp_nonce_url(
		add_query_arg(
			array(
				'page'    => 'sitestaffr',
				'action'  => 'view',
				'call_id' => $call->id,
			),
			admin_url( 'admin.php' )
		),
		'sitestaffr_view_call'
	);

	$slip_name  = isset( $call->lead_name ) ? trim( (string) $call->lead_name ) : '';
	$slip_phone = isset( $call->lead_phone ) ? trim( (string) $call->lead_phone ) : '';
	$slip_email = isset( $call->lead_email ) ? trim( (string) $call->lead_email ) : '';

	// The recap, formatted exactly like the Conversation Details page
	// (intro paragraph + key-detail bullets via the shared formatter).
	$slip_recap = '';
	if ( ! empty( $call->ai_summary ) ) {
		$slip_recap = sitestaffr_format_recap_html( $call->ai_summary );
	} elseif ( ! empty( $call->lead_interest ) ) {
		$slip_recap = '<p>' . esc_html( trim( wp_strip_all_tags( (string) $call->lead_interest ) ) ) . '</p>';
	}

	$slip_channel = ( 'phone' === $call->service_type )
		? __( 'voice', 'sitestaffr' )
		: __( 'text chat', 'sitestaffr' );
	$slip_meta = array( $slip_channel );
	if ( $call->call_duration > 0 ) {
		$slip_meta[] = sprintf( '%d:%02d', floor( $call->call_duration / 60 ), $call->call_duration % 60 );
	}
	/* translators: %s: human time diff, e.g. "4 hours". */
	$slip_meta[] = sprintf( __( '%s ago', 'sitestaffr' ), human_time_diff( strtotime( $call->created_at ), current_time( 'timestamp' ) ) );
	?>
	<div class="sitestaffr-slip" data-call-id="<?php echo esc_attr( $call->id ); ?>">
		<div class="sitestaffr-slip-body">
			<div class="sitestaffr-slip-head">
				<span class="sitestaffr-slip-name">
					<?php echo '' !== $slip_name ? esc_html( $slip_name ) : esc_html__( 'No name given', 'sitestaffr' ); ?>
				</span>
				<span class="sitestaffr-slip-meta"><?php echo esc_html( implode( ' · ', $slip_meta ) ); ?></span>
			</div>
			<?php if ( '' !== $slip_recap ) : ?>
				<div class="sitestaffr-slip-recap sitestaffr-summary-body"><?php echo wp_kses_post( $slip_recap ); ?></div>
			<?php endif; ?>
			<div class="sitestaffr-slip-actions">
				<?php if ( '' !== $slip_phone ) : ?>
					<a class="sitestaffr-slip-action" href="<?php echo esc_url( 'tel:' . preg_replace( '/[^0-9+]/', '', $slip_phone ) ); ?>">
						<span class="dashicons dashicons-phone" aria-hidden="true"></span><?php echo esc_html( $slip_phone ); ?>
					</a>
				<?php endif; ?>
				<?php if ( '' !== $slip_email ) : ?>
					<a class="sitestaffr-slip-action" href="<?php echo esc_url( 'mailto:' . $slip_email ); ?>">
						<span class="dashicons dashicons-email" aria-hidden="true"></span><?php echo esc_html( $slip_email ); ?>
					</a>
				<?php endif; ?>
				<a class="sitestaffr-slip-action sitestaffr-slip-view" href="<?php echo esc_url( $view_url ); ?>">
					<?php esc_html_e( 'View conversation', 'sitestaffr' ); ?>
					<span class="dashicons dashicons-arrow-right-alt2" aria-hidden="true"></span>
				</a>
				<button type="button" class="sitestaffr-slip-done sitestaffr-attention-mark-read" data-call-id="<?php echo esc_attr( $call->id ); ?>">
					<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>
					<?php esc_html_e( 'Followed up', 'sitestaffr' ); ?>
				</button>
			</div>
		</div>
	</div>
	<?php
}

/**
 * Render a vs-last-cycle delta chip.
 *
 * @param int  $now      Current-cycle count.
 * @param int  $prev     Same-point-last-cycle count.
 * @param bool $has_prev Whether a previous cycle exists to compare.
 * @return string HTML.
 */
function sitestaffr_dashboard_delta_chip( $now, $prev, $has_prev ) {
	if ( ! $has_prev ) {
		return '';
	}
	$diff = $now - $prev;
	if ( 0 === $diff ) {
		$class = 'is-flat';
		$text  = '±0';
	} elseif ( $diff > 0 ) {
		$class = 'is-up';
		$text  = '+' . number_format_i18n( $diff );
	} else {
		$class = 'is-down';
		$text  = '−' . number_format_i18n( abs( $diff ) );
	}
	return '<span class="sitestaffr-delta ' . esc_attr( $class ) . '" title="' . esc_attr__( 'vs this point last cycle', 'sitestaffr' ) . '">' . esc_html( $text )
		. '<span class="screen-reader-text"> ' . esc_html__( 'vs this point last cycle', 'sitestaffr' ) . '</span></span>';
}

/**
 * Render a 14-day conversations-per-day sparkline as inline SVG.
 *
 * @param int[] $values Daily totals, oldest first.
 * @return string SVG markup.
 */
function sitestaffr_dashboard_sparkline_svg( $values ) {
	$w = 220;
	$h = 36;
	$pad = 2;
	$max = max( 1, max( $values ) );
	$n = count( $values );
	$points = array();
	foreach ( $values as $i => $v ) {
		$x = $pad + ( $i / max( 1, $n - 1 ) ) * ( $w - 2 * $pad );
		$y = $h - $pad - ( $v / $max ) * ( $h - 2 * $pad );
		$points[] = round( $x, 1 ) . ',' . round( $y, 1 );
	}
	// Closed polygon under the line gives the sparkline an area fill.
	$area_points = array_merge(
		array( $pad . ',' . ( $h - $pad ) ),
		$points,
		array( ( $w - $pad ) . ',' . ( $h - $pad ) )
	);
	return '<svg class="sitestaffr-sparkline" viewBox="0 0 ' . (int) $w . ' ' . (int) $h . '" role="img" aria-label="'
		. esc_attr__( 'Conversations per day, last 14 days', 'sitestaffr' ) . '">'
		. '<polygon class="sitestaffr-sparkline-area" points="' . esc_attr( implode( ' ', $area_points ) ) . '" />'
		. '<polyline fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" points="'
		. esc_attr( implode( ' ', $points ) ) . '" /></svg>';
}
?>

<div class="wrap sitestaffr-wrap sitestaffr-dashboard">
    <?php
    $sitestaffr_page_title = __( 'Dashboard', 'sitestaffr' );
    include SITESTAFFR_PLUGIN_DIR . 'admin/partials/sitestaffr-header.php';
    ?>

    <?php
    // Plan status alert banner (canceled / trial_expired / unpaid / past_due)
    $sitestaffr_alert_statuses = array( 'canceled', 'trial_expired', 'unpaid', 'past_due' );
    if ( in_array( $dashboard_status_key, $sitestaffr_alert_statuses, true ) ) :
        $sitestaffr_usage_url = admin_url( 'admin.php?page=sitestaffr-usage#purchase-minutes' );

        if ( 'canceled' === $dashboard_status_key ) :
            $sitestaffr_alert_class  = 'sitestaffr-plan-alert-danger';
            $sitestaffr_alert_title  = __( 'Subscription Canceled', 'sitestaffr' );
            $sitestaffr_alert_body   = __( 'Your subscription has been canceled. Your AI voice agent is no longer active.', 'sitestaffr' );
            $sitestaffr_alert_cta    = __( 'Resubscribe', 'sitestaffr' );
        elseif ( 'trial_expired' === $dashboard_status_key ) :
            $sitestaffr_alert_class  = 'sitestaffr-plan-alert-warning';
            $sitestaffr_alert_title  = __( 'Free Trial Expired', 'sitestaffr' );
            $sitestaffr_alert_body   = __( 'Your free trial has expired. Upgrade to keep your AI voice agent running.', 'sitestaffr' );
            $sitestaffr_alert_cta    = __( 'Upgrade Now', 'sitestaffr' );
        else : // unpaid or past_due
            $sitestaffr_alert_class  = ( 'past_due' === $dashboard_status_key ) ? 'sitestaffr-plan-alert-warning' : 'sitestaffr-plan-alert-danger';
            $sitestaffr_alert_title  = __( 'Payment Failed', 'sitestaffr' );
            $sitestaffr_alert_body   = __( 'Your payment has failed. Please update your payment method to continue service.', 'sitestaffr' );
            $sitestaffr_alert_cta    = __( 'Update Payment', 'sitestaffr' );
        endif;
    ?>
    <div class="sitestaffr-plan-alert-banner <?php echo esc_attr( $sitestaffr_alert_class ); ?>" id="sitestaffr-plan-alert-banner" role="alert">
        <span class="sitestaffr-plan-alert-icon dashicons dashicons-warning" aria-hidden="true"></span>
        <div class="sitestaffr-plan-alert-body">
            <strong><?php echo esc_html( $sitestaffr_alert_title ); ?></strong>
            <?php echo esc_html( $sitestaffr_alert_body ); ?>
            <a href="<?php echo esc_url( $sitestaffr_usage_url ); ?>" class="sitestaffr-plan-alert-cta"><?php echo esc_html( $sitestaffr_alert_cta ); ?></a>
        </div>
        <button type="button" class="sitestaffr-plan-alert-dismiss dashicons dashicons-dismiss" aria-label="<?php esc_attr_e( 'Dismiss', 'sitestaffr' ); ?>"></button>
    </div>
    <?php endif; ?>

    <?php
    // Display admin notices from nonce-verified redirects (e.g. mark-read, delete).
    // Uses wp_verify_nonce on a redirect nonce to satisfy WP.org scanner requirements.
    if ( isset( $_GET['message'], $_GET['_wpnonce'] )
        && wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), 'sitestaffr_admin_notice' )
    ) {
        $message = sanitize_key( wp_unslash( $_GET['message'] ) );
        $success_messages = array(
            'marked_read'        => __( 'Conversation marked as read.', 'sitestaffr' ),
            'marked_unread'      => __( 'Conversation marked as unread.', 'sitestaffr' ),
            'deleted'            => __( 'Conversation deleted.', 'sitestaffr' ),
            'bulk_marked_read'   => __( 'Selected conversations marked as read.', 'sitestaffr' ),
            'bulk_marked_unread' => __( 'Selected conversations marked as unread.', 'sitestaffr' ),
            'bulk_deleted'       => __( 'Selected conversations deleted.', 'sitestaffr' ),
        );

        if ( isset( $success_messages[ $message ] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $success_messages[ $message ] ) . '</p></div>';
        }
    }
    ?>

    <?php if ( ! $has_real_conversations ) : ?>

    <!-- First-run: getting-started checklist replaces the metric strip + attention list -->
    <div class="sitestaffr-widget sitestaffr-getting-started">
        <div class="sitestaffr-widget-header">
            <h2>
                <span class="dashicons dashicons-flag"></span>
                <?php esc_html_e( 'Getting started', 'sitestaffr' ); ?>
            </h2>
        </div>
        <ol class="sitestaffr-checklist">
            <?php
            $knowledge_stats = $health_knowledge_stats;
            $sitestaffr_checklist = array(
                array(
                    'done'  => (bool) $is_setup_complete,
                    'label' => __( 'Complete your business setup', 'sitestaffr' ),
                    'url'   => admin_url( 'admin.php?page=sitestaffr-setup' ),
                ),
                array(
                    'done'  => ( (int) $knowledge_stats['total_posts'] > 0 ),
                    'label' => __( 'Sync your website knowledge so your agent can answer from it', 'sitestaffr' ),
                    'url'   => admin_url( 'admin.php?page=sitestaffr-my-agent#sitestaffr-knowledge' ),
                ),
                array(
                    'done'    => (bool) $last_test_call,
                    'label'   => __( 'Test your widget with a practice conversation', 'sitestaffr' ),
                    'url'     => SiteStaffr_Test_Mode::get_test_url(),
                    'new_tab' => true,
                ),
                array(
                    'done'    => false,
                    'waiting' => true,
                    'label'   => __( 'Your first visitor conversation will appear here', 'sitestaffr' ),
                ),
            );
            foreach ( $sitestaffr_checklist as $sitestaffr_checklist_item ) : ?>
                <li class="sitestaffr-checklist-item <?php echo esc_attr( $sitestaffr_checklist_item['done'] ? 'is-done' : ( empty( $sitestaffr_checklist_item['waiting'] ) ? '' : 'is-waiting' ) ); ?>">
                    <span class="dashicons <?php echo esc_attr( $sitestaffr_checklist_item['done'] ? 'dashicons-yes-alt' : 'dashicons-marker' ); ?>" aria-hidden="true"></span>
                    <?php if ( ! $sitestaffr_checklist_item['done'] && ! empty( $sitestaffr_checklist_item['url'] ) ) : ?>
                        <a href="<?php echo esc_url( $sitestaffr_checklist_item['url'] ); ?>"<?php echo ! empty( $sitestaffr_checklist_item['new_tab'] ) ? ' target="_blank" rel="noopener"' : ''; ?>><?php echo esc_html( $sitestaffr_checklist_item['label'] ); ?></a>
                    <?php else : ?>
                        <span><?php echo esc_html( $sitestaffr_checklist_item['label'] ); ?></span>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ol>
    </div>

    <?php else : ?>

    <!-- Row 1: metric strip — Qualified Leads is the headline -->
    <div class="sitestaffr-dash-strip">
        <a class="sitestaffr-dash-tile sitestaffr-dash-tile--leads"
            href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=sitestaffr&view=leads' ), 'sitestaffr_view' ) ); ?>">
            <span class="sitestaffr-dash-tile-label"><?php esc_html_e( 'Qualified Leads', 'sitestaffr' ); ?></span>
            <span class="sitestaffr-dash-tile-value">
                <?php echo esc_html( number_format_i18n( $leads_now ) ); ?>
                <?php echo wp_kses_post( sitestaffr_dashboard_delta_chip( $leads_now, $leads_prev, $has_prev_cycle_data ) ); ?>
            </span>
            <span class="sitestaffr-dash-tile-sub"><?php esc_html_e( 'This billing cycle — view all', 'sitestaffr' ); ?></span>
        </a>

        <a class="sitestaffr-dash-tile sitestaffr-dash-tile--conversations"
            href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr-usage' ) ); ?>">
            <span class="sitestaffr-dash-tile-label"><?php esc_html_e( 'Conversations', 'sitestaffr' ); ?></span>
            <span class="sitestaffr-dash-tile-value">
                <?php echo esc_html( number_format_i18n( $convos_now ) ); ?>
                <?php echo wp_kses_post( sitestaffr_dashboard_delta_chip( $convos_now, $convos_prev, $has_prev_cycle_data ) ); ?>
            </span>
            <?php if ( array_sum( $spark_values ) > 0 ) : ?>
                <?php echo wp_kses( sitestaffr_dashboard_sparkline_svg( $spark_values ), array(
                    'svg'      => array( 'class' => true, 'viewbox' => true, 'role' => true, 'aria-label' => true ),
                    'polygon'  => array( 'class' => true, 'points' => true ),
                    'polyline' => array( 'fill' => true, 'stroke' => true, 'stroke-width' => true, 'stroke-linejoin' => true, 'stroke-linecap' => true, 'points' => true ),
                ) ); ?>
                <span class="sitestaffr-dash-tile-sub"><?php esc_html_e( 'Per day, last 14 days', 'sitestaffr' ); ?></span>
            <?php else : ?>
                <span class="sitestaffr-dash-tile-sub"><?php esc_html_e( 'This billing cycle', 'sitestaffr' ); ?></span>
            <?php endif; ?>
        </a>

        <a class="sitestaffr-dash-tile sitestaffr-dash-tile--minutes status-<?php echo esc_attr( $status ); ?>"
            href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr-usage#purchase-minutes' ) ); ?>">
            <span class="sitestaffr-dash-tile-label"><?php esc_html_e( 'AI Minutes', 'sitestaffr' ); ?></span>
            <span class="sitestaffr-dash-tile-value">
                <span class="sitestaffr-health-dot" aria-hidden="true"></span>
                <?php echo esc_html( sprintf( /* translators: %s: minutes remaining */ __( '%s left', 'sitestaffr' ), number_format_i18n( $total ) ) ); ?>
            </span>
            <span class="sitestaffr-dash-tile-sub">
                <?php echo esc_html( sprintf( /* translators: %s: date */ __( 'Resets %s', 'sitestaffr' ), $next_month ) ); ?><?php if ( '' !== $projection_stat_value ) : ?> · <?php echo esc_html( sprintf( /* translators: %s: approximate day count */ __( '%s days at current pace', 'sitestaffr' ), $projection_stat_value ) ); ?><?php endif; ?>
            </span>
            <?php
            // Minutes ring: percentage of the cycle's minutes still available.
            // Colored by the same health tier as the tile (CSS currentColor).
            $ring_r    = 17;
            $ring_c    = 2 * M_PI * $ring_r;
            $ring_dash = max( 0, min( $ring_c, ( $percentage / 100 ) * $ring_c ) );
            ?>
            <svg class="sitestaffr-minutes-ring" viewBox="0 0 44 44" role="img" aria-label="<?php echo esc_attr( sprintf( /* translators: %d: percent of minutes remaining */ __( '%d%% of AI minutes remaining', 'sitestaffr' ), round( $percentage ) ) ); ?>">
                <circle class="sitestaffr-minutes-ring-track" cx="22" cy="22" r="<?php echo (int) $ring_r; ?>" />
                <circle class="sitestaffr-minutes-ring-fill" cx="22" cy="22" r="<?php echo (int) $ring_r; ?>"
                    stroke-dasharray="<?php echo esc_attr( round( $ring_dash, 1 ) . ' ' . round( $ring_c, 1 ) ); ?>" />
                <text class="sitestaffr-minutes-ring-text" x="22" y="26"><?php echo esc_html( round( $percentage ) . '%' ); ?></text>
            </svg>
        </a>
    </div>

    <?php if ( $has_new_calls ) : ?>
    <!-- Follow-ups: unread conversations where the visitor left contact info -->
    <div class="sitestaffr-widget sitestaffr-attention-widget has-new-calls" id="sitestaffr-new-calls-section">
        <div class="sitestaffr-widget-header sitestaffr-new-calls-header">
            <h2>
                <span class="dashicons dashicons-phone"></span>
                <?php esc_html_e( 'Follow-ups', 'sitestaffr' ); ?>
                <span class="sitestaffr-new-calls-count"><?php echo esc_html( count( $follow_ups ) ); ?></span>
            </h2>
            <button type="button" class="sitestaffr-toggle-new-calls" aria-expanded="true" aria-controls="sitestaffr-new-calls-content">
                <span class="dashicons dashicons-arrow-up-alt2"></span>
            </button>
        </div>

        <div class="sitestaffr-new-calls-content" id="sitestaffr-new-calls-content">
            <div class="sitestaffr-calls-list sitestaffr-attention-list sitestaffr-slip-list">
                <?php foreach ( $follow_ups as $call ) : ?>
                    <?php sitestaffr_dashboard_render_follow_up_slip( $call ); ?>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php else : ?>
    <!-- No follow-ups: slim reassurance bar instead of a tall empty block -->
    <div class="sitestaffr-followups-clear" id="sitestaffr-new-calls-section">
        <span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>
        <span class="sitestaffr-followups-clear-text">
            <strong><?php esc_html_e( 'No follow-ups waiting.', 'sitestaffr' ); ?></strong>
            <?php esc_html_e( 'Your agent has the desk — every visitor who left a message has been handled.', 'sitestaffr' ); ?>
        </span>
    </div>
    <?php endif; ?>
    <?php endif; ?>

    <!-- Columns: Activity (left) + Agent health / Quick Actions (right) -->
    <div class="sitestaffr-dash-columns">

        <!-- Activity: day-grouped feed -->
        <div class="sitestaffr-widget sitestaffr-calls-widget sitestaffr-recent-calls-widget">
            <div class="sitestaffr-widget-header">
                <h3>
                    <span class="dashicons dashicons-list-view"></span>
                    <?php esc_html_e( 'Activity', 'sitestaffr' ); ?>
                </h3>
                <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=sitestaffr&view=all' ), 'sitestaffr_view' ) ); ?>" class="sitestaffr-view-all-link">
                    <span class="sitestaffr-view-all-text"><?php esc_html_e( 'View all', 'sitestaffr' ); ?></span>
                    <span class="dashicons dashicons-arrow-right-alt2"></span>
                </a>
            </div>
            <?php if ( ! empty( $activity_groups ) ) : ?>
            <div class="sitestaffr-calls-list sitestaffr-activity-feed">
                <?php foreach ( $activity_groups as $activity_day_key => $activity_day ) : ?>
                    <h4 class="sitestaffr-day-header">
                        <?php
                        if ( 'today' === $activity_day_key ) {
                            esc_html_e( 'Today', 'sitestaffr' );
                        } elseif ( 'yesterday' === $activity_day_key ) {
                            esc_html_e( 'Yesterday', 'sitestaffr' );
                        } else {
                            echo esc_html( wp_date( 'l, F j', strtotime( $activity_day_key . ' 12:00:00' ) ) );
                        }
                        ?>
                    </h4>
                    <?php foreach ( $activity_day['calls'] as $call ) : ?>
                        <?php sitestaffr_dashboard_render_call_row( $call ); ?>
                    <?php endforeach; ?>
                    <?php if ( ! empty( $activity_day['brief'] ) ) : ?>
                        <?php $brief_count = count( $activity_day['brief'] ); ?>
                        <div class="sitestaffr-brief-group">
                            <button type="button" class="sitestaffr-brief-toggle" aria-expanded="false">
                                <span class="dashicons dashicons-phone" aria-hidden="true"></span>
                                <?php
                                echo esc_html( sprintf(
                                    /* translators: %s: number of brief conversations. */
                                    _n( '%s brief conversation — no message left', '%s brief conversations — no message left', $brief_count, 'sitestaffr' ),
                                    number_format_i18n( $brief_count )
                                ) );
                                ?>
                                <span class="dashicons dashicons-arrow-down-alt2" aria-hidden="true"></span>
                            </button>
                            <div class="sitestaffr-brief-items" hidden>
                                <?php foreach ( $activity_day['brief'] as $call ) : ?>
                                    <?php sitestaffr_dashboard_render_call_row( $call ); ?>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
            <?php else : ?>
            <div class="sitestaffr-empty-state">
                <span class="dashicons dashicons-format-chat"></span>
                <p><?php esc_html_e( 'No conversations yet. Once conversations come in, they\'ll appear here.', 'sitestaffr' ); ?></p>
            </div>
            <?php endif; ?>
            <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=sitestaffr&view=all' ), 'sitestaffr_view' ) ); ?>" class="sitestaffr-view-all-link sitestaffr-view-all-link-mobile">
                <span class="sitestaffr-view-all-text"><?php esc_html_e( 'View all', 'sitestaffr' ); ?></span>
                <span class="dashicons dashicons-arrow-right-alt2"></span>
            </a>
        </div><!-- Activity -->

        <div class="sitestaffr-dash-columns-side">

            <!-- Agent Health: cream rows = status (static), white rows = a fix to act on -->
            <div class="sitestaffr-widget sitestaffr-health-widget">
                <div class="sitestaffr-widget-header">
                    <h2>
                        <span class="dashicons dashicons-heart"></span>
                        <?php esc_html_e( 'Agent Health', 'sitestaffr' ); ?>
                    </h2>
                </div>
                <div class="sitestaffr-health-rows">

                    <?php if ( $health_agent_paused ) : ?>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr-usage' ) ); ?>" class="sitestaffr-health-row is-bad">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-warning"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Agent paused', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc"><?php esc_html_e( 'Subscription inactive — visitors get the contact form', 'sitestaffr' ); ?></div>
                        </div>
                        <span class="dashicons dashicons-arrow-right-alt2"></span>
                    </a>
                    <?php else : ?>
                    <div class="sitestaffr-health-row is-ok is-static">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-admin-users"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Agent active', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc">
                                <?php
                                /* translators: %s: widget mode label, e.g. "text + voice". */
                                echo esc_html( sprintf( __( 'Answering as %s', 'sitestaffr' ), $health_mode_label ) );
                                ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if ( $widget_auto_display ) : ?>
                    <div class="sitestaffr-health-row is-ok is-static">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-visibility"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Widget visible', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc"><?php esc_html_e( 'Showing on your site for every visitor', 'sitestaffr' ); ?></div>
                        </div>
                    </div>
                    <?php else : ?>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr-widget-settings' ) ); ?>" class="sitestaffr-health-row is-bad">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-hidden"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Widget turned off', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc"><?php esc_html_e( 'Visitors can\'t see it — turn it on in Widget & Button', 'sitestaffr' ); ?></div>
                        </div>
                        <span class="dashicons dashicons-arrow-right-alt2"></span>
                    </a>
                    <?php endif; ?>

                    <?php if ( $stale_knowledge_count > 0 ) : ?>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr-my-agent#sitestaffr-knowledge' ) ); ?>" class="sitestaffr-health-row is-warn">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-update"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Knowledge out of date', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc">
                                <?php
                                echo esc_html( sprintf(
                                    /* translators: %s: number of pages */
                                    _n( '%s page changed since last sync — re-sync now', '%s pages changed since last sync — re-sync now', $stale_knowledge_count, 'sitestaffr' ),
                                    number_format_i18n( $stale_knowledge_count )
                                ) );
                                ?>
                            </div>
                        </div>
                        <span class="dashicons dashicons-arrow-right-alt2"></span>
                    </a>
                    <?php elseif ( $health_knowledge_total > 0 ) : ?>
                    <div class="sitestaffr-health-row is-ok is-static">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-book"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Knowledge up to date', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc">
                                <?php
                                echo esc_html( sprintf(
                                    /* translators: %s: number of pages */
                                    _n( '%s page synced', '%s pages synced', $health_knowledge_total, 'sitestaffr' ),
                                    number_format_i18n( $health_knowledge_total )
                                ) );
                                ?>
                            </div>
                        </div>
                    </div>
                    <?php else : ?>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr-my-agent#sitestaffr-knowledge' ) ); ?>" class="sitestaffr-health-row is-warn">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-book"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'No knowledge synced yet', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc"><?php esc_html_e( 'Sync your site so your agent can answer from it', 'sitestaffr' ); ?></div>
                        </div>
                        <span class="dashicons dashicons-arrow-right-alt2"></span>
                    </a>
                    <?php endif; ?>

                    <?php if ( $health_service_connected ) : ?>
                    <div class="sitestaffr-health-row is-ok is-static">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-cloud"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Connected to SiteStaffr', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc"><?php esc_html_e( 'AI and billing service reachable', 'sitestaffr' ); ?></div>
                        </div>
                    </div>
                    <?php else : ?>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr-diagnostics' ) ); ?>" class="sitestaffr-health-row is-bad">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-cloud"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Can\'t reach SiteStaffr', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc"><?php esc_html_e( 'The service didn\'t respond just now — check Diagnostics', 'sitestaffr' ); ?></div>
                        </div>
                        <span class="dashicons dashicons-arrow-right-alt2"></span>
                    </a>
                    <?php endif; ?>

                    <?php if ( $health_last_convo_ago ) : ?>
                    <div class="sitestaffr-health-row is-ok is-static">
                        <span class="sitestaffr-sidebar-icon"><span class="dashicons dashicons-clock"></span></span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Last conversation', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc">
                                <?php
                                /* translators: %s: human time diff, e.g. "4 hours". */
                                echo esc_html( sprintf( __( '%s ago', 'sitestaffr' ), $health_last_convo_ago ) );
                                ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                </div>
            </div>

            <!-- Quick Actions -->
            <div class="sitestaffr-widget sitestaffr-actions-sidebar">
                <div class="sitestaffr-widget-header">
                    <h2>
                        <span class="dashicons dashicons-admin-tools"></span>
                        <?php esc_html_e( 'Quick Actions', 'sitestaffr' ); ?>
                    </h2>
                </div>
                <div class="sitestaffr-sidebar-actions">
                    <a href="<?php echo esc_url( SiteStaffr_Test_Mode::get_test_url() ); ?>" target="_blank" rel="noopener" class="sitestaffr-sidebar-button">
                        <span class="sitestaffr-sidebar-icon">
                            <span class="dashicons dashicons-microphone"></span>
                        </span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Test your widget', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc"><?php esc_html_e( 'Have a practice conversation — it won\'t appear in stats or leads', 'sitestaffr' ); ?></div>
                        </div>
                        <span class="dashicons dashicons-arrow-right-alt2"></span>
                    </a>
                    <?php if ( $widget_auto_display ) : ?>
                    <a href="<?php echo esc_url( home_url( '/' ) ); ?>" target="_blank" rel="noopener" class="sitestaffr-sidebar-button">
                        <span class="sitestaffr-sidebar-icon">
                            <span class="dashicons dashicons-visibility"></span>
                        </span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'View live widget', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc"><?php esc_html_e( 'Open your site and see the widget as visitors do', 'sitestaffr' ); ?></div>
                        </div>
                        <span class="dashicons dashicons-arrow-right-alt2"></span>
                    </a>
                    <?php endif; ?>
                    <button type="button" class="sitestaffr-sidebar-button" data-open-buy-modal>
                        <span class="sitestaffr-sidebar-icon">
                            <span class="dashicons dashicons-plus-alt2"></span>
                        </span>
                        <div class="sitestaffr-sidebar-content">
                            <div class="sitestaffr-action-title"><?php esc_html_e( 'Buy More Minutes', 'sitestaffr' ); ?></div>
                            <div class="sitestaffr-action-desc"><?php esc_html_e( '60 min add-on for $20', 'sitestaffr' ); ?></div>
                        </div>
                        <span class="dashicons dashicons-arrow-right-alt2"></span>
                    </button>
                </div>
                <div id="sitestaffr-action-status" class="sitestaffr-action-status"></div>
            </div>

        </div><!-- .sitestaffr-dash-columns-side -->
    </div><!-- .sitestaffr-dash-columns -->

</div><!-- .wrap -->

<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound,WordPress.Security.NonceVerification.Recommended ?>
