<?php
/**
 * Dashboard Views Trait
 *
 * Moves Dashboard header and stats render methods out of the monolithic dashboard class.
 *
 * @package opti-behavior
 * @version 1.0.3
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Dashboard Views Trait
 *
 * Provides dashboard rendering methods.
 *
 * @since 1.0.0
 */
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
if ( ! trait_exists( 'opti_behavior_Dashboard_Views_Trait' ) ) {
	trait Opti_Behavior_Dashboard_Views_Trait {
		/**
		 * Render dashboard header.
		 *
		 * @since 1.0.0
		 * @param array  $date_range Date range.
		 * @param string $period Period.
		 */
		private function render_dashboard_header( $date_range = null, $period = 'last30days' ) {
            $start_val = $date_range && isset($date_range['start']) ? substr($date_range['start'],0,10) : '';
            $end_val = $date_range && isset($date_range['end']) ? substr($date_range['end'],0,10) : '';
            $tooltips = opti_behavior_get_dashboard_tooltips();
            ?>
            <div class="dashboard-header">
                <div class="dashboard-title-section">
                    <div class="dashboard-icon"><i data-lucide="bar-chart-3"></i></div>
                    <div class="dashboard-title-text">
                        <h1 class="dashboard-title">
                            <?php esc_html_e( 'Analytics Dashboard', 'opti-behavior' ); ?>
                            <?php opti_behavior_tooltip_e( $tooltips['dashboard_overview']['title'], $tooltips['dashboard_overview']['content'], $tooltips['dashboard_overview']['simple'], '', array( 'position' => 'bottom' ) ); ?>
                        </h1>
                        <div class="dashboard-subtitle">
                            <span class="subtitle-text"><?php esc_html_e( 'Real-time insights and user behavior analytics', 'opti-behavior' ); ?></span>
                        </div>
                    </div>
                </div>
                <div class="dashboard-controls">
                    <select class="period-selector" id="dashboard-period">
                        <option value="today" <?php selected($period,'today'); ?>><?php esc_html_e( 'Today', 'opti-behavior' ); ?></option>
                        <option value="yesterday" <?php selected($period,'yesterday'); ?>><?php esc_html_e( 'Yesterday', 'opti-behavior' ); ?></option>
                        <option value="last7days" <?php selected($period,'last7days'); ?>><?php esc_html_e( 'Last 7 Days', 'opti-behavior' ); ?></option>
                        <option value="last30days" <?php selected($period,'last30days'); ?>><?php esc_html_e( 'Last 30 Days', 'opti-behavior' ); ?></option>
                        <option value="thismonth" <?php selected($period,'thismonth'); ?>><?php esc_html_e( 'This Month', 'opti-behavior' ); ?></option>
                        <option value="custom" <?php selected($period,'custom'); ?>><?php esc_html_e( 'Custom Range', 'opti-behavior' ); ?></option>
                    </select>
                    <input type="date" id="start-date" value="<?php echo esc_attr($start_val); ?>" />
                    <input type="date" id="end-date" value="<?php echo esc_attr($end_val); ?>" />
                    <button class="refresh-btn" id="apply-range">
                        <i data-lucide="calendar"></i>
                        <?php esc_html_e( 'Apply', 'opti-behavior' ); ?>
                    </button>
                    <button class="refresh-btn" id="refresh-dashboard">
                        <i data-lucide="refresh-cw"></i>
                        <?php esc_html_e( 'Refresh', 'opti-behavior' ); ?>
                    </button>
                    <button class="filter-btn" id="exclude-spam-toggle" aria-pressed="false" aria-label="<?php esc_attr_e( 'Exclude spam traffic', 'opti-behavior' ); ?>" title="<?php esc_attr_e( 'Exclude spam traffic from all statistics', 'opti-behavior' ); ?>">
                        <span class="filter-icon"><i data-lucide="shield-off"></i></span>
                        <span class="filter-label"><?php esc_html_e( 'Exclude Spam', 'opti-behavior' ); ?></span>
                    </button>
                </div>
            </div>
            <?php
        }

        /**
         * Render dashboard stats
         */
        private function render_dashboard_stats($stats, $changes) {
            /* translators: %s: percentage change value */
            $fmt = function($delta){ $sign = ($delta > 0 ? '+' : ($delta < 0 ? '' : '')); return $sign . (int)round($delta) . esc_html__( '% vs last period', 'opti-behavior' ); };
            $cls = function($delta){ return $delta > 0 ? 'positive' : ($delta < 0 ? 'negative' : 'neutral'); };
            $tooltips = opti_behavior_get_dashboard_tooltips();
            ?>
            <div class="dashboard-stats">
                <div class="stat-card" data-stat="visitors">
                    <div class="stat-icon"><i data-lucide="users"></i></div>
                    <div class="stat-content">
                        <div class="stat-value"><span class="stat-value-spinner"></span></div>
                        <div class="stat-label">
                            <?php esc_html_e( 'Visitors', 'opti-behavior' ); ?>
                            <?php opti_behavior_tooltip_e( $tooltips['visitors']['title'], $tooltips['visitors']['content'], $tooltips['visitors']['simple'], $tooltips['visitors']['example'], array( 'position' => 'bottom', 'size' => 'sm' ) ); ?>
                        </div>
                        <div class="stat-change neutral"><?php esc_html_e( '0% vs last period', 'opti-behavior' ); ?></div>
                        <div class="stat-history">
                            <canvas id="history-visitors" width="280" height="50"></canvas>
                        </div>
                    </div>
                </div>

                <div class="stat-card" data-stat="sessions">
                    <div class="stat-icon"><i data-lucide="activity"></i></div>
                    <div class="stat-content">
                        <div class="stat-value"><span class="stat-value-spinner"></span></div>
                        <div class="stat-label">
                            <?php esc_html_e( 'Sessions', 'opti-behavior' ); ?>
                            <?php opti_behavior_tooltip_e( $tooltips['sessions']['title'], $tooltips['sessions']['content'], $tooltips['sessions']['simple'], $tooltips['sessions']['example'], array( 'position' => 'bottom', 'size' => 'sm' ) ); ?>
                        </div>
                        <div class="stat-change neutral"><?php esc_html_e( '0% vs last period', 'opti-behavior' ); ?></div>
                        <div class="stat-history">
                            <canvas id="history-sessions" width="280" height="50"></canvas>
                        </div>
                    </div>
                </div>

                <div class="stat-card" data-stat="pageviews">
                    <div class="stat-icon"><i data-lucide="file-text"></i></div>
                    <div class="stat-content">
                        <div class="stat-value"><span class="stat-value-spinner"></span></div>
                        <div class="stat-label">
                            <?php esc_html_e( 'Page Views', 'opti-behavior' ); ?>
                            <?php opti_behavior_tooltip_e( $tooltips['pageviews']['title'], $tooltips['pageviews']['content'], $tooltips['pageviews']['simple'], $tooltips['pageviews']['example'], array( 'position' => 'bottom', 'size' => 'sm' ) ); ?>
                        </div>
                        <div class="stat-change neutral"><?php esc_html_e( '0% vs last period', 'opti-behavior' ); ?></div>
                        <div class="stat-history">
                            <canvas id="history-pageviews" width="280" height="50"></canvas>
                        </div>
                    </div>
                </div>

                <div class="stat-card" data-stat="avg_session_time">
                    <div class="stat-icon"><i data-lucide="clock"></i></div>
                    <div class="stat-content">
                        <div class="stat-value"><span class="stat-value-spinner"></span></div>
                        <div class="stat-label">
                            <?php esc_html_e( 'Avg. Session Time', 'opti-behavior' ); ?>
                            <?php opti_behavior_tooltip_e( $tooltips['avg_session_time']['title'], $tooltips['avg_session_time']['content'], $tooltips['avg_session_time']['simple'], $tooltips['avg_session_time']['example'], array( 'position' => 'bottom', 'size' => 'sm' ) ); ?>
                        </div>
                        <div class="stat-change neutral"><?php esc_html_e( '0% vs last period', 'opti-behavior' ); ?></div>
                        <div class="stat-history">
                            <canvas id="history-avg-session-time" width="280" height="50"></canvas>
                        </div>
                    </div>
                </div>

                <div class="stat-card" data-stat="avg_scroll_depth">
                    <div class="stat-icon"><i data-lucide="scroll-text"></i></div>
                    <div class="stat-content">
                        <div class="stat-value"><span class="stat-value-spinner"></span></div>
                        <div class="stat-label">
                            <?php esc_html_e( 'Avg. Scroll Depth', 'opti-behavior' ); ?>
                            <?php opti_behavior_tooltip_e( $tooltips['avg_scroll_depth']['title'], $tooltips['avg_scroll_depth']['content'], $tooltips['avg_scroll_depth']['simple'], $tooltips['avg_scroll_depth']['example'], array( 'position' => 'bottom', 'size' => 'sm' ) ); ?>
                        </div>
                        <div class="stat-change neutral"><?php esc_html_e( '0% vs last period', 'opti-behavior' ); ?></div>
                        <div class="stat-history">
                            <canvas id="history-avg-scroll-depth" width="280" height="50"></canvas>
                        </div>
                    </div>
                </div>

                <div class="stat-card" data-stat="bounce_rate">
                    <div class="stat-icon"><i data-lucide="trending-down"></i></div>
                    <div class="stat-content">
                        <div class="stat-value"><span class="stat-value-spinner"></span></div>
                        <div class="stat-label">
                            <?php esc_html_e( 'Bounce Rate', 'opti-behavior' ); ?>
                            <?php opti_behavior_tooltip_e( $tooltips['bounce_rate']['title'], $tooltips['bounce_rate']['content'], $tooltips['bounce_rate']['simple'], $tooltips['bounce_rate']['example'], array( 'position' => 'bottom', 'size' => 'sm' ) ); ?>
                        </div>
                        <div class="stat-change neutral"><?php esc_html_e( '0% vs last period', 'opti-behavior' ); ?></div>
                        <div class="stat-history">
                            <canvas id="history-bounce-rate" width="280" height="50"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
        /**
         * Render dashboard content
         */
        private function render_dashboard_content_view($dashboard_data) {
            // Get tooltips for all widgets
            $tooltips = opti_behavior_get_dashboard_tooltips();
            ?>
            <div class="dashboard-content">
                <div class="dashboard-grid">
                    <!--
                    ╔══════════════════════════════════════════════════════════════════════════════╗
                    ║                        DASHBOARD WIDGET DISPLAY ORDER                        ║
                    ╠══════════════════════════════════════════════════════════════════════════════╣
                    ║  ⚠️ SINGLE SOURCE OF TRUTH - Widget order controlled in PHP (this file)     ║
                    ║  CSS order property is NOT used - widgets appear in natural HTML order      ║
                    ║                                                                              ║
                    ║  DISPLAY ORDER (matching https://optiuser.com EXACTLY):                     ║
                    ║  ┌────────────────────────────────────────────────────────────────────────┐ ║
                    ║  │ LEVEL 1: Stats cards (6 cards)                                        │ ║
                    ║  │ LEVEL 2: Real-time Visitors (2-col) + Real-time Map (1-col)          │ ║
                    ║  │ LEVEL 3: Traffic Overview (3-col span / full-width)                   │ ║
                    ║  │ LEVEL 4: Top Engaged Users (2-col) + Top Pages (1-col)                │ ║
                    ║  │ LEVEL 5: Visitor Activity Heatmap (3-col span / full-width)           │ ║
                    ║  │ LEVEL 6: Traffic Classification + Bot Traffic + User Intent           │ ║
                    ║  │ LEVEL 7: Top Referrers + Top Countries + Browsers                     │ ║
                    ║  │ LEVEL 8: Device Types + Operating Systems + Screen Resolution         │ ║
                    ║  └────────────────────────────────────────────────────────────────────────┘ ║
                    ║                                                                              ║
                    ║  HTML ORDER (below):                                                         ║
                    ║  Real-time Visitors → Real-time Map → Traffic Overview → Top Engaged Users  ║
                    ║  → Top Pages → Visitor Activity Heatmap → Rest in natural order             ║
                    ╚══════════════════════════════════════════════════════════════════════════════╝
                    -->

                    <!-- Real-time Visitors [DISPLAY ORDER: 2] -->
                    <div id="realtime-widget" class="dashboard-widget realtime-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title">
                                <span class="live-badge" aria-label="<?php esc_attr_e( 'Live', 'opti-behavior' ); ?>"><span class="live-dot" aria-hidden="true"></span><?php esc_html_e( 'Live', 'opti-behavior' ); ?></span>
                                <?php esc_html_e( 'Real-time Visitors', 'opti-behavior' ); ?>
                                <span class="visitor-count"><?php echo count($dashboard_data['realtime']['active_visitors']); ?></span>
                                <?php opti_behavior_tooltip_e( $tooltips['realtime_visitors']['title'], $tooltips['realtime_visitors']['content'], $tooltips['realtime_visitors']['simple'], $tooltips['realtime_visitors']['example'] ?? '', array( 'position' => 'bottom' ) ); ?>
                            </h3>
                        </div>
                        <div class="widget-content">
                            <div class="realtime-visitors" id="realtime-visitors">
                                <?php foreach ($dashboard_data['realtime']['active_visitors'] as $visitor): ?>
                                <div class="visitor-item grid">
                                    <span class="visitor-datetime"><?php echo esc_html($visitor['visited_at'] ?? ''); ?><?php if(!empty($visitor['time_ago'])): ?> - <span class="ago"><?php echo esc_html($visitor['time_ago']); ?></span><?php endif; ?></span>
                                    <span class="visitor-flag-country"><span class="visitor-flag"><?php echo $visitor['flag']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Flag emoji is safe, generated from validated ISO country code ?></span> <span class="visitor-location"><?php echo esc_html($visitor['country']); ?></span></span>
                                    <span class="visitor-pageblock"><span class="visitor-title"><?php echo esc_html($visitor['page_title'] ?? ''); ?></span><a class="visitor-url" href="<?php echo esc_url($visitor['current_url'] ?? ''); ?>" target="_blank" rel="noopener"><?php echo esc_html($visitor['current_url'] ?? ''); ?></a></span>
                                    <span class="visitor-ip-col"><?php
									$ip_raw = isset( $visitor['ip'] ) ? trim( (string) $visitor['ip'] ) : '';
									if ( '' === $ip_raw ) {
										echo '<span class="visitor-ip-pill">-</span>';
									} elseif ( 'Anonymous' === $ip_raw ) {
										echo '<span class="visitor-ip-pill visitor-ip-anon"><i data-lucide="shield-check" style="width:13px;height:13px;display:inline-block;vertical-align:-2px;margin-right:3px;"></i>' . esc_html__( 'Anonymous', 'opti-behavior' ) . '</span>';
									} elseif ( false !== strpos( $ip_raw, ':' ) ) {
										echo '<span class="visitor-ip-pill">' . esc_html( substr( $ip_raw, 0, 7 ) . "\xE2\x80\xA6" . substr( $ip_raw, -7 ) ) . '</span>';
									} else {
										echo '<span class="visitor-ip-pill">' . esc_html( $ip_raw ) . '</span>';
									}
								?></span>
                                </div>
                                <?php endforeach; ?>

                                <?php if (empty($dashboard_data['realtime']['active_visitors'])): ?>
                                <div class="optibehavior-empty-state is-visible">
                                    <i data-lucide="users" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                                    <div class="optibehavior-empty-title"><?php esc_html_e( 'No active visitors right now', 'opti-behavior' ); ?></div>
                                    <div class="optibehavior-empty-sub"><?php esc_html_e( 'Traffic updates in real-time.', 'opti-behavior' ); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Real-time Visitor Map -->
                    <div id="realtime-map-widget" class="dashboard-widget realtime-map-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title"><span class="widget-icon"><i data-lucide="map"></i></span> <?php esc_html_e( 'Real-time Visitor Map', 'opti-behavior' ); ?><?php opti_behavior_tooltip_e( $tooltips['realtime_map']['title'], $tooltips['realtime_map']['content'], $tooltips['realtime_map']['simple'], '', array( 'position' => 'bottom' ) ); ?></h3>
                        </div>
                        <div class="widget-content">
                            <div id="realtime-map" class="realtime-map" aria-label="<?php esc_attr_e( 'Interactive world map of live visitors', 'opti-behavior' ); ?>"></div>
                        </div>
                    </div>
                    <!-- Note: Realtime map tooltip styles are enqueued via wp_add_inline_style() in trait-opti-behavior-assets.php -->
                    <!-- Note: Realtime map initialization script is enqueued via wp_add_inline_script() in get_dashboard_scripts() method -->

                    <!-- LEVEL 3: Traffic chart - full width -->
                    <!-- Traffic Overview Chart -->
                    <div id="sessions-chart-widget" class="dashboard-widget chart-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title">
                                <span class="widget-icon"><i data-lucide="chart-spline"></i></span>
                                <?php esc_html_e( 'Traffic Overview', 'opti-behavior' ); ?>
                                <?php opti_behavior_tooltip_e( $tooltips['traffic_overview']['title'], $tooltips['traffic_overview']['content'], $tooltips['traffic_overview']['simple'], $tooltips['traffic_overview']['example'], array( 'position' => 'bottom' ) ); ?>
                            </h3>
                        </div>
                        <div class="widget-content">
                            <div class="chart-container">
                                <canvas id="sessions-chart"></canvas>
                            </div>
                        </div>
                    </div>

                    <!-- LEVEL 4: Engagement metrics - 2 widgets side by side -->
                    <!-- Top Engaged Users -->
                    <?php $optibehavior_tu_nonce = wp_create_nonce('optibehavior_top_users'); $optibehavior_tu_ajax = admin_url('admin-ajax.php'); ?>
                    <div id="top-users-widget" class="dashboard-widget top-users-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title"><span class="widget-icon"><i data-lucide="user-check"></i></span> <?php echo esc_html__('Top Engaged Users','opti-behavior'); ?><?php opti_behavior_tooltip_e( $tooltips['top_engaged_users']['title'], $tooltips['top_engaged_users']['content'], $tooltips['top_engaged_users']['simple'], $tooltips['top_engaged_users']['example'], array( 'position' => 'bottom' ) ); ?></h3>
                        </div>
                        <div class="widget-content">
                            <div class="optibehavior-table-wrap" style="display: none;">
                                <table class="widefat striped">
                                    <thead>
                                    <tr>
                                        <th>#</th>
                                        <th><?php echo esc_html__('Visitor','opti-behavior'); ?></th>
                                        <th title="<?php echo esc_attr__('Average sessions per active day', 'opti-behavior'); ?>"><?php echo esc_html__('Daily Freq', 'opti-behavior'); ?></th>
                                        <th title="<?php echo esc_attr__('Average time per session', 'opti-behavior'); ?>"><?php echo esc_html__('Avg Session', 'opti-behavior'); ?></th>
                                        <th><?php echo esc_html__('Total Time','opti-behavior'); ?></th>
                                        <th><?php echo esc_html__('Sessions','opti-behavior'); ?></th>
                                        <th title="<?php echo esc_attr__('Pages per session', 'opti-behavior'); ?>"><?php echo esc_html__('Pages/Sess', 'opti-behavior'); ?></th>
                                        <th><?php echo esc_html__('Country','opti-behavior'); ?></th>
                                        <th><?php echo esc_html__('Last Seen','opti-behavior'); ?></th>
                                    </tr>
                                    </thead>
                                    <tbody id="optibehavior-tu2-body">
                                    </tbody>
                                </table>
                            </div>
                            <div class="optibehavior-empty-state is-visible">
                                <i data-lucide="user-check" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                                <div class="optibehavior-empty-title"><?php esc_html_e( 'No engaged users for this period', 'opti-behavior' ); ?></div>
                                <div class="optibehavior-empty-sub"><?php esc_html_e( 'As visitors engage more, you\'ll see them ranked here.', 'opti-behavior' ); ?></div>
                            </div>
                        </div>
                    </div>
                    <!-- Note: Top users loading script is now properly enqueued via wp_add_inline_script() in get_dashboard_scripts() method -->

                    <!-- Top Pages -->
                    <div id="top-pages-widget" class="dashboard-widget pages-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title">
                                <i data-lucide="file-text"></i>
                                <?php esc_html_e( 'Top Pages', 'opti-behavior' ); ?>
                                <?php opti_behavior_tooltip_e( $tooltips['top_pages']['title'], $tooltips['top_pages']['content'], $tooltips['top_pages']['simple'], '', array( 'position' => 'bottom' ) ); ?>
                            </h3>
                        </div>
                        <div class="widget-content">
                            <div class="top-pages">
                                <?php if ( empty( $dashboard_data['charts']['top_pages'] ) ) : ?>
                                    <div class="optibehavior-empty-state is-visible">
                                        <svg viewBox='0 0 24 24' fill='none' stroke='#9ca3af' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'><path d='M4 3h14a2 2 0 0 1 2 2v14l-4-4H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z'/></svg>
                                        <div class="optibehavior-empty-title"><?php esc_html_e( 'No page views yet', 'opti-behavior' ); ?></div>
                                        <div class="optibehavior-empty-sub"><?php esc_html_e( 'Once visitors view pages, you will see them here.', 'opti-behavior' ); ?></div>
                                    </div>
                                <?php else : ?>
                                    <?php foreach ( $dashboard_data['charts']['top_pages'] as $page ) : ?>
                                        <?php
                                        $title              = isset( $page['title'] ) ? (string) $page['title'] : '';
                                        $url                = isset( $page['url'] ) ? (string) $page['url'] : '';
                                        $views              = isset( $page['views'] ) ? (int) $page['views'] : 0;
                                        $sessions           = isset( $page['sessions'] ) ? (int) $page['sessions'] : 0;
                                        $clicks             = isset( $page['clicks'] ) ? (int) $page['clicks'] : 0;
                                        $views_change       = isset( $page['views_change'] ) ? (int) $page['views_change'] : 0;
                                        $views_trend        = isset( $page['views_trend'] ) ? (string) $page['views_trend'] : 'neutral';
                                        $clicks_change      = isset( $page['clicks_change'] ) ? (int) $page['clicks_change'] : 0;
                                        $clicks_trend       = isset( $page['clicks_trend'] ) ? (string) $page['clicks_trend'] : 'neutral';
                                        $pc_heatmap_url     = isset( $page['pc_heatmap'] ) ? $page['pc_heatmap'] : '';
                                        $mobile_heatmap_url = isset( $page['mobile_heatmap'] ) ? $page['mobile_heatmap'] : '';

                                        $views_trend_class = 'neutral';
                                        $views_arrow       = '–';
                                        if ( 'up' === $views_trend ) {
                                            $views_trend_class = 'positive';
                                            $views_arrow       = '↑';
                                        } elseif ( 'down' === $views_trend ) {
                                            $views_trend_class = 'negative';
                                            $views_arrow       = '↓';
                                        }

                                        $clicks_trend_class = 'neutral';
                                        $clicks_arrow       = '–';
                                        if ( 'up' === $clicks_trend ) {
                                            $clicks_trend_class = 'positive';
                                            $clicks_arrow       = '↑';
                                        } elseif ( 'down' === $clicks_trend ) {
                                            $clicks_trend_class = 'negative';
                                            $clicks_arrow       = '↓';
                                        }

                                        $views_change_display  = abs( $views_change );
                                        $clicks_change_display = abs( $clicks_change );
                                        ?>
                                        <div class="page-item">
                                            <div class="page-left">
                                                <div class="page-title-row">
                                                    <div class="page-title" title="<?php echo esc_attr( $title ); ?>">
                                                        <?php echo esc_html( $title ); ?>
                                                    </div>
                                                    <a class="page-url" href="<?php echo esc_url( $url ); ?>" target="_blank" rel="noopener noreferrer" title="<?php echo esc_attr( $url ); ?>">
                                                        <?php echo esc_html( $url ); ?>
                                                    </a>
                                                </div>
                                            </div>
                                            <div class="page-right">
                                                <div class="page-metrics">
                                                    <div class="metric metric-views" title="<?php echo esc_attr__( 'Heatmap sessions', 'opti-behavior' ); ?>">
                                                        <i class="metric-icon" data-lucide="flame"></i>
                                                        <span class="metric-value"><?php echo esc_html( number_format_i18n( $sessions ) ); ?></span>
                                                        <span class="metric-change <?php echo esc_attr( $views_trend_class ); ?>">
                                                            <span class="metric-arrow"><?php echo esc_html( $views_arrow ); ?></span>
                                                            <span class="metric-percent"><?php echo esc_html( $views_change_display ); ?>%</span>
                                                        </span>
                                                    </div>
                                                    <div class="metric metric-clicks" title="<?php echo esc_attr__( 'Clicks', 'opti-behavior' ); ?>">
                                                        <i class="metric-icon" data-lucide="mouse-pointer-click"></i>
                                                        <span class="metric-value"><?php echo esc_html( number_format_i18n( $clicks ) ); ?></span>
                                                        <span class="metric-change <?php echo esc_attr( $clicks_trend_class ); ?>">
                                                            <span class="metric-arrow"><?php echo esc_html( $clicks_arrow ); ?></span>
                                                            <span class="metric-percent"><?php echo esc_html( $clicks_change_display ); ?>%</span>
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Visitor Heatmap Widget (LEVEL 5) -->
                    <div id="visitor-heatmap-widget" class="dashboard-widget visitor-heatmap-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title">
                                <span class="widget-icon"><i data-lucide="flame"></i></span>
                                <?php echo esc_html__( 'Visitor Activity Heatmap', 'opti-behavior' ); ?>
                                <?php opti_behavior_tooltip_e( $tooltips['visitor_heatmap']['title'], $tooltips['visitor_heatmap']['content'], $tooltips['visitor_heatmap']['simple'], $tooltips['visitor_heatmap']['example'], array( 'position' => 'bottom' ) ); ?>
                            </h3>
                        </div>
                        <div class="widget-content">
                            <div id="visitor-heatmap-container" class="visitor-heatmap-container"></div>
                        </div>
                    </div>

                    <!-- LEVEL 5.5: New vs Returning Visitors + Visited Directories + New Registered Users -->
                    <!-- New vs Returning Visitors Widget -->
                    <?php
                    if ( isset( $dashboard_data['new_vs_returning'] ) ) {
                        $this->render_new_vs_returning_widget( $dashboard_data['new_vs_returning'] );
                    }
                    ?>

                    <!-- Visited Directories Widget -->
                    <?php
                    if ( isset( $dashboard_data['visited_directories'] ) ) {
                        $this->render_visited_directories_widget( $dashboard_data['visited_directories'] );
                    }
                    ?>

                    <!-- New Registered Users Widget -->
                    <?php
                    if ( isset( $dashboard_data['new_registered_users'] ) ) {
                        $this->render_new_registered_users_widget( $dashboard_data['new_registered_users'] );
                    }
                    ?>

                    <!-- LEVEL 6: Traffic Classification + Bot Traffic + User Intent -->
                    <!-- Traffic Classification Widget -->
                    <?php
                    if ( isset( $dashboard_data['traffic_classification'] ) ) {
                        $this->render_traffic_classification_widget( $dashboard_data['traffic_classification'] );
                    }
                    ?>

                    <!-- Bot Traffic Widget -->
                    <?php
                    if ( isset( $dashboard_data['bot_traffic'] ) ) {
                        $this->render_bot_traffic_widget( $dashboard_data['bot_traffic'] );
                    }
                    ?>

                    <!-- User Intent Widget -->
                    <div id="user-intent-widget" class="dashboard-widget user-intent-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title">
                                <span class="widget-icon"><i data-lucide="target"></i></span>
                                <?php esc_html_e( 'User Intent', 'opti-behavior' ); ?>
                                <?php opti_behavior_tooltip_e( $tooltips['user_intent']['title'], $tooltips['user_intent']['content'], $tooltips['user_intent']['simple'], $tooltips['user_intent']['example'], array( 'position' => 'bottom' ) ); ?>
                            </h3>
                        </div>
                        <div class="widget-content">
                            <?php $this->render_user_intent_chart(); ?>
                        </div>
                    </div>

                    <!-- LEVEL 7: Top Referrers + Top Countries + Browsers -->
                    <!-- Top Referrers -->
                    <div id="referrers-widget" class="dashboard-widget referrers-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title"><span class="widget-icon"><i data-lucide="link"></i></span> <?php esc_html_e( 'Referrers', 'opti-behavior' ); ?><?php opti_behavior_tooltip_e( $tooltips['referrers']['title'], $tooltips['referrers']['content'], $tooltips['referrers']['simple'], $tooltips['referrers']['example'] ?? '', array( 'position' => 'bottom' ) ); ?></h3>
                        </div>
                        <div class="widget-content">
                            <div class="referrers-table-container" style="display: none;">
                                <table class="referrers-table">
                                    <tbody id="referrers-table-body">
                                    </tbody>
                                </table>
                            </div>
                            <div class="optibehavior-empty-state is-visible">
                                <i data-lucide="link" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                                <div class="optibehavior-empty-title"><?php esc_html_e( 'No referrer data available', 'opti-behavior' ); ?></div>
                                <div class="optibehavior-empty-sub"><?php esc_html_e( 'Try broadening the date range or check back later.', 'opti-behavior' ); ?></div>
                            </div>
                        </div>
                    </div>

                    <!-- Top Countries Widget -->
                    <div id="countries-widget" class="dashboard-widget countries-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title"><span class="widget-icon"><i data-lucide="globe"></i></span> <?php esc_html_e( 'Countries', 'opti-behavior' ); ?><?php opti_behavior_tooltip_e( $tooltips['countries']['title'], $tooltips['countries']['content'], $tooltips['countries']['simple'], '', array( 'position' => 'bottom' ) ); ?></h3>
                        </div>
                        <div class="widget-content">
                            <div class="countries-table-container">
                                <table class="countries-table">
                                    <tbody id="countries-table-body">
                                        <tr class="loading-row">
                                            <td colspan="2" class="loading-cell">
                                                <div class="optibehavior-empty-state">
                                                    <i data-lucide="globe" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                                                    <div class="optibehavior-empty-title"><?php esc_html_e( 'Loading countries...', 'opti-behavior' ); ?></div>
                                                </div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Browsers Widget -->
                    <div id="browsers-widget" class="dashboard-widget browsers-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title"><span class="widget-icon"><i data-lucide="compass"></i></span> <?php esc_html_e( 'Browsers', 'opti-behavior' ); ?><?php opti_behavior_tooltip_e( $tooltips['browsers']['title'], $tooltips['browsers']['content'], $tooltips['browsers']['simple'], $tooltips['browsers']['example'], array( 'position' => 'bottom' ) ); ?></h3>
                        </div>
                        <div class="widget-content">
                            <div class="browsers-table-container" style="display: none;">
                                <table class="browsers-table">
                                    <tbody id="browsers-table-body">
                                    </tbody>
                                </table>
                            </div>
                            <div class="optibehavior-empty-state is-visible">
                                <i data-lucide="compass" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                                <div class="optibehavior-empty-title"><?php esc_html_e( 'No browser data available', 'opti-behavior' ); ?></div>
                                <div class="optibehavior-empty-sub"><?php esc_html_e( 'Try broadening the date range or check back later.', 'opti-behavior' ); ?></div>
                            </div>
                        </div>
                    </div>

                    <!-- LEVEL 8: Device Types + Operating Systems + Screen Resolution -->

                    <!-- Device Types Widget -->
                    <div id="device-types-widget" class="dashboard-widget device-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title"><span class="widget-icon"><i data-lucide="smartphone"></i></span> <?php esc_html_e( 'Device Types', 'opti-behavior' ); ?><?php opti_behavior_tooltip_e( $tooltips['device_types']['title'], $tooltips['device_types']['content'], $tooltips['device_types']['simple'], '', array( 'position' => 'bottom' ) ); ?></h3>
                        </div>
                        <div class="widget-content compact">
                            <?php $this->render_device_types_chart(); ?>
                        </div>
                    </div>

                    <!-- Operating Systems Widget -->
                    <div id="operating-systems-widget" class="dashboard-widget os-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title"><span class="widget-icon"><i data-lucide="monitor"></i></span> <?php esc_html_e( 'Operating Systems', 'opti-behavior' ); ?><?php opti_behavior_tooltip_e( $tooltips['operating_systems']['title'], $tooltips['operating_systems']['content'], $tooltips['operating_systems']['simple'], '', array( 'position' => 'bottom' ) ); ?></h3>
                        </div>
                        <div class="widget-content compact">
                            <?php $this->render_operating_systems_chart(); ?>
                        </div>
                    </div>

                    <!-- Screen Resolution Widget (LEVEL 15) -->
                    <div id="screen-resolution-widget" class="dashboard-widget resolution-widget">
                        <?php opti_behavior_render_widget_loading(); ?>
                        <div class="widget-header">
                            <h3 class="widget-title"><span class="widget-icon"><i data-lucide="monitor-dot"></i></span> <?php echo esc_html__( 'Screen Resolution', 'opti-behavior' ); ?><?php opti_behavior_tooltip_e( $tooltips['screen_resolution']['title'], $tooltips['screen_resolution']['content'], $tooltips['screen_resolution']['simple'], $tooltips['screen_resolution']['example'], array( 'position' => 'bottom' ) ); ?></h3>
                        </div>
                        <div class="widget-content compact">
                            <?php $this->render_screen_resolution_chart(); ?>
                        </div>
                    </div>
                    <!-- This widget will be added in the next task -->

                </div>
            </div>
            <?php
        }

        /**
         * Render user intent pie chart
         */
        private function render_user_intent_chart() {
            $intent_data = $this->get_user_intent_data();
            $has_data = $intent_data['total_sessions'] > 0;

            if (!$has_data) {
                // Show empty state when no data is available
                ?>
                <div class="optibehavior-empty-state is-visible">
                    <i data-lucide="target" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                    <div class="optibehavior-empty-title"><?php esc_html_e( 'No data available', 'opti-behavior' ); ?></div>
                    <div class="optibehavior-empty-sub"><?php esc_html_e( 'Try broadening the date range or check back later.', 'opti-behavior' ); ?></div>
                </div>
                <?php
                return;
            }
            ?>
            <div class="user-intent-chart-container">
                <canvas id="user-intent-chart" width="300" height="300"></canvas>
                <table class="user-intent-legend">
                    <tbody id="user-intent-legend-body">
                        <!-- Populated by JavaScript -->
                    </tbody>
                </table>
            </div>
            <!-- Note: User intent chart script is now properly enqueued via wp_add_inline_script() in get_dashboard_scripts() method -->
            <?php
        }

        /**
         * Get user intent data for the chart
         */
        private function get_user_intent_data($start_date = null, $end_date = null) {
            global $wpdb;

            // Use provided dates or default to last 30 days
            if (!$start_date || !$end_date) {
                $end_date = gmdate('Y-m-d H:i:s');
                $start_date = gmdate('Y-m-d H:i:s', strtotime('-30 days'));
            }

            // Check cache first (5-minute TTL for performance)
            $exclude_spam = $this->is_spam_excluded();
            $cache_key = 'opti_behavior_user_intent_' . md5( $start_date . $end_date . ( $exclude_spam ? '1' : '0' ) );
            $cached = get_transient( $cache_key );
            if ( false !== $cached ) {
                return $cached;
            }

            // Get spam exclusion clause
            $spam_clause = $this->get_spam_exclusion_clause( 's' );

            // Get user-defined intent rules from settings
            $intent_rules = get_option( 'opti_behavior_intent_rules', array(
                'low_intent' => array(
                    'time_spent' => 10,
                    'clicks' => 1,
                    'scroll_depth' => 25,
                ),
                'medium_intent' => array(
                    'time_spent' => 30,
                    'clicks' => 3,
                    'scroll_depth' => 50,
                ),
                'high_intent' => array(
                    'time_spent' => 60,
                    'clicks' => 5,
                    'scroll_depth' => 75,
                ),
            ) );

            $low_rules = $intent_rules['low_intent'];
            $medium_rules = $intent_rules['medium_intent'];
            $high_rules = $intent_rules['high_intent'];

            // Calculate previous period
            $duration = max(1, strtotime($end_date) - strtotime($start_date) + 1);
            $prev_end = gmdate('Y-m-d H:i:s', strtotime($start_date) - 1);
            $prev_start = gmdate('Y-m-d H:i:s', strtotime($start_date) - $duration);

            // Get current period session data with scroll depth
            // Using LIMIT 10000 to sample data for performance (prevents timeout on large datasets)
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Dynamic SQL with spam clause
            $sql = $wpdb->prepare(
                "SELECT
                    s.id,
                    s.duration,
                    COUNT(e.id) as interaction_count,
                    COUNT(CASE WHEN e.event IN (16, 17) THEN 1 END) as click_count,
                    MAX(pv.scroll_depth) as max_scroll_depth
                FROM {$wpdb->prefix}optibehavior_sessions s
                LEFT JOIN {$wpdb->prefix}optibehavior_events e ON s.id = e.session_id
                LEFT JOIN {$wpdb->prefix}optibehavior_pageviews pv ON s.id = pv.session_id
                WHERE s.start_time >= %s AND s.start_time <= %s{$spam_clause}
                GROUP BY s.id
                LIMIT 10000",
                $start_date,
                $end_date
            );

            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Dynamic SQL with proper prepare; analytics queries.
            $sessions = $wpdb->get_results($sql);

            // Get previous period session data
            // Using LIMIT 10000 to sample data for performance (prevents timeout on large datasets)
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Dynamic SQL with spam clause
            $prev_sql = $wpdb->prepare(
                "SELECT
                    s.id,
                    s.duration,
                    COUNT(e.id) as interaction_count,
                    COUNT(CASE WHEN e.event IN (16, 17) THEN 1 END) as click_count,
                    MAX(pv.scroll_depth) as max_scroll_depth
                FROM {$wpdb->prefix}optibehavior_sessions s
                LEFT JOIN {$wpdb->prefix}optibehavior_events e ON s.id = e.session_id
                LEFT JOIN {$wpdb->prefix}optibehavior_pageviews pv ON s.id = pv.session_id
                WHERE s.start_time >= %s AND s.start_time <= %s{$spam_clause}
                GROUP BY s.id
                LIMIT 10000",
                $prev_start,
                $prev_end
            );

            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Dynamic SQL with proper prepare; analytics queries.
            $prev_sessions = $wpdb->get_results($prev_sql);

            // Current period classification using user-defined rules
            $low_intent = 0;
            $medium_intent = 0;
            $high_intent = 0;
            $total_sessions = count($sessions);

            foreach ($sessions as $session) {
                $duration = (int) $session->duration;
                $clicks = (int) $session->click_count;
                $scroll_depth = (int) ($session->max_scroll_depth ?? 0);

                // Classify based on user-defined rules using scoring system
                // Count how many high intent criteria are met (need at least 2 out of 3)
                $high_score = 0;
                if ($duration >= $high_rules['time_spent']) $high_score++;
                if ($clicks >= $high_rules['clicks']) $high_score++;
                if ($scroll_depth >= $high_rules['scroll_depth']) $high_score++;

                // High intent: At least 2 out of 3 criteria meet high thresholds
                if ($high_score >= 2) {
                    $high_intent++;
                }
                else {
                    // Count how many medium intent criteria are met (need at least 2 out of 3)
                    $medium_score = 0;
                    if ($duration >= $medium_rules['time_spent']) $medium_score++;
                    if ($clicks >= $medium_rules['clicks']) $medium_score++;
                    if ($scroll_depth >= $medium_rules['scroll_depth']) $medium_score++;

                    // Medium intent: At least 2 out of 3 criteria meet medium thresholds
                    if ($medium_score >= 2) {
                        $medium_intent++;
                    }
                    // Low intent: Does not meet at least 2 medium thresholds
                    else {
                        $low_intent++;
                    }
                }
            }

            // Previous period classification
            $prev_low_intent = 0;
            $prev_medium_intent = 0;
            $prev_high_intent = 0;

            foreach ($prev_sessions as $session) {
                $duration = (int) $session->duration;
                $clicks = (int) $session->click_count;
                $scroll_depth = (int) ($session->max_scroll_depth ?? 0);

                // Use same classification logic for previous period
                // Count how many high intent criteria are met (need at least 2 out of 3)
                $high_score = 0;
                if ($duration >= $high_rules['time_spent']) $high_score++;
                if ($clicks >= $high_rules['clicks']) $high_score++;
                if ($scroll_depth >= $high_rules['scroll_depth']) $high_score++;

                // High intent: At least 2 out of 3 criteria meet high thresholds
                if ($high_score >= 2) {
                    $prev_high_intent++;
                }
                else {
                    // Count how many medium intent criteria are met (need at least 2 out of 3)
                    $medium_score = 0;
                    if ($duration >= $medium_rules['time_spent']) $medium_score++;
                    if ($clicks >= $medium_rules['clicks']) $medium_score++;
                    if ($scroll_depth >= $medium_rules['scroll_depth']) $medium_score++;

                    // Medium intent: At least 2 out of 3 criteria meet medium thresholds
                    if ($medium_score >= 2) {
                        $prev_medium_intent++;
                    }
                    // Low intent: Does not meet at least 2 medium thresholds
                    else {
                        $prev_low_intent++;
                    }
                }
            }

            // Calculate percentages
            if ($total_sessions > 0) {
                $low_percentage = round(($low_intent / $total_sessions) * 100, 1);
                $medium_percentage = round(($medium_intent / $total_sessions) * 100, 1);
                $high_percentage = round(($high_intent / $total_sessions) * 100, 1);
            } else {
                $low_percentage = $medium_percentage = $high_percentage = 0;
            }

            $result = array(
                'low_sessions' => $low_intent,
                'medium_sessions' => $medium_intent,
                'high_sessions' => $high_intent,
                'low_percentage' => $low_percentage,
                'medium_percentage' => $medium_percentage,
                'high_percentage' => $high_percentage,
                'total_sessions' => $total_sessions,
                'prev_low_sessions' => $prev_low_intent,
                'prev_medium_sessions' => $prev_medium_intent,
                'prev_high_sessions' => $prev_high_intent
            );

            // Cache for 15 minutes for dashboard performance
            set_transient( $cache_key, $result, 900 );

            return $result;
        }

        /**
         * Render device types pie chart
         */
        private function render_device_types_chart() {
            $device_data = $this->get_device_types_data_for_chart();
            $has_data = $device_data['total_sessions'] > 0;
            ?>
            <div class="user-intent-chart-container">
                <canvas id="device-types-pie" width="300" height="300"></canvas>
                <table class="device-types-legend">
                    <tbody id="device-types-legend-body">
                        <!-- Populated by JavaScript -->
                    </tbody>
                </table>
            </div>
            <!-- Note: Device types chart script is now properly enqueued via wp_add_inline_script() in get_dashboard_scripts() method -->
            <?php
        }

        /**
         * Get device types data formatted for the chart
         */
        private function get_device_types_data_for_chart() {
            // Get the current date range from dashboard data
            // phpcs:disable WordPress.Security.NonceVerification.Recommended -- GET parameters used for filtering dashboard view (read-only operation)
            // phpcs:disable WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- wp_unslash not needed for sanitize_text_field
            $period = isset($_GET['period']) ? sanitize_text_field($_GET['period']) : 'last7days';
            $start_q = isset($_GET['start_date']) ? sanitize_text_field($_GET['start_date']) : null;
            $end_q = isset($_GET['end_date']) ? sanitize_text_field($_GET['end_date']) : null;
            // phpcs:enable WordPress.Security.NonceVerification.Recommended
            // phpcs:enable WordPress.Security.ValidatedSanitizedInput.MissingUnslash

            // Get date range
            $date_range = $this->get_date_range($period, $start_q, $end_q);
            $start_date = $date_range['start'];
            $end_date = $date_range['end'];

            // Get device types data
            $device_types = $this->get_device_types_data($start_date, $end_date);

            $desktop_sessions = 0;
            $mobile_sessions = 0;
            $tablet_sessions = 0;
            $total_sessions = 0;

            foreach ($device_types as $device) {
                $count = (int) $device['count'];
                $total_sessions += $count;

                switch ($device['name']) {
                    case 'Desktop':
                        $desktop_sessions = $count;
                        break;
                    case 'Mobile':
                        $mobile_sessions = $count;
                        break;
                    case 'Tablet':
                        $tablet_sessions = $count;
                        break;
                }
            }

            // Calculate percentages
            $desktop_percentage = $total_sessions > 0 ? round(($desktop_sessions / $total_sessions) * 100, 1) : 0;
            $mobile_percentage = $total_sessions > 0 ? round(($mobile_sessions / $total_sessions) * 100, 1) : 0;
            $tablet_percentage = $total_sessions > 0 ? round(($tablet_sessions / $total_sessions) * 100, 1) : 0;

            return array(
                'desktop_sessions' => $desktop_sessions,
                'mobile_sessions' => $mobile_sessions,
                'tablet_sessions' => $tablet_sessions,
                'desktop_percentage' => $desktop_percentage,
                'mobile_percentage' => $mobile_percentage,
                'tablet_percentage' => $tablet_percentage,
                'total_sessions' => $total_sessions
            );
        }

        /**
         * Render operating systems pie chart
         */
        private function render_operating_systems_chart() {
            $os_data = $this->get_operating_systems_data_for_chart();
            $has_data = $os_data['total_sessions'] > 0;
            ?>
            <div class="user-intent-chart-container">
                <canvas id="operating-systems-chart" width="300" height="300"></canvas>
                <div class="os-table-container">
                    <table class="os-legend">
                        <tbody id="os-legend-body">
                            <!-- Populated by JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>
            <!-- Note: Operating systems chart script is now properly enqueued via wp_add_inline_script() in get_dashboard_scripts() method -->
            <?php
        }

        /**
         * Get operating systems data formatted for the chart
         */
        private function get_operating_systems_data_for_chart() {
            // Nonce verification not required for GET parameters used for read-only data filtering
            // This method is called from admin pages protected by 'manage_options' capability
            // phpcs:disable WordPress.Security.NonceVerification.Recommended -- GET parameters used for filtering dashboard view (read-only operation)
            // phpcs:disable WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- wp_unslash not needed for sanitize_text_field
            $period = isset($_GET['period']) ? sanitize_text_field($_GET['period']) : 'last7days';
            $start_q = isset($_GET['start_date']) ? sanitize_text_field($_GET['start_date']) : null;
            $end_q = isset($_GET['end_date']) ? sanitize_text_field($_GET['end_date']) : null;
            // phpcs:enable WordPress.Security.NonceVerification.Recommended
            // phpcs:enable WordPress.Security.ValidatedSanitizedInput.MissingUnslash

            // Get date range
            $date_range = $this->get_date_range($period, $start_q, $end_q);
            $start_date = $date_range['start'];
            $end_date = $date_range['end'];

            // Get operating systems data
            $operating_systems = $this->get_operating_systems_data($start_date, $end_date);

            $total_sessions = 0;
            $os_counts = array();

            // Count sessions for each OS
            foreach ($operating_systems as $os) {
                $count = (int) $os['count'];
                $total_sessions += $count;
                $os_counts[$os['os']] = $count;
            }

            // Define OS colors and CSS classes
            $os_config = array(
                'Windows' => array('color' => '#0078d4', 'css_class' => 'windows-os'),
                'macOS' => array('color' => '#000000', 'css_class' => 'macos-os'),
                'iOS' => array('color' => '#007aff', 'css_class' => 'ios-os'),
                'Android' => array('color' => '#3ddc84', 'css_class' => 'android-os'),
                'Linux' => array('color' => '#fcc624', 'css_class' => 'linux-os'),
                'ChromeOS' => array('color' => '#4285f4', 'css_class' => 'chromeos-os'),
            );

            // Default colors for unknown OS
            $default_colors = array('#6b7280', '#9ca3af', '#d1d5db', '#e5e7eb');
            $color_index = 0;

            $os_list = array();
            foreach ($os_counts as $os_name => $sessions) {
                if (isset($os_config[$os_name])) {
                    $color = $os_config[$os_name]['color'];
                    $css_class = $os_config[$os_name]['css_class'];
                } else {
                    $color = $default_colors[$color_index % count($default_colors)];
                    $css_class = 'unknown-os';
                    $color_index++;
                }

                $percentage = $total_sessions > 0 ? round(($sessions / $total_sessions) * 100, 1) : 0;

                $os_list[] = array(
                    'name' => $os_name,
                    'sessions' => $sessions,
                    'percentage' => $percentage,
                    'color' => $color,
                    'css_class' => $css_class
                );
            }

            // Sort by session count (descending)
            usort($os_list, function($a, $b) {
                return $b['sessions'] - $a['sessions'];
            });

            return array(
                'os_list' => $os_list,
                'total_sessions' => $total_sessions
            );
        }

        /**
         * Render traffic classification widget
         *
         * @param array $data Traffic classification data.
         */
        private function render_traffic_classification_widget( $data ) {
            $has_data = ! empty( $data ) && isset( $data['total'] ) && $data['total'] > 0;

            ?>
            <div id="traffic-classification-widget" class="dashboard-widget traffic-classification-widget">
                <?php opti_behavior_render_widget_loading(); ?>
                <?php $tooltips = opti_behavior_get_dashboard_tooltips(); ?>
                <div class="widget-header">
                    <h3 class="widget-title">
                        <span class="widget-icon"><i data-lucide="traffic-cone"></i></span>
                        <?php esc_html_e( 'Traffic Classification', 'opti-behavior' ); ?>
                        <?php opti_behavior_tooltip_e( $tooltips['traffic_classification']['title'], $tooltips['traffic_classification']['content'], $tooltips['traffic_classification']['simple'], $tooltips['traffic_classification']['example'], array( 'position' => 'bottom' ) ); ?>
                    </h3>
                </div>
                <div class="widget-content">
                    <div class="optibehavior-empty-state <?php echo $has_data ? '' : 'is-visible'; ?>">
                        <i data-lucide="traffic-cone" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                        <div class="optibehavior-empty-title"><?php esc_html_e( 'No data available', 'opti-behavior' ); ?></div>
                        <div class="optibehavior-empty-sub"><?php esc_html_e( 'Try broadening the date range or check back later.', 'opti-behavior' ); ?></div>
                    </div>
                    <div class="user-intent-chart-container" style="<?php echo $has_data ? '' : 'display: none;'; ?>">
                        <canvas id="traffic-classification-chart" width="300" height="300"></canvas>
                        <table class="traffic-classification-legend">
                            <tbody id="traffic-classification-legend-body">
                                <!-- Populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <!-- Note: Traffic classification chart script is now properly enqueued via wp_add_inline_script() in get_dashboard_scripts() method -->
            <?php
        }

        /**
         * Render bot traffic widget
         *
         * @param array $data Bot traffic data.
         */
        private function render_bot_traffic_widget( $data ) {
            $has_data = ! empty( $data ) && isset( $data['total'] ) && $data['total'] > 0;

            $total = $has_data ? intval( $data['total'] ) : 0;
            $bots = $has_data && isset( $data['bots'] ) ? $data['bots'] : array();
            $change_pct = $has_data && isset( $data['change_percentage'] ) ? intval( $data['change_percentage'] ) : 0;
            ?>
            <div id="bot-traffic-widget" class="dashboard-widget bot-traffic-widget">
                <?php opti_behavior_render_widget_loading(); ?>
                <?php $tooltips = opti_behavior_get_dashboard_tooltips(); ?>
                <div class="widget-header">
                    <h3 class="widget-title">
                        <span class="widget-icon"><i data-lucide="bot"></i></span>
                        <?php esc_html_e( 'Bot Traffic', 'opti-behavior' ); ?>
                        <?php opti_behavior_tooltip_e( $tooltips['bot_traffic']['title'], $tooltips['bot_traffic']['content'], $tooltips['bot_traffic']['simple'], $tooltips['bot_traffic']['example'], array( 'position' => 'bottom' ) ); ?>
                    </h3>
                    <div class="widget-meta" id="bot-traffic-meta" style="<?php echo $has_data ? '' : 'display: none;'; ?>">
                        <span class="total-count"><span id="bot-traffic-total"><?php echo esc_html( number_format( $total ) ); ?></span> <?php esc_html_e( 'visits', 'opti-behavior' ); ?></span>
                        <span class="change-indicator <?php echo $change_pct > 0 ? 'positive' : 'negative'; ?>" id="bot-traffic-change" style="<?php echo $change_pct !== 0 ? '' : 'display: none;'; ?>">
                            <span id="bot-traffic-change-value"><?php echo $change_pct > 0 ? '↑' : '↓'; ?> <?php echo esc_html( abs( $change_pct ) ); ?>%</span>
                        </span>
                    </div>
                </div>
                <div class="widget-content">
                    <div class="optibehavior-empty-state <?php echo $has_data ? '' : 'is-visible'; ?>">
                        <i data-lucide="bot" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                        <div class="optibehavior-empty-title"><?php esc_html_e( 'No bot visits detected', 'opti-behavior' ); ?></div>
                        <div class="optibehavior-empty-sub"><?php esc_html_e( 'Bot visits will appear here when detected.', 'opti-behavior' ); ?></div>
                    </div>
                    <div class="bot-traffic-list" id="bot-traffic-list" style="<?php echo $has_data ? '' : 'display: none;'; ?>">
                        <?php if ( $has_data ) : ?>
                            <?php foreach ( $bots as $bot_type => $bot_data ) : ?>
                                <?php
                                $count      = intval( $bot_data['count'] );
                                $percentage = floatval( $bot_data['percentage'] );
                                $bot_label  = $this->get_bot_label( $bot_type );
                                $bot_icon   = $this->get_bot_icon( $bot_type );
                                ?>
                                <div class="bot-item ob-metric-row">
                                    <div class="bot-info ob-metric-main">
                                        <span class="bot-icon"><?php echo wp_kses( $bot_icon, array( 'i' => array( 'data-lucide' => true, 'class' => true ) ) ); ?></span>
                                        <span class="bot-label ob-metric-label"><?php echo esc_html( $bot_label ); ?></span>
                                    </div>
                                    <div class="bot-stats ob-metric-values">
                                        <span class="visitor-count"><?php echo esc_html( number_format( $count ) ); ?></span>
                                        <span class="visitor-percentage"><?php echo esc_html( $percentage ); ?>%</span>
                                        <span class="visitor-trend trend-up">
                                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <path d="M5 12l5-5 5 5"></path>
                                            </svg>
                                            100%
                                        </span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        <!-- Will be populated by JavaScript when data loads asynchronously -->
                    </div>
                </div>
            </div>
            <?php
        }

        /**
         * Get bot label from bot type
         *
         * @param string $bot_type Bot type.
         * @return string Bot label.
         */
        private function get_bot_label( $bot_type ) {
            $labels = array(
                'googlebot'       => 'Googlebot',
                'googlebot-image' => 'Googlebot Image',
                'googlebot-news'  => 'Googlebot News',
                'bingbot'         => 'Bingbot',
                'bingpreview'     => 'Bing Preview',
                'yahoo'           => 'Yahoo Slurp',
                'duckduckbot'     => 'DuckDuckBot',
                'baiduspider'     => 'Baidu Spider',
                'yandexbot'       => 'Yandex Bot',
                'facebookbot'     => 'Facebook Bot',
                'twitterbot'      => 'Twitter Bot',
                'linkedinbot'     => 'LinkedIn Bot',
                'pinterestbot'    => 'Pinterest Bot',
                'whatsapp'        => 'WhatsApp',
                'ahrefsbot'       => 'Ahrefs Bot',
                'semrushbot'      => 'SEMrush Bot',
                'mj12bot'         => 'Majestic Bot',
                'dotbot'          => 'Moz DotBot',
                'screaming-frog'  => 'Screaming Frog',
                'uptimerobot'     => 'UptimeRobot',
                'pingdom'         => 'Pingdom',
                'statuspage'      => 'StatusPage',
                'custom'          => 'Custom Bot',
            );

            return isset( $labels[ $bot_type ] ) ? $labels[ $bot_type ] : ucfirst( str_replace( array( '-', '_' ), ' ', $bot_type ) );
        }

        /**
         * Get bot icon from bot type
         *
         * @param string $bot_type Bot type.
         * @return string Bot icon (Lucide icon HTML).
         */
        private function get_bot_icon( $bot_type ) {
            $icons = array(
                'googlebot'       => '<i data-lucide="search"></i>',
                'googlebot-image' => '<i data-lucide="image"></i>',
                'googlebot-news'  => '<i data-lucide="newspaper"></i>',
                'bingbot'         => '<i data-lucide="search"></i>',
                'bingpreview'     => '<i data-lucide="eye"></i>',
                'yahoo'           => '<i data-lucide="search"></i>',
                'duckduckbot'     => '<i data-lucide="search"></i>',
                'baiduspider'     => '<i data-lucide="bug"></i>',
                'yandexbot'       => '<i data-lucide="search"></i>',
                'facebookbot'     => '<i data-lucide="users"></i>',
                'twitterbot'      => '<i data-lucide="twitter"></i>',
                'linkedinbot'     => '<i data-lucide="linkedin"></i>',
                'pinterestbot'    => '<i data-lucide="pin"></i>',
                'whatsapp'        => '<i data-lucide="message-circle"></i>',
                'ahrefsbot'       => '<i data-lucide="bar-chart"></i>',
                'semrushbot'      => '<i data-lucide="trending-up"></i>',
                'mj12bot'         => '<i data-lucide="link"></i>',
                'dotbot'          => '<i data-lucide="link"></i>',
                'screaming-frog'  => '<i data-lucide="bug"></i>',
                'uptimerobot'     => '<i data-lucide="clock"></i>',
                'pingdom'         => '<i data-lucide="radio"></i>',
                'statuspage'      => '<i data-lucide="activity"></i>',
                'custom'          => '<i data-lucide="bot"></i>',
            );

            return isset( $icons[ $bot_type ] ) ? $icons[ $bot_type ] : '<i data-lucide="bot"></i>';
        }

        /**
         * Get screen resolution data for chart
         *
         * @return array
         */
        private function get_screen_resolution_data_for_chart() {
            // Nonce verification not required for GET parameters used for read-only data filtering
            // This method is called from admin pages protected by 'manage_options' capability
            // phpcs:disable WordPress.Security.NonceVerification.Recommended -- GET parameters used for filtering dashboard view (read-only operation)
            // phpcs:disable WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- wp_unslash not needed for sanitize_text_field
            $period = isset( $_GET['period'] ) ? sanitize_text_field( $_GET['period'] ) : 'last7days';
            $start_q = isset( $_GET['start_date'] ) ? sanitize_text_field( $_GET['start_date'] ) : null;
            $end_q = isset( $_GET['end_date'] ) ? sanitize_text_field( $_GET['end_date'] ) : null;
            // phpcs:enable WordPress.Security.NonceVerification.Recommended
            // phpcs:enable WordPress.Security.ValidatedSanitizedInput.MissingUnslash

            // Get date range
            $date_range = $this->get_date_range( $period, $start_q, $end_q );
            $start_date = $date_range['start'];
            $end_date = $date_range['end'];

            // Get screen resolution data
            $screen_resolutions = $this->get_screen_resolution_data( $start_date, $end_date );

            $total_sessions = 0;
            $resolution_counts = array();

            // Count sessions for each resolution
            foreach ( $screen_resolutions as $resolution ) {
                $count = (int) $resolution['count'];
                $total_sessions += $count;
                $resolution_counts[ $resolution['resolution'] ] = $count;
            }

            // Define color palette for resolutions
            $colors = array( '#6366F1', '#10B981', '#F59E0B', '#EF4444', '#3B82F6', '#8B5CF6', '#14B8A6', '#F472B6', '#84CC16', '#06B6D4' );
            $color_index = 0;

            $resolution_list = array();
            foreach ( $resolution_counts as $resolution_name => $sessions ) {
                $color = $colors[ $color_index % count( $colors ) ];
                $color_index++;

                $percentage = $total_sessions > 0 ? round( ( $sessions / $total_sessions ) * 100, 1 ) : 0;

                $resolution_list[] = array(
                    'name' => $resolution_name,
                    'sessions' => $sessions,
                    'percentage' => $percentage,
                    'color' => $color,
                    'css_class' => 'resolution-' . sanitize_html_class( $resolution_name ),
                );
            }

            // Sort by session count (descending)
            usort(
                $resolution_list,
                function ( $a, $b ) {
                    return $b['sessions'] - $a['sessions'];
                }
            );

            return array(
                'resolution_list' => $resolution_list,
                'total_sessions' => $total_sessions,
            );
        }

        /**
         * Render screen resolution pie chart
         *
         * @return void
         */
        private function render_screen_resolution_chart() {
            ?>
            <div class="user-intent-chart-container">
                <canvas id="screen-resolution-chart" width="300" height="300"></canvas>
                <div class="resolution-table-container">
                    <table class="resolution-legend">
                        <tbody id="resolution-legend-body">
                            <!-- Populated by JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>
            <!-- Note: Screen resolution chart script is now properly enqueued via wp_add_inline_script() in get_dashboard_scripts() method -->
            <?php
        }

        /**
         * Render new vs returning visitors widget
         *
         * @param array $data New vs returning visitors data.
         */
        private function render_new_vs_returning_widget( $data ) {
            $has_data = ! empty( $data ) && isset( $data['total'] ) && $data['total'] > 0;

            ?>
            <div id="new-vs-returning-widget" class="dashboard-widget new-vs-returning-widget">
                <?php opti_behavior_render_widget_loading(); ?>
                <?php $tooltips = opti_behavior_get_dashboard_tooltips(); ?>
                <div class="widget-header">
                    <h3 class="widget-title">
                        <span class="widget-icon"><i data-lucide="users-round"></i></span>
                        <?php esc_html_e( 'New vs Returning Visitors', 'opti-behavior' ); ?>
                        <?php opti_behavior_tooltip_e( $tooltips['new_vs_returning']['title'], $tooltips['new_vs_returning']['content'], $tooltips['new_vs_returning']['simple'], $tooltips['new_vs_returning']['example'], array( 'position' => 'bottom' ) ); ?>
                    </h3>
                </div>
                <div class="widget-content">
                    <div class="optibehavior-empty-state <?php echo $has_data ? '' : 'is-visible'; ?>">
                        <i data-lucide="users-round" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                        <div class="optibehavior-empty-title"><?php esc_html_e( 'No visitor data available', 'opti-behavior' ); ?></div>
                        <div class="optibehavior-empty-sub"><?php esc_html_e( 'Try broadening the date range or check back later.', 'opti-behavior' ); ?></div>
                    </div>
                    <div class="user-intent-chart-container" style="<?php echo $has_data ? '' : 'display: none;'; ?>">
                        <canvas id="new-vs-returning-chart" width="300" height="300"></canvas>
                        <table class="traffic-classification-legend">
                            <tbody id="new-vs-returning-legend-body">
                                <!-- Populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php
        }

        /**
         * Render visited directories widget
         *
         * @param array $data Visited directories data.
         */
        private function render_visited_directories_widget( $data ) {
            $has_data = ! empty( $data ) && isset( $data['directories'] ) && ! empty( $data['directories'] );
            ?>
            <div id="visited-directories-widget" class="dashboard-widget visited-directories-widget">
                <?php opti_behavior_render_widget_loading(); ?>
                <?php $tooltips = opti_behavior_get_dashboard_tooltips(); ?>
                <div class="widget-header">
                    <h3 class="widget-title">
                        <span class="widget-icon"><i data-lucide="folder-tree"></i></span>
                        <?php esc_html_e( 'Visited Directories', 'opti-behavior' ); ?>
                        <?php opti_behavior_tooltip_e( $tooltips['visited_directories']['title'], $tooltips['visited_directories']['content'], $tooltips['visited_directories']['simple'], $tooltips['visited_directories']['example'], array( 'position' => 'bottom' ) ); ?>
                    </h3>
                </div>
                <div class="widget-content">
                    <div class="optibehavior-empty-state <?php echo $has_data ? '' : 'is-visible'; ?>">
                        <i data-lucide="folder-tree" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                        <div class="optibehavior-empty-title"><?php esc_html_e( 'No directory data available', 'opti-behavior' ); ?></div>
                        <div class="optibehavior-empty-sub"><?php esc_html_e( 'Try broadening the date range or check back later.', 'opti-behavior' ); ?></div>
                    </div>
                    <div class="visited-directories-list" style="<?php echo $has_data ? '' : 'display: none;'; ?>">
                        <table class="traffic-classification-legend">
                            <tbody id="visited-directories-legend-body">
                                <!-- Populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php
        }

        /**
         * Render new registered users widget
         *
         * @param array $data New registered users data.
         */
        private function render_new_registered_users_widget( $data ) {
            $has_data = ! empty( $data ) && isset( $data['total'] ) && $data['total'] > 0;
            ?>
            <div id="new-registered-users-widget" class="dashboard-widget new-registered-users-widget">
                <?php opti_behavior_render_widget_loading(); ?>
                <?php $tooltips = opti_behavior_get_dashboard_tooltips(); ?>
                <div class="widget-header">
                    <h3 class="widget-title">
                        <span class="widget-icon"><i data-lucide="user-plus"></i></span>
                        <?php esc_html_e( 'Visitor Authentication', 'opti-behavior' ); ?>
                        <?php opti_behavior_tooltip_e( $tooltips['visitor_auth']['title'], $tooltips['visitor_auth']['content'], $tooltips['visitor_auth']['simple'], '', array( 'position' => 'bottom' ) ); ?>
                    </h3>
                </div>
                <div class="widget-content">
                    <div class="optibehavior-empty-state <?php echo $has_data ? '' : 'is-visible'; ?>">
                        <i data-lucide="user-plus" style="width: 48px; height: 48px; color: #9ca3af; stroke-width: 1.5;"></i>
                        <div class="optibehavior-empty-title"><?php esc_html_e( 'No visitors data', 'opti-behavior' ); ?></div>
                        <div class="optibehavior-empty-sub"><?php esc_html_e( 'Visitor and registration data will appear here.', 'opti-behavior' ); ?></div>
                    </div>
                    <div class="user-intent-chart-container" id="new-registered-users-chart-container" style="<?php echo $has_data ? '' : 'display: none;'; ?>">
                        <canvas id="new-registered-users-chart"></canvas>
                        <table class="traffic-classification-legend">
                            <tbody id="new-registered-users-legend-body">
                                <!-- Populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php
        }

		/**
		 * Render the Pro Trial Banner.
		 *
		 * Displays one of three banner variants depending on trial state:
		 * - invite:  Encourages user to start 6-month free trial
		 * - active:  Shows countdown and download link
		 * - expired: Shows trial ended message with upgrade link
		 *
		 * Banner is hidden when Pro is active with valid manifest,
		 * or when the user has recently dismissed it.
		 *
		 * @since 1.1.3
		 */
		private function render_pro_trial_banner() {
			$state = $this->get_trial_banner_state();

			if ( 'hidden' === $state['display'] ) {
				return;
			}

			// Build CSS classes
			$classes = 'opti-behavior-trial-banner';
			if ( 'active' === $state['display'] ) {
				$classes .= ' opti-behavior-trial-active';
			} elseif ( 'expired' === $state['display'] ) {
				$classes .= ' opti-behavior-trial-expired';
			}

			?>
			<div class="<?php echo esc_attr( $classes ); ?>">
				<?php if ( 'invite' === $state['display'] ) : ?>
					<?php // --- INVITE STATE --- ?>
					<div class="opti-behavior-trial-banner-content">
						<div class="opti-behavior-trial-banner-icon">
							<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/><path d="M5 3v4"/><path d="M19 17v4"/><path d="M3 5h4"/><path d="M17 19h4"/></svg>
						</div>
						<div class="opti-behavior-trial-banner-text">
							<p class="opti-behavior-trial-banner-title">
								<?php
								printf(
									/* translators: %s: highlighted "6 months" text */
									esc_html__( 'Try Pro FREE for %s — No Credit Card Needed!', 'opti-behavior' ),
									'<span class="opti-behavior-trial-highlight">' . esc_html__( '6 Months', 'opti-behavior' ) . '</span>'
								);
								?>
							</p>
							<p class="opti-behavior-trial-banner-description">
								<?php esc_html_e( 'Unlock session recordings, error tracking, user journeys, form analytics & advanced heatmaps. One click to activate.', 'opti-behavior' ); ?>
							</p>
							<div class="opti-behavior-trial-features">
								<span class="opti-behavior-trial-feature-pill">
									<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5"/><rect x="2" y="6" width="14" height="12" rx="2"/></svg>
									<?php esc_html_e( 'Recordings', 'opti-behavior' ); ?>
								</span>
								<span class="opti-behavior-trial-feature-pill">
									<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
									<?php esc_html_e( 'Error Tracking', 'opti-behavior' ); ?>
								</span>
								<span class="opti-behavior-trial-feature-pill">
									<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"/></svg>
									<?php esc_html_e( 'User Journeys', 'opti-behavior' ); ?>
								</span>
								<span class="opti-behavior-trial-feature-pill">
									<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2" ry="2"/><rect x="2" y="14" width="20" height="8" rx="2" ry="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>
									<?php esc_html_e( 'Form Analytics', 'opti-behavior' ); ?>
								</span>
							</div>
						</div>
					</div>
					<div class="opti-behavior-trial-banner-actions">
						<button type="button" class="opti-behavior-trial-btn-start">
							<span class="opti-behavior-trial-spinner"></span>
							<span class="opti-behavior-trial-btn-icon">
								<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12V8H6a2 2 0 0 1-2-2c0-1.1.9-2 2-2h12v4"/><path d="M4 6v12c0 1.1.9 2 2 2h14v-4"/><path d="M18 12a2 2 0 0 0-2 2c0 1.1.9 2 2 2h4v-4h-4z"/></svg>
							</span>
							<?php esc_html_e( 'Start Free Trial', 'opti-behavior' ); ?>
						</button>
						<button type="button" class="opti-behavior-trial-btn-dismiss" title="<?php esc_attr_e( 'Dismiss', 'opti-behavior' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
						</button>
					</div>

				<?php elseif ( 'active' === $state['display'] ) : ?>
					<?php // --- ACTIVE STATE --- ?>
					<div class="opti-behavior-trial-banner-content">
						<div class="opti-behavior-trial-success-check">
							<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
						</div>
						<div class="opti-behavior-trial-banner-text">
							<p class="opti-behavior-trial-banner-title">
								<?php esc_html_e( 'Pro Trial Active', 'opti-behavior' ); ?>
							</p>
							<p class="opti-behavior-trial-banner-description">
								<?php
								if ( function_exists( 'opti_behavior_pro_active' ) && opti_behavior_pro_active() ) {
									esc_html_e( 'All Pro features are unlocked. Enjoy session recordings, error tracking, and more!', 'opti-behavior' );
								} else {
									esc_html_e( 'Your trial is active! Download and install the Pro plugin to unlock all premium features.', 'opti-behavior' );
								}
								?>
							</p>
						</div>
					</div>
					<div class="opti-behavior-trial-banner-actions">
						<span class="opti-behavior-trial-banner-countdown">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
							<?php
							printf(
								/* translators: %d: number of days remaining */
								esc_html__( '%d days left', 'opti-behavior' ),
								(int) $state['days_left']
							);
							?>
						</span>
						<?php if ( ! ( function_exists( 'opti_behavior_pro_active' ) && opti_behavior_pro_active() ) ) : ?>
							<a href="<?php echo esc_url( $state['download_url'] ); ?>" class="opti-behavior-trial-btn-download" target="_blank" rel="noopener noreferrer">
								<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
								<?php esc_html_e( 'Download Pro Plugin', 'opti-behavior' ); ?>
							</a>
						<?php endif; ?>
						<button type="button" class="opti-behavior-trial-btn-dismiss" title="<?php esc_attr_e( 'Dismiss', 'opti-behavior' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
						</button>
					</div>

				<?php elseif ( 'expired' === $state['display'] ) : ?>
					<?php // --- EXPIRED STATE --- ?>
					<div class="opti-behavior-trial-banner-content">
						<div class="opti-behavior-trial-banner-icon">
							<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
						</div>
						<div class="opti-behavior-trial-banner-text">
							<p class="opti-behavior-trial-banner-title">
								<?php esc_html_e( 'Your Pro Trial Has Ended', 'opti-behavior' ); ?>
							</p>
							<p class="opti-behavior-trial-banner-description">
								<?php esc_html_e( 'Your 6-month free trial has expired. Upgrade to continue using session recordings, error tracking, and all premium features.', 'opti-behavior' ); ?>
							</p>
						</div>
					</div>
					<div class="opti-behavior-trial-banner-actions">
						<a href="<?php echo esc_url( $state['download_url'] ); ?>" class="opti-behavior-trial-btn-upgrade" target="_blank" rel="noopener noreferrer">
							<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>
							<?php esc_html_e( 'Upgrade to Pro', 'opti-behavior' ); ?>
						</a>
						<button type="button" class="opti-behavior-trial-btn-dismiss" title="<?php esc_attr_e( 'Dismiss', 'opti-behavior' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
						</button>
					</div>
				<?php endif; ?>
			</div>
			<?php
		}

    }
}

